protected static function SendRequestToGateway($requestString, $testAccount, $gateway)
 {
     $serverUrl = 'https://';
     if ($testAccount) {
         $serverUrl .= 'test';
     }
     switch (strtolower($gateway)) {
         default:
         case 'worldnet':
             $serverUrl .= 'payments.worldnettps.com';
             break;
         case 'cashflows':
             $serverUrl .= 'cashflows.worldnettps.com';
             break;
         case 'payius':
             $serverUrl .= 'payments.payius.com';
             break;
         case 'pago':
             $serverUrl .= 'payments.pagotechnology.com';
             break;
         case 'globalone':
             $serverUrl .= 'payments.globalone.me';
             break;
     }
     $XMLSchemaFile = $serverUrl . '/merchant/gateway.xsd';
     $serverUrl .= '/merchant/xmlpayment';
     $requestXML = new DOMDocument("1.0", "utf-8");
     $requestXML->formatOutput = true;
     $requestXML->loadXML($requestString);
     if (!$requestXML->schemaValidate($XMLSchemaFile)) {
         die('<b>XML VALIDATION FAILED AGAINST SCHEMA:</b>' . $XMLSchemaFile . libxml_display_errors());
     }
     unset($requestXML);
     // Initialisation
     $ch = curl_init();
     // Set parameters
     curl_setopt($ch, CURLOPT_URL, $serverUrl);
     // Return a variable instead of posting it directly
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
     //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
     curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-type: application/xml'));
     // Activate the POST method
     curl_setopt($ch, CURLOPT_POST, 1);
     // Request
     curl_setopt($ch, CURLOPT_POSTFIELDS, $requestString);
     // execute the connection
     $result = curl_exec($ch);
     // Close it
     curl_close($ch);
     if ($result != '') {
         return $result;
     } else {
         return '<?xml version="1.0" encoding="UTF-8"?><ERROR><ERRORSTRING>Content is not allowed in prolog.</ERRORSTRING></ERROR>';
     }
 }
                     $cache = $data;
                 }
             }
             // end of fix
             if (!xml_parse($xml_parser, $data, feof($fp))) {
                 // if reading of the xml file in not successfull :
                 // set errorFound, set error msg, break while statement
                 $errorFound = true;
                 array_push($errorMsgs, $langErrorReadingManifest);
                 // Since manifest.xml cannot be parsed, test versus IMS CP 1.4.4 XSD (compatible with all SCORM packages as well)
                 require_once 'include/validateXML.php';
                 libxml_use_internal_errors(true);
                 $xml = new DOMDocument();
                 $xml->load($manifestPath . "imsmanifest.xml");
                 if (!$xml->schemaValidate($urlServer . 'modules/learnPath/export/imscp_v1p2.xsd')) {
                     $messages = libxml_display_errors();
                     array_push($errorMsgs, $langErrorValidatingManifest . $messages);
                 }
                 break;
             }
         }
         // close file
         fclose($fp);
     }
     // liberate parser ressources
     xml_parser_free($xml_parser);
 }
 //if (!$errorFound)
 // check if all starts assets files exist in the zip file
 if (!$errorFound) {
     array_push($okMsgs, $langOkManifestRead);
Esempio n. 3
0
                            echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
                        } else {
                            exit("image error");
                        }
                    }
                } else {
                }
                break;
            default:
                break;
        }
    }
}
//check if shema is validate
if (!$xml->schemaValidate('contactListSchema.xsd')) {
    $value = libxml_display_errors();
    $dr = $value;
    appendToHtml('
    <div class="alert alert-danger alert-fixed-bottom" id="alertMsg">
  <strong>Warning !!!!</strong>' . $dr . '
<button onclick="hideAlert()">Make Modification</button>"</div>');
} else {
    //save the xml is validation o.k
    $xml->save("contactList.xml");
    appendToHtml('
    <div class="alert alert-success alert-fixed-bottom" id="alertMsg">
  <strong>Success!</strong>' . $dr . '
<button onclick="goToMainPage()">Go to main Page</button>"</div>');
}
$html = str_replace("{{alert}}", $html, $htmlFile);
// replaces placeholder with $username
Esempio n. 4
0
<?php

# validateAIML.php
$status = '';
if (!empty($_FILES)) {
    $uploadDir = "upload/";
    $target = $uploadDir . basename($_FILES['uploaded']['name']);
    if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) {
        $fileName = str_replace($uploadDir, '' . $target);
        libxml_use_internal_errors(true);
        $xml = new DOMDocument();
        $xml->load($target);
        if (!$xml->schemaValidate('config/aiml.xsd')) {
            $status = "File {$fileName} is invalid!<br />\n";
            libxml_display_errors();
        } else {
            $status = "File {$fileName} is valid.<br />\n";
        }
    }
}
function libxml_display_error($error)
{
    $return = "<br/>\n";
    switch ($error->level) {
        case LIBXML_ERR_WARNING:
            $return .= "<b>Warning {$error->code}</b>: ";
            break;
        case LIBXML_ERR_ERROR:
            $return .= "<b>Error {$error->code}</b>: ";
            break;
        case LIBXML_ERR_FATAL:
$xml->formatOutput = true;
$xml->loadXML($XML_TOT);
if ($xml->schemaValidate('./datasetAppaltiL190.xsd')) {
    echo '
    <div class="alert alert-success">
    	<strong>Il documento è corretto.</strong>
    	<p>Scarica il <a href="../../crea_xml_avcp_query.php?anno=' . $anno . '">file XML</a>
    	da pubblicare sul sito o torna alla <a href="../../">homepage</a></p>
    </div>';
} else {
    echo '
    <div class="alert alert-error">
    	<strong>Il documento contiene degli errori e non può essere validato!</strong>
    	<p>Torna alla <a href="../../">homepage</a></p>
    </div>';
    $errorLine = libxml_display_errors();
    // Evidenzio le linee degli errori per prism.js, plugin line-highlight
    // http://prismjs.com/plugins/line-highlight/
    $outErrorLine = null;
    foreach ($errorLine as $el) {
        $outErrorLine .= $el . ',';
    }
}
?>
			</div>
			</div>
		</div>
		<div class="row">
			<div class="span12">
				<div class="well">
				<?php 
Esempio n. 6
0
function parseAIML($fn, $aimlContent)
{
    if (empty($aimlContent)) {
        return "File {$fn} was empty!";
    }
    global $debugmode, $bot_id, $default_charset;
    $fileName = basename($fn);
    $success = false;
    $dbconn = db_open();
    #Clear the database of the old entries
    $sql = "DELETE FROM `aiml`  WHERE `filename` = '{$fileName}' AND bot_id = '{$bot_id}'";
    if (isset($_POST['clearDB'])) {
        $x = updateDB($sql);
    }
    $myBot_id = isset($_POST['bot_id']) ? $_POST['bot_id'] : $bot_id;
    # Read new file into the XML parser
    $sql_start = "insert into `aiml` (`id`, `bot_id`, `aiml`, `pattern`, `thatpattern`, `template`, `topic`, `filename`, `php_code`) values\n";
    $sql = $sql_start;
    $sql_template = "(NULL, {$myBot_id}, '[aiml_add]', '[pattern]', '[that]', '[template]', '[topic]', '{$fileName}', ''),\n";
    # Validate the incoming document
    /*******************************************************/
    /*       Set up for validation from a common DTD       */
    /*       This will involve removing the XML and        */
    /*       AIML tags from the beginning of the file      */
    /*       and replacing them with our own tags          */
    /*******************************************************/
    $validAIMLHeader = '<?xml version="1.0" encoding="[charset]"?>
<!DOCTYPE aiml PUBLIC "-//W3C//DTD Specification Version 1.0//EN" "http://www.program-o.com/xml/aiml.dtd">
<aiml version="1.0.1" xmlns="http://alicebot.org/2001/AIML-1.0.1">';
    $validAIMLHeader = str_replace('[charset]', $default_charset, $validAIMLHeader);
    $aimlTagStart = stripos($aimlContent, '<aiml', 0);
    $aimlTagEnd = strpos($aimlContent, '>', $aimlTagStart) + 1;
    $aimlFile = $validAIMLHeader . substr($aimlContent, $aimlTagEnd);
    //die('<pre>' . htmlentities("File contents:<br />\n$aimlFile"));
    try {
        libxml_use_internal_errors(true);
        $xml = new DOMDocument();
        $xml->loadXML($aimlFile);
        //$xml->validate();
        $aiml = new SimpleXMLElement($xml->saveXML());
        $rowCount = 0;
        if (!empty($aiml->topic)) {
            foreach ($aiml->topic as $topicXML) {
                # handle any topic tag(s) in the file
                $topicAttributes = $topicXML->attributes();
                $topic = $topicAttributes['name'];
                foreach ($topicXML->category as $category) {
                    $fullCategory = $category->asXML();
                    $pattern = $category->pattern;
                    $pattern = str_replace("'", ' ', $pattern);
                    $that = $category->that;
                    $template = $category->template->asXML();
                    $template = str_replace('<template>', '', $template);
                    $template = str_replace('</template>', '', $template);
                    $aiml_add = str_replace("\r\n", '', $fullCategory);
                    # Strip CRLF from category (windows)
                    $aiml_add = str_replace("\n", '', $aiml_add);
                    # Strip LF from category (mac/*nix)
                    $sql_add = str_replace('[aiml_add]', mysql_real_escape_string($aiml_add), $sql_template);
                    $sql_add = str_replace('[pattern]', $pattern, $sql_add);
                    $sql_add = str_replace('[that]', $that, $sql_add);
                    $sql_add = str_replace('[template]', mysql_real_escape_string($template), $sql_add);
                    $sql_add = str_replace('[topic]', $topic, $sql_add);
                    $sql .= "{$sql_add}";
                    $rowCount++;
                    if ($rowCount >= 100) {
                        $rowCount = 0;
                        $sql = rtrim($sql, ",\n") . ';';
                        $success = updateDB($sql) >= 0 ? true : false;
                        $sql = $sql_start;
                    }
                }
            }
        }
        if (!empty($aiml->category)) {
            foreach ($aiml->category as $category) {
                $fullCategory = $category->asXML();
                $pattern = $category->pattern;
                $pattern = str_replace("'", ' ', $pattern);
                $that = $category->that;
                $template = $category->template->asXML();
                $template = str_replace('<template>', '', $template);
                $template = str_replace('</template>', '', $template);
                $aiml_add = str_replace("\r\n", '', $fullCategory);
                # Strip CRLF from category (windows)
                $aiml_add = str_replace("\n", '', $aiml_add);
                # Strip LF from category (mac/*nix)
                $sql_add = str_replace('[aiml_add]', mysql_real_escape_string($aiml_add), $sql_template);
                $sql_add = str_replace('[pattern]', $pattern, $sql_add);
                $sql_add = str_replace('[that]', $that, $sql_add);
                $sql_add = str_replace('[template]', mysql_real_escape_string($template), $sql_add);
                $sql_add = str_replace('[topic]', '', $sql_add);
                $sql .= "{$sql_add}";
                $rowCount++;
                if ($rowCount >= 100) {
                    $rowCount = 0;
                    $sql = rtrim($sql, ",\n") . ';';
                    $success = updateDB($sql) >= 0 ? true : false;
                    $sql = $sql_start;
                }
            }
        }
        if ($sql != $sql_start) {
            $sql = rtrim($sql, ",\n") . ';';
            $success = updateDB($sql) >= 0 ? true : false;
        }
        $msg = "Successfully added {$fileName} to the database.<br />\n";
    } catch (Exception $e) {
        $success = false;
        $msg = "There was a problem adding file {$fileName} to the database. Please validate the file and try again.<br >\n";
        $msg = libxml_display_errors($msg);
    }
    return $msg;
}
function doImport($course_code, $webDir, $scoFileSize, $scoFileName, $displayExtraMessages = false) {
    global $langUnamedPath;
    global $langFileScormError;
    global $langNotice;
    global $langMaxFileSize;
    global $langNoSpace;
    global $langOkFileReceived;
    global $langErrorNoZlibExtension;
    global $langErrorReadingZipFile;
    global $langZipNoPhp;
    global $langErrortExtractingManifest;
    global $langErrorFileMustBeZip;
    global $langErrorOpeningManifest;
    global $langOkManifestFound;
    global $langErrorReadingManifest;
    global $langOkManifestRead;
    global $langErrorAssetNotFound;
    global $langErrorNoModuleInPackage;
    global $langErrorSql;
    global $langOkChapterHeadAdded;
    global $langUnamedModule;
    global $langDefaultModuleComment;
    global $langDefaultModuleAddedComment;
    global $langOkModuleAdded;
    global $langOkDefaultTitleUsed;
    global $langDefaultLearningPathComment;
    global $langOkDefaultCommentUsed;
    global $langSuccessOk;
    global $langError;
    global $langInstalled;
    global $langNotInstalled;
    global $langBack;
    global $errorFound;
    global $elementsPile;
    global $itemsPile;
    global $manifestData;
    global $iterator;
    global $course_code;
    global $course_id;
    global $langErrorValidatingManifest;
    global $urlServer;

    $pwd = getcwd();

    // init msg arays
    $okMsgs = array();
    $errorMsgs = array();

    $maxFilledSpace = 100000000;

    $courseDir = "/courses/" . $course_code . "/scormPackages/";
    $tempDir = "/courses/" . $course_code . "/temp/";
    $baseWorkDir = $webDir . $courseDir; // path_id
    $tempWorkDir = $webDir . $tempDir;

    if (!is_dir($baseWorkDir)) {
        claro_mkdir($baseWorkDir, CLARO_FILE_PERMISSIONS);
    }

    // arrays used to store inserted ids
    $insertedModule_id = array();
    $insertedAsset_id = array();

    $lpName = $langUnamedPath;

    // we need a new path_id for this learning path so we prepare a line in DB
    // this line will be removed if an error occurs
    $rankMax = 1 + intval(Database::get()->querySingle("SELECT MAX(`rank`) AS max
            FROM `lp_learnPath` WHERE `course_id` = ?d", $course_id)->max);

    $tempPathId = Database::get()->query("INSERT INTO `lp_learnPath`
            (`course_id`, `name`,`visible`,`rank`,`comment`)
            VALUES (?d, ?s, 0, ?d,'')", $course_id, $lpName, $rankMax)->lastInsertID;
    $baseWorkDir .= "path_" . $tempPathId;

    if (!is_dir($baseWorkDir)) {
        claro_mkdir($baseWorkDir, CLARO_FILE_PERMISSIONS);
    }

    // unzip package
    require_once("include/pclzip/pclzip.lib.php");

    /*
     * Check the file size doesn't exceed
     * the maximum file size authorized in the directory
     */

    if (!enough_size($scoFileSize, $baseWorkDir, $maxFilledSpace)) {
        $errorFound = true;
        array_push($errorMsgs, $langNoSpace);
    }

    /*
     * Unzipping stage
     */ elseif (preg_match("/.zip$/i", $scoFileName)) {
        array_push($okMsgs, $langOkFileReceived . basename($scoFileName));

        if (!function_exists('gzopen')) {
            $errorFound = true;
            array_push($errorMsgs, $langErrorNoZlibExtension);
        } else {
            $zipFile = new pclZip($tempWorkDir . $scoFileName);
            $is_allowedToUnzip = true; // default initialisation
            // Check the zip content (real size and file extension)

            $zipContentArray = $zipFile->listContent();

            if ($zipContentArray == 0) {
                $errorFound = true;
                array_push($errorMsgs, $langErrorReadingZipFile);
            }

            $pathToManifest = ""; // empty by default because we can expect that the manifest.xml is in the root of zip file
            $pathToManifestFound = false;
            $realFileSize = 0;

            foreach ($zipContentArray as $thisContent) {
                if (preg_match('/.(php[[:digit:]]?|phtml)$/i', $thisContent['filename'])) {
                    $errorFound = true;
                    array_push($errorMsgs, $langZipNoPhp);
                    $is_allowedToUnzip = false;
                    break;
                }

                if (strtolower(substr($thisContent['filename'], -15)) == "imsmanifest.xml") {
                    // this check exists to find the less deep imsmanifest.xml in the zip if there are several imsmanifest.xml
                    // if this is the first imsmanifest.xml we found OR path to the new manifest found is shorter (less deep)
                    if (!$pathToManifestFound || ( count(explode('/', $thisContent['filename'])) < count(explode('/', $pathToManifest . "imsmanifest.xml")) )
                    ) {
                        $pathToManifest = substr($thisContent['filename'], 0, -15);
                        $pathToManifestFound = true;
                    }
                }
                $realFileSize += $thisContent['size'];
            }

            if (!isset($alreadyFilledSpace)) {
                $alreadyFilledSpace = 0;
            }

            if (($realFileSize + $alreadyFilledSpace) > $maxFilledSpace) { // check the real size.
                $errorFound = true;
                array_push($errorMsgs, $langNoSpace);
                $is_allowedToUnzip = false;
            }

            if ($is_allowedToUnzip && !$errorFound) {
                // PHP extraction of zip file using zlib

                chdir($baseWorkDir);
                $unzippingState = $zipFile->extract(PCLZIP_OPT_BY_NAME, $pathToManifest . "imsmanifest.xml", PCLZIP_OPT_PATH, '', PCLZIP_OPT_REMOVE_PATH, $pathToManifest);
                if ($unzippingState == 0) {
                    $errorFound = true;
                    array_push($errorMsgs, $langErrortExtractingManifest);
                }
            } //end of if ($is_allowedToUnzip)
        } // end of if (!function_exists...
    } else {
        $errorFound = true;
        array_push($errorMsgs, $langErrorFileMustBeZip . ": " . basename($scoFileName));
    }
    // find xmlmanifest (must be in root else ==> cancel operation, delete files)
    // parse xml manifest to find :
    // package name - learning path name
    // SCO list
    // start asset path

    if (!$errorFound) {
        $elementsPile = array(); // array used to remember where we are in the arborescence of the XML file
        $itemsPile = array(); // array used to remember parents items
        // declaration of global arrays used for extracting needed info from manifest for the new modules/SCO
        $manifestData = array();   // for global data  of the learning path
        $manifestData['items'] = array(); // item tags content (attributes + some child elements data (title for an example)
        $manifestData['scos'] = array();  // for path of start asset id of each new module to create

        $iterator = 0; // will be used to increment position of paths in manifestData['scosPaths"]
        // and to have the names at the same pos if found
        //$xml_parser = xml_parser_create();
        $xml_parser = xml_parser_create('utf-8');
        xml_set_element_handler($xml_parser, "startElement", "endElement");
        xml_set_character_data_handler($xml_parser, "elementData");

        // this file has to exist in a SCORM conformant package
        // this file must be in the root the sent zip
        $file = "imsmanifest.xml";

        if (!($fp = @fopen($file, "r"))) {
            $errorFound = true;
            array_push($errorMsgs, $langErrorOpeningManifest);
        } else {
            if (!isset($manifestPath)) {
                $manifestPath = "";
            }

            array_push($okMsgs, $langOkManifestFound . $manifestPath . "imsmanifest.xml");

            while ($data = str_replace("\n", "", fread($fp, 4096))) {
                // fix for fread breaking thing
                // msg from "ml at csite dot com" 02-Jul-2003 02:29 on http://www.php.net/xml
                // preg expression has been modified to match tag with inner attributes

                if (!isset($cache)) {
                    $cache = "";
                }

                $data = $cache . $data;
                if (!feof($fp)) {
                    // search fo opening, closing, empty tags (with or without attributes)
                    if (preg_match_all("/<[^\>]*.>/", $data, $regs)) {
                        $lastTagname = $regs[0][count($regs[0]) - 1];
                        $split = false;
                        for ($i = strlen($data) - strlen($lastTagname); $i >= strlen($lastTagname); $i--) {
                            if ($lastTagname == substr($data, $i, strlen($lastTagname))) {
                                $cache = substr($data, $i, strlen($data));
                                $data = substr($data, 0, $i);
                                $split = true;
                                break;
                            }
                        }
                    }

                    if (!$split) {
                        $cache = $data;
                    }
                }
                // end of fix

                if (!xml_parse($xml_parser, $data, feof($fp))) {
                    // if reading of the xml file in not successfull :
                    // set errorFound, set error msg, break while statement

                    $errorFound = true;
                    array_push($errorMsgs, $langErrorReadingManifest);
                    // Since manifest.xml cannot be parsed, test versus IMS CP 1.4.4 XSD (compatible with all SCORM packages as well)
                    require_once 'include/validateXML.php';
                    libxml_use_internal_errors(true);
                    
                    $xml = new DOMDocument();
                    $xml->load($manifestPath."imsmanifest.xml");
                    
                    if (!$xml->schemaValidate($urlServer . 'modules/learnPath/export/imscp_v1p2.xsd')) {
                        $messages = libxml_display_errors();
                        
                        array_push($errorMsgs, $langErrorValidatingManifest . $messages);
                    }
                    break;
                }
            }
            // close file
            fclose($fp);
        }

        // liberate parser ressources
        xml_parser_free($xml_parser);
    } //if (!$errorFound)
    // check if all starts assets files exist in the zip file
    if (!$errorFound) {
        array_push($okMsgs, $langOkManifestRead);
        if (sizeof($manifestData['items']) > 0) {
            // if there is items in manifest we look for sco type resources referenced in idientifierref
            foreach ($manifestData['items'] as $item) {
                if (!isset($item['identifierref']) || $item['identifierref'] == '') {
                    break; // skip if no ressource reference in item (item is probably a chapter head)
                }

                    
// find the file in the zip file
                $scoPathFound = false;

                for ($i = 0; $i < sizeof($zipContentArray); $i++) {
                    if (isset($manifestData['scos'][$item['identifierref']]['xml:base'])) {
                        $extraPath = $manifestData['scos'][$item['identifierref']]['xml:base'];
                    } else if (isset($manifestData['assets'][$item['identifierref']]['xml:base'])) {
                        $extraPath = $manifestData['assets'][$item['identifierref']]['xml:base'];
                    } else {
                        $extraPath = "";
                    }

                    if (isset($zipContentArray[$i]["filename"]) &&
                            ( ( isset($manifestData['scos'][$item['identifierref']]['href']) && $zipContentArray[$i]["filename"] == $pathToManifest . $extraPath . $manifestData['scos'][$item['identifierref']]['href']) || (isset($manifestData['assets'][$item['identifierref']]['href']) && $zipContentArray[$i]["filename"] == $pathToManifest . $extraPath . $manifestData['assets'][$item['identifierref']]['href'])
                            )
                    ) {
                        $scoPathFound = true;
                        break;
                    }
                }

                if (!$scoPathFound) {
                    $errorFound = true;
                    array_push($errorMsgs, $langErrorAssetNotFound . $manifestData['scos'][$item['identifierref']]['href']);
                    break;
                }
            }
        } //if (sizeof ...)
        elseif (sizeof($manifestData['scos']) > 0) {
            // if there ie no items in the manifest file
            // check for scos in resources

            foreach ($manifestData['scos'] as $sco) {
                // find the file in the zip file
                // create a fake item so that the rest of the procedure (add infos of in db) can remains the same
                $manifestData['items'][$sco['href']]['identifierref'] = $sco['href'];
                $manifestData['items'][$sco['href']]['parameters'] = '';
                $manifestData['items'][$sco['href']]['isvisible'] = "true";
                $manifestData['items'][$sco['href']]['title'] = $sco['title'];
                $manifestData['items'][$sco['href']]['description'] = $sco['description'];
                $manifestData['items'][$attributes['IDENTIFIER']]['parent'] = 0;

                $scoPathFound = false;

                for ($i = 0; $i < sizeof($zipContentArray); $i++) {
                    if ($zipContentArray[$i]["filename"] == $sco['href']) {
                        $scoPathFound = true;
                        break;
                    }
                }
                if (!$scoPathFound) {
                    $errorFound = true;
                    array_push($errorMsgs, $langErrorAssetNotFound . $sco['href']);
                    break;
                }
            }
        } // if sizeof (...ΰ
        else {
            $errorFound = true;
            array_push($errorMsgs, $langErrorNoModuleInPackage);
        }
    }// if errorFound
    // unzip all files
    // &&
    // insert corresponding entries in database

    if (!$errorFound) {
        // PHP extraction of zip file using zlib
        chdir($baseWorkDir);

        // PCLZIP_OPT_PATH is the path where files will be extracted ( '' )
        // PLZIP_OPT_REMOVE_PATH suppress a part of the path of the file ( $pathToManifest )
        // the result is that the manifest is in th eroot of the path_# directory and all files will have a path related to the root
        $unzippingState = $zipFile->extract(PCLZIP_OPT_PATH, '', PCLZIP_OPT_REMOVE_PATH, $pathToManifest);

        // insert informations in DB :
        //        - 1 learning path ( already added because we needed its id to create the package directory )
        //        - n modules
        //        - n asset as start asset of modules

        if (sizeof($manifestData['items']) == 0) {
            $errorFound = true;
            array_push($errorMsgs, $langErrorNoModuleInPackage);
        } else {
            $i = 0;
            $insertedLPMid = array(); // array of learnPath_module_id && order of related group
            $inRootRank = 1; // default rank for root module (parent == 0)

            foreach ($manifestData['items'] as $item) {
                if (isset($item['parent']) && isset($insertedLPMid[$item['parent']])) {
                    $parent = $insertedLPMid[$item['parent']]['LPMid'];
                    $rank = $insertedLPMid[$item['parent']]['rank'] ++;
                } else {
                    $parent = 0;
                    $rank = $inRootRank++;
                }

                //-------------------------------------------------------------------------------
                // add chapter head
                //-------------------------------------------------------------------------------

                if ((!isset($item['identifierref']) || $item['identifierref'] == '') && isset($item['title']) && $item['title'] != '') {
                    // add title as a module
                    $chapterTitle = $item['title'];

                    // array of all inserted module ids
                    $insertedModule_id[$i] = Database::get()->query("INSERT INTO `lp_module`
                            (`course_id`, `name`, `comment`, `contentType`, `launch_data`)
                            VALUES (?d, ?s, '', ?s,'')", $course_id, $chapterTitle, CTLABEL_)->lastInsertID;
                    if (!$insertedModule_id[$i]) {
                        $errorFound = true;
                        array_push($errorMsgs, $langErrorSql);
                        break;
                    }
                    // visibility
                    if (isset($item['isvisible']) && $item['isvisible'] != '') {
                        $visibility = ($item['isvisible'] == "true") ? 1 : 0;
                    } else {
                        $visibility = 1; // IMS consider that the default value of 'isvisible' is true
                    }

                    // add title module in the learning path
                    // finally : insert in learning path
                    // get the inserted id of the learnPath_module rel to allow 'parent' link in next inserts
                    $insertedLPMid[$item['itemIdentifier']]['LPMid'] = Database::get()->query("INSERT INTO `lp_rel_learnPath_module`
                            (`learnPath_id`, `module_id`,`rank`, `visible`, `parent`)
                            VALUES (?d, ?d, ?d, ?d, ?d)", $tempPathId, $insertedModule_id[$i], $rank, $visibility, $parent)->lastInsertID;
                    $insertedLPMid[$item['itemIdentifier']]['rank'] = 1;

                    if (!$insertedLPMid[$item['itemIdentifier']]['LPMid']) {
                        $errorFound = true;
                        array_push($errorMsgs, $langErrorSql);
                        break;
                    }
                    if (!$errorFound) {
                        array_push($okMsgs, $langOkChapterHeadAdded . "<i>" . $chapterTitle . "</i>");
                    }
                    $i++;
                    continue;
                }

                // use found title of module or use default title
                if (!isset($item['title']) || $item['title'] == '') {
                    $moduleName = $langUnamedModule;
                } else {
                    $moduleName = $item['title'];
                }

                // set description as comment or default comment
                // look fo description in item description or in sco (resource) description
                // don't remember why I checked for parameters string ... so comment it
                if ((!isset($item['description']) || $item['description'] == '' ) &&
                        (!isset($manifestData['scos'][$item['identifierref']]['description']) /* || $manifestData['scos'][$item['identifierref']]['parameters'] == '' */ )
                ) {
                    $description = $langDefaultModuleComment;
                } else {
                    if (isset($item['description']) && $item['description'] != '') {
                        $description = $item['description'];
                    } else {
                        $description = $manifestData['scos'][$item['identifierref']]['description'];
                    }
                }

                // insert modules and their start asset
                // create new module

                if (!isset($item['datafromlms'])) {
                    $item['datafromlms'] = "";
                }

                // elegxoume an to contentType prepei na einai scorm h asset
                if (isset($manifestData['scos'][$item['identifierref']]['contentTypeFlag']) && $manifestData['scos'][$item['identifierref']]['contentTypeFlag'] == CTSCORMASSET_) {
                    $contentType = CTSCORMASSET_;
                } else {
                    $contentType = CTSCORM_;
                }

                // array of all inserted module ids
                $insertedModule_id[$i] = Database::get()->query("INSERT INTO `lp_module`
                        (`course_id`, `name`, `comment`, `contentType`, `launch_data`)
                        VALUES (?d, ?s, ?s, ?s, ?s)", $course_id, $moduleName, $description, $contentType, $item['datafromlms'])->lastInsertID;
                
                if (!$insertedModule_id[$i]) {
                    $errorFound = true;
                    array_push($errorMsgs, $langErrorSql);
                    break;
                }
                // build asset path
                // a $manifestData['scos'][$item['identifierref']] __SHOULD__ not exist if a $manifestData['assets'][$item['identifierref']] exists
                // so according to IMS we can say that one is empty if the other is filled, so we concat them without more verification than if the var exists.

                // suppress notices
                if (!isset($manifestData['xml:base']['manifest'])) {
                    $manifestData['xml:base']['manifest'] = "";
                }
                if (!isset($manifestData['xml:base']['ressources'])) {
                    $manifestData['xml:base']['ressources'] = "";
                }
                if (!isset($manifestData['scos'][$item['identifierref']]['href'])) {
                    $manifestData['scos'][$item['identifierref']]['href'] = "";
                }
                if (!isset($manifestData['assets'][$item['identifierref']]['href'])) {
                    $manifestData['assets'][$item['identifierref']]['href'] = "";
                }
                if (!isset($manifestData['scos'][$item['identifierref']]['parameters'])) {
                    $manifestData['scos'][$item['identifierref']]['parameters'] = "";
                }
                if (!isset($manifestData['assets'][$item['identifierref']]['parameters'])) {
                    $manifestData['assets'][$item['identifierref']]['parameters'] = "";
                }
                if (!isset($manifestData['items'][$item['itemIdentifier']]['parameters'])) {
                    $manifestData['items'][$item['itemIdentifier']]['parameters'] = "";
                }

                if (isset($manifestData['scos'][$item['identifierref']]['xml:base'])) {
                    $extraPath = $manifestData['scos'][$item['identifierref']]['xml:base'];
                } else if (isset($manifestData['assets'][$item['identifierref']]['xml:base'])) {
                    $extraPath = $manifestData['assets'][$item['identifierref']]['xml:base'];
                } else {
                    $extraPath = "";
                }

                $assetPath = "/"
                        . $manifestData['xml:base']['manifest']
                        . $manifestData['xml:base']['ressources']
                        . $extraPath
                        . $manifestData['scos'][$item['identifierref']]['href']
                        . $manifestData['assets'][$item['identifierref']]['href']
                        . $manifestData['scos'][$item['identifierref']]['parameters']
                        . $manifestData['assets'][$item['identifierref']]['parameters']
                        . $manifestData['items'][$item['itemIdentifier']]['parameters'];

                // create new asset
                // array of all inserted asset ids
                $insertedAsset_id[$i] = Database::get()->query("INSERT INTO `lp_asset`
                        (`path` , `module_id` , `comment`)
                        VALUES (?s, ?d, '')", $assetPath, $insertedModule_id[$i])->lastInsertID;
                
                if (!$insertedAsset_id[$i]) {
                    $errorFound = true;
                    array_push($errorMsgs, $langErrorSql);
                    break;
                }
                // update of module with correct start asset id
                Database::get()->query("UPDATE `lp_module`
                        SET `startAsset_id` = ?d
                        WHERE `module_id` = ?d
                        AND `course_id` = ?d", $insertedAsset_id[$i], $insertedModule_id[$i], $course_id);

                // visibility
                if (isset($item['isvisible']) && $item['isvisible'] != '') {
                    ( $item['isvisible'] == "true" ) ? $visibility = 1 : $visibility = 0;
                } else {
                    $visibility = 1; // IMS consider that the default value of 'isvisible' is true
                }

                // finally : insert in learning path
                // get the inserted id of the learnPath_module rel to allow 'parent' link in next inserts
                $insertedLPMid[$item['itemIdentifier']]['LPMid'] = Database::get()->query("INSERT INTO `lp_rel_learnPath_module`
                        (`learnPath_id`, `module_id`, `specificComment`, `rank`, `visible`, `lock`, `parent`)
                        VALUES (?d, ?d, ?s, ?d, ?d, 'OPEN', ?d)", $tempPathId, $insertedModule_id[$i], $langDefaultModuleAddedComment, $rank, $visibility, $parent)->lastInsertID;
                $insertedLPMid[$item['itemIdentifier']]['rank'] = 1;

                if (!$insertedLPMid[$item['itemIdentifier']]['LPMid']) {
                    $errorFound = true;
                    array_push($errorMsgs, $langErrorSql);
                    break;
                }

                if (!$errorFound) {
                    array_push($okMsgs, $langOkModuleAdded . "<i>" . $moduleName . "</i>");
                }
                $i++;
            }//foreach
        } // if sizeof($manifestData['items'] == 0 )
    } // if errorFound
    // last step
    // - delete all added files/directories/records in db
    // or
    // - update the learning path record

    if ($errorFound) {
        // delete all database entries of this "module"
        // delete modules and assets (build query)
        // delete assets
        $sqlDelAssets = "DELETE FROM `lp_asset` WHERE 1 = 0";
        foreach ($insertedAsset_id as $insertedAsset) {
            $sqlDelAssets .= " OR `asset_id` = " . intval($insertedAsset);
        }
        Database::get()->query($sqlDelAssets);

        // delete modules
        $sqlDelModules = "DELETE FROM `lp_module` WHERE 1 = 0";
        foreach ($insertedModule_id as $insertedModule) {
            $sqlDelModules .= " OR ( `module_id` = " . intval($insertedModule) . " AND `course_id` = " . intval($course_id) . " )";
        }
        Database::get()->query($sqlDelModules);

        // delete learningPath_module
        Database::get()->query("DELETE FROM `lp_rel_learnPath_module` WHERE `learnPath_id` = ?d", $tempPathId);

        // delete learning path
        Database::get()->query("DELETE FROM `lp_learnPath`
                     WHERE `learnPath_id` = ?d
                     AND `course_id` = ?d", $tempPathId, $course_id);

        // delete the directory (and files) of this learning path and all its content
        claro_delete_file($baseWorkDir);
    } else {
        // finalize insertion : update the empty learning path insert that was made to find its id
        $rankMax = 1 + intval(Database::get()->querySingle("SELECT MAX(`rank`) AS max
                FROM `lp_learnPath`
                WHERE `course_id` = ?d", $course_id)->max);

        if (isset($manifestData['packageTitle'])) {
            $lpName = $manifestData['packageTitle'];
        } else {
            array_push($okMsgs, $langOkDefaultTitleUsed);
        }

        if (isset($manifestData['packageDesc'])) {
            $lpComment = $manifestData['packageDesc'];
        } else {
            $lpComment = $langDefaultLearningPathComment;
            array_push($okMsgs, $langOkDefaultCommentUsed);
        }

        Database::get()->query("UPDATE `lp_learnPath`
                SET `rank` = ?d,
                    `name` = ?s,
                    `comment` = ?s,
                    `visible` = 1
                WHERE `learnPath_id` = ?d
                AND `course_id` = ?d", $rankMax, $lpName, $lpComment, $tempPathId, $course_id);
    }

    /* --------------------------------------
      status messages
      -------------------------------------- */
    $importMessages = "\n<p>\n";
    //$importMessages .= "<!-- Messages -->";
    foreach ($okMsgs as $msg) {
        $importMessages .= "\n<b>[</b><span class=\"correct\">$langSuccessOk</span><b>]</b>&nbsp;&nbsp;&nbsp;" . $msg . "<br />";
    }

    foreach ($errorMsgs as $msg) {
        $importMessages .= "\n<b>[</b><span class=\"error\">$langError</span><b>]</b>&nbsp;&nbsp;&nbsp;" . $msg . "<br />";
    }

    $importMessages .= "\n\n";
    //$importMessages .= "<!-- End messages -->";
    // installation completed or not message
    if (!$errorFound) {
        $importMessages .= "\n<br /><center><b>" . $langInstalled . "</b></center>";
        if ($displayExtraMessages == true) {
            $importMessages .= "\n<br /><br ><center><a href=\"learningPathAdmin.php?course=$course_code&amp;path_id=" . $tempPathId . "\">" . $lpName . "</a></center>";
        }        
        $importMessages .= "\n<br /><br >";
    }
    else {
        $importMessages .= "\n<br /><center><b>" . $langNotInstalled . "</b></center>";
    }
    //$importMessages .= "\n<br /><a href=\"index.php?course=$course_code\">$langBack</a></p>";
    $importMessages .= "\n<br /></p>";

    chdir($pwd);

    return array($importMessages, $tempPathId);
}