From 81e95d99d2e23ba6b4e65e0cccf142bfed6b25be Mon Sep 17 00:00:00 2001 From: MightyMCoder <130976036+MightyMCoder@users.noreply.github.com> Date: Fri, 24 Jan 2025 20:47:26 +0100 Subject: [PATCH] improved code documentation, refactoring, small changes --- classes/configdata.php | 26 +-- classes/configtable.php | 165 +++++++++----- classes/items.php | 137 +++++++---- common_function.php | 150 ++++++------ fields/fields.php | 27 ++- fields/fields_delete.php | 127 ++++------- fields/fields_edit_new.php | 36 +-- fields/fields_function.php | 73 ++++-- import/import_column_config.php | 102 +++++---- import/import_items.php | 66 +++--- import/import_read_file.php | 3 +- inventory_manager.php | 212 ++++++++++------- inventory_manager_profile_addin.php | 114 ++++++---- items/items_delete.php | 79 ++++--- items/items_edit_new.php | 19 +- items/items_export_to_pff.php | 4 +- items/items_history.php | 12 +- items/items_save.php | 16 +- preferences/preferences.php | 77 +++---- preferences/preferences_check_for_update.php | 227 +++++++++---------- preferences/preferences_function.php | 31 ++- 21 files changed, 965 insertions(+), 738 deletions(-) diff --git a/classes/configdata.php b/classes/configdata.php index bfbda70..e745e08 100644 --- a/classes/configdata.php +++ b/classes/configdata.php @@ -26,36 +26,36 @@ class CConfigDataPIM /** * Default configuration data for plugin InventoryManager */ - const CONFIG_DEFAULT = [ - 'Optionen' => [ + const CONFIG_DEFAULT = array( + 'Optionen' => array( 'interface_pff' => 0, - 'profile_addin' => [ + 'profile_addin' => array( 'ITEMNAME', 'LAST_RECEIVER' - ], + ), 'file_name' => 'InventoryManager', 'add_date' => 0, 'allow_keeper_edit' => 0, - 'allowed_keeper_edit_fields' => [ + 'allowed_keeper_edit_fields' => array( 'IN_INVENTORY', 'LAST_RECEIVER', 'RECEIVED_ON', 'RECEIVED_BACK_ON' - ], + ), 'current_user_default_keeper' => 0, 'allow_negative_numbers' => 1, 'decimal_step' => 0.1, 'field_date_time_format' => 'date', - ], - 'Plugininformationen' => [ + ), + 'Plugininformationen' => array( 'version' => '', 'beta-version' => '', 'stand' => '', - ], - 'access' => [ - 'preferences' => [] - ] - ]; + ), + 'access' => array( + 'preferences' => array(0) + ) + ); /** * Database token for plugin InventoryManager diff --git a/classes/configtable.php b/classes/configtable.php index e4d80e4..27db19a 100644 --- a/classes/configtable.php +++ b/classes/configtable.php @@ -8,17 +8,33 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * - * methods: * + * Methods: + * __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 + * 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 + * 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 + * 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 + * 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 + * 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 + * 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 - * *********************************************************************************************** */ @@ -49,9 +65,10 @@ public function __construct() /** * Checks if the plugin FormFiller is installed + * * @return void */ - private function checkPffInst() + private function checkPffInst() : void { global $gDb, $gCurrentOrgId; @@ -75,18 +92,20 @@ private function checkPffInst() /** * If the plugin FormFiller is installed * then this method will return true otherwise false - * @return bool Returns @b true if plugin FormFiller is installed + * + * @return bool Returns @b true if plugin FormFiller is installed */ - public function isPffInst() + public function isPffInst() : bool { return $this->isPffInst; } /** * Checks if a FormFiller directory exists + * * @return void */ - private function findPff() + private function findPff() : void { $location = ADMIDIO_PATH . FOLDER_PLUGINS; $searchedFile = 'formfiller.php'; @@ -120,7 +139,8 @@ private function findPff() /** * Returns the Plugin FormFiller directory - * @return bool/string Returns the FormFiller directory otherwise false + * + * @return bool/string Returns the FormFiller directory otherwise false */ public function pffDir() { @@ -129,9 +149,10 @@ public function pffDir() /** * checks if the configuration table exists, if necessarry creats it and fills it with default configuration data + * * @return void */ - public function init() + public function init() : void { $this->createTablesIfNotExist(); $this->initializeDefaultFieldsByOrgId(); @@ -140,9 +161,10 @@ public function init() /** * Creates the necessary tables if they do not exist + * * @return void */ - private function createTablesIfNotExist() + private function createTablesIfNotExist() : void { $this->createTableIfNotExist(TBL_INVENTORY_MANAGER_FIELDS, ' imf_id int(10) unsigned NOT NULL AUTO_INCREMENT, @@ -204,11 +226,12 @@ private function createTablesIfNotExist() /** * 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 + * + * @param string $tableName The name of the table + * @param string $tableDefinition The SQL definition of the table * @return void */ - private function createTableIfNotExist($tableName, $tableDefinition) + private function createTableIfNotExist($tableName, $tableDefinition) : void { global $gDb; @@ -223,9 +246,10 @@ private function createTableIfNotExist($tableName, $tableDefinition) /** * Initializes default fields in the inventory manager database + * * @return void */ - private function initializeDefaultFieldsByOrgId() + private function initializeDefaultFieldsByOrgId() : void { global $gDb, $gCurrentOrgId; @@ -393,17 +417,18 @@ private function initializeDefaultFieldsByOrgId() /** * 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 + * + * @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 = '') + private function createField($name, $internalName, $type, $description, $sequence, $system, $mandatory, $valueList = '') : void { global $gDb, $gCurrentOrgId; @@ -422,9 +447,10 @@ private function createField($name, $internalName, $type, $description, $sequenc /** * Initializes preferences for the inventory manager + * * @return void */ - private function initializePreferencesByOrgId() + private function initializePreferencesByOrgId() : void { global $gDb, $gCurrentOrgId; @@ -466,9 +492,10 @@ private function initializePreferencesByOrgId() /** * Writes the configuration data of plugin InventoryManager to the database + * * @return void */ - public function write() + public function write() : void { global $gDb, $gCurrentOrgId; @@ -489,7 +516,8 @@ public function write() // 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 { + } + 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)); @@ -500,32 +528,43 @@ public function write() /** * Reads the configuration data of plugin InventoryManager from the database - * @return void + * + * @return bool */ - public function read() + public function read() : bool { - $this->readConfigData(self::SHORTCUT, $this->config); + return $this->readConfigData(self::SHORTCUT, $this->config); } /** * Reads the configuration data of plugin FormFiller (PFF) from the database - * @return void + * + * @return bool */ - public function readPff() + public function readPff() : bool { - $this->readConfigData('PFF', $this->configPff); + 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 void + * + * @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) + 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)); @@ -564,13 +603,15 @@ private function readConfigData($pluginShortcut, &$configArray) } } } + return true; } /** * Compare plugin version and stand with current version and stand from database + * * @return bool */ - public function checkForUpdate() + public function checkForUpdate() : bool { global $gDb; @@ -595,9 +636,10 @@ public function checkForUpdate() /** * Compare plugin version with the current version from the database + * * @return bool */ - private function compareVersion() + private function compareVersion() : bool { global $gDb, $gCurrentOrgId; @@ -613,9 +655,10 @@ private function compareVersion() /** * Compare plugin stand with the current stand from the database + * * @return bool */ - private function compareStand() + private function compareStand() : bool { global $gDb, $gCurrentOrgId; @@ -631,9 +674,10 @@ private function compareStand() /** * 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. + * + * @return bool Returns true if there are no default fields for the current organization, false otherwise. */ - private function checkDefaultFieldsForCurrentOrg() + private function checkDefaultFieldsForCurrentOrg() : bool { global $gDb, $gCurrentOrgId; @@ -649,10 +693,12 @@ private function checkDefaultFieldsForCurrentOrg() /** * 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 Result message + * + * @param int $deinstOrgSelect 0 = only delete data from current org, + * 1 = delete data from every org + * @return string Result message */ - public function deleteConfigData($deinstOrgSelect) + public function deleteConfigData($deinstOrgSelect) : string { global $gDb, $gCurrentOrgId, $gL10n; @@ -669,7 +715,7 @@ public function deleteConfigData($deinstOrgSelect) $params[] = $gCurrentOrgId; } $result_data = $gDb->queryPrepared($sql, $params); - $result .= ($result_data ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', [$this->table_preferences_name]) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', [$this->table_preferences_name])); + $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; @@ -678,9 +724,9 @@ public function deleteConfigData($deinstOrgSelect) 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', [$this->table_preferences_name]) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_TABLE_DELETE_ERROR', [$this->table_preferences_name])); + $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', [$this->table_preferences_name]); + $result .= $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_CONFIGTABLE_DELETE_NOTPOSSIBLE', array($this->table_preferences_name)); } return $result; @@ -688,39 +734,40 @@ public function deleteConfigData($deinstOrgSelect) /** * 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) + 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, [$gCurrentOrgId]); - $result .= ($result_data ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', [TABLE_PREFIX . '_inventory_manager_data']) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', [TABLE_PREFIX . '_inventory_manager_data'])); + $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, [$gCurrentOrgId]); - $result .= ($result_log ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', [TABLE_PREFIX . '_inventory_manager_log']) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', [TABLE_PREFIX . '_inventory_manager_log'])); + $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, [$gCurrentOrgId]); - $result .= ($result_items ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', [TABLE_PREFIX . '_inventory_manager_items']) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', [TABLE_PREFIX . '_inventory_manager_items'])); + $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, [$gCurrentOrgId]); - $result .= ($result_fields ? $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN', [TABLE_PREFIX . '_inventory_manager_fields']) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_DATA_DELETED_IN_ERROR', [TABLE_PREFIX . '_inventory_manager_fields'])); + $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 = [ + $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; @@ -729,9 +776,9 @@ public function deleteItemData($deinstOrgSelect) 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', [$table_name]) : $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_TABLE_DELETE_ERROR', [$table_name])); + $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', [$table_name]); + $result .= $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_TABLE_DELETE_NOTPOSSIBLE', array($table_name)); } } diff --git a/classes/items.php b/classes/items.php index ff05218..eaf280c 100644 --- a/classes/items.php +++ b/classes/items.php @@ -8,31 +8,33 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * - * methods: * + * 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 * __sleep() : Called on serialization of this object. The database object could not be serialized and should be ignored * clearItemData() : Item data of all item fields will be initialized + * getItemId() : Retrieves the ID of the item * getProperty($fieldNameIntern, $column, $format = '') : Returns the value of a column from the table adm_inventory_manager_fields for a given internal field name * getPropertyById($fieldId, $column, $format = '') : Returns the value of a column from the table adm_inventory_manager_fields for a given field ID * getListValue($fieldNameIntern, $value, $format) : Returns the list values for a given field name intern (imf_name_intern) - * getHtmlValue($fieldNameIntern, $value,) : Returns the value of the field in html format with consideration of all layout parameters + * getHtmlValue($fieldNameIntern, $value) : Returns the value of the field in html format with consideration of all layout parameters * getValue($fieldNameIntern, $format = '') : Returns the item value for this column * showFormerItems($newValue = null) : This method reads or stores the variable for showing former items * isNewItem() : 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 * isDeletedItem() : If the recordset was deleted from database then this method will return true otherwise false * readItemData($itemId, $organizationId) : Reads the item data of all item fields out of database table adm_inventory_manager_data * saveItemData() : Save data of every item field - * readItemFields($organizationId) : Reads the item fields structure out of database table adm_inventory_manager_fields + * readItemFields($organizationId, $orderBy = 'imf_id') : Reads the item fields structure out of database table adm_inventory_manager_fields * readItems($organizationId) : Reads the items out of database table adm_inventory_manager_items - * readItemsByUser($organizationId, $userId) : Reads the items for a user out of database table adm_inventory_manager_items + * readItemsByUser($organizationId, $userId, $fieldNames) : Reads the items for a user out of database table adm_inventory_manager_items * setValue($fieldNameIntern, $newValue) : Set a new value for the item field of the table adm_inventory_manager_data * getNewItemId($organizationId) : Generates a new ItemId. The new value will be stored in mItemId * deleteItem($itemId, $organizationId) : Deletes an item from the database * makeItemFormer($itemId, $organizationId) : Marks an item as former in the database - * sendNotification($organizationId) : Sends a notification to all users that have the right to see the item - * + * undoItemFormer($itemId, $organizationId) : Marks an item as no longer former in the database + * setImportedItem() : Marks an item as imported + * sendNotification($importData = null) : Sends a notification to all users that have the right to see the item *********************************************************************************************** */ require_once(__DIR__ . '/configtable.php'); @@ -82,10 +84,12 @@ 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. + * 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 + * @return void */ - public function setDatabase($database) + public function setDatabase($database) : void { $this->mDb = $database; } @@ -93,6 +97,7 @@ public function setDatabase($database) /** * 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() @@ -103,8 +108,10 @@ public function __sleep() /** * Item data of all item fields will be initialized * the fields array will not be renewed + * + * @return void */ - public function clearItemData() + public function clearItemData() : void { $this->mChangedItemData = array(); $this->mItemData = array(); @@ -113,21 +120,22 @@ public function clearItemData() } /** - * Retrieves the ID of the item. + * Retrieves the ID of the item * - * @return int The ID of the item. + * @return int The ID of the item */ - public function getItemId() + 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. + * 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) - * @return array|string Returns the value for the column. + * @return array|string Returns the value for the column */ public function getProperty($fieldNameIntern, $column, $format = '') { @@ -147,12 +155,13 @@ 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) * @return string Returns the value for the column. */ - public function getPropertyById($fieldId, $column, $format = '') + public function getPropertyById($fieldId, $column, $format = '') : string { foreach ($this->mItemFields as $field) { if ((int) $field->getValue('imf_id') === (int) $fieldId) { @@ -164,13 +173,14 @@ public function getPropertyById($fieldId, $column, $format = '') } /** - * Returns the list values for a given field name intern (imf_name_intern). + * 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) - * @return array Returns an array with the list values for the given field name intern. + * @return array Returns an array with the list values for the given field name intern */ - protected function getListValue($fieldNameIntern, $value, $format) + protected function getListValue($fieldNameIntern, $value, $format) : array { $arrListValuesWithItems = array(); // array with list values and items that represents the internal value @@ -225,12 +235,13 @@ protected function getListValue($fieldNameIntern, $value, $format) /** * 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 * 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) + public function getHtmlValue($fieldNameIntern, $value) : string { global $gSettingsManager; @@ -255,6 +266,7 @@ public function getHtmlValue($fieldNameIntern, $value) '; break; + case 'DATE': if ($value !== '') { // date must be formatted @@ -280,6 +292,7 @@ public function getHtmlValue($fieldNameIntern, $value) } } break; + case 'DROPDOWN': case 'RADIO_BUTTON': $arrListValuesWithItems = array(); // array with list values and items that represents the internal value @@ -317,13 +330,15 @@ public function getHtmlValue($fieldNameIntern, $value) 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)); } break; + case 'TEXT_BIG': $htmlValue = nl2br($value); break; @@ -343,12 +358,13 @@ public function getHtmlValue($fieldNameIntern, $value) /** * 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 * or datetime (detailed description in method description) - * @return string|int|bool Returns the value for the column. + * @return string|int|bool Returns the value for the column */ public function getValue($fieldNameIntern, $format = '') { @@ -396,11 +412,13 @@ public function getValue($fieldNameIntern, $format = '') else { $value = $date->format($gSettingsManager->getString('system_date')); } - } else { + } + else { $value = $date->format($format); } } break; + case 'DROPDOWN': case 'RADIO_BUTTON': // the value in db is only the position, now search for the text @@ -424,10 +442,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. * @return bool Returns the current value of @b showFormerItems */ - public function showFormerItems($newValue = null) + public function showFormerItems($newValue = null) : bool { if ($newValue !== null) { $this->showFormerItems = $newValue; @@ -438,18 +457,20 @@ public function showFormerItems($newValue = null) /** * 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() + 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() + public function isDeletedItem() : bool { return $this->itemDeleted; } @@ -458,11 +479,13 @@ public function isDeletedItem() * 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 * structure should be read if necessary. + * @return void */ - public function readItemData($itemId, $organizationId) + public function readItemData($itemId, $organizationId) : void { if (count($this->mItemFields) === 0) { $this->readItemFields($organizationId); @@ -495,8 +518,10 @@ public function readItemData($itemId, $organizationId) /** * Save data of every item field + * + * @return void */ - public function saveItemData() + public function saveItemData() : void { $this->mDb->startTransaction(); @@ -531,10 +556,13 @@ public function saveItemData() /** * 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 * structure should be read. + * @param string $orderBy The field by which the item fields should be sorted + * @return void */ - public function readItemFields($organizationId, $orderBy = 'imf_id') + public function readItemFields($organizationId, $orderBy = 'imf_id') : void { // first initialize existing data $this->mItemFields = array(); @@ -559,9 +587,11 @@ public function readItemFields($organizationId, $orderBy = 'imf_id') /** * 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. + * @return void */ - public function readItems($organizationId) + public function readItems($organizationId) : void { // first initialize existing data $this->items = array(); @@ -587,11 +617,13 @@ public function readItems($organizationId) /** * 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 string[] $fieldNames field names that 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')) + public function readItemsByUser($organizationId, $userId, $fieldNames = array('KEEPER')) : void { // first initialize existing data $this->items = array(); @@ -630,11 +662,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 * @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) + public function setValue($fieldNameIntern, $newValue) : bool { global $gSettingsManager; @@ -713,11 +746,12 @@ public function setValue($fieldNameIntern, $newValue) } /** - * Generates a new ItemId. The new value will be stored in @b mItemId. + * 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. - * @return int @b mItemId + * @return int mItemId */ - public function getNewItemId($organizationId) + 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 @@ -750,10 +784,12 @@ public function getNewItemId($organizationId) /** * 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 + * @return void */ - public function deleteItem($itemId, $organizationId) + public function deleteItem($itemId, $organizationId) : void { $sql = 'DELETE FROM '.TBL_INVENTORY_MANAGER_LOG.' WHERE iml_imi_id = ?;'; $this->mDb->queryPrepared($sql, array($itemId)); @@ -768,12 +804,14 @@ public function deleteItem($itemId, $organizationId) } /** - * Marks an item as former. + * 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 + * @return void */ - public function makeItemFormer($itemId, $organizationId) { - + 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);'; $this->mDb->queryPrepared($sql, array($itemId, $organizationId)); @@ -781,11 +819,14 @@ public function makeItemFormer($itemId, $organizationId) { } /** - * Marks an item as no longer former. + * 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. + * @return void */ - public function undoItemFormer($itemId, $organizationId) { + 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);'; $this->mDb->queryPrepared($sql, array($itemId, $organizationId)); @@ -794,8 +835,11 @@ public function undoItemFormer($itemId, $organizationId) { /** * Marks an item as imported. + * + * @return void */ - public function setImportedItem() { + public function setImportedItem() : void + { $this->itemImported = true; } @@ -804,14 +848,15 @@ public function setImportedItem() { * 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 int $organizationId The id of the organization from which the notifications should be sent + * + * @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($organizationId, $importData = null): bool + public function sendNotification($importData = null) : bool { - global $gProfileFields, $gCurrentUser, $gSettingsManager, $gL10n; + global $gCurrentUser, $gSettingsManager, $gL10n; // check if notifications are enabled if ($gSettingsManager->getBool('system_notifications_new_entries')) { diff --git a/common_function.php b/common_function.php index bce5ff0..1d0ca42 100644 --- a/common_function.php +++ b/common_function.php @@ -9,33 +9,37 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * - * methods: * - * defineConstantsPIM() : Define necessary constants if not already defined - * isUserAuthorizedForPIM($scriptName) : Check if the user is authorized to access the plugin - * getMenuIdByScriptNamePIM($scriptName) : Get menu ID by script name - * isUserAuthorizedForPreferencesPIM() : Check if the user is authorized to access the Preferences module - * function isUserAuthorizedForAddinPIM() : Check if the user is authorized to see the Inventory Manager Addin on the profile page - * convlanguagePIM($field_name) : Translate field name according to naming conventions - * getNewNameInternPIM($name, $index) : Generate a new internal name - * genNewSequencePIM() : Generate a new sequence number - * umlautePIM($tmptext) : Replace umlauts in the text + * Methods: + * defineConstantsPIM() : Define necessary constants if not already defined + * isUserAuthorizedForPIM($scriptName) : Check if the user is authorized to access the plugin + * isUserAuthorizedForPreferencesPIM() : Check if the user is authorized to access the Preferences module + * isUserAuthorizedForAddinPIM() : Check if the user is authorized to see the + * Inventory Manager Addin on the profile page + * isKeeperAuthorizedToEdit($keeper) : Check if the keeper is authorized to edit spezific item data + * getMenuIdByScriptNamePIM($scriptName) : Get menu ID by script name + * convlanguagePIM($field_name) : Translate field name according to naming conventions + * getNewNameInternPIM($name, $index) : Generate a new internal name + * genNewSequencePIM() : Generate a new sequence number + * umlautePIM($tmptext) : Replace umlauts in the text * getPreferencePanelPIM($group, $id, $title, $icon, $body) : Generate HTML for a preference panel - * + * getSqlOrganizationsUsersCompletePIM() : Get all users with their id, name, and address + * getSqlOrganizationsUsersShortPIM() : Get all users with their id and name *********************************************************************************************** */ require_once(__DIR__ . '/../../adm_program/system/common.php'); +// Define necessary constants if not already defined defineConstantsPIM(); /** * Define necessary constants if not already defined + * + * @return void */ -function defineConstantsPIM() +function defineConstantsPIM() : void { - global $g_tbl_praefix; - if (!defined('PLUGIN_FOLDER_IM')) { define('PLUGIN_FOLDER_IM', '/' . basename(__DIR__)); } @@ -55,10 +59,11 @@ function defineConstantsPIM() /** * Check if the user is authorized to access the plugin + * * @param string $scriptName The script name of the plugin * @return bool true if the user is authorized */ -function isUserAuthorizedForPIM($scriptName) +function isUserAuthorizedForPIM($scriptName) : bool { global $gMessage, $gL10n, $gDb, $gCurrentUser; $gCurrentUser = $GLOBALS['gCurrentUser']; @@ -88,29 +93,12 @@ function isUserAuthorizedForPIM($scriptName) return $userIsAuthorized; } -/** - * Get menu ID by script name - * @param string $scriptName The script name of the plugin - * @return int|null The menu ID or null if not found - */ -function getMenuIdByScriptNamePIM($scriptName) -{ - global $gDb; - - $sql = 'SELECT men_id FROM ' . TBL_MENU . ' WHERE men_url = ?;'; - $menuStatement = $gDb->queryPrepared($sql, array($scriptName)); - - if ($menuStatement->rowCount() === 1) { - return (int)$menuStatement->fetch()['men_id']; - } - return null; -} - /** * Check if the user is authorized to access the Preferences module + * * @return bool true if the user is authorized */ -function isUserAuthorizedForPreferencesPIM() +function isUserAuthorizedForPreferencesPIM() : bool { global $pPreferences, $gCurrentUser; $gCurrentUser = $GLOBALS['gCurrentUser']; @@ -127,32 +115,12 @@ function isUserAuthorizedForPreferencesPIM() return false; } - -/** - * Check if the keeper is authorized to edit spezific item data - * - * @param int|null $keeper The user ID of the keeper. - * @return bool Returns true if the current user is authorized, otherwise false. - */ -function isKeeperAuthorizedToEdit(int $keeper = null) -{ - global $pPreferences, $gCurrentUser; - $gCurrentUser = $GLOBALS['gCurrentUser']; - - if ($pPreferences->config['Optionen']['allow_keeper_edit'] === 1) { - if (isset($keeper) && $keeper === $gCurrentUser->getValue('usr_id')) { - return true; - } - } - - return false; -} - /** * Check if the user is authorized to see the Inventory Manager Addin on the profile page + * * @return bool true if the user is authorized */ -function isUserAuthorizedForAddinPIM() +function isUserAuthorizedForAddinPIM() : bool { global $gDb; @@ -186,12 +154,52 @@ function isUserAuthorizedForAddinPIM() return false; } +/** + * Check if the keeper is authorized to edit spezific item data + * + * @param int|null $keeper The user ID of the keeper + * @return bool true if the keeper is authorized + */ +function isKeeperAuthorizedToEdit(int $keeper = null) : bool +{ + global $pPreferences, $gCurrentUser; + $gCurrentUser = $GLOBALS['gCurrentUser']; + + if ($pPreferences->config['Optionen']['allow_keeper_edit'] === 1) { + if (isset($keeper) && $keeper === $gCurrentUser->getValue('usr_id')) { + return true; + } + } + + return false; +} + +/** + * Get menu ID by script name + * + * @param string $scriptName The script name of the plugin + * @return int|null The menu ID or null if not found + */ +function getMenuIdByScriptNamePIM($scriptName) : ?int +{ + global $gDb; + + $sql = 'SELECT men_id FROM ' . TBL_MENU . ' WHERE men_url = ?;'; + $menuStatement = $gDb->queryPrepared($sql, array($scriptName)); + + if ($menuStatement->rowCount() === 1) { + return (int)$menuStatement->fetch()['men_id']; + } + return null; +} + /** * Translate field name according to naming conventions + * * @param string $field_name field name to translate * @return string translated field name */ -function convlanguagePIM($field_name) +function convlanguagePIM($field_name) : string { global $gL10n; @@ -200,11 +208,12 @@ function convlanguagePIM($field_name) /** * Generate a new internal name + * * @param string $name name to generate internal name from * @param int $index index to append to the internal name * @return string new internal name */ -function getNewNameInternPIM($name, $index) +function getNewNameInternPIM($name, $index) : string { global $gDb; @@ -227,9 +236,10 @@ function getNewNameInternPIM($name, $index) /** * Generate a new sequence number + * * @return int new sequence number */ -function genNewSequencePIM() +function genNewSequencePIM() : int { global $gDb, $gCurrentOrgId; @@ -242,10 +252,11 @@ function genNewSequencePIM() /** * Replace umlauts in the text + * * @param string $tmptext text to replace umlauts in * @return string text with replaced umlauts */ -function umlautePIM($tmptext) +function umlautePIM($tmptext) : string { $replacements = [ 'ü' => 'ue', @@ -265,6 +276,7 @@ function umlautePIM($tmptext) /** * Generate HTML for a preference panel + * * @param string $group group the preference panel belongs to * @param string $id unique ID of the preference panel * @param string $title title of the preference panel @@ -272,7 +284,7 @@ function umlautePIM($tmptext) * @param string $body body of the preference panel * @return string HTML for the preference panel */ -function getPreferencePanelPIM($group, $id, $title, $icon, $body) +function getPreferencePanelPIM($group, $id, $title, $icon, $body) : string { return '
@@ -288,7 +300,12 @@ function getPreferencePanelPIM($group, $id, $title, $icon, $body) '; } -function getSqlOrganizationsUsersCompletePIM() +/** + * Get all users with their id, name, and address + * + * @return string SQL query to get all users with their ID and name + */ +function getSqlOrganizationsUsersCompletePIM() : string { global $gProfileFields, $gCurrentOrgId; @@ -302,7 +319,12 @@ function getSqlOrganizationsUsersCompletePIM() 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;'; } -function getSqlOrganizationsUsersShortPIM() +/** + * Get all users with their id and name + * + * @return string SQL query to get all users with their ID and name + */ +function getSqlOrganizationsUsersShortPIM() : string { global $gProfileFields, $gCurrentOrgId; @@ -311,4 +333,4 @@ function getSqlOrganizationsUsersShortPIM() 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;'; -} \ No newline at end of file +} diff --git a/fields/fields.php b/fields/fields.php index 576a85c..118ac41 100644 --- a/fields/fields.php +++ b/fields/fields.php @@ -8,11 +8,11 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * - * Parameters: * - * imf_id : ID of the item field to be managed - * mode : 4 - change sequence of item field - * sequence : direction to move the item field, values are TableUserField::MOVE_UP, TableUserField::MOVE_DOWN + * Parameters: + * imf_id : ID of the item field to be managed + * mode : 3 - change sequence of item field + * sequence : direction to move the item field, values are TableUserField::MOVE_UP, TableUserField::MOVE_DOWN *********************************************************************************************** */ @@ -93,7 +93,7 @@ function moveCategory(direction, imfID) { if (secondSequence > 0) { // Nun erst mal die neue Position von dem gewaehlten Feld aktualisieren - $.get("' . SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM . '/fields/fields_function.php', array('mode' => 4)) . '&imf_id=" + imfID + "&sequence=" + direction); + $.get("' . SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM . '/fields/fields_function.php', array('mode' => 3)) . '&imf_id=" + imfID + "&sequence=" + direction); } } '); @@ -105,14 +105,14 @@ function moveCategory(direction, imfID) { $table->setMessageIfNoRowsFound('ORG_NO_FIELD_CREATED'); // create array with all column heading values -$columnHeading = [ +$columnHeading = array( $gL10n->get('SYS_FIELD'), ' ', $gL10n->get('SYS_DESCRIPTION'), '', $gL10n->get('ORG_DATATYPE'), ' ' -]; +); $table->addRowHeadingByArray($columnHeading); // Intialize variables @@ -150,16 +150,19 @@ function moveCategory(direction, imfID) { $imfSystem = $itemField->getValue('imf_system') == 1 ? '' - : ' - '; + : ' + + '; // create array with all column values $columnValues = array( '' . convlanguagePIM($itemField->getValue('imf_name')) . ' ', ' - - - ', + + + + + ', $fieldDescription, $mandatory, $itemFieldText[$itemField->getValue('imf_type')], diff --git a/fields/fields_delete.php b/fields/fields_delete.php index 5eb393a..965ab02 100644 --- a/fields/fields_delete.php +++ b/fields/fields_delete.php @@ -8,12 +8,9 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * - * Parameters: * - * mode : 1 - Menu and preview of the item field that should be deleted - * 2 - Delete an item field + * Parameters: * imf_id : ID of the item field that should be deleted - * *********************************************************************************************** */ @@ -25,7 +22,6 @@ // Access only with valid login require_once(__DIR__ . '/../../../adm_program/system/login_valid.php'); -$getMode = admFuncVariableIsValid($_GET, 'mode', 'numeric', array('defaultValue' => 1)); $getimfId = admFuncVariableIsValid($_GET, 'imf_id', 'int'); $pPreferences = new CConfigTablePIM(); @@ -37,79 +33,50 @@ } $itemField = new TableAccess($gDb, TBL_INVENTORY_MANAGER_FIELDS, 'imf', $getimfId); - -switch ($getMode) { - case 1: - $headline = $gL10n->get('PLG_INVENTORY_MANAGER_ITEMFIELD_DELETE'); - - // create html page object - $page = new HtmlPage('plg-inventory-manager-fields-delete', $headline); - - $page->addJavascript(' - function setValueList() { - if ($("#imf_type").val() === "DROPDOWN" || $("#imf_type").val() === "RADIO_BUTTON") { - $("#imf_value_list_group").show("slow"); - $("#imf_value_list").attr("required", "required"); - } else { - $("#imf_value_list").removeAttr("required"); - $("#imf_value_list_group").hide(); - } +$headline = $gL10n->get('PLG_INVENTORY_MANAGER_ITEMFIELD_DELETE'); + +// create html page object +$page = new HtmlPage('plg-inventory-manager-fields-delete', $headline); + +$page->addJavascript(' + function setValueList() { + if ($("#imf_type").val() === "DROPDOWN" || $("#imf_type").val() === "RADIO_BUTTON") { + $("#imf_value_list_group").show("slow"); + $("#imf_value_list").attr("required", "required"); + } else { + $("#imf_value_list").removeAttr("required"); + $("#imf_value_list_group").hide(); } - - setValueList(); - $("#imf_type").click(function() { setValueList(); });', true); - - // add current url to navigation stack - $gNavigation->addUrl(CURRENT_URL, $headline); - - $page->addHtml('

' . $gL10n->get('PLG_INVENTORY_MANAGER_ITEMFIELD_DELETE_DESC') . '

'); - - // show form - $form = new HtmlForm('itemfield_delete_form', SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM . '/fields/fields_delete.php', array('imf_id' => $getimfId, 'mode' => 2)), $page); - - $form->addInput('imf_name', $gL10n->get('SYS_NAME'), $itemField->getValue('imf_name', 'database'), array('maxLength' => 100, 'property' => HtmlForm::FIELD_DISABLED)); - - // show internal field name for information - $form->addInput('imf_name_intern', $gL10n->get('SYS_INTERNAL_NAME'), $itemField->getValue('imf_name_intern'), array('maxLength' => 100, 'property' => HtmlForm::FIELD_DISABLED)); - - $itemFieldText = array( - 'CHECKBOX' => $gL10n->get('SYS_CHECKBOX'), - 'DATE' => $gL10n->get('SYS_DATE'), - 'DECIMAL' => $gL10n->get('SYS_DECIMAL_NUMBER'), - 'DROPDOWN' => $gL10n->get('SYS_DROPDOWN_LISTBOX'), - 'NUMBER' => $gL10n->get('SYS_NUMBER'), - 'RADIO_BUTTON' => $gL10n->get('SYS_RADIO_BUTTON'), - 'TEXT' => $gL10n->get('SYS_TEXT') . ' (100 ' . $gL10n->get('SYS_CHARACTERS') . ')', - 'TEXT_BIG' => $gL10n->get('SYS_TEXT') . ' (4000 ' . $gL10n->get('SYS_CHARACTERS') . ')', - ); - asort($itemFieldText); - - $form->addInput('imf_type', $gL10n->get('ORG_DATATYPE'), $itemFieldText[$itemField->getValue('imf_type')], array('maxLength' => 30, 'property' => HtmlForm::FIELD_DISABLED)); - - $form->addMultilineTextInput('imf_value_list', $gL10n->get('ORG_VALUE_LIST'), (string) $itemField->getValue('imf_value_list', 'database'), 6, array('property' => HtmlForm::FIELD_DISABLED)); - - $form->addMultilineTextInput('imf_description', $gL10n->get('SYS_DESCRIPTION'), $itemField->getValue('imf_description'), 3, array('property' => HtmlForm::FIELD_DISABLED)); - - $form->addSubmitButton('btn_delete', $gL10n->get('SYS_DELETE'), array('icon' => 'fa-trash-alt', 'class' => ' offset-sm-3')); - - $page->addHtml($form->show(false)); - $page->show(); - break; - - case 2: - $sql = 'DELETE FROM ' . TBL_INVENTORY_MANAGER_LOG . ' WHERE iml_imf_id = ?;'; - $gDb->queryPrepared($sql, array($getimfId)); - - $sql = 'DELETE FROM '.TBL_INVENTORY_MANAGER_DATA.' WHERE imd_imf_id = ?;'; - $gDb->queryPrepared($sql, array($getimfId)); - - $sql = 'DELETE FROM '.TBL_INVENTORY_MANAGER_FIELDS.' WHERE imf_id = ? AND (imf_org_id = ? OR imf_org_id IS NULL);'; - $gDb->queryPrepared($sql, array($getimfId, $gCurrentOrgId)); - - // go back to item view - $gMessage->setForwardUrl($gNavigation->getPreviousUrl(), 1000); - $gMessage->show($gL10n->get('PLG_INVENTORY_MANAGER_ITEMFIELD_DELETED')); - - break; - // => EXIT -} \ No newline at end of file + } + + setValueList(); + $("#imf_type").click(function() { setValueList(); });', + true +); + +// add current url to navigation stack +$gNavigation->addUrl(CURRENT_URL, $headline); +$page->addHtml('

' . $gL10n->get('PLG_INVENTORY_MANAGER_ITEMFIELD_DELETE_DESC') . '

'); + +// show form +$itemFieldText = array( + 'CHECKBOX' => $gL10n->get('SYS_CHECKBOX'), + 'DATE' => $gL10n->get('SYS_DATE'), + 'DECIMAL' => $gL10n->get('SYS_DECIMAL_NUMBER'), + 'DROPDOWN' => $gL10n->get('SYS_DROPDOWN_LISTBOX'), + 'NUMBER' => $gL10n->get('SYS_NUMBER'), + 'RADIO_BUTTON' => $gL10n->get('SYS_RADIO_BUTTON'), + 'TEXT' => $gL10n->get('SYS_TEXT') . ' (100 ' . $gL10n->get('SYS_CHARACTERS') . ')', + 'TEXT_BIG' => $gL10n->get('SYS_TEXT') . ' (4000 ' . $gL10n->get('SYS_CHARACTERS') . ')', +); +asort($itemFieldText); + +$form = new HtmlForm('itemfield_delete_form', SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM . '/fields/fields_function.php', array('imf_id' => $getimfId, 'mode' => 2)), $page); +$form->addInput('imf_name', $gL10n->get('SYS_NAME'), $itemField->getValue('imf_name', 'database'), array('maxLength' => 100, 'property' => HtmlForm::FIELD_DISABLED)); +$form->addInput('imf_name_intern', $gL10n->get('SYS_INTERNAL_NAME'), $itemField->getValue('imf_name_intern'), array('maxLength' => 100, 'property' => HtmlForm::FIELD_DISABLED)); +$form->addInput('imf_type', $gL10n->get('ORG_DATATYPE'), $itemFieldText[$itemField->getValue('imf_type')], array('maxLength' => 30, 'property' => HtmlForm::FIELD_DISABLED)); +$form->addMultilineTextInput('imf_value_list', $gL10n->get('ORG_VALUE_LIST'), (string) $itemField->getValue('imf_value_list', 'database'), 6, array('property' => HtmlForm::FIELD_DISABLED)); +$form->addMultilineTextInput('imf_description', $gL10n->get('SYS_DESCRIPTION'), $itemField->getValue('imf_description'), 3, array('property' => HtmlForm::FIELD_DISABLED)); +$form->addSubmitButton('btn_delete', $gL10n->get('SYS_DELETE'), array('icon' => 'fa-trash-alt', 'class' => ' offset-sm-3')); +$page->addHtml($form->show(false)); +$page->show(); diff --git a/fields/fields_edit_new.php b/fields/fields_edit_new.php index eb40fc9..b75e7ad 100644 --- a/fields/fields_edit_new.php +++ b/fields/fields_edit_new.php @@ -8,12 +8,11 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * - * Parameters: * + * Parameters: * imf_id : ID of the item field that should be edited * field_name : Name of the field that should be set * redirect_to_import : If true, the user will be redirected to the import page after saving the field - * *********************************************************************************************** */ @@ -78,23 +77,24 @@ function setValueList() { } setValueList(); - $("#imf_type").click(function() { setValueList(); }); -', true); + $("#imf_type").click(function() { setValueList(); });', + true +); // show form -$form = new HtmlForm('item_fields_edit_form', SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM . '/fields/fields_function.php', ['imf_id' => $getimfId, 'mode' => 1, 'redirect_to_import' => $getRedirectToImport]), $page); +$form = new HtmlForm('item_fields_edit_form', SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM . '/fields/fields_function.php', array('imf_id' => $getimfId, 'mode' => 1, 'redirect_to_import' => $getRedirectToImport)), $page); $form->addInput('imf_name', $gL10n->get('SYS_NAME'), $itemField->getValue('imf_name', 'database'), array( - 'maxLength' => 100, - 'property' => $itemField->getValue('imf_system') == 1 ? HtmlForm::FIELD_DEFAULT : HtmlForm::FIELD_REQUIRED + 'maxLength' => 100, + 'property' => $itemField->getValue('imf_system') == 1 ? HtmlForm::FIELD_DEFAULT : HtmlForm::FIELD_REQUIRED ) ); if ($getimfId > 0) { $form->addInput('imf_name_intern', $gL10n->get('SYS_INTERNAL_NAME'), $itemField->getValue('imf_name_intern'), array( - 'maxLength' => 100, - 'property' => HtmlForm::FIELD_DISABLED, - 'helpTextIdLabel' => 'SYS_INTERNAL_NAME_DESC' + 'maxLength' => 100, + 'property' => HtmlForm::FIELD_DISABLED, + 'helpTextIdLabel' => 'SYS_INTERNAL_NAME_DESC' ) ); } @@ -113,28 +113,28 @@ function setValueList() { //bei Systemfeldern darf der Datentyp nicht mehr veraendert werden $form->addSelectBox('imf_type', $gL10n->get('ORG_DATATYPE'), $itemFieldText, array( - 'property' => $itemField->getValue('imf_system') == 1 ? HtmlForm::FIELD_DISABLED : HtmlForm::FIELD_REQUIRED, - 'defaultValue' => $itemField->getValue('imf_type') + 'property' => $itemField->getValue('imf_system') == 1 ? HtmlForm::FIELD_DISABLED : HtmlForm::FIELD_REQUIRED, + 'defaultValue' => $itemField->getValue('imf_type') ) ); $form->addMultilineTextInput('imf_value_list', $gL10n->get('ORG_VALUE_LIST'), (string)$itemField->getValue('imf_value_list', 'database'), 6, array( - 'property' => HtmlForm::FIELD_REQUIRED, - 'helpTextIdLabel' => 'ORG_VALUE_LIST_DESC' + 'property' => HtmlForm::FIELD_REQUIRED, + 'helpTextIdLabel' => 'ORG_VALUE_LIST_DESC' ) ); $form->addCheckbox('imf_mandatory', $gL10n->get('SYS_REQUIRED_INPUT'), (bool)$itemField->getValue('imf_mandatory'), array( - 'property' => HtmlForm::FIELD_DEFAULT, - 'icon' => 'fa-asterisk' + 'property' => HtmlForm::FIELD_DEFAULT, + 'icon' => 'fa-asterisk' ) ); $form->addMultilineTextInput('imf_description', $gL10n->get('SYS_DESCRIPTION'), $itemField->getValue('imf_description'), 3); $form->addSubmitButton('btn_save', $gL10n->get('SYS_SAVE'), array( - 'icon' => 'fa-check', - 'class' => 'offset-sm-3' + 'icon' => 'fa-check', + 'class' => 'offset-sm-3' ) ); diff --git a/fields/fields_function.php b/fields/fields_function.php index 827d78a..97bc2d4 100644 --- a/fields/fields_function.php +++ b/fields/fields_function.php @@ -8,17 +8,17 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * - * Parameters: * + * Parameters: * imf_id : ID of the item field to be managed * mode : 1 - create or edit item field * 2 - delete item field - * 4 - change sequence of item field + * 3 - change sequence of item field * sequence : direction to move the item field, values are TableUserField::MOVE_UP, TableUserField::MOVE_DOWN * redirect_to_import : If true, the user will be redirected to the import page after saving the field * - * Methods: * + * Methods: * handleCreateOrUpdate($itemField, $getRedirectToImport) : Handles the creation or update of an item field * handleDelete($itemField) : Handles the deletion of an item field * handleChangeSequence($itemField, $getSequence) : Handles changing the sequence of an item field @@ -65,20 +65,26 @@ case 1: handleCreateOrUpdate($itemField, $getRedirectToImport); break; + case 2: handleDelete($itemField); break; - case 4: + + case 3: handleChangeSequence($itemField, $getSequence); break; } /** - * Handles the creation or update of an item field. - * @param TableAccess $itemField The item field object to be created or updated. + * Handles the creation or update of an item field + * + * @param TableAccess $itemField The item field object to be created or updated + * @param bool $redirectToImport If true, the user will be redirected to the import page after saving the field + * @return void */ -function handleCreateOrUpdate($itemField, $redirectToImport = false) { - global $gMessage, $gL10n, $gDb, $gCurrentOrgId; +function handleCreateOrUpdate($itemField, $redirectToImport = false) : void +{ + global $gMessage, $gL10n, $gCurrentOrgId; $_SESSION['fields_request'] = $_POST; @@ -104,7 +110,8 @@ function handleCreateOrUpdate($itemField, $redirectToImport = false) { $itemField->setValue($item, $value); } } - } catch (AdmException $e) { + } + catch (AdmException $e) { $e->showHtml(); } @@ -127,7 +134,8 @@ function handleCreateOrUpdate($itemField, $redirectToImport = false) { if ($redirectToImport) { $gMessage->setForwardUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM . '/import/import_column_config.php', 1000); - } else { + } + else { $gMessage->setForwardUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM . '/fields/fields.php', 1000); } $gMessage->show($gL10n->get('SYS_SAVE_DATA')); @@ -135,23 +143,32 @@ function handleCreateOrUpdate($itemField, $redirectToImport = false) { } /** - * Handles the deletion of an item field. - * @param TableAccess $itemField The item field object to be deleted. + * Handles the deletion of an item field + * + * @param TableAccess $itemField The item field object to be deleted + * @return void */ -function handleDelete($itemField) { +function handleDelete($itemField) : void +{ + global $gMessage, $gL10n, $gNavigation; if ($itemField->delete()) { - // Deletion successful -> Return for XMLHttpRequest - echo 'done'; + // Deletion successful + // go back to field view + $gMessage->setForwardUrl($gNavigation->getPreviousUrl(), 1000); + $gMessage->show($gL10n->get('PLG_INVENTORY_MANAGER_ITEMFIELD_DELETED')); } exit(); } /** - * Handles changing the sequence of an item field. - * @param TableAccess $itemField The item field object whose sequence is to be changed. - * @param string $getSequence The direction to move the item field, values are TableUserField::MOVE_UP, TableUserField::MOVE_DOWN. + * Handles changing the sequence of an item field + * + * @param TableAccess $itemField The item field object whose sequence is to be changed + * @param string $getSequence The direction to move the item field, values are TableUserField::MOVE_UP, TableUserField::MOVE_DOWN + * @return void */ -function handleChangeSequence($itemField, $getSequence) { +function handleChangeSequence($itemField, $getSequence) : void +{ global $gDb, $gCurrentOrgId; $imfSequence = (int) $itemField->getValue('imf_sequence'); @@ -181,10 +198,13 @@ function handleChangeSequence($itemField, $getSequence) { } /** - * Validates the required fields for an item field. - * @param TableAccess $itemField The item field object to be validated. + * Validates the required fields for an item field + * + * @param TableAccess $itemField The item field object to be validated + * @return void */ -function validateRequiredFields($itemField) { +function validateRequiredFields($itemField) : void +{ global $gMessage, $gL10n; if ($itemField->getValue('imf_system') == 0) { @@ -206,10 +226,13 @@ function validateRequiredFields($itemField) { } /** - * Checks if an item field already exists. - * @param string $itemField The item field string to be checked. + * Checks if an item field already exists + * + * @param string $itemField The item field string to be checked + * @return void */ -function checkFieldExists($itemField) { +function checkFieldExists($itemField) : void +{ global $gMessage, $gL10n, $gDb, $gCurrentOrgId, $getimfId; $sql = 'SELECT COUNT(*) AS count FROM ' . TBL_INVENTORY_MANAGER_FIELDS . ' diff --git a/import/import_column_config.php b/import/import_column_config.php index 1305caf..f6344de 100644 --- a/import/import_column_config.php +++ b/import/import_column_config.php @@ -7,6 +7,10 @@ * @author MightyMCoder * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only + * + * + * Methods: + * getColumnAssignmentHtml() : Creates the html for each assignment of a profile field to a column of the import file *********************************************************************************************** */ @@ -44,53 +48,6 @@ $formValues['first_row'] = true; } -/** - * Function creates the html for each assignment of a profile field to a column of the import file. - * @param array $arrayColumnList The array contains the following elements cat_name, cat_tooltip, id, name, name_intern, tooltip - * @param array $arrayCsvColumns An array with the names of the columns from the import file. - * @return string Returns the HTML of a table with all profile fields and possible assigned columns of the import file. - * @throws Exception - */ -function getColumnAssignmentHtml(array $arrayColumnList, array $arrayCsvColumns): string -{ - $html = ''; - - foreach ($arrayColumnList as $field) { - foreach ($field as $key => $value) { - $html .= ' - - '; - - $selectEntries = ''; - // list all columns of the file - $found = false; - foreach ($arrayCsvColumns as $colKey => $colValue) { - $colValue = trim(strip_tags(str_replace('"', '', $colValue))); - - $selected = ''; - // Otherwise, detect the entry where the column header - // matches the Admidio field name or internal field name (case-insensitive) - if (strtolower($colValue) == strtolower($value)) { - $selected .= ' selected="selected"'; - $found = true; - } - $selectEntries .= ''; - } - // add html for select box - // Insert default (empty) entry and select if no other item is selected - $html .= ' - - - '; - } - } - return $html; -} - // create html page object $page = new HtmlPage('admidio-items-import-csv', $headline); $page->addHtml('

'.$gL10n->get('PLG_INVENTORY_MANAGER_IMPORT_ASSIGN_FIELDS').'

'); @@ -100,8 +57,7 @@ function getColumnAssignmentHtml(array $arrayColumnList, array $arrayCsvColumns) $form->addCheckbox('first_row', $gL10n->get('SYS_FIRST_LINE_COLUMN_NAME'), $formValues['first_row']); $form->addHtml('
'.$gL10n->get('PLG_INVENTORY_MANAGER_IMPORT_UNUSED_HEAD').'
-
'); -$page->addJavascript( - ' +$page->addJavascript(' $(".admidio-import-field").change(function() { var available = []; $("#import_assign_fields_form .admidio-import-field").first().children("option").each(function() { @@ -177,3 +133,51 @@ function getColumnAssignmentHtml(array $arrayColumnList, array $arrayCsvColumns) // add form to html page and show page $page->addHtml($form->show()); $page->show(); + + +/** + * Function creates the html for each assignment of a profile field to a column of the import file + * + * @param array $arrayColumnList The array contains the following elements cat_name, cat_tooltip, id, name, name_intern, tooltip + * @param array $arrayCsvColumns An array with the names of the columns from the import file + * @return string The HTML of a table with all profile fields and possible assigned columns of the import file + */ +function getColumnAssignmentHtml(array $arrayColumnList, array $arrayCsvColumns) : string +{ + $html = ''; + + foreach ($arrayColumnList as $field) { + foreach ($field as $key => $value) { + $html .= ' + + '; + + $selectEntries = ''; + // list all columns of the file + $found = false; + foreach ($arrayCsvColumns as $colKey => $colValue) { + $colValue = trim(strip_tags(str_replace('"', '', $colValue))); + + $selected = ''; + // Otherwise, detect the entry where the column header + // matches the Admidio field name or internal field name (case-insensitive) + if (strtolower($colValue) == strtolower($value)) { + $selected .= ' selected="selected"'; + $found = true; + } + $selectEntries .= ''; + } + // add html for select box + // Insert default (empty) entry and select if no other item is selected + $html .= ' + + + '; + } + } + return $html; +} \ No newline at end of file diff --git a/import/import_items.php b/import/import_items.php index 398f811..833b370 100644 --- a/import/import_items.php +++ b/import/import_items.php @@ -8,9 +8,10 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * - * methods: * - * compareArrays(array $array1, array $array2) : Compares two arrays to determine if they are different based on specific criteria. + * Methods: + * compareArrays(array $array1, array $array2) : Compares two arrays to determine if they are + * different based on specific criteria *********************************************************************************************** */ @@ -27,34 +28,6 @@ $gMessage->show($gL10n->get('SYS_NO_RIGHTS')); } -/** - * Compares two arrays to determine if they are different based on specific criteria. - * - * This function filters out certain keys ('KEEPER', 'LAST_RECEIVER', 'CATEGORY') from the first array, - * converts date fields ('RECEIVED_ON', 'RECEIVED_BACK_ON') from 'd.m.Y' format to 'Y-m-d' format, - * and then checks if any value in the filtered and transformed first array is not present in the second array. - * - * @param array $array1 The first array to compare. - * @param array $array2 The second array to compare. - * @return bool Returns true if the arrays are different based on the criteria, otherwise false. - */ -function compareArrays(array $array1, array $array2): bool { - $array1 = array_filter($array1, function($key) { - return $key !== 'KEEPER' && $key !== 'LAST_RECEIVER' && $key !== 'IN_INVENTORY' && $key !== 'RECEIVED_ON' && $key !== 'RECEIVED_BACK_ON'; - }, ARRAY_FILTER_USE_KEY); - - foreach ($array1 as $value) { - if ($value === '') { - continue; - } - - if (!in_array($value, $array2, true)) { - return true; - } - } - return false; -} - $_SESSION['import_csv_request'] = $_POST; // check the CSRF token of the form against the session token @@ -113,8 +86,9 @@ function compareArrays(array $array1, array $array2): bool { $itemValues = array(); foreach ($items->mItemData as $key => $itemData) { $itemValue = $itemData->getValue('imd_value'); - if ($itemData->getValue('imf_name_intern') === 'KEEPER' || $itemData->getValue('imf_name_intern') === 'LAST_RECEIVER' || $itemData->getValue('imf_name_intern') === 'IN_INVENTORY' || $itemData->getValue('imf_name_intern') === 'RECEIVED_ON' || $itemData->getValue('imf_name_intern') === 'RECEIVED_BACK_ON') - { + if ($itemData->getValue('imf_name_intern') === 'KEEPER' || $itemData->getValue('imf_name_intern') === 'LAST_RECEIVER' || + $itemData->getValue('imf_name_intern') === 'IN_INVENTORY' || $itemData->getValue('imf_name_intern') === 'RECEIVED_ON' || + $itemData->getValue('imf_name_intern') === 'RECEIVED_BACK_ON') { continue; } @@ -147,6 +121,7 @@ function compareArrays(array $array1, array $array2): bool { } } +// get all values of the item fields $valueList = array(); $importedItemData = array(); @@ -305,7 +280,7 @@ function compareArrays(array $array1, array $array2): bool { } // Send notification to all users -$items->sendNotification($gCurrentOrgId, $importedItemData); +$items->sendNotification($importedItemData); $gNavigation->deleteLastUrl(); @@ -321,4 +296,29 @@ function compareArrays(array $array1, array $array2): bool { else { $gMessage->setForwardUrl($gNavigation->getUrl()); $gMessage->show($gL10n->get('PLG_INVENTORY_MANAGER_NO_NEW_IMPORT_DATA')); +} + +/** + * Compares two arrays to determine if they are different based on specific criteria + * + * @param array $array1 The first array to compare + * @param array $array2 The second array to compare + * @return bool true if the arrays are different based on the criteria, otherwise false + */ +function compareArrays(array $array1, array $array2) : bool +{ + $array1 = array_filter($array1, function($key) { + return $key !== 'KEEPER' && $key !== 'LAST_RECEIVER' && $key !== 'IN_INVENTORY' && $key !== 'RECEIVED_ON' && $key !== 'RECEIVED_BACK_ON'; + }, ARRAY_FILTER_USE_KEY); + + foreach ($array1 as $value) { + if ($value === '') { + continue; + } + + if (!in_array($value, $array2, true)) { + return true; + } + } + return false; } \ No newline at end of file diff --git a/import/import_read_file.php b/import/import_read_file.php index fc1dd23..0ea9fbb 100644 --- a/import/import_read_file.php +++ b/import/import_read_file.php @@ -48,7 +48,8 @@ try { // check the CSRF token of the form against the session token SecurityUtils::validateCsrfToken($_POST['admidio-csrf-token']); -} catch (AdmException $exception) { +} +catch (AdmException $exception) { $exception->showHtml(); // => EXIT } diff --git a/inventory_manager.php b/inventory_manager.php index bb66380..095ce2f 100644 --- a/inventory_manager.php +++ b/inventory_manager.php @@ -3,7 +3,7 @@ *********************************************************************************************** * InventoryManager * - * Version 1.1.3 + * Version 1.1.4 * * InventoryManager is an Admidio plugin for managing the inventory of an organisation. * @@ -32,18 +32,27 @@ * * * Parameters: + * mode : Output(html, print, csv-ms, csv-oo, pdf, pdfl, xlsx, ods) + * filter_string : general filter string + * filter_category : filter for category + * filter_keeper : filter for keeper + * show_all : 0 - (Default) show active items only + * 1 - show all items (also made to former) + * same_side : 0 - (Default) side was called by another side + * 1 - internal call of the side * - * mode : Output(html, print, csv-ms, csv-oo, pdf, pdfl, xlsx, ods) - * filter_string : general filter string - * filter_category : filter for category - * filter_keeper : filter for keeper - * show_all : 0 - (Default) show active items only - * 1 - show all items (also made to former) - * same_side : 0 - (Default) side was called by another side - * 1 - internal call of the side + * + * Methods: + * formatSpreadsheet($spreadsheet, $data, $containsHeadline) : Format the spreadsheet *********************************************************************************************** */ +// PhpSpreadsheet namespaces + use PhpOffice\PhpSpreadsheet\Spreadsheet; + use PhpOffice\PhpSpreadsheet\Writer\Csv; + use PhpOffice\PhpSpreadsheet\Writer\Ods; + use PhpOffice\PhpSpreadsheet\Writer\Xlsx; + require_once(__DIR__ . '/../../adm_program/system/common.php'); require_once(__DIR__ . '/common_function.php'); require_once(__DIR__ . '/classes/items.php'); @@ -60,11 +69,6 @@ $gMessage->show($gL10n->get('SYS_NO_RIGHTS')); } -use PhpOffice\PhpSpreadsheet\Spreadsheet; -use PhpOffice\PhpSpreadsheet\Writer\Csv; -use PhpOffice\PhpSpreadsheet\Writer\Ods; -use PhpOffice\PhpSpreadsheet\Writer\Xlsx; - $sessionDefaults = array( 'filter_string' => '', 'filter_category' => '', @@ -72,8 +76,9 @@ 'show_all' => false ); +// check if plugin need to be updated $pPreferences = new CConfigTablePIM(); -$pPreferences->read(); +$pPreferences->checkForUpdate() ? $pPreferences->init() : $pPreferences->read(); // check if user is authorized for preferences panel if (isUserAuthorizedForPreferencesPIM()) { @@ -90,9 +95,10 @@ } $getMode = admFuncVariableIsValid($_GET, 'mode', 'string', array( - 'defaultValue' => 'html', - 'validValues' => ['csv-ms', 'csv-oo', 'html', 'print', 'pdf', 'pdfl', 'xlsx', 'ods'] -)); + 'defaultValue' => 'html', + 'validValues' => ['csv-ms', 'csv-oo', 'html', 'print', 'pdf', 'pdfl', 'xlsx', 'ods'] + ) +); $getFilterString = admFuncVariableIsValid($_GET, 'filter_string', 'string'); $getFilterCategory = admFuncVariableIsValid($_GET, 'filter_category', 'string'); $getFilterKeeper = admFuncVariableIsValid($_GET, 'filter_keeper', 'int'); @@ -114,8 +120,6 @@ $getShowAll = $_SESSION['pInventoryManager']['show_all']; } -$pPreferences->checkForUpdate() ? $pPreferences->init() : $pPreferences->read(); - // initialize some special mode parameters $separator = ''; $valueQuotes = ''; @@ -168,8 +172,7 @@ $headline = $gL10n->get('PLG_INVENTORY_MANAGER_INVENTORY_MANAGER'); // if html mode and last url was not a list view then save this url to navigation stack -if ($gNavigation->count() === 0 || ($getMode == 'html' && strpos($gNavigation->getUrl(), 'inventory_manager.php') === false)) -{ +if ($gNavigation->count() === 0 || ($getMode == 'html' && strpos($gNavigation->getUrl(), 'inventory_manager.php') === false)) { $gNavigation->addStartUrl(CURRENT_URL, $headline, 'fa-warehouse'); } @@ -181,6 +184,7 @@ case 'ods': case 'xlsx': break; // don't show HtmlTable + case 'print': // create html page object without the custom theme files $page = new HtmlPage('plg-inventory-manager-main-print'); @@ -189,6 +193,7 @@ $page->setHeadline($headline); $table = new HtmlTable('adm_inventory_table', $page, $hoverRows, $datatable, $classTable); break; + case 'pdf': $pdf = new TCPDF($orientation, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); @@ -226,6 +231,7 @@ $table->addAttribute('border', '1'); $table->addAttribute('cellpadding', '1'); break; + case 'html': $datatable = true; $hoverRows = true; @@ -242,90 +248,113 @@ $page->addJavascript(' $("#filter_category").change(function () { self.location.href = "'.SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/inventory_manager.php', array( - 'mode' => 'html', - 'filter_string' => $getFilterString, - 'filter_keeper' => $getFilterKeeper, - 'same_side' => true, - 'show_all' => $getShowAll - )) . '&filter_category=" + $(this).val(); + 'mode' => 'html', + 'filter_string' => $getFilterString, + 'filter_keeper' => $getFilterKeeper, + 'same_side' => true, + 'show_all' => $getShowAll + ) + ) . '&filter_category=" + $(this).val(); }); $("#filter_keeper").change(function () { self.location.href = "'.SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/inventory_manager.php', array( - 'mode' => 'html', - 'filter_string' => $getFilterString, - 'filter_category' => $getFilterCategory, - 'same_side' => true, - 'show_all' => $getShowAll - )) . '&filter_keeper=" + $(this).val(); + 'mode' => 'html', + 'filter_string' => $getFilterString, + 'filter_category' => $getFilterCategory, + 'same_side' => true, + 'show_all' => $getShowAll + ) + ) . '&filter_keeper=" + $(this).val(); }); $("#menu_item_lists_print_view").click(function() { window.open("'.SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/inventory_manager.php', array( - 'filter_string' => $getFilterString, - 'filter_category' => $getFilterCategory, - 'filter_keeper' => $getFilterKeeper, - 'show_all' => $getShowAll, - 'mode' => 'print' - )) . '", "_blank"); + 'filter_string' => $getFilterString, + 'filter_category' => $getFilterCategory, + 'filter_keeper' => $getFilterKeeper, + 'show_all' => $getShowAll, + 'mode' => 'print' + ) + ) . '", "_blank" + ); }); $("#show_all").change(function() { $("#navbar_inventorylist_form").submit(); }); $("#filter_string").change(function() { $("#navbar_inventorylist_form").submit(); - }); - ', true); + });', + true + ); // links to print and exports $page->addPageFunctionsMenuItem('menu_item_lists_print_view', $gL10n->get('SYS_PRINT_PREVIEW'), 'javascript:void(0);', 'fa-print'); $page->addPageFunctionsMenuItem('menu_item_lists_export', $gL10n->get('SYS_EXPORT_TO'), '#', 'fa-file-download'); $page->addPageFunctionsMenuItem('menu_item_lists_xlsx', $gL10n->get('SYS_MICROSOFT_EXCEL').' (*.xlsx)', SecurityUtils::encodeUrl(ADMIDIO_URL.FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/inventory_manager.php', array( - 'filter_string' => $getFilterString, - 'filter_category' => $getFilterCategory, - 'filter_keeper' => $getFilterKeeper, - 'show_all' => $getShowAll, - 'mode' => 'xlsx')), - 'fa-file-excel', 'menu_item_lists_export'); + 'filter_string' => $getFilterString, + 'filter_category' => $getFilterCategory, + 'filter_keeper' => $getFilterKeeper, + 'show_all' => $getShowAll, + 'mode' => 'xlsx' + ) + ), + 'fa-file-excel', 'menu_item_lists_export' + ); $page->addPageFunctionsMenuItem('menu_item_lists_ods', $gL10n->get('SYS_ODF_SPREADSHEET'), SecurityUtils::encodeUrl(ADMIDIO_URL.FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/inventory_manager.php', array( - 'filter_string' => $getFilterString, - 'filter_category' => $getFilterCategory, - 'filter_keeper' => $getFilterKeeper, - 'show_all' => $getShowAll, - 'mode' => 'ods')), - 'fa-file-alt', 'menu_item_lists_export'); + 'filter_string' => $getFilterString, + 'filter_category' => $getFilterCategory, + 'filter_keeper' => $getFilterKeeper, + 'show_all' => $getShowAll, + 'mode' => 'ods' + ) + ), + 'fa-file-alt', 'menu_item_lists_export' + ); $page->addPageFunctionsMenuItem('menu_item_lists_csv_ms', $gL10n->get('SYS_COMMA_SEPARATED_FILE'), SecurityUtils::encodeUrl(ADMIDIO_URL.FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/inventory_manager.php', array( - 'filter_string' => $getFilterString, - 'filter_category' => $getFilterCategory, - 'filter_keeper' => $getFilterKeeper, - 'show_all' => $getShowAll, - 'mode' => 'csv-ms')), - 'fa-file-excel', 'menu_item_lists_export'); + 'filter_string' => $getFilterString, + 'filter_category' => $getFilterCategory, + 'filter_keeper' => $getFilterKeeper, + 'show_all' => $getShowAll, + 'mode' => 'csv-ms' + ) + ), + 'fa-file-excel', 'menu_item_lists_export' + ); $page->addPageFunctionsMenuItem('menu_item_lists_csv', $gL10n->get('SYS_COMMA_SEPARATED_FILE').' ('.$gL10n->get('SYS_UTF8').')', SecurityUtils::encodeUrl(ADMIDIO_URL.FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/inventory_manager.php', array( - 'filter_string' => $getFilterString, - 'filter_category' => $getFilterCategory, - 'filter_keeper' => $getFilterKeeper, - 'show_all' => $getShowAll, - 'mode' => 'csv-oo')), - 'fa-file-csv', 'menu_item_lists_export'); + 'filter_string' => $getFilterString, + 'filter_category' => $getFilterCategory, + 'filter_keeper' => $getFilterKeeper, + 'show_all' => $getShowAll, + 'mode' => 'csv-oo' + ) + ), + 'fa-file-csv', 'menu_item_lists_export' + ); $page->addPageFunctionsMenuItem('menu_item_lists_pdf', $gL10n->get('SYS_PDF').' ('.$gL10n->get('SYS_PORTRAIT').')', SecurityUtils::encodeUrl(ADMIDIO_URL.FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/inventory_manager.php', array( - 'filter_string' => $getFilterString, - 'filter_category' => $getFilterCategory, - 'filter_keeper' => $getFilterKeeper, - 'show_all' => $getShowAll, - 'mode' => 'pdf')), - 'fa-file-pdf', 'menu_item_lists_export'); + 'filter_string' => $getFilterString, + 'filter_category' => $getFilterCategory, + 'filter_keeper' => $getFilterKeeper, + 'show_all' => $getShowAll, + 'mode' => 'pdf' + ) + ), + 'fa-file-pdf', 'menu_item_lists_export' + ); $page->addPageFunctionsMenuItem('menu_item_lists_pdfl', $gL10n->get('SYS_PDF').' ('.$gL10n->get('SYS_LANDSCAPE').')', SecurityUtils::encodeUrl(ADMIDIO_URL.FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/inventory_manager.php', array( - 'filter_string' => $getFilterString, - 'filter_category' => $getFilterCategory, - 'filter_keeper' => $getFilterKeeper, - 'show_all' => $getShowAll, - 'mode' => 'pdfl')), - 'fa-file-pdf', 'menu_item_lists_export'); + 'filter_string' => $getFilterString, + 'filter_category' => $getFilterCategory, + 'filter_keeper' => $getFilterKeeper, + 'show_all' => $getShowAll, + 'mode' => 'pdfl' + ) + ), + 'fa-file-pdf', 'menu_item_lists_export' + ); if ($authorizedForPreferences) { $page->addPageFunctionsMenuItem('menu_preferences', $gL10n->get('SYS_SETTINGS'), SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/preferences/preferences.php'), 'fa-cog'); @@ -390,6 +419,7 @@ $table->setDatatablesRowsPerPage($gSettingsManager->getInt('groups_roles_members_per_page')); } break; + default: $table = new HtmlTable('adm_inventory_table', $page, $hoverRows, $datatable, $classTable); break; @@ -416,10 +446,12 @@ case 'GENDER': $columnAlign[] = 'center'; break; + case 'NUMBER': case 'DECIMAL': $columnAlign[] = 'right'; break; + default: $columnAlign[] = 'left'; break; @@ -441,13 +473,16 @@ case 'csv': $csvStr .= $separator . $valueQuotes . $columnHeader . $valueQuotes; break; + case "ods": case 'xlsx': $header[$columnHeader] = 'string'; break; + case 'pdf': $arrValidColumns[] = $columnHeader; break; + case 'html': case 'print': $columnValues[] = $columnHeader; @@ -497,8 +532,7 @@ $imfNameIntern = $itemField->getValue('imf_name_intern'); if (($getFilterCategory !== '' && $imfNameIntern == 'CATEGORY' && $getFilterCategory != $items->getValue($imfNameIntern, 'database')) || - ($getFilterKeeper !== 0 && $imfNameIntern == 'KEEPER' && $getFilterKeeper != $items->getValue($imfNameIntern)) - ) { + ($getFilterKeeper !== 0 && $imfNameIntern == 'KEEPER' && $getFilterKeeper != $items->getValue($imfNameIntern))) { continue 2; } @@ -648,11 +682,13 @@ case 'csv': $csvStr .= $tmp_csv . "\n"; break; + case 'ods': case 'xlsx': $rows[] = $columnValues; $strikethroughs[] = $strikethrough; break; + default: $table->addRowByArray($columnValues, '', array('nobr' => 'true')); break; @@ -688,6 +724,7 @@ $writer->save('php://output'); break; + case 'pdf': $pdf->writeHTML($table->getHtmlTable(), true, false, true); $file = ADMIDIO_PATH . FOLDER_DATA . '/temp/' . $filename; @@ -697,10 +734,12 @@ ignore_user_abort(true); try { FileSystemUtils::deleteFileIfExists($file); - } catch (\RuntimeException $exception) { + } + catch (\RuntimeException $exception) { $gLogger->error('Could not delete file!', array('filePath' => $file)); } break; + case 'ods': case 'xlsx': $contentType = ($getMode == 'xlsx') ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" : "application/vnd.oasis.opendocument.spreadsheet"; @@ -737,17 +776,26 @@ $writer = new $writerClass($spreadsheet); $writer->save('php://output'); break; + case 'html': $page->addHtml($table->show()); $page->show(); break; + case 'print': $page->addHtml($table->show()); $page->show(); break; } -function formatSpreadsheet($spreadsheet, $data, $containsHeadline) +/** + * Formats the spreadsheet + * + * @param PhpOffice\PhpSpreadsheet\Spreadsheet $spreadsheet + * @param array $data + * @param bool $containsHeadline + */ +function formatSpreadsheet($spreadsheet, $data, $containsHeadline) : void { $alphabet = range('A', 'Z'); $column = $alphabet[count($data[0])-1]; diff --git a/inventory_manager_profile_addin.php b/inventory_manager_profile_addin.php index 65e214e..7d101ba 100644 --- a/inventory_manager_profile_addin.php +++ b/inventory_manager_profile_addin.php @@ -8,10 +8,15 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * - * Note: * + * Note: * Add the following line to profile.php (before $page->show();): * "require_once(ADMIDIO_PATH . FOLDER_PLUGINS .'/InventoryManager/inventory_manager_profile_addin.php');" + * + * + * Methods: + * insertKeeperView($page, $user, $itemsKeeper) : Inserts the keeper view into the profile page + * insertReceiverView($page, $user, $itemsReceiver) : Inserts the receiver view into the profile page *********************************************************************************************** */ @@ -25,9 +30,7 @@ require_once(__DIR__ . '/../../adm_program/system/login_valid.php'); // Check if the user is authorized to see the plugin addin on the profile page -$userIsAuthorized = isUserAuthorizedForAddinPIM(); - -if ($userIsAuthorized) { +if (isUserAuthorizedForAddinPIM()) { $getUserUuid = admFuncVariableIsValid($_GET, 'user_uuid', 'string', array('defaultValue' => $gCurrentUser->getValue('usr_uuid'))); $creationMode = ''; @@ -53,8 +56,7 @@ $creationMode = 'both'; } - switch($creationMode) - { + switch($creationMode) { case 'keeper': insertKeeperView($page, $user, $itemsKeeper); break; @@ -70,14 +72,23 @@ } } -function insertKeeperView($page, $user, $itemsKeeper) { +/** + * Inserts the keeper view into the profile page + * + * @param HtmlPage $page The page object + * @param User $user The user object + * @param CItems $itemsKeeper The items object + */ +function insertKeeperView($page, $user, $itemsKeeper) : void +{ global $gL10n, $gCurrentOrgId; $pPreferences = new CConfigTablePIM(); $pPreferences->read(); - $page->addHtml('
-
' . $gL10n->get('PLG_INVENTORY_MANAGER_INVENTORY_MANAGER') . ' (' . $gL10n->get('SYS_VIEW') . ': ' . $gL10n->get('PIM_KEEPER') . ') + $page->addHtml(' +
+
' . $gL10n->get('PLG_INVENTORY_MANAGER_INVENTORY_MANAGER') . ' (' . $gL10n->get('SYS_VIEW') . ': ' . $gL10n->get('PIM_KEEPER') . ') -
-
-

' . $gL10n->get('PLG_INVENTORY_MANAGER_ADDIN_KEEPER_DESC') . '

-
    '); +
+
+

' . $gL10n->get('PLG_INVENTORY_MANAGER_ADDIN_KEEPER_DESC') . '

+
    ' + ); // prepare header for table $inventoryAddinTable = new HtmlTable('adm_inventory_addin_table_keeper', $page, true, true, 'table table-condensed'); @@ -181,17 +193,19 @@ function insertKeeperView($page, $user, $itemsKeeper) { $tempValue = ''; if ($pPreferences->isPffInst()) { - $tempValue .= ' - - '; + $tempValue .= ' + + + '; } if (isUserAuthorizedForPreferencesPIM()) { - $tempValue .= ' - - '; - $tempValue .= ' - - '; + $tempValue .= ' + + + + + + '; } $columnValues[] = $tempValue; @@ -199,18 +213,31 @@ function insertKeeperView($page, $user, $itemsKeeper) { } $page->addHtml($inventoryAddinTable->show()); - $page->addHtml('
'); + $page->addHtml(' + +
+
' + ); $page->addHtml(''); } -function insertReceiverView($page, $user, $itemsReceiver) { +/** + * Inserts the receiver view into the profile page + * + * @param HtmlPage $page The page object + * @param User $user The user object + * @param CItems $itemsReceiver The items object + */ +function insertReceiverView($page, $user, $itemsReceiver) : void +{ global $gL10n, $gCurrentOrgId; $pPreferences = new CConfigTablePIM(); $pPreferences->read(); - $page->addHtml('
-
' . $gL10n->get('PLG_INVENTORY_MANAGER_INVENTORY_MANAGER') . ' (' . $gL10n->get('SYS_VIEW') . ': ' . $gL10n->get('PIM_LAST_RECEIVER') . ') + $page->addHtml(' +
+
' . $gL10n->get('PLG_INVENTORY_MANAGER_INVENTORY_MANAGER') . ' (' . $gL10n->get('SYS_VIEW') . ': ' . $gL10n->get('PIM_LAST_RECEIVER') . ') -
-
-

' . $gL10n->get('PLG_INVENTORY_MANAGER_ADDIN_LAST_RECEIVER_DESC') . '

-
    '); +
+
+

' . $gL10n->get('PLG_INVENTORY_MANAGER_ADDIN_LAST_RECEIVER_DESC') . '

+
    ' + ); // prepare header for table $inventoryAddinTable = new HtmlTable('adm_inventory_addin_table_receiver', $page, true, true, 'table table-condensed'); @@ -315,17 +343,19 @@ function insertReceiverView($page, $user, $itemsReceiver) { $tempValue = ''; if ($pPreferences->isPffInst()) { - $tempValue .= ' - - '; + $tempValue .= ' + + + '; } if (isUserAuthorizedForPreferencesPIM()) { - $tempValue .= ' - - '; - $tempValue .= ' - - '; + $tempValue .= ' + + + + + + '; } $columnValues[] = $tempValue; @@ -333,6 +363,10 @@ function insertReceiverView($page, $user, $itemsReceiver) { } $page->addHtml($inventoryAddinTable->show()); - $page->addHtml('
'); + $page->addHtml(' + +
+
' + ); $page->addHtml(''); } \ No newline at end of file diff --git a/items/items_delete.php b/items/items_delete.php index d46343c..7badfb8 100644 --- a/items/items_delete.php +++ b/items/items_delete.php @@ -8,15 +8,21 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * + * * Parameters: + * mode : 1 - Display form to delete or mark item as former + * 2 - Delete an item + * 3 - Mark an item as former + * 4 - Undo marking an item as former + * item_id : ID of the item to be deleted or marked as former + * item_former : 0 - Item is active + * 1 - Item is already marked as former * - * mode : 1 - Display form to delete or mark item as former - * 2 - Delete an item - * 3 - Mark an item as former - * 4 - Undo marking an item as former - * item_id : ID of the item to be deleted or marked as former - * item_former: 0 - Item is active - * 1 - Item is already marked as former + * Methods: + * displayItemDeleteForm() : Displays the form to delete an item + * deleteItem() : Deletes an item from the database + * makeItemFormer() : Marks an item as former + * undoItemFormer() : Marks an item as no longer former *********************************************************************************************** */ @@ -59,6 +65,7 @@ case 1: displayItemDeleteForm($items, $user, $getItemId, $getItemFormer, $authorizedForDelete); break; + case 2: if ($authorizedForDelete) { deleteItem($items, $getItemId, $gCurrentOrgId); @@ -67,22 +74,26 @@ $gMessage->show($gL10n->get('SYS_NO_RIGHTS')); } break; + case 3: makeItemFormer($items, $getItemId, $gCurrentOrgId); break; + case 4: undoItemFormer($items, $getItemId, $gCurrentOrgId); break; } /** - * Displays the form to delete an item. - * @param CItems $items The items object containing item data. - * @param User $user The user object. - * @param int $getItemId The ID of the item to be deleted. - * @param bool $getItemFormer Indicates if the item is already marked as former. + * Displays the form to delete an item + * + * @param CItems $items The items object containing item data + * @param User $user The user object + * @param int $getItemId The ID of the item to be deleted + * @param bool $getItemFormer Indicates if the item is already marked as former */ -function displayItemDeleteForm($items, $user, $getItemId, $getItemFormer, $authorizedForDelete) { +function displayItemDeleteForm($items, $user, $getItemId, $getItemFormer, $authorizedForDelete) : void +{ global $gL10n, $gNavigation; $headline = $gL10n->get('PLG_INVENTORY_MANAGER_ITEM_DELETE'); @@ -139,18 +150,20 @@ function displayItemDeleteForm($items, $user, $getItemId, $getItemFormer, $autho } /** - * Deletes an item from the database. - * @param CItems $items The items object containing item data. - * @param int $getItemId The ID of the item to be deleted. - * @param int $gCurrentOrgId The ID of the current organization. + * Deletes an item from the database + * + * @param CItems $items The items object containing item data + * @param int $getItemId The ID of the item to be deleted + * @param int $gCurrentOrgId The ID of the current organization */ -function deleteItem($items, $getItemId, $gCurrentOrgId) { +function deleteItem($items, $getItemId, $gCurrentOrgId) : void +{ global $gMessage, $gNavigation, $gL10n; $items->deleteItem($getItemId, $gCurrentOrgId); // Send notification to all users - $items->sendNotification($gCurrentOrgId); + $items->sendNotification(); // Go back to item view if ($gNavigation->count() > 2) { @@ -162,36 +175,40 @@ function deleteItem($items, $getItemId, $gCurrentOrgId) { } /** - * Marks an item as former. - * @param CItems $items The items object containing item data. - * @param int $getItemId The ID of the item to be marked as former. - * @param int $gCurrentOrgId The ID of the current organization. + * Marks an item as former + * + * @param CItems $items The items object containing item data + * @param int $getItemId The ID of the item to be marked as former + * @param int $gCurrentOrgId The ID of the current organization */ -function makeItemFormer($items, $getItemId, $gCurrentOrgId) { +function makeItemFormer($items, $getItemId, $gCurrentOrgId) : void +{ global $gMessage, $gNavigation, $gL10n; $items->makeItemFormer($getItemId, $gCurrentOrgId); // Send notification to all users - $items->sendNotification($gCurrentOrgId); + $items->sendNotification(); $gMessage->setForwardUrl($gNavigation->getPreviousUrl(), 1000); $gMessage->show($gL10n->get('PLG_INVENTORY_MANAGER_ITEM_MADE_TO_FORMER')); } /** - * Marks an item as no longer former. - * @param CItems $items The items object containing item data. - * @param int $getItemId The ID of the item to be marked as former. - * @param int $gCurrentOrgId The ID of the current organization. + * Marks an item as no longer former + * + * @param CItems $items The items object containing item data + * @param int $getItemId The ID of the item to be marked as former + * @param int $gCurrentOrgId The ID of the current organization */ -function undoItemFormer($items, $getItemId, $gCurrentOrgId) { +function undoItemFormer($items, $getItemId, $gCurrentOrgId) : void +{ global $gMessage, $gNavigation, $gL10n; $items->undoItemFormer($getItemId, $gCurrentOrgId); // Send notification to all users - $items->sendNotification($gCurrentOrgId); + $items->sendNotification(); $gMessage->setForwardUrl($gNavigation->getPreviousUrl(), 1000); $gMessage->show($gL10n->get('PLG_INVENTORY_MANAGER_ITEM_UNDO_FORMER')); diff --git a/items/items_edit_new.php b/items/items_edit_new.php index 3a410ec..7afcc1a 100644 --- a/items/items_edit_new.php +++ b/items/items_edit_new.php @@ -8,11 +8,11 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * + * * Parameters: - * - * item_id : ID of the item who should be edited - * copy : true - The item of the item_id will be copied and the base for this new item - * + * item_id : ID of the item who should be edited + * item_former : indicates that the item was made to former item + * copy : true - The item of the item_id will be copied and the base for this new item *********************************************************************************************** */ @@ -77,7 +77,7 @@ } // Create HTML form -$form = new HtmlForm('edit_item_form', SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM . '/items/items_save.php', ['item_id' => $getItemId]), $page); +$form = new HtmlForm('edit_item_form', SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM . '/items/items_save.php', array('item_id' => $getItemId)), $page); foreach ($items->mItemFields as $itemField) { $imfNameIntern = $itemField->getValue('imf_name_intern'); @@ -111,10 +111,9 @@ } if (isset($pimInInventoryId, $pimLastReceiverId, $pimReceivedOnId, $pimReceivedBackOnId) && $imfNameIntern === 'IN_INVENTORY') { - // Add JavaScript to check the PIM_LAST_RECEIVER field and set the required attribute for pimReceivedOnId - $pPreferences->config['Optionen']['field_date_time_format'] === 'datetime' ? $datetime = 'true' : $datetime = 'false'; - + + // Add JavaScript to check the PIM_LAST_RECEIVER field and set the required attribute for pimReceivedOnId and pimReceivedBackOnId $page->addJavascript(' document.addEventListener("DOMContentLoaded", function() { if (document.querySelector("[id=\'imf-' . $pimReceivedOnId . '_time\']")) { @@ -255,6 +254,7 @@ function validateReceivedOnAndBackOn() { ) ); break; + case 'DROPDOWN': $form->addSelectBox( 'imf-' . $items->getProperty($imfNameIntern, 'imf_id'), @@ -268,6 +268,7 @@ function validateReceivedOnAndBackOn() { ) ); break; + case 'RADIO_BUTTON': $form->addRadioButton( 'imf-' . $items->getProperty($imfNameIntern, 'imf_id'), @@ -282,6 +283,7 @@ function validateReceivedOnAndBackOn() { ) ); break; + case 'TEXT_BIG': $form->addMultilineTextInput( 'imf-' . $items->getProperty($imfNameIntern, 'imf_id'), @@ -296,6 +298,7 @@ function validateReceivedOnAndBackOn() { ) ); break; + default: $fieldType = 'text'; $maxlength = '50'; diff --git a/items/items_export_to_pff.php b/items/items_export_to_pff.php index ae8918e..39150d8 100644 --- a/items/items_export_to_pff.php +++ b/items/items_export_to_pff.php @@ -8,8 +8,8 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * - * Parameters: * + * Parameters: * item_id : ID of the item to be exported *********************************************************************************************** */ @@ -57,11 +57,13 @@ case 'DATE': $content = $items->getHtmlValue($imfNameIntern, $content); break; + case 'DROPDOWN': case 'RADIO_BUTTON': $arrListValues = $items->getProperty($imfNameIntern, 'imf_value_list', 'text'); $content = $arrListValues[$content]; break; + case 'CHECKBOX': $content = $content == 1 ? $gL10n->get('SYS_YES') : $gL10n->get('SYS_NO'); break; diff --git a/items/items_history.php b/items/items_history.php index 862838a..627099f 100644 --- a/items/items_history.php +++ b/items/items_history.php @@ -8,11 +8,11 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * - * Parameters: * - * item_id : If set, only show the item field history of that item - * filter_date_from: Set to the actual date if no date information is delivered - * filter_date_to : Set to 31.12.9999 if no date information is delivered + * Parameters: + * item_id : If set, only show the item field history of that item + * filter_date_from : Set to the actual date if no date information is delivered + * filter_date_to : Set to the actual date if no date information is delivered *********************************************************************************************** */ @@ -29,8 +29,8 @@ $filterDateFrom->modify('-'.$gSettingsManager->getInt('contacts_field_history_days').' day'); $getItemId = admFuncVariableIsValid($_GET, 'item_id', 'int'); -$getDateFrom = admFuncVariableIsValid($_GET, 'filter_date_from', 'date', ['defaultValue' => $filterDateFrom->format($gSettingsManager->getString('system_date'))]); -$getDateTo = admFuncVariableIsValid($_GET, 'filter_date_to', 'date', ['defaultValue' => DATE_NOW]); +$getDateFrom = admFuncVariableIsValid($_GET, 'filter_date_from', 'date', array('defaultValue' => $filterDateFrom->format($gSettingsManager->getString('system_date')))); +$getDateTo = admFuncVariableIsValid($_GET, 'filter_date_to', 'date', array('defaultValue' => DATE_NOW)); $items = new CItems($gDb, $gCurrentOrgId); $items->readItemData($getItemId, $gCurrentOrgId); diff --git a/items/items_save.php b/items/items_save.php index 12550ee..f6146f9 100644 --- a/items/items_save.php +++ b/items/items_save.php @@ -8,11 +8,12 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * - * Parameters: * - * item_id : >0 - ID of the item to be saved, 0 - a new item will be added - * copy_number: number of new items to be created - * copy_field : field for the current number + * Parameters: + * item_id : >0 - ID of the item to be saved + * =0 - a new item will be added + * copy_number : number of new items to be created + * copy_field : field for the current number *********************************************************************************************** */ @@ -26,10 +27,10 @@ // Initialize and check the parameters $getItemId = admFuncVariableIsValid($_GET, 'item_id', 'int'); -$postCopyNumber = admFuncVariableIsValid($_POST, 'copy_number', 'numeric', ['defaultValue' => 1]); +$postCopyNumber = admFuncVariableIsValid($_POST, 'copy_number', 'numeric', array('defaultValue' => 1)); $postCopyField = admFuncVariableIsValid($_POST, 'copy_field', 'int'); -$postRedirect = admFuncVariableIsValid($_POST, 'redirect', 'numeric', ['defaultValue' => 1]); -$postImported = admFuncVariableIsValid($_POST, 'imported', 'numeric', ['defaultValue' => 0]); +$postRedirect = admFuncVariableIsValid($_POST, 'redirect', 'numeric', array('defaultValue' => 1)); +$postImported = admFuncVariableIsValid($_POST, 'imported', 'numeric', array('defaultValue' => 0)); $pPreferences = new CConfigTablePIM(); $pPreferences->read(); @@ -55,7 +56,6 @@ foreach ($items->mItemFields as $itemField) { $postId = 'imf-' . $itemField->getValue('imf_id'); - if (isset($_POST[$postId])) { if (strlen($_POST[$postId]) === 0 && $itemField->getValue('imf_mandatory') == 1) { $gMessage->show($gL10n->get('SYS_FIELD_EMPTY', array(convlanguagePIM($itemField->getValue('imf_name'))))); diff --git a/preferences/preferences.php b/preferences/preferences.php index 31f0146..69f4388 100644 --- a/preferences/preferences.php +++ b/preferences/preferences.php @@ -8,10 +8,9 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * - * methods: * + * Methods: * addPreferencePanel($page, $id, $title, $icon, $content) : Add a new preference panel to the page - * *********************************************************************************************** */ @@ -23,21 +22,6 @@ // Access only with valid login require_once(__DIR__ . '/../../../adm_program/system/login_valid.php'); -/** - * Adds a new preference panel to the given page. - * - * @param object $page The page object where the preference panel will be added. - * @param string $id The unique identifier for the preference panel. - * @param string $title The title of the preference panel. - * @param string $icon The icon associated with the preference panel. - * @param string $content The HTML content of the preference panel. - * @return void - */ -// Function to add new preference panels -function addPreferencePanel($page, $id, $title, $icon, $content) { - $page->addHtml(getPreferencePanelPIM('preferences', $id, $title, $icon, $content)); -} - $pPreferences = new CConfigTablePIM(); $pPreferences->read(); @@ -103,15 +87,16 @@ function addPreferencePanel($page, $id, $title, $icon, $content) { ); $page->addHtml(' - - -
-
-
'); + + +
+
+
' +); $items = new CItems($gDb, $gCurrentOrgId); $valueList = array(); @@ -146,8 +131,7 @@ function addPreferencePanel($page, $id, $title, $icon, $content) { } // PANEL: PROFILE ADDIN -$formProfileAddin = new HtmlForm('profile_addin_form', SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/preferences/preferences_function.php', array('form' => 'profile_addin_preferences')), $page, array('class' => 'form-preferences')); - +$helpTextIdLabelLink = 'GitHub Wiki'; $valueList = array(); foreach ($items->mItemFields as $itemField) { if ($itemField->getValue('imf_name_intern') == 'ITEMNAME') { @@ -156,7 +140,7 @@ function addPreferencePanel($page, $id, $title, $icon, $content) { $valueList[$itemField->getValue('imf_name_intern')] = $itemField->getValue('imf_name'); } -$helpTextIdLabelLink = 'GitHub Wiki'; +$formProfileAddin = new HtmlForm('profile_addin_form', SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/preferences/preferences_function.php', array('form' => 'profile_addin_preferences')), $page, array('class' => 'form-preferences')); $helpTextIdLabel = $gL10n->get('PLG_INVENTORY_MANAGER_PROFILE_ADDIN_DESC2', array($helpTextIdLabelLink)); $formProfileAddin->addSelectBox('profile_addin', $gL10n->get('PLG_INVENTORY_MANAGER_ITEMFIELD'), $valueList, array('defaultValue' => $pPreferences->config['Optionen']['profile_addin'], 'helpTextIdInline' => 'PLG_INVENTORY_MANAGER_PROFILE_ADDIN_DESC', 'multiselect' => true, 'helpTextIdLabel' => $helpTextIdLabel)); $formProfileAddin->addSubmitButton('btn_save_profile_addin_preferences', $gL10n->get('SYS_SAVE'), array('icon' => 'fa-check', 'class' => ' offset-sm-3')); @@ -182,13 +166,14 @@ function addPreferencePanel($page, $id, $title, $icon, $content) { addPreferencePanel($page, 'deinstallation', $gL10n->get('PLG_INVENTORY_MANAGER_DEINSTALLATION'), 'fas fa-trash-alt', $formDeinstallation->show()); // PANEL: ACCESS_PREFERENCES -$formAccessPreferences = new HtmlForm('access_preferences_form', SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/preferences/preferences_function.php', array('form' => 'access_preferences')), $page, array('class' => 'form-preferences')); $sql = 'SELECT rol.rol_id, rol.rol_name, cat.cat_name FROM '.TBL_CATEGORIES.' AS cat, '.TBL_ROLES.' AS rol WHERE cat.cat_id = rol.rol_cat_id - AND rol.rol_id != 1 ' //remove admin role - . 'AND (cat.cat_org_id = '.$gCurrentOrgId.' + AND rol.rol_id != 1 ' . //ignore admin role + 'AND (cat.cat_org_id = '.$gCurrentOrgId.' OR cat.cat_org_id IS NULL) ORDER BY cat_sequence, rol.rol_name ASC;'; + +$formAccessPreferences = new HtmlForm('access_preferences_form', SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM .'/preferences/preferences_function.php', array('form' => 'access_preferences')), $page, array('class' => 'form-preferences')); $formAccessPreferences->addSelectBoxFromSql('access_preferences', '', $gDb, $sql, array('defaultValue' => $pPreferences->config['access']['preferences'], 'helpTextIdInline' => 'PLG_INVENTORY_MANAGER_ACCESS_PREFERENCES_DESC', 'multiselect' => true)); $formAccessPreferences->addSubmitButton('btn_save_access_preferences', $gL10n->get('SYS_SAVE'), array('icon' => 'fa-check', 'class' => ' offset-sm-3')); addPreferencePanel($page, 'access_preferences', $gL10n->get('PLG_INVENTORY_MANAGER_ACCESS_PREFERENCES'), 'fas fa-key', $formAccessPreferences->show()); @@ -199,22 +184,38 @@ function addPreferencePanel($page, $id, $title, $icon, $content) { $linkKeyManager = 'KeyManager (GitHub)'; $pluginInfo = sprintf($linkInventoryManager, $pluginName); $pluginBasedInfo = $pluginInfo .' ' . $gL10n->get('PLG_INVENTORY_MANAGER_BASED_ON', array($linkKeyManager)); -$updateCheck = ''.$pPreferences->config['Plugininformationen']['version'].' - '.$gL10n->get('SYS_CHECK_FOR_UPDATE').' - '; +$updateCheck = ' + '.$pPreferences->config['Plugininformationen']['version'].' + '.$gL10n->get('SYS_CHECK_FOR_UPDATE').' + '; $dokumentationLink = ''.$gL10n->get('PLG_INVENTORY_MANAGER_DOCUMENTATION_OPEN').''; $formPluginInformations = new HtmlForm('plugin_informations_preferences_form', null, $page, array('class' => 'form-preferences')); $formPluginInformations->addStaticControl('plg_name', $gL10n->get('PLG_INVENTORY_MANAGER_PLUGIN_NAME'), $pluginBasedInfo); $formPluginInformations->addStaticControl('plg_dokumentation', $gL10n->get('PLG_INVENTORY_MANAGER_DOCUMENTATION'), $dokumentationLink, array('helpTextIdLabel' => 'PLG_INVENTORY_MANAGER_DOCUMENTATION_OPEN_DESC')); - $formPluginInformations->addCustomContent($gL10n->get('PLG_INVENTORY_MANAGER_PLUGIN_VERSION'), $updateCheck); $formPluginInformations->addStaticControl('plg_date', $gL10n->get('PLG_INVENTORY_MANAGER_PLUGIN_DATE'), $pPreferences->config['Plugininformationen']['stand']); addPreferencePanel($page, 'plugin_informations', $gL10n->get('PLG_INVENTORY_MANAGER_PLUGIN_INFORMATION'), 'fas fa-info-circle', $formPluginInformations->show()); $page->addHtml(' +
-
-
'); +
' +); $page->show(); + +/** + * Adds a new preference panel to the given page + * + * @param object $page The page object where the preference panel will be added + * @param string $id The unique identifier for the preference panel + * @param string $title The title of the preference panel + * @param string $icon The icon associated with the preference panel + * @param string $content The HTML content of the preference panel + * @return void + */ +function addPreferencePanel($page, $id, $title, $icon, $content) : void +{ + $page->addHtml(getPreferencePanelPIM('preferences', $id, $title, $icon, $content)); +} \ No newline at end of file diff --git a/preferences/preferences_check_for_update.php b/preferences/preferences_check_for_update.php index a65591f..a5a1262 100644 --- a/preferences/preferences_check_for_update.php +++ b/preferences/preferences_check_for_update.php @@ -8,18 +8,20 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * + * * Parameters: - * * mode : 1 - (Default) check availability of updates * 2 - Show results of update check * PIMVersion : The current version of the InventoryManager plugin * PIMBetaVersion : The current beta version of the InventoryManager plugin * - * methods: + * + * Methods: * getLatestReleaseVersion($owner, $repo) : Get the latest release version of the InventoryManager plugin * getLatestBetaReleaseVersion($owner, $repo) : Get the latest beta release version of the InventoryManager plugin - * checkVersion(string $currentVersion, string $checkStableVersion, string $checkBetaVersion, string $betaRelease, - * string $betaFlag) : Check the current version of the InventoryManager plugin and compare + * checkVersion(string $currentVersion,string $checkStableVersion, + * string $checkBetaVersion, string $betaRelease, + * string $betaFlag) : Check the current version of the InventoryManager plugin and compare * it with the latest stable and beta release versions *********************************************************************************************** */ @@ -43,111 +45,6 @@ $gMessage->show($gL10n->get('SYS_NO_RIGHTS')); } -/** - * This function checks the GitHub repository for the latest release version - * of the InventoryManager plugin. It fetches the release information using - * GitHub's API and returns the version number of the latest release. - * - * @param string $owner The owner of the repository. - * @param string $repo The name of the repository. - * @return array An array containing the version number and URL of the latest release. - */ -function getLatestReleaseVersion($owner, $repo) { - $url = "https://api.github.com/repos/$owner/$repo/releases/latest"; - - $options = [ - 'http' => [ - 'method' => 'GET', - 'header' => [ - 'User-Agent: PHP' // GitHub benötigt diesen Header - ] - ] - ]; - - $context = stream_context_create($options); - $response = @file_get_contents($url, false, $context); - - if ($response === FALSE) { - return ['version' => 'n/a', 'url' => '']; - } - - $data = json_decode($response, true); - return isset($data['tag_name']) ? ['version' => ltrim($data['tag_name'], 'v'), 'url' => $data['html_url']] : ['version' => 'n/a', 'url' => '']; -} - -/** - * This function checks the GitHub repository for the latest beta release version - * of the InventoryManager plugin. It fetches the release information using - * GitHub's API and returns the version number of the latest beta release. - * - * @param string $owner The owner of the repository. - * @param string $repo The name of the repository. - * @return array An array containing the version number, release name and URL of the latest beta release. - */ -function getLatestBetaReleaseVersion($owner, $repo) { - $url = "https://api.github.com/repos/$owner/$repo/releases"; - - $options = [ - 'http' => [ - 'method' => 'GET', - 'header' => [ - 'User-Agent: PHP' // Github requires this header - ] - ] - ]; - - $context = stream_context_create($options); - $response = @file_get_contents($url, false, $context); - - if ($response === FALSE) { - return ['version' => 'n/a', 'release' => '', 'url' => '']; - } - - $data = json_decode($response, true); - foreach ($data as $release) { - if ($release['prerelease']) { - return ['version' => ltrim($release['tag_name'], 'v'), 'url' => $release['html_url']]; - } - } - - return ['version' => 'n/a', 'url' => '']; -} - -/** - * This function checks the current version of the InventoryManager plugin - * and compares it with the latest stable and beta release versions. - * It returns an integer value indicating the update state. - * - * @param string $currentVersion The current version of the plugin. - * @param string $checkStableVersion The latest stable release version. - * @param string $checkBetaVersion The latest beta release version. - * @param string $betaRelease The name of the latest beta release. - * @param string $betaFlag The current beta version of the plugin. - * @return int An integer value indicating the update state. - */ -function checkVersion(string $currentVersion, string $checkStableVersion, string $currentBetaVersion, string $checkBetaVersion): int -{ - // Update state (0 = No update, 1 = New stable version, 2 = New beta version, 3 = New stable + beta version) - $update = 0; - - // Zunächst auf stabile Version prüfen - if (version_compare($checkStableVersion, $currentVersion, '>')) { - $update = 1; - } - - // Check for beta version now - $status = version_compare($checkBetaVersion, $currentVersion); - if ($status === 1 || ($status === 0 && version_compare($checkBetaVersion, $currentBetaVersion, '>'))) { - if ($update === 1) { - $update = 3; - } else { - $update = 2; - } - } - - return $update; -} - // Repository information $owner = 'MightyMCoder'; $repo = 'InventoryManager'; @@ -174,10 +71,7 @@ function checkVersion(string $currentVersion, string $checkStableVersion, string // check for update $versionUpdate = checkVersion($PIMVersion, $stableVersion, $PIMBetaVersion, $betaVersion); - -// Only continues in display mode, otherwise the current update state can be -// queried in the $versionUpdate variable. -// $versionUpdate (0 = No update, 1 = New stable version, 2 = New beta version, 3 = New stable + beta version, 99 = No connection) +// $versionUpdate (0 = No update, 1 = New stable version, 2 = New beta version, 3 = New stable + beta version) if ($getMode === 2) { // show update result if ($versionUpdate === 1) { @@ -194,7 +88,6 @@ function checkVersion(string $currentVersion, string $checkStableVersion, string if ($PIMBetaVersion !== 'n/a') { $versionsTextBeta = 'Beta '; } - $versionsText = $gL10n->get('PLG_INVENTORY_MANAGER_USING_CURRENT_VERSION', array($versionsTextBeta)); } @@ -220,3 +113,109 @@ function checkVersion(string $currentVersion, string $checkStableVersion, string

' . $versionsText . ''; } + +/** + * checks the GitHub repository for the latest release version + * + * @param string $owner The owner of the repository + * @param string $repo The name of the repository + * @return array Aarray containing the version number and URL of the latest release + */ +function getLatestReleaseVersion($owner, $repo) : array +{ + $url = "https://api.github.com/repos/$owner/$repo/releases/latest"; + + $options = array( + 'http' => array( + 'method' => 'GET', + 'header' => array( + 'User-Agent: PHP' // Github requires this header + ) + ) + ); + + $context = stream_context_create($options); + $response = @file_get_contents($url, false, $context); + + if ($response === FALSE) { + return array('version' => 'n/a', 'url' => ''); + } + + $data = json_decode($response, true); + + return isset($data['tag_name']) ? array('version' => ltrim($data['tag_name'], 'v'), 'url' => $data['html_url']) : array('version' => 'n/a', 'url' => ''); +} + +/** + * This function checks the GitHub repository for the latest beta release version + * of the InventoryManager plugin. It fetches the release information using + * GitHub's API and returns the version number of the latest beta release. + * + * @param string $owner The owner of the repository + * @param string $repo The name of the repository + * @return array Array containing the version number, release name and URL of the latest beta release + */ +function getLatestBetaReleaseVersion($owner, $repo) : array +{ + $url = "https://api.github.com/repos/$owner/$repo/releases"; + + $options = array( + 'http' => array( + 'method' => 'GET', + 'header' => array( + 'User-Agent: PHP' // Github requires this header + ) + ) + ); + + $context = stream_context_create($options); + $response = @file_get_contents($url, false, $context); + + if ($response === FALSE) { + return array('version' => 'n/a', 'release' => '', 'url' => ''); + } + + $data = json_decode($response, true); + foreach ($data as $release) { + if ($release['prerelease']) { + return array('version' => ltrim($release['tag_name'], 'v'), 'url' => $release['html_url']); + } + } + + return array('version' => 'n/a', 'url' => ''); +} + +/** + * This function checks the current version of the InventoryManager plugin + * and compares it with the latest stable and beta release versions. + * It returns an integer value indicating the update state. + * + * @param string $currentVersion The current version of the plugin + * @param string $checkStableVersion The latest stable release version + * @param string $checkBetaVersion The latest beta release version + * @param string $betaRelease The name of the latest beta release + * @param string $betaFlag The current beta version of the plugin + * @return int The update state (0 = No update, 1 = New stable version, 2 = New beta version, 3 = New stable + beta version) + */ +function checkVersion(string $currentVersion, string $checkStableVersion, string $currentBetaVersion, string $checkBetaVersion) : int +{ + // Update state (0 = No update, 1 = New stable version, 2 = New beta version, 3 = New stable + beta version) + $update = 0; + + // Zunächst auf stabile Version prüfen + if (version_compare($checkStableVersion, $currentVersion, '>')) { + $update = 1; + } + + // Check for beta version now + $status = version_compare($checkBetaVersion, $currentVersion); + if ($status === 1 || ($status === 0 && version_compare($checkBetaVersion, $currentBetaVersion, '>'))) { + if ($update === 1) { + $update = 3; + } else { + $update = 2; + } + } + + return $update; +} \ No newline at end of file diff --git a/preferences/preferences_function.php b/preferences/preferences_function.php index b476d94..c626ddc 100644 --- a/preferences/preferences_function.php +++ b/preferences/preferences_function.php @@ -8,12 +8,18 @@ * @copyright 2024 - today MightyMCoder * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 only * + * * Parameters: + * mode : 1 - write preferences to database + * 2 - show dialog for deinstallation + * 3 - deinstallation + * form : The name of the form preferences that were submitted. + * * - * mode : 1 - write preferences to database - * 2 - show dialog for deinstallation - * 3 - deinstallation - * form : The name of the form preferences that were submitted. + * Methods: + * handleFormSubmission() : Handles the form submission and updates the preferences accordingly. + * showDeinstallationDialog() : Displays the dialog for deinstallation of the plugin. + * performDeinstallation() : Performs the deinstallation of the plugin and cleans up the data. *********************************************************************************************** */ @@ -33,7 +39,7 @@ } // Initialize and check the parameters -$getMode = admFuncVariableIsValid($_GET, 'mode', 'numeric', ['defaultValue' => 1]); +$getMode = admFuncVariableIsValid($_GET, 'mode', 'numeric', array('defaultValue' => 1)); $getForm = admFuncVariableIsValid($_GET, 'form', 'string'); // in ajax mode only return simple text on error @@ -45,7 +51,8 @@ case 1: try { handleFormSubmission($getForm, $pPreferences); - } catch (AdmException $e) { + } + catch (AdmException $e) { $e->showText(); } @@ -69,7 +76,8 @@ * @param object $preferences The preferences object to be updated. * @return void */ -function handleFormSubmission($form, $preferences) { +function handleFormSubmission($form, $preferences) : void +{ switch ($form) { case 'interface_pff_preferences': $preferences->config['Optionen']['interface_pff'] = $_POST['interface_pff']; @@ -108,7 +116,8 @@ function handleFormSubmission($form, $preferences) { * * @return void */ -function showDeinstallationDialog() { +function showDeinstallationDialog() : void +{ global $gL10n, $gNavigation; $headline = $gL10n->get('PLG_INVENTORY_MANAGER_DEINSTALLATION'); @@ -122,8 +131,9 @@ function showDeinstallationDialog() { $page->addHtml('

' . $gL10n->get('PLG_INVENTORY_MANAGER_DEINSTALLATION_FORM_DESC') . '

'); // show form - $form = new HtmlForm('deinstallation_form', SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM . '/preferences/preferences_function.php', array('mode' => 3)), $page); $radioButtonEntries = array('0' => $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_ACTORGONLY'), '1' => $gL10n->get('PLG_INVENTORY_MANAGER_DEINST_ALLORG')); + + $form = new HtmlForm('deinstallation_form', SecurityUtils::encodeUrl(ADMIDIO_URL . FOLDER_PLUGINS . PLUGIN_FOLDER_IM . '/preferences/preferences_function.php', array('mode' => 3)), $page); $form->addRadioButton('deinst_org_select', $gL10n->get('PLG_INVENTORY_MANAGER_ORG_CHOICE'), $radioButtonEntries, array('defaultValue' => '0')); $form->addSubmitButton('btn_deinstall', $gL10n->get('PLG_INVENTORY_MANAGER_DEINSTALLATION'), array('icon' => 'fa-trash-alt', 'class' => 'offset-sm-3')); @@ -138,7 +148,8 @@ function showDeinstallationDialog() { * @param object $preferences The preferences object to be cleaned up. * @return void */ -function performDeinstallation($preferences) { +function performDeinstallation($preferences) : void +{ global $gNavigation, $gMessage, $gHomepage, $gL10n; $gNavigation->clear();