function prepareInputForAdd($input)
 {
     global $LANG;
     if (!isset($input['profiles_id']) || $input['profiles_id'] <= 0 || !isset($input['entities_id']) || $input['entities_id'] < 0 || !isset($input['users_id']) || $input['users_id'] < 0) {
         addMessageAfterRedirect($LANG['common'][24], false, ERROR);
         return false;
     }
     return $input;
 }
 function prepareInputForAdd($input)
 {
     global $LANG;
     // Check override of segment : do not add
     if (count(self::getSegmentsBetween($input['calendars_id'], $input['day'], $input['begin'], $input['day'], $input['end'])) > 0) {
         addMessageAfterRedirect($LANG['calendar'][8], false, ERROR);
         return false;
     }
     return $input;
 }
 /**
  * Prepare input datas for adding the relation
  *
  * Overloaded to check is Disconnect needed (during OCS sync)
  * and to manage autoupdate feature
  *
  *@param $input datas used to add the item
  *
  *@return the modified $input array
  *
  **/
 function prepareInputForAdd($input)
 {
     global $DB, $CFG_GLPI, $LANG;
     switch ($input['itemtype']) {
         case 'Monitor':
             $item = new Monitor();
             $ocstab = 'import_monitor';
             break;
         case 'Phone':
             // shoul really never occurs as OCS doesn't sync phone
             $item = new Phone();
             $ocstab = '';
             break;
         case 'Printer':
             $item = new Printer();
             $ocstab = 'import_printer';
             break;
         case 'Peripheral':
             $item = new Peripheral();
             $ocstab = 'import_peripheral';
             break;
         default:
             return false;
     }
     if (!$item->getFromDB($input['items_id'])) {
         return false;
     }
     if (!$item->getField('is_global')) {
         // Handle case where already used, should never happen (except from OCS sync)
         $query = "SELECT `id`, `computers_id`\n                   FROM `glpi_computers_items`\n                   WHERE `glpi_computers_items`.`items_id` = '" . $input['items_id'] . "'\n                         AND `glpi_computers_items`.`itemtype` = '" . $input['itemtype'] . "'";
         $result = $DB->query($query);
         while ($data = $DB->fetch_assoc($result)) {
             $temp = clone $this;
             $temp->delete($data);
             if ($ocstab) {
                 OcsServer::deleteInOcsArray($data["computers_id"], $data["id"], $ocstab);
             }
         }
         // Autoupdate some fields - should be in post_addItem (here to avoid more DB access)
         $comp = new Computer();
         if ($comp->getFromDB($input['computers_id'])) {
             $updates = array();
             if ($CFG_GLPI["is_location_autoupdate"] && $comp->fields['locations_id'] != $item->getField('locations_id')) {
                 $updates['locations_id'] = addslashes($comp->fields['locations_id']);
                 addMessageAfterRedirect($LANG['computers'][48], true);
             }
             if ($CFG_GLPI["is_user_autoupdate"] && $comp->fields['users_id'] != $item->getField('users_id') || $CFG_GLPI["is_group_autoupdate"] && $comp->fields['groups_id'] != $item->getField('groups_id')) {
                 if ($CFG_GLPI["is_user_autoupdate"]) {
                     $updates['users_id'] = $comp->fields['users_id'];
                 }
                 if ($CFG_GLPI["is_group_autoupdate"]) {
                     $updates['groups_id'] = $comp->fields['groups_id'];
                 }
                 addMessageAfterRedirect($LANG['computers'][50], true);
             }
             if ($CFG_GLPI["is_contact_autoupdate"] && ($comp->fields['contact'] != $item->getField('contact') || $comp->fields['contact_num'] != $item->getField('contact_num'))) {
                 $updates['contact'] = addslashes($comp->fields['contact']);
                 $updates['contact_num'] = addslashes($comp->fields['contact_num']);
                 addMessageAfterRedirect($LANG['computers'][49], true);
             }
             if ($CFG_GLPI["state_autoupdate_mode"] < 0 && $comp->fields['states_id'] != $item->getField('states_id')) {
                 $updates['states_id'] = $comp->fields['states_id'];
                 addMessageAfterRedirect($LANG['computers'][56], true);
             }
             if ($CFG_GLPI["state_autoupdate_mode"] > 0 && $item->getField('states_id') != $CFG_GLPI["state_autoupdate_mode"]) {
                 $updates['states_id'] = $CFG_GLPI["state_autoupdate_mode"];
             }
             if (count($updates)) {
                 $updates['id'] = $input['items_id'];
                 $item->update($updates);
             }
         }
     }
     return $input;
 }
Example #4
0
 /**
  * add files (from $_FILES) to a ticket
  * create document if needed
  * create link from document to ticket
  *
  * @param $id of the ticket
  *
  * @return array of doc added name
  **/
 function addFiles($id)
 {
     global $LANG, $CFG_GLPI;
     if (!isset($_FILES)) {
         return array();
     }
     $docadded = array();
     $doc = new Document();
     $docitem = new Document_Item();
     // add Document if exists
     if (isset($_FILES['multiple'])) {
         unset($_FILES['multiple']);
         $TMPFILE = $_FILES;
     } else {
         $TMPFILE = array($_FILES);
     }
     foreach ($TMPFILE as $_FILES) {
         if (isset($_FILES['filename']) && count($_FILES['filename']) > 0 && $_FILES['filename']["size"] > 0) {
             // Check for duplicate
             if ($doc->getFromDBbyContent($this->fields["entities_id"], $_FILES['filename']['tmp_name'])) {
                 $docID = $doc->fields["id"];
             } else {
                 $input2 = array();
                 $input2["name"] = addslashes($LANG['tracking'][24] . " {$id}");
                 $input2["tickets_id"] = $id;
                 $input2["entities_id"] = $this->fields["entities_id"];
                 $input2["documentcategories_id"] = $CFG_GLPI["documentcategories_id_forticket"];
                 $input2["_only_if_upload_succeed"] = 1;
                 $input2["entities_id"] = $this->fields["entities_id"];
                 $docID = $doc->add($input2);
             }
             if ($docID > 0) {
                 if ($docitem->add(array('documents_id' => $docID, 'itemtype' => $this->getType(), 'items_id' => $id))) {
                     $docadded[] = stripslashes($doc->fields["name"] . " - " . $doc->fields["filename"]);
                 }
             }
         } else {
             if (!empty($_FILES['filename']['name']) && isset($_FILES['filename']['error']) && $_FILES['filename']['error']) {
                 addMessageAfterRedirect($LANG['document'][46], false, ERROR);
             }
         }
     }
     unset($_FILES);
     return $docadded;
 }
  ------------------------------------------------------------------------

  @package   Plugin Monitoring for GLPI
  @author    David Durieux
  @co-author 
  @comment   
  @copyright Copyright (c) 2011-2012 Plugin Monitoring for GLPI team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      https://forge.indepnet.net/projects/monitoring/
  @since     2011

  ------------------------------------------------------------------------
*/
if (!defined('GLPI_ROOT')) {
    define('GLPI_ROOT', '../../..');
}
include GLPI_ROOT . "/inc/includes.php";
PluginMonitoringProfile::checkRight("config", "w");
commonHeader($LANG['plugin_monitoring']['title'][0], $_SERVER["PHP_SELF"], "plugins", "monitoring", "rrdtemplates");
if (isset($_FILES['filename'])) {
    if (strstr($_FILES['filename']['name'], ".json")) {
        if (Document::renameForce($_FILES['filename']['tmp_name'], GLPI_PLUGIN_DOC_DIR . "/monitoring/templates/" . $_FILES['filename']['name'])) {
            addMessageAfterRedirect($LANG['document'][26]);
        }
    }
    glpi_header($_SERVER['HTTP_REFERER']);
}
$pmRrdtool = new PluginMonitoringRrdtool();
$pmRrdtool->addTemplate();
commonFooter();
 function prepareInputForUpdate($input)
 {
     global $LANG;
     $job = new Ticket();
     $forbid_fields = array();
     if ($this->fields["users_id_validate"] == getLoginUserID()) {
         if ($input["status"] == "rejected" && (!isset($input["comment_validation"]) || $input["comment_validation"] == '')) {
             addMessageAfterRedirect($LANG['validation'][29], false, ERROR);
             return false;
         }
         if ($input["status"] == "waiting") {
             //             $input["comment_validation"] = '';
             $input["validation_date"] = 'NULL';
         } else {
             $input["validation_date"] = $_SESSION["glpi_currenttime"];
         }
         $forbid_fields = array('entities_id', 'users_id', 'tickets_id', 'users_id_validate', 'comment_submission', 'submission_date');
     } else {
         if (haveRight('create_validation', 1)) {
             // Update validation request
             $forbid_fields = array('entities_id', 'tickets_id', 'status', 'comment_validation', 'validation_date');
         }
     }
     if (count($forbid_fields)) {
         foreach ($forbid_fields as $key => $val) {
             if (isset($input[$key])) {
                 unset($input[$key]);
             }
         }
     }
     return $input;
 }
Example #7
0
         $splitter = explode("_", $_POST["_my_items"]);
         if (count($splitter) == 2) {
             $_POST["itemtype"] = $splitter[0];
             $_POST["items_id"] = $splitter[1];
         }
     }
     $track->update($_POST);
     Event::log($_POST["id"], "ticket", 4, "tracking", $_SESSION["glpiname"] . " " . $LANG['log'][21]);
     // Copy solution to KB redirect to KB
     if (isset($_POST['_sol_to_kb']) && $_POST['_sol_to_kb']) {
         glpi_header($CFG_GLPI["root_doc"] . "/front/knowbaseitem.form.php?id=new&tickets_id=" . $_POST["id"]);
     } else {
         if ($track->can($_POST["id"], 'r')) {
             glpi_header($CFG_GLPI["root_doc"] . "/front/ticket.form.php?id=" . $_POST["id"]);
         }
         addMessageAfterRedirect($LANG['job'][26], true, ERROR);
         glpi_header($CFG_GLPI["root_doc"] . "/front/ticket.php");
     }
 } else {
     if (isset($_POST['delete'])) {
         $track->check($_POST['id'], 'd');
         $track->delete($_POST);
         Event::log($_POST["id"], "ticket", 4, "tracking", $_SESSION["glpiname"] . " " . $LANG['log'][22]);
         $track->redirectToList();
         /*
         } else if (isset($_POST['add']) || isset($_POST['add_close']) || isset($_POST['add_reopen'])) {
            checkSeveralRightsOr(array('add_followups'     => '1',
                                       'global_add_followups' => '1',
                                       'show_assign_ticket' => '1'));
            $newID = $fup->add($_POST);
            Event::log($_POST["tickets_id"], "ticket", 4, "tracking",
 function prepareInputForAdd($input)
 {
     global $LANG;
     //      $input["_isadmin"] = haveRight("global_add_followups","1");
     $input["_job"] = new Ticket();
     if (!$input["_job"]->getFromDB($input["tickets_id"])) {
         return false;
     }
     // Manage File attached (from mailgate)
     $docadded = $input["_job"]->addFiles($input["tickets_id"]);
     if (count($docadded) > 0) {
         $input['content'] .= "\n";
         foreach ($docadded as $name) {
             $input['content'] .= "\n" . $LANG['mailing'][26] . " {$name}";
         }
     }
     // Pass old assign From Ticket in case of assign change
     //       if (isset($input["_old_assign"])) {
     //          $input["_job"]->fields["_old_assign"] = $input["_old_assign"];
     //       }
     //      if (!isset($input["type"])) {
     //         $input["type"] = "followup";
     //      }
     //      $input["_type"] = $input["type"];
     //      unset($input["type"]);
     $input['_close'] = 0;
     unset($input["add"]);
     if (!isset($input["users_id"]) && ($uid = getLoginUserID())) {
         $input["users_id"] = $uid;
     }
     //      if ($input["_isadmin"] && $input["_type"]!="update") {
     if (isset($input["add_close"])) {
         $input['_close'] = 1;
     }
     unset($input["add_close"]);
     if (isset($input["add_reopen"])) {
         if ($input["content"] == '') {
             addMessageAfterRedirect($LANG['jobresolution'][5], false, ERROR);
             return false;
         }
         $input['_reopen'] = 1;
     }
     unset($input["add_reopen"]);
     //      }
     $input["date"] = $_SESSION["glpi_currenttime"];
     return $input;
 }
                    } else {
                        $mailcollector->deleteOrImportSeveralEmails($emails_ids, 1, $_POST['entities_id']);
                    }
                }
                break;
            default:
                // Plugin specific actions
                $split = explode('_', $_POST["action"]);
                if ($split[0] == 'plugin' && isset($split[1])) {
                    // Normalized name plugin_name_action
                    // Allow hook from any plugin on any (core or plugin) type
                    doOneHook($split[1], 'MassiveActionsProcess', $_POST);
                } else {
                    if ($plug = isPluginItemType($_POST["itemtype"])) {
                        // non-normalized name
                        // hook from the plugin defining the type
                        doOneHook($plug['plugin'], 'MassiveActionsProcess', $_POST);
                    }
                }
        }
        addMessageAfterRedirect($LANG['common'][23]);
        glpi_header($REDIRECT);
    } else {
        //action, itemtype or item not defined
        echo "<div class='center'>" . "<img src='" . $CFG_GLPI["root_doc"] . "/pics/warning.png' alt='warning'><br><br>";
        echo "<b>" . $LANG['common'][24] . "</b></div>";
        displayBackLink();
    }
    commonFooter();
}
// itemtype defined
 function RemoteStartAgent($ID, $ip)
 {
     $ptcm = new PluginFusioninventoryConfigModules();
     $pfia = new PluginFusioninventoryAgents();
     if (!$ptcm->isActivated('remotehttpagent') and !PluginFusioninventory::haveRight("remotecontrol", "w")) {
         return false;
     }
     $pfia->getFromDB($ID);
     if (!($fp = fsockopen($ip, 62354, $errno, $errstr, 1))) {
         $input = 'Agent don\'t respond';
         addMessageAfterRedirect($input);
         return false;
     } else {
         $handle = fopen("http://" . $ip . ":62354/now/" . $pfia->fields['token'], "r");
         $input = 'Agent run Now';
         fclose($fp);
         addMessageAfterRedirect($input);
         return true;
     }
 }
Example #11
0
 /**
  * Cron action on infocom : alert on expired warranty
  *
  * @param $task to log, if NULL use display
  *
  * @return 0 : nothing to do 1 : done with success
  **/
 static function cronInfocom($task = NULL)
 {
     global $DB, $CFG_GLPI, $LANG;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     $message = array();
     $cron_status = 0;
     $items_infos = array();
     $items_messages = array();
     foreach (Entity::getEntitiesToNotify('use_infocoms_alert') as $entity => $value) {
         $query_end = "SELECT `glpi_infocoms`.*\n                       FROM `glpi_infocoms`\n                       LEFT JOIN `glpi_alerts` ON (`glpi_infocoms`.`id` = `glpi_alerts`.`items_id`\n                                                   AND `glpi_alerts`.`itemtype` = 'Infocom'\n                                                   AND `glpi_alerts`.`type`='" . Alert::END . "')\n                       WHERE (`glpi_infocoms`.`alert` & " . pow(2, Alert::END) . ") >'0'\n                             AND `glpi_infocoms`.`entities_id`='" . $entity . "'\n                             AND `glpi_infocoms`.`warranty_duration`>'0'\n                             AND `glpi_infocoms`.`warranty_date` IS NOT NULL\n                             AND DATEDIFF(ADDDATE(`glpi_infocoms`.`warranty_date`,\n                                                  INTERVAL (`glpi_infocoms`.`warranty_duration`) MONTH),\n                                          CURDATE() )<'0'\n                             AND `glpi_alerts`.`date` IS NULL";
         foreach ($DB->request($query_end) as $data) {
             $item_infocom = new $data["itemtype"]();
             if ($item_infocom->getFromDB($data["items_id"])) {
                 $entity = $data['entities_id'];
                 $warranty = getWarrantyExpir($data["warranty_date"], $data["warranty_duration"]);
                 $message = $LANG['mailing'][40] . " " . $item_infocom->getTypeName() . " - " . $item_infocom->getName() . " : " . $warranty . "<br>";
                 $data['warrantyexpiration'] = $warranty;
                 $data['item_name'] = $item_infocom->getName();
                 $items_infos[$entity][$data['id']] = $data;
                 if (!isset($items_messages[$entity])) {
                     $items_messages[$entity] = $LANG['mailing'][40] . "<br />";
                 }
                 $items_messages[$entity] .= $message;
             }
         }
     }
     foreach ($items_infos as $entity => $items) {
         if (NotificationEvent::raiseEvent("alert", new self(), array('entities_id' => $entity, 'items' => $items))) {
             $message = $items_messages[$entity];
             $cron_status = 1;
             if ($task) {
                 $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . ":  {$message}\n");
                 $task->addVolume(1);
             } else {
                 addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . ":  {$message}");
             }
             $alert = new Alert();
             $input["itemtype"] = 'Infocom';
             $input["type"] = Alert::END;
             foreach ($items as $id => $item) {
                 $input["items_id"] = $id;
                 $alert->add($input);
                 unset($alert->fields['id']);
             }
         } else {
             if ($task) {
                 $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . ":  Send infocom alert failed\n");
             } else {
                 addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . ":  Send infocom alert failed", false, ERROR);
             }
         }
     }
     return $cron_status;
 }
 function post_updateItem($history = 1)
 {
     global $DB, $LANG, $CFG_GLPI;
     // Manage changes for OCS if more than 1 element (date_mod)
     // Need dohistory==1 if dohistory==2 no locking fields
     if ($this->fields["is_ocs_import"] && $history == 1 && count($this->updates) > 1) {
         OcsServer::mergeOcsArray($this->fields["id"], $this->updates, "computer_update");
     }
     if (isset($this->input["_auto_update_ocs"])) {
         $query = "UPDATE `glpi_ocslinks`\n                   SET `use_auto_update` = '" . $this->input["_auto_update_ocs"] . "'\n                   WHERE `computers_id` = '" . $this->input["id"] . "'";
         $DB->query($query);
     }
     for ($i = 0; $i < count($this->updates); $i++) {
         // Update contact of attached items
         if (($this->updates[$i] == "contact" || $this->updates[$i] == "contact_num") && $CFG_GLPI["is_contact_autoupdate"]) {
             $items = array('Monitor', 'Peripheral', 'Phone', 'Printer');
             $update_done = false;
             $updates3[0] = "contact";
             $updates3[1] = "contact_num";
             foreach ($items as $t) {
                 $query = "SELECT *\n                         FROM `glpi_computers_items`\n                         WHERE `computers_id` = '" . $this->fields["id"] . "'\n                               AND `itemtype` = '" . $t . "'";
                 if ($result = $DB->query($query)) {
                     $resultnum = $DB->numrows($result);
                     $item = new $t();
                     if ($resultnum > 0) {
                         for ($j = 0; $j < $resultnum; $j++) {
                             $tID = $DB->result($result, $j, "items_id");
                             $item->getFromDB($tID);
                             if (!$item->getField('is_global')) {
                                 if ($item->getField('contact') != $this->fields['contact'] || $item->getField('contact_num') != $this->fields['contact_num']) {
                                     $tmp["id"] = $item->getField('id');
                                     $tmp['contact'] = $this->fields['contact'];
                                     $tmp['contact_num'] = $this->fields['contact_num'];
                                     $item->update($tmp);
                                     $update_done = true;
                                 }
                             }
                         }
                     }
                 }
             }
             if ($update_done) {
                 addMessageAfterRedirect($LANG['computers'][49], true);
             }
         }
         // Update users and groups of attached items
         if ($this->updates[$i] == "users_id" && $this->fields["users_id"] != 0 && $CFG_GLPI["is_user_autoupdate"] || $this->updates[$i] == "groups_id" && $this->fields["groups_id"] != 0 && $CFG_GLPI["is_group_autoupdate"]) {
             $items = array('Monitor', 'Peripheral', 'Phone', 'Printer');
             $update_done = false;
             $updates4[0] = "users_id";
             $updates4[1] = "groups_id";
             foreach ($items as $t) {
                 $query = "SELECT *\n                         FROM `glpi_computers_items`\n                         WHERE `computers_id` = '" . $this->fields["id"] . "'\n                               AND `itemtype` = '" . $t . "'";
                 if ($result = $DB->query($query)) {
                     $resultnum = $DB->numrows($result);
                     $item = new $t();
                     if ($resultnum > 0) {
                         for ($j = 0; $j < $resultnum; $j++) {
                             $tID = $DB->result($result, $j, "items_id");
                             $item->getFromDB($tID);
                             if (!$item->getField('is_global')) {
                                 if ($item->getField('users_id') != $this->fields["users_id"] || $item->getField('groups_id') != $this->fields["groups_id"]) {
                                     $tmp["id"] = $item->getField('id');
                                     if ($CFG_GLPI["is_user_autoupdate"]) {
                                         $tmp["users_id"] = $this->fields["users_id"];
                                     }
                                     if ($CFG_GLPI["is_group_autoupdate"]) {
                                         $tmp["groups_id"] = $this->fields["groups_id"];
                                     }
                                     $item->update($tmp);
                                     $update_done = true;
                                 }
                             }
                         }
                     }
                 }
             }
             if ($update_done) {
                 addMessageAfterRedirect($LANG['computers'][50], true);
             }
         }
         // Update state of attached items
         if ($this->updates[$i] == "states_id" && $CFG_GLPI["state_autoupdate_mode"] < 0) {
             $items = array('Monitor', 'Peripheral', 'Phone', 'Printer');
             $update_done = false;
             foreach ($items as $t) {
                 $query = "SELECT *\n                         FROM `glpi_computers_items`\n                         WHERE `computers_id` = '" . $this->fields["id"] . "'\n                               AND `itemtype` = '" . $t . "'";
                 if ($result = $DB->query($query)) {
                     $resultnum = $DB->numrows($result);
                     $item = new $t();
                     if ($resultnum > 0) {
                         for ($j = 0; $j < $resultnum; $j++) {
                             $tID = $DB->result($result, $j, "items_id");
                             $item->getFromDB($tID);
                             if (!$item->getField('is_global')) {
                                 if ($item->getField('states_id') != $this->fields["states_id"]) {
                                     $tmp["id"] = $item->getField('id');
                                     $tmp["states_id"] = $this->fields["states_id"];
                                     $item->update($tmp);
                                     $update_done = true;
                                 }
                             }
                         }
                     }
                 }
             }
             if ($update_done) {
                 addMessageAfterRedirect($LANG['computers'][56], true);
             }
         }
         // Update loction of attached items
         if ($this->updates[$i] == "locations_id" && $this->fields["locations_id"] != 0 && $CFG_GLPI["is_location_autoupdate"]) {
             $items = array('Monitor', 'Peripheral', 'Phone', 'Printer');
             $update_done = false;
             $updates2[0] = "locations_id";
             foreach ($items as $t) {
                 $query = "SELECT *\n                         FROM `glpi_computers_items`\n                         WHERE `computers_id` = '" . $this->fields["id"] . "'\n                               AND `itemtype` = '" . $t . "'";
                 if ($result = $DB->query($query)) {
                     $resultnum = $DB->numrows($result);
                     $item = new $t();
                     if ($resultnum > 0) {
                         for ($j = 0; $j < $resultnum; $j++) {
                             $tID = $DB->result($result, $j, "items_id");
                             $item->getFromDB($tID);
                             if (!$item->getField('is_global')) {
                                 if ($item->getField('locations_id') != $this->fields["locations_id"]) {
                                     $tmp["id"] = $item->getField('id');
                                     $tmp["locations_id"] = $this->fields["locations_id"];
                                     $item->update($tmp);
                                     $update_done = true;
                                 }
                             }
                         }
                     }
                 }
             }
             if ($update_done) {
                 addMessageAfterRedirect($LANG['computers'][48], true);
             }
         }
     }
 }
 function post_updateItem($history = 1)
 {
     global $DB, $LANG;
     if (in_array('is_helpdesk_default', $this->updates)) {
         if ($this->input["is_helpdesk_default"]) {
             $query = "UPDATE `" . $this->getTable() . "`\n                      SET `is_helpdesk_default` = '0'\n                      WHERE `id` <> '" . $this->input['id'] . "'";
             $DB->query($query);
         } else {
             addMessageAfterRedirect($LANG['setup'][313], true);
         }
     }
     if (in_array('is_mail_default', $this->updates)) {
         if ($this->input["is_mail_default"]) {
             $query = "UPDATE `" . $this->getTable() . "`\n                      SET `is_mail_default` = '0'\n                      WHERE `id` <> '" . $this->input['id'] . "'";
             $DB->query($query);
         } else {
             addMessageAfterRedirect($LANG['setup'][313], true);
         }
     }
 }
 /**
  * @param $params array
  **/
 static function computerImport($params = array())
 {
     if (isset($params['id'])) {
         $notimported = new PluginOcsinventoryngNotimportedcomputer();
         $notimported->getFromDB($params['id']);
         $changes = self::getOcsComputerInfos($notimported->fields);
         if (isset($params['force'])) {
             $result = PluginOcsinventoryngOcsServer::processComputer($notimported->fields['ocsid'], $notimported->fields['plugin_ocsinventoryng_ocsservers_id'], 0, $params['entity'], 0);
         } else {
             $result = PluginOcsinventoryngOcsServer::processComputer($notimported->fields['ocsid'], $notimported->fields['plugin_ocsinventoryng_ocsservers_id']);
         }
         if (in_array($result['status'], array(PluginOcsinventoryngOcsServer::COMPUTER_IMPORTED, PluginOcsinventoryngOcsServer::COMPUTER_LINKED, PluginOcsinventoryngOcsServer::COMPUTER_SYNCHRONIZED))) {
             $notimported->delete(array('id' => $params['id']));
             //If serial has been changed in order to import computer
             if (in_array('serial', $changes)) {
                 PluginOcsinventoryngOcsServer::mergeOcsArray($result['computers_id'], array('serial'), "computer_update");
             }
             addMessageAfterRedirect(__('Model'));
             return true;
         }
         $tmp = $notimported->fields;
         $tmp['reason'] = $result['status'];
         if (isset($result['entities_id'])) {
             $tmp["entities_id"] = $result['entities_id'];
         } else {
             $tmp['entities_id'] = 0;
         }
         $tmp["rules_id"] = json_encode($result['rule_matched']);
         $notimported->update($tmp);
         return false;
     }
 }
 /**
  * Perform checks to be sure that an itemtype and at least a field are selected
  *
  * @param input the values to insert in DB
  *
  * @return input the values to insert, but modified
  **/
 static function checkBeforeInsert($input)
 {
     global $LANG;
     if (!$input['itemtype'] || empty($input['_fields'])) {
         addMessageAfterRedirect($LANG['setup'][817], true, ERROR);
         $input = array();
     } else {
         $input['fields'] = implode(',', $input['_fields']);
         unset($input['_fields']);
     }
     return $input;
 }
 function sendNotification($options = array())
 {
     global $LANG;
     $mmail = new self();
     $mmail->AddCustomHeader("Auto-Submitted: auto-generated");
     $mmail->SetFrom($options['from'], $options['fromname']);
     if ($options['replyto']) {
         $mmail->AddReplyTo($options['replyto'], $options['replytoname']);
     }
     $mmail->Subject = $options['subject'];
     if (empty($options['content_html'])) {
         $mmail->isHTML(false);
         $mmail->Body = $options['content_text'];
     } else {
         $mmail->isHTML(true);
         $mmail->Body = $options['content_html'];
         $mmail->AltBody = $options['content_text'];
     }
     $mmail->AddAddress($options['to'], $options['toname']);
     $mmail->MessageID = "<GLPI-" . $options["items_id"] . "." . time() . "." . rand() . "@" . php_uname('n') . ">";
     $messageerror = $LANG['mailing'][47];
     if (!$mmail->Send()) {
         $senderror = true;
         addMessageAfterRedirect($messageerror . "<br>" . $mmail->ErrorInfo, true);
     } else {
         logInFile("mail", $LANG['tracking'][38] . " " . $options['to'] . " : " . $options['subject'] . "\n");
     }
     $mmail->ClearAddresses();
     return true;
 }
 /**
  * Check field unicity before insert or update
  *
  * @param add true for insert, false for update
  * @param $options array
  *
  * @return true if item can be written in DB, false if not
  **/
 function checkUnicity($add = false, $options = array())
 {
     global $LANG, $DB, $CFG_GLPI;
     $p['unicity_error_message'] = true;
     $p['add_event_on_duplicate'] = true;
     $p['disable_unicity_check'] = false;
     if (is_array($options) && count($options)) {
         foreach ($options as $key => $value) {
             $p[$key] = $value;
         }
     }
     $result = true;
     //Do not check unicity when creating infocoms or if checking is expliclty disabled
     if ($p['disable_unicity_check']) {
         return $result;
     }
     //Get all checks for this itemtype and this entity
     if (in_array(get_class($this), $CFG_GLPI["unicity_types"])) {
         // Get input entities if set / else get object one
         if (isset($this->input['entities_id'])) {
             $entities_id = $this->input['entities_id'];
         } else {
             $entities_id = $this->fields['entities_id'];
         }
         $all_fields = FieldUnicity::getUnicityFieldsConfig(get_class($this), $entities_id);
         foreach ($all_fields as $key => $fields) {
             //If there's fields to check
             if (!empty($fields) && !empty($fields['fields'])) {
                 $where = "";
                 $continue = true;
                 foreach (explode(',', $fields['fields']) as $field) {
                     if (isset($this->input[$field]) && (getTableNameForForeignKeyField($field) == '' && $this->input[$field] != '' || getTableNameForForeignKeyField($field) != '' && $this->input[$field] > 0) && !Fieldblacklist::isFieldBlacklisted(get_class($this), $entities_id, $field, $this->input[$field])) {
                         $where .= " AND `" . $this->getTable() . "`.`{$field}` = '" . $this->input[$field] . "'";
                     } else {
                         $continue = false;
                     }
                 }
                 if ($continue && $where != '') {
                     $entities = $fields['entities_id'];
                     if ($fields['is_recursive']) {
                         $entities = getSonsOf('glpi_entities', $fields['entities_id']);
                     }
                     $where_global = getEntitiesRestrictRequest(" AND", $this->getTable(), '', $entities);
                     //If update, exclude ID of the current object
                     if (!$add) {
                         $where .= " AND `" . $this->getTable() . "`.`id` NOT IN (" . $this->input['id'] . ") ";
                     }
                     if (countElementsInTable($this->table, "1 {$where} {$where_global}") > 0) {
                         if ($p['unicity_error_message'] || $p['add_event_on_duplicate']) {
                             $message = array();
                             foreach (explode(',', $fields['fields']) as $field) {
                                 $table = getTableNameForForeignKeyField($field);
                                 if ($table != '') {
                                     $searchOption = $this->getSearchOptionByField('field', 'name', $table);
                                 } else {
                                     $searchOption = $this->getSearchOptionByField('field', $field);
                                 }
                                 $message[] = $searchOption['name'] . '=' . $this->input[$field];
                             }
                             $doubles = getAllDatasFromTable($this->table, "1 {$where} {$where_global}");
                             $message_text = $this->getUncityErrorMessage($message, $fields, $doubles);
                             if ($p['unicity_error_message']) {
                                 if (!$fields['action_refuse']) {
                                     $show_other_messages = $fields['action_refuse'] ? true : false;
                                 } else {
                                     $show_other_messages = true;
                                 }
                                 addMessageAfterRedirect($message_text, true, $show_other_messages, $show_other_messages);
                             }
                             if ($p['add_event_on_duplicate']) {
                                 Event::log(!$add ? $this->fields['id'] : 0, get_class($this), 4, 'inventory', $_SESSION["glpiname"] . " " . $LANG['log'][123] . ' : ' . $message_text);
                             }
                         }
                         if ($fields['action_refuse']) {
                             $result = false;
                         }
                         if ($fields['action_notify']) {
                             $params = array('message' => html_clean($message_text), 'action_type' => $add, 'action_user' => getUserName(getLoginUserID()), 'entities_id' => $entities_id, 'itemtype' => get_class($this), 'date' => $_SESSION['glpi_currenttime'], 'refuse' => $fields['action_refuse']);
                             NotificationEvent::raiseEvent('refuse', new FieldUnicity(), $params);
                         }
                     }
                 }
             }
         }
     }
     return $result;
 }
 /**
  * Find a valid path for the new file
  *
  * @param $dir dir to search a free path for the file
  * @param $sha1sum SHA1 of the file
  *
  * @return nothing
  **/
 static function getUploadFileValidLocationName($dir, $sha1sum)
 {
     global $CFG_GLPI, $LANG;
     if (empty($dir)) {
         $message = $LANG['document'][32];
         if (haveRight('dropdown', 'r')) {
             $dt = new DocumentType();
             $message .= " <a target='_blank' href='" . $dt->getSearchURL() . "'>\n                         <img src=\"" . $CFG_GLPI["root_doc"] . "/pics/aide.png\"></a>";
         }
         addMessageAfterRedirect($message, false, ERROR);
         return '';
     }
     if (!is_dir(GLPI_DOC_DIR)) {
         addMessageAfterRedirect($LANG['document'][31] . " " . GLPI_DOC_DIR, false, ERROR);
         return '';
     }
     $subdir = $dir . '/' . substr($sha1sum, 0, 2);
     if (!is_dir(GLPI_DOC_DIR . "/" . $subdir) && @mkdir(GLPI_DOC_DIR . "/" . $subdir, 0777, true)) {
         addMessageAfterRedirect($LANG['document'][34] . " " . GLPI_DOC_DIR . "/" . $subdir);
     }
     if (!is_dir(GLPI_DOC_DIR . "/" . $subdir)) {
         addMessageAfterRedirect($LANG['document'][29] . " " . GLPI_DOC_DIR . "/" . $subdir . " " . $LANG['document'][30], false, ERROR);
         return '';
     }
     return $subdir . '/' . substr($sha1sum, 2) . '.' . $dir;
 }
 /**
  * Cron action on softwares : alert on expired licences
  *
  * @param $task to log, if NULL display
  *
  * @return 0 : nothing to do 1 : done with success
  **/
 static function cronSoftware($task = NULL)
 {
     global $DB, $CFG_GLPI, $LANG;
     $cron_status = 1;
     if (!$CFG_GLPI['use_mailing']) {
         return 0;
     }
     $message = array();
     $items_notice = array();
     $items_end = array();
     foreach (Entity::getEntitiesToNotify('use_licenses_alert') as $entity => $value) {
         // Check licenses
         $query = "SELECT `glpi_softwarelicenses`.*,\n                          `glpi_softwares`.`name` AS softname\n                   FROM `glpi_softwarelicenses`\n                   INNER JOIN `glpi_softwares`\n                        ON (`glpi_softwarelicenses`.`softwares_id` = `glpi_softwares`.`id`)\n                   LEFT JOIN `glpi_alerts`\n                        ON (`glpi_softwarelicenses`.`id` = `glpi_alerts`.`items_id`\n                            AND `glpi_alerts`.`itemtype` = 'SoftwareLicense'\n                            AND `glpi_alerts`.`type` = '" . Alert::END . "')\n                   WHERE `glpi_alerts`.`date` IS NULL\n                         AND `glpi_softwarelicenses`.`expire` IS NOT NULL\n                         AND `glpi_softwarelicenses`.`expire` < CURDATE()\n                         AND `glpi_softwares`.`is_template` = '0'\n                         AND `glpi_softwares`.`is_deleted` = '0'\n                         AND `glpi_softwares`.`entities_id` = '" . $entity . "'";
         $message = "";
         $items = array();
         foreach ($DB->request($query) as $license) {
             $name = $license['softname'] . ' - ' . $license['name'] . ' - ' . $license['serial'];
             $message .= $LANG['mailing'][51] . " " . $name . ": " . convDate($license["expire"]) . "<br>\n";
             $items[$license['id']] = $license;
         }
         if (!empty($items)) {
             $alert = new Alert();
             $options['entities_id'] = $entity;
             $options['licenses'] = $items;
             if (NotificationEvent::raiseEvent('alert', new SoftwareLicense(), $options)) {
                 if ($task) {
                     $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . " :  {$message}\n");
                     $task->addVolume(1);
                 } else {
                     addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . " :  {$message}");
                 }
                 $input["type"] = Alert::END;
                 $input["itemtype"] = 'SoftwareLicense';
                 // add alerts
                 foreach ($items as $ID => $consumable) {
                     $input["items_id"] = $ID;
                     $alert->add($input);
                     unset($alert->fields['id']);
                 }
             } else {
                 if ($task) {
                     $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . " : Send licenses alert failed\n");
                 } else {
                     addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . " : Send licenses alert failed", false, ERROR);
                 }
             }
         }
     }
     return $cron_status;
 }
 /**
  * Cron action on cartridges : alert if a stock is behind the threshold
  *
  * @param $task for log, display informations if NULL?
  *
  * @return 0 : nothing to do 1 : done with success
  *
  **/
 static function cronCartridge($task = NULL)
 {
     global $DB, $CFG_GLPI, $LANG;
     $cron_status = 1;
     if ($CFG_GLPI["use_mailing"]) {
         $message = array();
         $alert = new Alert();
         foreach (Entity::getEntitiesToNotify('cartridges_alert_repeat') as $entity => $repeat) {
             // if you change this query, please don't forget to also change in showDebug()
             $query_alert = "SELECT `glpi_cartridgeitems`.`id` AS cartID,\n                                   `glpi_cartridgeitems`.`entities_id` AS entity,\n                                   `glpi_cartridgeitems`.`ref` AS cartref,\n                                   `glpi_cartridgeitems`.`name` AS cartname,\n                                   `glpi_cartridgeitems`.`alarm_threshold` AS threshold,\n                                   `glpi_alerts`.`id` AS alertID,\n                                   `glpi_alerts`.`date`\n                            FROM `glpi_cartridgeitems`\n                            LEFT JOIN `glpi_alerts`\n                                 ON (`glpi_cartridgeitems`.`id` = `glpi_alerts`.`items_id`\n                                     AND `glpi_alerts`.`itemtype` = 'CartridgeItem')\n                            WHERE `glpi_cartridgeitems`.`is_deleted` = '0'\n                                  AND `glpi_cartridgeitems`.`alarm_threshold` >= '0'\n                                  AND `glpi_cartridgeitems`.`entities_id` = '" . $entity . "'\n                                  AND (`glpi_alerts`.`date` IS NULL\n                                       OR (`glpi_alerts`.date+{$repeat}) < CURRENT_TIMESTAMP());";
             $message = "";
             $items = array();
             foreach ($DB->request($query_alert) as $cartridge) {
                 if (($unused = Cartridge::getUnusedNumber($cartridge["cartID"])) <= $cartridge["threshold"]) {
                     // define message alert
                     $message .= $LANG['mailing'][35] . " " . $cartridge["cartname"] . " - " . $LANG['consumables'][2] . "&nbsp;: " . $cartridge["cartref"] . " - " . $LANG['software'][20] . "&nbsp;: " . $unused . "<br>";
                     $items[$cartridge["cartID"]] = $cartridge;
                     // if alert exists -> delete
                     if (!empty($cartridge["alertID"])) {
                         $alert->delete(array("id" => $cartridge["alertID"]));
                     }
                 }
             }
             if (!empty($items)) {
                 $options['entities_id'] = $entity;
                 $options['cartridges'] = $items;
                 if (NotificationEvent::raiseEvent('alert', new Cartridge(), $options)) {
                     if ($task) {
                         $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . "&nbsp;:  {$message}\n");
                         $task->addVolume(1);
                     } else {
                         addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . "&nbsp;:  {$message}");
                     }
                     $input["type"] = Alert::THRESHOLD;
                     $input["itemtype"] = 'CartridgeItem';
                     // add alerts
                     foreach ($items as $ID => $consumable) {
                         $input["items_id"] = $ID;
                         $alert->add($input);
                         unset($alert->fields['id']);
                     }
                 } else {
                     if ($task) {
                         $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . "&nbsp;: Send cartidge alert failed\n");
                     } else {
                         addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . "&nbsp;: Send cartidge alert failed", false, ERROR);
                     }
                 }
             }
         }
     }
 }
Example #21
0
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
include_once dirname(__FILE__) . '/../../lib/common.php';
$table = $_GET['inputTable'];
if (!in_array($table, $config['allowed_modals'])) {
    stopSession();
}
$champsId = $_GET['inputChamps'];
$id = $_GET['input' . $champsId];
eval("\$target = new {$table}();");
$ligne = $target->getFromID($id);
if ($ligne !== FALSE && $target->canEdit()) {
    if ($target->delete($id) !== FALSE) {
        addMessageAfterRedirect("ID {$id} Supprimé");
    } else {
        addMessageAfterRedirect("ID {$id} non Supprimé, action non autorisée", 'warning');
    }
} else {
    addMessageAfterRedirect("ID {$id} non Supprimé, action non autorisée", 'warning');
}
Example #22
0
if (!isset($_GET['id'])) {
    $_GET['id'] = "";
}
//LDAP Server add/update/delete
if (isset($_POST["update"])) {
    $config_ldap->update($_POST);
    glpi_header($_SERVER['HTTP_REFERER']);
} else {
    if (isset($_POST["add"])) {
        //If no name has been given to this configuration, then go back to the page without adding
        if ($_POST["name"] != "") {
            if ($newID = $config_ldap->add($_POST)) {
                if (AuthLdap::testLDAPConnection($newID)) {
                    addMessageAfterRedirect($LANG['login'][22]);
                } else {
                    addMessageAfterRedirect($LANG['login'][23], false, ERROR);
                }
                glpi_header($CFG_GLPI["root_doc"] . "/front/authldap.php?next=extauth_ldap&id=" . $newID);
            }
        }
        glpi_header($_SERVER['HTTP_REFERER']);
    } else {
        if (isset($_POST["delete"])) {
            $config_ldap->delete($_POST);
            $_SESSION['glpi_authconfig'] = 1;
            $config_ldap->redirectToList();
        } else {
            if (isset($_POST["test_ldap"])) {
                $ldap = new AuthLDAP();
                $ldap->getFromDB($_POST["id"]);
                if (AuthLdap::testLDAPConnection($_POST["id"])) {
 /**
  * Constructor
  *
  * @param $mailgateID ID of the mailgate
  * @param $display display messages in MessageAfterRedirect or just return error
  *
  * @return if $display = false return messages result string
  **/
 function collect($mailgateID, $display = 0)
 {
     global $LANG, $CFG_GLPI;
     if ($this->getFromDB($mailgateID)) {
         $this->mid = -1;
         $this->fetch_emails = 0;
         //Connect to the Mail Box
         $this->connect();
         $rejected = new NotImportedEmail();
         // Clean from previous collect (from GUI, cron already truncate the table)
         $rejected->deleteByCriteria(array('mailcollectors_id' => $this->fields['id']));
         if ($this->marubox) {
             // Get Total Number of Unread Email in mail box
             $tot = $this->getTotalMails();
             //Total Mails in Inbox Return integer value
             $error = 0;
             $refused = 0;
             for ($i = 1; $i <= $tot && $this->fetch_emails < $this->maxfetch_emails; $i++) {
                 $tkt = $this->buildTicket($i, array('mailgates_id' => $mailgateID, 'play_rules' => true));
                 //Indicates that the mail must be deleted from the mailbox
                 $delete_mail = false;
                 //If entity assigned, or email refused by rule, or no user associated with the email
                 $user_condition = $CFG_GLPI["use_anonymous_helpdesk"] || isset($tkt['_users_id_requester']) && $tkt['_users_id_requester'] > 0;
                 // Manage blacklisted emails
                 if (isset($tkt['_blacklisted']) && $tkt['_blacklisted']) {
                     $this->deleteMails($i);
                     // entities_id set when new ticket / tickets_id when new followup
                 } else {
                     if ((isset($tkt['entities_id']) || isset($tkt['tickets_id'])) && $user_condition || isset($tkt['_refuse_email_no_response']) || isset($tkt['_refuse_email_with_response'])) {
                         if (isset($tkt['_refuse_email_with_response'])) {
                             $this->sendMailRefusedResponse($tkt['_head']['from'], $tkt['name']);
                             $delete_mail = true;
                             $refused++;
                         } else {
                             if (isset($tkt['_refuse_email_no_response'])) {
                                 $delete_mail = true;
                                 $refused++;
                             } else {
                                 if (isset($tkt['entities_id']) || isset($tkt['tickets_id'])) {
                                     $tkt['_mailgate'] = $mailgateID;
                                     $result = imap_fetchheader($this->marubox, $i);
                                     // Is a mail responding of an already existgin ticket ?
                                     if (isset($tkt['tickets_id'])) {
                                         // Deletion of message with sucess
                                         if (false === is_array($result)) {
                                             $fup = new TicketFollowup();
                                             if ($fup->add($tkt)) {
                                                 $delete_mail = true;
                                             }
                                         } else {
                                             $error++;
                                         }
                                     } else {
                                         // New ticket
                                         // Deletion of message with sucess
                                         if (false === is_array($result)) {
                                             $track = new Ticket();
                                             if ($track->add($tkt)) {
                                                 $delete_mail = true;
                                             }
                                         } else {
                                             $error++;
                                         }
                                     }
                                 } else {
                                     // Case never raise
                                     $delete_mail = true;
                                     $refused++;
                                 }
                             }
                         }
                         //Delete Mail from Mail box if ticket is added successfully
                         if ($delete_mail) {
                             $this->deleteMails($i);
                         }
                     } else {
                         $input = array();
                         $input['mailcollectors_id'] = $mailgateID;
                         $input['from'] = $tkt['_head']['from'];
                         $input['to'] = $tkt['_head']['to'];
                         if (!$tkt['_users_id_requester']) {
                             $input['reason'] = NotImportedEmail::USER_UNKNOWN;
                         } else {
                             $input['reason'] = NotImportedEmail::MATCH_NO_RULE;
                         }
                         $input['users_id'] = $tkt['_users_id_requester'];
                         $input['subject'] = $this->textCleaner($tkt['_head']['subject']);
                         $input['messageid'] = $tkt['_head']['message_id'];
                         $input['date'] = $_SESSION["glpi_currenttime"];
                         $rejected->add($input);
                     }
                 }
                 $this->fetch_emails++;
             }
             imap_expunge($this->marubox);
             $this->close_mailbox();
             //Close Mail Box
             if ($display) {
                 if ($error == 0) {
                     addMessageAfterRedirect($LANG['mailgate'][3] . "&nbsp;: " . $this->fetch_emails);
                 } else {
                     addMessageAfterRedirect($LANG['mailgate'][3] . "&nbsp;: " . $this->fetch_emails . " ({$error} " . $LANG['common'][63] . ")", false, ERROR);
                 }
             } else {
                 return "Number of messages: available={$tot}, collected=" . $this->fetch_emails . ($error > 0 ? " ({$error} error(s))" : "" . ($refused > 0 ? " ({$refused} refused)" : ""));
             }
         } else {
             if ($display) {
                 addMessageAfterRedirect($LANG['log'][41], false, ERROR);
             } else {
                 return "Could not connect to mailgate server";
             }
         }
     } else {
         if ($display) {
             addMessageAfterRedirect($LANG['common'][54] . "&nbsp;: mailgate " . $mailgateID, false, ERROR);
         } else {
             return 'Could find mailgate ' . $mailgateID;
         }
     }
 }
Example #24
0
--------------------------------------------------------------------------
*/
// ----------------------------------------------------------------------
// Original Author of file: Remi Collet
// Purpose of file: Search engine from cron tasks
// ----------------------------------------------------------------------
define('GLPI_ROOT', '..');
include GLPI_ROOT . "/inc/includes.php";
checkRight("config", "w");
if (isset($_GET['execute'])) {
    if (is_numeric($_GET['execute'])) {
        // Execute button from list.
        $name = CronTask::launch(CronTask::MODE_INTERNAL, intval($_GET['execute']));
    } else {
        // Execute button from Task form (force)
        $name = CronTask::launch(-CronTask::MODE_INTERNAL, 1, $_GET['execute']);
    }
    if ($name) {
        addMessageAfterRedirect($LANG['crontask'][40] . " : " . $name);
    }
    glpi_header($_SERVER['HTTP_REFERER']);
}
commonHeader($LANG['crontask'][0], $_SERVER['PHP_SELF'], "config", "crontask");
$crontask = new CronTask();
if ($crontask->getNeedToRun(CronTask::MODE_INTERNAL)) {
    displayTitle(GLPI_ROOT . '/pics/warning.png', $LANG['crontask'][41], $LANG['crontask'][41] . "&nbsp;: " . $crontask->fields['name'], array($_SERVER['PHP_SELF'] . "?execute=1" => $LANG['buttons'][57]));
} else {
    displayTitle(GLPI_ROOT . '/pics/ok.png', $LANG['crontask'][43], $LANG['crontask'][43]);
}
Search::show('CronTask');
commonFooter();
 /**
  * Import a user from ldap
  * Check all the directories. When the user is found, then import it
  * @param $options array containing condition :
  *
  *          array('name'=>'glpi') or array('email' => 'test at test.com')
  **/
 static function importUserFromServers($options = array())
 {
     global $LANG;
     $auth = new Auth();
     $params = array();
     if (isset($options['name'])) {
         $params['value'] = $options['name'];
         $params['method'] = self::IDENTIFIER_LOGIN;
     }
     if (isset($options['email'])) {
         $params['value'] = $options['email'];
         $params['method'] = self::IDENTIFIER_EMAIL;
     }
     $auth->user_present = $auth->userExists($options);
     //If the user does not exists
     if ($auth->user_present == 0) {
         $auth->getAuthMethods();
         $ldap_methods = $auth->authtypes["ldap"];
         $userid = -1;
         foreach ($ldap_methods as $ldap_method) {
             if ($ldap_method['is_active']) {
                 $result = self::ldapImportUserByServerId($params, 0, $ldap_method["id"], true);
                 if ($result != false) {
                     return $result;
                 }
             }
         }
         addMessageAfterRedirect($LANG['login'][15], false, ERROR);
     } else {
         addMessageAfterRedirect($LANG['setup'][606], false, ERROR);
     }
     return false;
 }
    }
}
if (isset($_POST["_my_items"]) && !empty($_POST["_my_items"])) {
    $splitter = explode("_", $_POST["_my_items"]);
    if (count($splitter) == 2) {
        $_POST["itemtype"] = $splitter[0];
        $_POST["items_id"] = $splitter[1];
    }
}
if (!isset($_POST["itemtype"]) || empty($_POST["items_id"]) && $_POST["itemtype"] != 0) {
    $_POST["itemtype"] = '';
    $_POST["items_id"] = 0;
}
if ($newID = $track->add($_POST)) {
    if (isset($_POST["type"]) && $_POST["type"] == "Helpdesk") {
        echo "<div class='center'>" . $LANG['help'][18] . "<br><br>";
        displayBackLink();
        echo "</div>";
    } else {
        echo "<div class='center b spaced'>";
        echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/ok.png' alt='OK'></div>";
        addMessageAfterRedirect($LANG['help'][19]);
        displayMessageAfterRedirect();
    }
} else {
    echo "<div class='center'>";
    echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/warning.png' alt='warning'><br></div>";
    displayMessageAfterRedirect();
    displayBackLink();
}
nullFooter();
 /**
  * Check already planned user for a period
  *
  * @param $users_id user id
  * @param $begin begin date
  * @param $end end date
  * @param $except array of items which not be into account array('Reminder'=>array(1,2,id_of_items))
  **/
 static function checkAlreadyPlanned($users_id, $begin, $end, $except = array())
 {
     global $CFG_GLPI, $LANG;
     $planned = false;
     $message = '';
     foreach ($CFG_GLPI['planning_types'] as $itemtype) {
         $data = call_user_func(array($itemtype, 'populatePlanning'), array('who' => $users_id, 'who_group' => 0, 'begin' => $begin, 'end' => $end));
         if (count($data) && method_exists($itemtype, 'getAlreadyPlannedInformation')) {
             foreach ($data as $key => $val) {
                 if (!isset($except[$itemtype]) || is_array($except[$itemtype]) && !in_array($val['id'], $except[$itemtype])) {
                     $planned = true;
                     $message .= '- ' . call_user_func(array($itemtype, 'getAlreadyPlannedInformation'), $val) . '<br>';
                 }
             }
         }
     }
     if ($planned) {
         addMessageAfterRedirect($LANG['planning'][2] . '<br>' . $message, false, ERROR);
     }
     return $planned;
 }
 function post_addItem()
 {
     global $DB, $LANG;
     // Get netpoint for $sport and $dport
     $sport = $this->fields['networkports_id_1'];
     $dport = $this->fields['networkports_id_2'];
     $ps = new NetworkPort();
     if (!$ps->getFromDB($sport)) {
         return false;
     }
     $pd = new NetworkPort();
     if (!$pd->getFromDB($dport)) {
         return false;
     }
     // Check netpoint for copy
     $source = "";
     $destination = "";
     if (isset($ps->fields['netpoints_id']) && $ps->fields['netpoints_id'] != 0) {
         $source = $ps->fields['netpoints_id'];
     }
     if (isset($pd->fields['netpoints_id']) && $pd->fields['netpoints_id'] != 0) {
         $destination = $pd->fields['netpoints_id'];
     }
     // Update Item
     $updates[0] = 'netpoints_id';
     if (empty($source) && !empty($destination)) {
         $ps->fields['netpoints_id'] = $destination;
         $ps->updateInDB($updates);
         addMessageAfterRedirect($LANG['connect'][15] . "&nbsp;:&nbsp;" . $LANG['networking'][51]);
     } else {
         if (!empty($source) && empty($destination)) {
             $pd->fields['netpoints_id'] = $source;
             $pd->updateInDB($updates);
             addMessageAfterRedirect($LANG['connect'][15] . "&nbsp;:&nbsp;" . $LANG['networking'][51]);
         } else {
             if ($source != $destination) {
                 addMessageAfterRedirect($LANG['connect'][16] . "&nbsp;:&nbsp;" . $LANG['networking'][51]);
             }
         }
     }
     // Manage VLAN : use networkings one as defaults
     $npnet = -1;
     $npdev = -1;
     if ($ps->fields["itemtype"] != 'NetworkEquipment' && $pd->fields["itemtype"] == 'NetworkEquipment') {
         $npnet = $dport;
         $npdev = $sport;
     }
     if ($pd->fields["itemtype"] != 'NetworkEquipment' && $ps->fields["itemtype"] == 'NetworkEquipment') {
         $npnet = $sport;
         $npdev = $dport;
     }
     if ($npnet > 0 && $npdev > 0) {
         // Get networking VLAN
         // Unset MAC and IP from networking device
         $query = "SELECT *\n                   FROM `glpi_networkports_vlans`\n                   WHERE `networkports_id` = '{$npnet}'";
         if ($result = $DB->query($query)) {
             if ($DB->numrows($result) > 0) {
                 // Found VLAN : clean vlan device and add found ones
                 $query = "DELETE\n                         FROM `glpi_networkports_vlans`\n                         WHERE `networkports_id` = '{$npdev}' ";
                 $DB->query($query);
                 while ($data = $DB->fetch_array($result)) {
                     $query = "INSERT INTO `glpi_networkports_vlans`\n                                   (`networkports_id`, `vlans_id`)\n                            VALUES ('{$npdev}', '" . $data['vlans_id'] . "')";
                     $DB->query($query);
                 }
             }
         }
     }
     // end manage VLAN
     // Manage History
     $sourcename = NOT_AVAILABLE;
     $destname = NOT_AVAILABLE;
     $sourcehistory = false;
     $desthistory = false;
     if (class_exists($ps->fields['itemtype'])) {
         $sourceitem = new $ps->fields['itemtype']();
         if ($sourceitem->getFromDB($ps->fields['items_id'])) {
             $sourcename = $sourceitem->getName();
             $sourcehistory = $sourceitem->dohistory;
         }
     }
     if (class_exists($pd->fields['itemtype'])) {
         $destitem = new $pd->fields['itemtype']();
         if ($destitem->getFromDB($pd->fields['items_id'])) {
             $destname = $destitem->getName();
             $desthistory = $destitem->dohistory;
         }
     }
     $changes[0] = 0;
     $changes[1] = "";
     if ($sourcehistory) {
         $changes[2] = $destname;
         if ($ps->fields["itemtype"] == 'NetworkEquipment') {
             $changes[2] = "#" . $ps->fields["name"] . " > " . $changes[2];
         }
         if ($pd->fields["itemtype"] == 'NetworkEquipment') {
             $changes[2] = $changes[2] . " > #" . $pd->fields["name"];
         }
         Log::history($ps->fields["items_id"], $ps->fields["itemtype"], $changes, $pd->fields["itemtype"], HISTORY_CONNECT_DEVICE);
     }
     if ($desthistory) {
         $changes[2] = $sourcename;
         if ($pd->fields["itemtype"] == 'NetworkEquipment') {
             $changes[2] = "#" . $pd->fields["name"] . " > " . $changes[2];
         }
         if ($ps->fields["itemtype"] == 'NetworkEquipment') {
             $changes[2] = $changes[2] . " > #" . $ps->fields["name"];
         }
         Log::history($pd->fields["items_id"], $pd->fields["itemtype"], $changes, $ps->fields["itemtype"], HISTORY_CONNECT_DEVICE);
     }
 }
Example #29
0
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
include_once dirname(__FILE__) . '/../../lib/common.php';
$table = $_GET['inputTable'];
if (!in_array($table, $config['allowed_modals'])) {
    stopSession();
}
$id = FALSE;
eval("\$target = new {$table}();");
$insert = array();
if ($target->canEdit()) {
    $colonnes = $target->getColumns();
    foreach ($colonnes as $col) {
        if (isset($_GET[$col])) {
            $insert[$col] = $_GET[$col];
        }
    }
    if (sizeof($insert) > 0) {
        //@todo gérer le cas id inserable
        $id = $target->insert($insert);
        if ($id !== FALSE && $id !== "0") {
            addMessageAfterRedirect("ID {$id} Inséré");
        } else {
            addMessageAfterRedirect("Pas de modification, il semble que vous essayez d'insérer un doublon ou bien il ya une erreur interne", 'warning');
        }
    }
}
/**
 * Check if new version is available
 *
 * @param $auto boolean: check done autically ? (if not display result)
 * @param $messageafterredirect boolean: use message after redirect instead of display
 *
 * @return string explaining the result
**/
function checkNewVersionAvailable($auto = true, $messageafterredirect = false)
{
    global $LANG, $CFG_GLPI;
    if (!$auto && !haveRight("check_update", "r")) {
        return false;
    }
    if (!$auto && !$messageafterredirect) {
        echo "<br>";
    }
    $error = "";
    $latest_version = getURLContent("http://glpi-project.org/latest_version", $error);
    if (strlen(trim($latest_version)) == 0) {
        if (!$auto) {
            if ($messageafterredirect) {
                addMessageAfterRedirect($error, true, ERROR);
            } else {
                echo "<div class='center'>{$error}</div>";
            }
        } else {
            return $error;
        }
    } else {
        $splitted = explode(".", trim($CFG_GLPI["version"]));
        if ($splitted[0] < 10) {
            $splitted[0] .= "0";
        }
        if ($splitted[1] < 10) {
            $splitted[1] .= "0";
        }
        $cur_version = $splitted[0] * 10000 + $splitted[1] * 100;
        if (isset($splitted[2])) {
            if ($splitted[2] < 10) {
                $splitted[2] .= "0";
            }
            $cur_version += $splitted[2];
        }
        $splitted = explode(".", trim($latest_version));
        if ($splitted[0] < 10) {
            $splitted[0] .= "0";
        }
        if ($splitted[1] < 10) {
            $splitted[1] .= "0";
        }
        $lat_version = $splitted[0] * 10000 + $splitted[1] * 100;
        if (isset($splitted[2])) {
            if ($splitted[2] < 10) {
                $splitted[2] .= "0";
            }
            $lat_version += $splitted[2];
        }
        if ($cur_version < $lat_version) {
            $config_object = new Config();
            $input["id"] = 1;
            $input["founded_new_version"] = $latest_version;
            $config_object->update($input);
            if (!$auto) {
                if ($messageafterredirect) {
                    addMessageAfterRedirect($LANG['setup'][301] . " " . $latest_version . $LANG['setup'][302]);
                } else {
                    echo "<div class='center'>" . $LANG['setup'][301] . " " . $latest_version . "</div>";
                    echo "<div class='center'>" . $LANG['setup'][302] . "</div>";
                }
            } else {
                if ($messageafterredirect) {
                    addMessageAfterRedirect($LANG['setup'][301] . " " . $latest_version);
                } else {
                    return $LANG['setup'][301] . " " . $latest_version;
                }
            }
        } else {
            if (!$auto) {
                if ($messageafterredirect) {
                    addMessageAfterRedirect($LANG['setup'][303]);
                } else {
                    echo "<div class='center'>" . $LANG['setup'][303] . "</div>";
                }
            } else {
                if ($messageafterredirect) {
                    addMessageAfterRedirect($LANG['setup'][303]);
                } else {
                    return $LANG['setup'][303];
                }
            }
        }
    }
    return 1;
}