Plugin Directory

Changeset 3841460


Ignore:
Timestamp:
12/03/2026 02:27:39 AM (less than one hour ago)
Author:
codexpert
Message:

Deploy CF7 Submissions version 0.80

Location:
cf7-submissions
Files:
30 added
26 edited

Legend:

Unmodified
Added
Removed
  • cf7-submissions/trunk/app/Bootstrap/Deactivator.php

    r3836469 r3841460  
    3232         * @var string[]
    3333         */
    34         private $cron_hooks = array( 'codexpert-daily', 'cf7-submissions_db_upgrade' );
     34        private $cron_hooks = array( 'codexpert-daily', 'cf7-submissions_db_upgrade', 'cf7-submissions_backfill', 'cf7-submissions_purge_events' );
    3535
    3636        /**
  • cf7-submissions/trunk/app/Bootstrap/Initializer.php

    r3836469 r3841460  
    33
    44defined( 'ABSPATH' ) || exit;
     5
     6use CF7_Submissions\Helpers\Caps;
     7use CF7_Submissions\Leads\Backfill;
     8use CF7_Submissions\Leads\Retention;
     9use CF7_Submissions\Privacy\Eraser;
     10use CF7_Submissions\Privacy\Exporter;
    511
    612/**
    … …  
    1723                \CF7_Submissions\Controllers\Admin\Init::class,
    1824                \CF7_Submissions\Controllers\Admin\Menu::class,
     25                \CF7_Submissions\Controllers\Admin\Leads::class,
     26                \CF7_Submissions\Controllers\Admin\Form_Panel::class,
     27                \CF7_Submissions\Controllers\Admin\Settings::class,
    1928                \CF7_Submissions\Controllers\Admin\Submission::class,
    2029                \CF7_Submissions\Controllers\Admin\Table::class,
    … …  
    4756                $initializer = new self();
    4857
     58                Caps::register();
     59
    4960                add_action( 'init', array( $initializer, 'load_textdomain' ) );
    5061                add_action( 'admin_init', array( Installer::class, 'maybe_upgrade' ) );
    5162                add_action( 'init', array( Installer::class, 'schedule_upgrade' ) );
    5263                add_action( Installer::UPGRADE_HOOK, array( Installer::class, 'maybe_upgrade' ) );
     64                add_action( Backfill::HOOK, array( Backfill::class, 'cron' ) );
     65                // Admin only: reading an option that was never saved costs a query on every request, and the job is set up when the period is saved.
     66                add_action( 'admin_init', array( Retention::class, 'schedule' ) );
     67                add_action( Retention::HOOK, array( Retention::class, 'cron' ) );
     68                add_filter( 'wp_privacy_personal_data_exporters', array( Exporter::class, 'register' ) );
     69                add_filter( 'wp_privacy_personal_data_erasers', array( Eraser::class, 'register' ) );
    5370
    5471                // Common controllers load first, so the context controllers can rely on what they register.
  • cf7-submissions/trunk/app/Bootstrap/Installer.php

    r3836469 r3841460  
    44defined( 'ABSPATH' ) || exit;
    55
     6use CF7_Submissions\Helpers\Lock;
    67use CF7_Submissions\Models\Database;
    78
    89/**
    9  * Creates the plugin's database schema on activation.
     10 * Creates the plugin's database schema and brings existing sites up to date.
     11 *
     12 * The schema moves forward in versioned steps (see `steps()`). Each step runs once, in
     13 * order, and the stored version advances after every step, so a run that fails halfway
     14 * resumes where it stopped.
    1015 */
    1116class Installer {
    … …  
    1722
    1823        /**
    19          * Option row used as the upgrade lock (holds the time it was taken).
    20          */
    21         const LOCK_OPTION = 'cf7-submissions_upgrade_lock';
     24         * Name of the lock that keeps two upgrades from running at once.
     25         */
     26        const LOCK_NAME = 'upgrade';
    2227
    2328        /**
    … …  
    2530         */
    2631        const LOCK_TTL = 300;
     32
     33        /**
     34         * Schema version that introduced leads.
     35         */
     36        const LEADS_VERSION = '1.1.0';
     37
     38        /**
     39         * Schema version that added lead notes and the activity timeline.
     40         */
     41        const ACTIVITY_VERSION = '1.2.0';
     42
     43        /**
     44         * Schema version that added the audit log.
     45         */
     46        const AUDIT_VERSION = '1.3.0';
    2747
    2848        /**
    … …  
    3252                $installer = new self();
    3353
    34                 if ( ! $installer->is_database_up_to_date() ) {
    35                         $installer->create_tables();
     54                if ( ! $installer->is_database_up_to_date() && $installer->upgrade() ) {
    3655                        $installer->update_db_version();
    3756                }
    … …  
    4261         *
    4362         * Activation only runs when the plugin is switched on, not when it is updated, so
    44          * existing sites reach the current schema through here (hooked to `admin_init`).
    45          * Failures are retried at most every ten minutes so a broken database is not hammered.
     63         * existing sites reach the current schema through here (hooked to `admin_init`, and
     64         * to a cron event). Failures are retried at most every ten minutes so a broken
     65         * database is not hammered.
    4666         *
    4767         * @return void
    … …  
    5474                }
    5575
     76                $lock = new Lock( self::LOCK_NAME, self::LOCK_TTL );
     77
    5678                // Another request (or the cron event) is already running the upgrade.
    57                 if ( ! $installer->acquire_lock() ) {
     79                if ( ! $lock->acquire() ) {
    5880                        return;
    5981                }
    … …  
    6789                        set_transient( 'cf7-submissions_upgrade_failed', 1, 10 * MINUTE_IN_SECONDS );
    6890                } finally {
    69                         delete_option( self::LOCK_OPTION );
     91                        $lock->release();
    7092                }
    7193        }
    … …  
    93115
    94116        /**
    95          * Takes the upgrade lock.
    96          *
    97          * `add_option()` is atomic, so exactly one caller creates the row. A row older than
    98          * LOCK_TTL belongs to a run that died, and is taken over with a conditional `UPDATE`
    99          * so two callers cannot both win.
    100          *
    101          * @return bool True when this request holds the lock.
    102          */
    103         protected function acquire_lock() {
    104                 global $wpdb;
    105 
    106                 if ( add_option( self::LOCK_OPTION, time(), '', false ) ) {
    107                         return true;
    108                 }
    109 
    110                 $now     = time();
    111                 $updated = $wpdb->query(
    112                         $wpdb->prepare(
    113                                 "UPDATE {$wpdb->options} SET option_value = %s WHERE option_name = %s AND CAST(option_value AS UNSIGNED) < %d",
    114                                 (string) $now,
    115                                 self::LOCK_OPTION,
    116                                 $now - self::LOCK_TTL
    117                         )
     117         * Re-applies every table definition, then reports what is still wrong.
     118         *
     119         * The dbDelta call is safe to repeat: it adds a missing table, column or index and leaves
     120         * the rest. Backs the "Repair" tool; run from an admin request.
     121         *
     122         * @return string[] Problems left after the repair. Empty when the schema is complete.
     123         */
     124        public static function repair() {
     125                $installer = new self();
     126                $installer->create_tables();
     127
     128                return self::check();
     129        }
     130
     131        /**
     132         * Whether the leads tables are in place, so lead work can run.
     133         *
     134         * Until then submissions are still stored, and the backfill links them later.
     135         *
     136         * @param string $version Schema version the caller needs. Defaults to the leads table.
     137         * @return bool
     138         */
     139        public static function schema_ready( $version = self::LEADS_VERSION ) {
     140                return version_compare( (string) get_option( 'cf7-submissions_db_version', '0' ), $version, '>=' );
     141        }
     142
     143        /**
     144         * Compares the database with the schema the plugin expects.
     145         *
     146         * Backs the "Check database" tool: tables, columns and indexes that are missing.
     147         * It only reports, it changes nothing.
     148         *
     149         * @return string[] One line per problem. Empty when the schema is complete.
     150         */
     151        public static function check() {
     152                $installer = new self();
     153                $problems  = array();
     154
     155                foreach ( $installer->tables() as $name => $definition ) {
     156                        $model = new Database( $name );
     157                        $db    = $model->get_instance();
     158                        $table = $model->get_table();
     159
     160                        if ( $table !== $db->get_var( $db->prepare( 'SHOW TABLES LIKE %s', $db->esc_like( $table ) ) ) ) {
     161                                $problems[] = sprintf( 'Missing table %s', $table );
     162                                continue;
     163                        }
     164
     165                        $columns = $db->get_col( "SHOW COLUMNS FROM `{$table}`", 0 );
     166
     167                        foreach ( array_diff( array_keys( $definition['columns'] ), $columns ) as $column ) {
     168                                $problems[] = sprintf( 'Missing column %s.%s', $table, $column );
     169                        }
     170
     171                        $have    = $db->get_col( "SHOW INDEX FROM `{$table}`", 2 );
     172                        $options = $definition['options'];
     173                        $wanted  = array_merge(
     174                                array( 'PRIMARY' ),
     175                                array_keys( isset( $options['unique_keys'] ) ? $options['unique_keys'] : array() ),
     176                                array_keys( isset( $options['indexes'] ) ? $options['indexes'] : array() )
     177                        );
     178
     179                        foreach ( array_diff( $wanted, $have ) as $index ) {
     180                                $problems[] = sprintf( 'Missing index %s on %s', $index, $table );
     181                        }
     182                }
     183
     184                return $problems;
     185        }
     186
     187        /**
     188         * The schema steps, oldest first: database version => method.
     189         *
     190         * Add a step for every change to a table, and set CF7_SUBMISSIONS_DB_VERSION to the
     191         * version of the last one. A step must be safe to run twice and return true on success.
     192         *
     193         * @return array<string,string>
     194         */
     195        protected function steps() {
     196                return array(
     197                        // The three tables the first release created.
     198                        '1.0.0' => 'step_create_tables',
     199                        // `ip` was VARCHAR(15): IPv6 addresses did not fit and the submission was lost.
     200                        '1.0.1' => 'step_widen_ip',
     201                        // Leads: the leads table, and `lead_id` plus indexes on submissions.
     202                        '1.1.0' => 'step_leads',
     203                        // Lead notes and the activity timeline.
     204                        '1.2.0' => 'step_lead_activity',
     205                        // The audit log: exports, erasures, bulk deletes.
     206                        '1.3.0' => 'step_audit_log',
     207                        // `submission_id` indexes on the field and file tables, which every lookup of an entry goes through.
     208                        '1.4.0' => 'step_submission_indexes',
    118209                );
    119 
    120                 wp_cache_delete( self::LOCK_OPTION, 'options' );
    121 
    122                 return 1 === $updated;
    123         }
    124 
    125         /**
    126          * Applies the schema changes made since the first release.
     210        }
     211
     212        /**
     213         * Runs every step the site has not seen yet.
     214         *
     215         * @return bool True when the schema is current.
     216         */
     217        protected function upgrade() {
     218                $installed = (string) get_option( 'cf7-submissions_db_version', '0' );
     219
     220                foreach ( $this->steps() as $version => $method ) {
     221                        if ( version_compare( $installed, $version, '>=' ) ) {
     222                                continue;
     223                        }
     224
     225                        if ( ! $this->$method() ) {
     226                                return false;
     227                        }
     228
     229                        update_option( 'cf7-submissions_db_version', $version );
     230                        $installed = $version;
     231                }
     232
     233                return true;
     234        }
     235
     236        /**
     237         * Step 1.0.0: create the tables at their first definition.
     238         *
     239         * @return bool
     240         */
     241        protected function step_create_tables() {
     242                $this->create_tables();
     243
     244                $missing = $this->missing_tables( '1.0.0' );
     245
     246                return ! $missing;
     247        }
     248
     249        /**
     250         * Step 1.4.0: index `submission_id` on `submission_data` and `submission_files`.
     251         *
     252         * Opening, deleting, exporting and erasing an entry, the reply-address check and the
     253         * backfill all look rows up by it. Without the keys each of those scanned the whole table,
     254         * and the backfill did it once per batch of 500. dbDelta adds the missing keys and touches
     255         * nothing else. It runs from admin or cron under the lock, never from a visitor request.
     256         *
     257         * @return bool
     258         */
     259        protected function step_submission_indexes() {
     260                $this->create_tables();
     261
     262                return ! self::check();
     263        }
     264
     265        /**
     266         * Step 1.3.0: add the audit log.
     267         *
     268         * @return bool
     269         */
     270        protected function step_audit_log() {
     271                $this->create_tables();
     272
     273                $problems = self::check();
     274
     275                return ! $problems;
     276        }
     277
     278        /**
     279         * Step 1.2.0: add the notes and activity tables.
     280         *
     281         * @return bool
     282         */
     283        protected function step_lead_activity() {
     284                $this->create_tables();
     285
     286                $problems = self::check();
     287
     288                return ! $problems;
     289        }
     290
     291        /**
     292         * Step 1.1.0: add the leads table and link submissions to it.
     293         *
     294         * The dbDelta call adds the missing column and keys to `submissions` and creates `leads`.
     295         * It runs from admin or cron under the lock, never from a visitor request.
     296         *
     297         * @return bool
     298         */
     299        protected function step_leads() {
     300                $this->create_tables();
     301
     302                $problems = self::check();
     303
     304                return ! $problems;
     305        }
     306
     307        /**
     308         * Step 1.0.1: widen `ip` to hold an IPv6 address.
    127309         *
    128310         * Targeted on purpose: a plain `ALTER` changes only the column that needs it, where
    129311         * re-running dbDelta over tables created by older releases could touch every column.
    130312         *
    131          * @return bool True when the schema is current.
    132          */
    133         protected function upgrade() {
     313         * @return bool
     314         */
     315        protected function step_widen_ip() {
    134316                $submissions = new Database( 'submissions' );
    135317                $db          = $submissions->get_instance();
    136318                $table       = $submissions->get_table();
    137319
    138                 $like = $db->prepare( 'SHOW TABLES LIKE %s', $db->esc_like( $table ) );
    139 
    140                 // Nothing installed yet: create everything at the current definition.
    141                 if ( $table !== $db->get_var( $like ) ) {
     320                // Someone dropped the table: create everything at the current definition.
     321                $missing = $this->missing_tables( '1.0.1' );
     322
     323                if ( $missing ) {
    142324                        $this->create_tables();
    143                         return $table === $db->get_var( $like );
    144                 }
    145 
    146                 // `ip` was VARCHAR(15): IPv6 addresses did not fit and the submission was lost.
     325
     326                        $missing = $this->missing_tables( '1.0.1' );
     327
     328                        return ! $missing;
     329                }
     330
    147331                $column = $db->get_row( "SHOW COLUMNS FROM `{$table}` LIKE 'ip'", ARRAY_A );
    148332
    149333                if ( $column && preg_match( '/^varchar\((\d+)\)/i', $column['Type'], $match ) && (int) $match[1] < 45 ) {
    150                         if ( false === $db->query( "ALTER TABLE `{$table}` MODIFY ip VARCHAR(45) NOT NULL DEFAULT '0.0.0.0'" ) ) {
    151                                 return false;
    152                         }
     334                        return false !== $db->query( "ALTER TABLE `{$table}` MODIFY ip VARCHAR(45) NOT NULL DEFAULT '0.0.0.0'" );
    153335                }
    154336
    … …  
    172354
    173355        /**
    174          * Create database tables.
     356         * Names of the plugin tables that do not exist.
     357         *
     358         * @param string $upto Only tables introduced at or before this schema version. Empty for all.
     359         * @return string[]
     360         */
     361        protected function missing_tables( $upto = '' ) {
     362                $missing = array();
     363
     364                foreach ( $this->tables( $upto ) as $name => $definition ) {
     365                        $model = new Database( $name );
     366                        $db    = $model->get_instance();
     367                        $table = $model->get_table();
     368
     369                        if ( $table !== $db->get_var( $db->prepare( 'SHOW TABLES LIKE %s', $db->esc_like( $table ) ) ) ) {
     370                                $missing[] = $table;
     371                        }
     372                }
     373
     374                return $missing;
     375        }
     376
     377        /**
     378         * The tables and their current definition.
    175379         *
    176380         * Table names match the ones earlier releases created (`{prefix}cf7_submissions`
    177          * and friends), so existing submissions stay readable after an update.
     381         * and friends), so existing submissions stay readable after an update. Integer
     382         * widths are explicit (`BIGINT(20)`) because MySQL 5.7 and MariaDB report them, and
     383         * dbDelta would otherwise issue a `CHANGE COLUMN` for each on every run.
     384         *
     385         * Each entry: `columns` (name => SQL), and optional `options` for `create_table()`:
     386         * `primary_key`, `unique_keys` (name => columns) and `indexes` (name => columns).
     387         *
     388         * @param string $upto Only tables introduced at or before this schema version. Empty for all.
     389         * @return array<string,array>
     390         */
     391        protected function tables( $upto = '' ) {
     392                $tables = array(
     393                        'submissions'      => array(
     394                                'columns' => array(
     395                                        'id'      => 'BIGINT(20) NOT NULL AUTO_INCREMENT',
     396                                        'form_id' => 'BIGINT(20) NOT NULL',
     397                                        'post_id' => 'BIGINT(20) NOT NULL DEFAULT 0',
     398                                        'user_id' => 'MEDIUMINT(9) NOT NULL DEFAULT 0',
     399                                        'fields'  => 'SMALLINT(3) NOT NULL',
     400                                        'files'   => 'SMALLINT(3) NOT NULL',
     401                                        'ip'      => "VARCHAR(45) NOT NULL DEFAULT '0.0.0.0'",
     402                                        'seen'    => 'TINYINT(2) NOT NULL DEFAULT 0',
     403                                        'time'    => 'INT(10) NOT NULL',
     404                                        'lead_id' => 'BIGINT(20) UNSIGNED DEFAULT NULL',
     405                                ),
     406                                'options' => array(
     407                                        'indexes' => array(
     408                                                'form_lead' => 'form_id,lead_id',
     409                                                'lead_id'   => 'lead_id',
     410                                                'seen'      => 'seen',
     411                                        ),
     412                                ),
     413                        ),
     414                        'submission_data'  => array(
     415                                'columns' => array(
     416                                        'id'            => 'BIGINT(20) NOT NULL AUTO_INCREMENT',
     417                                        'submission_id' => 'BIGINT(20) NOT NULL',
     418                                        'field'         => 'VARCHAR(255) NOT NULL',
     419                                        'value'         => 'LONGTEXT NOT NULL',
     420                                ),
     421                                'options' => array(
     422                                        'indexes' => array(
     423                                                'submission_id' => 'submission_id',
     424                                        ),
     425                                ),
     426                        ),
     427                        'submission_files' => array(
     428                                'columns' => array(
     429                                        'id'            => 'BIGINT(20) NOT NULL AUTO_INCREMENT',
     430                                        'submission_id' => 'BIGINT(20) NOT NULL',
     431                                        'field'         => 'VARCHAR(255) NOT NULL',
     432                                        'name'          => 'VARCHAR(255) NOT NULL',
     433                                        'path'          => 'TEXT NOT NULL',
     434                                        'type'          => 'VARCHAR(255) NOT NULL',
     435                                        'size'          => 'BIGINT(20) NOT NULL',
     436                                ),
     437                                'options' => array(
     438                                        'indexes' => array(
     439                                                'submission_id' => 'submission_id',
     440                                        ),
     441                                ),
     442                        ),
     443                        'leads'            => array(
     444                                'since'   => '1.1.0',
     445                                'columns' => array(
     446                                        'id'                => 'BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT',
     447                                        'email'             => 'VARCHAR(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL',
     448                                        'first_name'        => 'VARCHAR(100) DEFAULT NULL',
     449                                        'last_name'         => 'VARCHAR(100) DEFAULT NULL',
     450                                        'phone'             => 'VARCHAR(50) DEFAULT NULL',
     451                                        'company'           => 'VARCHAR(190) DEFAULT NULL',
     452                                        'job_title'         => 'VARCHAR(150) DEFAULT NULL',
     453                                        'country'           => 'VARCHAR(2) DEFAULT NULL',
     454                                        'timezone'          => 'VARCHAR(64) DEFAULT NULL',
     455                                        'status'            => "VARCHAR(20) NOT NULL DEFAULT 'needs_reply'",
     456                                        'source'            => "VARCHAR(30) NOT NULL DEFAULT 'cf7'",
     457                                        'source_ref'        => 'VARCHAR(190) DEFAULT NULL',
     458                                        'owner_user_id'     => 'BIGINT(20) UNSIGNED DEFAULT NULL',
     459                                        'consent'           => "VARCHAR(20) NOT NULL DEFAULT 'unknown'",
     460                                        'consent_source'    => 'VARCHAR(60) DEFAULT NULL',
     461                                        'consent_at'        => 'DATETIME DEFAULT NULL',
     462                                        'email_status'      => "VARCHAR(20) NOT NULL DEFAULT 'active'",
     463                                        'unsubscribed_at'   => 'DATETIME DEFAULT NULL',
     464                                        'unsubscribe_token' => 'CHAR(32) NOT NULL',
     465                                        'submissions_count' => 'INT(10) UNSIGNED NOT NULL DEFAULT 0',
     466                                        'emails_sent_count' => 'INT(10) UNSIGNED NOT NULL DEFAULT 0',
     467                                        'first_seen_at'     => 'DATETIME NOT NULL',
     468                                        'last_seen_at'      => 'DATETIME NOT NULL',
     469                                        'last_replied_at'   => 'DATETIME DEFAULT NULL',
     470                                        'last_contacted_at' => 'DATETIME DEFAULT NULL',
     471                                        'next_follow_up_at' => 'DATETIME DEFAULT NULL',
     472                                        'score'             => 'INT(11) DEFAULT NULL',
     473                                        'created_at'        => 'DATETIME NOT NULL',
     474                                        'updated_at'        => 'DATETIME NOT NULL',
     475                                ),
     476                                'options' => array(
     477                                        'unique_keys' => array(
     478                                                'email'             => 'email',
     479                                                'unsubscribe_token' => 'unsubscribe_token',
     480                                        ),
     481                                        'indexes'     => array(
     482                                                'status_last_seen' => 'status,last_seen_at',
     483                                                'last_seen_at'     => 'last_seen_at',
     484                                        ),
     485                                ),
     486                        ),
     487                        'lead_events'      => array(
     488                                'since'   => '1.2.0',
     489                                'columns' => array(
     490                                        'id'            => 'BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT',
     491                                        'lead_id'       => 'BIGINT(20) UNSIGNED NOT NULL',
     492                                        'type'          => 'VARCHAR(40) NOT NULL',
     493                                        'object_type'   => 'VARCHAR(40) DEFAULT NULL',
     494                                        'object_id'     => 'BIGINT(20) UNSIGNED DEFAULT NULL',
     495                                        'actor_user_id' => 'BIGINT(20) UNSIGNED DEFAULT NULL',
     496                                        'data'          => 'LONGTEXT',
     497                                        'created_at'    => 'DATETIME NOT NULL',
     498                                ),
     499                                'options' => array(
     500                                        'indexes' => array(
     501                                                'lead_created' => 'lead_id,created_at',
     502                                                'type_created' => 'type,created_at',
     503                                        ),
     504                                ),
     505                        ),
     506                        'audit_log'        => array(
     507                                'since'   => '1.3.0',
     508                                'columns' => array(
     509                                        'id'            => 'BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT',
     510                                        'actor_user_id' => 'BIGINT(20) UNSIGNED DEFAULT NULL',
     511                                        'action'        => 'VARCHAR(40) NOT NULL',
     512                                        'object_type'   => 'VARCHAR(40) DEFAULT NULL',
     513                                        'object_id'     => 'BIGINT(20) UNSIGNED DEFAULT NULL',
     514                                        'outcome'       => "VARCHAR(20) NOT NULL DEFAULT 'ok'",
     515                                        'data'          => 'LONGTEXT',
     516                                        'created_at'    => 'DATETIME NOT NULL',
     517                                ),
     518                                'options' => array(
     519                                        'indexes' => array(
     520                                                'actor_created' => 'actor_user_id,created_at',
     521                                                'object'        => 'object_type,object_id',
     522                                        ),
     523                                ),
     524                        ),
     525                        'lead_notes'       => array(
     526                                'since'   => '1.2.0',
     527                                'columns' => array(
     528                                        'id'         => 'BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT',
     529                                        'lead_id'    => 'BIGINT(20) UNSIGNED NOT NULL',
     530                                        'type'       => "VARCHAR(20) NOT NULL DEFAULT 'note'",
     531                                        'body'       => 'LONGTEXT NOT NULL',
     532                                        'created_by' => 'BIGINT(20) UNSIGNED DEFAULT NULL',
     533                                        'created_at' => 'DATETIME NOT NULL',
     534                                        'updated_at' => 'DATETIME NOT NULL',
     535                                ),
     536                                'options' => array(
     537                                        'indexes' => array(
     538                                                'lead_created' => 'lead_id,created_at',
     539                                        ),
     540                                ),
     541                        ),
     542                );
     543
     544                if ( '' === $upto ) {
     545                        return $tables;
     546                }
     547
     548                return array_filter(
     549                        $tables,
     550                        static function ( $definition ) use ( $upto ) {
     551                                return version_compare( isset( $definition['since'] ) ? $definition['since'] : '1.0.0', $upto, '<=' );
     552                        }
     553                );
     554        }
     555
     556        /**
     557         * Creates, or brings in line with the definition, every table in `tables()`.
    178558         */
    179559        protected function create_tables() {
    180 
    181                 ( new Database( 'submissions' ) )->create_table(
    182                         array(
    183                                 'id'      => 'BIGINT(20) NOT NULL AUTO_INCREMENT',
    184                                 'form_id' => 'BIGINT(20) NOT NULL',
    185                                 'post_id' => 'BIGINT(20) NOT NULL DEFAULT 0',
    186                                 'user_id' => 'MEDIUMINT(9) NOT NULL DEFAULT 0',
    187                                 'fields'  => 'SMALLINT(3) NOT NULL',
    188                                 'files'   => 'SMALLINT(3) NOT NULL',
    189                                 'ip'      => "VARCHAR(45) NOT NULL DEFAULT '0.0.0.0'",
    190                                 'seen'    => 'TINYINT(2) NOT NULL DEFAULT 0',
    191                                 'time'    => 'INT(10) NOT NULL',
    192                         )
    193                 );
    194 
    195                 ( new Database( 'submission_data' ) )->create_table(
    196                         array(
    197                                 'id'            => 'BIGINT(20) NOT NULL AUTO_INCREMENT',
    198                                 'submission_id' => 'BIGINT(20) NOT NULL',
    199                                 'field'         => 'VARCHAR(255) NOT NULL',
    200                                 'value'         => 'LONGTEXT NOT NULL',
    201                         )
    202                 );
    203 
    204                 ( new Database( 'submission_files' ) )->create_table(
    205                         array(
    206                                 'id'            => 'BIGINT(20) NOT NULL AUTO_INCREMENT',
    207                                 'submission_id' => 'BIGINT(20) NOT NULL',
    208                                 'field'         => 'VARCHAR(255) NOT NULL',
    209                                 'name'          => 'VARCHAR(255) NOT NULL',
    210                                 'path'          => 'TEXT NOT NULL',
    211                                 'type'          => 'VARCHAR(255) NOT NULL',
    212                                 'size'          => 'BIGINT(20) NOT NULL',
    213                         )
    214                 );
     560                foreach ( $this->tables() as $name => $definition ) {
     561                        ( new Database( $name ) )->create_table( $definition['columns'], $definition['options'] );
     562                }
    215563        }
    216564
  • cf7-submissions/trunk/app/Bootstrap/Uninstaller.php

    r3836469 r3841460  
    55
    66use CF7_Submissions\Helpers\Filesystem;
     7use CF7_Submissions\Helpers\Lock;
    78use CF7_Submissions\Models\Database;
    89
    … …  
    1920         * @var string[]
    2021         */
    21         private $tables = array( 'submissions', 'submission_data', 'submission_files' );
     22        private $tables = array( 'submissions', 'submission_data', 'submission_files', 'leads', 'lead_events', 'lead_notes', 'audit_log' );
    2223
    2324        /**
    … …  
    2930                'cf7-submissions_activated',
    3031                'cf7-submissions_db_version',
    31                 'cf7-submissions_upgrade_lock',
     32                'cf7-submissions_backfill',
     33                'cf7-submissions_orphans_dismissed',
     34                'cf7-submissions_delete_data',
     35                'cf7-submissions_erase_submissions',
     36                'cf7-submissions_secret',
     37                'cf7-submissions_event_retention_days',
    3238                // Written by releases before 0.9.0.
    3339                'cf7s-submissions_version',
    … …  
    4955                 * only erased when a site opts in, so deleting the plugin never loses them.
    5056                 */
    51                 if ( apply_filters( 'cf7-submissions_delete_data_on_uninstall', false ) ) {
     57                if ( apply_filters( 'cf7-submissions_delete_data_on_uninstall', (bool) get_option( 'cf7-submissions_delete_data', false ) ) ) {
    5258                        $uninstaller->drop_tables();
    5359                        $uninstaller->remove_uploads();
    … …  
    9399                delete_transient( 'cf7-submissions_upgrade_failed' );
    94100                delete_transient( 'cf7-submissions_orphans' );
     101
     102                Lock::purge();
    95103        }
    96104}
  • cf7-submissions/trunk/app/Controllers/Admin/Contact.php

    r3836469 r3841460  
    44defined( 'ABSPATH' ) || exit;
    55
     6use CF7_Submissions\Bootstrap\Installer;
     7use CF7_Submissions\Helpers\Caps;
     8use CF7_Submissions\Helpers\Reply_Headers;
     9use CF7_Submissions\Leads\Field_Map;
     10use CF7_Submissions\Leads\Lead;
     11use CF7_Submissions\Models\Database;
    612use CF7_Submissions\Traits\Hook;
    713
    … …  
    3036                        ! isset( $_REQUEST['cf7sub_nonce'] )
    3137                        || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST['cf7sub_nonce'] ) ), 'cf7-submissions' )
    32                         || ! current_user_can( 'manage_options' )
     38                        || ! cf7sub_user_can( Caps::MANAGE_LEADS )
    3339                ) {
    3440                        wp_send_json_error(
    … …  
    5258                }
    5359
     60                // Only an address the submission holds, or a lead's own, so this cannot be used to mail strangers.
     61                foreach ( $recipients as $recipient ) {
     62                        if ( ! $this->may_reply_to( $recipient, $id ) ) {
     63                                $lead = Lead::find_by_email( $recipient );
     64
     65                                $this->fail(
     66                                        $lead && 'blocked' === $lead['email_status']
     67                                                ? __( 'Failed. This address is blocked from receiving email.', 'cf7-submissions' )
     68                                                : __( 'Failed. Please choose a recipient from the list.', 'cf7-submissions' )
     69                                );
     70                        }
     71                }
     72
    5473                if ( '' === $subject ) {
    5574                        $this->fail( __( 'Failed. Please add a subject.', 'cf7-submissions' ) );
    … …  
    6079                }
    6180
    62                 if ( ! wp_mail( $recipients, $subject, $message ) ) {
     81                if ( ! wp_mail( $recipients, $subject, $message, $this->headers( $id ) ) ) {
    6382                        $this->fail( __( 'Failed. The email could not be sent.', 'cf7-submissions' ) );
     83                }
     84
     85                // Note the reply on the lead's timeline. A lead problem must not turn a sent email into a failure.
     86                if ( Installer::schema_ready( Installer::ACTIVITY_VERSION ) ) {
     87                        try {
     88                                foreach ( $recipients as $recipient ) {
     89                                        Lead::record_reply( $recipient, $subject, $message, get_current_user_id() );
     90                                }
     91                        } catch ( \Throwable $e ) {
     92                                unset( $e );
     93                        }
    6494                }
    6595
    … …  
    71101                        200
    72102                );
     103        }
     104
     105        /**
     106         * Whether a reply may go to an address.
     107         *
     108         * Yes for a lead's address (unless it is blocked), or for an address among the values of
     109         * the submission the reply is about.
     110         *
     111         * @param string $email         Address.
     112         * @param int    $submission_id Submission the reply is about. 0 when none.
     113         * @return bool
     114         */
     115        public function may_reply_to( $email, $submission_id ) {
     116                global $wpdb;
     117
     118                $normal = Field_Map::normalise_email( $email );
     119
     120                if ( '' === $normal ) {
     121                        return false;
     122                }
     123
     124                $lead = Lead::find_by_email( $normal );
     125
     126                if ( $lead ) {
     127                        return 'blocked' !== $lead['email_status'];
     128                }
     129
     130                if ( ! $submission_id ) {
     131                        return false;
     132                }
     133
     134                $table = ( new Database( 'submission_data' ) )->get_table();
     135
     136                return (bool) $wpdb->get_var(
     137                        $wpdb->prepare(
     138                                "SELECT id FROM {$table} WHERE submission_id = %d AND LOWER(TRIM(value)) = %s LIMIT 1", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name from $wpdb->prefix.
     139                                (int) $submission_id,
     140                                $normal
     141                        )
     142                );
     143        }
     144
     145        /**
     146         * Headers for a reply to a submission: the From (and Reply-To) its form is set up with.
     147         *
     148         * Never fails the reply. A missing submission or form, or an unusable value, gives no
     149         * headers, and WordPress sends with its own default.
     150         *
     151         * @param int $submission_id Submission ID.
     152         * @return string[]
     153         */
     154        public function headers( $submission_id ) {
     155                try {
     156                        $submission = $submission_id ? ( new Database( 'submissions' ) )->get_by_id( (int) $submission_id ) : null;
     157
     158                        return $submission ? Reply_Headers::for_form( (int) $submission->form_id ) : array();
     159                } catch ( \Throwable $e ) {
     160                        return array();
     161                }
    73162        }
    74163
  • cf7-submissions/trunk/app/Controllers/Admin/Init.php

    r3836469 r3841460  
    2424                $this->action( 'admin_footer', array( $this, 'modal' ) );
    2525                $this->action( 'admin_notices', array( $this, 'orphan_notice' ) );
     26                $this->action( 'admin_post_cf7sub_dismiss_orphans', array( $this, 'dismiss_orphans' ) );
    2627                $this->filter( 'plugin_action_links_contact-form-7/wp-contact-form-7.php', array( $this, 'action_links' ) );
    2728                $this->filter( 'plugin_action_links_' . plugin_basename( CF7_SUBMISSIONS_FILE ), array( $this, 'action_links' ) );
    … …  
    4950                        'confirm'      => esc_html__( 'Are you sure you want to delete this? The data and its associated files will be completely erased. This action cannot be undone!', 'cf7-submissions' ),
    5051                        'confirm_all'  => esc_html__( 'Are you sure you want to delete these? The data and their associated files will be completely erased. This action cannot be undone!', 'cf7-submissions' ),
     52                        'unexpected'   => esc_html__( 'The server sent an unexpected reply. Check your PHP error log, or the browser console for the details.', 'cf7-submissions' ),
    5153                        'submissions'  => cf7sub_submission_counts(),
    5254                );
    … …  
    6062         * Before the IP column was widened, an entry from an IPv6 visitor failed to save its
    6163         * row but still wrote its field values with `submission_id = 0`. Those entries never
    62          * show in the list. The count is cached for an hour.
    63          *
    64          * @return int
    65          */
    66         public function orphan_count() {
    67                 $count = get_transient( 'cf7-submissions_orphans' );
    68 
    69                 if ( false === $count ) {
    70                         $count = ( new Database( 'submission_data' ) )->get_count( array( array( 'submission_id' => 0 ) ) );
    71                         set_transient( 'cf7-submissions_orphans', $count, HOUR_IN_SECONDS );
    72                 }
    73 
    74                 return (int) $count;
     64         * show in the list. The result is cached for an hour.
     65         *
     66         * `entries` is a lower bound: the most common field name appears once per lost entry
     67         * of that form, so the largest count of any one field is at least the number of entries.
     68         *
     69         * @return array{values:int,entries:int}
     70         */
     71        public function orphans() {
     72                global $wpdb;
     73
     74                $stats = get_transient( 'cf7-submissions_orphans' );
     75
     76                if ( ! is_array( $stats ) ) {
     77                        $table = ( new Database( 'submission_data' ) )->get_table();
     78
     79                        $stats = array(
     80                                'values'  => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE submission_id = 0" ), // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name from $wpdb->prefix.
     81                                'entries' => (int) $wpdb->get_var( "SELECT MAX(n) FROM ( SELECT COUNT(*) AS n FROM {$table} WHERE submission_id = 0 GROUP BY field ) AS per_field" ), // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name from $wpdb->prefix.
     82                        );
     83
     84                        set_transient( 'cf7-submissions_orphans', $stats, HOUR_IN_SECONDS );
     85                }
     86
     87                return $stats;
     88        }
     89
     90        /**
     91         * The notice about orphaned values, or an empty string when there is nothing to say.
     92         *
     93         * Hidden once dismissed, and shown again only if more orphaned values turn up than
     94         * were there when it was dismissed.
     95         *
     96         * @return string HTML.
     97         */
     98        public function orphan_notice_html() {
     99                $stats = $this->orphans();
     100
     101                if ( $stats['values'] < 1 || $stats['values'] <= (int) get_option( 'cf7-submissions_orphans_dismissed', 0 ) ) {
     102                        return '';
     103                }
     104
     105                $entries = max( 1, $stats['entries'] );
     106
     107                $text = sprintf(
     108                        /* translators: 1: number of saved field values, 2: "at least N lost entry/entries". */
     109                        _n(
     110                                '%1$s saved field value belongs to no submission, so it is not in the list (from %2$s). It was saved before the 0.80 fix, when a visitor with an IPv6 address made an entry fail to save. The data is still in your database; a recovery tool is planned.',
     111                                '%1$s saved field values belong to no submission, so they are not in the list (from %2$s). They were saved before the 0.80 fix, when a visitor with an IPv6 address made an entry fail to save. The data is still in your database; a recovery tool is planned.',
     112                                $stats['values'],
     113                                'cf7-submissions'
     114                        ),
     115                        number_format_i18n( $stats['values'] ),
     116                        sprintf(
     117                                /* translators: %s: number of lost entries. */
     118                                _n( 'at least %s lost entry', 'at least %s lost entries', $entries, 'cf7-submissions' ),
     119                                number_format_i18n( $entries )
     120                        )
     121                );
     122
     123                return sprintf(
     124                        '<div class="notice notice-warning"><p>%1$s <a href="%2$s">%3$s</a></p></div>',
     125                        esc_html( $text ),
     126                        esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=cf7sub_dismiss_orphans' ), 'cf7sub_dismiss_orphans' ) ),
     127                        esc_html__( 'Dismiss', 'cf7-submissions' )
     128                );
    75129        }
    76130
    … …  
    85139                }
    86140
    87                 $count = $this->orphan_count();
    88 
    89                 if ( ! $count ) {
    90                         return;
    91                 }
    92 
    93                 printf(
    94                         '<div class="notice notice-warning"><p>%s</p></div>',
    95                         esc_html(
    96                                 sprintf(
    97                                         /* translators: %s: number of saved field values. */
    98                                         _n(
    99                                                 '%s saved field value belongs to no entry. It comes from a form submitted before the IPv6 fix and cannot be shown in the list. A recovery tool is planned.',
    100                                                 '%s saved field values belong to no entry. They come from forms submitted before the IPv6 fix and cannot be shown in the list. A recovery tool is planned.',
    101                                                 $count,
    102                                                 'cf7-submissions'
    103                                         ),
    104                                         number_format_i18n( $count )
    105                                 )
    106                         )
    107                 );
     141                echo $this->orphan_notice_html(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped when built.
     142        }
     143
     144        /**
     145         * Remembers how many orphaned values were there, so the notice stays away until there are more.
     146         *
     147         * @return void
     148         */
     149        public function remember_orphans_dismissal() {
     150                update_option( 'cf7-submissions_orphans_dismissed', $this->orphans()['values'], false );
     151        }
     152
     153        /**
     154         * Handles the Dismiss link, then returns to the page it came from.
     155         *
     156         * @return void
     157         */
     158        public function dismiss_orphans() {
     159                check_admin_referer( 'cf7sub_dismiss_orphans' );
     160
     161                if ( ! current_user_can( 'manage_options' ) ) {
     162                        wp_die( esc_html__( 'You are not allowed to do this.', 'cf7-submissions' ), '', array( 'response' => 403 ) );
     163                }
     164
     165                $this->remember_orphans_dismissal();
     166
     167                wp_safe_redirect( wp_get_referer() ? wp_get_referer() : admin_url( 'admin.php?page=cf7-submissions' ) );
     168                exit;
    108169        }
    109170
  • cf7-submissions/trunk/app/Controllers/Admin/Menu.php

    r3836469 r3841460  
    44defined( 'ABSPATH' ) || exit;
    55
     6use CF7_Submissions\Helpers\Caps;
    67use CF7_Submissions\Traits\Hook;
    78use CF7_Submissions\Traits\Menu as Menu_Trait;
    … …  
    1011
    1112/**
    12  * Registers the Submissions screen under Contact Form 7's menu and renders it.
     13 * Registers the top-level Submissions menu, next to Contact Form 7's, and renders it.
    1314 */
    1415class Menu {
    … …  
    2526
    2627        /**
    27          * Registers the submenu and the Submissions column on CF7's forms list.
     28         * Registers the Submissions menu and the Submissions column on CF7's forms list.
    2829         *
    2930         * @return void
    … …  
    3738                $this->filter( 'manage_' . get_plugin_page_hookname( 'wpcf7', $parent ) . '_columns', array( $this, 'add_table_column' ), 11 );
    3839
    39                 $menu_title = esc_html__( 'Submissions', 'cf7-submissions' );
    40                 $unread     = current_user_can( 'manage_options' ) ? $this->unread_count() : 0;
    41 
    42                 if ( $unread > 0 ) {
    43                         $menu_title .= sprintf(
    44                                 ' <span class="awaiting-mod count-%1$d"><span class="pending-count">%2$s</span></span>',
    45                                 $unread,
    46                                 esc_html( number_format_i18n( $unread ) )
    47                         );
    48                 }
    49 
    50                 $this->add_submenu(
    51                         $parent,
    52                         esc_html__( 'Submissions', 'cf7-submissions' ),
    53                         $menu_title,
    54                         'manage_options',
    55                         'cf7-submissions',
    56                         array( $this, 'callback_main_menu' )
    57                 );
     40                $title    = esc_html__( 'Submissions', 'cf7-submissions' );
     41                $callback = array( $this, 'callback_main_menu' );
     42
     43                $capability = $this->menu_capability();
     44
     45                $this->add_menu( $title, $title, $capability, 'cf7-submissions', $callback, 'dashicons-feedback', $this->position_after( $parent ) );
     46
     47                // Without this WordPress names the first submenu item after the menu; it is the Submissions list.
     48                $this->add_submenu( 'cf7-submissions', $title, $title, $capability, 'cf7-submissions', $callback );
     49
     50                $this->add_unread_badge( current_user_can( 'manage_options' ) ? $this->unread_count() : 0 );
     51        }
     52
     53        /**
     54         * The capability the menu and its first item are registered with.
     55         *
     56         * Administrators get what they always had. Someone who only holds a Leads or Settings
     57         * capability still has to reach the menu, because WordPress refuses a submenu page
     58         * whose parent the user may not open. The Submissions list itself stays admin-only:
     59         * `callback_main_menu()` shows them a pointer instead.
     60         *
     61         * @return string
     62         */
     63        private function menu_capability() {
     64                if ( current_user_can( 'manage_options' ) ) {
     65                        return 'manage_options';
     66                }
     67
     68                foreach ( array( Caps::VIEW_LEADS, Caps::MANAGE_SETTINGS ) as $capability ) {
     69                        if ( current_user_can( $capability ) ) {
     70                                return $capability;
     71                        }
     72                }
     73
     74                return 'manage_options';
     75        }
     76
     77        /**
     78         * Appends the unread count to the menu's label.
     79         *
     80         * Added after the menu is registered, not in its title: WordPress derives the screen
     81         * ID from the title, so a count in it would change the ID (and the saved column
     82         * preferences) with every new entry.
     83         *
     84         * @param int $count Unread submissions.
     85         * @return void
     86         */
     87        private function add_unread_badge( $count ) {
     88                global $menu;
     89
     90                if ( $count < 1 ) {
     91                        return;
     92                }
     93
     94                foreach ( (array) $menu as $position => $item ) {
     95                        if ( isset( $item[2] ) && 'cf7-submissions' === $item[2] ) {
     96                                $menu[ $position ][0] .= sprintf( // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
     97                                        ' <span class="awaiting-mod count-%1$d"><span class="pending-count">%2$s</span></span>',
     98                                        $count,
     99                                        esc_html( number_format_i18n( $count ) )
     100                                );
     101                                return;
     102                        }
     103                }
     104        }
     105
     106        /**
     107         * Menu position that places this menu directly after Contact Form 7's.
     108         *
     109         * CF7 sits at position 30 unless another plugin moved it, so its real slot is read
     110         * from the menu rather than assumed. WordPress keeps a fractional position unique,
     111         * so the menu lands right below CF7's without pushing other items around.
     112         *
     113         * @param string $parent CF7's menu slug.
     114         * @return float
     115         */
     116        private function position_after( $parent ) {
     117                global $menu;
     118
     119                foreach ( (array) $menu as $position => $item ) {
     120                        if ( isset( $item[2] ) && $parent === $item[2] ) {
     121                                return (float) $position + 0.01;
     122                        }
     123                }
     124
     125                return 30.01;
    58126        }
    59127
    … …  
    117185         */
    118186        public function callback_main_menu() {
     187
     188                // Reached through a Leads or Settings capability only: the submissions are not theirs to read.
     189                if ( ! current_user_can( 'manage_options' ) ) {
     190                        printf(
     191                                '<div class="wrap"><h1>%1$s</h1><p>%2$s</p>%3$s</div>',
     192                                esc_html__( 'Submissions', 'cf7-submissions' ),
     193                                esc_html__( 'The submissions list is for administrators.', 'cf7-submissions' ),
     194                                current_user_can( Caps::VIEW_LEADS ) ? sprintf( '<p><a class="button" href="%1$s">%2$s</a></p>', esc_url( add_query_arg( 'page', 'cf7-submissions-leads', admin_url( 'admin.php' ) ) ), esc_html__( 'Go to Leads', 'cf7-submissions' ) ) : ''
     195                        );
     196                        return;
     197                }
    119198
    120199                echo '<div class="wrap metabox-holder">';
  • cf7-submissions/trunk/app/Controllers/Common/Submission.php

    r3836469 r3841460  
    4949
    5050                // phpcs:disable WordPress.Security.NonceVerification.Missing
     51                // A user ID the site did not sign (forged, tampered or missing) is stored as 0.
     52                $user_id = isset( $_POST['cf7s-user_id'] ) ? cf7sub_verify_user_id( sanitize_text_field( wp_unslash( $_POST['cf7s-user_id'] ) ) ) : 0;
     53
    5154                $submission_id = ( new Submission_Model() )->store(
    5255                        array(
    5356                                'form_id' => isset( $_POST['_wpcf7'] ) ? absint( $_POST['_wpcf7'] ) : 0,
    5457                                'post_id' => isset( $_POST['_wpcf7_container_post'] ) ? absint( $_POST['_wpcf7_container_post'] ) : 0,
    55                                 'user_id' => isset( $_POST['cf7s-user_id'] ) ? absint( $_POST['cf7s-user_id'] ) : 0,
     58                                'user_id' => $user_id,
    5659                                'ip'      => cf7sub_user_ip(),
    5760                                'time'    => date_i18n( 'U' ),
  • cf7-submissions/trunk/app/Helpers/Utility.php

    r3836469 r3841460  
    5050                 * Filters the theme directory searched for template overrides.
    5151                 *
    52                  * A theme overrides `views/submissions/single.php` by providing `cf7-submissions/single.php`.
     52                 * A theme overrides `views/submissions/single.php` by providing `cf7-submissions/single.php`
     53                 * (the `submissions/` folder is left out, as it always was) and any other view by its
     54                 * path below `views/`, for example `cf7-submissions/leads/single.php` or
     55                 * `cf7-submissions/partials/reply-box.php`. Two views named `single.php` no longer
     56                 * replace each other.
    5357                 *
    5458                 * @param string $dir      Directory, with trailing slash.
    … …  
    5761                 */
    5862                $override_dir = apply_filters( 'cf7sub_template_overwrite_dir', get_stylesheet_directory() . '/cf7-submissions/', $template, $args );
    59                 $override     = trailingslashit( $override_dir ) . basename( $template );
     63                $override     = trailingslashit( $override_dir ) . ( 0 === strpos( $template, 'submissions/' ) ? basename( $template ) : $template );
    6064
    6165                if ( file_exists( $override ) ) {
    … …  
    7781
    7882                return ob_get_clean();
     83        }
     84
     85        /**
     86         * An array a filter returned, or the fallback when a callback returned something else.
     87         *
     88         * Takes the value as mixed on purpose: a third-party callback can return anything, and a
     89         * list of columns or actions must stay a list.
     90         *
     91         * @param mixed $value    What the filter returned.
     92         * @param array $fallback What it was given.
     93         * @return array
     94         */
     95        public static function array_or( $value, array $fallback ) {
     96                return is_array( $value ) ? $value : $fallback;
    7997        }
    8098
  • cf7-submissions/trunk/app/Helpers/functions.php

    r3836469 r3841460  
    1515use CF7_Submissions\Models\Database;
    1616
     17if ( ! function_exists( 'cf7sub_user_can' ) ) {
     18        /**
     19         * Whether the current user holds one of the plugin's capabilities.
     20         *
     21         * Anyone who can manage options passes as well, so an administrator is never locked out.
     22         *
     23         * @param string $capability One of the `Caps` constants.
     24         * @return bool
     25         */
     26        function cf7sub_user_can( $capability ) {
     27                return current_user_can( $capability ) || current_user_can( 'manage_options' ); // phpcs:ignore WordPress.WP.Capabilities.Unknown -- registered by this plugin.
     28        }
     29}
     30
    1731if ( ! function_exists( 'cf7sub_upload_dir' ) ) {
    1832        /**
    … …  
    2640}
    2741
     42if ( ! function_exists( 'cf7sub_secret' ) ) {
     43        /**
     44         * Site secret used to sign the hidden user-id field.
     45         *
     46         * Created lazily with `add_option()` (atomic), so two requests racing on a fresh
     47         * site end up with the same value. If it cannot be stored, a key derived from the
     48         * WordPress salts is used instead, so the signature never falls back to a key
     49         * anybody could compute.
     50         *
     51         * @return string
     52         */
     53        function cf7sub_secret() {
     54                $secret = get_option( 'cf7-submissions_secret' );
     55
     56                if ( ! is_string( $secret ) || '' === $secret ) {
     57                        try {
     58                                add_option( 'cf7-submissions_secret', bin2hex( random_bytes( 32 ) ), '', false );
     59                        } catch ( \Exception $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
     60                                // No source of randomness: use the salt-derived key below.
     61                        }
     62
     63                        $secret = get_option( 'cf7-submissions_secret' );
     64                }
     65
     66                if ( ! is_string( $secret ) || '' === $secret ) {
     67                        $secret = hash_hmac( 'sha256', 'cf7-submissions', wp_salt( 'auth' ) );
     68                }
     69
     70                return $secret;
     71        }
     72}
     73
     74if ( ! function_exists( 'cf7sub_sign_user_id' ) ) {
     75        /**
     76         * Signs a user ID: `{id}.{hmac}`. Guests (0) stay a bare `0`.
     77         *
     78         * The value is not bound to a form. The signature only has to prove the ID was
     79         * issued by this site, and tying it to Contact Form 7's "current form" would drop
     80         * the user whenever that guess is wrong.
     81         *
     82         * @param int $user_id User ID.
     83         * @return string
     84         */
     85        function cf7sub_sign_user_id( $user_id ) {
     86                $user_id = absint( $user_id );
     87
     88                if ( ! $user_id ) {
     89                        return '0';
     90                }
     91
     92                return $user_id . '.' . hash_hmac( 'sha256', 'user|' . $user_id, cf7sub_secret() );
     93        }
     94}
     95
     96if ( ! function_exists( 'cf7sub_verify_user_id' ) ) {
     97        /**
     98         * Returns the user ID in a signed value, or 0 when it is missing, malformed or forged.
     99         *
     100         * @param mixed $value The posted `cf7s-user_id`.
     101         * @return int
     102         */
     103        function cf7sub_verify_user_id( $value ) {
     104                if ( ! is_string( $value ) || false === strpos( $value, '.' ) ) {
     105                        return 0;
     106                }
     107
     108                list( $user_id, $mac ) = explode( '.', $value, 2 );
     109
     110                // Canonical digits only: no sign, no leading zeros, no overflow.
     111                if ( ! ctype_digit( $user_id ) || (string) (int) $user_id !== $user_id || (int) $user_id < 1 ) {
     112                        return 0;
     113                }
     114
     115                return hash_equals( hash_hmac( 'sha256', 'user|' . $user_id, cf7sub_secret() ), $mac ) ? (int) $user_id : 0;
     116        }
     117}
     118
     119if ( ! function_exists( 'cf7sub_hidden_field_names' ) ) {
     120        /**
     121         * Names of the hidden fields this plugin adds. They are plumbing, never stored as data.
     122         *
     123         * @return string[]
     124         */
     125        function cf7sub_hidden_field_names() {
     126                return array( 'cf7s-user_id', 'cf7sub_nonce' );
     127        }
     128}
     129
    28130if ( ! function_exists( 'cf7sub_hidden_fields' ) ) {
    29131        /**
    … …  
    34136        function cf7sub_hidden_fields() {
    35137                return array(
    36                         'cf7s-user_id' => get_current_user_id(),
     138                        'cf7s-user_id' => cf7sub_sign_user_id( get_current_user_id() ),
    37139                        'cf7sub_nonce' => wp_create_nonce( 'cf7-submissions' ),
    38140                );
  • cf7-submissions/trunk/app/Models/Database.php

    r3836469 r3841460  
    8787                // Add primary key.
    8888                if ( ! empty( $options['primary_key'] ) ) {
    89                         $sql .= "PRIMARY KEY ({$options['primary_key']}),\n";
     89                        $sql .= "PRIMARY KEY  ({$options['primary_key']}),\n";
    9090                } else {
    91                         $sql .= "PRIMARY KEY ({$this->primary_key}),\n";
     91                        $sql .= "PRIMARY KEY  ({$this->primary_key}),\n";
    9292                }
    9393
    … …  
    102102                if ( ! empty( $options['indexes'] ) ) {
    103103                        foreach ( $options['indexes'] as $index => $columns ) {
    104                                 $sql .= "INDEX $index ($columns),\n";
     104                                $sql .= "KEY $index ($columns),\n";
    105105                        }
    106106                }
    … …  
    113113
    114114                // Check if the table exists after creation.
    115                 if ( $this->db->get_var( "SHOW TABLES LIKE '{$this->table_name}'" ) === null ) {
    116                         return false;
    117                 }
    118 
    119                 return true;
     115                $like = $this->db->prepare( 'SHOW TABLES LIKE %s', $this->db->esc_like( $this->table_name ) );
     116
     117                return $this->table_name === $this->db->get_var( $like );
    120118        }
    121119
  • cf7-submissions/trunk/app/Models/Submission.php

    r3836469 r3841460  
    44defined( 'ABSPATH' ) || exit;
    55
     6use CF7_Submissions\Bootstrap\Installer;
     7use CF7_Submissions\Leads\Lead;
    68use CF7_Submissions\Helpers\Filesystem;
    79
    … …  
    7678                }
    7779
    78                 $hidden = cf7sub_hidden_fields();
     80                $hidden = array_flip( cf7sub_hidden_field_names() );
    7981
    8082                foreach ( $posted_data as $key => $value ) {
    … …  
    100102
    101103                $this->store_files( $submission_id, $uploaded_files );
     104
     105                // Link the entry to a lead. Skipped until the leads schema is in place; the backfill catches up.
     106                if ( Installer::schema_ready() ) {
     107                        Lead::capture( $submission_id, array_diff_key( $posted_data, $hidden, $uploaded_files ), (int) $meta['time'], (int) $meta['form_id'] );
     108                }
    102109
    103110                return $submission_id;
    … …  
    176183                $dir           = trailingslashit( cf7sub_upload_dir() );
    177184
     185                // Remember whose it was, so that lead's count can be fixed afterwards.
     186                $row     = Installer::schema_ready() ? $this->submissions->get_by_id( $submission_id ) : null;
     187                $lead_id = $row && ! empty( $row->lead_id ) ? (int) $row->lead_id : 0;
     188
    178189                // Files first, while the rows that name them still exist.
    179190                $files = $this->files->get_rows( array( array( 'submission_id' => $submission_id ) ) );
    … …  
    186197                $this->data->delete_where( array( 'submission_id' => $submission_id ) );
    187198                $this->files->delete_where( array( 'submission_id' => $submission_id ) );
     199
     200                if ( $lead_id ) {
     201                        Lead::recount( array( $lead_id ) );
     202                }
    188203        }
    189204
  • cf7-submissions/trunk/app/Traits/Menu.php

    r3836469 r3841460  
    2828                add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
    2929        }
     30
     31        /**
     32         * Add a top-level menu page in the WordPress admin dashboard.
     33         *
     34         * @param string          $page_title Title tag text of the page.
     35         * @param string          $menu_title Text shown in the menu.
     36         * @param string          $capability Capability required to see the menu.
     37         * @param string          $menu_slug  Unique slug of the page.
     38         * @param callable|string $callback   Function that outputs the page.
     39         * @param string          $icon       Dashicons class or URL of the menu icon.
     40         * @param float|int|null  $position   Position in the menu order.
     41         */
     42        public function add_menu( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $icon = '', $position = null ) {
     43
     44                add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $callback, $icon, $position );
     45        }
    3046}
  • cf7-submissions/trunk/assets/admin/css/style.css

    r3836469 r3841460  
    5656.button.cf7s-send {
    5757    float: right;
     58}
     59#cf7s-contact-msg {
     60    display: inline-block;
     61    max-width: calc(100% - 120px);
     62    line-height: 28px;
     63    font-weight: 600;
     64}
     65#cf7s-contact-msg.cf7s-msg-ok {
     66    color: #007017;
     67}
     68#cf7s-contact-msg.cf7s-msg-error {
     69    color: #b32d2e;
    5870}
    5971#cf7s-actions-wrap p label {
  • cf7-submissions/trunk/assets/admin/js/init.js

    r3836469 r3841460  
    66                jQuery('#cf7-submissions-modal').hide();
    77        }
     8}
     9
     10// Shows the outcome of sending a reply next to the button: green when sent, red when not.
     11let cf7s_reply_message = ( text, sent ) => {
     12        jQuery('#cf7s-contact-msg')
     13                .text(text)
     14                .toggleClass('cf7s-msg-ok', !!sent)
     15                .toggleClass('cf7s-msg-error', !sent);
    816}
    917
    … …  
    2634        });
    2735
    28         $('#wpcf7-contact-form-list-table table.widefat tr > th > input[type=checkbox]').each(function() {
     36        // The row checkbox sits in a <th> on older WordPress and in a <td> on newer, so match both.
     37        $('#wpcf7-contact-form-list-table table.widefat tbody .check-column > input[type=checkbox]').each(function() {
    2938                var input = $(this);
    30                 var id = input.val();
    31                 input.closest('th').siblings('.column-submissions').html(CF7S.submissions[id]);
     39                var count = CF7S.submissions[ input.val() ];
     40
     41                if ( typeof count !== 'undefined' ) {
     42                        input.closest('tr').find('.column-submissions').html(count);
     43                }
    3244        });
    3345
    … …  
    4456                        dataType: 'JSON',
    4557                        success: function(resp) {
    46                                 $('#cf7s-contact-msg').text(resp.data.message);
    4758                                cf7s_modal(false);
     59
     60                                var data = resp && resp.data;
     61
     62                                // Not the reply we expect (for example a bare "0"): say so instead of staying silent.
     63                                if (!data || typeof data.message === 'undefined') {
     64                                        cf7s_reply_message(CF7S.unexpected, false);
     65                                        return;
     66                                }
     67
     68                                var sent = data.status === 1;
     69                                cf7s_reply_message(data.message, sent);
     70
     71                                // On the lead screen, show the reply on the timeline.
     72                                if (sent && $form.data('reload')) {
     73                                        setTimeout(function () { window.location.reload(); }, 800);
     74                                }
    4875                        },
    49                         error: function(err) {
    50                                 var data = err.responseJSON && err.responseJSON.data;
    51                                 $('#cf7s-contact-msg').text(data && data.message ? data.message : err.statusText);
     76                        error: function(xhr, status) {
    5277                                cf7s_modal(false);
     78
     79                                var data = xhr.responseJSON && xhr.responseJSON.data;
     80                                var text = data && data.message ? data.message : ('parsererror' === status ? CF7S.unexpected : (xhr.statusText || CF7S.unexpected));
     81
     82                                // The raw reply is what tells a developer what went wrong (a PHP notice, a fatal error).
     83                                if (window.console && xhr.responseText) {
     84                                        window.console.error('CF7 Submissions, reply failed:', xhr.status, xhr.responseText.slice(0, 500));
     85                                }
     86
     87                                cf7s_reply_message(text, false);
    5388                        }
    5489                });
  • cf7-submissions/trunk/cf7-submissions.php

    r3836469 r3841460  
    66 * Author URI: https://codexpert.io
    77 * Description: Securely Store and Manage Contact Form 7 Submissions Hassle-Free
    8  * Version: 0.50
     8 * Version: 0.80
    99 * Requires at least: 6.0
    1010 * Tested up to: 7.0
    … …  
    3434
    3535define( 'CF7_SUBMISSIONS_FILE', __FILE__ );
    36 define( 'CF7_SUBMISSIONS_VERSION', '0.50' );
     36define( 'CF7_SUBMISSIONS_VERSION', '0.80' );
    3737
    3838/**
    … …  
    4242 * installer against every existing site.
    4343 */
    44 define( 'CF7_SUBMISSIONS_DB_VERSION', '1.0.1' );
     44define( 'CF7_SUBMISSIONS_DB_VERSION', '1.4.0' );
    4545
    4646define( 'CF7_SUBMISSIONS_PLUGIN_DIR', plugin_dir_path( CF7_SUBMISSIONS_FILE ) );
  • cf7-submissions/trunk/readme.txt

    r3836469 r3841460  
    1 === CF7 Submissions – Securely Store Contact Form 7 Data and Attachments, Reply to the Sender and more ===
     1=== CF7 Submissions – Save Contact Form 7 Entries to the Database, Manage Leads and Reply ===
    22Contributors: pluggable, codexpert, mukto90
    33Donate link: https://pluggable.io/plugin/cf7-submissions
    4 Tags: contact form, contact form 7, contact form 7 submissions, contact form 7 entries, contact form 7 messages
     4Tags: contact form 7, cf7 database, contact form 7 submissions, form entries, leads
    55Requires at least: 6.0
    66Tested up to: 7.0
    7 Stable tag: 0.50
     7Stable tag: 0.80
    88Requires PHP: 7.4
     9Requires Plugins: contact-form-7
    910License: GPLv2 or later
    1011License URI: https://www.gnu.org/licenses/gpl-2.0.html
    1112
    12 Save every Contact Form 7 (CF7) submission and file upload to your database. Filter, read, reply and download, even when emails fail.
     13Save every Contact Form 7 submission and file upload to your database, turn senders into leads and reply from WordPress, even when emails fail.
    1314
    1415== Description ==
    1516
    16 **Contact Form 7 not sending email? Your messages are still safe.**
    17 
    18 Contact Form 7 is one of the most popular form plugins for WordPress, but it does not keep a copy of what your visitors send. Each submission goes out as an email, and then it is gone. If that email fails to send, bounces, lands in spam or gets deleted, the lead is lost for good.
    19 
    20 CF7 Submissions fixes that. It saves every Contact Form 7 entry, along with any uploaded files, to your WordPress database right after the form is submitted, whether the notification email goes out or not. You can then view, filter, reply to and manage every message from your dashboard.
    21 
    22 No setup and no per-form settings. Activate the plugin and every CF7 form on your site starts saving its entries automatically.
    23 
    24 ### Why Save Contact Form 7 Submissions?
    25 
    26 * **Email is not a backup.** Mail servers fail, SMTP gets misconfigured and spam filters hide real inquiries. A stored copy in your database is always there.
     17**Contact Form 7 does not save your form submissions. CF7 Submissions does.**
     18
     19Out of the box, Contact Form 7 (CF7) sends each submission as an email and keeps nothing. If that email fails, bounces, lands in spam or is deleted, the message is gone for good, and so is the person who wrote it.
     20
     21CF7 Submissions stores every Contact Form 7 entry in your WordPress database the moment the form is sent, together with any uploaded files, whether the notification email goes out or not. Then it helps you act on it:
     22
     23* **Read and manage** every entry in a **Submissions** list inside your dashboard.
     24* **Reply** to the sender without leaving WordPress.
     25* **Follow each person** as a lead, with a status, private notes and a timeline of everything that happened.
     26* **Stay in control** of personal data with WordPress's export and erase tools.
     27
     28No account, no API key and no per-form setup. Activate it and every CF7 form on your site starts saving its entries. Your data stays on your own site.
     29
     30### Why Save Contact Form 7 Submissions to the Database?
     31
     32* **Email is not a backup.** Mail servers fail, SMTP gets misconfigured and spam filters hide real enquiries. A copy in your database is always there.
    2733* **Files stay with the message.** Uploaded attachments are kept next to the entry they belong to, not buried in an inbox.
    28 * **One shared inbox for your admins.** Every administrator sees the same list of entries, with clear read and unread status, so no message is answered twice or missed.
    29 * **Your data stays on your site.** Entries are stored in your own WordPress database. Submissions are never sent to another server, and no account or API key is needed. See External Services below for the two optional feedback forms.
     34* **One shared inbox for your team.** Every administrator sees the same entries, with clear read and unread status, so no message is answered twice or missed.
     35* **Your data stays on your site.** Entries are stored in your own WordPress database and are never sent to another server. See External Services below for the two optional feedback forms.
    3036
    3137### How It Works
    … …  
    34402. Visitors fill in your forms exactly as before. Contact Form 7 keeps sending its emails as usual.
    35413. Each submission, including its uploaded files, is saved to your database.
    36 4. Open **Contact > Submissions** to read, filter, reply to, download and delete entries.
     424. Open **Submissions** in the admin menu to read, filter, reply to, download and delete entries, or open **Submissions → Leads** to follow up with each sender.
    3743
    3844### Key Features
    3945
     46#### Store Contact Form 7 Entries
     47
    4048**Automatic Contact Form 7 Database Storage**
    41 Every submission from every CF7 form is saved to dedicated database tables. Entries are stored even when Contact Form 7 fails to send the notification email. Nothing to configure.
     49Every submission from every CF7 form is saved to dedicated database tables, even when Contact Form 7 fails to send the notification email. Spam that Contact Form 7 or its spam protection flags is not saved.
    4250
    4351**Works With Every Field Type**
    … …  
    4755Files uploaded through your forms are copied to a protected folder and linked to their submission. Fields that accept several files are supported, and files with the same name are renamed so nothing is overwritten. Each entry shows the file name, type and size, with a download link that only administrators can use.
    4856
     57#### Manage Submissions
     58
    4959**All Entries in Your Dashboard**
    50 Find the **Submissions** page under the **Contact** menu. The list shows the submission ID, who sent it, the form, the page it came from and the date and time, with sortable columns and pagination.
     60Find the **Submissions** menu in the admin sidebar, right below **Contact**. The list shows the submission ID, who sent it, the form, the page it came from and the date and time, with sortable columns and pagination.
    5161
    5262**Submission Counts on the Contact Forms Screen**
    … …  
    5464
    5565**Filter Submissions**
    56 Narrow the list with the **form**, **container page**, **user** and **status** (read or unread) dropdowns, or click a form, page or user name in the list to filter by it. All entries from visitors who were not logged in are grouped under **Guest Users**.
     66Narrow the list with the **form**, **container page**, **user** and **status** (read or unread) dropdowns, or click a form, page or user name in the list to filter by it. Entries from visitors who were not logged in are grouped under **Guest Users**.
    5767
    5868**Detailed Submission View**
    59 Open an entry to see every field and value, the uploaded files, and its details: submission ID, form name, the page it was sent from, the user (or Guest), IP address and date and time. Use the **Older Submission** and **Newer Submission** buttons to move through entries without going back to the list.
    60 
    61 **Read and Unread Status**
    62 New entries are highlighted in the list. Opening an entry marks it as read automatically, and you can mark it unread again to come back to it later.
    63 
    64 **Unread Count in the Menu**
    65 The **Submissions** menu item shows how many unread entries are waiting, so a new message is noticed on any admin screen.
     69Open an entry to see every field and value, the uploaded files, and its details: submission ID, form name, the page it was sent from, the user (or Guest), IP address and date and time. Use **Older Submission** and **Newer Submission** to move through entries without going back to the list.
     70
     71**Read and Unread Status, With a Count in the Menu**
     72New entries are highlighted. Opening an entry marks it as read, and you can mark it unread again to come back to it. The **Submissions** menu shows how many unread entries are waiting, so a new message is noticed on any admin screen.
     73
     74**Bulk Actions and Clean Deletion**
     75Mark many entries as read or unread, or delete them in one go. Deleting a submission also removes its stored data and attached files, after a confirmation prompt, so nothing is left behind on your server.
     76
     77#### Reply to the Sender
    6678
    6779**Reply From WordPress**
    68 Answer a submitter right from the entry screen. CF7 Submissions finds the email addresses entered in the form and lets you pick one or more recipients, then write a subject and message and send it through WordPress. No copy and paste into an email client.
    69 
    70 **Bulk Actions**
    71 Select many entries and mark them as read, mark them as unread or delete them in one go.
    72 
    73 **Clean Deletion**
    74 Delete one entry from its screen or many from the list. Deleting a submission also removes its stored data and attached files, after a confirmation prompt, so nothing is left behind on your server.
     80Answer a submitter from the entry screen or from their lead. CF7 Submissions finds the email addresses entered in the form and lets you pick the recipient, then write a subject and message and send it through WordPress. No copy and paste into an email client.
     81
     82**Replies Use Your Form's Sender Settings**
     83Replies are sent from the name and address set in the form's **Mail** tab in Contact Form 7, and the recipient is listed by the sender's name. If the form has no usable sender, WordPress's default is used.
     84
     85#### Leads: One Record Per Person
     86
     87**Every Sender, Once**
     88Every submission that has an email address is added to **Submissions → Leads**: one lead per address, with name, phone and company filled in from the form. A second message from the same person updates their lead instead of creating a duplicate.
     89
     90**Status, Notes and a Timeline**
     91Mark each lead **Needs reply**, **Replied**, **Closed** or **Spam**. Keep private notes (note, call, meeting or email) that you can edit and delete. A timeline shows every submission, reply and status change in order.
     92
     93**Find and Act on Leads**
     94Search the list, filter it by form, change the status of many leads at once, block an address, or export the list as a CSV file that opens safely in Excel.
     95
     96**Turn Existing Submissions Into Leads**
     97A one-time build creates leads from the submissions you have already saved. You choose what status they start with, it runs with a progress bar, and what your submissions contain is never changed or deleted.
     98
     99**Choose the Email Field, Per Form**
     100In the Contact Form 7 form editor, the **Leads** tab lets you pick the field that holds the sender's address, or turn leads off for that form. By default the plugin finds it for you.
     101
     102**Block an Address**
     103Block a lead's email address from one lead or in bulk. Replies from the plugin are refused for a blocked address.
     104
     105#### Privacy and Control
     106
     107**Privacy Tools**
     108Leads, notes and submissions are included in WordPress's **Export Personal Data** and **Erase Personal Data** tools. Erasing a person removes their lead and, unless you turn that off in **Submissions → Settings**, their submissions too. A submission that only mentions the address in someone else's entry is left alone.
     109
     110**Keep Activity Only as Long as You Need**
     111Delete a lead's activity (status changes, replies, blocking) automatically after a number of days, in **Submissions → Settings → Privacy**. Notes, leads and submissions are never deleted by it, and it is off by default.
     112
     113**Roles and Permissions**
     114Administrators can do everything. To give another role access, add the capabilities `cf7sub_view_leads`, `cf7sub_manage_leads`, `cf7sub_delete_leads`, `cf7sub_export_leads` or `cf7sub_manage_settings` to it.
    75115
    76116**Lightweight and Secure**
    77 Built only for Contact Form 7. Every admin action is checked with a nonce and is limited to administrators, uploaded files are kept in a folder that blocks direct access on Apache servers, and downloads go through a guarded handler. Translation ready.
    78 
    79 **For Developers**
    80 Hook into storage and the admin screens with `cf7sub_submission_stored` and `cf7sub_list_before`. Override the list and single views by copying them to `<your-theme>/cf7-submissions/`. Return `true` from the `cf7-submissions_delete_data_on_uninstall` filter to remove all tables and files when the plugin is deleted.
     117Built only for Contact Form 7. Every admin action is checked with a nonce and limited to administrators (or to roles you give the plugin's capabilities). Uploaded files are kept in a folder that blocks direct access on Apache servers, and downloads go through a guarded handler. No scripts or styles are loaded on the pages that show your forms (the plugin only adds two hidden fields to each form), and it is translation ready.
     118
     119#### For Developers
     120
     121Hook into storage and the admin screens with `cf7sub_submission_stored` and `cf7sub_list_before`. Work with leads through `cf7sub_lead_created`, `cf7sub_lead_updated`, `cf7sub_lead_deleted`, `cf7sub_event_logged` and the filters `cf7sub_lead_field_map`, `cf7sub_lead_before_save`, `cf7sub_lead_statuses`, `cf7sub_leads_list_columns` and `cf7sub_leads_bulk_actions`. Override the list and single views by copying them to `<your-theme>/cf7-submissions/`. Return `true` from the `cf7-submissions_delete_data_on_uninstall` filter to remove all tables and files when the plugin is deleted.
    81122
    82123### What Gets Saved With Each Submission
    … …  
    90131* The date and time of the submission
    91132
     133For each sender who gave an email address, a lead is also kept: the address, name, phone, company, status, your notes and an activity timeline. Your own notes are stored on your site and nowhere else.
     134
    92135Because entries can include personal data, remember to mention it in your site's privacy policy.
    93136
    … …  
    136179== Installation ==
    137180
    138 1. Upload `cf7-submissions` to the `/wp-content/plugins/` directory
    139 2. Activate the plugin through the 'Plugins' menu in WordPress
    140 3. Find the `Submissions` submenu under `Contact` menu of Contact Form 7
     1811. Install and activate [Contact Form 7](https://wordpress.org/plugins/contact-form-7/) if you have not already.
     1822. In **Plugins → Add New**, search for **CF7 Submissions**, then click **Install Now** and **Activate**. You can also upload the `cf7-submissions` folder to `/wp-content/plugins/` and activate it from the **Plugins** menu.
     1833. Open the new **Submissions** menu in the admin sidebar, right below **Contact**. Entries from your forms appear here as soon as they are sent.
    141184
    142185== Frequently Asked Questions ==
    143186
     187= Where does Contact Form 7 save form submissions? =
     188
     189By default it does not. Contact Form 7 sends each submission as an email and keeps no copy. CF7 Submissions saves a copy of every entry, and its uploaded files, in your WordPress database so you can read it later in **Submissions**.
     190
     191= How do I save Contact Form 7 submissions to the database? =
     192
     193Install and activate CF7 Submissions next to Contact Form 7. Every form on your site starts saving its entries straight away, with nothing to set up. Open **Submissions** in the admin menu to see them.
     194
    144195= How does it work? =
    145196
    146 CF7 Submissions seamlessly stores all form submissions and associated files from Contact Form 7 in your WordPress database, eliminating the risk of losing important data. It provides a user-friendly dashboard interface where you can easily manage and organize submissions, including marking them as read/unread and deleting unwanted entries.
     197CF7 Submissions hooks into Contact Form 7 when a form is sent and writes the entry and its files to its own database tables. Your visitors and Contact Form 7's emails are not affected. In your dashboard you can read, filter, reply to, download and delete entries, and follow each sender as a lead.
     198
     199= Is it an alternative to Flamingo or CFDB7? =
     200
     201It does the same basic job, keeping Contact Form 7 entries in your database, and adds replies from WordPress, leads with notes and a timeline, and privacy tools. It does not import entries saved by other plugins yet, so older entries stay where they are.
     202
     203= Is it a CRM? =
     204
     205No. It keeps one record per sender with a status, private notes and a timeline, which is enough to follow up on enquiries. It does not send campaigns or manage deals.
    147206
    148207= Does it work with other contact form plugins? =
    … …  
    164223= Do I need to set anything up for each form? =
    165224
    166 No. Once activated, CF7 Submissions saves entries from all your Contact Form 7 forms automatically. There are no settings to configure.
     225No. Once activated, CF7 Submissions saves entries from all your Contact Form 7 forms automatically. The only optional setting per form is the **Leads** tab in the form editor, to choose which field holds the sender's email or to turn leads off for that form.
    167226
    168227= Where can I find the saved submissions? =
    169228
    170 Go to **Contact > Submissions** in your WordPress dashboard. You can also click the count in the **Submissions** column on the Contact Forms list to see the entries of a single form.
     229Go to **Submissions** in your WordPress dashboard. You can also click the count in the **Submissions** column on the Contact Forms list to see the entries of a single form.
    171230
    172231= Will it save submissions that were sent before I installed the plugin? =
    … …  
    188247= Who can see the submissions? =
    189248
    190 Only users who can manage site options, which by default means Administrators.
     249Only users who can manage site options, which by default means Administrators. The leads screens and settings can also be opened up to other roles by giving them the plugin's capabilities (see **Roles and Permissions**).
    191250
    192251= Are uploaded files safe? =
    … …  
    200259= Can I export submissions to CSV or Excel? =
    201260
    202 Not at the moment. Submissions can be viewed, filtered, replied to and deleted from the dashboard.
     261You can export the **Leads** list as a CSV file from **Submissions → Leads**. It contains the leads on screen (the status, form and search you have chosen) and opens safely in Excel. Submissions themselves cannot be exported yet. They can be viewed, filtered, replied to and deleted from the dashboard.
    203262
    204263= What happens to my data if I uninstall the plugin? =
    205264
    206 Your saved submissions and uploaded files are kept in the database and in the uploads folder, so you do not lose them by accident. Delete the submissions from the dashboard before uninstalling if you want them removed, or let a developer return `true` from the `cf7-submissions_delete_data_on_uninstall` filter to remove everything on deletion.
     265Your saved submissions and uploaded files are kept in the database and in the uploads folder, so you do not lose them by accident. To remove everything when the plugin is deleted, turn on **When the plugin is deleted** in **Submissions → Settings** (it is off by default), or let a developer return `true` from the `cf7-submissions_delete_data_on_uninstall` filter.
     266
     267= What are leads, and do I have to use them? =
     268
     269A lead is one person, identified by email address, with all their submissions, your notes and a timeline in one place. They are created automatically when a submission has an email address. You can turn leads off for a single form in its **Leads** tab. Your submissions list works exactly as before.
     270
     271= Can I reply to a sender from WordPress? =
     272
     273Yes. Use the **Contact Sender** box on a submission or on a lead. The email is sent from the name and address in the form's **Mail** tab, and a reply from a lead marks it **Replied**.
     274
     275= What happens to a lead if I delete it? =
     276
     277The lead, its notes and its timeline are deleted. The submissions it came from are kept, and a later message from the same address starts a new lead.
     278
     279= Does it slow down my site? =
     280
     281It adds a few database writes when a form is submitted. No scripts or styles are loaded on the front end; the only addition to a form is two hidden fields.
    207282
    208283= Is CF7 Submissions free? =
    … …  
    212287== Screenshots ==
    213288
    214 1. Submissions list with form, container, user and status filters, unread highlighting and bulk actions
    215 2. Single submission with form data, uploaded files, submission details and the reply box
    216 3. Reply to the sender from WordPress, with recipients picked from the submitted email addresses
    217 4. Submissions count column on the Contact Forms list, linking to each form's entries
     2891. Leads list with status filters, form filter, search and CSV export
     2902. Lead screen with the profile, status, email status and linked submissions
     2913. Reply to a lead from WordPress, add notes and calls, and follow the activity timeline
     2924. Submissions list with the lead each entry belongs to, unread highlighting and bulk actions
     2935. Single submission with form data, submission details and the reply box
     2946. Settings: choose which form field holds the sender's email, per form
     2957. Submissions count column on the Contact Forms list, linking to each form's entries
    218296
    219297== Changelog ==
     298
     299= v0.80 — 2026-12-03 =
     300
     301NEW:
     302
     303- **Leads.** Every submission with an email address is linked to a lead, one per person. The new Leads screen lists them with status filters (Needs reply, Replied, Closed, Spam), a form filter, search, sorting and CSV export
     304- **Lead screen** with an editable profile (name, phone, company, job title), the person's submissions, notes, calls and meetings, and an activity timeline
     305- **Reply from the lead screen.** Replies are sent from the form's own From address, logged on the timeline, and move the lead to Replied
     306- **Block an email address** so replies to it are refused. Unblock restores its earlier state
     307- **Build leads from existing submissions** from the Leads screen, with progress shown while it runs. Choose how old submissions start: all needing a reply, only recent ones, or all closed. Statuses are locked while it runs
     308- **Bulk actions** on Leads: change status, block or unblock an email, delete
     309- **Lead column on the Submissions list**, and the lead's name on a submission links to its screen
     310- **Submissions has its own top-level menu**, with Submissions, Leads and Settings
     311- **Settings** with General, Forms, Privacy and Tools tabs. Forms shows which field holds the sender's email for each form, with a link to change it in the form editor's new Leads tab
     312- **Privacy:** leads and their notes are covered by the WordPress personal-data exporter and eraser, and activity older than a chosen number of days can be deleted automatically. Notes, leads and submissions are never deleted by this
     313- **Roles:** new capabilities `cf7sub_view_leads`, `cf7sub_manage_leads`, `cf7sub_delete_leads`, `cf7sub_export_leads` and `cf7sub_manage_settings`. Administrators have them all with no role changes written to your database
     314
     315FIXES:
     316
     317- **Submission counts were blank on the Contact Forms list** with current WordPress
     318- **A forged user ID could be posted with a form.** The hidden user ID is now signed, and an unsigned value is saved as a guest
     319- **Replies were not always sent from the form's From address**, and the recipient was not named. A site title with square brackets no longer breaks it
     320- Reply recipients are limited to the email addresses the submission contains
     321- The reply form always shows the outcome, in green when sent and red when not, even when the server sends back something unexpected
     322- The database now has an index on the field and file tables, so deleting and opening a submission stays fast on large sites
     323- Leads screen stays fast on large sites: sorted pages past page 50 are loaded with a cursor instead of an offset
     324
     325IMPROVEMENTS:
     326
     327- The Leads list uses one index for sorting, with no full sort on a site with hundreds of thousands of leads
     328- The submission screen and the lead screen share one reply box
     329- Admin screens can be overridden from a theme, in `<theme>/cf7-submissions/leads/single.php` and the like
     330
     331FOR DEVELOPERS:
     332
     333- New filters: `cf7sub_lead_field_map`, `cf7sub_lead_before_save`, `cf7sub_leads_list_columns`, `cf7sub_leads_column_value`, `cf7sub_leads_bulk_actions`, `cf7sub_erase_submissions`
     334- New actions: `cf7sub_lead_created`, `cf7sub_lead_updated`, `cf7sub_lead_deleted`, `cf7sub_leads_bulk_action`, `cf7sub_event_logged`
     335- Helper functions `cf7sub_user_can()`, `cf7sub_sign_user_id()` and `cf7sub_verify_user_id()`
     336- Database version 1.4.0. The upgrade adds the lead tables and indexes on the next admin visit
    220337
    221338= v0.50 — 2026-12-01 =
    … …  
    321438== Upgrade Notice ==
    322439
     440= 0.80 =
     441Adds Leads and a database upgrade that runs on your next admin visit. Saved submissions and files are kept. Back up your site before updating.
     442
    323443= 0.50 =
    324444Internal rewrite. Saved submissions and files are kept. Back up your site before updating. Developers: the `cf7sub_get_posts` filter was renamed `cf7-submissions_get_posts`.
  • cf7-submissions/trunk/vendor/composer/autoload_classmap.php

    r3836469 r3841460  
    1313    'CF7_Submissions\\Bootstrap\\Uninstaller' => $baseDir . '/app/Bootstrap/Uninstaller.php',
    1414    'CF7_Submissions\\Controllers\\Admin\\Contact' => $baseDir . '/app/Controllers/Admin/Contact.php',
     15    'CF7_Submissions\\Controllers\\Admin\\Form_Panel' => $baseDir . '/app/Controllers/Admin/Form_Panel.php',
    1516    'CF7_Submissions\\Controllers\\Admin\\Init' => $baseDir . '/app/Controllers/Admin/Init.php',
     17    'CF7_Submissions\\Controllers\\Admin\\Leads' => $baseDir . '/app/Controllers/Admin/Leads.php',
    1618    'CF7_Submissions\\Controllers\\Admin\\Marketing' => $baseDir . '/app/Controllers/Admin/Marketing.php',
    1719    'CF7_Submissions\\Controllers\\Admin\\Menu' => $baseDir . '/app/Controllers/Admin/Menu.php',
     20    'CF7_Submissions\\Controllers\\Admin\\Settings' => $baseDir . '/app/Controllers/Admin/Settings.php',
    1821    'CF7_Submissions\\Controllers\\Admin\\Submission' => $baseDir . '/app/Controllers/Admin/Submission.php',
    1922    'CF7_Submissions\\Controllers\\Admin\\Table' => $baseDir . '/app/Controllers/Admin/Table.php',
    2023    'CF7_Submissions\\Controllers\\Common\\Submission' => $baseDir . '/app/Controllers/Common/Submission.php',
    2124    'CF7_Submissions\\Controllers\\Front\\Init' => $baseDir . '/app/Controllers/Front/Init.php',
     25    'CF7_Submissions\\Helpers\\Caps' => $baseDir . '/app/Helpers/Caps.php',
    2226    'CF7_Submissions\\Helpers\\Filesystem' => $baseDir . '/app/Helpers/Filesystem.php',
     27    'CF7_Submissions\\Helpers\\Lock' => $baseDir . '/app/Helpers/Lock.php',
     28    'CF7_Submissions\\Helpers\\Reply_Headers' => $baseDir . '/app/Helpers/Reply_Headers.php',
    2329    'CF7_Submissions\\Helpers\\Utility' => $baseDir . '/app/Helpers/Utility.php',
     30    'CF7_Submissions\\Leads\\Audit' => $baseDir . '/app/Leads/Audit.php',
     31    'CF7_Submissions\\Leads\\Backfill' => $baseDir . '/app/Leads/Backfill.php',
     32    'CF7_Submissions\\Leads\\Export' => $baseDir . '/app/Leads/Export.php',
     33    'CF7_Submissions\\Leads\\Field_Map' => $baseDir . '/app/Leads/Field_Map.php',
     34    'CF7_Submissions\\Leads\\Form_Settings' => $baseDir . '/app/Leads/Form_Settings.php',
     35    'CF7_Submissions\\Leads\\Lead' => $baseDir . '/app/Leads/Lead.php',
     36    'CF7_Submissions\\Leads\\Lead_Query' => $baseDir . '/app/Leads/Lead_Query.php',
     37    'CF7_Submissions\\Leads\\List_Table' => $baseDir . '/app/Leads/List_Table.php',
     38    'CF7_Submissions\\Leads\\Notes' => $baseDir . '/app/Leads/Notes.php',
     39    'CF7_Submissions\\Leads\\Retention' => $baseDir . '/app/Leads/Retention.php',
     40    'CF7_Submissions\\Leads\\Timeline' => $baseDir . '/app/Leads/Timeline.php',
    2441    'CF7_Submissions\\Models\\Database' => $baseDir . '/app/Models/Database.php',
    2542    'CF7_Submissions\\Models\\Submission' => $baseDir . '/app/Models/Submission.php',
     43    'CF7_Submissions\\Privacy\\Eraser' => $baseDir . '/app/Privacy/Eraser.php',
     44    'CF7_Submissions\\Privacy\\Exporter' => $baseDir . '/app/Privacy/Exporter.php',
     45    'CF7_Submissions\\Privacy\\Subject' => $baseDir . '/app/Privacy/Subject.php',
    2646    'CF7_Submissions\\Traits\\Asset' => $baseDir . '/app/Traits/Asset.php',
    2747    'CF7_Submissions\\Traits\\Hook' => $baseDir . '/app/Traits/Hook.php',
  • cf7-submissions/trunk/vendor/composer/autoload_static.php

    r3836469 r3841460  
    3232        'CF7_Submissions\\Bootstrap\\Uninstaller' => __DIR__ . '/../..' . '/app/Bootstrap/Uninstaller.php',
    3333        'CF7_Submissions\\Controllers\\Admin\\Contact' => __DIR__ . '/../..' . '/app/Controllers/Admin/Contact.php',
     34        'CF7_Submissions\\Controllers\\Admin\\Form_Panel' => __DIR__ . '/../..' . '/app/Controllers/Admin/Form_Panel.php',
    3435        'CF7_Submissions\\Controllers\\Admin\\Init' => __DIR__ . '/../..' . '/app/Controllers/Admin/Init.php',
     36        'CF7_Submissions\\Controllers\\Admin\\Leads' => __DIR__ . '/../..' . '/app/Controllers/Admin/Leads.php',
    3537        'CF7_Submissions\\Controllers\\Admin\\Marketing' => __DIR__ . '/../..' . '/app/Controllers/Admin/Marketing.php',
    3638        'CF7_Submissions\\Controllers\\Admin\\Menu' => __DIR__ . '/../..' . '/app/Controllers/Admin/Menu.php',
     39        'CF7_Submissions\\Controllers\\Admin\\Settings' => __DIR__ . '/../..' . '/app/Controllers/Admin/Settings.php',
    3740        'CF7_Submissions\\Controllers\\Admin\\Submission' => __DIR__ . '/../..' . '/app/Controllers/Admin/Submission.php',
    3841        'CF7_Submissions\\Controllers\\Admin\\Table' => __DIR__ . '/../..' . '/app/Controllers/Admin/Table.php',
    3942        'CF7_Submissions\\Controllers\\Common\\Submission' => __DIR__ . '/../..' . '/app/Controllers/Common/Submission.php',
    4043        'CF7_Submissions\\Controllers\\Front\\Init' => __DIR__ . '/../..' . '/app/Controllers/Front/Init.php',
     44        'CF7_Submissions\\Helpers\\Caps' => __DIR__ . '/../..' . '/app/Helpers/Caps.php',
    4145        'CF7_Submissions\\Helpers\\Filesystem' => __DIR__ . '/../..' . '/app/Helpers/Filesystem.php',
     46        'CF7_Submissions\\Helpers\\Lock' => __DIR__ . '/../..' . '/app/Helpers/Lock.php',
     47        'CF7_Submissions\\Helpers\\Reply_Headers' => __DIR__ . '/../..' . '/app/Helpers/Reply_Headers.php',
    4248        'CF7_Submissions\\Helpers\\Utility' => __DIR__ . '/../..' . '/app/Helpers/Utility.php',
     49        'CF7_Submissions\\Leads\\Audit' => __DIR__ . '/../..' . '/app/Leads/Audit.php',
     50        'CF7_Submissions\\Leads\\Backfill' => __DIR__ . '/../..' . '/app/Leads/Backfill.php',
     51        'CF7_Submissions\\Leads\\Export' => __DIR__ . '/../..' . '/app/Leads/Export.php',
     52        'CF7_Submissions\\Leads\\Field_Map' => __DIR__ . '/../..' . '/app/Leads/Field_Map.php',
     53        'CF7_Submissions\\Leads\\Form_Settings' => __DIR__ . '/../..' . '/app/Leads/Form_Settings.php',
     54        'CF7_Submissions\\Leads\\Lead' => __DIR__ . '/../..' . '/app/Leads/Lead.php',
     55        'CF7_Submissions\\Leads\\Lead_Query' => __DIR__ . '/../..' . '/app/Leads/Lead_Query.php',
     56        'CF7_Submissions\\Leads\\List_Table' => __DIR__ . '/../..' . '/app/Leads/List_Table.php',
     57        'CF7_Submissions\\Leads\\Notes' => __DIR__ . '/../..' . '/app/Leads/Notes.php',
     58        'CF7_Submissions\\Leads\\Retention' => __DIR__ . '/../..' . '/app/Leads/Retention.php',
     59        'CF7_Submissions\\Leads\\Timeline' => __DIR__ . '/../..' . '/app/Leads/Timeline.php',
    4360        'CF7_Submissions\\Models\\Database' => __DIR__ . '/../..' . '/app/Models/Database.php',
    4461        'CF7_Submissions\\Models\\Submission' => __DIR__ . '/../..' . '/app/Models/Submission.php',
     62        'CF7_Submissions\\Privacy\\Eraser' => __DIR__ . '/../..' . '/app/Privacy/Eraser.php',
     63        'CF7_Submissions\\Privacy\\Exporter' => __DIR__ . '/../..' . '/app/Privacy/Exporter.php',
     64        'CF7_Submissions\\Privacy\\Subject' => __DIR__ . '/../..' . '/app/Privacy/Subject.php',
    4565        'CF7_Submissions\\Traits\\Asset' => __DIR__ . '/../..' . '/app/Traits/Asset.php',
    4666        'CF7_Submissions\\Traits\\Hook' => __DIR__ . '/../..' . '/app/Traits/Hook.php',
  • cf7-submissions/trunk/vendor/composer/installed.php

    r3836469 r3841460  
    22    'root' => array(
    33        'name' => 'codexpert/cf7-submissions',
    4         'pretty_version' => 'v0.50',
    5         'version' => '0.50.0.0',
    6         'reference' => '055daf1d3cbdce14cdac342c1e36ea08748a0e94',
     4        'pretty_version' => 'v0.80',
     5        'version' => '0.80.0.0',
     6        'reference' => 'acf7338fe640696f6a6ed6c7da7738cb7426ecaf',
    77        'type' => 'wordpress-plugin',
    88        'install_path' => __DIR__ . '/../../',
    … …  
    1212    'versions' => array(
    1313        'codexpert/cf7-submissions' => array(
    14             'pretty_version' => 'v0.50',
    15             'version' => '0.50.0.0',
    16             'reference' => '055daf1d3cbdce14cdac342c1e36ea08748a0e94',
     14            'pretty_version' => 'v0.80',
     15            'version' => '0.80.0.0',
     16            'reference' => 'acf7338fe640696f6a6ed6c7da7738cb7426ecaf',
    1717            'type' => 'wordpress-plugin',
    1818            'install_path' => __DIR__ . '/../../',
  • cf7-submissions/trunk/views/submissions/list.php

    r3836469 r3841460  
    11<?php
    22use Codexpert\Plugin\Table;
     3use CF7_Submissions\Bootstrap\Installer;
     4use CF7_Submissions\Leads\Lead;
    35use CF7_Submissions\Models\Database;
    46
    … …  
    4143$admin_url      = admin_url( 'admin.php' );
    4244
    43 $data = array_map( function( $row ) use ( $cf7sub_nonce, $format, $admin_url ) {
     45// One lookup for every lead on the page, not one per row.
     46$show_leads = Installer::schema_ready();
     47$leads      = array();
     48
     49if ( $show_leads ) {
     50        global $wpdb;
     51
     52        $lead_ids = array_unique( array_filter( array_map( 'absint', wp_list_pluck( $data, 'lead_id' ) ) ) );
     53
     54        if ( $lead_ids ) {
     55                foreach ( (array) $wpdb->get_results( 'SELECT id, first_name, last_name, email FROM ' . Lead::table() . ' WHERE id IN (' . implode( ',', $lead_ids ) . ')', ARRAY_A ) as $lead ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- IDs are cast to integers.
     56                        $leads[ (int) $lead['id'] ] = $lead;
     57                }
     58        }
     59}
     60
     61$lead_url = Installer::schema_ready( Installer::ACTIVITY_VERSION );
     62
     63$data = array_map( function( $row ) use ( $cf7sub_nonce, $format, $admin_url, $leads, $lead_url ) {
    4464       
    4565        $row_id = $row['id'];
    … …  
    5979                esc_url( add_query_arg( [ 'page' => 'cf7-submissions', 'user' => $row['user_id'], 'cf7sub_nonce' => $cf7sub_nonce ], $admin_url ) )
    6080        );
     81
     82        // The lead's name, or its email when it has none; a dash when the submission has no lead.
     83        $lead = ! empty( $row['lead_id'] ) && isset( $leads[ (int) $row['lead_id'] ] ) ? $leads[ (int) $row['lead_id'] ] : null;
     84
     85        if ( $lead ) {
     86                $lead_name   = trim( $lead['first_name'] . ' ' . $lead['last_name'] );
     87                $row['lead'] = $lead_url
     88                        ? sprintf( '<a href="%2$s">%1$s</a>', esc_html( '' !== $lead_name ? $lead_name : $lead['email'] ), esc_url( Lead::url( (int) $lead['id'] ) ) )
     89                        : esc_html( '' !== $lead_name ? $lead_name : $lead['email'] );
     90        } else {
     91                $row['lead'] = '&mdash;';
     92        }
    6193
    6294        $row['form']            = sprintf(
    … …  
    92124 * Construct the config list
    93125 */
     126$columns = [
     127        'id'            => esc_html__( 'Submission ID', 'cf7-submissions' ),
     128        'user'          => esc_html__( 'Submitted By', 'cf7-submissions' ),
     129        'form'          => esc_html__( 'Form', 'cf7-submissions' ),
     130        'container'     => esc_html__( 'Container', 'cf7-submissions' ),
     131        'time'          => esc_html__( 'Date &amp; Time', 'cf7-submissions' ),
     132        'action'        => '',
     133];
     134
     135// The Lead column sits right after "Submitted By". Not sortable: its cells are links.
     136if ( $show_leads ) {
     137        $columns = array_slice( $columns, 0, 2, true ) + [ 'lead' => esc_html__( 'Lead', 'cf7-submissions' ) ] + array_slice( $columns, 2, null, true );
     138}
     139
    94140$config = [
    95141        'id'                    => 'cf7-submissions_list',
    96142        'per_page'              => 20,
    97         'columns'               => [
    98                 'id'            => esc_html__( 'Submission ID', 'cf7-submissions' ),
    99                 'user'          => esc_html__( 'Submitted By', 'cf7-submissions' ),
    100                 'form'          => esc_html__( 'Form', 'cf7-submissions' ),
    101                 'container'     => esc_html__( 'Container', 'cf7-submissions' ),
    102                 'time'          => esc_html__( 'Date &amp; Time', 'cf7-submissions' ),
    103                 'action'        => '',
    104         ],
     143        'columns'               => $columns,
    105144        'sortable'              => [ 'id', 'user', 'form', 'container', 'time' ],
    106145        'orderby'               => 'time',
  • cf7-submissions/trunk/views/submissions/single.php

    r3836469 r3841460  
    11<?php
     2use CF7_Submissions\Bootstrap\Installer;
     3use CF7_Submissions\Helpers\Utility;
     4use CF7_Submissions\Leads\Field_Map;
     5use CF7_Submissions\Leads\Form_Settings;
     6use CF7_Submissions\Leads\Lead;
    27use CF7_Submissions\Models\Database;
    38
    … …  
    155160                                        <?php echo esc_html( $submission_id ); ?>
    156161                                </p>
     162                                <?php if ( Installer::schema_ready() ) : ?>
     163                                <p>
     164                                        <span class="dashicons dashicons-id"></span>
     165                                        <label><?php esc_html_e( 'Lead:', 'cf7-submissions' ); ?></label>
     166                                        <?php
     167                                        $lead = ! empty( $submission['lead_id'] ) ? Lead::find( (int) $submission['lead_id'] ) : null;
     168
     169                                        if ( $lead ) {
     170                                                // The name, or the email when the lead has none.
     171                                                $lead_name  = trim( $lead['first_name'] . ' ' . $lead['last_name'] );
     172                                                $lead_label = '' !== $lead_name ? $lead_name : $lead['email'];
     173
     174                                                if ( Installer::schema_ready( Installer::ACTIVITY_VERSION ) ) {
     175                                                        printf( '<a href="%2$s">%1$s</a>', esc_html( $lead_label ), esc_url( Lead::url( (int) $lead['id'] ) ) );
     176                                                } else {
     177                                                        echo esc_html( $lead_label );
     178                                                }
     179                                        } else {
     180                                                printf( '<span title="%2$s">%1$s</span>', esc_html__( 'None', 'cf7-submissions' ), esc_attr__( 'No email address was found in this submission, or it is not linked yet.', 'cf7-submissions' ) );
     181                                        }
     182                                        ?>
     183                                </p>
     184                                <?php endif; ?>
    157185                                <p>
    158186                                        <span class="dashicons dashicons-media-document"></span>
    … …  
    212240
    213241                <?php
    214                 $emails = [];
    215                 foreach ( $fields as $row ) {
    216                         if( is_email( $row['value'] ) ) {
    217                                 $emails[ $row['field'] ] = $row['value'];
    218                         }
    219                 }
    220                 if( count( $emails ) > 0 ) : ?>
    221                
    222                 <div id="cf7s-contact-wrap" class="cf7s-wrap postbox">
    223                         <form id="cf7s-contact-form">
    224                                 <?php wp_nonce_field( 'cf7-submissions', 'cf7sub_nonce' ); ?>
    225                                 <input type="hidden" name="action" value="cf7s-contact">
    226                                 <input type="hidden" name="submission_id" value="<?php echo esc_attr( $submission_id ); ?>">
    227                                 <div class="postbox-header">
    228                                         <h2 class="hndle"><?php esc_html_e( 'Contact Sender', 'cf7-submissions' ); ?></h2>
    229                                 </div>
    230                                 <div class="inside">
    231                                         <p>
    232                                                 <label><?php esc_html_e( 'Recipient(s)', 'cf7-submissions' ); ?></label>
    233                                                 <select name="to[]" class="cf7s-contact-to chosen" multiple>
    234                                                         <?php
    235                                                         foreach ( $emails as $field => $email ) {
    236                                                                 printf(
    237                                                                         '<option value="%2$s">%1$s &lt;%2$s&gt;</option>',
    238                                                                         esc_html( $field ),
    239                                                                         esc_attr( $email )
    240                                                                 );
    241                                                         }
    242                                                         ?>
    243                                                 </select>
    244                                                 <small><?php esc_html_e( 'Based on the email address(es) collected in the form submission', 'cf7-submissions' ) ?></small>
    245                                         </p>
    246                                         <p>
    247                                                 <label><?php esc_html_e( 'Subject', 'cf7-submissions' ); ?></label>
    248                                                 <input type="text" name="subject" placeholder="<?php esc_html_e( 'Mail subject line', 'cf7-submissions' ); ?>" />
    249                                         </p>
    250                                         <p>
    251                                                 <label><?php esc_html_e( 'Message', 'cf7-submissions' ); ?></label>
    252                                                 <textarea name="message" placeholder="<?php esc_html_e( 'Main message body', 'cf7-submissions' ); ?>" rows="5"></textarea>
    253                                         </p>
    254                                 </div>
    255                                 <div class="handle-contact">
    256                                         <p id="cf7s-contact-buttons">
    257                                                 <span id="cf7s-contact-msg"></span>
    258                                                 <button type="submit" class="button button-small button-primary cf7s-send">
    259                                                         <span class="dashicons dashicons-yes"></span> <?php esc_html_e( 'Send Email', 'cf7-submissions' ); ?>
    260                                                 </button>
    261                                         </p>
    262                                 </div>
    263                         </form>
    264                 </div><!-- #cf7s-contact-wrap -->
    265                
    266                 <?php endif; ?>
     242                // The reply box is shared with the lead screen. It draws nothing when the submission holds no address.
     243                echo Utility::get_template( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- the partial escapes its own output.
     244                        'partials/reply-box.php',
     245                        array(
     246                                'recipients'    => Field_Map::recipients( wp_list_pluck( $fields, 'value', 'field' ), Form_Settings::get( (int) $submission['form_id'] ) ),
     247                                'submission_id' => $submission_id,
     248                        )
     249                );
     250                ?>
    267251
    268252        </div><!-- #cf7s-right-col -->
Note: See TracChangeset for help on using the changeset viewer.