diff --git a/ajax/asynchronousdatas.php b/ajax/asynchronousdatas.php index 5f1424c..487b8a0 100644 --- a/ajax/asynchronousdatas.php +++ b/ajax/asynchronousdatas.php @@ -12,24 +12,14 @@ if (!defined('GLPI_ROOT')) { die("Can not access directly to this file"); } -//include_once dirname(__FILE__)."/../inc/asynchronousdata.class.php" ; include_once dirname(__FILE__)."/../inc/crontaskaction.class.php" ; if( isset($_SERVER['REQUEST_METHOD']) ) { switch($_SERVER['REQUEST_METHOD']) { - //case 'OPTIONS' : - // header("Access-Control-Allow-Origin: *") ; - // header("Access-Control-Allow-Methods: POST"); - // header("Access-Control-Allow-Headers: Content-Type"); - // break ; case 'POST' : - //header("Access-Control-Allow-Origin: *") ; - //header("Content-Type: application/json; charset=UTF-8"); - $request_body = file_get_contents('php://input'); $datas = json_decode($request_body, true); -// $asyncdata = new PluginProcessmakerAsynchronousdata ; $asyncdata = new PluginProcessmakerCrontaskaction ; if( isset($datas['id']) && $asyncdata->getFromDB( $datas['id'] ) && $asyncdata->fields['state'] == PluginProcessmakerCrontaskaction::WAITING_DATAS ) { $initialdatas = json_decode($asyncdata->fields['postdatas'], true); diff --git a/ajax/dropdownProcesses.php b/ajax/dropdownProcesses.php index 9877afa..84636b6 100644 --- a/ajax/dropdownProcesses.php +++ b/ajax/dropdownProcesses.php @@ -6,17 +6,16 @@ // ---------------------------------------------------------------------- // Direct access to file -if (strpos($_SERVER['PHP_SELF'],"dropdownProcesses.php")) { - include ("../../../inc/includes.php"); - header("Content-Type: text/html; charset=UTF-8"); - Html::header_nocache(); +if (strpos($_SERVER['PHP_SELF'], "dropdownProcesses.php")) { + include ("../../../inc/includes.php"); + header("Content-Type: text/html; charset=UTF-8"); + Html::header_nocache(); } if (!defined('GLPI_ROOT')) { - die("Can not acces directly to this file"); + die("Can not acces directly to this file"); } -//include_once dirname(__FILE__)."/../inc/process.class.php" ; Session::checkLoginUser(); @@ -29,7 +28,7 @@ if (isset($_REQUEST["entity_restrict"]) // Security if (!($item = getItemForItemtype($_REQUEST['itemtype']))) { - exit(); + exit(); } $one_item = -1; @@ -40,36 +39,36 @@ if (isset($_POST['_one_id'])) { $count = 0; if (!isset($_REQUEST['emptylabel']) || ($_REQUEST['emptylabel'] == '')) { - $_REQUEST['emptylabel'] = Dropdown::EMPTY_VALUE; + $_REQUEST['emptylabel'] = Dropdown::EMPTY_VALUE; } $search=""; if (!empty($_REQUEST['searchText'])) { - $search = Search::makeTextSearch($_REQUEST['searchText']); + $search = Search::makeTextSearch($_REQUEST['searchText']); } $processes = array(); // Empty search text : display first if (empty($_REQUEST['searchText'])) { - if ($_REQUEST['display_emptychoice']) { - if (($one_item < 0) || ($one_item == 0)) { - array_push($processes, array('id' => 0, - 'text' => $_REQUEST['emptylabel'])); - } - } + if ($_REQUEST['display_emptychoice']) { + if (($one_item < 0) || ($one_item == 0)) { + array_push($processes, array('id' => 0, + 'text' => $_REQUEST['emptylabel'])); + } + } } $result = PluginProcessmakerProcess::getSqlSearchResult(false, $search); if ($DB->numrows($result)) { - while ($data=$DB->fetch_array($result)) { - if( in_array( $_REQUEST["entity_restrict"], PluginProcessmakerProcess::getEntitiesForProfileByProcess( $data["id"], $_SESSION['glpiactiveprofile']['id'], true) ) ) { - array_push( $processes, array( 'id' => $data["id"], - 'text' => $data["name"] )); - $count++; - } - } + while ($data=$DB->fetch_array($result)) { + if (in_array( $_REQUEST["entity_restrict"], PluginProcessmakerProcess::getEntitiesForProfileByProcess( $data["id"], $_SESSION['glpiactiveprofile']['id'], true) )) { + array_push( $processes, array( 'id' => $data["id"], + 'text' => $data["name"] )); + $count++; + } + } } $ret['results'] = $processes; diff --git a/ajax/dropdownUsers.php b/ajax/dropdownUsers.php index aafabf7..4967f43 100644 --- a/ajax/dropdownUsers.php +++ b/ajax/dropdownUsers.php @@ -9,7 +9,7 @@ // ---------------------------------------------------------------------- // Direct access to file -if (strpos($_SERVER['PHP_SELF'],"dropdownUsers.php")) { +if (strpos($_SERVER['PHP_SELF'], "dropdownUsers.php")) { include ("../../../inc/includes.php"); header("Content-Type: text/html; charset=UTF-8"); Html::header_nocache(); @@ -24,7 +24,7 @@ if (!defined('GLPI_ROOT')) { Session::checkLoginUser(); -$PM_DB = new PluginProcessmakerDB ; +$PM_DB = new PluginProcessmakerDB; if (!isset($_REQUEST['right'])) { $_REQUEST['right'] = "all"; @@ -35,13 +35,6 @@ if (!isset($_REQUEST['all'])) { $_REQUEST['all'] = 0; } - - - - - - - $used = array(); if (isset($_REQUEST['used'])) { @@ -64,9 +57,6 @@ if (!isset($_REQUEST['page'])) { if ($one_item < 0) { $start = ($_REQUEST['page']-1)*$_REQUEST['page_limit']; - //$result = User::getSqlSearchResult(false, $_REQUEST['right'], $_REQUEST["entity_restrict"], - // $_REQUEST['value'], $used, $_REQUEST['searchText'], $start, - // $_REQUEST['page_limit']); $LIMIT = "LIMIT $start,".$_REQUEST['page_limit']; $result = PluginProcessmakerUser::getSqlSearchResult( $_REQUEST['specific_tags']['pmTaskId'], false, $_REQUEST['right'], $_REQUEST["entity_restrict"], $_REQUEST['value'], $used, $_REQUEST['searchText'], $LIMIT); @@ -94,9 +84,6 @@ if (!function_exists('dpuser_cmp')) { } } -// Sort non case sensitive -//uasort($users, 'dpuser_cmp'); - $datas = array(); // Display first if empty search diff --git a/ajax/task_users.php b/ajax/task_users.php index bb8d2f0..2a1ade8 100644 --- a/ajax/task_users.php +++ b/ajax/task_users.php @@ -6,45 +6,41 @@ // ---------------------------------------------------------------------- // Direct access to file -if (strpos($_SERVER['PHP_SELF'],"task_users.php")) { - include ("../../../inc/includes.php"); - header("Content-Type: text/html; charset=UTF-8"); - Html::header_nocache(); +if (strpos($_SERVER['PHP_SELF'], "task_users.php")) { + include ("../../../inc/includes.php"); + header("Content-Type: text/html; charset=UTF-8"); + Html::header_nocache(); } if (!defined('GLPI_ROOT')) { - die("Can not acces directly to this file"); + die("Can not acces directly to this file"); } -//include_once dirname(__FILE__)."/../inc/processmaker.class.php" ; -//include_once dirname(__FILE__)."/../inc/users.class.php" ; - Session::checkLoginUser(); -$PM_DB = new PluginProcessmakerDB ; +$PM_DB = new PluginProcessmakerDB; $rand = rand(); echo "
"; - echo $LANG['processmaker']['item']['reassigncase']." "; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; +echo $LANG['processmaker']['item']['reassigncase']." "; +echo ""; +echo ""; +echo ""; +echo ""; +echo ""; +echo ""; +echo ""; +echo ""; - PluginProcessmakerUser::dropdown( array('name' => 'users_id_recipient', - 'value' => PluginProcessmakerUser::getGLPIUserId( $_REQUEST['userId'] ), - 'entity' => 0, //$item->fields["entities_id"], // not used, as any user can be assigned to any tasks - 'entity_sons' => false, // not used, as any user can be assigned to any tasks - 'right' => 'all', - 'rand' => $rand, - 'width' => '', - 'specific_tags' => array('pmTaskId' => $_REQUEST['taskId']))); - echo "  "; - echo ""; - Html::closeForm(true); -//echo "
"; +PluginProcessmakerUser::dropdown( array('name' => 'users_id_recipient', + 'value' => PluginProcessmakerUser::getGLPIUserId( $_REQUEST['userId'] ), + 'entity' => 0, //$item->fields["entities_id"], // not used, as any user can be assigned to any tasks + 'entity_sons' => false, // not used, as any user can be assigned to any tasks + 'right' => 'all', + 'rand' => $rand, + 'width' => '', + 'specific_tags' => array('pmTaskId' => $_REQUEST['taskId']))); +echo "  "; +echo ""; +Html::closeForm(true); diff --git a/config/db_updates.txt b/config/db_updates.txt deleted file mode 100644 index 6d4fdf2..0000000 --- a/config/db_updates.txt +++ /dev/null @@ -1,51 +0,0 @@ -ALTER TABLE `glpi_plugin_processmaker_processes` - ADD COLUMN `is_helpdeskvisible` TINYINT(1) NOT NULL DEFAULT '1' AFTER `trigger_guid`; - -ALTER TABLE `glpi_plugin_processmaker_processes` - ADD COLUMN `comment` TEXT NULL AFTER `is_helpdeskvisible`; - -ALTER TABLE `glpi_plugin_processmaker_cases` - ADD COLUMN `processes_id` VARCHAR(32) NULL AFTER `case_status`; - -ALTER TABLE `glpi_plugin_processmaker_processes` - ADD COLUMN `is_active` TINYINT(1) NOT NULL DEFAULT '0' AFTER `is_helpdeskvisible`, - CHANGE COLUMN `comment` `comment` TEXT NULL AFTER `is_active`, - ADD COLUMN `date_mod` DATETIME NULL DEFAULT NULL AFTER `comment`, - DROP COLUMN `trigger_guid`; - -ALTER TABLE `glpi_plugin_processmaker_configs` - ADD COLUMN `taskcategories_id` INT(11) NULL AFTER `comment`; - -ALTER TABLE `glpi_plugin_processmaker_processes` - ADD COLUMN `taskcategories_id` INT(11) NULL AFTER `comment`; - -CREATE TABLE `glpi_plugin_processmaker_taskcategories` ( - `id` INT(11) NOT NULL, - `pm_task_guid` VARCHAR(32) NOT NULL, - `processes_id` INT(11) NOT NULL - ) - COLLATE='utf8_general_ci' - ENGINE=InnoDB - ; - -ALTER TABLE `glpi_plugin_processmaker_profiles` - ADD COLUMN `profiles_id` INT(11) NOT NULL DEFAULT '0' COMMENT 'RELATION to glpi_profiles (id)' AFTER `id`, - DROP COLUMN `name`, - DROP INDEX `name`, - ADD INDEX `profiles_id` (`profiles_id`); -ALTER TABLE `glpi_plugin_processmaker_profiles` - CHANGE COLUMN `process` `process_config` CHAR(1) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci' AFTER `profiles_id`; - - - -ALTER TABLE `glpi_plugin_processmaker_processes` - ADD COLUMN `hide_case_num_title` TINYINT(1) NOT NULL DEFAULT '0' AFTER `is_active`; - -ALTER TABLE `glpi_plugin_processmaker_processes` - ADD COLUMN `insert_task_comment` TINYINT(1) NOT NULL DEFAULT '0' AFTER `hide_case_num_title`; - -ALTER TABLE `glpi_plugin_processmaker_configs` - ADD COLUMN `users_id` INT(11) NULL DEFAULT NULL AFTER `taskcategories_id`; - -ALTER TABLE `glpi_plugin_processmaker_configs` - ADD COLUMN `pm_group_guid` VARCHAR(32) NULL AFTER `users_id`; diff --git a/config/pm_db_config.sql b/config/pm_db_config.sql deleted file mode 100644 index e92158a..0000000 --- a/config/pm_db_config.sql +++ /dev/null @@ -1,175 +0,0 @@ - -USE wf_workflow; - -DROP TRIGGER IF EXISTS `GLPI_APPLICATION_DELETE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELAY_INSERT` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELAY_UPDATE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_INSERT` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_UPDATE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_DELETE` ; - - -DELIMITER // - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APPLICATION_DELETE` AFTER DELETE ON `application` FOR EACH ROW BEGIN - DECLARE loc_Ticket_id INT(11) ; - SELECT ticket_id INTO loc_Ticket_id FROM glpi.glpi_plugin_processmaker_ticketcase WHERE case_id=OLD.APP_UID; - IF loc_Ticket_id IS NOT NULL THEN - DELETE FROM glpi.glpi_plugin_processmaker_ticketcase WHERE case_id=OLD.APP_UID ; - END IF; -END // - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELAY_INSERT` AFTER INSERT ON `app_delay` FOR EACH ROW BEGIN - DECLARE loc_task_cat_id, loc_Ticket_id, loc_Found_Pos, loc_glpi_users_id, loc_Count_Ticket INT(11) ; - DECLARE APP_TITLE, APP_PRO_TITLE, APP_TAS_TITLE VARCHAR(255); - DECLARE loc_pm_user_id VARCHAR(32) ; - - IF NEW.APP_TYPE = 'PAUSE' THEN - SELECT ticket_id INTO loc_Ticket_id FROM glpi.glpi_plugin_processmaker_ticketcase WHERE case_id=NEW.APP_UID; - IF loc_Ticket_id IS NOT NULL THEN - - SELECT CONTENT.CON_VALUE into APP_TITLE FROM CONTENT WHERE NEW.APP_UID=CON_ID AND CON_CATEGORY='APP_TITLE' and CON_LANG = 'en' LIMIT 1; - IF APP_TITLE IS NULL THEN - SET APP_TITLE = ''; - END IF; - SELECT CONTENT.CON_VALUE into APP_PRO_TITLE FROM CONTENT WHERE NEW.PRO_UID=CON_ID AND CON_CATEGORY='PRO_TITLE' and CON_LANG = 'en' LIMIT 1; - SET APP_TAS_TITLE = 'Case is paused'; - - SELECT glpi_users_id INTO loc_glpi_users_id FROM glpi.glpi_plugin_processmaker_users WHERE pm_users_id=NEW.APP_DELEGATION_USER LIMIT 1; - - SELECT id INTO loc_task_cat_id FROM glpi.glpi_taskcategories WHERE name=APP_PRO_TITLE; - IF loc_task_cat_id IS NULL THEN - SET loc_task_cat_id=0 ; - END IF ; - - INSERT INTO glpi.glpi_tickettasks - ( `tickets_id`, `taskcategories_id`, `date`, `users_id`, `content`, `is_private`, `actiontime`, `begin`, `end`, `state`, `users_id_tech`) - VALUES ( loc_Ticket_id, - loc_task_cat_id, - Now(), - 1, - CONCAT( 'Bound to process: ', APP_PRO_TITLE, ',
case title: ', APP_TITLE, ',
task: ', APP_TAS_TITLE,'.
Go to Case tab to manage!' ), - 0, - 0, - NEW.APP_ENABLE_ACTION_DATE, - NEW.APP_DISABLE_ACTION_DATE, - 1, - loc_glpi_users_id); - - INSERT INTO glpi.glpi_plugin_processmaker_tasks (`tickettasks_id`, `case_id`, `del_index`) VALUES (LAST_INSERT_ID(), NEW.APP_DELAY_UID, 0 ); - - END IF; - END IF; -END // - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELAY_UPDATE` AFTER UPDATE ON `app_delay` FOR EACH ROW BEGIN - - DECLARE loc_tickettasks_id, loc_Count_Task INT(11) ; - DECLARE loc_glpi_users_id INT(11) ; - - SELECT glpi_pm_tasks.tickettasks_id INTO loc_tickettasks_id FROM glpi.glpi_plugin_processmaker_tasks as glpi_pm_tasks WHERE glpi_pm_tasks.case_id=NEW.APP_DELAY_UID ; - IF loc_tickettasks_id IS NOT NULL THEN - SELECT glpi_users_id INTO loc_glpi_users_id FROM glpi.glpi_plugin_processmaker_users WHERE pm_users_id=NEW.APP_DISABLE_ACTION_USER LIMIT 1; - - IF NEW.APP_DISABLE_ACTION_DATE IS NOT NULL THEN - UPDATE glpi.glpi_tickettasks - SET state=2, - `end`=NEW.APP_DISABLE_ACTION_DATE - WHERE id=loc_tickettasks_id ; - END IF ; - - END IF; -END // - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELEGATION_DELETE` AFTER DELETE ON `app_delegation` FOR EACH ROW BEGIN - - DECLARE loc_Ticket_id, loc_tickettask_id INT(11) ; - - SELECT glpi_pm_tcase.ticket_id INTO loc_Ticket_id FROM glpi.glpi_plugin_processmaker_ticketcase as glpi_pm_tcase WHERE glpi_pm_tcase.case_id=OLD.APP_UID; - IF loc_Ticket_id IS NOT NULL THEN - SELECT glpi_pm_tasks.tickettasks_id INTO loc_tickettask_id FROM glpi.glpi_plugin_processmaker_tasks as glpi_pm_tasks WHERE glpi_pm_tasks.case_id=OLD.APP_UID AND glpi_pm_tasks.del_index=OLD.DEL_INDEX LIMIT 1; - DELETE FROM glpi.glpi_plugin_processmaker_tasks WHERE tickettasks_id = loc_tickettask_id ; - DELETE FROM glpi.glpi_tickettasks WHERE id = loc_tickettask_id ; - END IF; - -END // - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELEGATION_INSERT` AFTER INSERT ON `app_delegation` FOR EACH ROW BEGIN - DECLARE loc_task_cat_id, loc_Ticket_id, loc_Found_Pos, loc_glpi_users_id, loc_Count_Ticket INT(11) ; - DECLARE APP_TITLE, APP_PRO_TITLE, APP_TAS_TITLE VARCHAR(255); - - SELECT ticket_id INTO loc_Ticket_id FROM glpi.glpi_plugin_processmaker_ticketcase WHERE case_id=NEW.APP_UID; - - IF loc_Ticket_id IS NOT NULL THEN - - SELECT CONTENT.CON_VALUE into APP_TITLE FROM CONTENT WHERE NEW.APP_UID=CON_ID AND CON_CATEGORY='APP_TITLE' and CON_LANG = 'en' LIMIT 1; - IF APP_TITLE IS NULL THEN - SET APP_TITLE = ''; - END IF; - SELECT CONTENT.CON_VALUE into APP_PRO_TITLE FROM CONTENT WHERE NEW.PRO_UID=CON_ID AND CON_CATEGORY='PRO_TITLE' and CON_LANG = 'en' LIMIT 1; - SELECT CONTENT.CON_VALUE into APP_TAS_TITLE FROM CONTENT WHERE NEW.TAS_UID=CON_ID AND CON_CATEGORY='TAS_TITLE' and CON_LANG = 'en' LIMIT 1; - - - SELECT glpi_users_id INTO loc_glpi_users_id FROM glpi.glpi_plugin_processmaker_users WHERE pm_users_id=NEW.USR_UID LIMIT 1; - IF loc_glpi_users_id IS NULL THEN - /* we must find a user linked to a group */ /* task is NEW.TAS_UID */ - select glpi.glpi_users.id INTO loc_glpi_users_id from task_user - join content on content.CON_ID=task_user.USR_UID and content.CON_CATEGORY='GRP_TITLE' - join glpi.glpi_users on glpi.glpi_users.name=content.CON_VALUE COLLATE utf8_unicode_ci - where tas_uid=NEW.TAS_UID and tu_relation=2 ; - END IF; - - SELECT id INTO loc_task_cat_id FROM glpi.glpi_taskcategories WHERE name=APP_PRO_TITLE; - IF loc_task_cat_id IS NULL THEN - SET loc_task_cat_id=0 ; - END IF ; - - INSERT INTO glpi.glpi_tickettasks - ( `tickets_id`, `taskcategories_id`, `date`, `users_id`, `content`, `is_private`, `actiontime`, `begin`, `end`, `state`, `users_id_tech`) - VALUES ( loc_Ticket_id, - loc_task_cat_id, - Now(), - 1, - CONCAT( 'Bound to process: ', APP_PRO_TITLE, ',
case title: ', APP_TITLE, ',
task: ', APP_TAS_TITLE,'.
Go to Case tab to manage!' ), - 0, - 0, - NEW.DEL_DELEGATE_DATE, - NEW.DEL_TASK_DUE_DATE, - 1, - loc_glpi_users_id); - - INSERT INTO glpi.glpi_plugin_processmaker_tasks (`tickettasks_id`, `case_id`, `del_index`) VALUES (LAST_INSERT_ID(), NEW.APP_UID, NEW.DEL_INDEX ); - - END IF; -END // - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELEGATION_UPDATE` AFTER UPDATE ON `app_delegation` FOR EACH ROW BEGIN - - DECLARE loc_tickettasks_id, loc_Count_Task INT(11) ; - DECLARE loc_glpi_users_id INT(11) ; - - SELECT glpi_pm_tasks.tickettasks_id INTO loc_tickettasks_id FROM glpi.glpi_plugin_processmaker_tasks as glpi_pm_tasks WHERE glpi_pm_tasks.case_id=NEW.APP_UID AND glpi_pm_tasks.del_index=NEW.DEL_INDEX ; - IF loc_tickettasks_id IS NOT NULL THEN - SELECT glpi_users_id INTO loc_glpi_users_id FROM glpi.glpi_plugin_processmaker_users WHERE pm_users_id=NEW.USR_UID LIMIT 1; - - IF NEW.DEL_THREAD_STATUS = 'CLOSED' THEN - UPDATE glpi.glpi_tickettasks - SET state=2, - `begin`=NEW.DEL_DELEGATE_DATE, - `end`=NEW.DEL_FINISH_DATE - WHERE id=loc_tickettasks_id ; - ELSE - UPDATE glpi.glpi_tickettasks - SET users_id_tech=loc_glpi_users_id - WHERE id=loc_tickettasks_id ; - END IF ; - - END IF; -END // - -DELIMITER ; - diff --git a/config/pm_db_install.mysql b/config/pm_db_install.mysql deleted file mode 100644 index 23173ff..0000000 --- a/config/pm_db_install.mysql +++ /dev/null @@ -1,218 +0,0 @@ - - -DROP TRIGGER IF EXISTS `GLPI_APPLICATION_DELETE` ; -DROP TRIGGER IF EXISTS `GLPI_APPLICATION_UPDATE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELAY_INSERT` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELAY_UPDATE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_INSERT` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_UPDATE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_DELETE` ; - - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APPLICATION_DELETE` AFTER DELETE ON `application` FOR EACH ROW BEGIN - DECLARE loc_item_id INT(11) ; - SELECT items_id INTO loc_item_id FROM glpi.glpi_plugin_processmaker_cases WHERE case_id=OLD.APP_UID; - IF loc_item_id IS NOT NULL THEN - DELETE FROM glpi.glpi_plugin_processmaker_cases WHERE case_id=OLD.APP_UID ; - END IF; -END ; - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APPLICATION_UPDATE` AFTER UPDATE ON `application` FOR EACH ROW BEGIN - DECLARE loc_item_id INT(11) ; - SELECT items_id INTO loc_item_id FROM glpi.glpi_plugin_processmaker_cases WHERE case_id=NEW.APP_UID; - IF loc_item_id IS NOT NULL THEN - UPDATE glpi.glpi_plugin_processmaker_cases SET case_status=NEW.APP_STATUS WHERE case_id=NEW.APP_UID ; - END IF; -END ; - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELAY_INSERT` AFTER INSERT ON `app_delay` FOR EACH ROW BEGIN - DECLARE loc_task_id, loc_task_cat_id, loc_item_id, loc_Found_Pos, loc_glpi_users_id, loc_Count_item INT(11) ; - DECLARE APP_TITLE, APP_PRO_TITLE, APP_TAS_TITLE VARCHAR(255); - DECLARE loc_pm_user_id, loc_item_type VARCHAR(32) ; - DECLARE locDate DATETIME ; - - IF NEW.APP_TYPE = 'PAUSE' THEN - - SELECT items_id, itemtype INTO loc_item_id, loc_item_type FROM glpi.glpi_plugin_processmaker_cases WHERE case_id=NEW.APP_UID; - - IF loc_item_id IS NOT NULL THEN - - SELECT CONTENT.CON_VALUE into APP_TITLE FROM CONTENT WHERE NEW.APP_UID=CON_ID AND CON_CATEGORY='APP_TITLE' and CON_LANG = 'en' LIMIT 1; - IF APP_TITLE IS NULL THEN - SET APP_TITLE = ''; - END IF; - SELECT CONTENT.CON_VALUE into APP_PRO_TITLE FROM CONTENT WHERE NEW.PRO_UID=CON_ID AND CON_CATEGORY='PRO_TITLE' and CON_LANG = 'en' LIMIT 1; - SET APP_TAS_TITLE = 'Task is paused'; - - - SELECT glpi_users_id INTO loc_glpi_users_id FROM glpi.glpi_plugin_processmaker_users WHERE pm_users_id=NEW.APP_DELEGATION_USER LIMIT 1; - IF loc_glpi_users_id IS NULL THEN - SET loc_glpi_users_id = 2 ; - END IF ; - - SELECT id INTO loc_task_cat_id FROM glpi.glpi_taskcategories WHERE name=APP_PRO_TITLE; - IF loc_task_cat_id IS NULL THEN - SET loc_task_cat_id=0 ; - END IF ; - - SET locDate = Now() ; - SET @table_name = CONCAT('glpi.glpi_', loc_item_type, 'tasks') ; - SET @field_name = CONCAT( loc_item_type, 's_id' ) ; - SET @query = CONCAT( 'INSERT INTO ', @table_name, ' - ( `', @field_name, '`, `taskcategories_id`, `date`, `users_id`, `content`, `actiontime`, `begin`, `end`, `state`, `users_id_tech`) - VALUES ( ',loc_item_id,', - ',loc_task_cat_id,', - ',locDate,', - 1, - \'Bound to process: ', APP_PRO_TITLE, ',
case title: ', APP_TITLE, ',
task: ', APP_TAS_TITLE,'.
Go to Case tab to manage!', '\', - 0,', - NEW.APP_ENABLE_ACTION_DATE, ',', - NEW.APP_DISABLE_ACTION_DATE, ', - 1,', - loc_glpi_users_id,');') ; - - SET loc_task_id = LAST_INSERT_ID(); - INSERT INTO glpi.glpi_plugin_processmaker_tasks (`tickettasks_id`, `case_id`, `del_index`) VALUES (loc_task_id, NEW.APP_DELAY_UID, 0 ); - - REPLACE INTO glpi.glpi_plugin_processmaker_tasksnotifications (`date`, `task_id`, `user_id`, `tech_id`, `action`) VALUES ( locDate, loc_task_id, 1, loc_glpi_users_id, 'INSERT'); - - END IF; - END IF; -END ; - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELAY_UPDATE` AFTER UPDATE ON `app_delay` FOR EACH ROW BEGIN - - DECLARE loc_tickettasks_id, loc_Count_Task INT(11) ; - DECLARE loc_glpi_users_id INT(11) ; - - SELECT glpi_pm_tasks.tickettasks_id INTO loc_tickettasks_id FROM glpi.glpi_plugin_processmaker_tasks as glpi_pm_tasks WHERE glpi_pm_tasks.case_id=NEW.APP_DELAY_UID ; - IF loc_tickettasks_id IS NOT NULL THEN - SELECT glpi_users_id INTO loc_glpi_users_id FROM glpi.glpi_plugin_processmaker_users WHERE pm_users_id=NEW.APP_DISABLE_ACTION_USER LIMIT 1; - IF loc_glpi_users_id IS NULL THEN - SET loc_glpi_users_id = 2 ; - END IF ; - - IF NEW.APP_DISABLE_ACTION_DATE IS NOT NULL THEN - UPDATE glpi.glpi_tickettasks - SET state=2, - `end`=NEW.APP_DISABLE_ACTION_DATE - WHERE id=loc_tickettasks_id ; - END IF ; - - REPLACE INTO glpi.glpi_plugin_processmaker_tasksnotifications (`date`, `task_id`, `user_id`, `tech_id`, `action`) VALUES ( Now(), loc_tickettasks_id, 1, loc_glpi_users_id, 'UPDATE'); - - END IF; - -END ; - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELEGATION_DELETE` AFTER DELETE ON `app_delegation` FOR EACH ROW BEGIN - - DECLARE loc_Ticket_id, loc_tickettask_id INT(11) ; - - SELECT glpi_pm_tcase.ticket_id INTO loc_Ticket_id FROM glpi.glpi_plugin_processmaker_cases as glpi_pm_tcase WHERE glpi_pm_tcase.case_id=OLD.APP_UID; - IF loc_Ticket_id IS NOT NULL THEN - SELECT glpi_pm_tasks.tickettasks_id INTO loc_tickettask_id FROM glpi.glpi_plugin_processmaker_tasks as glpi_pm_tasks WHERE glpi_pm_tasks.case_id=OLD.APP_UID AND glpi_pm_tasks.del_index=OLD.DEL_INDEX LIMIT 1; - DELETE FROM glpi.glpi_plugin_processmaker_tasks WHERE tickettasks_id = loc_tickettask_id ; - DELETE FROM glpi.glpi_tickettasks WHERE id = loc_tickettask_id ; - END IF; - -END ; - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELEGATION_INSERT` AFTER INSERT ON `app_delegation` FOR EACH ROW BEGIN - DECLARE loc_task_id, loc_task_cat_id, loc_Ticket_id, loc_Found_Pos, loc_glpi_users_id, loc_Count_Ticket INT(11) ; - DECLARE APP_TITLE, APP_PRO_TITLE, APP_TAS_TITLE VARCHAR(255); - DECLARE locDate DATETIME ; - /*DECLARE loc_pm_user_id VARCHAR(32) ;*/ - - SELECT ticket_id INTO loc_Ticket_id FROM glpi.glpi_plugin_processmaker_cases WHERE case_id=NEW.APP_UID; - - IF loc_Ticket_id IS NOT NULL THEN - - SELECT CONTENT.CON_VALUE into APP_TITLE FROM CONTENT WHERE NEW.APP_UID=CON_ID AND CON_CATEGORY='APP_TITLE' and CON_LANG = 'en' LIMIT 1; - IF APP_TITLE IS NULL THEN - SET APP_TITLE = ''; - END IF; - SELECT CONTENT.CON_VALUE into APP_PRO_TITLE FROM CONTENT WHERE NEW.PRO_UID=CON_ID AND CON_CATEGORY='PRO_TITLE' and CON_LANG = 'en' LIMIT 1; - SELECT CONTENT.CON_VALUE into APP_TAS_TITLE FROM CONTENT WHERE NEW.TAS_UID=CON_ID AND CON_CATEGORY='TAS_TITLE' and CON_LANG = 'en' LIMIT 1; - - - SELECT glpi_users_id INTO loc_glpi_users_id FROM glpi.glpi_plugin_processmaker_users WHERE pm_users_id=NEW.USR_UID LIMIT 1; - IF loc_glpi_users_id IS NULL THEN - /* we must find a user linked to a group */ /* task is NEW.TAS_UID */ - select glpi.glpi_users.id INTO loc_glpi_users_id from task_user - join content on content.CON_ID=task_user.USR_UID and content.CON_CATEGORY='GRP_TITLE' and CON_LANG = 'en' - join glpi.glpi_users on glpi.glpi_users.name=content.CON_VALUE COLLATE utf8_unicode_ci - where tas_uid=NEW.TAS_UID and tu_relation=2 LIMIT 1; - IF loc_glpi_users_id IS NULL THEN - SET loc_glpi_users_id = 2 ; - END IF ; - END IF; - SELECT id INTO loc_task_cat_id FROM glpi.glpi_taskcategories WHERE name=APP_PRO_TITLE LIMIT 1; - IF loc_task_cat_id IS NULL THEN - SET loc_task_cat_id=0 ; - END IF ; - - SET locDate = Now() ; - INSERT INTO glpi.glpi_tickettasks - ( `tickets_id`, `taskcategories_id`, `date`, `users_id`, `content`, `is_private`, `actiontime`, `begin`, `end`, `state`, `users_id_tech`) - VALUES ( loc_Ticket_id, - loc_task_cat_id, - locDate, - 1, - CONCAT( 'Bound to process: ', APP_PRO_TITLE, ',
case title: ', APP_TITLE, ',
task: ', APP_TAS_TITLE,'.
Go to Case tab to manage!' ), - 0, - 0, - NEW.DEL_DELEGATE_DATE, - NEW.DEL_TASK_DUE_DATE, - 1, - loc_glpi_users_id); - - SET loc_task_id = LAST_INSERT_ID(); - INSERT INTO glpi.glpi_plugin_processmaker_tasks (`tickettasks_id`, `case_id`, `del_index`) VALUES (loc_task_id, NEW.APP_UID, NEW.DEL_INDEX ); - - REPLACE INTO glpi.glpi_plugin_processmaker_tasksnotifications (`date`, `task_id`, `user_id`, `tech_id`, `action`) VALUES ( locDate, loc_task_id, 1, loc_glpi_users_id, 'INSERT'); - - END IF; -END ; - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELEGATION_UPDATE` AFTER UPDATE ON `app_delegation` FOR EACH ROW BEGIN - - DECLARE loc_tickettasks_id, loc_Count_Task INT(11) ; - DECLARE loc_glpi_users_id INT(11) ; - - SELECT glpi_pm_tasks.tickettasks_id INTO loc_tickettasks_id FROM glpi.glpi_plugin_processmaker_tasks as glpi_pm_tasks WHERE glpi_pm_tasks.case_id=NEW.APP_UID AND glpi_pm_tasks.del_index=NEW.DEL_INDEX ; - IF loc_tickettasks_id IS NOT NULL THEN - SELECT glpi_users_id INTO loc_glpi_users_id FROM glpi.glpi_plugin_processmaker_users WHERE pm_users_id=NEW.USR_UID LIMIT 1; - IF loc_glpi_users_id IS NULL THEN - SET loc_glpi_users_id = 2 ; - END IF ; - - IF NEW.DEL_THREAD_STATUS = 'CLOSED' THEN - UPDATE glpi.glpi_tickettasks - SET state=2, - `begin`=NEW.DEL_INIT_DATE, - `end`=NEW.DEL_FINISH_DATE, - `actiontime`= IFNULL(TIMESTAMPDIFF(SECOND,NEW.DEL_INIT_DATE,NEW.DEL_FINISH_DATE),0) - WHERE id=loc_tickettasks_id ; - ELSE - UPDATE glpi.glpi_tickettasks - SET users_id_tech=loc_glpi_users_id - WHERE id=loc_tickettasks_id ; - END IF ; - - REPLACE INTO glpi.glpi_plugin_processmaker_tasksnotifications (`date`, `task_id`, `user_id`, `tech_id`, `action`) VALUES ( Now(), loc_tickettasks_id, 1, loc_glpi_users_id, 'UPDATE'); - - END IF; - -END ; - -UPDATE glpi.glpi_plugin_processmaker_cases INNER JOIN wf_workflow.application on wf_workflow.application.APP_UID=glpi.glpi_plugin_processmaker_cases.case_id - SET glpi.glpi_plugin_processmaker_cases.case_status=wf_workflow.application.APP_STATUS ; - - diff --git a/config/pm_db_install.sql b/config/pm_db_install.sql deleted file mode 100644 index 0e7fadb..0000000 --- a/config/pm_db_install.sql +++ /dev/null @@ -1,203 +0,0 @@ - - -DROP TRIGGER IF EXISTS `GLPI_APPLICATION_DELETE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELAY_INSERT` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELAY_UPDATE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_INSERT` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_UPDATE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_DELETE` ; - - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APPLICATION_DELETE` AFTER DELETE ON `application` FOR EACH ROW BEGIN - DECLARE loc_Ticket_id INT(11) ; - SELECT ticket_id INTO loc_Ticket_id FROM glpi.glpi_plugin_processmaker_ticketcase WHERE case_id=OLD.APP_UID; - IF loc_Ticket_id IS NOT NULL THEN - DELETE FROM glpi.glpi_plugin_processmaker_ticketcase WHERE case_id=OLD.APP_UID ; - END IF; -END ; - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELAY_INSERT` AFTER INSERT ON `app_delay` FOR EACH ROW BEGIN -DECLARE loc_task_id, loc_task_cat_id, loc_Ticket_id, loc_Found_Pos, loc_glpi_users_id, loc_Count_Ticket INT(11) ; - DECLARE APP_TITLE, APP_PRO_TITLE, APP_TAS_TITLE VARCHAR(255); - DECLARE loc_pm_user_id VARCHAR(32) ; - DECLARE locDate DATETIME ; - - IF NEW.APP_TYPE = 'PAUSE' THEN - - SELECT ticket_id INTO loc_Ticket_id FROM glpi.glpi_plugin_processmaker_ticketcase WHERE case_id=NEW.APP_UID; - - IF loc_Ticket_id IS NOT NULL THEN - - SELECT CONTENT.CON_VALUE into APP_TITLE FROM CONTENT WHERE NEW.APP_UID=CON_ID AND CON_CATEGORY='APP_TITLE' and CON_LANG = 'en' LIMIT 1; - IF APP_TITLE IS NULL THEN - SET APP_TITLE = ''; - END IF; - SELECT CONTENT.CON_VALUE into APP_PRO_TITLE FROM CONTENT WHERE NEW.PRO_UID=CON_ID AND CON_CATEGORY='PRO_TITLE' and CON_LANG = 'en' LIMIT 1; - SET APP_TAS_TITLE = 'Task is paused'; - - SELECT glpi_users_id INTO loc_glpi_users_id FROM glpi.glpi_plugin_processmaker_users WHERE pm_users_id=NEW.APP_DELEGATION_USER LIMIT 1; - IF loc_glpi_users_id IS NULL THEN - SET loc_glpi_users_id = 2 ; - END IF ; - - SELECT id INTO loc_task_cat_id FROM glpi.glpi_taskcategories WHERE name=APP_PRO_TITLE; - IF loc_task_cat_id IS NULL THEN - SET loc_task_cat_id=0 ; - END IF ; - - SET locDate = Now() ; - INSERT INTO glpi.glpi_tickettasks - ( `tickets_id`, `taskcategories_id`, `date`, `users_id`, `content`, `is_private`, `actiontime`, `begin`, `end`, `state`, `users_id_tech`) - VALUES ( loc_Ticket_id, - loc_task_cat_id, - locDate, - 1, - CONCAT( 'Bound to process: ', APP_PRO_TITLE, ',
case title: ', APP_TITLE, ',
task: ', APP_TAS_TITLE,'.
Go to Case tab to manage!' ), - 0, - 0, - NEW.APP_ENABLE_ACTION_DATE, - NEW.APP_DISABLE_ACTION_DATE, - 1, - loc_glpi_users_id); - - SET loc_task_id = LAST_INSERT_ID(); - INSERT INTO glpi.glpi_plugin_processmaker_tasks (`tickettasks_id`, `case_id`, `del_index`) VALUES (loc_task_id, NEW.APP_DELAY_UID, 0 ); - - REPLACE INTO glpi.glpi_plugin_processmaker_tasksnotifications (`date`, `task_id`, `user_id`, `tech_id`, `action`) VALUES ( locDate, loc_task_id, 1, loc_glpi_users_id, 'INSERT'); - - END IF; - END IF; -END ; - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELAY_UPDATE` AFTER UPDATE ON `app_delay` FOR EACH ROW BEGIN - - DECLARE loc_tickettasks_id, loc_Count_Task INT(11) ; - DECLARE loc_glpi_users_id INT(11) ; - - SELECT glpi_pm_tasks.tickettasks_id INTO loc_tickettasks_id FROM glpi.glpi_plugin_processmaker_tasks as glpi_pm_tasks WHERE glpi_pm_tasks.case_id=NEW.APP_DELAY_UID ; - IF loc_tickettasks_id IS NOT NULL THEN - SELECT glpi_users_id INTO loc_glpi_users_id FROM glpi.glpi_plugin_processmaker_users WHERE pm_users_id=NEW.APP_DISABLE_ACTION_USER LIMIT 1; - IF loc_glpi_users_id IS NULL THEN - SET loc_glpi_users_id = 2 ; - END IF ; - - IF NEW.APP_DISABLE_ACTION_DATE IS NOT NULL THEN - UPDATE glpi.glpi_tickettasks - SET state=2, - `end`=NEW.APP_DISABLE_ACTION_DATE - WHERE id=loc_tickettasks_id ; - END IF ; - - REPLACE INTO glpi.glpi_plugin_processmaker_tasksnotifications (`date`, `task_id`, `user_id`, `tech_id`, `action`) VALUES ( Now(), loc_tickettasks_id, 1, loc_glpi_users_id, 'UPDATE'); - - END IF; - -END ; - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELEGATION_DELETE` AFTER DELETE ON `app_delegation` FOR EACH ROW BEGIN - - DECLARE loc_Ticket_id, loc_tickettask_id INT(11) ; - - SELECT glpi_pm_tcase.ticket_id INTO loc_Ticket_id FROM glpi.glpi_plugin_processmaker_ticketcase as glpi_pm_tcase WHERE glpi_pm_tcase.case_id=OLD.APP_UID; - IF loc_Ticket_id IS NOT NULL THEN - SELECT glpi_pm_tasks.tickettasks_id INTO loc_tickettask_id FROM glpi.glpi_plugin_processmaker_tasks as glpi_pm_tasks WHERE glpi_pm_tasks.case_id=OLD.APP_UID AND glpi_pm_tasks.del_index=OLD.DEL_INDEX LIMIT 1; - DELETE FROM glpi.glpi_plugin_processmaker_tasks WHERE tickettasks_id = loc_tickettask_id ; - DELETE FROM glpi.glpi_tickettasks WHERE id = loc_tickettask_id ; - END IF; - -END ; - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELEGATION_INSERT` AFTER INSERT ON `app_delegation` FOR EACH ROW BEGIN - DECLARE loc_task_id, loc_task_cat_id, loc_Ticket_id, loc_Found_Pos, loc_glpi_users_id, loc_Count_Ticket INT(11) ; - DECLARE APP_TITLE, APP_PRO_TITLE, APP_TAS_TITLE VARCHAR(255); - DECLARE locDate DATETIME ; - /*DECLARE loc_pm_user_id VARCHAR(32) ;*/ - - SELECT ticket_id INTO loc_Ticket_id FROM glpi.glpi_plugin_processmaker_ticketcase WHERE case_id=NEW.APP_UID; - - IF loc_Ticket_id IS NOT NULL THEN - - SELECT CONTENT.CON_VALUE into APP_TITLE FROM CONTENT WHERE NEW.APP_UID=CON_ID AND CON_CATEGORY='APP_TITLE' and CON_LANG = 'en' LIMIT 1; - IF APP_TITLE IS NULL THEN - SET APP_TITLE = ''; - END IF; - SELECT CONTENT.CON_VALUE into APP_PRO_TITLE FROM CONTENT WHERE NEW.PRO_UID=CON_ID AND CON_CATEGORY='PRO_TITLE' and CON_LANG = 'en' LIMIT 1; - SELECT CONTENT.CON_VALUE into APP_TAS_TITLE FROM CONTENT WHERE NEW.TAS_UID=CON_ID AND CON_CATEGORY='TAS_TITLE' and CON_LANG = 'en' LIMIT 1; - - - SELECT glpi_users_id INTO loc_glpi_users_id FROM glpi.glpi_plugin_processmaker_users WHERE pm_users_id=NEW.USR_UID LIMIT 1; - IF loc_glpi_users_id IS NULL THEN - /* we must find a user linked to a group */ /* task is NEW.TAS_UID */ - select glpi.glpi_users.id INTO loc_glpi_users_id from task_user - join content on content.CON_ID=task_user.USR_UID and content.CON_CATEGORY='GRP_TITLE' and CON_LANG = 'en' - join glpi.glpi_users on glpi.glpi_users.name=content.CON_VALUE COLLATE utf8_unicode_ci - where tas_uid=NEW.TAS_UID and tu_relation=2 LIMIT 1; - IF loc_glpi_users_id IS NULL THEN - SET loc_glpi_users_id = 2 ; - END IF ; - END IF; - SELECT id INTO loc_task_cat_id FROM glpi.glpi_taskcategories WHERE name=APP_PRO_TITLE LIMIT 1; - IF loc_task_cat_id IS NULL THEN - SET loc_task_cat_id=0 ; - END IF ; - - SET locDate = Now() ; - INSERT INTO glpi.glpi_tickettasks - ( `tickets_id`, `taskcategories_id`, `date`, `users_id`, `content`, `is_private`, `actiontime`, `begin`, `end`, `state`, `users_id_tech`) - VALUES ( loc_Ticket_id, - loc_task_cat_id, - locDate, - 1, - CONCAT( 'Bound to process: ', APP_PRO_TITLE, ',
case title: ', APP_TITLE, ',
task: ', APP_TAS_TITLE,'.
Go to Case tab to manage!' ), - 0, - 0, - NEW.DEL_DELEGATE_DATE, - NEW.DEL_TASK_DUE_DATE, - 1, - loc_glpi_users_id); - - SET loc_task_id = LAST_INSERT_ID(); - INSERT INTO glpi.glpi_plugin_processmaker_tasks (`tickettasks_id`, `case_id`, `del_index`) VALUES (loc_task_id, NEW.APP_UID, NEW.DEL_INDEX ); - - REPLACE INTO glpi.glpi_plugin_processmaker_tasksnotifications (`date`, `task_id`, `user_id`, `tech_id`, `action`) VALUES ( locDate, loc_task_id, 1, loc_glpi_users_id, 'INSERT'); - - END IF; -END ; - - -CREATE DEFINER=CURRENT_USER TRIGGER `GLPI_APP_DELEGATION_UPDATE` AFTER UPDATE ON `app_delegation` FOR EACH ROW BEGIN - - DECLARE loc_tickettasks_id, loc_Count_Task INT(11) ; - DECLARE loc_glpi_users_id INT(11) ; - - SELECT glpi_pm_tasks.tickettasks_id INTO loc_tickettasks_id FROM glpi.glpi_plugin_processmaker_tasks as glpi_pm_tasks WHERE glpi_pm_tasks.case_id=NEW.APP_UID AND glpi_pm_tasks.del_index=NEW.DEL_INDEX ; - IF loc_tickettasks_id IS NOT NULL THEN - SELECT glpi_users_id INTO loc_glpi_users_id FROM glpi.glpi_plugin_processmaker_users WHERE pm_users_id=NEW.USR_UID LIMIT 1; - IF loc_glpi_users_id IS NULL THEN - SET loc_glpi_users_id = 2 ; - END IF ; - - IF NEW.DEL_THREAD_STATUS = 'CLOSED' THEN - UPDATE glpi.glpi_tickettasks - SET state=2, - `begin`=NEW.DEL_INIT_DATE, - `end`=NEW.DEL_FINISH_DATE, - `actiontime`= IFNULL(TIMESTAMPDIFF(SECOND,NEW.DEL_INIT_DATE,NEW.DEL_FINISH_DATE),0) - WHERE id=loc_tickettasks_id ; - ELSE - UPDATE glpi.glpi_tickettasks - SET users_id_tech=loc_glpi_users_id - WHERE id=loc_tickettasks_id ; - END IF ; - - REPLACE INTO glpi.glpi_plugin_processmaker_tasksnotifications (`date`, `task_id`, `user_id`, `tech_id`, `action`) VALUES ( Now(), loc_tickettasks_id, 1, loc_glpi_users_id, 'UPDATE'); - - END IF; - -END ; - - diff --git a/config/pm_db_uninstall.mysql b/config/pm_db_uninstall.mysql deleted file mode 100644 index aaaf23e..0000000 --- a/config/pm_db_uninstall.mysql +++ /dev/null @@ -1,7 +0,0 @@ -DROP TRIGGER IF EXISTS `GLPI_APPLICATION_DELETE` ; -DROP TRIGGER IF EXISTS `GLPI_APPLICATION_UPDATE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELAY_INSERT` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELAY_UPDATE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_INSERT` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_UPDATE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_DELETE` ; diff --git a/config/pm_db_uninstall.sql b/config/pm_db_uninstall.sql deleted file mode 100644 index 558f5e8..0000000 --- a/config/pm_db_uninstall.sql +++ /dev/null @@ -1,6 +0,0 @@ -DROP TRIGGER IF EXISTS `GLPI_APPLICATION_DELETE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELAY_INSERT` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELAY_UPDATE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_INSERT` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_UPDATE` ; -DROP TRIGGER IF EXISTS `GLPI_APP_DELEGATION_DELETE` ; diff --git a/front/cases.front.php b/front/cases.front.php index 7e07ec1..bf8831a 100644 --- a/front/cases.front.php +++ b/front/cases.front.php @@ -2,39 +2,39 @@ include_once '../../../inc/includes.php'; // check if it is from PM pages -if( isset( $_REQUEST['UID'] ) && isset( $_REQUEST['APP_UID'] ) && isset( $_REQUEST['__DynaformName__'] ) ) { +if (isset( $_REQUEST['UID'] ) && isset( $_REQUEST['APP_UID'] ) && isset( $_REQUEST['__DynaformName__'] )) { // then get item id from DB - $myCase = new PluginProcessmakerCase ; - if( $myCase->getFromDB( $_REQUEST['APP_UID'] ) ) { - $myProcessMaker = new PluginProcessmakerProcessmaker() ; - $myProcessMaker->login( ) ; + $myCase = new PluginProcessmakerCase; + if ($myCase->getFromDB( $_REQUEST['APP_UID'] )) { + $myProcessMaker = new PluginProcessmakerProcessmaker(); + $myProcessMaker->login( ); - if( isset( $_REQUEST['form'] ) ) { + if (isset( $_REQUEST['form'] )) { $myProcessMaker->derivateCase( $myCase, $_REQUEST); //, $_SERVER['HTTP_COOKIE'] ) ; } } -} elseif ( isset( $_REQUEST['form'] ) && isset( $_REQUEST['form']['BTN_CATCH'] ) && isset( $_REQUEST['form']['APP_UID']) ) { +} else if (isset( $_REQUEST['form'] ) && isset( $_REQUEST['form']['BTN_CATCH'] ) && isset( $_REQUEST['form']['APP_UID'])) { // Claim task management // here we are in a Claim request - $myCase = new PluginProcessmakerCase ; - if( $myCase->getFromDB( $_REQUEST['form']['APP_UID'] ) ) { - $myProcessMaker = new PluginProcessmakerProcessmaker() ; - $myProcessMaker->login( ) ; + $myCase = new PluginProcessmakerCase; + if ($myCase->getFromDB( $_REQUEST['form']['APP_UID'] )) { + $myProcessMaker = new PluginProcessmakerProcessmaker(); + $myProcessMaker->login( ); - $pmClaimCase = $myProcessMaker->claimCase( $myCase->getID(), $_REQUEST['DEL_INDEX'] ) ; + $pmClaimCase = $myProcessMaker->claimCase( $myCase->getID(), $_REQUEST['DEL_INDEX'] ); // now manage tasks associated with item - $myProcessMaker->claimTask( $myCase->getID(), $_REQUEST['DEL_INDEX'] ) ; + $myProcessMaker->claimTask( $myCase->getID(), $_REQUEST['DEL_INDEX'] ); } } // now redirect to item form page -$config = PluginProcessmakerConfig::getInstance() ; +$config = PluginProcessmakerConfig::getInstance(); echo "" ; +echo ""; diff --git a/front/config.form.php b/front/config.form.php index 5578a36..3415874 100644 --- a/front/config.form.php +++ b/front/config.form.php @@ -1,26 +1,21 @@ check($_POST['id'], UPDATE); - - // save - $config->update($_POST); + $config->check($_POST['id'], UPDATE); + + // save + $config->update($_POST); - Html::back(); + Html::back(); -} elseif (isset($_POST["refresh"])) { - $config->refresh($_POST); // used to refresh process list, task category list - Html::back(); -} +} else if (isset($_POST["refresh"])) { + $config->refresh($_POST); // used to refresh process list, task category list + Html::back(); +} Html::redirect($CFG_GLPI["root_doc"]."/front/config.form.php?forcetab=". urlencode('PluginProcessmakerConfig$1')); diff --git a/front/process.form.php b/front/process.form.php index 0038c8d..ef7265e 100644 --- a/front/process.form.php +++ b/front/process.form.php @@ -1,34 +1,30 @@ check($_REQUEST['id'], UPDATE); - $PluginProcess->update($_REQUEST); - Html::back(); + $PluginProcess->check($_REQUEST['id'], UPDATE); + $PluginProcess->update($_REQUEST); + Html::back(); + +} else if (isset($_REQUEST["refreshtask"])) { + $PluginProcess->check($_REQUEST['id'], UPDATE); + $PluginProcess->refreshTasks($_REQUEST); + Html::back(); -} elseif (isset($_REQUEST["refreshtask"])) { - $PluginProcess->check($_REQUEST['id'], UPDATE); - $PluginProcess->refreshTasks($_REQUEST); - Html::back(); - } else { - // $PluginProcess->checkGlobal(READ); - Html::header($LANG['processmaker']['title'][1],$_SERVER["PHP_SELF"],"plugins","processmaker"); - - $PluginProcess->display($_REQUEST) ; - - // $PluginProcess->showForm($_REQUEST["id"]); - Html::footer(); + Html::header($LANG['processmaker']['title'][1], $_SERVER["PHP_SELF"], "plugins", "processmaker"); + + $PluginProcess->display($_REQUEST); + + Html::footer(); } -?> \ No newline at end of file diff --git a/front/process.php b/front/process.php index 66d793d..eb4546a 100644 --- a/front/process.php +++ b/front/process.php @@ -1,25 +1,23 @@ refresh(); - Html::back(); - } - - $process->title(); + if (isset( $_REQUEST['refresh'] ) && Session::haveRight("plugin_processmaker_config", UPDATE)) { + $process->refresh(); + Html::back(); + } - Search::show('PluginProcessmakerProcess'); + $process->title(); + + Search::show('PluginProcessmakerProcess'); } else { - Html::displayRightError(); + Html::displayRightError(); } Html::footer(); -?> \ No newline at end of file diff --git a/front/process_profile.form.php b/front/process_profile.form.php index fc1da8d..55c2472 100644 --- a/front/process_profile.form.php +++ b/front/process_profile.form.php @@ -1,42 +1,39 @@ check(-1,UPDATE,$_POST); - if ($right->add($_POST)) { - //Event::log($_POST["processes_id"], "PluginProcessMakerProcess", 4, "setup", - // $_SESSION["glpiname"]." ".$LANG['log'][61]); - } - Html::back(); + $right->check(-1, UPDATE, $_POST); + if ($right->add($_POST)) { + //Event::log($_POST["processes_id"], "PluginProcessMakerProcess", 4, "setup", + // $_SESSION["glpiname"]." ".$LANG['log'][61]); + } + Html::back(); } else if (isset($_POST["delete"])) { - if (isset($_POST["item"]) && count($_POST["item"])) { - foreach ($_POST["item"] as $key => $val) { - if ($val == 1) { - if ($right->can($key,UPDATE)) { - $right->delete(array('id' => $key)); - } + if (isset($_POST["item"]) && count($_POST["item"])) { + foreach ($_POST["item"] as $key => $val) { + if ($val == 1) { + if ($right->can($key, UPDATE)) { + $right->delete(array('id' => $key)); } - } - //if (isset($_POST["processes_id"])) { - // Event::log($_POST["processes_id"], "users", 4, "setup", - // $_SESSION["glpiname"]." ".$LANG['log'][62]); - // } - } + } + } + //if (isset($_POST["processes_id"])) { + // Event::log($_POST["processes_id"], "users", 4, "setup", + // $_SESSION["glpiname"]." ".$LANG['log'][62]); + // } + } Html::back(); -} - +} Html::displayErrorAndDie("lost"); -?> \ No newline at end of file diff --git a/front/processmaker.form.php b/front/processmaker.form.php index e921e46..533f23a 100644 --- a/front/processmaker.form.php +++ b/front/processmaker.form.php @@ -1,124 +1,123 @@ 0 ) { // then this case will be bound to an item - // we must check if a case is not already existing - // to manage the problem of F5 (Refresh) - $hasCase = PluginProcessmakerProcessmaker::getCaseIdFromItem( $_POST['itemtype'], $_POST['id'] ) ; - if( $hasCase === false && $_POST['plugin_processmaker_process_id'] > 0 ) { //$DB->numrows($res) == 0) { - $myProcessMaker = new PluginProcessmakerProcessmaker() ; - $myProcessMaker->login() ; //openSession(); +switch ($_POST["action"]) { + case 'newcase': + if (isset($_POST['id']) && $_POST['id'] > 0) { // then this case will be bound to an item + // we must check if a case is not already existing + // to manage the problem of F5 (Refresh) + $hasCase = PluginProcessmakerProcessmaker::getCaseIdFromItem( $_POST['itemtype'], $_POST['id'] ); + if ($hasCase === false && $_POST['plugin_processmaker_process_id'] > 0) { //$DB->numrows($res) == 0) { + $myProcessMaker = new PluginProcessmakerProcessmaker(); + $myProcessMaker->login(); //openSession(); - $resultCase = $myProcessMaker->startNewCase( $_POST['plugin_processmaker_process_id'], $_POST['itemtype'], $_POST['id'], Session::getLoginUserID() ) ; - - if ($resultCase->status_code == 0){ - Html::back(); - } - else - Session::addMessageAfterRedirect($LANG['processmaker']['item']['error'][$resultCase->status_code]."
".$resultCase->message." (".$resultCase->status_code.")", true, ERROR); - } else - Html::back(); - } - else { // the case is created before the ticket (used for post-only case creation before ticket creation) - $myProcessMaker = new PluginProcessmakerProcessmaker() ; - $myProcessMaker->login() ; - $resultCase = $myProcessMaker->newCase( $_POST['plugin_processmaker_process_id'], - array( 'GLPI_ITEM_CAN_BE_SOLVED' => 0, - 'GLPI_SELFSERVICE_CREATED' => '1', - 'GLPI_URL' => $CFG_GLPI['url_base'].$CFG_GLPI['root_doc']) ) ; - if ($resultCase->status_code == 0){ - // case is created - // Must show it... - // - $rand = rand( ) ; - Html::redirect($CFG_GLPI['root_doc']."/plugins/processmaker/front/processmaker.helpdesk.form.php?process_id=".$_POST['plugin_processmaker_process_id']."&case_id=".$resultCase->caseId."&rand=$rand&itilcategories_id=".$_POST["itilcategories_id"]."&type=".$_REQUEST["type"]."&entities_id=".$_REQUEST['entities_id']); + $resultCase = $myProcessMaker->startNewCase( $_POST['plugin_processmaker_process_id'], $_POST['itemtype'], $_POST['id'], Session::getLoginUserID() ); + if ($resultCase->status_code == 0) { + Html::back(); } else { - Session::addMessageAfterRedirect($LANG['processmaker']['item']['error'][$resultCase->status_code]."
$resultCase->message ($resultCase->status_code)", true, ERROR); //echo "Error creating case: $resultCase->message \n"; - Html::redirect($CFG_GLPI["root_doc"]."/front/helpdesk.public.php?create_ticket=1"); + Session::addMessageAfterRedirect($LANG['processmaker']['item']['error'][$resultCase->status_code]."
".$resultCase->message." (".$resultCase->status_code.")", true, ERROR); } + } else { + Html::back(); + } + } else { // the case is created before the ticket (used for post-only case creation before ticket creation) + $myProcessMaker = new PluginProcessmakerProcessmaker(); + $myProcessMaker->login(); + $resultCase = $myProcessMaker->newCase( $_POST['plugin_processmaker_process_id'], + array( 'GLPI_ITEM_CAN_BE_SOLVED' => 0, + 'GLPI_SELFSERVICE_CREATED' => '1', + 'GLPI_URL' => $CFG_GLPI['url_base'].$CFG_GLPI['root_doc']) ); + if ($resultCase->status_code == 0) { + // case is created + // Must show it... + // + $rand = rand( ); + Html::redirect($CFG_GLPI['root_doc']."/plugins/processmaker/front/processmaker.helpdesk.form.php?process_id=".$_POST['plugin_processmaker_process_id']."&case_id=".$resultCase->caseId."&rand=$rand&itilcategories_id=".$_POST["itilcategories_id"]."&type=".$_REQUEST["type"]."&entities_id=".$_REQUEST['entities_id']); - } + } else { + Session::addMessageAfterRedirect($LANG['processmaker']['item']['error'][$resultCase->status_code]."
$resultCase->message ($resultCase->status_code)", true, ERROR); //echo "Error creating case: $resultCase->message \n"; + Html::redirect($CFG_GLPI["root_doc"]."/front/helpdesk.public.php?create_ticket=1"); + } + + } break; - case 'unpausecase_or_reassign_or_delete' : - if( isset( $_POST['unpause'] ) ) { - $myProcessMaker = new PluginProcessmakerProcessmaker() ; - $myProcessMaker->login() ; //openSession(); - $pmResultUnpause = $myProcessMaker->unpauseCase( $_POST['plugin_processmaker_caseId'], $_POST['plugin_processmaker_delIndex'], $_POST['plugin_processmaker_userId'] ) ; - if ($pmResultUnpause->status_code == 0){ - Html::back(); + case 'unpausecase_or_reassign_or_delete' : + if (isset( $_POST['unpause'] )) { + $myProcessMaker = new PluginProcessmakerProcessmaker(); + $myProcessMaker->login(); //openSession(); + $pmResultUnpause = $myProcessMaker->unpauseCase( $_POST['plugin_processmaker_caseId'], $_POST['plugin_processmaker_delIndex'], $_POST['plugin_processmaker_userId'] ); + if ($pmResultUnpause->status_code == 0) { + Html::back(); + } else { + echo "Error unpausing case: ".$pmResultUnpause->message." \n"; + } + } else if (isset( $_POST['reassign'] )) { + // here we should re-assign the current task to $_POST['users_id_recipient'] + $GLPINewPMUserId = PluginProcessmakerUser::getPMUserId( $_POST['users_id_recipient'] ); + if ($_POST['plugin_processmaker_userId'] != $GLPINewPMUserId) { + $locPM = new PluginProcessmakerProcessmaker(); + $locPM->login( ); + + $pmResponse = $locPM->reassignCase( $_POST['plugin_processmaker_caseId'], $_POST['plugin_processmaker_delIndex'], $_POST['plugin_processmaker_userId'], $GLPINewPMUserId ); + if ($pmResponse->status_code == 0) { + // we need to change the delindex of the glpi task and the assigned tech to prevent creation of new tasks + // we need the delindex of the current glpi task, and the delindex of the new one + // search for new delindex + $newCaseInfo = $locPM->getCaseInfo( $_POST['plugin_processmaker_caseId'] ); + $newDelIndex = 0; + foreach ($newCaseInfo->currentUsers as $newCaseUser) { + if ($newCaseUser->taskId == $_POST['plugin_processmaker_taskId'] && $newCaseUser->delThread == $_POST['plugin_processmaker_delThread']) { + $newDelIndex = $newCaseUser->delIndex; + break; + } + } + $locPM->reassignTask( $_POST['plugin_processmaker_caseId'], $_POST['plugin_processmaker_delIndex'], $newDelIndex, $_POST['users_id_recipient'] ); + Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['reassigned'], true, INFO); + } else { + Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['notreassigned'].$pmResponse->message, true, ERROR); } - else - echo "Error unpausing case: ".$pmResultUnpause->message." \n"; - } - else if( isset( $_POST['reassign'] ) ) { - // here we should re-assign the current task to $_POST['users_id_recipient'] - $GLPINewPMUserId = PluginProcessmakerUser::getPMUserId( $_POST['users_id_recipient'] ) ; - if( $_POST['plugin_processmaker_userId'] != $GLPINewPMUserId ) { - $locPM = new PluginProcessmakerProcessmaker() ; - $locPM->login( ) ; + } else { + Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['assignedtoyou'], true, ERROR); // Html::back(); + } + } else if (isset($_POST['delete'])) { + // delete case from case table, this will also delete the tasks + $locCase = new PluginProcessmakerCase; + $locCase->getFromDB( $_POST['plugin_processmaker_caseId'] ); + if ($locCase->deleteCase()) { + // request delete from pm itself + $myProcessMaker = new PluginProcessmakerProcessmaker(); + $myProcessMaker->login(true); + $resultPM = $myProcessMaker->deleteCase( $_POST['plugin_processmaker_caseId'] ); - $pmResponse = $locPM->reassignCase( $_POST['plugin_processmaker_caseId'], $_POST['plugin_processmaker_delIndex'], $_POST['plugin_processmaker_userId'], $GLPINewPMUserId ) ; - if ($pmResponse->status_code == 0){ - // we need to change the delindex of the glpi task and the assigned tech to prevent creation of new tasks - // we need the delindex of the current glpi task, and the delindex of the new one - // search for new delindex - $newCaseInfo = $locPM->getCaseInfo( $_POST['plugin_processmaker_caseId'] ) ; - $newDelIndex = 0 ; - foreach( $newCaseInfo->currentUsers as $newCaseUser ){ - if( $newCaseUser->taskId == $_POST['plugin_processmaker_taskId'] && $newCaseUser->delThread == $_POST['plugin_processmaker_delThread'] ) { - $newDelIndex = $newCaseUser->delIndex ; - break ; - } - } - $locPM->reassignTask( $_POST['plugin_processmaker_caseId'], $_POST['plugin_processmaker_delIndex'], $newDelIndex, $_POST['users_id_recipient'] ) ; - Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['reassigned'], true, INFO); - // Html::back(); - } - else - Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['notreassigned'].$pmResponse->message, true, ERROR); - } else - Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['assignedtoyou'], true, ERROR); // Html::back(); - } - else if( isset($_POST['delete']) ) { - // delete case from case table, this will also delete the tasks - $locCase = new PluginProcessmakerCase ; - $locCase->getFromDB( $_POST['plugin_processmaker_caseId'] ) ; - if( $locCase->deleteCase() ) { - // request delete from pm itself - $myProcessMaker = new PluginProcessmakerProcessmaker() ; - $myProcessMaker->login(true) ; - $resultPM = $myProcessMaker->deleteCase( $_POST['plugin_processmaker_caseId'] ) ; + if ($resultPM->status_code == 0) { + Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['deleted'], true, INFO); + } else { + Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['errordeleted'], true, ERROR); + } + } else { + Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['errordeleted'], true, ERROR); + } + } else if (isset($_POST['cancel'])) { + // cancel case from PM + $myProcessMaker = new PluginProcessmakerProcessmaker(); + $myProcessMaker->login(); + $resultPM = $myProcessMaker->cancelCase( $_POST['plugin_processmaker_caseId'] ); //, $_POST['plugin_processmaker_delIndex'], $_POST['plugin_processmaker_userId'] ) ; + if ($resultPM->status_code === 0) { + $locCase = new PluginProcessmakerCase; + $locCase->getFromDB( $_POST['plugin_processmaker_caseId'] ); + if ($locCase->cancelCase()) { + Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['cancelled'], true, INFO); + } else { + Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['errorcancelled'], true, ERROR); + } + } else { + Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['errorcancelled'], true, ERROR); + } + } - if( $resultPM->status_code == 0 ) { - Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['deleted'], true, INFO); - } else - Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['errordeleted'], true, ERROR); - } else - Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['errordeleted'], true, ERROR); - } - else if( isset($_POST['cancel']) ) { - // cancel case from PM - $myProcessMaker = new PluginProcessmakerProcessmaker() ; - $myProcessMaker->login() ; - $resultPM = $myProcessMaker->cancelCase( $_POST['plugin_processmaker_caseId'] ) ; //, $_POST['plugin_processmaker_delIndex'], $_POST['plugin_processmaker_userId'] ) ; - if( $resultPM->status_code === 0 ) { - $locCase = new PluginProcessmakerCase ; - $locCase->getFromDB( $_POST['plugin_processmaker_caseId'] ) ; - if( $locCase->cancelCase() ) - Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['cancelled'], true, INFO); - else - Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['errorcancelled'], true, ERROR); - } else - Session::addMessageAfterRedirect($LANG['processmaker']['item']['case']['errorcancelled'], true, ERROR); - } - - break; + break; } diff --git a/front/processmaker.helpdesk.form.php b/front/processmaker.helpdesk.form.php index d36a7f6..303fa20 100644 --- a/front/processmaker.helpdesk.form.php +++ b/front/processmaker.helpdesk.form.php @@ -1,20 +1,18 @@ "; echo "
"; echo ""; - echo ""; + + if (Profile::canView()) { + $entname = "". + $data["name"].""; + } else { + $entname = $data["name"]; + } + + // if ($data["is_dynamic"] || $data["is_recursive"]) { + if ($data["is_recursive"]) { + $entname = sprintf(__('%1$s %2$s'), $entname, "("); + //if ($data["is_dynamic"]) { + // //TRANS: letter 'D' for Dynamic + // $entname = sprintf(__('%1$s%2$s'), $entname, __('D')); + //} + //if ($data["is_dynamic"] && $data["is_recursive"]) { + // $entname = sprintf(__('%1$s%2$s'), $entname, ", "); + //} + if ($data["is_recursive"]) { + //TRANS: letter 'R' for Recursive + $entname = sprintf(__('%1$s%2$s'), $entname, __('R')); + } + $entname = sprintf(__('%1$s%2$s'), $entname, ")"); + } + echo ""; + echo ""; + } + echo $header_begin.$header_bottom.$header_end; + echo "
".$LANG['processmaker']['item']['tab']."
"; echo $LANG['processmaker']['item']['selectprocess']." "; echo ""; @@ -22,7 +20,6 @@ function processMakerShowProcessList ($ID, $from_helpdesk) { echo ""; echo ""; echo ""; -// Dropdown::show('PluginProcessmakerProcessmaker', array( 'name' => 'plugin_processmaker_process_id', 'condition' => "is_active=1 and is_helpdeskvisible=1")); // condition is used to prevent start of none-active and none-helpdesk-visible cases PluginProcessmakerProcess::dropdown( array( 'value' => 0, 'entity' => $_SESSION['glpiactive_entity'], 'name' => 'plugin_processmaker_process_id' )); echo ""; echo ""; @@ -33,849 +30,6 @@ function processMakerShowProcessList ($ID, $from_helpdesk) { } -///** -//* Print the helpdesk form -//* -//* @param $ID int : ID of the user who want to display the Helpdesk -//* @param $ticket_template int : ID ticket template for preview : false if not used for preview -//* -//* @return nothing (print the helpdesk) -//**/ -//function showFormHelpdeskbak($ID, $pmItem, $caseInfo, $ticket_template=false) { -// global $DB, $CFG_GLPI, $LANG; - -// if (!Session::haveRight("ticket", CREATE)) { -// return false; -// } - -// $query = "SELECT `realname`, `firstname`, `name` -// FROM `glpi_users` -// WHERE `id` = '$ID'"; -// $result = $DB->query($query); - - -// $email = UserEmail::getDefaultForUser($ID); - - -// // Set default values... -// $default_values = array('_users_id_requester_notif' => array('use_notification' => ($email==""?0:1), -// 'alternative_email' => ''), -// 'nodelegate' => 1, -// '_users_id_requester' => 0, -// 'name' => '', -// 'content' => '', -// 'itilcategories_id' => 0, -// 'urgency' => 3, -// 'itemtype' => '', -// 'entities_id' => $_SESSION['glpiactive_entity'], -// 'items_id' => 0, -// 'plan' => array(), -// 'global_validation' => 'none', -// 'due_date' => 'NULL', -// 'slas_id' => 0, -// '_add_validation' => 0, -// 'type' => 1, -// '_right' => "id"); - -// if (!$ticket_template) { -// $options = $_REQUEST; -// } - -// // Restore saved value or override with page parameter -// foreach ($default_values as $name => $value) { -// if (!isset($options[$name])) { -// if (isset($_SESSION["helpdeskSaved"][$name])) { -// $options[$name] = $_SESSION["helpdeskSaved"][$name]; -// } else { -// $options[$name] = $value; -// } -// } -// } -// // Clean text fields -// $options['name'] = stripslashes($options['name']); -// $options['content'] = Html::cleanPostForTextArea($options['content']); - -// if (!$ticket_template) { -// echo "
"; -// } - - -// $delegating = User::getDelegateGroupsForUser($options['entities_id']); - -// if (count($delegating)) { -// echo "
"; -// echo ""; -// echo ""; - -// echo "
".$LANG['job'][69]." : "; - -// $rand = Dropdown::showYesNo("nodelegate", $options['nodelegate']); - -// $params = array ('nodelegate' => '__VALUE__', -// 'rand' => $rand, -// 'right' => "delegate", -// '_users_id_requester' -// => $options['_users_id_requester'], -// '_users_id_requester_notif' -// => $options['_users_id_requester_notif'], -// 'use_notification' -// => $options['_users_id_requester_notif']['use_notification'], -// 'entity_restrict' -// => $_SESSION["glpiactive_entity"]); - -// Ajax::UpdateItemOnSelectEvent("dropdown_nodelegate".$rand, "show_result".$rand, -// $CFG_GLPI["root_doc"]."/ajax/dropdownDelegationUsers.php", -// $params); - -// echo "
"; -// echo "
"; - -// $self = new Ticket(); -// if ($options["_users_id_requester"] == 0) { -// $options['_users_id_requester'] = Session::getLoginUserID(); -// } else { -// $options['_right'] = "delegate"; -// } -// $self->showActorAddFormOnCreate(Ticket::REQUESTER, $options); -// echo "
"; -// echo "
"; -// echo ""; -// } - -// echo ""; -// echo ""; - - -// // Load ticket template if available : -// $tt = new TicketTemplate(); - -// // First load default entity one -// if ($template_id = EntityData::getUsedConfig('tickettemplates_id', $_SESSION["glpiactive_entity"])) { -// // with type and categ -// $tt->getFromDBWithDatas($template_id, true); -// } - -// $field = ''; -// if ($options['type'] && $options['itilcategories_id']) { -// $categ = new ITILCategory(); -// if ($categ->getFromDB($options['itilcategories_id'])) { -// switch ($options['type']) { -// case Ticket::INCIDENT_TYPE : -// $field = 'tickettemplates_id_incident'; -// break; - -// case Ticket::DEMAND_TYPE : -// $field = 'tickettemplates_id_demand'; -// break; -// } - -// if (!empty($field) && $categ->fields[$field]) { -// // without type and categ -// $tt->getFromDBWithDatas($categ->fields[$field], false); -// } -// } -// } -// if ($ticket_template) { -// // with type and categ -// $tt->getFromDBWithDatas($ticket_template, true); -// } - -// // Predefined fields from template : reset them -// if (isset($options['_predefined_fields'])) { -// $options['_predefined_fields'] -// = unserialize(rawurldecode(stripslashes($options['_predefined_fields']))); -// } else { -// $options['_predefined_fields'] = array(); -// } - -// // Store predefined fields to be able not to take into account on change template -// $predefined_fields = array(); - -// if (isset($tt->predefined) && count($tt->predefined)) { -// foreach ($tt->predefined as $predeffield => $predefvalue) { -// if (isset($options[$predeffield]) && isset($default_values[$predeffield])) { -// // Is always default value : not set -// // Set if already predefined field -// // Set if ticket template change -// if ($options[$predeffield] == $default_values[$predeffield] -// || (isset($options['_predefined_fields'][$predeffield]) -// && $options[$predeffield] == $options['_predefined_fields'][$predeffield]) -// || (isset($options['_tickettemplates_id']) -// && $options['_tickettemplates_id'] != $tt->getID())) { -// $options[$predeffield] = $predefvalue; -// $predefined_fields[$predeffield] = $predefvalue; -// } -// } else { // Not defined options set as hidden field -// echo ""; -// } -// } - -// } else { // No template load : reset predefined values -// if (count($options['_predefined_fields'])) { -// foreach ($options['_predefined_fields'] as $predeffield => $predefvalue) { -// if ($options[$predeffield] == $predefvalue) { -// $options[$predeffield] = $default_values[$predeffield]; -// } -// } -// } -// } -// unset($_SESSION["helpdeskSaved"]); - -// if ($CFG_GLPI['urgency_mask']==(1<<3) || $tt->isHiddenField('urgency')) { -// // Dont show dropdown if only 1 value enabled or field is hidden -// echo ""; -// } - -// // Display predefined fields if hidden -// if ($tt->isHiddenField('itemtype')) { -// echo ""; -// echo ""; -// } - -// echo ""; -// echo "
"; - -// echo ""; - -// echo ""; -// echo ""; -// echo ""; - -// echo ""; -// echo ""; - - -// if ($CFG_GLPI['urgency_mask']!=(1<<3)) { -// if (!$tt->isHiddenField('urgency')) { -// echo ""; -// echo ""; -// echo ""; -// } -// } - -// if (empty($delegating) && NotificationTargetTicket::isAuthorMailingActivatedForHelpdesk()) { -// echo ""; -// echo ""; -// echo ""; -// } - -// if ($_SESSION["glpiactiveprofile"]["helpdesk_hardware"] != 0) { -// if (!$tt->isHiddenField('itemtype')) { -// echo ""; -// echo ""; -// echo ""; -// } -// } - -// if (!$tt->isHiddenField('name') -// || $tt->isPredefinedField('name')) { -// echo ""; -// echo ""; -// echo ""; -// } - -// if (!$tt->isHiddenField('content') -// || $tt->isPredefinedField('content')) { -// echo ""; -// echo ""; -// echo ""; -// } -// echo ""; -// echo ""; - - -// echo ""; -// echo ""; - -// echo ""; - -// echo ""; -// echo ""; -// echo ""; - -// if (!$ticket_template) { -// echo ""; -// echo ""; -// } - -// echo "
".$caseInfo->processName." : "; -// if (Session::isMultiEntitiesMode()) { -// echo " (".Dropdown::getDropdownName("glpi_entities", $_SESSION["glpiactive_entity"]).")"; -// } -// echo "
".$LANG['joblist'][29]." :".$tt->getMandatoryMark('urgency').""; -// Ticket::dropdownUrgency("urgency", $options['urgency']); -// echo "
".$LANG['help'][8]." : "; -// if ($options["_users_id_requester"] == 0) { -// $options['_users_id_requester'] = Session::getLoginUserID(); -// } -// $_REQUEST['value'] = $options['_users_id_requester']; -// $_REQUEST['field'] = '_users_id_requester_notif'; -// $_REQUEST['use_notification'] = $options['_users_id_requester_notif']['use_notification']; -// include (GLPI_ROOT."/ajax/uemailUpdate.php"); - -// echo "
 "; -// echo "
"; -// $rand = rand(); -// $pmCaseUser = $caseInfo->currentUsers[0] ; // by default -// $paramsURL = "DEL_INDEX=".$pmCaseUser->delIndex."&action=".$caseInfo->caseStatus ; - -// echo ""; -// echo "
 "; -// echo "
".$LANG['document'][2]." (".Document::getMaxUploadSize().") : "; -// echo "".
-//            $LANG["; - -// echo " "; -// Ticket::showDocumentAddButton(60); - -// echo "
"; - -// echo "
"; -// if (!$ticket_template) { -// Html::closeForm(); -// } -//} - - -/** - * Print the helpdesk form - * - * @param $ID integer ID of the user who want to display the Helpdesk - * @param $ticket_template boolean ticket template for preview : false if not used for preview - * (false by default) - * - * @return nothing (print the helpdesk) - **/ -//function showFormHelpdesk($ID, $pmItem, $caseInfo, $ticket_template=false) { -// global $DB, $CFG_GLPI; - -// if (!Ticket::canCreate()) { -// return false; -// } - -// if (!$ticket_template -// && Session::haveRightsOr('ticketvalidation', TicketValidation::getValidateRights())) { - -// $opt = array(); -// $opt['reset'] = 'reset'; -// $opt['criteria'][0]['field'] = 55; // validation status -// $opt['criteria'][0]['searchtype'] = 'equals'; -// $opt['criteria'][0]['value'] = CommonITILValidation::WAITING; -// $opt['criteria'][0]['link'] = 'AND'; - -// $opt['criteria'][1]['field'] = 59; // validation aprobator -// $opt['criteria'][1]['searchtype'] = 'equals'; -// $opt['criteria'][1]['value'] = Session::getLoginUserID(); -// $opt['criteria'][1]['link'] = 'AND'; - -// $url_validate = $CFG_GLPI["root_doc"]."/front/ticket.php?".Toolbox::append_params($opt, -// '&'); - -// if (TicketValidation::getNumberToValidate(Session::getLoginUserID()) > 0) { -// echo "". -// __('Tickets awaiting approval')."

"; -// } -// } - -// $query = "SELECT `realname`, `firstname`, `name` -// FROM `glpi_users` -// WHERE `id` = '$ID'"; -// $result = $DB->query($query); - - -// $email = UserEmail::getDefaultForUser($ID); -// $default_use_notif = Entity::getUsedConfig('is_notif_enable_default', $_SESSION['glpiactive_entity'], '', 1); - -// // Set default values... -// $default_values = array('_users_id_requester_notif' -// => array('use_notification' -// => (($email == "")?0:$default_use_notif)), -// 'nodelegate' => 1, -// '_users_id_requester' => 0, -// '_users_id_observer' => 0, -// '_users_id_observer_notif' -// => array('use_notification' => $default_use_notif), -// 'name' => '', -// 'content' => '', -// 'itilcategories_id' => 0, -// 'locations_id' => 0, -// 'urgency' => 3, -// 'itemtype' => '', -// 'items_id' => 0, -// 'entities_id' => $_SESSION['glpiactive_entity'], -// 'plan' => array(), -// 'global_validation' => CommonITILValidation::NONE, -// '_add_validation' => 0, -// 'type' => Entity::getUsedConfig('tickettype', -// $_SESSION['glpiactive_entity'], -// '', Ticket::INCIDENT_TYPE), -// '_right' => "id", -// '_filename' => array(), -// '_tag_filename' => array()); - -// // Get default values from posted values on reload form -// if (!$ticket_template) { -// if (isset($_POST)) { -// $values = Html::cleanPostForTextArea($_POST); -// } -// } - -// $ticket = new Ticket(); -// // Restore saved value or override with page parameter -// if( !function_exists('restoreInput') ) { -// function restoreInput(Array $default=array()) { - -// if (isset($_SESSION['saveInput']['Ticket'])) { -// $saved = Html::cleanPostForTextArea($_SESSION['saveInput']['Ticket']); - -// // clear saved data when restored (only need once) -// unset($_SESSION['saveInput']['Ticket']); - -// return $saved; -// } - -// return $default; -// } -// } - -// $saved = restoreInput(); -// foreach ($default_values as $name => $value) { -// if (!isset($values[$name])) { -// if (isset($saved[$name])) { -// $values[$name] = $saved[$name]; -// } else { -// $values[$name] = $value; -// } -// } -// } - - -// if (!$ticket_template) { -// echo ""; -// } - - -// $delegating = User::getDelegateGroupsForUser($values['entities_id']); - -// if (count($delegating)) { -// echo "
"; -// echo ""; -// echo ""; - -// echo "
".__('This ticket concerns me')." "; - -// $rand = Dropdown::showYesNo("nodelegate", $values['nodelegate']); - -// $params = array('nodelegate' => '__VALUE__', -// 'rand' => $rand, -// 'right' => "delegate", -// '_users_id_requester' -// => $values['_users_id_requester'], -// '_users_id_requester_notif' -// => $values['_users_id_requester_notif'], -// 'use_notification' -// => $values['_users_id_requester_notif']['use_notification'], -// 'entity_restrict' -// => $_SESSION["glpiactive_entity"]); - -// Ajax::UpdateItemOnSelectEvent("dropdown_nodelegate".$rand, "show_result".$rand, -// $CFG_GLPI["root_doc"]."/ajax/dropdownDelegationUsers.php", -// $params); - -// $class = 'right'; -// if ($CFG_GLPI['use_check_pref'] && $values['nodelegate']) { -// echo "".__('Check your personnal information'); -// $class = 'center'; -// } - -// echo "
"; -// echo "
"; - -// $self = $ticket; -// if ($values["_users_id_requester"] == 0) { -// $values['_users_id_requester'] = Session::getLoginUserID(); -// } else { -// $values['_right'] = "delegate"; -// } -// $self->showActorAddFormOnCreate(CommonITILActor::REQUESTER, $values); -// echo "
"; -// if ($CFG_GLPI['use_check_pref'] && $values['nodelegate']) { -// echo "
"; -// User::showPersonalInformation(Session::getLoginUserID()); -// } -// echo "
"; -// echo ""; - -// } else { -// // User as requester -// $values['_users_id_requester'] = Session::getLoginUserID(); - -// if ($CFG_GLPI['use_check_pref']) { -// echo "
"; -// echo ""; -// echo ""; -// echo "
".__('Check your personnal information')."
"; -// User::showPersonalInformation(Session::getLoginUserID()); -// echo "
"; -// } -// } - -// echo ""; -// echo ""; - - -// // Load ticket template if available : -// $tt = $ticket->getTicketTemplateToUse($ticket_template, $values['type'], -// $values['itilcategories_id'], -// $_SESSION["glpiactive_entity"]); - -// // Predefined fields from template : reset them -// if (isset($values['_predefined_fields'])) { -// $values['_predefined_fields'] -// = Toolbox::decodeArrayFromInput($values['_predefined_fields']); -// } else { -// $values['_predefined_fields'] = array(); -// } - -// // Store predefined fields to be able not to take into account on change template -// $predefined_fields = array(); - -// if (isset($tt->predefined) && count($tt->predefined)) { -// foreach ($tt->predefined as $predeffield => $predefvalue) { -// if (isset($values[$predeffield]) && isset($default_values[$predeffield])) { -// // Is always default value : not set -// // Set if already predefined field -// // Set if ticket template change -// if (((count($values['_predefined_fields']) == 0) -// && ($values[$predeffield] == $default_values[$predeffield])) -// || (isset($values['_predefined_fields'][$predeffield]) -// && ($values[$predeffield] == $values['_predefined_fields'][$predeffield])) -// || (isset($values['_tickettemplates_id']) -// && ($values['_tickettemplates_id'] != $tt->getID()))) { -// $values[$predeffield] = $predefvalue; -// $predefined_fields[$predeffield] = $predefvalue; -// } -// } else { // Not defined options set as hidden field -// echo ""; -// } -// } -// // All predefined override : add option to say predifined exists -// if (count($predefined_fields) == 0) { -// $predefined_fields['_all_predefined_override'] = 1; -// } -// } else { // No template load : reset predefined values -// if (count($values['_predefined_fields'])) { -// foreach ($values['_predefined_fields'] as $predeffield => $predefvalue) { -// if ($values[$predeffield] == $predefvalue) { -// $values[$predeffield] = $default_values[$predeffield]; -// } -// } -// } -// } - -// if (($CFG_GLPI['urgency_mask'] == (1<<3)) -// || $tt->isHiddenField('urgency')) { -// // Dont show dropdown if only 1 value enabled or field is hidden -// echo ""; -// } - -// // Display predefined fields if hidden -// if ($tt->isHiddenField('itemtype')) { -// echo ""; -// echo ""; -// } -// if ($tt->isHiddenField('locations_id')) { -// echo ""; -// } -// echo ""; -// echo ""; -// echo "
"; - -// echo ""; - -// echo ""; -// echo ""; -// echo ""; - -// echo ""; -// echo ""; -// echo ""; - - -// if ($CFG_GLPI['urgency_mask'] != (1<<3)) { -// if (!$tt->isHiddenField('urgency')) { -// echo ""; -// echo ""; -// echo ""; -// } -// } - -// if (empty($delegating) -// && NotificationTargetTicket::isAuthorMailingActivatedForHelpdesk()) { -// echo ""; -// echo ""; -// echo ""; -// } -// if (($_SESSION["glpiactiveprofile"]["helpdesk_hardware"] != 0) -// && (count($_SESSION["glpiactiveprofile"]["helpdesk_item_type"]))) { -// if (!$tt->isHiddenField('itemtype')) { -// echo ""; -// echo ""; -// echo ""; -// } -// } - -// if (!$tt->isHiddenField('locations_id')) { -// echo ""; -// } - -// if (!$tt->isHiddenField('_users_id_observer') -// || $tt->isPredefinedField('_users_id_observer')) { -// echo ""; -// echo ""; -// } - - -// if (!$tt->isHiddenField('name') -// || $tt->isPredefinedField('name')) { -// echo ""; -// echo ""; -// } - -// if (!$tt->isHiddenField('content') -// || $tt->isPredefinedField('content')) { -// echo ""; -// echo ""; -// } - - -// echo ""; -// echo ""; - - -// // File upload system -// $width = '100%'; -// if ($CFG_GLPI['use_rich_text']) { -// $width = '50%'; -// } -// echo ""; -// echo ""; -// echo ""; -// echo ""; - -// echo ""; -// echo ""; -// echo ""; - - - -// if (!$ticket_template) { -// echo ""; -// echo ""; -// } - -// echo "
".$caseInfo->processName.""; -// //echo "
".__('Describe the incident or request').""; -// if (Session::isMultiEntitiesMode()) { -// echo "(".Dropdown::getDropdownName("glpi_entities", $_SESSION["glpiactive_entity"]).")"; -// } -// echo "
".sprintf(__('%1$s%2$s'), __('Urgency'), $tt->getMandatoryMark('urgency')). -// ""; -// Ticket::dropdownUrgency(array('value' => $values["urgency"])); -// echo "
".__('Inform me about the actions taken').""; -// if ($values["_users_id_requester"] == 0) { -// $values['_users_id_requester'] = Session::getLoginUserID(); -// } -// $_POST['value'] = $values['_users_id_requester']; -// $_POST['field'] = '_users_id_requester_notif'; -// $_POST['use_notification'] = $values['_users_id_requester_notif']['use_notification']; -// include (GLPI_ROOT."/ajax/uemailUpdate.php"); - -// echo "
".__('Watcher').""; -// $values['_right'] = "groups"; - -// if (!$tt->isHiddenField('_users_id_observer')) { -// // Observer -// $rand_observer = $ticket->showActorAddFormOnCreate(CommonITILActor::OBSERVER, $values); -// echo '
'; - -// echo ""; -// Ajax::updateItemOnSelectEvent("dropdown__users_id_observer[]$rand_observer", -// "observer_$rand_observer", -// $CFG_GLPI["root_doc"]."/ajax/helpdesk_observer.php", -// $values); - -// } else { // predefined value -// if (isset($values["_users_id_observer"]) && $values["_users_id_observer"]) { -// echo Ticket::getActorIcon('user', CommonITILActor::OBSERVER)." "; -// echo Dropdown::getDropdownName("glpi_users", $values["_users_id_observer"]); -// echo ""; -// echo '
'; -// } -// } -// echo "
".sprintf(__('%1$s%2$s'), __('Title'), $tt->getMandatoryMark('name')).""; -// if (!$tt->isHiddenField('name')) { -// echo ""; -// } else { -// echo $values['name']; -// echo ""; -// } -// echo "
".sprintf(__('%1$s%2$s'), __('Description'), $tt->getMandatoryMark('content')). -// ""; -// $rand = mt_rand(); -// $rand_text = mt_rand(); - -// $cols = 90; -// $rows = 6; -// $content_id = "content$rand"; - -// //if ($CFG_GLPI["use_rich_text"]) { -// // $values["content"] = $ticket->setRichTextContent($content_id, $values["content"], $rand); -// // $cols = 100; -// // $rows = 10; -// //} else { -// $values["content"] = $ticket->setSimpleTextContent($values["content"]); -// //} - -// echo "
"; -// echo "
"; -// echo "
"; -// $rand = rand(); -// $pmCaseUser = $caseInfo->currentUsers[0] ; // by default -// $paramsURL = "DEL_INDEX=".$pmCaseUser->delIndex."&action=".$caseInfo->caseStatus ; -// echo ""; -// echo "
".sprintf(__('%1$s (%2$s)'), __('File'), Document::getMaxUploadSize()); -// DocumentType::showAvailableTypesLink(); -// echo ""; -// echo "
"; -// echo "
"; -// echo ""; -// echo ""; -// if ($CFG_GLPI['use_rich_text']) { -// echo ""; -// } -// echo "
"; - -// echo Html::file(array('multiple' => true, -// 'values' => array('filename' => $values['_filename'], -// 'tag' => $values['_tag_filename']) -// )); -// // "
"; -// echo "
"; -// if (!isset($rand)) { -// $rand = mt_rand(); -// } -// echo Html::imagePaste(array('rand' => $rand)); -// echo "
"; - -// echo "
"; -// if (!$ticket_template) { -// Html::closeForm(); -// } -//} - - function showFormHelpdesk($ID, $pmItem, $caseInfo, $ticket_template=false) { global $DB, $CFG_GLPI; @@ -947,7 +101,7 @@ function showFormHelpdesk($ID, $pmItem, $caseInfo, $ticket_template=false) { $ticket = new Ticket(); // Restore saved value or override with page parameter - if( !function_exists('restoreInput') ) { + if (!function_exists('restoreInput')) { function restoreInput(Array $default=array()) { if (isset($_SESSION['saveInput']['Ticket'])) { @@ -1001,7 +155,6 @@ function showFormHelpdesk($ID, $pmItem, $caseInfo, $ticket_template=false) { $CFG_GLPI["root_doc"]."/front/tracking.injector.php' enctype='multipart/form-data'>"; } - $delegating = User::getDelegateGroupsForUser($values['entities_id']); if (count($delegating)) { @@ -1036,7 +189,6 @@ function showFormHelpdesk($ID, $pmItem, $caseInfo, $ticket_template=false) { echo "
"; echo "
"; - $self = $ticket; // new self(); if ($values["_users_id_requester"] == 0) { $values['_users_id_requester'] = Session::getLoginUserID(); @@ -1072,7 +224,6 @@ function showFormHelpdesk($ID, $pmItem, $caseInfo, $ticket_template=false) { echo ""; - // Load ticket template if available : $tt = $ticket->getTicketTemplateToUse($ticket_template, $values['type'], $values['itilcategories_id'], @@ -1146,9 +297,8 @@ function showFormHelpdesk($ID, $pmItem, $caseInfo, $ticket_template=false) { echo ""; echo "
"; - echo ""; - if ($CFG_GLPI['urgency_mask'] != (1<<3)) { if (!$tt->isHiddenField('urgency')) { echo ""; @@ -1247,7 +396,7 @@ function showFormHelpdesk($ID, $pmItem, $caseInfo, $ticket_template=false) { if (!$tt->isHiddenField('_users_id_observer')) { // Observer - if($tt->isPredefinedField('_users_id_observer') + if ($tt->isPredefinedField('_users_id_observer') && !is_array($values['_users_id_observer'])) { //convert predefined value to array @@ -1260,11 +409,10 @@ function showFormHelpdesk($ID, $pmItem, $caseInfo, $ticket_template=false) { $values['_users_id_observer_notif']['use_notification'][1] = 1; } - echo "
"; if (isset($values['_users_id_observer'])) { $observers = $values['_users_id_observer']; - foreach($observers as $index_observer => $observer) { + foreach ($observers as $index_observer => $observer) { $options = array_merge($values, array('_user_index' => $index_observer)); Ticket::showFormHelpdeskObserver($options); } @@ -1283,7 +431,6 @@ function showFormHelpdesk($ID, $pmItem, $caseInfo, $ticket_template=false) { echo "
"; } - if (!$tt->isHiddenField('name') || $tt->isPredefinedField('name')) { echo ""; @@ -1310,17 +457,7 @@ function showFormHelpdesk($ID, $pmItem, $caseInfo, $ticket_template=false) { $rows = 6; $content_id = "content$rand"; - //if ($CFG_GLPI["use_rich_text"]) { - // $values["content"] = $ticket->setRichTextContent($content_id, $values["content"], $rand); - - - - // $cols = 100; - // $rows = 10; - //} else { - $values["content"] = $ticket->setSimpleTextContent($values["content"]); - - //} + $values["content"] = $ticket->setSimpleTextContent($values["content"]); echo "
"; echo "
"; + $this->fields["comment"].""; echo ""; echo ""; echo ""; //echo ""; @@ -443,19 +445,19 @@ class PluginProcessmakerProcess extends CommonDBTM { echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; @@ -506,125 +510,121 @@ class PluginProcessmakerProcess extends CommonDBTM { echo Html::convDateTime($this->fields["date_mod"]); echo ""; - $this->showFormButtons($options ); //$this->addDivForTabs(); - } + } - /** - * Execute the query to select box with all glpi users where select key = name - * - * Internaly used by showGroup_Users, dropdownUsers and ajax/dropdownUsers.php - * - * @param $count true if execute an count(*), - * @param $search pattern - * - * @return mysql result set. - **/ - static function getSqlSearchResult ($count=true, $search='') { - global $DB, $CFG_GLPI; + /** + * Execute the query to select box with all glpi users where select key = name + * + * Internaly used by showGroup_Users, dropdownUsers and ajax/dropdownUsers.php + * + * @param $count true if execute an count(*), + * @param $search pattern + * + * @return mysql result set. + **/ + static function getSqlSearchResult ($count=true, $search='') { + global $DB, $CFG_GLPI; - $orderby = '' ; + $orderby = ''; - $where = ' WHERE glpi_plugin_processmaker_processes.is_active=1 ' ; + $where = ' WHERE glpi_plugin_processmaker_processes.is_active=1 '; - if( $count ) { - $fields = " COUNT(DISTINCT glpi_plugin_processmaker_processes.id) AS cpt " ; - } else { - $fields = " DISTINCT glpi_plugin_processmaker_processes.* " ; - $orderby = " ORDER BY glpi_plugin_processmaker_processes.name ASC" ; - } + if ($count) { + $fields = " COUNT(DISTINCT glpi_plugin_processmaker_processes.id) AS cpt "; + } else { + $fields = " DISTINCT glpi_plugin_processmaker_processes.* "; + $orderby = " ORDER BY glpi_plugin_processmaker_processes.name ASC"; + } - if( strlen($search)>0 && $search!=$CFG_GLPI["ajax_wildcard"] ) - { - $where .= " AND (glpi_plugin_processmaker_processes.name $search - OR glpi_plugin_processmaker_processes.comment $search) " ; - } + if (strlen($search)>0 && $search!=$CFG_GLPI["ajax_wildcard"]) { + $where .= " AND (glpi_plugin_processmaker_processes.name $search + OR glpi_plugin_processmaker_processes.comment $search) "; + } + $query = "SELECT $fields FROM glpi_plugin_processmaker_processes ".$where." ".$orderby.";"; - $query = "SELECT $fields FROM glpi_plugin_processmaker_processes ".$where." ".$orderby.";" ; + return $DB->query($query); + } + /** + * Summary of getProcessName + * @param mixed $pid + * @param mixed $link + * @return mixed + */ + static function getProcessName( $pid, $link=0 ) { + global $DB; + $process=''; + if ($link==2) { + $process = array("name" => "", + "link" => "", + "comment" => ""); + } - return $DB->query($query); - } + $query="SELECT * FROM glpi_plugin_processmaker_processes WHERE id=$pid"; + $result = $DB->query($query); + if ($result && $DB->numrows($result)==1) { + $data = $DB->fetch_assoc($result); + $processname = $data["name"]; + if ($link==2) { + $process["name"] = $processname; + $process["link"] = $CFG_GLPI["root_doc"]."/plugins/processmaker/front/process.form.php?id=".$pid; + $process["comment"] = __('Name')." : ".$processname."
".__('Comments'). + " : ".$data["comment"]."
"; + } else { + $process = $processname; + } - /** - * Summary of getProcessName - * @param mixed $pid - * @param mixed $link - * @return mixed - */ - static function getProcessName( $pid, $link=0 ) { - global $DB; - $process=''; - if ($link==2) { - $process = array("name" => "", - "link" => "", - "comment" => ""); - } + } + return $process; + } - $query="SELECT * FROM glpi_plugin_processmaker_processes WHERE id=$pid"; - $result = $DB->query($query); - if ($result && $DB->numrows($result)==1) { - $data = $DB->fetch_assoc($result); - $processname = $data["name"] ; - if ($link==2) { - $process["name"] = $processname ; - $process["link"] = $CFG_GLPI["root_doc"]."/plugins/processmaker/front/process.form.php?id=".$pid; - $process["comment"] = __('Name')." : ".$processname."
".__('Comments'). - " : ".$data["comment"]."
"; - } else { - $process = $processname ; - } + /** + * retrieve the entities allowed to a process for a profile + * + * @param $processes_id Integer ID of the process + * @param $profiles_id Integer ID of the profile + * @param $child Boolean when true, include child entity when recursive right + * + * @return Array of entity ID + */ + static function getEntitiesForProfileByProcess($processes_id, $profiles_id, $child=false) { + global $DB; - } - return $process; - } - - /** - * retrieve the entities allowed to a process for a profile - * - * @param $processes_id Integer ID of the process - * @param $profiles_id Integer ID of the profile - * @param $child Boolean when true, include child entity when recursive right - * - * @return Array of entity ID - */ - static function getEntitiesForProfileByProcess($processes_id, $profiles_id, $child=false) { - global $DB; - - $query = "SELECT `entities_id`, `is_recursive` + $query = "SELECT `entities_id`, `is_recursive` FROM `glpi_plugin_processmaker_processes_profiles` WHERE `processes_id` = '$processes_id' AND `profiles_id` = '$profiles_id'"; - $entities = array(); - foreach ($DB->request($query) as $data) { - if ($child && $data['is_recursive']) { - foreach (getSonsOf('glpi_entities', $data['entities_id']) as $id) { - $entities[$id] = $id; - } - } else { - $entities[$data['entities_id']] = $data['entities_id']; + $entities = array(); + foreach ($DB->request($query) as $data) { + if ($child && $data['is_recursive']) { + foreach (getSonsOf('glpi_entities', $data['entities_id']) as $id) { + $entities[$id] = $id; } - } - return $entities; - } + } else { + $entities[$data['entities_id']] = $data['entities_id']; + } + } + return $entities; + } - /** - * Summary of dropdown - * @param mixed $options - * @return mixed - */ - static function dropdown($options=array()) { - global $CFG_GLPI; - $options['url'] = $CFG_GLPI["root_doc"].'/plugins/processmaker/ajax/dropdownProcesses.php' ; - return Dropdown::show( __CLASS__, $options ) ; + /** + * Summary of dropdown + * @param mixed $options + * @return mixed + */ + static function dropdown($options=array()) { + global $CFG_GLPI; + $options['url'] = $CFG_GLPI["root_doc"].'/plugins/processmaker/ajax/dropdownProcesses.php'; + return Dropdown::show( __CLASS__, $options ); - } + } } diff --git a/inc/process_profile.class.php b/inc/process_profile.class.php index 093c86c..b789a6d 100644 --- a/inc/process_profile.class.php +++ b/inc/process_profile.class.php @@ -10,50 +10,50 @@ */ class PluginProcessmakerProcess_Profile extends CommonDBTM { - function can($ID, $right, array &$input = NULL) { - return Session::haveRight('plugin_processmaker_config', $right) ; - } - - function getTabNameForItem( CommonGLPI $item, $withtemplate=0) { - global $LANG; - return $LANG['processmaker']['title'][4]; - } - - static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) { + function can($ID, $right, array &$input = NULL) { + return Session::haveRight('plugin_processmaker_config', $right); + } - global $DB,$CFG_GLPI, $LANG; + function getTabNameForItem( CommonGLPI $item, $withtemplate=0) { + global $LANG; + return $LANG['processmaker']['title'][4]; + } - $ID = $item->getField('id'); + static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) { - $canshowentity = Session::haveRight("entity", READ); - $canedit = Session::haveRight('plugin_processmaker_config', UPDATE) ; - - $rand=mt_rand(); + global $DB,$CFG_GLPI, $LANG; - if ($canedit) { - echo "
"; - echo ""; - echo "
".$caseInfo->processName.""; - //echo "
".__('Describe the incident or request').""; + if (Session::isMultiEntitiesMode()) { echo "(".Dropdown::getDropdownName("glpi_entities", $_REQUEST['entities_id']).")"; } @@ -1187,7 +337,6 @@ function showFormHelpdesk($ID, $pmItem, $caseInfo, $ticket_template=false) { ITILCategory::dropdown($opt); echo "
".$LANG['processmaker']['process']['process_guid']." :"; @@ -433,7 +435,7 @@ class PluginProcessmakerProcess extends CommonDBTM { echo "
".__("Active")." :"; - Dropdown::showYesNo("is_active",$this->fields["is_active"]); + Dropdown::showYesNo("is_active", $this->fields["is_active"]); echo "
".$LANG['processmaker']['process']['hide_case_num_title']." :"; - Dropdown::showYesNo("hide_case_num_title",$this->fields["hide_case_num_title"]); + Dropdown::showYesNo("hide_case_num_title", $this->fields["hide_case_num_title"]); echo "
".$LANG['processmaker']['process']['insert_task_comment']." :"; - Dropdown::showYesNo("insert_task_comment",$this->fields["insert_task_comment"]); + Dropdown::showYesNo("insert_task_comment", $this->fields["insert_task_comment"]); echo "
".$LANG['processmaker']['process']['type']." :"; if (true) { // $canupdate || !$ID $idticketcategorysearch = mt_rand(); $opt = array('value' => $this->fields["type"]); - $rand = $idtype = Ticket::dropdownType('type', $opt, array(),array('toupdate' => "search_".$idticketcategorysearch )); + $rand = $idtype = Ticket::dropdownType('type', $opt, array(), array('toupdate' => "search_".$idticketcategorysearch )); $opt = array('value' => $this->fields["type"]); $params = array('type' => '__VALUE__', //'entity_restrict' => -1, //$this->fields['entities_id'], @@ -471,24 +473,26 @@ class PluginProcessmakerProcess extends CommonDBTM { echo "".$LANG['processmaker']['process']['itilcategory']." :"; - if (true ) { // $canupdate || !$ID || $canupdate_descr + if (true) { // $canupdate || !$ID || $canupdate_descr $opt = array('value' => $this->fields["itilcategories_id"]); - switch ($this->fields['type']) { - case Ticket::INCIDENT_TYPE : - $opt['condition'] = "`is_incident`='1'"; - break; + switch ($this->fields['type']) { + case Ticket::INCIDENT_TYPE : + $opt['condition'] = "`is_incident`='1'"; + break; - case Ticket::DEMAND_TYPE : - $opt['condition'] = "`is_request`='1'"; - break; + case Ticket::DEMAND_TYPE : + $opt['condition'] = "`is_request`='1'"; + break; - default : - break; - } + default : + break; + } echo ""; - if( isset($idticketcategorysearch) ) $opt['rand'] = $idticketcategorysearch; + if (isset($idticketcategorysearch)) { + $opt['rand'] = $idticketcategorysearch; + } Dropdown::show('ITILCategory', $opt); echo ""; } else { @@ -498,7 +502,7 @@ class PluginProcessmakerProcess extends CommonDBTM { echo "
".$LANG['processmaker']['process']['project_type']." :"; - Dropdown::showFromArray( 'project_type', array( 'classic' => $LANG['processmaker']['process']['project_type_classic'], 'bpmn' => $LANG['processmaker']['process']['project_type_bpmn'] ), array( 'value' => $this->fields["project_type"] ) ) ; + Dropdown::showFromArray( 'project_type', array( 'classic' => $LANG['processmaker']['process']['project_type_classic'], 'bpmn' => $LANG['processmaker']['process']['project_type_bpmn'] ), array( 'value' => $this->fields["project_type"] ) ); echo "
"; - echo ""; + $ID = $item->getField('id'); - echo ""; + $canshowentity = Session::haveRight("entity", READ); + $canedit = Session::haveRight('plugin_processmaker_config', UPDATE); - echo "
".$LANG['processmaker']['title'][4]."
"; - echo ""; - Entity::Dropdown( array('entity' => $_SESSION['glpiactiveentities'])); - echo "".Profile::getTypeName(1).""; - Profile::dropdownUnder(array('value' => Profile::getDefault())); - echo "".__('Recursive').""; - Dropdown::showYesNo("is_recursive",0); - echo ""; - echo ""; - echo "
"; - Html::closeForm(); - echo "
"; - } + $rand=mt_rand(); - $query = "SELECT DISTINCT `glpi_plugin_processmaker_processes_profiles`.`id` AS linkID, + if ($canedit) { + echo "
"; + echo ""; + echo ""; + echo ""; + + echo ""; + + echo "
".$LANG['processmaker']['title'][4]."
"; + echo ""; + Entity::Dropdown( array('entity' => $_SESSION['glpiactiveentities'])); + echo "".Profile::getTypeName(1).""; + Profile::dropdownUnder(array('value' => Profile::getDefault())); + echo "".__('Recursive').""; + Dropdown::showYesNo("is_recursive", 0); + echo ""; + echo ""; + echo "
"; + Html::closeForm(); + echo "
"; + } + + $query = "SELECT DISTINCT `glpi_plugin_processmaker_processes_profiles`.`id` AS linkID, `glpi_profiles`.`id`, `glpi_profiles`.`name`, `glpi_plugin_processmaker_processes_profiles`.`is_recursive`, @@ -66,103 +66,102 @@ class PluginProcessmakerProcess_Profile extends CommonDBTM ON (`glpi_plugin_processmaker_processes_profiles`.`entities_id` = `glpi_entities`.`id`) WHERE `glpi_plugin_processmaker_processes_profiles`.`processes_id` = '$ID' ORDER BY `glpi_profiles`.`name`, `glpi_entities`.`completename`"; - $result = $DB->query($query); - $num = $DB->numrows($result); + $result = $DB->query($query); + $num = $DB->numrows($result); - echo "
"; - Html::openMassiveActionsForm('mass'.__CLASS__.$rand); + echo "
"; + Html::openMassiveActionsForm('mass'.__CLASS__.$rand); - if ($canedit && $num) { - $massiveactionparams = array('num_displayed' => $num, - 'container' => 'mass'.__CLASS__.$rand); - Html::showMassiveActions($massiveactionparams); - } + if ($canedit && $num) { + $massiveactionparams = array('num_displayed' => $num, + 'container' => 'mass'.__CLASS__.$rand); + Html::showMassiveActions($massiveactionparams); + } + if ($num > 0) { + echo ""; + $header_begin = ""; + $header_top = ''; + $header_bottom = ''; + $header_end = ''; + if ($canedit) { + $header_begin .= ""; + } + $header_end .= ""; + $header_end .= ""; + echo $header_begin.$header_top.$header_end; - if ($num > 0) { - echo "
"; + $header_top .= Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand); + $header_bottom .= Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand); + $header_end .= ""._n('Entity', 'Entities', Session::getPluralNumber())."".sprintf(__('%1$s (%2$s)'), Profile::getTypeName(Session::getPluralNumber()), + __('D=Dynamic, R=Recursive')); + $header_end .= "
"; - $header_begin = ""; - $header_top = ''; - $header_bottom = ''; - $header_end = ''; + while ($data = $DB->fetch_assoc($result)) { + echo ""; if ($canedit) { - $header_begin .= ""; - } - $header_end .= ""; - $header_end .= ""; - echo $header_begin.$header_top.$header_end; - - while ($data = $DB->fetch_assoc($result)) { - echo ""; - if ($canedit) { - echo ""; - } - echo ""; - - if (Profile::canView()) { - $entname = "". - $data["name"].""; - } else { - $entname = $data["name"]; - } - -// if ($data["is_dynamic"] || $data["is_recursive"]) { - if ($data["is_recursive"]) { - $entname = sprintf(__('%1$s %2$s'), $entname, "("); - //if ($data["is_dynamic"]) { - // //TRANS: letter 'D' for Dynamic - // $entname = sprintf(__('%1$s%2$s'), $entname, __('D')); - //} - //if ($data["is_dynamic"] && $data["is_recursive"]) { - // $entname = sprintf(__('%1$s%2$s'), $entname, ", "); - //} - if ($data["is_recursive"]) { - //TRANS: letter 'R' for Recursive - $entname = sprintf(__('%1$s%2$s'), $entname, __('R')); - } - $entname = sprintf(__('%1$s%2$s'), $entname, ")"); - } - echo ""; - echo ""; } - echo $header_begin.$header_bottom.$header_end; - echo "
"; - $header_top .= Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand); - $header_bottom .= Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand); - $header_end .= ""._n('Entity', 'Entities', Session::getPluralNumber())."".sprintf(__('%1$s (%2$s)'), Profile::getTypeName(Session::getPluralNumber()), - __('D=Dynamic, R=Recursive')); - $header_end .= "
"; - if (in_array($data["entities_id"], $_SESSION['glpiactiveentities'])) { - Html::showMassiveActionCheckBox(__CLASS__, $data["linkID"]); - } else { - echo " "; - } - echo ""; - - $link = $data["completename"]; - if ($_SESSION["glpiis_ids_visible"]) { - $link = sprintf(__('%1$s (%2$s)'), $link, $data["entities_id"]); - } - - if ($canshowentity) { - echo ""; - } - echo $link.($canshowentity ? "" : ''); + echo ""; + if (in_array($data["entities_id"], $_SESSION['glpiactiveentities'])) { + Html::showMassiveActionCheckBox(__CLASS__, $data["linkID"]); + } else { + echo " "; + } echo "".$entname."
"; - } else { - echo ""; - echo ""; - echo "
".__('No item found')."
\n"; - } + echo "
"; - if ($canedit && $num) { - $massiveactionparams['ontop'] = false; - Html::showMassiveActions($massiveactionparams); - } - Html::closeForm(); - echo ""; - } + $link = $data["completename"]; + if ($_SESSION["glpiis_ids_visible"]) { + $link = sprintf(__('%1$s (%2$s)'), $link, $data["entities_id"]); + } + + if ($canshowentity) { + echo ""; + } + echo $link.($canshowentity ? "" : ''); + echo "".$entname."
"; + } else { + echo ""; + echo ""; + echo "
".__('No item found')."
\n"; + } + + if ($canedit && $num) { + $massiveactionparams['ontop'] = false; + Html::showMassiveActions($massiveactionparams); + } + Html::closeForm(); + echo "
"; + } //static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids) { // global $CFG_GLPI; @@ -187,5 +186,5 @@ class PluginProcessmakerProcess_Profile extends CommonDBTM // break ; // } //} - + } diff --git a/inc/processmaker.class.php b/inc/processmaker.class.php index 926896b..6055974 100644 --- a/inc/processmaker.class.php +++ b/inc/processmaker.class.php @@ -1,7 +1,7 @@ $value) { - if(is_array($value)) { - $temp = array() ; - foreach($value as $k2 => $val2){ - $temp[ $key.'['.$k2.']' ] = $val2 ; - } - $vars = array_merge( $vars, http_formdata_flat_hierarchy($temp) ); +if (!function_exists('http_formdata_flat_hierarchy')) { + /** + * Summary of http_formdata_flat_hierarchy + * @param mixed $data + * @return array + */ + function http_formdata_flat_hierarchy($data) { + $vars=array(); + foreach ($data as $key=>$value) { + if (is_array($value)) { + $temp = array(); + foreach ($value as $k2 => $val2) { + $temp[ $key.'['.$k2.']' ] = $val2; } - else { - $vars[$key]=$value; - } - } - return $vars; - } + $vars = array_merge( $vars, http_formdata_flat_hierarchy($temp) ); + } else { + $vars[$key]=$value; + } + } + return $vars; + } } -if( !function_exists('stripcslashes_deep') ){ - /** - * Strip c slash for variable & array - * - * @param $value array or string: item to stripslashes (array or string) - * - * @return stripcslashes item +if (!function_exists('stripcslashes_deep')) { + /** + * Strip c slash for variable & array + * + * @param $value array or string: item to stripslashes (array or string) + * + * @return stripcslashes item **/ function stripcslashes_deep($value) { @@ -78,892 +77,849 @@ if( !function_exists('stripcslashes_deep') ){ */ class PluginProcessmakerProcessmaker extends CommonDBTM { + var $serverURL; -// const serverURL = "http://localhost:8080/sysworkflow/en/classic" ; - var $serverURL ; - //var $database ; - var $config ; - private $pmSoapClient = null ; - private $pmWorkspace = "" ; - private $pmAdminSession = false ; - //var $pmSession = '' ; - private $taskWriter = 0 ; - private $pm_group_guid = '' ; // guid for default user group in Process Maker is used for all GLPI user synchronization into ProcessMaker - var $lasterror; - var $lang; + var $config; + private $pmSoapClient = null; + private $pmWorkspace = ""; + private $pmAdminSession = false; + + private $taskWriter = 0; + private $pm_group_guid = ''; // guid for default user group in Process Maker is used for all GLPI user synchronization into ProcessMaker + var $lasterror; + var $lang; - /** - * Return the table used to store this object - * - * @return string - **/ - static function getTable() { + /** + * Return the table used to store this object + * + * @return string + **/ + static function getTable() { - return "glpi_plugin_processmaker_processes"; - } + return "glpi_plugin_processmaker_processes"; + } - /** - * Summary of addTicketFollowup - * @param mixed $itemId - * @param mixed $txtForFollowup - * @param integer $users_id optional, if null will uses logged-in user - */ - public function addTicketFollowup( $itemId, $txtForFollowup, $users_id=null ) { - $fu = new TicketFollowup() ; - $fu->getEmpty() ; // to get default values - $input = $fu->fields ; - if( isset( $txtForFollowup['GLPI_TICKET_FOLLOWUP_CONTENT'] ) ) { + /** + * Summary of addTicketFollowup + * @param mixed $itemId + * @param mixed $txtForFollowup + * @param integer $users_id optional, if null will uses logged-in user + */ + public function addTicketFollowup( $itemId, $txtForFollowup, $users_id=null ) { + $fu = new TicketFollowup(); + $fu->getEmpty(); // to get default values + $input = $fu->fields; + if (isset( $txtForFollowup['GLPI_TICKET_FOLLOWUP_CONTENT'] )) { $input['content']=$txtForFollowup['GLPI_TICKET_FOLLOWUP_CONTENT']; } - if( isset( $txtForFollowup['GLPI_TICKET_FOLLOWUP_IS_PRIVATE'] ) ) { + if (isset( $txtForFollowup['GLPI_TICKET_FOLLOWUP_IS_PRIVATE'] )) { $input['is_private']=$txtForFollowup['GLPI_TICKET_FOLLOWUP_IS_PRIVATE']; } - if( isset( $txtForFollowup['GLPI_TICKET_FOLLOWUP_REQUESTTYPES_ID'] ) ) { + if (isset( $txtForFollowup['GLPI_TICKET_FOLLOWUP_REQUESTTYPES_ID'] )) { $input['requesttypes_id']=$txtForFollowup['GLPI_TICKET_FOLLOWUP_REQUESTTYPES_ID']; } $input['tickets_id']=$itemId; - $input['users_id']= (isset($users_id) ? $users_id : Session::getLoginUserID( true )) ; // $this->taskWriter; + $input['users_id']= (isset($users_id) ? $users_id : Session::getLoginUserID( true )); // $this->taskWriter; - $fu->add( $input ) ; - } + $fu->add( $input ); + } - /** - * Summary of openSoap - * @return true if open succeeded, and pmSoapClient is initialized - * false otherwise - */ - private function openSoap( ) { - //global $DB; - try { - if( $this->pmSoapClient == null ) { - $this->lang = substr( $_SESSION["glpilanguage"], 0, 2) ; - if( strlen( $this->lang ) <> 2 ) { - $this->lang = "en" ; // by default - } - $this->config = PluginProcessmakerConfig::getInstance() ; - $this->pmWorkspace = $this->config->fields['pm_workspace'] ; - $this->serverURL = trim($this->config->fields['pm_server_URL'],'/').'/sys'.$this->config->fields['pm_workspace'].'/'.$this->lang.'/'.$this->config->fields['pm_theme'] ; - $this->taskWriter = $this->config->fields['users_id'] ; - $this->pm_group_guid = $this->config->fields['pm_group_guid'] ; - $this->pmSoapClient = new SoapClient($this->serverURL."/services/wsdl2", array( 'soap_version' => SOAP_1_2, 'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP) ); + /** + * Summary of openSoap + * @return true if open succeeded, and pmSoapClient is initialized + * false otherwise + */ + private function openSoap( ) { + + try { + if ($this->pmSoapClient == null) { + $this->lang = substr( $_SESSION["glpilanguage"], 0, 2); + if (strlen( $this->lang ) <> 2) { + $this->lang = "en"; // by default } + $this->config = PluginProcessmakerConfig::getInstance(); + $this->pmWorkspace = $this->config->fields['pm_workspace']; + $this->serverURL = trim($this->config->fields['pm_server_URL'], '/').'/sys'.$this->config->fields['pm_workspace'].'/'.$this->lang.'/'.$this->config->fields['pm_theme']; + $this->taskWriter = $this->config->fields['users_id']; + $this->pm_group_guid = $this->config->fields['pm_group_guid']; + $this->pmSoapClient = new SoapClient($this->serverURL."/services/wsdl2", array( 'soap_version' => SOAP_1_2, 'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP) ); + } - return true ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - $this->lasterror = $e; - return false ; //null ; - } - } + return true; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + $this->lasterror = $e; + return false; //null ; + } + } - - //function getSearchOptions() { - // global $LANG; - - // $tab = array(); - // $tab['common'] = "Header Needed"; - - // $tab[1001]['table'] = 'glpi_plugin_processmaker_cases'; - // $tab[1001]['field'] = 'case_status'; - // $tab[1001]['name'] = 'Case - Status' ; //$LANG['plugin_example']["name"]; - - // //$tab[2]['table'] = 'glpi_plugin_example_dropdowns'; - // //$tab[2]['field'] = 'name'; - // //$tab[2]['name'] = 'Dropdown'; - - // //$tab[3]['table'] = 'glpi_plugin_example_examples'; - // //$tab[3]['field'] = 'serial'; - // //$tab[3]['name'] = 'Serial'; - // //$tab[3]['usehaving'] = true; - // //$tab[3]['searchtype'] = 'equals'; - - // //$tab[30]['table'] = 'glpi_plugin_example_examples'; - // //$tab[30]['field'] = 'id'; - // //$tab[30]['name'] = $LANG["common"][2]; - - // return $tab; - //} - - - /** - * Summary of login - * @param mixed $admin_or_user if true will be admin, otherwise is user name (or user id), or current user - * @return true if login has been correctly done with current GLPI user, or if a PM session was already open - * false if an exception occured (like SOAP error or PM login error) - */ - function login( $admin_or_user=false ) { - global $DB, $PM_DB; - //unset($_SESSION["pluginprocessmaker"]["session"]["date"]) ; - try { - $locSession = new stdClass; // by default empty object - if( $this->openSoap( ) ) { - $cookie_lifetime = ini_get('session.cookie_lifetime') ; - if( $cookie_lifetime == 0 ) { - $cookie_lifetime = 15 * 60 ; //= 15 minutes - } - if( $admin_or_user === true ) { // admin rights has been requested, then force new login - $config = PluginProcessmakerConfig::getInstance() ; - $locSession = $this->pmSoapClient->login( array( 'userid' => $config->fields['pm_admin_user'], 'password' => Toolbox::decrypt($config->fields['pm_admin_passwd'], GLPIKEY)) ) ; - if( is_object( $locSession ) && $locSession->status_code == 0 ) { - $_SESSION["pluginprocessmaker"]["session"]["admin"] = true ; - $_SESSION["pluginprocessmaker"]["session"]["id"] = $locSession->message ; - $_SESSION["pluginprocessmaker"]["session"]["date"] = $locSession->timestamp ; - $this->pmAdminSession = true ; - return true ; - } - } elseif( empty($_SESSION["pluginprocessmaker"]["session"]["date"]) || ($_SESSION["pluginprocessmaker"]["session"]["admin"] == true) - || $this->pmAdminSession == true - || date_add( date_create( $_SESSION["pluginprocessmaker"]["session"]["date"] ), new DateInterval( "PT".$cookie_lifetime."S" ) ) < date_create( date( "Y-m-d H:i:s" ) ) ){ - // get the password of the user - $pmusr = new PluginProcessmakerUser ; - $gusr = new User ; - if( is_numeric($admin_or_user) ) { - $gusr->getFromDB( $admin_or_user ) ; - } else { - $gusr->getFromDBbyName( $admin_or_user !== false ? $admin_or_user : $_SESSION["glpiname"]) ; - } - $pmusr->getFromDB( $gusr->getID() ) ; - if( !isset($pmusr->fields['password']) || $pmusr->fields['password'] == "" ) { - $pass = md5(Toolbox::encrypt( $gusr->getID().$gusr->getName().time(), GLPIKEY) ) ; - $pmusr->update( array('id' => $pmusr->getID(), 'password' => $pass) ) ; - //$DB->query( "UPDATE glpi_plugin_processmaker_users SET password = '".$pass."' WHERE glpi_users_id = ".$pmusr->getID().";" ) ; - //$pmusr->update( array( $pmusr->getIndexName() => $pmusr->getID(), 'password' => $pass) ) ; - // and must be updated also in PM db - $PM_DB->query("UPDATE rbac_users SET USR_PASSWORD='".$pass."' WHERE USR_UID='".$pmusr->fields['pm_users_id']."' ") ; - $PM_DB->query("UPDATE users SET USR_PASSWORD='".$pass."' WHERE USR_UID='".$pmusr->fields['pm_users_id']."' ") ; - } - $locSession = $this->pmSoapClient->login( array( 'userid' => $gusr->fields['name'], 'password' => 'md5:'.$pmusr->fields['password']) ) ; - if( is_object( $locSession ) && $locSession->status_code == 0 ) { - $_SESSION["pluginprocessmaker"]["session"]["id"] = $locSession->message ; - $_SESSION["pluginprocessmaker"]["session"]["date"] = $locSession->timestamp ; - $_SESSION["pluginprocessmaker"]["session"]["admin"] = false ; - $this->pmAdminSession = false ; - return true ; - } - } else - return true ; // means a session is already existing in $_SESSION["pluginprocessmaker"]["session"] + /** + * Summary of login + * @param mixed $admin_or_user if true will be admin, otherwise is user name (or user id), or current user + * @return true if login has been correctly done with current GLPI user, or if a PM session was already open + * false if an exception occured (like SOAP error or PM login error) + */ + function login( $admin_or_user=false ) { + global $DB, $PM_DB; + try { + $locSession = new stdClass; // by default empty object + if ($this->openSoap( )) { + $cookie_lifetime = ini_get('session.cookie_lifetime'); + if ($cookie_lifetime == 0) { + $cookie_lifetime = 15 * 60; //= 15 minutes } + if ($admin_or_user === true) { // admin rights has been requested, then force new login + $config = PluginProcessmakerConfig::getInstance(); + $locSession = $this->pmSoapClient->login( array( 'userid' => $config->fields['pm_admin_user'], 'password' => Toolbox::decrypt($config->fields['pm_admin_passwd'], GLPIKEY)) ); + if (is_object( $locSession ) && $locSession->status_code == 0) { + $_SESSION["pluginprocessmaker"]["session"]["admin"] = true; + $_SESSION["pluginprocessmaker"]["session"]["id"] = $locSession->message; + $_SESSION["pluginprocessmaker"]["session"]["date"] = $locSession->timestamp; + $this->pmAdminSession = true; + return true; + } + } else if (empty($_SESSION["pluginprocessmaker"]["session"]["date"]) || ($_SESSION["pluginprocessmaker"]["session"]["admin"] == true) + || $this->pmAdminSession == true + || date_add( date_create( $_SESSION["pluginprocessmaker"]["session"]["date"] ), new DateInterval( "PT".$cookie_lifetime."S" ) ) < date_create( date( "Y-m-d H:i:s" ) ) ) { + // get the password of the user + $pmusr = new PluginProcessmakerUser; + $gusr = new User; + if (is_numeric($admin_or_user)) { + $gusr->getFromDB( $admin_or_user ); + } else { + $gusr->getFromDBbyName( $admin_or_user !== false ? $admin_or_user : $_SESSION["glpiname"]); + } + $pmusr->getFromDB( $gusr->getID() ); + if (!isset($pmusr->fields['password']) || $pmusr->fields['password'] == "") { + $pass = md5(Toolbox::encrypt( $gusr->getID().$gusr->getName().time(), GLPIKEY) ); + $pmusr->update( array('id' => $pmusr->getID(), 'password' => $pass) ); + //$DB->query( "UPDATE glpi_plugin_processmaker_users SET password = '".$pass."' WHERE glpi_users_id = ".$pmusr->getID().";" ) ; + //$pmusr->update( array( $pmusr->getIndexName() => $pmusr->getID(), 'password' => $pass) ) ; + // and must be updated also in PM db + $PM_DB->query("UPDATE RBAC_USERS SET USR_PASSWORD='".$pass."' WHERE USR_UID='".$pmusr->fields['pm_users_id']."' "); + $PM_DB->query("UPDATE USERS SET USR_PASSWORD='".$pass."' WHERE USR_UID='".$pmusr->fields['pm_users_id']."' "); + } + $locSession = $this->pmSoapClient->login( array( 'userid' => $gusr->fields['name'], 'password' => 'md5:'.$pmusr->fields['password']) ); + if (is_object( $locSession ) && $locSession->status_code == 0) { + $_SESSION["pluginprocessmaker"]["session"]["id"] = $locSession->message; + $_SESSION["pluginprocessmaker"]["session"]["date"] = $locSession->timestamp; + $_SESSION["pluginprocessmaker"]["session"]["admin"] = false; + $this->pmAdminSession = false; + return true; + } + } else { + return true; // means a session is already existing in $_SESSION["pluginprocessmaker"]["session"] + } + } - $this->pmAdminSession = false ; - unset($_SESSION["pluginprocessmaker"]["session"]) ; - Toolbox::logDebug( "Processmaker Plugin: $admin_or_user - Soap problem: ". print_r( $locSession, true ) ); - $this->lasterror = $locSession ; - return false ; - } - catch ( Exception $e ) { - $this->pmAdminSession = false ; - unset($_SESSION["pluginprocessmaker"]["session"]) ; - Toolbox::logDebug( $e ); - return false ; - } - } + $this->pmAdminSession = false; + unset($_SESSION["pluginprocessmaker"]["session"]); + Toolbox::logDebug( "Processmaker Plugin: $admin_or_user - Soap problem: ". print_r( $locSession, true ) ); + $this->lasterror = $locSession; + return false; + } catch (Exception $e) { + $this->pmAdminSession = false; + unset($_SESSION["pluginprocessmaker"]["session"]); + Toolbox::logDebug( $e ); + return false; + } + } - ///** - // * Summary of logout - // * used to clean variable session from current logged in session - // * will not really do a logout from PM, but is used to force cleaning when previously user was admin - // */ - //function logout( ) { - // unset($_SESSION["pluginprocessmaker"]["Session"]) ; - //} - /** - * Summary of processList - * Returns list of processes - * Embedded processList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#processList.28.29) - * A session must be open before with login() - * Normalizes output to an array, even when only one element is returned by PM - * @return an array of processListStruct objects - */ - function processList( ) { - try { - $pmProcessList = $this->pmSoapClient->processList( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"]) ) ; - if( isset( $pmProcessList->processes ) ) { - if( is_array( $pmProcessList->processes ) ) - return $pmProcessList->processes ; - else { - return array( 0 => $pmProcessList->processes ) ; + /** + * Summary of processList + * Returns list of processes + * Embedded processList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#processList.28.29) + * A session must be open before with login() + * Normalizes output to an array, even when only one element is returned by PM + * @return an array of processListStruct objects + */ + function processList( ) { + try { + $pmProcessList = $this->pmSoapClient->processList( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"]) ); + if (isset( $pmProcessList->processes )) { + if (is_array( $pmProcessList->processes )) { + return $pmProcessList->processes; + } else { + return array( 0 => $pmProcessList->processes ); + } + } + + return false; + + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } + + /** + * Summary of getCaseInfo + * returns information about a given case (as long as the logged in user has privileges to access the case). + * Embedded getCaseInfo() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#getCaseInfo.28.29) + * A session must be open before with login() + * Normalizes output of currentUsers to an array, even when only one element is returned by PM, + * Note: currentUsers field doesn't exist when case is CANCELLED + * @param $caseId: The case ID, which can be obtained with the caseList() function + * @param $delIndex: The delegation index, which is a positive integer to identify the current task of the case. If empty then use current delIndex. + * @return a getCaseInfoResponse object, or false exception occured + */ + function getCaseInfo( $caseId, $delIndex='') { + try { + $pmCaseInfo = $this->pmSoapClient->getCaseInfo( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId, 'delIndex' => $delIndex) ); + switch ($pmCaseInfo->caseStatus) { + case 'DRAFT' : + case 'TO_DO': + // case 'CANCELLED' : + if (is_object( $pmCaseInfo->currentUsers )) { + $pmCaseInfo->currentUsers = array( 0 => $pmCaseInfo->currentUsers ); + } + if ($pmCaseInfo->currentUsers[0]->delThreadStatus == 'PAUSE') { + $pmCaseInfo->caseStatus = "PAUSED"; + } + break; + } + return $pmCaseInfo; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + + } + + /** + * Summary of routeCase + * routes a case (i.e., moves the case to the next task in the process according to its routing rules). + * Embedded routeCase() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#routeCase.28.29) + * A session must be open before with login() + * @param $caseId The case ID, which can be obtained with the caseList() function + * @param $delIndex The delegation index, which is a positive integer to identify the current task of the case. If empty then use current delIndex. + * @return a routeCaseResponse object, or false exception occured. routing is normalized to be always an array of routeListStruct + */ + function routeCase( $caseId, $delIndex) { + try { + $pmRouteCaseResponse = $this->pmSoapClient->routeCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId, 'delIndex' => $delIndex) ); + if ($pmRouteCaseResponse->status_code != 0) { + Toolbox::logDebug( 'routeCase res:', $pmRouteCaseResponse ); + } + + if (property_exists( $pmRouteCaseResponse, 'routing' ) && is_object( $pmRouteCaseResponse->routing )) { + $pmRouteCaseResponse->routing = array( 0 => $pmRouteCaseResponse->routing); + } + + return $pmRouteCaseResponse; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } + + /** + * Summary of triggerList + * Returns list of triggers + * Embedded triggerList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#triggerList.28.29) + * A session must be open before with login() + * Normalizes output to an array, even when only one element is returned by PM + * @return an array of triggerListStruct objects, or false when exception occured + */ + function triggerList( ) { + try { + $pmTriggerList = $this->pmSoapClient->triggerList( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"]) ); + if (is_array( $pmTriggerList->triggers )) { + return $pmTriggerList->triggers; + } else { + return array( 0 => $pmTriggerList->triggers ); + } + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } + + /** + * Summary of taskList + * Returns list of tasks to which the logged-in user is assigned + * Embedded taskList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#taskList.28.29) + * A session must be open before with login() + * Normalizes output to an array, even when only one element is returned by PM + * @return an array of taskListStruct objects, or false when exception occured + */ + function taskList( ) { + try { + $pmTaskList = $this->pmSoapClient->taskList( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"]) ); + + if (is_array( $pmTaskList->tasks )) { + return $pmTaskList->tasks; + } else { + return array( 0 => $pmTaskList->tasks ); + } + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } + + + /** + * Summary of taskCase + * Returns list of tasks to which the logged-in user is assigned + * Embedded taskList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#taskList.28.29) + * A session must be open before with login() + * Normalizes output to an array, even when only one element is returned by PM + * @return array of taskListStruct objects, or false when exception occured + */ + function taskCase( $caseId ) { + try { + $pmTaskCase = $this->pmSoapClient->taskCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId ) ); + + if (is_array( $pmTaskCase->taskCases )) { + return $pmTaskCase->taskCases; + } else { + return array( 0 => $pmTaskCase->taskCases ); + } + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } + + /** + * Summary of claimCase + * @param mixed $caseId + * @param mixed $delIndex + * @return mixed + */ + function claimCase( $caseId, $delIndex) { + try { + $pmClaimCase = $this->pmSoapClient->claimCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'guid' => $caseId, 'delIndex' => $delIndex) ); + return $pmClaimCase; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } + + /** + * Summary of unpauseCase + * Unpauses a specified case. + * Embedded UnpauseCase() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#UnpauseCase.28.29) + * A session must be open before with login() + * Normalizes output to an array, even when only one element is returned by PM + * @param $caseId The unique ID of the case. + * @param $delIndex The delegation index of the current task in the case. + * @param $userId The unique ID of the user who will unpause the case. + * @return an array of UnpauseCaseStruct, or false when exception occured + */ + function unpauseCase( $caseId, $delIndex, $userId ) { + try { + $pmUnpauseCase = $this->pmSoapClient->unpauseCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseUid' => $caseId, 'delIndex' => $delIndex, 'userUid' => $userId) ); + + if (is_array( $pmUnpauseCase->processes )) { + return $pmUnpauseCase->processes; + } else { + return array( 0 => $pmUnpauseCase->processes ); + } + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } + + /** + * Summary of caseList + * returns a list of the cases for the logged-in user. + * Embedded caseList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#caseList.28.29) + * A session must be open before with login() + * Normalizes output to an array, even when only one element is returned by PM + * @return an array of cases, or false when exception occured + */ + function caseList( ) { + try { + $pmCaseList = $this->pmSoapClient->caseList( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"]) ); + + if (is_array( $pmCaseList->cases )) { + return $pmCaseList->cases; + } else { + return array( 0 => $pmCaseList->cases ); + } + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } + + /** + * Summary of reassignCase + * reassigns a case to a different user. Note that the logged-in user needs to have the PM_REASSIGNCASE permission in his/her role in order to be able to reassign the case. + * Embedded caseList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#reassignCase.28.29) + * A session must be open before with login() + * @param $caseId The case ID, which can be obtained with the caseList() function. + * @param $delIndex The current delegation index number of the case, which can be obtained with the caseList() function. + * @param $userIdSource The user who is currently assigned the case, which can be obtained with the caseList() function. + * @param $userIdTarget The target user who will be newly assigned to the case, which can be obtained with userList(). The case can only be reassigned to a user who is one of the assigned users or ad-hoc users to the current task in the case. + * @return A pmResponse object, or false when exception occured + */ + function reassignCase( $caseId, $delIndex, $userIdSource, $userIdTarget ) { + try { + $pmResults = $this->pmSoapClient->reassignCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId, 'delIndex' => $delIndex, 'userIdSource' => $userIdSource, 'userIdTarget'=> $userIdTarget) ); + return $pmResults; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } + + + /** + * Summary of deleteCase + * Deletes a case + * Embedded deleteCase() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#deleteCase.28.29) + * A session must be open before with login() + * Beware that at any time you may delete a case!!! + * @param $caseUid The case ID, which can be obtained with the caseList() function. + * @return A deleteCaseResponse object, or false when exception occured + */ + function deleteCase( $caseUid ) { + try { + $deleteCaseResponse = $this->pmSoapClient->deleteCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseUid' => $caseUid) ); + return $deleteCaseResponse; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } + + + /** + * Summary of cancelTask + * Cancels a task + * Embedded cancelCase() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#cancelCase.28.29) + * A session must be open before with login() + * Beware that this will only cancel the task with delIndex + * in the case of // tasks you must call cancelTask for each running task. + * in the case of one and only one task running, then it will cancel the case + * @param $caseUid The case ID, which can be obtained with the caseList() function. + * @param $delIndex The delegation index of the current task in the case. + * @param $userUid: The unique ID of the user who will unpause the case. + * @return A cancelCaseResponse object, or false when exception occured + */ + function cancelTask( $caseUid, $delIndex, $userUid ) { + try { + $cancelTaskResponse = $this->pmSoapClient->cancelCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseUid' => $caseUid, 'delIndex' => $delIndex, 'userUid' => $userUid) ); + return $cancelTaskResponse; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } + + + /** + * Summary of cancelCase + * Cancels a case + * Embedded cancelCase() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#cancelCase.28.29) + * A session must be open before with login() + * Beware that this will cancel all running task + * in the case of // tasks you must call cancelCase for each running task. + * in the case of one and only one task is running, then it will cancel the case + * @param $caseUid The case ID, which can be obtained with the caseList() function. + * @param $delIndex The delegation index of the current task in the case. + * @param $userUid: The unique ID of the user who will unpause the case. + * @return A cancelCaseResponse object, or false when exception occured + */ + function cancelCase( $caseUid ) { + try { + $pmCaseInfo = $this->getCaseInfo( $caseUid ); + if ($pmCaseInfo->status_code == 0) { + foreach ($pmCaseInfo->currentUsers as $pmUser) { + $pmCancelTask = $this->cancelTask( $caseUid, $pmUser->delIndex, $pmUser->userId ); + if ($pmCancelTask->status_code != 0) { + return $pmCancelTask; } } - - return false ; - - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false ; - } - } - - /** - * Summary of getCaseInfo - * returns information about a given case (as long as the logged in user has privileges to access the case). - * Embedded getCaseInfo() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#getCaseInfo.28.29) - * A session must be open before with login() - * Normalizes output of currentUsers to an array, even when only one element is returned by PM, - * Note: currentUsers field doesn't exist when case is CANCELLED - * @param $caseId: The case ID, which can be obtained with the caseList() function - * @param $delIndex: The delegation index, which is a positive integer to identify the current task of the case. If empty then use current delIndex. - * @return a getCaseInfoResponse object, or false exception occured - */ - function getCaseInfo( $caseId, $delIndex='') { - try { - $pmCaseInfo = $this->pmSoapClient->getCaseInfo( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId, 'delIndex' => $delIndex) ) ; - switch ( $pmCaseInfo->caseStatus ) { - case 'DRAFT' : - case 'TO_DO': -// case 'CANCELLED' : - if( is_object( $pmCaseInfo->currentUsers ) ) - $pmCaseInfo->currentUsers = array( 0 => $pmCaseInfo->currentUsers ) ; - if( $pmCaseInfo->currentUsers[0]->delThreadStatus == 'PAUSE' ) - $pmCaseInfo->caseStatus = "PAUSED" ; - break; - } - return $pmCaseInfo ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false ; - } - - } - - /** - * Summary of routeCase - * routes a case (i.e., moves the case to the next task in the process according to its routing rules). - * Embedded routeCase() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#routeCase.28.29) - * A session must be open before with login() - * @param $caseId The case ID, which can be obtained with the caseList() function - * @param $delIndex The delegation index, which is a positive integer to identify the current task of the case. If empty then use current delIndex. - * @return a routeCaseResponse object, or false exception occured. routing is normalized to be always an array of routeListStruct - */ - function routeCase( $caseId, $delIndex) { - try { - $pmRouteCaseResponse = $this->pmSoapClient->routeCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId, 'delIndex' => $delIndex) ) ; - if( $pmRouteCaseResponse->status_code != 0 ) - Toolbox::logDebug( 'routeCase res:', $pmRouteCaseResponse ) ; - - if( property_exists( $pmRouteCaseResponse, 'routing' ) && is_object( $pmRouteCaseResponse->routing ) ) - $pmRouteCaseResponse->routing = array( 0 => $pmRouteCaseResponse->routing) ; - - return $pmRouteCaseResponse ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false ; - } - } - - /** - * Summary of triggerList - * Returns list of triggers - * Embedded triggerList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#triggerList.28.29) - * A session must be open before with login() - * Normalizes output to an array, even when only one element is returned by PM - * @return an array of triggerListStruct objects, or false when exception occured - */ - function triggerList( ) { - try { - $pmTriggerList = $this->pmSoapClient->triggerList( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"]) ) ; - if( is_array( $pmTriggerList->triggers ) ) - return $pmTriggerList->triggers ; - else - return array( 0 => $pmTriggerList->triggers ) ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false ; - } - } - - /** - * Summary of taskList - * Returns list of tasks to which the logged-in user is assigned - * Embedded taskList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#taskList.28.29) - * A session must be open before with login() - * Normalizes output to an array, even when only one element is returned by PM - * @return an array of taskListStruct objects, or false when exception occured - */ - function taskList( ) { - try { - $pmTaskList = $this->pmSoapClient->taskList( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"]) ) ; - - if( is_array( $pmTaskList->tasks ) ) - return $pmTaskList->tasks ; - else - return array( 0 => $pmTaskList->tasks ) ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } + } + return $pmCancelTask; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } - /** - * Summary of taskCase - * Returns list of tasks to which the logged-in user is assigned - * Embedded taskList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#taskList.28.29) - * A session must be open before with login() - * Normalizes output to an array, even when only one element is returned by PM - * @return array of taskListStruct objects, or false when exception occured - */ - function taskCase( $caseId ) { - try { - $pmTaskCase = $this->pmSoapClient->taskCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId ) ) ; - - if( is_array( $pmTaskCase->taskCases ) ) - return $pmTaskCase->taskCases ; - else - return array( 0 => $pmTaskCase->taskCases ) ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } - - /** - * Summary of claimCase - * @param mixed $caseId - * @param mixed $delIndex - * @return mixed - */ - function claimCase( $caseId, $delIndex){ - try { - $pmClaimCase = $this->pmSoapClient->claimCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'guid' => $caseId, 'delIndex' => $delIndex) ) ; - return $pmClaimCase ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } - - /** - * Summary of unpauseCase - * Unpauses a specified case. - * Embedded UnpauseCase() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#UnpauseCase.28.29) - * A session must be open before with login() - * Normalizes output to an array, even when only one element is returned by PM - * @param $caseId The unique ID of the case. - * @param $delIndex The delegation index of the current task in the case. - * @param $userId The unique ID of the user who will unpause the case. - * @return an array of UnpauseCaseStruct, or false when exception occured - */ - function unpauseCase( $caseId, $delIndex, $userId ) { - try { - $pmUnpauseCase = $this->pmSoapClient->unpauseCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseUid' => $caseId, 'delIndex' => $delIndex, 'userUid' => $userId) ) ; - - if( is_array( $pmUnpauseCase->processes ) ) - return $pmUnpauseCase->processes ; - else - return array( 0 => $pmUnpauseCase->processes ) ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } - - /** - * Summary of caseList - * returns a list of the cases for the logged-in user. - * Embedded caseList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#caseList.28.29) - * A session must be open before with login() - * Normalizes output to an array, even when only one element is returned by PM - * @return an array of cases, or false when exception occured - */ - function caseList( ) { - try { - $pmCaseList = $this->pmSoapClient->caseList( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"]) ) ; - - if( is_array( $pmCaseList->cases ) ) - return $pmCaseList->cases ; - else - return array( 0 => $pmCaseList->cases ) ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } - - /** - * Summary of reassignCase - * reassigns a case to a different user. Note that the logged-in user needs to have the PM_REASSIGNCASE permission in his/her role in order to be able to reassign the case. - * Embedded caseList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#reassignCase.28.29) - * A session must be open before with login() - * @param $caseId The case ID, which can be obtained with the caseList() function. - * @param $delIndex The current delegation index number of the case, which can be obtained with the caseList() function. - * @param $userIdSource The user who is currently assigned the case, which can be obtained with the caseList() function. - * @param $userIdTarget The target user who will be newly assigned to the case, which can be obtained with userList(). The case can only be reassigned to a user who is one of the assigned users or ad-hoc users to the current task in the case. - * @return A pmResponse object, or false when exception occured - */ - function reassignCase( $caseId, $delIndex, $userIdSource, $userIdTarget ) { - try { - $pmResults = $this->pmSoapClient->reassignCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId, 'delIndex' => $delIndex, 'userIdSource' => $userIdSource, 'userIdTarget'=> $userIdTarget) ) ; - return $pmResults ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } - - - /** - * Summary of deleteCase - * Deletes a case - * Embedded deleteCase() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#deleteCase.28.29) - * A session must be open before with login() - * Beware that at any time you may delete a case!!! - * @param $caseUid The case ID, which can be obtained with the caseList() function. - * @return A deleteCaseResponse object, or false when exception occured - */ - function deleteCase( $caseUid ) { - try { - $deleteCaseResponse = $this->pmSoapClient->deleteCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseUid' => $caseUid) ) ; - return $deleteCaseResponse ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } - - - /** - * Summary of cancelTask - * Cancels a task - * Embedded cancelCase() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#cancelCase.28.29) - * A session must be open before with login() - * Beware that this will only cancel the task with delIndex - * in the case of // tasks you must call cancelTask for each running task. - * in the case of one and only one task running, then it will cancel the case - * @param $caseUid The case ID, which can be obtained with the caseList() function. - * @param $delIndex The delegation index of the current task in the case. - * @param $userUid: The unique ID of the user who will unpause the case. - * @return A cancelCaseResponse object, or false when exception occured - */ - function cancelTask( $caseUid, $delIndex, $userUid ) { - try { - $cancelTaskResponse = $this->pmSoapClient->cancelCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseUid' => $caseUid, 'delIndex' => $delIndex, 'userUid' => $userUid) ) ; - return $cancelTaskResponse ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } - - - /** - * Summary of cancelCase - * Cancels a case - * Embedded cancelCase() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#cancelCase.28.29) - * A session must be open before with login() - * Beware that this will cancel all running task - * in the case of // tasks you must call cancelCase for each running task. - * in the case of one and only one task is running, then it will cancel the case - * @param $caseUid The case ID, which can be obtained with the caseList() function. - * @param $delIndex The delegation index of the current task in the case. - * @param $userUid: The unique ID of the user who will unpause the case. - * @return A cancelCaseResponse object, or false when exception occured - */ - function cancelCase( $caseUid ) { - try { - $pmCaseInfo = $this->getCaseInfo( $caseUid ) ; - if( $pmCaseInfo->status_code == 0 ){ - foreach( $pmCaseInfo->currentUsers as $pmUser){ - $pmCancelTask = $this->cancelTask( $caseUid, $pmUser->delIndex, $pmUser->userId ) ; - if( $pmCancelTask->status_code != 0 ) - return $pmCancelTask; - } - } - return $pmCancelTask ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } - - - /** - * Summary of newCaseImpersonate - * Starts a new case under the name of the logged-in user. - * The task that will be started is the default one (=must be unique in process definition)! - * logged-in user must be assigned to this task, otherwise use newCaseImpersonate() to start the case. - * New case is started with DRAFT status. - * Embedded newCaseImpersonate() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#newCaseImpersonate.28.29) - * A session must be open before with login(), in order to call this function. - * @param $processId The ID of the process where the case should start, which can be obtained with processList() - * @param $userId The ID of the user who initiates the case, which can be obtained with userList(). - * @param $vars an array of associative variables (name => value) that will be injected into the case as case variables - * @return A newCaseResponse object, or false when exception occured - */ - function newCaseImpersonate( $processId, $userId, $vars = null ) { - try { - $this->getFromDB( $processId ) ; - - if( $vars !== null ) { - $aVars = array(); - foreach ($vars as $key => $val) - { - $obj = new variableStruct(); - $obj->name = $key; - $obj->value = $val; - $aVars[] = $obj; - } - } else $aVars = '' ; - - $newCaseResponse = $this->pmSoapClient->newCaseImpersonate( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'processId'=> $this->fields['process_guid'], 'userId' => $userId, 'taskId'=>'', 'variables'=> $aVars) ) ; - return $newCaseResponse ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } - - /** - * Summary of newCase - * Starts a new case under the name of the logged-in user. - * The task that will be started is the default one (=must be unique in process definition)! - * logged-in user must be assigned to this task, otherwise use newCaseImpersonate() to start the case. - * New case is started with DRAFT status. - * Embedded newCase() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#newCase.28.29) - * A session must be open before with login() - * @param string $processId The ID of the process which will be instantied into a case, which can be obtained with processList() - * @param array $vars an array of associative variables (name => value) that will be injected into the case as case variables - * @return A newCaseResponse object, or false when exception occured - */ - function newCase( $processId, $vars = array() ) { - try { - $this->getFromDB( $processId ) ; + /** + * Summary of newCaseImpersonate + * Starts a new case under the name of the logged-in user. + * The task that will be started is the default one (=must be unique in process definition)! + * logged-in user must be assigned to this task, otherwise use newCaseImpersonate() to start the case. + * New case is started with DRAFT status. + * Embedded newCaseImpersonate() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#newCaseImpersonate.28.29) + * A session must be open before with login(), in order to call this function. + * @param $processId The ID of the process where the case should start, which can be obtained with processList() + * @param $userId The ID of the user who initiates the case, which can be obtained with userList(). + * @param $vars an array of associative variables (name => value) that will be injected into the case as case variables + * @return A newCaseResponse object, or false when exception occured + */ + function newCaseImpersonate( $processId, $userId, $vars = null ) { + try { + $this->getFromDB( $processId ); + if ($vars !== null) { $aVars = array(); - foreach ($vars as $key => $val) - { - $obj = new variableStruct(); - $obj->name = $key; - $obj->value = $val; - $aVars[] = $obj; + foreach ($vars as $key => $val) { + $obj = new variableStruct(); + $obj->name = $key; + $obj->value = $val; + $aVars[] = $obj; } + } else { + $aVars = ''; + } - $newCaseResponse = $this->pmSoapClient->newCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'processId'=> $this->fields['process_guid'], 'taskId'=>'', 'variables'=> $aVars) ) ; + $newCaseResponse = $this->pmSoapClient->newCaseImpersonate( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'processId'=> $this->fields['process_guid'], 'userId' => $userId, 'taskId'=>'', 'variables'=> $aVars) ); + return $newCaseResponse; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } - return $newCaseResponse ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } + /** + * Summary of newCase + * Starts a new case under the name of the logged-in user. + * The task that will be started is the default one (=must be unique in process definition)! + * logged-in user must be assigned to this task, otherwise use newCaseImpersonate() to start the case. + * New case is started with DRAFT status. + * Embedded newCase() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#newCase.28.29) + * A session must be open before with login() + * @param string $processId The ID of the process which will be instantied into a case, which can be obtained with processList() + * @param array $vars an array of associative variables (name => value) that will be injected into the case as case variables + * @return A newCaseResponse object, or false when exception occured + */ + function newCase( $processId, $vars = array() ) { + try { + $this->getFromDB( $processId ); - /** - * Summary of sendVariables - * Sends variables to a case. - * Embedded sendVariables() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#sendVariables.28.29) - * A session must be open before with login() - * @param string $caseId The uID of the case - * @param array $vars an array of associative variables (name => value) that will be injected into the case as case variables - * @return A pmResponse object, or false when exception occured - */ - function sendVariables( $caseId, $vars = array() ) { - if( count( $vars ) == 0 ) // nothing to send - return true ; - try { - $aVars = array(); - foreach ($vars as $key => $val) - { - $obj = new variableStruct(); - $obj->name = $key; - if( is_array( $val ) ) - $obj->value = join( "|", $val ) ; - else - $obj->value = $val; - $aVars[] = $obj; + $aVars = array(); + foreach ($vars as $key => $val) { + $obj = new variableStruct(); + $obj->name = $key; + $obj->value = $val; + $aVars[] = $obj; + } + + $newCaseResponse = $this->pmSoapClient->newCase( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'processId'=> $this->fields['process_guid'], 'taskId'=>'', 'variables'=> $aVars) ); + + return $newCaseResponse; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } + + /** + * Summary of sendVariables + * Sends variables to a case. + * Embedded sendVariables() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#sendVariables.28.29) + * A session must be open before with login() + * @param string $caseId The uID of the case + * @param array $vars an array of associative variables (name => value) that will be injected into the case as case variables + * @return A pmResponse object, or false when exception occured + */ + function sendVariables( $caseId, $vars = array() ) { + if (count( $vars ) == 0) { // nothing to send + return true; + } + try { + $aVars = array(); + foreach ($vars as $key => $val) { + $obj = new variableStruct(); + $obj->name = $key; + if (is_array( $val )) { + $obj->value = join( "|", $val ); + } else { + $obj->value = $val; } + $aVars[] = $obj; + } - $pmResponse = $this->pmSoapClient->sendVariables( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId, 'variables'=> $aVars) ) ; + $pmResponse = $this->pmSoapClient->sendVariables( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId, 'variables'=> $aVars) ); - return $pmResponse ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } + return $pmResponse; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } - /** - * Summary of getVariables - * Gets variables from a case. - * Embedded getVariables() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#getVariables.28.29) - * A session must be open before with login() - * @param string $caseId The uID of the case - * @param array $vars an array of variable name that will be read from the case as case variables - * Normalizes output to an array, even when only one element is returned by PM - * @return array: an associative array (variable_name => value), or false when exception occured. The return array can be empty if requested variables are not found. - */ - function getVariables( $caseId, $vars = array() ) { - try { - $aVars = array(); - foreach ($vars as $key => $name) - { - $obj = new getVariableStruct(); - $obj->name = $name; - $aVars[] = $obj; - } + /** + * Summary of getVariables + * Gets variables from a case. + * Embedded getVariables() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#getVariables.28.29) + * A session must be open before with login() + * @param string $caseId The uID of the case + * @param array $vars an array of variable name that will be read from the case as case variables Normalizes output to an array, even when only one element is returned by PM Normalizes output to an array, even when only one element is returned by PM + * Normalizes output to an array, even when only one element is returned by PM + * @return array: an associative array (variable_name => value), or false when exception occured. The return array can be empty if requested variables are not found. + */ + function getVariables( $caseId, $vars = array() ) { + try { + $aVars = array(); + foreach ($vars as $key => $name) { + $obj = new getVariableStruct(); + $obj->name = $name; + $aVars[] = $obj; + } - $pmvariableListResponse = $this->pmSoapClient->getVariables( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId, 'variables'=> $aVars) ) ; + $pmvariableListResponse = $this->pmSoapClient->getVariables( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId, 'variables'=> $aVars) ); - $variablesArray = array() ; + $variablesArray = array(); - if ($pmvariableListResponse->status_code == 0 && isset( $pmvariableListResponse->variables )) { - if( is_array( $pmvariableListResponse->variables ) ) - foreach ($pmvariableListResponse->variables as $variable) - $variablesArray[$variable->name] = $variable->value; - else - $variablesArray[$pmvariableListResponse->variables->name] = $pmvariableListResponse->variables->value; - } + if ($pmvariableListResponse->status_code == 0 && isset( $pmvariableListResponse->variables )) { + if (is_array( $pmvariableListResponse->variables )) { + foreach ($pmvariableListResponse->variables as $variable) { + $variablesArray[$variable->name] = $variable->value; + } } else { + $variablesArray[$pmvariableListResponse->variables->name] = $pmvariableListResponse->variables->value; + } + } - return $variablesArray ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } + return $variablesArray; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } - /** - * Summary of groupList - * returns a list of the groups. For privileges to see the list, the logged-in user must have the PM_USERS permission in his/her role. - * Embedded groupList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#groupList.28.29) - * A session must be open before with login() - * Normalizes output to an array, even when only one element is returned by PM - * @return an array of groupListStruct, or false when exception occured - */ - function groupList( ) { - try { - $pmGroupList = $this->pmSoapClient->groupList( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"]) ) ; + /** + * Summary of groupList + * returns a list of the groups. For privileges to see the list, the logged-in user must have the PM_USERS permission in his/her role. + * Embedded groupList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#groupList.28.29) + * A session must be open before with login() + * Normalizes output to an array, even when only one element is returned by PM + * @return an array of groupListStruct, or false when exception occured + */ + function groupList( ) { + try { + $pmGroupList = $this->pmSoapClient->groupList( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"]) ); - if( is_array( $pmGroupList->groups ) ) - return $pmGroupList->groups ; - else - return array( 0 => $pmGroupList->groups ) ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } + if (is_array( $pmGroupList->groups )) { + return $pmGroupList->groups; + } else { + return array( 0 => $pmGroupList->groups ); + } + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } - /** - * Summary of assignUserToGroup - * assigns a user to a group. For privileges to assign a user, the logged-in user must have the PM_USERS permission in his/her role. - * Embedded assignUserToGroup() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#assignUserToGroup.28.29) - * A session must be open before with login() - * @param $userId a Processmaker user id (see userList()) - * @param $groupId a Processmaker group id (see groupList()) - * @return A pmResponse object, or false when exception occured - */ - function assignUserToGroup( $userId, $groupId) { - try { - $pmResults = $this->pmSoapClient->assignUserToGroup(array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], - 'userId' => $userId, - 'groupId' => $groupId - ) ) ; - return $pmResults ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false ; - } - } + /** + * Summary of assignUserToGroup + * assigns a user to a group. For privileges to assign a user, the logged-in user must have the PM_USERS permission in his/her role. + * Embedded assignUserToGroup() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#assignUserToGroup.28.29) + * A session must be open before with login() + * @param $userId a Processmaker user id (see userList()) + * @param $groupId a Processmaker group id (see groupList()) + * @return A pmResponse object, or false when exception occured + */ + function assignUserToGroup( $userId, $groupId) { + try { + $pmResults = $this->pmSoapClient->assignUserToGroup(array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], + 'userId' => $userId, + 'groupId' => $groupId + ) ); + return $pmResults; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } - /** - * Summary of createGroup - * creates a new group. For privileges to create a group, the logged-in user must have the PM_USERS permission in his/her role. - * group will be created as 'ACTIVE' - * Embedded createGroup() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#createGroup.28.29) - * A session must be open before with login() - * @param $name: the name of the group to be created - * @return A pmResponse object, or false when exception occured - */ - function createGroup( $name ) { - try { - $pmResults = $this->pmSoapClient->createGroup(array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], - 'name' => $name ) ) ; - return $pmResults ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false ; - } - } + /** + * Summary of createGroup + * creates a new group. For privileges to create a group, the logged-in user must have the PM_USERS permission in his/her role. + * group will be created as 'ACTIVE' + * Embedded createGroup() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#createGroup.28.29) + * A session must be open before with login() + * @param $name: the name of the group to be created + * @return A pmResponse object, or false when exception occured + */ + function createGroup( $name ) { + try { + $pmResults = $this->pmSoapClient->createGroup(array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], + 'name' => $name ) ); + return $pmResults; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } - /** - * Summary of updateGroup - * updates group directly into Processmaker DB - * @param $group_id: guid of the pm group - * @param $groupStatus: new status to be set to $group_id, could be 'ACTIVE' or 'INACTIVE' - * @return true if group status has been modified, false otherwise - */ - function updateGroup( $group_id, $groupStatus ){ - global $PM_DB ; - $query = "UPDATE groupwf SET GRP_STATUS='$groupStatus' WHERE GRP_UID=$group_id;"; - $PM_DB->query( $query ) ; - if( $PM_DB->affected_rows != 1 ) - return false; - else - return true; - } + /** + * Summary of updateGroup + * updates group directly into Processmaker DB + * @param $group_id: guid of the pm group + * @param $groupStatus: new status to be set to $group_id, could be 'ACTIVE' or 'INACTIVE' + * @return true if group status has been modified, false otherwise + */ + function updateGroup( $group_id, $groupStatus ) { + global $PM_DB; + $query = "UPDATE GROUPWF SET GRP_STATUS='$groupStatus' WHERE GRP_UID='$group_id';"; + $PM_DB->query( $query ); + if ($PM_DB->affected_rows != 1) { + return false; + } else { + return true; + } + } - /** - * Summary of userList - * returns a list of the Processmaker users. For privileges to see the list, the logged-in user must have the PM_USERS permission in his/her role. - * Embedded userList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#userList.28.29) - * A session must be open before with login() - * Normalizes output to an array, even if only one element is returned by PM - * @return an array of userListStruct, or false when exception occured - */ - function userList( ) { - try { - $pmUserList = $this->pmSoapClient->userList( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"]) ) ; + /** + * Summary of userList + * returns a list of the Processmaker users. For privileges to see the list, the logged-in user must have the PM_USERS permission in his/her role. + * Embedded userList() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#userList.28.29) + * A session must be open before with login() + * Normalizes output to an array, even if only one element is returned by PM + * @return an array of userListStruct, or false when exception occured + */ + function userList( ) { + try { + $pmUserList = $this->pmSoapClient->userList( array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"]) ); - if( is_array( $pmUserList->users ) ) - return $pmUserList->users ; - else - return array( 0 => $pmUserList->users ) ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } + if (is_array( $pmUserList->users )) { + return $pmUserList->users; + } else { + return array( 0 => $pmUserList->users ); + } + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } - /** - * Summary of createUser - * creates a new user. For privileges to create a user, the logged-in user must have the PM_USERS permission in his/her role. - * Embedded createUser() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#createUser.28.29) - * A session must be open before with login() - * @param $userId The username for the new user. The unique ID for the user will be automatically generated. Is the user Windows login! - * @param $firstname The user's first name. If empty (== null or == "") will default to $userId. - * @param $lastname The user's last name. If empty (== null or == "") will default to $userId. - * @param $email The user's email address. If empty (== null or == "") will default to $userId@DoNotReply.com. - * @param $role The user's role, such as 'PROCESSMAKER_ADMIN', 'PROCESSMAKER_MANAGER' or 'PROCESSMAKER_OPERATOR'. Possible values can be looked up with the roleList() function. - * @param $password The user's password, such as 'Be@gle2'. (It will be automatically converted into an MD5 hash when inserted in the database.) - * @param $status The user's status, such as "ACTIVE", "INACTIVE". - * @return returns a createUserResponse object, or false if exception occurred - */ - function createUser( $userId, $firstname, $lastname, $email, $role, $password, $status) { - try { - if( $firstname == null || $firstname == "" ) $firstname = $userId ; - if( $lastname == null || $lastname == "" ) $lastname = $userId ; - if( $email == "" ) $email = $userId."@DoNotReply.com" ; + /** + * Summary of createUser + * creates a new user. For privileges to create a user, the logged-in user must have the PM_USERS permission in his/her role. + * Embedded createUser() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#createUser.28.29) + * A session must be open before with login() + * @param $userId The username for the new user. The unique ID for the user will be automatically generated. Is the user Windows login! + * @param $firstname The user's first name. If empty (== null or == "") will default to $userId. + * @param $lastname The user's last name. If empty (== null or == "") will default to $userId. + * @param $email The user's email address. If empty (== null or == "") will default to $userId@DoNotReply.com. + * @param $role The user's role, such as 'PROCESSMAKER_ADMIN', 'PROCESSMAKER_MANAGER' or 'PROCESSMAKER_OPERATOR'. Possible values can be looked up with the roleList() function. + * @param $password The user's password, such as 'Be@gle2'. (It will be automatically converted into an MD5 hash when inserted in the database.) + * @param $status The user's status, such as "ACTIVE", "INACTIVE". + * @return returns a createUserResponse object, or false if exception occurred + */ + function createUser( $userId, $firstname, $lastname, $email, $role, $password, $status) { + try { + if ($firstname == null || $firstname == "") { + $firstname = $userId; + } + if ($lastname == null || $lastname == "") { + $lastname = $userId; + } + if ($email == "") { + $email = $userId."@DoNotReply.com"; + } - $pmResults = $this->pmSoapClient->createUser(array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], - 'userId' => $userId, - 'firstname'=> $firstname, - 'lastname' => $lastname, - 'email' => $email, - 'role' => $role, - 'password' => $password, - 'status' => $status ) ) ; - return $pmResults ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false; - } - } + $pmResults = $this->pmSoapClient->createUser(array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], + 'userId' => $userId, + 'firstname'=> $firstname, + 'lastname' => $lastname, + 'email' => $email, + 'role' => $role, + 'password' => $password, + 'status' => $status ) ); + return $pmResults; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } - /** - * Summary of updateUser - * updates user information. - * Embedded updateUser() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#updateUser.28.29) - * A session must be open before with login() - * @param $userUid the unique Id for the user (Processmaker user id) - * @param $userName is the user logon. IT IS STRONGLY ADVISE NOT TO CHANGE THIS INFORMATION - * @param $firstname The user's first name. If empty (== null or == "") will default to $userName. - * @param $lastname The user's last name. If empty (== null or == "") will default to $userName. - * @param $status The user's status, such as "ACTIVE", "INACTIVE". - * @return returns a UpdateUserResponse object, or false if exception occurred - */ - function updateUser( $userUid, $userName, $firstName, $lastName, $status) { - try { - if( $firstName == null || $firstName == "" ) $firstName = $userName ; - if( $lastName == null || $lastName == "" ) $lastName = $userName ; + /** + * Summary of updateUser + * updates user information. + * Embedded updateUser() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#updateUser.28.29) + * A session must be open before with login() + * @param $userUid the unique Id for the user (Processmaker user id) + * @param $userName is the user logon. IT IS STRONGLY ADVISE NOT TO CHANGE THIS INFORMATION + * @param $firstname The user's first name. If empty (== null or == "") will default to $userName. + * @param $lastname The user's last name. If empty (== null or == "") will default to $userName. + * @param $status The user's status, such as "ACTIVE", "INACTIVE". + * @return returns a UpdateUserResponse object, or false if exception occurred + */ + function updateUser( $userUid, $userName, $firstName, $lastName, $status) { + try { + if ($firstName == null || $firstName == "") { + $firstName = $userName; + } + if ($lastName == null || $lastName == "") { + $lastName = $userName; + } - $pmResults = $this->pmSoapClient->updateUser(array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], - 'userUid' => $userUid, - 'userName' => $userName, - 'firstName'=> $firstName, - 'lastName' => $lastName, - 'status' => $status - ) ) ; - return $pmResults ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false ; - } - } + $pmResults = $this->pmSoapClient->updateUser(array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], + 'userUid' => $userUid, + 'userName' => $userName, + 'firstName'=> $firstName, + 'lastName' => $lastName, + 'status' => $status + ) ); + return $pmResults; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } - /** - * Summary of executeTrigger - * executes a ProcessMaker trigger. - * Note that triggers which are tied to case derivation will be executed automatically, so this function does not need to be called when deriving cases. - * Embedded executeTrigger() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#executeTrigger.28.29) - * A session must be open before with login() - * @param $caseId The case ID, which is can be found with caseList(). - * @param $triggerIndex The ID of the trigger to execute, which can be found with triggerList(). - * @param $delIndex The delegation index number of the case, which can be found with caseList(). - * @return A pmResponse object. If successful, the message will contain "executed: ". Otherwise false in case of SOAP error - */ - function executeTrigger( $caseId, $triggerIndex, $delIndex ) { - try { - $pmResults = $this->pmSoapClient->executeTrigger(array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId, 'triggerIndex'=> $triggerIndex, 'delIndex' => $delIndex ) ) ; - return $pmResults ; - } - catch ( Exception $e ) { - Toolbox::logDebug( $e ); - return false ; - } - } + /** + * Summary of executeTrigger + * executes a ProcessMaker trigger. + * Note that triggers which are tied to case derivation will be executed automatically, so this function does not need to be called when deriving cases. + * Embedded executeTrigger() PM web service call (definition: http://wiki.processmaker.com/index.php/2.0/ProcessMaker_WSDL_Web_Services#executeTrigger.28.29) + * A session must be open before with login() + * @param $caseId The case ID, which is can be found with caseList(). + * @param $triggerIndex The ID of the trigger to execute, which can be found with triggerList(). + * @param $delIndex The delegation index number of the case, which can be found with caseList(). + * @return A pmResponse object. If successful, the message will contain "executed: ". Otherwise false in case of SOAP error + */ + function executeTrigger( $caseId, $triggerIndex, $delIndex ) { + try { + $pmResults = $this->pmSoapClient->executeTrigger(array( 'sessionId' => $_SESSION["pluginprocessmaker"]["session"]["id"], 'caseId' => $caseId, 'triggerIndex'=> $triggerIndex, 'delIndex' => $delIndex ) ); + return $pmResults; + } catch (Exception $e) { + Toolbox::logDebug( $e ); + return false; + } + } - /** - * summary of cronInfo - * Gives localized information about 1 cron task - * @param $name of the task - * @return array of strings - */ - static function cronInfo($name) { - global $LANG; + /** + * summary of cronInfo + * Gives localized information about 1 cron task + * @param $name of the task + * @return array of strings + */ + static function cronInfo($name) { + global $LANG; - switch ($name) { - case 'pmusers' : - return array('description' => $LANG['processmaker']['cron']['pmusers'] ); - //case 'pmnotifications' : - // return array('description' => $LANG['processmaker']['cron']['pmnotifications'] ); - case 'pmorphancases' : - return array('description' => $LANG['processmaker']['cron']['pmorphancases']['description'], 'parameter' => $LANG['processmaker']['cron']['pmorphancases']['parameter'] ); - case 'pmtaskactions' : - return array('description' => $LANG['processmaker']['cron']['pmtaskactions'] ); - } - return array(); - } + switch ($name) { + case 'pmusers' : + return array('description' => $LANG['processmaker']['cron']['pmusers'] ); + case 'pmorphancases' : + return array('description' => $LANG['processmaker']['cron']['pmorphancases']['description'], 'parameter' => $LANG['processmaker']['cron']['pmorphancases']['parameter'] ); + case 'pmtaskactions' : + return array('description' => $LANG['processmaker']['cron']['pmtaskactions'] ); + } + return array(); + } /** * summary of cronPMTaskActions @@ -978,76 +934,77 @@ class PluginProcessmakerProcessmaker extends CommonDBTM { global $DB, $CFG_GLPI, $PM_DB; if (!isset($PM_DB)) { - $PM_DB = new PluginProcessmakerDB ; + $PM_DB = new PluginProcessmakerDB; } $actionCode = 0; // by default - $error = false ; + $error = false; $task->setVolume(0); // start with zero $pm = new self; - $existingpmsession = isset($_SESSION["pluginprocessmaker"]["session"]) ; - $formerusers_id = 0 ; + $existingpmsession = isset($_SESSION["pluginprocessmaker"]["session"]); + $formerusers_id = 0; // get the list of taskactions to be done - foreach( $DB->request( getTableForItemType('PluginProcessmakerCrontaskaction'), ' `state` = '.PluginProcessmakerCrontaskaction::DATAS_READY ) as $taskaction ) { + foreach ($DB->request( getTableForItemType('PluginProcessmakerCrontaskaction'), ' `state` = '.PluginProcessmakerCrontaskaction::DATAS_READY ) as $taskaction) { - try{ + try { - if( $formerusers_id != $taskaction['users_id']) { - unset($_SESSION["pluginprocessmaker"]["session"]) ; // to reset previous user login if any + if ($formerusers_id != $taskaction['users_id']) { + unset($_SESSION["pluginprocessmaker"]["session"]); // to reset previous user login if any } $pm->login($taskaction['users_id']); - $postdatas = json_decode($taskaction['postdatas'], true) ; + $postdatas = json_decode($taskaction['postdatas'], true); - if( $taskaction['toclaim'] ) { + if ($taskaction['toclaim']) { // must do a claim before solving task - if( !$pm->claimCase( $postdatas['APP_UID'], $postdatas['DEL_INDEX'] ) ) - throw new Exception("Can't claim case"); + if (!$pm->claimCase( $postdatas['APP_UID'], $postdatas['DEL_INDEX'] )) { + throw new Exception("Can't claim case"); + } $donotif = $CFG_GLPI["use_mailing"]; - $CFG_GLPI["use_mailing"] = false ; + $CFG_GLPI["use_mailing"] = false; // now manage tasks associated with item - $pm->claimTask( $postdatas['APP_UID'], $postdatas['DEL_INDEX'], $taskaction['users_id'] ) ; + $pm->claimTask( $postdatas['APP_UID'], $postdatas['DEL_INDEX'], $taskaction['users_id'] ); - $CFG_GLPI["use_mailing"] = $donotif ; + $CFG_GLPI["use_mailing"] = $donotif; } - $myCase = new PluginProcessmakerCase ; - if( $myCase->getFromDB( $postdatas['APP_UID'] )) { + $myCase = new PluginProcessmakerCase; + if ($myCase->getFromDB( $postdatas['APP_UID'] )) { //$cookies = json_decode($taskaction['cookies'], true) ; - $pm->derivateCase( $myCase, $postdatas, $taskaction['users_id'] ) ; + $pm->derivateCase( $myCase, $postdatas, $taskaction['users_id'] ); } $tkaction = new PluginProcessmakerCrontaskaction; - $tkaction->update( array( 'id' => $taskaction['id'], 'state' => PluginProcessmakerCrontaskaction::DONE ) ) ; + $tkaction->update( array( 'id' => $taskaction['id'], 'state' => PluginProcessmakerCrontaskaction::DONE ) ); $task->addVolume(1); - $task->log( "Applied task action id: '".$taskaction['id']."'" ) ; + $task->log( "Applied task action id: '".$taskaction['id']."'" ); - } catch( Exception $e ) { - $task->log( "Can't apply task action id: '".$taskaction['id']."'" ) ; - $error = true ; + } catch (Exception $e) { + $task->log( "Can't apply task action id: '".$taskaction['id']."'" ); + $error = true; } - $formerusers_id = $taskaction['users_id'] ; + $formerusers_id = $taskaction['users_id']; } - if( $existingpmsession ) { - unset($_SESSION["pluginprocessmaker"]["session"]) ; // reset the one created during the foreach + if ($existingpmsession) { + unset($_SESSION["pluginprocessmaker"]["session"]); // reset the one created during the foreach if (!Session::isCron()) { $pm->login(); // re-log default user } } - - if($error) - return -1 ; - else + if ($error) { + return -1; + } else { return $actionCode; + } } /** @@ -1059,515 +1016,441 @@ class PluginProcessmakerProcessmaker extends CommonDBTM { * <0 : to be run again (not finished) * 0 : nothing to do */ - static function cronPMOrphanCases($task) { - global $PM_DB, $DB ; + static function cronPMOrphanCases($task) { + global $PM_DB, $DB; - if (!isset($PM_DB)) { - $PM_DB = new PluginProcessmakerDB ; - } + if (!isset($PM_DB)) { + $PM_DB = new PluginProcessmakerDB; + } - // get list of case assigned to GLPi items - $draftCases = array(0) ; - $query = "SELECT case_num FROM glpi_plugin_processmaker_cases WHERE case_status = 'DRAFT';" ; - foreach($DB->request( $query ) as $row){ - $draftCases[] = $row['case_num'] ; - } + // get list of case assigned to GLPi items + $draftCases = array(0); + $query = "SELECT case_num FROM glpi_plugin_processmaker_cases WHERE case_status = 'DRAFT';"; + foreach ($DB->request( $query ) as $row) { + $draftCases[] = $row['case_num']; + } - $actionCode = 0; // by default - $error = false ; - $task->setVolume(0); // start with zero + $actionCode = 0; // by default + $error = false; + $task->setVolume(0); // start with zero - if( count($draftCases) > 0 ) { - $pm = new self; - $pm->login(true); - $query = "SELECT * FROM application + if (count($draftCases) > 0) { + $pm = new self; + $pm->login(true); + $query = "SELECT * FROM APPLICATION WHERE APP_DATA LIKE '%s:24:\"GLPI_SELFSERVICE_CREATED\";s:1:\"1\"%' AND APP_STATUS = 'DRAFT' AND DATEDIFF( NOW(), APP_UPDATE_DATE) > ".$task->fields['param']." AND APP_NUMBER NOT IN (".implode(',', $draftCases)."); - " ; - foreach( $PM_DB->request( $query ) as $row ){ - $ret = $pm->deleteCase( $row['APP_UID'] ) ; - $task->addVolume(1); - if( $ret !== false ) { - $task->log( "Deleted case num: '".$row['APP_NUMBER']."'" ) ; - $actionCode = 1 ; - } else { - $task->log( "Can't delete case num: '".$row['APP_NUMBER']."'" ) ; - $error = true ; - } - } - } - if($error) - return -1 ; - else - return $actionCode; + "; + foreach ($PM_DB->request( $query ) as $row) { + $ret = $pm->deleteCase( $row['APP_UID'] ); + $task->addVolume(1); + if ($ret !== false) { + $task->log( "Deleted case num: '".$row['APP_NUMBER']."'" ); + $actionCode = 1; + } else { + $task->log( "Can't delete case num: '".$row['APP_NUMBER']."'" ); + $error = true; + } + } + } + if ($error) { + return -1; + } else { + return $actionCode; + } - } - ///** - //* summary of cronPMNotifications - //* Execute 1 task managed by the plugin - //* @param: $task CronTask class for log / stat - //* @return integer - //* >0 : done - //* <0 : to be run again (not finished) - //* 0 : nothing to do - //*/ - //static function cronPMNotifications($task) { - // global $DB, $GLOBALS, $CFG_GLPI ; + } + - // $actionCode = 0; // by default - // $error = false ; - // $task->setVolume(0); // start with zero + /** + * summary of cronPMUsers + * Executes 1 task managed by the plugin + * @param $task CronTask class for log / stat + * @return integer + * >0 : done + * <0 : to be run again (not finished) + * 0 : nothing to do + */ + static function cronPMUsers($task) { + global $DB, $PM_DB; - // if ( $CFG_GLPI["use_mailing"]) { + if (!isset($PM_DB)) { + $PM_DB = new PluginProcessmakerDB; + } - // // will simulate a real session - // $oldGlpiCronUserRunning = $_SESSION["glpicronuserrunning"] ; + $actionCode = 0; // by default + $error = false; + $task->setVolume(0); // start with zero - // // get the complete user list from GLPI DB - // $taskNotificationList = array() ; - // foreach($DB->request("SELECT * FROM glpi_plugin_processmaker_tasksnotifications ORDER BY id") as $locTicketNotification) { - // $locTicketTask = new TicketTask; - // if( $locTicketTask->getFromDB( $locTicketNotification['task_id'] ) ){ - // $locTec = new User ; - // $locTec->getFromDB( $locTicketNotification['tech_id'] ) ; - // if( $locTec->getFromDB( $locTicketNotification['tech_id'] ) && substr( $locTec->fields['realname'], 0, 1) != "*" ){ - // $_SESSION["glpicronuserrunning"] = $locTec->fields['realname']." ".$locTec->fields['firstname'] ; - // } - // switch( $locTicketNotification['action'] ) { - // case 'INSERT' : - // // in this case, we need the ticket in $locTicketTask->input['_job'] - // $item = new Ticket(); - // $item->getFromDB( $locTicketTask->fields['tickets_id'] ); - // $locTicketTask->input['_job']=$item; + // start a processmaker session + $myProcessMaker = new PluginProcessmakerProcessmaker(); + if (!$myProcessMaker->login( true )) { + $task->log( "Error PM: '".print_r($myProcessMaker->lasterror, true)."'" ); + return -1; + } - // $locTicketTask->post_addItem( ) ; - // break; - // case 'UPDATE' : - // // in this case we need to add updates array to $locTicketTask - // $locTicketTask->updates[] = 'actiontime' ; - // $locTicketTask->updates[] = 'state' ; - // $locTicketTask->updates[] = 'begin' ; - // $locTicketTask->updates[] = 'end' ; - // $locTicketTask->updates[] = 'users_id_tech' ; - // $locTicketTask->post_updateItem( ) ; - // break ; - // } - // $task->addVolume(1); - // //$task->log( "Notification sent" ) ; - // $_SESSION["glpicronuserrunning"] = $oldGlpiCronUserRunning ; - // } - // $query = "DELETE FROM glpi_plugin_processmaker_tasksnotifications WHERE id=".$locTicketNotification['id'].";" ; - // $DB->query( $query ) ; - // } + $pmGroupList = $myProcessMaker->groupList( ); + foreach ($pmGroupList as $pmGroup) { + if ($pmGroup->guid == $myProcessMaker->pm_group_guid) { + break; // to get the name :) + } + } - // } else { - // $task->log( "Notification are disabled!" ) ; - // // we must delete all existing notifications requests - // $query = "DELETE FROM glpi_plugin_processmaker_tasksnotifications;" ; - // $DB->query( $query ) ; - // } + $pmUserList = array(); + foreach ($myProcessMaker->userList() as $pmuser) { + $pmUserList[ strtolower($pmuser->name)] = array( 'name' => $pmuser->name, 'guid' => $pmuser->guid, 'status' => $pmuser->status ); + } - - // if($error) - // return -1 ; - // else - // return $actionCode; - - //} - - - /** - * summary of cronPMUsers - * Executes 1 task managed by the plugin - * @param $task CronTask class for log / stat - * @return integer - * >0 : done - * <0 : to be run again (not finished) - * 0 : nothing to do - */ - static function cronPMUsers($task) { - global $DB, $PM_DB ; - - if (!isset($PM_DB)) { - $PM_DB = new PluginProcessmakerDB ; - } - - $actionCode = 0; // by default - $error = false ; - $task->setVolume(0); // start with zero - - // start a processmaker session - $myProcessMaker = new PluginProcessmakerProcessmaker(); - if( !$myProcessMaker->login( true ) ) { - $task->log( "Error PM: '".print_r($myProcessMaker->lasterror, true)."'" ) ; - return -1 ; - } - - $pmGroupList = $myProcessMaker->groupList( ) ; - foreach( $pmGroupList as $pmGroup ) { - if( $pmGroup->guid == $myProcessMaker->pm_group_guid ) break ; // to get the name :) - } - - $pmUserList = array() ; - foreach( $myProcessMaker->userList() as $pmuser) { - $pmUserList[ strtolower($pmuser->name)] = array( 'name' => $pmuser->name, 'guid' => $pmuser->guid, 'status' => $pmuser->status ) ; - } - - // get the complete user list from GLPI DB - $glpiUserList = array() ; - foreach($DB->request("SELECT glpi_users.id, glpi_users.name, glpi_users.realname, glpi_users.firstname, glpi_users.is_active, glpi_users.is_deleted, glpi_plugin_processmaker_users.pm_users_id as pmUserId + // get the complete user list from GLPI DB + $glpiUserList = array(); + foreach ($DB->request("SELECT glpi_users.id, glpi_users.name, glpi_users.realname, glpi_users.firstname, glpi_users.is_active, glpi_users.is_deleted, glpi_plugin_processmaker_users.pm_users_id as pmUserId FROM glpi_users LEFT JOIN glpi_plugin_processmaker_users on glpi_plugin_processmaker_users.id = glpi_users.id WHERE name not like '*%'") as $dbgroup) { - $glpiUserList[ strtolower($dbgroup['name'])] = $dbgroup ; - } + $glpiUserList[ strtolower($dbgroup['name'])] = $dbgroup; + } - $arrayDiff = array_diff_key( $glpiUserList, $pmUserList ) ; + $arrayDiff = array_diff_key( $glpiUserList, $pmUserList ); - foreach( $arrayDiff as $user ){ - if( $user['is_active'] != 0 && $user['is_deleted'] != 1 ) { - $status = "ACTIVE" ; - $task->addVolume(1); - $pass = substr( Toolbox::encrypt($user['id'].$user['name'].time(), GLPIKEY), 0, 20) ; - $pmResult = $myProcessMaker->createUser( $user['name'], $user['firstname'], $user['realname'], "", "PROCESSMAKER_OPERATOR", $pass , $status) ; - if( $pmResult->status_code == 0) { - $task->log( "Added user: '".$user['name']."'" ) ; + foreach ($arrayDiff as $user) { + if ($user['is_active'] != 0 && $user['is_deleted'] != 1) { + $status = "ACTIVE"; + $task->addVolume(1); + $pass = substr( Toolbox::encrypt($user['id'].$user['name'].time(), GLPIKEY), 0, 20); + $pmResult = $myProcessMaker->createUser( $user['name'], $user['firstname'], $user['realname'], "", "PROCESSMAKER_OPERATOR", $pass, $status); + if ($pmResult->status_code == 0) { + $task->log( "Added user: '".$user['name']."'" ); - // then assign user to group - $pmResult2 = $myProcessMaker->assignUserToGroup( $pmResult->userUID, $pmGroup->guid ) ; - if( $pmResult2->status_code == 0 ) - $task->log( "Added user: '".$user['name']."' to '".$pmGroup->name."' group" ) ; - else - $task->log( "Error PM: '".$pmResult2->message."'" ) ; + // then assign user to group + $pmResult2 = $myProcessMaker->assignUserToGroup( $pmResult->userUID, $pmGroup->guid ); + if ($pmResult2->status_code == 0) { + $task->log( "Added user: '".$user['name']."' to '".$pmGroup->name."' group" ); + } else { + $task->log( "Error PM: '".$pmResult2->message."'" ); + } - // insert into DB the link between glpi users and pm user - $pmuser = new PluginProcessmakerUser ; - if( $pmuser->getFromDB( $user['id'] ) ) { - $pmuser->update( array( 'id' => $user['id'], 'pm_users_id' => $pmResult->userUID, 'password' => md5( $pass ) ) ) ; - } else { - $pmuser->add( array( 'id' => $user['id'], 'pm_users_id' => $pmResult->userUID, 'password' => md5( $pass ) ) ) ; - } - $actionCode = 1 ; + // insert into DB the link between glpi users and pm user + $pmuser = new PluginProcessmakerUser; + if ($pmuser->getFromDB( $user['id'] )) { + $pmuser->update( array( 'id' => $user['id'], 'pm_users_id' => $pmResult->userUID, 'password' => md5( $pass ) ) ); + } else { + $pmuser->add( array( 'id' => $user['id'], 'pm_users_id' => $pmResult->userUID, 'password' => md5( $pass ) ) ); + } + $actionCode = 1; - } else { - $task->log( "Error adding user: '".$user['name']."'" ) ; - $task->log( "Error PM: '".$pmResult->message."'" ) ; - $actionCode = -1 ; - $error = true ; - } - } else - unset( $glpiUserList[$user['name']] ) ; - } + } else { + $task->log( "Error adding user: '".$user['name']."'" ); + $task->log( "Error PM: '".$pmResult->message."'" ); + $actionCode = -1; + $error = true; + } + } else { + unset( $glpiUserList[$user['name']] ); + } + } - if( !$error ) { + if (!$error) { - // now should refresh the existing users - $arrayIntersect = array_intersect_key( $glpiUserList, $pmUserList ) ; - foreach( $arrayIntersect as $user ){ - if( $user['pmUserId'] == null || ($user['pmUserId'] != $pmUserList[strtolower($user['name'])]['guid'])){ //must be inserted into DB - // insert into DB the link between glpi users and pm user - $pmuser = new PluginProcessmakerUser ; - if( $pmuser->getFromDB( $user['id'] ) ) { - $ret = $pmuser->update( array( 'id' => $user['id'], 'pm_users_id' => $pmUserList[strtolower($user['name'])]['guid'] ) ) ; - } else { - $ret = $pmuser->add( array( 'id' => $user['id'], 'pm_users_id' => $pmUserList[strtolower($user['name'])]['guid'] ) ) ; - } + // now should refresh the existing users + $arrayIntersect = array_intersect_key( $glpiUserList, $pmUserList ); + foreach ($arrayIntersect as $user) { + if ($user['pmUserId'] == null || ($user['pmUserId'] != $pmUserList[strtolower($user['name'])]['guid'])) { //must be inserted into DB + // insert into DB the link between glpi users and pm user + $pmuser = new PluginProcessmakerUser; + if ($pmuser->getFromDB( $user['id'] )) { + $ret = $pmuser->update( array( 'id' => $user['id'], 'pm_users_id' => $pmUserList[strtolower($user['name'])]['guid'] ) ); + } else { + $ret = $pmuser->add( array( 'id' => $user['id'], 'pm_users_id' => $pmUserList[strtolower($user['name'])]['guid'] ) ); + } - //$query = "REPLACE INTO glpi_plugin_processmaker_users (glpi_users_id, pm_users_id) VALUES (".$user['id'].", '". $pmUserList[strtolower($user['name'])]['guid']."');" ; - //$DB->query( $query ) or - if( !$ret ) { - $task->log( "Cannot update user: '".$user['id']."' into glpi_plugin_processmaker_users!" ) ; - } - - } - if( $user['is_active'] == 0 || $user['is_deleted'] == 1 ) - $status = "INACTIVE" ; - else - $status = "ACTIVE" ; - if( $status != $pmUserList[strtolower($user['name'])]['status'] ) { - $task->addVolume(1); - $pmResult = $myProcessMaker->updateUser( $pmUserList[strtolower($user['name'])]['guid'], $user['name'], $user['firstname'], $user['realname'], $status ) ; - if( $pmResult->status_code == 0) { - $task->log( "Updated user: '".$user['name']."', status: '".$pmUserList[strtolower($user['name'])]['status']."' -> '".$status."'" ) ; - $actionCode = 1 ; - } else { - $task->log( "Error updating user: '".$user['name']."'" ) ; - $task->log( "Error PM: '".$pmResult->message."'" ) ; - $actionCode = -1 ; - $error = true ; - } - } + //$query = "REPLACE INTO glpi_plugin_processmaker_users (glpi_users_id, pm_users_id) VALUES (".$user['id'].", '". $pmUserList[strtolower($user['name'])]['guid']."');" ; + //$DB->query( $query ) or + if (!$ret) { + $task->log( "Cannot update user: '".$user['id']."' into glpi_plugin_processmaker_users!" ); + } } - } - - // now we should desactivate PM users who are not in glpi user list - //if( !$error ) { - // $status = "INACTIVE" ; - // $arrayDiff = array_diff_key( $pmUserList , $glpiUserList ) ; - // foreach( $arrayDiff as $user ){ - // $task->addVolume(1); - // if( $user['status'] == 'ACTIVE' && $user['name'] != 'admin' && $user['name'] != 'glpi'){ - // $pmResult = $myProcessMaker->updateUser( $user['guid'], $user['name'], null, null, $status ) ; - // if( $pmResult->status_code == 0) { - // $task->log( "Updated user: '".$user['name']."', status: '".$user['status']."' -> '".$status."'" ) ; - // $actionCode = 1 ; - // } else { - // $task->log( "Error updating user: '".$user['name']."'" ) ; - // $task->log( "Error PM: '".$pmResult->message."'" ) ; - // $actionCode = -1 ; - // $error = true ; - // } - // } - // } - //} - - - - // so now treat GLPI groups - $glpiGroupList = array(); - foreach($DB->request("SELECT id, name, is_task, is_usergroup FROM glpi_groups WHERE is_task=1 AND is_usergroup=1") as $dbgroup) { - $glpiGroupList[$dbgroup['name']] = $dbgroup; - } - - $pmGroupList = self::getPMGroups(); // array(); - //foreach($PM_DB->request("SELECT * FROM content WHERE content.CON_CATEGORY='GRP_TITLE' AND content.CON_LANG='en'") as $dbgroup){ - // $pmGroupList[$dbgroup['CON_VALUE']] = $dbgroup; - //} - - // here we can compare group lists like done for the users - $arrayDiff = array_diff_key( $glpiGroupList, $pmGroupList ) ; - - // then for each group we must check if it exists, and if not create a real PM group - foreach( $arrayDiff as $group ) { - // it is not existing in PM - // then create - $pmResult = $myProcessMaker->createGroup( $group['name'] ) ; - if( $pmResult->status_code == 0) { - $task->addVolume(1); - $task->log( "Added group: '".$group['name']."'" ) ; + if ($user['is_active'] == 0 || $user['is_deleted'] == 1) { + $status = "INACTIVE"; + } else { + $status = "ACTIVE"; + } + if ($status != $pmUserList[strtolower($user['name'])]['status']) { + $task->addVolume(1); + $pmResult = $myProcessMaker->updateUser( $pmUserList[strtolower($user['name'])]['guid'], $user['name'], $user['firstname'], $user['realname'], $status ); + if ($pmResult->status_code == 0) { + $task->log( "Updated user: '".$user['name']."', status: '".$pmUserList[strtolower($user['name'])]['status']."' -> '".$status."'" ); + $actionCode = 1; + } else { + $task->log( "Error updating user: '".$user['name']."'" ); + $task->log( "Error PM: '".$pmResult->message."'" ); + $actionCode = -1; + $error = true; + } } - } - // review and update all users in each group - $pmGroupList = self::getPMGroups(); // array(); - //$pmGroupList = array() ; // reset groups and get the new complete list from PM DB - //foreach($PM_DB->request("SELECT * FROM content WHERE content.CON_CATEGORY='GRP_TITLE' AND content.CON_LANG='en'") as $dbgroup){ - // $pmGroupList[$dbgroup['CON_VALUE']] = $dbgroup ; - //} + } + } - // now should refresh the existing users into groups - $arrayDiff = array_intersect_key( $glpiGroupList, $pmGroupList ) ; - foreach( $arrayDiff as $group ){ - // for each group will delete users and re-create them - // not really optimized, but this way we are sure that groups are synchronized - // must be redesigned - $query = "DELETE FROM group_user WHERE group_user.GRP_UID='".$pmGroupList[$group['name']]['CON_ID']."';"; - $PM_DB->query( $query ) ; - // and insert all users from real GLPI group - foreach( $DB->request("SELECT glpi_groups_users.users_id, glpi_plugin_processmaker_users.pm_users_id + // now we should desactivate PM users who are not in glpi user list + //if( !$error ) { + // $status = "INACTIVE" ; + // $arrayDiff = array_diff_key( $pmUserList , $glpiUserList ) ; + // foreach( $arrayDiff as $user ){ + // $task->addVolume(1); + // if( $user['status'] == 'ACTIVE' && $user['name'] != 'admin' && $user['name'] != 'glpi'){ + // $pmResult = $myProcessMaker->updateUser( $user['guid'], $user['name'], null, null, $status ) ; + // if( $pmResult->status_code == 0) { + // $task->log( "Updated user: '".$user['name']."', status: '".$user['status']."' -> '".$status."'" ) ; + // $actionCode = 1 ; + // } else { + // $task->log( "Error updating user: '".$user['name']."'" ) ; + // $task->log( "Error PM: '".$pmResult->message."'" ) ; + // $actionCode = -1 ; + // $error = true ; + // } + // } + // } + //} + + // so now treat GLPI groups + $glpiGroupList = array(); + foreach ($DB->request("SELECT id, name, is_task, is_usergroup FROM glpi_groups WHERE is_task=1 AND is_usergroup=1") as $dbgroup) { + $glpiGroupList[$dbgroup['name']] = $dbgroup; + } + + $pmGroupList = self::getPMGroups(); // array(); + + // here we can compare group lists like done for the users + $arrayDiff = array_diff_key( $glpiGroupList, $pmGroupList ); + + // then for each group we must check if it exists, and if not create a real PM group + foreach ($arrayDiff as $group) { + // it is not existing in PM + // then create + $pmResult = $myProcessMaker->createGroup( $group['name'] ); + if ($pmResult->status_code == 0) { + $task->addVolume(1); + $task->log( "Added group: '".$group['name']."'" ); + } + } + + // review and update all users in each group + $pmGroupList = self::getPMGroups(); // array(); + + // now should refresh the existing users into groups + $arrayDiff = array_intersect_key( $glpiGroupList, $pmGroupList ); + foreach ($arrayDiff as $group) { + // for each group will delete users and re-create them + // not really optimized, but this way we are sure that groups are synchronized + // must be redesigned + $query = "DELETE FROM GROUP_USER WHERE GROUP_USER.GRP_UID='".$pmGroupList[$group['name']]['CON_ID']."';"; + $PM_DB->query( $query ); + // and insert all users from real GLPI group + foreach ($DB->request("SELECT glpi_groups_users.users_id, glpi_plugin_processmaker_users.pm_users_id FROM glpi_groups JOIN glpi_groups_users ON glpi_groups_users.groups_id=glpi_groups.id JOIN glpi_plugin_processmaker_users ON glpi_plugin_processmaker_users.id=glpi_groups_users.users_id WHERE glpi_groups.name='".$group['name']."'") as $user ) { - $query = "INSERT INTO group_user (`GRP_UID`, `USR_UID`) VALUES ( '".$pmGroupList[$group['name']]['CON_ID']."', '".$user['pm_users_id']."' )" ; - $PM_DB->query( $query ) ; - } - $task->addVolume(1); - $task->log( "Updated users into PM group: '".$group['name']."'" ) ; - } + $query = "INSERT INTO GROUP_USER (`GRP_UID`, `USR_UID`) VALUES ( '".$pmGroupList[$group['name']]['CON_ID']."', '".$user['pm_users_id']."' )"; + $PM_DB->query( $query ); + } + $task->addVolume(1); + $task->log( "Updated users into PM group: '".$group['name']."'" ); + } - // now should renew the duedate of the users - $PM_DB->query("UPDATE users SET USR_DUE_DATE='2035-12-31' WHERE USR_DUE_DATE<>'2035-12-31'; ") ; - $PM_DB->query("UPDATE rbac_users SET USR_DUE_DATE='2035-12-31' WHERE USR_DUE_DATE<>'2035-12-31'; ") ; + // now should renew the duedate of the users + $PM_DB->query("UPDATE USERS SET USR_DUE_DATE='2035-12-31' WHERE USR_DUE_DATE<>'2035-12-31'; "); + $PM_DB->query("UPDATE RBAC_USERS SET USR_DUE_DATE='2035-12-31' WHERE USR_DUE_DATE<>'2035-12-31'; "); - if($error) - return -1 ; - else - return $actionCode; + if ($error) { + return -1; + } else { + return $actionCode; + } } - public static function plugin_pre_item_add_processmaker($parm) { - global $PM_DB; + public static function plugin_pre_item_add_processmaker($parm) { + global $PM_DB; - if( isset($parm->input['processmaker_caseid']) ) { - // a case is already started for this ticket, then change ticket title and ticket type and ITILCategory + if (isset($parm->input['processmaker_caseid'])) { + // a case is already started for this ticket, then change ticket title and ticket type and ITILCategory - $myProcessMaker = new PluginProcessmakerProcessmaker( ) ; - $myProcessMaker->login( ) ; - $caseInfo = $myProcessMaker->getCaseInfo( $parm->input['processmaker_caseid'], $parm->input['processmaker_delindex']) ; - $parm->input['name'] = $PM_DB->escape($caseInfo->caseName ) ; + $myProcessMaker = new PluginProcessmakerProcessmaker( ); + $myProcessMaker->login( ); + $caseInfo = $myProcessMaker->getCaseInfo( $parm->input['processmaker_caseid'], $parm->input['processmaker_delindex']); + $parm->input['name'] = $PM_DB->escape($caseInfo->caseName ); - $caseInitialDueDate = $myProcessMaker->getVariables( $parm->input['processmaker_caseid'], array( 'GLPI_ITEM_TITLE', 'GLPI_ITEM_INITIAL_DUE_DATE' )) ; - if( array_key_exists( 'GLPI_ITEM_INITIAL_DUE_DATE', $caseInitialDueDate ) ) { - $parm->input['due_date'] = $caseInitialDueDate[ 'GLPI_ITEM_INITIAL_DUE_DATE' ]." 23:59:59" ; + $caseInitialDueDate = $myProcessMaker->getVariables( $parm->input['processmaker_caseid'], array( 'GLPI_ITEM_TITLE', 'GLPI_ITEM_INITIAL_DUE_DATE' )); + if (array_key_exists( 'GLPI_ITEM_INITIAL_DUE_DATE', $caseInitialDueDate )) { + $parm->input['due_date'] = $caseInitialDueDate[ 'GLPI_ITEM_INITIAL_DUE_DATE' ]." 23:59:59"; + } + $txtItemTitle = $caseInfo->caseName; + if (array_key_exists( 'GLPI_ITEM_TITLE', $caseInitialDueDate )) { + $txtItemTitle = $caseInitialDueDate[ 'GLPI_ITEM_TITLE' ]; + // reset those variables + $resultSave = $myProcessMaker->sendVariables( $parm->input['processmaker_caseid'], array( "GLPI_ITEM_TITLE" => '') ); + } + $parm->input['name'] = $PM_DB->escape($txtItemTitle ); + + $procDef = new PluginProcessmakerProcess; + $procDef->getFromDBbyExternalID( $caseInfo->processId ); + if (isset($parm->input['type'])) { + $parm->input['type'] = $procDef->fields['type']; + } + + if (isset($parm->input['itilcategories_id'])) { + $parm->input['itilcategories_id'] = $procDef->fields['itilcategories_id']; + } + + } + } + + public static function plugin_item_add_processmaker($parm) { + global $DB, $GLOBALS; + + if (isset($parm->input['processmaker_caseid'])) { + // a case is already started for this ticket, then bind them together + $itemType = $parm->getType(); //$myCase->getField('itemtype'); + $itemId = $parm->fields['id']; //$myCase->getField('items_id'); + $caseId = $parm->input['processmaker_caseid']; + + $myCase = new PluginProcessmakerCase; + + //can't use std add due to forced case id + $process = new PluginProcessmakerProcess; + $process->getFromDBbyExternalID( $parm->input['processId'] ); + $query = "INSERT INTO glpi_plugin_processmaker_cases (items_id, itemtype, id, case_num, processes_id) VALUES ($itemId, '$itemType', '$caseId', ".$parm->input['processmaker_casenum'].", '".$process->getID()."');"; + $res = $DB->query($query); + + $myCase->getFromDB( $caseId ); // reloads case from DB + + $myProcessMaker = new PluginProcessmakerProcessmaker( ); + $myProcessMaker->login( ); + + $caseInfo = $myProcessMaker->getCaseInfo( $myCase->getID(), $parm->input['processmaker_delindex']); + + // here we create a fake task that will be used to store the creator of the case + // this is due for traceability only + $myProcessMaker->add1stTask( $myCase->fields['itemtype'], $myCase->fields['items_id'], $caseInfo, array( 'notif' => false) ); // no notif + // route case + $pmRouteCaseResponse = $myProcessMaker->routeCase( $myCase->getID(), $parm->input['processmaker_delindex'] ); + + // gets new case status + $caseInfo = $myProcessMaker->getCaseInfo( $myCase->getID(), $parm->input['processmaker_delindex']); + // now manage tasks associated with item + // create new tasks + if (property_exists( $pmRouteCaseResponse, 'routing' )) { + // now tries to get some variables to setup content for new task and to append text to solved task + $txtForTasks = $myProcessMaker->getVariables( $myCase->getID(), array( "GLPI_ITEM_APPEND_TO_TASK", + "GLPI_ITEM_SET_STATUS" ) ); + $itemSetStatus = ''; + if (array_key_exists( 'GLPI_ITEM_SET_STATUS', $txtForTasks )) { + $itemSetStatus = $txtForTasks[ 'GLPI_ITEM_SET_STATUS' ]; } - $txtItemTitle = $caseInfo->caseName; - if( array_key_exists( 'GLPI_ITEM_TITLE', $caseInitialDueDate ) ) { - $txtItemTitle = $caseInitialDueDate[ 'GLPI_ITEM_TITLE' ] ; - // reset those variables - $resultSave = $myProcessMaker->sendVariables( $parm->input['processmaker_caseid'] , array( "GLPI_ITEM_TITLE" => '') ) ; - } - $parm->input['name'] = $PM_DB->escape($txtItemTitle ) ; - - $procDef = new PluginProcessmakerProcess; - $procDef->getFromDBbyExternalID( $caseInfo->processId ) ; - if( isset($parm->input['type']) ){ - $parm->input['type'] = $procDef->fields['type'] ; + if (array_key_exists( 'GLPI_ITEM_APPEND_TO_TASK', $txtForTasks )) { + $txtToAppendToTask = $txtForTasks[ 'GLPI_ITEM_APPEND_TO_TASK' ]; + } else { + $txtToAppendToTask = ''; } - if( isset($parm->input['itilcategories_id']) ){ - $parm->input['itilcategories_id'] = $procDef->fields['itilcategories_id'] ; + // reset those variables + $resultSave = $myProcessMaker->sendVariables( $myCase->getID(), array( "GLPI_ITEM_APPEND_TO_TASK" => '', + "GLPI_ITEM_SET_STATUS" => '' ) ); + + // routing has been done, then solve 1st task + $myProcessMaker->solveTask( $myCase->getID(), $parm->input['processmaker_delindex'], array( 'txtToAppend' => $txtToAppendToTask, 'notif' => false) ); + + // and create GLPI tasks for the newly created PM tasks. + foreach ($pmRouteCaseResponse->routing as $route) { + $myProcessMaker->addTask( $myCase->fields['itemtype'], + $myCase->fields['items_id'], + $caseInfo, $route->delIndex, + PluginProcessmakerUser::getGLPIUserId( $route->userId ), + 0, + $route->taskId ); } - } - } - - public static function plugin_item_add_processmaker($parm) { - global $DB, $GLOBALS ; - - if( isset($parm->input['processmaker_caseid']) ) { - // a case is already started for this ticket, then bind them together - $itemType = $parm->getType() ; //$myCase->getField('itemtype'); - $itemId = $parm->fields['id'] ; //$myCase->getField('items_id'); - $caseId = $parm->input['processmaker_caseid'] ; - - $myCase = new PluginProcessmakerCase ; - - //can't use std add due to forced case id - $process = new PluginProcessmakerProcess; - $process->getFromDBbyExternalID( $parm->input['processId'] ) ; - $query = "INSERT INTO glpi_plugin_processmaker_cases (items_id, itemtype, id, case_num, processes_id) VALUES ($itemId, '$itemType', '$caseId', ".$parm->input['processmaker_casenum'].", '".$process->getID()."');" ; - $res = $DB->query($query) ; - - $myCase->getFromDB( $caseId ) ; // reloads case from DB - - $myProcessMaker = new PluginProcessmakerProcessmaker( ) ; - $myProcessMaker->login( ) ; - - $caseInfo = $myProcessMaker->getCaseInfo( $myCase->getID(), $parm->input['processmaker_delindex']) ; - - // here we create a fake task that will be used to store the creator of the case - // this is due for traceability only - $myProcessMaker->add1stTask( $myCase->fields['itemtype'], $myCase->fields['items_id'], $caseInfo, array( 'notif' => false) ); // no notif - // route case - $pmRouteCaseResponse = $myProcessMaker->routeCase( $myCase->getID(), $parm->input['processmaker_delindex'] ) ; - - // gets new case status - $caseInfo = $myProcessMaker->getCaseInfo( $myCase->getID(), $parm->input['processmaker_delindex']) ; - // now manage tasks associated with item - // create new tasks - if( property_exists( $pmRouteCaseResponse, 'routing' ) ) { - // now tries to get some variables to setup content for new task and to append text to solved task - $txtForTasks = $myProcessMaker->getVariables( $myCase->getID(), array( "GLPI_ITEM_APPEND_TO_TASK", - "GLPI_ITEM_SET_STATUS" ) ); - $itemSetStatus = ''; - if( array_key_exists( 'GLPI_ITEM_SET_STATUS', $txtForTasks ) ) { - $itemSetStatus = $txtForTasks[ 'GLPI_ITEM_SET_STATUS' ] ; - } - if( array_key_exists( 'GLPI_ITEM_APPEND_TO_TASK', $txtForTasks ) ) - $txtToAppendToTask = $txtForTasks[ 'GLPI_ITEM_APPEND_TO_TASK' ] ; - else - $txtToAppendToTask = '' ; - - // reset those variables - $resultSave = $myProcessMaker->sendVariables( $myCase->getID() , array( "GLPI_ITEM_APPEND_TO_TASK" => '', - "GLPI_ITEM_SET_STATUS" => '' ) ) ; - - // routing has been done, then solve 1st task - $myProcessMaker->solveTask( $myCase->getID(), $parm->input['processmaker_delindex'], array( 'txtToAppend' => $txtToAppendToTask, 'notif' => false) ) ; - - // and create GLPI tasks for the newly created PM tasks. - foreach( $pmRouteCaseResponse->routing as $route ) { - $myProcessMaker->addTask( $myCase->fields['itemtype'], - $myCase->fields['items_id'], - $caseInfo, $route->delIndex, - PluginProcessmakerUser::getGLPIUserId( $route->userId ), - 0, - $route->taskId ) ; - } - - if( $itemSetStatus != '' ) { - $myProcessMaker->setItemStatus($myCase->fields['itemtype'], $myCase->fields['items_id'], $itemSetStatus ) ; - } + if ($itemSetStatus != '') { + $myProcessMaker->setItemStatus($myCase->fields['itemtype'], $myCase->fields['items_id'], $itemSetStatus ); } + } - // evolution of case status: DRAFT, TO_DO, COMPLETED, CANCELLED - $myCase->update( array( 'id' => $myCase->getID(), 'case_status' => $caseInfo->caseStatus ) ) ; - } else {//if( array_key_exists('_head', $parm->input) ) { - // this ticket have been created via email receiver. - $ptnProcessToStart = "/##TicketProcess:\s*#([0-9a-f]{32})\s*##/i"; - $str = $parm->input['content'] ; - if( preg_match($ptnProcessToStart, $str, $matches) > 0 ){ - // and it is requested to start a case of process - $processId = $matches[1] ; - $hasCase = self::getCaseIdFromItem( 'Ticket', $parm->fields['id'] ) ; - if( $hasCase === false && $processId > 0 ) { - // check writer - $writer = new User; - $writer->getFromDB( $parm->fields['users_id_recipient'] ) ; - $myProcessMaker = new PluginProcessmakerProcessmaker() ; - $myProcessMaker->login( $writer->fields['name'] ) ; - $locProcess = new PluginProcessmakerProcess ; - if( $locProcess->getFromDBbyExternalID( $processId ) ) { - $found = false ; - // check rights of writer to start this $processId on the Ticket entity - foreach( Profile_User::getUserProfiles( $writer->getID() ) as $profID ) { - if( in_array( $parm->fields['entities_id'], PluginProcessmakerProcess::getEntitiesForProfileByProcess( $locProcess->getID(), $profID, true) ) ) { - $found=true; - break; - } - } - if( $found ) { - $resultCase = $myProcessMaker->startNewCase( $locProcess->getID(), 'Ticket', $parm->fields['id'], $writer->getID() ) ; + // evolution of case status: DRAFT, TO_DO, COMPLETED, CANCELLED + $myCase->update( array( 'id' => $myCase->getID(), 'case_status' => $caseInfo->caseStatus ) ); + } else {//if( array_key_exists('_head', $parm->input) ) { + // this ticket have been created via email receiver. + $ptnProcessToStart = "/##TicketProcess:\s*#([0-9a-f]{32})\s*##/i"; + $str = $parm->input['content']; + if (preg_match($ptnProcessToStart, $str, $matches) > 0) { + // and it is requested to start a case of process + $processId = $matches[1]; + $hasCase = self::getCaseIdFromItem( 'Ticket', $parm->fields['id'] ); + if ($hasCase === false && $processId > 0) { + // check writer + $writer = new User; + $writer->getFromDB( $parm->fields['users_id_recipient'] ); + $myProcessMaker = new PluginProcessmakerProcessmaker(); + $myProcessMaker->login( $writer->fields['name'] ); + $locProcess = new PluginProcessmakerProcess; + if ($locProcess->getFromDBbyExternalID( $processId )) { + $found = false; + // check rights of writer to start this $processId on the Ticket entity + foreach (Profile_User::getUserProfiles( $writer->getID() ) as $profID) { + if (in_array( $parm->fields['entities_id'], PluginProcessmakerProcess::getEntitiesForProfileByProcess( $locProcess->getID(), $profID, true) )) { + $found=true; + break; } } + if ($found) { + $resultCase = $myProcessMaker->startNewCase( $locProcess->getID(), 'Ticket', $parm->fields['id'], $writer->getID() ); + } } } - } - return ; - } + } + } + return; + } - public static function plugin_pre_item_add_processmaker_followup($parm) { - //global $DB ; + public static function plugin_pre_item_add_processmaker_followup($parm) { + //global $DB ; + + } - } - - - /** - * Summary of addWatcher - * add $techId as watcher to $glpi_item when techId has no rights on it - * @param string $itemType is the type of the CommonITILObject - * @param integer $itemId is the id of the ITIL object - * @param integer $techId is the users_id to be added - * @return boolean true if added, - */ +/** + * Summary of addWatcher + * add $techId as watcher to $glpi_item when techId has no rights on it + * @param string $itemType is the type of the CommonITILObject + * @param integer $itemId is the id of the ITIL object + * @param integer $techId is the users_id to be added + * @return boolean true if added, + */ public static function addWatcher( $itemType, $itemId, $techId ) { global $CFG_GLPI; // currently use $CFG_GLPI to disable notif //$plug = new Plugin; - if( $techId && $itemType != '' && $itemId > 0 ) { //!$plug->isActivated('arbehaviours') && + if ($techId && $itemType != '' && $itemId > 0) { //!$plug->isActivated('arbehaviours') && $glpi_item = getItemForItemtype( $itemType ); - $glpi_item->getFromDB( $itemId ) ; + $glpi_item->getFromDB( $itemId ); // then we should check if this user has rights on the item, if not then we must add it to the watcher list! $glpi_item = getItemForItemtype( $itemType ); - $glpi_item->getFromDB( $itemId ) ; - $user_entities = Profile_User::getUserEntities( $techId, true, true ) ; + $glpi_item->getFromDB( $itemId ); + $user_entities = Profile_User::getUserEntities( $techId, true, true ); $user_can_view = in_array( $glpi_item->fields['entities_id'], $user_entities ); - if( !$glpi_item->isUser( CommonITILActor::REQUESTER, $techId ) + if (!$glpi_item->isUser( CommonITILActor::REQUESTER, $techId ) && !$glpi_item->isUser( CommonITILActor::OBSERVER, $techId ) && !$glpi_item->isUser( CommonITILActor::ASSIGN, $techId ) && !$user_can_view ) { // then we must add this tech user to watcher list $glpi_item_user = getItemForItemtype( $glpi_item->getType() . "_User" ); $donotif = $CFG_GLPI["use_mailing"]; - $CFG_GLPI["use_mailing"] = false ; - $glpi_item_user->add( array( $glpi_item::getForeignKeyField() => $glpi_item->getId(), 'users_id' => $techId, 'type' => CommonITILActor::OBSERVER, '_disablenotif' => true ) ) ; // , '_no_notif' => true + $CFG_GLPI["use_mailing"] = false; + $glpi_item_user->add( array( $glpi_item::getForeignKeyField() => $glpi_item->getId(), 'users_id' => $techId, 'type' => CommonITILActor::OBSERVER, '_disablenotif' => true ) ); // , '_no_notif' => true $CFG_GLPI["use_mailing"]= $donotif; return true; } @@ -1577,426 +1460,429 @@ class PluginProcessmakerProcessmaker extends CommonDBTM { - /** - * Summary of addTask - * adds a GLPI task to given item - * @param $itemType string item type to which a task will be added - * @param $itemId integer item id to which a task will be added - * @param $caseInfo mixed getCaseInfoResponse object (see: getCaseInfo() function) - * @param $delIndex integer index of the delegation - * @param $techId integer GLPI user id to which a task must be assigned, if == 0 will use $groupId and/or $pmTaskId - * @param $groupId string PM group guid to assign to task, used when $techId == 0 - * @param $pmTaskId string PM task guid, used when $groupId == 0 AND $techID == 0 - * @param $options array of options, default values are - * 'txtTaskContent' => '', - * 'start_date' => '', - * 'end_date' => '', - * 'notif' => true - * @return - */ - public function addTask( $itemType, $itemId, $caseInfo, $delIndex, $techId, $groupId, $pmTaskId, $options=array() ) { - global $DB, $PM_DB, $LANG, $CFG_GLPI, $_SESSION ; + /** + * Summary of addTask + * adds a GLPI task to given item + * @param $itemType string item type to which a task will be added + * @param $itemId integer item id to which a task will be added + * @param $caseInfo mixed getCaseInfoResponse object (see: getCaseInfo() function) + * @param $delIndex integer index of the delegation + * @param $techId integer GLPI user id to which a task must be assigned, if == 0 will use $groupId and/or $pmTaskId + * @param groupId string PM group guid to assign to task, used when $techId == 0 + * @param pmTaskId string PM task guid, used when $groupId == 0 AND $techID == 0 + * @param $options array of options, default values are + * 'txtTaskContent' => '', + * 'start_date' => '', + * 'end_date' => '', + * 'notif' => true + * @return + */ + public function addTask( $itemType, $itemId, $caseInfo, $delIndex, $techId, $groupId, $pmTaskId, $options=array() ) { + global $DB, $PM_DB, $LANG, $CFG_GLPI, $_SESSION; - $default_options = array( - 'txtTaskContent' => '', - 'start_date' => '', - 'end_date' => '', - 'notif' => true - ) ; - foreach($default_options as $key => $opt){ - if(!isset($options[$key])){ - $options[$key] = $opt ; - } - } + $default_options = array( + 'txtTaskContent' => '', + 'start_date' => '', + 'end_date' => '', + 'notif' => true + ); + foreach ($default_options as $key => $opt) { + if (!isset($options[$key])) { + $options[$key] = $opt; + } + } - $glpi_task = getItemForItemtype( "{$itemType}Task" ); - $glpi_task->getEmpty(); + $glpi_task = getItemForItemtype( "{$itemType}Task" ); + $glpi_task->getEmpty(); - $input = array() ; // will contain all data for the Task + $input = array(); // will contain all data for the Task - $input[getForeignKeyFieldForItemType($itemType)] = $itemId ; - // search for task category - // - $pmtaskcat = new PluginProcessmakerTaskCategory ; - $pmtaskcat->getFromDBbyExternalID( $pmTaskId ) ; - $input['taskcategories_id'] = $pmtaskcat->fields['taskcategories_id'] ; - // load process information - $pmProcess = new PluginProcessmakerProcess ; - $pmProcess->getFromDB( $pmtaskcat->fields['processes_id'] ) ; + $input[getForeignKeyFieldForItemType($itemType)] = $itemId; + // search for task category + // + $pmtaskcat = new PluginProcessmakerTaskCategory; + $pmtaskcat->getFromDBbyExternalID( $pmTaskId ); + $input['taskcategories_id'] = $pmtaskcat->fields['taskcategories_id']; + // load process information + $pmProcess = new PluginProcessmakerProcess; + $pmProcess->getFromDB( $pmtaskcat->fields['processes_id'] ); - if( $options['start_date'] == '' ) { - $options['start_date'] = new DateTime( $_SESSION["glpi_currenttime"] ) ; - } else { - $options['start_date'] = new DateTime( $options['start_date'] ) ; - } + if ($options['start_date'] == '') { + $options['start_date'] = new DateTime( $_SESSION["glpi_currenttime"] ); + } else { + $options['start_date'] = new DateTime( $options['start_date'] ); + } - $input['begin'] = $options['start_date']->format("Y-m-d H:i:s"); + $input['begin'] = $options['start_date']->format("Y-m-d H:i:s"); - if( $options['end_date'] == '' || $options['end_date'] <= $input['begin']) { - $options['end_date'] = clone $options['start_date'] ; - $options['end_date']->add( new DateInterval('PT15M') ) ; - } else { - $options['end_date'] = new DateTime( $options['end_date'] ) ; - } - $input['end'] = $options['end_date']->format("Y-m-d H:i:s") ; - $input['plan']['begin'] = $input['begin']; - $temp = $options['start_date']->diff( $options['end_date'] ); - $input['plan']['_duration'] = $temp->d * DAY_TIMESTAMP + $temp->h * HOUR_TIMESTAMP + $temp->i * MINUTE_TIMESTAMP + $temp->s; - if( $input['plan']['_duration'] == 0 ) { - $input['plan']['_duration'] = 60; // at least - } + if ($options['end_date'] == '' || $options['end_date'] <= $input['begin']) { + $options['end_date'] = clone $options['start_date']; + $options['end_date']->add( new DateInterval('PT15M') ); + } else { + $options['end_date'] = new DateTime( $options['end_date'] ); + } + $input['end'] = $options['end_date']->format("Y-m-d H:i:s"); + $input['plan']['begin'] = $input['begin']; + $temp = $options['start_date']->diff( $options['end_date'] ); + $input['plan']['_duration'] = $temp->d * DAY_TIMESTAMP + $temp->h * HOUR_TIMESTAMP + $temp->i * MINUTE_TIMESTAMP + $temp->s; + if ($input['plan']['_duration'] == 0) { + $input['plan']['_duration'] = 60; // at least + } - $input['users_id'] = $this->taskWriter ; + $input['users_id'] = $this->taskWriter; - // manage groups - if( $techId == 0 ) { // then we must look-up DB to get the pseudo-group that will be assigned to the task - $groupname=''; - if( $groupId == 0 ) { - $query = "SELECT content.CON_VALUE FROM task_user - JOIN content ON content.CON_ID=task_user.USR_UID AND content.CON_CATEGORY='GRP_TITLE' AND content.CON_LANG = 'en' - WHERE task_user.tas_uid='$pmTaskId' AND task_user.tu_relation=2 LIMIT 1;" ; - } else { - $query = "SELECT CON_VALUE FROM content - WHERE content.CON_ID='$groupId' AND content.CON_CATEGORY='GRP_TITLE' AND content.CON_LANG = 'en' ;" ; - } - // as there is a LIMIT of 1 - // or - // as there is only one group per guid - // then we should have at maximun 1 record - foreach( $PM_DB->request($query) as $onlyrec ) { - $groupname = $onlyrec['CON_VALUE'] ; - } + // manage groups + if ($techId == 0) { // then we must look-up DB to get the pseudo-group that will be assigned to the task + $groupname=''; + if ($groupId == 0) { + $query = "SELECT CONTENT.CON_VALUE FROM TASK_USER + JOIN CONTENT ON CONTENT.CON_ID=TASK_USER.USR_UID AND CONTENT.CON_CATEGORY='GRP_TITLE' AND CONTENT.CON_LANG = 'en' + WHERE TASK_USER.TAS_UID='$pmTaskId' AND TASK_USER.TU_RELATION=2 LIMIT 1;"; + } else { + $query = "SELECT CON_VALUE FROM CONTENT + WHERE CONTENT.CON_ID='$groupId' AND CONTENT.CON_CATEGORY='GRP_TITLE' AND CONTENT.CON_LANG='en' ;"; + } + // as there is a LIMIT of 1 + // or + // as there is only one group per guid + // then we should have at maximun 1 record + foreach ($PM_DB->request($query) as $onlyrec) { + $groupname = $onlyrec['CON_VALUE']; + } - $groups_id_tech = 0; - $query = "SELECT id AS glpi_group_id FROM glpi_groups WHERE name LIKE '$groupname';"; - $res = $DB->query($query) ; - if( $DB->numrows($res) > 0) { - $row = $DB->fetch_array( $res ) ; - $groups_id_tech = $row['glpi_group_id'] ; - } + $groups_id_tech = 0; + $query = "SELECT id AS glpi_group_id FROM glpi_groups WHERE name LIKE '$groupname';"; + $res = $DB->query($query); + if ($DB->numrows($res) > 0) { + $row = $DB->fetch_array( $res ); + $groups_id_tech = $row['glpi_group_id']; + } - } else { - // adds the user tech to ticket watcher if neccessary - self::addWatcher( $itemType, $itemId, $techId ); - } + } else { + // adds the user tech to ticket watcher if neccessary + self::addWatcher( $itemType, $itemId, $techId ); + } + + // manage task description + $input['content'] = ""; // by default empty :) + if ($options['txtTaskContent'] != '') { + $input['content'] = $options['txtTaskContent']; + } else if (!$pmProcess->fields["hide_case_num_title"]) { + $input['content'] = $LANG['processmaker']['item']['task']['case'].$caseInfo->caseName; + } + + if ($pmProcess->fields["insert_task_comment"]) { + if ($input['content'] != '') { + $input['content'] .= "\n"; + } + $input['content'] .= $LANG['processmaker']['item']['task']['comment']; + } + if ($input['content'] != '') { + $input['content'] .= "\n"; + } + $input['content'] .= $LANG['processmaker']['item']['task']['manage']; + + $input['is_private'] = 0; + $input['actiontime'] = 0; + $input['state'] = 1; // == TO_DO + $input['users_id_tech'] = 0; // by default as it can't be empty + if ($techId) { + $input['users_id_tech'] = $techId; + } else if ($groups_id_tech) { + $input['groups_id_tech'] = $groups_id_tech; + } + + $donotif = $CFG_GLPI["use_mailing"]; + if (!$options['notif']) { + //$input['_no_notif'] = true; + $CFG_GLPI["use_mailing"] = false; + } + $glpi_task->add( Toolbox::addslashes_deep( $input ) ); + $CFG_GLPI["use_mailing"] = $donotif; + + if ($glpi_task->getId() > 0) { + // stores link to task in DB + $query = "INSERT INTO glpi_plugin_processmaker_tasks (items_id, itemtype, case_id, del_index) VALUES (".$glpi_task->getId().", '".$glpi_task->getType()."', '".$caseInfo->caseId."', ".$delIndex.");"; + $DB->query( $query ); + } + } + + /** + * Summary of add1stTask + * adds a GLPI task to ticket + * @param $intemType string itemtype of object (Ticket, Problem, ....) + * @param $itemId integer item id to which a task will be added + * @param $caseInfo mixed getCaseInfoResponse object (see: getCaseInfo() function) + * @param $options array of options, defaults are: + * 'txtTaskContent' => '', is content of the task + * 'userId' => false, is user id to be assigned to task + * 'notif' => true, if true notifications will be sent + * @return + */ + public function add1stTask ( $itemType, $itemId, $caseInfo, $options=array() ) { + + $default_options = array( + 'txtTaskContent' => '', + 'userId' => false, + 'notif' => true + ); + foreach ($default_options as $key => $opt) { + if (!isset($options[$key])) { + $options[$key] = $opt; + } + } + $start_date = new DateTime( $_SESSION["glpi_currenttime"] ); + $official_date_time = $_SESSION["glpi_currenttime"]; + $_SESSION["glpi_currenttime"] = $start_date->sub(new DateInterval("PT1S"))->format("Y-m-d H:i:s"); + $userId = $options['userId'] ? $options['userId'] : Session::getLoginUserID(); + unset($options['userId']); // unset it as it's not in the options of addTask + + $this->addTask( $itemType, + $itemId, + $caseInfo, + $caseInfo->currentUsers[0]->delIndex, + $userId, + 0, + $caseInfo->currentUsers[0]->taskId, + $options + ); + $_SESSION["glpi_currenttime"] = $official_date_time; + } - // manage task description - $input['content'] = "" ; // by default empty :) - if( $options['txtTaskContent'] != '' ) { - $input['content'] = $options['txtTaskContent'] ; - } - elseif( !$pmProcess->fields["hide_case_num_title"] ) { - $input['content'] = $LANG['processmaker']['item']['task']['case'].$caseInfo->caseName ; - } - - if( $pmProcess->fields["insert_task_comment"] ) { - if( $input['content'] != '' ) $input['content'] .= "\n" ; - $input['content'] .= $LANG['processmaker']['item']['task']['comment'] ; - } - if( $input['content'] != '' ) $input['content'] .= "\n" ; - $input['content'] .= $LANG['processmaker']['item']['task']['manage'] ; - - $input['is_private'] = 0 ; - $input['actiontime'] = 0 ; - $input['state'] = 1 ; // == TO_DO - $input['users_id_tech'] = 0; // by default as it can't be empty - if( $techId ) { - $input['users_id_tech'] = $techId; - } elseif( $groups_id_tech ) { - $input['groups_id_tech'] = $groups_id_tech; - } - - $donotif = $CFG_GLPI["use_mailing"]; - if( !$options['notif'] ) { - //$input['_no_notif'] = true; - $CFG_GLPI["use_mailing"] = false; - } - $glpi_task->add( Toolbox::addslashes_deep( $input ) ) ; - $CFG_GLPI["use_mailing"] = $donotif; - - if($glpi_task->getId() > 0 ) { - // stores link to task in DB - $query = "INSERT INTO glpi_plugin_processmaker_tasks (items_id, itemtype, case_id, del_index) VALUES (".$glpi_task->getId().", '".$glpi_task->getType()."', '".$caseInfo->caseId."', ".$delIndex.");" ; - $DB->query( $query ) ; - } - } - - /** - * Summary of add1stTask - * adds a GLPI task to ticket - * @param $intemType string itemtype of object (Ticket, Problem, ....) - * @param $itemId integer item id to which a task will be added - * @param $caseInfo mixed getCaseInfoResponse object (see: getCaseInfo() function) - * @param $options array of options, defaults are: - * 'txtTaskContent' => '', is content of the task - * 'userId' => false, is user id to be assigned to task - * 'notif' => true, if true notifications will be sent - * @return - */ - public function add1stTask ( $itemType, $itemId, $caseInfo, $options=array() ) { - - $default_options = array( - 'txtTaskContent' => '', - 'userId' => false, - 'notif' => true - ) ; - foreach($default_options as $key => $opt){ - if(!isset($options[$key])){ - $options[$key] = $opt ; - } - } - $start_date = new DateTime( $_SESSION["glpi_currenttime"] ) ; - $official_date_time = $_SESSION["glpi_currenttime"] ; - $_SESSION["glpi_currenttime"] = $start_date->sub(new DateInterval("PT1S"))->format("Y-m-d H:i:s") ; - $userId = $options['userId'] ? $options['userId'] : Session::getLoginUserID() ; - unset($options['userId']); // unset it as it's not in the options of addTask - - $this->addTask( $itemType, - $itemId, - $caseInfo, - $caseInfo->currentUsers[0]->delIndex, - $userId, - 0, - $caseInfo->currentUsers[0]->taskId, - $options - ) ; - $_SESSION["glpi_currenttime"] = $official_date_time ; - } - - - /** - * Summary of setItemStatus - * @param mixed $itemtype - * @param mixed $itemId - * @param mixed $newstatus - */ - public function setItemStatus( $itemtype, $itemId, $newstatus ) { - $item = getItemForItemtype( $itemtype ) ; - if( $item->getFromDB( $itemId ) ) { //&& $itemtype::isAllowedStatus( $item->fields['status'], $newstatus )) { + /** + * Summary of setItemStatus + * @param mixed $itemtype + * @param mixed $itemId + * @param mixed $newstatus + */ + public function setItemStatus( $itemtype, $itemId, $newstatus ) { + $item = getItemForItemtype( $itemtype ); + if ($item->getFromDB( $itemId )) { //&& $itemtype::isAllowedStatus( $item->fields['status'], $newstatus )) { //$item->fields['status'] = $newstatus ; - $item->update( array('id' => $item->getID(), 'status' => $newstatus) ) ; - } - } + $item->update( array('id' => $item->getID(), 'status' => $newstatus) ); + } + } - /// - /** - * Summary of computeTaskDuration - * Compute duration of the task - * @return mixed - */ - function computeTaskDuration( $task, $entity ) { + /** + * Summary of computeTaskDuration + * @param mixed $task + * @param mixed $entity + * @return mixed + */ + function computeTaskDuration( $task, $entity ) { - if (isset($task->fields['id']) && !empty($task->fields['begin'])) { - $calendars_id = Entity::getUsedConfig('calendars_id', $entity); - $calendar = new Calendar(); + if (isset($task->fields['id']) && !empty($task->fields['begin'])) { + $calendars_id = Entity::getUsedConfig('calendars_id', $entity); + $calendar = new Calendar(); - // Using calendar - if ($calendars_id>0 && $calendar->getFromDB($calendars_id)) { - return max(0, $calendar->getActiveTimeBetween($task->fields['begin'], - $_SESSION["glpi_currenttime"])); - } - // Not calendar defined - return max(0, strtotime($_SESSION["glpi_currenttime"])-strtotime($task->fields['begin'])); - } - return 0; - } + // Using calendar + if ($calendars_id>0 && $calendar->getFromDB($calendars_id)) { + return max(0, $calendar->getActiveTimeBetween($task->fields['begin'], + $_SESSION["glpi_currenttime"])); + } + // Not calendar defined + return max(0, strtotime($_SESSION["glpi_currenttime"])-strtotime($task->fields['begin'])); + } + return 0; + } - /** - * Summary of reassignTask - * @param mixed $caseId - * @param mixed $delIndex - * @param mixed $newDelIndex - * @param mixed $newTech - */ - public function reassignTask ( $caseId, $delIndex, $newDelIndex, $newTech) { - global $DB, $CFG_GLPI ; // $CFG_GLPI is only used to _disablenotif + /** + * Summary of reassignTask + * @param mixed $caseId + * @param mixed $delIndex + * @param mixed $newDelIndex + * @param mixed $newTech + */ + public function reassignTask ( $caseId, $delIndex, $newDelIndex, $newTech) { + global $DB, $CFG_GLPI; // $CFG_GLPI is only used to _disablenotif - $query = "SELECT * FROM glpi_plugin_processmaker_tasks WHERE case_id='$caseId' and del_index=$delIndex; "; - $res = $DB->query($query) ; - if( $DB->numrows($res) > 0) { - $row = $DB->fetch_array( $res ) ; - $glpi_task = new $row['itemtype'] ; - $glpi_task->getFromDB( $row['items_id'] ) ; + $query = "SELECT * FROM glpi_plugin_processmaker_tasks WHERE case_id='$caseId' and del_index=$delIndex; "; + $res = $DB->query($query); + if ($DB->numrows($res) > 0) { + $row = $DB->fetch_array( $res ); + $glpi_task = new $row['itemtype']; + $glpi_task->getFromDB( $row['items_id'] ); - $itemType = str_replace( 'Task', '', $row['itemtype'] ) ; - $foreignkey = getForeignKeyFieldForItemType( $itemType ) ; + $itemType = str_replace( 'Task', '', $row['itemtype'] ); + $foreignkey = getForeignKeyFieldForItemType( $itemType ); - //$glpi_item = getItemForItemtype( $itemType ); - //$glpi_item->getFromDB( $glpi_task->fields[ getForeignKeyFieldForItemType( $itemType ) ] ) ; + //$glpi_item = getItemForItemtype( $itemType ); + //$glpi_item->getFromDB( $glpi_task->fields[ getForeignKeyFieldForItemType( $itemType ) ] ) ; - //$plug = new Plugin; - //if( !$plug->isActivated('arbehaviours') ) { // check is done during Task update in this plugin - // $user_entities = Profile_User::getUserEntities( $newTech, true, true ) ; - // $user_can_view = in_array( $glpi_item->fields['entities_id'], $user_entities ); - // if( !$glpi_item->isUser( CommonITILActor::REQUESTER, $newTech ) && !$glpi_item->isUser( CommonITILActor::OBSERVER, $newTech ) && !$glpi_item->isUser( CommonITILActor::ASSIGN, $newTech ) && !$user_can_view ) { - // // then we must add this tech user to watcher list - // $glpi_item_user = getItemForItemtype( "{$itemType}_User" ); - // $donotif = $CFG_GLPI["use_mailing"] ; - // $CFG_GLPI["use_mailing"] = false; - // $glpi_item_user->add( array( $glpi_item->getForeignKeyField() => $glpi_item->getId() , 'users_id' => $newTech, 'type' => CommonITILActor::OBSERVER ) ) ; // , '_no_notif' => true - // $CFG_GLPI["use_mailing"] = $donotif; - // } - //} + //$plug = new Plugin; + //if( !$plug->isActivated('arbehaviours') ) { // check is done during Task update in this plugin + // $user_entities = Profile_User::getUserEntities( $newTech, true, true ) ; + // $user_can_view = in_array( $glpi_item->fields['entities_id'], $user_entities ); + // if( !$glpi_item->isUser( CommonITILActor::REQUESTER, $newTech ) && !$glpi_item->isUser( CommonITILActor::OBSERVER, $newTech ) && !$glpi_item->isUser( CommonITILActor::ASSIGN, $newTech ) && !$user_can_view ) { + // // then we must add this tech user to watcher list + // $glpi_item_user = getItemForItemtype( "{$itemType}_User" ); + // $donotif = $CFG_GLPI["use_mailing"] ; + // $CFG_GLPI["use_mailing"] = false; + // $glpi_item_user->add( array( $glpi_item->getForeignKeyField() => $glpi_item->getId() , 'users_id' => $newTech, 'type' => CommonITILActor::OBSERVER ) ) ; // , '_no_notif' => true + // $CFG_GLPI["use_mailing"] = $donotif; + // } + //} - self::addWatcher( $itemType, $glpi_task->fields[ $foreignkey ], $newTech ); + self::addWatcher( $itemType, $glpi_task->fields[ $foreignkey ], $newTech ); - $glpi_task->update( array( 'id' => $row['items_id'], $foreignkey => $glpi_task->fields[ $foreignkey ], 'users_id_tech' => $newTech )) ; + $glpi_task->update( array( 'id' => $row['items_id'], $foreignkey => $glpi_task->fields[ $foreignkey ], 'users_id_tech' => $newTech )); - // this is now done into GLPI core - //if( !$user_can_view ) { - // // to cheat the entity rigths, passes default user_entity to raiseEvent(), to be sure that task_tech will receive a notification. - // // drawback: notifications that are entity based could be missing. - // // tip: $user_entities[0] is the user's default entity - // NotificationEvent::raiseEvent('update_task', $glpi_item, array( 'entities_id' => $user_entities[0], 'task_id' => $glpi_task->getId(), 'is_private' => 0 ) ) ; - //} + // this is now done into GLPI core + //if( !$user_can_view ) { + // // to cheat the entity rigths, passes default user_entity to raiseEvent(), to be sure that task_tech will receive a notification. + // // drawback: notifications that are entity based could be missing. + // // tip: $user_entities[0] is the user's default entity + // NotificationEvent::raiseEvent('update_task', $glpi_item, array( 'entities_id' => $user_entities[0], 'task_id' => $glpi_task->getId(), 'is_private' => 0 ) ) ; + //} - // then update the delIndex - $query = "UPDATE glpi_plugin_processmaker_tasks SET del_index = $newDelIndex WHERE case_id='$caseId' and del_index=$delIndex; "; - $res = $DB->query($query) ; - } - } + // then update the delIndex + $query = "UPDATE glpi_plugin_processmaker_tasks SET del_index = $newDelIndex WHERE case_id='$caseId' and del_index=$delIndex; "; + $res = $DB->query($query); + } + } - /** - * Summary of solveTask - * @param string $caseId - * @param int $delIndex - * @param array $options - * 'txtToAppend' => '' : text to append to solved task - * 'notif' => true : if true will send notifications - * 'users_id_tech' => is the users_id of the tech that solved the task - */ - public function solveTask( $caseId, $delIndex, $options=array() ) { - global $DB, $CFG_GLPI ; + /** + * Summary of solveTask + * @param string $caseId + * @param int $delIndex + * @param array $options + * 'txtToAppend' => '' : text to append to solved task + * 'notif' => true : if true will send notifications + * 'users_id_tech' => is the users_id of the tech that solved the task + */ + public function solveTask( $caseId, $delIndex, $options=array() ) { + global $DB, $CFG_GLPI; - // change current glpi_currenttime to be sure that date_mode for solved task will not be identical than date_mode of the newly started task - $start_date = new DateTime( $_SESSION["glpi_currenttime"] ) ; - $official_date_time = $_SESSION["glpi_currenttime"] ; - $_SESSION["glpi_currenttime"] = $start_date->sub(new DateInterval("PT1S"))->format("Y-m-d H:i:s") ; + // change current glpi_currenttime to be sure that date_mode for solved task will not be identical than date_mode of the newly started task + $start_date = new DateTime( $_SESSION["glpi_currenttime"] ); + $official_date_time = $_SESSION["glpi_currenttime"]; + $_SESSION["glpi_currenttime"] = $start_date->sub(new DateInterval("PT1S"))->format("Y-m-d H:i:s"); - $default_options = array( - 'txtToAppend' => '', - 'notif' => true, - 'users_id_tech' => null - ) ; - foreach($default_options as $key => $opt){ - if(!isset($options[$key])){ - $options[$key] = $opt ; - } - } + $default_options = array( + 'txtToAppend' => '', + 'notif' => true, + 'users_id_tech' => null + ); + foreach ($default_options as $key => $opt) { + if (!isset($options[$key])) { + $options[$key] = $opt; + } + } - $query = "SELECT * FROM glpi_plugin_processmaker_tasks WHERE case_id='$caseId' and del_index=$delIndex; "; - $res = $DB->query($query) ; - if( $DB->numrows($res) > 0) { - $row = $DB->fetch_array( $res ) ; + $query = "SELECT * FROM glpi_plugin_processmaker_tasks WHERE case_id='$caseId' and del_index=$delIndex; "; + $res = $DB->query($query); + if ($DB->numrows($res) > 0) { + $row = $DB->fetch_array( $res ); - $glpi_task = new $row['itemtype'] ; - $glpi_task->getFromDB( $row['items_id'] ) ; - $hostItem = getItemForItemtype( $glpi_task->getItilObjectItemType() ) ; - $itemFKField = getForeignKeyFieldForItemType( $glpi_task->getItilObjectItemType() ) ; - $hostItem->getFromDB( $glpi_task->fields[ $itemFKField ] ) ; - $duration = $this->computeTaskDuration( $glpi_task, $hostItem->fields['entities_id'] ) ; - if( $options['txtToAppend'] != "" ) { - $options['txtToAppend'] = "\n
".$options['txtToAppend'] ; - } - $params = array( 'id' => $row['items_id'], - 'state' => 2, - 'end' => $_SESSION["glpi_currenttime"], - $itemFKField => $hostItem->getID(), - 'actiontime' => $duration, - 'users_id_tech' => (isset($options['users_id_tech']) ? $options['users_id_tech'] : Session::getLoginUserID()), - 'groups_id_tech' => 0, - 'content' => $DB->escape($glpi_task->fields[ 'content' ].$options['txtToAppend']) - ); - $donotif = $CFG_GLPI["use_mailing"]; - if( !$options['notif'] ) { - $CFG_GLPI["use_mailing"] = false ; - // $params['_no_notif']=true; - } - $glpi_task->update( $params ) ; - $CFG_GLPI["use_mailing"]= $donotif; - } + $glpi_task = new $row['itemtype']; + $glpi_task->getFromDB( $row['items_id'] ); + $hostItem = getItemForItemtype( $glpi_task->getItilObjectItemType() ); + $itemFKField = getForeignKeyFieldForItemType( $glpi_task->getItilObjectItemType() ); + $hostItem->getFromDB( $glpi_task->fields[ $itemFKField ] ); + $duration = $this->computeTaskDuration( $glpi_task, $hostItem->fields['entities_id'] ); + if ($options['txtToAppend'] != "") { + $options['txtToAppend'] = "\n
".$options['txtToAppend']; + } + $params = array( 'id' => $row['items_id'], + 'state' => 2, + 'end' => $_SESSION["glpi_currenttime"], + $itemFKField => $hostItem->getID(), + 'actiontime' => $duration, + 'users_id_tech' => (isset($options['users_id_tech']) ? $options['users_id_tech'] : Session::getLoginUserID()), + 'groups_id_tech' => 0, + 'content' => $DB->escape($glpi_task->fields[ 'content' ].$options['txtToAppend']) + ); + $donotif = $CFG_GLPI["use_mailing"]; + if (!$options['notif']) { + $CFG_GLPI["use_mailing"] = false; + // $params['_no_notif']=true; + } + $glpi_task->update( $params ); + $CFG_GLPI["use_mailing"]= $donotif; + } - // restore current glpi time - $_SESSION["glpi_currenttime"] = $official_date_time ; + // restore current glpi time + $_SESSION["glpi_currenttime"] = $official_date_time; - } + } - /** - * Summary of claimTask - * will unassign group, and assign tech - * @param mixed $caseId - * @param mixed $delIndex - * @param mixed $users_id_tech optional is the id of the tech - * who's claimed the task, default current logged-in user - */ - public function claimTask( $caseId, $delIndex, $users_id_tech=null ) { - global $DB ; + /** + * Summary of claimTask + * will unassign group, and assign tech + * @param mixed $caseId + * @param mixed $delIndex + * @param mixed $users_id_tech optional is the id of the tech + * who's claimed the task, default current logged-in user + */ + public function claimTask( $caseId, $delIndex, $users_id_tech=null ) { + global $DB; - $query = "SELECT * FROM glpi_plugin_processmaker_tasks WHERE case_id='$caseId' and del_index=$delIndex; "; - $res = $DB->query($query) ; - if( $DB->numrows($res) > 0) { - $row = $DB->fetch_array( $res ) ; - $glpi_task = new $row['itemtype'] ; - $glpi_task->getFromDB( $row['items_id'] ) ; + $query = "SELECT * FROM glpi_plugin_processmaker_tasks WHERE case_id='$caseId' and del_index=$delIndex; "; + $res = $DB->query($query); + if ($DB->numrows($res) > 0) { + $row = $DB->fetch_array( $res ); + $glpi_task = new $row['itemtype']; + $glpi_task->getFromDB( $row['items_id'] ); - $itemType = str_replace( 'Task', '', $row['itemtype'] ) ; - $glpi_item = getItemForItemtype( $itemType ); - $glpi_item->getFromDB( $glpi_task->fields[ getForeignKeyFieldForItemType( $itemType ) ] ) ; - - $glpi_task->update( array( 'id' => $row['items_id'], - $glpi_item->getForeignKeyField() => $glpi_item->getId(), - 'users_id_tech' => (isset($users_id_tech)?$users_id_tech: Session::getLoginUserID()), - 'groups_id_tech' => 0 )) ; - } - } + $itemType = str_replace( 'Task', '', $row['itemtype'] ); + $glpi_item = getItemForItemtype( $itemType ); + $glpi_item->getFromDB( $glpi_task->fields[ getForeignKeyFieldForItemType( $itemType ) ] ); + $glpi_task->update( array( 'id' => $row['items_id'], + $glpi_item->getForeignKeyField() => $glpi_item->getId(), + 'users_id_tech' => (isset($users_id_tech)?$users_id_tech: Session::getLoginUserID()), + 'groups_id_tech' => 0 )); + } + } /** * Summary of getCaseIdFromItem * get case id for an id item_id of type item_type (if a case if attached to it) - * @param string $item_type, the type for the item ("Ticket", "Problem", ...) - * @param integer $item_id, the id for the item + * @param string $item_type, the type for the item ("Ticket", "Problem", ...) + * @param integer $item_id, the id for the item * @return string the case guid, false if no case is attached to item, or if an error occurred */ - public static function getCaseIdFromItem ($item_type, $item_id ) { - global $DB ; + public static function getCaseIdFromItem ($item_type, $item_id ) { + global $DB; - $query = "SELECT * FROM glpi_plugin_processmaker_cases WHERE `itemtype` = '$item_type' AND `items_id` = $item_id ;" ; - $res = $DB->query($query) ; - if( $DB->numrows($res) > 0) { - // case is existing for this ticket - // then get info from db - $row = $DB->fetch_array($res); + $query = "SELECT * FROM glpi_plugin_processmaker_cases WHERE `itemtype` = '$item_type' AND `items_id` = $item_id ;"; + $res = $DB->query($query); + if ($DB->numrows($res) > 0) { + // case is existing for this ticket + // then get info from db + $row = $DB->fetch_array($res); - return $row['id'] ; - } + return $row['id']; + } - return false ; - } + return false; + } /** * Summary of getCaseFromItem * get case infos for an id item_id of type item_type (if a case if attached to it) - * @param string $item_type, the type for the item ("Ticket", "Problem", ...) - * @param integer $item_id, the id for the item + * @param string $item_type, the type for the item ("Ticket", "Problem", ...) + * @param integer $item_id, the id for the item * @return getCaseInfoResponse object, false if no case is attached to item, or if an error occurred */ - public function getCaseFromItem( $item_type, $item_id ) { - global $DB ; + public function getCaseFromItem( $item_type, $item_id ) { + global $DB; - $caseId = self::getCaseIdFromItem( $item_type, $item_id ) ; - if( $caseId !== false ) { - $caseInfo = $this->getCaseInfo( $caseId ) ; - if( $caseInfo !== false && $caseInfo->status_code == 0 ) - return $caseInfo ; - else - return false ; // means any error - } else - return false ; // means no case - } + $caseId = self::getCaseIdFromItem( $item_type, $item_id ); + if ($caseId !== false) { + $caseInfo = $this->getCaseInfo( $caseId ); + if ($caseInfo !== false && $caseInfo->status_code == 0) { + return $caseInfo; + } else { + return false; // means any error + } + } else { + return false; // means no case + } + } /** * Summary of multiexplode @@ -2004,12 +1890,12 @@ class PluginProcessmakerProcessmaker extends CommonDBTM { * @param $string * @return */ - static function multiexplode($delimiters, $string) { + static function multiexplode($delimiters, $string) { - $ready = str_replace($delimiters, $delimiters[0], $string); - $launch = explode($delimiters[0], $ready); - return $launch; - } + $ready = str_replace($delimiters, $delimiters[0], $string); + $launch = explode($delimiters[0], $ready); + return $launch; + } /** * Summary of pre_show_item_processmakerticket @@ -2017,106 +1903,106 @@ class PluginProcessmakerProcessmaker extends CommonDBTM { */ //private $pmCurrentCaseID = null ; - public static function pre_show_item_processmakerticket($params) { - //global $LANG; + public static function pre_show_item_processmakerticket($params) { + //global $LANG; - //$plug = new Plugin; + //$plug = new Plugin; - if( !is_array($params['item']) && is_subclass_of( $params['item'], 'CommonITILTask') ) { - // must check if Task is bound to a PM task - $pmTask = new PluginProcessmakerTask($params['item']->getType()); - if( $pmTask->getFromDBByQuery("WHERE itemtype='".$params['item']->getType()."' and items_id=".$params['item']->getId())) { - //echo 'Test' ; - $params['item']->fields['can_edit'] = false ; // to prevent task edition + if (!is_array($params['item']) && is_subclass_of( $params['item'], 'CommonITILTask')) { + // must check if Task is bound to a PM task + $pmTask = new PluginProcessmakerTask($params['item']->getType()); + if ($pmTask->getFromDBByQuery("WHERE itemtype='".$params['item']->getType()."' and items_id=".$params['item']->getId())) { + //echo 'Test' ; + $params['item']->fields['can_edit'] = false; // to prevent task edition - // replace ##ticket.url##_PluginProcessmakerCase$processmakercases by a setActiveTab to the Case panel - $taskCat = new TaskCategory ; - $taskCat->getFromDB( $params['item']->fields['taskcategories_id'] ) ; - $taskComment = isset($taskCat->fields['comment']) ? $taskCat->fields['comment'] : '' ; - if( Session::haveTranslations('TaskCategory', 'comment') ) { - $params['item']->fields['content'] = str_replace( '##processmaker.taskcomment##', - DropdownTranslation::getTranslatedValue( $taskCat->getID(), 'TaskCategory', 'comment', $_SESSION['glpilanguage'], $taskComment ), $params['item']->fields['content'] ) ; - } else { - $params['item']->fields['content'] = str_replace( '##processmaker.taskcomment##', $taskComment, $params['item']->fields['content'] ) ; - } - $taskJSId = "viewitem".$params['item']->getType().$params['item']->getId().$params['options']['rand'] ; - echo Html::scriptBlock( " + // replace ##ticket.url##_PluginProcessmakerCase$processmakercases by a setActiveTab to the Case panel + $taskCat = new TaskCategory; + $taskCat->getFromDB( $params['item']->fields['taskcategories_id'] ); + $taskComment = isset($taskCat->fields['comment']) ? $taskCat->fields['comment'] : ''; + if (Session::haveTranslations('TaskCategory', 'comment')) { + $params['item']->fields['content'] = str_replace( '##processmaker.taskcomment##', + DropdownTranslation::getTranslatedValue( $taskCat->getID(), 'TaskCategory', 'comment', $_SESSION['glpilanguage'], $taskComment ), $params['item']->fields['content'] ); + } else { + $params['item']->fields['content'] = str_replace( '##processmaker.taskcomment##', $taskComment, $params['item']->fields['content'] ); + } + $taskJSId = "viewitem".$params['item']->getType().$params['item']->getId().$params['options']['rand']; + echo Html::scriptBlock( " $('#$taskJSId').on('click', function ( ) { //debugger; var tabindex = $('#tabspanel').next('div').find('a[href*=\"_glpi_tab=PluginProcessmaker\"]').parent().index(); $('#tabspanel').next('div').tabs( 'option', 'active', tabindex ); } ).css('cursor', 'pointer') ; - ") ; - $params['item']->fields['content'] = str_replace( '##ticket.url##_PluginProcessmakerCase$processmakercases', "", $params['item']->fields['content'] ) ; //"".$LANG['processmaker']['item']['task']['manage_text']."" + "); + $params['item']->fields['content'] = str_replace( '##ticket.url##_PluginProcessmakerCase$processmakercases', "", $params['item']->fields['content'] ); //"".$LANG['processmaker']['item']['task']['manage_text']."" - if( isset( $params['item']->fields['tr_id'] ) ) { - $trID = $params['item']->fields['tr_id'] ; - //$params['item']->fields['content'] .= ""; - } - } - } + if (isset( $params['item']->fields['tr_id'] )) { + $trID = $params['item']->fields['tr_id']; + //$params['item']->fields['content'] .= ""; + } + } + } - //if( ($plug = new Plugin) && !$plug->isActivated('arbehaviours') ) { - // if ($params['item']->getID() && is_subclass_of( $params['item'], 'CommonITILObject')) { - // // then we are in a ticket - // if (isset($_REQUEST['glpi_tab']) && $_SESSION['glpiactiveprofile']['interface'] != "helpdesk" ) { - // $data = self::multiexplode(array('$','_'), $_REQUEST['glpi_tab']); - // $itemtype = $data[0]; - // // Default set - // $tabnum = 1; - // if (isset($data[1])) { - // $tabnum = $data[1]; - // } - // elseif( $itemtype == -1 ) - // $tabnum = -1 ; + //if( ($plug = new Plugin) && !$plug->isActivated('arbehaviours') ) { + // if ($params['item']->getID() && is_subclass_of( $params['item'], 'CommonITILObject')) { + // // then we are in a ticket + // if (isset($_REQUEST['glpi_tab']) && $_SESSION['glpiactiveprofile']['interface'] != "helpdesk" ) { + // $data = self::multiexplode(array('$','_'), $_REQUEST['glpi_tab']); + // $itemtype = $data[0]; + // // Default set + // $tabnum = 1; + // if (isset($data[1])) { + // $tabnum = $data[1]; + // } + // elseif( $itemtype == -1 ) + // $tabnum = -1 ; - // if( $data[0] == "processmaker" && $tabnum == 1 ) { + // if( $data[0] == "processmaker" && $tabnum == 1 ) { - // } - // if( ($data[0] == "Ticket" && $tabnum == 2) || $tabnum == -1) { - // // then we are showing the Solution tab - // // then we must prevent solving of ticket if a case is running - // if( !PluginProcessmakerCase::canSolve( $params['item'] ) ) { - // // then output a new div to hide solution - // $pmHideSolution = true ; - // echo "