Plugin Directory

Changeset 3229645


Ignore:
Timestamp:
01/27/2025 02:13:01 PM (14 months ago)
Author:
ctomczyk
Message:

Release version 1.5.14

Location:
sitelint/trunk
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • sitelint/trunk/README.txt

    r3226285 r3229645  
    44Requires at least: 4.7
    55Tested up to: 6.6.2
    6 Stable tag: 1.5.13
     6Stable tag: 1.5.14
    77License: GPLv2 or later
    88License URI: https://www.gnu.org/licenses/gpl-2.0.html
     
    2929
    3030== Changelog ==
     31
     32= 1.5.14 =
     33
     34* Ensure SiteLint API token is added to the Auditor report HTTP request when available; otherwise remove it
    3135
    3236= 1.5.13 =
  • sitelint/trunk/admin/partials/sitelint-setup.php

    r3132698 r3229645  
    7575              <select name="apiToken" id="apiToken" data-form-api-token>
    7676                <option value="null" selected disabled>Select site</option>
    77                 <?php foreach ($options['sites'] as $site) {
    78                   if(isset($options['site'])&& $options['site'] !== null && $options['site'] === $site){
    79                     echo '<option selected value=' . esc_attr($site['apiToken']['tokenId']) . '>' . esc_html($site['name']) . '</option>';
    80                   } else {
    81                     echo '<option value=' . esc_attr($site['apiToken']['tokenId']) . '>' . esc_html($site['name']) . '</option>';
     77                <?php
     78                  foreach ($options['sites'] as $site) {
     79                    if(isset($options['site'])&& $options['site'] !== null && $options['site'] === $site){
     80                      echo '<option selected value=' . esc_attr($site['apiToken']['tokenId']) . '>' . esc_html($site['name']) . '</option>';
     81                    } else {
     82                      echo '<option value=' . esc_attr($site['apiToken']['tokenId']) . '>' . esc_html($site['name']) . '</option>';
     83                    }
    8284                  }
    83                 } ?>
     85                ?>
    8486              </select>
    8587            </div>
  • sitelint/trunk/admin/sitelint-admin.php

    r3226276 r3229645  
    11<?php
     2
    23/**
    34 * The admin-specific functionality of the plugin.
     
    1112
    1213if (!defined('ABSPATH')) {
    13     exit(); // Exit if accessed directly
     14  exit(); // Exit if accessed directly
    1415}
    1516
    1617define('__SITELINT_ROOT__', dirname(dirname(__FILE__)));
    1718require_once __SITELINT_ROOT__ . '/shared/services/Api.php';
    18 
    19 use SiteLint\Auth\Api;
     19require_once __SITELINT_ROOT__ . '/shared/constants/http.constants.php';
     20
     21use SiteLint\Shared\Services\Api;
    2022
    2123class SiteLint_Admin
    2224{
    23     const OPTION_NAME = 'sitelint';
    24 
    25     protected static $instance = null;
    26 
    27     private $plugin_name;
    28     private $message = null;
    29     private $formAction = null;
    30     private $email = null;
    31 
    32     /**
    33      * The version of SiteLint plugin.
    34      *
    35      * @since    1.0.0
    36      * @access   private
    37      * @var      string    $version    The current version of SiteLint plugin.
    38      */
    39     private $version;
    40 
    41     /**
    42      * Initialize the class and set its properties.
    43      *
    44      * @since    1.0.0
    45      * @param      string    $plugin_name       The name of SiteLint plugin.
    46      * @param      string    $version    The version of SiteLint plugin.
    47      */
    48 
    49     public function __construct($plugin_name = 'sitelint', $version = '1.0.0')
    50     {
    51         require_once __DIR__ . '/../includes/functions.php';
    52 
    53         $this->plugin_name = $plugin_name;
    54         $this->version = $version;
    55     }
    56 
    57     public static function get_instance()
    58     {
    59         if (self::$instance == null) {
    60             self::$instance = new self();
    61         }
    62 
    63         return self::$instance;
    64     }
    65 
    66     /**
    67      * Register the stylesheets for the admin area.
    68      *
    69      * @since    1.0.0
    70      */
    71     public function enqueue_styles()
    72     {
    73         add_action('admin_enqueue_scripts', function() {
    74             wp_enqueue_style(
    75                 $this->plugin_name . '-admin-styles',
    76                 plugin_dir_url(__FILE__) . 'css/styles.css',
    77                 [],
    78                 filemtime(plugin_dir_path(__FILE__) . 'css/styles.css')
    79             );
    80         });
    81     }   
    82 
    83     /**
    84      * Register the JavaScript for the admin area.
    85      *
    86      * @since    1.0.0
    87      */
    88     public function enqueue_scripts()
    89     {
    90         $sitelintScriptId = 'sitelint_script_admin';
    91  
    92         add_action('admin_enqueue_scripts', function() use ($sitelintScriptId) {
    93             wp_register_script($sitelintScriptId, '');
    94             wp_enqueue_script($sitelintScriptId);
    95 
    96             wp_enqueue_script(
    97                 $this->plugin_name,
    98                 plugin_dir_url(__FILE__) . 'scripts/app.js',
    99                 [],
    100                 filemtime(plugin_dir_path(__FILE__) . 'scripts/app.js')
    101             );
    102         });
    103     }
    104 
    105     public function renderAdminPage()
    106     {
    107         $this->render('partials/sitelint-admin-display.php', [
    108             'domain' => $this->plugin_name,
    109             'options' => $this->getOptions(),
    110             'message' => $this->message,
    111             'formAction' => $this->formAction,
    112             'email' => $this->email
    113         ]);
    114     }
    115 
    116     private function render($template, $vars = [])
    117     {
    118         call_user_func_array(function () use ($template, $vars) {
    119             extract($vars);
    120             include_once $template;
    121         }, []);
    122     }
    123 
    124     public function addMenuItems()
    125     {
    126         $capability = sitelint_get_publish_cap();
    127 
    128         add_menu_page(
    129             __('SiteLint', 'sitelint'),
    130             __('SiteLint', 'sitelint'),
    131             $capability,
    132             $this->plugin_name,
    133             [$this, 'renderAdminPage'],
    134             'dashicons-welcome-view-site'
    135         );
    136     }
    137 
    138     public function handleInAdminHeader()
    139     {
    140         if (isset($_GET['page']) && $_GET['page'] !== 'sitelint') {
    141             return;
    142         }
    143 
    144         remove_all_actions('admin_notices');
    145         remove_all_actions('all_admin_notices');
    146 
    147         add_action('admin_notices', function () {
    148             // echo 'Custom notice';
    149         });
    150     }
    151 
    152     public function performAction()
    153     {
    154         $options = $this->getOptions();
    155         $action = null;
    156 
    157         if (isset($_POST['_action']) === false && isset($options['apiToken']) === false) {
    158             return;
    159         }
    160 
    161         if (isset($_POST['_action']) === true) {
    162             $action = sanitize_text_field((string) $_POST['_action']);
    163         }
    164 
    165         $api = new Api();
    166 
    167         if ($action === 'checkEmail') {
    168             $response = $api->checkEmail(sanitize_email($_POST['email']));
    169 
    170             echo esc_html($response['body']);
    171             exit();
    172         }
    173 
    174         if ($action == null && isset($options['apiToken'])) {
    175 
    176             $audits = $api->audits($options['apiToken']);
    177 
    178             if (isset($audits['body']) === false || is_null($audits['body']) === true) {
    179               return;
     25  private const OPTION_NAME = 'sitelint';
     26
     27  protected static $instance = null;
     28
     29  private $plugin_name;
     30  private $message = null;
     31  private $formAction = null;
     32  private $email = null;
     33
     34  /**
     35   * The version of SiteLint plugin.
     36   *
     37   * @since    1.0.0
     38   * @access   private
     39   * @var      string    $version    The current version of SiteLint plugin.
     40   */
     41  private $version;
     42
     43  /**
     44   * Initialize the class and set its properties.
     45   *
     46   * @since    1.0.0
     47   * @param      string    $plugin_name       The name of SiteLint plugin.
     48   * @param      string    $version    The version of SiteLint plugin.
     49   */
     50
     51  public function __construct($plugin_name = 'sitelint', $version = '1.0.0')
     52  {
     53    require_once __DIR__ . '/../includes/functions.php';
     54
     55    $this->plugin_name = $plugin_name;
     56    $this->version = $version;
     57  }
     58
     59  public static function get_instance()
     60  {
     61    if (self::$instance == null) {
     62      self::$instance = new self();
     63    }
     64
     65    return self::$instance;
     66  }
     67
     68  /**
     69   * Register the stylesheets for the admin area.
     70   *
     71   * @since    1.0.0
     72   */
     73  public function enqueue_styles()
     74  {
     75    add_action('admin_enqueue_scripts', function () {
     76      wp_enqueue_style(
     77        $this->plugin_name . '-admin-styles',
     78        plugin_dir_url(__FILE__) . 'css/styles.css',
     79        [],
     80        filemtime(plugin_dir_path(__FILE__) . 'css/styles.css')
     81      );
     82    });
     83  }
     84
     85  /**
     86   * Register the JavaScript for the admin area.
     87   *
     88   * @since    1.0.0
     89   */
     90  public function enqueue_scripts()
     91  {
     92    $sitelintScriptId = 'sitelint_script_admin';
     93
     94    add_action('admin_enqueue_scripts', function () use ($sitelintScriptId) {
     95      wp_register_script($sitelintScriptId, '');
     96      wp_enqueue_script($sitelintScriptId);
     97
     98      wp_enqueue_script(
     99        $this->plugin_name,
     100        plugin_dir_url(__FILE__) . 'scripts/app.js',
     101        [],
     102        filemtime(plugin_dir_path(__FILE__) . 'scripts/app.js')
     103      );
     104    });
     105  }
     106
     107  public function renderAdminPage()
     108  {
     109    $this->render('partials/sitelint-admin-display.php', [
     110      'domain' => $this->plugin_name,
     111      'options' => $this->getOptions(),
     112      'message' => $this->message,
     113      'formAction' => $this->formAction,
     114      'email' => $this->email
     115    ]);
     116  }
     117
     118  private function render($template, $vars = [])
     119  {
     120    call_user_func_array(function () use ($template, $vars) {
     121      extract($vars);
     122      include_once $template;
     123    }, []);
     124  }
     125
     126  public function addMenuItems()
     127  {
     128    $capability = sitelint_get_publish_cap();
     129
     130    add_menu_page(
     131      __('SiteLint', 'sitelint'),
     132      __('SiteLint', 'sitelint'),
     133      $capability,
     134      $this->plugin_name,
     135      [$this, 'renderAdminPage'],
     136      'dashicons-welcome-view-site'
     137    );
     138  }
     139
     140  public function handleInAdminHeader()
     141  {
     142    if (isset($_GET['page']) && $_GET['page'] !== 'sitelint') {
     143      return;
     144    }
     145
     146    remove_all_actions('admin_notices');
     147    remove_all_actions('all_admin_notices');
     148
     149    add_action('admin_notices', function () {
     150      // echo 'Custom notice';
     151    });
     152  }
     153
     154  public function performAction()
     155  {
     156    $options = $this->getOptions();
     157    $action = null;
     158
     159    if (isset($_POST['_action']) === false && isset($options['apiToken']) === false) {
     160      return;
     161    }
     162
     163    if (isset($_POST['_action']) === true) {
     164      $action = sanitize_text_field((string) $_POST['_action']);
     165    }
     166
     167    $api = new Api();
     168
     169    if ($action === 'checkEmail') {
     170      $response = $api->checkEmail(sanitize_email($_POST['email']));
     171
     172      echo esc_html($response['body']);
     173      exit();
     174    }
     175
     176    if ($action == null && isset($options['apiToken'])) {
     177
     178      $audits = $api->audits($options['apiToken']);
     179
     180      if (isset($audits['body']) === false || is_null($audits['body']) === true) {
     181        return;
     182      }
     183
     184      $body = json_decode($audits['body'], true);
     185
     186      $this->updateOptions([
     187        'audits' => $body
     188      ]);
     189
     190      return;
     191    }
     192
     193    switch ($action) {
     194      case 'login':
     195      case 'register':
     196        $this->formAction = $action;
     197        $data = [
     198          'email' => sanitize_email($_POST['email']),
     199        ];
     200
     201        if (isset($_POST['password'])) {
     202          $data['password'] = sanitize_text_field($_POST['password']);
     203        }
     204
     205        if (isset($_POST['displayName'])) {
     206          $data['displayName'] = sanitize_user($_POST['displayName']);
     207        }
     208
     209        if (isset($_POST['aesKey'])) {
     210          $data['cryptData'] = [
     211            'aesKey' => sanitize_text_field($_POST['aesKey']),
     212            'publicKey' => sanitize_text_field($_POST['publicKey']),
     213            'privateKey' => sanitize_text_field($_POST['privateKey'])
     214          ];
     215        }
     216
     217        if (isset($_POST['createdVia'])) {
     218          $data['createdVia'] = sanitize_text_field($_POST['createdVia']);
     219        }
     220
     221        if (isset($_POST['timezone'])) {
     222          $data['timezone'] = sanitize_text_field($_POST['timezone']);
     223        }
     224
     225        if (isset($_POST['timezoneOffset'])) {
     226          $data['timezoneOffset'] = sanitize_text_field($_POST['timezoneOffset']);
     227        }
     228
     229        if (isset($_POST['userLanguage'])) {
     230          $data['userLanguage'] = sanitize_text_field($_POST['userLanguage']);
     231        }
     232
     233        if (isset($_POST['deriveKey'])) {
     234          $data['deriveKey'] = sanitize_text_field($_POST['deriveKey']);
     235        }
     236
     237        try {
     238          $response = $this->formAction === 'login' ? $api->login($data) : $api->create($data);
     239          $body = json_decode($response['body'], true);
     240
     241          if (isset($body['app']['user']) && $body['app']['user']['authenticated']) {
     242            if (isset($body['app']['token'])) {
     243              $this->activate(
     244                $body['app']['token']['accessToken'],
     245                $body['app']['token']['refreshToken'],
     246                sanitize_email($_POST['email']),
     247                $body['app']['user']['lastUsedWorkspace']
     248              );
     249
     250              $sites = $api->sites($body['app']['user']['lastUsedWorkspace']);
     251              $sites = json_decode($sites['body'], true);
     252
     253              $apiTokens = $api->tokens($body['app']['user']['lastUsedWorkspace']);
     254
     255              $apiTokensBody = json_decode($apiTokens['body'], true);
     256
     257              $workspaces = $api->workspaces(sanitize_email($_POST['email']));
     258              $workspaces = json_decode($workspaces['body'], true);
     259
     260              $this->updateOptions([
     261                'workspaces' => $workspaces['workspaces'],
     262                'workspace' => $body['app']['user']['lastUsedWorkspace'],
     263                'apiToken' => $apiTokensBody['tokens'][0]['tokenId'],
     264                'sites' => $sites['sites'],
     265              ]);
     266
     267              $audits = $api->audits($apiTokensBody['tokens'][0]['tokenId']);
     268
     269              $auditsBody = json_decode($audits['body'], true);
     270
     271              $this->updateOptions([
     272                'audits' => $auditsBody,
     273              ]);
     274            } else {
     275              $access_token = '';
     276              $refresh_token = '';
     277
     278              foreach ($response['headers'] as $key => $header) {
     279                if ($key === 'x-access-token') {
     280                  $access_token = $header;
     281                }
     282
     283                if ($key === 'x-refresh-token') {
     284                  $refresh_token = $header;
     285                }
     286              }
     287
     288              $this->activate($access_token, $refresh_token, sanitize_email($_POST['email']));
     289
     290              $workspaces = $api->workspaces(sanitize_email($_POST['email']));
     291              $body = json_decode($workspaces['body'], true);
     292              if (isset($body['workspaces'])) {
     293                $this->updateOptions([
     294                  'workspaces' => $body['workspaces'],
     295                ]);
     296              }
    180297            }
    181 
    182             $body = json_decode($audits['body'], true);
    183 
    184             $this->updateOptions([
    185                 'audits' => $body
    186             ]);
    187 
    188             return;
    189         }
    190 
    191         switch ($action) {
    192             case 'login':
    193             case 'register':
    194                 $this->formAction = $action;
    195                 $data = [
    196                     'email' => sanitize_email($_POST['email']),
    197                 ];
    198 
    199                 if (isset($_POST['password'])) {
    200                     $data['password'] = sanitize_text_field($_POST['password']);
    201                 }
    202 
    203                 if (isset($_POST['displayName'])) {
    204                     $data['displayName'] = sanitize_user($_POST['displayName']);
    205                 }
    206 
    207                 if (isset($_POST['aesKey'])) {
    208                     $data['cryptData'] = [
    209                         'aesKey' => sanitize_text_field($_POST['aesKey']),
    210                         'publicKey' => sanitize_text_field($_POST['publicKey']),
    211                         'privateKey' => sanitize_text_field($_POST['privateKey'])
    212                     ];
    213                 }
    214 
    215                 if (isset($_POST['createdVia'])) {
    216                     $data['createdVia'] = sanitize_text_field($_POST['createdVia']);
    217                 }
    218 
    219                 if (isset($_POST['timezone'])) {
    220                     $data['timezone'] = sanitize_text_field($_POST['timezone']);
    221                 }
    222 
    223                 if (isset($_POST['timezoneOffset'])) {
    224                     $data['timezoneOffset'] = sanitize_text_field($_POST['timezoneOffset']);
    225                 }
    226 
    227                 if (isset($_POST['userLanguage'])) {
    228                     $data['userLanguage'] = sanitize_text_field($_POST['userLanguage']);
    229                 }
    230 
    231                 if (isset($_POST['deriveKey'])) {
    232                     $data['deriveKey'] = sanitize_text_field($_POST['deriveKey']);
    233                 }
    234 
    235                 try {
    236                     $response = $this->formAction === 'login' ? $api->login($data) : $api->create($data);
    237                     $body = json_decode($response['body'], true);
    238                     if (isset($body['app']['user']) && $body['app']['user']['authenticated']) {
    239                         if (isset($body['app']['token'])) {
    240                             $this->activate(
    241                                 $body['app']['token']['accessToken'],
    242                                 $body['app']['token']['refreshToken'],
    243                                 sanitize_email($_POST['email']),
    244                                 $body['app']['user']['lastUsedWorkspace']
    245                             );
    246 
    247                             $sites = $api->sites($body['app']['user']['lastUsedWorkspace']);
    248                             $sites = json_decode($sites['body'], true);
    249 
    250                             $apiTokens = $api->tokens($body['app']['user']['lastUsedWorkspace']);
    251 
    252                             $apiTokensBody = json_decode($apiTokens['body'], true);
    253 
    254                             $workspaces = $api->workspaces(sanitize_email($_POST['email']));
    255                             $workspaces = json_decode($workspaces['body'], true);
    256 
    257                             $this->updateOptions([
    258                                 'workspaces' => $workspaces['workspaces'],
    259                                 'workspace' => $body['app']['user']['lastUsedWorkspace'],
    260                                 'apiToken' => $apiTokensBody['tokens'][0]['tokenId'],
    261                                 'sites' => $sites['sites'],
    262                             ]);
    263 
    264                             $audits = $api->audits($apiTokensBody['tokens'][0]['tokenId']);
    265 
    266                             $auditsBody = json_decode($audits['body'], true);
    267 
    268                             $this->updateOptions([
    269                                 'audits' => $auditsBody,
    270                             ]);
    271                         } else {
    272                             $access_token = '';
    273                             $refresh_token = '';
    274 
    275                             foreach ($response['headers'] as $key => $header) {
    276                                 if ($key === 'x-access-token') {
    277                                     $access_token = $header;
    278                                 }
    279 
    280                                 if ($key === 'x-refresh-token') {
    281                                     $refresh_token = $header;
    282                                 }
    283                             }
    284 
    285                             $this->activate($access_token, $refresh_token, sanitize_email($_POST['email']));
    286 
    287                             $workspaces = $api->workspaces(sanitize_email($_POST['email']));
    288                             $body = json_decode($workspaces['body'], true);
    289                             if (isset($body['workspaces'])) {
    290                                 $this->updateOptions([
    291                                     'workspaces' => $body['workspaces'],
    292                                 ]);
    293                             }
    294                         }
    295                     } else {
    296                         $this->message = $body['app']['description'];
    297                         $this->email = sanitize_email($_POST['email']);
    298                     }
    299                 } catch (Exception $e) {
    300                     print_r($e);
    301                     $this->message = $e->getMessage();
    302                     $this->email = sanitize_email($_POST['email']);
    303                 }
    304                 break;
    305             case 'loadWorkspaceTokens':
    306                 $this->updateOptions([
    307                     'workspace' => sanitize_text_field($_POST['workspace']),
    308                 ]);
    309 
    310                 $tokens = $api->tokens(sanitize_text_field($_POST['workspace']));
    311                 $sites = $api->sites(sanitize_text_field($_POST['workspace']));
    312 
    313                 if (empty($tokens['body']) || empty($sites['body'])) {
    314                   return;
    315                 }
    316 
    317                 $body = json_decode($tokens['body'], true);
    318                 $sites = json_decode($sites['body'], true);
    319 
    320                 $this->updateOptions([
    321                     'apiTokens' => $body['tokens'],
    322                     'sites' => $sites['sites'],
    323                 ]);
    324                 break;
    325             case 'updateToken':
    326                 $this->updateOptions([
    327                     'apiToken' => sanitize_text_field($_POST['apiToken']),
    328                 ]);
    329 
    330                 $tokenId = $_POST['apiToken'];
    331 
    332                 if (empty($options['sites'])) {
    333                   return;
    334                 }
    335 
    336                 foreach ($options['sites'] as $site) {
    337                     if ($site['apiToken']['tokenId'] == $tokenId) {
    338                         $options['site'] = $site;
    339                     }
    340                 }
    341 
    342                 $this->updateOptions([
    343                     'site' => $options['site']['name'],
    344                 ]);
    345 
    346                 $audits = $api->audits(sanitize_text_field($_POST['apiToken']));
    347                 $body = json_decode($audits['body'], true);
    348 
    349                 $this->updateOptions([
    350                     'audits' => $body
    351                 ]);
    352 
    353                 break;
    354             case 'clearToken':
    355                 $this->updateOptions([
    356                     'apiToken' => null,
    357                     'audits' => null,
    358                 ]);
    359                 $workspaces = $api->workspaces($options['email']);
    360                 $body = json_decode($workspaces['body'], true);
    361                 if (isset($body['workspaces'])) {
    362                     $this->updateOptions([
    363                         'workspaces' => $body['workspaces'],
    364                     ]);
    365                 }
    366 
    367                 if (isset($options['workspace'])) {
    368                     $tokens = $api->tokens($options['workspace']);
    369                     $body = json_decode($tokens['body'], true);
    370                     $this->updateOptions([
    371                         'apiTokens' => $body['tokens'],
    372                     ]);
    373                 }
    374                 break;
    375             case 'clearWorkspace':
    376                 $this->updateOptions([
    377                     'workspace' => null,
    378                     'apiToken' => null,
    379                     'audits' => null,
    380                 ]);
    381                 $workspaces = $api->workspaces($options['email']);
    382                 $body = json_decode($workspaces['body'], true);
    383                 if (isset($body['workspaces'])) {
    384                     $this->updateOptions([
    385                         'workspaces' => $body['workspaces'],
    386                     ]);
    387                 }
    388                 break;
    389             case 'allowSiteLint':
    390                 $key = $options['active'] ? false : true;
    391                 $this->updateOptions([
    392                     'active' => $key
    393                 ]);
    394                 break;
    395             case 'addSiteLintLogo':
    396                 $key = $options['addLogo'] ? false : true;
    397                 $this->updateOptions([
    398                     'addLogo' => $key
    399                 ]);
    400                 break;
    401             case 'disable':
    402                 $this->deactivate();
    403                 break;
    404             default:
    405                 $this->message = 'Invalid action';
    406                 break;
    407         }
    408     }
    409 
    410     private function activate($accessToken, $refreshToken, $email, $workspace = null)
    411     {
    412         $this->updateOptions([
    413             'active' => true,
    414             'accessToken' => (string) $accessToken,
    415             'refreshToken' => (string) $refreshToken,
    416             'apiToken' => '',
    417             'apiTokens' => [],
    418             'workspace' => null,
    419             'workspaces' => null,
    420             'email' => (string) $email,
    421             'audits' => null,
    422             'addLogo' => false,
    423             'sites' => null
    424         ]);
    425 
    426         if ($workspace !== null) {
    427             $this->updateOptions([
    428                 'workspace' => $workspace,
    429             ]);
    430         }
    431     }
    432 
    433     private function deactivate()
    434     {
    435         $this->updateOptions([
    436             'active' => false,
    437             'accessToken' => null,
    438             'refreshToken' => null,
    439             'apiToken' => '',
    440             'apiTokens' => [],
    441             'workspace' => null,
    442             'workspaces' => null,
    443             'email' => null,
    444             'audits' => null,
    445             'addLogo' => false,
    446             'sites' => null
    447         ]);
    448     }
    449 
    450     private function updateOptions(array $options)
    451     {
    452         $current = $this->getOptions();
    453         foreach ($options as $key => $option) {
    454             $current[$key] = $option;
    455         }
    456         update_option(self::OPTION_NAME, $current);
    457     }
    458 
    459     private function getOptions()
    460     {
    461         return get_option(self::OPTION_NAME);
    462     }
     298          } else {
     299            $this->message = $body['app']['description'];
     300            $this->email = sanitize_email($_POST['email']);
     301          }
     302        } catch (Exception $e) {
     303          $this->message = $e->getMessage();
     304          $this->email = sanitize_email($_POST['email']);
     305        }
     306        break;
     307
     308      case 'loadWorkspaceTokens':
     309        $this->updateOptions([
     310          'workspace' => sanitize_text_field($_POST['workspace']),
     311        ]);
     312
     313        $tokens = $api->tokens(sanitize_text_field($_POST['workspace']));
     314        $sites = $api->sites(sanitize_text_field($_POST['workspace']));
     315
     316        if (empty($tokens['body']) || empty($sites['body'])) {
     317          return;
     318        }
     319
     320        $body = json_decode($tokens['body'], true);
     321        $sites = json_decode($sites['body'], true);
     322
     323        $this->updateOptions([
     324          'apiTokens' => $body['tokens'],
     325          'sites' => $sites['sites']
     326        ]);
     327        break;
     328      case 'updateToken':
     329        $this->updateOptions([
     330          'apiToken' => sanitize_text_field($_POST['apiToken']),
     331        ]);
     332
     333        $tokenId = $_POST['apiToken'];
     334
     335        if (empty($options['sites'])) {
     336          return;
     337        }
     338
     339        foreach ($options['sites'] as $site) {
     340          if ($site['apiToken']['tokenId'] == $tokenId) {
     341            $options['site'] = $site;
     342          }
     343        }
     344
     345        $this->updateOptions([
     346          'site' => $options['site']['name'],
     347        ]);
     348
     349        $audits = $api->audits(sanitize_text_field($_POST['apiToken']));
     350        $body = json_decode($audits['body'], true);
     351
     352        $this->updateOptions([
     353          'audits' => $body
     354        ]);
     355
     356        break;
     357      case 'clearToken':
     358        $this->updateOptions([
     359          'apiToken' => null,
     360          'audits' => null,
     361        ]);
     362        $workspaces = $api->workspaces($options['email']);
     363        $body = json_decode($workspaces['body'], true);
     364        if (isset($body['workspaces'])) {
     365          $this->updateOptions([
     366            'workspaces' => $body['workspaces'],
     367          ]);
     368        }
     369
     370        if (isset($options['workspace'])) {
     371          $tokens = $api->tokens($options['workspace']);
     372          $body = json_decode($tokens['body'], true);
     373          $this->updateOptions([
     374            'apiTokens' => $body['tokens'],
     375          ]);
     376        }
     377        break;
     378      case 'clearWorkspace':
     379        $this->updateOptions([
     380          'workspace' => null,
     381          'apiToken' => null,
     382          'audits' => null,
     383        ]);
     384        $workspaces = $api->workspaces($options['email']);
     385        $body = json_decode($workspaces['body'], true);
     386        if (isset($body['workspaces'])) {
     387          $this->updateOptions([
     388            'workspaces' => $body['workspaces'],
     389          ]);
     390        }
     391        break;
     392      case 'allowSiteLint':
     393        $key = $options['active'] ? false : true;
     394        $this->updateOptions([
     395          'active' => $key
     396        ]);
     397        break;
     398      case 'addSiteLintLogo':
     399        $key = $options['addLogo'] ? false : true;
     400        $this->updateOptions([
     401          'addLogo' => $key
     402        ]);
     403        break;
     404      case 'disable':
     405        $this->deactivate();
     406        break;
     407      default:
     408        $this->message = 'Invalid action';
     409        break;
     410    }
     411  }
     412
     413  private function activate($accessToken, $refreshToken, $email, $workspace = null)
     414  {
     415    $this->updateOptions([
     416      'active' => true,
     417      'accessToken' => (string) $accessToken,
     418      'refreshToken' => (string) $refreshToken,
     419      'apiToken' => '',
     420      'apiTokens' => [],
     421      'workspace' => null,
     422      'workspaces' => null,
     423      'email' => (string) $email,
     424      'audits' => null,
     425      'addLogo' => false,
     426      'sites' => null
     427    ]);
     428
     429    if ($workspace !== null) {
     430      $this->updateOptions([
     431        'workspace' => $workspace,
     432      ]);
     433    }
     434  }
     435
     436  private function deactivate()
     437  {
     438    $this->updateOptions([
     439      'active' => false,
     440      'accessToken' => null,
     441      'refreshToken' => null,
     442      'apiToken' => '',
     443      'apiTokens' => [],
     444      'workspace' => null,
     445      'workspaces' => null,
     446      'email' => null,
     447      'audits' => null,
     448      'addLogo' => false,
     449      'sites' => null
     450    ]);
     451  }
     452
     453  private function updateOptions(array $options)
     454  {
     455    $current = $this->getOptions();
     456    foreach ($options as $key => $option) {
     457      $current[$key] = $option;
     458    }
     459    update_option(self::OPTION_NAME, $current);
     460  }
     461
     462  private function getOptions()
     463  {
     464    return get_option(self::OPTION_NAME);
     465  }
    463466}
  • sitelint/trunk/includes/sitelint-audits.php

    r3226285 r3229645  
    129129        SiteLint_Loader::add_action('admin_init', $plugin_admin, 'performAction');
    130130        SiteLint_Loader::add_action('in_admin_header', $plugin_admin, 'handleInAdminHeader');
    131 
     131       
    132132        $plugin_admin->enqueue_styles();
    133133        $plugin_admin->enqueue_scripts();
  • sitelint/trunk/public/sitelint-public.php

    r3226258 r3229645  
    6868    public function enqueue_scripts()
    6969    {
    70         $sitelint = get_option('sitelint');
     70      $sitelint = get_option('sitelint');
    7171
    72         $config = file_get_contents(__DIR__ . '/config.json');
    73         $appConfig = json_decode($config, true);
    74         $sitelintLoader = '';
    75         $sitelintLoaderId = '';
     72      $config = file_get_contents(__DIR__ . '/config.json');
     73      $appConfig = json_decode($config, true);
     74      $sitelintLoader = '';
     75      $sitelintLoaderId = '';
     76      $isApiTokenAvailable = !empty($sitelint['apiToken']) && (is_string($sitelint['apiToken']) && $sitelint['apiToken'] !== 'null');
     77      $auditorUrlParam = $isApiTokenAvailable ? "?tokenId=" . esc_html($sitelint['apiToken']) : "";
    7678
    77         // Note: $sitelint['apiToken'] === 'null' is used because initial value was saved from null previously, but WordPress converts it to string 'null'
     79      if ($sitelint['active'] == false) {
     80        return;
     81      }
    7882
    79         if ($sitelint['active'] == true && !empty($sitelint['apiToken']) && (is_string($sitelint['apiToken']) && $sitelint['apiToken'] !== 'null')) {
    80           $sitelintLoaderId = 'auditor_script_admin';
     83      if (is_admin()) {
     84        return;
     85      }
    8186
    82           $sitelintLoader = "(function(w,d,s,a,m,t) {
     87      // Note: $sitelint['apiToken'] === 'null' is used because initial value was saved from null previously, but WordPress converts it to string 'null'
    8388
    84                 const auditorScript = document.getElementById('auditor_script_public');
    85                 const auditorAppScript = document.getElementById('auditor_app');
     89      $sitelintLoaderId = 'auditor_script';
    8690
    87                 if (auditorScript) {
    88                   auditorScript.remove();
    89                 }
     91      $sitelintLoader = "(function(w,d,s,a,m,t) {
     92        const auditorAppScript = document.getElementById('auditor_app');
    9093
    91                 if (auditorAppScript) {
    92                   auditorAppScript.remove();
    93                 }
    94 
    95                 a = d.createElement(s);m = d.getElementsByTagName(s)[0];a.defer = true;a.id = 'auditor_app';a.src = '" . esc_attr($appConfig['auditorUrl']) . "/auditor.bundle.js?tokenId=" .
    96                 esc_html($sitelint['apiToken']) .
    97                 "';
    98 
    99                 function onPageLoaded() {
    100                   w.clearTimeout(t);
    101                   w.removeEventListener('DOMContentLoaded', onPageLoaded);
    102                   m.parentNode.insertBefore(a, m);
    103                 }
    104 
    105                 function onAuditorLoaded(){
    106                   auditor.config({
    107                     includeHidden: true,
    108                     saveMinimizedMaximizedState: true,
    109                     stripTextFromReport: false
    110                   }).run();
    111                 }
    112 
    113                 function onBeforeUnload() {
    114                   const element = document.getElementById('auditor_app');
    115                   if (element) {
    116                     element.remove();
    117                   }
    118                 }
    119 
    120                 a.addEventListener('load', onAuditorLoaded);
    121 
    122                 if (d.readyState !== 'loading') {
    123                   onPageLoaded();
    124                   return;
    125                 }
    126 
    127                 w.addEventListener('DOMContentLoaded', onPageLoaded);
    128 
    129                 document.addEventListener('beforeunload', onBeforeUnload);
    130               })(window, document, 'script');";
    131         } else if ($sitelint['active'] == false || empty($sitelint['apiToken']) || (is_string($sitelint['apiToken']) && $sitelint['apiToken'] === 'null')) {
    132 
    133           $sitelintLoaderId = 'auditor_script_public';
    134 
    135           $sitelintLoader = "(function(w,d,s,a,m,t) {
    136 
    137                 const auditorScript = document.getElementById('auditor_script_admin');
    138                 const auditorAppScript = document.getElementById('auditor_app');
    139 
    140                 if (auditorScript) {
    141                   auditorScript.remove();
    142                 }
    143 
    144                 if (auditorAppScript) {
    145                   auditorAppScript.remove();
    146                 }
    147 
    148                 a = d.createElement(s);m = d.getElementsByTagName(s)[0];a.defer = true;a.id = 'auditor_app';a.src = '" . esc_attr($appConfig['auditorUrl']) . "/auditor.bundle.js';
    149 
    150                 function onPageLoaded() {
    151                   w.clearTimeout(t);
    152                   w.removeEventListener('DOMContentLoaded', onPageLoaded);
    153                   m.parentNode.insertBefore(a, m);
    154                 }
    155 
    156                 function onAuditorLoaded(){
    157                   auditor.config({
    158                     includeHidden: true,
    159                     saveMinimizedMaximizedState: true,
    160                     stripTextFromReport: false,
    161                     skipSendingReports: true
    162                   }).run();
    163                 }
    164 
    165                 function onBeforeUnload() {
    166                   const element = document.getElementById('auditor_app');
    167                   if (element) {
    168                     element.remove();
    169                   }
    170                 }
    171 
    172                 a.addEventListener('load', onAuditorLoaded);
    173 
    174                 if (d.readyState !== 'loading') {
    175                   onPageLoaded();
    176                   return;
    177                 }
    178 
    179                 w.addEventListener('DOMContentLoaded', onPageLoaded);
    180 
    181                 document.addEventListener('beforeunload', onBeforeUnload);
    182               })(window, document, 'script');";
     94        if (auditorAppScript) {
     95          return;
    18396        }
    18497
    185         function add_inline_script($sitelintLoaderId, $sitelintLoader) {
    186           wp_register_script($sitelintLoaderId, '');
    187           wp_enqueue_script($sitelintLoaderId);
    188           wp_add_inline_script($sitelintLoaderId, $sitelintLoader);
     98        a = d.createElement(s);m = d.getElementsByTagName(s)[0];a.defer = true;a.id = 'auditor_app';a.src = '" . esc_attr($appConfig['auditorUrl']) . "/auditor.bundle.js" . $auditorUrlParam . "';
     99
     100        function onPageLoaded() {
     101          w.clearTimeout(t);
     102          w.removeEventListener('DOMContentLoaded', onPageLoaded);
     103          m.parentNode.insertBefore(a, m);
    189104        }
    190105
    191         add_action('wp_enqueue_scripts', function() use ($sitelintLoaderId, $sitelintLoader) {
    192           add_inline_script($sitelintLoaderId, $sitelintLoader);
    193         });
     106        function onAuditorLoaded(){
     107          auditor.config({
     108            includeHidden: true,
     109            saveMinimizedMaximizedState: true,
     110            stripTextFromReport: false" . ($isApiTokenAvailable ? "" : ",\n skipSendingReports: true") . "
     111          }).run();
     112        }
     113
     114        function onBeforeUnload() {
     115          const element = document.getElementById('auditor_app');
     116          if (element) {
     117            element.remove();
     118          }
     119        }
     120
     121        a.addEventListener('load', onAuditorLoaded);
     122
     123        if (d.readyState !== 'loading') {
     124          onPageLoaded();
     125          return;
     126        }
     127
     128        w.addEventListener('DOMContentLoaded', onPageLoaded);
     129
     130        document.addEventListener('beforeunload', onBeforeUnload);
     131      })(window, document, 'script');";
     132
     133      wp_register_script($sitelintLoaderId, '');
     134      wp_enqueue_script($sitelintLoaderId);
     135      wp_add_inline_script($sitelintLoaderId, $sitelintLoader);
    194136    }
    195137
  • sitelint/trunk/shared/services/Api.php

    r3223115 r3229645  
    11<?php
    2 namespace SiteLint\Auth;
     2namespace SiteLint\Shared\Services;
    33
    44use Exception;
    55use stdClass;
    6 use SiteLint\Shared\Http\ResponseStatus;
    76
    87/**
     
    2120class Api
    2221{
    23     private $config;
    24     private $appConfig;
    25     private $apiBaseUrl;
    26 
    27     const OPTION_NAME = 'sitelint';
    28 
    29     /** URL paths for all used resources endpoints methods */
    30     const URL_CHECK_EMAIL = 'user/check-email',
    31         URL_LOGIN = 'user/login',
    32         URL_CREATE = 'user/signup',
    33         URL_WORKSPACES = 'workspaces/user',
    34         URL_TOKENS = 'api-token/workspaces',
    35         URL_SITES = 'sites',
    36         URL_REFRESH_ACCESS_TOKEN = 'auth/refreshAccessToken',
    37         URL_AUDITS = 'audits';
    38 
    39 
    40     public function __construct()
    41     {
    42         $this->config = file_get_contents(__DIR__ . '/../../public/config.json');
    43         $this->appConfig = json_decode($this->config, true);
    44         $this->apiBaseUrl = $this->appConfig['apiUrl'];
    45     }
    46 
    47     /**
    48      * Allows to create user.
    49      *
    50      * @param array $data
    51      * @return array
    52      */
    53     public function create($data)
    54     {
    55         return $this->post(self::URL_CREATE, $data);
    56     }
    57 
    58     /**
    59      * Allows to log in account and obtain user key.
    60      *
    61      * @param array $data
    62      * @return array
    63      */
    64     public function login($data)
    65     {
    66         return $this->post(self::URL_LOGIN, $data);
    67     }
    68 
    69     /**
    70      * Allows to log in account and obtain user key.
    71      *
    72      * @param array $data
    73      * @return array
    74      */
    75     public function checkEmail($email)
    76     {
    77         $queryParams = [
    78             'email' => $email
    79         ];
    80 
    81         return $this->get(self::URL_CHECK_EMAIL, $queryParams);
    82     }
    83 
    84     /**
    85      * Allows to log in account and obtain user key.
    86      *
    87      * @param array $data
    88      * @return array
    89      */
    90     public function workspaces($email)
    91     {
    92         $queryParams = [
    93             'email' => $email
    94         ];
    95 
    96         return $this->get(self::URL_WORKSPACES,  $queryParams);
    97     }
    98 
    99     /**
    100      * Allows to log in account and obtain user key.
    101      *
    102      * @param array $data
    103      * @return array
    104      */
    105     public function tokens($workspace)
    106     {
    107         $queryParams = [
    108             "skip" => 0,
    109             "limit" => 0
    110         ];
    111 
    112         return $this->get(self::URL_TOKENS . "/$workspace", $queryParams);
    113     }
    114 
    115     /**
    116      * Allows to fetch sites by workspace Id.
    117      *
    118      * @param string $workspace
    119      * @return array
    120      */
    121     public function sites($workspace)
    122     {
    123         $queryParams = [
    124             "workspaceId" => $workspace,
    125             "skip" => 0,
    126             "limit" => 0,
    127         ];
    128 
    129         return $this->get(self::URL_SITES, $queryParams);
    130     }
    131 
    132     /**
    133      * Allows to log in account and obtain user key.
    134      *
    135      * @param array $data
    136      * @return array
    137      */
    138     public function audits($apiToken)
    139     {
    140       if (empty($apiToken)) {
    141         return [];
     22  private $config;
     23  private $appConfig;
     24  private $apiBaseUrl;
     25
     26  private const OPTION_NAME = 'sitelint';
     27
     28  /** URL paths for all used resources endpoints methods */
     29  private const URL_CHECK_EMAIL = 'user/check-email',
     30    URL_LOGIN = 'user/login',
     31    URL_CREATE = 'user/signup',
     32    URL_WORKSPACES = 'workspaces/user',
     33    URL_TOKENS = 'api-token/workspaces',
     34    URL_SITES = 'sites',
     35    URL_REFRESH_ACCESS_TOKEN = 'auth/refreshAccessToken',
     36    URL_AUDITS = 'audits';
     37
     38
     39  public function __construct()
     40  {
     41    $this->config = file_get_contents(__DIR__ . '/../../public/config.json');
     42    $this->appConfig = json_decode($this->config, true);
     43    $this->apiBaseUrl = $this->appConfig['apiUrl'];
     44  }
     45
     46  /**
     47   * Allows to create user.
     48   *
     49   * @param array $data
     50   * @return array
     51   */
     52  public function create($data)
     53  {
     54    return $this->post(self::URL_CREATE, $data);
     55  }
     56
     57  /**
     58   * Allows to log in account and obtain user key.
     59   *
     60   * @param array $data
     61   * @return array
     62   */
     63  public function login($data)
     64  {
     65    return $this->post(self::URL_LOGIN, $data);
     66  }
     67
     68  /**
     69   * Allows to log in account and obtain user key.
     70   *
     71   * @param array $data
     72   * @return array
     73   */
     74  public function checkEmail($email)
     75  {
     76    $queryParams = [
     77      'email' => $email
     78    ];
     79
     80    return $this->get(self::URL_CHECK_EMAIL, $queryParams);
     81  }
     82
     83  /**
     84   * Allows to log in account and obtain user key.
     85   *
     86   * @param array $data
     87   * @return array
     88   */
     89  public function workspaces($email)
     90  {
     91    $queryParams = [
     92      'email' => $email
     93    ];
     94
     95    return $this->get(self::URL_WORKSPACES,  $queryParams);
     96  }
     97
     98  /**
     99   * Allows to log in account and obtain user key.
     100   *
     101   * @param array $data
     102   * @return array
     103   */
     104  public function tokens($workspace)
     105  {
     106    $queryParams = [
     107      "skip" => 0,
     108      "limit" => 0
     109    ];
     110
     111    return $this->get(self::URL_TOKENS . "/$workspace", $queryParams);
     112  }
     113
     114  /**
     115   * Allows to fetch sites by workspace Id.
     116   *
     117   * @param string $workspace
     118   * @return array
     119   */
     120  public function sites($workspace)
     121  {
     122    $queryParams = [
     123      "workspaceId" => $workspace,
     124      "skip" => 0,
     125      "limit" => 0,
     126    ];
     127
     128    return $this->get(self::URL_SITES, $queryParams);
     129  }
     130
     131  /**
     132   * Allows to log in account and obtain user key.
     133   *
     134   * @param array $data
     135   * @return array
     136   */
     137  public function audits($apiToken)
     138  {
     139    if (empty($apiToken)) {
     140      return [];
     141    }
     142
     143    $queryParams = [
     144      "auditTypes" => "accessibility,logs,performance,privacy,quality,security,seo",
     145      "statuses" => "error,passed",
     146      "impactsType" => "critical,high,low,info",
     147      "standardVersions" => "1.0,2.0,2.1,2.2",
     148      "standardLevels" => "A,AA,AAA,best_practices",
     149      "errors" => "true",
     150      "needsReview" => "true",
     151      "recommendations" => "true"
     152    ];
     153
     154    return $this->get(self::URL_AUDITS . "/$apiToken/last", $queryParams);
     155  }
     156
     157  /**
     158   * Helper function to execute POST request.
     159   *
     160   * @param string $path request path
     161   * @param array $data optional POST data array
     162   * @return array|string array data or json encoded string of result
     163   * @throws Exception
     164   */
     165  private function post($path, $data)
     166  {
     167    $option = get_option(self::OPTION_NAME);
     168    $headers = ['Accept' => 'application/json', 'Content-Type' => 'application/json'];
     169
     170    if (isset($option['accessToken'])) {
     171      $headers['Authorization'] = 'Bearer ' . $option['accessToken'];
     172    }
     173
     174    $httpParams = [];
     175
     176    $httpParams['httpversion'] = '1.1';
     177    $httpParams['headers'] = $headers;
     178    $httpParams['body'] = json_encode($data);
     179    $httpParams['sslverify'] = false;
     180
     181    $response = wp_remote_post($this->apiBaseUrl . $path, $httpParams);
     182
     183    if (is_wp_error($response)) {
     184      return NULL;
     185    }
     186
     187    return $response;
     188  }
     189
     190  /**
     191   * Helper function to execute POST request.
     192   *
     193   * @param string $path request path
     194   * @param array $data optional POST data array
     195   * @return array|string array data or json encoded string of result
     196   * @throws Exception
     197   */
     198  private function get($path, $query, $retryCount = 0)
     199  {
     200    $option = get_option(self::OPTION_NAME);
     201    $headers = ['Accept' => 'application/json'];
     202
     203    if (isset($option['accessToken'])) {
     204      $headers['Authorization'] = 'Bearer ' . $option['accessToken'];
     205    }
     206
     207    $httpParams = [];
     208    $httpParams['httpversion'] = '1.1';
     209    $httpParams['headers'] = $headers;
     210    $httpParams['sslverify'] = false;
     211
     212    $response = wp_remote_get($this->apiBaseUrl . $path . '?' . http_build_query($query), $httpParams);
     213
     214    if (is_wp_error($response)) {
     215      return NULL;
     216    }
     217
     218    $body = wp_remote_retrieve_body($response);
     219
     220    if (empty($body)) {
     221      $body = new stdClass();
     222    } else {
     223      $body = json_decode($body);
     224    }
     225
     226    if ($body === null && json_last_error() !== JSON_ERROR_NONE) {
     227      $body = new stdClass();
     228    }
     229
     230    if (isset($body->status) && $body->status == \SiteLint\Shared\Http\ResponseStatus::FORBIDDEN) {
     231      $retryCount++;
     232
     233      if ($retryCount > MAX_REFRESH_ACCESS_TOKEN_RETRIES) {
     234        return NULL;
    142235      }
    143236
    144       $queryParams = [
    145           "auditTypes" => "accessibility,logs,performance,privacy,quality,security,seo",
    146           "statuses" => "error,passed",
    147           "impactsType" => "critical,high,low,info",
    148           "standardVersions" => "1.0,2.0,2.1,2.2",
    149           "standardLevels" => "A,AA,AAA,best_practices",
    150           "errors" => "true",
    151           "needsReview" => "true",
    152           "recommendations" => "true"
    153       ];
    154 
    155       return $this->get(self::URL_AUDITS . "/$apiToken/last", $queryParams);
    156     }
    157 
    158     /**
    159      * Helper function to execute POST request.
    160      *
    161      * @param string $path request path
    162      * @param array $data optional POST data array
    163      * @return array|string array data or json encoded string of result
    164      * @throws Exception
    165      */
    166     private function post($path, $data)
    167     {
    168         $option = get_option(self::OPTION_NAME);
    169         $headers = ['Accept' => 'application/json', 'Content-Type' => 'application/json'];
    170 
    171         if (isset($option['accessToken'])) {
    172             $headers['Authorization'] = 'Bearer ' . $option['accessToken'];
    173         }
    174 
    175         $httpParams = [];
    176 
    177         $httpParams['httpversion'] = '1.1';
    178         $httpParams['headers'] = $headers;
    179         $httpParams['body'] = json_encode($data);
    180         $httpParams['sslverify'] = false;
    181 
    182         $response = wp_remote_post($this->apiBaseUrl . $path, $httpParams);
    183 
    184         if (is_wp_error($response)) {
    185             print_r($response);
    186 
    187             return NULL;
    188         }
    189 
    190         return $response;
    191     }
    192 
    193     /**
    194      * Helper function to execute POST request.
    195      *
    196      * @param string $path request path
    197      * @param array $data optional POST data array
    198      * @return array|string array data or json encoded string of result
    199      * @throws Exception
    200      */
    201     private function get($path, $query, $retryCount = 0)
    202     {
    203         $option = get_option(self::OPTION_NAME);
    204         $headers = ['Accept' => 'application/json'];
    205 
    206         if (isset($option['accessToken'])) {
    207             $headers['Authorization'] = 'Bearer ' . $option['accessToken'];
    208         }
    209 
    210         $httpParams = [];
    211         $httpParams['httpversion'] = '1.1';
    212         $httpParams['headers'] = $headers;
    213         $httpParams['sslverify'] = false;
    214 
    215         $response = wp_remote_get($this->apiBaseUrl . $path . '?' . http_build_query($query), $httpParams);
    216 
    217         if (is_wp_error($response)) {
    218             return NULL;
    219         }
    220 
    221         $body = wp_remote_retrieve_body($response);
    222 
    223         if (empty($body)) {
    224           $body = new stdClass();
    225         } else {
    226           $body = json_decode($body, true); // Corrected variable usage
    227         }
    228 
    229         if ($body === null && json_last_error() !== JSON_ERROR_NONE) {
    230           $body = new stdClass();
    231         }
    232 
    233         if (isset($body->status) && $body->status == ResponseStatus::FORBIDDEN) {
    234             $retryCount++;
    235 
    236             if ($retryCount > MAX_REFRESH_ACCESS_TOKEN_RETRIES) {
    237                 return NULL;
    238             }
    239 
    240             $this->refreshAccessToken();
    241             return $this->get($path, $query, $retryCount);
    242         }
    243 
    244         return $response;
    245     }
    246 
    247     private function refreshAccessToken()
    248     {
    249         $option = get_option(self::OPTION_NAME);
    250 
    251         if (isset($option['accessToken'])) {
    252             $headers['x-refresh-token'] = $option['refreshToken'];
    253         }
    254 
    255         $httpParams = [];
    256 
    257         $httpParams['httpversion'] = '1.1';
    258         $httpParams['headers'] = $headers;
    259         $httpParams['sslverify'] = false;
    260         $response = wp_remote_get($this->apiBaseUrl . self::URL_REFRESH_ACCESS_TOKEN, $httpParams);
    261 
    262         if (is_wp_error($response) || isset($body['error'])) {
    263             $this->deactivate();
    264 
    265             $page = esc_url_raw($_SERVER['PHP_SELF']);
    266             $sec = '1';
    267 
    268             header("Refresh: $sec; url=$page");
    269         }
    270 
    271         if (isset($response['headers']['x-access-token'])) {
    272             $this->updateOptions([
    273                 'accessToken' => $response['headers']['x-access-token']
    274             ]);
    275         }
    276     }
    277 
    278     private function deactivate()
    279     {
    280         $this->updateOptions([
    281             'active' => false,
    282             'accessToken' => null,
    283             'refreshToken' => null,
    284             'apiToken' => null,
    285             'apiTokens' => null,
    286             'workspace' => null,
    287             'workspaces' => null,
    288             'email' => null,
    289             'audits' => null,
    290         ]);
    291     }
    292 
    293     private function updateOptions(array $options)
    294     {
    295         $current = $this->getOptions();
    296         foreach ($options as $key => $option) {
    297             $current[$key] = $option;
    298         }
    299         update_option(self::OPTION_NAME, $current);
    300     }
    301 
    302     /**
    303      * @return array
    304      */
    305     private function getOptions()
    306     {
    307         return get_option(self::OPTION_NAME);
    308     }
     237      $this->refreshAccessToken();
     238      return $this->get($path, $query, $retryCount);
     239    }
     240
     241    return $response;
     242  }
     243
     244  private function refreshAccessToken()
     245  {
     246    $option = get_option(self::OPTION_NAME);
     247
     248    if (isset($option['accessToken'])) {
     249      $headers['x-refresh-token'] = $option['refreshToken'];
     250    }
     251
     252    $httpParams = [];
     253
     254    $httpParams['httpversion'] = '1.1';
     255    $httpParams['headers'] = $headers;
     256    $httpParams['sslverify'] = false;
     257    $response = wp_remote_get($this->apiBaseUrl . self::URL_REFRESH_ACCESS_TOKEN, $httpParams);
     258
     259    if (is_wp_error($response) || isset($body['error'])) {
     260      $this->deactivate();
     261
     262      $page = esc_url_raw($_SERVER['PHP_SELF']);
     263      $sec = '1';
     264
     265      header("Refresh: $sec; url=$page");
     266    }
     267
     268    if (isset($response['headers']['x-access-token'])) {
     269      $this->updateOptions([
     270        'accessToken' => $response['headers']['x-access-token']
     271      ]);
     272    }
     273  }
     274
     275  private function deactivate()
     276  {
     277    $this->updateOptions([
     278      'active' => false,
     279      'accessToken' => null,
     280      'refreshToken' => null,
     281      'apiToken' => null,
     282      'apiTokens' => null,
     283      'workspace' => null,
     284      'workspaces' => null,
     285      'email' => null,
     286      'audits' => null,
     287    ]);
     288  }
     289
     290  private function updateOptions(array $options)
     291  {
     292    $current = $this->getOptions();
     293    foreach ($options as $key => $option) {
     294      $current[$key] = $option;
     295    }
     296    update_option(self::OPTION_NAME, $current);
     297  }
     298
     299  /**
     300   * @return array
     301   */
     302  private function getOptions()
     303  {
     304    return get_option(self::OPTION_NAME);
     305  }
    309306}
  • sitelint/trunk/sitelint.php

    r3226285 r3229645  
    1010 * Plugin Name:       SiteLint
    1111 * Description:       SiteLint - official plugin. Accessibility, SEO, Performance, Security, Privacy, Technical issues in one place. Client-side & real-time checker.
    12  * Version:           1.5.13
     12 * Version:           1.5.14
    1313 * Author:            SiteLint
    1414 * Author URI:        https://www.sitelint.com
     
    2727 * Currently plugin version. Use SemVer - https://semver.org
    2828 */
    29 define('SITELINT_VERSION', '1.5.13');
     29define('SITELINT_VERSION', '1.5.14');
    3030
    3131/**
Note: See TracChangeset for help on using the changeset viewer.