<!doctype html>
  <html lang="en" >
  <head>
  
  <meta charset="utf-8" />
  <title>Import package</title>

<?php
    
$lpid = 0;

error_reporting(E_ERROR | E_PARSE);

ini_set('max_execution_time',700);
if (file_exists(__DIR__.'/../../../../main/inc/global.inc.php')) {
  require_once __DIR__.'/../../../../main/inc/global.inc.php';
} else {
  echo "Error: global.inc.php file not found.";
  exit;
}

require_once __DIR__.'/../../inc/functions.php';
   
$version = "1.11.16-38";
$idPage = 0;
$action = '';
$renderPath = getPathRenderCacheChamiDoc();

$appP = api_get_path(SYS_APP_PATH).'cache/';

if(!file_exists($appP.'files')){
  mkdir($appP.'files', 0777,true);
}
if(!file_exists($appP.'filestmp')){
  mkdir($appP.$appP.'filestmp', 0777,true);
}

$appPR = api_get_path(SYS_APP_PATH).'upload/';

if(!file_exists($appPR.'import-package')){
  mkdir($appPR.'import-package', 0777,true);
}
if(!file_exists($appP.'import-package/files')){
  mkdir($appP.$appP.'import-package/files', 0777,true);
}
if(!file_exists($appP.'import-package/files/tmp')){
  mkdir($appP.$appP.'import-package/files/tmp', 0777,true);
}

if (isset($_GET['lpid'])) {

  $idPage = intval($_GET['lpid']);
  $lpid = intval($_GET['lpid']);
  $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']):'step1';
  $typefile = isset($_GET['typefile']) ? Security::remove_XSS($_GET['typefile']):'';

  if (!api_is_anonymous()) {
      $user = api_get_user_info();
      if (isset($user['status'])) {
        if($user['status']==SESSIONADMIN
          ||$user['status']==COURSEMANAGER
          ||$user['status']==PLATFORM_ADMIN) {
        } else {
          echo "<div style='color:red;' >Status !".$user['status']."</div>";
          echo "<script>setTimeout(function(){ location.href = '../../index.php'; }, 3000);</script>";
          exit;
        }
    }
  }
  
} else {

  echo "Error";
  exit;

}

?>
  
  <script src="../../resources/js/jquery.min.js?v=<?php echo $version ?>"></script>
  <link href="css/style.css?v=<?php echo $version ?>" rel="stylesheet"/>

</head>
<body style="background-color:rgb(246, 247, 247);overflow: hidden;" >
    
    <?php 
    if ($action=='step1') {
    ?>
      <center>
        
        <h3>Direct import file</h3>

        <div id="run" style="text-align:center;overflow: hidden;" >

          <form class="uploader" action="inc/bigUpload.php?action=post-unsupported" method="post" enctype="multipart/form-data" id="bigUploadForm">

              <input type="file" id="bigUploadFile" name="bigUploadFile" accept=".jpg,.png,.gif,.mp3,.mp4,.pdf,.odt,.ods,.xlsx,.docx,.h5p" />
      
              <div id="bigUploadProgressBarContainer" >
                <div id="bigUploadProgressBarFilled"></div>
              </div>
              
              <button class=" btn btn-primary " name="button" type="button" onclick="upload();" id="bigUploadSubmit" >
              <em class="fa fa-upload"></em>Upload</button>
                
              <input type="button" class="bigUploadButton bigUploadAbort" style="display:none;" value="Annuler" onclick="abort();" />
              <input id="scormid" name="scormid" type="hidden" value="testsco" />

          </form>

        </div>

      </center>

      <div id="bigUploadTimeRemaining"></div>
      <div id="bigUploadResponse"></div>
      <div id="finalNameSrc"></div>

      <?php $lk = getWPathChamiDocPath().'plug/libimport/import-file.php?lpid='.$lpid; ?>
      
      <div id="linkact" style="display:none;" ><?php echo $lk; ?></div>
      
      <div id="see" style="display:none;" >
        <img style="margin:15px;" src="../../resources/img/load.gif" />
      </div>

      <script src="js/big_upload.js?v=<?php echo $version ?>"></script>
      <script src="js/init_oel.js?v=<?php echo $version ?>"></script>

    <?php } ?>
    
    <?php if ($action=='present') { ?>
    
    <center>
      
      <h3>&nbsp;</h3>

      <?php

          $namFileF = '';
          $lpid = intval($_GET['lpid']);

          if (isset($_GET['namesrc'])) {
            
            $namFile = $_GET['namesrc'];

            $zipFileInfo = ['tmp_name','name'];
            $zipFileInfo['tmp_name'] = api_get_path(SYS_APP_PATH).'/upload/rendercache/import-package/files/'.$namFile;
            $zipFileInfo['name'] = $namFile;
            
            if (findIndexOf($namFile,'.mp4')) {

              $course_info = api_get_course_info();
              $groupPart = '';
              $groupPath = '';
              $exportDir = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/document'.$groupPath;
              $groupId = api_get_group_id();
              $groupInfo = GroupManager::get_group_properties($groupId);
              $exportPath = $exportDir.'/'.$namFile;
              $namFileF = $namFile;
              
              @copy($zipFileInfo['tmp_name'],$exportPath);
              
              if (file_exists($exportPath)) {
                
                $doc_id = add_document(
                    $course_info,
                    $groupPath.'/'.$namFile,
                    'file',
                    filesize($exportPath),
                    ''
                );
                api_item_property_update(
                    $course_info,
                    TOOL_DOCUMENT,
                    $doc_id,
                    'DocumentAdded',
                    api_get_user_id(),
                    $groupInfo
                );
                echo '<script>';
                echo 'parent.postMessage("importfileok:/courses/'.get_directory($lpid).'/document/'.$namFileF.'","*");';
                echo '</script>';
              } else {
                $minLogs = '';
                $zipName = $zipFileInfo['tmp_name'];
                if (!file_exists($zipName)) {
                  $minLogs = $zipName.' not exits ';
                }
                $minLogs .= $exportPath;
                echo '<script>';
                echo 'parent.postMessage("importfileko: '. $minLogs. '","*");';
                echo '</script>';
              
              }


            }

            if (findIndexOf($namFile,'.h5p')) {

              $h5pplayfolder = $appPR.'rendercache/h5pplay/';
              if(!file_exists($h5pplayfolder)){
                @mkdir($h5pplayfolder,0777);
              }

              $namFolder = 'h5p-'.$namFile;
              $namFolder = str_replace('.h5p','h5p',$namFolder);
              $destifolder = $appPR.'rendercache/h5pplay/'.$namFolder.'/';
              
              if(!file_exists($destifolder)){
                @mkdir($destifolder,0777);
              }
              
              $destifolderZipsource = $zipFileInfo['tmp_name'];
              $destifolderZipExtract = $appPR.'rendercache/h5pplay/'.$namFolder;
            
              $zipFile = new PclZip($destifolderZipsource);
              $zip_content_array = $zipFile->listContent();
              foreach ($zip_content_array as $this_content) {
              // echo $this_content['filename'].' '.$this_content['size'].'<br/>';
              }
              $newDir = $destifolderZipExtract;
              if ($newDir[strlen($newDir) - 1] == '/') {
                $newDir = substr($newDir, 0, -1);
              }
              chdir($newDir);
              if ($zipFile->extract(PCLZIP_OPT_PATH,$newDir)==0) {
                echo ("Unzip failed. Error : ".$zipFile->errorInfo(true).'<br>');
              }

              $contentSource = $appPR.'rendercache/h5pplay/play-src.html';
              $targetSource = $appPR.'rendercache/h5pplay/'.$namFolder.'.html';
              $contentFlx = file_get_contents($contentSource);

              $contentFlx = str_replace("@base_id@",$namFolder, $contentFlx);

              $fp = fopen($targetSource,'w');
              fwrite($fp, $contentFlx);
              fclose($fp);

              echo '<script>';
              echo 'parent.postMessage("importfileok:'.$namFolder.'","*");';
              echo '</script>';
              
            }

            @unlink($zipFileInfo['tmp_name']);

          } else {
            //echo "File not authorized !";
            $namFileF = 'filenot';
          }
          // /courses/TESTLP/document/
      ?>
      </center>
      
    <?php } ?>
    
</body>
</html>

<?php

  function get_directory($lpid) {

    $lpid = intval($lpid);
    $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
    $tblCLp = Database::get_course_table(TABLE_LP_MAIN);
    $courseDir = '';
    $sqlC = "SELECT directory FROM $course_table INNER JOIN $tblCLp ON $tblCLp.c_id = $course_table.id WHERE $tblCLp.id = $lpid";
    $resultC = Database::query($sqlC);
    while($PartC=Database::fetch_array($resultC)){
        $courseDir = $PartC['directory'];
    }
    return $courseDir;

  }

  function findIndexOf($mystring,$search)
  {
    $pos = strrpos($mystring,$search);
    if($pos===false){
      return false;
    }else{
      return true;
    }
  }

?>
