/** * @return int */ static function sendAlert() { global $DB, $CFG_GLPI; if (!$CFG_GLPI["use_mailing"]) { return 0; } $items_infos = array(); $query = "SELECT `glpi_plugin_ocsinventoryng_notimportedcomputers`.*\n FROM `glpi_plugin_ocsinventoryng_notimportedcomputers`\n LEFT JOIN `glpi_alerts`\n ON (`glpi_plugin_ocsinventoryng_notimportedcomputers`.`id` = `glpi_alerts`.`items_id`\n AND `glpi_alerts`.`itemtype` = 'PluginOcsinventoryngNotimportedcomputer'\n AND `glpi_alerts`.`type` = '" . Alert::END . "')\n WHERE `glpi_alerts`.`date` IS NULL"; foreach ($DB->request($query) as $notimported) { $items_infos[$notimported['entities_id']][$notimported['id']] = $notimported; } foreach ($items_infos as $entity => $items) { if (NotificationEvent::raiseEvent('not_imported', new PluginOcsinventoryngNotimportedcomputer(), array('entities_id' => $entity, 'notimported' => $items))) { $alert = new Alert(); $input["itemtype"] = 'PluginOcsinventoryngNotimportedcomputer'; $input["type"] = Alert::END; foreach ($items as $id => $item) { $input["items_id"] = $id; $alert->add($input); unset($alert->fields['id']); } } else { Toolbox::logDebug(__('%1$s: %2$s') . "\n", Dropdown::getDropdownName("glpi_entities", $entity), __('Send OCSNG not imported computers alert failed', 'ocsinventoryng')); } } }
foreach ($_POST["fields"] as $field => $value) { if ($type->can($_POST["id"], PURGE) && $value == 1 && PluginGenericobjectField::checkNecessaryFieldsDelete($itemtype, $field)) { PluginGenericobjectField::deleteField(getTableForItemType($itemtype), $field); Session::addMessageAfterRedirect(__("Field(s) deleted successfully", "genericobject"), true, INFO); } } } elseif (isset ($_POST["add_field"])) { $type = new PluginGenericobjectType(); if ($_POST["new_field"] && $type->can($_POST["id"], UPDATE)) { $itemtype = $type->fields['itemtype']; PluginGenericobjectType::registerOneType($itemtype); Toolbox::logDebug(array( 'itemtype' => $itemtype, 'getTableForItemType'=>getTableForItemType($itemtype), 'new_field' => $_POST['new_field'] )); PluginGenericobjectField::addNewField(getTableForItemType($itemtype), $_POST["new_field"]); Session::addMessageAfterRedirect(__("Field added successfully", "genericobject")); } } elseif (isset($_POST['action'])) { //Move field PluginGenericobjectField::changeFieldOrder($_POST); } Html::back();
function stop() { if (self::$run) { $data = xhprof_disable(); $incl = defined('XHPROF_PATH') ? XHPROF_PATH : self::XHPROF_PATH; include_once $incl . '/utils/xhprof_lib.php'; include_once $incl . '/utils/xhprof_runs.php'; $runs = new XHProfRuns_Default(); $id = $runs->save_run($data, 'glpi'); $url = defined('XHPROF_URL') ? XHPROF_URL : self::XHPROF_URL; $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost'; $link = "http://" . $host . "{$url}/index.php?run={$id}&source=glpi"; Toolbox::logDebug("Stop profiling with XHProf, result URL", $link); self::$run = false; } }
/** * Constructor of massive actions. * There is three stages and each one have its own objectives: * - initial: propose the actions and filter the checkboxes (only once) * - specialize: add action specific fields and filter items. There can be as many as needed! * - process: process the massive action (only once, but can be reload to avoid timeout) * * We trust all previous stages: we don't redo the checks * * @param $POST something like $_POST * @param $GET something like $_GET * @param $stage the current stage * * @return nothing (it is a constructor). **/ function __construct(array $POST, array $GET, $stage) { global $CFG_GLPI; if (!empty($POST)) { if (!isset($POST['is_deleted'])) { $POST['is_deleted'] = 0; } $this->nb_items = 0; if (isset($POST['item']) || isset($POST['items'])) { $remove_from_post = array(); switch ($stage) { case 'initial': $POST['action_filter'] = array(); // 'specific_actions': restrict all possible actions or introduce new ones // thus, don't try to load other actions and don't filter any item if (isset($POST['specific_actions'])) { $POST['actions'] = $POST['specific_actions']; $specific_action = 1; $dont_filter_for = array_keys($POST['actions']); } else { $specific_action = 0; if (isset($POST['add_actions'])) { $POST['actions'] = $POST['add_actions']; $dont_filter_for = array_keys($POST['actions']); } else { $POST['actions'] = array(); $dont_filter_for = array(); } } if (count($dont_filter_for)) { $POST['dont_filter_for'] = array_combine($dont_filter_for, $dont_filter_for); } else { $POST['dont_filter_for'] = array(); } $remove_from_post[] = 'specific_actions'; $remove_from_post[] = 'add_actions'; $POST['items'] = array(); foreach ($POST['item'] as $itemtype => $ids) { // initial are raw checkboxes: 0=unchecked or 1=checked $items = array(); foreach ($ids as $id => $checked) { if ($checked == 1) { $items[$id] = $id; $this->nb_items++; } } $POST['items'][$itemtype] = $items; if (!$specific_action) { $actions = self::getAllMassiveActions($itemtype, $POST['is_deleted'], $this->getCheckItem($POST)); $POST['actions'] = array_merge($actions, $POST['actions']); foreach ($actions as $action => $label) { $POST['action_filter'][$action][] = $itemtype; $POST['actions'][$action] = $label; } } } if (empty($POST['actions'])) { throw new Exception(__('No action available')); } // Initial items is used to define $_SESSION['glpimassiveactionselected'] $POST['initial_items'] = $POST['items']; $remove_from_post[] = 'item'; break; case 'specialize': if (!isset($POST['action'])) { Toolbox::logDebug('Implementation error !'); throw new Exception(__('Implementation error !')); } if ($POST['action'] == -1) { // Case when no action is choosen exit; } if (isset($POST['actions'])) { // First, get the name of current action ! if (!isset($POST['actions'][$POST['action']])) { Toolbox::logDebug('Implementation error !'); throw new Exception(__('Implementation error !')); } $POST['action_name'] = $POST['actions'][$POST['action']]; $remove_from_post[] = 'actions'; // Then filter the items regarding the action if (!isset($POST['dont_filter_for'][$POST['action']])) { if (isset($POST['action_filter'][$POST['action']])) { $items = array(); foreach ($POST['action_filter'][$POST['action']] as $itemtype) { if (isset($POST['items'][$itemtype])) { $items[$itemtype] = $POST['items'][$itemtype]; } } $POST['items'] = $items; } } // Don't affect items that forbid the action $items = array(); foreach ($POST['items'] as $itemtype => $ids) { if ($item = getItemForItemtype($itemtype)) { $forbidden = $item->getForbiddenStandardMassiveAction(); if (in_array($POST['action'], $forbidden)) { continue; } $items[$itemtype] = $ids; } } $POST['items'] = $items; $remove_from_post[] = 'dont_filter_for'; $remove_from_post[] = 'action_filter'; } // Some action works for only one itemtype. Then, we filter items. if (isset($POST['specialize_itemtype'])) { $itemtype = $POST['specialize_itemtype']; if (isset($POST['items'][$itemtype])) { $POST['items'] = array($itemtype => $POST['items'][$itemtype]); } else { $POST['items'] = array(); } $remove_from_post[] = 'specialize_itemtype'; } // Extract processor of the action if (!isset($POST['processor'])) { $action = explode(self::CLASS_ACTION_SEPARATOR, $POST['action']); if (count($action) == 2) { $POST['processor'] = $action[0]; $POST['action'] = $action[1]; } else { $POST['processor'] = 'MassiveAction'; $POST['action'] = $POST['action']; } } // Count number of items ! foreach ($POST['items'] as $itemtype => $ids) { $this->nb_items += count($ids); } break; case 'process': if (isset($POST['initial_items'])) { $_SESSION['glpimassiveactionselected'] = $POST['initial_items']; } else { $_SESSION['glpimassiveactionselected'] = array(); } $remove_from_post = array('items', 'action', 'action_name', 'processor', 'massiveaction', 'is_deleted', 'initial_items'); $this->identifier = mt_rand(); $this->done = array(); $this->nb_done = 0; $this->action_name = $POST['action_name']; $this->results = array('ok' => 0, 'ko' => 0, 'noright' => 0, 'messages' => array()); foreach ($POST['items'] as $itemtype => $ids) { $this->nb_items += count($ids); } if (isset($_SERVER['HTTP_REFERER'])) { $this->redirect = $_SERVER['HTTP_REFERER']; } else { $this->redirect = $CFG_GLPI['root_doc'] . "/front/central.php"; } // Don't display progress bars if delay is less than 1 second $this->display_progress_bars = false; break; } $this->POST = $POST; foreach (array('items', 'action', 'processor') as $field) { if (isset($this->POST[$field])) { $this->{$field} = $this->POST[$field]; } } foreach ($remove_from_post as $field) { if (isset($this->POST[$field])) { unset($this->POST[$field]); } } } if ($this->nb_items == 0) { throw new Exception(__('No selected items')); } } else { if ($stage != 'process' || !isset($_SESSION['current_massive_action'][$GET['identifier']])) { Toolbox::logDebug('Implementation error !'); throw new Exception(__('Implementation error !')); } $identifier = $GET['identifier']; foreach ($_SESSION['current_massive_action'][$identifier] as $attribute => $value) { $this->{$attribute} = $value; } if ($this->identifier != $identifier) { $this->error = __('Invalid process'); return; } unset($_SESSION['current_massive_action'][$identifier]); } // Add process elements if ($stage == 'process') { if (!isset($this->remainings)) { $this->remainings = $this->items; } $this->fields_to_remove_when_reload = array('fields_to_remove_when_reload'); $this->timer = new Timer(); $this->timer->start(); $this->fields_to_remove_when_reload[] = 'timer'; $max_time = get_cfg_var("max_execution_time") == 0 ? 60 : get_cfg_var("max_execution_time"); $this->timeout_delay = $max_time - 3; $this->fields_to_remove_when_reload[] = 'timeout_delay'; if (isset($_SESSION["MESSAGE_AFTER_REDIRECT"])) { $this->messaget_after_redirect = $_SESSION["MESSAGE_AFTER_REDIRECT"]; unset($_SESSION["MESSAGE_AFTER_REDIRECT"]); } } }
/** * Get logs of job * * @param array $task_ids list of tasks id * @return array */ function getJoblogs($task_ids = array()) { global $DB; $debug_mode = $_SESSION['glpi_use_mode'] == Session::DEBUG_MODE; $runclass = new PluginFusioninventoryTaskjobstate(); $run_states = $runclass->getStateNames(); $query_where = array(); $query_where[] = "WHERE 1"; if (isset($_SESSION['glpiactiveentities_string'])) { $query_where[] = getEntitiesRestrictRequest("AND", 'task'); } if (is_array($task_ids) and count($task_ids) > 0) { $query_where[] = "AND task.`id` IN (" . implode(",", $task_ids) . ")"; } // quickly filter empty WHERE entry $query_where = array_filter($query_where); $query_fields = array(array('task.id', 'task.`id`'), array('task.name', 'task.`name`'), array('job.id', 'job.`id`'), array('job.name', 'job.`name`'), array('job.method', 'job.`method`'), array('job.targets', 'job.`targets`')); $fieldmap = array(); foreach ($query_fields as $index => $key) { $fieldmap[$key[0]] = $index; } $query_select = array(); foreach ($query_fields as $index => $key) { $query_select[] = $key[1] . " AS '" . $key[0] . "'"; } $query_joins = array(); $query_joins['task'] = implode("\n", array("INNER JOIN `glpi_plugin_fusioninventory_tasks` as task", " ON job.`plugin_fusioninventory_tasks_id` = task.`id`", " AND task.`is_active` = 1")); $data_structure = array('query' => implode("\n", array("SELECT", implode(",\n", $query_select), "FROM `glpi_plugin_fusioninventory_taskjobs` as job", implode("\n", $query_joins), implode("\n", $query_where))), 'result' => null); $data_structure['result'] = $DB->query($data_structure['query']); //Results grouped by tasks > jobs > jobstates $logs = array(); //Target cache (used to speed up data formatting) $targets_cache = array(); $expanded = array(); if (isset($_SESSION['plugin_fusioninventory_tasks_expanded'])) { $expanded = $_SESSION['plugin_fusioninventory_tasks_expanded']; } while ($result = $data_structure['result']->fetch_row()) { $task_id = $result[$fieldmap['task.id']]; if (!array_key_exists($task_id, $logs)) { $logs[$task_id] = array('task_name' => $result[$fieldmap['task.name']], 'task_id' => $result[$fieldmap['task.id']], 'expanded' => false, 'jobs' => array()); } if (isset($expanded[$task_id])) { $logs[$task_id]['expanded'] = $expanded[$task_id]; } $job_id = $result[$fieldmap['job.id']]; $jobs_handle =& $logs[$task_id]['jobs']; if (!array_key_exists($job_id, $jobs_handle)) { $jobs_handle[$job_id] = array('name' => $result[$fieldmap['job.name']], 'id' => $result[$fieldmap['job.id']], 'method' => $result[$fieldmap['job.method']], 'targets' => array()); } $targets = importArrayFromDB($result[$fieldmap['job.targets']]); $targets_handle =& $jobs_handle[$job_id]['targets']; $agent_state_types = array('agents_prepared', 'agents_cancelled', 'agents_running', 'agents_success', 'agents_error', 'agents_notdone'); if ($result[$fieldmap['job.method']] == 'networkinventory') { $pfNetworkinventory = new PluginFusioninventoryNetworkinventory(); foreach ($targets as $keyt => $target) { $item_type = key($target); $items_id = current($target); if ($item_type == 'PluginFusioninventoryIPRange') { unset($targets[$keyt]); // In this case get devices of this iprange $deviceList = $pfNetworkinventory->getDevicesOfIPRange($items_id); $targets = array_merge($targets, $deviceList); } } } foreach ($targets as $target) { $item_type = key($target); $item_id = current($target); $target_id = $item_type . "_" . $item_id; if (isset($targets_cache[$target_id])) { $item = $targets_cache[$target_id]; } else { $item = new $item_type(); $item->getFromDB($item_id); $targets_cache[$target_id] = $item; } $targets_handle[$target_id] = array('id' => $item->fields['id'], 'name' => $item->fields['name'], 'type_name' => $item->getTypeName(), 'item_link' => $item->getLinkUrl(), 'counters' => array(), 'agents' => array()); // create agent states counter lists foreach ($agent_state_types as $type) { $targets_handle[$target_id]['counters'][$type] = array(); } } } // Query fields mapping used to easily select fields by name $query_fields = array(array('task.id', 'task.`id`'), array('task.name', 'task.`name`'), array('job.id', 'job.`id`'), array('job.name', 'job.`name`'), array('job.method', 'job.`method`'), array('agent.id', 'agent.`id`'), array('agent.name', 'agent.`name`'), array('run.id', 'run.`id`'), array('run.itemtype', 'run.`itemtype`'), array('run.items_id', 'run.`items_id`'), array('run.state', 'run.`state`'), array('log.last_date', 'log.`date`'), array('log.last_timestamp', 'UNIX_TIMESTAMP(log.`date`)'), array('log.last_id', 'log.`id`'), array('log.last_comment', 'log.`comment`')); $fieldmap = array(); foreach ($query_fields as $index => $key) { $fieldmap[$key[0]] = $index; } $query_select = array(); foreach ($query_fields as $index => $key) { $query_select[] = $key[1] . " AS '" . $key[0] . "'"; } $query_joins = array(); $query_joins['max_run'] = implode("\n", array("INNER JOIN (", " SELECT", " MAX(run.`id`) AS max_id,", " run.`plugin_fusioninventory_agents_id`,", " run.`plugin_fusioninventory_taskjobs_id`,", " run.`items_id`, run.`itemtype`,", " MAX(log.`id`) AS max_log_id", " FROM `glpi_plugin_fusioninventory_taskjobstates` AS run", " LEFT JOIN `glpi_plugin_fusioninventory_taskjoblogs` AS log", " ON log.`plugin_fusioninventory_taskjobstates_id` = run.`id`", " GROUP BY", " run.`plugin_fusioninventory_agents_id`,", " run.`plugin_fusioninventory_taskjobs_id`,", " run.`items_id`, run.`itemtype`", ") max_run ON max_run.`plugin_fusioninventory_agents_id` = agent.`id`")); $query_joins['run'] = implode("\n", array("INNER JOIN `glpi_plugin_fusioninventory_taskjobstates` AS run", " ON max_run.`max_id` = run.`id`")); $query_joins['log'] = implode("\n", array("LEFT JOIN `glpi_plugin_fusioninventory_taskjoblogs` as log", " ON log.`id` = max_run.`max_log_id`")); $query_joins['job'] = implode("\n", array("INNER JOIN `glpi_plugin_fusioninventory_taskjobs` AS job", " ON job.`id` = run.`plugin_fusioninventory_taskjobs_id`")); $query_joins['task'] = implode("\n", array("INNER JOIN `glpi_plugin_fusioninventory_tasks` as task", " ON job.`plugin_fusioninventory_tasks_id` = task.`id`")); $queries = array(); /* * Get latest jobstates for agents */ $queries['1_last_runs'] = array('query' => implode(" \n", array("SELECT", implode(",\n", $query_select), "FROM `glpi_plugin_fusioninventory_agents` AS agent", implode("\n", $query_joins), implode("\n", $query_where), "GROUP BY job.`id`, agent.`id`, run.`id`")), 'result' => null); /* * Get last finished jobstates (ie. `state` >= 3) */ $query_joins['max_run'] = implode("\n", array("INNER JOIN (", " SELECT", " MAX(run.`id`) AS max_id,", " run.`plugin_fusioninventory_agents_id`,", " run.`plugin_fusioninventory_taskjobs_id`,", " run.`items_id`, run.`itemtype`,", " MAX(log.`id`) AS max_log_id", " FROM `glpi_plugin_fusioninventory_taskjobstates` AS run", " LEFT JOIN `glpi_plugin_fusioninventory_taskjoblogs` AS log", " ON log.`plugin_fusioninventory_taskjobstates_id` = run.`id`", " WHERE run.`state` IN ( " . implode(",", array(PluginFusioninventoryTaskjobstate::FINISHED, PluginFusioninventoryTaskjobstate::IN_ERROR)) . " )", " GROUP BY", " run.`plugin_fusioninventory_agents_id`,", " run.`plugin_fusioninventory_taskjobs_id`,", " run.`items_id`, run.`itemtype`", ") max_run ON max_run.`plugin_fusioninventory_agents_id` = agent.`id`")); $queries['2_finished_runs'] = array('query' => implode(" \n", array("SELECT", implode(",\n", $query_select), "FROM `glpi_plugin_fusioninventory_agents` AS agent", implode("\n", $query_joins), implode("\n", $query_where), "GROUP BY job.`id`, agent.`id`, run.`id`")), 'result' => null); $query_chrono = array("start" => microtime(true), "end" => 0); ksort($queries); foreach ($queries as $query_name => $contents) { $queries[$query_name]['result'] = $DB->query($contents['query']); $query_chrono['end'] = microtime(true); // For debug only //if ($debug_mode) { // file_put_contents("/tmp/glpi_".$query_name.".sql",$contents['query']); //} } $agents = array(); $format_chrono = array("start" => microtime(true), "end" => 0); foreach ($queries as $query_name => $contents) { if (!is_null($contents['result'])) { while ($result = $contents['result']->fetch_row()) { // We need to check if the results are consistent with the view's structure gathered // by the first query $task_id = $result[$fieldmap['task.id']]; //if (!array_key_exists($task_id, $logs)) { if (!isset($logs[$task_id])) { continue; } $job_id = $result[$fieldmap['job.id']]; $jobs =& $logs[$task_id]['jobs']; if (!isset($jobs[$job_id])) { continue; } $target_id = $result[$fieldmap['run.itemtype']] . '_' . $result[$fieldmap['run.items_id']]; $targets =& $jobs[$job_id]['targets']; if (!isset($targets[$target_id])) { continue; } $counters =& $targets[$target_id]['counters']; $agent_id = $result[$fieldmap['agent.id']]; $agents[$agent_id] = $result[$fieldmap['agent.name']]; if (!isset($targets[$target_id]['agents'][$agent_id])) { $targets[$target_id]['agents'][$agent_id] = array(); } $agent_state = ''; // Update counters switch ($result[$fieldmap['run.state']]) { case PluginFusioninventoryTaskjobstate::CANCELLED: // We put this agent in the cancelled counter if it does not have any other job // states. if (!isset($counters['agents_prepared'][$agent_id]) and !isset($counters['agents_running'][$agent_id])) { $counters['agents_cancelled'][$agent_id] = 1; $agent_state = 'cancelled'; } break; case PluginFusioninventoryTaskjobstate::PREPARED: // We put this agent in the prepared counter if it has not yet completed any job. $counters['agents_prepared'][$agent_id] = 1; $agent_state = 'prepared'; break; case PluginFusioninventoryTaskjobstate::SERVER_HAS_SENT_DATA: case PluginFusioninventoryTaskjobstate::AGENT_HAS_SENT_DATA: // This agent is running so it must not be in any other counter foreach ($agent_state_types as $type) { if (isset($counters[$type][$agent_id])) { unset($counters[$type][$agent_id]); } } $counters['agents_running'][$agent_id] = 1; $agent_state = 'running'; break; case PluginFusioninventoryTaskjobstate::IN_ERROR: if (isset($counters['agents_success'][$agent_id])) { unset($counters['agents_success'][$agent_id]); } $counters['agents_error'][$agent_id] = 1; $agent_state = 'error'; if (isset($counters['agents_notdone'][$agent_id])) { unset($counters['agents_notdone'][$agent_id]); } break; case PluginFusioninventoryTaskjobstate::FINISHED: if (isset($counters['agents_error'][$agent_id])) { unset($counters['agents_error'][$agent_id]); } $counters['agents_success'][$agent_id] = 1; $agent_state = 'success'; if (isset($counters['agents_notdone'][$agent_id])) { unset($counters['agents_notdone'][$agent_id]); } break; } if (!isset($counters['agents_error'][$agent_id]) and !isset($counters['agents_success'][$agent_id])) { $counters['agents_notdone'][$agent_id] = 1; } if (isset($counters['agents_running'][$agent_id]) or isset($counters['agents_prepared'][$agent_id])) { unset($counters['agents_cancelled'][$agent_id]); } $targets[$target_id]['agents'][$agent_id][] = array('agent_id' => $agent_id, 'numstate' => $result[$fieldmap['run.state']], 'state' => $agent_state, 'jobstate_id' => $result[$fieldmap['run.id']], 'last_log_id' => $result[$fieldmap['log.last_id']], 'last_log_date' => $result[$fieldmap['log.last_date']], 'timestamp' => $result[$fieldmap['log.last_timestamp']], 'last_log' => $result[$fieldmap['log.last_comment']]); } } } $format_chrono['end'] = microtime(true); if ($debug_mode) { function tmp_display_log($log) { return "ID:" . $log['task_id'] . "(" . $log['task_name'] . ")"; } if (PluginFusioninventoryConfig::isExtradebugActive()) { Toolbox::logDebug(array("tasks" => implode(',', array_map('tmp_display_log', $logs)), "row count" => count($logs), "Joblogs Query" => self::FormatChrono($query_chrono), "Format logs results" => self::FormatChrono($format_chrono))); } } return array('tasks' => $logs, 'agents' => $agents); }
public static function generateTemplate($fields) { $classname = "PluginFields" . ucfirst($fields['itemtype'] . preg_replace('/s$/', '', $fields['name'])); $template_class = file_get_contents(GLPI_ROOT . "/plugins/fields/templates/container.class.tpl"); $template_class = str_replace("%%CLASSNAME%%", $classname, $template_class); $template_class = str_replace("%%ITEMTYPE%%", $fields['itemtype'], $template_class); $template_class = str_replace("%%CONTAINER%%", $fields['id'], $template_class); $template_class = str_replace("%%ITEMTYPE_RIGHT%%", strtolower($fields['itemtype']), $template_class); $class_filename = strtolower($fields['itemtype'] . preg_replace('/s$/', '', $fields['name']) . ".class.php"); if (file_put_contents(GLPI_ROOT . "/plugins/fields/inc/{$class_filename}", $template_class) === false) { Toolbox::logDebug("Error : class file creation - {$class_filename}"); return false; } // Generate Datainjection files $template_class = file_get_contents(GLPI_ROOT . "/plugins/fields/templates/injection.class.tpl"); $template_class = str_replace("%%CLASSNAME%%", $classname, $template_class); $template_class = str_replace("%%ITEMTYPE%%", $fields['itemtype'], $template_class); $template_class = str_replace("%%CONTAINER_ID%%", $fields['id'], $template_class); $template_class = str_replace("%%CONTAINER_NAME%%", $fields['label'], $template_class); $class_filename = strtolower($fields['itemtype'] . preg_replace('/s$/', '', $fields['name']) . "injection.class.php"); if (file_put_contents(GLPI_ROOT . "/plugins/fields/inc/{$class_filename}", $template_class) === false) { Toolbox::logDebug("Error : datainjection class file creation - {$class_filename}"); return false; } // Generate Datainjection injection files $template_class = file_get_contents(GLPI_ROOT . "/plugins/fields/templates/injectioninjection.class.tpl"); $template_class = str_replace("%%CLASSNAME%%", $classname, $template_class); $template_class = str_replace("%%ITEMTYPE%%", $fields['itemtype'], $template_class); $template_class = str_replace("%%CONTAINER_ID%%", $fields['id'], $template_class); $class_filename = strtolower($fields['itemtype'] . preg_replace('/s$/', '', $fields['name']) . "injectioninjection.class.php"); if (file_put_contents(GLPI_ROOT . "/plugins/fields/inc/{$class_filename}", $template_class) === false) { Toolbox::logDebug("Error : datainjection class file creation - {$class_filename}"); return false; } return true; }
static function cronWakeupAgents($crontask) { global $DB; $wakeupArray = array(); $tasks = array(); //Get the maximum number of agent to wakeup, //as allowed in the general configuration $config = new PluginFusioninventoryConfig(); $maxWakeUp = $config->getValue('wakeup_agent_max'); $counter = 0; $continue = true; //Get all active timeslots $timeslot = new PluginFusioninventoryTimeslot(); $timeslots = $timeslot->getCurrentActiveTimeslots(); if (empty($timeslots)) { $query_timeslot = ''; } else { $query_timeslot = "OR (`plugin_fusioninventory_timeslots_id` IN (" . implode(',', $timeslots) . "))"; } //Get all active task requiring an agent wakeup //Check all tasks without timeslot or task with a current active timeslot $query = "SELECT `id`, `wakeup_agent_counter`, `wakeup_agent_time`, `last_agent_wakeup` \n FROM `glpi_plugin_fusioninventory_tasks` \n WHERE `wakeup_agent_time` > 0 \n AND `wakeup_agent_counter` > 0\n AND `is_active`='1' \n AND ((`plugin_fusioninventory_timeslots_id`='0') \n {$query_timeslot})"; foreach ($DB->request($query) as $task) { if (!is_null($task['wakeup_agent_time'])) { //Do not wake up is last wake up in inferior to the minimum wake up interval $interval = time() - strtotime($task['last_agent_wakeup']); if ($interval < $task['wakeup_agent_time'] * MINUTE_TIMESTAMP) { continue; } } //For each task, get a number of taskjobs at the PREPARED state //(the maximum is defined in wakeup_agent_counter) $query_states = "SELECT `taskjobstates`.`plugin_fusioninventory_agents_id`, \n `tasks`.`id` as `taskID`, \n `tasks`.`wakeup_agent_time`,\n `tasks`.`last_agent_wakeup`\n FROM `glpi_plugin_fusioninventory_taskjobstates` as `taskjobstates`,\n `glpi_plugin_fusioninventory_taskjobs` as `taskjobs`\n LEFT JOIN `glpi_plugin_fusioninventory_tasks` as `tasks` \n ON `tasks`.`id`=`taskjobs`.`plugin_fusioninventory_tasks_id`\n WHERE `tasks`.`id`='" . $task['id'] . "' \n AND `taskjobs`.`id`=`taskjobstates`.`plugin_fusioninventory_taskjobs_id` \n AND `taskjobstates`.`state`='" . PluginFusioninventoryTaskjobstate::PREPARED . "' \n ORDER BY `taskjobstates`.`id` ASC LIMIT " . $task['wakeup_agent_counter']; foreach ($DB->request($query_states) as $state) { $agents_id = $state['plugin_fusioninventory_agents_id']; //Check if agent is already added to the list of agents to wake up if (!isset($wakeupArray[$agents_id])) { //This agent must be woken up $wakeupArray[$agents_id] = $agents_id; $counter++; } //Store task ID if (!in_array($state['taskID'], $tasks)) { $tasks[] = $state['taskID']; } //Do not process more than the maximum number of wakeup allowed in the configuration if ($counter >= $maxWakeUp) { if (PluginFusioninventoryConfig::isExtradebugActive()) { Toolbox::logDebug(__("Maximum number of agent wakeup reached", 'fusioninventory') . ":" . $maxWakeUp); } $continue = false; break; } } //We've reached the maximum number of agents to wake up ! if (!$continue) { break; } } //Number of agents successfully woken up $wokeup = 0; $myTask = new PluginFusioninventoryTask(); if (!empty($tasks)) { //Update last wake up time each task $query_lastrun = "UPDATE `glpi_plugin_fusioninventory_tasks` \n SET `last_agent_wakeup`='" . $_SESSION['glpi_currenttime'] . "' \n WHERE `id` IN (" . implode(",", $tasks) . ")"; $DB->query($query_lastrun); $agent = new PluginFusioninventoryAgent(); //Try to wake up agents one by one foreach ($wakeupArray as $ID => $value) { $agent->getFromDB($ID); if ($agent->wakeUp()) { $wokeup++; } } } $crontask->addVolume($wokeup); return true; }
/** * Optimize sql table * * @param $migration migration class (default NULL) * @param $cron to know if optimize must be done (false by default) * * @return number of tables **/ static function optimize_tables($migration = NULL, $cron = false) { global $DB; $crashed_tables = self::checkForCrashedTables(); if (!empty($crashed_tables)) { Toolbox::logDebug("Cannot launch automatic action : crashed tables detected"); return -1; } if (!is_null($migration) && method_exists($migration, 'displayMessage')) { $migration->displayTitle(__('Optimizing tables')); $migration->addNewMessageArea('optimize_table'); // to force new ajax zone $migration->displayMessage(sprintf(__('%1$s - %2$s'), __('optimize'), __('Start'))); } $result = $DB->list_tables(); $nb = 0; while ($line = $DB->fetch_row($result)) { $table = $line[0]; // For big database to reduce delay of migration if ($cron || countElementsInTable($table) < 15000000) { if (!is_null($migration) && method_exists($migration, 'displayMessage')) { $migration->displayMessage(sprintf(__('%1$s - %2$s'), __('optimize'), $table)); } $query = "OPTIMIZE TABLE `" . $table . "` ;"; $DB->query($query); $nb++; } } $DB->free_result($result); if (!is_null($migration) && method_exists($migration, 'displayMessage')) { $migration->displayMessage(sprintf(__('%1$s - %2$s'), __('optimize'), __('End'))); } return $nb; }
$json_response = array("success" => TRUE, "reason" => ''); if (Session::haveRight('plugin_fusioninventory_package', UPDATE)) { PluginFusioninventoryDeployPackage::alter_json('move_item', $_REQUEST); } else { $json_response['success'] = FALSE; $json_response['reason'] = __('Package modification is forbidden by your profile.'); } echo json_encode($json_response); exit; } if (!isset($_REQUEST['orders_id']) && !isset($_REQUEST['rand']) && !isset($_REQUEST['subtype'])) { exit; } if (!is_numeric($_REQUEST['orders_id'])) { Toolbox::logDebug("Error: orders_id in request is not an integer"); Toolbox::logDebug(var_dump($_REQUEST['orders_id'])); exit; } $order = new PluginFusioninventoryDeployOrder(); $order->getFromDB($_REQUEST['orders_id']); //TODO: In the displayForm function, $_REQUEST is somewhat too much for the '$datas' parameter // I think we could use only $order -- Kevin 'kiniou' Roy switch ($_REQUEST['subtype']) { case 'check': PluginFusioninventoryDeployCheck::displayForm($order, $_REQUEST, $_REQUEST['rand'], $_POST['mode']); break; case 'file': PluginFusioninventoryDeployFile::displayForm($order, $_REQUEST, $_REQUEST['rand'], $_POST['mode']); break; case 'action': PluginFusioninventoryDeployAction::displayForm($order, $_REQUEST, $_REQUEST['rand'], $_POST['mode']);
static function destroy($dropdown_name) { $classname = self::getClassname($dropdown_name); $class_filename = PLUGINFIELDS_CLASS_PATH . "/" . $dropdown_name . "dropdown.class.php"; //call uninstall method in dropdown class if ($classname::uninstall() === false) { Toolbox::logDebug("Error : calling dropdown {$classname} uninstallation"); return false; } //remove class file for this dropdown if (file_exists($class_filename)) { if (unlink($class_filename) === false) { Toolbox::logDebug("Error : dropdown class file creation - " . $dropdown_name . "dropdown.class.php"); return false; } } //remove front file for this dropdown $front_filename = PLUGINFIELDS_FRONT_PATH . "/" . $dropdown_name . "dropdown.php"; if (file_exists($front_filename)) { if (unlink($front_filename) === false) { Toolbox::logDebug("Error : dropdown front file removing - " . $dropdown_name . "dropdown.php"); return false; } } //remove front.form file for this dropdown $form_filename = PLUGINFIELDS_FRONT_PATH . "/" . $dropdown_name . "dropdown.form.php"; if (file_exists($form_filename)) { if (unlink($form_filename) === false) { Toolbox::logDebug("Error : dropdown form file removing - " . $dropdown_name . "dropdown.form.php"); return false; } } return true; }
@link https://forge.indepnet.net/projects/barscode @since 2009 ------------------------------------------------------------------------ */ include '../../../inc/includes.php'; if (!defined("GLPI_PLUGIN_DOC_DIR")) { define("GLPI_PLUGIN_DOC_DIR", GLPI_ROOT . "/files/_plugins"); } $docDir = GLPI_PLUGIN_DOC_DIR . '/barcode'; if (isset($_GET['file'])) { $filename = $_GET['file']; // Security test : document in $docDir if (strstr($filename, "../") || strstr($filename, "..\\")) { echo "Security attack !!!"; Toolbox::logDebug("[Plugin barcode][security][sendfile] " . $_SESSION["glpiname"] . " try to get a non standard file : " . $filename); } $file = $docDir . '/' . $filename; if (!file_exists($file)) { echo "Error file {$filename} does not exist"; //TODO : traduire } else { // Now send the file with header() magic header("Expires: Mon, 26 Nov 1962 00:00:00 GMT"); header('Pragma: private'); /// IE BUG + SSL //header('Pragma: no-cache'); header('Cache-control: private, must-revalidate'); /// IE BUG + SSL header("Content-disposition: filename=\"{$filename}\""); header("Content-type: application/pdf");
static function destroy($dropdown_name) { $classname = self::getClassname($dropdown_name); $class_filename = GLPI_ROOT . "/plugins/fields/inc/" . $dropdown_name . "dropdown.class.php"; //load class manually on plugin uninstallation if (file_exists($class_filename)) { if (!class_exists($classname)) { require_once $dropdown_name . "dropdown.class.php"; } //call uninstall method in dropdown class if ($classname::uninstall() === false) { Toolbox::logDebug("Error : calling dropdown {$classname} uninstallation"); return false; } } //remove class file for this dropdown if (file_exists($class_filename)) { if (unlink($class_filename) === false) { Toolbox::logDebug("Error : dropdown class file creation - " . $dropdown_name . "dropdown.class.php"); return false; } } //remove front file for this dropdown $front_filename = GLPI_ROOT . "/plugins/fields/front/" . $dropdown_name . "dropdown.php"; if (file_exists($front_filename)) { if (unlink($front_filename) === false) { Toolbox::logDebug("Error : dropdown front file removing - " . $dropdown_name . "dropdown.php"); return false; } } //remove front.form file for this dropdown $form_filename = GLPI_ROOT . "/plugins/fields/front/" . $dropdown_name . "dropdown.form.php"; if (file_exists($form_filename)) { if (unlink($form_filename) === false) { Toolbox::logDebug("Error : dropdown form file removing - " . $dropdown_name . "dropdown.form.php"); return false; } } return true; }
/** * Display the Form end-user form to be filled * * @param CommonGLPI $item Instance of the Form to be displayed * * @return Null Nothing, just display the form */ public function displayUserForm(CommonGLPI $item) { if (isset($_SESSION['formcreator']['datas'])) { $datas = $_SESSION['formcreator']['datas']; unset($_SESSION['formcreator']['datas']); } else { $datas = null; } echo '<form name="formcreator_form' . $item->getID() . '" method="post" role="form" enctype="multipart/form-data" action="' . $GLOBALS['CFG_GLPI']['root_doc'] . '/plugins/formcreator/front/form.form.php" class="formcreator_form form_horizontal" onsubmit="return validateForm(this);">'; echo '<h1 class="form-title">' . $item->fields['name'] . '</h1>'; // Form Header if (!empty($item->fields['content'])) { echo '<div class="form_header">'; echo html_entity_decode($item->fields['content']); echo '</div>'; } // Get and display sections of the form $question = new PluginFormcreatorQuestion(); $questions = array(); $section_class = new PluginFormcreatorSection(); $find_sections = $section_class->find('plugin_formcreator_forms_id = ' . (int) $item->getID(), '`order` ASC'); echo '<div class="form_section">'; foreach ($find_sections as $section_line) { echo '<h2>' . $section_line['name'] . '</h2>'; // Display all fields of the section $questions = $question->find('plugin_formcreator_sections_id = ' . (int) $section_line['id'], '`order` ASC'); foreach ($questions as $question_line) { if (isset($datas[$question_line['id']])) { // multiple choice question are saved as JSON and needs to be decoded $answer = in_array($question_line['fieldtype'], array('checkboxes', 'multiselect')) ? json_decode($datas[$question_line['id']]) : $datas[$question_line['id']]; } else { $answer = null; } PluginFormcreatorFields::showField($question_line, $answer); } } echo '<script type="text/javascript">formcreatorShowFields();</script>'; // Show validator selector if ($item->fields['validation_required'] > 0) { $validators = array(0 => Dropdown::EMPTY_VALUE); // Groups if ($item->fields['validation_required'] == 2) { $query = 'SELECT g.`id`, g.`completename` FROM `glpi_groups` g LEFT JOIN `glpi_plugin_formcreator_formvalidators` fv ON fv.`users_id` = g.`id` WHERE fv.`forms_id` = ' . (int) $this->getID(); Toolbox::logDebug($query); $result = $GLOBALS['DB']->query($query); while ($validator = $GLOBALS['DB']->fetch_assoc($result)) { $validators[$validator['id']] = $validator['completename']; } // Users } else { $query = 'SELECT u.`id`, u.`name`, u.`realname`, u.`firstname` FROM `glpi_users` u LEFT JOIN `glpi_plugin_formcreator_formvalidators` fv ON fv.`users_id` = u.`id` WHERE fv.`forms_id` = ' . (int) $this->getID(); $result = $GLOBALS['DB']->query($query); while ($validator = $GLOBALS['DB']->fetch_assoc($result)) { $validators[$validator['id']] = formatUserName($validator['id'], $validator['name'], $validator['realname'], $validator['firstname']); } } echo '<div class="form-group required liste line' . (count($questions) + 1) % 2 . '" id="form-validator">'; echo '<label>' . __('Choose a validator', 'formcreator') . ' <span class="red">*</span></label>'; Dropdown::showFromArray('formcreator_validator', $validators); echo '</div>'; } echo '</div>'; // Display submit button echo '<div class="center">'; echo '<input type="submit" name="submit_formcreator" class="submit_button" value="' . __('Send') . '" />'; echo '</div>'; echo '<input type="hidden" name="formcreator_form" value="' . $item->getID() . '">'; echo '<input type="hidden" name="_glpi_csrf_token" value="' . Session::getNewCSRFToken() . '">'; echo '</form>'; }
function get_tickets($from_date, $to_date, $date_fmt) { global $DEBUG_SQL; $response = array(); $range_date = array(); if (!is_null($from_date)) { $range_date_start = new DateTime($from_date->format('Y-m-d')); } else { $range_date_start = null; } $range_date_end = new DateTime($to_date->format('Y-m-d')); \Toolbox::logDebug($range_date_start, $range_date_end); // TODO: build dates filler at the end. If from_date is null it should // take the date from the first ticket created // while($range_date_start < $range_date_end) { // $range_date[] = self::format_dates($range_date_start->format('Y-m-d'),$date_fmt); // $range_date_start->add(DateInterval::createFromDateString('1 day')); // } $current_entity = $_SESSION['glpiactive_entity_name']; $entities_restrict = getEntitiesRestrictRequest('', getTableForItemtype('Ticket'), '', '', false, false); $filter = array(); // TODO: Handle 'until' types of request. // Check if $from_date is null and get everything before $to_date if (is_null($from_date)) { $filter[] = " AND ( " . " (date <= '" . $to_date->format('Y-m-d') . "')" . ") AND is_deleted = 0"; } else { $filter[] = " AND ( " . " (date between '" . $from_date->format('Y-m-d') . "'" . " and '" . $to_date->format('Y-m-d') . "')" . " OR (solvedate between '" . $from_date->format('Y-m-d') . "'" . " and '" . $to_date->format('Y-m-d') . "')" . " OR (closedate between '" . $from_date->format('Y-m-d') . "'" . " and '" . $to_date->format('Y-m-d') . "')" . ") AND is_deleted = 0"; } // $filter[] = // " AND ( ". // "date < '".$to_date->format('Y-m-d')."'". // ")"; $filter[] = " AND " . $entities_restrict; array_unshift($filter, '1'); $tickets = $this->factories['tickets']->find(implode("\n", $filter), "id ASC"); // Get Categories $categories = $this->factories['categories']->find(implode("\n", array("1 "))); $category_ids = array_keys($categories); $solutiontypes = $this->factories['solution_types']->find(); $response['result'] = array(); $result =& $response['result']; $category = null; foreach ($tickets as $ticket) { $category_id = $ticket['itilcategories_id']; $solutiontypes_id = $tickets['solutiontypes_id']; $solutiontype = null; if ($solutiontypes_id > 0) { $solutiontype = $solutiontypes[$solutiontypes_id]['name']; } else { $solutiontype = __('None'); } if (!array_key_exists($category_id, $categories)) { $category = "N/A"; $category_names = array("N/A"); } else { $category = $categories[$category_id]; //TODO: make the following configurable. $category_names = explode(" > ", $category['completename']); } $type = null; switch ($ticket['type']) { case Ticket::INCIDENT_TYPE: $type = 'incident'; break; case Ticket::DEMAND_TYPE: $type = 'request'; break; } $result[] = array('id' => $ticket['id'], 'date_opened' => self::format_dates($ticket['date'], $date_fmt), 'date_solved' => self::format_dates($ticket['solvedate'], $date_fmt), 'date_closed' => self::format_dates($ticket['closedate'], $date_fmt), 'status_code' => $ticket['status'], 'status' => Ticket::getStatus($ticket['status']), 'category' => $category_names, 'category_id' => $category_id, 'impact' => Ticket::getImpactName($ticket['impact']), 'priority' => Ticket::getPriorityName($ticket['priority']), 'urgency' => Ticket::getUrgencyName($ticket['urgency']), 'solve_delay_stat' => intval($ticket['solve_delay_stat']), 'type' => $type, 'type_name' => Ticket::getTicketTypeName($ticket['type']), 'solution_type' => $solutiontype); } $response['metadata'] = array('count' => count($result), 'from_date' => !is_null($from_date) ? $from_date->format('c') : null, 'to_date' => $to_date->format('c'), 'current_entity' => $current_entity, 'range_dates' => array_values(array_unique($range_date))); $response['_debug'] = array('entities_restrict' => $entities_restrict, 'filter' => $filter, 'DEBUG_SQL' => $DEBUG_SQL); return $response; }
static function alter_json($action_type, $params) { //route to sub class $item_type = $params['itemtype']; if (in_array($item_type, array('PluginFusioninventoryDeployCheck', 'PluginFusioninventoryDeployFile', 'PluginFusioninventoryDeployAction'))) { switch ($action_type) { case "add_item": $item_type::add_item($params); break; case "save_item": $item_type::save_item($params); break; case "remove_item": $item_type::remove_item($params); break; case "move_item": $item_type::move_item($params); break; } } else { Toolbox::logDebug("package subtype not found : " . $params['itemtype']); Html::displayErrorAndDie("package subtype not found"); } }
/** * Cron for ticketsatisfaction's automatic generated * * @param $task : crontask object * * @return integer (0 : nothing done - 1 : done) **/ static function cronCreateInquest($task) { global $DB; $conf = new Entity(); $inquest = new TicketSatisfaction(); $tot = 0; $maxentity = array(); $tabentities = array(); $rate = Entity::getUsedConfig('inquest_config', 0, 'inquest_rate'); if ($rate > 0) { $tabentities[0] = $rate; } foreach ($DB->request('glpi_entities') as $entity) { $rate = Entity::getUsedConfig('inquest_config', $entity['id'], 'inquest_rate'); $parent = Entity::getUsedConfig('inquest_config', $entity['id'], 'entities_id'); if ($rate > 0) { $tabentities[$entity['id']] = $rate; } } foreach ($tabentities as $entity => $rate) { $parent = Entity::getUsedConfig('inquest_config', $entity, 'entities_id'); $delay = Entity::getUsedConfig('inquest_config', $entity, 'inquest_delay'); $duration = Entity::getUsedConfig('inquest_config', $entity, 'inquest_duration'); $type = Entity::getUsedConfig('inquest_config', $entity); $max_closedate = Entity::getUsedConfig('inquest_config', $entity, 'max_closedate'); $query = "SELECT `glpi_tickets`.`id`,\n `glpi_tickets`.`closedate`,\n `glpi_tickets`.`entities_id`\n FROM `glpi_tickets`\n LEFT JOIN `glpi_ticketsatisfactions`\n ON `glpi_ticketsatisfactions`.`tickets_id` = `glpi_tickets`.`id`\n LEFT JOIN `glpi_entities`\n ON `glpi_tickets`.`entities_id` = `glpi_entities`.`id`\n WHERE `glpi_tickets`.`entities_id` = '{$entity}'\n AND `glpi_tickets`.`is_deleted` = 0\n AND `glpi_tickets`.`status` = '" . self::CLOSED . "'\n AND `glpi_tickets`.`closedate` > '{$max_closedate}'\n AND ADDDATE(`glpi_tickets`.`closedate`, INTERVAL {$delay} DAY)<=NOW()\n AND ADDDATE(`glpi_entities`.`max_closedate`, INTERVAL {$duration} DAY)<=NOW()\n AND `glpi_ticketsatisfactions`.`id` IS NULL\n ORDER BY `closedate` ASC"; Toolbox::logDebug($entity . ' ' . $rate . ' ' . $parent . ' ' . $delay . ' ' . $type . ' ' . $max_closedate); $nb = 0; $max_closedate = ''; foreach ($DB->request($query) as $tick) { $max_closedate = $tick['closedate']; if (mt_rand(1, 100) <= $rate) { if ($inquest->add(array('tickets_id' => $tick['id'], 'date_begin' => $_SESSION["glpi_currenttime"], 'entities_id' => $tick['entities_id'], 'type' => $type))) { $nb++; } } } // conservation de toutes les max_closedate des entites filles if (!empty($max_closedate) && (!isset($maxentity[$parent]) || $max_closedate > $maxentity[$parent])) { $maxentity[$parent] = $max_closedate; } if ($nb) { $tot += $nb; $task->addVolume($nb); $task->log(sprintf(__('%1$s: %2$s'), Dropdown::getDropdownName('glpi_entities', $entity), $nb)); } } // Sauvegarde du max_closedate pour ne pas tester les même tickets 2 fois foreach ($maxentity as $parent => $maxdate) { $conf->getFromDB($parent); $conf->update(array('id' => $conf->fields['id'], 'max_closedate' => $maxdate)); } return $tot > 0; }
public function isOverBudget($ID) { global $DB; //Do not check if it's a template if ($this->fields['is_template']) { return PluginOrderOrder::ORDER_IS_UNDER_BUDGET; } // Compute all prices for BUDGET $table = $this->getTable(); $query = "SELECT *\n FROM `{$table}`\n WHERE `budgets_id` = '{$this->fields['budgets_id']}'"; // Get BUDGET $budget = new Budget(); if (!$budget->getFromDB($this->fields['budgets_id'])) { return false; } Toolbox::logDebug($budget); if ($budget->fields['value'] == 0) { return PluginOrderOrder::ORDER_IS_UNDER_BUDGET; } $total_HT = 0; foreach ($DB->request($query) as $data) { $item = new PluginOrderOrder_Item(); $prices = $item->getAllPrices($data['id']); $total_HT += $prices["priceHT"] + $data['port_price']; } // Compare BUDGET value to TOTAL_HT value if ($total_HT > $budget->getField('value')) { return PluginOrderOrder::ORDER_IS_OVER_BUDGET; } elseif ($total_HT == $budget->getField('value')) { return PluginOrderOrder::ORDER_IS_EQUAL_BUDGET; } else { return PluginOrderOrder::ORDER_IS_UNDER_BUDGET; } }
public static function generateTemplate($fields) { $itemtypes = count($fields['itemtypes']) > 0 ? json_decode($fields['itemtypes'], TRUE) : array(); foreach ($itemtypes as $itemtype) { $classname = "PluginFields" . ucfirst($itemtype . preg_replace('/s$/', '', $fields['name'])); $template_class = file_get_contents(GLPI_ROOT . "/plugins/fields/templates/container.class.tpl"); $template_class = str_replace("%%CLASSNAME%%", $classname, $template_class); $template_class = str_replace("%%ITEMTYPE%%", $itemtype, $template_class); $template_class = str_replace("%%CONTAINER%%", $fields['id'], $template_class); $template_class = str_replace("%%ITEMTYPE_RIGHT%%", $itemtype::$rightname, $template_class); $class_filename = strtolower($itemtype . preg_replace('/s$/', '', $fields['name']) . ".class.php"); if (file_put_contents(PLUGINFIELDS_CLASS_PATH . "/{$class_filename}", $template_class) === false) { Toolbox::logDebug("Error : class file creation - {$class_filename}"); return false; } // Generate Datainjection files $template_class = file_get_contents(GLPI_ROOT . "/plugins/fields/templates/injection.class.tpl"); $template_class = str_replace("%%CLASSNAME%%", $classname, $template_class); $template_class = str_replace("%%ITEMTYPE%%", $itemtype, $template_class); $template_class = str_replace("%%CONTAINER_ID%%", $fields['id'], $template_class); $template_class = str_replace("%%CONTAINER_NAME%%", $fields['label'], $template_class); $class_filename = strtolower($itemtype . preg_replace('/s$/', '', $fields['name']) . "injection.class.php"); if (file_put_contents(PLUGINFIELDS_CLASS_PATH . "/{$class_filename}", $template_class) === false) { Toolbox::logDebug("Error : datainjection class file creation - {$class_filename}"); return false; } } return true; }