From 3256f60c69e887541d7400b90aaef689369e0759 Mon Sep 17 00:00:00 2001 From: Jens Hartlep Date: Wed, 26 Feb 2025 13:34:02 +0100 Subject: [PATCH 1/2] first iteration for PostgreSQL support --- classes/configtable.php | 1549 ++++++++++++++++++++------------------- classes/items.php | 342 ++++----- inventory_manager.php | 26 +- 3 files changed, 982 insertions(+), 935 deletions(-) diff --git a/classes/configtable.php b/classes/configtable.php index 27db19a..ed13a4d 100644 --- a/classes/configtable.php +++ b/classes/configtable.php @@ -7,781 +7,830 @@ * @author MightyMCoder * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only - * - * + * + * * Methods: - * __construct() : constructor + * __construct() : constructor * checkPffInst() : used to check if the plugin FormFiller is installed - * isPffInst() : used to check if plugin FormFiller is installed; if yes returns true otherwise false + * isPffInst() : used to check if plugin FormFiller is installed; if yes returns true otherwise false * findPff() : used to check if a FormFiller directory exists - * pffDir() : used to get the installation directory of the Plugin FormFiller; returns false if it doesn't exists or if it exists multiple times - * init() : used to check if the configuration table exists, if not creates it and sets default values + * pffDir() : used to get the installation directory of the Plugin FormFiller; returns false if it doesn't exists or if it exists multiple times + * init() : used to check if the configuration table exists, if not creates it and sets default values * createTablesIfNotExist() : used to create the necessary tables if they do not exist * createTableIfNotExist($tableName, - * $tableDefinition) : used to create a table if it does not exist + * $tableDefinition) : used to create a table if it does not exist * initializeDefaultFieldsByOrgId() : used to initialize default fields in the inventory manager database * createField($name, $internalName, $type, $description, - * $sequence, $system, $mandatory, - * $valueList = '') : used to create a field in the inventory manager database + * $sequence, $system, $mandatory, + * $valueList = '') : used to create a field in the inventory manager database * initializePreferencesByOrgId() : used to initialize preferences for the inventory manager - * write() : used to write the configuration data to database - * read() : used to read the configuration data from database + * write() : used to write the configuration data to database + * read() : used to read the configuration data from database * readPff() : used to read the configuration data of plugin FormFiller from database * readConfigData($pluginShortcut, - * &$configArray) : used to read the configuration data of a plugin from the database - * checkForUpdate() : used to compare version and stand of file "/../version.php" with data from database + * &$configArray) : used to read the configuration data of a plugin from the database + * checkForUpdate() : used to compare version and stand of file "/../version.php" with data from database * compareVersion() : used to compare plugin version with the current version from the database * compareStand() : used to compare plugin stand with the current stand from the database * checkDefaultFieldsForCurrentOrg() : used to check if there are default fields for the current organization - * deleteConfigData($deinstOrgSelect) : used to delete configuration data in database - * deleteItemData($deinstOrgSelect) : used to delete item data in database + * deleteConfigData($deinstOrgSelect) : used to delete configuration data in database + * deleteItemData($deinstOrgSelect) : used to delete item data in database *********************************************************************************************** */ class CConfigTablePIM { - public $config = array(); // array with configuration-data - public $configPff = array(); // array with configuration-data of (P)lugin (f)orm (f)iller + const TABLE_DEFINITION_MYSQL_INVENTORY_MANAGER_FIELDS = ' + imf_id int(10) unsigned NOT NULL AUTO_INCREMENT, + imf_org_id int(10) unsigned NOT NULL, + imf_type varchar(30) NOT NULL, + imf_name varchar(100) NOT NULL, + imf_name_intern varchar(110) NOT NULL, + imf_sequence int(10) unsigned NOT NULL, + imf_system boolean NOT NULL DEFAULT \'0\', + imf_mandatory boolean NOT NULL DEFAULT \'0\', + imf_description text NOT NULL DEFAULT \'\', + imf_value_list text, + imf_usr_id_create int(10) unsigned DEFAULT NULL, + imf_timestamp_create timestamp NULL DEFAULT CURRENT_TIMESTAMP, + imf_usr_id_change int(10) unsigned DEFAULT NULL, + imf_timestamp_change timestamp NULL DEFAULT NULL, + PRIMARY KEY (imf_id) + '; + const TABLE_DEFINITION_POSTGRESQL_INVENTORY_MANAGER_FIELDS = ' + imf_id SERIAL PRIMARY KEY, + imf_org_id INTEGER NOT NULL, + imf_type VARCHAR(30) NOT NULL, + imf_name VARCHAR(100) NOT NULL, + imf_name_intern VARCHAR(110) NOT NULL, + imf_sequence INTEGER NOT NULL, + imf_system BOOLEAN NOT NULL DEFAULT FALSE, + imf_mandatory BOOLEAN NOT NULL DEFAULT FALSE, + imf_description TEXT NOT NULL DEFAULT \'\', + imf_value_list TEXT, + imf_usr_id_create INTEGER DEFAULT NULL, + imf_timestamp_create TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + imf_usr_id_change INTEGER DEFAULT NULL, + imf_timestamp_change TIMESTAMP DEFAULT NULL + '; + const TABLE_DEFINITION_MYSQL_INVENTORY_MANAGER_DATA = ' + imd_id int(10) unsigned NOT NULL AUTO_INCREMENT, + imd_imf_id int(10) unsigned NOT NULL, + imd_imi_id int(10) unsigned NOT NULL, + imd_value varchar(4000) NOT NULL DEFAULT \'\', + PRIMARY KEY (imd_id) + '; + const TABLE_DEFINITION_POSTGRESQL_INVENTORY_MANAGER_DATA = ' + imd_id SERIAL PRIMARY KEY, + imd_imf_id INTEGER NOT NULL, + imd_imi_id INTEGER NOT NULL, + imd_value VARCHAR(4000) NOT NULL DEFAULT \'\' + '; + const TABLE_DEFINITION_MYSQL_INVENTORY_MANAGER_ITEMS = ' + imi_id int(10) unsigned NOT NULL AUTO_INCREMENT, + imi_org_id int(10) unsigned NOT NULL, + imi_former boolean DEFAULT 0, + imi_usr_id_create int(10) unsigned DEFAULT NULL, + imi_timestamp_create timestamp NULL DEFAULT CURRENT_TIMESTAMP, + imi_usr_id_change int(10) unsigned DEFAULT NULL, + imi_timestamp_change timestamp NULL DEFAULT NULL, + PRIMARY KEY (imi_id) + '; + const TABLE_DEFINITION_POSTGRESQL_INVENTORY_MANAGER_ITEMS = ' + imi_id SERIAL PRIMARY KEY, + imi_org_id INTEGER NOT NULL, + imi_former BOOLEAN DEFAULT FALSE, + imi_usr_id_create INTEGER DEFAULT NULL, + imi_timestamp_create TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + imi_usr_id_change INTEGER DEFAULT NULL, + imi_timestamp_change TIMESTAMP DEFAULT NULL + '; + const TABLE_DEFINITION_MYSQL_INVENTORY_MANAGER_LOG = ' + iml_id int(10) unsigned NOT NULL AUTO_INCREMENT, + iml_imi_id int(10) unsigned NOT NULL, + iml_imf_id int(10) unsigned NOT NULL, + iml_value_old varchar(4000) NOT NULL DEFAULT \'\', + iml_value_new varchar(4000) NOT NULL DEFAULT \'\', + iml_usr_id_create int(10) unsigned DEFAULT NULL, + iml_timestamp_create timestamp NULL DEFAULT CURRENT_TIMESTAMP, + iml_comment varchar(255) NOT NULL DEFAULT \'\', + PRIMARY KEY (iml_id) + '; + const TABLE_DEFINITION_POSTGRESQL_INVENTORY_MANAGER_LOG = ' + iml_id SERIAL PRIMARY KEY, + iml_imi_id INTEGER NOT NULL, + iml_imf_id INTEGER NOT NULL, + iml_value_old VARCHAR(4000) NOT NULL DEFAULT \'\', + iml_value_new VARCHAR(4000) NOT NULL DEFAULT \'\', + iml_usr_id_create INTEGER DEFAULT NULL, + iml_timestamp_create TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + iml_comment VARCHAR(255) NOT NULL DEFAULT \'\' + '; + const TABLE_DEFINITION_MYSQL_TABLE_PREFERENCES_NAME = ' + plp_id integer unsigned NOT NULL AUTO_INCREMENT, + plp_org_id integer unsigned NOT NULL, + plp_name varchar(255) NOT NULL, + plp_value text, + PRIMARY KEY (plp_id) + '; + const TABLE_DEFINITION_POSTGRESQL_TABLE_PREFERENCES_NAME = ' + plp_id SERIAL PRIMARY KEY, + plp_org_id INTEGER NOT NULL, + plp_name VARCHAR(255) NOT NULL, + plp_value TEXT + '; + + public $config = array(); // array with configuration-data + public $configPff = array(); // array with configuration-data of (P)lugin (f)orm (f)iller + + private $table_preferences_name; // db table name *_plugin_preferences + private $isPffInst; // (is) (P)lugin (f)orm (f)iller (Inst)alled + private $pffDir; // (p)lugin (f)orm (f)iller (Dir)ectory + + private const SHORTCUT = 'PIM'; // praefix for (P)lugin(I)nventory(M)anager preferences + + /** + * CConfigTablePIM constructor + */ + public function __construct() + { + require_once(__DIR__ . '/../version.php'); + require_once(__DIR__ . '/configdata.php'); - private $table_preferences_name; // db table name *_plugin_preferences - private $isPffInst; // (is) (P)lugin (f)orm (f)iller (Inst)alled - private $pffDir; // (p)lugin (f)orm (f)iller (Dir)ectory + $this->table_preferences_name = TABLE_PREFIX . '_plugin_preferences'; - private const SHORTCUT = 'PIM'; // praefix for (P)lugin(I)nventory(M)anager preferences + $this->findPff(); + $this->checkPffInst(); + } /** - * CConfigTablePIM constructor + * Checks if the plugin FormFiller is installed + * + * @return void + */ + private function checkPffInst(): void + { + global $gDb, $gCurrentOrgId; + + // check if configuration table for plugin FormFiller exists + $sql = 'SELECT table_name FROM information_schema.tables WHERE table_name = \'' . $this->table_preferences_name . '\';'; + $statement = $gDb->queryPrepared($sql); + + if ($statement->rowCount() !== 0) { + $sql = 'SELECT COUNT(*) AS COUNT FROM ' . $this->table_preferences_name . ' WHERE plp_name = ? AND (plp_org_id = ? OR plp_org_id IS NULL);'; + $statement = $gDb->queryPrepared($sql, array('PFF__Plugininformationen__version', $gCurrentOrgId)); + + $this->isPffInst = ((int)$statement->fetchColumn() === 1 && $this->pffDir !== false); + } else { + $this->isPffInst = false; + } + } + + /** + * If the plugin FormFiller is installed + * then this method will return true otherwise false + * + * @return bool Returns @b true if plugin FormFiller is installed */ - public function __construct() - { - require_once(__DIR__ . '/../version.php'); - require_once(__DIR__ . '/configdata.php'); - - $this->table_preferences_name = TABLE_PREFIX .'_plugin_preferences'; - - $this->findPff(); - $this->checkPffInst(); - } - - /** - * Checks if the plugin FormFiller is installed - * - * @return void - */ - private function checkPffInst() : void - { - global $gDb, $gCurrentOrgId; - - // check if configuration table for plugin FormFiller exists - $sql = 'SHOW TABLES LIKE \''.$this->table_preferences_name.'\';'; - $statement = $gDb->queryPrepared($sql); - - if ($statement->rowCount() !== 0) - { - $sql = 'SELECT COUNT(*) AS COUNT FROM '.$this->table_preferences_name.' WHERE plp_name = ? AND (plp_org_id = ? OR plp_org_id IS NULL);'; - $statement = $gDb->queryPrepared($sql, array('PFF__Plugininformationen__version', $gCurrentOrgId)); - - $this->isPffInst = ((int) $statement->fetchColumn() === 1 && $this->pffDir !== false); - } - else - { - $this->isPffInst = false; - } - } - - /** - * If the plugin FormFiller is installed - * then this method will return true otherwise false - * - * @return bool Returns @b true if plugin FormFiller is installed - */ - public function isPffInst() : bool - { - return $this->isPffInst; - } - - /** - * Checks if a FormFiller directory exists - * - * @return void - */ - private function findPff() : void - { - $location = ADMIDIO_PATH . FOLDER_PLUGINS; - $searchedFile = 'formfiller.php'; - $formFillerfiles = array(); - $tempFiles = array(); - - $all = opendir($location); - while ($found = readdir($all)) - { - if (is_dir($location.'/'.$found) and $found<> ".." and $found<> ".") - { - $tempFiles= glob($location.'/'.$found.'/'. $searchedFile); - if (count($tempFiles) > 0) - { - $formFillerfiles[] = $found; // only directory is needed - } - } - } - closedir($all); - unset($all); - - if (count($formFillerfiles) != 1) - { - $this->pffDir = false; - } - else - { - $this->pffDir = $formFillerfiles[0]; - } - } - - /** - * Returns the Plugin FormFiller directory - * - * @return bool/string Returns the FormFiller directory otherwise false - */ - public function pffDir() - { - return $this->pffDir; - } - + public function isPffInst(): bool + { + return $this->isPffInst; + } + + /** + * Checks if a FormFiller directory exists + * + * @return void + */ + private function findPff(): void + { + $location = ADMIDIO_PATH . FOLDER_PLUGINS; + $searchedFile = 'formfiller.php'; + $formFillerfiles = array(); + $tempFiles = array(); + + $all = opendir($location); + while ($found = readdir($all)) { + if (is_dir($location . '/' . $found) and $found <> ".." and $found <> ".") { + $tempFiles = glob($location . '/' . $found . '/' . $searchedFile); + if (count($tempFiles) > 0) { + $formFillerfiles[] = $found; // only directory is needed + } + } + } + closedir($all); + unset($all); + + if (count($formFillerfiles) != 1) { + $this->pffDir = false; + } else { + $this->pffDir = $formFillerfiles[0]; + } + } + + /** + * Returns the Plugin FormFiller directory + * + * @return bool/string Returns the FormFiller directory otherwise false + */ + public function pffDir() + { + return $this->pffDir; + } + /** * checks if the configuration table exists, if necessarry creats it and fills it with default configuration data - * + * + * @return void + */ + public function init(): void + { + $this->createTablesIfNotExist(); + $this->initializeDefaultFieldsByOrgId(); + $this->initializePreferencesByOrgId(); + } + + /** + * Creates the necessary tables if they do not exist + * + * @return void + */ + private function createTablesIfNotExist(): void + { + global $gDbType; + + switch ($gDbType) { + case 'pgsql': + $this->createTableIfNotExist(TBL_INVENTORY_MANAGER_FIELDS, self::TABLE_DEFINITION_POSTGRESQL_INVENTORY_MANAGER_FIELDS); + $this->createTableIfNotExist(TBL_INVENTORY_MANAGER_DATA, self::TABLE_DEFINITION_POSTGRESQL_INVENTORY_MANAGER_DATA); + $this->createTableIfNotExist(TBL_INVENTORY_MANAGER_ITEMS, self::TABLE_DEFINITION_POSTGRESQL_INVENTORY_MANAGER_ITEMS); + $this->createTableIfNotExist(TBL_INVENTORY_MANAGER_LOG, self::TABLE_DEFINITION_POSTGRESQL_INVENTORY_MANAGER_LOG); + $this->createTableIfNotExist($this->table_preferences_name, self::TABLE_DEFINITION_POSTGRESQL_TABLE_PREFERENCES_NAME); + break; + case 'mysql': + default: + $this->createTableIfNotExist(TBL_INVENTORY_MANAGER_FIELDS, self::TABLE_DEFINITION_MYSQL_INVENTORY_MANAGER_FIELDS); + $this->createTableIfNotExist(TBL_INVENTORY_MANAGER_DATA, self::TABLE_DEFINITION_MYSQL_INVENTORY_MANAGER_DATA); + $this->createTableIfNotExist(TBL_INVENTORY_MANAGER_ITEMS, self::TABLE_DEFINITION_MYSQL_INVENTORY_MANAGER_ITEMS); + $this->createTableIfNotExist(TBL_INVENTORY_MANAGER_LOG, self::TABLE_DEFINITION_MYSQL_INVENTORY_MANAGER_LOG); + $this->createTableIfNotExist($this->table_preferences_name, self::TABLE_DEFINITION_MYSQL_TABLE_PREFERENCES_NAME); + } + } + + /** + * Creates a table if it does not exist + * + * @param string $tableName The name of the table + * @param string $tableDefinition The SQL definition of the table + * @return void + */ + private function createTableIfNotExist($tableName, $tableDefinition): void + { + global $gDb, $gDbType; + + $sql = 'SELECT table_name FROM information_schema.tables WHERE table_name = \'' . $tableName . '\';'; + $statement = $gDb->query($sql); + + if (!$statement->rowCount()) { + switch ($gDbType) { + case 'pgsql': + $sql = 'CREATE TABLE ' . $tableName . ' (' . $tableDefinition . ');'; + break; + case 'mysql': + default: + $sql = 'CREATE TABLE ' . $tableName . ' (' . $tableDefinition . ') ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;'; + } + $gDb->query($sql); + } + } + + /** + * Initializes default fields in the inventory manager database + * + * @return void + */ + private function initializeDefaultFieldsByOrgId(): void + { + global $gDb, $gCurrentOrgId; + + $defaultData = array( + array('imf_id' => 1, 'imf_name' => 'PIM_ITEMNAME', 'imf_name_intern' => 'ITEMNAME', 'imf_type' => 'TEXT', 'imf_description' => convlanguagePIM('PIM_ITEMNAME_DESCRIPTION'), 'imf_sequence' => 0, 'imf_system' => 1, 'imf_mandatory' => 1), + array('imf_id' => 2, 'imf_name' => 'PIM_CATEGORY', 'imf_name_intern' => 'CATEGORY', 'imf_type' => 'DROPDOWN', 'imf_description' => convlanguagePIM('PIM_CATEGORY_DESCRIPTION'), 'imf_sequence' => 1, 'imf_system' => 1, 'imf_mandatory' => 1, 'imf_value_list' => 'Allgemein'), + array('imf_id' => 3, 'imf_name' => 'PIM_KEEPER', 'imf_name_intern' => 'KEEPER', 'imf_type' => 'TEXT', 'imf_description' => convlanguagePIM('PIM_KEEPER_DESCRIPTION'), 'imf_sequence' => 2, 'imf_system' => 1, 'imf_mandatory' => 0), + array('imf_id' => 4, 'imf_name' => 'PIM_IN_INVENTORY', 'imf_name_intern' => 'IN_INVENTORY', 'imf_type' => 'CHECKBOX', 'imf_description' => convlanguagePIM('PIM_IN_INVENTORY_DESCRIPTION'), 'imf_sequence' => 3, 'imf_system' => 1, 'imf_mandatory' => 0), + array('imf_id' => 5, 'imf_name' => 'PIM_LAST_RECEIVER', 'imf_name_intern' => 'LAST_RECEIVER', 'imf_type' => 'TEXT', 'imf_description' => convlanguagePIM('PIM_LAST_RECEIVER_DESCRIPTION'), 'imf_sequence' => 4, 'imf_system' => 1, 'imf_mandatory' => 0), + array('imf_id' => 6, 'imf_name' => 'PIM_RECEIVED_ON', 'imf_name_intern' => 'RECEIVED_ON', 'imf_type' => 'DATE', 'imf_description' => convlanguagePIM('PIM_RECEIVED_ON_DESCRIPTION'), 'imf_sequence' => 5, 'imf_system' => 1, 'imf_mandatory' => 0), + array('imf_id' => 7, 'imf_name' => 'PIM_RECEIVED_BACK_ON', 'imf_name_intern' => 'RECEIVED_BACK_ON', 'imf_type' => 'DATE', 'imf_description' => convlanguagePIM('PIM_RECEIVED_BACK_ON_DESCRIPTION'), 'imf_sequence' => 6, 'imf_system' => 1, 'imf_mandatory' => 0) + ); + + $sql = 'SELECT imf_id, imf_name, imf_name_intern, imf_type, imf_description, imf_sequence, imf_system, imf_mandatory, imf_value_list FROM ' . TBL_INVENTORY_MANAGER_FIELDS . ' WHERE imf_org_id = \'' . $gCurrentOrgId . '\';'; + $statement = $gDb->query($sql); + + $existingFields = array(); + while ($row = $statement->fetch()) { + $existingFields[$row['imf_name']] = $row; + } + + $defaultFieldNames = array_column($defaultData, 'imf_name'); + + $pimFields = array(); + $customFields = array(); + + // Sort the array by imf_sequence to get the imf_name and imf_sequence for custom fields of the previous field + $existingFieldsOrdered = $existingFields; + usort($existingFieldsOrdered, function ($a, $b) { + return $a['imf_sequence'] <=> $b['imf_sequence']; + }); + + foreach ($existingFields as $fieldName => $fieldData) { + if (strpos($fieldName, 'PIM_') === 0) { + $pimFields[$fieldName] = $fieldData; + } else { + $customFields[$fieldName] = $fieldData; + $customFields[$fieldName]['previous_imf_name'] = $existingFieldsOrdered[$fieldData['imf_sequence'] - 1]['imf_name']; + $customFields[$fieldName]['previous_sequence'] = $existingFieldsOrdered[$fieldData['imf_sequence'] - 1]['imf_sequence']; + } + } + + // Adjust pimFields to match the defaultData + foreach ($defaultData as $defaultField) { + $defaultFieldName = $defaultField['imf_name']; + if (!isset($pimFields[$defaultFieldName])) { + // Field does not exist, add it to pimFields + $pimFields[$defaultFieldName] = $defaultField; + } else { + foreach ($defaultField as $key => $value) { + if ($key === 'imf_value_list') { + continue; + } + $pimFields[$defaultFieldName][$key] = $value; + } + } + } + + // Sort the array by imd_id but keep the name as imf_name + usort($pimFields, function ($a, $b) { + return $a['imf_id'] <=> $b['imf_id']; + }); + + $pimFields = array_combine(array_column($pimFields, 'imf_name'), $pimFields); + + // Remove PIM fields that are not in the defaultData + foreach ($pimFields as $fieldName => $fieldData) { + if (!in_array($fieldName, $defaultFieldNames)) { + unset($pimFields[$fieldName]); + } + } + + // Append customFields to pimFields + $allFields = $pimFields; + + // Adjust the sequence of pimFields based on customFields + foreach ($customFields as $customField) { + if (isset($customField['previous_imf_name']) && isset($allFields[$customField['previous_imf_name']])) { + $customSequence = $allFields[$customField['previous_imf_name']]['imf_sequence'] + 1; + $customField['imf_sequence'] = $customSequence; + } else { + //old previous item doesnt exist anymore + $customSequence = $customField['previous_sequence'] - 1; + } + + foreach ($allFields as &$pimField) { + if ($pimField['imf_sequence'] >= $customSequence) { + $pimField['imf_sequence']++; + } + } + + unset($pimField); // Break reference to the last element + + if (isset($customField['imf_name'])) { + $allFields[$customField['imf_name']] = $customField; + } + } + // Now $allFields contains the combined and updated fields + + // Clear the table and reset the AUTO_INCREMENT + //$sql = 'TRUNCATE TABLE ' . TBL_INVENTORY_MANAGER_FIELDS; + $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_FIELDS . ' WHERE imf_org_id = ?;'; + $gDb->queryPrepared($sql, array($gCurrentOrgId)); + + // Insert the new array into the database and keep track of new IDs + $newFieldIds = array(); + foreach ($allFields as $field) { + $this->createField( + $field['imf_name'], + $field['imf_name_intern'], + $field['imf_type'], + $field['imf_description'], + $field['imf_sequence'], + $field['imf_system'], + $field['imf_mandatory'], + isset($field['imf_value_list']) ? $field['imf_value_list'] : '' + ); + + // Get the new ID of the inserted field + $newFieldId = $gDb->lastInsertId(); + $newFieldIds[$field['imf_name']] = $newFieldId; + } + + if (count($existingFields) < count($newFieldIds)) { + // Sort existing fields by imf_id in descending order + usort($existingFields, function ($a, $b) { + return $b['imf_id'] <=> $a['imf_id']; + }); + + // Update the imd_imf_id in TBL_INVENTORY_MANAGER_DATA if the ID has changed + $existingFields = array_combine(array_column($existingFields, 'imf_name'), $existingFields); + } + + foreach ($existingFields as $oldField) { + $oldFieldName = $oldField['imf_name']; + if (isset($newFieldIds[$oldFieldName])) { + if ($newFieldIds[$oldFieldName] != $oldField['imf_id']) { + $sql = 'UPDATE ' . TBL_INVENTORY_MANAGER_DATA . ' SET imd_imf_id = ? WHERE imd_imf_id = ?'; + $gDb->queryPrepared($sql, array($newFieldIds[$oldFieldName], $oldField['imf_id'])); + } + } else { + // Field no longer exists, set the field to empty and show an error message + $sql = 'UPDATE ' . TBL_INVENTORY_MANAGER_DATA . ' SET imd_imf_id = NULL WHERE imd_imf_id = ?'; + $gDb->queryPrepared($sql, array($oldField['imf_id'])); + $_SESSION['error_messages'][] = 'Error: Field "' . $oldFieldName . '" no longer exists. Please manually check and adjust the database table"' . TBL_INVENTORY_MANAGER_DATA . '" where "imd_imf_id" equals "NULL" to avoid data loss.'; + } + } + + // Display error messages in a browser window if there are any + if (!empty($_SESSION['error_messages'])) { + // Prepare error messages for safe output in JavaScript + $jsErrorMessages = json_encode(implode("\n", $_SESSION['error_messages'])); + + echo ''; + + unset($_SESSION['error_messages']); + } + } + + /** + * Creates a field in the inventory manager database + * + * @param string $name The name of the field + * @param string $internalName The internal name of the field + * @param string $type The type of the field + * @param string $description The description of the field + * @param int $sequence The sequence order of the field + * @param bool $system Whether the field is a system field + * @param bool $mandatory Whether the field is mandatory + * @param string $valueList The value list for dropdown fields + * @return void + */ + private function createField($name, $internalName, $type, $description, $sequence, $system, $mandatory, $valueList = ''): void + { + global $gDb, $gCurrentOrgId; + + $itemField = new TableAccess($gDb, TBL_INVENTORY_MANAGER_FIELDS, 'imf'); + $itemField->setValue('imf_org_id', (int)$gCurrentOrgId); + $itemField->setValue('imf_sequence', $sequence); + $itemField->setValue('imf_system', $system); + $itemField->setValue('imf_mandatory', $mandatory); + $itemField->setValue('imf_name', $name); + $itemField->setValue('imf_name_intern', $internalName); + $itemField->setValue('imf_type', $type); + $itemField->setValue('imf_description', $description); + $itemField->setValue('imf_value_list', $valueList); + $itemField->save(); + } + + /** + * Initializes preferences for the inventory manager + * + * @return void + */ + private function initializePreferencesByOrgId(): void + { + global $gDb, $gCurrentOrgId; + + $this->read(); + + $this->config['Plugininformationen']['version'] = CPluginInfoPIM::getPluginVersion(); + $this->config['Plugininformationen']['beta-version'] = CPluginInfoPIM::getPluginBetaVersion(); + $this->config['Plugininformationen']['stand'] = CPluginInfoPIM::getPluginStand(); + + $configCurrent = $this->config; + + foreach (CConfigDataPIM::CONFIG_DEFAULT as $section => $sectiondata) { + foreach ($sectiondata as $item => $value) { + if (isset($configCurrent[$section][$item])) { + unset($configCurrent[$section][$item]); + } else { + $this->config[$section][$item] = $value; + } + } + if ((isset($configCurrent[$section]) && count($configCurrent[$section]) == 0)) { + unset($configCurrent[$section]); + } + } + + foreach ($configCurrent as $section => $sectiondata) { + foreach ($sectiondata as $item => $value) { + $plp_name = self::SHORTCUT . '__' . $section . '__' . $item; + $sql = 'DELETE FROM ' . $this->table_preferences_name . ' WHERE plp_name = ? AND plp_org_id = ?;'; + $gDb->queryPrepared($sql, array($plp_name, $gCurrentOrgId)); + unset($this->config[$section][$item]); + } + if (count($this->config[$section]) == 0) { + unset($this->config[$section]); + } + } + + $this->write(); + } + + /** + * Writes the configuration data of plugin InventoryManager to the database + * * @return void */ - public function init() : void - { - $this->createTablesIfNotExist(); - $this->initializeDefaultFieldsByOrgId(); - $this->initializePreferencesByOrgId(); - } - - /** - * Creates the necessary tables if they do not exist - * - * @return void - */ - private function createTablesIfNotExist() : void - { - $this->createTableIfNotExist(TBL_INVENTORY_MANAGER_FIELDS, ' - imf_id int(10) unsigned NOT NULL AUTO_INCREMENT, - imf_org_id int(10) unsigned NOT NULL, - imf_type varchar(30) NOT NULL, - imf_name varchar(100) NOT NULL, - imf_name_intern varchar(110) NOT NULL, - imf_sequence int(10) unsigned NOT NULL, - imf_system boolean NOT NULL DEFAULT \'0\', - imf_mandatory boolean NOT NULL DEFAULT \'0\', - imf_description text NOT NULL DEFAULT \'\', - imf_value_list text, - imf_usr_id_create int(10) unsigned DEFAULT NULL, - imf_timestamp_create timestamp NULL DEFAULT CURRENT_TIMESTAMP, - imf_usr_id_change int(10) unsigned DEFAULT NULL, - imf_timestamp_change timestamp NULL DEFAULT NULL, - PRIMARY KEY (imf_id) - '); - - $this->createTableIfNotExist(TBL_INVENTORY_MANAGER_DATA, ' - imd_id int(10) unsigned NOT NULL AUTO_INCREMENT, - imd_imf_id int(10) unsigned NOT NULL, - imd_imi_id int(10) unsigned NOT NULL, - imd_value varchar(4000) NOT NULL DEFAULT \'\', - PRIMARY KEY (imd_id) - '); - - $this->createTableIfNotExist(TBL_INVENTORY_MANAGER_ITEMS, ' - imi_id int(10) unsigned NOT NULL AUTO_INCREMENT, - imi_org_id int(10) unsigned NOT NULL, - imi_former boolean DEFAULT 0, - imi_usr_id_create int(10) unsigned DEFAULT NULL, - imi_timestamp_create timestamp NULL DEFAULT CURRENT_TIMESTAMP, - imi_usr_id_change int(10) unsigned DEFAULT NULL, - imi_timestamp_change timestamp NULL DEFAULT NULL, - PRIMARY KEY (imi_id) - '); - - $this->createTableIfNotExist(TBL_INVENTORY_MANAGER_LOG, ' - iml_id int(10) unsigned NOT NULL AUTO_INCREMENT, - iml_imi_id int(10) unsigned NOT NULL, - iml_imf_id int(10) unsigned NOT NULL, - iml_value_old varchar(4000) NOT NULL DEFAULT \'\', - iml_value_new varchar(4000) NOT NULL DEFAULT \'\', - iml_usr_id_create int(10) unsigned DEFAULT NULL, - iml_timestamp_create timestamp NULL DEFAULT CURRENT_TIMESTAMP, - iml_comment varchar(255) NOT NULL DEFAULT \'\', - PRIMARY KEY (iml_id) - '); - - $this->createTableIfNotExist($this->table_preferences_name, ' - plp_id integer unsigned NOT NULL AUTO_INCREMENT, - plp_org_id integer unsigned NOT NULL, - plp_name varchar(255) NOT NULL, - plp_value text, - PRIMARY KEY (plp_id) - '); - } - - /** - * Creates a table if it does not exist - * - * @param string $tableName The name of the table - * @param string $tableDefinition The SQL definition of the table - * @return void - */ - private function createTableIfNotExist($tableName, $tableDefinition) : void - { - global $gDb; - - $sql = 'SHOW TABLES LIKE \'' . $tableName . '\';'; - $statement = $gDb->query($sql); - - if (!$statement->rowCount()) { - $sql = 'CREATE TABLE ' . $tableName . ' (' . $tableDefinition . ') ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;'; - $gDb->query($sql); - } - } - - /** - * Initializes default fields in the inventory manager database - * - * @return void - */ - private function initializeDefaultFieldsByOrgId() : void - { - global $gDb, $gCurrentOrgId; - - $defaultData = array( - array('imf_id' => 1, 'imf_name' => 'PIM_ITEMNAME', 'imf_name_intern' => 'ITEMNAME', 'imf_type' => 'TEXT', 'imf_description' => convlanguagePIM('PIM_ITEMNAME_DESCRIPTION'), 'imf_sequence' => 0, 'imf_system' => 1, 'imf_mandatory' => 1), - array('imf_id' => 2, 'imf_name' => 'PIM_CATEGORY', 'imf_name_intern' => 'CATEGORY', 'imf_type' => 'DROPDOWN', 'imf_description' => convlanguagePIM('PIM_CATEGORY_DESCRIPTION'), 'imf_sequence' => 1, 'imf_system' => 1, 'imf_mandatory' => 1, 'imf_value_list' => 'Allgemein'), - array('imf_id' => 3, 'imf_name' => 'PIM_KEEPER', 'imf_name_intern' => 'KEEPER', 'imf_type' => 'TEXT', 'imf_description' => convlanguagePIM('PIM_KEEPER_DESCRIPTION'), 'imf_sequence' => 2, 'imf_system' => 1, 'imf_mandatory' => 0), - array('imf_id' => 4, 'imf_name' => 'PIM_IN_INVENTORY', 'imf_name_intern' => 'IN_INVENTORY', 'imf_type' => 'CHECKBOX', 'imf_description' => convlanguagePIM('PIM_IN_INVENTORY_DESCRIPTION'), 'imf_sequence' => 3, 'imf_system' => 1, 'imf_mandatory' => 0), - array('imf_id' => 5, 'imf_name' => 'PIM_LAST_RECEIVER', 'imf_name_intern' => 'LAST_RECEIVER', 'imf_type' => 'TEXT', 'imf_description' => convlanguagePIM('PIM_LAST_RECEIVER_DESCRIPTION'), 'imf_sequence' => 4, 'imf_system' => 1, 'imf_mandatory' => 0), - array('imf_id' => 6, 'imf_name' => 'PIM_RECEIVED_ON', 'imf_name_intern' => 'RECEIVED_ON', 'imf_type' => 'DATE', 'imf_description' => convlanguagePIM('PIM_RECEIVED_ON_DESCRIPTION'), 'imf_sequence' => 5, 'imf_system' => 1, 'imf_mandatory' => 0), - array('imf_id' => 7, 'imf_name' => 'PIM_RECEIVED_BACK_ON', 'imf_name_intern' => 'RECEIVED_BACK_ON', 'imf_type' => 'DATE', 'imf_description' => convlanguagePIM('PIM_RECEIVED_BACK_ON_DESCRIPTION'), 'imf_sequence' => 6, 'imf_system' => 1, 'imf_mandatory' => 0) - ); - - $sql = 'SELECT imf_id, imf_name, imf_name_intern, imf_type, imf_description, imf_sequence, imf_system, imf_mandatory, imf_value_list FROM ' . TBL_INVENTORY_MANAGER_FIELDS . ' WHERE imf_org_id = \'' . $gCurrentOrgId . '\';'; - $statement = $gDb->query($sql); - - $existingFields = array(); - while ($row = $statement->fetch()) { - $existingFields[$row['imf_name']] = $row; - } - - $defaultFieldNames = array_column($defaultData, 'imf_name'); - - $pimFields = array(); - $customFields = array(); - - // Sort the array by imf_sequence to get the imf_name and imf_sequence for custom fields of the previous field - $existingFieldsOrdered = $existingFields; - usort($existingFieldsOrdered, function($a, $b) { - return $a['imf_sequence'] <=> $b['imf_sequence']; - }); - - foreach ($existingFields as $fieldName => $fieldData) { - if (strpos($fieldName, 'PIM_') === 0) { - $pimFields[$fieldName] = $fieldData; - } - else { - $customFields[$fieldName] = $fieldData; - $customFields[$fieldName]['previous_imf_name'] = $existingFieldsOrdered[$fieldData['imf_sequence'] - 1]['imf_name']; - $customFields[$fieldName]['previous_sequence'] = $existingFieldsOrdered[$fieldData['imf_sequence'] - 1]['imf_sequence']; - } - } - - // Adjust pimFields to match the defaultData - foreach ($defaultData as $defaultField) { - $defaultFieldName = $defaultField['imf_name']; - if (!isset($pimFields[$defaultFieldName])) { - // Field does not exist, add it to pimFields - $pimFields[$defaultFieldName] = $defaultField; - } - else { - foreach($defaultField as $key => $value) { - if ($key === 'imf_value_list') { - continue; - } - $pimFields[$defaultFieldName][$key] = $value; - } - } - } - - // Sort the array by imd_id but keep the name as imf_name - usort($pimFields, function($a, $b) { - return $a['imf_id'] <=> $b['imf_id']; - }); - - $pimFields = array_combine(array_column($pimFields, 'imf_name'), $pimFields); - - // Remove PIM fields that are not in the defaultData - foreach ($pimFields as $fieldName => $fieldData) { - if (!in_array($fieldName, $defaultFieldNames)) { - unset($pimFields[$fieldName]); - } - } - - // Append customFields to pimFields - $allFields = $pimFields; - - // Adjust the sequence of pimFields based on customFields - foreach ($customFields as $customField) { - if (isset($customField['previous_imf_name']) && isset($allFields[$customField['previous_imf_name']])) { - $customSequence = $allFields[$customField['previous_imf_name']]['imf_sequence'] + 1; - $customField['imf_sequence'] = $customSequence; - } - else { - //old previous item doesnt exist anymore - $customSequence = $customField['previous_sequence'] - 1; - } - - foreach ($allFields as &$pimField) { - if ($pimField['imf_sequence'] >= $customSequence) { - $pimField['imf_sequence']++; - } - } - - unset($pimField); // Break reference to the last element - - if (isset($customField['imf_name'])) { - $allFields[$customField['imf_name']] = $customField; - } - } - // Now $allFields contains the combined and updated fields - - // Clear the table and reset the AUTO_INCREMENT - //$sql = 'TRUNCATE TABLE ' . TBL_INVENTORY_MANAGER_FIELDS; - $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_FIELDS . ' WHERE imf_org_id = ?;'; - $gDb->queryPrepared($sql, array($gCurrentOrgId)); - - // Insert the new array into the database and keep track of new IDs - $newFieldIds = array(); - foreach ($allFields as $field) { - $this->createField( - $field['imf_name'], - $field['imf_name_intern'], - $field['imf_type'], - $field['imf_description'], - $field['imf_sequence'], - $field['imf_system'], - $field['imf_mandatory'], - isset($field['imf_value_list']) ? $field['imf_value_list'] : '' - ); - - // Get the new ID of the inserted field - $newFieldId = $gDb->lastInsertId(); - $newFieldIds[$field['imf_name']] = $newFieldId; - } - - if (count($existingFields) < count($newFieldIds)) { - // Sort existing fields by imf_id in descending order - usort($existingFields, function($a, $b) { - return $b['imf_id'] <=> $a['imf_id']; - }); - - // Update the imd_imf_id in TBL_INVENTORY_MANAGER_DATA if the ID has changed - $existingFields = array_combine(array_column($existingFields, 'imf_name'), $existingFields); - } - - foreach ($existingFields as $oldField) { - $oldFieldName = $oldField['imf_name']; - if (isset($newFieldIds[$oldFieldName])) { - if ($newFieldIds[$oldFieldName] != $oldField['imf_id']) { - $sql = 'UPDATE ' . TBL_INVENTORY_MANAGER_DATA . ' SET imd_imf_id = ? WHERE imd_imf_id = ?'; - $gDb->queryPrepared($sql, array($newFieldIds[$oldFieldName], $oldField['imf_id'])); - } - } - else { - // Field no longer exists, set the field to empty and show an error message - $sql = 'UPDATE ' . TBL_INVENTORY_MANAGER_DATA . ' SET imd_imf_id = NULL WHERE imd_imf_id = ?'; - $gDb->queryPrepared($sql, array($oldField['imf_id'])); - $_SESSION['error_messages'][] = 'Error: Field "' . $oldFieldName . '" no longer exists. Please manually check and adjust the database table"' . TBL_INVENTORY_MANAGER_DATA .'" where "imd_imf_id" equals "NULL" to avoid data loss.'; - } - } - - // Display error messages in a browser window if there are any - if (!empty($_SESSION['error_messages'])) { - // Prepare error messages for safe output in JavaScript - $jsErrorMessages = json_encode(implode("\n", $_SESSION['error_messages'])); - - echo ''; - - unset($_SESSION['error_messages']); - } - } - - /** - * Creates a field in the inventory manager database - * - * @param string $name The name of the field - * @param string $internalName The internal name of the field - * @param string $type The type of the field - * @param string $description The description of the field - * @param int $sequence The sequence order of the field - * @param bool $system Whether the field is a system field - * @param bool $mandatory Whether the field is mandatory - * @param string $valueList The value list for dropdown fields - * @return void - */ - private function createField($name, $internalName, $type, $description, $sequence, $system, $mandatory, $valueList = '') : void - { - global $gDb, $gCurrentOrgId; - - $itemField = new TableAccess($gDb, TBL_INVENTORY_MANAGER_FIELDS, 'imf'); - $itemField->setValue('imf_org_id', (int) $gCurrentOrgId); - $itemField->setValue('imf_sequence', $sequence); - $itemField->setValue('imf_system', $system); - $itemField->setValue('imf_mandatory', $mandatory); - $itemField->setValue('imf_name', $name); - $itemField->setValue('imf_name_intern', $internalName); - $itemField->setValue('imf_type', $type); - $itemField->setValue('imf_description', $description); - $itemField->setValue('imf_value_list', $valueList); - $itemField->save(); - } - - /** - * Initializes preferences for the inventory manager - * - * @return void - */ - private function initializePreferencesByOrgId() : void - { - global $gDb, $gCurrentOrgId; - - $this->read(); - - $this->config['Plugininformationen']['version'] = CPluginInfoPIM::getPluginVersion(); - $this->config['Plugininformationen']['beta-version'] = CPluginInfoPIM::getPluginBetaVersion(); - $this->config['Plugininformationen']['stand'] = CPluginInfoPIM::getPluginStand(); - - $configCurrent = $this->config; - - foreach (CConfigDataPIM::CONFIG_DEFAULT as $section => $sectiondata) { - foreach ($sectiondata as $item => $value) { - if (isset($configCurrent[$section][$item])) { - unset($configCurrent[$section][$item]); - } else { - $this->config[$section][$item] = $value; - } - } - if ((isset($configCurrent[$section]) && count($configCurrent[$section]) == 0)) { - unset($configCurrent[$section]); - } - } - - foreach ($configCurrent as $section => $sectiondata) { - foreach ($sectiondata as $item => $value) { - $plp_name = self::SHORTCUT . '__' . $section . '__' . $item; - $sql = 'DELETE FROM ' . $this->table_preferences_name . ' WHERE plp_name = ? AND plp_org_id = ?;'; - $gDb->queryPrepared($sql, array($plp_name, $gCurrentOrgId)); - unset($this->config[$section][$item]); - } - if (count($this->config[$section]) == 0) { - unset($this->config[$section]); - } - } - - $this->write(); - } - - /** - * Writes the configuration data of plugin InventoryManager to the database - * - * @return void - */ - public function write() : void - { - global $gDb, $gCurrentOrgId; - - foreach ($this->config as $section => $sectionData) { - foreach ($sectionData as $item => $value) { - if (is_array($value)) { - // Data is enclosed in double brackets to mark this record as an array in the database - $value = '((' . implode(CConfigDataPIM::DB_TOKEN, $value) . '))'; - } - - $plpName = self::SHORTCUT . '__' . $section . '__' . $item; - - $sql = 'SELECT plp_id FROM ' . $this->table_preferences_name . ' WHERE plp_name = ? AND (plp_org_id = ? OR plp_org_id IS NULL);'; - $statement = $gDb->queryPrepared($sql, array($plpName, $gCurrentOrgId)); - $row = $statement->fetchObject(); - - if (isset($row->plp_id) && strlen($row->plp_id) > 0) { - // Record exists, update it - $sql = 'UPDATE ' . $this->table_preferences_name . ' SET plp_value = ? WHERE plp_id = ?;'; - $gDb->queryPrepared($sql, array($value, $row->plp_id)); - } - else { - // Record does not exist, insert it - $sql = 'INSERT INTO ' . $this->table_preferences_name . ' (plp_org_id, plp_name, plp_value) VALUES (?, ?, ?);'; - $gDb->queryPrepared($sql, array($gCurrentOrgId, $plpName, $value)); - } - } - } - } - - /** - * Reads the configuration data of plugin InventoryManager from the database - * - * @return bool - */ - public function read() : bool - { - return $this->readConfigData(self::SHORTCUT, $this->config); - } - - /** - * Reads the configuration data of plugin FormFiller (PFF) from the database - * - * @return bool - */ - public function readPff() : bool - { - return $this->readConfigData('PFF', $this->configPff); - } - - /** - * Reads the configuration data of a plugin from the database - * - * @param string $pluginShortcut The shortcut of the plugin - * @param array &$configArray The array to store the configuration data - * @return bool - */ - private function readConfigData($pluginShortcut, &$configArray) : bool - { - global $gDb, $gCurrentOrgId; - - // Check if table *_plugin_preferences exists - $sql = 'SHOW TABLES LIKE \'' . $this->table_preferences_name . '\' '; - $tablePreferencesExistStatement = $gDb->queryPrepared($sql); - - if ($tablePreferencesExistStatement->rowCount() === 0) { - return false; - } - - $sql = 'SELECT plp_id, plp_name, plp_value FROM '.$this->table_preferences_name.' WHERE plp_name LIKE ? AND (plp_org_id = ? OR plp_org_id IS NULL);'; - $statement = $gDb->queryPrepared($sql, array($pluginShortcut.'__%', $gCurrentOrgId)); - - while ($row = $statement->fetch()) - { - $array = explode('__', $row['plp_name']); - - // if plp_value is enclosed in (( )) -> array - if ((substr($row['plp_value'], 0, 2) == '((' ) && (substr($row['plp_value'], -2) == '))' )) - { - $row['plp_value'] = substr($row['plp_value'], 2, -2); - $configArray[$array[1]] [$array[2]] = explode(CConfigDataPIM::DB_TOKEN, $row['plp_value']); - } - else - { - if (is_numeric($row['plp_value'])) { - if (strpos($row['plp_value'], '.') !== false) { - $configArray[$array[1]] [$array[2]] = (float)$row['plp_value']; - } else { - $configArray[$array[1]] [$array[2]] = (int)$row['plp_value']; - } - } else { - $configArray[$array[1]] [$array[2]] = $row['plp_value']; - } - } - - // if array data is again enclosed in (( )) -> split again - if ($pluginShortcut === 'PFF' && is_array($configArray[$array[1]] [$array[2]])) { - for ($i = 0; $i < count($configArray[$array[1]] [$array[2]]); $i++) - { - if ((substr($configArray[$array[1]] [$array[2]][$i], 0, 2) == '((' ) && (substr($configArray[$array[1]] [$array[2]][$i], -2) == '))' )) - { - $temp = substr($configArray[$array[1]] [$array[2]][$i], 2, -2); - $configArray[$array[1]] [$array[2]][$i] = explode(CConfigDataPIM::DB_TOKEN_FORMFILLER, $temp); - } - } - } - } - return true; - } - - /** - * Compare plugin version and stand with current version and stand from database - * - * @return bool - */ - public function checkForUpdate() : bool - { - global $gDb; - - $needsUpdate = false; - - // Check if table *_plugin_preferences exists - $sql = 'SHOW TABLES LIKE \'' . $this->table_preferences_name . '\' '; - $tablePreferencesExistStatement = $gDb->queryPrepared($sql); - - $sql = 'SHOW TABLES LIKE \'' . TBL_INVENTORY_MANAGER_FIELDS . '\' '; - $tableFieldsExistStatement = $gDb->queryPrepared($sql); - - if ($tablePreferencesExistStatement->rowCount() && $tableFieldsExistStatement->rowCount()) { - $needsUpdate = $this->checkDefaultFieldsForCurrentOrg() || $this->compareVersion() || $this->compareStand(); - } else { - // Update needed because it is not installed yet - $needsUpdate = true; - } - - return $needsUpdate; - } - - /** - * Compare plugin version with the current version from the database - * - * @return bool - */ - private function compareVersion() : bool - { - global $gDb, $gCurrentOrgId; - - $plp_name = self::SHORTCUT . '__Plugininformationen__version'; - - $sql = 'SELECT plp_value FROM ' . $this->table_preferences_name . ' WHERE plp_name = ? AND (plp_org_id = ? OR plp_org_id IS NULL);'; - $statement = $gDb->queryPrepared($sql, array($plp_name, $gCurrentOrgId)); - $row = $statement->fetchObject(); - - // Compare versions - return !isset($row->plp_value) || strlen($row->plp_value) === 0 || $row->plp_value !== CPluginInfoPIM::getPluginVersion(); - } - - /** - * Compare plugin stand with the current stand from the database - * - * @return bool - */ - private function compareStand() : bool - { - global $gDb, $gCurrentOrgId; - - $plp_name = self::SHORTCUT . '__Plugininformationen__stand'; - - $sql = 'SELECT plp_value FROM ' . $this->table_preferences_name . ' WHERE plp_name = ? AND (plp_org_id = ? OR plp_org_id IS NULL);'; - $statement = $gDb->queryPrepared($sql, array($plp_name, $gCurrentOrgId)); - $row = $statement->fetchObject(); - - // Compare stands - return !isset($row->plp_value) || strlen($row->plp_value) === 0 || $row->plp_value !== CPluginInfoPIM::getPluginStand(); - } - - /** - * Checks if there are default fields for the current organization. - * - * @return bool Returns true if there are no default fields for the current organization, false otherwise. - */ - private function checkDefaultFieldsForCurrentOrg() : bool - { - global $gDb, $gCurrentOrgId; - - $sql = 'SELECT imf_name_intern FROM ' . TBL_INVENTORY_MANAGER_FIELDS . ' WHERE imf_org_id = ?;'; - $statement = $gDb->queryPrepared($sql, array($gCurrentOrgId)); - $row = $statement->fetchObject(); - - if (!$row) { - return true; - } - return false; - } - - /** - * Delete configuration data from the database - * - * @param int $deinstOrgSelect 0 = only delete data from current org, - * 1 = delete data from every org - * @return string Result message - */ - public function deleteConfigData($deinstOrgSelect) : string - { - global $gDb, $gCurrentOrgId, $gL10n; - - $result = ''; - $sqlWhereCondition = ''; - - if ($deinstOrgSelect == 0) { - $sqlWhereCondition = 'AND plp_org_id = ?'; - } - - $sql = 'DELETE FROM ' . $this->table_preferences_name . ' WHERE plp_name LIKE ? ' . $sqlWhereCondition; - $params = [self::SHORTCUT . '__%']; - if ($deinstOrgSelect == 0) { - $params[] = $gCurrentOrgId; - } - $result_data = $gDb->queryPrepared($sql, $params); - $result .= ($result_data ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', array($this->table_preferences_name)) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', array($this->table_preferences_name))); - - // Check if the table is empty and can be deleted - $sql = 'SELECT * FROM ' . $this->table_preferences_name; - $statement = $gDb->queryPrepared($sql); - - if ($statement->rowCount() == 0) { - $sql = 'DROP TABLE ' . $this->table_preferences_name; - $result_db = $gDb->queryPrepared($sql); - $result .= ($result_db ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_TABLE_DELETED', array($this->table_preferences_name)) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_TABLE_DELETE_ERROR', array($this->table_preferences_name))); - } else { - $result .= $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_CONFIGTABLE_DELETE_NOTPOSSIBLE', array($this->table_preferences_name)); - } - - return $result; - } - - /** - * Delete the item data from the database - * - * @param int $deinstOrgSelect 0 = only delete data from current org, 1 = delete data from every org - * @return string $result Result message - */ - public function deleteItemData($deinstOrgSelect) : string - { - global $gDb, $gCurrentOrgId, $gL10n; - $result = ''; - - if ($deinstOrgSelect == 0) { - $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_DATA . ' WHERE imd_imi_id IN (SELECT imi_id FROM ' . TBL_INVENTORY_MANAGER_ITEMS . ' WHERE imi_org_id = ?)'; - $result_data = $gDb->queryPrepared($sql, array($gCurrentOrgId)); - $result .= ($result_data ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', array(TABLE_PREFIX . '_inventory_manager_data')) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', array(TABLE_PREFIX . '_inventory_manager_data'))); - - $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_LOG . ' WHERE iml_imi_id IN (SELECT imi_id FROM ' . TBL_INVENTORY_MANAGER_ITEMS . ' WHERE imi_org_id = ?)'; - $result_log = $gDb->queryPrepared($sql, array($gCurrentOrgId)); - $result .= ($result_log ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', array(TABLE_PREFIX . '_inventory_manager_log')) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', array(TABLE_PREFIX . '_inventory_manager_log'))); - - $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_ITEMS . ' WHERE imi_org_id = ?'; - $result_items = $gDb->queryPrepared($sql, array($gCurrentOrgId)); - $result .= ($result_items ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', array(TABLE_PREFIX . '_inventory_manager_items')) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', array(TABLE_PREFIX . '_inventory_manager_items'))); - - $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_FIELDS . ' WHERE imf_org_id = ?'; - $result_fields = $gDb->queryPrepared($sql, array($gCurrentOrgId)); - $result .= ($result_fields ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', array(TABLE_PREFIX . '_inventory_manager_fields')) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', array(TABLE_PREFIX . '_inventory_manager_fields'))); - } - - // Drop tables if they are empty or if data should be deleted from every org - $table_array = array( - TBL_INVENTORY_MANAGER_FIELDS, - TBL_INVENTORY_MANAGER_DATA, - TBL_INVENTORY_MANAGER_ITEMS, - TBL_INVENTORY_MANAGER_LOG - ); - - foreach ($table_array as $table_name) { - $sql = 'SELECT * FROM ' . $table_name; - $statement = $gDb->queryPrepared($sql); - - if ($statement->rowCount() == 0 || $deinstOrgSelect == 1) { - $sql = 'DROP TABLE ' . $table_name; - $result_db = $gDb->queryPrepared($sql); - $result .= ($result_db ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_TABLE_DELETED', array($table_name)) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_TABLE_DELETE_ERROR', array($table_name))); - } else { - $result .= $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_TABLE_DELETE_NOTPOSSIBLE', array($table_name)); - } - } - - return $result; - } + public function write(): void + { + global $gDb, $gCurrentOrgId; + + foreach ($this->config as $section => $sectionData) { + foreach ($sectionData as $item => $value) { + if (is_array($value)) { + // Data is enclosed in double brackets to mark this record as an array in the database + $value = '((' . implode(CConfigDataPIM::DB_TOKEN, $value) . '))'; + } + + $plpName = self::SHORTCUT . '__' . $section . '__' . $item; + + $sql = 'SELECT plp_id FROM ' . $this->table_preferences_name . ' WHERE plp_name = ? AND (plp_org_id = ? OR plp_org_id IS NULL);'; + $statement = $gDb->queryPrepared($sql, array($plpName, $gCurrentOrgId)); + $row = $statement->fetchObject(); + + if (isset($row->plp_id) && strlen($row->plp_id) > 0) { + // Record exists, update it + $sql = 'UPDATE ' . $this->table_preferences_name . ' SET plp_value = ? WHERE plp_id = ?;'; + $gDb->queryPrepared($sql, array($value, $row->plp_id)); + } else { + // Record does not exist, insert it + $sql = 'INSERT INTO ' . $this->table_preferences_name . ' (plp_org_id, plp_name, plp_value) VALUES (?, ?, ?);'; + $gDb->queryPrepared($sql, array($gCurrentOrgId, $plpName, $value)); + } + } + } + } + + /** + * Reads the configuration data of plugin InventoryManager from the database + * + * @return bool + */ + public function read(): bool + { + return $this->readConfigData(self::SHORTCUT, $this->config); + } + + /** + * Reads the configuration data of plugin FormFiller (PFF) from the database + * + * @return bool + */ + public function readPff(): bool + { + return $this->readConfigData('PFF', $this->configPff); + } + + /** + * Reads the configuration data of a plugin from the database + * + * @param string $pluginShortcut The shortcut of the plugin + * @param array &$configArray The array to store the configuration data + * @return bool + */ + private function readConfigData($pluginShortcut, &$configArray): bool + { + global $gDb, $gCurrentOrgId; + + // Check if table *_plugin_preferences exists + $sql = 'SELECT table_name FROM information_schema.tables WHERE table_name = \'' . $this->table_preferences_name . '\';'; + $tablePreferencesExistStatement = $gDb->queryPrepared($sql); + + if ($tablePreferencesExistStatement->rowCount() === 0) { + return false; + } + + $sql = 'SELECT plp_id, plp_name, plp_value FROM ' . $this->table_preferences_name . ' WHERE plp_name LIKE ? AND (plp_org_id = ? OR plp_org_id IS NULL);'; + $statement = $gDb->queryPrepared($sql, array($pluginShortcut . '__%', $gCurrentOrgId)); + + while ($row = $statement->fetch()) { + $array = explode('__', $row['plp_name']); + + // if plp_value is enclosed in (( )) -> array + if ((substr($row['plp_value'], 0, 2) == '((') && (substr($row['plp_value'], -2) == '))')) { + $row['plp_value'] = substr($row['plp_value'], 2, -2); + $configArray[$array[1]] [$array[2]] = explode(CConfigDataPIM::DB_TOKEN, $row['plp_value']); + } else { + if (is_numeric($row['plp_value'])) { + if (strpos($row['plp_value'], '.') !== false) { + $configArray[$array[1]] [$array[2]] = (float)$row['plp_value']; + } else { + $configArray[$array[1]] [$array[2]] = (int)$row['plp_value']; + } + } else { + $configArray[$array[1]] [$array[2]] = $row['plp_value']; + } + } + + // if array data is again enclosed in (( )) -> split again + if ($pluginShortcut === 'PFF' && is_array($configArray[$array[1]] [$array[2]])) { + for ($i = 0; $i < count($configArray[$array[1]] [$array[2]]); $i++) { + if ((substr($configArray[$array[1]] [$array[2]][$i], 0, 2) == '((') && (substr($configArray[$array[1]] [$array[2]][$i], -2) == '))')) { + $temp = substr($configArray[$array[1]] [$array[2]][$i], 2, -2); + $configArray[$array[1]] [$array[2]][$i] = explode(CConfigDataPIM::DB_TOKEN_FORMFILLER, $temp); + } + } + } + } + return true; + } + + /** + * Compare plugin version and stand with current version and stand from database + * + * @return bool + */ + public function checkForUpdate(): bool + { + global $gDb; + + $needsUpdate = false; + + // Check if table *_plugin_preferences exists + $sql = 'SELECT table_name FROM information_schema.tables WHERE table_name = \'' . $this->table_preferences_name . '\';'; + $tablePreferencesExistStatement = $gDb->queryPrepared($sql); + + $sql = 'SELECT table_name FROM information_schema.tables WHERE table_name = \'' . TBL_INVENTORY_MANAGER_FIELDS . '\';'; + $tableFieldsExistStatement = $gDb->queryPrepared($sql); + + if ($tablePreferencesExistStatement->rowCount() && $tableFieldsExistStatement->rowCount()) { + $needsUpdate = $this->checkDefaultFieldsForCurrentOrg() || $this->compareVersion() || $this->compareStand(); + } else { + // Update needed because it is not installed yet + $needsUpdate = true; + } + + return $needsUpdate; + } + + /** + * Compare plugin version with the current version from the database + * + * @return bool + */ + private function compareVersion(): bool + { + global $gDb, $gCurrentOrgId; + + $plp_name = self::SHORTCUT . '__Plugininformationen__version'; + + $sql = 'SELECT plp_value FROM ' . $this->table_preferences_name . ' WHERE plp_name = ? AND (plp_org_id = ? OR plp_org_id IS NULL);'; + $statement = $gDb->queryPrepared($sql, array($plp_name, $gCurrentOrgId)); + $row = $statement->fetchObject(); + + // Compare versions + return !isset($row->plp_value) || strlen($row->plp_value) === 0 || $row->plp_value !== CPluginInfoPIM::getPluginVersion(); + } + + /** + * Compare plugin stand with the current stand from the database + * + * @return bool + */ + private function compareStand(): bool + { + global $gDb, $gCurrentOrgId; + + $plp_name = self::SHORTCUT . '__Plugininformationen__stand'; + + $sql = 'SELECT plp_value FROM ' . $this->table_preferences_name . ' WHERE plp_name = ? AND (plp_org_id = ? OR plp_org_id IS NULL);'; + $statement = $gDb->queryPrepared($sql, array($plp_name, $gCurrentOrgId)); + $row = $statement->fetchObject(); + + // Compare stands + return !isset($row->plp_value) || strlen($row->plp_value) === 0 || $row->plp_value !== CPluginInfoPIM::getPluginStand(); + } + + /** + * Checks if there are default fields for the current organization. + * + * @return bool Returns true if there are no default fields for the current organization, false otherwise. + */ + private function checkDefaultFieldsForCurrentOrg(): bool + { + global $gDb, $gCurrentOrgId; + + $sql = 'SELECT imf_name_intern FROM ' . TBL_INVENTORY_MANAGER_FIELDS . ' WHERE imf_org_id = ?;'; + $statement = $gDb->queryPrepared($sql, array($gCurrentOrgId)); + $row = $statement->fetchObject(); + + if (!$row) { + return true; + } + return false; + } + + /** + * Delete configuration data from the database + * + * @param int $deinstOrgSelect 0 = only delete data from current org, + * 1 = delete data from every org + * @return string Result message + */ + public function deleteConfigData($deinstOrgSelect): string + { + global $gDb, $gCurrentOrgId, $gL10n; + + $result = ''; + $sqlWhereCondition = ''; + + if ($deinstOrgSelect == 0) { + $sqlWhereCondition = 'AND plp_org_id = ?'; + } + + $sql = 'DELETE FROM ' . $this->table_preferences_name . ' WHERE plp_name LIKE ? ' . $sqlWhereCondition; + $params = [self::SHORTCUT . '__%']; + if ($deinstOrgSelect == 0) { + $params[] = $gCurrentOrgId; + } + $result_data = $gDb->queryPrepared($sql, $params); + $result .= ($result_data ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', array($this->table_preferences_name)) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', array($this->table_preferences_name))); + + // Check if the table is empty and can be deleted + $sql = 'SELECT * FROM ' . $this->table_preferences_name; + $statement = $gDb->queryPrepared($sql); + + if ($statement->rowCount() == 0) { + $sql = 'DROP TABLE ' . $this->table_preferences_name; + $result_db = $gDb->queryPrepared($sql); + $result .= ($result_db ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_TABLE_DELETED', array($this->table_preferences_name)) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_TABLE_DELETE_ERROR', array($this->table_preferences_name))); + } else { + $result .= $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_CONFIGTABLE_DELETE_NOTPOSSIBLE', array($this->table_preferences_name)); + } + + return $result; + } + + /** + * Delete the item data from the database + * + * @param int $deinstOrgSelect 0 = only delete data from current org, 1 = delete data from every org + * @return string $result Result message + */ + public function deleteItemData($deinstOrgSelect): string + { + global $gDb, $gCurrentOrgId, $gL10n; + $result = ''; + + if ($deinstOrgSelect == 0) { + $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_DATA . ' WHERE imd_imi_id IN (SELECT imi_id FROM ' . TBL_INVENTORY_MANAGER_ITEMS . ' WHERE imi_org_id = ?)'; + $result_data = $gDb->queryPrepared($sql, array($gCurrentOrgId)); + $result .= ($result_data ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', array(TABLE_PREFIX . '_inventory_manager_data')) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', array(TABLE_PREFIX . '_inventory_manager_data'))); + + $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_LOG . ' WHERE iml_imi_id IN (SELECT imi_id FROM ' . TBL_INVENTORY_MANAGER_ITEMS . ' WHERE imi_org_id = ?)'; + $result_log = $gDb->queryPrepared($sql, array($gCurrentOrgId)); + $result .= ($result_log ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', array(TABLE_PREFIX . '_inventory_manager_log')) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', array(TABLE_PREFIX . '_inventory_manager_log'))); + + $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_ITEMS . ' WHERE imi_org_id = ?'; + $result_items = $gDb->queryPrepared($sql, array($gCurrentOrgId)); + $result .= ($result_items ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', array(TABLE_PREFIX . '_inventory_manager_items')) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', array(TABLE_PREFIX . '_inventory_manager_items'))); + + $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_FIELDS . ' WHERE imf_org_id = ?'; + $result_fields = $gDb->queryPrepared($sql, array($gCurrentOrgId)); + $result .= ($result_fields ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', array(TABLE_PREFIX . '_inventory_manager_fields')) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', array(TABLE_PREFIX . '_inventory_manager_fields'))); + } + + // Drop tables if they are empty or if data should be deleted from every org + $table_array = array( + TBL_INVENTORY_MANAGER_FIELDS, + TBL_INVENTORY_MANAGER_DATA, + TBL_INVENTORY_MANAGER_ITEMS, + TBL_INVENTORY_MANAGER_LOG + ); + + foreach ($table_array as $table_name) { + $sql = 'SELECT * FROM ' . $table_name; + $statement = $gDb->queryPrepared($sql); + + if ($statement->rowCount() == 0 || $deinstOrgSelect == 1) { + $sql = 'DROP TABLE ' . $table_name; + $result_db = $gDb->queryPrepared($sql); + $result .= ($result_db ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_TABLE_DELETED', array($table_name)) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_TABLE_DELETE_ERROR', array($table_name))); + } else { + $result .= $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_TABLE_DELETE_NOTPOSSIBLE', array($table_name)); + } + } + + return $result; + } } diff --git a/classes/items.php b/classes/items.php index eaf280c..bc0a411 100644 --- a/classes/items.php +++ b/classes/items.php @@ -7,8 +7,8 @@ * @author MightyMCoder * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only - * - * + * + * * Methods: * __construct($database, $organizationId) : Constructor that will initialize variables and read the item field structure * setDatabase($database) : Set the database object for communication with the database of this class @@ -41,10 +41,10 @@ class CItems { - public $mItemFields = array(); ///< Array with all item fields objects - public $mChangedItemData = array(); ///< Array with all changed item data objects for notification - public $mItemData = array(); ///< Array with all item data objects - public $items = array(); ///< Array with all item objects + public $mItemFields = array(); ///< Array with all item fields objects + public $mChangedItemData = array(); ///< Array with all changed item data objects for notification + public $mItemData = array(); ///< Array with all item data objects + public $items = array(); ///< Array with all item objects private $mItemId; ///< ItemId of the current item of this object private $mDb; ///< An object of the class Database for communication with the database @@ -59,11 +59,11 @@ class CItems private $pPreferences; ///< object of the class CConfigTablePIM private $itemFieldsSort = array(); - + /** * Constructor that will initialize variables and read the item field structure - * @param \Database $database Database object (should be @b $gDb) - * @param int $organizationId The id of the organization for which the item field structure should be read + * @param \Database $database Database object (should be @b $gDb) + * @param int $organizationId The id of the organization for which the item field structure should be read */ public function __construct($database, $organizationId, $fieldsOrderBy = 'imf_id') { @@ -85,11 +85,11 @@ public function __construct($database, $organizationId, $fieldsOrderBy = 'imf_id /** * Set the database object for communication with the database of this class - * - * @param \Database $database An object of the class Database. This should be the global $gDb object + * + * @param \Database $database An object of the class Database. This should be the global $gDb object * @return void */ - public function setDatabase($database) : void + public function setDatabase($database): void { $this->mDb = $database; } @@ -97,21 +97,21 @@ public function setDatabase($database) : void /** * Called on serialization of this object. The database object could not * be serialized and should be ignored. - * + * * @return string[] Returns all class variables that should be serialized. */ public function __sleep() { return array_diff(array_keys(get_object_vars($this)), array('mDb')); } - + /** * Item data of all item fields will be initialized * the fields array will not be renewed - * + * * @return void */ - public function clearItemData() : void + public function clearItemData(): void { $this->mChangedItemData = array(); $this->mItemData = array(); @@ -124,17 +124,17 @@ public function clearItemData() : void * * @return int The ID of the item */ - public function getItemId() : int + public function getItemId(): int { return $this->mItemId; } /** * Returns the value of a column from the table adm_inventory_manager_fields for a given internal field name - * - * @param string $fieldNameIntern Expects the @b imf_name_intern of table @b adm_inventory_manager_fields - * @param string $column The column name of @b adm_inventory_manager_fields for which you want the value - * @param string $format Optional the format (is necessary for timestamps) + * + * @param string $fieldNameIntern Expects the @b imf_name_intern of table @b adm_inventory_manager_fields + * @param string $column The column name of @b adm_inventory_manager_fields for which you want the value + * @param string $format Optional the format (is necessary for timestamps) * @return array|string Returns the value for the column */ public function getProperty($fieldNameIntern, $column, $format = '') @@ -155,16 +155,16 @@ public function getProperty($fieldNameIntern, $column, $format = '') /** * Returns the value of a column from the table adm_inventory_manager_fields for a given field ID - * - * @param int $fieldId Expects the @b imf_id of table @b adm_inventory_manager_fields - * @param string $column The column name of @b adm_inventory_manager_fields for which you want the value - * @param string $format Optional the format (is necessary for timestamps) + * + * @param int $fieldId Expects the @b imf_id of table @b adm_inventory_manager_fields + * @param string $column The column name of @b adm_inventory_manager_fields for which you want the value + * @param string $format Optional the format (is necessary for timestamps) * @return string Returns the value for the column. */ - public function getPropertyById($fieldId, $column, $format = '') : string + public function getPropertyById($fieldId, $column, $format = ''): string { foreach ($this->mItemFields as $field) { - if ((int) $field->getValue('imf_id') === (int) $fieldId) { + if ((int)$field->getValue('imf_id') === (int)$fieldId) { return $field->getValue($column, $format); } } @@ -174,13 +174,13 @@ public function getPropertyById($fieldId, $column, $format = '') : string /** * Returns the list values for a given field name intern (imf_name_intern) - * - * @param string $fieldNameIntern Expects the @b imf_name_intern of table @b adm_inventory_manager_fields - * @param string $value The value to be formatted - * @param string $format Optional the format (is necessary for timestamps) + * + * @param string $fieldNameIntern Expects the @b imf_name_intern of table @b adm_inventory_manager_fields + * @param string $value The value to be formatted + * @param string $format Optional the format (is necessary for timestamps) * @return array Returns an array with the list values for the given field name intern */ - protected function getListValue($fieldNameIntern, $value, $format) : array + protected function getListValue($fieldNameIntern, $value, $format): array { $arrListValuesWithItems = array(); // array with list values and items that represents the internal value @@ -198,8 +198,7 @@ protected function getListValue($fieldNameIntern, $value, $format) : array // if there is imagefile and text separated by | then explode them if (StringUtils::strContains($listValue, '|')) { list($listValueImage, $listValueText) = explode('|', $listValue); - } - else { + } else { $listValueImage = $listValue; $listValueText = $this->getValue('usf_name'); } @@ -211,12 +210,10 @@ protected function getListValue($fieldNameIntern, $value, $format) : array // if no image is wanted then return the text part or only the position of the entry if (StringUtils::strContains($listValue, '|')) { $listValue = $listValueText; - } - else { + } else { $listValue = $item + 1; } - } - else { + } else { $listValue = Image::getIconHtml($listValueImage, $listValueText); } } @@ -235,13 +232,13 @@ protected function getListValue($fieldNameIntern, $value, $format) : array /** * Returns the value of the field in html format with consideration of all layout parameters - * - * @param string $fieldNameIntern Internal item field name of the field that should be html formatted - * @param string|int $value The value that should be formatted must be committed so that layout + * + * @param string $fieldNameIntern Internal item field name of the field that should be html formatted + * @param string|int $value The value that should be formatted must be committed so that layout * is also possible for values that aren't stored in database * @return string Returns an html formatted string that considered the profile field settings */ - public function getHtmlValue($fieldNameIntern, $value) : string + public function getHtmlValue($fieldNameIntern, $value): string { global $gSettingsManager; @@ -260,8 +257,8 @@ public function getHtmlValue($fieldNameIntern, $value) : string $htmlValue = $value == 1 ? ' - ' - : ' + ' + : ' '; @@ -273,14 +270,13 @@ public function getHtmlValue($fieldNameIntern, $value) : string if ($this->pPreferences->config['Optionen']['field_date_time_format'] === 'datetime') { //check if date is datetime or only date if (strpos($value, ' ') === false) { - $value .= ' 00:00'; + $value .= ' 00:00'; } $date = \DateTime::createFromFormat('Y-m-d H:i', $value); if ($date instanceof \DateTime) { - $htmlValue = $date->format($gSettingsManager->getString('system_date').' '.$gSettingsManager->getString('system_time')); + $htmlValue = $date->format($gSettingsManager->getString('system_date') . ' ' . $gSettingsManager->getString('system_time')); } - } - else { + } else { // check if date is date or datetime if (strpos($value, ' ') !== false) { $value = substr($value, 0, 10); @@ -304,12 +300,11 @@ public function getHtmlValue($fieldNameIntern, $value) : string foreach ($arrListValues as $index => $listValue) { // if value is imagefile or imageurl then show image if ($imfType === 'RADIO_BUTTON' && (Image::isFontAwesomeIcon($listValue) - || StringUtils::strContains($listValue, '.png', false) || StringUtils::strContains($listValue, '.jpg', false))) { + || StringUtils::strContains($listValue, '.png', false) || StringUtils::strContains($listValue, '.jpg', false))) { // if there is imagefile and text separated by | then explode them if (StringUtils::strContains($listValue, '|')) { list($listValueImage, $listValueText) = explode('|', $listValue); - } - else { + } else { $listValueImage = $listValue; $listValueText = $this->getValue('imf_name'); } @@ -330,8 +325,7 @@ public function getHtmlValue($fieldNameIntern, $value) : string if (array_key_exists($value, $arrListValuesWithItems)) { $htmlValue = $arrListValuesWithItems[$value]; - } - else { + } else { // if value is not in list then delete the value $htmlValue = ''; //'list value '.$value .' not found'; //$htmlValue = $gL10n->get('PLG_INVENTORY_MANAGER_ITEMFIELD', array($value)); @@ -345,8 +339,7 @@ public function getHtmlValue($fieldNameIntern, $value) : string } $value = $htmlValue; - } - else { + } else { // special case for type CHECKBOX and no value is there, then show unchecked checkbox if ($this->mItemFields[$fieldNameIntern]->getValue('imf_type') === 'CHECKBOX') { $value = ''; @@ -358,11 +351,11 @@ public function getHtmlValue($fieldNameIntern, $value) : string /** * Returns the item value for this column - * + * * format = 'html' : returns the value in html-format if this is necessary for that field type * format = 'database' : returns the value that is stored in database with no format applied - * @param string $fieldNameIntern Expects the @b imf_name_intern of table @b adm_inventory_manager_fields - * @param string $format Returns the field value in a special format @b text, @b html, @b database + * @param string $fieldNameIntern Expects the @b imf_name_intern of table @b adm_inventory_manager_fields + * @param string $format Returns the field value in a special format @b text, @b html, @b database * or datetime (detailed description in method description) * @return string|int|bool Returns the value for the column */ @@ -388,11 +381,10 @@ public function getValue($fieldNameIntern, $format = '') if ($this->pPreferences->config['Optionen']['field_date_time_format'] === 'datetime') { //check if date is datetime or only date if (strpos($value, ' ') === false) { - $value .= ' 00:00'; - } + $value .= ' 00:00'; + } $date = \DateTime::createFromFormat('Y-m-d H:i', $value); - } - else { + } else { // check if date is date or datetime if (strpos($value, ' ') !== false) { $value = substr($value, 0, 10); @@ -407,13 +399,11 @@ public function getValue($fieldNameIntern, $format = '') // if no format or html is set then show date format from Admidio settings if ($format === '' || $format === 'html') { if ($this->pPreferences->config['Optionen']['field_date_time_format'] === 'datetime') { - $value = $date->format($gSettingsManager->getString('system_date').' '.$gSettingsManager->getString('system_time')); - } - else { + $value = $date->format($gSettingsManager->getString('system_date') . ' ' . $gSettingsManager->getString('system_time')); + } else { $value = $date->format($gSettingsManager->getString('system_date')); } - } - else { + } else { $value = $date->format($format); } } @@ -442,11 +432,11 @@ public function getValue($fieldNameIntern, $format = '') /** * This method reads or stores the variable for showing former items. * The values will be stored in database without any inspections! - * - * @param bool|null $newValue If set, then the new value will be stored in @b showFormerItems. + * + * @param bool|null $newValue If set, then the new value will be stored in @b showFormerItems. * @return bool Returns the current value of @b showFormerItems */ - public function showFormerItems($newValue = null) : bool + public function showFormerItems($newValue = null): bool { if ($newValue !== null) { $this->showFormerItems = $newValue; @@ -457,20 +447,20 @@ public function showFormerItems($newValue = null) : bool /** * If the recordset is new and wasn't read from database or was not stored in database * then this method will return true otherwise false - * + * * @return bool Returns @b true if record is not stored in database */ - public function isNewItem() : bool + public function isNewItem(): bool { return $this->itemCreated; } /** * If the recordset was deleted from database then this method will return true otherwise false - * + * * @return bool Returns @b true if record is removed from databaseIf the recordset was deleted from database then this method will return true otherwise false */ - public function isDeletedItem() : bool + public function isDeletedItem(): bool { return $this->itemDeleted; } @@ -479,14 +469,14 @@ public function isDeletedItem() : bool * Reads the item data of all item fields out of database table @b adm_inventory_manager_data * and adds an object for each field data to the @b mItemData array. * If profile fields structure wasn't read, this will be done before. - * - * @param int $itemId The id of the item for which the item data should be read. - * @param int $organizationId The id of the organization for which the item fields + * + * @param int $itemId The id of the item for which the item data should be read. + * @param int $organizationId The id of the organization for which the item fields * structure should be read if necessary. * @return void */ - public function readItemData($itemId, $organizationId) : void - { + public function readItemData($itemId, $organizationId): void + { if (count($this->mItemFields) === 0) { $this->readItemFields($organizationId); } @@ -498,8 +488,8 @@ public function readItemData($itemId, $organizationId) : void $this->mItemId = $itemId; // read all item data - $sql = 'SELECT * FROM '.TBL_INVENTORY_MANAGER_DATA.' - INNER JOIN '.TBL_INVENTORY_MANAGER_FIELDS.' + $sql = 'SELECT * FROM ' . TBL_INVENTORY_MANAGER_DATA . ' + INNER JOIN ' . TBL_INVENTORY_MANAGER_FIELDS . ' ON imf_id = imd_imf_id WHERE imd_imi_id = ?;'; $itemDataStatement = $this->mDb->queryPrepared($sql, array($itemId)); @@ -510,18 +500,17 @@ public function readItemData($itemId, $organizationId) : void } $this->mItemData[$row['imd_imf_id']]->setArray($row); } - } - else { + } else { $this->itemCreated = true; } } /** * Save data of every item field - * + * * @return void */ - public function saveItemData() : void + public function saveItemData(): void { $this->mDb->startTransaction(); @@ -534,8 +523,7 @@ public function saveItemData() : void // if value exists and new value is empty then delete entry if ($value->getValue('imd_id') > 0 && $value->getValue('imd_value') === '') { $value->delete(); - } - else { + } else { $value->save(); } } @@ -556,21 +544,21 @@ public function saveItemData() : void /** * Reads the item fields structure out of database table @b adm_inventory_manager_fields * and adds an object for each field structure to the @b mItemFields array. - * - * @param int $organizationId The id of the organization for which the item fields + * + * @param int $organizationId The id of the organization for which the item fields * structure should be read. - * @param string $orderBy The field by which the item fields should be sorted + * @param string $orderBy The field by which the item fields should be sorted * @return void */ - public function readItemFields($organizationId, $orderBy = 'imf_id') : void + public function readItemFields($organizationId, $orderBy = 'imf_id'): void { // first initialize existing data $this->mItemFields = array(); $this->clearItemData(); - $sql = 'SELECT * FROM '.TBL_INVENTORY_MANAGER_FIELDS.' + $sql = 'SELECT * FROM ' . TBL_INVENTORY_MANAGER_FIELDS . ' WHERE (imf_org_id IS NULL OR imf_org_id = ?) - ORDER BY '. $orderBy .';'; + ORDER BY ' . $orderBy . ';'; $statement = $this->mDb->queryPrepared($sql, array($organizationId)); while ($row = $statement->fetch()) { @@ -587,18 +575,19 @@ public function readItemFields($organizationId, $orderBy = 'imf_id') : void /** * Reads the items out of database table @b adm_inventory_manager_items * and stores the values to the @b items array. - * - * @param int $organizationId The id of the organization for which the items should be read. + * + * @param int $organizationId The id of the organization for which the items should be read. * @return void */ - public function readItems($organizationId) : void + public function readItems($organizationId): void { + global $gDbType; // first initialize existing data $this->items = array(); $sqlWhereCondition = ''; if (!$this->showFormerItems) { - $sqlWhereCondition .= 'AND imi_former = 0'; + $sqlWhereCondition .= 'AND imi_former = false'; } $sql = 'SELECT DISTINCT imi_id, imi_former FROM '.TBL_INVENTORY_MANAGER_ITEMS.' @@ -617,13 +606,13 @@ public function readItems($organizationId) : void /** * Reads the items for a user out of database table @b adm_inventory_manager_items * and stores the values to the @b items array. - * - * @param int $organizationId The id of the organization for which the items should be read. - * @param int $userId The id of the user for which the items should be read. - * @param array $fieldNames The internal unique profile field names for which the items should be read + * + * @param int $organizationId The id of the organization for which the items should be read. + * @param int $userId The id of the user for which the items should be read. + * @param array $fieldNames The internal unique profile field names for which the items should be read * @return void */ - public function readItemsByUser($organizationId, $userId, $fieldNames = array('KEEPER')) : void + public function readItemsByUser($organizationId, $userId, $fieldNames = array('KEEPER')): void { // first initialize existing data $this->items = array(); @@ -638,19 +627,19 @@ public function readItemsByUser($organizationId, $userId, $fieldNames = array('K foreach ($fieldNames as $fieldNameIntern) { $sqlImfIds .= 'imf_id = ' . $this->getProperty($fieldNameIntern, 'imf_id') . ' OR '; } - $sqlImfIds = substr($sqlImfIds, 0, -4).')'; + $sqlImfIds = substr($sqlImfIds, 0, -4) . ')'; } - $sql = 'SELECT DISTINCT imi_id, imi_former FROM '.TBL_INVENTORY_MANAGER_DATA.' - INNER JOIN '.TBL_INVENTORY_MANAGER_FIELDS.' + $sql = 'SELECT DISTINCT imi_id, imi_former FROM ' . TBL_INVENTORY_MANAGER_DATA . ' + INNER JOIN ' . TBL_INVENTORY_MANAGER_FIELDS . ' ON imf_id = imd_imf_id - '. $sqlImfIds .' - INNER JOIN '.TBL_INVENTORY_MANAGER_ITEMS.' + ' . $sqlImfIds . ' + INNER JOIN ' . TBL_INVENTORY_MANAGER_ITEMS . ' ON imi_id = imd_imi_id WHERE (imi_org_id IS NULL OR imi_org_id = ?) AND imd_value = ? - '.$sqlWhereCondition.';'; + ' . $sqlWhereCondition . ';'; $statement = $this->mDb->queryPrepared($sql, array($organizationId, $userId)); while ($row = $statement->fetch()) { @@ -662,12 +651,12 @@ public function readItemsByUser($organizationId, $userId, $fieldNames = array('K * Set a new value for the item field of the table adm_inventory_manager_data. * If the user log is activated then the change of the value will be logged in @b adm_inventory_manager_log. * The value is only saved in the object. You must call the method @b save to store the new value to the database - * - * @param string $fieldNameIntern The internal unique profile field name - * @param mixed $newValue The new value that should be stored in the database field + * + * @param string $fieldNameIntern The internal unique profile field name + * @param mixed $newValue The new value that should be stored in the database field * @return bool Returns @b true if the value is stored in the current object and @b false if a check failed */ - public function setValue($fieldNameIntern, $newValue) : bool + public function setValue($fieldNameIntern, $newValue): bool { global $gSettingsManager; @@ -675,19 +664,17 @@ public function setValue($fieldNameIntern, $newValue) : bool if (!array_key_exists($imfId, $this->mItemData)) { $oldFieldValue = ''; - } - else { + } else { $oldFieldValue = $this->mItemData[$imfId]->getValue('imd_value'); } // item data from adm_inventory_manager_fields table - $newValue = (string) $newValue; + $newValue = (string)$newValue; // save old and new data for notification if (array_key_exists($imfId, $this->mItemData)) { $this->mChangedItemData[] = array($this->mItemData[$imfId]->getValue('imf_name_intern') => array('oldValue' => $oldFieldValue, 'newValue' => $newValue)); - } - else { + } else { $this->mChangedItemData[] = array($this->mItemFields[$fieldNameIntern]->getValue('imf_name_intern') => array('oldValue' => $oldFieldValue, 'newValue' => $newValue)); } @@ -697,14 +684,13 @@ public function setValue($fieldNameIntern, $newValue) : bool if ($this->pPreferences->config['Optionen']['field_date_time_format'] === 'datetime') { //check if date is datetime or only date if (strpos($newValue, ' ') === false) { - $newValue .= ' 00:00'; - } + $newValue .= ' 00:00'; + } $date = \DateTime::createFromFormat('Y-m-d H:i', $newValue); if ($date !== false) { $newValue = $date->format('Y-m-d H:i'); } - } - else { + } else { // check if date is date or datetime if (strpos($newValue, ' ') !== false) { $newValue = substr($newValue, 0, 10); @@ -747,16 +733,16 @@ public function setValue($fieldNameIntern, $newValue) : bool /** * Generates a new ItemId. The new value will be stored in mItemId. - * - * @param int $organizationId The id of the organization for which the items should be read. + * + * @param int $organizationId The id of the organization for which the items should be read. * @return int mItemId */ - public function getNewItemId($organizationId) : int + public function getNewItemId($organizationId): int { // If an error occurred while generating an item, there is an ItemId but no data for that item. // the following routine deletes these unused ItemIds - $sql = 'SELECT * FROM '.TBL_INVENTORY_MANAGER_ITEMS.' - LEFT JOIN '.TBL_INVENTORY_MANAGER_DATA.' + $sql = 'SELECT * FROM ' . TBL_INVENTORY_MANAGER_ITEMS . ' + LEFT JOIN ' . TBL_INVENTORY_MANAGER_DATA . ' ON imd_imi_id = imi_id WHERE imd_imi_id is NULL;'; $statement = $this->mDb->queryPrepared($sql); @@ -784,35 +770,35 @@ public function getNewItemId($organizationId) : int /** * delete an item - * - * @param int $itemId The id of the item that should be deleted - * @param int $organizationId The id of the organization from which the items should be deleted + * + * @param int $itemId The id of the item that should be deleted + * @param int $organizationId The id of the organization from which the items should be deleted * @return void */ - public function deleteItem($itemId, $organizationId) : void + public function deleteItem($itemId, $organizationId): void { - $sql = 'DELETE FROM '.TBL_INVENTORY_MANAGER_LOG.' WHERE iml_imi_id = ?;'; + $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_LOG . ' WHERE iml_imi_id = ?;'; $this->mDb->queryPrepared($sql, array($itemId)); - - $sql = 'DELETE FROM '.TBL_INVENTORY_MANAGER_DATA.' WHERE imd_imi_id = ?;'; + + $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_DATA . ' WHERE imd_imi_id = ?;'; $this->mDb->queryPrepared($sql, array($itemId)); - - $sql = 'DELETE FROM '.TBL_INVENTORY_MANAGER_ITEMS.' WHERE imi_id = ? AND (imi_org_id = ? OR imi_org_id IS NULL);'; + + $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_ITEMS . ' WHERE imi_id = ? AND (imi_org_id = ? OR imi_org_id IS NULL);'; $this->mDb->queryPrepared($sql, array($itemId, $organizationId)); - + $this->itemDeleted = true; } /** * Marks an item as former - * - * @param int $itemId The ID of the item to be marked as former. - * @param int $organizationId The id of the organization from which the items should be marked as former + * + * @param int $itemId The ID of the item to be marked as former. + * @param int $organizationId The id of the organization from which the items should be marked as former * @return void */ - public function makeItemFormer($itemId, $organizationId) : void + public function makeItemFormer($itemId, $organizationId): void { - $sql = 'UPDATE '.TBL_INVENTORY_MANAGER_ITEMS.' SET imi_former = 1 WHERE imi_id = ? AND (imi_org_id = ? OR imi_org_id IS NULL);'; + $sql = 'UPDATE ' . TBL_INVENTORY_MANAGER_ITEMS . ' SET imi_former = 1 WHERE imi_id = ? AND (imi_org_id = ? OR imi_org_id IS NULL);'; $this->mDb->queryPrepared($sql, array($itemId, $organizationId)); $this->itemMadeFormer = true; @@ -820,14 +806,14 @@ public function makeItemFormer($itemId, $organizationId) : void /** * Marks an item as no longer former - * - * @param int $itemId The ID of the item to be marked as no longer former. - * @param int $organizationId The id of the organization from which the items should be marked as no longer former. + * + * @param int $itemId The ID of the item to be marked as no longer former. + * @param int $organizationId The id of the organization from which the items should be marked as no longer former. * @return void */ - public function undoItemFormer($itemId, $organizationId) : void + public function undoItemFormer($itemId, $organizationId): void { - $sql = 'UPDATE '.TBL_INVENTORY_MANAGER_ITEMS.' SET imi_former = 0 WHERE imi_id = ? AND (imi_org_id = ? OR imi_org_id IS NULL);'; + $sql = 'UPDATE ' . TBL_INVENTORY_MANAGER_ITEMS . ' SET imi_former = 0 WHERE imi_id = ? AND (imi_org_id = ? OR imi_org_id IS NULL);'; $this->mDb->queryPrepared($sql, array($itemId, $organizationId)); $this->itemMadeFormer = false; @@ -835,10 +821,10 @@ public function undoItemFormer($itemId, $organizationId) : void /** * Marks an item as imported. - * + * * @return void */ - public function setImportedItem() : void + public function setImportedItem(): void { $this->itemImported = true; } @@ -848,13 +834,13 @@ public function setImportedItem() : void * to all members of the notification role. This role is configured within the global preference * **system_notifications_role**. The email contains the item name, the name of the current user, * the timestamp, and the details of the changes. - * - * @param array $importData The data of the imported items + * + * @param array $importData The data of the imported items * @return bool Returns **true** if the notification was sent * @throws AdmException 'SYS_EMAIL_NOT_SEND' * @throws Exception */ - public function sendNotification($importData = null) : bool + public function sendNotification($importData = null): bool { global $gCurrentUser, $gSettingsManager, $gL10n; @@ -864,28 +850,22 @@ public function sendNotification($importData = null) : bool if ($this->itemImported && $importData === null) { return false; - } - elseif ($this->itemImported) { + } elseif ($this->itemImported) { $messageTitleText = 'PLG_INVENTORY_MANAGER_NOTIFICATION_SUBJECT_ITEMS_IMPORTED'; $messageHead = 'PLG_INVENTORY_MANAGER_NOTIFICATION_MESSAGE_ITEMS_IMPORTED'; - } - elseif ($this->itemCreated) { + } elseif ($this->itemCreated) { $messageTitleText = 'PLG_INVENTORY_MANAGER_NOTIFICATION_SUBJECT_ITEM_CREATED'; $messageHead = 'PLG_INVENTORY_MANAGER_NOTIFICATION_MESSAGE_ITEM_CREATED'; - } - elseif ($this->itemDeleted) { + } elseif ($this->itemDeleted) { $messageTitleText = 'PLG_INVENTORY_MANAGER_NOTIFICATION_SUBJECT_ITEM_DELETED'; $messageHead = 'PLG_INVENTORY_MANAGER_NOTIFICATION_MESSAGE_ITEM_DELETED'; - } - elseif ($this->itemMadeFormer) { + } elseif ($this->itemMadeFormer) { $messageTitleText = 'PLG_INVENTORY_MANAGER_NOTIFICATION_SUBJECT_ITEM_MADE_FORMER'; $messageHead = 'PLG_INVENTORY_MANAGER_NOTIFICATION_MESSAGE_ITEM_MADE_FORMER'; - } - elseif ($this->itemChanged) { + } elseif ($this->itemChanged) { $messageTitleText = 'PLG_INVENTORY_MANAGER_NOTIFICATION_SUBJECT_ITEM_CHANGED'; $messageHead = 'PLG_INVENTORY_MANAGER_NOTIFICATION_MESSAGE_ITEM_CHANGED'; - } - else { + } else { return false; } @@ -895,8 +875,8 @@ public function sendNotification($importData = null) : bool if ($this->itemImported || $this->itemCreated || $this->itemChanged) { $format_hdr = " %s %s %s \n"; $format_row = " %s %s %s \n"; - $table_begin = "" - . ""; + $table_begin = "" + . "
"; $table_end = '

'; // create message header @@ -904,7 +884,7 @@ public function sendNotification($importData = null) : bool $message = $gL10n->get($messageHead, array($gCurrentUser->getValue('FIRST_NAME') . ' ' . $gCurrentUser->getValue('LAST_NAME'))) . '

'; $itemData = $importData; } else { - $message = $gL10n->get($messageHead, array($this->getValue('ITEMNAME','html'), $gCurrentUser->getValue('FIRST_NAME') . ' ' . $gCurrentUser->getValue('LAST_NAME'))) . '

'; + $message = $gL10n->get($messageHead, array($this->getValue('ITEMNAME', 'html'), $gCurrentUser->getValue('FIRST_NAME') . ' ' . $gCurrentUser->getValue('LAST_NAME'))) . '

'; $itemData[] = $this->mChangedItemData; } @@ -917,15 +897,14 @@ public function sendNotification($importData = null) : bool $listValues = $this->getProperty(strtoupper(str_replace('PIM_', '', $key)), 'imf_value_list'); if ($key === 'ITEMNAME') { $itemName = $value['newValue']; - } - elseif ($key === 'KEEPER') { + } elseif ($key === 'KEEPER') { $sql = getSqlOrganizationsUsersCompletePIM(); $statement = $this->mDb->query($sql); foreach ($statement->fetchAll() as $user) { $users[$user['usr_id']] = $user['name']; } - + $textOld = $gL10n->get('SYS_NO_USER_FOUND'); $textNew = ''; if ($this->itemImported) { @@ -938,8 +917,7 @@ public function sendNotification($importData = null) : bool isset($users[$value['oldValue']]) ? $users[$value['oldValue']] : $textOld, isset($users[$value['newValue']]) ? $users[$value['newValue']] : $textNew ); - } - elseif ($key === 'LAST_RECEIVER') { + } elseif ($key === 'LAST_RECEIVER') { $sql = getSqlOrganizationsUsersCompletePIM(); $statement = $this->mDb->query($sql); @@ -952,22 +930,19 @@ public function sendNotification($importData = null) : bool isset($users[$value['oldValue']]) ? $users[$value['oldValue']] : $value['oldValue'], isset($users[$value['newValue']]) ? $users[$value['newValue']] : $value['newValue'] ); - } - elseif ($key === 'IN_INVENTORY') { + } elseif ($key === 'IN_INVENTORY') { $changes[] = array( $key, $value['oldValue'] == 1 ? $gL10n->get('SYS_YES') : ($value['oldValue'] == 0 ? $gL10n->get('SYS_NO') : $value['oldValue']), $value['newValue'] == 1 ? $gL10n->get('SYS_YES') : ($value['newValue'] == 0 ? $gL10n->get('SYS_NO') : $value['newValue']) ); - } - elseif ($listValues !== '') { + } elseif ($listValues !== '') { $changes[] = array( $key, isset($listValues[$value['oldValue']]) ? $listValues[$value['oldValue']] : '', isset($listValues[$value['newValue']]) ? $listValues[$value['newValue']] : '' ); - } - else { + } else { $changes[] = array($key, $value['oldValue'], $value['newValue']); } } @@ -976,9 +951,9 @@ public function sendNotification($importData = null) : bool if ($changes) { if ($itemName === "") { - $itemName = $this->getValue('ITEMNAME','html'); + $itemName = $this->getValue('ITEMNAME', 'html'); } - $message .= '

'. $itemName . ':

'; + $message .= '

' . $itemName . ':

'; $message .= $table_begin . sprintf( $format_hdr, @@ -995,19 +970,18 @@ public function sendNotification($importData = null) : bool $changes = array(); } } - } - else { + } else { $messageUserText = 'SYS_CHANGED_BY'; $messageDateText = 'SYS_CHANGED_AT'; $message = $gL10n->get($messageHead) . '

' - . '' . $gL10n->get('PIM_ITEMNAME') . ': ' . $this->getValue('ITEMNAME','html') . '
' + . '' . $gL10n->get('PIM_ITEMNAME') . ': ' . $this->getValue('ITEMNAME', 'html') . '
' . '' . $gL10n->get($messageUserText) . ': ' . $gCurrentUser->getValue('FIRST_NAME') . ' ' . $gCurrentUser->getValue('LAST_NAME') . '
' . '' . $gL10n->get($messageDateText) . ': ' . date($gSettingsManager->getString('system_date') . ' ' . $gSettingsManager->getString('system_time')) . '
'; } - + return $notification->sendNotification( - $gL10n->get($messageTitleText, array($this->getValue('ITEMNAME','html'))), + $gL10n->get($messageTitleText, array($this->getValue('ITEMNAME', 'html'))), $message ); } diff --git a/inventory_manager.php b/inventory_manager.php index 2c77b57..7c0f4ca 100644 --- a/inventory_manager.php +++ b/inventory_manager.php @@ -391,7 +391,30 @@ } // read all keeper - $sql = 'SELECT DISTINCT imd_value, + switch ($gDbType) { + case 'pgsql': + $sql = 'SELECT DISTINCT imd_value, + CASE + WHEN imd_value = \'-1\' THEN \'n/a\' + ELSE CONCAT_WS(\', \', last_name.usd_value, first_name.usd_value) + END as keeper_name + FROM '.TBL_INVENTORY_MANAGER_DATA.' + INNER JOIN '.TBL_INVENTORY_MANAGER_FIELDS.' + ON imf_id = imd_imf_id + LEFT JOIN '. TBL_USER_DATA. ' as last_name + ON CAST(last_name.usd_usr_id AS VARCHAR)= imd_value + AND last_name.usd_usf_id = '. $gProfileFields->getProperty('LAST_NAME', 'usf_id'). ' + LEFT JOIN '. TBL_USER_DATA. ' as first_name + ON CAST(first_name.usd_usr_id AS VARCHAR)= imd_value + AND first_name.usd_usf_id = '. $gProfileFields->getProperty('FIRST_NAME', 'usf_id'). ' + WHERE (imf_org_id = '. $gCurrentOrgId .' + OR imf_org_id IS NULL) + AND imf_name_intern = \'KEEPER\' + ORDER BY keeper_name ASC;'; + break; + case 'mysql': + default: + $sql = 'SELECT DISTINCT imd_value, CASE WHEN imd_value = -1 THEN \'n/a\' ELSE CONCAT_WS(\', \', last_name.usd_value, first_name.usd_value) @@ -409,6 +432,7 @@ OR imf_org_id IS NULL) AND imf_name_intern = \'KEEPER\' ORDER BY keeper_name ASC;'; + } $form->addSelectBoxFromSql('filter_keeper',$selectBoxKeeperLabel, $gDb, $sql, array('defaultValue' => $getFilterKeeper , 'showContextDependentFirstEntry' => true)); $form->addCheckbox('show_all', $gL10n->get('PLG_INVENTORY_MANAGER_SHOW_ALL_ITEMS'), $getShowAll, array('helpTextIdLabel' => 'PLG_INVENTORY_MANAGER_SHOW_ALL_DESC')); From 8a40a0f00798b42c0fe080d695ff3a9da1b216e2 Mon Sep 17 00:00:00 2001 From: Jens Hartlep Date: Wed, 26 Feb 2025 14:03:51 +0100 Subject: [PATCH 2/2] using COALESCE instead of IFNULL and boolean(true) instead of 1 --- common_function.php | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/common_function.php b/common_function.php index 1d0ca42..06be140 100644 --- a/common_function.php +++ b/common_function.php @@ -307,16 +307,16 @@ function getPreferencePanelPIM($group, $id, $title, $icon, $body) : string */ function getSqlOrganizationsUsersCompletePIM() : string { - global $gProfileFields, $gCurrentOrgId; - - return 'SELECT usr_id, CONCAT(last_name.usd_value, \', \', first_name.usd_value, IFNULL(CONCAT(\', \', postcode.usd_value),\'\'), IFNULL(CONCAT(\' \', city.usd_value),\'\'), IFNULL(CONCAT(\', \', street.usd_value),\'\') ) as name - FROM ' . TBL_USERS . ' - JOIN ' . TBL_USER_DATA . ' as last_name ON last_name.usd_usr_id = usr_id AND last_name.usd_usf_id = ' . $gProfileFields->getProperty('LAST_NAME', 'usf_id') . ' - JOIN ' . TBL_USER_DATA . ' as first_name ON first_name.usd_usr_id = usr_id AND first_name.usd_usf_id = ' . $gProfileFields->getProperty('FIRST_NAME', 'usf_id') . ' - LEFT JOIN ' . TBL_USER_DATA . ' as postcode ON postcode.usd_usr_id = usr_id AND postcode.usd_usf_id = ' . $gProfileFields->getProperty('POSTCODE', 'usf_id') . ' - LEFT JOIN ' . TBL_USER_DATA . ' as city ON city.usd_usr_id = usr_id AND city.usd_usf_id = ' . $gProfileFields->getProperty('CITY', 'usf_id') . ' - LEFT JOIN ' . TBL_USER_DATA . ' as street ON street.usd_usr_id = usr_id AND street.usd_usf_id = ' . $gProfileFields->getProperty('ADDRESS', 'usf_id') . ' - WHERE usr_valid = 1 AND EXISTS (SELECT 1 FROM ' . TBL_MEMBERS . ', ' . TBL_ROLES . ', ' . TBL_CATEGORIES . ' WHERE mem_usr_id = usr_id AND mem_rol_id = rol_id AND mem_begin <= \'' . DATE_NOW . '\' AND mem_end > \'' . DATE_NOW . '\' AND rol_valid = 1 AND rol_cat_id = cat_id AND (cat_org_id = ' . $gCurrentOrgId . ' OR cat_org_id IS NULL)) ORDER BY last_name.usd_value, first_name.usd_value;'; + global $gProfileFields, $gCurrentOrgId; + + return 'SELECT usr_id, CONCAT(last_name.usd_value, \', \', first_name.usd_value, COALESCE(CONCAT(\', \', postcode.usd_value),\'\'), COALESCE(CONCAT(\' \', city.usd_value),\'\'), COALESCE(CONCAT(\', \', street.usd_value),\'\') ) as name + FROM ' . TBL_USERS . ' + JOIN ' . TBL_USER_DATA . ' as last_name ON last_name.usd_usr_id = usr_id AND last_name.usd_usf_id = ' . $gProfileFields->getProperty('LAST_NAME', 'usf_id') . ' + JOIN ' . TBL_USER_DATA . ' as first_name ON first_name.usd_usr_id = usr_id AND first_name.usd_usf_id = ' . $gProfileFields->getProperty('FIRST_NAME', 'usf_id') . ' + LEFT JOIN ' . TBL_USER_DATA . ' as postcode ON postcode.usd_usr_id = usr_id AND postcode.usd_usf_id = ' . $gProfileFields->getProperty('POSTCODE', 'usf_id') . ' + LEFT JOIN ' . TBL_USER_DATA . ' as city ON city.usd_usr_id = usr_id AND city.usd_usf_id = ' . $gProfileFields->getProperty('CITY', 'usf_id') . ' + LEFT JOIN ' . TBL_USER_DATA . ' as street ON street.usd_usr_id = usr_id AND street.usd_usf_id = ' . $gProfileFields->getProperty('ADDRESS', 'usf_id') . ' + WHERE usr_valid = true AND EXISTS (SELECT 1 FROM ' . TBL_MEMBERS . ', ' . TBL_ROLES . ', ' . TBL_CATEGORIES . ' WHERE mem_usr_id = usr_id AND mem_rol_id = rol_id AND mem_begin <= \'' . DATE_NOW . '\' AND mem_end > \'' . DATE_NOW . '\' AND rol_valid = true AND rol_cat_id = cat_id AND (cat_org_id = ' . $gCurrentOrgId . ' OR cat_org_id IS NULL)) ORDER BY last_name.usd_value, first_name.usd_value;'; } /** @@ -326,11 +326,11 @@ function getSqlOrganizationsUsersCompletePIM() : string */ function getSqlOrganizationsUsersShortPIM() : string { - global $gProfileFields, $gCurrentOrgId; + global $gProfileFields, $gCurrentOrgId; - return 'SELECT usr_id, CONCAT(last_name.usd_value, \', \', first_name.usd_value) as name - FROM ' . TBL_USERS . ' - JOIN ' . TBL_USER_DATA . ' as last_name ON last_name.usd_usr_id = usr_id AND last_name.usd_usf_id = ' . $gProfileFields->getProperty('LAST_NAME', 'usf_id') . ' - JOIN ' . TBL_USER_DATA . ' as first_name ON first_name.usd_usr_id = usr_id AND first_name.usd_usf_id = ' . $gProfileFields->getProperty('FIRST_NAME', 'usf_id') . ' - WHERE usr_valid = 1 AND EXISTS (SELECT 1 FROM ' . TBL_MEMBERS . ', ' . TBL_ROLES . ', ' . TBL_CATEGORIES . ' WHERE mem_usr_id = usr_id AND mem_rol_id = rol_id AND mem_begin <= \'' . DATE_NOW . '\' AND mem_end > \'' . DATE_NOW . '\' AND rol_valid = 1 AND rol_cat_id = cat_id AND (cat_org_id = ' . $gCurrentOrgId . ' OR cat_org_id IS NULL)) ORDER BY last_name.usd_value, first_name.usd_value;'; + return 'SELECT usr_id, CONCAT(last_name.usd_value, \', \', first_name.usd_value) as name + FROM ' . TBL_USERS . ' + JOIN ' . TBL_USER_DATA . ' as last_name ON last_name.usd_usr_id = usr_id AND last_name.usd_usf_id = ' . $gProfileFields->getProperty('LAST_NAME', 'usf_id') . ' + JOIN ' . TBL_USER_DATA . ' as first_name ON first_name.usd_usr_id = usr_id AND first_name.usd_usf_id = ' . $gProfileFields->getProperty('FIRST_NAME', 'usf_id') . ' + WHERE usr_valid = true AND EXISTS (SELECT 1 FROM ' . TBL_MEMBERS . ', ' . TBL_ROLES . ', ' . TBL_CATEGORIES . ' WHERE mem_usr_id = usr_id AND mem_rol_id = rol_id AND mem_begin <= \'' . DATE_NOW . '\' AND mem_end > \'' . DATE_NOW . '\' AND rol_valid = true AND rol_cat_id = cat_id AND (cat_org_id = ' . $gCurrentOrgId . ' OR cat_org_id IS NULL)) ORDER BY last_name.usd_value, first_name.usd_value;'; }