mirror of
https://github.com/SuiteCRM/SuiteCRM-Core.git
synced 2025-08-29 08:17:18 +08:00
81ce7933fd SuiteCRM 7.13.0 Release 595d2bd92b Fix saveDropDown getting called statically a70c5d1b99 Fix message deletion after auto import f57b5ede02 Fix Inbound Email allow_outbound_group_usage filtering 9d38016f59 Remove external_oauth_providers config d5b4f0025c Remove provider field from ExternalOAuthConnection d457827c7d Change ExternalOAuthProvider to use open visibility by default for group records 3a51437d3a Add null check b49d6b79a0 Fix Inbound email tests 277f2c91cb Set default on inbound emails 261dae81c1 Add group to OutboundEmailAccounts menu 3e9dbdd5de Fix ExternalOAuthConnection list view pagination and checkboxes 36cbb6a90c Fix ExternalOAuthProvider list view pagination and checkboxes fe5f0a10d6 Fix OutboundEmailAccounts list view pagination and checkboxes b9217a36e2 Fix InboundEmail list view pagination and checkboxes 83bd0024a6 Allow selecting group InboundEmails in folder management f6a9111b25 Fix inbound email relationship definition 07b3110f8a Filter listview email displayed accounts according to preferences 6c49df527a Remove code that auto-selects a group email none is selected 243a0276af Fix preferences mail folder management dropdown e7838f0bd4 Fix owner field definition in OutboundEmailAccounts db9a52a27d Fix bounce mailbox type not being properly set 14d43e1efa Fix compose emails not sending f9e3677db8 Add optional connection string to InboundEmail module cef8b2bdb6 Allow setting placeholder for varchar on editview b2d669a022 Fix group_id not being saved properly on InboundEmail 8d25cc19d8 Fix: From not populating fae3d7b629 Fix folders not clearing subscription a8e9eba917 Fix signatures not being editable after being created 1762704a28 Fix menu label in ExternalOAuthConnections module e97ddb6af0 Fix inbound_emails_external_oauth_connections relationship 2cbebdd5a9 Replace External Oauth Provider sugar_config with module 89f2cee005 Add admin menu entry for ExternalOAuthProviders dbe91ffe26 Add External providers to ExternalOAuthConnector menu 63b944e033 Add ExternalOAuthProvider module 214f0d9008 Rename ExternalOAuthProvider to ExternalOAuthProviderConnector 972356fa90 Add stringmap field c701e4c6d5 Add json_decode smarty modifier 49024376be Update Travis build to remove php 7.3 test runs c23f0e57ac Update Minimum php version to php 7.4 b5914d782e Fix #9670 - Disabling the user profile option about notification of assignments does not work c2f260e477 Clear caches used by Inline Edition 89de5b620f Fix #99568: Ignore int length when comparing vardefs in newer MySQL versions fb50e2250e ElasticSearch Indexing batch error handling 32af678e4f Fix #9473 - Missing item "Survey" in campainglog_activity_type_dom a12f4f37be Fix #9638 - Elasticsearch issue with accented characters d85d72996d Fix #9499 - Add View Survey Responses Menu item dcd3ea1091 Fix #9574 - Update method to static for module renaming c56a5b2188 Fix #9646 - Display TinyMCE in step 4 of the campaigns form wizard d99439aca1 Fix #9717 - Security Suite Record Group selector doesn't appear when duplicating records ea0b42469a Add new ACL access logic hooks be0dec47dc Refactor module access query for extendability 8361cceb60 fix #9802 - Diagnostic checkboxes 44e4f47cca SuiteCRM 7.13.0-beta Release 0d6fef782e Fix #9839 - Make Inbound Email not auditable c0b93a5d2a Fix #9839 - Align Inbound and Outbound email menu labels 3883c2cb7e Fix #9839 - Inbound email assignment fields save and detail display 0a4fbfa2a9 Fix #9839 - Inbound email filters not displaying 6fefdd79a0 Fix #9839 - OutboundEmailAccounts list filtering 3dcab78053 Fix #9839 - Hide sort fields in search modal if none is sortable 95d099d3b4 Fix #9839 - Always sort emails by date received aff7965abd Fix #9839 - Add showing sort direction when field is not manually sortable e3f7d02a65 Fix #9839 - Use previously selected email mailbox when using the navigation links 01c96bf15c Fix #9839 - Add Imap2Handler to use imap2 lib d8dee51d94 Fix #9839 - Move email list retrieval from InboundEmail to ImapHandler f798b9af4a Fix #9839 - Update InboundEmail calls to mailparser to send 2nd argument 68a8fa97dd Fix #9839 - Move stream validity check to ImapHandlers fb4f1c81ec Fix #9839 - Fix InboundEmail pagination totals dc26951a35 Fix #9839 - Use previously selected email mailbox when using the navigation links cca80e945b Fix #9839 - Move case macro input to Case module settings admin menu 0fb1075aa2 Fix #9839 - Fix undefined error in listview displayEmptyDataMessages 990e98e4bc Fix #9839 - Add support to test oauth connection in InboundEmail 7259c9ce79 Fix #9839 - Allow refreshing ExternalOAuthConnection tokens 49c5c0ee09 Fix #9839 - Make ExternalOAuthConnection sensitive fields db_encrypted 17bbeb3683 Fix #9839 - Allow admins to list Group and personal ExternalOAuthConnection 0f559a6223 Fix #9839 - Allow encrypting fields on db by setting db_encrypted 471792d75f Fix #9839 - Apply acl and group check filtering to OutboundEmailAccounts 093f08f27b Fix #9839 - Apply acl and group check filtering to InboundEmail decdd27b23 Fix #9839 - Apply acl and group check filtering to ExternalOAuthConnection 584e40cfb3 Fix #9839 - Add user acl group action check 07c5b9f021 Fix #9839 - Show no-data message on empty OutboundEmailAccounts listview b857e4feab Fix #9839 - Show no-data message on empty ExternalOAuthConnection listview 9b6a7c4fcf Fix #9839 - Validate required fields on InboundEmail folder selection 0755e4bc7e Fix #9839 - Mark fields required when changing authType in InboundEmail 55123f4d70 Fix #9839 - Show no-data message on empty InboundEmail listview 059d112349 Fix #9839 - Fix InboundEmail save a656abd069 Fix #9839 - Make getUserRoleNames a static method ae49f130a9 Fix #9839 - Add is-value-set data to password field 2964fcbebc Fix #9839 - Add option to disable listview empty data messages a5794343cb Fix #9839 - Add ExternalOAuthConnection link to admin menu 215413931c Fix #9839 - Align mail related menu entries ee9e98741d Fix #9839 - Always keep write-only fields in OutboundEmailAccounts 4e0551e9f0 Fix #9839 - Disable massupdate and export in OutboundEmailAccounts bulk actions bbf351ee5e Fix #9839 - Disable massupdate and export in InboundEmail bulkactions 6871295c66 Fix #9839 - Allow selecting auth type in InboundEmail module 9befcd0ae6 Fix #9839 - Add ExternalOAuthConnection entrypoints 2cee6f1d67 Fix #9839 - Add ExternalOAuthConnection module 70025d5b66 Fix #9839 - Add write-only display option to text fields 25e2443850 Fix #9839 - Add write-only display option to varchar fields 6be8a334b1 Fix #9839 - Allow creating personal outbound email accounts 8bff1fb237 Fix #9839 - Align Outbound email accounts views with Inbound e396b7373c Fix #9839 - Allow admin to create personal inbound accounts for users 284d0eca76 Fix #9839 - Align inbound email and outbound email list views 186d8e41e4 Fix #9839 - Add Security Groups subpanel to Outbound email accounts c07f43decb Fix #9839 - Add Security Groups subpanel to Inbound email accounts 87c9eee413 Fix #9839 - Add access checks to personal outbound email accounts 2f76e6a5f5 Fix #9839 - Add access checks to personal inbound email accounts 88adc8135b Fix #9839 - Remove email account configuration from User Settings 33feb0b1c2 Fix #9839 - Allow setting personal InboundEmail signatures 4cb0fd99aa Fix #9839 - Allow setting personal InboundEmail as default b8cc31d8dd Fix #9839 - Add security groups to OutboundEmailAccounts 70a0daba51 Fix #9839 - Tidy OutboundEmailAccounts view definitions ca171a4460 Fix #9839 - Remove email_provider_chooser from OutboundEmailAccounts f8a6105618 Fix #9839 - Add menu definition to OutboundEmailAccounts 7d6cfd6c6c Fix #9839 - Load InboundEmail stored_options into fields on load f18ec84b47 Fix #9839 - Adjust InboundEmail save to use new fields 54bfb4f72c Fix #9839 - Remove InboundEmail legacy custom views 69d008671e Fix #9839 - Add new menu entries to InboundEmail d01a196f3b Fix #9839 - Add js code for inboundEmail 701498d007 Fix #9839 - Add standard view definitions to InboundEmail b5870531ba Fix #9839 - Add fields for stored_options in InboundEmail 8c57b07591 Fix #9839 - Add inbound and outbound email menu links to Users module a8bc647662 Fix #9839 - Add combinescripts smarty plugin e4db0fbfd4 Fix #9839 - Add writeonly display mode for password fields 1cc85c2dbf Fix #9839 - Add readonly display mode for enum fields git-subtree-dir: public/legacy git-subtree-split: 81ce7933fd9cecc378154ed4eac7eaab5ec1f139
590 lines
18 KiB
PHP
590 lines
18 KiB
PHP
<?php
|
|
/**
|
|
* SugarCRM Community Edition is a customer relationship management program developed by
|
|
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
|
|
*
|
|
* SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
|
|
* Copyright (C) 2011 - 2021 SalesAgility Ltd.
|
|
*
|
|
* This program is free software; you can redistribute it and/or modify it under
|
|
* the terms of the GNU Affero General Public License version 3 as published by the
|
|
* Free Software Foundation with the addition of the following permission added
|
|
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
|
|
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
|
|
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
|
|
*
|
|
* This program is distributed in the hope that it will be useful, but WITHOUT
|
|
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
|
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
|
* details.
|
|
*
|
|
* You should have received a copy of the GNU Affero General Public License along with
|
|
* this program; if not, see http://www.gnu.org/licenses or write to the Free
|
|
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
|
* 02110-1301 USA.
|
|
*
|
|
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
|
|
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
|
|
*
|
|
* The interactive user interfaces in modified source and object code versions
|
|
* of this program must display Appropriate Legal Notices, as required under
|
|
* Section 5 of the GNU Affero General Public License version 3.
|
|
*
|
|
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
|
* these Appropriate Legal Notices must retain the display of the "Powered by
|
|
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
|
|
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
|
|
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
|
|
*/
|
|
|
|
namespace SuiteCRM\Search\ElasticSearch;
|
|
|
|
if (!defined('sugarEntry') || !sugarEntry) {
|
|
die('Not A Valid Entry Point');
|
|
}
|
|
|
|
use Carbon\Carbon;
|
|
use Elasticsearch\Client;
|
|
use Elasticsearch\Common\Exceptions\Missing404Exception;
|
|
use Exception;
|
|
use JsonSchema\Exception\RuntimeException;
|
|
use LoggerManager;
|
|
use Monolog\Logger;
|
|
use SugarBean;
|
|
use SuiteCRM\Search\Index\AbstractIndexer;
|
|
use SuiteCRM\Search\Index\Documentify\AbstractDocumentifier;
|
|
use SuiteCRM\Search\Index\Documentify\SearchDefsDocumentifier;
|
|
use SuiteCRM\Search\Index\IndexingLockFileTrait;
|
|
use SuiteCRM\Search\Index\IndexingSchedulerTrait;
|
|
use SuiteCRM\Search\Index\IndexingStatisticsTrait;
|
|
|
|
/**
|
|
* Class ElasticSearchIndexer takes care of creating a search index for the database.
|
|
*/
|
|
class ElasticSearchIndexer extends AbstractIndexer
|
|
{
|
|
use IndexingStatisticsTrait;
|
|
use IndexingLockFileTrait;
|
|
use IndexingSchedulerTrait;
|
|
|
|
/** @var string The name of the Elasticsearch index to use. */
|
|
private $index;
|
|
/** @var Client */
|
|
private $client;
|
|
/** @var int the size of the batch to be sent to the Elasticsearch while batch indexing */
|
|
private $batchSize = 1000;
|
|
/** @var Carbon|false the timestamp of the last indexing. false if unknown */
|
|
private $lastRunTimestamp = false;
|
|
|
|
/**
|
|
* ElasticSearchIndexer constructor.
|
|
*
|
|
* @param Client|null $client
|
|
*/
|
|
public function __construct(Client $client = null)
|
|
{
|
|
parent::__construct();
|
|
|
|
$this->client = $client ?? ElasticSearchClientBuilder::getClient();
|
|
}
|
|
|
|
/**
|
|
* Returns whether the Elasticsearch is enabled by user configuration or not.
|
|
*
|
|
* @return bool
|
|
*/
|
|
public static function isEnabled(): ?bool
|
|
{
|
|
/** @noinspection PhpVariableNamingConventionInspection */
|
|
global $sugar_config;
|
|
|
|
try {
|
|
return !empty($sugar_config['search']['ElasticSearch']['enabled']);
|
|
} catch (Exception $exception) {
|
|
LoggerManager::getLogger()->fatal("Failed to retrieve ElasticSearch options");
|
|
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/** @inheritdoc */
|
|
public function index()
|
|
{
|
|
$this->logger->info('Starting indexing procedures');
|
|
|
|
$this->resetCounts();
|
|
|
|
$this->logger->debug('Indexing is performed using ' . $this->getDocumentifierName());
|
|
|
|
if ($this->differentialIndexing) {
|
|
$this->lastRunTimestamp = $this->readLockFile();
|
|
}
|
|
|
|
$modules = $this->getModulesToIndex();
|
|
$start = microtime(true);
|
|
|
|
if ($this->differentialIndexing()) {
|
|
$this->logger->debug('A differential indexing will be performed');
|
|
} else {
|
|
$this->logger->debug('A full indexing will be performed');
|
|
|
|
foreach ($modules as $module) {
|
|
try {
|
|
$lowercaseModule = strtolower($module);
|
|
$this->removeIndex($lowercaseModule);
|
|
$this->createIndex($lowercaseModule);
|
|
} catch (Exception $exception) {
|
|
$message = "Failed to create index $module! Exception details follow";
|
|
$this->logger->error($message);
|
|
$this->logger->error($exception);
|
|
}
|
|
}
|
|
}
|
|
|
|
foreach ($modules as $module) {
|
|
try {
|
|
$this->indexModule($module);
|
|
} catch (Exception $exception) {
|
|
$message = "Failed to index module $module! Exception details follow";
|
|
$this->logger->error($message);
|
|
$this->logger->error($exception);
|
|
}
|
|
}
|
|
|
|
$end = microtime(true);
|
|
|
|
if ($this->differentialIndexing) {
|
|
$this->writeLockFile();
|
|
}
|
|
|
|
$this->statistics($end, $start);
|
|
|
|
$this->logger->info("Indexing complete");
|
|
}
|
|
|
|
/**
|
|
* @param string $index
|
|
*/
|
|
public function removeIndex(string $index): void
|
|
{
|
|
$params = ['index' => $index];
|
|
$params['client'] = ['ignore' => [404]];
|
|
|
|
$this->client->indices()->delete($params);
|
|
|
|
$this->logger->debug("Removed index '$index'");
|
|
}
|
|
|
|
/**
|
|
* Creates a new index in the Elasticsearch server.
|
|
*
|
|
* The optional $body can be used to set up the index settings, mappings, etc.
|
|
*
|
|
* @param string $index name of the index
|
|
* @param array|null $body options of the index
|
|
*/
|
|
public function createIndex(string $index, array $body = null): void
|
|
{
|
|
$params = ['index' => $index];
|
|
|
|
if (!empty($body) && is_array($body)) {
|
|
$params['body'] = $body;
|
|
}
|
|
|
|
$this->client->indices()->create($params);
|
|
|
|
$this->logger->debug("Created new index '$index'");
|
|
}
|
|
|
|
/** @inheritdoc */
|
|
public function indexModule($module)
|
|
{
|
|
$isDifferential = $this->differentialIndexing();
|
|
$dataPuller = new ElasticSearchModuleDataPuller($module, $isDifferential, $this->logger);
|
|
|
|
$this->buildWhereClause($dataPuller, $isDifferential, $module);
|
|
|
|
$this->logger->debug(sprintf('Indexing module %s...', $module));
|
|
|
|
try {
|
|
$beanTime = Carbon::now()->toDateTimeString();
|
|
|
|
while ($beans = $dataPuller->pullNextBatch()) {
|
|
$this->indexBeans($module, $beans);
|
|
}
|
|
$this->logger->debug(sprintf('Finished %s. Processed %d Records', $module, $dataPuller->recordsPulled));
|
|
|
|
} catch (RuntimeException $exception) {
|
|
$this->logger->error("Failed to index module $module");
|
|
$this->logger->error($exception);
|
|
|
|
return;
|
|
}
|
|
|
|
if ($dataPuller->recordsPulled === 0) {
|
|
if (!$isDifferential) {
|
|
$this->logger->notice(sprintf('Skipped %s because $beans was null. The table is probably empty',
|
|
$module));
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
$this->putMeta($module, [
|
|
'last_index' => $beanTime,
|
|
'module_name' => $module
|
|
]);
|
|
$this->indexedModulesCount++;
|
|
}
|
|
|
|
/**
|
|
* For differential runs, attempt to pull the Last Index time and set on dataPuller
|
|
*
|
|
* @param ElasticSearchModuleDataPuller $dataPuller
|
|
* @param bool $isDifferential
|
|
* @param string $module
|
|
* @return void
|
|
*/
|
|
protected function buildWhereClause($dataPuller, $isDifferential, $module): void
|
|
{
|
|
if ($isDifferential) {
|
|
try {
|
|
$datetime = $this->getModuleLastIndexed($module);
|
|
$dataPuller->setLastIndexTime($datetime)->setShowDeleted(-1);
|
|
} catch (Exception $exception) {
|
|
$this->logger->notice("Time metadata not found for $module, performing full index for this module");
|
|
$dataPuller->setDifferential(false);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** @inheritdoc */
|
|
public function indexBeans($module, array $beans)
|
|
{
|
|
$oldCount = $this->indexedRecordsCount;
|
|
$oldRemCount = $this->removedRecordsCount;
|
|
$this->indexBatch($module, $beans);
|
|
$diff = $this->indexedRecordsCount - $oldCount;
|
|
$remDiff = $this->removedRecordsCount - $oldRemCount;
|
|
$total = count($beans) - $remDiff;
|
|
$type = $total === $diff ? Logger::DEBUG : Logger::WARNING;
|
|
$this->logger->log($type, sprintf('Indexed %d', $diff));
|
|
}
|
|
|
|
/** Removes all the indexes from Elasticsearch, effectively nuking all data. */
|
|
public function removeAllIndices(): void
|
|
{
|
|
$this->logger->debug("Deleting all indices");
|
|
try {
|
|
$this->client->indices()->delete(['index' => '_all']);
|
|
} /** @noinspection PhpRedundantCatchClauseInspection */
|
|
catch (Missing404Exception $ignore) {
|
|
// Index not there, not big deal since we meant to delete it anyway.
|
|
$this->logger->warn('Index not found, no index has been deleted.');
|
|
}
|
|
}
|
|
|
|
/** @inheritdoc */
|
|
public function indexBean(SugarBean $bean)
|
|
{
|
|
$this->logger->debug("Indexing {$bean->module_name}($bean->name)");
|
|
|
|
$args = $this->makeIndexParamsFromBean($bean);
|
|
|
|
$this->client->index($args);
|
|
}
|
|
|
|
/** @inheritdoc */
|
|
public function removeBean(SugarBean $bean)
|
|
{
|
|
$this->logger->debug("Removing {$bean->module_name}($bean->name)");
|
|
|
|
$args = $this->makeParamsHeaderFromBean($bean);
|
|
$this->client->delete($args);
|
|
}
|
|
|
|
/**
|
|
* @inheritdoc
|
|
*
|
|
* @param bool $ignore404 deleting something that is not there won't throw an error
|
|
*/
|
|
public function removeBeans(array $beans, $ignore404 = true)
|
|
{
|
|
$params = [];
|
|
|
|
if ($ignore404) {
|
|
$params['client']['ignore'] = [404];
|
|
}
|
|
|
|
foreach ($beans as $bean) {
|
|
$params['body'][] = ['delete' => $this->makeParamsHeaderFromBean($bean)];
|
|
}
|
|
|
|
$this->sendBatch($params);
|
|
}
|
|
|
|
/**
|
|
* Attempts to contact the Elasticsearch server and perform a simple request.
|
|
*
|
|
* Returns `false` in case of failure or the time it took to perform the operation in microseconds.
|
|
*
|
|
* @return int|false
|
|
*/
|
|
public function ping()
|
|
{
|
|
$start = Carbon::now()->micro;
|
|
$status = $this->client->ping();
|
|
$elapsed = Carbon::now()->micro - $start;
|
|
|
|
if ($status === false) {
|
|
$this->logger->error("Failed to ping server");
|
|
|
|
return false;
|
|
}
|
|
|
|
$this->logger->debug("Ping performed in $elapsed µs");
|
|
|
|
return $elapsed;
|
|
}
|
|
|
|
/**
|
|
* Writes the metadata fields for one index.
|
|
*
|
|
* @param string $module name of the module
|
|
* @param array $meta an associative array with the fields to populate
|
|
*/
|
|
public function putMeta(string $module, array $meta): void
|
|
{
|
|
$params = [
|
|
'index' => strtolower($module),
|
|
'body' => ['_meta' => $meta],
|
|
'ignore_unavailable' => true
|
|
];
|
|
|
|
$this->client->indices()->putMapping($params);
|
|
}
|
|
|
|
/**
|
|
* Returns the metadata fields for one index.
|
|
*
|
|
* @param string $module name of the module
|
|
*
|
|
* @return array an associative array with the metadata
|
|
*/
|
|
public function getMeta(string $module): ?array
|
|
{
|
|
$lowercaseModule = strtolower($module);
|
|
$params = ['index' => $lowercaseModule];
|
|
$results = $this->client->indices()->getMapping($params);
|
|
|
|
if (!isset($results[$lowercaseModule])) {
|
|
return null;
|
|
}
|
|
|
|
return $results[$lowercaseModule]['mappings']['_meta'];
|
|
}
|
|
|
|
/**
|
|
* @return int
|
|
*/
|
|
public function getBatchSize(): int
|
|
{
|
|
return $this->batchSize;
|
|
}
|
|
|
|
/**
|
|
* @param int $batchSize
|
|
*/
|
|
public function setBatchSize(int $batchSize): void
|
|
{
|
|
$this->batchSize = $batchSize;
|
|
}
|
|
|
|
/** @return string */
|
|
public function getIndex(): string
|
|
{
|
|
return $this->index;
|
|
}
|
|
|
|
/**
|
|
* Sets the name of the Elasticsearch index to send requests to.
|
|
*
|
|
* @param string $index
|
|
*/
|
|
public function setIndex(string $index): void
|
|
{
|
|
$this->logger->debug("Setting index to $index");
|
|
$this->index = $index;
|
|
}
|
|
|
|
/**
|
|
* Creates a batch indexing request for Elasticsearch.
|
|
*
|
|
* The size of the batch is defined by `this::batchSize`.
|
|
*
|
|
* Additionally, Beans marked as deleted will be remove from the index.
|
|
*
|
|
* @param string $module
|
|
* @param SugarBean[] $beans
|
|
*
|
|
* @see batchSize
|
|
*/
|
|
private function indexBatch(string $module, array $beans): void
|
|
{
|
|
$params = ['body' => []];
|
|
|
|
foreach ($beans as $key => $bean) {
|
|
$head = ['_index' => strtolower($module), '_id' => $bean->id];
|
|
|
|
if ($bean->deleted) {
|
|
$params['body'][] = ['delete' => $head];
|
|
$this->removedRecordsCount++;
|
|
} else {
|
|
$body = $this->makeIndexParamsBodyFromBean($bean);
|
|
$params['body'][] = ['index' => $head];
|
|
$params['body'][] = $body;
|
|
$this->indexedRecordsCount++;
|
|
$this->indexedFieldsCount += count($body);
|
|
}
|
|
|
|
// Send a batch of $this->batchSize elements to the server
|
|
if ($key % $this->batchSize == 0) {
|
|
$this->sendBatch($params);
|
|
}
|
|
}
|
|
|
|
// Send the last batch if it exists
|
|
if (!empty($params['body'])) {
|
|
$this->sendBatch($params);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Returns true if differentialIndexing is enabled and a previous run timestamp was found.
|
|
*
|
|
* @return bool
|
|
*/
|
|
private function differentialIndexing(): bool
|
|
{
|
|
return $this->differentialIndexing && $this->lastRunTimestamp !== false;
|
|
}
|
|
|
|
/**
|
|
* Creates the body of a Elasticsearch request for a given bean.
|
|
*
|
|
* It uses a Documentifier to make a document out of a SugarBean.
|
|
*
|
|
* @param SugarBean $bean
|
|
*
|
|
* @return array
|
|
* @see AbstractDocumentifier
|
|
*/
|
|
private function makeIndexParamsBodyFromBean(SugarBean $bean): array
|
|
{
|
|
return $this->documentifier->documentify($bean);
|
|
}
|
|
|
|
/**
|
|
* Sends a batch request with the given params.
|
|
*
|
|
* Sends the requests and attempts to parse errors and fix the number of indexed records in case of errors.
|
|
*
|
|
* @param array $params
|
|
*/
|
|
private function sendBatch(array &$params): void
|
|
{
|
|
// sends the batch over to the server
|
|
$responses = $this->client->bulk($params);
|
|
|
|
if (isset($responses['errors']) && $responses['errors'] === true) {
|
|
// logs the errors
|
|
foreach ($responses['items'] as $item) {
|
|
$action = array_keys($item)[0];
|
|
if(isset($item[$action]['error'])) {
|
|
$type = $item[$action]['error']['type'];
|
|
$reason = $item[$action]['error']['reason'];
|
|
$this->logger->error("[$action] [$type] $reason");
|
|
|
|
if ($action === 'index') {
|
|
$this->indexedRecordsCount--;
|
|
}
|
|
|
|
if ($action === 'delete') {
|
|
$this->removedRecordsCount--;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// erase the old bulk request
|
|
$params = ['body' => []];
|
|
|
|
// unset the bulk response when you are done to save memory
|
|
unset($responses);
|
|
}
|
|
|
|
/**
|
|
* Generates the params for indexing a bean from the bean itself.
|
|
*
|
|
* @param SugarBean $bean
|
|
*
|
|
* @return array
|
|
*/
|
|
private function makeIndexParamsFromBean(SugarBean $bean): array
|
|
{
|
|
$args = $this->makeParamsHeaderFromBean($bean);
|
|
$args['body'] = $this->makeIndexParamsBodyFromBean($bean);
|
|
|
|
return $args;
|
|
}
|
|
|
|
/**
|
|
* Generates the headers for indexing a bean from the bean itself.
|
|
*
|
|
* @param SugarBean $bean
|
|
*
|
|
* @return array
|
|
*/
|
|
private function makeParamsHeaderFromBean(SugarBean $bean): array
|
|
{
|
|
return [
|
|
'index' => strtolower($bean->module_name),
|
|
'id' => $bean->id,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Retrieves the last time a module was indexed from a metadata stored in the Elasticsearch index.
|
|
*
|
|
* @param string $module
|
|
*
|
|
* @return string a datetime string
|
|
*/
|
|
private function getModuleLastIndexed(string $module): string
|
|
{
|
|
$meta = $this->getMeta($module);
|
|
|
|
if (!isset($meta['last_index'])) {
|
|
throw new RuntimeException("Last index metadata not found.");
|
|
}
|
|
|
|
return $meta['last_index'];
|
|
}
|
|
|
|
/**
|
|
* @param bool $differential
|
|
* @param int $searchdefs
|
|
*/
|
|
public static function repairElasticsearchIndex(bool $differential = true, int $searchdefs = 0): void
|
|
{
|
|
$indexer = new ElasticSearchIndexer();
|
|
if (!$indexer::isEnabled()) {
|
|
return;
|
|
}
|
|
$indexer->setDifferentialIndexing($differential);
|
|
if ($searchdefs) {
|
|
$indexer->setDocumentifier(new SearchDefsDocumentifier());
|
|
}
|
|
$indexer->index();
|
|
}
|
|
}
|