JFIF $ d d 7 * Z qn )ZP 0 !1 A "#a$2Qr D8 a Ri [f \m I ykI w0 c u F c Rı?lO7 к _f˓ [C $殷WF< _W ԣ s Kc ëI zyQy /_LK ℂ ;C",p F A : /] =H ~ , l s / 9 ć: [=/#f ; ) x { ٛE Q )~ = 𘙲r*2~ a _V = ' ku m F D } KYYC )( { * g& f `툪 r y ` = ^ c J. I ]( * `wq 1dđ #̩ ͑ 0 ; H ] u 搂 @:~ ו K L N s h } O I R* 8 :2 ! lD JV o ( 3 = M ( z Ȱ+i *N A r6K n S l ) ! J J Ӂ* % ݉?|D } d5: eP0 R; {$X' x F @ .ÊB {,WJ uQ ɲRI ;9 Q E琯 6 2fT .DU J ;*c P A\IL Nj! J ۱+ O\ ͔ ] ޒ S J ȧ c%A N ol ՎprU L Zԛe r E2= X D Xg VQeӓ k y P7 U* o m Q I s ,K `) 6\G3t?pgjr m ۛجw luGt f h 9uyP 0D;Uڽ"OXl i f $ ) &|ML 0 Z rm1 [ H XP l P R0 'G=i 2N +0 e 2 ]] 9 VT P O 7 h(F * 癈 ' = Q VZD F,d ߬ ~ T X G[ `le 69C R(!S2! P < 0 x < !1AQ "Raq 02Br #S CTb ? Ζ "]mH5WR 7 k.ۛ ! } Q~ + yԏ z |@ T20 S~ K e k *zF f^2X *( @ 8 r ? C I uI|֓>^Ex LgNU Y+{.R Ѫ τV YT D I 6 2 '8Y2 7'\T P.6 d &˦ @V q i |8 -O Ε ] ʔ U= T L 8= ;6c | !qfF3 a ů& ~$ l} 'NW U s$U k^S V : U#6w + +s &r+n ڐ { @ 29gL u " T Ù M=6 (^ "7 r}=6Yݾ lC u hquymp Ǧ G jhs ǜNl ɻ} o 7 #S6 a w 4 ! OS r D 5 7 % | ?x> L | / nD 6?/8 w # [ ) L 7 +6〼T A T g ! %5 Mm Z /c -{1_Je "| ^$ 'O & ޱմ < H vNqϡQ$ < 6 &Nݛ ֨tǻN (9 n ru~'όN sMG& ,uH Kw *Ī 5@ u6 BԒ i YN * f 0 _ GhKW u lT <nj- 0{ M L~ | /a v\ E = ?1 \ɟuq Ђ Y O a K ޡP q $ H8o Q˼EV ~ k 0 h' L Pp M -M" m^ !6l nմ 쮝C U T . ! :vMǨb h ډ Vc r @~p # !1QAa q ? AL0L x LU 4 d ; x " 16ad0 7.\ߋ 0 = P l v/ " c A Ay A|2pO8"d MV #1] = \ " ˡ ] k v I9 d ۓ & q ) ǐq E ꞅ v "P )q X &Q З non]я u ג./ ; gZ$ M QР 2M ]h ni 0 P $ێ 3CɏGjώy : m c # S_ l@ '_ \m|C 2`K _ 1 cIvGc $? PCQ S+D ? K aײ k Fr b 8 ύ NEدg ĝ U 3 6 #Ik+ v { v i ( ވ ? a e) X xy/*@Q Ǽ Ծ ) $ IWO l c G; !i k{ gOŀ L ('x T rb $ w) R $ & N1E td U3Uȉ1p M"N* (DNy d96.(jQ) X 5 c QɎMy W ? Q *!R > 6=7)Xj 5`J ] e 8%t ! + ' ! 1Q 5 !1 AQaq ё #2 "0BRb ? G t^ ## .l lQ T $ v , ,m 㵜5u bV =sY+ @d { N ! dn O < .- B; _w J t 6;Q Jd. Q c%p{ 1 ,sND dF H I0 Гo X ш e黅X ۢ F :)[ F G X ƹ / w _c MeD ,ʡc c . W D tA $ j@ : ) - #u c1< @ۗ9F ) KJ- hpP] _ x [ q B lb p ʖ w q " LFGd ƶ * s +ډ_Zc " ? % t[I P 6 J ]# =ɺ V v v CGs Gh1 > )6 |e y ? L ӣ m,4 G W Ui ` ] uJVo VDG< SB 6ϏQ @ TiU l y O U 0 kfV ~ ~}S Z @ *WU Ui ## ; s /[ = ! 7}" W N ] ' (L ! ~ y5 g9T̅J kbM' +s :S +B) v @ M j e C f j E 0 Y\Qn z G 1 д~ W o{T 9?` Rm yhsy3 !HAD ] m c1 ~ 2 L S u7x T ;j$ `} 4-> L# vzŏ I L S ֭ T { r jGK C ; b pU= - ` Bs K. S F w4 M q] Z dH S 0 ) tLg
<?php
namespace WPForms\Integrations\LiteConnect;
use WPForms\Admin\Notice;
use WPForms\Helpers\Transient;
use WPForms\Tasks\Tasks;
/**
* Class Integration.
*
* Base integration between Lite Connect API and WPForms.
*
* @since 1.7.4
*/
class Integration extends API {
/**
* Authentication data.
*
* @since 1.7.4
*
* @var array
*/
protected $auth = [];
/**
* Option name to store the total count of Lite Connect entries.
*
* @since 1.7.4
*
* @var string
*/
const LITE_CONNECT_ENTRIES_COUNT_OPTION = 'wpforms_lite_connect_entries_count';
/**
* Post meta name to store the total count of Lite Connect form entries.
*
* @since 1.7.9
*
* @var string
*/
const LITE_CONNECT_FORM_ENTRIES_COUNT_META = 'wpforms_lite_connect_form_entries_count';
/**
* Integration constructor.
*
* @since 1.7.4
*/
public function __construct() {
static $updated;
parent::__construct();
$this->hooks();
// Update the site key and access token.
if (
! $updated &&
( is_admin() && ! wp_doing_ajax() ) &&
( ( wpforms()->is_pro() && self::get_enabled_since() ) || LiteConnect::is_enabled() )
) {
$this->maybe_update_access_token();
$this->update_keys();
$updated = true;
}
}
/**
* Hooks.
*
* @since 1.7.5
*/
private function hooks() {
add_action( 'admin_init', [ $this, 'max_attempts_notice' ], 10 );
add_filter( 'wpforms_upgrade_link', [ $this, 'add_lite_connect_site_id_param' ] );
}
/**
* Update the site key and access token if they do not exist.
*
* @since 1.7.4
*/
public function update_keys() {
if ( isset( $this->auth['site_key'], $this->auth['access_token'] ) ) {
return;
}
$site_key = $this->get_site_key();
$this->auth = [
'site_key' => $site_key,
'access_token' => $this->get_access_token( $site_key ),
];
}
/**
* Get the site key.
*
* @since 1.7.4
*
* @return string|false|array The site key, or false on error.
*/
protected function get_site_key() {
// At first, try to get the site key from the wp-config.php file.
$debug_site_key = $this->get_debug_setting( 'key' );
if ( $debug_site_key !== false ) {
return $debug_site_key;
}
// If site key already exists, then we won't need to regenerate it.
$curr_key = wpforms_setting( 'site', false, self::get_option_name() );
if ( ! empty( $curr_key['key'] ) ) {
return $curr_key['key'];
}
// Generate the site key.
return $this->generate_site_key();
}
/**
* Get the access token.
*
* @since 1.7.4
*
* @param string|array $site_key The site key.
* @param bool $force True to force generate a new access token.
*
* @return string|false|void The access token, or false on error.
*/
protected function get_access_token( $site_key, $force = false ) {
if ( ! $site_key ) {
return false;
}
$curr_token = wpforms_setting( 'access_token', false, self::get_option_name() );
// It won't regenerate the access token if $force is false, and the current token is not expired.
if ( $force === false && isset( $curr_token['expires_at'] ) && (int) $curr_token['expires_at'] - time() > 0 ) {
return $curr_token['access_token'];
}
// Generate the access token.
$response = $this->generate_access_token( $site_key );
if ( $response ) {
$response = json_decode( $response, true );
if ( isset( $response['access_token'] ) ) {
$settings = get_option( self::get_option_name(), [] );
$settings['access_token'] = $response;
update_option( self::get_option_name(), $settings );
// Create task to refresh access token in 6 days.
$this->refresh_access_token_task();
return $response['access_token'];
}
wpforms_log(
'Lite Connect: unable to generate access token',
[
'response' => $response,
'request' => [
'domain' => $this->domain,
'site_id' => $this->site_id,
'wp_version' => get_bloginfo( 'version' ),
],
],
[ 'type' => [ 'error' ] ]
);
}
return false;
}
/**
* Create a task to refresh the access token.
*
* @since 1.7.4
*/
private function refresh_access_token_task() {
$tasks = wpforms()->obj( 'tasks' );
if ( $tasks instanceof Tasks && ! $tasks->is_scheduled( RefreshAccessTokenTask::LITE_CONNECT_TASK ) ) {
( new RefreshAccessTokenTask() )->create();
}
}
/**
* Get the name for the Lite Connect's option.
*
* @since 1.7.4
*
* @return string
*/
public static function get_option_name() {
if ( self::is_staging() ) {
return API::STAGING_LITE_CONNECT_OPTION;
}
return API::LITE_CONNECT_OPTION;
}
/**
* Get the Lite Connect entries count.
*
* @since 1.7.4
*
* @return int The entries count.
*/
public static function get_entries_count() {
return (int) get_option( self::LITE_CONNECT_ENTRIES_COUNT_OPTION, 0 );
}
/**
* Get the Lite Connect form entries count.
*
* @since 1.7.9
*
* @param int $form_id The form ID.
*
* @return int The form entries count.
*/
public static function get_form_entries_count( $form_id ) {
return (int) get_post_meta( $form_id, self::LITE_CONNECT_FORM_ENTRIES_COUNT_META, true );
}
/**
* Get the Lite Connect new entries count (since previous import).
*
* @since 1.7.4
*
* @return int The new entries count.
*/
public static function get_new_entries_count() {
// Get current total entries count.
$count = self::get_entries_count();
// Reduces the entries that were already imported previously from the count.
$import = wpforms_setting( 'import', false, self::get_option_name() );
$prev_count = 0;
if ( isset( $import['previous_import_count'] ) ) {
$prev_count = (int) $import['previous_import_count'];
}
if ( isset( $import['previous_failed_count'] ) ) {
$prev_count += (int) $import['previous_failed_count'];
}
return $count < $prev_count ? 0 : $count - $prev_count;
}
/**
* Maybe restart the import flag (for when the user re-upgrades to pro).
*
* @since 1.7.4
* @since 2.0.0 Bails out while an import is scheduled or running.
*/
public static function maybe_restart_import_flag() {
$settings = get_option( self::get_option_name(), [] );
if ( empty( $settings ) ) {
return;
}
$status = isset( $settings['import']['status'] ) ? $settings['import']['status'] : false;
// A queued or in-progress import must not be interrupted: unsetting its
// status makes ImportEntriesTask::process() skip the import silently,
// with no retry and no log. The deferred Pro install routine hits this
// right after the Onboarding Wizard schedules the restore (#17996).
// Restarting is only meaningful for a finished or absent import.
if ( in_array( $status, [ 'scheduled', 'running' ], true ) ) {
return;
}
if ( $status === 'done' ) {
$previous_imported_entries = Transient::get( 'lite_connect_imported_entries' );
$settings['import']['previous_import_count'] = is_array( $previous_imported_entries ) ? count( $previous_imported_entries ) : 0;
$previous_failed_entries = Transient::get( 'lite_connect_failed_entries' );
$settings['import']['previous_failed_count'] = is_array( $previous_failed_entries ) ? count( $previous_failed_entries ) : 0;
}
self::maybe_set_entries_count();
// Reset import status to be able to restart import process.
unset(
$settings['import']['status'],
$settings['import']['user_notified']
);
update_option( self::get_option_name(), $settings );
if ( Transient::get( 'lite_connect_error' ) !== false ) {
Transient::delete( 'lite_connect_error' );
}
}
/**
* Get the Lite Connect enabled since timestamp.
*
* @since 1.7.4
*
* @return bool|int
*/
public static function get_enabled_since() {
return wpforms_setting( LiteConnect::SETTINGS_SLUG . '-since' );
}
/**
* Get the Email of the user who enabled Lite Connect.
*
* @since 1.7.4
*
* @return bool|string
*/
public static function get_enabled_email() {
return wpforms_setting( LiteConnect::SETTINGS_SLUG . '-email' );
}
/**
* Append the Lite Connect site ID as a referral arg on lite-upgrade URLs.
*
* Hooked into the `wpforms_upgrade_link` filter so every URL built through
* `wpforms_admin_upgrade_link()` carries an opaque `wpf_ref` value that lets the
* marketing side attribute upgrade traffic back to the originating site
* without exposing a recognisable identifier in the URL.
*
* @since 2.0.0
* @since 2.0.1 Renamed the appended query arg from `ref` to `wpf_ref`.
*
* @param string $url Upgrade URL produced by `wpforms_admin_upgrade_link()`.
*
* @return string URL with the `wpf_ref` arg appended when applicable.
*/
public function add_lite_connect_site_id_param( $url ) {
// Affiliates can override the upgrade link.
if ( ! is_string( $url ) || strpos( $url, 'https://wpforms.com/lite-upgrade' ) !== 0 ) {
return $url;
}
// Lite Connect must be enabled.
if ( ! LiteConnect::is_enabled() ) {
return $url;
}
// The site ID should be defined here.
// Also, respect debug settings for testing purposes.
if ( $this->site_id === '' ) {
return $url;
}
return add_query_arg( 'wpf_ref', rawurlencode( $this->site_id ), $url );
}
/**
* Normalize Lite Connect entries counter when their value is wrong.
*
* @since 1.7.4
*/
public static function maybe_set_entries_count() {
$settings = get_option( self::get_option_name(), [] );
if ( empty( $settings ) ) {
return;
}
$previous_import_count = isset( $settings['import']['previous_import_count'] ) ? (int) $settings['import']['previous_import_count'] : 0;
$previous_failed_count = isset( $settings['import']['previous_failed_count'] ) ? (int) $settings['import']['previous_failed_count'] : 0;
$previous_import_count += $previous_failed_count;
// When the entries counter was manually deleted from options OR it was modified by another process,
// we are setting the counter to the value of the previous imported entries.
// In this way, the next form submission will increase counter properly, and user will see value of the backed up entries.
// Obviously, this solution is not perfect, but we don't have another source of the total entries count.
if ( $previous_import_count > self::get_entries_count() ) {
update_option( self::LITE_CONNECT_ENTRIES_COUNT_OPTION, $previous_import_count );
}
}
/**
* Show the Lite Connect notice about the max attempts to generate the API key.
*
* @since 1.7.5
*/
public function max_attempts_notice() {
$attempts_count = get_option( self::GENERATE_KEY_ATTEMPT_COUNTER_OPTION, 0 );
$notice_text = sprintf(
wp_kses( /* translators: %s - WPForms documentation link. */
__( 'Your form entries can’t be backed up because WPForms can’t connect to the backup server. If you’d like to back up your entries, find out how to <a href="%s" target="_blank" rel="noopener noreferrer">fix entry backup issues</a>.', 'wpforms-lite' ),
[
'a' => [
'href' => [],
'target' => [],
'rel' => [],
],
]
),
wpforms_utm_link( 'https://wpforms.com/docs/how-to-use-lite-connect-for-wpforms/#backup-issues', 'Admin Notice' )
);
if ( $attempts_count >= self::MAX_GENERATE_KEY_ATTEMPTS ) {
Notice::warning(
$notice_text,
[
'dismiss' => Notice::DISMISS_GLOBAL,
'slug' => 'max_attempts',
]
);
}
}
/**
* Maybe update access token.
*
* @since 1.7.6
*/
public function maybe_update_access_token() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$action = isset( $_GET['wpforms_lite_connect_action'] ) ? sanitize_key( $_GET['wpforms_lite_connect_action'] ) : '';
if (
! isset( $_GET['_wpnonce'] ) ||
$action !== 'update-access-token' ||
! current_user_can( 'manage_options' ) ||
! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'wpforms_lite_connect_action' )
) {
return;
}
$this->get_access_token( $this->get_site_key(), true );
}
/**
* Determine if Lite Connect staging is used.
*
* @since 1.9.1
*
* @return bool
*/
private static function is_staging(): bool {
return defined( 'WPFORMS_LITE_CONNECT_STAGING' ) && WPFORMS_LITE_CONNECT_STAGING;
}
/**
* Get the site credentials.
*
* @since 1.9.1
*
* @return array
*/
public static function get_site_credentials(): array {
$settings = (array) get_option( self::get_option_name(), [] );
if ( ! empty( $settings['site']['id'] ) && ! empty( $settings['access_token']['access_token'] ) ) {
return [
'site_id' => $settings['site']['id'],
'access_token' => $settings['access_token']['access_token'],
];
}
$instance = ( new self() );
// Try to get the site id from the wp-config.php file.
$debug_site_id = $instance->get_debug_setting( 'id' );
if ( empty( $debug_site_id ) ) {
return [];
}
$access_token = $instance->get_access_token( $instance->get_site_key() );
if ( ! $access_token ) {
return [];
}
return [
'site_id' => $debug_site_id,
'access_token' => $access_token,
'is_production' => ! self::is_staging(),
];
}
/**
* Fetch entry stats from the LiteConnect API.
*
* Uses a direct `wp_remote_post()` instead of the inherited `request()` transport
* to avoid an additional `Integration` instance during normal credentialed requests.
* Note: `get_site_credentials()` may still instantiate `Integration` as a fallback
* when stored credentials are absent (debug-settings path).
*
* @since 2.0.2
*
* @param int $period Number of trailing days (1-366). Default 30.
* @param string $timezone IANA name or UTC offset. Default: site timezone.
*
* @return array Parsed response on success, empty array on any failure.
*/
public static function get_stats( int $period = 30, string $timezone = '' ): array {
$credentials = self::get_site_credentials();
if ( empty( $credentials['site_id'] ) || empty( $credentials['access_token'] ) ) {
return [];
}
$api_url = self::is_staging() ? API::STAGING_API_URL : API::API_URL;
$response = self::post(
$api_url . '/retrieval/stats',
[
'site_id' => $credentials['site_id'],
'period' => $period,
'timezone' => $timezone ? $timezone : wp_timezone_string(),
],
[
'X-WPForms-Lite-Connect-Access-Token' => $credentials['access_token'],
]
);
if ( is_wp_error( $response ) ) {
wpforms_log(
'Lite Connect: stats request failed',
[ 'error' => $response->get_error_message() ],
[ 'type' => [ 'error' ] ]
);
return [];
}
$code = (int) wp_remote_retrieve_response_code( $response );
if ( $code < 200 || $code >= 300 ) {
wpforms_log(
'Lite Connect: stats request returned non-2xx',
[
'code' => $code,
'body' => wp_remote_retrieve_body( $response ),
],
[ 'type' => [ 'error' ] ]
);
return [];
}
$data = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! StatsResponseValidator::validate( $data ) ) {
wpforms_log(
'Lite Connect: stats response failed schema validation',
[ 'body' => wp_remote_retrieve_body( $response ) ],
[ 'type' => [ 'error' ] ]
);
return [];
}
return $data;
}
}