2.4.1 initial commit

Previous releases can be found here:
https://forge.glpi-project.org/projects/processmaker
This commit is contained in:
tomolimo
2015-10-09 14:13:52 +02:00
commit 1cf75ef869
39 changed files with 8296 additions and 0 deletions

115
ajax/dropdownProcesses.php Normal file
View File

@@ -0,0 +1,115 @@
<?php
// ----------------------------------------------------------------------
// Original Author of file: Olivier Moron
// Purpose of file:
// ----------------------------------------------------------------------
// Direct access to file
if (strpos($_SERVER['PHP_SELF'],"dropdownProcesses.php")) {
$AJAX_INCLUDE = 1;
define('GLPI_ROOT','../../..');
include (GLPI_ROOT."/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");
}
include_once dirname(__FILE__)."/../inc/process.class.php" ;
Session::checkLoginUser();
if (!isset($_POST['right'])) {
$_POST['right'] = "all";
}
// Default view : Nobody
if (!isset($_POST['all'])) {
$_POST['all'] = 0;
}
$used = array();
if (isset($_POST['used'])) {
if (is_array($_POST['used'])) {
$used = $_POST['used'];
} else {
$used = unserialize(stripslashes($_POST['used']));
}
}
if (isset($_POST["entity_restrict"])
&& !is_numeric($_POST["entity_restrict"])
&& !is_array($_POST["entity_restrict"])) {
$_POST["entity_restrict"] = unserialize(stripslashes($_POST["entity_restrict"]));
}
$result = PluginProcessmakerProcess::getSqlSearchResult(false, $_POST['right'], $_POST["entity_restrict"],
$_POST['value'], $used, $_POST['searchText']);
$processes = array();
if ($DB->numrows($result)) {
while ($data=$DB->fetch_array($result)) {
if( in_array( $_POST["entity_restrict"], PluginProcessmakerProcess::getEntitiesForProfileByProcess( $data["id"], $_SESSION['glpiactiveprofile']['id'], true) ) ) {
$processes[$data["id"]] = $data["name"];
}
}
}
echo "<select id='dropdown_".$_POST["myname"].$_POST["rand"]."' name='".$_POST['myname']."'";
if (isset($_POST["on_change"]) && !empty($_POST["on_change"])) {
echo " onChange='".$_POST["on_change"]."'";
}
echo ">";
if ($_POST['searchText']!=$CFG_GLPI["ajax_wildcard"]
&& $DB->numrows($result)==$CFG_GLPI["dropdown_max"]) {
echo "<option value='0'>--".$LANG['common'][11]."--</option>";
}
if ($_POST['all']==0) {
echo "<option value='0'>".Dropdown::EMPTY_VALUE."</option>";
} else if ($_POST['all']==1) {
echo "<option value='0'>[".$LANG['common'][66]."]</option>";
}
if (isset($_POST['value'])) {
$output = PluginProcessmakerProcess::getProcessName($_POST['value']);
if (!empty($output) && $output!="&nbsp;") {
echo "<option selected value='".$_POST['value']."'>".$output."</option>";
}
}
if (count($processes)) {
foreach ($processes as $ID => $output) {
echo "<option value='$ID' title=\"".Html::cleanInputText($output)."\">".
Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"])."</option>";
}
}
echo "</select>";
if (isset($_POST["comment"]) && $_POST["comment"]) {
$paramscomment = array('value' => '__VALUE__',
'table' => "glpi_plugin_processmaker_processes");
if (isset($_POST['update_link'])) {
$paramscomment['withlink'] = "comment_link_".$_POST["myname"].$_POST["rand"];
}
Ajax::updateItemOnSelectEvent("dropdown_".$_POST["myname"].$_POST["rand"],
"comment_".$_POST["myname"].$_POST["rand"],
$CFG_GLPI["root_doc"]."/ajax/comments.php", $paramscomment);
}
Ajax::commonDropdownUpdateItem($_POST);
?>

134
ajax/dropdownUsers.php Normal file
View File

@@ -0,0 +1,134 @@
<?php
/*
*/
// ----------------------------------------------------------------------
// Original Author of file: Olivier Moron
// Purpose of file:
// ----------------------------------------------------------------------
// Direct access to file
if (strpos($_SERVER['PHP_SELF'],"dropdownUsers.php")) {
$AJAX_INCLUDE = 1;
define('GLPI_ROOT','../../..');
include (GLPI_ROOT."/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");
}
include_once dirname(__FILE__)."/../inc/users.class.php" ;
Session::checkLoginUser();
if (!isset($_POST['right'])) {
$_POST['right'] = "all";
}
// Default view : Nobody
if (!isset($_POST['all'])) {
$_POST['all'] = 0;
}
$used = array();
if (isset($_POST['used'])) {
if (is_array($_POST['used'])) {
$used = $_POST['used'];
} else {
$used = unserialize(stripslashes($_POST['used']));
}
}
if (isset($_POST["entity_restrict"])
&& !is_numeric($_POST["entity_restrict"])
&& !is_array($_POST["entity_restrict"])) {
$_POST["entity_restrict"] = unserialize(stripslashes($_POST["entity_restrict"]));
}
$result = PluginProcessmakerUsers::getSqlSearchResult( $_POST['pmTaskId'], false, $_POST['right'], $_POST["entity_restrict"],
$_POST['value'], $used, $_POST['searchText']);
$users = array();
// check if $_POST["myname"] matches _itil_\w+\[users_id\]
if( preg_match( "/^_itil_\\w+\\[users_id\\]/", $_POST["myname"] ) || preg_match( "/^_users_id_\\w+/", $_POST["myname"] )) {
// prevent use of pseudo-groups like *Raynet-Development_Intranet (TASK USE ONLY!)
$raynetPseudoGroupNoUse = true ;
} else $raynetPseudoGroupNoUse = false ;
if ($DB->numrows($result)) {
while ($data=$DB->fetch_array($result)) {
if( !$raynetPseudoGroupNoUse || mb_strpos( $data["name"], "*" ) === false ) {
$users[$data["id"]] = formatUserName($data["id"], $data["name"], $data["realname"],
$data["firstname"]);
$logins[$data["id"]] = $data["name"];
}
}
}
if (!function_exists('dpuser_cmp')) {
function dpuser_cmp($a, $b) {
return strcasecmp($a, $b);
}
}
// Sort non case sensitive
uasort($users, 'dpuser_cmp');
echo "<select id='dropdown_".$_POST["myname"].$_POST["rand"]."' name='".$_POST['myname']."'";
if (isset($_POST["on_change"]) && !empty($_POST["on_change"])) {
echo " onChange='".$_POST["on_change"]."'";
}
echo ">";
if ($_POST['searchText']!=$CFG_GLPI["ajax_wildcard"]
&& $DB->numrows($result)==$CFG_GLPI["dropdown_max"]) {
echo "<option value='0'>--".$LANG['common'][11]."--</option>";
}
if ($_POST['all']==0) {
echo "<option value='0'>".Dropdown::EMPTY_VALUE."</option>";
} else if ($_POST['all']==1) {
echo "<option value='0'>[".$LANG['common'][66]."]</option>";
}
if (isset($_POST['value'])) {
$output = getUserName($_POST['value']);
if (!empty($output) && $output!="&nbsp;") {
echo "<option selected value='".$_POST['value']."'>".$output."</option>";
}
}
if (count($users)) {
foreach ($users as $ID => $output) {
echo "<option value='$ID' title=\"".Html::cleanInputText($output." - ".$logins[$ID])."\">".
Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"])."</option>";
}
}
echo "</select>";
if (isset($_POST["comment"]) && $_POST["comment"]) {
$paramscomment = array('value' => '__VALUE__',
'table' => "glpi_users");
if (isset($_POST['update_link'])) {
$paramscomment['withlink'] = "comment_link_".$_POST["myname"].$_POST["rand"];
}
Ajax::updateItemOnSelectEvent("dropdown_".$_POST["myname"].$_POST["rand"],
"comment_".$_POST["myname"].$_POST["rand"],
$CFG_GLPI["root_doc"]."/ajax/comments.php", $paramscomment);
}
Ajax::commonDropdownUpdateItem($_POST);
?>

81
ajax/task_resume.php Normal file
View File

@@ -0,0 +1,81 @@
<?php
function HandleHeaderLine( $curl, $header_line ) {
$temp = explode( ": ", $header_line ) ;
if( is_array( $temp ) && $temp[0] == 'Set-Cookie' ) {
header("Set-Cookie: ".$temp[1], false) ;
}
return strlen($header_line);
}
$ch = curl_init();
$pmURL = urldecode($_REQUEST['url']) ;
curl_setopt($ch, CURLOPT_URL, $pmURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "HandleHeaderLine");
$body = curl_exec($ch);
curl_close ($ch);
$pmBaseURL = explode( "/", $pmURL, 4 ) ;
array_pop( $pmBaseURL ) ;
echo "
<!DOCTYPE html>
<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta charset='utf-8' />
<title></title>
<link href='".implode("/", $pmBaseURL)."/css/classic-blank.css' rel='stylesheet' type='text/css'/>
</head>
<body aLink='#999999' leftMargin='0' rightMargin='0' topMargin='0' bgColor='#ffffff' text='#000000' vLink='#000000' link='#000000' marginwidth='0' marginheight='0'>
<table cellSpacing='0' cellPadding='0' width='100%' height='100%'>
<tbody><tr>
<td vAlign='top' width='100%'>
<table style='padding-top: 3px;' border='0' cellSpacing='0' cellPadding='0' width='100%'>
<tbody><tr>
<td align='center'>
<div style='margin: 0px;' id='publisherContent[0]' align='center'> <form style='margin: 0px;' id='bHNTajBhT2lsNUhqMmFUTXg1cXM1NTdTWWR1ZDJB' class='formDefault' onsubmit='return validateForm(\"[]\");' encType='multipart/form-data' method='post' name='cases_Resume' action=''> <div style='border-width: 1px; width: 550px; padding-right: 0px; padding-left: 0px;' class='borderForm'>
<div class='boxTop'><div class='a'>&nbsp;</div><div class='b'>&nbsp;</div><div class='c'>&nbsp;</div></div>
<div style='height: 100%;' class='content'>
<table width='99%'>
<tbody><tr>
<td vAlign='top'>
<table border='0' cellSpacing='0' cellPadding='0' width='100%'>
<tbody><tr>
<td class='FormTitle' colSpan='2' align=''><span >Task Properties</span></td>
</tr>
<tr>
<td class='FormLabel' width='150'><label >Ongoing Task</label></td>
<td class='FormFieldContent' width='400'>".urldecode($_REQUEST['taskname'])."</td>
<tr>
<td class='FormLabel' width='150'><label >By</label></td>
<td class='FormFieldContent' width='400'>".urldecode($_REQUEST['username'])."</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
</div>
<div class='boxBottom'><div class='a'>&nbsp;</div><div class='b'>&nbsp;</div><div class='c'>&nbsp;</div></div>
</div>
</form>
</div></td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
</body>
</html>
" ;

50
ajax/task_users.php Normal file
View File

@@ -0,0 +1,50 @@
<?php
// ----------------------------------------------------------------------
// Original Author of file: Olivier Moron
// Purpose of file:
// ----------------------------------------------------------------------
// Direct access to file
if (strpos($_SERVER['PHP_SELF'],"task_users.php")) {
$AJAX_INCLUDE = 1;
define('GLPI_ROOT','../../..');
include (GLPI_ROOT."/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");
}
include_once dirname(__FILE__)."/../inc/processmaker.class.php" ;
include_once dirname(__FILE__)."/../inc/users.class.php" ;
Session::checkLoginUser();
$rand = rand();
echo "<form style='margin-bottom: 0px' name='processmaker_form_task$rand-".$_REQUEST['delIndex']."' id='processmaker_form_task$rand-".$_REQUEST['delIndex']."' method='post' action='".Toolbox::getItemTypeFormURL("PluginProcessmakerProcessmaker")."'>";
echo $LANG['processmaker']['item']['reassigncase']."&nbsp;";
echo "<input type='hidden' name='action' value='unpausecase_or_reassign_or_delete'>";
echo "<input type='hidden' name='id' value='".$_REQUEST['itemId']."'>";
echo "<input type='hidden' name='itemtype' value='".$_REQUEST['itemType']."'>";
echo "<input type='hidden' name='plugin_processmaker_caseId' value='".$_REQUEST['caseId']."'>";
echo "<input type='hidden' name='plugin_processmaker_delIndex' value='".$_REQUEST['delIndex']."'>";
echo "<input type='hidden' name='plugin_processmaker_userId' value='".$_REQUEST['userId']."'>";
echo "<input type='hidden' name='plugin_processmaker_taskId' value='".$_REQUEST['taskId']."'>";
echo "<input type='hidden' name='plugin_processmaker_delThread' value='".$_REQUEST['delThread']."'>";
PluginProcessmakerUsers::dropdown( array('name' => 'users_id_recipient',
'value' => PluginProcessmakerProcessmaker::getGLPIUserId( $_REQUEST['userId'] ),
'entity' => 0, //$item->fields["entities_id"],
'entity_sons' => true,
'right' => 'all',
'rand' => $rand,
'pmTaskId' => $_REQUEST['taskId']));
echo "&nbsp;&nbsp;";
echo "<input type='submit' name='reassign' value='".$LANG['processmaker']['item']['buttonreassigncase']."' class='submit'>";
echo "</form>";
?>

51
config/db_updates.txt Normal file
View File

@@ -0,0 +1,51 @@
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`;

175
config/pm_db_config.sql Normal file
View File

@@ -0,0 +1,175 @@

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, ',<br/>case title: ', APP_TITLE, ',<br/>task: ', APP_TAS_TITLE,'.<br/><a href="?id=', loc_Ticket_id, '&forcetab=processmaker_1">Go to Case tab to manage!</a>' ),
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, ',<br/>case title: ', APP_TITLE, ',<br/>task: ', APP_TAS_TITLE,'.<br/><a href="?id=', loc_Ticket_id, '&forcetab=processmaker_1">Go to Case tab to manage!</a>' ),
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 ;

218
config/pm_db_install.mysql Normal file
View File

@@ -0,0 +1,218 @@
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, ',<br/>case title: ', APP_TITLE, ',<br/>task: ', APP_TAS_TITLE,'.<br/><a href="?id=', loc_item_id, '&forcetab=processmaker_1">Go to Case tab to manage!</a>', '\',
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, ',<br/>case title: ', APP_TITLE, ',<br/>task: ', APP_TAS_TITLE,'.<br/><a href="?id=', loc_Ticket_id, '&forcetab=processmaker_1">Go to Case tab to manage!</a>' ),
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 ;

203
config/pm_db_install.sql Normal file
View File

@@ -0,0 +1,203 @@
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, ',<br/>case title: ', APP_TITLE, ',<br/>task: ', APP_TAS_TITLE,'.<br/><a href="?id=', loc_Ticket_id, '&forcetab=processmaker_1">Go to Case tab to manage!</a>' ),
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, ',<br/>case title: ', APP_TITLE, ',<br/>task: ', APP_TAS_TITLE,'.<br/><a href="?id=', loc_Ticket_id, '&forcetab=processmaker_1">Go to Case tab to manage!</a>' ),
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 ;

View File

@@ -0,0 +1,7 @@
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` ;

View File

@@ -0,0 +1,6 @@
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` ;

86
front/cases.front.php Normal file
View File

@@ -0,0 +1,86 @@
<?php
define('GLPI_ROOT', '../../..');
include (GLPI_ROOT."/inc/includes.php");
include_once '../inc/processmaker.class.php' ;
include_once '../inc/cases.class.php' ;
// check if it is from PM pages
if( isset( $_REQUEST['UID'] ) && isset( $_REQUEST['APP_UID'] ) && isset( $_REQUEST['__DynaformName__'] ) ) {
// then get item id from DB
$myCase = new PluginProcessmakerCases ;
if( $myCase->getFromDB( $_REQUEST['APP_UID'] ) ) {
$myProcessMaker = new PluginProcessmakerProcessmaker() ;
$myProcessMaker->login( ) ;
if( isset( $_REQUEST['form'] ) ) {
// save the case variables
//$resultSave = $myProcessMaker->sendVariables( $myCase->getID() , $_REQUEST['form'] ) ;
$resultSave = $myProcessMaker->saveForm( $_REQUEST, $_SERVER['HTTP_COOKIE'] ) ;
//$myCase->sendVariables( $_REQUEST['form'] ) ;
// now derivate the case !!!
$pmRouteCaseResponse = $myProcessMaker->routeCase( $myCase->getID(), $_REQUEST['DEL_INDEX']) ;
// 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_TASK_CONTENT", "GLPI_ITEM_APPEND_TO_TASK", "GLPI_NEXT_GROUP_TO_BE_ASSIGNED" ) );
if( array_key_exists( 'GLPI_ITEM_APPEND_TO_TASK', $txtForTasks ) )
$txtToAppendToTask = $txtForTasks[ 'GLPI_ITEM_APPEND_TO_TASK' ] ;
else
$txtToAppendToTask = '' ;
if( array_key_exists( 'GLPI_ITEM_TASK_CONTENT', $txtForTasks ) )
$txtTaskContent = $txtForTasks[ 'GLPI_ITEM_TASK_CONTENT' ] ;
else
$txtTaskContent = '' ;
if( array_key_exists( 'GLPI_NEXT_GROUP_TO_BE_ASSIGNED', $txtForTasks ) )
$groupId = $txtForTasks[ 'GLPI_NEXT_GROUP_TO_BE_ASSIGNED' ] ;
else
$groupId = 0 ;
// reset those variables
$resultSave = $myProcessMaker->sendVariables( $myCase->getID() , array( "GLPI_ITEM_APPEND_TO_TASK" => '', 'GLPI_ITEM_TASK_CONTENT' => '', 'GLPI_NEXT_GROUP_TO_BE_ASSIGNED' => '' ) ) ;
// print_r( $pmRouteCaseResponse ) ;
// die() ;
// now manage tasks associated with item
$itemType = $myCase->getField('itemtype');
$itemId = $myCase->getField('items_id');
// switch own task to 'done' and create a new one
$myProcessMaker->solveTask( $myCase->getID(), $_REQUEST['DEL_INDEX'], $txtToAppendToTask ) ;
$caseInfo = $myProcessMaker->getCaseInfo( $myCase->getID(), $_REQUEST['DEL_INDEX']) ;
if( property_exists( $pmRouteCaseResponse, 'routing' ) ) {
foreach( $pmRouteCaseResponse->routing as $route ) {
$myProcessMaker->addTask( $itemType, $itemId, $caseInfo, $route->delIndex, PluginProcessmakerProcessmaker::getGLPIUserId( $route->userId ), $groupId, $route->taskId, $txtTaskContent ) ;
}
}
// evolution of case status: DRAFT, TO_DO, COMPLETED, CANCELLED
$myCase->update( array( 'id' => $myCase->getID(), 'case_status' => $caseInfo->caseStatus ) ) ;
}
}
}
// Claim task management
elseif( isset( $_REQUEST['form'] ) && isset( $_REQUEST['form']['BTN_CATCH'] ) && isset( $_REQUEST['form']['APP_UID']) ){
// here we are in a Claim request
$myCase = new PluginProcessmakerCases ;
if( $myCase->getFromDB( $_REQUEST['form']['APP_UID'] ) ) {
$myProcessMaker = new PluginProcessmakerProcessmaker() ;
$myProcessMaker->login( ) ;
$pmClaimCase = $myProcessMaker->claimCase( $myCase->getID(), $_REQUEST['DEL_INDEX'] ) ;
// now manage tasks associated with item
$myProcessMaker->claimTask( $myCase->getID(), $_REQUEST['DEL_INDEX'] ) ;
}
}
// now redirect to item form page
//Html::redirect( Toolbox::getItemTypeFormURL($myCase->getField('itemtype')));
echo "<html><body><input id='GLPI_FORCE_RELOAD' type='hidden' value='GLPI_FORCE_RELOAD'/></body></html>" ;
?>

23
front/config.form.php Normal file
View File

@@ -0,0 +1,23 @@
<?php
/**
*/
define('GLPI_ROOT', '../../..');
include (GLPI_ROOT . "/inc/includes.php");
// No autoload when plugin is not activated
require_once('../inc/config.class.php');
$config = new PluginProcessmakerConfig();
if (isset($_POST["update"])) {
$config->check($_POST['id'],'w');
$config->update($_POST);
Html::back();
} elseif (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'));

33
front/process.form.php Normal file
View File

@@ -0,0 +1,33 @@
<?php
define('GLPI_ROOT', '../../..');
include (GLPI_ROOT."/inc/includes.php");
Plugin::load('processmaker',true);
if (!isset($_REQUEST["id"])) {
$_REQUEST["id"] = "";
}
$PluginProcess = new PluginProcessmakerProcess();
if (isset($_REQUEST["update"])) {
$PluginProcess->check($_REQUEST['id'], 'w');
$PluginProcess->update($_REQUEST);
Html::back();
} elseif (isset($_REQUEST["refreshtask"])) {
$PluginProcess->check($_REQUEST['id'], 'w');
$PluginProcess->refreshTasks($_REQUEST);
Html::back();
} else {
$PluginProcess->checkGlobal('r');
Html::header($LANG['processmaker']['title'][1],$_SERVER["PHP_SELF"],"plugins","processmaker");
$PluginProcess->showForm($_REQUEST["id"]);
Html::footer();
}
?>

25
front/process.php Normal file
View File

@@ -0,0 +1,25 @@
<?php
define('GLPI_ROOT', '../../..');
include (GLPI_ROOT."/inc/includes.php");
Html::header($LANG['processmaker']['title'][1], $_SERVER['PHP_SELF'], "plugins", "processmaker");
if (plugin_processmaker_haveRight("process_config","r") || Session::haveRight("config","w")) {
$process=new PluginProcessmakerProcess();
if( isset( $_REQUEST['refresh'] ) && plugin_processmaker_haveRight("process_config","w") ) {
$process->refresh();
Html::back();
}
$process->title();
Search::show('PluginProcessmakerProcess');
} else {
Html::displayRightError();
}
Html::footer();
?>

View File

@@ -0,0 +1,42 @@
<?php
define('GLPI_ROOT', '../../..');
include (GLPI_ROOT."/inc/includes.php");
Session::checkCentralAccess();
$profile = new Profile();
$right = new PluginProcessmakerProcess_Profile();
$process = new PluginProcessmakerProcess();
if (isset($_POST["add"])) {
$right->check(-1,'w',$_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,'w')) {
$right->delete(array('id' => $key));
}
}
}
//if (isset($_POST["processes_id"])) {
// Event::log($_POST["processes_id"], "users", 4, "setup",
// $_SESSION["glpiname"]." ".$LANG['log'][62]);
// }
}
Html::back();
}
Html::displayErrorAndDie("lost");
?>

201
front/processmaker.form.php Normal file
View File

@@ -0,0 +1,201 @@
<?php
if( !defined ('GLPI_ROOT' ) )
define('GLPI_ROOT', '../../..');
include_once (GLPI_ROOT."/inc/includes.php");
include_once '../inc/processmaker.class.php' ;
include_once '../inc/cases.class.php' ;
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();
$requesters = PluginProcessmakerProcessmaker::getItemUsers( $_POST['itemtype'], $_POST['id'], 1 ) ; // 1 for requesters
if( !key_exists( 0, $requesters ) ) {
$requesters[0]['glpi_id'] = 0 ;
$requesters[0]['pm_id'] = 0 ;
}
//$technicians = PluginProcessmakerProcessmaker::getItemUsers( $_POST['itemtype'], $_POST['id'], 2 ) ; // 2 for technicians
//if( !key_exists( 0, $technicians ) ) {
// $technicians[0]['glpi_id'] = Session::getLoginUserID() ;
// $technicians[0]['pm_id'] = PluginProcessmakerProcessmaker::getPMUserId( Session::getLoginUserID() ) ;
//}
// get item info to retreive title, description and duedate
$locTicket = new $_POST['itemtype'] ; //Ticket();
$locTicket->getFromDB( $_POST['id'] ) ;
if($locTicket->countUsers($locTicket::ASSIGN) == 0
|| !$locTicket->isUser($locTicket::ASSIGN, Session::getLoginUserID()) ){
$locTicket->update( array( 'id' => $_POST['id'], '_itil_assign' => array( '_type' => 'user', 'users_id' => Session::getLoginUserID() ) ) ) ;
}
//$writer = PluginProcessmakerProcessmaker::getPMUserId( Session::getLoginUserID() );
if( !isset($locTicket->fields['due_date']) || $locTicket->fields['due_date'] == null ) {
$locTicket->fields['due_date'] = "";
}
$resultCase = $myProcessMaker->newCase( $_POST['plugin_processmaker_process_id'],
array( 'GLPI_ITEM_CAN_BE_SOLVED' => 0,
'GLPI_TICKET_ID' => $_POST['id'],
'GLPI_ITEM_TYPE' => $_POST['itemtype'],
'GLPI_TICKET_REQUESTER_GLPI_ID' => $requesters[0]['glpi_id'],
'GLPI_TICKET_REQUESTER_PM_ID' => $requesters[0]['pm_id'],
'GLPI_TICKET_TITLE' => $locTicket->fields['name'],
'GLPI_TICKET_DESCRIPTION' => $locTicket->fields['content'],
'GLPI_TICKET_DUE_DATE' => $locTicket->fields['due_date'],
'GLPI_TICKET_URGENCY' => $locTicket->fields['urgency'],
'GLPI_ITEM_IMPACT' => $locTicket->fields['impact'],
'GLPI_ITEM_PRIORITY' => $locTicket->fields['priority'],
'GLPI_TICKET_GLOBAL_VALIDATION' => $locTicket->fields['global_validation'] ,
'GLPI_TICKET_TECHNICIAN_GLPI_ID' => Session::getLoginUserID(), //$technicians[0]['glpi_id'],
'GLPI_TICKET_TECHNICIAN_PM_ID' => PluginProcessmakerProcessmaker::getPMUserId( Session::getLoginUserID() ) //$technicians[0]['pm_id']
) ) ;
if ($resultCase->status_code == 0){
$caseInfo = $myProcessMaker->getCaseInfo( $resultCase->caseId );
//$query = "UPDATE APPLICATION SET APP_STATUS='TO_DO' WHERE APP_UID='".$resultCase->caseId."' AND APP_STATUS='DRAFT'" ;
//$res = $DB->query($query) ;
// save info to DB
$query = "INSERT INTO glpi_plugin_processmaker_cases (items_id, itemtype, id, case_num, case_status, processes_id) VALUES (".$_POST['id'].", '".$_POST['itemtype']."', '".$resultCase->caseId."', ".$resultCase->caseNumber.", '".$caseInfo->caseStatus."', '".$caseInfo->processId."');" ;
$res = $DB->query($query) ;
$myProcessMaker->add1stTask($_POST['itemtype'], $_POST['id'], $caseInfo ) ;
//echo "New case ID: $result->caseId, Case No: $result->caseNumber \n";
Html::back();
}
else
Session::addMessageAfterRedirect($LANG['processmaker']['item']['error'][$resultCase->status_code]."<br>$resultCase->message ($resultCase->status_code)", true, ERROR); //echo "Error creating case: $resultCase->message \n";
} else
Html::back();
}
else { // the case is created before the ticket (used for user management before ticket creation)
// list of requesters is needed
// so read ticket
//$requesters = array( ) ;
//foreach( $DB->request( $query ) as $dbuser ) {
// $requesters[] = $dbuser['pm_users_id'] ;
//}
//$writer = PluginProcessmakerProcessmaker::getPMUserId( Session::getLoginUserID() );
//$userGLPI = new User();
//$userGLPI->getFromDB( Session::getLoginUserID() ) ;
//if( $userGLPI->fields['language'] != null )
// $lang = substr( $userGLPI->fields['language'], 0, 2) ;
//else
// $lang = "en" ;
$myProcessMaker = new PluginProcessmakerProcessmaker() ;
$myProcessMaker->login() ; //openSession( $userGLPI->fields['name'], "md5:37d442efb43ebb80ec6f9649b375ab72", $lang) ;
//$resultCase = $myProcessMaker->newCaseImpersonate( $_POST['plugin_processmaker_process_id'], $writer) ;
$resultCase = $myProcessMaker->newCase( $_POST['plugin_processmaker_process_id'], array( 'GLPI_ITEM_CAN_BE_SOLVED' => 0 ) ) ;
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"]);
} else {
//Html::helpHeader($LANG['job'][13], $_SERVER['PHP_SELF'], $_SESSION["glpiname"]);
//// case is not created show error message
//echo "Error : ".$resultCase->status_code."</br>" ;
//echo $resultCase->message."</br>" ;
//Html::helpFooter();
Session::addMessageAfterRedirect($LANG['processmaker']['item']['error'][$resultCase->status_code]."<br>$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();
}
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 = PluginProcessmakerProcessmaker::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);
// 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 PluginProcessmakerCases ;
$locCase->getFromDB( $_POST['plugin_processmaker_caseId'] ) ;
if( $locCase->deleteCase() ) {
// request delete from pm itself
$myProcessMaker = new PluginProcessmakerProcessmaker() ;
$myProcessMaker->login() ;
$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 PluginProcessmakerCases ;
$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;
}
// to return to ticket
Html::back();
?>

View File

@@ -0,0 +1,509 @@
<?php
if( !defined( 'GLPI_ROOT' ) )
define('GLPI_ROOT', '../../..');
include_once (GLPI_ROOT."/inc/includes.php");
include_once '../inc/processmaker.class.php' ;
function processMakerShowProcessList ($ID, $from_helpdesk) {
global $DB, $CFG_GLPI, $LANG, $_SESSION ;
if (!Session::haveRight("create_ticket","1")) {
return false;
}
$rand = rand();
echo "<form name= 'processmaker_form$rand' id='processmaker_form$rand' method='post' action='".Toolbox::getItemTypeFormURL("PluginProcessmakerProcessmaker")."'>";
echo "<div class='center'><table class='tab_cadre_fixehov'>";
echo "<tr><th colspan='2'>".$LANG['processmaker']['item']['tab']."</th></tr>";
echo "<tr class='tab_bg_2'><td class='right' colspan='1'>";
echo $LANG['processmaker']['item']['selectprocess']."&nbsp;";
echo "<input type='hidden' name='action' value='newcase'>";
echo "<input type='hidden' name='id' value='-1'>";
echo "<input type='hidden' name='itemtype' value='Ticket'>";
// 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( 'entity' => $_SESSION['glpiactive_entity'], 'name' => 'plugin_processmaker_process_id' ));
echo "</td><td class='center'>";
echo "<input type='submit' name='additem' value='Start' class='submit'>";
echo "</td></tr>";
echo "</table>";
Html::closeForm();
}
/**
* 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 showFormHelpdesk($ID, $pmItem, $caseInfo, $ticket_template=false) {
global $DB, $CFG_GLPI, $LANG;
if (!Session::haveRight("create_ticket","1")) {
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' => EntityData::getUsedConfig('tickettype',
$_SESSION['glpiactive_entity'],
'', Ticket::INCIDENT_TYPE),
'_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 "<form method='post' name='helpdeskform' action='".
$CFG_GLPI["root_doc"]."/front/tracking.injector.php' enctype='multipart/form-data'>";
}
$delegating = User::getDelegateGroupsForUser($options['entities_id']);
if (count($delegating)) {
echo "<div class='center'><table class='tab_cadre_fixe'>";
echo "<tr><th colspan='2'>".$LANG['job'][69]."&nbsp;:&nbsp;";
$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 "</th></tr>";
echo "<tr class='tab_bg_1'><td colspan='2' class='center'>";
echo "<div id='show_result$rand'>";
$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 "</div>";
echo "</td></tr>";
echo "</table></div>";
echo "<input type='hidden' name='_users_id_recipient' value='".Session::getLoginUserID()."'>";
}
echo "<input type='hidden' name='_from_helpdesk' value='1'>";
echo "<input type='hidden' name='requesttypes_id' value='".RequestType::getDefault('helpdesk').
"'>";
// 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 "<input type='hidden' name='$predeffield' value='$predefvalue'>";
}
}
} 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 "<input type='hidden' name='urgency' value='".$options['urgency']."'>";
}
// Display predefined fields if hidden
if ($tt->isHiddenField('itemtype')) {
echo "<input type='hidden' name='itemtype' value='".$options['itemtype']."'>";
echo "<input type='hidden' name='items_id' value='".$options['items_id']."'>";
}
echo "<input type='hidden' name='entities_id' value='".$_SESSION["glpiactive_entity"]."'>";
echo "<div class='center'><table class='tab_cadre_fixe'>";
echo "<tr><th colspan='2'>".$caseInfo->processName."&nbsp;:&nbsp;";
if (Session::isMultiEntitiesMode()) {
echo "&nbsp;(".Dropdown::getDropdownName("glpi_entities", $_SESSION["glpiactive_entity"]).")";
}
echo "</th></tr>";
echo "<tr class='tab_bg_1' style='display:none;'>";
echo "<td>".$LANG['common'][17]."&nbsp;:".$tt->getMandatoryMark('type')."</td>";
echo "<td>";
Ticket::dropdownType('type', array('value' => $options['type'],
'on_change' => 'submit()'));
echo "</td></tr>";
echo "<tr class='tab_bg_1' style='display:none;'>";
echo "<td>".$LANG['common'][36]."&nbsp;:";
echo $tt->getMandatoryMark('itilcategories_id');
echo "</td><td>";
$condition = "`is_helpdeskvisible`='1'";
switch ($options['type']) {
case Ticket::DEMAND_TYPE :
$condition .= " AND `is_request`='1'";
break;
default: // Ticket::INCIDENT_TYPE :
$condition .= " AND `is_incident`='1'";
}
$opt = array('value' => $options['itilcategories_id'],
'condition' => $condition,
'on_change' => 'submit()');
if ($options['itilcategories_id'] && $tt->isMandatoryField("itilcategories_id")) {
$opt['display_emptychoice'] = false;
}
Dropdown::show('ITILCategory', $opt);
echo "</td></tr>";
if ($CFG_GLPI['urgency_mask']!=(1<<3)) {
if (!$tt->isHiddenField('urgency')) {
echo "<tr class='tab_bg_1'>";
echo "<td>".$LANG['joblist'][29]."&nbsp;:".$tt->getMandatoryMark('urgency')."</td>";
echo "<td>";
Ticket::dropdownUrgency("urgency", $options['urgency']);
echo "</td></tr>";
}
}
if (empty($delegating) && NotificationTargetTicket::isAuthorMailingActivatedForHelpdesk()) {
echo "<tr class='tab_bg_1'>";
echo "<td>".$LANG['help'][8]."&nbsp;:&nbsp;</td>";
echo "<td>";
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 "</td></tr>";
}
if ($_SESSION["glpiactiveprofile"]["helpdesk_hardware"] != 0) {
if (!$tt->isHiddenField('itemtype')) {
echo "<tr class='tab_bg_1' style='display:none;'>";
echo "<td>".$LANG['help'][24]."&nbsp;: ".$tt->getMandatoryMark('itemtype')."</td>";
echo "<td>";
Ticket::dropdownMyDevices($options['_users_id_requester'], $_SESSION["glpiactive_entity"],
$options['itemtype'], $options['items_id']);
Ticket::dropdownAllDevices("itemtype", $options['itemtype'], $options['items_id'], 0, $options['_users_id_requester'],
$_SESSION["glpiactive_entity"]);
echo "<span id='item_ticket_selection_information'></span>";
echo "</td></tr>";
}
}
if (!$tt->isHiddenField('name')
|| $tt->isPredefinedField('name')) {
echo "<tr class='tab_bg_1' style='display:none;'>";
echo "<td>".$LANG['common'][57]."&nbsp;:".
$tt->getMandatoryMark('name')."</td>";
echo "<td><input type='text' maxlength='250' size='80' name='name'
value=\"".$options['name']."\"></td></tr>";
}
if (!$tt->isHiddenField('content')
|| $tt->isPredefinedField('content')) {
echo "<tr class='tab_bg_1' style='display:none;'>";
echo "<td>".$LANG['joblist'][6]."&nbsp;:".
$tt->getMandatoryMark('content')."</td>";
echo "<td><textarea name='content' cols='80' rows='14'>".$options['content']."</textarea>";
echo "</td></tr>";
}
echo "<tr class='tab_bg_1'>";
echo "<th class='center' colspan=2>&nbsp;";
echo "</th></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td class='center' colspan=2>";
$rand = rand();
$pmCaseUser = $caseInfo->currentUsers[0] ; // by default
$paramsURL = "DEL_INDEX=".$pmCaseUser->delIndex."&action=".$caseInfo->caseStatus ;
echo "<iframe onload='onLoadFrame( event, \"".$caseInfo->caseId."\", ".$pmCaseUser->delIndex.", ".$caseInfo->caseNumber.", \"".$caseInfo->processName."\") ;' id='caseiframe' width=100% style='border:none;' src='".$pmItem->serverURL."/cases/cases_Open?sid=". $_SESSION["pluginprocessmaker"]["session"]["id"]."&APP_UID=".$caseInfo->caseId."&".$paramsURL."&rand=$rand' ></iframe>";
echo "</td></tr>";
echo "<tr><th colspan='2'>&nbsp;";
echo "</th></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>".$LANG['document'][2]." (".Document::getMaxUploadSize().")&nbsp;:&nbsp;";
echo "<img src='".$CFG_GLPI["root_doc"]."/pics/aide.png' class='pointer' alt='".
$LANG['central'][7]."' onclick=\"window.open('".$CFG_GLPI["root_doc"].
"/front/documenttype.list.php','Help','scrollbars=1,resizable=1,width=1000,height=800')\">";
echo "&nbsp;";
Ticket::showDocumentAddButton(60);
echo "</td>";
echo "<td><div id='uploadfiles'><input type='file' name='filename[]' value='' size='60'></div>";
echo "</td></tr>";
if (!$ticket_template) {
echo "<tr class='tab_bg_1' style='display:none;'>";
echo "<td colspan='2' class='center'>";
if ($tt->isField('id') && $tt->fields['id'] > 0) {
echo "<input type='hidden' name='_tickettemplates_id' value='".$tt->fields['id']."'>";
echo "<input type='hidden' name='_predefined_fields'
value=\"".rawurlencode(serialize($predefined_fields))."\">";
}
echo "<input type='submit' name='add' value=\"".$LANG['help'][14]."\" class='submit'>";
echo "</td></tr>";
}
echo "</table></div>";
if (!$ticket_template) {
Html::closeForm();
}
}
function processMakerShowCase( $ID, $from_helpdesk ) {
global $LANG ;
Html::helpHeader($LANG['job'][13], $_SERVER['PHP_SELF'], $_SESSION["glpiname"]);
//$userGLPI = new User();
//$userGLPI->getFromDB( $ID ) ;
//if( $userGLPI->fields['language'] != null )
// $lang = substr( $userGLPI->fields['language'], 0, 2) ;
//else
// $lang = "en" ;
$pmItem = new PluginProcessmakerProcessmaker( ) ;
$pmItem->login( ) ;
//if( isset( $_REQUEST['sid'] )) {
// $pmItem->useSession( $_REQUEST['sid'], $lang ) ;
//}
//else {
// $pmItem->openSession( $userGLPI->fields['name'], "md5:37d442efb43ebb80ec6f9649b375ab72", $lang ) ;
//}
$caseInfo = $pmItem->getCaseInfo( $_REQUEST['case_id'] ) ;
if ($caseInfo->status_code == 0){
// case is created
// Must show it...
// we may input this case into a temporary case table with session id for key
// we need some more info, del_index...
// $pmCaseUser = $caseInfo->currentUsers[0] ; // by default
$rand = rand();
// echo "<div id='toHideDefaultTicketCreation' style='display: none;'>" ;
//echo "<div id='toHideDefaultTicketCreation' >" ;
echo "<script type='text/javascript' src='".GLPI_ROOT."/plugins/processmaker/js/cases.helpdesk.js'></script>" ; //?rand=$rand'
showFormHelpdesk(Session::getLoginUserID(), $pmItem, $caseInfo);
//echo "</div>";
//echo "<form name='processmaker_form$rand' id='processmaker_form$rand' method='post' action='".Toolbox::getItemTypeFormURL("PluginProcessmakerProcessmaker")."'>";
// echo "<div class='center'><table class='tab_cadre_fixehov'>";
// echo "<tr><th >Input your request, and click on 'Next Step' (when needed add files above)</th></tr>";
//echo "<tr class='tab_bg_2' ><td id='GLPI-PM-scriptCases' colspan=2>
// <script type='text/javascript' src='".GLPI_ROOT."/plugins/processmaker/js/cases.helpdesk.js'></script>
// </td></tr>" ; //?rand=$rand'
// echo "<tr><td class='center'>";
//// echo "<iframe onload='onLoadFrame( event, \"".$caseInfo->caseId."\", ".$pmCaseUser->delIndex.", ".$caseInfo->caseNumber.", \"".$caseInfo->processName."\") ;' id='caseiframe' width=100% style='border:none;' src='".$pmItem->serverURL."/cases/cases_Open?sid=". $_SESSION["pluginprocessmaker"]["session"]["id"]."&APP_UID=".$caseInfo->caseId."&".$paramsURL."&rand=$rand' ></iframe>";
// echo "</td></tr>";
//echo "<tr><td class='center'>";
////echo "<div id='toHideDefaultTicketCreation' >" ;
////echo "</div>";
//echo "</td></tr>";
echo "</table>";
// Html::closeForm();
}
}
function in_array_recursive($needle, $haystack) {
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack));
foreach($it AS $element) {
if($element == $needle) {
return true;
}
}
return false;
}
// redirect if no create ticket right
if (!Session::haveRight('create_ticket', 1)) {
if (Session::haveRight('observe_ticket', 1) || Session::haveRight('validate_ticket', 1)) {
Html::redirect($CFG_GLPI['root_doc']."/front/ticket.php");
} else if (Session::haveRight('reservation_helpdesk', 1)) {
Html::redirect($CFG_GLPI['root_doc']."/front/reservationitem.php");
} else if (Session::haveRight('faq', 'r')) {
Html::redirect($CFG_GLPI['root_doc']."/front/helpdesk.faq.php");
}
}
Session::checkHelpdeskAccess();
Html::helpHeader($LANG['job'][13], $_SERVER['PHP_SELF'], $_SESSION["glpiname"]);
if (isset($_REQUEST['case_id'])) {
$query = "SELECT * FROM glpi_plugin_processmaker_cases WHERE id='".$_REQUEST['case_id']."'" ;
$res = $DB->query( $query ) ;
if( $DB->numrows( $res ) ) // a ticket already exists for this case, then show new cases
processMakerShowProcessList(Session::getLoginUserID(), 1);
else {
// before showing the case, we must check the rights for this user to view it, if entity has been changed in the meanwhile
$processList = PluginProcessmakerProcessmaker::getProcessesWithCategoryAndProfile( $_REQUEST["itilcategories_id"], $_REQUEST["type"], $_SESSION['glpiactiveprofile']['id'], $_SESSION['glpiactive_entity'] ) ;
if( in_array_recursive( $_REQUEST['process_id'], $processList ) ) {
processMakerShowCase(Session::getLoginUserID(), 1);
} else {
Html::redirect($CFG_GLPI["root_doc"]."/front/helpdesk.public.php?create_ticket=1");
}
}
} else
processMakerShowProcessList(Session::getLoginUserID(), 1);
Html::helpFooter();
?>

15
front/profile.form.php Normal file
View File

@@ -0,0 +1,15 @@
<?php
define('GLPI_ROOT', '../../..');
include (GLPI_ROOT."/inc/includes.php");
Session::checkRight("profile", "r");
$prof = new PluginProcessmakerProfile();
//Save profile
if (isset ($_POST['update_user_profile'])) {
$prof->update($_POST);
Html::back();
}
?>

109
front/tracking.injector.php Normal file
View File

@@ -0,0 +1,109 @@
<?php
// ----------------------------------------------------------------------
// Original Author of file:
// Purpose of file:
// ----------------------------------------------------------------------
if( !defined('GLPI_ROOT' ) ) {
define('GLPI_ROOT', '../../..');
}
include_once (GLPI_ROOT . "/inc/includes.php");
if (empty($_POST["_type"])
|| ($_POST["_type"] != "Helpdesk")
|| !$CFG_GLPI["use_anonymous_helpdesk"]) {
Session::checkRight("create_ticket", "1");
}
// Security check
if (empty($_POST) || count($_POST) == 0) {
Html::redirect($CFG_GLPI["root_doc"]."/front/helpdesk.public.php");
}
// here we are going to test if we must start a process
if( isset($_POST["_from_helpdesk"]) && $_POST["_from_helpdesk"] == 1
&& isset($_POST["type"]) && $_POST["type"] == Ticket::DEMAND_TYPE
&& isset($_POST["itilcategories_id"])
&& isset($_POST["entities_id"])) {
// here we have to check if there is an existing process in the entity and with the category
// if yes we will start it
// if not we will continue
// special case if RUMT plugin is enabled and no process is available and category is 'User Management' then must start RUMT.
$processList = PluginProcessmakerProcessmaker::getProcessesWithCategoryAndProfile( $_POST["itilcategories_id"], $_POST["type"], $_SESSION['glpiactiveprofile']['id'], $_SESSION['glpiactive_entity'] ) ;
// currently only one process should be assigned to this itilcategory so this array should contain only one row
$processQt = count( $processList ) ;
if( $processQt == 1 ) {
$_POST['action']='newcase';
$_POST['plugin_processmaker_process_id'] = $processList[0]['id'];
include (GLPI_ROOT . "/plugins/processmaker/front/processmaker.form.php");
die() ;
} elseif( $processQt > 1 ) {
// in this case we should show the process dropdown selection
include (GLPI_ROOT . "/plugins/processmaker/front/processmaker.helpdesk.form.php");
die() ;
} else{
// in this case should start RUMT
// if and only if itilcategories_id matches one of the 'User Management' categories
// could be done via ARBehviours or RUMT itself
$userManagementCat = array( 100556, 100557, 100558 ) ;
$plug = new Plugin ;
if( $processQt == 0 && in_array( $_POST["itilcategories_id"], $userManagementCat) && $plug->isActivated('rayusermanagementticket' )) {
Html::redirect($CFG_GLPI['root_doc']."/plugins/rayusermanagementticket/front/rayusermanagementticket.helpdesk.public.php");
}
}
}
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 ;
}
$vars = array_merge( $vars, http_formdata_flat_hierarchy($temp) );
}
else {
$vars[$key]=$value;
}
}
return $vars;
}
}
// by default loads standard page from GLPI
//include (GLPI_ROOT . "/front/tracking.injector.php");
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIE, $_SERVER['HTTP_COOKIE']);
curl_setopt($ch, CURLOPT_REFERER, "http://localhost".$CFG_GLPI["root_doc"]."/front/tracking.injector.php" ) ;
curl_setopt($ch, CURLOPT_POST, 1);
$data = http_formdata_flat_hierarchy( $_REQUEST ) ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1 ) ;
//curl_setopt($ch, CURLOPT_PROXY, "localhost:8888");
curl_setopt($ch, CURLOPT_URL, "http://localhost".$CFG_GLPI["root_doc"]."/front/tracking.injector.php");
// as sessions in PHP are not re-entrant, we MUST close current one before curl_exec
@session_write_close() ;
curl_exec ($ch);
curl_close ($ch);

822
hook.php Normal file
View File

@@ -0,0 +1,822 @@
<?php
include_once 'inc/processmaker.class.php' ;
//function plugin_planning_populate_processmaker($param) {
// if ( !isset($param['begin']) || !isset($param['who']) ) {
// return $param;
// }
// if( isset($param['items'] ) ) {
// foreach( $param['items'] as $key => &$val) {
// $item=false;
// if( isset( $val['tickettasks_id'] ) )
// $item = new TicketTask ;
// if( $item ) {
// $item->getFromDB( $val['id'] ) ;
// PluginProcessmakerProcessmaker::canedit_item_processmakertickettask( $item ) ;
// $val['content']=$item->fields['content'];
// }
// }
// }
// return $param;
//}
function plugin_processmaker_MassiveActions($type) {
global $LANG;
switch ($type) {
case 'PluginProcessmakerProcess' :
if( plugin_processmaker_haveRight('process_config', 'w' ) )
return array('plugin_processmaker_taskrefresh' => 'Synchronize Task List');
}
return array();
}
function plugin_processmaker_MassiveActionsDisplay($options) {
global $LANG;
switch ($options['itemtype']) {
case 'PluginProcessmakerProcess' :
switch ($options['action']) {
// No case for add_document : use GLPI core one
case "plugin_processmaker_taskrefresh" :
echo "<input type='submit' name='massiveaction' class='submit' ".
"value='".$LANG['buttons'][2]."'>";
break;
}
break;
}
return "";
}
function plugin_processmaker_MassiveActionsProcess($data) {
global $LANG,$DB;
switch ($data['action']) {
case "plugin_processmaker_taskrefresh" :
if ($data['itemtype'] == 'PluginProcessmakerProcess') {
foreach ($data["item"] as $key => $val) {
if ($val == 1) {
$process = new PluginProcessmakerProcess;
//$process->getFromDB($key);
$process->refreshTasks( array( 'id' => $key ) ) ;
}
}
}
break;
}
}
/**
* Summary of plugin_processmaker_install
* Creates tables and initializes tasks, "GLPI Requesters" group
* and so on
* @return true or die!
*/
function plugin_processmaker_install() {
global $DB ;
if (TableExists("glpi_plugin_processmaker_config")) {
$query = "ALTER TABLE `glpi_plugin_processmaker_config`
ADD COLUMN `date_mod` DATETIME NULL DEFAULT NULL AFTER `pm_theme`,
ADD COLUMN `comment` TEXT NULL AFTER `date_mod`;
RENAME TABLE `glpi_plugin_processmaker_config` TO `glpi_plugin_processmaker_configs`;" ;
$DB->query($query) or die("error creating glpi_plugin_processmaker_configs" . $DB->error());
}
else
if (!TableExists("glpi_plugin_processmaker_configs")) {
$query = " CREATE TABLE `glpi_plugin_processmaker_configs` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`pm_server_URL` VARCHAR(250) NOT NULL DEFAULT 'http://localhost/',
`pm_workspace` VARCHAR(50) NOT NULL DEFAULT 'workflow',
`pm_theme` VARCHAR(50) NOT NULL DEFAULT 'classic',
`date_mod` DATETIME NULL DEFAULT NULL,
`taskcategories_id` INT(11) NULL ,
`users_id` INT(11) NULL DEFAULT NULL,
`pm_group_guid` VARCHAR(32) NULL DEFAULT NULL,
`comment` TEXT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
";
$DB->query($query) or die("error creating glpi_plugin_processmaker_configs" . $DB->error());
// ProcessMaker user creation
$user = new User;
$user->add( array( 'name' => 'ProcessMaker', 'realname' => 'Process', 'firstname' => 'Maker') ) ;
// ProcessMaker plugin configuration
$DB->query("INSERT INTO glpi_plugin_processmaker_configs ( id, name, users_id) VALUES ( 1, 'Process Maker 1', ".$user->getID()." );" ) or die("error when inserting default config" . $DB->error());
}
if (!TableExists("glpi_plugin_processmaker_profiles")) {
$query = "CREATE TABLE `glpi_plugin_processmaker_profiles` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`profiles_id` INT(11) NOT NULL DEFAULT '0' COMMENT 'RELATION to glpi_profiles (id)',
`process_config` CHAR(1) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
PRIMARY KEY (`id`),
INDEX `profiles_id` (`profiles_id`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB;" ;
$DB->query($query) or die("error creating glpi_plugin_processmaker_profiles" . $DB->error());
}
if (!TableExists("glpi_plugin_processmaker_cases")) {
$query = "CREATE TABLE `glpi_plugin_processmaker_cases` (
`id` VARCHAR(32) NOT NULL,
`items_id` INT(11) NOT NULL,
`itemtype` VARCHAR(10) NOT NULL DEFAULT 'Ticket',
`case_num` INT(11) NOT NULL,
`case_status` VARCHAR(20) NOT NULL DEFAULT 'DRAFT',
UNIQUE INDEX `items` (`itemtype`, `items_id`),
INDEX `case_status` (`case_status`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
";
$DB->query($query) or die("error creating glpi_plugin_processmaker_cases" . $DB->error());
}
if (!TableExists("glpi_plugin_processmaker_tasks")) {
$query = "CREATE TABLE `glpi_plugin_processmaker_tasks` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`items_id` INT(11) NOT NULL,
`itemtype` VARCHAR(32) NOT NULL,
`case_id` VARCHAR(32) NOT NULL,
`del_index` INT(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `case_id` (`case_id`, `del_index`),
UNIQUE INDEX `items` (`itemtype`, `items_id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
";
$DB->query($query) or die("error creating glpi_plugin_processmaker_tasks" . $DB->error());
}
if (!TableExists("glpi_plugin_processmaker_users")) {
$query = "CREATE TABLE `glpi_plugin_processmaker_users` (
`glpi_users_id` INT(11) NOT NULL ,
`pm_users_id` VARCHAR(32) NOT NULL ,
UNIQUE INDEX `glpi_users_id` (`glpi_users_id`),
UNIQUE INDEX `pm_users_id` (`pm_users_id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
";
$DB->query($query) or die("error creating glpi_plugin_processmaker_users" . $DB->error());
}
if (!TableExists("glpi_plugin_processmaker_processes")) {
$query = "CREATE TABLE `glpi_plugin_processmaker_processes` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`process_guid` VARCHAR(32) NOT NULL,
`name` VARCHAR(255) NOT NULL,
`is_active` TINYINT(1) NOT NULL DEFAULT '0',
`hide_case_num_title` TINYINT(1) NOT NULL DEFAULT '0',
`insert_task_comment` TINYINT(1) NOT NULL DEFAULT '0',
`comment` TEXT NULL,
`task_category_id` INT(11) NULL ,
`itilcategories_id` INT(11) NOT NULL DEFAULT '0',
`type` INT(11) NOT NULL DEFAULT '1' COMMENT 'Only used for Tickets',
`date_mod` DATETIME NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `process_guid` (`process_guid`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
";
$DB->query($query) or die("error creating glpi_plugin_processmaker_processes" . $DB->error());
}
if( FieldExists( 'glpi_plugin_processmaker_processes', 'is_helpdeskvisible') ) {
$query = "ALTER TABLE `glpi_plugin_processmaker_processes`
CHANGE COLUMN `is_helpdeskvisible` `is_helpdeskvisible_notusedanymore` TINYINT(1) NOT NULL DEFAULT '0' COMMENT 'Not used any more since version 2.2' AFTER `name`;" ;
$DB->query($query) ;
}
if( !FieldExists( 'glpi_plugin_processmaker_processes', 'itilcategories_id') ) {
$query = "ALTER TABLE `glpi_plugin_processmaker_processes`
ADD COLUMN `itilcategories_id` INT(11) NOT NULL DEFAULT '0',
ADD COLUMN `type` INT(11) NOT NULL DEFAULT '1' COMMENT 'Only used for Tickets';" ;
$DB->query($query) or die("error adding columns 'itilcategories_id' and 'type' to glpi_plugin_processmaker_processes" . $DB->error());
}
if (!TableExists("glpi_plugin_processmaker_processes_profiles")) { // since version 2.2
$query = "CREATE TABLE `glpi_plugin_processmaker_processes_profiles` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`processes_id` INT(11) NOT NULL DEFAULT '0',
`profiles_id` INT(11) NOT NULL DEFAULT '0',
`entities_id` INT(11) NOT NULL DEFAULT '0',
`is_recursive` TINYINT(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
INDEX `entities_id` (`entities_id`),
INDEX `profiles_id` (`profiles_id`),
INDEX `processes_id` (`processes_id`),
INDEX `is_recursive` (`is_recursive`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB;" ;
$DB->query($query) or die("error creating glpi_plugin_processmaker_processes_profiles" . $DB->error());
}
if (!TableExists("glpi_plugin_processmaker_taskcategories")) {
$query = "CREATE TABLE `glpi_plugin_processmaker_taskcategories` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`processes_id` INT(11) NOT NULL,
`pm_task_guid` VARCHAR(32) NOT NULL,
`taskcategories_id` INT(11) NOT NULL,
`start` BIT(1) NOT NULL DEFAULT b'0',
PRIMARY KEY (`id`),
UNIQUE INDEX `pm_task_guid` (`pm_task_guid`),
UNIQUE INDEX `items` (`taskcategories_id`),
INDEX `processes_id` (`processes_id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=57
;
";
$DB->query($query) or die("error creating glpi_plugin_processmaker_taskcategories" . $DB->error());
}
// create default TaskCategory if needed
// verify if taskcategory_id is set in config
// required cause autoload don't work for unactive plugin'
include_once(GLPI_ROOT."/plugins/processmaker/inc/config.class.php");
$config = new PluginProcessmakerConfig ;
$config->getFromDB( 1 ) ;
$pmCategory = $config->fields['taskcategories_id'] ;
if( !$pmCategory ) {
// add main category into config and glpi_taskcategories
$taskCat = new TaskCategory;
$pmCategory = $taskCat->add( array( 'is_recursive' => 1, 'name' => 'Process Maker', 'comment' => 'Is top category for Process Maker tasks. Name can be changed if desired.' ) ) ;
if( $pmCategory )
$config->update( array( 'id' => $config->getID(), 'taskcategories_id' => $pmCategory ) ) ;
}
$myProcessMaker = new PluginProcessmakerProcessmaker() ;
$myProcessMaker->login(true) ; // to force admin login
// verify if group 'GLPI Requesters' exists in config, if not will create it in PM and add GUID in config
$pmGroup = $config->fields['pm_group_guid'] ;
if( !$pmGroup ) {
$pmres = $myProcessMaker->createGroup( "GLPI Requesters" ) ;
if( $pmres->status_code == 0 )
$config->update( array( 'id' => $config->getID(), 'pm_group_guid' => $pmres->groupUID ) ) ;
}
// To be called for each task managed by the plugin
// task in class
CronTask::Register('PluginProcessmakerProcessmaker', 'pmusers', DAY_TIMESTAMP, array( 'state' => CronTask::STATE_DISABLE, 'mode' => CronTask::MODE_EXTERNAL));
//CronTask::Register('PluginProcessmakerProcessmaker', 'pmnotifications', DAY_TIMESTAMP, array( 'state' => CronTask::STATE_DISABLE, 'mode' => CronTask::MODE_EXTERNAL));
// required cause autoload doesn't work for unactive plugin'
include_once(GLPI_ROOT."/plugins/processmaker/inc/profile.class.php");
PluginProcessmakerProfile::createAdminAccess($_SESSION['glpiactiveprofile']['id']);
return true;
}
function plugin_processmaker_uninstall() {
global $DB;
// Current version tables
//if (TableExists("glpi_plugin_processmaker_ticketcase")) {
// $query = "DROP TABLE `glpi_plugin_processmaker_ticketcase`";
// $DB->query($query) or die("error deleting glpi_plugin_processmaker_ticketcase");
//}
CronTask::Unregister('PluginProcessmakerProcessmaker');
//if (TableExists("glpi_plugin_processmaker_processes")) {
// $query = "DROP TABLE `glpi_plugin_processmaker_processes`";
// $DB->query($query) or die("error deleting glpi_plugin_processmaker_processes");
//}
// now uninstall triggers from PM tables
//$DB->close();
//$DB->dbdefault='wf_workflow';
//$DB->connect( ) ;
//$DB->runFile(GLPI_ROOT.'/plugins/processmaker/config/pm_db_uninstall.sql') or die("error creating triggers on wf_workflow database!" . $DB->error());
//$DB->close();
//$DB->dbdefault='glpi';
//$DB->connect( ) ;
//
return true;
}
//// Define headings added by the plugin
//function plugin_get_headings_processmaker($item, $withtemplate) {
// global $LANG ;
// switch (get_class($item)) {
// case 'Ticket' :
// return array(1 => $LANG['processmaker']['ticket']['tab']);
// //case 'Profile' :
// // $prof = new Profile();
// // if ($item->fields['interface'] == 'central') {
// // return array(1 => "Test PLugin");
// // }
// // return array();
// //case 'Computer' :
// // // new object / template case
// // if ($withtemplate) {
// // return array();
// // // Non template case / editing an existing object
// // }
// // return array(1 => "Test PLugin");
// //case 'ComputerDisk' :
// //case 'Supplier' :
// // if ($item->getField('id')) { // Not in create mode
// // return array(1 => "Test PLugin",
// // 2 => "Test PLugin 2");
// // }
// // break;
// //case 'Central' :
// //case 'Preference':
// //case 'Notification':
// // return array(1 => "Test PLugin");
// }
// return false;
//}
//// Define headings actions added by the plugin
//function plugin_headings_actions_processmaker($item) {
// switch (get_class($item)) {
// //case 'Profile' :
// //case 'Computer' :
// // return array(1 => "plugin_headings_processmaker");
// //case 'ComputerDisk' :
// //case 'Supplier' :
// // return array(1 => "plugin_headings_processmaker",
// // 2 => "plugin_headings_processmaker");
// //case 'Central' :
// //case 'Preference' :
// //case 'Notification' :
// case 'Ticket' :
// return array(1 => "plugin_headings_processmaker");
// }
// return false;
//}
//// Example of an action heading
//function plugin_headings_processmaker($item, $withtemplate=0) {
// global $LANG, $DB, $GLOBALS ;
// if (!$withtemplate) {
// echo "<div class='center'>";
// switch (get_class($item)) {
// //case 'Central' :
// // echo "Plugin central action ".$LANG['plugin_processmaker']["test"];
// // break;
// //case 'Preference' :
// // // Complete form display
// // $data = plugin_version_processmaker();
// // echo "<form action='Where to post form'>";
// // echo "<table class='tab_cadre_fixe'>";
// // echo "<tr><th colspan='3'>".$data['name']." - ".$data['version'];
// // echo "</th></tr>";
// // echo "<tr class='tab_bg_1'><td>Name of the pref</td>";
// // echo "<td>Input to set the pref</td>";
// // echo "<td><input class='submit' type='submit' name='submit' value='submit'></td>";
// // echo "</tr>";
// // echo "</table>";
// // echo "</form>";
// // break;
// //case 'Notification' :
// // echo "Plugin mailing action ".$LANG['plugin_processmaker']["test"];
// // break;
// case 'Ticket' :
// //echo "Show the iframe";
// $rand = rand();
// echo "<form name='processmaker_form$rand' id='processmaker_form$rand' method='post' action='".Toolbox::getItemTypeFormURL("PluginProcessmakerProcessmaker")."'>";
// echo "<div class='center'><table class='tab_cadre_fixehov'>";
// echo "<tr><th colspan='2'>".$LANG['processmaker']['ticket']['tab']."</th></tr>";
// //$userGLPI = new User();
// //$userGLPI->getFromDB( Session::getLoginUserID() ) ;
// //if( $userGLPI->fields['language'] != null )
// // $lang = substr( $userGLPI->fields['language'], 0, 2) ;
// //else
// // $lang = "en" ;
// $myProcessMaker = new PluginProcessmakerProcessmaker( ) ;
// $myProcessMaker->login(); //openSession( $userGLPI->fields['name'], "md5:37d442efb43ebb80ec6f9649b375ab72", $lang ) ;
// // first search for the case
// $ticket_id = $item->getField('id') ;
// $caseInfo = $myProcessMaker->getCaseFromItem( "Ticket", $ticket_id ) ;
// if( $caseInfo !== false ){
// // need to get info on the thread of the GLPI current user
// // we must retreive currentGLPI user from this array
// $GLPICurrentPMUserId = PluginProcessmakerProcessmaker::getPMUserId( Session::getLoginUserID() ) ; //$userGLPI->fields['id'] ) ;
// $pmCaseUser = $caseInfo->currentUsers[0] ; // by default
// foreach( $caseInfo->currentUsers as $caseUser) {
// if( $caseUser->userId == $GLPICurrentPMUserId ){
// $pmCaseUser = $caseUser ;
// break ;
// }
// }
// if( $pmCaseUser->delThreadStatus == 'PAUSE' ) {
// // means the case itself may not be PAUSED, but task assigned to current GLPI user is paused...
// // then forced PAUSE view for this thread
// // and give possibility to unpause it
// $caseInfo->caseStatus = 'PAUSED' ;
// }
// switch ( $caseInfo->caseStatus ) {
// case "CANCELLED" :
// echo "<tr><th colspan='2'>".$LANG['processmaker']['ticket']['cancelledcase']."</th></tr>";
// $paramsURL = "DEL_INDEX=1" ;
// break;
// case 'PAUSED' :
// // we need to add a button to unpause the case
// echo "<input type='hidden' name='action' value='unpausecase'>";
// echo "<input type='hidden' name='id' value='".$ticket_id."'>";
// echo "<input type='hidden' name='itemtype' value='".$item->gettype()."'>";
// echo "<input type='hidden' name='plugin_processmaker_caseId' value='".$caseInfo->caseId."'>";
// echo "<input type='hidden' name='plugin_processmaker_delIndex' value='".$pmCaseUser->delIndex."'>";
// echo "<input type='hidden' name='plugin_processmaker_userId' value='".$pmCaseUser->userId."'>";
// echo "<tr><th>".$LANG['processmaker']['ticket']['pausedtask']."</th><th>";
// echo "<input type='submit' name='unpausecase' value='".$LANG['processmaker']['ticket']['unpause']."' class='submit'>";
// echo "</th></tr>";
// case "DRAFT" :
// case "TO_DO" :
// $paramsURL = "DEL_INDEX=".$pmCaseUser->delIndex."&action=".$caseInfo->caseStatus ;
// break ;
// case "COMPLETED" :
// echo "<tr><th colspan='2'>".$LANG['processmaker']['ticket']['completedcase']."</th></tr>";
// $paramsURL = "DEL_INDEX=1" ;
// break ;
// }
// echo "<tr class='tab_bg_2' ><td colspan=2>" ;
// echo "<script>
// //var bLoads = 0 ;
// function reloadParent( locParent ) {
// if( locParent.location == locParent.parent.location )
// locParent.location.reload( ) ;
// else
// reloadParent( locParent.parent ) ;
// }
// var oldHandler ;
// var oldParent ;
// var submitButton ;
// function onClickContinue( obj ) {
// // call old handler
// if( obj != undefined )
// oldHandler(obj.target);
// reloadParent( oldParent ) ;
// }
// function onLoadFrame() {
// //debug();
// var caseTimerCounter = 0 ;
// var caseTimer = window.setInterval(function() {
// //debug() ;
// var contentDocument = document.getElementById('caseiframe').contentDocument.getElementById('openCaseFrame').contentDocument ;
// var cancelButton = contentDocument.getElementById('form[BTN_CANCEL]') ;
// var formDerivation = contentDocument.getElementById('frmDerivation') ;
// var buttonContinue = contentDocument.getElementById('btnContinue') ;
// if(cancelButton != undefined) {
// window.clearInterval(caseTimer) ;
// cancelButton.style.visibility='hidden';
// // TODO manage 'Claim' button
// } elseif( formDerivation != undefined && buttonContinue != undefined ) {
// window.clearInterval(caseTimer) ;
// buttonContinue.form.action = '' ;
// oldHandler = buttonContinue.onclick ;
// buttonContinue.onclick = onClickContinue ;
// oldParent = document ;
// } else
// caseTimerCounter = caseTimerCounter + 1 ;
// if( caseTimerCounter > 3000 ) {
// window.clearInterval(caseTimer) ;
// }
// }, 10) ;
// //alert( bLoads ) ;
// //if( bLoads >= 1 )
// // means something has been done in the iFrame of ProcessMaker, then we may reload the complete page in order to
// // 1) prevent view of the casesListExtJs
// // 2) refresh the view of the case with the open form
// // reloadParent( parent ) ;
// //else bLoads = bLoads + 1 ;
// }
// </script>";
// echo "<iframe onload='onLoadFrame();' id='caseiframe' height=1080 width=100% src='".$myProcessMaker->serverURL."/cases/open?sid=".$_SESSION["pluginprocessmaker"]["Session"]."&APP_UID=".$caseInfo->caseId."&".$paramsURL."' >" ;
// echo "</iframe>";
// echo "</td></tr>";
// } else {
// // no running case for this ticket
// // propose to start one
// echo "<tr><th colspan='2'>".$LANG['processmaker']['ticket']['nocase'] ;
// // check if ticket is not solved nor closed
// if( $item->fields['status'] != 'solved' && $item->fields['status'] != 'closed' ) {
// // propose case start
// echo "&nbsp;-&nbsp;".$LANG['processmaker']['ticket']['startone'];
// echo "</th></tr>";
// echo "<tr class='tab_bg_2'><td class='right' colspan='1'>";
// echo $LANG['processmaker']['ticket']['selectprocess']."&nbsp;";
// echo "<input type='hidden' name='action' value='newcase'>";
// echo "<input type='hidden' name='id' value='".$item->getField('id')."'>";
// echo "<input type='hidden' name='itemtype' value='".$item->gettype()."'>";
// Dropdown::show('PluginProcessmakerProcessmaker', array( 'name' => 'plugin_processmaker_process_id', 'condition' => "trigger_guid != ''")); // condition is used to prevent start of cases without trigger
// echo "</td><td class='center'>";
// echo "<input type='submit' name='additem' value='".$LANG['processmaker']['ticket']['start']."' class='submit'>";
// echo "</td></tr>";
// }
// else echo "</th></tr>";
// }
// echo "</table>";
// echo "</form>";
// break;
// default :
// echo "Plugin function with headings CLASS=".get_class($item)." id=".$item->getField('id');
// break;
// }
// echo "</div>";
// }
//}
function plugin_processmaker_getAddSearchOptions($itemtype) {
global $LANG;
$sopt = array();
if ($itemtype == 'Ticket') {
$sopt[10001]['table'] = 'glpi_plugin_processmaker_cases';
$sopt[10001]['field'] = 'case_status';
//$sopt[1001]['linkfield'] = 'id';
$sopt[10001]['massiveaction'] = false;
$sopt[10001]['name'] = $LANG['processmaker']['search']['case'].' - '.$LANG['processmaker']['search']['status'];
$sopt[10001]['datatype'] = 'text';
$sopt[10001]['forcegroupby'] = true ;
//$sopt[10001]['searchtype'] = 'equals';
//$sopt[1001]['itemlink_type'] = 'PluginProcessmakerTicketcase';
//$sopt[1001]['table'] = 'glpi_plugin_processmaker_ticketcase';
//$sopt[1001]['field'] = 'case_status';
//$sopt[1001]['massiveaction'] = false;
//$sopt[1001]['name'] = 'Case - Status';
//$sopt[1001]['forcegroupby'] = true;
//$sopt[1001]['datatype'] = 'itemlink';
// $sopt[1001]['itemlink_type'] = 'PluginProcessmakerProcessmaker';
//$sopt[1001]['joinparams'] = array('beforejoin'
// => array('table' => 'glpi_plugin_processmaker_ticketcase',
// 'linkfield' => 'ticket_id'));
//$sopt[1001]['joinparams']['jointype'] = "itemtype_id";
//$sopt[1001]['pfields_type'] = ;
}
return $sopt;
}
function plugin_processmaker_addLeftJoin($type,$ref_table,$new_table,$linkfield,&$already_link_tables) {
switch ($type){
case 'Ticket':
switch ($new_table){
case "glpi_plugin_processmaker_cases" :
$out= " LEFT JOIN `glpi_plugin_processmaker_cases`
ON (`$ref_table`.`id` = `glpi_plugin_processmaker_cases`.`items_id` AND `glpi_plugin_processmaker_cases`.`itemtype` like 'Ticket') ";
return $out;
break;
}
return "";
break;
}
return "";
}
/**
* Summary of plugin_pre_item_update_processmaker
* @param CommonITILObject $parm
*/
function plugin_pre_item_update_processmaker(CommonITILObject $parm) {
global $DB ;
if( isset($_SESSION['glpiname']) && $parm->getType() == 'Ticket' ) {
$locCase = new PluginProcessmakerCases ;
$itemId = $parm->getID() ;
$itemType = $parm->getType() ;
if( $locCase->getCaseFromItemTypeAndItemId( $itemType, $itemId ) ) {
$locPM = new PluginProcessmakerProcessmaker ;
$locPM->login() ;
// case is existing for this item
$technicians = PluginProcessmakerProcessmaker::getItemUsers( $itemType, $itemId, 2 ) ; // 2 for technicians
// beware to empty injection when not modified!!!
$locVar = array( ) ;
foreach( $parm->input as $key => $val ) {
switch( $key ) {
case 'global_validation' :
$locVar[ 'GLPI_TICKET_GLOBAL_VALIDATION' ] = $val ;
break;
case 'due_date' :
$locVar[ 'GLPI_TICKET_DUE_DATE' ] = $val ;
break;
case 'urgency' :
$locVar[ 'GLPI_TICKET_URGENCY' ] = $val ;
break;
case 'impact' :
$locVar[ 'GLPI_ITEM_IMPACT' ] = $val ;
break;
case 'priority' :
$locVar[ 'GLPI_ITEM_PRIORITY' ] = $val ;
break;
}
}
// $locVar['GLPI_TICKET_TECHNICIAN_GLPI_ID']=$technicians[0]['glpi_id'];
// $locVar['GLPI_TICKET_TECHNICIAN_PM_ID']=$technicians[0]['pm_id'];
$pmResponse = $locPM->sendVariables( $locCase->getID(), $locVar) ;
//$locCase->sendVariables( $locVar ) ;
}
}
}
function plugin_item_update_processmaker_satisfaction($parm) {
global $DB, $GLOBALS ;
$locCase = new PluginProcessmakerCases ;
if( $locCase->getCaseFromItemTypeAndItemId( 'Ticket', $parm->fields['tickets_id'] ) ) {
// case is existing for this item
//$query = "select * from wf_workflow.application where APP_UID='".$locCase->getID()."';" ;
//$res = $DB->query($query) ;
//$app_data = array() ;
//if( $DB->numrows($res) > 0) {
// $row = $DB->fetch_assoc($res);
// $app_data = unserialize($row['APP_DATA'] ) ;
//}
//$locVars = array( 'GLPI_SATISFACTION_QUALITY' => $parm->fields['satisfaction'],
// 'GLPI_SATISFACTION_RESPONSETIME' => $parm->fields['responsetime'],
// 'GLPI_SATISFACTION_FRIENDLINESS' => $parm->fields['friendliness'] ) ;
$locPM = new PluginProcessmakerProcessmaker ;
$locPM->login() ;
$pmResponse = $locPM->sendVariables( $locCase->getID(), array(
'GLPI_SATISFACTION_QUALITY' => $parm->fields['satisfaction'],
'GLPI_SATISFACTION_RESPONSETIME' => $parm->fields['responsetime'],
'GLPI_SATISFACTION_FRIENDLINESS' => $parm->fields['friendliness']
)) ;
//$locCase->sendVariables( $locVars ) ;
}
}
function plugin_pre_item_update_processmaker_followup($parm) {
}
function plugin_pre_item_purge_processmaker ( $parm ) {
if( $parm->getType() == 'Ticket_User' && is_array( $parm->fields ) && isset( $parm->fields['type'] ) && $parm->fields['type'] == 2 ) {
$itemId = $parm->fields['tickets_id'] ;
$itemType = 'Ticket' ;
$technicians = PluginProcessmakerProcessmaker::getItemUsers( $itemType, $itemId, 2 ) ; // 2 for technicians
//$locCase = new PluginProcessmakerCases ;
if( PluginProcessmakerCases::getCaseIdFromItemTypeAndItemId( $itemType, $itemId ) && count($technicians) == 1 ) {
$parm->input = null ; // to cancel deletion of the last tech in the ticket
}
}
}
function plugin_item_purge_processmaker($parm) {
global $DB ;
if( $parm->getType() == 'Ticket_User' && is_array( $parm->fields ) && isset( $parm->fields['type'] ) && $parm->fields['type'] == 2 ) {
// We just deleted a tech from this ticket then we must if needed "de-assign" the tasks assigned to this tech
// and re-assign them to the first tech in the list !!!!
$locCase = new PluginProcessmakerCases ;
$itemId = $parm->fields['tickets_id'] ;
$itemType = 'Ticket' ;
if( $locCase->getCaseFromItemTypeAndItemId( $itemType, $itemId ) ) {
// case is existing for this item
$technicians = PluginProcessmakerProcessmaker::getItemUsers( $itemType, $itemId, 2 ) ; // 2 for technicians
$locPM = new PluginProcessmakerProcessmaker ;
$locPM->login() ;
//$pmResponse = $locPM->sendVariables( $locCase->getID(), array(
// 'GLPI_TICKET_TECHNICIAN_GLPI_ID' => $technicians[0]['glpi_id'],
// 'GLPI_TICKET_TECHNICIAN_PM_ID' => $technicians[0]['pm_id']
// ) ) ;
$locVars = array( 'GLPI_TICKET_TECHNICIAN_GLPI_ID' => $technicians[0]['glpi_id'],
'GLPI_TICKET_TECHNICIAN_PM_ID' => $technicians[0]['pm_id'] ) ;
//$locCase->sendVariables( $locVars ) ;
// and we must find all tasks assigned to this former user and re-assigned them to new user (if any :))!
$caseInfo = $locPM->getCaseInfo( $locCase->getID() ) ;
if( $caseInfo !== false ){
$locPM->sendVariables( $locCase->getID( ), $locVars ) ;
// need to get info on the thread of the GLPI current user
// we must retreive currentGLPI user from this array
$GLPICurrentPMUserId = PluginProcessmakerProcessmaker::getPMUserId( $parm->fields['users_id'] ) ;
foreach( $caseInfo->currentUsers as $caseUser) {
if( $caseUser->userId == $GLPICurrentPMUserId && in_array( $caseUser->delThreadStatus, array('DRAFT', 'OPEN', 'PAUSE' ) ) ){
$pmResponse = $locPM->reassignCase( $locCase->getID(), $caseUser->delIndex, $GLPICurrentPMUserId, $technicians[0]['pm_id'] ) ;
// now should managed GLPI Tasks previously assigned to the $GLPICurrentPMUserId
if( $pmResponse->status_code == 0 ) {
// ATTENTION: should be aware of: ticket tech == task tech
// In this particular flow due to 'Change Management'
// 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( $locCase->getID() ) ;
$newDelIndex = 0 ;
foreach( $newCaseInfo->currentUsers as $newCaseUser ){
if( $newCaseUser->taskId == $caseUser->taskId && $newCaseUser->delThread == $caseUser->delThread ) {
$newDelIndex = $newCaseUser->delIndex ;
break ;
}
}
$locPM->reassignTask( $locCase->getID(), $caseUser->delIndex, $newDelIndex, $technicians[0]['glpi_id'] ) ;
}
}
}
}
}
}
}
?>

32
importUsersGLPI2PM.php Normal file
View File

@@ -0,0 +1,32 @@
<?php
/*
*
* */
// ----------------------------------------------------------------------
// Original Author of file: Olivier Moron
// Purpose of file: script to be used to purge logos from DB
// ----------------------------------------------------------------------
// Ensure current directory as run command prompt
chdir(dirname($_SERVER["SCRIPT_FILENAME"]));
define('DO_NOT_CHECK_HTTP_REFERER', 1);
define('GLPI_ROOT', '../..');
include (GLPI_ROOT . "/inc/includes.php");
include_once 'inc/processmaker.class.php' ;
$myCronTask = new CronTask;
if( $myCronTask->getFromDBbyName( "PluginProcessmakerProcessmaker", "pmusers" ) ) {
$myCronTask->start();
$ret = PluginProcessmakerProcessmaker::cronPMUsers( $myCronTask ) ;
$myCronTask->end( $ret ) ;
} else
echo "Cron not found!\n" ;
?>

14
inc/case.class.php Normal file
View File

@@ -0,0 +1,14 @@
<?php
/**
* case short summary.
*
* case description.
*
* @version 1.0
* @author MoronO
*/
class PluginProcessmakerCase extends CommonDBTM {
}
?>

713
inc/cases.class.php Normal file
View File

@@ -0,0 +1,713 @@
<?php
/**
* ticketcase short summary.
*
* ticketcase description.
*
* @version 1.0
* @author MoronO
*/
class PluginProcessmakerCases extends CommonDBTM {
function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
global $LANG;
$item_id = $item->getID() ;
$item_type = $item->getType() ;
if( self::getCaseFromItemTypeAndItemId($item_type, $item_id ) ){
return array( 'processmakercases' => $LANG['processmaker']['item']['tab']."<sup>(".$this->fields['case_status'].")</sup>" );
} else
return array( 'processmakercases' => $LANG['processmaker']['item']['tab'] );
}
/**
* Summary of getCaseIdFromItemTypeAndItemId
* @param mixed $itemType
* @param mixed $itemId
* @return mixed
*/
static function getCaseIdFromItemTypeAndItemId( $itemType, $itemId) {
global $DB;
$query = "SELECT * FROM glpi_plugin_processmaker_cases WHERE items_id=$itemId and itemtype='$itemType';" ;
if( ($res = $DB->query($query) ) && $DB->numrows($res) > 0) {
$row = $DB->fetch_array($res);
return $row['id'] ;
}
return false ;
}
/**
* Summary of getCaseFromItemTypeAndItemId
* @param mixed $itemType
* @param mixed $itemId
* @return mixed: returns false when there is no case associated with the item, else fills in the item fields from DB, and returns true
*/
function getCaseFromItemTypeAndItemId($itemType, $itemId) {
if( $caseId = self::getCaseIdFromItemTypeAndItemId( $itemType, $itemId) )
return $this->getFromDB( $caseId ) ;
return false ;
}
/**
* Summary of getFromDB
* @param mixed $ID
* @return mixed
*/
function getFromDB($ID) {
global $DB;
// Search for object in database and fills 'fields'
// != 0 because 0 is consider as empty
if (strlen($ID)==0) {
return false;
}
$query = "SELECT *
FROM `".$this->getTable()."`
WHERE `".$this->getIndexName()."` = '".$ID."'";
if ( ($result = $DB->query($query)) && $DB->numrows($result)==1) {
$this->fields = $DB->fetch_assoc($result);
$this->post_getFromDB();
return true;
}
return false;
}
/**
* Summary of getVariables
* Gets variables from a case.
* @param array $vars an array of variable name that will be read from the case as case variables
* @return an associative array (variable_name => value). The returned array can be empty if requested variables are not found.
*/
function getVariables( $vars = array() ) {
global $DB ;
$locVars = array( ) ;
$app_data = array() ; // by default
$caseId = $this->getID() ;
$query = "select APP_DATA from wf_workflow.application where APP_UID='$caseId';" ;
if( ($res = $DB->query($query)) && $DB->numrows($res) > 0) {
$row = $DB->fetch_assoc($res);
$app_data = unserialize($row['APP_DATA'] ) ;
$locVars = array_intersect_key( $app_data, array_flip($vars) ) ;
}
return $locVars ;
}
/**
* Summary of sendVariables
* Sends variables to a case.
* BEWARE that this will not work correctly for values containning special chars like \
* instead use the web service function from PluginProcessmakerProcessmaker class
* @param array $vars an array of associative variables (name => value) that will be injected into the case as case variables
* @return true if variables have been saved to the case, false otherwise
*/
function sendVariables( $vars = array() ) {
global $DB ;
$variablesSent = false ; // be default
$app_data = array() ; // by default
$caseId = $this->getID() ;
$query = "select APP_DATA from wf_workflow.application where APP_UID='$caseId';" ;
if( ($res = $DB->query($query)) && $DB->numrows($res) > 0) {
$row = $DB->fetch_assoc($res);
$app_data = unserialize($row['APP_DATA'] ) ;
}
$app_data = array_replace( $app_data, $vars ) ;
$serialized = serialize( $app_data ) ;
$query = "update wf_workflow.application set APP_DATA='$serialized' where APP_UID='$caseId';" ;
$res = $DB->query( $query ) ;
if( $DB->affected_rows() == 1 ) {
$variablesSent = true ;
}
return $variablesSent ;
}
/**
* Summary of displayTabContentForItem
* @param CommonGLPI $item
* @param mixed $tabnum
* @param mixed $withtemplate
* @return mixed
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
global $LANG, $DB;
$item_id = $item->getID() ;
$item_type = $item->getType() ;
////retrieve container for current tab
//$container = new self;
//$found_c = $container->find("`itemtype` = '$item_type' AND `items_id` = $item_id ");
//echo "Show the frame";
$rand = rand();
echo "<form style='margin-bottom: 0px' name='processmaker_form$rand' id='processmaker_form$rand' method='post' action='".Toolbox::getItemTypeFormURL("PluginProcessmakerProcessmaker")."'>";
echo "<div class='center'><table style='margin-bottom: 0px' class='tab_cadre_fixehov'>";
echo "<tr><th colspan='4'>".$LANG['processmaker']['item']['tab']."</th></tr>";
$pmCaseUser = false ; // initial value: no user
// first search for the case
if( self::getCaseIdFromItemTypeAndItemId($item_type, $item_id ) ){
$myProcessMaker = new PluginProcessmakerProcessmaker( ) ;
$myProcessMaker->login();
$caseInfo = $myProcessMaker->getCaseFromItem( $item_type, $item_id ) ;
if( $caseInfo->caseStatus != 'CANCELLED' && $caseInfo->caseStatus != 'COMPLETED' ) {
// need to get info on the thread of the GLPI current user
// we must retreive currentGLPI user from this array
$GLPICurrentPMUserId = PluginProcessmakerProcessmaker::getPMUserId( Session::getLoginUserID() ) ;
$pmCaseUser = $caseInfo->currentUsers[0] ; // by default currently manage only one task at a time, must define tab management for several tasks
foreach( $caseInfo->currentUsers as $caseUser) {
if( $caseUser->userId == $GLPICurrentPMUserId ){
$pmCaseUser = $caseUser ;
break ;
}
}
//if( $pmCaseUser->delThreadStatus == 'PAUSE' ) {
// // means the case itself may not be PAUSED, but task assigned to current GLPI user is paused...
// // then forced PAUSE view for this thread
// // and give possibility to unpause it
// $caseInfo->caseStatus = 'PAUSED' ;
//}
}
$locDelIndex = 1 ; // by default
switch ( $caseInfo->caseStatus ) {
case "CANCELLED" :
echo "<tr><th colspan='4'>".$LANG['processmaker']['item']['cancelledcase']."</th></tr>";
$paramsURL = "DEL_INDEX=1" ;
// echo "<tr class='tab_bg_1' ><td id='GLPI-PM-DEL_INDEX' ><script>var GLPI_DEL_INDEX = 1; </script></td></tr>" ;
break;
//case 'PAUSED' :
// // we need to add a button to unpause the case
// //echo "<input type='hidden' name='id' value='$item_id'>";
// //echo "<input type='hidden' name='itemtype' value='$item_type'>";
// //echo "<input type='hidden' name='plugin_processmaker_caseId' value='".$caseInfo->caseId."'>";
// //echo "<input type='hidden' name='plugin_processmaker_delIndex' value='".$pmCaseUser->delIndex."'>";
// //echo "<input type='hidden' name='plugin_processmaker_userId' value='".$pmCaseUser->userId."'>";
// echo "<tr><th colspan='4'>".$LANG['processmaker']['item']['pausedtask']."</th><th>";
// echo "<input type='submit' name='unpausecase' value='".$LANG['processmaker']['item']['unpause']."' class='submit'>";
// echo "</th></tr>";
case "DRAFT" :
case "TO_DO" :
$paramsURL = "DEL_INDEX=".$pmCaseUser->delIndex."&action=".$caseInfo->caseStatus ;
$locDelIndex = $pmCaseUser->delIndex ;
if( $pmCaseUser->userId != '' ) {
echo "<tr class='tab_bg_1'>" ;
if( $caseInfo->caseStatus == "DRAFT" ) {
// then propose a button to delete case
echo "<td class='tab_bg_2'>";
echo $LANG['processmaker']['item']['deletecase'] ;
echo "</td><td class='tab_bg_2'>";
echo "<input type='hidden' name='action' value='unpausecase_or_reassign_or_delete'>";
echo "<input type='hidden' name='plugin_processmaker_caseId' value='".$caseInfo->caseId."'>";
echo "<input onclick='ret = confirm(\"".$LANG['processmaker']['item']['buttondeletecaseconfirmation']."\"); cancelMyMask = !ret ; return ret;' type='submit' name='delete' value='".$LANG['processmaker']['item']['buttondeletecase']."' class='submit' >";
echo "</td>";
} elseif( $GLPICurrentPMUserId == $pmCaseUser->userId) {
// then propose a button to cancel case only when assigned user is == to glpi current user
echo "<td class='tab_bg_2' >";
echo $LANG['processmaker']['item']['cancelcase'] ;
echo "</td><td class='tab_bg_2'>";
echo "<input type='hidden' name='action' value='unpausecase_or_reassign_or_delete'>";
echo "<input type='hidden' name='plugin_processmaker_caseId' value='".$caseInfo->caseId."'>";
//echo "<input type='hidden' name='plugin_processmaker_delIndex' value='".$pmCaseUser->delIndex."'>";
//echo "<input type='hidden' name='plugin_processmaker_userId' value='".$pmCaseUser->userId."'>";
echo "<input onclick='ret = confirm(\"".$LANG['processmaker']['item']['buttoncancelcaseconfirmation']."\") ; cancelMyMask = !ret ; return ret;' type='submit' name='cancel' value='".$LANG['processmaker']['item']['buttoncancelcase']."' class='submit'>";
echo "</td>";
}
echo "<td class='tab_bg_2' colspan='1'>";
echo "</form>";
echo "</td></tr>";
}
break ;
case "COMPLETED" :
echo "<tr><th colspan='4'>".$LANG['processmaker']['item']['completedcase']."</th></tr>";
$paramsURL = "DEL_INDEX=" ; // DEL_INDEX is not set to tell PM to show the current task i.e.: the last one
break ;
}
// then propose a button to view case history
echo "<tr class='tab_bg_1' >" ;
echo "<td class='tab_bg_2' colspan='1'>";
echo "<input type='button' class='button' onclick=\"javascript:Actions.tabFrame('caseMap');\" value='".$LANG['processmaker']['item']['case']['viewcasemap']."'>";
echo "</td>";
echo "<td class='tab_bg_2' colspan='1'>";
echo "<input type='button' class='button' onclick=\"javascript:Actions.tabFrame('caseHistory');\" value='".$LANG['processmaker']['item']['case']['viewcasehistory']."'>";
echo "</td>";
echo "<td class='tab_bg_2' colspan='1'>";
echo "<input type='button' class='button' onclick=\"javascript:Actions.tabFrame('historyDynaformPage');\" value='".$LANG['processmaker']['item']['case']['viewdynaforms']."'>";
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1' ><td class='tab_bg_2' colspan=4>" ;
echo "<div id=processmakertabpanel></div>" ;
echo "</td></tr>";
echo "<tr class='tab_bg_1' ><td class='tab_bg_2' colspan=4 >" ;
echo "<script type='text/javascript' src='".GLPI_ROOT."/plugins/processmaker/js/cases.js'></script>" ; //?rand=$rand'
echo "<script>
var historyGridListChangeLogGlobal = { viewIdHistory: '', viewIdDin: '', viewDynaformName: '', idHistory: '' } ;
var ActionTabFrameGlobal = { tabData: '', tabName: '', tabTitle: '' } ;
var Actions = { tabFrame: function( actionToDo ) {
if( actionToDo == 'caseMap' ) {
if( !tabs.items.containsKey( 'caseMap' ) ) {
tabs.add( {
title: '".$LANG['processmaker']['item']['case']['casemap']."',
id: 'caseMap',
closable: true,
listeners: { activate: function () {
// debugger ;
onOtherFrameLoad( 'caseMap', 'caseMapFrame', 'body' ) ;
}
},
html: \"<iframe id='caseMapFrame' \" +
\"style='border:none;' \" +
\"onload='onOtherFrameLoad( \\\"caseMap\\\", \\\"caseMapFrame\\\", \\\"body\\\" );' \" +
\"width='100%' \" +
\"src='".$myProcessMaker->serverURL."/cases/ajaxListener?action=processMap&rand=$rand' >\" +
\"</iframe>\"
} ) ;
tabs.doLayout( ) ;
}
tabs.setActiveTab( 'caseMap' ) ;
}
else
if( actionToDo == 'caseHistory' ) {
if( !tabs.items.containsKey( 'caseHistory' ) ) {
tabs.add( {
title: '".$LANG['processmaker']['item']['case']['casehistory']."',
id: 'caseHistory',
closable: true,
listeners: { activate: function () {
//debugger ;
onOtherFrameLoad( 'caseHistory', 'caseHistoryFrame', 'body' ) ;
}
},
html: \"<iframe id='caseHistoryFrame' \" +
\"height='500px' \" +
\"style='border:none;' \" +
\"onload='onOtherFrameLoad( \\\"caseHistory\\\", \\\"caseHistoryFrame\\\", \\\"body\\\" );' \" +
\"width='100%' \" +
\"src='".$myProcessMaker->serverURL."/cases/ajaxListener?action=caseHistory&rand=$rand' >\" +
\"</iframe>\"
} ) ;
tabs.doLayout( ) ;
}
tabs.setActiveTab( 'caseHistory' ) ;
}
else
if( actionToDo == 'dynaformViewFromHistory' ) {
//debugger;
actionToDo = 'dynaformChangeLogViewHistory' + historyGridListChangeLogGlobal.viewIdDin + historyGridListChangeLogGlobal.dynDate ;
if( !tabs.items.containsKey( actionToDo ) ) {
ajaxResponse = Ext.util.JSON.decode(historyGridListChangeLogGlobal.viewDynaformName);
tabs.add( {
title: ajaxResponse.dynTitle + ' <sup>(' + historyGridListChangeLogGlobal.dynDate + ')</sup>',
id: actionToDo,
closable: true,
listeners: { activate: function () {
// debugger ;
onOtherFrameLoad( actionToDo, actionToDo+'Frame', 'body' ) ;
}
},
html: \"<iframe id='\"+actionToDo+\"Frame' \" +
\"style='border:none;' \" +
\"width='100%' \" +
\"onload='onOtherFrameLoad( \\\"\"+actionToDo+\"\\\", \\\"\"+actionToDo+\"Frame\\\", \\\"body\\\" );' \" +
\"src='".$myProcessMaker->serverURL."/cases/ajaxListener?action=dynaformViewFromHistory&DYN_UID=\" + historyGridListChangeLogGlobal.viewIdDin + \"&HISTORY_ID=\" + historyGridListChangeLogGlobal.viewIdHistory + \"&rand=$rand' >\" +
\"</iframe>\"
} ) ;
tabs.doLayout( ) ;
}
tabs.setActiveTab( actionToDo ) ;
}
else
if( actionToDo == 'historyDynaformPage' ) {
if( !tabs.items.containsKey( 'historyDynaformPage' ) ) {
tabs.add( {
title: '".$LANG['processmaker']['item']['case']['dynaforms']."',
id: 'historyDynaformPage',
closable: true,
listeners: { activate: function () {
//debugger ;
onOtherFrameLoad( 'historyDynaformPage', 'historyDynaformPageFrame', 'body' ) ;
}
},
html: \"<iframe id='historyDynaformPageFrame' \" +
\"onload='onOtherFrameLoad( \\\"\"+actionToDo+\"\\\", \\\"\"+actionToDo+\"Frame\\\", \\\"body\\\" );' \" +
\"style='border:none;' \" +
\"width='100%' \" +
\"src='".$myProcessMaker->serverURL."/cases/casesHistoryDynaformPage_Ajax?actionAjax=historyDynaformPage&rand=$rand' >\" +
\"</iframe>\"
} ) ;
tabs.doLayout( ) ;
}
tabs.setActiveTab( 'historyDynaformPage' ) ;
}
else
if( actionToDo.search( '^changeLog' ) == 0 ) {
if( !tabs.items.containsKey( 'changeLog' ) ) {
tabs.add( {
title: '".$LANG['processmaker']['item']['case']['changelog']."',
id: 'changeLog',
closable: true,
listeners: { activate: function () {
//debugger ;
onOtherFrameLoad( 'changeLog', 'changeLogFrame', 'body' ) ;
}
}, html: \"<iframe id='changeLogFrame' \" +
\"style='border:none;' \" +
\"height='500px' \" +
\"width='100%' \" +
\"onload='onOtherFrameLoad( \\\"changeLog\\\", \\\"changeLogFrame\\\", \\\"body\\\" );' \" +
\"src='".$myProcessMaker->serverURL."/cases/ajaxListener?action=changeLogTab&idHistory=\" + historyGridListChangeLogGlobal.idHistory + \"&rand=$rand' >\" +
\"</iframe>\"
} ) ;
tabs.doLayout( ) ;
}
tabs.setActiveTab( 'changeLog' ) ;
}
else
if( actionToDo.search( '^historyDynaformGridPreview' ) == 0 ) {
actionToDo = actionToDo.replace('_', '$') ;
if( !tabs.items.containsKey( actionToDo ) ) {
var act = actionToDo.replace( '$', '&DYN_UID=') ;
tabs.add( {
title: ActionTabFrameGlobal.tabTitle,
id: actionToDo,
closable: true,
listeners: { activate: function () {
// debugger ;
onOtherFrameLoad( actionToDo, actionToDo+'Frame', 'form' ) ;
}
},
html: \"<iframe id='\"+actionToDo+\"Frame' \" +
\"style='border:none;' \" +
\"height='500px' \" +
\"width='100%' \" +
\"onload='onOtherFrameLoad( \\\"\"+actionToDo+\"\\\", \\\"\"+actionToDo+\"Frame\\\", \\\"form\\\" );' \" +
\"src='".$myProcessMaker->serverURL."/cases/casesHistoryDynaformPage_Ajax?actionAjax=\" + act + \"&rand=$rand' >\" +
\"</iframe>\"
} ) ;
tabs.doLayout( ) ;
}
tabs.setActiveTab( actionToDo ) ;
}
else
if( actionToDo.search( '^historyDynaformGridHistory' ) == 0) {
if( !tabs.items.containsKey( actionToDo ) ) {
var ajaxResponse = Ext.util.JSON.decode(ActionTabFrameGlobal.tabData);
var act = 'showDynaformListHistory&PRO_UID=' + ajaxResponse.PRO_UID + '&APP_UID=' + ajaxResponse.APP_UID + '&TAS_UID=-1&DYN_UID=' + ajaxResponse.DYN_UID;
tabs.add( {
title: ActionTabFrameGlobal.tabTitle,
id: actionToDo,
closable: true,
listeners: { activate: function () {
// debugger ;
onOtherFrameLoad( actionToDo, actionToDo+'Frame', 'body' ) ;
}
},
html: \"<iframe id='\"+actionToDo+\"Frame' \" +
\"style='border:none;' \" +
\"height='500px' \" +
\"width='100%' \" +
\"onload='onOtherFrameLoad( \\\"\"+actionToDo+\"\\\", \\\"\"+actionToDo+\"Frame\\\", \\\"body\\\" );' \" +
\"src='".$myProcessMaker->serverURL."/cases/casesHistoryDynaformPage_Ajax?actionAjax=\" + act + \"&rand=$rand' >\" +
\"</iframe>\"
} ) ;
tabs.doLayout( ) ;
}
tabs.setActiveTab( actionToDo ) ;
}
else
if( actionToDo.search( '^dynaformChangeLogViewHistory' ) == 0) {
var ajaxResponse = Ext.util.JSON.decode(ActionTabFrameGlobal.tabData);
actionToDo='dynaformChangeLogViewHistory' + ajaxResponse.dynUID + ajaxResponse.dynDate ;
if( !tabs.items.containsKey( actionToDo ) ) {
var act = 'dynaformChangeLogViewHistory&DYN_UID=' + ajaxResponse.dynUID + '&HISTORY_ID=' + ajaxResponse.tablename;
tabs.add( {
title: ajaxResponse.dynTitle + ' <sup>(' + ajaxResponse.dynDate + ')</sup>',
id: actionToDo,
closable: true,
listeners: { activate: function () {
// debugger ;
onOtherFrameLoad( actionToDo, actionToDo+'Frame', 'form' ) ;
}
},
html: \"<iframe id='\"+actionToDo+\"Frame' \" +
\"style='border:none;' \" +
\"height='500px' \" +
\"width='100%' \" +
\"onload='onOtherFrameLoad( \\\"\"+actionToDo+\"\\\", \\\"\"+actionToDo+\"Frame\\\", \\\"form\\\" );' \" +
\"src='".$myProcessMaker->serverURL."/cases/casesHistoryDynaformPage_Ajax?actionAjax=\" + act + \"&rand=$rand' >\" +
\"</iframe>\"
} ) ;
tabs.doLayout( ) ;
}
tabs.setActiveTab( actionToDo ) ;
}
}
} ;
//debugger;
var tabs = new Ext.TabPanel({
renderTo: 'processmakertabpanel',
width: 930,
deferredRender: false,
enableTabScroll: true,
items: [";
if( $pmCaseUser ) {
$first = true ;
foreach($caseInfo->currentUsers as $caseUser) {
if( !$first ) echo "," ;
echo "{
title: ".($caseUser->userId != $GLPICurrentPMUserId?"'<i><sub>Task: ".$caseUser->taskName."</sub></i>'":"'Task: ".$caseUser->taskName."'").",
id: 'task-".$caseUser->delIndex."',
listeners: { activate: function () {
try {
//debugger;
if( typeof onOtherFrameLoad == 'function' )
onOtherFrameLoad( 'task-".$caseUser->delIndex."', 'caseiframe-".$caseUser->delIndex."', 'table' ) ;
// to load users for re-assign only when task is not to be 'claimed'
if( ".($caseUser->userId?"true":"false")." && Ext.get('divUsers-".$caseUser->delIndex."').dom.innerHTML == '' ) {
Ext.get('divUsers-".$caseUser->delIndex."').load({
url : '".GLPI_ROOT."/plugins/processmaker/ajax/task_users.php',
scripts: true,
params: 'caseId=".$caseInfo->caseId."&itemId=".$item_id."&itemType=".$item_type."&userId=".$caseUser->userId."&taskId=".$caseUser->taskId."&delIndex=".$caseUser->delIndex."&delThread=".$caseUser->delThread."&rand=$rand',
});
}
} catch( evt ) {
//debugger;
}
}
} ,
html: \"<div class='tab_bg_2' id='divUsers-".$caseUser->delIndex."' >\" +
\"</div>\" +
\"<iframe id='caseiframe-".$caseUser->delIndex."' \" +
\"onload='onTaskFrameLoad( ".$caseUser->delIndex." );' \" +
\"style='border:none;' \" +
\"class='tab_bg_2' \" +
\"width='100%' \" +
\"src='".($caseUser->userId == $GLPICurrentPMUserId || $caseUser->userId == ''?
$myProcessMaker->serverURL."/cases/cases_open?sid=".$_SESSION["pluginprocessmaker"]["session"]["id"]."&APP_UID=".$caseInfo->caseId."&DEL_INDEX=".$caseUser->delIndex."&action=TO_DO"
:
GLPI_ROOT."/plugins/processmaker/ajax/task_resume.php?username=".urlencode( $caseUser->userName )."&taskname=".urlencode( $caseUser->taskName )."&url=".urlencode( $myProcessMaker->serverURL."/cases/cases_open?sid=".$_SESSION["pluginprocessmaker"]["session"]["id"]."&APP_UID=".$caseInfo->caseId."&DEL_INDEX=".$caseUser->delIndex."&action=TO_DO" )
)."&rand=$rand'>\" +
\"</iframe>\"
}";
$first = false ;
}
} else {
// no user means CANCELLED or COMPLETED
// then create artificial panel to host case infos
echo "{
title: '".$LANG['processmaker']['item']['case']['caseinfo']."',
id: 'caseInfo',
listeners: { activate: function () {
// debugger ;
if( typeof onOtherFrameLoad == 'function' )
onOtherFrameLoad( 'caseInfo', 'caseInfoFrame', 'body' ) ;
}
},
html: \"<iframe \" +
\"id='caseInfoFrame' \" +
\"style='border:none;' \" +
\"width='100%' \" +
\"onload='onOtherFrameLoad( \\\"caseInfo\\\", \\\"caseInfoFrame\\\", \\\"body\\\" );' \" +
\"src='".$myProcessMaker->serverURL."/cases/cases_open?sid=".$_SESSION["pluginprocessmaker"]["session"]["id"]."&APP_UID=".$caseInfo->caseId."&".$paramsURL."&action=TO_DO&rand=$rand'>\" +
\"</iframe>\"
}";
}
echo " ]
});";
if( $pmCaseUser )
echo " tabs.setActiveTab( 'task-".$pmCaseUser->delIndex."') ;" ;
else
echo " tabs.setActiveTab( 'caseInfo') ;" ;
echo "</script>";
//////echo "<iframe id='caseiframe' onload='onGLPILoadFrame( event ) ;' height='1080px' style='border:none;' width='100%' src='".$myProcessMaker->serverURL."/cases/open?sid=".$_SESSION["pluginprocessmaker"]["session"]["id"]."&APP_UID=".$caseInfo->caseId."&".$paramsURL."&rand=$rand' >" ;
//////echo "</iframe>";
echo "</td></tr>";
} else {
// no running case for this ticket
// propose to start one
echo "<tr><th colspan='4'>".$LANG['processmaker']['item']['nocase'] ;
// check if item is not solved nor closed
if( $item->fields['status'] != 'solved' && $item->fields['status'] != 'closed' && $_SESSION['glpiactiveprofile']['interface'] != 'helpdesk' ) {
// propose case start
echo "&nbsp;-&nbsp;".$LANG['processmaker']['item']['startone'];
echo "</th></tr>";
echo "<tr class='tab_bg_2'><td class='tab_bg_2' colspan='1'>";
echo $LANG['processmaker']['item']['selectprocess']."&nbsp;";
echo "<input type='hidden' name='action' value='newcase'>";
echo "<input type='hidden' name='id' value='$item_id'>";
echo "<input type='hidden' name='itemtype' value='$item_type'>";
// Dropdown::show('PluginProcessmakerProcessmaker', array( 'entity' => $item->fields['entities_id'], 'name' => 'plugin_processmaker_process_id', 'condition' => "is_active=1")); // condition is used to prevent start of none-active cases
PluginProcessmakerProcess::dropdown(array( 'entity' => $item->fields['entities_id'], 'name' => 'plugin_processmaker_process_id'));
echo "</td><td class='tab_bg_2'>";
echo "<input type='submit' name='additem' value='".$LANG['processmaker']['item']['start']."' class='submit'>";
echo "</td></tr>";
}
else echo "</th></tr>";
}
echo "</table>";
echo "</form>";
return true ;
}
/**
* Summary of deleteTasks
* will delete all tasks associated with this case from the item
* BEWARE that this will only be done when case is in DRAFT status
* @return true if tasks have been deleted from associated item and from case table
*/
private function deleteTasks( ) {
global $DB ;
$ret = false ;
if( isset($this->fields['case_status']) && $this->fields['case_status'] == "DRAFT" ) {
$query = "DELETE from glpi_".$this->fields['itemtype']."tasks where id in (select items_id from glpi_plugin_processmaker_tasks where case_id='".$this->fields['id']."')";
if( $DB->query( $query ) ) {
$query = "DELETE from glpi_plugin_processmaker_tasks where case_id='".$this->fields['id']."'";
if( $DB->query( $query ) )
$ret = true ;
}
}
return $ret ;
}
/**
* Summary of deleteCase
* will delete case and all tasks associated with this case from the item
* BEWARE that this will only be done when case is in DRAFT status
* @return true if case and tasks have been deleted from associated item and from case table
*/
function deleteCase( ) {
global $DB ;
$ret = false ;
if( isset($this->fields['case_status']) && $this->fields['case_status'] == "DRAFT" ) {
if( $this->deleteTasks() )
if( $this->deleteFromDB( ) )
$ret = true ;
}
return $ret ;
}
/**
* Summary of cancelTasks
* will mark as information all to_do tasks
* BEWARE that this will only be done when case is in TO_DO status
* @return true if tasks have been deleted from associated item and from case table
*/
private function cancelTasks( ) {
global $DB ;
$ret = false ;
if( isset($this->fields['case_status']) && $this->fields['case_status'] == "TO_DO" ) {
$query = "UPDATE glpi_".$this->fields['itemtype']."tasks SET state=0,users_id_tech=0,begin=NULL,end=NULL WHERE state=1 AND id in (select items_id from glpi_plugin_processmaker_tasks where case_id='".$this->fields['id']."')";
if( $DB->query( $query ) ) {
$ret = true ;
}
}
return $ret ;
}
/**
* Summary of cancelCase
* will cancel case and mark 'to_do' tasks associated with this case from the item as information
* BEWARE that this will only be done when case is in TO_DO status
* @return true if case and tasks have been cancelled or marked from associated item and from case table
*/
function cancelCase( ) {
global $DB ;
$ret = false ;
if( isset($this->fields['case_status']) && $this->fields['case_status'] == "TO_DO" )
if( $this->cancelTasks() )
if( $this->update( array( 'id' => $this->getID(), 'case_status' => 'CANCELLED' ) ) )
$ret=true;
return $ret ;
}
/**
* Summary of canSolve
* To know if a Ticket (Problem or Change) can be solved
* i.e. the case permits solving of item
* @param mixed $parm
* @return bool
*/
public static function canSolve ($parm) {
$myCase = new self;
if( $myCase->getCaseFromItemTypeAndItemId( $parm->getType(), $parm->getID() ) ) {
$pmVar = $myCase->getVariables( array( 'GLPI_ITEM_CAN_BE_SOLVED' ) ) ;
if( $myCase->fields['case_status'] != 'COMPLETED' && $myCase->fields['case_status'] != 'CANCELLED' && (!isset($pmVar['GLPI_ITEM_CAN_BE_SOLVED']) || $pmVar['GLPI_ITEM_CAN_BE_SOLVED'] != 1) ) {
// then item can't be solved
return false ;
}
}
return true ;
}
/**
* Summary of getToDoTasks
* @param mixed $parm is a Ticket, a Problem or a Change
* @return array list of tasks with status 'to do' for case associated with item
*/
public static function getToDoTasks($parm) {
$myCase = new self;
if( $myCase->getCaseFromItemTypeAndItemId( $parm->getType(), $parm->getID() ) ) {
return PluginProcessmakerTasks::getToDoTasks( $myCase->getID(), $parm->getType()."Task" ) ;
}
return array();
}
}

208
inc/config.class.php Normal file
View File

@@ -0,0 +1,208 @@
<?php
/**
*/
class PluginProcessmakerConfig extends CommonDBTM {
static private $_instance = NULL;
function canCreate() {
return Session::haveRight('config', 'w');
}
function canView() {
return Session::haveRight('config', 'r');
}
static function getTypeName() {
global $LANG;
return $LANG['common'][12];
}
function getName($with_comment=0) {
global $LANG;
return $LANG['processmaker']['title'][1];
}
/**
* Singleton for the unique config record
*/
static function getInstance() {
if (!isset(self::$_instance)) {
self::$_instance = new self();
if (!self::$_instance->getFromDB(1)) {
self::$_instance->getEmpty();
}
}
return self::$_instance;
}
//static function install(Migration $mig) {
// global $DB, $LANG;
// $table = 'glpi_plugin_behaviors_configs';
// if (!TableExists($table)) { //not installed
// $query = "CREATE TABLE `$table` (
// `id` int(11) NOT NULL,
// `use_requester_item_group` tinyint(1) NOT NULL default '0',
// `use_requester_user_group` tinyint(1) NOT NULL default '0',
// `is_ticketsolutiontype_mandatory` tinyint(1) NOT NULL default '0',
// `is_ticketrealtime_mandatory` tinyint(1) NOT NULL default '0',
// `is_requester_mandatory` tinyint(1) NOT NULL default '0',
// `is_ticketdate_locked` tinyint(1) NOT NULL default '0',
// `use_assign_user_group` tinyint(1) NOT NULL default '0',
// `tickets_id_format` VARCHAR(15) NULL,
// `remove_from_ocs` tinyint(1) NOT NULL default '0',
// `add_notif` tinyint(1) NOT NULL default '0',
// `use_lock` tinyint(1) NOT NULL default '0',
// `date_mod` datetime default NULL,
// `comment` text,
// PRIMARY KEY (`id`)
// ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
// $DB->query($query) or die($LANG['update'][90] . "&nbsp;:<br>" . $DB->error());
// $query = "INSERT INTO `$table` (id, date_mod) VALUES (1, NOW())";
// $DB->query($query) or die($LANG['update'][90] . "&nbsp;:<br>" . $DB->error());
// } else {
// // Upgrade
// $mig->addField($table, 'tickets_id_format', 'string');
// $mig->addField($table, 'remove_from_ocs', 'bool');
// $mig->addField($table, 'is_requester_mandatory', 'bool');
// // version 0.78.0 - feature #2801 Forbid change of ticket's creation date
// $mig->addField($table, 'is_ticketdate_locked', 'bool');
// // Version 0.80.0 - set_use_date_on_state now handle in GLPI
// $mig->dropField($table, 'set_use_date_on_state');
// // Version 0.80.4 - feature #3171 additional notifications
// $mig->addField($table, 'add_notif', 'bool');
// // Version 0.83.0 - groups now have is_requester and is_assign attribute
// $mig->dropField($table, 'sql_user_group_filter');
// $mig->dropField($table, 'sql_tech_group_filter');
// // Version 0.83.1 - prevent update on ticket updated by another user
// $mig->addField($table, 'use_lock', 'bool');
// }
// return true;
//}
//static function uninstall() {
// global $DB;
// if (TableExists('glpi_plugin_behaviors_configs')) { //not installed
// $query = "DROP TABLE `glpi_plugin_behaviors_configs`";
// $DB->query($query) or die($DB->error());
// }
// return true;
//}
static function showConfigForm($item) {
global $LANG, $DB;
$ui_theme = array(
'classic' => 'classic',
'neoclassic' => 'neoclassic',
'uxmodern' => 'uxmodern' ,
'uxs' => 'uxs'
);
$config = self::getInstance();
$config->showFormHeader();
echo "<tr class='tab_bg_1'>";
echo "<td>".$LANG['processmaker']['config']['name']."&nbsp;:</td><td>";
echo $config->fields['name'];
echo "</td><td colspan='2' class='center'>".$LANG['processmaker']['config']['comments']."&nbsp;:";
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>".$LANG['processmaker']['config']['URL']."&nbsp;:</td><td>";
echo "<input type='text' name='pm_server_URL' value='".$config->fields['pm_server_URL']."'>" ;
echo "</td><td rowspan='5' colspan='2' class='center'>";
echo "<textarea cols='60' rows='8' name='comment' >".$config->fields['comment']."</textarea>";
echo "<br>".$LANG['common'][26]."&nbsp;: ";
echo Html::convDateTime($config->fields["date_mod"]);
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>".$LANG['processmaker']['config']['workspace']."&nbsp;:</td><td>";
echo "<input type='text' name='pm_workspace' value='".$config->fields['pm_workspace']."'>" ;
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>".$LANG['processmaker']['config']['theme']."&nbsp;:</td><td>";
Dropdown::showFromArray('pm_theme', $ui_theme,
array('value' => $config->fields['pm_theme']));
echo "</td></tr>";
$taskCatogrie = new TaskCategory;
$taskCatogrie->getFromDB( $config->fields['taskcategories_id'] ) ;
echo "<tr class='tab_bg_1'>";
echo "<td>".$LANG['processmaker']['config']['main_task_category']."&nbsp;:</td><td>";
echo "<a href='".Toolbox::getItemTypeFormURL( 'TaskCategory' )."?id=". $config->fields['taskcategories_id']."'>".str_replace(" ", "&nbsp;", $taskCatogrie->fields['name']);
if ($_SESSION["glpiis_ids_visible"]) {
echo " (".$config->fields['taskcategories_id'].")";
}
echo "</a>" ;
echo "</td></tr>\n";
$taskUser = new User;
$taskUser->getFromDB( $config->fields['users_id'] ) ;
echo "<tr class='tab_bg_1'>";
echo "<td>".$LANG['processmaker']['config']['taskwriter']."&nbsp;:</td><td>";
echo "<a href='".Toolbox::getItemTypeFormURL( 'User' )."?id=". $config->fields['users_id']."'>".str_replace(" ", "&nbsp;", $taskUser->getName());
if ($_SESSION["glpiis_ids_visible"]) {
echo " (".$config->fields['users_id'].")";
}
echo "</a>" ;
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>".$LANG['processmaker']['config']['pm_group_name']."&nbsp;:</td><td>";
$query = "SELECT * FROM wf_".$config->fields['pm_workspace'].".content WHERE CON_CATEGORY='GRP_TITLE' and CON_ID='".$config->fields['pm_group_guid']."' ;" ;
echo "<table>";
foreach( $DB->request( $query ) as $row ) {
echo "<tr><td>".$row['CON_LANG']."</td><td>".$row['CON_VALUE']."</td>";
}
echo "</table>" ;
echo "</td></tr>\n";
$config->showFormButtons(array('candel'=>false));
return false;
}
function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
global $LANG;
if ($item->getType()=='Config') {
return $LANG['processmaker']['title'][1];
}
return '';
}
static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
if ($item->getType()=='Config') {
self::showConfigForm($item);
}
return true;
}
}

767
inc/process.class.php Normal file
View File

@@ -0,0 +1,767 @@
<?php
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* process short summary.
*
* process description.
*
* @version 1.0
* @author MoronO
*/
class PluginProcessmakerProcess extends CommonDBTM {
function canCreate() {
return plugin_processmaker_haveRight('process_config', 'w');
}
function canView() {
return plugin_processmaker_haveRight('process_config', 'r');
}
function maybeDeleted(){
return false ;
}
/**
* Summary of refreshTasks
* will refresh (re-synch) all process task list
*/
function refreshTasks( $post ) {
global $DB, $CFG_GLPI ;
if( $this->getFromDB( $post['id'] ) ) {
// here we are in the right process
// we need to get the tasks + content from PM db
$config = new PluginProcessmakerConfig ;
$config->getFromDB( 1 ) ;
$database = $config->fields['pm_workspace'] ;
if( TableExists( 'glpi_dropdowntranslations' ) && class_exists('DropdownTranslation') ){
// to force rigths to add translations
$_SESSION['glpi_dropdowntranslations']['TaskCategory']['name'] = 'name' ;
$_SESSION['glpi_dropdowntranslations']['TaskCategory']['completename'] = 'completename' ;
$_SESSION['glpi_dropdowntranslations']['TaskCategory']['comment'] = 'comment' ;
$translates = true ;
// create a reversed map for languages
foreach( $CFG_GLPI['languages'] as $key => $valArray){
$mapLangs[ locale_get_primary_language( $key ) ][] = $key ;
}
} else {
$translates = false ;
$mapLangs = array( ) ;
}
$lang = $CFG_GLPI['languages'][ $CFG_GLPI['language'] ][ 2 ] ;
$query = "select task.TAS_UID, task.TAS_START, content.CON_LANG, content.CON_CATEGORY, content.CON_VALUE from wf_$database.task
inner join wf_$database.content on content.CON_ID=task.TAS_UID
where task.PRO_UID = '".$this->fields['process_guid']."' and content.CON_CATEGORY in ('TAS_TITLE', 'TAS_DESCRIPTION') ".($translates?"":"and content.CON_LANG='$lang'")." ;" ;
$taskArray = array() ;
$defaultLangTaskArray=array();
foreach( $DB->request( $query ) as $task ) {
if( $task['CON_LANG'] == $lang ) {
$defaultLangTaskArray[ $task['TAS_UID'] ][ $task['CON_CATEGORY'] ] = $task['CON_VALUE'] ;
$defaultLangTaskArray[ $task['TAS_UID'] ]['start']=($task['TAS_START']=='TRUE'?true:false);
} else {
foreach( $mapLangs[ $task['CON_LANG'] ] as $valL ) {
$taskArray[ $task['TAS_UID'] ][ $valL ][ $task['CON_CATEGORY'] ] = $task['CON_VALUE'] ;
}
}
}
foreach( $defaultLangTaskArray as $taskGUID => $task ) {
$pmTaskCat = new PluginProcessmakerTaskCategory ;
$taskCat = new TaskCategory ;
if( $pmTaskCat->getFromDBbyExternalID( $taskGUID ) ){
// got it then check names, and if != update
if( $taskCat->getFromDB( $pmTaskCat->fields['taskcategories_id'] ) ) {
// found it must test if should be updated
if( $taskCat->fields['name'] != $task['TAS_TITLE'] || $taskCat->fields['comment'] != $task['TAS_DESCRIPTION'] ) {
$taskCat->update( array( 'id' => $taskCat->getID(), 'name' => $task['TAS_TITLE'], 'comment' => $task['TAS_DESCRIPTION'], 'taskcategories_id' => $this->fields['taskcategories_id'] ) ) ;
}
if( $pmTaskCat->fields['start'] != $task['start'] ) {
$pmTaskCat->update( array( 'id' => $pmTaskCat->getID(), 'start' => $task['start'] ) ) ;
}
} else {
// taskcat must be created
$taskCat->add( array( 'is_recursive' => true, 'name' => $task['TAS_TITLE'], 'comment' => $task['TAS_DESCRIPTION'], 'taskcategories_id' => $this->fields['taskcategories_id'] ) ) ;
// update pmTaskCat
$pmTaskCat->update( array( 'id' => $pmTaskCat->getID(), 'taskcategories_id' => $taskCat->getID(), 'start' => $task['start'] ) ) ;
}
} else {
// should create a new one
// taskcat must be created
$taskCat->add( array( 'is_recursive' => true, 'name' => $task['TAS_TITLE'], 'comment' => $task['TAS_DESCRIPTION'], 'taskcategories_id' => $this->fields['taskcategories_id'] ) ) ;
// pmTaskCat must be created too
$pmTaskCat->add( array( 'processes_id' => $this->getID(), 'pm_task_guid' => $taskGUID, 'taskcategories_id' => $taskCat->getID(), 'start' => $task['start'] ) ) ;
}
// here we should take into account translations if any
if( $translates && isset($taskArray[ $taskGUID ]) ) {
foreach( $taskArray[ $taskGUID ] as $langTask => $taskL ) {
// look for 'name' field
if( $loc_id = DropdownTranslation::getTranslationID( $taskCat->getID(), 'TaskCategory', 'name', $langTask ) ) {
if( DropdownTranslation::getTranslatedValue( $taskCat->getID(), 'TaskCategory', 'name', $langTask ) != $taskL[ 'TAS_TITLE' ] ) {
// must be updated
$trans = new DropdownTranslation ;
$trans->update( array( 'id' => $loc_id, 'field' => 'name', 'value' => $taskL[ 'TAS_TITLE' ], 'itemtype' => 'TaskCategory', 'items_id' => $taskCat->getID(), 'language' => $langTask ) ) ;
$trans->generateCompletename( array( 'itemtype' => 'TaskCategory', 'items_id' => $taskCat->getID(), 'language' => $langTask ) ) ;
}
} else {
// must be added
// must be updated
$trans = new DropdownTranslation ;
$trans->add( array( 'items_id' => $taskCat->getID(), 'itemtype' => 'TaskCategory', 'language' => $langTask, 'field' => 'name', 'value' => $taskL[ 'TAS_TITLE' ] ) ) ;
$trans->generateCompletename( array( 'itemtype' => 'TaskCategory', 'items_id' => $taskCat->getID(),'language' => $langTask ) ) ;
}
// look for 'comment' field
if( $loc_id = DropdownTranslation::getTranslationID( $taskCat->getID(), 'TaskCategory', 'comment', $langTask ) ) {
if( DropdownTranslation::getTranslatedValue( $taskCat->getID(), 'TaskCategory', 'comment', $langTask ) != $taskL[ 'TAS_DESCRIPTION' ] ) {
// must be updated
$trans = new DropdownTranslation ;
$trans->update( array( 'id' => $loc_id, 'field' => 'comment', 'value' => $taskL[ 'TAS_DESCRIPTION' ] , 'itemtype' => 'TaskCategory', 'items_id' => $taskCat->getID(), 'language' => $langTask) ) ;
}
} else {
// must be added
$trans = new DropdownTranslation ;
$trans->add( array( 'items_id' => $taskCat->getID(), 'itemtype' => 'TaskCategory', 'language' => $langTask, 'field' => 'comment', 'value' => $taskL[ 'TAS_DESCRIPTION' ] ) ) ;
}
}
}
}
//if( $translates ) {
// unset( $_SESSION['glpi_dropdowntranslations']['TaskCategory'] ) ;
//}
}
}
/**
* Summary of refresh
* used to refresh process list and task category list
*/
function refresh( ) {
// then refresh list of available process from PM to inner table
$pm = new PluginProcessmakerProcessmaker ;
$pm->login( true ) ;
$pmProcessList = $pm->processList() ;
$config = new PluginProcessmakerConfig ;
$config->getFromDB( 1 ) ;
$pmMainTaskCat = $config->fields['taskcategories_id'] ;
// and get processlist from GLPI
foreach( $pmProcessList as $process ) {
$glpiprocess = new PluginProcessmakerProcess ;
if( $glpiprocess->getFromDBbyExternalID($process->guid) ) {
// then update it only if name has changed
if( $glpiprocess->fields['name'] != $process->name ) {
$glpiprocess->update( array( 'id' => $glpiprocess->getID(), 'name' => $process->name ) ) ;
}
// and check if main task category needs update
if( !$glpiprocess->fields['taskcategories_id'] ) {
// then needs to be added
$glpiprocess->addTaskCategory( $pmMainTaskCat ) ;
} else {
$glpiprocess->updateTaskCategory( ) ;
}
} else {
// create it
if( $glpiprocess->add( array( 'process_guid' => $process->guid, 'name' => $process->name )) ){
// and add main task category for this process
$glpiprocess->addTaskCategory( $pmMainTaskCat ) ;
}
}
}
}
/**
* Summary of updateTaskCategory
* Updates TaskCategory for current process, only if needed (i.e. name has changed)
* returns true if update is done, false otherwise
*/
function updateTaskCategory( ) {
$taskCat = new TaskCategory ;
if( $taskCat->getFromDB( $this->fields['taskcategories_id'] ) && $taskCat->fields['name'] != $this->fields['name'] ) {
return $taskCat->update( array( 'id' => $taskCat->getID(), 'name' => $this->fields['name'] ) ) ;
}
return false ;
}
/**
* Summary of addTaskCategory
* Adds a new TaskCategory for $this process
* @param int $pmMainTaskCat is the main TaskCategory from PM configuration
* returns true if TaskCategory has been created and updated into $this process, else otherwise
*/
function addTaskCategory( $pmMainTaskCat ) {
$taskCat = new TaskCategory ;
if( $taskCat->add( array( 'is_recursive' => true, 'taskcategories_id' => $pmMainTaskCat, 'name' => $this->fields['name']) ) ) {
return $this->update( array( 'id' => $this->getID(), 'taskcategories_id' => $taskCat->getID() ) ) ;
}
return false ;
}
/**
* Print a good title for process pages
* add button for re-synchro of process list (only if rigths are w)
* @return nothing (display)
**/
function title() {
global $LANG, $CFG_GLPI;
$buttons = array();
$title = $LANG['processmaker']['config']['refreshprocesslist'];
if ($this->canCreate()) {
$buttons["process.php?refresh=1"] = $LANG['processmaker']['config']['refreshprocesslist'];
$title = "";
Html::displayTitle($CFG_GLPI["root_doc"] . "/plugins/processmaker/pics/gears.png", $LANG['processmaker']['config']['refreshprocesslist'], $title,
$buttons);
}
}
/**
* Retrieve a Process from the database using its external id (unique index): process_guid
*
* @param $extid string externalid
*
* @return true if succeed else false
**/
function getFromDBbyExternalID($extid) {
global $DB;
$query = "SELECT *
FROM `".$this->getTable()."`
WHERE `process_guid` = '$extid'";
if ($result = $DB->query($query)) {
if ($DB->numrows($result) != 1) {
return false;
}
$this->fields = $DB->fetch_assoc($result);
if (is_array($this->fields) && count($this->fields)) {
return true;
}
}
return false;
}
/**
* Summary of getSearchOptions
* @return mixed
*/
function getSearchOptions() {
global $LANG;
$tab = array();
$tab['common'] = $LANG['processmaker']['title'][1];
$tab[1]['table'] = 'glpi_plugin_processmaker_processes';
$tab[1]['field'] = 'name';
$tab[1]['name'] = $LANG['common'][16];
$tab[1]['datatype'] = 'itemlink';
$tab[1]['itemlink_type'] = $this->getType();
//$tab[7]['table'] = 'glpi_plugin_processmaker_processes';
//$tab[7]['field'] = 'is_helpdeskvisible';
//$tab[7]['name'] = $LANG['tracking'][39];
//$tab[7]['massiveaction'] = true;
//$tab[7]['datatype'] = 'bool';
$tab[8]['table'] = 'glpi_plugin_processmaker_processes';
$tab[8]['field'] = 'is_active';
$tab[8]['name'] = $LANG['common'][60];
$tab[8]['massiveaction'] = true;
$tab[8]['datatype'] = 'bool';
$tab[4]['table'] = 'glpi_plugin_processmaker_processes';
$tab[4]['field'] = 'comment';
$tab[4]['name'] = $LANG['common'][25];
$tab[4]['massiveaction'] = true;
$tab[4]['datatype'] = 'text';
$tab[9]['table'] = 'glpi_plugin_processmaker_processes';
$tab[9]['field'] = 'date_mod';
$tab[9]['name'] = $LANG['common'][26];
$tab[9]['massiveaction'] = false;
$tab[9]['datatype'] = 'datetime';
$tab[10]['table'] = 'glpi_plugin_processmaker_processes';
$tab[10]['field'] = 'process_guid';
$tab[10]['name'] = $LANG['processmaker']['process']['process_guid'];
$tab[10]['massiveaction'] = false;
$tab[10]['datatype'] = 'text';
return $tab;
}
static function getTypeName($nb=0) {
global $LANG;
if ($nb>1) {
return $LANG['processmaker']['title'][1];
}
return $LANG['processmaker']['title'][2];
}
function defineTabs($options=array()) {
$ong = array('empty' => $this->getTypeName(1));
$this->addStandardTab('PluginProcessmakerTaskCategory', $ong, $options);
$this->addStandardTab('PluginProcessmakerProcess_Profile', $ong, $options);
//$this->addStandardTab('Ticket', $ong, $options);
//$this->addStandardTab('Log', $ong, $options);
return $ong;
}
function showForm ($ID, $options=array('candel'=>false)) {
global $DB, $CFG_GLPI, $LANG;
if ($ID > 0) {
$this->check($ID,'r');
}
$canedit = $this->can($ID,'w');
$this->showTabs($options);
$this->showFormHeader($options);
echo "<tr class='tab_bg_1'>";
echo "<td>".$LANG["common"][16]."&nbsp;:</td><td>";
//Html::autocompletionTextField($this, "name");
echo $this->fields["name"];
echo "</td>";
echo "<td rowspan='5' class='middle right'>".$LANG["common"][25]."&nbsp;:</td>";
echo "<td class='center middle' rowspan='5'><textarea cols='45' rows='6' name='comment' >".
$this->fields["comment"]."</textarea></td></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td >".$LANG['processmaker']['process']['process_guid']."&nbsp;:</td><td>";
echo $this->fields["process_guid"];
echo "</td></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td >".$LANG['common'][60]."&nbsp;:</td><td>";
Dropdown::showYesNo("is_active",$this->fields["is_active"]);
echo "</td></tr>";
//echo "<tr class='tab_bg_1'>";
//echo "<td >".$LANG['tracking'][39]."&nbsp;:</td><td>";
//Dropdown::showYesNo("is_helpdeskvisible",$this->fields["is_helpdeskvisible"]);
//echo "</td></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td >".$LANG['processmaker']['process']['hide_case_num_title']."&nbsp;:</td><td>";
Dropdown::showYesNo("hide_case_num_title",$this->fields["hide_case_num_title"]);
echo "</td></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td >".$LANG['processmaker']['process']['insert_task_comment']."&nbsp;:</td><td>";
Dropdown::showYesNo("insert_task_comment",$this->fields["insert_task_comment"]);
echo "</td></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td >".$LANG['processmaker']['process']['type']."&nbsp;:</td><td>";
if (true) { // $canupdate || !$ID
$idticketcategorysearch = mt_rand(); $opt = array('value' => $this->fields["type"]);
$rand = $idtype = Ticket::dropdownType('type', $opt, array(),array('toupdate' => "search_".$idticketcategorysearch ));
$opt = array('value' => $this->fields["type"]);
$params = array('type' => '__VALUE__',
'entity_restrict' => $this->fields['entities_id'],
'value' => $this->fields['itilcategories_id'],
'currenttype' => $this->fields['type']);
Ajax::updateItemOnSelectEvent("dropdown_type$rand", "show_category_by_type",
$CFG_GLPI["root_doc"]."/ajax/dropdownTicketCategories.php",
$params);
} else {
echo Ticket::getTicketTypeName($this->fields["type"]);
}
echo "</td>";
echo "<td >".$LANG['processmaker']['process']['itilcategory']."&nbsp;:</td><td>";
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;
case Ticket::DEMAND_TYPE :
$opt['condition'] .= "`is_request`='1'";
break;
default :
break;
}
echo "<span id='show_category_by_type'>";
if( isset($idticketcategorysearch) ) $opt['rand'] = $idticketcategorysearch;
Dropdown::show('ITILCategory', $opt);
echo "</span>";
} else {
echo Dropdown::getDropdownName("glpi_itilcategories", $this->fields["itilcategories_id"]);
}
echo "</td></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td >".$LANG['common'][26]."&nbsp;:</td><td>";
echo Html::convDateTime($this->fields["date_mod"]);
echo "</td></tr>";
$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 $right limit user who have specific right
* @param $entity_restrict Restrict to a defined entity
* @param $value default value
* @param $used Already used items ID: not to display in dropdown
* @param $search pattern
*
* @return mysql result set.
**/
static function getSqlSearchResult ($count=true, $right="all", $entity_restrict=-1, $value=0,
$used=array(), $search='') {
global $DB, $CFG_GLPI;
$orderby = '' ;
$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( strlen($search)>0 && $search!=$CFG_GLPI["ajax_wildcard"] )
{
$where .= " AND (glpi_plugin_processmaker_processes.name LIKE '%$search%'
OR glpi_plugin_processmaker_processes.comment LIKE '%$search%') " ;
}
// LEFT JOIN glpi_plugin_processmaker_processes_profiles ON glpi_plugin_processmaker_processes_profiles.processes_id=glpi_plugin_processmaker_processes.id
$query = "SELECT $fields FROM glpi_plugin_processmaker_processes ".$where." ".$orderby.";" ;
//// No entity define : use active ones
//if ($entity_restrict < 0) {
// $entity_restrict = $_SESSION["glpiactiveentities"];
//}
//$joinprofile = false;
//switch ($right) {
// case "interface" :
// $where = " `glpi_profiles`.`interface` = 'central' ";
// $joinprofile = true;
// $where .= getEntitiesRestrictRequest("AND","glpi_profiles_users",'',$entity_restrict,1);
// break;
// case "id" :
// $where = " `glpi_users`.`id` = '".Session::getLoginUserID()."' ";
// break;
// case "delegate" :
// $groups = self::getDelegateGroupsForUser($entity_restrict);
// $users = array();
// if (count($groups)) {
// $query = "SELECT `glpi_users`.`id`
// FROM `glpi_groups_users`
// LEFT JOIN `glpi_users`
// ON (`glpi_users`.`id` = `glpi_groups_users`.`users_id`)
// WHERE `glpi_groups_users`.`groups_id` IN ('".implode("','",$groups)."')
// AND `glpi_groups_users`.`users_id` <> '".Session::getLoginUserID()."'";
// $result = $DB->query($query);
// if ($DB->numrows($result)) {
// while ($data=$DB->fetch_array($result)) {
// $users[$data["id"]] = $data["id"];
// }
// }
// }
// // Add me to users list for central
// if ($_SESSION['glpiactiveprofile']['interface'] == 'central') {
// $users[Session::getLoginUserID()] = Session::getLoginUserID();
// }
// if (count($users)) {
// $where = " `glpi_users`.`id` IN ('".implode("','",$users)."')";
// } else {
// $where = '0';
// }
// break;
// case "all" :
// $where = " `glpi_users`.`id` > '1' ".
// getEntitiesRestrictRequest("AND","glpi_profiles_users",'',$entity_restrict,1);
// break;
// default :
// $joinprofile = true;
// // Check read or active for rights
// $where = " (`glpi_profiles`.`".$right."` IN ('1', 'r', 'w') ".
// getEntitiesRestrictRequest("AND", "glpi_profiles_users", '',
// $entity_restrict, 1)." ";
// if (!in_array($right,Profile::$helpdesk_rights)) {
// $where .= " AND `glpi_profiles`.`interface` = 'central' ";
// }
// $where .= ')';
//}
//$where .= " AND `glpi_users`.`is_deleted` = '0'
// AND `glpi_users`.`is_active` = '1' ";
//if ((is_numeric($value) && $value)
// || count($used)) {
// $where .= " AND `glpi_users`.`id` NOT IN (";
// if (is_numeric($value)) {
// $first = false;
// $where .= $value;
// } else {
// $first = true;
// }
// foreach ($used as $val) {
// if ($first) {
// $first = false;
// } else {
// $where .= ",";
// }
// $where .= $val;
// }
// $where .= ")";
//}
//if ($count) {
// $query = "SELECT COUNT(DISTINCT `glpi_users`.`id` ) AS cpt
// FROM `glpi_users` ";
//} else {
// $query = "SELECT DISTINCT `glpi_users`.*
// FROM `glpi_users` ";
//}
//$query .= " LEFT JOIN `glpi_useremails`
// ON (`glpi_users`.`id` = `glpi_useremails`.`users_id`)";
//$query .= " LEFT JOIN `glpi_profiles_users`
// ON (`glpi_users`.`id` = `glpi_profiles_users`.`users_id`)";
//if ($joinprofile) {
// $query .= " LEFT JOIN `glpi_profiles`
// ON (`glpi_profiles`.`id` = `glpi_profiles_users`.`profiles_id`) ";
//}
//if ($count) {
// $query .= " WHERE $where ";
//} else {
// if (strlen($search)>0 && $search!=$CFG_GLPI["ajax_wildcard"]) {
// $where .= " AND (`glpi_users`.`name` ".Search::makeTextSearch($search)."
// OR `glpi_users`.`realname` ".Search::makeTextSearch($search)."
// OR `glpi_users`.`firstname` ".Search::makeTextSearch($search)."
// OR `glpi_users`.`phone` ".Search::makeTextSearch($search)."
// OR `glpi_useremails`.`email` ".Search::makeTextSearch($search)."
// OR CONCAT(`glpi_users`.`realname`,' ',`glpi_users`.`firstname`) ".
// Search::makeTextSearch($search).")";
// }
// $query .= " WHERE $where ";
// if ($_SESSION["glpinames_format"] == FIRSTNAME_BEFORE) {
// $query.=" ORDER BY `glpi_users`.`firstname`,
// `glpi_users`.`realname`,
// `glpi_users`.`name` ";
// } else {
// $query.=" ORDER BY `glpi_users`.`realname`,
// `glpi_users`.`firstname`,
// `glpi_users`.`name` ";
// }
// if ($search != $CFG_GLPI["ajax_wildcard"]) {
// $query .= " LIMIT 0,".$CFG_GLPI["dropdown_max"];
// }
//}
return $DB->query($query);
}
static function getProcessName( $pid, $link=0 ) {
global $DB, $LANG;
$process='';
if ($link==2) {
$process = array("name" => "",
"link" => "",
"comment" => "");
}
$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"] = $LANG['common'][16]."&nbsp;: ".$processname."<br>".$LANG["common"][25].
"&nbsp;: ".$data["comment"]."<br>";
} else {
$process = $processname ;
}
}
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`
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'];
}
}
return $entities;
}
/**
* Summary of dropdown
* @param mixed $options
* @return mixed
*/
static function dropdown($options=array()) {
global $DB, $CFG_GLPI, $LANG;
// Default values
$p['name'] = 'processes_id';
$p['value'] = '';
$p['right'] = 'id';
$p['all'] = 0;
$p['on_change'] = '';
$p['comments'] = 1;
$p['entity'] = -1;
$p['entity_sons'] = false;
$p['used'] = array();
$p['ldap_import'] = false;
$p['toupdate'] = '';
$p['rand'] = mt_rand();
if (is_array($options) && count($options)) {
foreach ($options as $key => $val) {
$p[$key] = $val;
}
}
// Make a select box with all glpi users
$use_ajax = false;
if ($CFG_GLPI["use_ajax"]) {
$res = self::getSqlSearchResult (true, $p['right'], $p['entity'], $p['value'], $p['used']);
$nb = ($res ? $DB->result($res,0,"cpt") : 0);
if ($nb > $CFG_GLPI["ajax_limit_count"]) {
$use_ajax = true;
}
}
$process = self::getProcessName($p['value'],2);
$default_display = "<select id='dropdown_".$p['name'].$p['rand']."' name='".$p['name']."'>";
$default_display .= "<option value='".$p['value']."'>";
$default_display .= Toolbox::substr($process["name"], 0, $_SESSION["glpidropdown_chars_limit"]);
$default_display .= "</option></select>";
//$view_users = (Session::haveRight("user", "r"));
//TODO: management of rights
$view_processes = true ;
$params = array('searchText' => '__VALUE__',
'value' => $p['value'],
'myname' => $p['name'],
'all' => $p['all'],
'right' => $p['right'],
'comment' => $p['comments'],
'rand' => $p['rand'],
'on_change' => $p['on_change'],
'entity_restrict' => $p['entity'],
'used' => $p['used'],
'update_item' => $p['toupdate'],);
if ($view_processes) {
$params['update_link'] = $view_processes;
}
$default = "";
if (!empty($p['value']) && $p['value']>0) {
$default = $default_display;
} else {
$default = "<select name='".$p['name']."' id='dropdown_".$p['name'].$p['rand']."'>";
if ($p['all']) {
$default.= "<option value='0'>[ ".$LANG['common'][66]." ]</option></select>";
} else {
$default.= "<option value='0'>".Dropdown::EMPTY_VALUE."</option></select>\n";
}
}
Ajax::dropdown($use_ajax, "/plugins/processmaker/ajax/dropdownProcesses.php", $params, $default, $p['rand']);
// Display comment
if ($p['comments']) {
if (!$view_processes) {
$process["link"] = '';
} else if (empty($process["link"])) {
$process["link"] = $CFG_GLPI['root_doc']."/plugins/processmaker/front/process.php";
}
Html::showToolTip($process["comment"],
array('contentid' => "comment_".$p['name'].$p['rand'],
'link' => $process["link"],
'linkid' => "comment_link_".$p["name"].$p['rand']));
}
return $p['rand'];
}
}

View File

@@ -0,0 +1,124 @@
<?php
/**
* process_profile short summary.
*
* process_profile description.
*
* @version 1.0
* @author MoronO
*/
class PluginProcessmakerProcess_Profile extends CommonDBTM
{
function can($ID, $right, &$input = NULL) {
return plugin_processmaker_haveRight('process_config', $right) ;
}
function getTabNameForItem( CommonGLPI $item, $withtemplate=0) {
global $LANG;
return $LANG['processmaker']['title'][4];
}
static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
global $DB,$CFG_GLPI, $LANG;
$ID = $item->getField('id');
$canshowentity = Session::haveRight("entity","r");
$canedit = plugin_processmaker_haveRight('process_config', 'w') ;
$rand=mt_rand();
echo "<form name='entityprocess_form$rand' id='entityprocess_form$rand' method='post' action='";
echo Toolbox::getItemTypeFormURL(__CLASS__)."'>";
if ($canedit) {
echo "<div class='firstbloc'>";
echo "<table class='tab_cadre_fixe'>";
echo "<tr class='tab_bg_1'><th colspan='4'>".$LANG['processmaker']['title'][4]."</tr>";
echo "<tr class='tab_bg_2'><td class='center'>";
echo "<input type='hidden' name='processes_id' value='$ID'>";
Dropdown::show('Entity', array('entity' => $_SESSION['glpiactiveentities']));
echo "</td><td class='center'>".$LANG['profiles'][22]."&nbsp;: ";
Profile::dropdownUnder(array('value' => Profile::getDefault()));
echo "</td><td class='center'>".$LANG['profiles'][28]."&nbsp;: ";
Dropdown::showYesNo("is_recursive",0);
echo "</td><td class='center'>";
echo "<input type='submit' name='add' value=\"".$LANG['buttons'][8]."\" class='submit'>";
echo "</td></tr>";
echo "</table></div>";
}
echo "<div class='spaced'><table class='tab_cadre_fixehov'>";
echo "<tr><th colspan='2'>".$LANG['Menu'][37]."</th>";
echo "<th>".$LANG['profiles'][22]." (D=".$LANG['profiles'][29].", R=".$LANG['profiles'][28].")";
echo "</th></tr>";
$query = "SELECT DISTINCT `glpi_plugin_processmaker_processes_profiles`.`id` AS linkID,
`glpi_profiles`.`id`,
`glpi_profiles`.`name`,
`glpi_plugin_processmaker_processes_profiles`.`is_recursive`,
`glpi_entities`.`completename`,
`glpi_plugin_processmaker_processes_profiles`.`entities_id`
FROM `glpi_plugin_processmaker_processes_profiles`
LEFT JOIN `glpi_profiles`
ON (`glpi_plugin_processmaker_processes_profiles`.`profiles_id` = `glpi_profiles`.`id`)
LEFT JOIN `glpi_entities`
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);
if ($DB->numrows($result) >0) {
while ($data = $DB->fetch_array($result)) {
echo "<tr class='tab_bg_1'>";
echo "<td width='10'>";
if ($canedit && in_array($data["entities_id"], $_SESSION['glpiactiveentities'])) {
echo "<input type='checkbox' name='item[".$data["linkID"]."]' value='1'>";
} else {
echo "&nbsp;";
}
echo "</td>";
if ($data["entities_id"] == 0) {
$data["completename"] = $LANG['entity'][2];
}
echo "<td>";
if ($canshowentity) {
echo "<a href='".Toolbox::getItemTypeFormURL('Entity')."?id=".$data["entities_id"]."'>";
}
echo $data["completename"].
($_SESSION["glpiis_ids_visible"]?" (".$data["entities_id"].")":"");
if ($canshowentity) {
echo "</a>";
}
echo "</td>";
echo "<td>".$data["name"];
if ($data["is_recursive"]) {
echo "<span class='b'>&nbsp;(";
echo "R";
echo ")</span>";
}
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
if ($canedit) {
Html::openArrowMassives("entityprocess_form$rand",true);
Html::closeArrowMassives(array('delete' => $LANG['buttons'][6]));
}
Html::closeForm();
echo "</div>";
}
}

1905
inc/processmaker.class.php Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,190 @@
<?php
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* This class manages the mail settings
*/
class ProcessmakerConfig extends CommonDBTM {
var $table = 'glpi_plugins_processmaker_config';
static function getTypeName() {
global $LANG;
return 'Process Maker Plugin Configuration';
}
function defineTabs($options=array()) {
$ong = array();
$this->addStandardTab(__CLASS__, $ong, $options);
return $ong;
}
function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
global $LANG, $CFG_GLPI;
switch ($item->getType()) {
case __CLASS__ :
$tabs[1] = $LANG['common'][12];
return $tabs;
}
return '';
}
static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
global $CFG_GLPI;
if($item->getType() == __CLASS__) {
switch ($tabnum) {
case 1 :
$item->showFormMailServerConfig();
break;
}
}
return true;
}
/**
* Print the mailing config form
*
* @param $ID integer ID of the item
* @param $options array
* - target filename : where to go when done.
* - tabs integer : ID of the tab to display
*
* @return Nothing (display)
*
**/
function showForm($ID, $options=array()) {
global $LANG, $CFG_GLPI;
if (!Session::haveRight("config", "w")) {
return false;
}
if (!$CFG_GLPI['use_mailing']) {
$options['colspan'] = 1;
}
$this->getFromDB($ID);
$this->showTabs($options);
$this->addDivForTabs();
return true;
}
function canCreate() {
return Session::haveRight('config', 'w');
}
function canView() {
return Session::haveRight('config', 'r');
}
//function showFormMailServerConfig() {
// global $LANG, $CFG_GLPI;
// echo "<form action='".Toolbox::getItemTypeFormURL(__CLASS__)."' method='post'>";
// echo "<div>";
// echo "<table class='tab_cadre_fixe'>";
// echo "<input type='hidden' name='id' value='1'>";
// echo "<tr class='tab_bg_1'><th colspan='4'>".$LANG['setup'][704]."</th></tr>";
// echo "<tr class='tab_bg_2'><td>" . $LANG['setup'][202] . "&nbsp;:</td><td>";
// Dropdown::showYesNo("use_mailing", $CFG_GLPI["use_mailing"]);
// echo "</td>";
// if ($CFG_GLPI['use_mailing']) {
// echo "<td >" . $LANG['setup'][227] . "&nbsp;:</td>";
// echo "<td><input type='text' name='url_base' size='40' value='".$CFG_GLPI["url_base"]."'>";
// echo "</td></tr>";
// echo "<tr class='tab_bg_2'>";
// echo "<td>" . $LANG['setup'][203] . "&nbsp;:</td>";
// echo "<td><input type='text' name='admin_email' size='40' value='".
// $CFG_GLPI["admin_email"]."'>";
// if (!NotificationMail::isUserAddressValid($CFG_GLPI["admin_email"])) {
// echo "<span class='red'>&nbsp;".$LANG['mailing'][110]."</span>";
// }
// echo "</td>";
// echo "<td >" . $LANG['setup'][208] . "&nbsp;:</td>";
// echo "<td><input type='text' name='admin_email_name' size='40' value='" .
// $CFG_GLPI["admin_email_name"] . "'>";
// echo " </td></tr>";
// echo "<tr class='tab_bg_2'>";
// echo "<td >" . $LANG['setup'][207] . "&nbsp;:</td>";
// echo "<td><input type='text' name='admin_reply' size='40' value='" .
// $CFG_GLPI["admin_reply"] . "'>";
// if (!NotificationMail::isUserAddressValid($CFG_GLPI["admin_reply"])) {
// echo "<span class='red'>&nbsp;".$LANG['mailing'][110]."</span>";
// }
// echo " </td>";
// echo "<td >" . $LANG['setup'][209] . "&nbsp;:</td>";
// echo "<td><input type='text' name='admin_reply_name' size='40' value='" .
// $CFG_GLPI["admin_reply_name"] . "'>";
// echo " </td></tr>";
// if (!function_exists('mail')) {
// echo "<tr class='tab_bg_2'><td class='center' colspan='2'>";
// echo "<span class='red'>" . $LANG['setup'][217] . "&nbsp;:</span>".
// $LANG['setup'][218] . "</td></tr>";
// }
// echo "<tr class='tab_bg_2'>";
// echo "<td>" . $LANG['setup'][204] . "&nbsp;:</td>";
// echo "<td colspan='3'><textarea cols='60' rows='3' name='mailing_signature'>".
// $CFG_GLPI["mailing_signature"]."</textarea></td></tr>";
// echo "<tr class='tab_bg_1'><th colspan='4'>".$LANG['setup'][660]."</th></tr>";
// echo "<tr class='tab_bg_2'><td>" . $LANG['setup'][231] . "&nbsp;:</td><td>";
// $mail_methods = array(MAIL_MAIL => $LANG['setup'][650],
// MAIL_SMTP => $LANG['setup'][651],
// MAIL_SMTPSSL => $LANG['setup'][652],
// MAIL_SMTPTLS => $LANG['setup'][653]);
// Dropdown::showFromArray("smtp_mode", $mail_methods,
// array('value' => $CFG_GLPI["smtp_mode"]));
// echo "</td><td colspan='2' class='center'>&nbsp;";
// echo "</td></tr>";
// echo "<tr class='tab_bg_2'><td >" . $LANG['setup'][232] . "&nbsp;:</td>";
// echo "<td><input type='text' name='smtp_host' size='40' value='".$CFG_GLPI["smtp_host"]."'>";
// echo "</td>";
// echo "<td >" . $LANG['setup'][234] . "&nbsp;:</td>";
// echo "<td><input type='text' name='smtp_username' size='40' value='" .
// $CFG_GLPI["smtp_username"] . "'></td></tr>";
// echo "<tr class='tab_bg_2'><td >" . $LANG['setup'][175] . "&nbsp;:</td>";
// echo "<td><input type='text' name='smtp_port' size='5' value='".$CFG_GLPI["smtp_port"]."'>";
// echo "</td>";
// echo "<td >" . $LANG['setup'][235] . "&nbsp;:</td>";
// echo "<td><input type='password' name='smtp_passwd' size='40' value='' autocomplete='off'>";
// echo "<br><input type='checkbox' name='_blank_smtp_passwd'>&nbsp;".$LANG['setup'][284];
// echo "</td></tr>";
// } else {
// echo "<td colspan='2'></td></tr>";
// }
// $options['candel'] = false;
// $options['addbuttons'] = array('test_smtp_send' => $LANG['setup'][229]);
// $this->showFormButtons($options);
//}
}
?>

143
inc/profile.class.php Normal file
View File

@@ -0,0 +1,143 @@
<?php
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
class PluginProcessmakerProfile extends CommonDBTM {
//if profile deleted
static function cleanProfiles(Profile $prof) {
$plugprof = new self();
$plugprof->delete(array('id' => $prof->getID()));
}
static function select() {
$prof = new self();
if ($prof->getFromDBByProfile($_SESSION['glpiactiveprofile']['id'])) {
$_SESSION["glpi_plugin_processmaker_profile"] = $prof->fields;
} else {
unset($_SESSION["glpi_plugin_processmaker_profile"]);
}
}
//profiles modification
function showForm($ID, $options=array()) {
global $LANG;
$target = $this->getFormURL();
if (isset($options['target'])) {
$target = $options['target'];
}
if (!Session::haveRight("profile","r")) {
return false;
}
$canedit = Session::haveRight("profile", "w");
$prof = new Profile();
if ($ID) {
$this->getFromDBByProfile($ID);
$prof->getFromDB($ID);
}
echo "<form action='".$target."' method='post'>";
echo "<table class='tab_cadre_fixe'>";
echo "<tr><th colspan='2'>".$LANG['processmaker']['profile']['rightmgt']." : ".$prof->fields["name"].
"</th></tr>";
echo "<tr class='tab_bg_2'>";
echo "<td>".$LANG['processmaker']['profile']['process_config']." :</td><td>";
if ($prof->fields['interface']!='helpdesk') {
Profile::dropdownNoneReadWrite("process_config", $this->fields["process_config"], 1, 1, 1);
} else {
echo $LANG['profiles'][12]; // No access;
}
echo "</td></tr>";
if ($canedit) {
echo "<tr class='tab_bg_1'>";
echo "<td class='center' colspan='2'>";
echo "<input type='hidden' name='id' value=".$this->getID().">";
echo "<input type='submit' name='update_user_profile' value=\"".$LANG['buttons'][7]."\"
class='submit'>";
echo "</td></tr>";
}
echo "</table>";
Html::closeForm();
}
function getFromDBByProfile($profiles_id) {
global $DB;
$query = "SELECT * FROM `".$this->getTable()."`
WHERE `profiles_id` = '" . $profiles_id . "' ";
if ($result = $DB->query($query)) {
if ($DB->numrows($result) != 1) {
return false;
}
$this->fields = $DB->fetch_assoc($result);
if (is_array($this->fields) && count($this->fields)) {
return true;
} else {
return false;
}
}
return false;
}
static function createAdminAccess($ID) {
$myProf = new self();
if (!$myProf->getFromDBByProfile($ID)) {
$myProf->add(array(
'profiles_id' => $ID,
'process_config' => 'w'
));
}
}
function createUserAccess($Profile) {
return $this->add(array('profiles_id' => $Profile->getID()
));
}
function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
global $LANG;
if ($item->getType()=='Profile') {
return $LANG['processmaker']['title'][1];
}
return '';
}
static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
global $CFG_GLPI;
if ($item->getType()=='Profile') {
$ID = $item->getID();
$prof = new self();
if ($prof->getFromDBByProfile($ID) || $prof->createUserAccess($item)) {
$prof->showForm($ID);
}
}
return true;
}
}
?>

116
inc/taskcategory.class.php Normal file
View File

@@ -0,0 +1,116 @@
<?php
/**
* PluginProcessmakerTaskCategory short summary.
*
* PluginProcessmakerTaskCategory description.
*
* @version 1.0
* @author MoronO
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
class PluginProcessmakerTaskCategory extends CommonDBTM
{
function getTabNameForItem( CommonGLPI $item, $withtemplate=0) {
global $LANG;
return $LANG['processmaker']['title'][3];
}
static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
global $LANG, $DB ;
self::title($item) ;
echo "<div class='center'><br><table class='tab_cadre_fixehov'>";
echo "<tr><th colspan='5'>".$LANG['processmaker']['title'][3]."</th></tr>";
echo "<tr><th>".$LANG['processmaker']['process']['taskcategories']['name']."</th>".
"<th>".$LANG['processmaker']['process']['taskcategories']['completename']."</th>" .
"<th>".$LANG['processmaker']['process']['taskcategories']['guid']."</th>" .
"<th>".$LANG['processmaker']['process']['taskcategories']['start']."</th>" .
"<th>".$LANG['processmaker']['process']['taskcategories']['comment']."</th></tr>";
$query = "select pm.pm_task_guid, pm.taskcategories_id, pm.`start`, gl.name, gl.completename, gl.`comment` from glpi_plugin_processmaker_taskcategories as pm
left join glpi_taskcategories as gl on pm.taskcategories_id=gl.id
where pm.processes_id=".$item->getID().";" ;
foreach ($DB->request($query) as $taskCat) {
echo "<tr class='tab_bg_1'><td class='b'><a href='".
Toolbox::getItemTypeFormURL( 'TaskCategory' )."?id=".
$taskCat['taskcategories_id']."'>".str_replace(" ", "&nbsp;", $taskCat['name']);
if ($_SESSION["glpiis_ids_visible"]) {
echo " (".$taskCat['taskcategories_id'].")";
}
echo "</a></td><td >".str_replace(" ", "&nbsp;", $taskCat['completename'])."</td>
<td >".$taskCat['pm_task_guid']."</td>".
"<td>".($taskCat['start']?'x':'')."</td><td >".
$taskCat['comment']."</td></tr>";
}
echo "</table></div>";
return true;
}
/**
* Print a good title for task categories tab
* add button for re-synchro of taskcategory list (only if rigths are w)
* @return nothing (display)
**/
static function title(CommonGLPI $item) {
global $LANG, $CFG_GLPI;
$buttons = array();
$title = $LANG['processmaker']['config']['refreshtasklist'];
if (plugin_processmaker_haveRight('process_config', 'w')) {
$buttons["process.form.php?refreshtask=1&id=".$item->getID()] = $LANG['processmaker']['config']['refreshtasklist'];
$title = "";
Html::displayTitle($CFG_GLPI["root_doc"] . "/plugins/processmaker/pics/gears.png", $LANG['processmaker']['config']['refreshtasklist'], $title,
$buttons);
}
}
function getLinkItemFromExternalID($extId) {
if( $this->getFromDBbyExternalID( $extId ) ) {
$taskcat = new TaskCategory ;
return $taskcat->getFromDB( $this->fields['items_id'] ) ;
}
}
/**
* Retrieve a TaskCat from the database using its external id (unique index): pm_task_guid
*
* @param $extid string externalid
*
* @return true if succeed else false
**/
function getFromDBbyExternalID($extid) {
global $DB;
$query = "SELECT *
FROM `".$this->getTable()."`
WHERE `pm_task_guid` = '$extid'";
if ($result = $DB->query($query)) {
if ($DB->numrows($result) != 1) {
return false;
}
$this->fields = $DB->fetch_assoc($result);
if (is_array($this->fields) && count($this->fields)) {
return true;
}
}
return false;
}
}

68
inc/tasks.class.php Normal file
View File

@@ -0,0 +1,68 @@
<?php
/**
* tasks short summary.
*
* tasks description.
*
* @version 1.0
* @author MoronO
*/
class PluginProcessmakerTasks extends CommonITILTask
{
private $itemtype ;
function __construct($itemtype) {
parent::__construct();
$this->itemtype=$itemtype;
}
/**
* Summary of getFromDB
* @param mixed $items_id
* @param mixed $itemtype
* @return bool
*/
function getFromDB($items_id) {
global $DB ;
$query = "SELECT * FROM ".self::getTable()." WHERE itemtype='".$this->itemtype."' AND items_id=$items_id;" ;
$ret = $DB->query( $query ) ;
if( $ret && $DB->numrows( $ret ) == 1 ) {
$row = $DB->fetch_assoc( $ret ) ;
$task = new $this->itemtype;
if( $task->getFromDB( $row['items_id'] ) ) {
// then we should add our own fields
unset( $row['id'] ) ;
unset( $row['items_id'] ) ;
unset( $row['itemtype'] ) ;
foreach( $row as $field => $val) {
$task->fields[ $field ] = $val ;
}
$this->fields = $task->fields ;
return true ;
}
}
return false ;
}
/**
* Summary of getToDoTasks
* returns all 'to do' tasks associated with this case
* @param mixed $case_id
*/
public static function getToDoTasks( $case_id, $itemtype ) {
global $DB ;
$ret = array();
$selfTable = getTableForItemType( __CLASS__) ;
$itemTypeTaskTable = getTableForItemType( $itemtype );
$query = "SELECT glpi_tickettasks.id as taskID from $itemTypeTaskTable
INNER JOIN $selfTable on $selfTable.items_id=$itemTypeTaskTable.id
WHERE $itemTypeTaskTable.state=1 and $selfTable.case_id='$case_id';";
foreach($DB->request($query) as $row){
$ret[$row['taskID']]=$row['taskID'];
}
return $ret ;
}
}

409
inc/users.class.php Normal file
View File

@@ -0,0 +1,409 @@
<?php
/**
* user short summary.
*
* user description.
*
* @version 1.0
* @author MoronO
*/
class PluginProcessmakerUsers extends CommonDBTM {
///**
// * Execute the query to select box with all PM users where select key = name
// *
// * Internaly used by showGroup_Users, dropdownUsers and ajax/dropdownUsers.php
// *
// * @param $taskId id of the PM task
// * @param $count true if execute an count(*),
// * @param $value default value
// * @param $used Already used items ID: not to display in dropdown
// * @param $search pattern
// *
// * @return mysql result set.
// **/
//static function getSqlSearchResult ($taskId, $count=true, $value=0,
// $used=array(), $search='') {
// global $DB, $CFG_GLPI;
// $where = " TAS_UID = '$taskId' " ;
// $where .= " AND `glpi_users`.`is_deleted` = '0'
// AND `glpi_users`.`is_active` = '1' ";
// if ((is_numeric($value) && $value)
// || count($used)) {
// $where .= " AND `glpi_users`.`id` NOT IN (";
// if (is_numeric($value)) {
// $first = false;
// $where .= $value;
// } else {
// $first = true;
// }
// foreach ($used as $val) {
// if ($first) {
// $first = false;
// } else {
// $where .= ",";
// }
// $where .= $val;
// }
// $where .= ")";
// }
// if ($count) {
// $query = "SELECT COUNT(DISTINCT glpi_users.id ) AS cpt ";
// } else {
// $query = "SELECT DISTINCT glpi_users.* ";
// }
// $query .= "from wf_workflow.task_user
// join wf_workflow.group_user on wf_workflow.group_user.GRP_UID=wf_workflow.task_user.USR_UID and wf_workflow.task_user.TU_RELATION = 2 and wf_workflow.task_user.TU_TYPE=1
// join glpi_plugin_processmaker_users on glpi_plugin_processmaker_users.pm_users_id=wf_workflow.group_user.USR_UID
// join glpi_users on glpi_users.id=glpi_plugin_processmaker_users.glpi_users_id " ;
// $query .= " LEFT JOIN `glpi_useremails`
// ON (`glpi_users`.`id` = `glpi_useremails`.`users_id`)";
// if ($count) {
// $query .= " WHERE $where ";
// } else {
// if (strlen($search)>0 && $search!=$CFG_GLPI["ajax_wildcard"]) {
// $where .= " AND (`glpi_users`.`name` ".Search::makeTextSearch($search)."
// OR `glpi_users`.`realname` ".Search::makeTextSearch($search)."
// OR `glpi_users`.`firstname` ".Search::makeTextSearch($search)."
// OR `glpi_users`.`phone` ".Search::makeTextSearch($search)."
// OR `glpi_useremails`.`email` ".Search::makeTextSearch($search)."
// OR CONCAT(`glpi_users`.`realname`,' ',`glpi_users`.`firstname`) ".
// Search::makeTextSearch($search).")";
// }
// $query .= " WHERE $where ";
// if ($_SESSION["glpinames_format"] == FIRSTNAME_BEFORE) {
// $query.=" ORDER BY `glpi_users`.`firstname`,
// `glpi_users`.`realname`,
// `glpi_users`.`name` ";
// } else {
// $query.=" ORDER BY `glpi_users`.`realname`,
// `glpi_users`.`firstname`,
// `glpi_users`.`name` ";
// }
// if ($search != $CFG_GLPI["ajax_wildcard"]) {
// $query .= " LIMIT 0,".$CFG_GLPI["dropdown_max"];
// }
// }
// return $DB->query($query);
//}
/**
* 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 $right limit user who have specific right
* @param $entity_restrict Restrict to a defined entity
* @param $value default value
* @param $used Already used items ID: not to display in dropdown
* @param $search pattern
*
* @return mysql result set.
**/
static function getSqlSearchResult ($taskId, $count=true, $right="all", $entity_restrict=-1, $value=0,
$used=array(), $search='') {
global $DB, $CFG_GLPI;
// No entity define : use active ones
if ($entity_restrict < 0) {
$entity_restrict = $_SESSION["glpiactiveentities"];
}
$joinprofile = false;
switch ($right) {
case "interface" :
$where = " `glpi_profiles`.`interface` = 'central' ";
$joinprofile = true;
$where .= getEntitiesRestrictRequest("AND","glpi_profiles_users",'',$entity_restrict,1);
break;
case "id" :
$where = " `glpi_users`.`id` = '".Session::getLoginUserID()."' ";
break;
case "delegate" :
$groups = self::getDelegateGroupsForUser($entity_restrict);
$users = array();
if (count($groups)) {
$query = "SELECT `glpi_users`.`id`
FROM `glpi_groups_users`
LEFT JOIN `glpi_users`
ON (`glpi_users`.`id` = `glpi_groups_users`.`users_id`)
WHERE `glpi_groups_users`.`groups_id` IN ('".implode("','",$groups)."')
AND `glpi_groups_users`.`users_id` <> '".Session::getLoginUserID()."'";
$result = $DB->query($query);
if ($DB->numrows($result)) {
while ($data=$DB->fetch_array($result)) {
$users[$data["id"]] = $data["id"];
}
}
}
// Add me to users list for central
if ($_SESSION['glpiactiveprofile']['interface'] == 'central') {
$users[Session::getLoginUserID()] = Session::getLoginUserID();
}
if (count($users)) {
$where = " `glpi_users`.`id` IN ('".implode("','",$users)."')";
} else {
$where = '0';
}
break;
case "all" :
$where = " `glpi_users`.`id` > '1' ".
getEntitiesRestrictRequest("AND","glpi_profiles_users",'',$entity_restrict,1);
break;
default :
$joinprofile = true;
// Check read or active for rights
$where = " (`glpi_profiles`.`".$right."` IN ('1', 'r', 'w') ".
getEntitiesRestrictRequest("AND", "glpi_profiles_users", '',
$entity_restrict, 1)." ";
if (!in_array($right,Profile::$helpdesk_rights)) {
$where .= " AND `glpi_profiles`.`interface` = 'central' ";
}
$where .= ')';
}
$where .= " AND TAS_UID = '$taskId' " ;
$where .= " AND `glpi_users`.`is_deleted` = '0'
AND `glpi_users`.`is_active` = '1' ";
if ((is_numeric($value) && $value)
|| count($used)) {
$where .= " AND `glpi_users`.`id` NOT IN (";
if (is_numeric($value)) {
$first = false;
$where .= $value;
} else {
$first = true;
}
foreach ($used as $val) {
if ($first) {
$first = false;
} else {
$where .= ",";
}
$where .= $val;
}
$where .= ")";
}
if ($count) {
$query = "SELECT COUNT(DISTINCT glpi_users.id ) AS cpt ";
} else {
$query = "SELECT DISTINCT glpi_users.* ";
}
$query .= "from wf_workflow.task_user
join wf_workflow.group_user on wf_workflow.group_user.GRP_UID=wf_workflow.task_user.USR_UID and wf_workflow.task_user.TU_RELATION = 2 and wf_workflow.task_user.TU_TYPE=1
join glpi_plugin_processmaker_users on glpi_plugin_processmaker_users.pm_users_id=wf_workflow.group_user.USR_UID
join glpi_users on glpi_users.id=glpi_plugin_processmaker_users.glpi_users_id " ;
$query .= " LEFT JOIN `glpi_useremails`
ON (`glpi_users`.`id` = `glpi_useremails`.`users_id`)";
$query .= " LEFT JOIN `glpi_profiles_users`
ON (`glpi_users`.`id` = `glpi_profiles_users`.`users_id`)";
if ($joinprofile) {
$query .= " LEFT JOIN `glpi_profiles`
ON (`glpi_profiles`.`id` = `glpi_profiles_users`.`profiles_id`) ";
}
if ($count) {
$query .= " WHERE $where ";
} else {
if (strlen($search)>0 && $search!=$CFG_GLPI["ajax_wildcard"]) {
$where .= " AND (`glpi_users`.`name` ".Search::makeTextSearch($search)."
OR `glpi_users`.`realname` ".Search::makeTextSearch($search)."
OR `glpi_users`.`firstname` ".Search::makeTextSearch($search)."
OR `glpi_users`.`phone` ".Search::makeTextSearch($search)."
OR `glpi_useremails`.`email` ".Search::makeTextSearch($search)."
OR CONCAT(`glpi_users`.`realname`,' ',`glpi_users`.`firstname`) ".
Search::makeTextSearch($search).")";
}
$query .= " WHERE $where ";
if ($_SESSION["glpinames_format"] == FIRSTNAME_BEFORE) {
$query.=" ORDER BY `glpi_users`.`firstname`,
`glpi_users`.`realname`,
`glpi_users`.`name` ";
} else {
$query.=" ORDER BY `glpi_users`.`realname`,
`glpi_users`.`firstname`,
`glpi_users`.`name` ";
}
if ($search != $CFG_GLPI["ajax_wildcard"]) {
$query .= " LIMIT 0,".$CFG_GLPI["dropdown_max"];
}
}
return $DB->query($query);
}
/**
* Make a select box with all glpi users where select key = name
*
* Parameters which could be used in options array :
* - name : string / name of the select (default is users_id)
* - right : string / limit user who have specific right :
* id -> only current user (default case);
* interface -> central ;
* all -> all users ;
* specific right like show_all_ticket, create_ticket....
* - comments : boolean / is the comments displayed near the dropdown (default true)
* - entity : integer or array / restrict to a defined entity or array of entities
* (default -1 : no restriction)
* - entity_sons : boolean / if entity restrict specified auto select its sons
* only available if entity is a single value not an array(default false)
* - all : Nobody or All display for none selected
* all=0 (default) -> Nobody
* all=1 -> All
* all=-1-> nothing
* - rand : integer / already computed rand value
* - toupdate : array / Update a specific item on select change on dropdown
* (need value_fieldname, to_update, url (see Ajax::updateItemOnSelectEvent for informations)
* and may have moreparams)
* - used : array / Already used items ID: not to display in dropdown (default empty)
* - on_change : string / value to transmit to "onChange"
*
* @param $options possible options
*
* @return nothing (print out an HTML select box)
**/
static function dropdown($options=array()) {
global $DB, $CFG_GLPI, $LANG;
// Default values
$p['name'] = 'users_id';
$p['value'] = '';
$p['right'] = 'id';
$p['all'] = 0;
$p['on_change'] = '';
$p['comments'] = 1;
$p['entity'] = -1;
$p['entity_sons'] = false;
$p['used'] = array();
$p['ldap_import'] = false;
$p['toupdate'] = '';
$p['rand'] = mt_rand();
$p['pmTaskId'] = 0 ;
if (is_array($options) && count($options)) {
foreach ($options as $key => $val) {
$p[$key] = $val;
}
}
if (!($p['entity']<0) && $p['entity_sons']) {
if (is_array($p['entity'])) {
echo "entity_sons options is not available with array of entity";
} else {
$p['entity'] = getSonsOf('glpi_entities',$p['entity']);
}
}
// Make a select box with all glpi users
$use_ajax = false;
if ($CFG_GLPI["use_ajax"]) {
$res = self::getSqlSearchResult ($p['pmTaskId'], true, $p['right'], $p['entity'], $p['value'], $p['used']);
//$res = self::getSqlSearchResult ($taskId, true, $p['value'], $p['used']);
$nb = ($res ? $DB->result($res,0,"cpt") : 0);
if ($nb > $CFG_GLPI["ajax_limit_count"]) {
$use_ajax = true;
}
}
$user = getUserName($p['value'],2);
$default_display = "<select id='dropdown_".$p['name'].$p['rand']."' name='".$p['name']."'>";
$default_display .= "<option value='".$p['value']."'>";
$default_display .= Toolbox::substr($user["name"], 0, $_SESSION["glpidropdown_chars_limit"]);
$default_display .= "</option></select>";
$view_users = (Session::haveRight("user", "r"));
$params = array('searchText' => '__VALUE__',
'value' => $p['value'],
'myname' => $p['name'],
'all' => $p['all'],
'right' => $p['right'],
'comment' => $p['comments'],
'rand' => $p['rand'],
'on_change' => $p['on_change'],
'entity_restrict' => $p['entity'],
'used' => $p['used'],
'update_item' => $p['toupdate'],
'pmTaskId' => $p['pmTaskId']);
if ($view_users) {
$params['update_link'] = $view_users;
}
$default = "";
if (!empty($p['value']) && $p['value']>0) {
$default = $default_display;
} else {
$default = "<select name='".$p['name']."' id='dropdown_".$p['name'].$p['rand']."'>";
if ($p['all']) {
$default.= "<option value='0'>[ ".$LANG['common'][66]." ]</option></select>";
} else {
$default.= "<option value='0'>".Dropdown::EMPTY_VALUE."</option></select>\n";
}
}
Ajax::dropdown($use_ajax, "/plugins/processmaker/ajax/dropdownUsers.php", $params, $default, $p['rand']);
// Display comment
if ($p['comments']) {
if (!$view_users) {
$user["link"] = '';
} else if (empty($user["link"])) {
$user["link"] = $CFG_GLPI['root_doc']."/front/user.php";
}
Html::showToolTip($user["comment"],
array('contentid' => "comment_".$p['name'].$p['rand'],
'link' => $user["link"],
'linkid' => "comment_link_".$p["name"].$p['rand']));
}
if (Session::haveRight('import_externalauth_users','w')
&& $p['ldap_import']
&& EntityData::isEntityDirectoryConfigured($_SESSION['glpiactive_entity'])) {
echo "<img alt='' title=\"".$LANG['ldap'][35]."\" src='".$CFG_GLPI["root_doc"].
"/pics/add_dropdown.png' style='cursor:pointer; margin-left:2px;'
onClick=\"var w = window.open('".$CFG_GLPI['root_doc'].
"/front/popup.php?popup=add_ldapuser&amp;rand=".$p['rand']."&amp;entity=".
$_SESSION['glpiactive_entity']."' ,'glpipopup', 'height=400, ".
"width=1000, top=100, left=100, scrollbars=yes' );w.focus();\">";
}
return $p['rand'];
}
}

93
js/cases.helpdesk.js Normal file
View File

@@ -0,0 +1,93 @@

var oldHandler ;
var submitButton ;
function onClickContinue( obj ) {
// call old handler
if (obj != undefined && oldHandler)
oldHandler(obj.target);
submitButton.click() ;
}
// used to find an element in a list and to hide it!
function bGLPIHideElement(eltList, attribute, value) {
var ret = false;
for (var i = 0; i < eltList.length; i++) {
var node = eltList[i];
if (node.getAttribute(attribute) == value) {
// hide the link
node.style.display = 'none';
ret = true;
}
}
return ret;
}
function onLoadFrame( evt, caseId, delIndex, caseNumber, processName ) {
var caseTimerCounter = 0;
var redimIFrame = false;
//var bAreaUseRequestSumUp = false;
var bButtonContinue = false;
var caseTimer = window.setInterval(function () {
//debugger ;
// look for frmDerivation form
caseIFrame = document.getElementById('caseiframe');
if (caseIFrame != undefined && caseIFrame.contentDocument != undefined) {
var contentDocument = caseIFrame.contentDocument;
var buttonContinue = contentDocument.getElementById('form[btnGLPISendRequest]');
var txtAreaUseRequestSumUp = contentDocument.getElementById('form[UserRequestSumUp]');
var linkList = contentDocument.getElementsByTagName('a');
if (txtAreaUseRequestSumUp != undefined) { // !bAreaUseRequestSumUp &&
//bAreaUseRequestSumUp = true; // to prevent multiple adds
Ext.select("textarea[name='content']").elements[0].value = txtAreaUseRequestSumUp.value;
} else
Ext.select("textarea[name='content']").elements[0].value = '_';
if (!bButtonContinue && buttonContinue != undefined && linkList != undefined && linkList.length > 0) {
bButtonContinue = true; //window.clearInterval(caseTimer); // to be sure that it will be done only one time
// change action for the attached form and add some parameters
//debugger;
bGLPIHideElement(linkList, 'href', 'cases_Step?TYPE=ASSIGN_TASK&UID=-1&POSITION=10000&ACTION=ASSIGN');
//buttonContinue.form.action = null; //'';
//if (buttonContinue.addEventListener)
// buttonContinue.addEventListener("click", onClickContinue, false);
//else
// buttonContinue.attachEvent("onclick", onClickContinue);
oldHandler = buttonContinue.onclick;
buttonContinue.onclick = onClickContinue;
submitButton = Ext.select("input[name='add'][type=submit]").elements[0];
submitButton.insertAdjacentHTML('beforebegin', "<input type='hidden' name='processmaker_action' value='routecase'/>");
submitButton.insertAdjacentHTML('beforebegin', "<input type='hidden' name='processmaker_caseid' value='" + caseId + "'/>");
submitButton.insertAdjacentHTML('beforebegin', "<input type='hidden' name='processmaker_delindex' value='" + delIndex + "'/>");
submitButton.insertAdjacentHTML('beforebegin', "<input type='hidden' name='processmaker_casenum' value='" + caseNumber + "'/>");
Ext.select("input[name='name'][type=text]").elements[0].value = processName;
}
// try to redim caseIFrame
if (!redimIFrame) {
var locElt = contentDocument.getElementsByTagName("form")[0];
var newHeight = (locElt.clientHeight < 100 ? 100 : locElt.clientHeight) + locElt.offsetParent.offsetTop + 10 ;
caseIFrame.height = newHeight;
redimIFrame = true;
}
}
if( caseTimerCounter > 3000 )
window.clearInterval(caseTimer) ;
else
caseTimerCounter = caseTimerCounter + 1;
},
10) ;
}

192
js/cases.js Normal file
View File

@@ -0,0 +1,192 @@
//debugger;
// To manage submits to cases.front.php
var loc_split = window.location.href.split('/');
var GLPI_HTTP_CASE_FORM = window.location.href.split('/', loc_split.length-2 ).join('/') + '/plugins/processmaker/front/cases.front.php'; // http://hostname/glpi/...
// to manage reloads
var GLPI_RELOAD_PARENT = window; //.location;
var GLPI_DURING_RELOAD = false;
// used to find an element in a list and to hide it!
function bGLPIHideElement(eltList, attribute, value) {
var ret = false;
for (var i = 0; i < eltList.length && !ret; i++) {
var node = eltList[i];
if (node.getAttribute(attribute) == value) {
// hide the link
node.style.display = 'none';
ret = true;
}
}
return ret;
}
function showMask(elt) {
if( !elt.defaultPrevented ) {
Ext.getBody().moveTo(0, 0);
var myMask = new Ext.LoadMask(Ext.getBody(), { removeMask: false });
myMask.show();
}
};
function onTaskFrameLoad(delIndex) {
//alert("Loaded frame " + delIndex);
var taskFrameId = "caseiframe-" + delIndex;
var bShowHideNextStep = false ; // not done yet!
var bHideClaimCancelButton = false; // To manage 'Claim' button
var taskFrameTimerCounter = 0;
var redimIFrame = false;
var taskFrameTimer = window.setInterval(function () {
try {
var locContentDocument;
var taskFrame = document.getElementById(taskFrameId);
if (taskFrame != undefined && taskFrame.contentDocument != undefined) {
// here we've caught the content of the iframe
// then look if btnGLPISendRequest exists,
locContentDocument = taskFrame.contentDocument;
var locElt = locContentDocument.getElementById('form[btnGLPISendRequest]');
if (!bShowHideNextStep && locElt != undefined ) {
var linkList = locContentDocument.getElementsByTagName('a');
if (bGLPIHideElement(linkList, 'href', 'cases_Step?TYPE=ASSIGN_TASK&UID=-1&POSITION=10000&ACTION=ASSIGN')) {
// the next step link is hidden
// if yes then change the link behind the button itself
locElt.type = 'submit';
locElt.onclick = null; // in order to force use of the action of form POST
var formList = locContentDocument.getElementsByTagName('form');
// if yes then change the action of the form POST
var node = formList[0]; // must have one element in list: in a dynaform there is one and only one HTML form
var action = node.action.split('?');
node.action = GLPI_HTTP_CASE_FORM + '?' + action[1] + '&DEL_INDEX=' + delIndex;
// try to add showMask function to submit event
//locElt.addEventListener( 'click', showMask ); // it is not good if a validation error occurs
node.addEventListener('submit', showMask, true);
} else {
// then hide the button itself
locElt.style.display = 'none';
}
bShowHideNextStep = true;
}
// Hide 'Cancel' button on 'Claim' form
var cancelButton = locContentDocument.getElementById('form[BTN_CANCEL]');
if (cancelButton != undefined && !bHideClaimCancelButton) {
cancelButton.style.display = 'none';
// to manage Claim
var formList = locContentDocument.getElementsByTagName('form');
var node = formList[0]; // must have one element in list: in a dynaform there is one and only one HTML form
var action = node.action.split('?');
node.action = GLPI_HTTP_CASE_FORM + '?' + action[1] + '&DEL_INDEX=' + delIndex;
bHideClaimCancelButton = true;
node.addEventListener('submit', showMask);
}
// to force immediat reload of GLPI item form
var forcedReload = locContentDocument.getElementById('GLPI_FORCE_RELOAD');
if (forcedReload != undefined && !GLPI_DURING_RELOAD) {
//showMask();
GLPI_DURING_RELOAD = true; // to prevent double reload
window.clearInterval(taskFrameTimer); // stop timer
GLPI_RELOAD_PARENT.location.reload();
}
// try to redim caseIFrame
if (!redimIFrame) {
var locElt = locContentDocument.getElementsByTagName("table")[0];
var newHeight = (locElt.clientHeight < 400 ? 400 : locElt.clientHeight) + locElt.offsetParent.offsetTop ;
//locElt.clientHeight = newHeight; // don't know if this is neccessary!!! --> bugs on IE8
tabs.getItem('task-' + delIndex).setHeight(newHeight);
taskFrame.height = newHeight ;
redimIFrame = true;
}
}
taskFrameTimerCounter = taskFrameTimerCounter + 1;
if (taskFrameTimerCounter > 3000 || bShowHideNextStep || bHideClaimCancelButton) // either timeout or hiding is done
window.clearInterval(taskFrameTimer);
} catch (evt) {
// nothing to do here for the moment
}
}, 10);
}
function clearClass(lociFrame) {
var otherFrameTimerCounter = 0;
var otherFrameTimer = window.setInterval(function () {
try {
var locElt = lociFrame.contentDocument.getElementsByTagName('body')[0];
if (locElt != undefined && locElt.className != '') {
//debugger;
locElt.className = '';
window.clearInterval(otherFrameTimer);
} else {
otherFrameTimerCounter = otherFrameTimerCounter + 1;
if (otherFrameTimerCounter > 3000 )
window.clearInterval(otherFrameTimer);
}
} catch (ev) {
}
}, 10);
}
function onOtherFrameLoad(tabPanelName, frameName, eltTagName) {
var otherFrameId = frameName; //tabPanelName ; //+ 'Frame';
var otherFrameTimerCounter = 0;
var redimIFrame = false;
//debugger;
var otherFrameTimer = window.setInterval(function () {
try {
var locContentDocument;
var otherFrame = document.getElementById(otherFrameId);
if (otherFrame != undefined && otherFrame.contentDocument != undefined) {
// here we've caught the content of the iframe
clearClass(otherFrame);
locContentDocument = otherFrame.contentDocument;
// try to redim otherFrame
// and tabPanel
if (!redimIFrame) {
var locElt = locContentDocument.getElementsByTagName(eltTagName)[0];
if (locElt != undefined) {
var newHeight ;
if (locElt.offsetParent)
newHeight = (locElt.clientHeight < 400 ? 400 : locElt.clientHeight) + locElt.offsetParent.offsetTop ;
else
newHeight = (locElt.clientHeight < 400 ? 400 : locElt.clientHeight) ;
if (locElt.scrollHeight && locElt.scrollHeight > newHeight )
newHeight = locElt.scrollHeight ;
tabs.getItem(tabPanelName).setHeight(newHeight);
otherFrame.height = newHeight;
redimIFrame = true;
}
}
}
otherFrameTimerCounter = otherFrameTimerCounter + 1;
if (otherFrameTimerCounter > 3000 || redimIFrame)
window.clearInterval(otherFrameTimer);
} catch (ev) {
// nothing to do here for the moment
}
}, 10);
}

63
js/helpdesk.public.js.php Normal file
View File

@@ -0,0 +1,63 @@
<?php
// Direct access to file
if (strpos($_SERVER['PHP_SELF'],"processmaker/js/helpdesk.public.js.php")) {
$AJAX_INCLUDE = 1;
define('GLPI_ROOT','../../..');
include (GLPI_ROOT."/inc/includes.php");
header("Content-type: application/javascript");
Html::header_nocache();
}
if (!defined('GLPI_ROOT')) {
die("Can not access directly to this file");
}
echo "Ext.onReady(function () {
function showMask(){Ext.getBody().moveTo( 0, 0); var myMask = new Ext.LoadMask(Ext.getBody(), {removeMask:false}); myMask.show();};
// look if name='helpdeskform' is present. If yes replace the form.location
var ahrefTI = '".$CFG_GLPI["root_doc"]."/plugins/processmaker/front/tracking.injector.php';
var formLink = Ext.select(\"form[name='helpdeskform']\").elements[0];
if (formLink != undefined) {
formLink.action = ahrefTI;
}
var ticketType = Ext.select(\"select[name='type']\").elements[0];
if (ticketType != undefined) {
ticketType.addEventListener( 'change', showMask );
}
var ticketCat = Ext.select(\"select[name='itilcategories_id']\").elements[0];
if (ticketCat!= undefined) {
ticketCat.addEventListener( 'change', showMask );
}
});
"; // end of echo
//Ext.onReady(function () {
// var ahref = "../plugins/processmaker/front/processmaker.helpdesk.form.php";
// var markup = '';
// // look for menu id = menu2 to insert a new menu
// var createTicketMenu = Ext.get('menu2');
// if (createTicketMenu != undefined) {
// markup = '<li id="menu2"><a href="' + ahref + '" class="itemP" title="Create User ticket">Create User ticket</a></li>';
// Ext.DomHelper.insertAfter(createTicketMenu, markup)
// }
// // look for 'Create a ticket' in order to insert a link <a>
// var ticketLink = Ext.select('table.tab_cadrehov tbody tr th a').elements[0];
// if (ticketLink != undefined) {
// var img = Ext.select('table.tab_cadrehov tbody tr th a img').elements[0];
// // add a link to the user management screen
// markup = '&nbsp;<a href="' + ahref + '">User Management Ticket<img src="' + img.attributes["src"].value + '"></a>';
// Ext.DomHelper.insertAfter(ticketLink, markup)
// //window.clearInterval(ticketTimer)
// }
//});
?>

92
locales/en_GB.php Normal file
View File

@@ -0,0 +1,92 @@
<?php
$LANG['processmaker']['title'][1]="Process Maker";
$LANG['processmaker']['title'][2]="Process";
$LANG['processmaker']['title'][3]="Task List";
$LANG['processmaker']['title'][4]="Authorizations";
$LANG['processmaker']['profile']['rightmgt']="Rights Management";
$LANG['processmaker']['profile']['process_config']="Process configuration";
$LANG['processmaker']['process']['process_guid']="Process GUID";
$LANG['processmaker']['process']['hide_case_num_title']="Hide case number and title in task descriptions";
$LANG['processmaker']['process']['insert_task_comment']="Insert Task Category comments in Task Description";
$LANG['processmaker']['process']['type']="Type (helpdesk)";
$LANG['processmaker']['process']['itilcategory']="ITIL Category (helpdesk)";
$LANG['processmaker']['process']['taskcategories']['guid']="Task GUID";
$LANG['processmaker']['process']['taskcategories']['name']="Task name";
$LANG['processmaker']['process']['taskcategories']['completename']="Complete name";
$LANG['processmaker']['process']['taskcategories']['start']="Start";
$LANG['processmaker']['process']['taskcategories']['comment']="Comment";
$LANG['processmaker']['config']['name']="Name";
$LANG['processmaker']['config']['URL']="Process Maker Server URL";
$LANG['processmaker']['config']['workspace']="Workspace Name";
$LANG['processmaker']['config']['theme']="Theme Name";
$LANG['processmaker']['config']['comments']="Comments";
$LANG['processmaker']['config']['refreshprocesslist']="Synchronize Process List";
$LANG['processmaker']['config']['refreshtasklist']="Synchronize Task List";
$LANG['processmaker']['config']['main_task_category']="Main Task Category (edit to change name)";
$LANG['processmaker']['config']['taskwriter']="Task Writer (edit to change name)";
$LANG['processmaker']['config']['pm_group_name']="Group in Process Maker which contains all GLPI users (lang : name)";
$LANG['processmaker']['item']['tab']="Process - Case";
$LANG['processmaker']['item']['cancelledcase']="Status: Cancelled";
$LANG['processmaker']['item']['pausedtask']="Status: Task is paused - unpause it?";
$LANG['processmaker']['item']['completedcase']="Status: Completed";
$LANG['processmaker']['item']['nocase']="No case for this item!";
$LANG['processmaker']['item']['startone']="Start one?";
$LANG['processmaker']['item']['selectprocess']="Select the process you want to start:";
$LANG['processmaker']['item']['start']="Start";
$LANG['processmaker']['item']['unpause']="Unpause";
$LANG['processmaker']['item']['deletecase']="Delete case?" ;
$LANG['processmaker']['item']['buttondeletecase']="Delete" ;
$LANG['processmaker']['item']['reassigncase']="Re-assign task to:";
$LANG['processmaker']['item']['buttonreassigncase']="Re-assign";
$LANG['processmaker']['item']['cancelcase']="Cancel case?" ;
$LANG['processmaker']['item']['buttoncancelcase']="Cancel" ;
$LANG['processmaker']['item']['buttondeletecaseconfirmation']="Delete this case?" ;
$LANG['processmaker']['item']['buttoncancelcaseconfirmation']="Cancel this case?" ;
$LANG['processmaker']['item']['case']['deleted']="Case has been deleted!";
$LANG['processmaker']['item']['case']['errordeleted']="Unable to delete case!";
$LANG['processmaker']['item']['case']['cancelled']="Case has been cancelled!";
$LANG['processmaker']['item']['case']['errorcancelled']="Unable to cancel case!";
$LANG['processmaker']['item']['case']['notreassigned']="Error re-assigning task: ";
$LANG['processmaker']['item']['case']['assignedtoyou']="Task already assigned to this person!";
$LANG['processmaker']['item']['case']['reassigned']="Task re-assigned!";
$LANG['processmaker']['item']['case']['casemap']="Case map";
$LANG['processmaker']['item']['case']['casehistory']='Case History' ;
$LANG['processmaker']['item']['case']['dynaforms']='Dynaforms';
$LANG['processmaker']['item']['case']['changelog']='Change Log';
$LANG['processmaker']['item']['case']['caseinfo']='Case info';
$LANG['processmaker']['item']['case']['viewcasemap']='View Case Map';
$LANG['processmaker']['item']['case']['viewcasehistory']='View Case History';
$LANG['processmaker']['item']['case']['viewdynaforms']='View Dynaforms';
$LANG['processmaker']['item']['error'][11]="Error creating case!";
$LANG['processmaker']['item']['error'][14]="Can't create case: no rights for it!";
$LANG['processmaker']['item']['preventsolution'][1]="A 'Case' is running!";
$LANG['processmaker']['item']['preventsolution'][2]="You must manage it first (see 'Process - Case' tab)!";
$LANG['processmaker']['item']['task']['process']="Bound to process: ";
$LANG['processmaker']['item']['task']['case']="Case title: ";
$LANG['processmaker']['item']['task']['task']="Task: ";
$LANG['processmaker']['item']['task']['comment']="##processmaker.taskcomment##" ;
$LANG['processmaker']['item']['task']['manage']="##ticket.url##_PluginProcessmakerCases\$processmakercases" ; //"Go to: ##ticket.url##_PluginProcessmakerCases\$processmakercases" ;
$LANG['processmaker']['item']['task']['manage_text']= "" ; //"Process - Case tab";
$LANG['processmaker']['case']['statuses']['TO_DO'] = "Processing";
$LANG['processmaker']['case']['statuses']['CANCELLED'] = "Cancelled";
$LANG['processmaker']['case']['statuses']['DRAFT'] = "New";
$LANG['processmaker']['case']['statuses']['COMPLETED'] = "Closed";
$LANG['processmaker']['search']['case']="Case";
$LANG['processmaker']['search']['status']="Status";
$LANG['processmaker']['search']['processtitle']="Process Title";
$LANG['processmaker']['search']['casetitle']="Case Title";
$LANG['processmaker']['search']['hascase']="Running Case?";
$LANG['processmaker']['cron']['pmusers']="Syncs GLPI users and pseudo-groups into ProcessMaker." ;
$LANG['processmaker']['cron']['pmnotifications']="Notifications for GLPI Tasks bound to ProcessMaker Tasks." ;

92
locales/fr_FR.php Normal file
View File

@@ -0,0 +1,92 @@
<?php
$LANG['processmaker']['title'][1]="Process Maker";
$LANG['processmaker']['title'][2]="Processus";
$LANG['processmaker']['title'][3]="Liste des tâches";
$LANG['processmaker']['title'][4]="Autorisations";
$LANG['processmaker']['profile']['rightmgt']="Gestion des droits";
$LANG['processmaker']['profile']['process_config']="Configuration des Processus";
$LANG['processmaker']['process']['process_guid']="GUID du Processus";
$LANG['processmaker']['process']['taskcategories']['guid']="GUID de la Tâche";
$LANG['processmaker']['process']['hide_case_num_title']="Masquer numéro et titre des Cas dans les descriptions des tâches";
$LANG['processmaker']['process']['insert_task_comment']="Insérer les commentaires des Catégories de Tâches dans les descriptions des Tâches";
$LANG['processmaker']['process']['type']="Type (helpdesk)";
$LANG['processmaker']['process']['itilcategory']="Catégorie ITIL (helpdesk)";
$LANG['processmaker']['process']['taskcategories']['name']="Nom de la Tâche";
$LANG['processmaker']['process']['taskcategories']['completename']="Nom complet";
$LANG['processmaker']['process']['taskcategories']['start']="Début";
$LANG['processmaker']['process']['taskcategories']['comment']="Commentaire";
$LANG['processmaker']['config']['name']="Nom";
$LANG['processmaker']['config']['URL']="URL du serveur Process Maker";
$LANG['processmaker']['config']['workspace']="Nom du Workspace";
$LANG['processmaker']['config']['theme']="Nom du Theme";
$LANG['processmaker']['config']['comments']="Commentaires";
$LANG['processmaker']['config']['refreshprocesslist']="Synchroniser la liste des Processus";
$LANG['processmaker']['config']['refreshtasklist']="Synchroniser la liste des Tâches";
$LANG['processmaker']['config']['main_task_category']="Categorie principale des tâches (editer pour changer le nom)";
$LANG['processmaker']['config']['taskwriter']="Auteur des Tâches (editer pour changer le nom)";
$LANG['processmaker']['config']['pm_group_name']="Groupe dans Process Maker des utilisateurs de GLPI (les contient tous)";
$LANG['processmaker']['item']['tab']="Processus - Cas";
$LANG['processmaker']['item']['cancelledcase']="Statut : Annulé";
$LANG['processmaker']['item']['pausedtask']="Statut : Tâche en pause - la relancer ?";
$LANG['processmaker']['item']['completedcase']="Statut : Terminé";
$LANG['processmaker']['item']['nocase']="Pas de cas en cours pour cet item!";
$LANG['processmaker']['item']['startone']="Démarrer un nouveau cas ?";
$LANG['processmaker']['item']['selectprocess']="Choisir le processus à démarrer :";
$LANG['processmaker']['item']['start']="Démarrer";
$LANG['processmaker']['item']['unpause']="Relancer";
$LANG['processmaker']['item']['deletecase']="Effacer cas ?" ;
$LANG['processmaker']['item']['buttondeletecase']="Effacer" ;
$LANG['processmaker']['item']['reassigncase']="Ré-affecter tâche à :";
$LANG['processmaker']['item']['buttonreassigncase']="Ré-affecter";
$LANG['processmaker']['item']['cancelcase']="Annuler cas ?" ;
$LANG['processmaker']['item']['buttoncancelcase']="Annuler" ;
$LANG['processmaker']['item']['buttondeletecaseconfirmation']="Effacer ce cas ?" ;
$LANG['processmaker']['item']['buttoncancelcaseconfirmation']="Annuler ce cas ?" ;
$LANG['processmaker']['item']['case']['deleted']="Le cas a été effacé !";
$LANG['processmaker']['item']['case']['errordeleted']="Impossible d'effacer le cas !";
$LANG['processmaker']['item']['case']['cancelled']="Le cas a été annulé !";
$LANG['processmaker']['item']['case']['errorcancelled']="Impossible d'annuler le cas !";
$LANG['processmaker']['item']['case']['notreassigned']="Impossible de re-assigner cette tâche : ";
$LANG['processmaker']['item']['case']['assignedtoyou']="Tâche déjà assignée à cette personne !";
$LANG['processmaker']['item']['case']['reassigned']="Tâche ré-assignée !";
$LANG['processmaker']['item']['case']['casemap']="Carte du cas";
$LANG['processmaker']['item']['case']['casehistory']='Historique du cas' ;
$LANG['processmaker']['item']['case']['dynaforms']='Dynaforms';
$LANG['processmaker']['item']['case']['changelog']='Historique des modifications';
$LANG['processmaker']['item']['case']['caseinfo']='Infos du cas';
$LANG['processmaker']['item']['case']['viewcasemap']='Voir carte du cas';
$LANG['processmaker']['item']['case']['viewcasehistory']='Voir historique du cas';
$LANG['processmaker']['item']['case']['viewdynaforms']='Voir dynaforms';
$LANG['processmaker']['item']['error'][11]="Erreur à la création du cas !";
$LANG['processmaker']['item']['error'][14]="Impossible de créer le cas : pas de droits pour cela !";
$LANG['processmaker']['item']['preventsolution'][1]="Un 'Cas' est en cours !";
$LANG['processmaker']['item']['preventsolution'][2]="Vous devez d'abord le terminer (voir onglet 'Processus - Cas') !";
$LANG['processmaker']['item']['task']['process']="Lié au processus : ";
$LANG['processmaker']['item']['task']['case']="Titre du cas : ";
$LANG['processmaker']['item']['task']['task']="Tâche : ";
$LANG['processmaker']['item']['task']['comment']="##processmaker.taskcomment##" ;
$LANG['processmaker']['item']['task']['manage']="##ticket.url##_PluginProcessmakerCases\$processmakercases" ;; //"Allez à : ##ticket.url##_PluginProcessmakerCases\$processmakercases" ;
$LANG['processmaker']['item']['task']['manage_text']=""; //"l'onglet Processus - Cas";
$LANG['processmaker']['case']['statuses']['TO_DO'] = "En cours";
$LANG['processmaker']['case']['statuses']['CANCELLED'] = "Annulé";
$LANG['processmaker']['case']['statuses']['DRAFT'] = "Nouveau";
$LANG['processmaker']['case']['statuses']['COMPLETED'] = "Achevé";
$LANG['processmaker']['search']['case']="Cas";
$LANG['processmaker']['search']['status']="Statut";
$LANG['processmaker']['search']['processtitle']="Nom du processus";
$LANG['processmaker']['search']['casetitle']="Titre du cas";
$LANG['processmaker']['search']['hascase']="Cas en cours ?";
$LANG['processmaker']['cron']['pmusers']="Synchro des utilisateurs GLPI et des pseudo-groups avec ProcessMaker." ;
$LANG['processmaker']['cron']['pmnotifications']="Notifications des tâches GLPI liées à des tâches de ProcessMaker." ;

BIN
pics/gears.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

170
setup.php Normal file
View File

@@ -0,0 +1,170 @@
<?php
// Init the hooks of the plugins -Needed
function plugin_init_processmaker() {
global $PLUGIN_HOOKS;
Plugin::registerClass('PluginProcessmakerProcessmaker');//, array(
// 'notificationtemplates_types' => true,
// 'addtabon' => array('Ticket')));
Plugin::registerClass('PluginProcessmakerCases', array(
'notificationtemplates_types' => true,
'addtabon' => array('Ticket')));
Plugin::registerClass('PluginProcessmakerTaskCategory');
if (Session::haveRight('config','w')) {
Plugin::registerClass('PluginProcessmakerConfig', array('addtabon' => 'Config'));
$PLUGIN_HOOKS['config_page']['processmaker'] = 'front/config.form.php';
}
Plugin::registerClass('PluginProcessmakerProfile',
array('addtabon' => 'Profile'));
$PLUGIN_HOOKS['change_profile']['processmaker'] = array('PluginProcessmakerProfile','select');
Plugin::registerClass('PluginProcessmakerProcess_Profile');
$PLUGIN_HOOKS['csrf_compliant']['processmaker'] = true;
// tabs management
//$PLUGIN_HOOKS['headings']['processmaker'] = 'plugin_get_headings_processmaker';
//$PLUGIN_HOOKS['headings_action']['processmaker'] = 'plugin_headings_actions_processmaker';
$PLUGIN_HOOKS['canedit']['processmaker']
= array('TicketTask' => array('PluginProcessmakerProcessmaker',
'canedit_item_processmakertickettask'));
$PLUGIN_HOOKS['pre_show_item']['processmaker']
= array('Ticket' => array('PluginProcessmakerProcessmaker',
'pre_show_item_processmakerticket'));
$PLUGIN_HOOKS['post_show_item']['processmaker']
= array('Ticket' => array('PluginProcessmakerProcessmaker',
'post_show_item_processmakerticket'));
// $PLUGIN_HOOKS["helpdesk_menu_entry"]['processmaker'] = '/front/processmaker.helpdesk.form.php';
// Display a menu entry ?
if (plugin_processmaker_haveRight("process_config","r")) {
$PLUGIN_HOOKS['menu_entry']['processmaker'] = 'front/process.php';
$PLUGIN_HOOKS['submenu_entry']['processmaker']['search'] = 'front/process.php';
}
Plugin::registerClass('PluginProcessmakerProcess', array( 'massiveaction_nodelete_types' => true) ) ;
//$CFG_GLPI["massiveaction_nodelete_types"][] = 'PluginProcessmakerProcess' ;
// Config page
//if (Session::haveRight('config','w')) {
// $PLUGIN_HOOKS['config_page']['processmaker'] = 'front/config.form.php';
//}
/*,
'TicketFollowup' => array('PluginProcessmakerProcessmaker', 'plugin_pre_item_add_processmaker_followup') */
$PLUGIN_HOOKS['pre_item_add']['processmaker'] = array(
'Ticket' => array('PluginProcessmakerProcessmaker', 'plugin_pre_item_add_processmaker')
);
$PLUGIN_HOOKS['pre_item_update']['processmaker'] = array(
'Ticket' => 'plugin_pre_item_update_processmaker'
);
// , 'TicketFollowup' => 'plugin_pre_item_update_processmaker_followup'
$PLUGIN_HOOKS['item_update']['processmaker'] = array(
'TicketSatisfaction' => 'plugin_item_update_processmaker_satisfaction'
);
$PLUGIN_HOOKS['item_add']['processmaker'] = array(
'Ticket' => array('PluginProcessmakerProcessmaker', 'plugin_item_add_processmaker')
);
$PLUGIN_HOOKS['item_get_datas']['processmaker'] = array(
'NotificationTargetTicket' => array('PluginProcessmakerProcessmaker', 'plugin_item_get_datas_processmaker')
);
$PLUGIN_HOOKS['pre_item_purge']['processmaker'] = array(
'Ticket_User' => 'plugin_pre_item_purge_processmaker'
) ;
$PLUGIN_HOOKS['item_purge']['processmaker'] = array(
'Ticket_User' => 'plugin_item_purge_processmaker'
) ;
$url = explode("/", $_SERVER['PHP_SELF']);
$pageName = explode("?", array_pop($url));
switch($pageName[0]) {
case "tracking.injector.php":
case "helpdesk.public.php":
//$plug = new Plugin;
//if( !$plug->isActivated('rayusermanagementticket') )
$PLUGIN_HOOKS['add_javascript']['processmaker'] = "js/helpdesk.public.js.php";
break;
}
$PLUGIN_HOOKS['use_massive_action']['processmaker'] = 1;
//$PLUGIN_HOOKS['planning_populate']['processmaker'] = "plugin_planning_populate_processmaker"; // used for task descriptions
}
// Get the name and the version of the plugin - Needed
function plugin_version_processmaker(){
global $LANG;
return array ('name' => 'Process Maker',
'version' => '2.4.1',
'author' => 'Olivier Moron',
'homepage' => '',
'minGlpiVersion' => '0.83.8');
}
// Optional : check prerequisites before install : may print errors or add to message after redirect
function plugin_processmaker_check_prerequisites(){
if (version_compare(GLPI_VERSION,'0.83.8','lt') || version_compare(GLPI_VERSION,'0.84','ge')) {
echo "This plugin requires GLPI 0.83.8 or higher";
return false;
}
$plug = new Plugin ;
if (!$plug->isActivated('mhooks') || version_compare( $plug->fields['version'], '1.1.0', '<')) {
echo "'mhooks 1.1.0' plugin is needed to run 'processmaker' plugin, please add it to your GLPI plugin configuration.";
return false;
}
return true;
}
function plugin_processmaker_check_config($verbose = false){
$plug = new Plugin ;
if ($plug->isActivated('mhooks') && version_compare( $plug->fields['version'], '1.1.0', '>=')) {
return true;
}
if ($verbose) {
echo "'mhooks 1.1.0' plugin is needed to run 'processmaker' plugin, please add it to your GLPI plugin configuration.";
}
return false;
}
function plugin_processmaker_haveRight($module,$right) {
$matches=array("" => array("", "r", "w"), // should never happend
"r" => array("r", "w"),
"w" => array("w"),
"1" => array("1"),
"0" => array("0", "1")); // should never happend;
if (isset($_SESSION["glpi_plugin_processmaker_profile"][$module])
&& in_array($_SESSION["glpi_plugin_processmaker_profile"][$module], $matches[$right])) {
return true;
} else {
return false;
}
}
?>