Compilatio: Refactoring to use RESTful api - refs BT#22064

pull/5852/head
Angel Fernando Quiroz Campos 11 months ago
parent 0ee56d480c
commit 97a6bab4a5
No known key found for this signature in database
GPG Key ID: B284841AE3E562CD
  1. 597
      main/inc/lib/Compilatio.php
  2. 34
      main/plagiarism/compilatio/compiladmin.php
  3. 18
      main/plagiarism/compilatio/compilatio_ajax.php
  4. 106
      main/plagiarism/compilatio/upload.php
  5. 33
      main/work/work.lib.php

@ -2,6 +2,9 @@
/* For licensing terms, see /license.txt */ /* For licensing terms, see /license.txt */
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Utils;
/** /**
* Build the communication with the SOAP server Compilatio.net * Build the communication with the SOAP server Compilatio.net
* call several methods for the file management in Compilatio.net. * call several methods for the file management in Compilatio.net.
@ -12,6 +15,10 @@ class Compilatio
{ {
/** Identification key for the Compilatio account*/ /** Identification key for the Compilatio account*/
public $key; public $key;
/**
* @var string
*/
protected $baseUrl;
/** Webservice connection*/ /** Webservice connection*/
public $soapcli; public $soapcli;
private $transportMode; private $transportMode;
@ -22,165 +29,92 @@ class Compilatio
private $proxyHost; private $proxyHost;
private $proxyPort; private $proxyPort;
/**
* @var Client
*/
public $client;
/** /**
* Compilatio constructor. * Compilatio constructor.
*/ */
public function __construct() public function __construct()
{ {
if (empty(api_get_configuration_value('allow_compilatio_tool')) || $settings = $this->getSettings();
empty(api_get_configuration_value('compilatio_tool'))
) {
throw new Exception('Compilatio not available');
}
$settings = api_get_configuration_value('compilatio_tool');
if (isset($settings['settings'])) {
$settings = $settings['settings'];
} else {
throw new Exception('Compilatio config available');
}
$key = $this->key = $settings['key'];
$urlsoap = $settings['soap_url'];
$proxyHost = $this->proxyHost = $settings['proxy_host'];
$proxyPort = $this->proxyPort = $settings['proxy_port'];
$this->transportMode = $settings['transport_mode']; $this->transportMode = $settings['transport_mode'];
$this->maxFileSize = $settings['max_filesize']; $this->maxFileSize = $settings['max_filesize'];
$this->wgetUri = $settings['wget_uri']; $this->wgetUri = $settings['wget_uri'];
$this->wgetLogin = $settings['wget_login']; $this->wgetLogin = $settings['wget_login'];
$this->wgetPassword = $settings['wget_password']; $this->wgetPassword = $settings['wget_password'];
$soapVersion = 2; $this->key = $settings['key'];
$this->baseUrl = $settings['soap_url'];
try { if (!empty($settings['proxy_host'])) {
if (!empty($key)) { $this->proxyHost = $settings['proxy_host'];
$this->key = $key; $this->proxyPort = $settings['proxy_port'];
if (!empty($urlsoap)) {
if (!empty($proxyHost)) {
$param = [
'trace' => false,
'soap_version' => $soapVersion,
'exceptions' => true,
'proxy_host' => '"'.$proxyHost.'"',
'proxy_port' => $proxyPort,
];
} else {
$param = [
'trace' => false,
'soap_version' => $soapVersion,
'exceptions' => true,
];
}
$this->soapcli = new SoapClient($urlsoap, $param);
} else {
throw new Exception('WS urlsoap not available');
}
} else {
throw new Exception('API key not available');
}
} catch (SoapFault $fault) {
$this->soapcli = "Error constructor compilatio $fault->faultcode $fault->faultstring ";
} catch (Exception $e) {
$this->soapcli = "Error constructor compilatio with urlsoap $urlsoap ".$e->getMessage();
} }
}
/**
* @return string
*/
public function getKey()
{
return $this->key;
}
/** $clientConfig = [
* @param mixed $key 'base_uri' => api_remove_trailing_slash($this->baseUrl).'/',
* 'headers' => [
* @return Compilatio 'X-Auth-Token' => $this->key,
*/ 'Accept' => 'application/json',
public function setKey($key) ],
{ ];
$this->key = $key;
return $this; if ($this->proxyPort) {
} $clientConfig['proxy'] = $this->proxyHost.':'.$this->proxyPort;
}
/** $this->client = new Client($clientConfig);
* @return mixed
*/
public function getTransportMode()
{
return $this->transportMode;
} }
/** /**
* @param mixed $transportMode * @throws Exception
*
* @return Compilatio
*/ */
public function setTransportMode($transportMode) protected function getSettings(): array
{ {
$this->transportMode = $transportMode; if (empty(api_get_configuration_value('allow_compilatio_tool')) ||
empty(api_get_configuration_value('compilatio_tool'))
return $this; ) {
} throw new Exception('Compilatio not available');
}
/** $compilatioTool = api_get_configuration_value('compilatio_tool');
* @return mixed
*/
public function getMaxFileSize()
{
return $this->maxFileSize;
}
/** if (!isset($compilatioTool['settings'])) {
* @param mixed $maxFileSize throw new Exception('Compilatio config available');
* }
* @return Compilatio
*/
public function setMaxFileSize($maxFileSize)
{
$this->maxFileSize = $maxFileSize;
return $this; $settings = $compilatioTool['settings'];
}
/** if (empty($settings['key'])) {
* @return mixed throw new Exception('API key not available');
*/ }
public function getWgetUri()
{
return $this->wgetUri;
}
/** if (empty($settings['soap_url'])) {
* @param mixed $wgetUri throw new Exception('WS urlsoap not available');
* }
* @return Compilatio
*/
public function setWgetUri($wgetUri)
{
$this->wgetUri = $wgetUri;
return $this; return $settings;
} }
/** /**
* @return mixed * @return string
*/ */
public function getWgetLogin() public function getKey()
{ {
return $this->wgetLogin; return $this->key;
} }
/** /**
* @param mixed $wgetLogin * @param mixed $key
* *
* @return Compilatio * @return Compilatio
*/ */
public function setWgetLogin($wgetLogin) public function setKey($key)
{ {
$this->wgetLogin = $wgetLogin; $this->key = $key;
return $this; return $this;
} }
@ -188,21 +122,9 @@ class Compilatio
/** /**
* @return mixed * @return mixed
*/ */
public function getWgetPassword() public function getMaxFileSize()
{
return $this->wgetPassword;
}
/**
* @param mixed $wgetPassword
*
* @return Compilatio
*/
public function setWgetPassword($wgetPassword)
{ {
$this->wgetPassword = $wgetPassword; return $this->maxFileSize;
return $this;
} }
/** /**
@ -213,18 +135,6 @@ class Compilatio
return $this->proxyHost; return $this->proxyHost;
} }
/**
* @param mixed $proxyHost
*
* @return Compilatio
*/
public function setProxyHost($proxyHost)
{
$this->proxyHost = $proxyHost;
return $this;
}
/** /**
* @return mixed * @return mixed
*/ */
@ -233,161 +143,144 @@ class Compilatio
return $this->proxyPort; return $this->proxyPort;
} }
/**
* @param mixed $proxyPort
*
* @return Compilatio
*/
public function setProxyPort($proxyPort)
{
$this->proxyPort = $proxyPort;
return $this;
}
/** /**
* Method for the file load. * Method for the file load.
*
* @param $title
* @param $description
* @param $filename
* @param $mimeType
* @param $content
*
* @return string
*/ */
public function sendDoc($title, $description, $filename, $mimeType, $content) public function sendDoc(
{ string $title,
try { string $description,
if (!is_object($this->soapcli)) { string $filename,
return "Error in constructor compilatio() $this->soapcli"; string $filepath
} ) {
$user = api_get_user_entity(api_get_user_id());
return $this->soapcli->__call(
'addDocumentBase64', $postData = [
'folder_id' => '',
'title' => $title,
'filename' => basename($filename),
'indexed' => 'true',
'user_notes' => [
'description' => $description
],
'authors' => [
[ [
$this->key, 'firstname' => $user->getFirstname(),
utf8_encode(urlencode($title)), 'lastname' => $user->getlastname(),
utf8_encode(urlencode($description)), 'email_address' => $user->getEmail(),
utf8_encode(urlencode($filename)),
utf8_encode($mimeType),
base64_encode($content),
] ]
); ],
} catch (SoapFault $fault) { 'depositor' => [
return "Erreur sendDoc()".$fault->faultcode." ".$fault->faultstring; 'firstname' => $user->getFirstname(),
'lastname' => $user->getlastname(),
'email_address' => $user->getEmail(),
]
];
try {
$responseBody = $this->client
->post(
'private/documents',
[
'multipart' => [
[
'name' => 'postData',
'contents' => json_encode($postData)
],
[
'name' => 'file',
'contents' => Utils::tryFopen($filepath, 'r'),
]
]
]
)
->getBody()
;
} catch (Exception $e) {
throw new Exception($e->getMessage());
} }
$body = json_decode((string) $responseBody, true);
return $body['data']['document']['id'];
} }
/** /**
* Method for recover a document's information. * Method for recover a document's information.
* *
* @param $compiHash * @throws Exception
*
* @return string
*/ */
public function getDoc($compiHash) public function getDoc(string $documentId): array
{ {
try { try {
if (!is_object($this->soapcli)) { $responseBody = $this->client
return "Error in constructor compilatio() ".$this->soapcli; ->get(
} "private/documents/$documentId"
$param = [$this->key, $compiHash]; )
->getBody()
return $this->soapcli->__call('getDocument', $param); ;
} catch (SoapFault $fault) { } catch (Exception $e) {
return "Erreur getDoc()".$fault->faultcode." ".$fault->faultstring; throw new Exception($e->getMessage());
} }
}
/** $responseJson = json_decode((string) $responseBody, true);
* method for recover an url document's report. $dataDocument = $responseJson['data']['document'];
*
* @param $compiHash
*
* @return string
*/
public function getReportUrl($compiHash)
{
try {
if (!is_object($this->soapcli)) {
return "Error in constructor compilatio() ".$this->soapcli;
}
$param = [$this->key, $compiHash];
return $this->soapcli->__call('getDocumentReportUrl', $param); $documentInfo = [
} catch (SoapFault $fault) { 'report_url' => $dataDocument['report_url'],
return "Erreur getReportUrl()".$fault->faultcode." ".$fault->faultstring; ];
if (isset($dataDocument['analyses']['anasim']['state'])) {
$documentInfo['analysis_status'] = $dataDocument['analyses']['anasim']['state'];
} }
if (isset($dataDocument['light_reports']['anasim']['scores']['global_score_percent'])) {
$documentInfo['report_percent'] = $dataDocument['light_reports']['anasim']['scores']['global_score_percent'];
}
return $documentInfo;
} }
/** /**
* Method for deleting a Compialtio's account document. * Method for deleting a Compialtio's account document.
*
* @param $compiHash
*
* @return string
*/ */
public function deldoc($compiHash) public function deldoc(string $documentId)
{ {
try {
if (!is_object($this->soapcli)) {
return "Error in constructor compilatio() ".$this->soapcli;
}
$param = [$this->key, $compiHash];
$this->soapcli->__call('deleteDocument', $param);
} catch (SoapFault $fault) {
return "Erreur deldoc()".$fault->faultcode." ".$fault->faultstring;
}
} }
/** /**
* Method for start the analysis for a document. * Method for start the analysis for a document.
* *
* @param $compiHash * @throws Exception
*
* @return string
*/ */
public function startAnalyse($compiHash) public function startAnalyse(string $compilatioId): string
{ {
try { try {
if (!is_object($this->soapcli)) { $responseBody = $this->client
return "Error in constructor compilatio() ".$this->soapcli; ->post(
} 'private/analyses',
$param = [$this->key, $compiHash]; [
$this->soapcli->__call('startDocumentAnalyse', $param); 'json' => [
} catch (SoapFault $fault) { 'doc_id' => $compilatioId,
return "Erreur startAnalyse()".$fault->faultcode." ".$fault->faultstring; 'recipe_name' => 'anasim'
],
]
)
->getBody()
;
} catch (Exception $e) {
throw new Exception($e->getMessage());
} }
}
/** $body = json_decode((string) $responseBody, true);
* Method for recover the account's quota.
*
* @return string
*/
public function getQuotas()
{
try {
if (!is_object($this->soapcli)) {
return "Error in constructor compilatio() ".$this->soapcli;
}
$param = [$this->key];
return $this->soapcli->__call('getAccountQuotas', $param); return $body['data']['analysis']['state'];
} catch (SoapFault $fault) {
return "Erreur getQuotas()".$fault->faultcode." ".$fault->faultstring;
}
} }
/** /**
* Method for identify a file extension and the possibility that the document can be managed by Compilatio. * Method for identify a file extension and the possibility that the document can be managed by Compilatio.
*
* @param $filename
*
* @return bool
*/ */
public static function verifiFileType($filename) public static function verifiFileType(string $filename): bool
{ {
$types = ['doc', 'docx', 'rtf', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'pdf', 'txt', 'htm', 'html']; $types = ['doc', 'docx', 'rtf', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'pdf', 'txt', 'htm', 'html'];
$extension = substr($filename, strrpos($filename, '.') + 1); $extension = substr($filename, strrpos($filename, '.') + 1);
@ -396,105 +289,39 @@ class Compilatio
return in_array($extension, $types); return in_array($extension, $types);
} }
/**
* Fonction affichage de la barre de progression d'analyse version 3.1.
*
* @param string $status From the document
* @param int $pour
* @param array $text Array includes the extract from the text
*
* @return string
*/
public static function getProgressionAnalyseDocv31($status, $pour = 0, $text = [])
{
$loading = Display::returnFontAwesomeIcon('spinner', null, true, 'fa-spin');
$loading .= ' ';
switch ($status) {
case 'ANALYSE_IN_QUEUE':
$content = $loading.$text['analysisinqueue'];
break;
case 'ANALYSE_PROCESSING':
$content = $loading.$text['analysisinfinalization'];
break;
default:
$content = Display::bar_progress($pour, true);
break;
}
return $content;
}
/** /**
* Method for display the PomprseuilmankBar (% de plagiat). * Method for display the PomprseuilmankBar (% de plagiat).
*
* @param $index
* @param $weakThreshold
* @param $highThreshold
*
* @return string
*/ */
public static function getPomprankBarv31( public static function getPomprankBarv31(
$index, int $index,
$weakThreshold, int $weakThreshold,
$highThreshold int $highThreshold
) { ): string {
$index = round($index); $index = round($index);
$class = 'error'; $class = 'danger';
if ($index < $weakThreshold) { if ($index < $weakThreshold) {
$class = 'success'; $class = 'success';
} else { } elseif ($index < $highThreshold) {
if ($index >= $weakThreshold && $index < $highThreshold) { $class = 'warning';
$class = 'warning';
}
} }
return Display::bar_progress($index, true, null, $class); return Display::bar_progress($index, true, null, $class);
} }
/** /**
* Method for validation of hash. * Function for delete a document of the compilatio table if plagiarismTool is Compilatio.
*
* @param string $hash
*
* @return bool
*/ */
public static function isMd5($hash) public static function plagiarismDeleteDoc(int $courseId, int $itemId)
{ {
return preg_match('`^[a-f0-9]{32}$`', $hash) || preg_match('`^[a-f0-9]{40}$`', $hash); if (api_get_configuration_value('allow_compilatio_tool') !== false) {
} $table = Database::get_course_table(TABLE_PLAGIARISM);
$params = [$courseId, $itemId];
/** Database::delete($table, ['c_id = ? AND document_id = ?' => $params]);
* function for delete a document of the compilatio table if plagiarismTool is Compilatio.
*
* @param int $courseId
* @param int $itemId
*
* @return bool
*/
public static function plagiarismDeleteDoc($courseId, $itemId)
{
if (api_get_configuration_value('allow_compilatio_tool') === false) {
return false;
} }
$table = Database::get_course_table(TABLE_PLAGIARISM);
$params = [$courseId, $itemId];
Database::delete($table, ['c_id = ? AND document_id = ?' => $params]);
return true;
} }
/** public function saveDocument(int $courseId, int $documentId, string $compilatioId)
* @param int $courseId
* @param int $documentId
* @param int $compilatioId
*/
public function saveDocument($courseId, $documentId, $compilatioId)
{ {
$documentId = (int) $documentId;
$courseId = (int) $courseId;
$table = Database::get_course_table(TABLE_PLAGIARISM); $table = Database::get_course_table(TABLE_PLAGIARISM);
$params = [ $params = [
'c_id' => $courseId, 'c_id' => $courseId,
@ -504,100 +331,62 @@ class Compilatio
Database::insert($table, $params); Database::insert($table, $params);
} }
/** public function getCompilatioId(int $documentId, int $courseId): ?string
* @param int $documentId
* @param int $courseId
*
* @return string md5 value
*/
public function getCompilatioId($documentId, $courseId)
{ {
$documentId = (int) $documentId;
$courseId = (int) $courseId;
$table = Database::get_course_table(TABLE_PLAGIARISM); $table = Database::get_course_table(TABLE_PLAGIARISM);
$sql = "SELECT compilatio_id FROM $table $sql = "SELECT compilatio_id FROM $table
WHERE document_id = $documentId AND c_id= $courseId"; WHERE document_id = $documentId AND c_id= $courseId";
$result = Database::query($sql); $result = Database::query($sql);
$result = Database::fetch_object($result); $result = Database::fetch_object($result);
if ($result) { return $result ? (string)$result->compilatio_id : null;
return (string) $result->compilatio_id;
}
return 0;
} }
/** public function giveWorkIdState(int $workId): string
* @param int $workId
*
* @return string
*/
public function giveWorkIdState($workId)
{ {
$courseId = api_get_course_int_id(); $courseId = api_get_course_int_id();
$compilatioId = $this->getCompilatioId($workId, $courseId); $compilatioId = $this->getCompilatioId($workId, $courseId);
$actionCompilatio = ''; // if the compilatio's hash is not a valide hash md5,
// we return à specific status (cf : IsInCompilatio() )
$actionCompilatio = get_lang('CompilatioDocumentTextNotImage').'<br/>'.
get_lang('CompilatioDocumentNotCorrupt');
$status = ''; $status = '';
if (!empty($compilatioId)) { if (!empty($compilatioId)) {
if (self::isMd5($compilatioId)) { // if compilatio_id is a hash md5, we call the function of the compilatio's
// if compilatio_id is a hash md5, we call the function of the compilatio's // webservice who return the document's status
// webservice who return the document's status $soapRes = $this->getDoc($compilatioId);
$soapRes = $this->getDoc($compilatioId); $status = $soapRes['analysis_status'] ?? '';
if (isset($soapRes->documentStatus)) {
$status = $soapRes->documentStatus->status; $spinnerIcon = Display::returnFontAwesomeIcon('spinner', null, true, 'fa-spin');
}
} else {
// if the compilatio's hash is not a valide hash md5,
// we return à specific status (cf : IsInCompilatio() )
$status = 'NOT_IN_COMPILATIO';
$actionCompilatio = get_lang('CompilatioDocumentTextNotImage').'<br/>'.
get_lang('CompilatioDocumentNotCorrupt');
}
switch ($status) { switch ($status) {
case 'ANALYSE_COMPLETE': case 'finished':
$urlRapport = $this->getReportUrl($compilatioId); $actionCompilatio .= self::getPomprankBarv31($soapRes['report_percent'], 10, 35)
$actionCompilatio .= self::getPomprankBarv31( .PHP_EOL
$soapRes->documentStatus->indice,
10,
35
)
.Display::url( .Display::url(
get_lang('CompilatioAnalysis'), get_lang('CompilatioAnalysis'),
$urlRapport, $soapRes['report_url'],
['class' => 'btn btn-primary btn-xs', 'target' => '_blank'] ['class' => 'btn btn-primary btn-xs', 'target' => '_blank']
); );
break; break;
case 'ANALYSE_PROCESSING': case 'running':
$actionCompilatio .= "<div style='font-weight:bold;text-align:left'>" $actionCompilatio .= "<div style='font-weight:bold;text-align:left'>"
.get_lang('CompilatioAnalysisInProgress') .get_lang('CompilatioAnalysisInProgress')
."</div>"; ."</div>";
$actionCompilatio .= "<div style='font-size:80%;font-style:italic;margin-bottom:5px;'>" $actionCompilatio .= "<div style='font-size:80%;font-style:italic;margin-bottom:5px;'>"
.get_lang('CompilatioAnalysisPercentage') .get_lang('CompilatioAnalysisPercentage')
."</div>"; ."</div>";
$text = []; $actionCompilatio .= $spinnerIcon.PHP_EOL .get_lang('CompilatioAnalysisEnding');
$text['analysisinqueue'] = get_lang('CompilatioWaitingAnalysis');
$text['analysisinfinalization'] = get_lang('CompilatioAnalysisEnding');
$text['refresh'] = get_lang('Refresh');
$actionCompilatio .= self::getProgressionAnalyseDocv31(
$status,
$soapRes->documentStatus->progression,
$text
);
break; break;
case 'ANALYSE_IN_QUEUE': case 'waiting':
$loading = Display::returnFontAwesomeIcon('spinner', null, true, 'fa-spin'); $actionCompilatio .= $spinnerIcon.PHP_EOL.get_lang('CompilatioWaitingAnalysis');
$actionCompilatio .= $loading.'&nbsp;'.get_lang('CompilatioAwaitingAnalysis');
break; break;
case 'BAD_FILETYPE': case 'canceled':
$actionCompilatio .= get_lang('FileFormatNotSupported') $actionCompilatio .= get_lang('Cancelled');
.'<br/>'
.get_lang('CompilatioProtectedPdfVerification');
break; break;
case 'BAD_FILESIZE': case 'scheduled':
$actionCompilatio .= get_lang('UplFileTooBig'); $actionCompilatio .= $spinnerIcon.PHP_EOL.get_lang('CompilatioAwaitingAnalysis');
break; break;
} }
} }

@ -3,12 +3,8 @@
exit; exit;
ini_set('soap.wsdl_cache_enabled', 0);
ini_set('default_socket_timeout', '1000');
require_once '../../inc/global.inc.php'; require_once '../../inc/global.inc.php';
$compilatio = new Compilatio();
$use_space = number_format($quotas->usedSpace / 1000000, 2); $use_space = number_format($quotas->usedSpace / 1000000, 2);
$total_space = $quotas->space / 1000000; $total_space = $quotas->space / 1000000;
@ -33,27 +29,31 @@ if (!isset($_GET['action'])) {
} else { } else {
echo get_lang('CompilatioConnectionTestSoap')."<br>"; echo get_lang('CompilatioConnectionTestSoap')."<br>";
echo "1) ".get_lang('CompilatioServerConnection')."<br>"; echo "1) ".get_lang('CompilatioServerConnection')."<br>";
$compilatio = new Compilatio();
try {
$compilatio = new Compilatio();
} catch (Exception $e) {
$compilatio = null;
echo get_lang('CompilatioNoConnection')."<br>";
echo get_lang('CompilatioParamVerification')."<br>";
}
if ($compilatio) { if ($compilatio) {
echo get_lang('CompilatioConnectionSuccessful')."<br>"; echo get_lang('CompilatioConnectionSuccessful')."<br>";
echo "2) ".get_lang('CompilatioSendTextToServer')."<br>"; echo "2) ".get_lang('CompilatioSendTextToServer')."<br>";
$text = sprintf(get_lang('CompilatioTextSendingTestKeyX'), $compilatio->getKey()); $text = sprintf(get_lang('CompilatioTextSendingTestKeyX'), $compilatio->getKey());
$id_compi = $compilatio->SendDoc( try {
'Doc de test', $id_compi = $compilatio->sendDoc(
'test', 'Doc de test',
'test', 'test',
'text/plain', 'test',
$text $text
); );
if (Compilatio::isMd5($id_compi)) {
echo get_lang('CompilatioSuccessfulTransfer')."<br>"; echo get_lang('CompilatioSuccessfulTransfer')."<br>";
} else { } catch (Exception $e) {
echo get_lang('CompilatioFailedTransfer')."<br>"; echo get_lang('CompilatioFailedTransfer')."<br>";
echo get_lang('CompilatioParamVerification')."<br>"; echo get_lang('CompilatioParamVerification')."<br>";
} }
} else {
echo get_lang('CompilatioNoConnection')."<br>";
echo get_lang('CompilatioParamVerification')."<br>";
} }
} }
?> ?>

@ -8,12 +8,18 @@ api_protect_course_script();
if (isset($_GET['workid'])) { if (isset($_GET['workid'])) {
$workIdList = $_GET['workid']; // list of workid separate by the : $workIdList = $_GET['workid']; // list of workid separate by the :
$workList = explode('a', $workIdList); $workList = explode('a', $workIdList);
$compilatio = new Compilatio(); $workList = array_map('intval', $workList);
$result = ''; $workList = array_filter($workList);
foreach ($workList as $workId) { try {
if (!empty($workId)) { $compilatio = new Compilatio();
$result .= $compilatio->giveWorkIdState($workId); $result = '';
foreach ($workList as $workId) {
if (!empty($workId)) {
$result .= $compilatio->giveWorkIdState($workId);
}
} }
echo $result;
} catch (Exception $e) {
echo $e->getMessage();
} }
echo $result;
} }

@ -14,7 +14,14 @@ api_protect_course_script();
$courseId = api_get_course_int_id(); $courseId = api_get_course_int_id();
$courseInfo = api_get_course_info(); $courseInfo = api_get_course_info();
$compilatio = new Compilatio();
try {
$compilatio = new Compilatio();
} catch (Exception $e) {
$message = Display::return_message($e->getMessage(), 'error');
exit($message);
}
/* if we have to upload severals documents*/ /* if we have to upload severals documents*/
if (isset($_REQUEST['type']) && 'multi' === $_REQUEST['type']) { if (isset($_REQUEST['type']) && 'multi' === $_REQUEST['type']) {
@ -39,47 +46,22 @@ if (isset($_REQUEST['type']) && 'multi' === $_REQUEST['type']) {
$sqlResult = Database::query($query); $sqlResult = Database::query($query);
$doc = Database::fetch_object($sqlResult); $doc = Database::fetch_object($sqlResult);
if ($doc) { if ($doc) {
/*We load the document in compilatio through the webservice */ try {
$currentCourseRepositoryWeb = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/';
$WrkUrl = $currentCourseRepositoryWeb.$doc->url;
$LocalWrkUrl = $courseInfo['course_sys_path'].$doc->url;
$mime = DocumentManager::file_get_mime_type($doc->title);
if ('wget' === $compilatio->getTransportMode()) {
/*Compilatio's server recover tjre file throught wget like this:
username:password@http://somedomain.com/reg/remotefilename.tar.gz */
if (strlen($compilatio->getWgetUri()) > 2) {
$filename = preg_replace(
'/$',
'',
$compilatio->getWgetUri()
).'/'.$courseInfo['path'].'/'.$doc->url;
} else {
$filename = $WrkUrl;
}
if (strlen($compilatio->getWgetLogin()) > 2) {
$filename = $compilatio->getWgetLogin().':'.$compilatio->getWgetPassword().'@'.$filename;
}
$mime = 'text/plain';
$compilatioId = $compilatio->sendDoc($doc->title, '', $filename, $mime, 'get_url');
} else {
/* we use strictly the SOAP for the data trasmission */
$pieces = explode('/', $doc->url);
$nbPieces = count($pieces);
$filename = $pieces[$nbPieces - 1];
$compilatioId = $compilatio->sendDoc( $compilatioId = $compilatio->sendDoc(
$doc->title, $doc->title,
'', $doc->description,
$filename, $doc->url,
$mime, $courseInfo['course_sys_path'].$doc->url
file_get_contents($LocalWrkUrl)
); );
}
/*we associate in the database the document chamilo to the document compilatio*/ /*we associate in the database the document chamilo to the document compilatio*/
/*we verify that the docmuent's id is an hash_md5*/
if (Compilatio::isMd5($compilatioId)) {
$compilatio->saveDocument($courseId, $doc->id, $compilatioId); $compilatio->saveDocument($courseId, $doc->id, $compilatioId);
sleep(10); sleep(10);
$soapRes = $compilatio->startAnalyse($compilatioId); $compilatio->startAnalyse($compilatioId);
} catch (Exception $e) {
$message = Display::return_message($e->getMessage(), 'error');
exit($message);
} }
} }
} }
@ -92,14 +74,14 @@ if (isset($_REQUEST['type']) && 'multi' === $_REQUEST['type']) {
function sendDocument($documentId, $courseInfo) function sendDocument($documentId, $courseInfo)
{ {
if (empty($courseInfo)) { if (empty($courseInfo)) {
return false; return;
} }
$courseId = $courseInfo['real_id'] ?? 0; $courseId = $courseInfo['real_id'] ?? 0;
$documentId = (int) $documentId; $documentId = (int) $documentId;
if (empty($courseId) || empty($documentId)) { if (empty($courseId) || empty($documentId)) {
return false; return;
} }
compilatioUpdateWorkDocument($documentId, $courseId); compilatioUpdateWorkDocument($documentId, $courseId);
@ -108,37 +90,25 @@ function sendDocument($documentId, $courseInfo)
WHERE id = $documentId AND c_id= $courseId"; WHERE id = $documentId AND c_id= $courseId";
$sqlResult = Database::query($query); $sqlResult = Database::query($query);
$doc = Database::fetch_object($sqlResult); $doc = Database::fetch_object($sqlResult);
$currentCourseRepositoryWeb = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/';
$documentUrl = $currentCourseRepositoryWeb.$doc->url;
$filePath = $courseInfo['course_sys_path'].$doc->url; $filePath = $courseInfo['course_sys_path'].$doc->url;
$mime = DocumentManager::file_get_mime_type($doc->title);
$compilatio = new Compilatio(); try {
if ('wget' === $compilatio->getTransportMode()) { $compilatio = new Compilatio();
if (strlen($compilatio->getWgetUri()) > 2) {
$filename = preg_replace('/$', '', $compilatio->getWgetUri()).'/'.$courseInfo['path'].'/'.$doc->title; $compilatioId = $compilatio->sendDoc(
} else { $doc->title,
$filename = $documentUrl; $doc->description,
} $doc->url,
if (strlen($compilatio->getWgetLogin()) > 2) { $filePath
$filename = $compilatio->getWgetLogin().':'.$compilatio->getWgetPassword().'@'.$filename; );
}
$compilatioId = $compilatio->sendDoc($doc->title, '', $filename, 'text/plain', 'get_url');
} else {
$pieces = explode('/', $doc->url);
$nbPieces = count($pieces);
$filename = $pieces[$nbPieces - 1];
$compilatioId = $compilatio->sendDoc($doc->title, '', $filename, $mime, file_get_contents($filePath));
}
if (Compilatio::isMd5($compilatioId)) {
$compilatio->saveDocument($courseId, $doc->id, $compilatioId); $compilatio->saveDocument($courseId, $doc->id, $compilatioId);
sleep(10); sleep(10);
$compilatio->startAnalyse($compilatioId); $compilatio->startAnalyse($compilatioId);
echo Display::return_message(get_lang('Uploaded')); echo Display::return_message(get_lang('Uploaded'), 'success');
} else { } catch (Exception $e) {
echo Display::return_message(get_lang('Error'), 'error'); echo Display::return_message($e->getMessage(), 'error');
} }
} }
@ -208,16 +178,6 @@ function getWorkFolder($txt)
return $res; return $res;
} }
function getShortFilename($txt)
{
$res = $txt;
if (strlen($txt) > 10) {
$res = substr($txt, 0, 10);
}
return $res;
}
function compilatioUpdateWorkDocument($docId, $courseId) function compilatioUpdateWorkDocument($docId, $courseId)
{ {
$_course = api_get_course_info(); $_course = api_get_course_info();

@ -2101,16 +2101,17 @@ function get_work_user_list(
$group_id = api_get_group_id(); $group_id = api_get_group_id();
$course_info = api_get_course_info(); $course_info = api_get_course_info();
$course_info = empty($course_info) ? api_get_course_info_by_id($courseId) : $course_info; $course_info = empty($course_info) ? api_get_course_info_by_id($courseId) : $course_info;
$course_id = isset($course_info['real_id']) ? $course_info['real_id'] : $courseId; $course_id = (int) ($course_info['real_id'] ?? $courseId);
$work_id = (int) $work_id; $work_id = (int) $work_id;
$start = (int) $start; $start = (int) $start;
$limit = (int) $limit; $limit = (int) $limit;
$column = !empty($column) ? Database::escape_string($column) : 'sent_date'; $column = !empty($column) ? Database::escape_string($column) : 'sent_date';
$compilation = null; try {
if (api_get_configuration_value('allow_compilatio_tool')) { $compilatio = new Compilatio();
$compilation = new Compilatio(); } catch (Exception $e) {
$compilatio = false;
} }
if (!in_array($direction, ['asc', 'desc'])) { if (!in_array($direction, ['asc', 'desc'])) {
@ -2281,7 +2282,7 @@ function get_work_user_list(
} }
while ($work = Database::fetch_array($result, 'ASSOC')) { while ($work = Database::fetch_array($result, 'ASSOC')) {
$item_id = $work['id']; $item_id = (int) $work['id'];
$dbTitle = $work['title']; $dbTitle = $work['title'];
// Get the author ID for that document from the item_property table // Get the author ID for that document from the item_property table
$is_author = false; $is_author = false;
@ -2557,8 +2558,8 @@ function get_work_user_list(
$work['actions'] = '<div class="work-action">'.$linkToDownload.$action.'</div>'; $work['actions'] = '<div class="work-action">'.$linkToDownload.$action.'</div>';
$work['correction'] = $correction; $work['correction'] = $correction;
if (!empty($compilation) && $is_allowed_to_edit) { if ($compilatio && $is_allowed_to_edit) {
$compilationId = $compilation->getCompilatioId($item_id, $course_id); $compilationId = $compilatio->getCompilatioId($item_id, $course_id);
if ($compilationId) { if ($compilationId) {
$actionCompilatio = "<div id='id_avancement".$item_id."' class='compilation_block'> $actionCompilatio = "<div id='id_avancement".$item_id."' class='compilation_block'>
".$loading.'&nbsp;'.get_lang('CompilatioConnectionWithServer').'</div>'; ".$loading.'&nbsp;'.get_lang('CompilatioConnectionWithServer').'</div>';
@ -2566,7 +2567,7 @@ function get_work_user_list(
$workDirectory = api_get_path(SYS_COURSE_PATH).$course_info['directory']; $workDirectory = api_get_path(SYS_COURSE_PATH).$course_info['directory'];
if (!Compilatio::verifiFileType($dbTitle)) { if (!Compilatio::verifiFileType($dbTitle)) {
$actionCompilatio = get_lang('FileFormatNotSupported'); $actionCompilatio = get_lang('FileFormatNotSupported');
} elseif (filesize($workDirectory.'/'.$work['url']) > $compilation->getMaxFileSize()) { } elseif (filesize($workDirectory.'/'.$work['url']) > $compilatio->getMaxFileSize()) {
$sizeFile = round(filesize($workDirectory.'/'.$work['url']) / 1000000); $sizeFile = round(filesize($workDirectory.'/'.$work['url']) / 1000000);
$actionCompilatio = get_lang('UplFileTooBig').': '.format_file_size($sizeFile).'<br />'; $actionCompilatio = get_lang('UplFileTooBig').': '.format_file_size($sizeFile).'<br />';
} else { } else {
@ -2688,10 +2689,12 @@ function getAllWork(
} }
$courseQueryToString = implode(' OR ', $courseQuery); $courseQueryToString = implode(' OR ', $courseQuery);
$compilation = null;
/*if (api_get_configuration_value('allow_compilatio_tool')) { //try {
$compilation = new Compilatio(); $compilatio = new Compilatio();
}*/ //} catch (Exception $e) {
// $compilatio = null;
//}
if ($getCount) { if ($getCount) {
if (empty($courseQuery)) { if (empty($courseQuery)) {
@ -3094,8 +3097,8 @@ function getAllWork(
$work['actions'] = '<div class="work-action">'.$linkToDownload.$action.'</div>'; $work['actions'] = '<div class="work-action">'.$linkToDownload.$action.'</div>';
$work['correction'] = $correction; $work['correction'] = $correction;
if (!empty($compilation)) { if (!empty($compilatio)) {
$compilationId = $compilation->getCompilatioId($item_id, $courseId); $compilationId = $compilatio->getCompilatioId($item_id, $courseId);
if ($compilationId) { if ($compilationId) {
$actionCompilatio = "<div id='id_avancement".$item_id."' class='compilation_block'> $actionCompilatio = "<div id='id_avancement".$item_id."' class='compilation_block'>
".$loading.'&nbsp;'.get_lang('CompilatioConnectionWithServer').'</div>'; ".$loading.'&nbsp;'.get_lang('CompilatioConnectionWithServer').'</div>';
@ -3103,7 +3106,7 @@ function getAllWork(
$workDirectory = api_get_path(SYS_COURSE_PATH).$courseInfo['directory']; $workDirectory = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'];
if (!Compilatio::verifiFileType($dbTitle)) { if (!Compilatio::verifiFileType($dbTitle)) {
$actionCompilatio = get_lang('FileFormatNotSupported'); $actionCompilatio = get_lang('FileFormatNotSupported');
} elseif (filesize($workDirectory.'/'.$work['url']) > $compilation->getMaxFileSize()) { } elseif (filesize($workDirectory.'/'.$work['url']) > $compilatio->getMaxFileSize()) {
$sizeFile = round(filesize($workDirectory.'/'.$work['url']) / 1000000); $sizeFile = round(filesize($workDirectory.'/'.$work['url']) / 1000000);
$actionCompilatio = get_lang('UplFileTooBig').': '.format_file_size($sizeFile).'<br />'; $actionCompilatio = get_lang('UplFileTooBig').': '.format_file_size($sizeFile).'<br />';
} else { } else {

Loading…
Cancel
Save