static function httpSendFile($params)
 {
     if (!isset($params['file'])) {
         header("HTTP/1.1 500");
         exit;
     }
     $matches = array();
     preg_match('/.\\/..\\/([^\\/]+)/', $params['file'], $matches);
     $sha512 = $matches[1];
     //      $short_sha512 = substr($sha512, 0, 6);
     $repoPath = GLPI_PLUGIN_DOC_DIR . "/fusioninventory/files/repository/";
     $filePath = $repoPath . PluginFusioninventoryDeployFile::getDirBySha512($sha512) . '/' . $sha512;
     if (!is_file($filePath)) {
         header("HTTP/1.1 404");
         print "\n" . $filePath . "\n\n";
         exit;
     } else {
         if (!is_readable($filePath)) {
             header("HTTP/1.1 403");
             exit;
         }
     }
     error_reporting(0);
     header('Content-Description: File Transfer');
     header('Content-Type: application/octet-stream');
     header('Content-Disposition: attachment; filename=' . $sha512);
     header('Content-Transfer-Encoding: binary');
     header('Expires: 0');
     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
     header('Pragma: public');
     header('Content-Length: ' . filesize($filePath));
     if (ob_get_level() > 0) {
         ob_clean();
     }
     flush();
     readfile($filePath);
     exit;
 }
Esempio n. 2
0
/**
 * Migrate tables from plugin fusinvdeploy to fusioninventory
 *    all datas in exploded tables are merged and stored in json in order table
 * @param  Migration $migration
 * @return nothing
 */
function migrateTablesFromFusinvDeploy($migration)
{
    global $DB;
    if (TableExists("glpi_plugin_fusioninventory_deployorders") && TableExists("glpi_plugin_fusinvdeploy_checks") && TableExists("glpi_plugin_fusinvdeploy_files") && TableExists("glpi_plugin_fusinvdeploy_actions")) {
        //add json field in deploy order table to store datas from old misc tables
        $field_created = $migration->addField("glpi_plugin_fusioninventory_deployorders", "json", "longtext DEFAULT NULL");
        $migration->migrationOneTable("glpi_plugin_fusioninventory_deployorders");
        $final_datas = array();
        //== glpi_plugin_fusioninventory_deployorders ==
        $o_query = "SELECT * FROM glpi_plugin_fusioninventory_deployorders";
        $o_res = $DB->query($o_query);
        while ($o_datas = $DB->fetch_assoc($o_res)) {
            $order_id = $o_datas['id'];
            $o_line = array();
            $of_line = array();
            $o_line['checks'] = array();
            $o_line['actions'] = array();
            $o_line['associatedFiles'] = array();
            //=== Checks ===
            if (TableExists("glpi_plugin_fusinvdeploy_checks")) {
                $c_query = "SELECT type, path, value, 'error' as `return`\n               FROM glpi_plugin_fusinvdeploy_checks\n               WHERE plugin_fusinvdeploy_orders_id = {$order_id}\n               ORDER BY ranking ASC";
                $c_res = $DB->query($c_query);
                $c_i = 0;
                while ($c_datas = $DB->fetch_assoc($c_res)) {
                    foreach ($c_datas as $c_key => $c_value) {
                        //specific case for filesytem sizes, convert to bytes
                        if (!empty($c_value) && is_numeric($c_value) && $c_datas['type'] !== 'freespaceGreater') {
                            $c_value = $c_value * 1024 * 1024;
                        }
                        //construct job check entry
                        $o_line['checks'][$c_i][$c_key] = $c_value;
                    }
                    $c_i++;
                }
            }
            $files_list = array();
            //=== Files ===
            if (TableExists("glpi_plugin_fusinvdeploy_files")) {
                $f_query = "SELECT id, name, is_p2p as p2p, filesize, mimetype, " . "p2p_retention_days as `p2p-retention-duration`, uncompress, sha512 " . "FROM glpi_plugin_fusinvdeploy_files " . "WHERE plugin_fusinvdeploy_orders_id = {$order_id}";
                $f_res = $DB->query($f_query);
                while ($f_datas = $DB->fetch_assoc($f_res)) {
                    //jump to next entry if sha512 is empty
                    // This kind of entries could happen sometimes on upload errors
                    if (empty($f_datas['sha512'])) {
                        continue;
                    }
                    //construct job file entry
                    $o_line['associatedFiles'][] = $f_datas['sha512'];
                    foreach ($f_datas as $f_key => $f_value) {
                        //we don't store the sha512 field in json
                        if ($f_key == "sha512" || $f_key == "id" || $f_key == "filesize" || $f_key == "mimetype") {
                            continue;
                        }
                        //construct order file entry
                        $of_line[$f_datas['sha512']][$f_key] = $f_value;
                    }
                    if (!in_array($f_datas['sha512'], $files_list)) {
                        $files_list[] = $f_datas['sha512'];
                    }
                }
            }
            //=== Actions ===
            $cmdStatus['RETURNCODE_OK'] = 'okCode';
            $cmdStatus['RETURNCODE_KO'] = 'errorCode';
            $cmdStatus['REGEX_OK'] = 'okPattern';
            $cmdStatus['REGEX_KO'] = 'errorPattern';
            if (TableExists("glpi_plugin_fusinvdeploy_actions")) {
                $a_query = "SELECT *\n               FROM glpi_plugin_fusinvdeploy_actions\n               WHERE plugin_fusinvdeploy_orders_id = {$order_id}\n               ORDER BY ranking ASC";
                $a_res = $DB->query($a_query);
                $a_i = 0;
                while ($a_datas = $DB->fetch_assoc($a_res)) {
                    //get type
                    $type = strtolower(str_replace("PluginFusinvdeployAction_", "", $a_datas['itemtype']));
                    //specific case for command type
                    $type = str_replace("command", "cmd", $type);
                    //table for action itemtype
                    $a_table = getTableForItemType($a_datas['itemtype']);
                    //get table fields
                    $at_query = "SELECT *\n                  FROM {$a_table}\n                  WHERE id = " . $a_datas['items_id'];
                    $at_res = $DB->query($at_query);
                    while ($at_datas = $DB->fetch_assoc($at_res)) {
                        foreach ($at_datas as $at_key => $at_value) {
                            //we don't store the id field of action itemtype table in json
                            if ($at_key == "id") {
                                continue;
                            }
                            //specific case for 'path' field
                            if ($at_key == "path") {
                                $o_line['actions'][$a_i][$type]['list'][] = $at_value;
                            } else {
                                //construct job actions entry
                                $o_line['actions'][$a_i][$type][$at_key] = $at_value;
                            }
                        }
                        //specific case for commands : we must add status and env vars
                        if ($a_datas['itemtype'] === "PluginFusinvdeployAction_Command") {
                            $ret_cmd_query = "SELECT type, value\n                        FROM glpi_plugin_fusinvdeploy_actions_commandstatus\n                        WHERE plugin_fusinvdeploy_commands_id = " . $at_datas['id'];
                            $ret_cmd_res = $DB->query($ret_cmd_query);
                            while ($res_cmd_datas = $DB->fetch_assoc($ret_cmd_res)) {
                                // Skip empty retchecks type:
                                // This surely means they have been drop at some point but entry has not been
                                // removed from database.
                                if (!empty($res_cmd_datas['type'])) {
                                    //construct command status array entry
                                    $o_line['actions'][$a_i][$type]['retChecks'][] = array('type' => $cmdStatus[$res_cmd_datas['type']], 'values' => array($res_cmd_datas['value']));
                                }
                            }
                        }
                    }
                    $a_i++;
                }
            }
            $final_datas[$order_id]['jobs'] = $o_line;
            $final_datas[$order_id]['associatedFiles'] = $of_line;
            unset($o_line);
            unset($of_line);
        }
        $options = 0;
        if (version_compare(PHP_VERSION, '5.3.3') >= 0) {
            $options = $options | JSON_NUMERIC_CHECK;
        }
        if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
            $options = $options | JSON_UNESCAPED_SLASHES;
        }
        //store json in order table
        foreach ($final_datas as $order_id => $data) {
            $json = $DB->escape(json_encode($data, $options));
            $order_query = "UPDATE glpi_plugin_fusioninventory_deployorders\n            SET json = '{$json}'\n            WHERE id = {$order_id}";
            $DB->query($order_query);
        }
    }
    //=== Fileparts ===
    if (TableExists('glpi_plugin_fusinvdeploy_fileparts') && TableExists('glpi_plugin_fusinvdeploy_files')) {
        $files_list = $DB->request('glpi_plugin_fusinvdeploy_files');
        // multipart file datas
        foreach ($files_list as $file) {
            $sha = $file['sha512'];
            if (empty($sha)) {
                continue;
            }
            $shortsha = substr($sha, 0, 6);
            $fp_query = "SELECT  fp.`sha512` as filepart_hash, " . "        f.`sha512`  as file_hash      " . "FROM `glpi_plugin_fusinvdeploy_files` as f " . "INNER JOIN `glpi_plugin_fusinvdeploy_fileparts` as fp " . "ON   f.`id` = fp.`plugin_fusinvdeploy_files_id` " . "     AND f.`shortsha512` = '{$shortsha}' " . "GROUP BY fp.`sha512` " . "ORDER BY fp.`id`";
            $fp_res = $DB->query($fp_query);
            if ($DB->numrows($fp_res) > 0) {
                //print("writing file : " . GLPI_PLUGIN_DOC_DIR."/fusioninventory/files/manifests/{$sha}" . "\n");
                $fhandle = fopen(GLPI_PLUGIN_DOC_DIR . "/fusioninventory/files/manifests/{$sha}", 'w+');
                while ($fp_datas = $DB->fetch_assoc($fp_res)) {
                    if ($fp_datas['file_hash'] === $sha) {
                        fwrite($fhandle, $fp_datas['filepart_hash'] . "\n");
                    }
                }
                fclose($fhandle);
            }
        }
    }
    //migrate fusinvdeploy_files to fusioninventory_deployfiles
    if (TableExists("glpi_plugin_fusinvdeploy_files")) {
        $DB->query("TRUNCATE TABLE `glpi_plugin_fusioninventory_deployfiles`");
        if (FieldExists("glpi_plugin_fusinvdeploy_files", "filesize")) {
            $f_query = implode(array("SELECT  files.`id`, files.`name`,", "        files.`filesize`, files.`mimetype`,", "        files.`sha512`, files.`shortsha512`,", "        files.`create_date`,", "        pkgs.`entities_id`, pkgs.`is_recursive`", "FROM glpi_plugin_fusinvdeploy_files as files", "LEFT JOIN glpi_plugin_fusioninventory_deployorders as orders", "  ON orders.`id` = files.`plugin_fusinvdeploy_orders_id`", "LEFT JOIN glpi_plugin_fusioninventory_deploypackages as pkgs", "  ON orders.`plugin_fusioninventory_deploypackages_id` = pkgs.`id`", "WHERE", "  files.`shortsha512` != \"\""), " \n");
            $f_res = $DB->query($f_query);
            while ($f_datas = $DB->fetch_assoc($f_res)) {
                $entry = array("id" => $f_datas["id"], "name" => $f_datas["name"], "filesize" => $f_datas["filesize"], "mimetype" => $f_datas["mimetype"], "shortsha512" => $f_datas["shortsha512"], "sha512" => $f_datas["sha512"], "comments" => "", "date_mod" => $f_datas["create_date"], "entities_id" => $f_datas["entities_id"], "is_recursive" => $f_datas["is_recursive"]);
                $migration->displayMessage("\n");
                // Check if file exists
                $i_DeployFile = new PluginFusioninventoryDeployFile();
                $migration->displayMessage("migrating file " . $entry['name'] . " sha:" . $entry['sha512'] . "\n");
                if ($i_DeployFile->checkPresenceManifest($entry['sha512'])) {
                    $migration->displayMessage("manifest exists" . "\n");
                    $migration->insertInTable("glpi_plugin_fusioninventory_deployfiles", $entry);
                }
            }
        }
    }
    /**
     * JSON orders fixer:
     *    This piece of code makes sure that JSON orders in database are valid and will fix it
     *    otherwise.
     */
    $orders = $DB->request('glpi_plugin_fusioninventory_deployorders');
    foreach ($orders as $order_config) {
        $pfDeployOrder = new PluginFusioninventoryDeployOrder();
        $json_order = json_decode($order_config['json']);
        //print("deployorders fixer : actual order structure for ID ".$order_config['id']."\n" . print_r($json_order,true) ."\n");
        // Checks for /jobs json property
        if (!isset($json_order->jobs) || !is_object($json_order->jobs)) {
            //print("deployorders fixer : create missing required 'jobs' property\n");
            $json_order->jobs = new stdClass();
        }
        if (!isset($json_order->jobs->checks)) {
            //print("deployorders fixer : create missing required '/jobs/checks' array property\n");
            $json_order->jobs->checks = array();
        }
        if (!isset($json_order->jobs->actions)) {
            //print("deployorders fixer : create missing required '/jobs/actions' array property\n");
            $json_order->jobs->actions = array();
        }
        if (!isset($json_order->jobs->associatedFiles)) {
            //print("deployorders fixer : create missing required '/jobs/associatedFiles' array property\n");
            $json_order->jobs->associatedFiles = array();
        }
        // Checks for /associatedFiles json property
        if (!isset($json_order->associatedFiles) || !is_object($json_order->associatedFiles)) {
            //print("deployorders fixer : create missing required 'associatedFiles' property\n");
            $json_order->associatedFiles = new stdClass();
        }
        //print(
        //"deployorders fixer : final order structure for ID ".$order_config['id']."\n" .
        //   json_encode($json_order,JSON_PRETTY_PRINT) ."\n"
        //);
        $pfDeployOrder::updateOrderJson($order_config['id'], $json_order);
    }
    /**
     * Drop unused tables
     */
    $old_deploy_tables = array('glpi_plugin_fusinvdeploy_actions', 'glpi_plugin_fusinvdeploy_actions_commandenvvariables', 'glpi_plugin_fusinvdeploy_actions_commands', 'glpi_plugin_fusinvdeploy_actions_commandstatus', 'glpi_plugin_fusinvdeploy_actions_copies', 'glpi_plugin_fusinvdeploy_actions_deletes', 'glpi_plugin_fusinvdeploy_actions_messages', 'glpi_plugin_fusinvdeploy_actions_mkdirs', 'glpi_plugin_fusinvdeploy_actions_moves', 'glpi_plugin_fusinvdeploy_checks', 'glpi_plugin_fusinvdeploy_fileparts', 'glpi_plugin_fusinvdeploy_files', 'glpi_plugin_fusinvdeploy_files_mirrors');
    foreach ($old_deploy_tables as $table) {
        $migration->dropTable($table);
    }
    //drop unused views
    $old_deploy_views = array('glpi_plugin_fusinvdeploy_taskjobs', 'glpi_plugin_fusinvdeploy_tasks');
    foreach ($old_deploy_views as $view) {
        $DB->query("DROP VIEW IF EXISTS {$view}");
    }
}
  @author    David Durieux
  @co-author
  @copyright Copyright (c) 2010-2014 FusionInventory team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      http://www.fusioninventory.org/
  @link      http://forge.fusioninventory.org/projects/fusioninventory-for-glpi/
  @since     2010

  ------------------------------------------------------------------------
*/
include "../../../inc/includes.php";
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
Session::checkCentralAccess();
if (!isset($_POST['rand']) && !isset($_POST['subtype'])) {
    exit;
}
$rand = $_POST['rand'];
$mode = $_POST['mode'];
switch ($_POST['type']) {
    case 'check':
        PluginFusioninventoryDeployCheck::displayAjaxValues(NULL, $_POST, $rand, $mode);
        break;
    case 'file':
        PluginFusioninventoryDeployFile::displayAjaxValues(NULL, $_POST, $rand, $mode);
        break;
    case 'action':
        PluginFusioninventoryDeployAction::displayAjaxValues(NULL, $_POST, $rand, $mode);
        break;
}
  (at your option) any later version.

  FusionInventory 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 Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.

  ------------------------------------------------------------------------

  @package   FusionInventory
  @author    Alexandre Delaunay
  @co-author
  @copyright Copyright (c) 2010-2014 FusionInventory team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      http://www.fusioninventory.org/
  @link      http://forge.fusioninventory.org/projects/fusioninventory-for-glpi/
  @since     2010

  ------------------------------------------------------------------------
*/
$AJAX_INCLUDE = 1;
include "../../../inc/includes.php";
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
Session::checkLoginUser();
PluginFusioninventoryDeployFile::getServerFileTree($_REQUEST);
 /**
  * Used to import package
  *
  */
 function importPackage($zipfile)
 {
     $zip = new ZipArchive();
     $pfDeployOrder = new PluginFusioninventoryDeployOrder();
     $pfDeployFile = new PluginFusioninventoryDeployFile();
     $filename = GLPI_PLUGIN_DOC_DIR . "/fusioninventory/files/import/" . $zipfile;
     $extract_folder = GLPI_PLUGIN_DOC_DIR . "/fusioninventory/files/import/" . $zipfile . ".extract";
     if ($zip->open($filename, ZipArchive::CREATE) == TRUE) {
         $zip->extractTo($extract_folder);
         $zip->close();
     }
     $json_string = file_get_contents($extract_folder . "/information.json");
     $a_info = json_decode($json_string, true);
     // Find package with this uuid
     $a_packages = $this->find("`uuid`='" . $a_info['package']['uuid'] . "'");
     if (count($a_packages) == 0) {
         // Create it
         $_SESSION['tmp_clone_package'] = true;
         $packages_id = $this->add($a_info['package']);
         unset($_SESSION['tmp_clone_package']);
         foreach ($a_info['orders'] as $input) {
             $input['plugin_fusioninventory_deploypackages_id'] = $packages_id;
             $pfDeployOrder->add($input);
             echo "|";
         }
         foreach ($a_info['files'] as $input) {
             $pfDeployFile->add($input);
         }
     } else {
         // Update current
     }
     // Copy files
     foreach ($a_info['manifests'] as $manifest) {
         rename($extract_folder . "/files/manifests/" . $manifest, GLPI_PLUGIN_DOC_DIR . "/fusioninventory/files/manifests/" . $manifest);
     }
     foreach ($a_info['repository'] as $repository) {
         $split = explode('/', $repository);
         array_pop($split);
         $folder = '';
         foreach ($split as $dir) {
             $folder .= '/' . $dir;
             if (!file_exists(GLPI_PLUGIN_DOC_DIR . "/fusioninventory/files/repository" . $folder)) {
                 mkdir(GLPI_PLUGIN_DOC_DIR . "/fusioninventory/files/repository" . $folder);
             }
         }
         rename($extract_folder . "/files/repository/" . $repository, GLPI_PLUGIN_DOC_DIR . "/fusioninventory/files/repository/" . $repository);
     }
 }
}
if (!isset($_REQUEST['orders_id']) && !isset($_REQUEST['rand']) && !isset($_REQUEST['subtype'])) {
    exit;
}
if (!is_numeric($_REQUEST['orders_id'])) {
    Toolbox::logDebug("Error: orders_id in request is not an integer");
    Toolbox::logDebug(var_dump($_REQUEST['orders_id']));
    exit;
}
$order = new PluginFusioninventoryDeployOrder();
$order->getFromDB($_REQUEST['orders_id']);
//TODO: In the displayForm function, $_REQUEST is somewhat too much for the '$datas' parameter
// I think we could use only $order -- Kevin 'kiniou' Roy
switch ($_REQUEST['subtype']) {
    case 'check':
        PluginFusioninventoryDeployCheck::displayForm($order, $_REQUEST, $_REQUEST['rand'], $_POST['mode']);
        break;
    case 'file':
        PluginFusioninventoryDeployFile::displayForm($order, $_REQUEST, $_REQUEST['rand'], $_POST['mode']);
        break;
    case 'action':
        PluginFusioninventoryDeployAction::displayForm($order, $_REQUEST, $_REQUEST['rand'], $_POST['mode']);
        break;
    case 'package_json_debug':
        if (isset($order->fields['json'])) {
            PluginFusioninventoryDeployPackage::display_json_debug($order);
        } else {
            echo "{}";
        }
        break;
}
/**
 * Unregister the invalid manifests from database.
 */
function unregisterInvalidManifests($logger, $dryrun, $invalid_manifests)
{
    global $DB;
    $logger->info("Unregistering " . count($invalid_manifests) . " manifests from database.");
    $pfDeployFile = new PluginFusioninventoryDeployFile();
    foreach ($invalid_manifests as $manifest) {
        $short_sha512 = substr($manifest, 0, 6);
        $data = $pfDeployFile->find("shortsha512 = '" . $short_sha512 . "'");
        foreach ($data as $config) {
            $pfDeployFile->getFromDB($config['id']);
            $logger->info("Unregister file " . $pfDeployFile->fields['name']);
            if (!$dryrun) {
                $pfDeployFile->deleteFromDB();
            }
        }
    }
}
 static function displayList(PluginFusioninventoryDeployOrder $order, $datas, $rand)
 {
     global $CFG_GLPI;
     $pfDeployPackage = new PluginFusioninventoryDeployPackage();
     $pfDeployPackage->getFromDB($order->fields['plugin_fusioninventory_deploypackages_id']);
     $checks_types = self::getTypes();
     echo "<table class='tab_cadrehov package_item_list' id='table_check_{$rand}'>";
     $i = 0;
     foreach ($datas['jobs']['checks'] as $check) {
         //specific case for filesystem size
         if (is_numeric($check['value'])) {
             if ($check['type'] == "freespaceGreater") {
                 $check['value'] = $check['value'] * 1024 * 1024;
             }
             $check['value'] = PluginFusioninventoryDeployFile::processFilesize($check['value']);
         }
         echo Search::showNewLine(Search::HTML_OUTPUT, $i % 2);
         if ($pfDeployPackage->can($pfDeployPackage->getID(), UPDATE)) {
             echo "<td class='control'>";
             echo "<input type='checkbox' name='check_entries[]' value='{$i}' />";
             echo "</td>";
         }
         echo "<td>";
         echo "<a class='edit'" . "onclick=\"edit_subtype('check', {$order->fields['id']}, {$rand} ,this)\">" . $checks_types[$check['type']] . "</a><br />";
         echo $check['path'];
         if (!empty($check['value'])) {
             echo "&nbsp;&nbsp;&nbsp;<b>";
             if (strpos($check['type'], "Greater") !== FALSE) {
                 echo "&gt;";
             } else {
                 if (strpos($check['type'], "Lower") !== FALSE) {
                     echo "&lt;";
                 } else {
                     echo "=";
                 }
             }
             echo "</b>&nbsp;&nbsp;&nbsp;";
             echo $check['value'];
         }
         echo "</td>";
         if ($pfDeployPackage->can($pfDeployPackage->getID(), UPDATE)) {
             echo "<td class='rowhandler control' title='" . __('drag', 'fusioninventory') . "'><div class='drag row'></div></td>";
         }
         echo "</tr>";
         $i++;
     }
     if ($pfDeployPackage->can($pfDeployPackage->getID(), UPDATE)) {
         echo "<tr><th>";
         Html::checkAllAsCheckbox("checksList{$rand}", mt_rand());
         echo "</th><th colspan='3' class='mark'></th></tr>";
     }
     echo "</table>";
     if ($pfDeployPackage->can($pfDeployPackage->getID(), UPDATE)) {
         echo "&nbsp;&nbsp;<img src='" . $CFG_GLPI["root_doc"] . "/pics/arrow-left.png' alt='' />";
         echo "<input type='submit' name='delete' value=\"" . __('Delete', 'fusioninventory') . "\" class='submit' />";
     }
 }