ent ); } public static function getVariationsProgress() { $percent = 0; $totalItems = absint( self::getInfo( 'total_variations_for_indexing', Config::getIndexRole() ) ); $processed = absint( self::getInfo( 'variations_processed', Config::getIndexRole() ) ); if ( ! empty( $totalItems ) && is_numeric( $totalItems ) && ! empty( $processed ) && is_numeric( $processed ) ) { $percent = $processed * 100 / $totalItems; } return absint( $percent ); } public static function getTaxonomiesProgress() { $percent = 0; $totalItems = absint( self::getInfo( 'total_terms_for_indexing', Config::getIndexRole() ) ); $processed = absint( self::getInfo( 'terms_processed', Config::getIndexRole() ) ); if ( ! empty( $totalItems ) && is_numeric( $totalItems ) && ! empty( $processed ) && is_numeric( $processed ) ) { $percent = $processed * 100 / $totalItems; } return absint( $percent ); } public static function getProgressBarValue() { if ( self::getInfo( 'status', Config::getIndexRole() ) === 'completed' ) { return 100; } $percentR = self::getReadableProgress(); $percentS = self::getSearchableProgress(); $percentV = self::getVariationsProgress(); $percentT = self::getTaxonomiesProgress(); if ( self::canBuildVariationsIndex() && self::canBuildTaxonomyIndex() ) { $progress = $percentR * 0.4 + $percentS * 0.4 + $percentV * 0.1 + $percentT * 0.1; } elseif ( self::canBuildVariationsIndex() || self::canBuildTaxonomyIndex() ) { $progress = $percentR * 0.4 + $percentS * 0.4 + $percentV * 0.2 + $percentT * 0.2; } else { $progress = ( $percentR + $percentS ) / 2; } $progress = apply_filters( 'dgwt/wcas/indexer/process_status/progress', $progress, $percentR, $percentS, $percentV, $percentT ); return $progress > 100 ? 99 : $progress; } public static function renderIndexingStatus( $refreshStatus = true ) { if ( $refreshStatus ) { self::refreshStatus(); } $html = '
'; $html .= self::getIndexHeader(); $html .= self::getProcessStatus(); $html .= '
'; return $html; } public static function refreshStatus() { global $wpdb; $status = self::getInfo( 'status', Config::getIndexRole() ); $startTs = absint( self::getInfo( 'start_ts', Config::getIndexRole() ) ); $sStartTs = absint( self::getInfo( 'start_searchable_ts', Config::getIndexRole() ) ); $rStartTs = absint( self::getInfo( 'start_readable_ts', Config::getIndexRole() ) ); $taxStartTs = absint( self::getInfo( 'start_taxonomies_ts', Config::getIndexRole() ) ); $sEndTs = absint( self::getInfo( 'end_searchable_ts', Config::getIndexRole() ) ); $rEndTs = absint( self::getInfo( 'end_readable_ts', Config::getIndexRole() ) ); $taxEndTs = absint( self::getInfo( 'end_taxonomies_ts', Config::getIndexRole() ) ); switch ( $status ) { case 'cancellation': self::addInfo( 'status', 'not-exist' ); self::log( 'Canceling completed' ); break; case 'error': self::cancelBuildIndex(); break; } } public static function getIndexHeader( $indexRole = '' ) { if ( empty( $indexRole ) ) { $indexRole = Config::getIndexRole(); } $text = ''; $statusColor = ''; $statusText = ''; $status = self::getInfo( 'status', $indexRole ); $endTs = absint( self::getInfo( 'end_ts', $indexRole) ); $totalProducts = absint( self::getInfo( 'total_products_for_indexing', $indexRole ) ); $totalNonProducts = absint( self::getInfo( 'total_non_products_for_indexing', $indexRole ) ); $nonCriticalErrors = self::getInfo( 'non_critical_errors', $indexRole); $lastErrorCode = ''; $lastErrorMessage = ''; switch ( $status ) { case 'preparing': $text = __( 'Wait... Preparing indexing in progress', 'ajax-search-for-woocommerce' ); $statusText = __( 'This process will continue in the background. You can leave this page!', 'ajax-search-for-woocommerce' ); $statusColor = '#e6a51d'; break; case 'building': $text = __( 'Wait... Indexing in progress', 'ajax-search-for-woocommerce' ); $statusText = __( 'This process will continue in the background. You can leave this page!', 'ajax-search-for-woocommerce' ); $statusColor = '#e6a51d'; break; case 'cancellation': $text = __( 'Wait... The index build process is canceling', 'ajax-search-for-woocommerce' ); $statusText = __( 'Canceling...', 'ajax-search-for-woocommerce' ); $statusColor = '#7293b0'; break; case 'completed': $lastDate = ! empty( $endTs ) ? Helpers::localDate( $endTs ) : '-'; if ( empty( $nonCriticalErrors ) ) { $text = __( 'The search index was built successfully.', 'ajax-search-for-woocommerce' ); } else { $text = __( 'The search index was built successfully, but some non-critical errors occurred.', 'ajax-search-for-woocommerce' ); } $statusText = __( 'Completed. Works.', 'ajax-search-for-woocommerce' ); $statusColor = '#4caf50'; break; case 'error': $text = __( 'The search index could not be built.', 'ajax-search-for-woocommerce' ); $statusText = __( 'Errors', 'ajax-search-for-woocommerce' ); $statusColor = '#d75f5f'; list( $lastErrorCode, $lastErrorMessage ) = Logger::getLastEmergencyLog(); break; default: $text = __( 'The search index does not exist yet. Build it now.', 'ajax-search-for-woocommerce' ); $statusText = __( 'Not exist', 'ajax-search-for-woocommerce' ); $statusColor = '#aaaaaa'; break; } $actionButton = self::getIndexButton(); $isDetails = get_transient( self::DETAILS_DISPLAY_KEY ); $status = self::getInfo( 'status', $indexRole ); $oldIndexEndTime = Helpers::localDate( absint( self::getInfo( 'end_ts', 'main' ) ), 'Y-m-d H:i:s' ); $notices = array(); $infoLimitedEngine = '' . __( 'Search engine status:', 'ajax-search-for-woocommerce' ) . ' '; $infoLimitedEngine .= __( "Your search engine does not work optimally because the index hasn't been built yet.", 'ajax-search-for-woocommerce' ); $infoLimitedEngine .= ' ' . __( 'The best speed and all pro features will be available after the index has been built.', 'ajax-search-for-woocommerce' ); if ( Config::isParallelBuildingEnabled() && self::getInfo( 'status', 'tmp' ) !== 'completed' ) { if ( self::getInfo( 'status', 'main' ) === 'completed' ) { $notices['info'] = '' . __( 'Search engine status:', 'ajax-search-for-woocommerce' ) . ' '; $notices['info'] .= __( 'We have some good news!', 'ajax-search-for-woocommerce' ); if ( in_array( self::getInfo( 'status', 'tmp' ), array( 'preparing', 'building' ) ) ) { $notices['info'] .= ' ' . __( "Even though the current index is being built, it doesn't affect your search engine.", 'ajax-search-for-woocommerce' ); } else { $notices['info'] .= ' ' . __( "Even though the current index wasn't built, it doesn't affect your search engine.", 'ajax-search-for-woocommerce' ); } $notices['info'] .= ' ' . sprintf( __( "It works well based on the last properly built index from %s", 'ajax-search-for-woocommerce' ), $oldIndexEndTime ); } else { $notices['info'] = $infoLimitedEngine; } } if ( ! Config::isParallelBuildingEnabled() && self::getInfo( 'status', 'main' ) !== 'completed' ) { $notices['info'] = $infoLimitedEngine; } ob_start(); include DGWT_WCAS_DIR . 'partials/admin/indexer-notices.php'; include DGWT_WCAS_DIR . 'partials/admin/indexer-header.php'; $html = ob_get_contents(); ob_end_clean(); return $html; } public static function getIndexButton() { $status = self::getInfo( 'status', Config::getIndexRole()); if ( in_array( $status, array( 'building', 'preparing' ) ) ) { $html = ''; } elseif ( in_array( $status, array( 'completed' ) ) ) { $html = ''; } elseif ( in_array( $status, array( 'error' ) ) ) { $html = ''; } elseif ( in_array( $status, array( 'cancellation' ) ) ) { $html = ''; } else { $html = ''; } return $html; } /** * Check if readable products table exist * * @return bool */ public static function readableIndexExists( $indexRoleSuffix = '' ) { global $wpdb; return Helpers::isTableExists( $wpdb->dgwt_wcas_index . $indexRoleSuffix ); } /** * Check if readable taxonmies table exist * * @return bool */ public static function taxIndexExists( $indexRoleSuffix = '' ) { global $wpdb; return Helpers::isTableExists( $wpdb->dgwt_wcas_tax_index . $indexRoleSuffix ); } /** * Check if variations table exist * * @return bool */ public static function variationsIndexExists( $indexRoleSuffix = '' ) { global $wpdb; return Helpers::isTableExists( $wpdb->dgwt_wcas_var_index . $indexRoleSuffix ); } /** * Check if vendors table exist * * @return bool */ public static function vendorsIndexExists( $indexRoleSuffix = '' ) { global $wpdb; return Helpers::isTableExists( $wpdb->dgwt_wcas_ven_index . $indexRoleSuffix ); } /** * Check if searchable tables exist * * @param string $currentLang * @param string $source * * @return bool */ public static function searchableIndexExists( $currentLang = '', $indexRoleSuffix = '' ) { global $wpdb; $isShortInit = defined( 'SHORTINIT' ) && SHORTINIT; $wordlistExists = false; $doclistExists = false; $currentLang = Multilingual::isLangCode( $currentLang ) ? $currentLang : ''; $wpdb->hide_errors(); ob_start(); if ( ! empty( $currentLang ) || ( ! $isShortInit && Multilingual::isMultilingual() ) ) { $wordlistInstances = 0; $doclistInstances = 0; if ( ! empty( $currentLang ) ) { $langs = array( $currentLang ); } else { $langs = Multilingual::getLanguages(); } foreach ( $langs as $lang ) { $lang = str_replace( '-', '_', $lang ); $wordlistTable = $wpdb->dgwt_wcas_si_wordlist . '_' . $lang . $indexRoleSuffix; $doclistTable = $wpdb->dgwt_wcas_si_doclist . '_' . $lang . $indexRoleSuffix; if ( Helpers::isTableExists( $wordlistTable ) ) { $wordlistInstances ++; } if ( Helpers::isTableExists( $doclistTable ) ) { $doclistInstances ++; } } if ( $wordlistInstances === count( $langs ) ) { $wordlistExists = true; } if ( $doclistInstances === count( $langs ) ) { $doclistExists = true; } } else { $wordlistExists = Helpers::isTableExists( $wpdb->dgwt_wcas_si_wordlist . $indexRoleSuffix ); $doclistExists = Helpers::isTableExists( $wpdb->dgwt_wcas_si_doclist . $indexRoleSuffix ); } ob_end_clean(); return $wordlistExists && $doclistExists; } /** * Check if cache table exists * * @param string $lang Language * @param string $postType Post type. Leave empty to check 'product' table * * @return bool */ public static function searchableCacheExists( $lang = '', $postType = '' ) { global $wpdb; $lang = Multilingual::isLangCode( $lang ) ? $lang : ''; $lang = str_replace( '-', '_', $lang ); $cacheTable = $wpdb->dgwt_wcas_si_cache; if ( ! empty( $postType ) ) { $cacheTable .= '_' . $postType; } if ( ! empty( $lang ) ) { $cacheTable .= '_' . $lang; } return Helpers::isTableExists( $cacheTable ); } public static function getReadableTotalIndexed() { global $wpdb; $count = 0; if ( self::readableIndexExists( Config::getIndexRoleSuffix() ) ) { $r = $wpdb->get_var( 'SELECT COUNT(DISTINCT post_id) FROM ' . $wpdb->dgwt_wcas_index . Config::getIndexRoleSuffix() ); if ( ! empty( $r ) && is_numeric( $r ) ) { $count = absint( $r ); } } return $count; } public static function getProcessStatus() { $info = array(); foreach ( self::getIndexInfoStruct() as $key => $field ) { $offset = get_option( 'gmt_offset' ); $value = self::getInfo( $key, Config::getIndexRole() ); if ( strpos( $key, '_ts' ) !== false && ! empty( $value ) && ! empty( $offset ) ) { $info[ $key ] = absint( $value ) + ( $offset * 3600 ); } else { $info[ $key ] = $value; } } $progressPercent = self::getProgressBarValue(); $logs = self::getLogs( Config::getIndexRole() ); $isDetails = get_transient( self::DETAILS_DISPLAY_KEY ); $canBuildTaxonomyIndex = self::canBuildTaxonomyIndex(); $canBuildVendorsIndex = self::canBuildVendorsIndex(); ob_start(); include DGWT_WCAS_DIR . 'partials/admin/indexer-body.php'; $html = ob_get_contents(); ob_end_clean(); return $html; } /** * Check if can index taxonomies * * @return bool */ public static function canBuildTaxonomyIndex() { return ! empty( DGWT_WCAS()->tntsearchMySql->taxonomies->getActiveTaxonomies( 'search_direct' ) ); } /** * Check if can index vendors * * @return bool */ public static function canBuildVendorsIndex() { return apply_filters( 'dgwt/wcas/search/vendors', false ); } /** * Check if can build variations index * * @return bool */ public static function canBuildVariationsIndex() { $canBuild = false; if ( ! empty( $_POST['dgwt_wcas_settings'] ) ) { $settings = $_POST['dgwt_wcas_settings']; if ( ! empty( $settings['search_in_product_sku'] ) && $settings['search_in_product_sku'] === 'on' ) { $canBuild = true; } } if ( ! $canBuild ) { $canBuild = DGWT_WCAS()->settings->getOption( 'search_in_product_sku' ) === 'on'; } return $canBuild; } /** * Check if index is completed and valid * * @param string $lang * * @return bool */ public static function isIndexValid( $lang = '', $indexRole = 'main' ) { $valid = false; $indexRoleSuffix = $indexRole === 'main' ? '' : '_tmp'; if ( self::getInfo( 'status', $indexRole ) === 'completed' && self::searchableIndexExists( $lang, $indexRoleSuffix ) && self::readableIndexExists( $indexRoleSuffix ) ) { $valid = true; } return $valid; } /** * Wipe all data of deprecated SQLite driver * * @return void */ public static function wipeSQLiteAfterEffects() { $uploadDir = wp_upload_dir(); if ( ! empty( $uploadDir['basedir'] ) ) { $directory = $uploadDir['basedir'] . '/wcas-search'; $file = $uploadDir['basedir'] . '/wcas-search/products.index'; if ( file_exists( $file ) && is_writable( $file ) ) { @unlink( $file ); } if ( file_exists( $directory ) && is_writable( $directory ) ) { @rmdir( $directory ); } } } /** * Complete the search index * * @return void */ public static function maybeMarkAsCompleted() { $status = self::getInfo( 'status', Config::getIndexRole() ); $sEndTs = absint( self::getInfo( 'end_searchable_ts', Config::getIndexRole() ) ); $rEndTs = absint( self::getInfo( 'end_readable_ts', Config::getIndexRole() ) ); $tEndTs = self::canBuildTaxonomyIndex() ? absint( self::getInfo( 'end_taxonomies_ts', Config::getIndexRole() ) ) : 1; $vEndTs = self::canBuildVariationsIndex() ? absint( self::getInfo( 'end_variation_ts', Config::getIndexRole() ) ) : 1; if ( 'building' === $status && ! empty( $sEndTs ) && ! empty( $rEndTs ) && ! empty( $vEndTs ) && ! empty( $tEndTs ) ) { self::addInfo( 'status', 'completed' ); self::addInfo( 'end_ts', time() ); self::log( 'Indexing completed' ); self::copyTmpIndexToMain(); self::flushOptionsCache(); do_action( 'dgwt/wcas/indexer/status/completed' ); } } public static function copyTmpIndexToMain() { global $wpdb; // Break early if parallel index building is disabled. if ( ! Config::isParallelBuildingEnabled() ) { Builder::log( '[Indexer] Skipping copying of "tmp" tables - parallel building is disabled', 'debug', 'file' ); return; } if ( ! Builder::isIndexValid( '', 'tmp' ) ) { Builder::log( '[Indexer] Skipping copying of "tmp" tables - "tmp" index is invalid', 'debug', 'file' ); return; } $tables = Utils::getAllPluginTables(); foreach ( $tables as $table ) { if ( strpos( $table, 'dgwt_wcas_stats' ) ) { continue; } // Remove all not "main" index tables (even those that don't have "tmp" version). if ( strpos( $table, '_tmp' ) === false ) { $wpdb->query( "DROP TABLE IF EXISTS $table" ); } if ( strpos( $table, '_tmp' ) !== false ) { $mainTable = str_replace( '_tmp', '', $table ); // Make sure the table at index "main" does not exist. $wpdb->query( "DROP TABLE IF EXISTS $mainTable" ); $wpdb->query( "RENAME TABLE $table TO $mainTable" ); } } foreach ( self::getIndexInfoStruct() as $key => $value ) { $value = get_option( self::LAST_BUILD_OPTION_KEY . '_' . $key . '_tmp', $value ); delete_option( self::LAST_BUILD_OPTION_KEY . '_' . $key ); /* * Make sure the options are copied. * Sometimes it happened that some options were not copied, and we have to be sure that everything went OK. */ $count = 0; do { $count ++; if ( $count > 1 ) { usleep( 500000 ); } if ( $count === 1 ) { $addResult = add_option( self::LAST_BUILD_OPTION_KEY . '_' . $key, $value, '', 'no' ); $savedValue = get_option( self::LAST_BUILD_OPTION_KEY . '_' . $key ); $continue = ! $addResult || $value !== $savedValue; } else { delete_option( self::LAST_BUILD_OPTION_KEY . '_' . $key ); $wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->options (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, 'no')", self::LAST_BUILD_OPTION_KEY . '_' . $key, maybe_serialize( $value ) ) ); $continue = false; } if ( $key === 'logs' ) { break; } } while ( $continue && $count < 3 ); } } /** * Remove all options created by this plugin * * @param bool $networkScope delete tables in whole network * * @return void */ public static function deleteIndexOptions( $networkScope = false ) { global $wpdb; $prefix = $wpdb->prefix; if ( is_multisite() && $networkScope ) { $prefix = $wpdb->base_prefix; } $lastBuildOptionKey = $wpdb->esc_like( self::LAST_BUILD_OPTION_KEY ) . '%'; $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->options WHERE option_name LIKE %s", $lastBuildOptionKey ) ); delete_transient( self::DETAILS_DISPLAY_KEY ); if ( is_multisite() && $networkScope ) { foreach ( get_sites() as $site ) { if ( is_numeric( $site->blog_id ) ) { $blogID = $site->blog_id == 1 ? '' : $site->blog_id . '_'; $table = $prefix . $blogID . 'options'; $wpdb->query( $wpdb->prepare( "DELETE FROM $table WHERE option_name LIKE %s", $lastBuildOptionKey ) ); $wpdb->delete( $table, array( 'option_name' => '_transient_timeout_' . self::DETAILS_DISPLAY_KEY ) ); $wpdb->delete( $table, array( 'option_name' => '_transient_' . self::DETAILS_DISPLAY_KEY ) ); } } } } /** * Remove all database tables created by this plugin * * @param bool $networkScope delete tables in whole network * * @return void */ public static function deleteDatabaseTables( $networkScope = false ) { global $wpdb; // DB tables $tables = Utils::getAllPluginTables( $networkScope ); if ( ! empty( $tables ) ) { foreach ( $tables as $table ) { $wpdb->query( "DROP TABLE IF EXISTS $table" ); } } } /** * Removal of planned actions that will update products in the index */ public static function wipeActionScheduler() { $queue = Utils::getQueue(); if ( empty( $queue ) ) { return; } try { $queue->cancel_all( 'dgwt/wcas/tnt/background_product_update' ); } catch ( Exception $e ) { } } /** * Dispatch building variation index */ public static function maybeDispatchVariationAsyncProcess() { if ( ! self::canBuildVariationsIndex() ) { return; } $status = self::getInfo( 'status', Config::getIndexRole() ); $sEndTs = absint( self::getInfo( 'end_searchable_ts', Config::getIndexRole() ) ); $rEndTs = absint( self::getInfo( 'end_readable_ts', Config::getIndexRole() ) ); if ( ( Config::isIndexerMode( 'async' ) && $status === 'building' && ! empty( $rEndTs ) ) || ( Config::isIndexerMode( 'sync' ) && $status === 'building' && ! empty( $sEndTs ) && ! empty( $rEndTs ) ) || ( Config::isIndexerMode( 'direct' ) && $status === 'building' ) ) { self::addInfo( 'start_variation_ts', time() ); // Reset end time because this process may end several times self::addInfo( 'end_variation_ts', 0 ); self::log( '[Variation index] Building...' ); DGWT_WCAS()->tntsearchMySql->asynchBuildIndexV->maybe_dispatch(); } } /** * Dispatch building taxonomies index */ public static function maybeDispatchTaxonomyAsyncProcess() { if ( ! self::canBuildTaxonomyIndex() ) { self::maybeDispatchVariationAsyncProcess(); return; } $status = self::getInfo( 'status', Config::getIndexRole() ); $rEndTs = absint( self::getInfo( 'end_readable_ts', Config::getIndexRole() ) ); if ( ( Config::isIndexerMode( 'async' ) && $status === 'building' && ! empty( $rEndTs ) ) || ( Config::isIndexerMode( 'sync' ) && $status === 'building' && ! empty( $rEndTs ) ) || ( Config::isIndexerMode( 'direct' ) && $status === 'building' ) ) { RequestT::handle(); } } /** * Check if the indexer working too long without any action * * @return bool */ public static function isIndexerWorkingTooLong( $forceMaxNoActionTime = 0 ) { $status = Builder::getInfo( 'status', Config::getIndexRole() ); // Return early if indexer is not working if ( ! in_array( $status, array( 'building', 'preparing' ) ) ) { return false; } $lastActionTs = absint( Builder::getInfo( 'last_action_ts', Config::getIndexRole() ) ); // Return early if the indexer info hasn't been created yet if ( empty( $lastActionTs ) ) { return false; } $diff = time() - $lastActionTs; $maxNoActionTime = defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ? 61 * MINUTE_IN_SECONDS : 16 * MINUTE_IN_SECONDS; /** * Filters maximum no action time of indexer. * * @param int $maxNoActionTime Max time in seconds. 16 min if WP-Cron is enabled or 61 min if not */ $maxNoActionTime = apply_filters( 'dgwt/wcas/indexer/max_no_action_time', $maxNoActionTime ); if ( $forceMaxNoActionTime > 0 ) { $maxNoActionTime = $forceMaxNoActionTime; } return in_array( $status, array( 'building', 'preparing' ) ) && $diff >= $maxNoActionTime; } }