From af7936afa75eb083605993b064109d1af049c48f Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Wed, 5 Dec 2018 16:17:43 +0100 Subject: [PATCH 01/33] build: disable official releas flag Signed-off-by: Thierry Bugier --- setup.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.php b/setup.php index f9ab13f2c..dca61e6b9 100644 --- a/setup.php +++ b/setup.php @@ -37,7 +37,7 @@ // Schema version of this version define('PLUGIN_FORMCREATOR_SCHEMA_VERSION', '2.7'); // is or is not an official release of the plugin -define('PLUGIN_FORMCREATOR_IS_OFFICIAL_RELEASE', true); +define('PLUGIN_FORMCREATOR_IS_OFFICIAL_RELEASE', false); // Minimal GLPI version, inclusive define ('PLUGIN_FORMCREATOR_GLPI_MIN_VERSION', '9.3.0'); From 167c43ff874d6fa6dfacf0dfeda7550e6aa078b5 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Thu, 6 Dec 2018 14:52:43 +0100 Subject: [PATCH 02/33] fix(textfield): abuse escaping Signed-off-by: Thierry Bugier --- inc/fields/textfield.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inc/fields/textfield.class.php b/inc/fields/textfield.class.php index e6d606963..767001917 100644 --- a/inc/fields/textfield.class.php +++ b/inc/fields/textfield.class.php @@ -79,7 +79,7 @@ public function getValueForDesign() { } public function getValueForTargetText($richText) { - return Toolbox::addslashes_deep($this->value); + return $this->value; } public function getDocumentsForTarget() { From 1849e61fdcef58877e342e4bb5e99e68bcca4749 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Mon, 10 Dec 2018 17:08:58 +0100 Subject: [PATCH 03/33] fix(urgencyfield): default value Signed-off-by: Thierry Bugier --- inc/fields/urgencyfield.class.php | 7 +++++-- inc/question.class.php | 4 ++-- tests/suite-integration/PluginFormcreatorTargetTicket.php | 1 + 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/inc/fields/urgencyfield.class.php b/inc/fields/urgencyfield.class.php index 2df943e9c..ef2ff1137 100644 --- a/inc/fields/urgencyfield.class.php +++ b/inc/fields/urgencyfield.class.php @@ -63,6 +63,9 @@ public static function getName() { } public function prepareQuestionInputForSave($input) { + $this->value = $input['default_values'] != '' + ? (int) $input['default_values'] + : '3'; return $input; } @@ -103,7 +106,7 @@ public function getAvailableValues() { public function serializeValue() { if ($this->value === null || $this->value === '') { - return ''; + return '3'; } return $this->value; @@ -112,7 +115,7 @@ public function serializeValue() { public function deserializeValue($value) { $this->value = ($value !== null && $value !== '') ? $value - : ''; + : '3'; } public function getValueForDesign() { diff --git a/inc/question.class.php b/inc/question.class.php index 2a255fdef..91ec7cc19 100644 --- a/inc/question.class.php +++ b/inc/question.class.php @@ -264,8 +264,8 @@ public static function showForForm(CommonDBTM $item, $withtemplate = '') { /** * Validate form fields before add or update a question - * @param Array $input Datas used to add the item - * @return Array The modified $input array + * @param array $input Datas used to add the item + * @return array The modified $input array */ private function checkBeforeSave($input) { // Control fields values : diff --git a/tests/suite-integration/PluginFormcreatorTargetTicket.php b/tests/suite-integration/PluginFormcreatorTargetTicket.php index 312752b35..678ba4e71 100644 --- a/tests/suite-integration/PluginFormcreatorTargetTicket.php +++ b/tests/suite-integration/PluginFormcreatorTargetTicket.php @@ -124,6 +124,7 @@ public function testUrgency() { [ 'name' => 'custom urgency', 'fieldtype' => 'urgency', + 'default_values' => '3', ], ], ], From 6270c5b5316c91e899ed16dcf698a228f066f1e9 Mon Sep 17 00:00:00 2001 From: Alexandre Delaunay Date: Tue, 18 Dec 2018 08:36:02 +0100 Subject: [PATCH 04/33] refactor: comaptibility with GLPI 9.3 and 9.4 * replace all 'find' occurence * test getCategoryTree * manage dropdown's condition * factorize insertion of displayPreferences * tests/logsstderr.log should be tests/logs/stderr.log * remove deprecations of 9.3 --- .travis.yml | 12 +- front/formdisplay.php | 14 +- front/targetchange.form.php | 28 ++- front/targetticket.form.php | 12 +- hook.php | 28 ++- inc/category.class.php | 32 ++- inc/common.class.php | 18 +- inc/composite.class.php | 14 +- inc/fields/dropdownfield.class.php | 32 ++- inc/fields/tagfield.class.php | 25 +- inc/form.class.php | 234 +++++++++++------- inc/formanswer.class.php | 66 +++-- inc/issue.class.php | 25 +- inc/question.class.php | 88 +++++-- inc/question_condition.class.php | 11 +- inc/section.class.php | 99 +++++--- inc/target.class.php | 46 +++- inc/targetbase.class.php | 59 +++-- inc/targetchange.class.php | 75 ++++-- inc/targetticket.class.php | 208 +++++++++++----- inc/wizard.class.php | 11 +- install/install.php | 73 ++---- install/upgrade_to_2.5.php | 101 ++++---- install/upgrade_to_2.6.php | 26 +- setup.php | 15 +- tests/bootstrap.php | 2 +- .../PluginFormcreatorForm.php | 85 +++++-- .../PluginFormcreatorSection.php | 23 +- .../PluginFormcreatorTargetTicket.php | 16 +- tests/suite-uninstall/Config.php | 22 +- .../suite-unit/PluginFormcreatorCategory.php | 96 +++++++ tests/suite-unit/PluginFormcreatorForm.php | 22 +- tests/suite-unit/PluginFormcreatorSection.php | 21 +- 33 files changed, 1115 insertions(+), 524 deletions(-) create mode 100644 tests/suite-unit/PluginFormcreatorCategory.php diff --git a/.travis.yml b/.travis.yml index a74d83d55..6f102afaf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,23 +6,25 @@ env: - CS=7.2 - DBNAME=glpitest - OLDDBNAME=glpiupgradetest - - AFTER_SUCCESS_BRANCH=9.3/bugfixes + - AFTER_SUCCESS_BRANCH=9.4/bugfixes matrix: - GLPI_BRANCH=9.3.0 - GLPI_BRANCH=9.3/bugfixes - - GLPI_BRANCH=master + - GLPI_BRANCH=9.4/bugfixes +# - GLPI_BRANCH=master php: - 5.6 - 7.0 - 7.1 - 7.2 + - 7.3 - nightly matrix: allow_failures: - php: nightly - - env: GLPI_BRANCH=master +# - env: GLPI_BRANCH=master before_script: - "./tests/before_script.sh" @@ -30,13 +32,13 @@ before_script: script: - if [ "${TRAVIS_PHP_VERSION:0:3}" = "$CS" ] && [ "$GLPI_BRANCH" = "$AFTER_SUCCESS_BRANCH" ]; then COVERAGE="--nccfc CommonTreeDropdown CommonDropdown CommonDBTM CommonGLPI"; else COVERAGE="-ncc"; fi - if [ -e ../../scripts/cliinstall.php ] ; then php ../../scripts/cliinstall.php --db=$OLDDBNAME --user=root --tests ; fi - - if [ -e ../../tools/cliinstall.php ] ; then php ../../tools/cliinstall.php --db=$OLDDBNAME --user=root --tests ; fi + - if [ -e ../../bin/console ] ; then php ../../bin/console glpi:database:install --db-name=$OLDDBNAME --db-user=root --config-dir=../../tests --no-interaction --force; fi - mysql -u root $OLDDBNAME < tests/plugin_formcreator_empty_2.5.0.sql - mysql -u root $OLDDBNAME < tests/plugin_formcreator_config_2.5.0.sql - php scripts/cliinstall.php --tests - rm ../../tests/config_db.php - if [ -e ../../scripts/cliinstall.php ] ; then php ../../scripts/cliinstall.php --db=$DBNAME --user=root --tests ; fi - - if [ -e ../../tools/cliinstall.php ] ; then php ../../tools/cliinstall.php --db=$DBNAME --user=root --tests ; fi + - if [ -e ../../bin/console ] ; then php ../../bin/console glpi:database:install --db-name=$DBNAME --db-user=root --config-dir=../../tests --no-interaction --force; fi - vendor/bin/atoum -ft -bf tests/bootstrap.php -d tests/suite-install -ncc - vendor/bin/atoum -ft -bf tests/bootstrap.php -d tests/suite-integration $COVERAGE - vendor/bin/atoum -ft -bf tests/bootstrap.php -d tests/suite-unit $COVERAGE diff --git a/front/formdisplay.php b/front/formdisplay.php index 67b7690d7..5e8bce919 100644 --- a/front/formdisplay.php +++ b/front/formdisplay.php @@ -56,12 +56,14 @@ } if ($form->fields['access_rights'] == PluginFormcreatorForm::ACCESS_RESTRICTED) { - $form_profile = new PluginFormcreatorForm_Profile(); - $formId = $form->getID(); - $activeProfileId = $_SESSION['glpiactiveprofile']['id']; - $rows = $form_profile->find("profiles_id = '$activeProfileId' - AND plugin_formcreator_forms_id = '$formId'", "", "1"); - if (count($rows) == 0) { + $iterator = $DB->request(PluginFormcreatorForm_Profile::getTable(), [ + 'WHERE' => [ + 'profiles_id' => $_SESSION['glpiactiveprofile']['id'], + 'plugin_formcreator_forms_id' => $form->getID() + ], + 'LIMIT' => 1 + ]); + if (count($iterator) == 0) { Html::displayRightError(); exit(); } diff --git a/front/targetchange.form.php b/front/targetchange.form.php index bbce1218f..b784fc66f 100644 --- a/front/targetchange.form.php +++ b/front/targetchange.form.php @@ -40,15 +40,17 @@ if (!$plugin->isActivated('formcreator')) { Html::displayNotFoundError(); } -$targetticket = new PluginFormcreatorTargetChange(); +$targetchange = new PluginFormcreatorTargetChange(); // Edit an existing target change if (isset($_POST["update"])) { - $target = new PluginFormcreatorTarget(); - $found = $target->find('items_id = ' . (int) $_POST['id']); - $found = array_shift($found); - $target->update(['id' => $found['id'], 'name' => $_POST['name']]); - $targetticket->update($_POST); + $DB->update(PluginFormcreatorTarget::getTable(), [ + 'name' => $_POST['name'] + ], [ + 'items_id' => (int) $_POST['id'], + 'itemtype' => 'PluginFormcreatorTargetChange' + ]); + $targetchange->update($_POST); Html::back(); } else if (isset($_POST['actor_role'])) { @@ -84,9 +86,15 @@ ); $itemtype = "PluginFormcreatorTargetChange"; - $target = new PluginFormcreatorTarget; - $found = $target->find("itemtype = '$itemtype' AND items_id = " . (int) $_REQUEST['id']); - $first = array_shift($found); + $iterator = $DB->request([ + 'SELECT' => ['plugin_formcreator_forms_id'], + 'FROM' => PluginFormcreatorTarget::getTable(), + 'WHERE' => [ + 'itemtype' => $itemtype, + 'items_id' => (int) $_REQUEST['id'], + ] + ]); + $first = $iterator->next(); $form = new PluginFormcreatorForm; $form->getFromDB($first['plugin_formcreator_forms_id']); @@ -94,7 +102,7 @@ $form->getTypeName(1), $form->getName()); $_SESSION['glpilisturl'][$itemtype] = $form->getFormURL()."?id=".$form->getID(); - $targetticket->display($_REQUEST); + $targetchange->display($_REQUEST); Html::footer(); } diff --git a/front/targetticket.form.php b/front/targetticket.form.php index 7089e374f..258ef40df 100644 --- a/front/targetticket.form.php +++ b/front/targetticket.form.php @@ -80,9 +80,15 @@ ); $itemtype = "PluginFormcreatorTargetTicket"; - $target = new PluginFormcreatorTarget; - $found = $target->find("itemtype = '$itemtype' AND items_id = " . (int) $_REQUEST['id']); - $first = array_shift($found); + $iterator = $DB->request([ + 'SELECT' => ['plugin_formcreator_forms_id'], + 'FROM' => PluginFormcreatorTarget::getTable(), + 'WHERE' => [ + 'itemtype' => $itemtype, + 'items_id' => (int) $_REQUEST['id'], + ] + ]); + $first = $iterator->next(); $form = new PluginFormcreatorForm; $form->getFromDB($first['plugin_formcreator_forms_id']); diff --git a/hook.php b/hook.php index b5c412551..d1279653a 100644 --- a/hook.php +++ b/hook.php @@ -334,13 +334,21 @@ function plugin_formcreator_hook_update_ticket(CommonDBTM $item) { } function plugin_formcreator_hook_delete_ticket(CommonDBTM $item) { + global $DB; + if ($item instanceof Ticket) { $id = $item->getID(); // mark formanswers as deleted - $item_ticket = new Item_Ticket(); - $rows = $item_ticket->find("`itemtype` = 'PluginFormcreatorFormAnswer' AND `tickets_id` = '$id'"); - foreach ($rows as $row) { + $iterator = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => Item_Ticket::getTable(), + 'WHERE' => [ + 'itemtype' => 'PluginFormcreatorFormAnswer', + 'tickets_id' => $id, + ] + ]); + foreach ($iterator as $row) { $form_answer = new PluginFormcreatorFormAnswer(); $form_answer->update([ 'id' => $row['id'], @@ -358,13 +366,21 @@ function plugin_formcreator_hook_delete_ticket(CommonDBTM $item) { } function plugin_formcreator_hook_restore_ticket(CommonDBTM $item) { + global $DB; + if ($item instanceof Ticket) { $id = $item->getID(); // Restore deletes form_answers - $item_ticket = new Item_Ticket(); - $rows = $item_ticket->find("`itemtype` = 'PluginFormcreatorFormAnswer' AND `tickets_id` = '$id'"); - foreach ($rows as $row) { + $iterator = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => Item_Ticket::getTable(), + 'WHERE' => [ + 'itemtype' => 'PluginFormcreatorFormAnswer', + 'tickets_id' => $id, + ] + ]); + foreach ($iterator as $row) { $form_answer = new PluginFormcreatorFormAnswer(); $form_answer->update([ 'id' => $row['id'], diff --git a/inc/category.class.php b/inc/category.class.php index 0e1489c7a..675cf0b41 100644 --- a/inc/category.class.php +++ b/inc/category.class.php @@ -80,18 +80,19 @@ public function getAdditionalFields() { * @return array Tree of form categories as nested array */ public static function getCategoryTree($rootId = 0, $helpdeskHome = false) { + global $DB; + $cat_table = PluginFormcreatorCategory::getTable(); $form_table = PluginFormcreatorForm::getTable(); $table_fp = PluginFormcreatorForm_Profile::getTable(); + $helpdesk = ''; if ($helpdeskHome) { $helpdesk = "AND $form_table.`helpdesk_home` = 1"; - } else { - $helpdesk = ''; } $query_faqs = KnowbaseItem::getListRequest([ - 'faq' => '1', - 'contains' => '' + 'faq' => '1', + 'contains' => '' ]); // Selects categories containing forms or sub-categories @@ -118,20 +119,35 @@ public static function getCategoryTree($rootId = 0, $helpdeskHome = false) { AND `faqs`.`knowbaseitemcategories_id` <> '0' ) > 0"; - $formCategory = new self(); if ($rootId == 0) { - $items = $formCategory->find("`level`='1' AND ($where)", '`name`'); + $query = "SELECT * + FROM $cat_table + WHERE `level` = '1' + AND ($where) + ORDER BY `name`"; $name = ''; $parent = 0; } else { - $items = $formCategory->find("`plugin_formcreator_categories_id`='$rootId' AND ($where)", - '`name`'); + $query = "SELECT * + FROM $cat_table + WHERE `plugin_formcreator_categories_id` = '$rootId' + AND ($where) + ORDER BY `name`"; $formCategory = new self(); $formCategory->getFromDB($rootId); $name = $formCategory->getField('name'); $parent = $formCategory->getField('plugin_formcreator_categories_id'); } + $items = []; + if ($result = $DB->query($query)) { + if ($DB->numrows($result)) { + while ($item = $DB->fetch_assoc($result)) { + $items[$item['id']] = $item; + } + } + } + // No sub-categories, then return if (count($items) == 0) { return [ diff --git a/inc/common.class.php b/inc/common.class.php index f5e0b1d7d..e5fa0bff3 100644 --- a/inc/common.class.php +++ b/inc/common.class.php @@ -121,14 +121,22 @@ public static function getFormcreatorRequestTypeId() { /** * Get the maximum value of a column for a given itemtype * @param CommonDBTM $item - * @param string $condition + * @param array $condition * @param string $fieldName * @return NULL|integer */ - public static function getMax(CommonDBTM $item, $condition, $fieldName) { - $rows = $item->find($condition, "`$fieldName` DESC", '1'); - $line = array_pop($rows); - if ($line === null) { + public static function getMax(CommonDBTM $item, array $condition, $fieldName) { + global $DB; + + $line = $DB->request([ + 'SELECT' => [$fieldName], + 'FROM' => $item::getTable(), + 'WHERE' => $condition, + 'ORDER' => "$fieldName DESC", + 'LIMIT' => 1 + ])->next(); + + if ($line === false) { return null; } return (int) $line[$fieldName]; diff --git a/inc/composite.class.php b/inc/composite.class.php index 36eb703bc..818e4e495 100644 --- a/inc/composite.class.php +++ b/inc/composite.class.php @@ -60,9 +60,21 @@ public function addTarget(PluginFormcreatorTargetBase $target, CommonDBTM $gener } public function buildCompositeRelations() { + global $DB; + if (isset($this->targets['PluginFormcreatorTargetTicket'])) { foreach ($this->targets['PluginFormcreatorTargetTicket'] as $targetId => $generatedObject) { - $rows = $this->item_targetTicket->find("`plugin_formcreator_targettickets_id` = '$targetId'"); + $rows = $DB->request([ + 'SELECT' => [ + 'itemtype', + 'items_id', + 'link' + ], + 'FROM' => $this->item_targetTicket->getTable(), + 'WHERE' => [ + 'plugin_formcreator_targettickets_id' => $targetId + ] + ]); foreach ($rows as $row) { switch ($row['itemtype']) { case 'Ticket': diff --git a/inc/fields/dropdownfield.class.php b/inc/fields/dropdownfield.class.php index beff4e2c9..8508326b2 100644 --- a/inc/fields/dropdownfield.class.php +++ b/inc/fields/dropdownfield.class.php @@ -60,6 +60,7 @@ public function displayField($canEdit = true) { 'entity' => $_SESSION['glpiactive_entity'], 'rand' => $rand]; + $dparams_cond_crit = []; switch ($itemtype) { case User::class: $dparams['right'] = 'all'; @@ -70,27 +71,41 @@ public function displayField($canEdit = true) { if (isset ($_SESSION['glpiactiveprofile']['interface']) && $_SESSION['glpiactiveprofile']['interface'] == 'helpdesk') { $dparams['condition'] .= " AND `is_helpdeskvisible` = '1'"; + $dparams_cond_crit['is_helpdeskvisible'] = 1; } switch ($decodedValues['show_ticket_categories']) { case 'request': $dparams['condition'] .= " AND `is_request` = '1'"; + $dparams_cond_crit['is_request'] = 1; break; case 'incident': $dparams['condition'] .= " AND `is_incident` = '1'"; + $dparams_cond_crit['is_incident'] = 1; break; case 'both': $dparams['condition'] .= " AND (`is_incident` = '1' OR `is_request` = '1')"; + $dparams_cond_crit['OR'] = [ + 'is_incident' => 1, + 'is_request' => 1, + ]; break; case 'change': $dparams['condition'] .= " AND `is_change` = '1'"; + $dparams_cond_crit['is_change'] = 1; break; case 'all': $dparams['condition'] .= " AND (`is_change` = '1' OR `is_incident` = '1' OR `is_request` = '1')"; + $dparams_cond_crit['OR'] = [ + 'is_change' => 1, + 'is_incident' => 1, + 'is_request' => 1, + ]; break; } if (isset($decodedValues['show_ticket_categories_depth']) && $decodedValues['show_ticket_categories_depth'] > 0) { $dparams['condition'] .= " AND `level` <= '" . $decodedValues['show_ticket_categories_depth'] . "'"; + $dparams_cond_crit['level'] = ['<=', $decodedValues['show_ticket_categories_depth']]; } if (isset($decodedValues['show_ticket_categories_root']) && (int) $decodedValues['show_ticket_categories_root'] > 0) { @@ -100,6 +115,7 @@ public function displayField($canEdit = true) { ); $sons = "'" . implode("', '", $sons) . "'"; $dparams['condition'] .= " AND `id` IN ('" . $decodedValues['show_ticket_categories_root'] . "')"; + $dparams_cond_crit['id'] = $decodedValues['show_ticket_categories_root']; } break; @@ -118,15 +134,27 @@ public function displayField($canEdit = true) { && !$canViewAllHardware && $canViewMyHardware) { $userId = $_SESSION['glpiID']; $dparams['condition'] = "`$userFk`='$userId'"; + $dparams_cond_crit[$userFk] = $userId; } if ($DB->fieldExists($itemtype::getTable(), $groupFk) && !$canViewAllHardware && count($groups) > 0) { + $dparams_cond_crit = [ + 'OR' => [ + $groupFk => $groups, + ] + $dparams_cond_crit + ]; $groups = implode("', '", $groups); $dparams['condition'] .= " OR `$groupFk` IN ('$groups')"; } } } + // TODO remove if and the above raw queries (in $dparams['condition']) + // when 9.3/bf compat will no be needed anymore + if (version_compare(GLPI_VERSION, "9.4", '>=')) { + $dparams['condition'] = $dparams_cond_crit; + } + $itemtype::dropdown($dparams); } echo PHP_EOL; @@ -308,7 +336,7 @@ public function equals($value) { if (!$dropdown->getFromDB($this->value)) { throw new PluginFormcreatorComparisonException('Item not found for comparison'); } - if (is_a($dropdown, CommonTreeDropdown::class)) { + if ($dropdown instanceof CommonTreeDropdown) { $name = $dropdown->getField($dropdown->getCompleteNameField()); } else { $name = $dropdown->getField($dropdown->getNameField()); @@ -327,7 +355,7 @@ public function greaterThan($value) { if (!$dropdown->getFromDB($this->value)) { throw new PluginFormcreatorComparisonException('Item not found for comparison'); } - if (is_a($dropdown, CommonTreeDropdown::class)) { + if ($dropdown instanceof CommonTreeDropdown) { $name = $dropdown->getField($dropdown->getCompleteNameField()); } else { $name = $dropdown->getField($dropdown->getNameField()); diff --git a/inc/fields/tagfield.class.php b/inc/fields/tagfield.class.php index 51e967d17..7e740293c 100644 --- a/inc/fields/tagfield.class.php +++ b/inc/fields/tagfield.class.php @@ -38,27 +38,30 @@ public function isPrerequisites() { } public function displayField($canEdit = true) { + global $DB; + $id = $this->fields['id']; $rand = mt_rand(); $fieldName = 'formcreator_field_' . $id; - $domId = $fieldName . $rand; if ($canEdit) { if (!class_exists(PluginTagTag::class)) { // Plugin Tag not available echo ''; return; } - $required = $this->fields['required'] ? ' required' : ''; - + $result = $DB->request([ + 'SELECT' => ['id', 'name'], + 'FROM' => PluginTagTag::getTable(), + 'WHERE' => [ + 'OR' => [ + ['type_menu' => ['LIKE', '%\"Ticket\"%']], + ['type_menu' => ['LIKE', '%\"Change\"%']], + ['type_menu' => ['LIKE', '0']], + ] + ] + getEntitiesRestrictCriteria(PluginTagTag::getTable(), '', '', true), + 'ORDER' => 'name' + ]); $values = []; - - $obj = new PluginTagTag(); - $obj->getEmpty(); - - $where = "(`type_menu` LIKE '%\"Ticket\"%' OR`type_menu` LIKE '%\"Change\"%' OR `type_menu` LIKE '0')"; - $where .= getEntitiesRestrictRequest('AND', getTableForItemType(PluginTagTag::class), '', '', true); - - $result = $obj->find($where, 'name'); foreach ($result AS $id => $data) { $values[$id] = $data['name']; } diff --git a/inc/form.class.php b/inc/form.class.php index b808b0596..2e7b81cc9 100644 --- a/inc/form.class.php +++ b/inc/form.class.php @@ -110,15 +110,6 @@ static function getMenuContent() { return $menu; } - /** - * Define search options for forms - * - * @return Array Array of fields to show in search engine and options for each fields - */ - public function getSearchOptionsNew() { - return $this->rawSearchOptions(); - } - public function rawSearchOptions() { $tab = []; @@ -417,10 +408,14 @@ public function showForm($ID, $options = []) { ]); // Validators users + $rows = $DB->request([ + 'SELECT' => ['items_id'], + 'FROM' => PluginFormcreatorForm_Validator::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $this->getID() + ] + ]); $validators = []; - $formId = $this->getID(); - $form_validator = new PluginFormcreatorForm_Validator(); - $rows = $form_validator->find("`plugin_formcreator_forms_id` = '$formId'"); foreach ($rows as $row) { $validators[] = $row['items_id']; } @@ -529,11 +524,12 @@ public function showForm($ID, $options = []) { * @return String Name to be displayed */ public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { + global $DB; + switch ($item->getType()) { case PluginFormcreatorConfig::class: - $object = new self; - $found = $object->find(); - $number = count($found); + $found = $DB->request(self::getTable(), []); + $number = count($found); return self::createTabEntry(self::getTypeName($number), $number); break; case PluginFormcreatorForm::class: @@ -919,7 +915,6 @@ public function displayUserForm() { echo Html::css("plugins/formcreator/css/print_form.css", ['media' => 'print']); // Display form - $formName = 'formcreator_form' . $this->getID(); echo "
"; @@ -936,17 +931,29 @@ class='formcreator_form form_horizontal'>"; echo ''; } // Get and display sections of the form - $question = new PluginFormcreatorQuestion(); $questions = []; - $section_class = new PluginFormcreatorSection(); - $find_sections = $section_class->find('plugin_formcreator_forms_id = ' . $this->getID(), '`order` ASC'); + $find_sections = $DB->request([ + 'SELECT' => ['id', 'name'], + 'FROM' => PluginFormcreatorSection::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $this->getID() + ], + 'ORDER' => 'order ASC' + ]); echo '
'; foreach ($find_sections as $section_line) { echo '

' . $section_line['name'] . '

'; // Display all fields of the section - $questions = $question->find('plugin_formcreator_sections_id = ' . $section_line['id'], '`order` ASC'); + $questions = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => PluginFormcreatorQuestion::getTable(), + 'WHERE' => [ + 'plugin_formcreator_sections_id' => $section_line['id'] + ], + 'ORDER' => 'order ASC' + ]); foreach ($questions as $question_line) { $question = new PluginFormcreatorQuestion(); $question->getFromDB($question_line['id']); @@ -1176,7 +1183,6 @@ public function saveForm($input) { $found_questions = $question->getQuestionsFromForm($this->getID()); foreach ($found_questions as $id => $question) { - $key = 'formcreator_field_' . $id; $fields[$id] = PluginFormcreatorFields::getFieldInstance( $question->fields['fieldtype'], $question @@ -1230,36 +1236,25 @@ public function increaseUsageCount() { public function getByQuestionId($questionId) { $table_sections = PluginFormcreatorSection::getTable(); $table_questions = PluginFormcreatorQuestion::getTable(); - if (!method_exists($this, 'getFromDBByRequest')) { - $this->getFromDBByQuery( - "WHERE `id` = ( - SELECT `plugin_formcreator_forms_id` FROM `$table_sections` - INNER JOIN `$table_questions` - ON `$table_questions`.`plugin_formcreator_sections_id` = `$table_sections`.`id` - WHERE `$table_questions`.`id` = '$questionId' - )" - ); - } else { - $this->getFromDBByRequest([ - 'INNER JOIN' => [ - PluginFormcreatorSection::getTable() => [ - 'FKEY' => [ - PluginFormcreatorForm::getTable() => 'id', - PluginFormcreatorSection::getTable() => PluginFormcreatorSection::getForeignKeyField(), - ] - ], - PluginFormcreatorQuestion::getTable() => [ - 'FKEY' => [ - PluginFormcreatorQuestion::getTable() => PluginFormcreatorSection::getForeignKeyField(), - PluginFormcreatorSection::getTable() => 'id' - ] + $this->getFromDBByRequest([ + 'INNER JOIN' => [ + PluginFormcreatorSection::getTable() => [ + 'FKEY' => [ + PluginFormcreatorForm::getTable() => 'id', + PluginFormcreatorSection::getTable() => PluginFormcreatorSection::getForeignKeyField(), ] ], - 'WHERE' => [ - PluginFormcreatorQuestion::getTable() . '.id' => $questionId, + PluginFormcreatorQuestion::getTable() => [ + 'FKEY' => [ + PluginFormcreatorQuestion::getTable() => PluginFormcreatorSection::getForeignKeyField(), + PluginFormcreatorSection::getTable() => 'id' + ] ] - ]); - } + ], + 'WHERE' => [ + PluginFormcreatorQuestion::getTable() . '.id' => $questionId, + ] + ]); } /** @@ -1270,6 +1265,8 @@ public function getByQuestionId($questionId) { * @return Boolean true if success, false otherwise. */ public function duplicate() { + global $DB; + $target = new PluginFormcreatorTarget(); $target_ticket = new PluginFormcreatorTargetTicket(); $target_change = new PluginFormcreatorTargetChange(); @@ -1297,7 +1294,12 @@ public function duplicate() { } // Form profiles - $rows = $form_profile->find("`plugin_formcreator_forms_id` = '$old_form_id'"); + $rows = $DB->request([ + 'FROM' => $form_profile::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $old_form_id + ] + ]); foreach ($rows as $row) { unset($row['id'], $row['uuid']); @@ -1308,7 +1310,12 @@ public function duplicate() { } // Form validators - $rows = $form_validator->find("`plugin_formcreator_forms_id` = '$old_form_id'"); + $rows = $DB->request([ + 'FROM' => $form_validator::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $old_form_id + ] + ]); foreach ($rows as $row) { unset($row['id'], $row['uuid']); @@ -1319,8 +1326,15 @@ public function duplicate() { } // Form sections - $sectionRows = $form_section->find("`plugin_formcreator_forms_id` = '$old_form_id'", "`order` ASC"); - foreach ($sectionRows as $sections_id => $sectionRow) { + $sectionRows = $DB->request([ + 'FROM' => $form_section::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $old_form_id + ], + 'ORDER' => 'order ASC' + ]); + foreach ($sectionRows as $sectionRow) { + $sections_id = $sectionRow['id']; unset($sectionRow['id'], $sectionRow['uuid']); $sectionRow['plugin_formcreator_forms_id'] = $new_form_id; @@ -1330,8 +1344,15 @@ public function duplicate() { } // Form questions - $questionRows = $section_question->find("`plugin_formcreator_sections_id` = '$sections_id'", "`order` ASC"); - foreach ($questionRows as $questions_id => $questionRow) { + $questionRows = $DB->request([ + 'FROM' => $section_question::getTable(), + 'WHERE' => [ + 'plugin_formcreator_sections_id' => $sections_id + ], + 'ORDER' => 'order ASC' + ]); + foreach ($questionRows as $questionRow) { + $questions_id = $questionRow['id']; unset($questionRow['id'], $questionRow['uuid']); $questionRow['plugin_formcreator_sections_id'] = $new_sections_id; @@ -1356,7 +1377,7 @@ public function duplicate() { $oldQuestion ); $parameters = $field->getParameters(); - foreach ($parameters as $fieldName => $parameter) { + foreach ($parameters as $parameter) { $newQuestion = new PluginFormcreatorQuestion(); $newQuestion->getFromDB($new_questions_id); $parameter = $parameter->duplicate($newQuestion, $tab_questions); @@ -1365,22 +1386,33 @@ public function duplicate() { } // Form questions conditions - $questionIds = implode("', '", array_keys($tab_questions)); - $rows = $question_condition->find("`plugin_formcreator_questions_id` IN ('$questionIds')"); - foreach ($rows as $row) { - unset($row['id'], - $row['uuid']); - $row['show_field'] = $tab_questions[$row['show_field']]; - $row['plugin_formcreator_questions_id'] = $tab_questions[$row['plugin_formcreator_questions_id']]; - $row['show_value'] = Toolbox::addslashes_deep($row['show_value']); - if (!$question_condition->add($row)) { - return false; + if (count($tab_questions)) { + $qc_rows = $DB->request([ + 'FROM' => $question_condition::getTable(), + 'WHERE' => [ + 'plugin_formcreator_questions_id' => $tab_questions + ] + ]); + foreach ($qc_rows as $row) { + unset($row['id'], + $row['uuid']); + $row['show_field'] = $tab_questions[$row['show_field']]; + $row['plugin_formcreator_questions_id'] = $tab_questions[$row['plugin_formcreator_questions_id']]; + $row['show_value'] = Toolbox::addslashes_deep($row['show_value']); + if (!$question_condition->add($row)) { + return false; + } } } // Form targets - $rows = $target->find("`plugin_formcreator_forms_id` = '$old_form_id'"); - foreach ($rows as $target_values) { + $t_rows = $DB->request([ + 'FROM' => $target::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $old_form_id + ] + ]); + foreach ($t_rows as $target_values) { unset($target_values['id'], $target_values['uuid']); $target_values['plugin_formcreator_forms_id'] = $new_form_id; @@ -1516,12 +1548,17 @@ public function duplicate() { ]); // Form target tickets actors - $rows = $target_ticket_actor->find("`plugin_formcreator_targettickets_id` = '{$target_values['items_id']}'"); - foreach ($rows as $row) { - unset($row['id'], - $row['uuid']); - $row['plugin_formcreator_targettickets_id'] = $new_target_item_id; - if (!$target_ticket_actor->add($row)) { + $tta_rows = $DB->request([ + 'FROM' => $target_ticket_actor::getTable(), + 'WHERE' => [ + 'plugin_formcreator_targettickets_id' => $target_values['items_id'] + ] + ]); + foreach ($tta_rows as $tta_row) { + unset($tta_row['id'], + $tta_row['uuid']); + $tta_row['plugin_formcreator_targettickets_id'] = $new_target_item_id; + if (!$target_ticket_actor->add($tta_row)) { return false; } } @@ -1534,12 +1571,17 @@ public function duplicate() { ]); // Form target change actors - $rows = $target_change_actor->find("`plugin_formcreator_targetchanges_id` = '{$target_values['items_id']}'"); - foreach ($rows as $row) { - unset($row['id'], - $row['uuid']); - $row['plugin_formcreator_targetchanges_id'] = $new_target_item_id; - if (!$target_change_actor->add($row)) { + $tca_rows = $DB->request([ + 'FROM' => $target_change_actor::getTable(), + 'WHERE' => [ + 'plugin_formcreator_targetchanges_id' => $target_values['items_id'] + ] + ]); + foreach ($tca_rows as $tca_row) { + unset($tca_row['id'], + $tca_row['uuid']); + $tca_row['plugin_formcreator_targetchanges_id'] = $new_target_item_id; + if (!$target_change_actor->add($tca_row)) { return false; } } @@ -1672,6 +1714,8 @@ public static function countAvailableForm() { * @return array the array with all data (with sub tables) */ function export($remove_uuid = false) { + global $DB; + if (!$this->getID()) { return false; } @@ -1702,7 +1746,13 @@ function export($remove_uuid = false) { // get sections $form['_sections'] = []; - $all_sections = $form_section->find("plugin_formcreator_forms_id = ".$this->getID()); + $all_sections = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => $form_section::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $this->getID() + ] + ]); foreach ($all_sections as $section) { $form_section->getFromDB($section['id']); $form['_sections'][] = $form_section->export($remove_uuid); @@ -1710,7 +1760,13 @@ function export($remove_uuid = false) { // get validators $form['_validators'] = []; - $all_validators = $form_validator->find("plugin_formcreator_forms_id = ".$this->getID()); + $all_validators = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => $form_validator::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $this->getID() + ] + ]); foreach ($all_validators as $validator) { $form_validator->getFromDB($validator['id']); $form['_validators'][] = $form_validator->export($remove_uuid); @@ -1718,7 +1774,13 @@ function export($remove_uuid = false) { // get targets $form['_targets'] = []; - $all_target = $form_target->find("plugin_formcreator_forms_id = ".$this->getID()); + $all_target = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => $form_target::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $this->getID() + ] + ]); foreach ($all_target as $target) { $form_target->getFromDB($target['id']); $form['_targets'][] = $form_target->export($remove_uuid); @@ -1726,7 +1788,13 @@ function export($remove_uuid = false) { // get profiles $form['_profiles'] = []; - $all_profiles = $form_profile->find("plugin_formcreator_forms_id = ".$this->getID()); + $all_profiles = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => $form_profile::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $this->getID() + ] + ]); foreach ($all_profiles as $profile) { $form_profile->getFromDB($profile['id']); $form['_profiles'][] = $form_profile->export($remove_uuid); diff --git a/inc/formanswer.class.php b/inc/formanswer.class.php index 2c6d99853..a10cfe4ec 100644 --- a/inc/formanswer.class.php +++ b/inc/formanswer.class.php @@ -127,15 +127,6 @@ public static function getTypeName($nb = 0) { return _n('Form answer', 'Form answers', $nb, 'formcreator'); } - /** - * Define search options for forms - * - * @return Array Array of fields to show in search engine and options for each fields - */ - public function getSearchOptionsNew() { - return $this->rawSearchOptions(); - } - public function rawSearchOptions() { $tab = []; @@ -380,8 +371,8 @@ static function showForForm(PluginFormcreatorForm $form, $params = []) { $_SESSION['formcreator']['form_search_answers'] = $form->getID(); // prepare params for search - $item = new PluginFormcreatorFormAnswer(); - $searchOptions = $item->getSearchOptionsNew(); + $item = new PluginFormcreatorFormAnswer(); + $searchOptions = $item->rawSearchOptions(); $filteredOptions = []; foreach ($searchOptions as $value) { if (is_numeric($value['id']) && $value['id'] <= 7) { @@ -425,6 +416,19 @@ public function canValidate($form, CommonDBTM $form_answer) { FROM `$table_form_validator` WHERE `itemtype` = 'Group' AND `plugin_formcreator_forms_id` = '$formId' )"; + // TODO remove if and the above raw query when 9.3/bf compat will no be needed anymore + if (version_compare(GLPI_VERSION, "9.4", '>=')) { + $condition = [ + 'glpi_groups.id' => new QuerySubQuery([ + 'SELECT' => ['items_id'], + 'FROM' => $table_form_validator, + 'WHERE' => [ + 'itemtype' => 'Group', + 'plugin_formcreator_forms_id' => $formId + ] + ]) + ]; + } $groupList = Group_User::getUserGroups($userId, $condition); $canValidate = (count($groupList) > 0); } else { @@ -695,6 +699,8 @@ public function pre_deleteItem() { * @return boolean */ public function saveAnswers(PluginFormcreatorForm $form, $data, $fields) { + global $DB; + $formanswers_id = isset($data['id']) ? intval($data['id']) : -1; @@ -779,7 +785,7 @@ public function saveAnswers(PluginFormcreatorForm $form, $data, $fields) { foreach ($fields[$questionId]->getDocumentsForTarget() as $documentId) { $docItem = new Document_Item(); $docItem->add([ - 'documents_id' => $docID, + 'documents_id' => $documentId, 'itemtype' => __CLASS__, 'items_id' => $this->getID(), ]); @@ -832,7 +838,14 @@ public function saveAnswers(PluginFormcreatorForm $form, $data, $fields) { // when several rows matches // Both are processed the same way $itemTicket = new Item_Ticket(); - $rows = $itemTicket->find("`itemtype` = 'PluginFormcreatorFormAnswer' AND `items_id` = '$formAnswerId'"); + $rows = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => $itemTicket::getTable(), + 'WHERE' => [ + 'itemtype' => 'PluginFormcreatorFormAnswer', + 'items_id' => $formAnswerId, + ] + ]); if (count($rows) != 1) { if ($is_newFormAnswer) { // This is a new answer for the form. Create an issue @@ -874,8 +887,8 @@ public function saveAnswers(PluginFormcreatorForm $form, $data, $fields) { } } else { $ticket = new Ticket(); - reset($rows); - $itemTicket->getFromDB(key($rows)); + $result = $rows->next(); + $itemTicket->getFromDB($result['id']); $ticket->getFromDB($itemTicket->getField('tickets_id')); $ticketId = $ticket->getID(); if ($is_newFormAnswer) { @@ -1039,14 +1052,18 @@ public function acceptAnswers($input) { * Generates all targets for the answers */ public function generateTarget() { - global $CFG_GLPI; + global $CFG_GLPI, $DB; $success = true; // Get all targets - $target_class = new PluginFormcreatorTarget(); - $found_targets = $target_class->find('plugin_formcreator_forms_id = ' . $this->fields['plugin_formcreator_forms_id']); - + $found_targets = $DB->request([ + 'SELECT' => ['itemtype', 'items_id'], + 'FROM' => PluginFormcreatorTarget::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $this->fields['plugin_formcreator_forms_id'] + ] + ]); $CFG_GLPI['plugin_formcreator_disable_hook_create_ticket'] = '1'; // Generate targets $generatedTargets = new PluginFormcreatorComposite(new PluginFormcreatorItem_TargetTicket(), new Ticket_Ticket()); @@ -1075,8 +1092,15 @@ public function generateTarget() { * @return array */ public function getAnswers($formAnswerId) { - $answer = new PluginFormcreatorAnswer(); - $answers = $answer->find("`plugin_formcreator_formanswers_id` = '$formAnswerId'"); + global $DB; + + $answers = $DB->request([ + 'SELECT' => ['plugin_formcreator_questions_id', 'answer'], + 'FROM' => PluginFormcreatorAnswer::getTable(), + 'WHERE' => [ + 'plugin_formcreator_formanswers_id' => $formAnswerId + ] + ]); $answers_values = []; foreach ($answers as $found_answer) { $answers_values['formcreator_field_' . $found_answer['plugin_formcreator_questions_id']] = $found_answer['answer']; diff --git a/inc/issue.class.php b/inc/issue.class.php index c684b26de..9c8888bc3 100644 --- a/inc/issue.class.php +++ b/inc/issue.class.php @@ -256,15 +256,21 @@ public function displaySimplified($options = []) { * @return mixed the provide _item key replaced if needed */ public function getTicketsForDisplay($options) { + global $DB; + $item = $options['_item']; $formanswerId = $options['id']; - $item_ticket = new Item_Ticket(); - $rows = $item_ticket->find("`itemtype` = 'PluginFormcreatorFormAnswer' - AND `items_id` = $formanswerId", "`tickets_id` ASC"); - + $rows = $DB->request([ + 'FROM' => Item_Ticket::getTable(), + 'WHERE' => [ + 'itemtype' => 'PluginFormcreatorFormAnswer', + 'items_id' => $formanswerId + ], + 'ORDER' => 'tickets_id ASC' + ]); if (count($rows) == 1) { // one ticket, replace item - $ticket = array_shift($rows); + $ticket = $rows->next(); $item = new Ticket; $item->getFromDB($ticket['tickets_id']); } else if (count($rows) > 1) { @@ -275,15 +281,6 @@ public function getTicketsForDisplay($options) { return $item; } - /** - * Define search options for forms - * - * @return Array Array of fields to show in search engine and options for each fields - */ - public function getSearchOptionsNew() { - return $this->rawSearchOptions(); - } - public function rawSearchOptions() { $tab = []; diff --git a/inc/question.class.php b/inc/question.class.php index 91ec7cc19..affa26274 100644 --- a/inc/question.class.php +++ b/inc/question.class.php @@ -85,20 +85,32 @@ function addMessageOnPurgeAction() {} * @return String Name to be displayed */ public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { + global $DB; + switch ($item->getType()) { case PluginFormcreatorForm::class: $number = 0; - $section = new PluginFormcreatorSection(); - $found = $section->find('plugin_formcreator_forms_id = ' . $item->getID()); + $found = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => PluginFormcreatorSection::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $item->getID() + ] + ]); $tab_section = []; foreach ($found as $section_item) { $tab_section[] = $section_item['id']; } if (!empty($tab_section)) { - $object = new self; - $found = $object->find('plugin_formcreator_sections_id IN (' . implode(', ', $tab_section) . ')'); - $number = count($found); + $count = $DB->request([ + 'COUNT' => 'cpt', + 'FROM' => self::getTable(), + 'WHERE' => [ + 'plugin_formcreator_sections_id' => $tab_section + ] + ])->next(); + $number = $count['cpt']; } return self::createTabEntry(self::getTypeName($number), $number); } @@ -125,13 +137,18 @@ public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $ } public static function showForForm(CommonDBTM $item, $withtemplate = '') { - global $CFG_GLPI; + global $CFG_GLPI, $DB; // TODO: move the content of this method into a new showForForm() method echo ''; // Get sections - $section = new PluginFormcreatorSection(); - $found_sections = $section->find('plugin_formcreator_forms_id = ' . (int) $item->getId(), '`order`'); + $found_sections = $DB->request([ + 'FROM' => PluginFormcreatorSection::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => (int) $item->getId() + ], + 'ORDER' => 'order' + ]); $section_number = count($found_sections); $token = Session::getNewCSRFToken(); foreach ($found_sections as $section) { @@ -176,8 +193,13 @@ public static function showForForm(CommonDBTM $item, $withtemplate = '') { echo ''; // Get questions - $question = new PluginFormcreatorQuestion(); - $found_questions = $question->find('plugin_formcreator_sections_id = ' . (int) $section['id'], '`order`'); + $found_questions = $DB->request([ + 'FROM' => PluginFormcreatorQuestion::getTable(), + 'WHERE' => [ + 'plugin_formcreator_sections_id' => (int) $section['id'] + ], + 'ORDER' => 'order' + ]); $question_number = count($found_questions); $i = 0; foreach ($found_questions as $question) { @@ -365,8 +387,6 @@ private function checkBeforeSave($input) { * @return array the modified $input array */ public function prepareInputForAdd($input) { - global $DB; - if (!isset($input['_skip_checks']) || !$input['_skip_checks']) { $input = $this->checkBeforeSave($input); @@ -382,8 +402,9 @@ public function prepareInputForAdd($input) { } // Get next order - $sectionId = $input['plugin_formcreator_sections_id']; - $maxOrder = PluginFormcreatorCommon::getMax($this, "`plugin_formcreator_sections_id` = '$sectionId'", 'order'); + $maxOrder = PluginFormcreatorCommon::getMax($this, [ + "plugin_formcreator_sections_id" => $input['plugin_formcreator_sections_id'] + ], 'order'); if ($maxOrder === null) { $input['order'] = 1; } else { @@ -434,7 +455,9 @@ public function prepareInputForUpdate($input) { $DB->query($query); // Get the order for the new section - $maxOrder = PluginFormcreatorCommon::getMax($this, "`plugin_formcreator_sections_id` = '$newId'", 'order'); + $maxOrder = PluginFormcreatorCommon::getMax($this, [ + "plugin_formcreator_sections_id" => $newId + ], 'order'); if ($maxOrder === null) { $input['order'] = 1; } else { @@ -735,8 +758,6 @@ public function showForm($ID, $options = []) { echo ''; echo '
'; - $dbUtil = new DbUtils(); - $table = $dbUtil->getTableForItemtype('PluginFormcreatorSection'); $sections = []; foreach ((new PluginFormcreatorSection())->getSectionsFromForm($form_id) as $section) { $sections[$section->getID()] = $section->getField('name'); @@ -1287,6 +1308,8 @@ function change_LDAP(ldap) { * @return integer|boolean ID of the new question, false otherwise */ public function duplicate() { + global $DB; + $oldQuestionId = $this->getID(); $newQuestion = new static(); $question_condition = new PluginFormcreatorQuestion_Condition(); @@ -1307,7 +1330,7 @@ public function duplicate() { $this ); $parameters = $this->field->getParameters(); - foreach ($parameters as $fieldName => $parameter) { + foreach ($parameters as $parameter) { $row = $parameter->fields; $row[PluginFormcreatorQuestion::getForeignKeyField()] = $newQuestion->getID(); unset($row['id']); @@ -1315,7 +1338,12 @@ public function duplicate() { } // Form questions conditions - $rows = $question_condition->find("`plugin_formcreator_questions_id` IN ('$oldQuestionId')"); + $rows = $DB->request([ + 'FROM' => $question_condition::getTable(), + 'WHERE' => [ + 'plugin_formcreator_questions_id' => $oldQuestionId + ] + ]); foreach ($rows as $row) { unset($row['id'], $row['uuid']); @@ -1416,6 +1444,8 @@ public static function import(PluginFormcreatorImportLinker $importLinker, $sect * @return array the array with all data (with sub tables) */ public function export($remove_uuid = false) { + global $DB; + if (!$this->getID()) { return false; } @@ -1429,7 +1459,13 @@ public function export($remove_uuid = false) { // get question conditions $question['_conditions'] = []; - $all_conditions = $form_question_condition->find("plugin_formcreator_questions_id = ".$this->getID()); + $all_conditions = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => $form_question_condition::getTable(), + 'WHERE' => [ + 'plugin_formcreator_questions_id' => $this->getID() + ] + ]); foreach ($all_conditions as $condition) { if ($form_question_condition->getFromDB($condition['id'])) { $question['_conditions'][] = $form_question_condition->export($remove_uuid); @@ -1495,7 +1531,6 @@ public function getForm() { public function getQuestionsFromForm($formId, $crit = []) { global $DB; - $dbUtil = new DbUtils(); $table_question = PluginFormcreatorQuestion::getTable(); $table_section = PluginFormcreatorSection::getTable(); $sectionFk = PluginFormcreatorSection::getForeignKeyField(); @@ -1542,8 +1577,17 @@ public function getQuestionsFromForm($formId, $crit = []) { * @return PluginFormcreatorQuestion[] */ public function getQuestionsFromSection($sectionId) { + global $DB; + $questions = []; - $rows = $this->find("`plugin_formcreator_sections_id` = '$sectionId'", "`order` ASC"); + $rows = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => self::getTable(), + 'WHERE' => [ + 'plugin_formcreator_sections_id' => $sectionId + ], + 'ORDER' => 'order ASC' + ]); foreach ($rows as $row) { $question = new self(); $question->getFromDB($row['id']); diff --git a/inc/question_condition.class.php b/inc/question_condition.class.php index c4a583776..d712d6ac1 100644 --- a/inc/question_condition.class.php +++ b/inc/question_condition.class.php @@ -158,8 +158,17 @@ public function export($remove_uuid = false) { } public function getConditionsFromQuestion($questionId) { + global $DB; + $questionConditions = []; - $rows = $this->find("`plugin_formcreator_questions_id` = '$questionId'", "`order` ASC"); + $rows = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => self::getTable(), + 'WHERE' => [ + 'plugin_formcreator_questions_id' => $questionId + ], + 'ORDER' => 'order ASC' + ]); foreach ($rows as $row) { $questionCondition = new static(); $questionCondition->getFromDB($row['id']); diff --git a/inc/section.class.php b/inc/section.class.php index e4eddf19b..d81c1f87d 100644 --- a/inc/section.class.php +++ b/inc/section.class.php @@ -77,8 +77,6 @@ public static function getTypeName($nb = 0) { * @return array the modified $input array **/ public function prepareInputForAdd($input) { - global $DB; - // Control fields values : // - name is required if (!isset($input['name']) || @@ -95,7 +93,9 @@ public function prepareInputForAdd($input) { // Get next order $formId = $input['plugin_formcreator_forms_id']; - $maxOrder = PluginFormcreatorCommon::getMax($this, "`plugin_formcreator_forms_id` = '$formId'", 'order'); + $maxOrder = PluginFormcreatorCommon::getMax($this, [ + "plugin_formcreator_forms_id" => $formId + ], 'order'); if ($maxOrder === null) { $input['order'] = 1; } else { @@ -157,6 +157,8 @@ public function post_purgeItem() { * @return integer|boolean ID of the new section, false otherwise */ public function duplicate() { + global $DB; + $oldSectionId = $this->getID(); $newSection = new static(); $section_question = new PluginFormcreatorQuestion(); @@ -173,7 +175,13 @@ public function duplicate() { } // Form questions - $rows = $section_question->find("`plugin_formcreator_sections_id` = '$oldSectionId'", "`order` ASC"); + $rows = $DB->request([ + 'FROM' => $section_question::getTable(), + 'WHERE' => [ + 'plugin_formcreator_sections_id' => $oldSectionId + ], + 'ORDER' => 'order ASC' + ]); foreach ($rows as $questions_id => $row) { unset($row['id'], $row['uuid']); @@ -195,7 +203,7 @@ public function duplicate() { $oldQuestion ); $parameters = $this->field->getParameters(); - foreach ($parameters as $fieldName => $parameter) { + foreach ($parameters as $parameter) { if (!$parameter->isNewItem()) { // Should always happen $newQuestion = new PluginFormcreatorQuestion(); @@ -208,8 +216,12 @@ public function duplicate() { // Form questions conditions if (count($tab_questions) > 0) { - $questionIds = implode("', '", array_keys($tab_questions)); - $rows = $question_condition->find("`plugin_formcreator_questions_id` IN ('$questionIds')"); + $rows = $DB->request([ + 'FROM' => $question_condition::getTable(), + 'WHERE' => [ + 'plugin_formcreator_questions_id' => $tab_questions + ] + ]); foreach ($rows as $row) { unset($row['id'], $row['uuid']); @@ -232,22 +244,16 @@ public function moveUp() { $order = $this->fields['order']; $formId = $this->fields['plugin_formcreator_forms_id']; $otherItem = new static(); - if (!method_exists($otherItem, 'getFromDBByRequest')) { - $otherItem->getFromDBByQuery("WHERE `plugin_formcreator_forms_id` = '$formId' - AND `order` < '$order' - ORDER BY `order` DESC LIMIT 1"); - } else { - $otherItem->getFromDBByRequest([ - 'WHERE' => [ - 'AND' => [ - 'plugin_formcreator_forms_id' => $formId, - 'order' => ['<', $order] - ] - ], - 'ORDER' => ['order DESC'], - 'LIMIT' => 1 - ]); - } + $otherItem->getFromDBByRequest([ + 'WHERE' => [ + 'AND' => [ + 'plugin_formcreator_forms_id' => $formId, + 'order' => ['<', $order] + ] + ], + 'ORDER' => ['order DESC'], + 'LIMIT' => 1 + ]); if (!$otherItem->isNewItem()) { $this->update([ 'id' => $this->getID(), @@ -264,22 +270,16 @@ public function moveDown() { $order = $this->fields['order']; $formId = $this->fields['plugin_formcreator_forms_id']; $otherItem = new static(); - if (!method_exists($otherItem, 'getFromDBByRequest')) { - $otherItem->getFromDBByQuery("WHERE `plugin_formcreator_forms_id` = '$formId' - AND `order` > '$order' - ORDER BY `order` ASC LIMIT 1"); - } else { - $otherItem->getFromDBByRequest([ - 'WHERE' => [ - 'AND' => [ - 'plugin_formcreator_forms_id' => $formId, - 'order' => ['>', $order] - ] - ], - 'ORDER' => ['order ASC'], - 'LIMIT' => 1 - ]); - } + $otherItem->getFromDBByRequest([ + 'WHERE' => [ + 'AND' => [ + 'plugin_formcreator_forms_id' => $formId, + 'order' => ['>', $order] + ] + ], + 'ORDER' => ['order ASC'], + 'LIMIT' => 1 + ]); if (!$otherItem->isNewItem()) { $this->update([ 'id' => $this->getID(), @@ -382,6 +382,8 @@ public static function import(PluginFormcreatorImportLinker $importLinker, $form * @return array the array with all data (with sub tables) */ public function export($remove_uuid = false) { + global $DB; + if (!$this->getID()) { return false; } @@ -395,7 +397,13 @@ public function export($remove_uuid = false) { // get questions $section['_questions'] = []; - $all_questions = $form_question->find("plugin_formcreator_sections_id = ".$this->getID()); + $all_questions = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => $form_question::getTable(), + 'WHERE' => [ + 'plugin_formcreator_sections_id' => $this->getID() + ] + ]); foreach ($all_questions as $question) { if ($form_question->getFromDB($question['id'])) { $section['_questions'][] = $form_question->export($remove_uuid); @@ -415,8 +423,17 @@ public function export($remove_uuid = false) { * @return array sections in a form */ public function getSectionsFromForm($formId) { + global $DB; + $sections = []; - $rows = $this->find("`plugin_formcreator_forms_id` = '$formId'", "`order` ASC"); + $rows = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => self::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $formId + ], + 'ORDER' => 'order ASC' + ]); foreach ($rows as $row) { $section = new self(); $section->getFromDB($row['id']); diff --git a/inc/target.class.php b/inc/target.class.php index 9113b1e43..b19b29451 100644 --- a/inc/target.class.php +++ b/inc/target.class.php @@ -60,18 +60,25 @@ public static function getTypeName($nb = 1) { } public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { + global $DB; + switch ($item->getType()) { case "PluginFormcreatorForm": - $env = new self; - $found_env = $env->find('plugin_formcreator_forms_id = '.$item->getID()); - $nb = count($found_env); + $found_env = $DB->request([ + 'COUNT' => 'cpt', + 'FROM' => self::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $item->getID(), + ] + ])->next(); + $nb = $found_env['cpt']; return self::createTabEntry(self::getTypeName($nb), $nb); } return ''; } public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) { - global $CFG_GLPI; + global $CFG_GLPI, $DB; echo ''; @@ -79,9 +86,13 @@ public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $ echo ''; echo ''; - $target_class = new PluginFormcreatorTarget(); - $found_targets = $target_class->find('plugin_formcreator_forms_id = '.$item->getID()); - $token = Session::getNewCSRFToken(); + $found_targets = $DB->request([ + 'FROM' => PluginFormcreatorTarget::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $item->getID() + ], + ]); + $token = Session::getNewCSRFToken(); $i = 0; foreach ($found_targets as $target) { $i++; @@ -288,6 +299,8 @@ public static function import($forms_id = 0, $target = []) { * @return array the array with all data (with sub tables) */ public function export($remove_uuid = false) { + global $DB; + if (!$this->getID()) { return false; } @@ -311,7 +324,13 @@ public function export($remove_uuid = false) { // get target actors $target['_data']['_actors'] = []; $foreignKey = $target_item->getForeignKeyField(); - $all_target_actors = $form_target_actor->find("`$foreignKey` = '$targetId'"); + $all_target_actors = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => $form_target_actor::getTable(), + 'WHERE' => [ + $foreignKey => $targetId + ] + ]); foreach ($all_target_actors as $target_actor) { if ($form_target_actor->getFromDB($target_actor['id'])) { $target['_data']['_actors'][] = $form_target_actor->export($remove_uuid); @@ -360,9 +379,16 @@ public function showSubForm($ID) { * @param PluginFormcreatorForm $form */ public function getTargetsForForm(PluginFormcreatorForm $form) { + global $DB; + $targets = []; - $formId = $form->getID(); - $foundTargets = $this->find("plugin_formcreator_forms_id = '$formId'"); + $foundTargets = $DB->request([ + 'SELECT' => ['itemtype', 'items_id'], + 'FROM' => self::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $form->getID() + ] + ]); foreach ($foundTargets as $row) { $target = getItemForItemtype($row['itemtype']); $target->getFromDB($row['items_id']); diff --git a/inc/targetbase.class.php b/inc/targetbase.class.php index 7cb62ff0b..320a2912a 100644 --- a/inc/targetbase.class.php +++ b/inc/targetbase.class.php @@ -266,10 +266,14 @@ protected function getTargetEntity(PluginFormcreatorFormAnswer $formanswer, $req // Default entity of a user from the answer of a user's type question case 'user' : - $answer = new PluginFormcreatorAnswer(); - $found = $answer->find('plugin_formcreator_formanswers_id = '.$formanswer->fields['id']. - ' AND plugin_formcreator_questions_id = '.$this->fields['destination_entity_value']); - $user = array_shift($found); + $user = $DB->request([ + 'SELECT' => ['answer'], + 'FROM' => PluginFormcreatorAnswer::getTable(), + 'WHERE' => [ + 'plugin_formcreator_formanswers_id' => $formanswer->fields['id'], + 'plugin_formcreator_questions_id' => $this->fields['destination_entity_value'], + ] + ])->next(); $user_id = $user['answer']; if ($user_id > 0) { @@ -281,11 +285,14 @@ protected function getTargetEntity(PluginFormcreatorFormAnswer $formanswer, $req // Entity from the answer of an entity's type question case 'entity' : - $answer = new PluginFormcreatorAnswer(); - $found = $answer->find('plugin_formcreator_formanswers_id = '.$formanswer->fields['id']. - ' AND plugin_formcreator_questions_id = '.$this->fields['destination_entity_value']); - $entity = array_shift($found); - + $entity = $DB->request([ + 'SELECT' => ['answer'], + 'FROM' => PluginFormcreatorAnswer::getTable(), + 'WHERE' => [ + 'plugin_formcreator_formanswers_id' => $formanswer->fields['id'], + 'plugin_formcreator_questions_id' => $this->fields['destination_entity_value'], + ] + ])->next(); $entityId = $entity['answer']; break; } @@ -297,11 +304,17 @@ protected function getTargetEntity(PluginFormcreatorFormAnswer $formanswer, $req * find all actors and prepare data for the ticket being created */ protected function prepareActors(PluginFormcreatorForm $form, PluginFormcreatorFormAnswer $formanswer) { - $targetId = $this->getID(); + global $DB; + $target_actor = $this->getItem_Actor(); - $foreignKey = $this->getForeignKeyField(); - $rows = $target_actor->find("`$foreignKey` = '$targetId'"); + $foreignKey = $this->getForeignKeyField(); + $rows = $DB->request([ + 'FROM' => $target_actor::getTable(), + 'WHERE' => [ + $foreignKey => $this->getID(), + ] + ]); foreach ($rows as $actor) { // If actor type is validator and if the form doesn't have a validator, continue to other actors if ($actor['actor_type'] == 'validator' && !$form->fields['validation_required']) { @@ -910,14 +923,16 @@ function change_tag_type() { // Specific tags echo ''; echo '
'._n('Destinations', 'Destinations', 2, 'formcreator').'
'; echo __('Link to an other ticket', 'formcreator'); @@ -729,8 +744,12 @@ function updateCompositePeerType() { echo Html::scriptBlock($script); // get already linked items $targetTicketId = $this->getID(); - $item_targetTicket = new PluginFormcreatorItem_TargetTicket(); - $rows = $item_targetTicket->find("`plugin_formcreator_targettickets_id` = '$targetTicketId'"); + $rows = $DB->request([ + 'FROM' => PluginFormcreatorItem_TargetTicket::getTable(), + 'WHERE' => [ + 'plugin_formcreator_targettickets_id' => $targetTicketId + ] + ]); $excludedTargetTicketsIds = []; $excludedTicketIds = []; foreach ($rows as $row) { @@ -758,18 +777,40 @@ function updateCompositePeerType() { // dropdown of target tickets echo ''; $excludedTargetTicketsIds[] = $this->getID(); + $condition = "`id` IN ( + SELECT `items_id` FROM `glpi_plugin_formcreator_targets` AS `t1` + WHERE `plugin_formcreator_forms_id` = ( + SELECT `plugin_formcreator_forms_id` FROM `glpi_plugin_formcreator_targets` AS `t2` + WHERE `t2`.`itemtype` = 'PluginFormcreatorTargetTicket' AND `t2`.`items_id` = '$targetTicketId' + ) + AND `t1`.`itemtype` = 'PluginFormcreatorTargetTicket' + )"; + // TODO remove if and the above raw query when 9.3/bf compat will no be needed anymore + if (version_compare(GLPI_VERSION, "9.4", '>=')) { + $condition = [ + 'id' => new QuerySubQuery([ + 'SELECT' => ['items_id'], + 'FROM' => 'glpi_plugin_formcreator_targets AS t1', + 'WHERE' => [ + 't1.itemtype' => 'PluginFormcreatorTargetTicket', + 'plugin_formcreator_forms_id' => new QuerySubQuery([ + 'SELECT' => ['plugin_formcreator_forms_id'], + 'FROM' => 'glpi_plugin_formcreator_targets AS t2', + 'WHERE' => [ + 't2.itemtype' => 'PluginFormcreatorTargetTicket', + 't2.items_id' => $targetTicketId + ] + ]), + ] + ]), + ]; + } echo PluginFormcreatorTargetTicket::dropdown([ - 'name' => '_link_targettickets_id', - 'rand' => $rand, - 'display' => false, - 'used' => $excludedTargetTicketsIds, - 'condition' => "`id` IN ( - SELECT `items_id` FROM `glpi_plugin_formcreator_targets` AS `t1` - WHERE `plugin_formcreator_forms_id` = ( - SELECT `plugin_formcreator_forms_id` FROM `glpi_plugin_formcreator_targets` AS `t2` - WHERE `t2`.`itemtype` = 'PluginFormcreatorTargetTicket' AND `t2`.`items_id` = '$targetTicketId' - ) - AND `t1`.`itemtype` = 'PluginFormcreatorTargetTicket')", + 'name' => '_link_targettickets_id', + 'rand' => $rand, + 'display' => false, + 'used' => $excludedTargetTicketsIds, + 'condition' => $condition, ]); echo ''; echo ''; @@ -1185,9 +1226,14 @@ public function save(PluginFormcreatorFormAnswer $formanswer) { // Default entity of a user from the answer of a user's type question case 'user' : - $found = $answer->find('plugin_formcreator_formanswers_id = '.$formanswer->fields['id']. - ' AND plugin_formcreator_questions_id = '.$this->fields['destination_entity_value']); - $user = array_shift($found); + $user = $DB->request([ + 'SELECT' => ['answer'], + 'FROM' => $answer::getTable(), + 'WHERE' => [ + 'plugin_formcreator_formanswers_id' => $formanswer->fields['id'], + 'plugin_formcreator_questions_id' => $this->fields['destination_entity_value'] + ] + ])->next(); $user_id = $user['answer']; if ($user_id > 0) { @@ -1201,9 +1247,14 @@ public function save(PluginFormcreatorFormAnswer $formanswer) { // Entity from the answer of an entity's type question case 'entity' : - $found = $answer->find('plugin_formcreator_formanswers_id = '.$formanswer->fields['id']. - ' AND plugin_formcreator_questions_id = '.$this->fields['destination_entity_value']); - $entity = array_shift($found); + $entity = $DB->request([ + 'SELECT' => ['answer'], + 'FROM' => $answer::getTable(), + 'WHERE' => [ + 'plugin_formcreator_formanswers_id' => $formanswer->fields['id'], + 'plugin_formcreator_questions_id' => $this->fields['destination_entity_value'] + ] + ])->next(); $data['entities_id'] = $entity['answer']; break; @@ -1332,14 +1383,18 @@ public function save(PluginFormcreatorFormAnswer $formanswer) { } protected function setTargetCategory($data, $formanswer) { + global $DB; + switch ($this->fields['category_rule']) { case 'answer': - $answer = new PluginFormcreatorAnswer(); - $formAnswerId = $formanswer->fields['id']; - $categoryQuestion = $this->fields['category_question']; - $found = $answer->find("`plugin_formcreator_formanswers_id` = '$formAnswerId' - AND `plugin_formcreator_questions_id` = '$categoryQuestion'"); - $category = array_shift($found); + $category = $DB->request([ + 'SELECT' => ['answer'], + 'FROM' => PluginFormcreatorAnswer::getTable(), + 'WHERE' => [ + 'plugin_formcreator_formanswers_id' => $formanswer->fields['id'], + 'plugin_formcreator_questions_id' => $this->fields['category_question'] + ] + ])->next(); $category = $category['answer']; break; case 'specific': @@ -1356,14 +1411,18 @@ protected function setTargetCategory($data, $formanswer) { } protected function setTargetUrgency($data, $formanswer) { + global $DB; + switch ($this->fields['urgency_rule']) { case 'answer': - $answer = new PluginFormcreatorAnswer(); - $formAnswerId = $formanswer->fields['id']; - $urgencyQuestion = $this->fields['urgency_question']; - $found = $answer->find("`plugin_formcreator_formanswers_id` = '$formAnswerId' - AND `plugin_formcreator_questions_id` = '$urgencyQuestion'"); - $urgency = array_shift($found); + $urgency = $DB->request([ + 'SELECT' => ['answer'], + 'FROM' => PluginFormcreatorAnswer::getTable(), + 'WHERE' => [ + 'plugin_formcreator_formanswers_id' => $formanswer->fields['id'], + 'plugin_formcreator_questions_id' => $this->fields['urgency_question'] + ] + ])->next(); $urgency = $urgency['answer']; break; case 'specific': @@ -1380,14 +1439,18 @@ protected function setTargetUrgency($data, $formanswer) { } protected function setTargetLocation($data, $formanswer) { + global $DB; + switch ($this->fields['location_rule']) { case 'answer': - $answer = new PluginFormcreatorAnswer(); - $formAnswerId = $formanswer->fields['id']; - $locationQuestion = $this->fields['location_question']; - $found = $answer->find("`plugin_formcreator_formanswers_id` = '$formAnswerId' - AND `plugin_formcreator_questions_id` = '$locationQuestion'"); - $location = array_shift($found); + $location = $DB->request([ + 'SELECT' => ['answer'], + 'FROM' => PluginFormcreatorAnswer::getTable(), + 'WHERE' => [ + 'plugin_formcreator_formanswers_id' => $formanswer->fields['id'], + 'plugin_formcreator_questions_id' => $this->fields['location_question'] + ] + ])->next(); $location = $location['answer']; break; case 'specific': @@ -1421,6 +1484,8 @@ private static function getDeleteImage($id) { * @return integer the targetticket's id */ public static function import($targetitems_id = 0, $target_data = []) { + global $DB; + $item = new self; $target_data['_skip_checks'] = true; @@ -1429,20 +1494,30 @@ public static function import($targetitems_id = 0, $target_data = []) { // convert question uuid into id $targetTicket = new PluginFormcreatorTargetTicket(); $targetTicket->getFromDB($targetitems_id); - $formId = $targetTicket->getForm()->getID(); - $section = new PluginFormcreatorSection(); - $found_section = $section->find("plugin_formcreator_forms_id = '$formId'", - "`order` ASC"); + $found_section = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => PluginFormcreatorSection::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $targetTicket->getForm()->getID() + ], + 'ORDER' => 'order ASC' + ]); $tab_section = []; foreach ($found_section as $section_item) { $tab_section[] = $section_item['id']; } if (!empty($tab_section)) { - $sectionList = "'" . implode(', ', $tab_section) . "'"; - $question = new PluginFormcreatorQuestion(); - $rows = $question->find("`plugin_formcreator_sections_id` IN ($sectionList)", "`order` ASC"); - foreach ($rows as $id => $question_line) { + $rows = $DB->request([ + 'SELECT' => ['id', 'uuid'], + 'FROM' => PluginFormcreatorQuestion::getTable(), + 'WHERE' => [ + 'plugin_formcreator_sections_id' => $tab_section + ], + 'ORDER' => 'order ASC' + ]); + foreach ($rows as $question_line) { + $id = $question_line['id']; $uuid = $question_line['uuid']; $content = $target_data['title']; @@ -1481,6 +1556,8 @@ public static function import($targetitems_id = 0, $target_data = []) { * @return array the array with all data (with sub tables) */ public function export($remove_uuid = false) { + global $DB; + if (!$this->getID()) { return false; } @@ -1495,20 +1572,30 @@ public function export($remove_uuid = false) { } // convert questions ID into uuid for ticket description - $formId = $this->getForm()->getID(); - $section = new PluginFormcreatorSection(); - $found_section = $section->find("plugin_formcreator_forms_id = '$formId'", - "`order` ASC"); + $found_section = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => PluginFormcreatorSection::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $this->getForm()->getID() + ], + 'ORDER' => 'order ASC' + ]); $tab_section = []; foreach ($found_section as $section_item) { $tab_section[] = $section_item['id']; } if (!empty($tab_section)) { - $sectionList = "'" . implode(', ', $tab_section) . "'"; - $question = new PluginFormcreatorQuestion(); - $rows = $question->find("`plugin_formcreator_sections_id` IN ($sectionList)", "`order` ASC"); - foreach ($rows as $id => $question_line) { + $rows = $DB->request([ + 'SELECT' => ['id', 'uuid'], + 'FROM' => PluginFormcreatorQuestion::getTable(), + 'WHERE' => [ + 'plugin_formcreator_sections_id' => $tab_section + ], + 'ORDER' => 'order ASC' + ]); + foreach ($rows as $question_line) { + $id = $question_line['id']; $uuid = $question_line['uuid']; $content = $target_data['name']; @@ -1526,8 +1613,13 @@ public function export($remove_uuid = false) { // get data from ticket relations $target_data['_ticket_relations'] = []; $target_ticketLink = new PluginFormcreatorItem_TargetTicket(); - $targetTicketId = $target_data['id']; - $all_ticketLinks = $target_ticketLink->find("`plugin_formcreator_targettickets_id` = '$targetTicketId'"); + $all_ticketLinks = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => $target_ticketLink::getTable(), + 'WHERE' => [ + 'plugin_formcreator_targettickets_id' => $target_data['id'] + ], + ]); foreach ($all_ticketLinks as $ticketLink) { $target_ticketLink->getFromDB($ticketLink['id']); $target_data['_ticket_relations'][] = $target_ticketLink->export(); diff --git a/inc/wizard.class.php b/inc/wizard.class.php index ab8a93fb3..6268d736d 100644 --- a/inc/wizard.class.php +++ b/inc/wizard.class.php @@ -107,11 +107,12 @@ public static function header($title) { echo ''; if (Session::haveRight("reservation", ReservationItem::RESERVEANITEM)) { - $reservation_item = new reservationitem; - $entity_filter = getEntitiesRestrictRequest("", 'glpi_reservationitems', 'entities_id', - $_SESSION['glpiactiveentities']); - $found_available_res = $reservation_item->find($entity_filter); - if (count($found_available_res)) { + $found_available_res = $DB->request([ + 'COUNT' => 'cpt', + 'FROM' => ReservationItem::getTable(), + 'WHERE' => getEntitiesRestrictCriteria(ReservationItem::getTable(), 'entities_id'), + ])->next(); + if ($found_available_res['cpt'] > 0) { echo '
  • '; echo ''; echo ''; diff --git a/install/install.php b/install/install.php index 30dba88de..b3ea1147e 100644 --- a/install/install.php +++ b/install/install.php @@ -242,57 +242,20 @@ protected function createRequestType() { } protected function createDefaultDisplayPreferences() { - global $DB; $this->migration->displayMessage("create default display preferences"); - - // Create standard display preferences - $displayprefs = new DisplayPreference(); - $found_dprefs = $displayprefs->find("`itemtype` = 'PluginFormcreatorFormAnswer'"); - if (count($found_dprefs) == 0) { - $query = "INSERT IGNORE INTO `glpi_displaypreferences` - (`id`, `itemtype`, `num`, `rank`, `users_id`) VALUES - (NULL, 'PluginFormcreatorFormAnswer', 2, 2, 0), - (NULL, 'PluginFormcreatorFormAnswer', 3, 3, 0), - (NULL, 'PluginFormcreatorFormAnswer', 4, 4, 0), - (NULL, 'PluginFormcreatorFormAnswer', 5, 5, 0), - (NULL, 'PluginFormcreatorFormAnswer', 6, 6, 0)"; - $DB->query($query) or die ($DB->error()); - } - - $displayprefs = new DisplayPreference; - $found_dprefs = $displayprefs->find("`itemtype` = 'PluginFormcreatorForm'"); - if (count($found_dprefs) == 0) { - $query = "INSERT IGNORE INTO `glpi_displaypreferences` - (`id`, `itemtype`, `num`, `rank`, `users_id`) VALUES - (NULL, 'PluginFormcreatorForm', 30, 1, 0), - (NULL, 'PluginFormcreatorForm', 3, 2, 0), - (NULL, 'PluginFormcreatorForm', 10, 3, 0), - (NULL, 'PluginFormcreatorForm', 7, 4, 0), - (NULL, 'PluginFormcreatorForm', 8, 5, 0), - (NULL, 'PluginFormcreatorForm', 9, 6, 0);"; - $DB->query($query) or die ($DB->error()); - } - - $displayprefs = new DisplayPreference; - $found_dprefs = $displayprefs->find("`itemtype` = 'PluginFormcreatorIssue'"); - if (count($found_dprefs) == 0) { - $query = "INSERT IGNORE INTO `glpi_displaypreferences` - (`id`, `itemtype`, `num`, `rank`, `users_id`) VALUES - (NULL, 'PluginFormcreatorIssue', 1, 1, 0), - (NULL, 'PluginFormcreatorIssue', 2, 2, 0), - (NULL, 'PluginFormcreatorIssue', 4, 3, 0), - (NULL, 'PluginFormcreatorIssue', 5, 4, 0), - (NULL, 'PluginFormcreatorIssue', 6, 5, 0), - (NULL, 'PluginFormcreatorIssue', 7, 6, 0), - (NULL, 'PluginFormcreatorIssue', 8, 7, 0)"; - $DB->query($query) or die ($DB->error()); - } + $this->migration->updateDisplayPrefs([ + 'PluginFormcreatorFormAnswer' => [2, 3, 4, 5, 6], + 'PluginFormcreatorForm' => [30, 3, 10, 7, 8, 9], + 'PluginFormcreatorIssue' => [1, 2, 4, 5, 6, 7, 8], + ]); } /** * Declares the notifications that the plugin handles */ protected function createNotifications() { + global $DB; + $this->migration->displayMessage("create notifications"); $notifications = [ @@ -337,10 +300,17 @@ protected function createNotifications() { foreach ($notifications as $event => $data) { // Check if notification already exists - $exists = $notification->find("itemtype = 'PluginFormcreatorFormAnswer' AND event = '$event'"); + $exists = $DB->request([ + 'COUNT' => 'cpt', + 'FROM' => $notification::getTable(), + 'WHERE' => [ + 'itemtype' => 'PluginFormcreatorFormAnswer', + 'event' => $event, + ] + ])->next(); // If it doesn't exists, create it - if (count($exists) == 0) { + if ($exists['cpt'] == 0) { $template_id = $template->add([ 'name' => Toolbox::addslashes_deep($data['name']), 'comment' => '', @@ -386,6 +356,8 @@ protected function createNotifications() { } protected function deleteNotifications() { + global $DB; + // Delete translations $translation = new NotificationTemplateTranslation(); $translation->deleteByCriteria([ @@ -425,13 +397,18 @@ protected function deleteNotifications() { // Delete notifications and their templates $notification = new Notification(); $notification_notificationTemplate = new Notification_NotificationTemplate(); - $rows = $notification->find("`itemtype` = 'PluginFormcreatorFormAnswer'"); + $rows = $DB->request([ + 'SELECT' => ['id'], + 'FROM' => $notification::getTable(), + 'WHERE' => [ + 'itemtype' => 'PluginFormcreatorFormAnswer' + ] + ]); foreach ($rows as $row) { $notification_notificationTemplate->deleteByCriteria(['notifications_id' => $row['id']]); $notification->delete($row); } - $notification = new Notification(); $notification->deleteByCriteria(['itemtype' => PluginFormcreatorFormAnswer::class]); } diff --git a/install/upgrade_to_2.5.php b/install/upgrade_to_2.5.php index 375a4adb6..646053264 100644 --- a/install/upgrade_to_2.5.php +++ b/install/upgrade_to_2.5.php @@ -240,14 +240,11 @@ function updateForm_Profile_2_5(Migration $migration) { $migration->migrationOneTable('glpi_plugin_formcreator_forms_profiles'); // fill missing uuid - $obj = new PluginFormcreatorForm_Profile(); - $all_form_profiles = $obj->find("uuid IS NULL"); - foreach ($all_form_profiles as $form_profiles_id => $form_profile) { - $obj->update([ - 'id' => $form_profiles_id, - 'uuid' => plugin_formcreator_getUuid() - ]); - } + $DB->update(PluginFormcreatorForm_Profile::getTable(), [ + 'uuid' => plugin_formcreator_getUuid() + ], [ + 'uuid' => null + ]); } function updateFormValidator_2_5(Migration $migration) { @@ -280,12 +277,11 @@ function updateFormValidator_2_5(Migration $migration) { } // fill missing uuid - $obj = new PluginFormcreatorForm_Validator(); - $all_validators = $obj->find("uuid IS NULL"); - foreach ($all_validators as $validators_id => $validator) { - $obj->update(['id' => $validators_id, - 'uuid' => plugin_formcreator_getUuid()]); - } + $DB->update(PluginFormcreatorForm_Validator::getTable(), [ + 'uuid' => plugin_formcreator_getUuid() + ], [ + 'uuid' => null + ]); } function updateForm_2_5(Migration $migration) { @@ -368,12 +364,11 @@ function updateForm_2_5(Migration $migration) { $migration->migrationOneTable('glpi_plugin_formcreator_forms'); // fill missing uuid (force update of forms, see PluginFormcreatorForm::prepareInputForUpdate) - $obj = new PluginFormcreatorForm(); - $all_forms = $obj->find("uuid IS NULL"); - foreach ($all_forms as $forms_id => $form) { - $obj->update(['id' => $forms_id]); - } - unset($obj); + $DB->update(PluginFormcreatorForm::getTable(), [ + 'uuid' => plugin_formcreator_getUuid() + ], [ + 'uuid' => null + ]); } function updateHeader_2_5(Migration $migration) { @@ -572,12 +567,11 @@ function updateQuestionCondition_2_5(Migration $migration) { $migration->addKey('glpi_plugin_formcreator_questions_conditions', 'plugin_formcreator_questions_id'); // fill missing uuid (force update of questions, see PluginFormcreatorQuestoin_Condition::prepareInputForUpdate) - $condition_obj = new PluginFormcreatorQuestion_Condition(); - $all_conditions = $condition_obj->find("uuid IS NULL"); - foreach ($all_conditions as $conditions_id => $condition) { - $condition_obj->update(['id' => $conditions_id, - 'uuid' => plugin_formcreator_getUuid()]); - } + $DB->update(PluginFormcreatorQuestion_Condition::getTable(), [ + 'uuid' => plugin_formcreator_getUuid() + ], [ + 'uuid' => null + ]); } function updateQuestion_2_5(Migration $migration) { @@ -780,12 +774,12 @@ function updateQuestion_2_5(Migration $migration) { $migration->addKey('glpi_plugin_formcreator_questions', 'plugin_formcreator_sections_id'); - // fill missing uuid (force update of questions, see PlugiinFormcreatorQuestion::prepareInputForUpdate) - $obj = new PluginFormcreatorQuestion(); - $all_questions = $obj->find("uuid IS NULL"); - foreach ($all_questions as $questions_id => $question) { - $obj->update(['id' => $questions_id]); - } + // fill missing uuid (force update of questions, see PluginFormcreatorQuestion::prepareInputForUpdate) + $DB->update(PluginFormcreatorQuestion::getTable(), [ + 'uuid' => plugin_formcreator_getUuid() + ], [ + 'uuid' => null + ]); } function updateSection_2_5(Migration $migration) { @@ -863,11 +857,11 @@ function updateSection_2_5(Migration $migration) { $migration->addKey('glpi_plugin_formcreator_sections', 'plugin_formcreator_forms_id'); // fill missing uuid (force update of sections, see PluginFormcreatorSection::prepareInputForUpdate) - $obj = new PluginFormcreatorSection(); - $all_sections = $obj->find("uuid IS NULL"); - foreach ($all_sections as $sections_id => $section) { - $obj->update(['id' => $sections_id]); - } + $DB->update(PluginFormcreatorSection::getTable(), [ + 'uuid' => plugin_formcreator_getUuid() + ], [ + 'uuid' => null + ]); } function updateTarget_2_5(Migration $migration) { @@ -1023,11 +1017,11 @@ function updateTarget_2_5(Migration $migration) { } // fill missing uuid (force update of targets, see PluginFormcreatorTarget::prepareInputForUpdate) - $obj = new PluginFormcreatorTarget(); - $all_targets = $obj->find("uuid IS NULL"); - foreach ($all_targets as $targets_id => $target) { - $obj->update(['id' => $targets_id]); - } + $DB->update(PluginFormcreatorTarget::getTable(), [ + 'uuid' => plugin_formcreator_getUuid() + ], [ + 'uuid' => null + ]); } function updateTargetChange_Actor_2_5(Migration $migration) { @@ -1073,13 +1067,11 @@ function updateTargetChange_Actor_2_5(Migration $migration) { } // fill missing uuid - $obj = new PluginFormcreatorTargetChange_Actor(); - $all_actor = $obj->find("uuid IS NULL"); - foreach ($all_actor as $actors_id => $actor) { - $obj->update(['id' => $actors_id, - 'uuid' => plugin_formcreator_getUuid()]); - } - + $DB->update(PluginFormcreatorTargetChange_Actor::getTable(), [ + 'uuid' => plugin_formcreator_getUuid() + ], [ + 'uuid' => null + ]); } function updateTargetTicket_Actor_2_5(Migration $migration) { @@ -1116,12 +1108,11 @@ function updateTargetTicket_Actor_2_5(Migration $migration) { } // fill missing uuid - $obj = new PluginFormcreatorTargetTicket_Actor(); - $all_actor = $obj->find("uuid IS NULL"); - foreach ($all_actor as $actors_id => $actor) { - $obj->update(['id' => $actors_id, - 'uuid' => plugin_formcreator_getUuid()]); - } + $DB->update(PluginFormcreatorTargetTicket_Actor::getTable(), [ + 'uuid' => plugin_formcreator_getUuid() + ], [ + 'uuid' => null + ]); } function updateTargetTicket_2_5(Migration $migration) { diff --git a/install/upgrade_to_2.6.php b/install/upgrade_to_2.6.php index c1876d083..c6c6a812e 100644 --- a/install/upgrade_to_2.6.php +++ b/install/upgrade_to_2.6.php @@ -50,17 +50,26 @@ public function upgrade(Migration $migration) { $table = 'glpi_plugin_formcreator_questions'; $migration->displayMessage("Upgrade $table"); - $question = new PluginFormcreatorQuestion(); - $rows = $question->find("`fieldtype` = 'dropdown' AND `values` = 'ITILCategory'"); - foreach ($rows as $id => $row) { + $rows = $DB->request([ + 'SELECT' => ['id', 'values'], + 'FROM' => PluginFormcreatorQuestion::getTable(), + 'WHERE' => [ + 'fieldtype' => 'dropdown', + 'values' => 'ITILCategory' + ] + ]); + foreach ($rows as $row) { $updatedValue = json_encode([ 'itemtype' => $row['values'], 'show_ticket_categories' => 'both', 'show_ticket_categories_depth' => 0 ]); // Don't use update() method because the json will be HTML-entities-ified (see prepareInputForUpdate() ) - $query = "UPDATE `$table` SET `values`='$updatedValue' WHERE `id`='$id'"; - $DB->query($query) or plugin_formcreator_upgrade_error($migration); + $DB->update($table, [ + 'values' => $updatedValue + ], [ + 'id' => $row['id'] + ]) or plugin_formcreator_upgrade_error($migration); } // Update Form Answers @@ -136,7 +145,12 @@ public function upgrade(Migration $migration) { $migration->addField($table, 'uuid', 'string', ['after' => 'category_question']); $migration->migrationOneTable($table); $obj = new PluginFormcreatorTargetTicket(); - $all_targetTickets = $obj->find("`uuid` IS NULL"); + $all_targetTickets = $DB->request([ + 'FROM' => $obj::getTable(), + 'WHERE' => [ + 'uuid' => null, + ] + ]); foreach ($all_targetTickets as $targetTicket) { $targetTicket['_skip_checks'] = true; $targetTicket['title'] = $targetTicket['name']; diff --git a/setup.php b/setup.php index dca61e6b9..4f3be5934 100644 --- a/setup.php +++ b/setup.php @@ -42,7 +42,7 @@ // Minimal GLPI version, inclusive define ('PLUGIN_FORMCREATOR_GLPI_MIN_VERSION', '9.3.0'); // Maximum GLPI version, exclusive -define ('PLUGIN_FORMCREATOR_GLPI_MAX_VERSION', '9.4'); +define ('PLUGIN_FORMCREATOR_GLPI_MAX_VERSION', '9.5'); define('FORMCREATOR_ROOTDOC', $CFG_GLPI['root_doc'] . '/plugins/formcreator'); @@ -330,15 +330,10 @@ function plugin_formcreator_getFromDBByField(CommonDBTM $item, $field = '', $val $field = $DB->escape($field); $value = $DB->escape($value); - if (!method_exists(PluginFormcreatorForm::class, 'getFromDBByRequest')) { - $found = $item->getFromDBByQuery("WHERE `".$item::getTable()."`.`$field` = '" - .$value."' LIMIT 1"); - } else { - $found = $item->getFromDBByRequest([ - 'WHERE' => [$item::getTable() . '.' . $field => $value], - 'LIMIT' => 1 - ]); - } + $found = $item->getFromDBByRequest([ + 'WHERE' => [$item::getTable() . '.' . $field => $value], + 'LIMIT' => 1 + ]); if ($found) { return $item->getID(); diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 3c6bf31a7..f69166a43 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -24,7 +24,7 @@ define('GLPI_LOG_DIR', __DIR__ . '/logs'); @mkdir(GLPI_LOG_DIR); if (!defined('STDERR')) { - define('STDERR', fopen(GLPI_LOG_DIR . 'stderr.log', 'w')); + define('STDERR', fopen(GLPI_LOG_DIR . '/stderr.log', 'w')); } // Giving --debug argument to atoum will be detected by GLPI too diff --git a/tests/suite-integration/PluginFormcreatorForm.php b/tests/suite-integration/PluginFormcreatorForm.php index 92fe428eb..c086599e1 100644 --- a/tests/suite-integration/PluginFormcreatorForm.php +++ b/tests/suite-integration/PluginFormcreatorForm.php @@ -83,9 +83,8 @@ public function setUp() { ]); $form_target->getFromDB($targets_id); - $targettickets_id = $form_target->fields['items_id']; - $form_profiles_id = $form_profile->add(['plugin_formcreator_forms_id' => $forms_id, + $form_profile->add(['plugin_formcreator_forms_id' => $forms_id, 'profiles_id' => 1]); $item_targetTicket->add(['plugin_formcreator_targettickets_id' => $targetTicket_id, @@ -108,6 +107,8 @@ public function beforeTestMethod($method) { * */ public function testDuplicateForm() { + global $DB; + $formData = [ 'entities_id' => $_SESSION['glpiactive_entity'], 'name' => 'a form', @@ -228,30 +229,76 @@ public function testDuplicateForm() { $this->integer((int) $newFormId)->isNotEqualTo($sourceFormId); // Check sections were copied - $section = new \PluginFormcreatorSection(); - $sourceRows = $section->find("`plugin_formcreator_forms_id` = '$sourceFormId'"); - $newRows = $section->find("`plugin_formcreator_forms_id` = '$newFormId'"); - $this->integer(count($newRows))->isEqualTo(count($sourceRows)); + $sourceRows = $DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \PluginFormcreatorSection::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $sourceFormId, + ] + ])->next(); + $newRows = $DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \PluginFormcreatorSection::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $newFormId, + ] + ])->next(); + $this->integer((int)$newRows['cpt'])->isEqualTo((int)$sourceRows['cpt']); // Check questions were copied - $table_section = \PluginFormcreatorSection::getTable(); - $question = new \PluginFormcreatorQuestion(); - $sourceRows = $question->find("`plugin_formcreator_sections_id` IN ( - SELECT `id` FROM `$table_section` WHERE `$table_section`.`plugin_formcreator_forms_id` = '$sourceFormId' - )"); - $newRows = $question->find("`plugin_formcreator_sections_id` IN ( - SELECT `id` FROM `$table_section` WHERE `$table_section`.`plugin_formcreator_forms_id` = '$newFormId' - )"); - $this->integer(count($newRows))->isEqualTo(count($sourceRows)); + $question_table = \PluginFormcreatorQuestion::getTable(); + $section_table = \PluginFormcreatorSection::getTable(); + $sourceRows = $DB->request([ + 'COUNT' => 'cpt', + 'FROM' => $question_table, + 'INNER JOIN' => [ + $section_table => [ + 'FKEY' => [ + "$section_table.id", + "$question_table.plugin_formcreator_sections_id" + ] + ] + ], + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $sourceFormId, + ] + ])->next(); + $newRows = $DB->request([ + 'COUNT' => 'cpt', + 'FROM' => $question_table, + 'INNER JOIN' => [ + $section_table => [ + 'FKEY' => [ + "$section_table.id", + "$question_table.plugin_formcreator_sections_id" + ] + ] + ], + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $newFormId, + ] + ])->next(); + $this->integer((int)$newRows['cpt'])->isEqualTo((int)$sourceRows['cpt']); // check target were created - $target = new \PluginFormcreatorTarget(); - $sourceRows = $target->find("`plugin_formcreator_forms_id` = '$sourceFormId'"); - $newRows = $target->find("`plugin_formcreator_forms_id` = '$sourceFormId'"); + $sourceRows = $DB->request([ + 'SELECT' => ['itemtype', 'items_id'], + 'FROM' => \PluginFormcreatorTarget::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $sourceFormId, + ] + ]); + $newRows = $DB->request([ + 'SELECT' => ['itemtype', 'items_id'], + 'FROM' => \PluginFormcreatorTarget::getTable(), + 'WHERE' => [ + 'plugin_formcreator_forms_id' => $newFormId, + ] + ]); $this->integer(count($newRows))->isEqualTo(count($sourceRows)); // check target tickets were created - foreach ($newRows as $targetId => $newTarget) { + foreach ($newRows as $newTarget) { if ($newTarget['itemtype'] == 'PluginFormcreatorTargetTicket') { $targetTicket = new \PluginFormcreatorTArgetTicket(); $targetTicket->getFromDB($newTarget['items_id']); diff --git a/tests/suite-integration/PluginFormcreatorSection.php b/tests/suite-integration/PluginFormcreatorSection.php index 6cc7b73d5..8e77523c6 100644 --- a/tests/suite-integration/PluginFormcreatorSection.php +++ b/tests/suite-integration/PluginFormcreatorSection.php @@ -105,6 +105,8 @@ public function testDelete() { * */ public function testDuplicate() { + global $DB; + $form = $this->getForm(); $section = new \PluginFormcreatorSection(); @@ -112,7 +114,7 @@ public function testDuplicate() { $sections_id = $section->add(['name' => "test clone section", 'plugin_formcreator_forms_id' => $form->getID()]); - $questions_id_1 = $question->add(['name' => "test clone question 1", + $question->add(['name' => "test clone question 1", 'fieldtype' => 'text', 'plugin_formcreator_sections_id' => $sections_id, 'default_values' => '', @@ -123,7 +125,7 @@ public function testDuplicate() { ] ], ]); - $questions_id_2 = $question->add(['name' => "test clone question 2", + $question->add(['name' => "test clone question 2", 'fieldtype' => 'textarea', 'plugin_formcreator_sections_id' => $sections_id ]); @@ -132,7 +134,6 @@ public function testDuplicate() { $this->integer($section->duplicate()); //get cloned section - $originalId = $section->getID(); $new_section = new \PluginFormcreatorSection; $new_section->getFromDBByCrit([ 'AND' => [ @@ -144,8 +145,20 @@ public function testDuplicate() { $this->boolean($new_section->isNewItem())->isFalse(); // check questions - $all_questions = $question->find("plugin_formcreator_sections_id = ".$section->getID()); - $all_new_questions = $question->find("plugin_formcreator_sections_id = ".$new_section->getID()); + $all_questions = $DB->request([ + 'SELECT' => ['uuid'], + 'FROM' => $question::getTable(), + 'WHERE' => [ + 'plugin_formcreator_sections_id' => $section->getID(), + ] + ]); + $all_new_questions = $DB->request([ + 'SELECT' => ['uuid'], + 'FROM' => $question::getTable(), + 'WHERE' => [ + 'plugin_formcreator_sections_id' => $new_section->getID(), + ] + ]); $this->integer(count($all_new_questions))->isEqualTo(count($all_questions)); // check that all question uuid are new diff --git a/tests/suite-integration/PluginFormcreatorTargetTicket.php b/tests/suite-integration/PluginFormcreatorTargetTicket.php index 678ba4e71..725769648 100644 --- a/tests/suite-integration/PluginFormcreatorTargetTicket.php +++ b/tests/suite-integration/PluginFormcreatorTargetTicket.php @@ -106,6 +106,8 @@ public function testTargetTicketActors() { } public function testUrgency() { + global $DB; + $form = new \PluginFormcreatorForm(); $formId = $form->add([ 'entities_id' => $_SESSION['glpiactive_entity'], @@ -199,9 +201,6 @@ public function testUrgency() { if (!empty($targetData['urgency_question'])) { $questionName = $targetData['urgency_question']; $question = new \PluginFormcreatorQuestion(); - $table_section = \PluginFormcreatorSection::getTable(); - $table_form = \PluginFormcreatorForm::getTable(); - $table_question = \PluginFormcreatorQuestion::getTable(); $question->getFromDBByRequest([ 'LEFT JOIN' => [ \PluginFormcreatorSection::getTable() => [ @@ -266,10 +265,15 @@ public function testUrgency() { foreach ($urgencyQuestions as $question) { $targetTicket = $question['targetTicket']; $targetName = $targetTicket->getField('name'); - $itemTicket = new \Item_Ticket(); $tickets = []; - $rows = $itemTicket->find("`itemtype` = 'PluginFormcreatorFormAnswer' - AND `items_id` = '" . $formAnswer->getID() . "'"); + $rows = $DB->request([ + 'SELECT' => ['tickets_id'], + 'FROM' => \Item_Ticket::getTable(), + 'WHERE' => [ + 'itemtype' => 'PluginFormcreatorFormAnswer', + 'items_id' => $formAnswer->getID() + ] + ]); foreach ($rows as $row) { $tickets[] = $row['tickets_id']; } diff --git a/tests/suite-uninstall/Config.php b/tests/suite-uninstall/Config.php index 85ac164c2..81033817a 100644 --- a/tests/suite-uninstall/Config.php +++ b/tests/suite-uninstall/Config.php @@ -72,13 +72,23 @@ public function testUninstallPlugin() { $this->integer(count($tables))->isEqualTo(0, "not deleted tables \n" . json_encode($tables, JSON_PRETTY_PRINT)); // Check the notifications of the plugin no longer exist - $notification = new \Notification(); - $rows = $notification->find("`itemtype` = 'PluginFormcreatorFormAnswer'"); - $this->integer(count($rows))->isEqualTo(0); + $rows = $DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \Notification::getTable(), + 'WHERE' => [ + 'itemtype' => 'PluginFormcreatorFormAnswer', + ] + ])->next(); + $this->integer((int)$rows['cpt'])->isEqualTo(0); - $template = new \NotificationTemplate(); - $rows = $template->find("`itemtype` = 'PluginFormcreatorFormAnswer'"); - $this->integer(count($rows))->isEqualTo(0); + $rows = $DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \NotificationTemplate::getTable(), + 'WHERE' => [ + 'itemtype' => 'PluginFormcreatorFormAnswer', + ] + ])->next(); + $this->integer((int)$rows['cpt'])->isEqualTo(0); // TODO: need to find a reliable way to detect not clenaed // - NotificationTemplateTranslation diff --git a/tests/suite-unit/PluginFormcreatorCategory.php b/tests/suite-unit/PluginFormcreatorCategory.php new file mode 100644 index 000000000..a51ec5684 --- /dev/null +++ b/tests/suite-unit/PluginFormcreatorCategory.php @@ -0,0 +1,96 @@ +. + * --------------------------------------------------------------------- + * + * @copyright Copyright © 2011 - 2018 Teclib' + * @license http://www.gnu.org/licenses/gpl.txt GPLv3+ + * @link https://github.com/pluginsGLPI/formcreator/ + * @link https://pluginsglpi.github.io/formcreator/ + * @link http://plugins.glpi-project.org/#/plugin/formcreator + * --------------------------------------------------------------------- + */ +namespace tests\units; +use GlpiPlugin\Formcreator\Tests\CommonTestCase; + +class PluginFormcreatorCategory extends CommonTestCase { + public function testgetCategoryTree() { + $this->login('glpi', 'glpi'); + $_SESSION["glpicronuserrunning"] = true; + + // create a sub entity which will take in the forms and cateory for this test + // and not conflict with previous data + $entity = new \Entity(); + $rand = mt_rand(); + $entities_id = $entity->add([ + 'name' => "test formcreator sub entity $rand", + 'entities_id' => 0 + ]); + + // create some categories for forms + $category = new \PluginFormcreatorCategory; + $categories = []; + for ($i = 0; $i < 5; $i++) { + $root_cat = $category->add([ + 'name' => "test category root $i", + ]); + $categories[] = $root_cat; + + $sub_cat = $category->add([ + 'name' => "test sub category $i", + 'plugin_formcreator_categories_id' => $root_cat + ]); + $categories[] = $sub_cat; + } + + // create some forms + $form = new \PluginFormcreatorForm; + for ($i = 0; $i < 10; $i++) { + $form->add([ + 'name' => "testgetCategoryTree form $i", + 'entities_id' => $entities_id, + 'is_active' => 1, + 'is_helpdesk_home' => 1, + 'plugin_formcreator_categories_id' => $categories[$i] + ]); + } + + // Set active entity + \Session::changeActiveEntities($entities_id, true); + + //test method + $tree = \PluginFormcreatorCategory::getCategoryTree(0, true); + $this->array($tree) + ->isNotEmpty() + ->child['subcategories'](function($child) { + $child->size->isGreaterThanOrEqualTo(5); + }); + + foreach ($tree['subcategories'] as $subcategory) { + $this->array($subcategory) + ->hasKeys(['name', 'parent', 'id', 'subcategories']); + } + + // return to root entity + \Session::changeActiveEntities(0, true); + } +} diff --git a/tests/suite-unit/PluginFormcreatorForm.php b/tests/suite-unit/PluginFormcreatorForm.php index d69463a10..4ac31442c 100644 --- a/tests/suite-unit/PluginFormcreatorForm.php +++ b/tests/suite-unit/PluginFormcreatorForm.php @@ -172,6 +172,8 @@ public function testPurgeForm($formData) { } public function testCreateValidationNotification() { + global $DB; + \Config::setConfigurationValues( 'core', ['use_notifications' => 1, 'notifications_mailing' => 1] @@ -192,7 +194,7 @@ public function testCreateValidationNotification() { 'validation_required' => \PluginFormcreatorForm_Validator::VALIDATION_USER, '_validator_users' => [$_SESSION['glpiID']], ]); - $section =$this->getSection([ + $this->getSection([ $form::getForeignKeyField() => $form->getID(), 'name' => 'section', ]); @@ -206,9 +208,15 @@ public function testCreateValidationNotification() { // 1 notification to the validator // 1 notification to the requester - $notification = new \QueuedNotification(); - $foundNotifications = $notification->find("`itemtype` = 'PluginFormcreatorFormAnswer' AND `items_id` = '$formAnswerId'"); - $this->integer(count($foundNotifications))->isEqualTo(2); + $foundNotifications = $DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \QueuedNotification::getTable(), + 'WHERE' => [ + 'itemtype' => 'PluginFormcreatorFormAnswer', + 'items_id' => $formAnswerId, + ] + ])->next(); + $this->integer((int) $foundNotifications['cpt'])->isEqualTo(2); } /** @@ -272,8 +280,8 @@ public function testExportForm() { 'content' => '##FULLFORM##' ]); $form_target->getFromDB($targets_id); - $targettickets_id = $form_target->fields['items_id']; - $form_profiles_id = $form_profile->add(['plugin_formcreator_forms_id' => $forms_id, + $form_target->fields['items_id']; + $form_profile->add(['plugin_formcreator_forms_id' => $forms_id, 'profiles_id' => 1]); $item_targetTicket->add(['plugin_formcreator_targettickets_id' => $targetTicket_id, 'link' => \Ticket_Ticket::LINK_TO, @@ -415,7 +423,7 @@ public function testIsPublicAcess($input, $expected) { } public function providerGetFromSection() { $section = $this->getSection(); - $formId = $section->getField(\PluginFormcreatorForm::getForeignKeyField()); + $section->getField(\PluginFormcreatorForm::getForeignKeyField()); $dataset = [ [ 'section' => $section, diff --git a/tests/suite-unit/PluginFormcreatorSection.php b/tests/suite-unit/PluginFormcreatorSection.php index 470b2eaa0..4b8741cbf 100644 --- a/tests/suite-unit/PluginFormcreatorSection.php +++ b/tests/suite-unit/PluginFormcreatorSection.php @@ -71,6 +71,8 @@ public function setup() { * @cover PluginFormcreatorSection::clone */ public function testDuplicate() { + global $DB; + // instanciate classes $form = new \PluginFormcreatorForm; $section = new \PluginFormcreatorSection; @@ -97,16 +99,27 @@ public function testDuplicate() { $this->integer($newSection_id)->isGreaterThan(0); //get cloned section - $new_section = new \PluginFormcreatorSection; - $question = new \PluginFormcreatorQuestion; + $new_section = new \PluginFormcreatorSection; $new_section->getFromDB($newSection_id); // check uuid $this->string($new_section->getField('uuid'))->isNotEqualTo($section->getField('uuid')); // check questions - $all_questions = $question->find("plugin_formcreator_sections_id = ".$section->getID()); - $all_new_questions = $question->find("plugin_formcreator_sections_id = ".$new_section->getID()); + $all_questions = $DB->request([ + 'SELECT' => ['uuid'], + 'FROM' => \PluginFormcreatorQuestion::getTable(), + 'WHERE' => [ + 'plugin_formcreator_sections_id' => $section->getID() + ] + ]); + $all_new_questions = $DB->request([ + 'SELECT' => ['uuid'], + 'FROM' => \PluginFormcreatorQuestion::getTable(), + 'WHERE' => [ + 'plugin_formcreator_sections_id' => $new_section->getID() + ] + ]); $this->integer(count($all_new_questions))->isEqualTo(count($all_questions)); // check that all question uuid are new From e05e20bac3e3a5229eb1c86fcfcadcd2ee3c61ac Mon Sep 17 00:00:00 2001 From: Alexandre Delaunay Date: Mon, 17 Dec 2018 10:58:38 +0100 Subject: [PATCH 05/33] fix(form): access rights checking --- inc/form.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inc/form.class.php b/inc/form.class.php index 2e7b81cc9..972b887e7 100644 --- a/inc/form.class.php +++ b/inc/form.class.php @@ -1082,7 +1082,7 @@ public function prepareInputForUpdate($input) { || isset($input['usage_count'])) { if (isset($input['access_rights']) - && $input['access_right'] == self::ACCESS_PUBLIC + && $input['access_rights'] == self::ACCESS_PUBLIC ) { // check that accessibility to eh form is compatible with its questions $question = new PluginFormcreatorQuestion(); From 8355480c9ae1eb5281e71ef3a9ba94f0a522560f Mon Sep 17 00:00:00 2001 From: Alexandre Delaunay Date: Mon, 17 Dec 2018 15:36:55 +0100 Subject: [PATCH 06/33] fix(targetTicket): generation of ticket regression causing sql error on content since 4588efa57b3a --- inc/targetticket.class.php | 1 + 1 file changed, 1 insertion(+) diff --git a/inc/targetticket.class.php b/inc/targetticket.class.php index 0d95bdcd3..7c48ef304 100644 --- a/inc/targetticket.class.php +++ b/inc/targetticket.class.php @@ -1147,6 +1147,7 @@ public function save(PluginFormcreatorFormAnswer $formanswer) { $richText ); + $data['content'] = Toolbox::addslashes_deep($data['content']); $data['content'] = $this->parseTags($data['content'], $formanswer, $richText); $data['_users_id_recipient'] = $_SESSION['glpiID']; From c08e29978c825a0d6a07b0c778276b0cffd1fd93 Mon Sep 17 00:00:00 2001 From: btry Date: Tue, 18 Dec 2018 10:44:21 +0100 Subject: [PATCH 07/33] fix(install): create tables before filling them (#1234) Signed-off-by: Thierry Bugier --- install/upgrade_to_2.7.php | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/install/upgrade_to_2.7.php b/install/upgrade_to_2.7.php index 15d05eb0e..e58e11ac3 100644 --- a/install/upgrade_to_2.7.php +++ b/install/upgrade_to_2.7.php @@ -116,6 +116,17 @@ public function upgrade(Migration $migration) { // Migrate regex question parameters $table = 'glpi_plugin_formcreator_questions'; if ($DB->fieldExists($table, 'regex')) { + $DB->query( + "CREATE TABLE IF NOT EXISTS `glpi_plugin_formcreator_questionregexes` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `plugin_formcreator_questions_id` int(11) NOT NULL, + `regex` text DEFAULT NULL, + `fieldname` varchar(255) DEFAULT NULL, + `uuid` varchar(255) DEFAULT NULL, + PRIMARY KEY (`id`), + INDEX `plugin_formcreator_questions_id` (`plugin_formcreator_questions_id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;" + ); $request = [ 'FROM' => $table, 'WHERE' => ['fieldtype' => ['float', 'integer', 'text', 'textarea']] @@ -134,6 +145,18 @@ public function upgrade(Migration $migration) { // Migrate range question parameters $table = 'glpi_plugin_formcreator_questions'; if ($DB->fieldExists($table, 'range_min')) { + $DB->query( + "CREATE TABLE IF NOT EXISTS `glpi_plugin_formcreator_questionranges` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `plugin_formcreator_questions_id` int(11) NOT NULL, + `range_min` varchar(255) DEFAULT NULL, + `range_max` varchar(255) DEFAULT NULL, + `fieldname` varchar(255) DEFAULT NULL, + `uuid` varchar(255) DEFAULT NULL, + PRIMARY KEY (`id`), + INDEX `plugin_formcreator_questions_id` (`plugin_formcreator_questions_id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;" + ); $request = [ 'FROM' => $table, 'WHERE' => ['fieldtype' => ['float', 'integer', 'checkboxes', 'multiselect', 'text']] From 6afe5fea0f53e62b1e5c3447cd13d4cc9ffcb124 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Tue, 18 Dec 2018 11:13:21 +0100 Subject: [PATCH 08/33] feat(targetticket): compatibility with GLPI 9.4 Signed-off-by: Thierry Bugier --- inc/targetticket.class.php | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/inc/targetticket.class.php b/inc/targetticket.class.php index 7c48ef304..e958d9222 100644 --- a/inc/targetticket.class.php +++ b/inc/targetticket.class.php @@ -1368,13 +1368,27 @@ public function save(PluginFormcreatorFormAnswer $formanswer) { $use_mailing = PluginFormcreatorCommon::isNotificationEnabled(); PluginFormcreatorCommon::setNotification(false); - $ticketFollowup = new TicketFollowup(); - $ticketFollowup->add([ - 'tickets_id' => $ticketID, - 'date' => $_SESSION['glpi_currenttime'], - 'users_id' => $_SESSION['glpiID'], - 'content' => $message - ]); + $followUpInput = [ + 'date' => $_SESSION['glpi_currenttime'], + 'users_id' => Session::getLoginUserID(), + 'content' => $message, + ]; + if (class_exists(ITILFollowup::class)) { + // GLPI 9.4+ + $followUpInput += [ + 'items_id' => $ticketID, + 'itemtype' => Ticket::class, + ]; + $ticketFollowup = new ITILFollowup(); + $ticketFollowup->add($followUpInput); + } else { + // GLPI < 9.4 + $followUpInput += [ + 'tickets_id' => $ticketID, + ]; + $ticketFollowup = new TicketFollowup(); + $ticketFollowup->add($followUpInput); + } // Restore mail notification setting PluginFormcreatorCommon::setNotification($use_mailing); From f0a3536f51014ecb8e6526f0bc0611ea91968fd8 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Tue, 18 Dec 2018 12:39:21 +0100 Subject: [PATCH 09/33] docs: fix declared compatibility wqith GLPI Signed-off-by: Thierry Bugier --- plugin.xml | 5 +---- setup.php | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/plugin.xml b/plugin.xml index 7680e3dde..938427717 100644 --- a/plugin.xml +++ b/plugin.xml @@ -241,11 +241,8 @@ Features 2.7.0-beta.1 - 9.2.1 - 9.2.2 - 9.2.3 - 9.2.4 9.3 + 9.4 diff --git a/setup.php b/setup.php index 4f3be5934..5c6997709 100644 --- a/setup.php +++ b/setup.php @@ -42,7 +42,7 @@ // Minimal GLPI version, inclusive define ('PLUGIN_FORMCREATOR_GLPI_MIN_VERSION', '9.3.0'); // Maximum GLPI version, exclusive -define ('PLUGIN_FORMCREATOR_GLPI_MAX_VERSION', '9.5'); +define ('PLUGIN_FORMCREATOR_GLPI_MAX_VERSION', '9.4'); define('FORMCREATOR_ROOTDOC', $CFG_GLPI['root_doc'] . '/plugins/formcreator'); From 60a13a9bf1284320c459228b92254f9fc768093b Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Tue, 18 Dec 2018 08:56:11 +0100 Subject: [PATCH 10/33] test(category): add tests Signed-off-by: Thierry Bugier --- .../suite-unit/PluginFormcreatorCategory.php | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/tests/suite-unit/PluginFormcreatorCategory.php b/tests/suite-unit/PluginFormcreatorCategory.php index a51ec5684..06dbdab80 100644 --- a/tests/suite-unit/PluginFormcreatorCategory.php +++ b/tests/suite-unit/PluginFormcreatorCategory.php @@ -33,7 +33,37 @@ use GlpiPlugin\Formcreator\Tests\CommonTestCase; class PluginFormcreatorCategory extends CommonTestCase { - public function testgetCategoryTree() { + public function providerGetTypeName() { + return [ + [ + 0, + 'Form categories' + ], + [ + 1, + 'Form category' + ], + [ + 2, + 'Form categories' + ], + ]; + } + + /** + * @dataProvider providerGetTypeName + * + * @param integer $nb + * @param string $expected + * @return void + */ + public function testGetTypeName($nb, $expected) { + $instance = new $this->newTestedInstance(); + $output = $instance->getTypeName($nb); + $this->string($output)->isEqualTo($expected); + } + + public function testGetCategoryTree() { $this->login('glpi', 'glpi'); $_SESSION["glpicronuserrunning"] = true; From 20534d4588279035e1a29317192a4e17f371b0ac Mon Sep 17 00:00:00 2001 From: Alexandre Delaunay Date: Tue, 18 Dec 2018 15:24:03 +0100 Subject: [PATCH 11/33] add test for Form::saveForm --- tests/suite-unit/PluginFormcreatorForm.php | 57 ++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/tests/suite-unit/PluginFormcreatorForm.php b/tests/suite-unit/PluginFormcreatorForm.php index 4ac31442c..45a33ea8b 100644 --- a/tests/suite-unit/PluginFormcreatorForm.php +++ b/tests/suite-unit/PluginFormcreatorForm.php @@ -445,4 +445,61 @@ public function testgetFormFromSection($section, $expected) { $output = $form->getFromDBBySection($section); $this->boolean($output)->isEqualTo($expected); } + + public function testSaveForm() { + $answer = "test answer to question"; + + // prepare a fake form with targets + $question = $this->getQuestion(); + $section = new \PluginFormcreatorSection(); + $section->getFromDB($question->fields[\PluginFormcreatorSection::getForeignKeyField()]); + $form = new \PluginFormcreatorForm(); + $form->getFromDB($section->fields[\PluginFormcreatorForm::getForeignKeyField()]); + $formFk = \PluginFormcreatorForm::getForeignKeyField(); + $this->getTargetTicket([ + $formFk => $form->getID(), + ]); + $this->getTargetChange([ + $formFk => $form->getID(), + ]); + + // prepare input + $input = [ + 'formcreator_form' => $form->getID(), + 'formcreator_field_'.$question->getID() => $answer + ]; + + // send for answer + $formAnswerId = $form->saveForm($input); + $this->boolean((bool)$formAnswerId)->isTrue(); + + // check existence of generated target + // - ticket + $item_ticket = new \Item_Ticket; + $this->boolean($item_ticket->getFromDBByCrit([ + 'itemtype' => 'PluginFormcreatorFormAnswer', + 'items_id' => $formAnswerId, + ]))->isTrue(); + $ticket = new \Ticket; + $this->boolean($ticket->getFromDB($item_ticket->fields['tickets_id']))->isTrue(); + $this->string($ticket->fields['content'])->contains($answer); + + // - change + $change_item = new \Change_Item; + $this->boolean($change_item->getFromDBByCrit([ + 'itemtype' => 'PluginFormcreatorFormAnswer', + 'items_id' => $formAnswerId, + ]))->isTrue(); + $change = new \Change; + $this->boolean($change->getFromDB($change_item->fields['changes_id']))->isTrue(); + $this->string($change->fields['content'])->contains($answer); + + // - issue + $issue = new \PluginFormcreatorIssue; + $this->boolean($issue->getFromDBByCrit([ + 'sub_itemtype' => PluginFormcreatorFormAnswer::class, + 'original_id' => $formAnswerId + ]))->isTrue(); + + } } From 3b13b1c85b43ec996ef8785353be97036611fb92 Mon Sep 17 00:00:00 2001 From: Alexandre Delaunay Date: Tue, 18 Dec 2018 16:38:44 +0100 Subject: [PATCH 12/33] fix tests --- inc/fields/checkboxesfield.class.php | 4 ++-- inc/fields/floatfield.class.php | 4 ++-- inc/fields/integerfield.class.php | 4 ++-- inc/fields/multiselectfield.class.php | 4 ++-- inc/fields/textfield.class.php | 4 ++-- tests/src/CommonTestCase.php | 3 +++ tests/suite-unit/PluginFormcreatorForm.php | 4 ++-- 7 files changed, 15 insertions(+), 12 deletions(-) diff --git a/inc/fields/checkboxesfield.class.php b/inc/fields/checkboxesfield.class.php index f281d2e65..cdd4b3441 100644 --- a/inc/fields/checkboxesfield.class.php +++ b/inc/fields/checkboxesfield.class.php @@ -153,13 +153,13 @@ private function isValidValue($value) { if (!$parameters['range']->isNewItem()) { $rangeMin = $parameters['range']->fields['range_min']; $rangeMax = $parameters['range']->fields['range_max']; - if (strlen($rangeMin) > 0 && count($value) < $rangeMin) { + if ($rangeMin > 0 && count($value) < $rangeMin) { $message = sprintf(__('The following question needs of at least %d answers', 'formcreator'), $rangeMin); Session::addMessageAfterRedirect($message . ' ' . $this->getLabel(), false, ERROR); return false; } - if (strlen($rangeMax) > 0 && count($value) > $rangeMax) { + if ($rangeMax > 0 && count($value) > $rangeMax) { $message = sprintf(__('The following question does not accept more than %d answers', 'formcreator'), $rangeMax); Session::addMessageAfterRedirect($message . ' ' . $this->getLabel(), false, ERROR); return false; diff --git a/inc/fields/floatfield.class.php b/inc/fields/floatfield.class.php index e8a89072a..00f41d5cb 100644 --- a/inc/fields/floatfield.class.php +++ b/inc/fields/floatfield.class.php @@ -125,13 +125,13 @@ private function isValidValue($value) { if (!$parameters['range']->isNewItem()) { $rangeMin = $parameters['range']->fields['range_min']; $rangeMax = $parameters['range']->fields['range_max']; - if (strlen($rangeMin) > 0 && $value < $rangeMin) { + if ($rangeMin > 0 && $value < $rangeMin) { $message = sprintf(__('The following number must be greater than %d:', 'formcreator'), $rangeMin); Session::addMessageAfterRedirect($message . ' ' . $this->fields['name'], false, ERROR); return false; } - if (strlen($rangeMax) > 0 && $value > $rangeMax) { + if ($rangeMax > 0 && $value > $rangeMax) { $message = sprintf(__('The following number must be lower than %d:', 'formcreator'), $rangeMax); Session::addMessageAfterRedirect($message . ' ' . $this->fields['name'], false, ERROR); return false; diff --git a/inc/fields/integerfield.class.php b/inc/fields/integerfield.class.php index 37ee43a11..566569a93 100644 --- a/inc/fields/integerfield.class.php +++ b/inc/fields/integerfield.class.php @@ -126,13 +126,13 @@ public function isValidValue() { if (!$parameters['range']->isNewItem()) { $rangeMin = $parameters['range']->fields['range_min']; $rangeMax = $parameters['range']->fields['range_max']; - if (strlen($rangeMin) > 0 && $this->value < $rangeMin) { + if ($rangeMin 0 && $this->value < $rangeMin) { $message = sprintf(__('The following number must be greater than %d:', 'formcreator'), $rangeMin); Session::addMessageAfterRedirect($message . ' ' . $this->fields['name'], false, ERROR); return false; } - if (strlen($rangeMax) > 0 && $this->value > $rangeMax) { + if ($rangeMax 0 && $this->value > $rangeMax) { $message = sprintf(__('The following number must be lower than %d:', 'formcreator'), $rangeMax); Session::addMessageAfterRedirect($message . ' ' . $this->fields['name'], false, ERROR); return false; diff --git a/inc/fields/multiselectfield.class.php b/inc/fields/multiselectfield.class.php index 3835ca076..0f1a20727 100644 --- a/inc/fields/multiselectfield.class.php +++ b/inc/fields/multiselectfield.class.php @@ -117,13 +117,13 @@ private function isValidValue($value) { // Check the field matches the format regex $rangeMin = $parameters['range']->fields['range_min']; $rangeMax = $parameters['range']->fields['range_max']; - if (strlen($rangeMin) > 0 && count($value) < $rangeMin) { + if ($rangeMin > 0 && count($value) < $rangeMin) { $message = sprintf(__('The following question needs of at least %d answers', 'formcreator'), $rangeMin); Session::addMessageAfterRedirect($message . ' ' . $this->getLabel(), false, ERROR); return false; } - if (strlen($rangeMax) > 0 && count($value) > $rangeMax) { + if ($rangeMax > 0 && count($value) > $rangeMax) { $message = sprintf(__('The following question does not accept more than %d answers', 'formcreator'), $rangeMax); Session::addMessageAfterRedirect($message . ' ' . $this->getLabel(), false, ERROR); return false; diff --git a/inc/fields/textfield.class.php b/inc/fields/textfield.class.php index 767001917..8d4361be7 100644 --- a/inc/fields/textfield.class.php +++ b/inc/fields/textfield.class.php @@ -119,12 +119,12 @@ private function isValidValue($value) { // Check the field is in the range $rangeMin = $parameters['range']->fields['range_min']; $rangeMax = $parameters['range']->fields['range_max']; - if (strlen($rangeMin) > 0 && strlen($value) < $rangeMin) { + if ($rangeMin > 0 && strlen($value) < $rangeMin) { Session::addMessageAfterRedirect(sprintf(__('The text is too short (minimum %d characters):', 'formcreator'), $rangeMin) . ' ' . $this->fields['name'], false, ERROR); return false; } - if (strlen($rangeMax) > 0 && strlen($value) > $rangeMax) { + if ($rangeMax > 0 && strlen($value) > $rangeMax) { Session::addMessageAfterRedirect(sprintf(__('The text is too short (minimum %d characters):', 'formcreator'), $rangeMax) . ' ' . $this->fields['name'], false, ERROR); return false; } diff --git a/tests/src/CommonTestCase.php b/tests/src/CommonTestCase.php index 701c27f88..304595ac1 100644 --- a/tests/src/CommonTestCase.php +++ b/tests/src/CommonTestCase.php @@ -158,6 +158,9 @@ protected function getForm($input = []) { if (!isset($input['name'])) { $input['name'] = $this->getUniqueString(); } + if (!isset($input['is_active'])) { + $input['is_active'] = true; + } $form = new \PluginFormcreatorForm(); $form->add($input); $this->boolean($form->isNewItem())->isFalse(); diff --git a/tests/suite-unit/PluginFormcreatorForm.php b/tests/suite-unit/PluginFormcreatorForm.php index 45a33ea8b..4fec755e5 100644 --- a/tests/suite-unit/PluginFormcreatorForm.php +++ b/tests/suite-unit/PluginFormcreatorForm.php @@ -497,8 +497,8 @@ public function testSaveForm() { // - issue $issue = new \PluginFormcreatorIssue; $this->boolean($issue->getFromDBByCrit([ - 'sub_itemtype' => PluginFormcreatorFormAnswer::class, - 'original_id' => $formAnswerId + 'sub_itemtype' => \Ticket::class, + 'original_id' => $ticket->getID() ]))->isTrue(); } From b59cd1371b1132d5fb7edce0830d83b26b7dbd70 Mon Sep 17 00:00:00 2001 From: Alexandre Delaunay Date: Tue, 18 Dec 2018 16:48:12 +0100 Subject: [PATCH 13/33] fix previous --- inc/fields/integerfield.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/inc/fields/integerfield.class.php b/inc/fields/integerfield.class.php index 566569a93..c0cb11b36 100644 --- a/inc/fields/integerfield.class.php +++ b/inc/fields/integerfield.class.php @@ -126,13 +126,13 @@ public function isValidValue() { if (!$parameters['range']->isNewItem()) { $rangeMin = $parameters['range']->fields['range_min']; $rangeMax = $parameters['range']->fields['range_max']; - if ($rangeMin 0 && $this->value < $rangeMin) { + if ($rangeMin > 0 && $this->value < $rangeMin) { $message = sprintf(__('The following number must be greater than %d:', 'formcreator'), $rangeMin); Session::addMessageAfterRedirect($message . ' ' . $this->fields['name'], false, ERROR); return false; } - if ($rangeMax 0 && $this->value > $rangeMax) { + if ($rangeMax > 0 && $this->value > $rangeMax) { $message = sprintf(__('The following number must be lower than %d:', 'formcreator'), $rangeMax); Session::addMessageAfterRedirect($message . ' ' . $this->fields['name'], false, ERROR); return false; From 5f56730e6ef8e05dff55fbe1dbf51c82a4163b07 Mon Sep 17 00:00:00 2001 From: Alexandre Delaunay Date: Tue, 18 Dec 2018 16:54:45 +0100 Subject: [PATCH 14/33] bad message --- inc/fields/textfield.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inc/fields/textfield.class.php b/inc/fields/textfield.class.php index 8d4361be7..c5272c7b3 100644 --- a/inc/fields/textfield.class.php +++ b/inc/fields/textfield.class.php @@ -125,7 +125,7 @@ private function isValidValue($value) { } if ($rangeMax > 0 && strlen($value) > $rangeMax) { - Session::addMessageAfterRedirect(sprintf(__('The text is too short (minimum %d characters):', 'formcreator'), $rangeMax) . ' ' . $this->fields['name'], false, ERROR); + Session::addMessageAfterRedirect(sprintf(__('The text is too long (maximum %d characters):', 'formcreator'), $rangeMax) . ' ' . $this->fields['name'], false, ERROR); return false; } From 2ad95a235bfe156ba3575bf21f04d3150179c8df Mon Sep 17 00:00:00 2001 From: Alexandre Delaunay Date: Tue, 18 Dec 2018 17:03:09 +0100 Subject: [PATCH 15/33] force login --- tests/suite-unit/PluginFormcreatorForm.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/suite-unit/PluginFormcreatorForm.php b/tests/suite-unit/PluginFormcreatorForm.php index 4fec755e5..bb877e43f 100644 --- a/tests/suite-unit/PluginFormcreatorForm.php +++ b/tests/suite-unit/PluginFormcreatorForm.php @@ -447,6 +447,8 @@ public function testgetFormFromSection($section, $expected) { } public function testSaveForm() { + $this->login('glpi', 'glpi'); + $answer = "test answer to question"; // prepare a fake form with targets From 14bdde11c13748a78586df854d5b94ba6a66aa22 Mon Sep 17 00:00:00 2001 From: Alexandre Delaunay Date: Tue, 18 Dec 2018 17:04:46 +0100 Subject: [PATCH 16/33] int for is_active --- tests/src/CommonTestCase.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/src/CommonTestCase.php b/tests/src/CommonTestCase.php index 304595ac1..052fb2f4f 100644 --- a/tests/src/CommonTestCase.php +++ b/tests/src/CommonTestCase.php @@ -159,7 +159,7 @@ protected function getForm($input = []) { $input['name'] = $this->getUniqueString(); } if (!isset($input['is_active'])) { - $input['is_active'] = true; + $input['is_active'] = 1; } $form = new \PluginFormcreatorForm(); $form->add($input); From bfa0a149fa8f3e6381078985ef20a23133708449 Mon Sep 17 00:00:00 2001 From: Alexandre Delaunay Date: Tue, 18 Dec 2018 17:25:45 +0100 Subject: [PATCH 17/33] disable notifications for the test --- tests/suite-unit/PluginFormcreatorForm.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/suite-unit/PluginFormcreatorForm.php b/tests/suite-unit/PluginFormcreatorForm.php index bb877e43f..b87e71cbb 100644 --- a/tests/suite-unit/PluginFormcreatorForm.php +++ b/tests/suite-unit/PluginFormcreatorForm.php @@ -447,8 +447,14 @@ public function testgetFormFromSection($section, $expected) { } public function testSaveForm() { + global $CFG_GLPI; + $this->login('glpi', 'glpi'); + // disable notifications as we may fail in some case (not the purpose of this test btw) + $use_notifications = $CFG_GLPI['use_notifications']; + $CFG_GLPI['use_notifications'] = 0; + $answer = "test answer to question"; // prepare a fake form with targets @@ -503,5 +509,6 @@ public function testSaveForm() { 'original_id' => $ticket->getID() ]))->isTrue(); + $CFG_GLPI['use_notifications'] = $use_notifications; } } From a2cbcb4cd063c63432c5595db1d326d3f7941256 Mon Sep 17 00:00:00 2001 From: Alexandre Delaunay Date: Tue, 18 Dec 2018 17:38:19 +0100 Subject: [PATCH 18/33] test integer --- tests/suite-unit/PluginFormcreatorForm.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/suite-unit/PluginFormcreatorForm.php b/tests/suite-unit/PluginFormcreatorForm.php index b87e71cbb..03cd05d48 100644 --- a/tests/suite-unit/PluginFormcreatorForm.php +++ b/tests/suite-unit/PluginFormcreatorForm.php @@ -479,7 +479,7 @@ public function testSaveForm() { // send for answer $formAnswerId = $form->saveForm($input); - $this->boolean((bool)$formAnswerId)->isTrue(); + $this->integer($formAnswerId)->isGreaterThan(0); // check existence of generated target // - ticket From f5dfae05ff3cb9d87195a0a51e80be8e69c1e1e6 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Wed, 19 Dec 2018 16:26:34 +0100 Subject: [PATCH 19/33] test(entityconfig): add tests Signed-off-by: Thierry Bugier --- inc/entityconfig.class.php | 2 - .../PluginFormcreatorEntityConfig.php | 96 +++++++++++++++++++ 2 files changed, 96 insertions(+), 2 deletions(-) create mode 100644 tests/suite-unit/PluginFormcreatorEntityConfig.php diff --git a/inc/entityconfig.class.php b/inc/entityconfig.class.php index fff56f94e..b3a71ac78 100644 --- a/inc/entityconfig.class.php +++ b/inc/entityconfig.class.php @@ -51,7 +51,6 @@ class PluginFormcreatorEntityconfig extends CommonDBTM { public $dohistory = true; public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { - $tabNames = []; if (!$withtemplate) { if ($item->getType() == 'Entity') { @@ -62,7 +61,6 @@ public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { } public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) { - if ($item->getType() == 'Entity') { $config = new self(); $config->showFormForEntity($item); diff --git a/tests/suite-unit/PluginFormcreatorEntityConfig.php b/tests/suite-unit/PluginFormcreatorEntityConfig.php new file mode 100644 index 000000000..1f27e2d9e --- /dev/null +++ b/tests/suite-unit/PluginFormcreatorEntityConfig.php @@ -0,0 +1,96 @@ +. + * --------------------------------------------------------------------- + * + * @copyright Copyright © 2011 - 2018 Teclib' + * @license http://www.gnu.org/licenses/gpl.txt GPLv3+ + * @link https://github.com/pluginsGLPI/formcreator/ + * @link https://pluginsglpi.github.io/formcreator/ + * @link http://plugins.glpi-project.org/#/plugin/formcreator + * --------------------------------------------------------------------- + */ +namespace tests\units; +use GlpiPlugin\Formcreator\Tests\CommonTestCase; + +class PluginFormcreatorEntityconfig extends CommonTestCase { + public function providerGetTabNameForItem() { + return [ + [ + new \Entity, + ['1' => 'Forms'], + ], + [ + new \Ticket, + [], + ] + ]; + } + + /** + * @dataProvider providerGetTabNameForItem + */ + public function testGetTabNameForItem($item, $expected) { + $instance = $this->newTestedInstance(); + $output = $instance->getTabNameForItem($item); + $this->array($output)->isIdenticalTo($expected); + } + + public function testGetUsedConfig() { + $this->login('glpi', 'glpi'); + $base = 'Root entity > ' . $this->getUniqueString(); + $entity = new \Entity(); + $entityId = $entity->add([ + 'name' => $this->getUniqueString(), + 'entities_id' => '0', + ]); + $entityId1 = $entity->add([ + 'name' => "$base > a", + 'entities_id' => $entityId, + ]); + $entityId2 = $entity->add([ + 'name' => "b", + 'entities_id' => $entityId1, + ]); + + $instance = $this->newTestedInstance(); + $instance->add([ + 'id' => $entityId1, + 'replace_helpdesk' => \PluginFormcreatorEntityconfig::CONFIG_SIMPLIFIED_SERVICE_CATALOG, + ]); + $instance->add([ + 'id' => $entityId2, + 'replace_helpdesk' => \PluginFormcreatorEntityconfig::CONFIG_EXTENDED_SERVICE_CATALOG, + ]); + + $output = $instance::getUsedConfig('replace_helpdesk', $entityId1); + $this->integer((int) $output)->isEqualTo(\PluginFormcreatorEntityconfig::CONFIG_SIMPLIFIED_SERVICE_CATALOG); + $output = $instance::getUsedConfig('replace_helpdesk', $entityId2); + $this->integer((int) $output)->isEqualTo(\PluginFormcreatorEntityconfig::CONFIG_EXTENDED_SERVICE_CATALOG); + $instance->update([ + 'id' => $entityId2, + 'replace_helpdesk' => \PluginFormcreatorEntityconfig::CONFIG_PARENT, + ]); + $output = $instance::getUsedConfig('replace_helpdesk', $entityId2); + $this->integer((int) $output)->isEqualTo(\PluginFormcreatorEntityconfig::CONFIG_SIMPLIFIED_SERVICE_CATALOG); + } +} From bdac6897851f9ca360e08a45de05a122bea22b90 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Fri, 21 Dec 2018 12:32:31 +0100 Subject: [PATCH 20/33] fix(formanswer): missing right check Signed-off-by: Thierry Bugier --- front/formanswer.form.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/front/formanswer.form.php b/front/formanswer.form.php index b3d421a72..f85df4096 100644 --- a/front/formanswer.form.php +++ b/front/formanswer.form.php @@ -71,7 +71,11 @@ // Show target ticket form } else { - if (plugin_formcreator_replaceHelpdesk()) { + $formanswer->getFromDB(intval((int) $_GET['id'])); + if (!$formanswer->checkEntity()) { + Html::displayRightError(); + } + if (plugin_formcreator_replaceHelpdesk()) { PluginFormcreatorWizard::header(__('Service catalog', 'formcreator')); } else { if ($_SESSION['glpiactiveprofile']['interface'] == 'helpdesk') { From 403f97ee33dc1dae1f503a012fa90c473e5c77dd Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Fri, 21 Dec 2018 14:51:36 +0100 Subject: [PATCH 21/33] style(formanswer): indentation problem Signed-off-by: Thierry Bugier --- front/formanswer.form.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/front/formanswer.form.php b/front/formanswer.form.php index f85df4096..2f3fcc402 100644 --- a/front/formanswer.form.php +++ b/front/formanswer.form.php @@ -71,11 +71,11 @@ // Show target ticket form } else { - $formanswer->getFromDB(intval((int) $_GET['id'])); - if (!$formanswer->checkEntity()) { - Html::displayRightError(); - } - if (plugin_formcreator_replaceHelpdesk()) { + $formanswer->getFromDB(intval((int) $_GET['id'])); + if (!$formanswer->checkEntity()) { + Html::displayRightError(); + } + if (plugin_formcreator_replaceHelpdesk()) { PluginFormcreatorWizard::header(__('Service catalog', 'formcreator')); } else { if ($_SESSION['glpiactiveprofile']['interface'] == 'helpdesk') { From 3853f4a146e99077c8c19f8307ee83664e719cb2 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Fri, 21 Dec 2018 14:47:02 +0100 Subject: [PATCH 22/33] test(fields): add tests Signed-off-by: Thierry Bugier --- tests/suite-unit/PluginFormcreatorFields.php | 34 +++++++++++++++++++ .../PluginFormcreatorQuestion_Condition.php | 22 ++++++++++++ 2 files changed, 56 insertions(+) diff --git a/tests/suite-unit/PluginFormcreatorFields.php b/tests/suite-unit/PluginFormcreatorFields.php index 681a6c1aa..0bd3fbb0c 100644 --- a/tests/suite-unit/PluginFormcreatorFields.php +++ b/tests/suite-unit/PluginFormcreatorFields.php @@ -290,4 +290,38 @@ public function testIsVisible($show_rule, $conditions, $answers, $expectedVisibi $isVisible = \PluginFormcreatorFields::isVisible($question->getID(), $realAnswers); $this->boolean((boolean) $isVisible)->isEqualTo($expectedVisibility); } + + public function testGetFieldClassname() { + $output = \PluginFormcreatorFields::getFieldClassname('dummy'); + $this->string($output)->isEqualTo('PluginFormcreatorDummyField'); + } + + public function testFieldTypeExists() { + $output = \PluginFormcreatorFields::fieldTypeExists('dummy'); + $this->boolean($output)->isFalse(); + $output = \PluginFormcreatorFields::fieldTypeExists('textarea'); + $this->boolean($output)->isTrue(); + } + + public function testUpdateVisibility() { + $question1 = $this->getQuestion(); + $question2 = $this->getQuestion([ + 'plugin_formcreator_sections_id' => $question1->fields['plugin_formcreator_sections_id'], + ]); + + $form = new \PluginFormcreatorForm(); + $section = new \PluginFormcreatorSection(); + $section->getFromDB($question1->fields['plugin_formcreator_sections_id']); + $form->getFromDBBySection($section); + $input = [ + 'formcreator_form' => $form->getID(), + $question1->getID() => '', + $question2->getID() => '', + ]; + $output = \PluginFormcreatorFields::updateVisibility($input); + $this->array($output)->isIdenticalTo([ + $question1->getID() => true, + $question2->getID() => true, + ]); + } } diff --git a/tests/suite-unit/PluginFormcreatorQuestion_Condition.php b/tests/suite-unit/PluginFormcreatorQuestion_Condition.php index 1d59be6d2..18d9f2fc0 100644 --- a/tests/suite-unit/PluginFormcreatorQuestion_Condition.php +++ b/tests/suite-unit/PluginFormcreatorQuestion_Condition.php @@ -39,4 +39,26 @@ public function beforeTestMethod($method) { self::login('glpi', 'glpi'); } + + public function testGetConditionsFromQuestion() { + // crete a question with some conditions + $question = $this->getQuestion(); + + $questionFk = \PluginFormcreatorQuestion::getForeignKeyField(); + $questionCondition = $this->newTestedInstance(); + $questionCondition->add([ + $questionFk => $question->getID(), + ]); + $this->boolean($questionCondition->isNewItem())->isFalse(); + + $questionCondition = $this->newTestedInstance(); + $questionCondition->add([ + $questionFk => $question->getID(), + ]); + $this->boolean($questionCondition->isNewItem())->isFalse(); + + // Check that all conditions are retrieved + $output = $question->getConditionsFromQuestion(); + $this->array($output)->hasSize(2); + } } From ee6b40994408bca4f5a8d06a09a5b8e29f578958 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Fri, 21 Dec 2018 16:14:52 +0100 Subject: [PATCH 23/33] test(form_validator): add tests Signed-off-by: Thierry Bugier --- inc/form_profile.class.php | 2 +- .../PluginFormcreatorForm_Profile.php | 88 +++++++++++++++++++ .../PluginFormcreatorForm_Validator.php | 50 +++++++++++ 3 files changed, 139 insertions(+), 1 deletion(-) create mode 100644 tests/suite-unit/PluginFormcreatorForm_Profile.php create mode 100644 tests/suite-unit/PluginFormcreatorForm_Validator.php diff --git a/inc/form_profile.class.php b/inc/form_profile.class.php index 3f6080c42..19ec26465 100644 --- a/inc/form_profile.class.php +++ b/inc/form_profile.class.php @@ -47,7 +47,7 @@ static function getTypeName($nb = 0) { } function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { - return self::getTypeName(2); + return self::getTypeName(2); } /** diff --git a/tests/suite-unit/PluginFormcreatorForm_Profile.php b/tests/suite-unit/PluginFormcreatorForm_Profile.php new file mode 100644 index 000000000..881495876 --- /dev/null +++ b/tests/suite-unit/PluginFormcreatorForm_Profile.php @@ -0,0 +1,88 @@ +. + * --------------------------------------------------------------------- + * + * @copyright Copyright © 2011 - 2018 Teclib' + * @license http://www.gnu.org/licenses/gpl.txt GPLv3+ + * @link https://github.com/pluginsGLPI/formcreator/ + * @link https://pluginsglpi.github.io/formcreator/ + * @link http://plugins.glpi-project.org/#/plugin/formcreator + * --------------------------------------------------------------------- + */ +namespace tests\units; +use GlpiPlugin\Formcreator\Tests\CommonTestCase; + +class PluginFormcreatorForm_Profile extends CommonTestCase { + public function providerGetTypeName() { + return [ + [ + 0, + 'Targets' + ], + [ + 1, + 'Target' + ], + [ + 2, + 'Targets' + ], + ]; + } + + /** + * @dataProvider providerGetTypeName + * + * @param integer $nb + * @param string $expected + * @return void + */ + public function testGetTypeName($nb, $expected) { + $instance = new $this->newTestedInstance(); + $output = $instance->getTypeName($nb); + $this->string($output)->isEqualTo($expected); + } + + public function testGetTabNameForItem() { + $instance = $this->newTestedInstance(); + $item = new \Computer(); + $output = $instance->getTabNameForItem($item); + + $this->string($output)->isEqualTo('Targets'); + } + + public function testPrepareInputForAdd() { + $instance = $this->newTestedInstance(); + $output = $instance->prepareInputForAdd([ + 'uuid' => '0000', + ]); + + $this->array($output)->HasKey('uuid'); + $this->string($output['uuid'])->isEqualTo('0000'); + + $output = $instance->prepareInputForAdd([]); + + $this->array($output)->HasKey('uuid'); + $this->string($output['uuid']); + } +} diff --git a/tests/suite-unit/PluginFormcreatorForm_Validator.php b/tests/suite-unit/PluginFormcreatorForm_Validator.php new file mode 100644 index 000000000..78739930e --- /dev/null +++ b/tests/suite-unit/PluginFormcreatorForm_Validator.php @@ -0,0 +1,50 @@ +. + * --------------------------------------------------------------------- + * + * @copyright Copyright © 2011 - 2018 Teclib' + * @license http://www.gnu.org/licenses/gpl.txt GPLv3+ + * @link https://github.com/pluginsGLPI/formcreator/ + * @link https://pluginsglpi.github.io/formcreator/ + * @link http://plugins.glpi-project.org/#/plugin/formcreator + * --------------------------------------------------------------------- + */ +namespace tests\units; +use GlpiPlugin\Formcreator\Tests\CommonTestCase; + +class PluginFormcreatorForm_Validator extends CommonTestCase { + public function testPrepareInputForAdd() { + $instance = $this->newTestedInstance(); + $output = $instance->prepareInputForAdd([ + 'uuid' => '0000', + ]); + + $this->array($output)->HasKey('uuid'); + $this->string($output['uuid'])->isEqualTo('0000'); + + $output = $instance->prepareInputForAdd([]); + + $this->array($output)->HasKey('uuid'); + $this->string($output['uuid']); + } +} From 6c05c9013f32318d6830c079ebcb0eed3d78429f Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Fri, 21 Dec 2018 16:39:32 +0100 Subject: [PATCH 24/33] test(formlist): add tests Signed-off-by: Thierry Bugier --- .../suite-unit/PluginFormcreatorFormList.php | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 tests/suite-unit/PluginFormcreatorFormList.php diff --git a/tests/suite-unit/PluginFormcreatorFormList.php b/tests/suite-unit/PluginFormcreatorFormList.php new file mode 100644 index 000000000..58cc0caf8 --- /dev/null +++ b/tests/suite-unit/PluginFormcreatorFormList.php @@ -0,0 +1,65 @@ +. + * --------------------------------------------------------------------- + * + * @copyright Copyright © 2011 - 2018 Teclib' + * @license http://www.gnu.org/licenses/gpl.txt GPLv3+ + * @link https://github.com/pluginsGLPI/formcreator/ + * @link https://pluginsglpi.github.io/formcreator/ + * @link http://plugins.glpi-project.org/#/plugin/formcreator + * --------------------------------------------------------------------- + */ +namespace tests\units; +use GlpiPlugin\Formcreator\Tests\CommonTestCase; + +class PluginFormcreatorFormList extends CommonTestCase { + public function providerGetTypeName() { + return [ + [ + 0, + 'Forms' + ], + [ + 1, + 'Form' + ], + [ + 2, + 'Forms' + ], + ]; + } + + /** + * @dataProvider providerGetTypeName + * + * @param integer $nb + * @param string $expected + * @return void + */ + public function testGetTypeName($nb, $expected) { + $instance = new $this->newTestedInstance(); + $output = $instance->getTypeName($nb); + $this->string($output)->isEqualTo($expected); + } +} From 50fa81151f6cfd7c2ecf53794208d1a2483e197d Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Mon, 31 Dec 2018 09:56:19 +0100 Subject: [PATCH 25/33] test(question_condition): fix test Signed-off-by: Thierry Bugier --- tests/suite-unit/PluginFormcreatorQuestion_Condition.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/suite-unit/PluginFormcreatorQuestion_Condition.php b/tests/suite-unit/PluginFormcreatorQuestion_Condition.php index 18d9f2fc0..25b1dc8df 100644 --- a/tests/suite-unit/PluginFormcreatorQuestion_Condition.php +++ b/tests/suite-unit/PluginFormcreatorQuestion_Condition.php @@ -58,7 +58,7 @@ public function testGetConditionsFromQuestion() { $this->boolean($questionCondition->isNewItem())->isFalse(); // Check that all conditions are retrieved - $output = $question->getConditionsFromQuestion(); + $output = $questionCondition->getConditionsFromQuestion($question->getID()); $this->array($output)->hasSize(2); } } From 09c010114808e64c57e856c46edcc5f253a80074 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Wed, 2 Jan 2019 17:06:06 +0100 Subject: [PATCH 26/33] fix(install): update relation when upgrading to 2.7.0 the plugin needs to update relation between form answers and changes Signed-off-by: Thierry Bugier --- install/upgrade_to_2.7.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/install/upgrade_to_2.7.php b/install/upgrade_to_2.7.php index e58e11ac3..d8d3a9dc2 100644 --- a/install/upgrade_to_2.7.php +++ b/install/upgrade_to_2.7.php @@ -52,6 +52,13 @@ public function upgrade(Migration $migration) { 'itemtype' => 'PluginFormcreatorForm_Answer' ] ); + $DB->update( + 'glpi_changes_items', [ + 'itemtype' => 'PluginFormcreatorFormAnswer', + ], [ + 'itemtype' => 'PluginFormcreatorForm_Answer' + ] + ); $DB->update( 'glpi_notifications', [ 'itemtype' => 'PluginFormcreatorFormAnswer', From 1e652766d82d8d50095647cddf9dca16a81b3add Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Mon, 31 Dec 2018 14:49:21 +0100 Subject: [PATCH 27/33] fix(formanswer):use of obsolete static property Signed-off-by: Thierry Bugier --- hook.php | 4 +++- inc/formanswer.class.php | 6 ++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/hook.php b/hook.php index d1279653a..2cb54488e 100644 --- a/hook.php +++ b/hook.php @@ -130,7 +130,9 @@ function plugin_formcreator_addDefaultWhere($itemtype) { case PluginFormcreatorFormAnswer::class: if (isset($_SESSION['formcreator']['form_search_answers']) && $_SESSION['formcreator']['form_search_answers']) { - $condition = "`$table`.`".PluginFormcreatorFormAnswer::$items_id."` = ". + // Context is displaying the answers for a given form + $formFk = PluginFormcreatorForm::getForeignKeyField(); + $condition = "`$table`.`$formFk` = ". $_SESSION['formcreator']['form_search_answers']; } else { $condition = plugin_formcreator_getCondition($itemtype); diff --git a/inc/formanswer.class.php b/inc/formanswer.class.php index a10cfe4ec..700f069cb 100644 --- a/inc/formanswer.class.php +++ b/inc/formanswer.class.php @@ -41,9 +41,6 @@ class PluginFormcreatorFormAnswer extends CommonDBTM public $usenotepad = true; public $usenotepadrights = true; - static public $itemtype = "PluginFormcreatorForm"; - static public $items_id = "plugin_formcreator_forms_id"; - const SOPTION_ANSWER = 900000; /** @@ -354,10 +351,11 @@ public function defineTabs($options = []) { public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { if ($item instanceof PluginFormcreatorForm) { $dbUtils = new DbUtils(); + $formFk = PluginFormcreatorForm::getForeignKeyField(); $number = $dbUtils->countElementsInTableForMyEntities( static::getTable(), [ - self::$items_id => $item->getID() + $formFk => $item->getID() ] ); return self::createTabEntry(self::getTypeName($number), $number); From 2478b2c00b84634a796a92b374d611cba37ae64c Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Mon, 31 Dec 2018 15:32:14 +0100 Subject: [PATCH 28/33] fix(formanswer): empty list of answers in some conditions the search criterias are set when displaying answers of a form Signed-off-by: Thierry Bugier --- inc/formanswer.class.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/inc/formanswer.class.php b/inc/formanswer.class.php index 700f069cb..a35eaa401 100644 --- a/inc/formanswer.class.php +++ b/inc/formanswer.class.php @@ -355,7 +355,8 @@ public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { $number = $dbUtils->countElementsInTableForMyEntities( static::getTable(), [ - $formFk => $item->getID() + $formFk => $item->getID(), + 'is_deleted' => 0, ] ); return self::createTabEntry(self::getTypeName($number), $number); @@ -383,7 +384,7 @@ static function showForForm(PluginFormcreatorForm $form, $params = []) { $forcedisplay = array_combine($sopt_keys, $sopt_keys); // do search - $params = Search::manageParams(__CLASS__, $params); + $params = Search::manageParams(__CLASS__, $params, false); $data = Search::prepareDatasForSearch(__CLASS__, $params, $forcedisplay); Search::constructSQL($data); Search::constructData($data); From 9bda871ae957c05d3e242ea26afc0482eb669fc2 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Mon, 7 Jan 2019 13:52:21 +0100 Subject: [PATCH 29/33] fix(issue): fix filtered searches of issues Signed-off-by: Thierry Bugier --- inc/issue.class.php | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/inc/issue.class.php b/inc/issue.class.php index 9c8888bc3..eab08084f 100644 --- a/inc/issue.class.php +++ b/inc/issue.class.php @@ -576,22 +576,31 @@ static function getAllStatusArray($withmetaforsearch = false) { } static function getIncomingCriteria() { + $currentUser = Session::getLoginUserID(); return ['criteria' => [['field' => 4, 'searchtype' => 'equals', 'value' => 'process', - 'value' => 'notold']], + 'value' => 'notold'], + ['field' => 8, + 'searchtype' => 'equals', + 'value' => $currentUser]], 'reset' => 'reset']; } static function getWaitingCriteria() { + $currentUser = Session::getLoginUserID(); return ['criteria' => [['field' => 4, 'searchtype' => 'equals', 'value' => 'process', - 'value' => Ticket::WAITING]], + 'value' => Ticket::WAITING], + ['field' => 8, + 'searchtype' => 'equals', + 'value' => $currentUser]], 'reset' => 'reset']; } static function getValidateCriteria() { + $currentUser = Session::getLoginUserID(); return ['criteria' => [['field' => 4, 'searchtype' => 'equals', 'value' => 'process', @@ -600,7 +609,7 @@ static function getValidateCriteria() { ['field' => 9, 'searchtype' => 'equals', 'value' => 'process', - 'value' => $_SESSION['glpiID'], + 'value' => $currentUser, 'link' => 'AND'], ['field' => 4, 'searchtype' => 'equals', @@ -610,15 +619,19 @@ static function getValidateCriteria() { ['field' => 11, 'searchtype' => 'equals', 'value' => 'process', - 'value' => $_SESSION['glpiID'], + 'value' => $currentUser, 'link' => 'AND']], 'reset' => 'reset']; } static function getSolvedCriteria() { + $currentUser = Session::getLoginUserID(); return ['criteria' => [['field' => 4, 'searchtype' => 'equals', - 'value' => 'old']], + 'value' => 'old'], + ['field' => 8, + 'searchtype' => 'equals', + 'value' => $currentUser]], 'reset' => 'reset']; } From 04f169507213a877fb35ec1f39dd9a6ea1064067 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Tue, 8 Jan 2019 14:55:36 +0100 Subject: [PATCH 30/33] fix(descriptionfield): show / hide did not work Signed-off-by: Thierry Bugier --- inc/fields/descriptionfield.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inc/fields/descriptionfield.class.php b/inc/fields/descriptionfield.class.php index 35b82c049..aabc03959 100644 --- a/inc/fields/descriptionfield.class.php +++ b/inc/fields/descriptionfield.class.php @@ -38,7 +38,7 @@ public function isPrerequisites() { } public function show($canEdit = true) { - echo '
    '; + echo '
    '; echo nl2br(html_entity_decode($this->fields['description'])); echo '
    ' . PHP_EOL; } From db8d4d25022dd96d3f0a429234cd9490f1ff5ed2 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Tue, 15 Jan 2019 18:24:53 +0100 Subject: [PATCH 31/33] build: bump version Signed-off-by: Thierry Bugier --- plugin.xml | 5 +++++ setup.php | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/plugin.xml b/plugin.xml index 938427717..9d52a5494 100644 --- a/plugin.xml +++ b/plugin.xml @@ -244,6 +244,11 @@ Features 9.3 9.4 + + 2.7.0-beta.2 + 9.3 + 9.4 + ca_ES diff --git a/setup.php b/setup.php index 5c6997709..edf538a9a 100644 --- a/setup.php +++ b/setup.php @@ -33,11 +33,11 @@ global $CFG_GLPI; // Version of the plugin -define('PLUGIN_FORMCREATOR_VERSION', '2.7.0-beta.1'); +define('PLUGIN_FORMCREATOR_VERSION', '2.7.0-beta.2'); // Schema version of this version define('PLUGIN_FORMCREATOR_SCHEMA_VERSION', '2.7'); // is or is not an official release of the plugin -define('PLUGIN_FORMCREATOR_IS_OFFICIAL_RELEASE', false); +define('PLUGIN_FORMCREATOR_IS_OFFICIAL_RELEASE', true); // Minimal GLPI version, inclusive define ('PLUGIN_FORMCREATOR_GLPI_MIN_VERSION', '9.3.0'); From 8b1186b56d398f18ef85e1c3d3f1dfb72956b49b Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Wed, 16 Jan 2019 16:11:10 +0100 Subject: [PATCH 32/33] docs: bump version in package.json --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 0e1c75d47..a94a287dd 100644 --- a/package.json +++ b/package.json @@ -11,5 +11,5 @@ } }, "dependencies": [], - "version": "2.7.0-beta.1" + "version": "2.7.0-beta.2" } From 1e3af941e7228650bfc19a9a895e0a46a3e6fd96 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Wed, 16 Jan 2019 16:11:10 +0100 Subject: [PATCH 33/33] docs(changelog): update changelog Signed-off-by: Thierry Bugier --- CHANGELOG.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d96cdc58..41684719d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,27 @@ +
    +# [2.7.0-beta.2](https://github.com/pluginsglpi/formcreator/compare/v2.7.0-beta.1...v2.7.0-beta.2) (2019-01-16) + + +### Bug Fixes + +* **descriptionfield:** show / hide did not work ([04f1695](https://github.com/pluginsglpi/formcreator/commit/04f1695)) +* **form:** access rights checking ([e05e20b](https://github.com/pluginsglpi/formcreator/commit/e05e20b)) +* **formanswer:** empty list of answers ([2478b2c](https://github.com/pluginsglpi/formcreator/commit/2478b2c)) +* **formanswer:** missing right check ([bdac689](https://github.com/pluginsglpi/formcreator/commit/bdac689)) +* **install:** create tables before filling them ([#1234](https://github.com/pluginsglpi/formcreator/issues/1234)) ([c08e299](https://github.com/pluginsglpi/formcreator/commit/c08e299)) +* **install:** update relation ([09c0101](https://github.com/pluginsglpi/formcreator/commit/09c0101)) +* **issue:** fix filtered searches of issues ([9bda871](https://github.com/pluginsglpi/formcreator/commit/9bda871)) +* **targetTicket:** generation of ticket ([8355480](https://github.com/pluginsglpi/formcreator/commit/8355480)) +* **textfield:** abuse escaping ([167c43f](https://github.com/pluginsglpi/formcreator/commit/167c43f)) +* **urgencyfield:** default value ([1849e61](https://github.com/pluginsglpi/formcreator/commit/1849e61)) + + +### Features + +* **targetticket:** compatibility with GLPI 9.4 ([6afe5fe](https://github.com/pluginsglpi/formcreator/commit/6afe5fe)) + + + # [2.7.0-beta.1](https://github.com/pluginsglpi/formcreator/compare/v2.6.4...v2.7.0-beta.1) (2018-12-05)