acquire_key( 'job-' . absint( $job_id ) ); } /** * Same two locks for a named resumable task that is not a job row (for example a * migration dry run identified by its token). * * @param string $key Key: letters, digits and dashes (max 40 chars). * @return bool False when another request holds it. */ public function acquire_key( string $key ): bool { global $wpdb; $key = substr( (string) preg_replace( '/[^a-z0-9-]/', '', strtolower( $key ) ), 0, 40 ); if ( '' === $key ) { return false; } // 1. Database named lock (max 64 chars). $name = 'brv_t_' . substr( md5( DB_NAME . '|' . $wpdb->prefix ), 0, 12 ) . '_' . $key; $prev = $wpdb->suppress_errors( true ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $got = $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $name ) ); $wpdb->suppress_errors( $prev ); if ( '0' === (string) $got ) { return false; } if ( '1' === (string) $got ) { $this->db_name = $name; } // 2. File lock. $file = trailingslashit( Working_Dir::root() ) . 'locks/' . $key . '.lock'; $dir = dirname( $file ); if ( Working_Dir::ensure() && ( is_dir( $dir ) || wp_mkdir_p( $dir ) ) ) { Working_Dir::harden( $dir ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen $fh = @fopen( $file, 'c' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_fopen if ( false !== $fh ) { $would_block = 0; if ( flock( $fh, LOCK_EX | LOCK_NB, $would_block ) ) { $this->fh = $fh; } else { fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose if ( $would_block ) { $this->release(); return false; } // flock() is not supported on this filesystem: rely on the database lock. } } } return true; } /** * Release whatever is held. */ public function release(): void { if ( is_resource( $this->fh ) ) { flock( $this->fh, LOCK_UN ); fclose( $this->fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose } $this->fh = null; if ( '' !== $this->db_name ) { global $wpdb; $prev = $wpdb->suppress_errors( true ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $this->db_name ) ); $wpdb->suppress_errors( $prev ); $this->db_name = ''; } } /** * Remove a finished job's lock file. * * @param int $job_id Job id. */ public static function forget( int $job_id ): void { $path = self::path( $job_id ); if ( file_exists( $path ) ) { wp_delete_file( $path ); } } }