function glpiautoload($classname)
 {
     global $DEBUG_AUTOLOAD, $CFG_GLPI;
     static $notfound = array();
     // empty classname or non concerted plugin
     if (empty($classname) || is_numeric($classname)) {
         return FALSE;
     }
     $dir = GLPI_ROOT . "/inc/";
     //$classname="PluginExampleProfile";
     if ($plug = isPluginItemType($classname)) {
         $plugname = strtolower($plug['plugin']);
         $dir = GLPI_ROOT . "/plugins/{$plugname}/inc/";
         $item = strtolower($plug['class']);
         // Is the plugin activate ?
         // Command line usage of GLPI : need to do a real check plugin activation
         if (isCommandLine()) {
             $plugin = new Plugin();
             if (count($plugin->find("directory='{$plugname}' AND state=" . Plugin::ACTIVATED)) == 0) {
                 // Plugin does not exists or not activated
                 return FALSE;
             }
         } else {
             // Standard use of GLPI
             if (!in_array($plugname, $_SESSION['glpi_plugins'])) {
                 // Plugin not activated
                 return FALSE;
             }
         }
     } else {
         // Is ezComponent class ?
         $matches = array();
         if (preg_match('/^ezc([A-Z][a-z]+)/', $classname, $matches)) {
             include_once GLPI_EZC_BASE;
             ezcBase::autoload($classname);
             return TRUE;
         } else {
             $item = strtolower($classname);
         }
     }
     // No errors for missing classes due to implementation
     if (!isset($CFG_GLPI['missingclasses']) or !in_array($item, $CFG_GLPI['missingclasses'])) {
         if (file_exists("{$dir}{$item}.class.php")) {
             include_once "{$dir}{$item}.class.php";
             if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE) {
                 $DEBUG_AUTOLOAD[] = $classname;
             }
         } else {
             if (!isset($notfound["{$classname}"])) {
                 // trigger an error to get a backtrace, but only once (use prefix 'x' to handle empty case)
                 //Toolbox::logInFile('debug', "file $dir$item.class.php not founded trying to load class $classname\n");
                 trigger_error("GLPI autoload : file {$dir}{$item}.class.php not founded trying to load class '{$classname}'");
                 $notfound["{$classname}"] = TRUE;
             }
         }
     }
 }
示例#2
0
/**
 * Get the Login User ID or return cron user ID for cron jobs
 *
 * @param $force_human boolean : force human / do not return cron user
 *
 * return false if user is not logged in
 *
 * @return int or string : int for user id, string for cron jobs
**/
function getLoginUserID($force_human = true)
{
    if (!$force_human) {
        // Check cron jobs
        if (isset($_SESSION["glpicronuserrunning"]) && (isCommandLine() || strpos($_SERVER['PHP_SELF'], "cron.php"))) {
            return $_SESSION["glpicronuserrunning"];
        }
    }
    if (isset($_SESSION["glpiID"])) {
        return $_SESSION["glpiID"];
    }
    return false;
}
 /**
  * Specific error handler in Debug mode
  *
  * @param $errno     integer  level of the error raised.
  * @param $errmsg    string   error message.
  * @param $filename  string   filename that the error was raised in.
  * @param $linenum   integer  line number the error was raised at.
  * @param $vars      array    that points to the active symbol table at the point the error occurred.
  **/
 static function userErrorHandlerDebug($errno, $errmsg, $filename, $linenum, $vars)
 {
     // For file record
     $type = self::userErrorHandlerNormal($errno, $errmsg, $filename, $linenum, $vars);
     // Display
     if (!isCommandLine()) {
         echo '<div style="position:fload-left; background-color:red; z-index:10000">' . '<span class="b">PHP ' . $type . ': </span>';
         echo $errmsg . ' in ' . $filename . ' at line ' . $linenum . '</div>';
     } else {
         echo 'PHP ' . $type . ': ' . $errmsg . ' in ' . $filename . ' at line ' . $linenum . "\n";
     }
 }
 /**
  * Do automatic transfer if option is enable
  *
  * @param $line_links array : data from glpi_plugin_ocsinventoryng_ocslinks table
  * @return nothing
  * @internal param array $line_ocs : data from ocs tables
  *
  */
 static function transferComputer($line_links)
 {
     global $DB, $CFG_GLPI;
     $ocsClient = self::getDBocs($line_links["plugin_ocsinventoryng_ocsservers_id"]);
     $cfg_ocs = self::getConfig($line_links["plugin_ocsinventoryng_ocsservers_id"]);
     $ocsComputer = $ocsClient->getComputer($line_links["ocsid"]);
     $locations_id = 0;
     $contact = isset($ocsComputer['META']["USERID"]) ? $ocsComputer['META']["USERID"] : "";
     if (!empty($contact)) {
         $query = "SELECT `id`\n                   FROM `glpi_users`\n                   WHERE `name` = '" . $contact . "';";
         $result = $DB->query($query);
         if ($DB->numrows($result) == 1) {
             $user_id = $DB->result($result, 0, 0);
             $user = new User();
             $user->getFromDB($user_id);
             $locations_id = $user->fields["locations_id"];
         }
     }
     // Get all rules for the current plugin_ocsinventoryng_ocsservers_id
     $rule = new RuleImportEntityCollection();
     $data = array();
     $data = $rule->processAllRules(array('ocsservers_id' => $line_links["plugin_ocsinventoryng_ocsservers_id"], '_source' => 'ocsinventoryng', 'locations_id' => $locations_id), array('locations_id' => $locations_id), array('ocsid' => $line_links["ocsid"]));
     // If entity is changing move items to the new entities_id
     if (isset($data['entities_id']) && $data['entities_id'] > -1 && $data['entities_id'] != $line_links['entities_id']) {
         if (!isCommandLine() && !Session::haveAccessToEntity($data['entities_id'])) {
             Html::displayRightError();
         }
         $transfer = new Transfer();
         $transfer->getFromDB($CFG_GLPI['transfers_id_auto']);
         $item_to_transfer = array("Computer" => array($line_links['computers_id'] => $line_links['computers_id']));
         $transfer->moveItems($item_to_transfer, $data['entities_id'], $transfer->fields);
     }
     //If location is update by a rule
     self::updateLocation($line_links, $data, $cfg_ocs);
 }
示例#5
0
 /**
  * Print footer for null page
  **/
 static function nullFooter()
 {
     global $CFG_GLPI, $FOOTER_LOADED;
     // Print foot for null page
     if ($FOOTER_LOADED) {
         return;
     }
     $FOOTER_LOADED = true;
     if (!isCommandLine()) {
         echo "</div></div>";
         echo "<div id='footer-login'>";
         echo "<a href='http://glpi-project.org/' title='Powered By Teclib'>";
         echo "GLPI version " . (isset($CFG_GLPI["version"]) ? $CFG_GLPI["version"] : "") . " Copyright (C) " . "2015-" . " By Teclib'" . " - Copyright (C) 2003-2015 INDEPNET Development Team";
         echo "</a></div>";
         echo "</body></html>";
     }
     closeDBConnections();
 }
示例#6
0
 /**
  * Update date mod of the ticket
  *
  * @since version 0.83.3 new proto
  *
  * @param $ID                           ID of the ticket
  * @param $no_stat_computation  boolean do not cumpute take into account stat (false by default)
  * @param $users_id_lastupdater integer to force last_update id (default 0 = not used)
  **/
 function updateDateMod($ID, $no_stat_computation = false, $users_id_lastupdater = 0)
 {
     global $DB;
     if ($this->getFromDB($ID)) {
         if (!$no_stat_computation && (Session::haveRight('task', CommonITILTask::ADDALLITEM) || Session::haveRightsOr('followup', array(TicketFollowup::ADDALLTICKET, TicketFollowup::ADDMYTICKET, TicketFollowup::ADDGROUPTICKET)) || $this->isUser(CommonITILActor::ASSIGN, Session::getLoginUserID()) || isset($_SESSION["glpigroups"]) && $this->haveAGroup(CommonITILActor::ASSIGN, $_SESSION['glpigroups']) || isCommandLine())) {
             if ($this->fields['takeintoaccount_delay_stat'] == 0) {
                 return $this->update(array('id' => $ID, 'takeintoaccount_delay_stat' => $this->computeTakeIntoAccountDelayStat(), '_disablenotif' => true));
             }
         }
         parent::updateDateMod($ID, $no_stat_computation, $users_id_lastupdater);
     }
 }
示例#7
0
 /**
  * Print footer for null page
  **/
 static function nullFooter()
 {
     global $CFG_GLPI, $FOOTER_LOADED;
     // Print foot for null page
     if ($FOOTER_LOADED) {
         return;
     }
     $FOOTER_LOADED = true;
     if (!isCommandLine()) {
         echo "</div></div>";
         echo "<div id='footer-login'>" . self::getCopyrightMessage() . "</div>";
         echo "</body></html>";
     }
     closeDBConnections();
 }
 /**
  * @see RuleCollection::replayRulesOnExistingDB()
  **/
 function replayRulesOnExistingDB($offset = 0, $maxtime = 0, $items = array(), $params = array())
 {
     global $DB;
     if (isCommandLine()) {
         printf(__('Replay rules on existing database started on %s') . "\n", date("r"));
     }
     $nb = 0;
     $i = $offset;
     //Select all the differents software
     $sql = "SELECT DISTINCT `glpi_printers`.`name`,\n                     `glpi_manufacturers`.`name` AS manufacturer,\n                     `glpi_printers`.`manufacturers_id` AS manufacturers_id,\n                     `glpi_printers`.`comment` AS comment\n              FROM `glpi_printers`\n              LEFT JOIN `glpi_manufacturers`\n                  ON (`glpi_manufacturers`.`id` = `glpi_printers`.`manufacturers_id`) ";
     // Do not replay on dustbin and templates
     $sql .= "WHERE `glpi_printers`.`is_deleted` = '0'\n                     AND `glpi_printers`.`is_template` = '0' ";
     if ($offset) {
         $sql .= " LIMIT " . intval($offset) . ",999999999";
     }
     $res = $DB->query($sql);
     $nb = $DB->numrows($res) + $offset;
     $step = $nb > 1000 ? 50 : ($nb > 20 ? floor($DB->numrows($res) / 20) : 1);
     while ($input = $DB->fetch_assoc($res)) {
         if (!($i % $step)) {
             if (isCommandLine()) {
                 //TRANS: %1$s is a date, %2$s is a row, %3$s is total row, %4$s is memory
                 printf(__('%1$s - replay rules on existing database: %2$s/%3$s (%4$s Mio)') . "\n", date("H:i:s"), $i, $nb, round(memory_get_usage() / (1024 * 1024), 2));
             } else {
                 Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}");
             }
         }
         //Replay printer dictionnary rules
         $res_rule = $this->processAllRules($input, array(), array());
         foreach (array('manufacturer', 'is_global', 'name') as $attr) {
             if (isset($res_rule[$attr]) && $res_rule[$attr] == '') {
                 unset($res_rule[$attr]);
             }
         }
         //If the software's name or version has changed
         if (self::somethingHasChanged($res_rule, $input)) {
             $IDs = array();
             //Find all the printers in the database with the same name and manufacturer
             $sql = "SELECT `id`\n                    FROM `glpi_printers`\n                    WHERE `name` = '" . $input["name"] . "'\n                          AND `manufacturers_id` = '" . $input["manufacturers_id"] . "'";
             $res_printer = $DB->query($sql);
             if ($DB->numrows($res_printer) > 0) {
                 //Store all the printer's IDs in an array
                 while ($result = $DB->fetch_assoc($res_printer)) {
                     $IDs[] = $result["id"];
                 }
                 //Replay dictionnary on all the printers
                 $this->replayDictionnaryOnPrintersByID($IDs, $res_rule);
             }
         }
         $i++;
         if ($maxtime) {
             $crt = explode(" ", microtime());
             if ($crt[0] + $crt[1] > $maxtime) {
                 break;
             }
         }
     }
     if (isCommandLine()) {
         printf(__('Replay rules on existing database: %1$s/%2$s') . "\n", $i, $nb);
     } else {
         Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}");
     }
     if (isCommandLine()) {
         printf(__('Replay rules on existing database ended on %s') . "\n", date("r"));
     }
     return $i == $nb ? -1 : $i;
 }
示例#9
0
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
// Ensure current directory when run from crontab
chdir(dirname($_SERVER["SCRIPT_FILENAME"]));
define('DO_NOT_CHECK_HTTP_REFERER', 1);
include '../inc/includes.php';
if (!is_writable(GLPI_LOCK_DIR)) {
    //TRANS: %s is a directory
    echo "\t" . sprintf(__('ERROR: %s is not writable') . "\n", GLPI_LOCK_DIR);
    echo "\t" . __('run script as apache user') . "\n";
    exit(1);
}
if (!isCommandLine()) {
    //The advantage of using background-image is that cron is called in a separate
    //request and thus does not slow down output of the main page as it would if called
    //from there.
    $image = pack("H*", "47494638396118001800800000ffffff00000021f90401000000002c0000000" . "018001800000216848fa9cbed0fa39cb4da8bb3debcfb0f86e248965301003b");
    header("Content-Type: image/gif");
    header("Content-Length: " . strlen($image));
    header("Cache-Control: no-cache,no-store");
    header("Pragma: no-cache");
    header("Connection: close");
    echo $image;
    flush();
    CronTask::launch(CronTask::MODE_INTERNAL);
} else {
    if (isset($_SERVER['argc']) && $_SERVER['argc'] > 1) {
        // Parse command line options
示例#10
0
/**
 * To load classes
 *
 * @param $classname : class to load
**/
function glpi_autoload($classname)
{
    global $DEBUG_AUTOLOAD, $CFG_GLPI;
    static $notfound = array('xStates' => true, 'xAllAssets' => true);
    // empty classname or non concerted plugin or classname containing dot (leaving GLPI main treee)
    if (empty($classname) || is_numeric($classname) || strpos($classname, '.') !== false) {
        return false;
    }
    $dir = GLPI_ROOT . "/inc/";
    if ($plug = isPluginItemType($classname)) {
        $plugname = strtolower($plug['plugin']);
        $dir = GLPI_ROOT . "/plugins/{$plugname}/inc/";
        $item = strtolower($plug['class']);
        // Is the plugin activate ?
        // Command line usage of GLPI : need to do a real check plugin activation
        if (isCommandLine()) {
            $plugin = new Plugin();
            if (count($plugin->find("directory='{$plugname}' AND state=" . Plugin::ACTIVATED)) == 0) {
                // Plugin does not exists or not activated
                return false;
            }
        } else {
            // Standard use of GLPI
            if (!in_array($plugname, $_SESSION['glpi_plugins'])) {
                // Plugin not activated
                return false;
            }
        }
    } else {
        // Is ezComponent class ?
        if (preg_match('/^ezc([A-Z][a-z]+)/', $classname, $matches)) {
            include_once GLPI_EZC_BASE;
            ezcBase::autoload($classname);
            return true;
        }
        // Is Zend class ?
        //       if (preg_match('/^Zend/',$classname,$matches)) {
        //          if (GLPI_ZEND_PATH) {
        //             set_include_path(GLPI_ZEND_PATH . PATH_SEPARATOR . get_include_path());
        //          }
        //          require_once("Zend/Loader.php");
        //
        //          Zend_Loader::loadClass($classname);
        //          return true;
        //       }
        // Do not try to load phpcas using GLPI autoload
        if (preg_match('/^CAS_.*/', $classname)) {
            return false;
        }
        $item = strtolower($classname);
    }
    // No errors for missing classes due to implementation
    if (file_exists("{$dir}{$item}.class.php")) {
        include_once "{$dir}{$item}.class.php";
        if (isset($_SESSION['glpi_use_mode']) && $_SESSION['glpi_use_mode'] == Session::DEBUG_MODE) {
            $DEBUG_AUTOLOAD[] = $classname;
        }
    } else {
        if (!isset($notfound["x{$classname}"])) {
            // trigger an error to get a backtrace, but only once (use prefix 'x' to handle empty case)
            //          trigger_error("GLPI autoload : file $dir$item.class.php not founded trying to load class '$classname'");
            $notfound["x{$classname}"] = true;
        }
    }
}
示例#11
0
 /**
  * Detect cron mode or interactive
  *
  * @since version 0.84
  *
  * @return Boolean
  **/
 static function isCron()
 {
     return isset($_SESSION["glpicronuserrunning"]) && (isCommandLine() || strpos($_SERVER['PHP_SELF'], 'cron.php') || strpos($_SERVER['PHP_SELF'], 'crontask.form.php'));
 }
示例#12
0
 function getSearchOptions()
 {
     // Only use for History (not by search Engine)
     $tab = array();
     $tab['common'] = __('Characteristics');
     $tab[1]['table'] = $this->getTable();
     $tab[1]['field'] = 'name';
     $tab[1]['name'] = __('Name');
     $tab[1]['datatype'] = 'itemlink';
     $tab[1]['massiveaction'] = false;
     $tab[2]['table'] = $this->getTable();
     $tab[2]['field'] = 'id';
     $tab[2]['name'] = __('ID');
     $tab[2]['massiveaction'] = false;
     $tab[2]['datatype'] = 'number';
     $tab += Location::getSearchOptionsToAdd();
     $tab[16]['table'] = $this->getTable();
     $tab[16]['field'] = 'comment';
     $tab[16]['name'] = __('Comments');
     $tab[16]['datatype'] = 'text';
     $tab[62]['table'] = 'glpi_softwarecategories';
     $tab[62]['field'] = 'completename';
     $tab[62]['name'] = __('Category');
     $tab[62]['datatype'] = 'dropdown';
     $tab[19]['table'] = $this->getTable();
     $tab[19]['field'] = 'date_mod';
     $tab[19]['name'] = __('Last update');
     $tab[19]['datatype'] = 'datetime';
     $tab[19]['massiveaction'] = false;
     $tab[23]['table'] = 'glpi_manufacturers';
     $tab[23]['field'] = 'name';
     $tab[23]['name'] = __('Publisher');
     $tab[23]['datatype'] = 'dropdown';
     $tab[24]['table'] = 'glpi_users';
     $tab[24]['field'] = 'name';
     $tab[24]['linkfield'] = 'users_id_tech';
     $tab[24]['name'] = __('Technician in charge of the hardware');
     $tab[24]['datatype'] = 'dropdown';
     $tab[24]['right'] = 'own_ticket';
     $tab[49]['table'] = 'glpi_groups';
     $tab[49]['field'] = 'completename';
     $tab[49]['linkfield'] = 'groups_id_tech';
     $tab[49]['name'] = __('Group in charge of the hardware');
     $tab[49]['condition'] = '`is_assign`';
     $tab[49]['datatype'] = 'dropdown';
     $tab[70]['table'] = 'glpi_users';
     $tab[70]['field'] = 'name';
     $tab[70]['name'] = __('User');
     $tab[70]['datatype'] = 'dropdown';
     $tab[70]['right'] = 'all';
     $tab[71]['table'] = 'glpi_groups';
     $tab[71]['field'] = 'completename';
     $tab[71]['name'] = __('Group');
     $tab[71]['condition'] = '`is_itemgroup`';
     $tab[71]['datatype'] = 'dropdown';
     $tab[61]['table'] = $this->getTable();
     $tab[61]['field'] = 'is_helpdesk_visible';
     $tab[61]['name'] = __('Associable to a ticket');
     $tab[61]['datatype'] = 'bool';
     $tab[63]['table'] = $this->getTable();
     $tab[63]['field'] = 'is_valid';
     //TRANS: Indicator to know is all licenses of the software are valids
     $tab[63]['name'] = __('Valid licenses');
     $tab[63]['datatype'] = 'bool';
     $tab[80]['table'] = 'glpi_entities';
     $tab[80]['field'] = 'completename';
     $tab[80]['name'] = __('Entity');
     $tab[80]['massiveaction'] = false;
     $tab[80]['datatype'] = 'dropdown';
     $tab[72]['table'] = 'glpi_computers_softwareversions';
     $tab[72]['field'] = 'id';
     $tab[72]['name'] = _x('quantity', 'Number of installations');
     $tab[72]['forcegroupby'] = true;
     $tab[72]['usehaving'] = true;
     $tab[72]['datatype'] = 'count';
     $tab[72]['nometa'] = true;
     $tab[72]['massiveaction'] = false;
     if (Session::getLoginUserID()) {
         $tab[72]['joinparams'] = array('jointype' => 'child', 'condition' => "AND NEWTABLE.`is_deleted_computer` = '0'\n                                                          AND NEWTABLE.`is_deleted` = '0'\n                                                          AND NEWTABLE.`is_template_computer` = '0'\n                                                          " . getEntitiesRestrictRequest('AND', 'NEWTABLE'), 'beforejoin' => array('table' => 'glpi_softwareversions', 'joinparams' => array('jointype' => 'child')));
     }
     $tab[86]['table'] = $this->getTable();
     $tab[86]['field'] = 'is_recursive';
     $tab[86]['name'] = __('Child entities');
     $tab[86]['datatype'] = 'bool';
     $tab[86]['massiveaction'] = false;
     $tab['versions'] = _n('Version', 'Versions', Session::getPluralNumber());
     $tab[5]['table'] = 'glpi_softwareversions';
     $tab[5]['field'] = 'name';
     $tab[5]['name'] = __('Version name');
     $tab[5]['forcegroupby'] = true;
     $tab[5]['massiveaction'] = false;
     $tab[5]['joinparams'] = array('jointype' => 'child');
     $tab[5]['datatype'] = 'dropdown';
     $tab[31]['table'] = 'glpi_states';
     $tab[31]['field'] = 'completename';
     $tab[31]['name'] = __('Status');
     $tab[31]['datatype'] = 'dropdown';
     $tab[31]['forcegroupby'] = true;
     $tab[31]['massiveaction'] = false;
     $tab[31]['joinparams'] = array('beforejoin' => array('table' => 'glpi_softwareversions', 'joinparams' => array('jointype' => 'child')));
     $tab[170]['table'] = 'glpi_softwareversions';
     $tab[170]['field'] = 'comment';
     $tab[170]['name'] = __('Version comments');
     $tab[170]['forcegroupby'] = true;
     $tab[170]['datatype'] = 'text';
     $tab[170]['massiveaction'] = false;
     $tab[170]['joinparams'] = array('jointype' => 'child');
     $tab[4]['table'] = 'glpi_operatingsystems';
     $tab[4]['field'] = 'name';
     $tab[4]['datatype'] = 'dropdown';
     $tab[4]['name'] = __('Operating system');
     $tab[4]['forcegroupby'] = true;
     $tab[4]['joinparams'] = array('beforejoin' => array('table' => 'glpi_softwareversions', 'joinparams' => array('jointype' => 'child')));
     $tab += Notepad::getSearchOptionsToAdd();
     $tab['license'] = _n('License', 'Licenses', Session::getPluralNumber());
     $licjoin = array();
     $licjoinexpire = array();
     if (!Session::isCron() && !isCommandLine()) {
         // no filter for cron
         $licjoin = array('jointype' => 'child', 'condition' => getEntitiesRestrictRequest(' AND', "NEWTABLE", '', '', true));
         $licjoinexpire = array('jointype' => 'child', 'condition' => getEntitiesRestrictRequest(' AND', "NEWTABLE", '', '', true) . " AND (NEWTABLE.`expire` IS NULL\n                                                      OR NEWTABLE.`expire` > NOW())");
     }
     $tab[160]['table'] = 'glpi_softwarelicenses';
     $tab[160]['field'] = 'name';
     $tab[160]['name'] = __('License name');
     $tab[160]['datatype'] = 'dropdown';
     $tab[160]['forcegroupby'] = true;
     $tab[160]['massiveaction'] = false;
     $tab[160]['joinparams'] = $licjoinexpire;
     $tab[161]['table'] = 'glpi_softwarelicenses';
     $tab[161]['field'] = 'serial';
     $tab[161]['datatype'] = 'string';
     $tab[161]['name'] = __('License serial number');
     $tab[161]['forcegroupby'] = true;
     $tab[161]['massiveaction'] = false;
     $tab[161]['joinparams'] = $licjoinexpire;
     $tab[162]['table'] = 'glpi_softwarelicenses';
     $tab[162]['field'] = 'otherserial';
     $tab[162]['datatype'] = 'string';
     $tab[162]['name'] = __('License inventory number');
     $tab[162]['forcegroupby'] = true;
     $tab[162]['massiveaction'] = false;
     $tab[162]['joinparams'] = $licjoinexpire;
     $tab[163]['table'] = 'glpi_softwarelicenses';
     $tab[163]['field'] = 'number';
     $tab[163]['name'] = _x('phone', 'Number of licenses');
     $tab[163]['forcegroupby'] = true;
     $tab[163]['usehaving'] = true;
     $tab[163]['datatype'] = 'number';
     $tab[163]['massiveaction'] = false;
     $tab[163]['joinparams'] = $licjoinexpire;
     $tab[164]['table'] = 'glpi_softwarelicensetypes';
     $tab[164]['field'] = 'name';
     $tab[164]['datatype'] = 'dropdown';
     $tab[164]['name'] = _n('License type', 'License types', Session::getPluralNumber());
     $tab[164]['forcegroupby'] = true;
     $tab[164]['massiveaction'] = false;
     $tab[164]['joinparams'] = array('beforejoin' => array('table' => 'glpi_softwarelicenses', 'joinparams' => $licjoinexpire));
     $tab[165]['table'] = 'glpi_softwarelicenses';
     $tab[165]['field'] = 'comment';
     $tab[165]['name'] = __('License comments');
     $tab[165]['forcegroupby'] = true;
     $tab[165]['datatype'] = 'text';
     $tab[165]['massiveaction'] = false;
     $tab[165]['joinparams'] = $licjoinexpire;
     $tab[166]['table'] = 'glpi_softwarelicenses';
     $tab[166]['field'] = 'expire';
     $tab[166]['name'] = __('Expiration');
     $tab[166]['forcegroupby'] = true;
     $tab[166]['datatype'] = 'date';
     $tab[166]['emptylabel'] = __('Never expire');
     $tab[166]['massiveaction'] = false;
     $tab[166]['joinparams'] = $licjoinexpire;
     $tab[167]['table'] = 'glpi_softwarelicenses';
     $tab[167]['field'] = 'is_valid';
     $tab[167]['name'] = _x('adjective', 'Valid');
     $tab[167]['forcegroupby'] = true;
     $tab[167]['datatype'] = 'bool';
     $tab[167]['massiveaction'] = false;
     $tab[167]['joinparams'] = $licjoinexpire;
     return $tab;
 }
示例#13
0
 /**
  * Update some elements of an item in the database.
  *
  * @param $input     array    the _POST vars returned by the item form when press update
  * @param $history   boolean  do history log ? (default 1)
  * @param options    array    with the insert options
  *
  * @return boolean : true on success
  **/
 function update(array $input, $history = 1, $options = array())
 {
     global $DB, $CFG_GLPI;
     if ($DB->isSlave()) {
         return false;
     }
     if (!$this->getFromDB($input[static::getIndexName()])) {
         return false;
     }
     // Store input in the object to be available in all sub-method / hook
     $this->input = $input;
     // Plugin hook - $this->input can be altered
     Plugin::doHook("pre_item_update", $this);
     if ($this->input && is_array($this->input)) {
         $this->input = $this->prepareInputForUpdate($this->input);
         if (isset($this->input['update'])) {
             $this->input['_update'] = $this->input['update'];
             unset($this->input['update']);
         }
         $this->filterValues(!isCommandLine());
     }
     // Valid input for update
     if ($this->checkUnicity(false, $options)) {
         if ($this->input && is_array($this->input)) {
             // Fill the update-array with changes
             $x = 0;
             $this->updates = array();
             $this->oldvalues = array();
             foreach ($this->input as $key => $val) {
                 if (array_key_exists($key, $this->fields)) {
                     // Prevent history for date statement (for date for example)
                     if (is_null($this->fields[$key]) && $this->input[$key] == 'NULL') {
                         $this->fields[$key] = 'NULL';
                     }
                     // Compare item
                     $ischanged = true;
                     $searchopt = $this->getSearchOptionByField('field', $key, $this->getTable());
                     if (isset($searchopt['datatype'])) {
                         switch ($searchopt['datatype']) {
                             case 'string':
                             case 'text':
                                 $ischanged = strcmp($DB->escape($this->fields[$key]), $this->input[$key]) != 0;
                                 break;
                             case 'itemlink':
                                 if ($key == 'name') {
                                     $ischanged = strcmp($DB->escape($this->fields[$key]), $this->input[$key]) != 0;
                                     break;
                                 }
                                 // else default
                             // else default
                             default:
                                 $ischanged = $DB->escape($this->fields[$key]) != $this->input[$key];
                                 break;
                         }
                     } else {
                         // No searchoption case
                         $ischanged = $DB->escape($this->fields[$key]) != $this->input[$key];
                     }
                     if ($ischanged) {
                         if ($key != "id") {
                             // Store old values
                             if (!in_array($key, $this->history_blacklist)) {
                                 $this->oldvalues[$key] = $this->fields[$key];
                             }
                             $this->fields[$key] = $this->input[$key];
                             $this->updates[$x] = $key;
                             $x++;
                         }
                     }
                 }
             }
             if (count($this->updates)) {
                 if (array_key_exists('date_mod', $this->fields)) {
                     // is a non blacklist field exists
                     if (count(array_diff($this->updates, $this->history_blacklist)) > 0) {
                         $this->fields['date_mod'] = $_SESSION["glpi_currenttime"];
                         $this->updates[$x++] = 'date_mod';
                     }
                 }
                 $this->pre_updateInDB();
                 if (count($this->updates)) {
                     if ($this->updateInDB($this->updates, $this->dohistory && $history ? $this->oldvalues : array())) {
                         $this->addMessageOnUpdateAction();
                         Plugin::doHook("item_update", $this);
                         //Fill forward_entity_to array with itemtypes coming from plugins
                         if (isset(self::$plugins_forward_entity[$this->getType()])) {
                             foreach (self::$plugins_forward_entity[$this->getType()] as $itemtype) {
                                 static::$forward_entity_to[] = $itemtype;
                             }
                         }
                         // forward entity information if needed
                         if (count(static::$forward_entity_to) && (in_array("entities_id", $this->updates) || in_array("is_recursive", $this->updates))) {
                             $this->forwardEntityInformations();
                         }
                         // If itemtype is in infocomtype and if states_id field is filled
                         // and item not a template
                         if (InfoCom::canApplyOn($this) && in_array('states_id', $this->updates) && $this->getField('is_template') != NOT_AVAILABLE) {
                             //Check if we have to automatical fill dates
                             Infocom::manageDateOnStatusChange($this, false);
                         }
                     }
                 }
             }
             $this->post_updateItem($history);
             if ($this->mailqueueonaction) {
                 QueuedMail::forceSendFor($this->getType(), $this->fields['id']);
             }
             return true;
         }
     }
     return false;
 }
示例#14
0
 static function getSearchOptionsToAdd()
 {
     $tab = array();
     if (!self::canView()) {
         return $tab;
     }
     $tab['license'] = _n('License', 'Licenses', Session::getPluralNumber());
     $licjoin = array();
     $licjoinexpire = array();
     if (!Session::isCron() && !isCommandLine()) {
         // no filter for cron
         $licjoin = array('jointype' => 'child', 'condition' => getEntitiesRestrictRequest(' AND', "NEWTABLE", '', '', true));
         $licjoinexpire = array('jointype' => 'child', 'condition' => getEntitiesRestrictRequest(' AND', "NEWTABLE", '', '', true) . " AND (NEWTABLE.`expire` IS NULL\n                                                      OR NEWTABLE.`expire` > NOW())");
     }
     $tab[160]['table'] = 'glpi_softwarelicenses';
     $tab[160]['field'] = 'name';
     $tab[160]['name'] = __('License name');
     $tab[160]['datatype'] = 'dropdown';
     $tab[160]['forcegroupby'] = true;
     $tab[160]['massiveaction'] = false;
     $tab[160]['joinparams'] = $licjoinexpire;
     $tab[161]['table'] = 'glpi_softwarelicenses';
     $tab[161]['field'] = 'serial';
     $tab[161]['datatype'] = 'string';
     $tab[161]['name'] = __('License serial number');
     $tab[161]['forcegroupby'] = true;
     $tab[161]['massiveaction'] = false;
     $tab[161]['joinparams'] = $licjoinexpire;
     $tab[162]['table'] = 'glpi_softwarelicenses';
     $tab[162]['field'] = 'otherserial';
     $tab[162]['datatype'] = 'string';
     $tab[162]['name'] = __('License inventory number');
     $tab[162]['forcegroupby'] = true;
     $tab[162]['massiveaction'] = false;
     $tab[162]['joinparams'] = $licjoinexpire;
     $tab[163]['table'] = 'glpi_softwarelicenses';
     $tab[163]['field'] = 'number';
     $tab[163]['name'] = _x('phone', 'Number of licenses');
     $tab[163]['forcegroupby'] = true;
     $tab[163]['usehaving'] = true;
     $tab[163]['datatype'] = 'number';
     $tab[163]['massiveaction'] = false;
     $tab[163]['joinparams'] = $licjoinexpire;
     $tab[164]['table'] = 'glpi_softwarelicensetypes';
     $tab[164]['field'] = 'name';
     $tab[164]['datatype'] = 'dropdown';
     $tab[164]['name'] = _n('License type', 'License types', Session::getPluralNumber());
     $tab[164]['forcegroupby'] = true;
     $tab[164]['massiveaction'] = false;
     $tab[164]['joinparams'] = array('beforejoin' => array('table' => 'glpi_softwarelicenses', 'joinparams' => $licjoinexpire));
     $tab[165]['table'] = 'glpi_softwarelicenses';
     $tab[165]['field'] = 'comment';
     $tab[165]['name'] = __('License comments');
     $tab[165]['forcegroupby'] = true;
     $tab[165]['datatype'] = 'text';
     $tab[165]['massiveaction'] = false;
     $tab[165]['joinparams'] = $licjoinexpire;
     $tab[166]['table'] = 'glpi_softwarelicenses';
     $tab[166]['field'] = 'expire';
     $tab[166]['name'] = __('Expiration');
     $tab[166]['forcegroupby'] = true;
     $tab[166]['datatype'] = 'date';
     $tab[166]['emptylabel'] = __('Never expire');
     $tab[166]['massiveaction'] = false;
     $tab[166]['joinparams'] = $licjoinexpire;
     $tab[167]['table'] = 'glpi_softwarelicenses';
     $tab[167]['field'] = 'is_valid';
     $tab[167]['name'] = _x('adjective', 'Valid');
     $tab[167]['forcegroupby'] = true;
     $tab[167]['datatype'] = 'bool';
     $tab[167]['massiveaction'] = false;
     $tab[167]['joinparams'] = $licjoinexpire;
     return $tab;
 }
示例#15
0
 /**
  * Start a task, timer, stat, log, ...
  *
  * @return bool : true if ok (not start by another)
  **/
 function start()
 {
     global $DB, $LANG;
     if (!isset($this->fields['id']) || $DB->isSlave()) {
         return false;
     }
     $query = "UPDATE `" . $this->getTable() . "`\n                SET `state` = '" . self::STATE_RUNNING . "',\n                    `lastrun` = NOW()\n                WHERE `id` = '" . $this->fields['id'] . "'\n                      AND `state` != '" . self::STATE_RUNNING . "'";
     $result = $DB->query($query);
     if ($DB->affected_rows($result) > 0) {
         $this->timer = microtime(true);
         $this->volume = 0;
         $log = new CronTaskLog();
         $txt = $LANG['crontask'][36] . " : " . $this->getModeName(isCommandLine() ? self::MODE_EXTERNAL : self::MODE_INTERNAL);
         $this->startlog = $log->add(array('crontasks_id' => $this->fields['id'], 'date' => $_SESSION['glpi_currenttime'], 'content' => addslashes($txt), 'crontasklogs_id' => 0, 'state' => CronTaskLog::STATE_START, 'volume' => 0, 'elapsed' => 0));
         return true;
     }
     return false;
 }
示例#16
0
 * The contents of this file are subject to the RECIPROCAL PUBLIC LICENSE
 * Version 1.1 ("License"); You may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://opensource.org/licenses/rpl.php. Software distributed under the
 * License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
 * either express or implied.
 *
 * @author:  Mr. Milk (aka Marcelo Leite)
 * @email:   mrmilk@anysoft.com.br
 * @version: 0.9 beta
 * @date:    2007-07-07
 *
 *****************************************************************************/
if (isDownload()) {
    downloadFile();
} elseif (isCommandLine()) {
    processBatch();
}
?>
<html>
  <head>
  <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
  <script>
    var menus = [
      [ "Indentation and General Formatting", "", [
        [ "indent_size", "&nbsp;characters per indentation level" ],
        [ "indent_with_tabs", "Indent with tabs instead of spaces" ],
        [ "keep_redundant_lines", "Keep redundant lines" ],
        [ "space_inside_parentheses", "Space inside parentheses" ],
        [ "space_outside_parentheses", "Space outside parentheses" ],
        [ "space_after_comma", "Space after comma" ]
示例#17
0
if (isset($_REQUEST['forcetab'])) {
    if (preg_match('/([a-zA-Z]+).form.php/', $_SERVER['PHP_SELF'], $matches)) {
        $itemtype = $matches[1];
        Session::setActiveTab($matches[1], $_REQUEST['forcetab']);
    }
}
// Manage tabs
if (isset($_REQUEST['glpi_tab']) && isset($_REQUEST['itemtype'])) {
    Session::setActiveTab($_REQUEST['itemtype'], $_REQUEST['glpi_tab']);
}
// Override list-limit if choosen
if (isset($_REQUEST['glpilist_limit'])) {
    $_SESSION['glpilist_limit'] = $_REQUEST['glpilist_limit'];
}
// Security : Check HTTP_REFERRER : need to be in GLPI.
if (!defined('DO_NOT_CHECK_HTTP_REFERER') && !isCommandLine() && isset($_POST) && is_array($_POST) && count($_POST)) {
    if (!isset($_SERVER['HTTP_REFERER']) || !is_array($url = parse_url($_SERVER['HTTP_REFERER'])) || !isset($url['host']) || $url['host'] != $_SERVER['SERVER_NAME'] && (!isset($_SERVER['HTTP_X_FORWARDED_SERVER']) || $url['host'] != $_SERVER['HTTP_X_FORWARDED_SERVER']) || !isset($url['path']) || !empty($CFG_GLPI['root_doc']) && strpos($url['path'], $CFG_GLPI['root_doc']) !== 0) {
        Html::displayErrorAndDie(__("The action you have requested is not allowed. Reload previous page before doing action again."), true);
    }
}
// Security : check CSRF token
if (GLPI_USE_CSRF_CHECK && isset($_POST) && is_array($_POST) && count($_POST)) {
    // No ajax pages
    if (!preg_match(':' . $CFG_GLPI['root_doc'] . '(/plugins/[^/]*|)/ajax/:', $_SERVER['REQUEST_URI'])) {
        if (!Session::validateCSRF($_POST)) {
            Html::displayErrorAndDie(__("The action you have requested is not allowed. Reload previous page before doing action again."), true);
        }
    }
}
// SET new global Token
$CURRENTCSRFTOKEN = '';
示例#18
0
 /**
  * Do automatic transfer if option is enable
  *
  * @param $line_links array : data from glpi_plugin_ocsinventoryng_ocslinks table
  * @param $line_ocs array : data from ocs tables
  *
  * @return nothing
  **/
 static function transferComputer($line_links, $line_ocs)
 {
     global $DB, $PluginOcsinventoryngDBocs, $CFG_GLPI;
     // Get all rules for the current plugin_ocsinventoryng_ocsservers_id
     $rule = new RuleImportEntityCollection();
     $data = array();
     $data = $rule->processAllRules(array('ocsservers_id' => $line_links["plugin_ocsinventoryng_ocsservers_id"], '_source' => 'ocsinventoryng'), array(), array('ocsid' => $line_links["ocsid"]));
     // If entity is changing move items to the new entities_id
     if (isset($data['entities_id']) && $data['entities_id'] != $line_links['entities_id']) {
         if (!isCommandLine() && !Session::haveAccessToEntity($data['entities_id'])) {
             Html::displayRightError();
         }
         $transfer = new Transfer();
         $transfer->getFromDB($CFG_GLPI['transfers_id_auto']);
         $item_to_transfer = array("Computer" => array($line_links['computers_id'] => $line_links['computers_id']));
         $transfer->moveItems($item_to_transfer, $data['entities_id'], $transfer->fields);
     }
     //If location is update by a rule
     self::updateLocation($line_links, $data);
 }
示例#19
0
/**
 * To load classes
 *
 * @param $classname : class to load
**/
function glpi_autoload($classname)
{
    global $DEBUG_AUTOLOAD, $CFG_GLPI;
    static $notfound = array('xStates' => true, 'xAllAssets' => true);
    // empty classname or non concerted plugin or classname containing dot (leaving GLPI main treee)
    if (empty($classname) || is_numeric($classname) || strpos($classname, '.') !== false) {
        die("Security die. trying to load an forbidden class name");
    }
    $dir = GLPI_ROOT . "/inc/";
    if ($plug = isPluginItemType($classname)) {
        $plugname = strtolower($plug['plugin']);
        $dir = GLPI_ROOT . "/plugins/{$plugname}/inc/";
        $item = strtolower($plug['class']);
        // Is the plugin activate ?
        // Command line usage of GLPI : need to do a real check plugin activation
        if (isCommandLine()) {
            $plugin = new Plugin();
            if (count($plugin->find("directory='{$plugname}' AND state=" . Plugin::ACTIVATED)) == 0) {
                // Plugin does not exists or not activated
                return false;
            }
        } else {
            // Standard use of GLPI
            if (!isset($_SESSION['glpi_plugins']) || !in_array($plugname, $_SESSION['glpi_plugins'])) {
                // Plugin not activated
                return false;
            }
        }
    } else {
        //TODO: clean, seems uneeded, as composer autoloader is used first
        // Do not try to load phpcas using GLPI autoload
        //if (preg_match('/^CAS_.*/', $classname)) {
        //   return false;
        //}
        // Do not try to load Zend using GLPI autoload
        //if (preg_match('/^Zend.*/', $classname)) {
        //   return false;
        //}
        // Do not try to load Simplepie using GLPI autoload
        //if (preg_match('/^SimplePie.*/', $classname)) {
        //   return false;
        //}
        $item = strtolower($classname);
    }
    if (file_exists("{$dir}{$item}.class.php")) {
        include_once "{$dir}{$item}.class.php";
        if (isset($_SESSION['glpi_use_mode']) && $_SESSION['glpi_use_mode'] == Session::DEBUG_MODE) {
            $DEBUG_AUTOLOAD[] = $classname;
        }
    } else {
        if (!isset($notfound["x{$classname}"])) {
            // trigger an error to get a backtrace, but only once (use prefix 'x' to handle empty case)
            // trigger_error("GLPI autoload : file $dir$item.class.php not founded trying to load class '$classname'");
            $notfound["x{$classname}"] = true;
        }
    }
}
 static function preItemUpdate(CommonDBTM $item)
 {
     if (!Session::haveRight("plugin_geninventorynumber", UPDATE)) {
         return array('noright');
     }
     if (PluginGeninventorynumberConfig::isGenerationActive() && PluginGeninventorynumberConfigField::isActiveForItemType(get_class($item)) && !isset($item->input['massiveaction'])) {
         if (isset($item->fields['otherserial']) && isset($item->input['otherserial']) && $item->fields['otherserial'] != $item->input['otherserial']) {
             $item->input['otherserial'] = $item->fields['otherserial'];
             if (!isCommandLine()) {
                 Session::addMessageAfterRedirect(__('GenerateInventoryNumberDenied', 'geninventorynumber'), true, ERROR);
                 return array('ko');
             }
         }
         return array('ok');
     }
     return '';
 }
 /**
  * @see RuleCollection::replayRulesOnExistingDB()
  **/
 function replayRulesOnExistingDB($offset = 0, $maxtime = 0, $items = array(), $params = array())
 {
     global $DB;
     if (isCommandLine()) {
         echo "replayRulesOnExistingDB started : " . date("r") . "\n";
     }
     $nb = 0;
     $i = $offset;
     if (count($items) == 0) {
         //Select all the differents software
         $sql = "SELECT DISTINCT `glpi_softwares`.`name`,\n                        `glpi_manufacturers`.`name` AS manufacturer,\n                        `glpi_softwares`.`manufacturers_id` AS manufacturers_id,\n                        `glpi_softwares`.`entities_id` AS entities_id,\n                        `glpi_softwares`.`is_helpdesk_visible` AS helpdesk\n                 FROM `glpi_softwares`\n                 LEFT JOIN `glpi_manufacturers`\n                     ON (`glpi_manufacturers`.`id` = `glpi_softwares`.`manufacturers_id`)";
         // Do not replay on dustbin and templates
         $sql .= "WHERE `glpi_softwares`.`is_deleted` = '0'\n                        AND `glpi_softwares`.`is_template` = '0' ";
         if (isset($params['manufacturer']) && $params['manufacturer']) {
             $sql .= " AND `glpi_softwares`.`manufacturers_id` = '" . $params['manufacturer'] . "'";
         }
         if ($offset) {
             $sql .= " LIMIT " . intval($offset) . ",999999999";
         }
         $res = $DB->query($sql);
         $nb = $DB->numrows($res) + $offset;
         $step = $nb > 1000 ? 50 : ($nb > 20 ? floor($DB->numrows($res) / 20) : 1);
         while ($input = $DB->fetch_assoc($res)) {
             if (!($i % $step)) {
                 if (isCommandLine()) {
                     printf(__('%1$s - replay rules on existing database: %2$s/%3$s (%4$s Mio)') . "\n", date("H:i:s"), $i, $nb, round(memory_get_usage() / (1024 * 1024), 2));
                 } else {
                     Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}");
                 }
             }
             //If manufacturer is set, then first run the manufacturer's dictionnary
             if (isset($input["manufacturer"])) {
                 $input["manufacturer"] = Manufacturer::processName(addslashes($input["manufacturer"]));
             }
             //Replay software dictionnary rules
             $res_rule = $this->processAllRules($input, array(), array());
             if (isset($res_rule["name"]) && $res_rule["name"] != $input["name"] || isset($res_rule["version"]) && $res_rule["version"] != '' || isset($res_rule['new_entities_id']) && $res_rule['new_entities_id'] != $input['entities_id'] || isset($res_rule['is_helpdesk_visible']) && $res_rule['is_helpdesk_visible'] != $input['helpdesk'] || isset($res_rule['manufacturer']) && $res_rule['manufacturer'] != $input['manufacturer']) {
                 $IDs = array();
                 //Find all the softwares in the database with the same name and manufacturer
                 $sql = "SELECT `id`\n                       FROM `glpi_softwares`\n                       WHERE `name` = '" . $input["name"] . "'\n                             AND `manufacturers_id` = '" . $input["manufacturers_id"] . "'";
                 $res_soft = $DB->query($sql);
                 if ($DB->numrows($res_soft) > 0) {
                     //Store all the software's IDs in an array
                     while ($result = $DB->fetch_assoc($res_soft)) {
                         $IDs[] = $result["id"];
                     }
                     //Replay dictionnary on all the softwares
                     $this->replayDictionnaryOnSoftwaresByID($IDs, $res_rule);
                 }
             }
             $i++;
             if ($maxtime) {
                 $crt = explode(" ", microtime());
                 if ($crt[0] + $crt[1] > $maxtime) {
                     break;
                 }
             }
         }
         // each distinct software
         if (isCommandLine()) {
             printf(__('Replay rules on existing database: %1$s/%2$s') . "   \n", $i, $nb);
         } else {
             Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}");
         }
     } else {
         $this->replayDictionnaryOnSoftwaresByID($items);
         return true;
     }
     if (isCommandLine()) {
         printf(__('Replay rules on existing database ended on %s') . "\n", date("r"));
     }
     return $i == $nb ? -1 : $i;
 }
示例#22
0
             echo "<p class='red'>";
             _e('Service is down for maintenance. It will be back shortly.');
             echo "</p>";
             if (isset($CFG_GLPI["maintenance_text"]) && !empty($CFG_GLPI["maintenance_text"])) {
                 echo "<p>" . $CFG_GLPI["maintenance_text"] . "</p>";
             }
             echo "</div>";
             Html::nullFooter();
         }
         exit;
     }
 }
 // Check version
 if ((!isset($CFG_GLPI["version"]) || trim($CFG_GLPI["version"]) != GLPI_VERSION) && !isset($_GET["donotcheckversion"])) {
     Session::loadLanguage();
     if (isCommandLine()) {
         _e('The version of the database is not compatible with the version of the installed files. An update is necessary.');
         echo "\n";
     } else {
         Html::nullHeader("UPDATE NEEDED", $CFG_GLPI["root_doc"]);
         echo "<div class='center'>";
         echo "<table class='tab_cadre'>";
         $error = Toolbox::commonCheckForUseGLPI();
         echo "</table><br>";
         if ($error) {
             echo "<form action='" . $CFG_GLPI["root_doc"] . "/index.php' method='post'>";
             echo "<input type='submit' name='submit' class='submit' value=\"" . __s('Try again') . "\">";
             Html::closeForm();
         }
         if ($error < 2) {
             if (!isset($CFG_GLPI["version"]) || trim($CFG_GLPI["version"]) < GLPI_VERSION) {
示例#23
0
 /**
  * Start a task, timer, stat, log, ...
  *
  * @return bool : true if ok (not start by another)
  **/
 function start()
 {
     global $DB;
     if (!isset($this->fields['id']) || $DB->isSlave()) {
         return false;
     }
     if (isCommandLine() && function_exists('pcntl_signal')) {
         pcntl_signal(SIGTERM, [$this, 'signal']);
     }
     $query = "UPDATE `" . $this->getTable() . "`\n                SET `state` = '" . self::STATE_RUNNING . "',\n                    `lastrun` = DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:00')\n                WHERE `id` = '" . $this->fields['id'] . "'\n                      AND `state` != '" . self::STATE_RUNNING . "'";
     $result = $DB->query($query);
     if ($DB->affected_rows($result) > 0) {
         $this->timer = microtime(true);
         $this->volume = 0;
         $log = new CronTaskLog();
         // No gettext for log
         $txt = sprintf('%1$s: %2$s', 'Run mode', $this->getModeName(isCommandLine() ? self::MODE_EXTERNAL : self::MODE_INTERNAL));
         $this->startlog = $log->add(array('crontasks_id' => $this->fields['id'], 'date' => $_SESSION['glpi_currenttime'], 'content' => addslashes($txt), 'crontasklogs_id' => 0, 'state' => CronTaskLog::STATE_START, 'volume' => 0, 'elapsed' => 0));
         return true;
     }
     return false;
 }
 /**
  * Replay collection rules on an existing DB for model dropdowns
  *
  * @param $offset    offset used to begin (default 0)
  * @param $maxtime   maximum time of process (reload at the end) (default 0)
  *
  * @return -1 on completion else current offset
  **/
 function replayRulesOnExistingDBForModel($offset = 0, $maxtime = 0)
 {
     global $DB;
     if (isCommandLine()) {
         printf(__('Replay rules on existing database started on %s') . "\n", date("r"));
     }
     // Model check : need to check using manufacturer extra data
     if (strpos($this->item_table, 'models') === false) {
         _e('Error replaying rules');
         return false;
     }
     $model_table = getPlural(str_replace('models', '', $this->item_table));
     $model_field = getForeignKeyFieldForTable($this->item_table);
     // Need to give manufacturer from item table
     $Sql = "SELECT DISTINCT `glpi_manufacturers`.`id` AS idmanu,\n                     `glpi_manufacturers`.`name` AS manufacturer,\n                     `" . $this->item_table . "`.`id`,\n                     `" . $this->item_table . "`.`name` AS name,\n                     `" . $this->item_table . "`.`comment`\n              FROM `" . $this->item_table . "`,\n                   `{$model_table}`\n              LEFT JOIN `glpi_manufacturers`\n                  ON (`{$model_table}`.`manufacturers_id` = `glpi_manufacturers`.`id`)\n              WHERE `{$model_table}`.`{$model_field}` = `" . $this->item_table . "`.`id`";
     if ($offset) {
         $Sql .= " LIMIT " . intval($offset) . ",999999999";
     }
     $result = $DB->query($Sql);
     $nb = $DB->numrows($result) + $offset;
     $i = $offset;
     if ($result && $nb > $offset) {
         // Step to refresh progressbar
         $step = $nb > 20 ? floor($nb / 20) : 1;
         $tocheck = array();
         while ($data = $DB->fetch_assoc($result)) {
             if (!($i % $step)) {
                 if (isCommandLine()) {
                     printf(__('Replay rules on existing database: %1$s/%2$s') . "\r", $i, $nb);
                 } else {
                     Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}");
                 }
             }
             // Model case
             if (isset($data["manufacturer"])) {
                 $data["manufacturer"] = Manufacturer::processName(addslashes($data["manufacturer"]));
             }
             //Replay Type dictionnary
             $ID = Dropdown::importExternal(getItemTypeForTable($this->item_table), addslashes($data["name"]), -1, $data, addslashes($data["comment"]));
             if ($data['id'] != $ID) {
                 $tocheck[$data["id"]][] = $ID;
                 $sql = "UPDATE `{$model_table}`\n                                          SET `{$model_field}` = '{$ID}'\n                                          WHERE `{$model_field}` = '" . $data['id'] . "'";
                 if (empty($data['idmanu'])) {
                     $sql .= " AND (`manufacturers_id` IS NULL\n                                 OR `manufacturers_id` = '0')";
                 } else {
                     $sql .= " AND `manufacturers_id` = '" . $data['idmanu'] . "'";
                 }
                 $DB->query($sql);
             }
             $i++;
             if ($maxtime) {
                 $crt = explode(" ", microtime());
                 if ($crt[0] + $crt[1] > $maxtime) {
                     break;
                 }
             }
         }
         foreach ($tocheck as $ID => $tab) {
             $sql = "SELECT COUNT(*)\n                                 FROM `{$model_table}`\n                                 WHERE `{$model_field}` = '{$ID}'";
             $result = $DB->query($sql);
             $deletecartmodel = false;
             // No item left : delete old item
             if ($result && $DB->result($result, 0, 0) == 0) {
                 $Sql = "DELETE\n                                    FROM `" . $this->item_table . "`\n                                    WHERE `id` = '{$ID}'";
                 $resdel = $DB->query($Sql);
                 $deletecartmodel = true;
             }
             // Manage cartridge assoc Update items
             if ($this->getRuleClassName() == 'RuleDictionnaryPrinterModel') {
                 $sql = "SELECT *\n                       FROM `glpi_cartridgeitems_printermodels`\n                       WHERE `printermodels_id` = '{$ID}'";
                 if ($result = $DB->query($sql)) {
                     if ($DB->numrows($result)) {
                         // Get compatible cartridge type
                         $carttype = array();
                         while ($data = $DB->fetch_assoc($result)) {
                             $carttype[] = $data['cartridgeitems_id'];
                         }
                         // Delete cartrodges_assoc
                         if ($deletecartmodel) {
                             $sql = "DELETE\n                                FROM `glpi_cartridgeitems_printermodels`\n                                WHERE `printermodels_id` = 'id'";
                             $DB->query($sql);
                         }
                         // Add new assoc
                         $ct = new CartridgeItem();
                         foreach ($carttype as $cartID) {
                             foreach ($tab as $model) {
                                 $ct->addCompatibleType($cartID, $model);
                             }
                         }
                     }
                 }
             }
         }
         // each tocheck
     }
     if (isCommandLine()) {
         printf(__('Replay rules on existing database ended on %s') . "\n", date("r"));
     } else {
         Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}");
     }
     return $i == $nb ? -1 : $i;
 }
示例#25
0
 /**
  *  Display a common mysql connection error
  **/
 static function displayMySQLError()
 {
     if (!isCommandLine()) {
         Html::nullHeader("Mysql Error", '');
         echo "<div class='center'><p class ='b'>\n                A link to the Mysql server could not be established. Please check your configuration.\n                </p><p class='b'>\n                Le serveur Mysql est inaccessible. Vérifiez votre configuration</p>\n               </div>";
         Html::nullFooter();
     } else {
         echo "A link to the Mysql server could not be established. Please check your configuration.\n";
         echo "Le serveur Mysql est inaccessible. Vérifiez votre configuration\n";
     }
     die;
 }
/**
 * Print footer for null page
 **/
function nullFooter()
{
    global $CFG_GLPI, $FOOTER_LOADED;
    // Print foot for null page
    if ($FOOTER_LOADED) {
        return;
    }
    $FOOTER_LOADED = true;
    if (!isCommandLine()) {
        echo "<div class='bas'></div></div></div>";
        echo "<div id='footer-login'>";
        echo "<a href='http://glpi-project.org/' title='Powered By Indepnet'>";
        echo 'GLPI version ' . (isset($CFG_GLPI["version"]) ? $CFG_GLPI["version"] : "") . ' Copyright (C) 2003-' . date("Y") . ' INDEPNET Development Team.';
        echo "</a></div>";
        echo "</body></html>";
    }
    closeDBConnections();
}
示例#27
0
 /**
  * @since version 0.85
  **/
 static function getSearchOptionsToAdd()
 {
     $tab = array();
     $tab[145]['table'] = 'glpi_links';
     $tab[145]['field'] = '_virtual';
     $tab[145]['name'] = _n('External link', 'External links', Session::getPluralNumber());
     $tab[145]['datatype'] = 'specific';
     $tab[145]['additionalfields'] = array('id', 'link', 'name', 'data', 'open_window');
     $tab[145]['nosearch'] = true;
     $tab[145]['forcegroupby'] = true;
     $tab[145]['nosort'] = true;
     $tab[145]['joinparams'] = array('beforejoin' => array('table' => 'glpi_links_itemtypes', 'joinparams' => array('jointype' => 'itemtypeonly')));
     if (!Session::isCron() && !isCommandLine()) {
         $tab[145]['joinparams']['condition'] = getEntitiesRestrictRequest('AND', 'NEWTABLE');
     }
     return $tab;
 }
示例#28
0
 /**
  * Do automatic transfer if option is enable
  *
  * @param $line_links array : data from glpi_ocslinks table
  * @param $line_ocs array : data from ocs tables
  *
  * @return nothing
  **/
 static function transferComputer($line_links, $line_ocs)
 {
     global $DB, $DBocs, $CFG_GLPI;
     // Get all rules for the current ocsservers_id
     $rules = new RuleOcsCollection($line_links["ocsservers_id"]);
     $data = array();
     $data = $rules->processAllRules(array(), array(), $line_links["ocsid"]);
     // If entity is changing move items to the new entities_id
     if (isset($data['entities_id']) && $data['entities_id'] != $line_links['entities_id']) {
         if (!isCommandLine() && !haveAccessToEntity($data['entities_id'])) {
             displayRightError();
         }
         $transfer = new Transfer();
         $transfer->getFromDB($CFG_GLPI['transfers_id_auto']);
         $item_to_transfer = array("Computer" => array($line_links['computers_id'] => $line_links['computers_id']));
         $transfer->moveItems($item_to_transfer, $data['entities_id'], $transfer->fields);
     }
     // Update TAG
     self::updateTag($line_links, $line_ocs);
 }