is_gravityforms_supported() && class_exists('GF_Field')) { require_once 'class-unique-id-field.php'; } } /** * Initialize hooks required for admin and theme. * * @since 1.0 * * @return void */ public function init() { parent::init(); $this->maybe_create_table(); add_filter('gform_entry_post_save', array($this, 'populate_unique_ids'), 8, 2); add_action('gform_post_payment_completed', array($this, 'populate_after_payment'), 10, 2); } /** * Initialize hooks required for admin. * * @since 1.0 * * @return void */ public function init_admin() { parent::init_admin(); add_action('gform_editor_js', array($this, 'add_unique_id_script')); add_action('gform_field_standard_settings', array($this, 'unique_id_field_settings'), 10, 2); add_action('gform_editor_js_set_default_values', array($this, 'set_defaults_js_value')); } /** * Registered ID types. Each type defines its length rules and the callback that generates the raw ID, * so new formats can be added through the `alphagf_unique_id_types` filter without touching this class. * * @return array */ public static function get_types() { return apply_filters( 'alphagf_unique_id_types', array( 'alphanumeric' => array( 'label' => esc_html__('Alphanumeric', 'alpha-addons-for-gravity-forms'), 'min_length' => 4, 'max_length' => 64, 'default_length' => 9, 'supports' => array(), 'callback' => array(__CLASS__, 'generate_alphanumeric'), ), 'numeric' => array( 'label' => esc_html__('Numeric', 'alpha-addons-for-gravity-forms'), 'min_length' => apply_filters('alphagf_unique_id_numeric_min_length', 4), 'max_length' => 19, 'default_length' => 9, 'supports' => array(), 'callback' => array(__CLASS__, 'generate_numeric'), ), 'sequential' => array( 'label' => esc_html__('Sequential', 'alpha-addons-for-gravity-forms'), 'min_length' => 0, 'max_length' => 19, 'default_length' => 0, 'supports' => array('starting_number'), 'unique' => true, // The sequence guarantees uniqueness, no collision check needed. 'callback' => array(__CLASS__, 'generate_sequential'), ), ) ); } /** * Get a single type definition, falling back to the first registered type. */ public static function get_type($type) { $types = self::get_types(); if (isset($types[$type])) { return $types[$type]; } return reset($types); } /** * Resolve the core ID length for a field within its type's limits. */ public static function get_length($field) { $type = self::get_type($field->alphagf_unique_id_type); $length = absint($field->alphagf_unique_id_length); if (! $length) { return (int) $type['default_length']; } return (int) min(max($length, (int) $type['min_length']), (int) $type['max_length']); } /** * Unique ID fields of a form. * * @return GF_Field[] */ public function get_unique_id_fields($form) { return GFAPI::get_fields_by_type($form, array(self::FIELD_TYPE)); } /** * Generate IDs for every Unique ID field once the entry is saved. */ public function populate_unique_ids($entry, $form) { if (rgar($entry, 'status') === 'spam') { return $entry; } /** * Delay generation until a payment add-on marks the payment as completed. * * @param bool $wait Whether to wait for payment. * @param array $form The form object. * @param array $entry The entry object. */ if (apply_filters('alphagf_unique_id_wait_for_payment', false, $form, $entry) && ! in_array(rgar($entry, 'payment_status'), array('Paid', 'Approved'), true)) { return $entry; } return $this->populate_entry($entry, $form); } /** * Generate delayed IDs once the payment is completed. */ public function populate_after_payment($entry, $action) { $form = GFAPI::get_form(rgar($entry, 'form_id')); if (! $form || rgar($entry, 'status') === 'spam' || ! apply_filters('alphagf_unique_id_wait_for_payment', false, $form, $entry)) { return; } $this->populate_entry($entry, $form); } /** * Fill empty Unique ID fields of an entry and save them. */ public function populate_entry($entry, $form) { foreach ($this->get_unique_id_fields($form) as $field) { if (! rgblank(rgar($entry, (string) $field->id))) { continue; } $value = $this->get_unique_value($field, $form, $entry); if (rgblank($value)) { continue; } GFAPI::update_entry_field($entry['id'], $field->id, $value); $entry[(string) $field->id] = $value; } return $entry; } /** * Build the final value (prefix + ID + suffix), retrying random types until it is unique for the field. */ public function get_unique_value($field, $form, $entry) { $type_key = $field->alphagf_unique_id_type ? $field->alphagf_unique_id_type : 'alphanumeric'; $type = self::get_type($type_key); if (! is_callable($type['callback'])) { return ''; } /** * Filter the attributes used to generate the ID. * * @param array $args type, length, starting_number, prefix and suffix. * @param array $form The form object. * @param GF_Field $field The field object. * @param array $entry The entry object. */ $args = apply_filters( 'alphagf_unique_id_attributes', array( 'type' => $type_key, 'length' => self::get_length($field), 'starting_number' => max(1, absint($field->alphagf_unique_id_start)), 'prefix' => $this->replace_merge_tags($field->alphagf_unique_id_prefix, $form, $entry), 'suffix' => $this->replace_merge_tags($field->alphagf_unique_id_suffix, $form, $entry), 'form_id' => (int) $form['id'], 'field_id' => (int) $field->id, ), $form, $field, $entry ); $attempts = rgar($type, 'unique') ? 1 : self::MAX_ATTEMPTS; for ($i = 0; $i < $attempts; $i++) { $id = (string) call_user_func($type['callback'], $args, $field, $form, $entry); $value = $args['prefix'] . $id . $args['suffix']; /** * Filter the generated ID before it is saved. */ $value = apply_filters('alphagf_unique_id', $value, $form['id'], $field->id, $args, $entry); if (rgar($type, 'unique') || ! $this->value_exists($value, $form['id'], $field->id)) { return $value; } } GFCommon::log_error(__METHOD__ . '(): Could not generate a unique ID for field #' . $field->id . ' after ' . $attempts . ' attempts.'); return ''; } public function replace_merge_tags($text, $form, $entry) { if (rgblank($text)) { return ''; } return GFCommon::replace_variables($text, $form, $entry, false, false, false, 'text'); } /** * Whether a value is already stored for this field on another entry. */ public function value_exists($value, $form_id, $field_id) { global $wpdb; $table = GFFormsModel::get_entry_meta_table_name(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM %i WHERE form_id = %d AND meta_key = %s AND meta_value = %s", $table, $form_id, (string) $field_id, $value)); return (int) $count > 0; } public static function generate_alphanumeric($args) { $chars = apply_filters('alphagf_unique_id_alphanumeric_chars', '0123456789abcdefghijklmnopqrstuvwxyz'); return self::random_string($chars, $args['length']); } public static function generate_numeric($args) { // First digit is non-zero so the ID keeps its full length when treated as a number. return self::random_string('123456789', 1) . self::random_string('0123456789', $args['length'] - 1); } public static function generate_sequential($args) { $sequence_key = apply_filters('alphagf_unique_id_sequence_key', $args['form_id'] . '_' . $args['field_id'], $args); $number = self::get_instance()->next_sequence_number($sequence_key, $args['starting_number']); return $args['length'] ? str_pad((string) $number, $args['length'], '0', STR_PAD_LEFT) : (string) $number; } public static function random_string($chars, $length) { $string = ''; $max = strlen($chars) - 1; for ($i = 0; $i < $length; $i++) { $string .= $chars[random_int(0, $max)]; } return $string; } public function get_table_name() { global $wpdb; return $wpdb->prefix . 'alphagf_unique_id_sequences'; } public function maybe_create_table() { if (get_option(self::DB_VERSION_OPTION) === self::DB_VERSION) { return; } global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $table = $this->get_table_name(); $charset_collate = $wpdb->get_charset_collate(); dbDelta("CREATE TABLE {$table} ( sequence_key varchar(191) NOT NULL, current bigint(20) unsigned NOT NULL DEFAULT 0, PRIMARY KEY (sequence_key) ) {$charset_collate};"); update_option(self::DB_VERSION_OPTION, self::DB_VERSION); } /** * Atomically increment a sequence. LAST_INSERT_ID(expr) keeps the new value on this connection, * so concurrent submissions never receive the same number. */ public function next_sequence_number($sequence_key, $starting_number = 1) { global $wpdb; $table = $this->get_table_name(); /** * Runs before a sequential ID is incremented. */ do_action('alphagf_unique_id_sequential_pre_insert', $sequence_key, $starting_number); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query($wpdb->prepare("INSERT INTO %i (sequence_key, current) VALUES (%s, LAST_INSERT_ID(%d)) ON DUPLICATE KEY UPDATE current = LAST_INSERT_ID(GREATEST(current + 1, %d))", $table, $sequence_key, $starting_number, $starting_number)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return (int) $wpdb->get_var('SELECT LAST_INSERT_ID()'); } public function unique_id_field_settings($position) { if ((int) $position !== 20) { return; } ?>