Plugin Directory

Changeset 3262157


Ignore:
Timestamp:
03/26/2025 12:20:02 PM (12 months ago)
Author:
minicrmio
Message:

Performance enhancements and bugfixes

Location:
minicrm-woocommerce-sync/trunk
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • minicrm-woocommerce-sync/trunk/includes/settings.js

    r2582919 r3262157  
    4343}
    4444
     45function startSync(test) {
     46  jQuery.ajax ({
     47    data: {
     48      action: 'get_projects',
     49    },
     50    dataType: 'json',
     51    method: 'GET',
     52    url: minicrmWoocommerceSyncData.ajaxUrl,
     53    timeout: minicrmWoocommerceSyncData.timeoutInSecs * 1000,
     54  })
     55  .error (() => {
     56    progressText.innerHTML = __('An unexpected <strong class="minicrm-woocommerce-sync-error">error occured</strong> while fetching orders for sync. Please try again later!')
     57    return
     58  })
     59  .done ((response) => {
     60    setActiveState (true)
     61    iterateSyncCycle(test, response.projects, response.projects.length, false, new Date)
     62  })
     63}
     64
    4565/**
    4666 * @param {boolean} test              If syncing with test server
    4767 * @param {Array}   [projectIdsLeft]  Project IDs left to sync.
    48  * @param {boolean} [hasErrorOccured] Number of failed sync requests.
     68 * @param {int}     [projectIdsCount]  Number of all project IDs.
     69 * @param {boolean} [hasErrorOccurred] Number of failed sync requests.
    4970 * @param {Date}    [start]           Time of sync start
    5071 */
    51 function iterateSyncCycle (test, projectIdsLeft, hasErrorOccured, start) {
     72function iterateSyncCycle (test, projectIdsLeft, projectIdsCount, hasErrorOccurred, start) {
    5273
    5374  // Error occured
    54   if (hasErrorOccured) {
     75  if (hasErrorOccurred) {
    5576    progressText.innerHTML = __('An unexpected <strong class="minicrm-woocommerce-sync-error">error occured</strong>, the sync was aborted. (Please check the Sync log).')
    5677    return
    57   }
    58 
    59   // Init
    60   var allCount = minicrmWoocommerceSyncData.projectIds.length
    61 
    62   /**
    63    * Init first iteration (with 1 argument). We clone the original project IDs
    64    * array instead of mutating it directly, so the user can run multiple cycles.
    65    */
    66   if (arguments.length === 1) {
    67     var projectIdsLeft = [...minicrmWoocommerceSyncData.projectIds]
    68     var hasErrorOccured = false
    69     var start = new Date
    70     setActiveState (true)
    7178  }
    7279
     
    7582    progressText.innerHTML = __(
    7683      'Finished syncing all (%s) projects. <strong class="minicrm-woocommerce-sync-success">No error</strong> occured, but complete success can only be verified from the Sync log.',
    77       allCount
     84        projectIdsCount
    7885    )
    7986    setActiveState (false)
     
    8289
    8390  // Sync next iteration of projects
    84   var processedCount = allCount - projectIdsLeft.length
    85   var percent = Math.floor (100 * processedCount / allCount)
     91  var processedCount = projectIdsCount - projectIdsLeft.length
     92  var percent = Math.floor (100 * processedCount / projectIdsCount)
    8693  var projectIds = projectIdsLeft.splice (0, PROJECTS_PER_ITERATION)
    8794  jQuery.ajax ({
     
    96103  })
    97104  .error (() => {
    98     hasErrorOccured = true
     105    hasErrorOccurred = true
    99106  })
    100107  .always (() => {
    101     iterateSyncCycle (test, projectIdsLeft, hasErrorOccured, start)
     108    iterateSyncCycle (test, projectIdsLeft, projectIdsCount, hasErrorOccurred, start)
    102109  })
    103110
    104111  // Calculate remaining seconds
    105112  var remainingSecs = minicrmWoocommerceSyncData.timeoutInSecs
    106   if (arguments.length) {
     113  if (processedCount > 0) {
    107114    var now = new Date
    108115    var elapsed = (now - start) / 1000
     
    150157// Add btn click event handlers
    151158jQuery (btnProd).bind ('click', () => {
    152   iterateSyncCycle (false)
     159  startSync(false)
    153160})
    154161jQuery (btnTest).bind ('click', () => {
    155   iterateSyncCycle (true)
     162  startSync(true)
    156163})
    157164
  • minicrm-woocommerce-sync/trunk/languages/minicrm-woocommerce-sync.pot

    r3102566 r3262157  
    44"Project-Id-Version: MiniCRM "
    55"WooCommerce Sync plugin "
    6 "v1.5.28\n"
     6"v1.7.0\n"
    77"POT-Creation-Date: 2022-05-30 "
    88"22:22+0200\n"
  • minicrm-woocommerce-sync/trunk/lib/AbstractXmlEndpoint.php

    r2849279 r3262157  
    8585    protected static function _verifySecret ()
    8686    {
    87         if (!get_transient ($_GET['secret'])) throw new \Exception ('Failed to validate secret.', 401);
     87        if (!Plugin::checkNonce($_GET['secret'])) throw new \Exception ('Failed to validate secret.', 401);
    8888    }
    8989}
  • minicrm-woocommerce-sync/trunk/lib/Integration.php

    r3102566 r3262157  
    9191     * @return int[] Project IDs to sync
    9292     */
    93     public static function getProjectIds ()
    94     {
     93    public static function getProjectIds()
     94    {
     95        // Try to get cached data first
     96        $cached_project_ids = get_transient('minicrm_project_ids_cache');
     97        if ($cached_project_ids !== false) {
     98            return $cached_project_ids;
     99        }
     100
    95101        $projectIds = [];
    96102        $filters = [
    97103            'post_type'      => 'shop_order',
    98104            'post_status'    => 'any',
    99             'posts_per_page' => 10,
    100             'paged'          => 1, // NOTE: Starts on 1, not 0
    101             'order'          => 'ASC',
     105            'posts_per_page' => 100,
    102106            'orderby'        => 'ID',
     107            'order'          => 'DESC',
    103108            'fields'         => 'ids',
     109            'no_found_rows'  => true
    104110        ];
    105         do {
    106             $query = new \WP_Query ($filters);
    107             $orderIds = $query->get_posts ();
    108             foreach ($orderIds as $orderId) {
    109                 $customerId = get_post_meta ($orderId, '_customer_user', true);
    110                 $customerId = (int) $customerId;
    111                 $projectId = Plugin::getOrderProjectId ($orderId, $customerId);
    112                 if (!in_array ($projectId, $projectIds)) {
    113                     $projectIds [] = $projectId;
    114                 }
     111
     112        $query = new \WP_Query($filters);
     113        $orderIds = $query->get_posts();
     114
     115        foreach ($orderIds as $orderId) {
     116            $customerId = (int) get_post_meta($orderId, '_customer_user', true);
     117            $projectId = Plugin::getOrderProjectId($orderId, $customerId);
     118            if (!in_array($projectId, $projectIds)) {
     119                $projectIds[] = $projectId;
    115120            }
    116             $filters ['paged'] ++;
    117         } while ($query->have_posts ());
     121        }
     122
     123        // Cache the results for 1 hour
     124        set_transient('minicrm_project_ids_cache', $projectIds, 1 * HOUR_IN_SECONDS);
     125
    118126        return $projectIds;
    119127    }
  • minicrm-woocommerce-sync/trunk/lib/Plugin.php

    r2849279 r3262157  
    7070        if (current_user_can ('manage_options')) {
    7171            $success = self::_syncProjects (
    72                 $_GET ['projects'],
     72                $_GET['projects'],
    7373                $_GET ['test'] === '1'
    7474            );
     
    8282            http_response_code (500);
    8383            exit (1);
     84        }
     85
     86        // Forbidden
     87        http_response_code (403);
     88        exit (2);
     89    }
     90
     91    public static function ajaxGetProjects() {
     92        if (current_user_can ('manage_options')) {
     93            $project_ids = Integration::getProjectIds();
     94
     95            $response = json_encode([
     96                'projects' => $project_ids
     97            ]);
     98            header('Content-Type: application/json; charset=utf8');
     99            echo $response;
     100            exit (0);
    84101        }
    85102
     
    344361                    $data = [
    345362                        'ajaxUrl'       => admin_url ('admin-ajax.php'),
    346                         'projectIds'    => Integration::getProjectIds (),
    347363                        'timeoutInSecs' => Feed::TIMEOUT_IN_SECS,
    348364                        'translations'  => [
     
    385401        );
    386402
     403        add_action (
     404            'wp_ajax_get_projects',
     405            self::_ignoreTypeErrors ([__CLASS__, 'ajaxGetProjects']),
     406            10,
     407            0
     408        );
     409
    387410        // Add "Settings" link to plugin list item
    388411        add_filter (
     
    556579
    557580        //generating access secret and saving it in memory
    558         $secret = bin2hex (random_bytes (16));
    559         set_transient ($secret, true, 60 * 60 * 6);
     581        $secret = self::generateNonce();
    560582
    561583        // Init feed URL
     
    596618        return true;
    597619    }
     620
     621    /**
     622     * Generate a nonce and store it in memory
     623     * @return string
     624     * @throws \Random\RandomException
     625     */
     626    public static function generateNonce (): string
     627    {
     628        $secret = bin2hex (random_bytes (16));
     629        set_transient ($secret, true, 60 * 60 * 6);
     630        return $secret;
     631    }
     632
     633    /**
     634     * Check if the given value is a valid nonce
     635     * @param string $value
     636     * @return bool
     637     */
     638    public static function checkNonce (string $value): bool
     639    {
     640        return get_transient($value) !== false;
     641    }
    598642}
  • minicrm-woocommerce-sync/trunk/minicrm-woocommerce-sync.php

    r3102566 r3262157  
    1010 * Requires PHP: 8.0
    1111 * Text Domain: minicrm-woocommerce-sync
    12  * Version: 1.5.28
     12 * Version: 1.7.0
    1313 * WC requires at least: 4.0.0
    1414 * WC tested up to: 7.2
  • minicrm-woocommerce-sync/trunk/readme.txt

    r3102566 r3262157  
    55Requires at least: 4.9
    66Requires PHP: 8.0
    7 Stable tag: 1.5.28
     7Stable tag: 1.7.0
    88Tested up to: 6.2
    99WC requires at least: 4.0.0
Note: See TracChangeset for help on using the changeset viewer.