Update to latest code

Yannick Warnier 10 years ago
commit 8d5aceeac1
  1. 52
      app/Migrations/Schema/V110/Version20151221150100.php
  2. 7
      documentation/changelog.html
  3. 7
      documentation/installation_guide.html
  4. 4
      main/document/downloadfolder.inc.php
  5. 2
      main/exercice/question.class.php
  6. 2
      main/inc/ajax/model.ajax.php
  7. 2
      main/inc/lib/attendance.lib.php
  8. 9
      main/inc/lib/display.lib.php
  9. 2
      main/inc/lib/document.lib.php
  10. 2
      main/inc/lib/exercise.lib.php
  11. 12
      main/inc/lib/fileUpload.lib.php
  12. 2
      main/inc/lib/link.lib.php
  13. 92
      main/lang/brazilian/trad4all.inc.php
  14. 128
      main/newscorm/learnpath.class.php
  15. 39
      main/newscorm/scorm.class.php
  16. 2
      main/user/user.php
  17. 633
      main/webservices/lp.php

@ -0,0 +1,52 @@
<?php
/* For licensing terms, see /license.txt */
namespace Application\Migrations\Schema\V110;
use Application\Migrations\AbstractMigrationChamilo;
use Doctrine\DBAL\Schema\Schema;
/**
* Fix c_quiz_answer's correct field for id_auto
*/
class Version20151221150100 extends AbstractMigrationChamilo
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
$this->addSql("
UPDATE track_e_attempt a
INNER JOIN c_quiz_answer qa
ON a.question_id = qa.question_id
INNER JOIN c_quiz_question q
ON qa.question_id = q.id
SET a.answer = qa.id_auto
WHERE
a.answer = qa.id AND
q.c_id = a.c_id AND
q.type IN (" . MATCHING . ", " . DRAGGABLE . ", " . MATCHING_DRAGGABLE . ")
");
$this->addSql("
UPDATE c_quiz_answer a
INNER JOIN c_quiz_answer b
ON a.question_id = b.question_id
INNER JOIN c_quiz_question q
ON b.question_id = q.id
SET a.correct = b.id_auto
WHERE
a.correct = b.id AND
q.c_id = a.c_id AND
q.type IN (" . MATCHING . ", " . DRAGGABLE . ", " . MATCHING_DRAGGABLE . ")
");
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
}
}

@ -64,7 +64,7 @@
<h3>Notable new Features</h3> <h3>Notable new Features</h3>
<h4>For end-users, teachers and Chamilo admins</h4> <h4>For end-users, teachers and Chamilo admins</h4>
<ul> <ul>
<li>Migrations from 1.9.x is now possible without major issues.</li> <li>Migrations from 1.9.x is now possible without major issue (that we know of).</li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/90e2852223d5aad04802f282b7919379084ec624">90e28522</a>) If chamilo exercise added in LP has pass % then change status to passed/failed</li> <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/90e2852223d5aad04802f282b7919379084ec624">90e28522</a>) If chamilo exercise added in LP has pass % then change status to passed/failed</li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/edf83bdc0d778d347dcf3e37425369eaaecb1335">edf83bdc</a> - <a href="https://support.chamilo.org/issues/7768">#7768</a>) Add filter by user on sales report</li> <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/edf83bdc0d778d347dcf3e37425369eaaecb1335">edf83bdc</a> - <a href="https://support.chamilo.org/issues/7768">#7768</a>) Add filter by user on sales report</li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/5b26584ff2b2db0b5a33a5c642a431b80ecb2c5b">5b26584f</a> - <a href="https://support.chamilo.org/issues/7768">#7768</a>) Display payment method on sale report</li> <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/5b26584ff2b2db0b5a33a5c642a431b80ecb2c5b">5b26584f</a> - <a href="https://support.chamilo.org/issues/7768">#7768</a>) Display payment method on sale report</li>
@ -94,7 +94,7 @@
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/5ac54cf549bd9dfe15fb3f5b9ec977e24afe8c7c">5ac54cf5</a>) Remove deprecated javascript_service_displayed variable to avoid notice</li> <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/5ac54cf549bd9dfe15fb3f5b9ec977e24afe8c7c">5ac54cf5</a>) Remove deprecated javascript_service_displayed variable to avoid notice</li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/c8bc145b1bbebe0e8c2fdfd56e17fcfeebbffe98">c8bc145b</a>) Delete courses folder after migration if folder is empty.</li> <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/c8bc145b1bbebe0e8c2fdfd56e17fcfeebbffe98">c8bc145b</a>) Delete courses folder after migration if folder is empty.</li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/2b95a8c296a0bf9d2552c775c7a71fec7b574b1a">2b95a8c2</a>) Add "I am a {language} user" and expose background context for tests</li> <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/2b95a8c296a0bf9d2552c775c7a71fec7b574b1a">2b95a8c2</a>) Add "I am a {language} user" and expose background context for tests</li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/b6d11076a24ac3005ea0b5963b9f5e1ce1f34cc5">b6d11076</a> - <a href="https://support.chamilo.org/issues/7898">#7898</a>) Change of <i> to <em> for WCAG support</li> <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/b6d11076a24ac3005ea0b5963b9f5e1ce1f34cc5">b6d11076</a> - <a href="https://support.chamilo.org/issues/7898">#7898</a>) Change of &lt;i&gt; to &lt;em&gt; for WCAG support</li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/775ef96c85f853daedd93fb05118fcd936315953">775ef96c</a> - <a href="https://support.chamilo.org/issues/7910">#7910</a>) Add curl dependency</li> <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/775ef96c85f853daedd93fb05118fcd936315953">775ef96c</a> - <a href="https://support.chamilo.org/issues/7910">#7910</a>) Add curl dependency</li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/a380a6905be8086ea6d22c1194bd5a40bf249852">a380a690</a>) Add possibility to use SVG logo for the platform</li> <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/a380a6905be8086ea6d22c1194bd5a40bf249852">a380a690</a>) Add possibility to use SVG logo for the platform</li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/2776c37887aa3b3d646a8a4501e823264f6de5cb">2776c378</a> - <a href="https://support.chamilo.org/issues/7909">#7909</a>) Add temporary indexes to speed up migration queries</li> <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/2776c37887aa3b3d646a8a4501e823264f6de5cb">2776c378</a> - <a href="https://support.chamilo.org/issues/7909">#7909</a>) Add temporary indexes to speed up migration queries</li>
@ -246,6 +246,9 @@
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/d16ecc995ba6c9ca067f71002f04c01fb7e8b30a">d16ecc99</a> - <a href="https://support.chamilo.org/issues/8007">#8007</a>) Set Mozilla Firefox as able to play MP3 files</li> <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/d16ecc995ba6c9ca067f71002f04c01fb7e8b30a">d16ecc99</a> - <a href="https://support.chamilo.org/issues/8007">#8007</a>) Set Mozilla Firefox as able to play MP3 files</li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/d712139fd837eabf397695390fb34cbecb1fb3a5">d712139f</a> - <a href="https://support.chamilo.org/issues/8004">#8004</a>) fix scroll items forum lpview CT#8004</li> <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/d712139fd837eabf397695390fb34cbecb1fb3a5">d712139f</a> - <a href="https://support.chamilo.org/issues/8004">#8004</a>) fix scroll items forum lpview CT#8004</li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/6645ea2f74eb2c0e88fe34ac559f6caa7fa8b8a0">6645ea2f</a>) Add User Access Overview report</li> <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/6645ea2f74eb2c0e88fe34ac559f6caa7fa8b8a0">6645ea2f</a>) Add User Access Overview report</li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/ac29dcda0be27d206cdf50904a4d575cc5351a6c">ac29dcda</a> - <a href="https://support.chamilo.org/issues/8003">#8003</a>) Avoid the filter the Gravatar URL when images are displayed </li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/b9fe27560b89251ff7409ecbfaeb8f1cd7abcd2e">b9fe2756</a> - <a href="https://support.chamilo.org/issues/8013">#8013</a>) Fix SQL queries related to fulltext search engine</li>
<li>(<a href="https://github.com/chamilo/chamilo-lms/commit/4c6d2e9e4899d2544cb7c7ee1aae362c93fb28f7">4c6d2e9e</a>) Fix c_quiz_answer's correct field with id_auto</li>
</ul> </ul>
<h3>Stylesheets and theming</h3> <h3>Stylesheets and theming</h3>
<ul> <ul>

@ -315,6 +315,13 @@ As this is only a minor version change from previous 1.10.* versions of Chamilo,
<li> you're done! No other upgrade procedure is required</li> <li> you're done! No other upgrade procedure is required</li>
</ul> </ul>
Please note that if you (unluckily) upgraded from any of the 1.9 versions to 1.10.0 against our recommendations, we
provide a patch script that should get most of it in order. The script is available here:<br />
<a href="https://raw.githubusercontent.com/chamilo/chamilo-lms/1.10.x/tests/scripts/fix_migrations_1.9.x_1.10.0.php">https://raw.githubusercontent.com/chamilo/chamilo-lms/1.10.x/tests/scripts/fix_migrations_1.9.x_1.10.0.php</a> or, if
you are using a development version of Chamilo, directly into you tests/scripts/ folder. You should place the file
in the /tests/scripts/ folder, then edit it to remove the "die();" line, then launch it from your browser (after
connecting to your Chamilo site as admin). You should also remove the scripts afterwards.<br />
This script is provided without warranty. Please *always* take a backup before you use it.
<br /> <br />

@ -198,7 +198,7 @@ if (api_is_allowed_to_edit()) {
1st: Get all files that are visible in the given path 1st: Get all files that are visible in the given path
*/ */
$querypath = Database::escape_string($querypath); $querypath = Database::escape_string($querypath);
$sql = "SELECT path, session_id, docs.id, props.to_group_id, docs.c_id $sql = "SELECT path, docs.session_id, docs.id, props.to_group_id, docs.c_id
FROM $doc_table AS docs FROM $doc_table AS docs
INNER JOIN $prop_table AS props INNER JOIN $prop_table AS props
ON ON
@ -235,7 +235,7 @@ if (api_is_allowed_to_edit()) {
} }
// 2nd: Get all folders that are invisible in the given path // 2nd: Get all folders that are invisible in the given path
$sql = "SELECT path, session_id, docs.id, props.to_group_id, docs.c_id $sql = "SELECT path, docs.session_id, docs.id, props.to_group_id, docs.c_id
FROM $doc_table AS docs INNER JOIN $prop_table AS props FROM $doc_table AS docs INNER JOIN $prop_table AS props
ON ON
docs.id = props.ref AND docs.id = props.ref AND

@ -965,7 +965,7 @@ abstract class Question
$tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF); $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
if ($addQs || $rmQs) { if ($addQs || $rmQs) {
//there's only one row per question on normal db and one document per question on search engine db //there's only one row per question on normal db and one document per question on search engine db
$sql = 'SELECT * FROM % $sql = 'SELECT * FROM %s
WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=%s LIMIT 1'; WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=%s LIMIT 1';
$sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id); $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
} else { } else {

@ -750,7 +750,7 @@ switch ($action) {
$count_skill_by_course[$course_item['code']] = $skills_in_course[$course_item['code']]; $count_skill_by_course[$course_item['code']] = $skills_in_course[$course_item['code']];
} }
} }
$item['photo'] = Display::img($user_info['avatar_small']); $item['photo'] = Display::img($user_info['avatar_small'], $user_info['complete_name'], [], false);
$item['currently_learning'] = !empty($count_skill_by_course) ? array_sum($count_skill_by_course) : 0; $item['currently_learning'] = !empty($count_skill_by_course) ? array_sum($count_skill_by_course) : 0;
} }
} }

@ -693,7 +693,7 @@ class Attendance
$value['result_color_bar'] = $user_faults['color_bar']; $value['result_color_bar'] = $user_faults['color_bar'];
} }
$photo = '<img src ="'.$userInfo['avatar_small'].'" />'; $photo = Display::img($userInfo['avatar_small'], $userInfo['complete_name'], [], false);
$value['photo'] = $photo; $value['photo'] = $photo;
$value['firstname'] = $user_data['firstname']; $value['firstname'] = $user_data['firstname'];

@ -775,15 +775,18 @@ class Display
/** /**
* Returns the htmlcode for an image * Returns the htmlcode for an image
* *
* @param string $image the filename of the file (in the main/img/ folder * @param string $image_path the filename of the file (in the main/img/ folder
* @param string $alt_text the alt text (probably a language variable) * @param string $alt_text the alt text (probably a language variable)
* @param array $additional_attributes (for instance height, width, onclick, ...) * @param array $additional_attributes (for instance height, width, onclick, ...)
* @param boolean $filterPath Optional. Whether filter the image path. Default is true
* @author Julio Montoya 2010 * @author Julio Montoya 2010
*/ */
public static function img($image_path, $alt_text = '', $additional_attributes = array()) public static function img($image_path, $alt_text = '', $additional_attributes = array(), $filterPath = true)
{ {
// Sanitizing the parameter $image_path // Sanitizing the parameter $image_path
$image_path = Security::filter_img_path($image_path); if ($filterPath) {
$image_path = Security::filter_img_path($image_path);
}
// alt text = the image name if there is none provided (for XHTML compliance) // alt text = the image name if there is none provided (for XHTML compliance)
if ($alt_text == '') { if ($alt_text == '') {

@ -5522,7 +5522,7 @@ class DocumentManager
} }
} }
if ($user_image) { if ($user_image) {
return Display::img($icon, $basename, array()); return Display::img($icon, $basename, array(), false);
} }
return Display::return_icon($icon, $basename, array()); return Display::return_icon($icon, $basename, array());
} }

@ -141,7 +141,7 @@ class ExerciseLib
$select_items[0]['letter'] = '--'; $select_items[0]['letter'] = '--';
$select_items[0]['answer'] = ''; $select_items[0]['answer'] = '';
foreach ($answer_matching as $id => $value) { foreach ($answer_matching as $id => $value) {
$select_items[$i]['id'] = $value['id']; $select_items[$i]['id'] = $value['id_auto'];
$select_items[$i]['letter'] = $cpt1[$id]; $select_items[$i]['letter'] = $cpt1[$id];
$select_items[$i]['answer'] = $value['answer']; $select_items[$i]['answer'] = $value['answer'];
$i++; $i++;

@ -412,7 +412,7 @@ function handle_uploaded_document(
); );
// Redo visibility // Redo visibility
api_set_default_visibility(TOOL_DOCUMENT, $documentId); api_set_default_visibility(TOOL_DOCUMENT, $documentId, null, $courseInfo);
} else { } else {
// There might be cases where the file exists on disk but there is no registration of that in the database // There might be cases where the file exists on disk but there is no registration of that in the database
// In this case, and if we are in overwrite mode, overwrite and create the db record // In this case, and if we are in overwrite mode, overwrite and create the db record
@ -445,7 +445,7 @@ function handle_uploaded_document(
); );
// Redo visibility // Redo visibility
api_set_default_visibility(TOOL_DOCUMENT, $documentId); api_set_default_visibility(TOOL_DOCUMENT, $documentId, null, $courseInfo);
} }
} }
@ -492,7 +492,7 @@ function handle_uploaded_document(
); );
// Redo visibility // Redo visibility
api_set_default_visibility(TOOL_DOCUMENT, $documentId); api_set_default_visibility(TOOL_DOCUMENT, $documentId, null, $courseInfo);
} }
// If the file is in a folder, we need to update all parent folders // If the file is in a folder, we need to update all parent folders
item_property_update_on_folder($courseInfo, $uploadPath, $userId); item_property_update_on_folder($courseInfo, $uploadPath, $userId);
@ -569,7 +569,7 @@ function handle_uploaded_document(
); );
// Redo visibility // Redo visibility
api_set_default_visibility(TOOL_DOCUMENT, $documentId); api_set_default_visibility(TOOL_DOCUMENT, $documentId, null, $courseInfo);
} }
// If the file is in a folder, we need to update all parent folders // If the file is in a folder, we need to update all parent folders
@ -631,7 +631,7 @@ function handle_uploaded_document(
$sessionId $sessionId
); );
// Redo visibility // Redo visibility
api_set_default_visibility(TOOL_DOCUMENT, $documentId); api_set_default_visibility(TOOL_DOCUMENT, $documentId, null, $courseInfo);
} }
// If the file is in a folder, we need to update all parent folders // If the file is in a folder, we need to update all parent folders
@ -1237,7 +1237,7 @@ function add_document(
Database::query($sql); Database::query($sql);
if ($save_visibility) { if ($save_visibility) {
api_set_default_visibility($documentId, TOOL_DOCUMENT, $group_id); api_set_default_visibility($documentId, TOOL_DOCUMENT, $group_id, $_course);
} }
return $documentId; return $documentId;

@ -306,7 +306,7 @@ class Link extends Model
$tbl_se_ref = Database:: get_main_table( $tbl_se_ref = Database:: get_main_table(
TABLE_MAIN_SEARCH_ENGINE_REF TABLE_MAIN_SEARCH_ENGINE_REF
); );
$sql = 'INSERT INTO %s (c_id, id, course_code, tool_id, ref_id_high_level, search_did) $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
VALUES (NULL , \'%s\', \'%s\', %s, %s)'; VALUES (NULL , \'%s\', \'%s\', %s, %s)';
$sql = sprintf( $sql = sprintf(
$sql, $sql,

@ -1132,6 +1132,7 @@ $AdminPass = "Senha do Administrador (<font color=\"red\">você poderá alterar
$EducationManager = "Gerente do projeto"; $EducationManager = "Gerente do projeto";
$CampusName = "Nome da sua plataforma"; $CampusName = "Nome da sua plataforma";
$DBSettingIntro = "O script de instalação irá criar o(s) banco(s) de dados principal(is) do Doekos. Se você tiver permissão para usar apenas uma base de dados no seu Serviço de Hospedagem, o Chamilo não irá funcionar, a não ser que você escolher a opção \"Uma base de dados\"."; $DBSettingIntro = "O script de instalação irá criar o(s) banco(s) de dados principal(is) do Doekos. Se você tiver permissão para usar apenas uma base de dados no seu Serviço de Hospedagem, o Chamilo não irá funcionar, a não ser que você escolher a opção \"Uma base de dados\".";
$TimeSpentByStudentsInCourses = "Tempo gasto por estudantes em cursos";
$Step3 = "Passo 3 de 6"; $Step3 = "Passo 3 de 6";
$Step4 = "Passo 4 de 6"; $Step4 = "Passo 4 de 6";
$Step5 = "Passo 5 de 6"; $Step5 = "Passo 5 de 6";
@ -1141,6 +1142,7 @@ $DBSetting = "Configurações da base de dados MySQL";
$MainLang = "Língua principal"; $MainLang = "Língua principal";
$Licence = "Licença"; $Licence = "Licença";
$LastCheck = "Ultima verificação antes da instalação"; $LastCheck = "Ultima verificação antes da instalação";
$AutoEvaluation = "Auto avaliação";
$DbPrefixForm = "Prefixo da base de dados MySQL"; $DbPrefixForm = "Prefixo da base de dados MySQL";
$DbPrefixCom = "Deixe em branco se não for necessário"; $DbPrefixCom = "Deixe em branco se não for necessário";
$EncryptUserPass = "Encriptar senhas de usuário na base de dados"; $EncryptUserPass = "Encriptar senhas de usuário na base de dados";
@ -1396,6 +1398,7 @@ $NoCategories = "Não há categorias";
$AllowCoursesInCategory = "Permitir a adição de cursos nessa categoria ?"; $AllowCoursesInCategory = "Permitir a adição de cursos nessa categoria ?";
$GoToForum = "Ir para o fórum"; $GoToForum = "Ir para o fórum";
$CategoryCode = "Código da categoria"; $CategoryCode = "Código da categoria";
$MetaTwitterCreatorComment = "O Twitter Criador é uma conta no Twitter (por exemplo @ywarnier) que representa o ou a *pessoa* que criou o site. Este campo é opcional.";
$EditNode = "Editar esta categoria"; $EditNode = "Editar esta categoria";
$OpenNode = "Abrir esta categoria"; $OpenNode = "Abrir esta categoria";
$DeleteNode = "Excluir esta categoria"; $DeleteNode = "Excluir esta categoria";
@ -1406,6 +1409,7 @@ $TreeRecountedIn = "Diretório recontado em";
$RebuildTree = "Reconstruir diretórios"; $RebuildTree = "Reconstruir diretórios";
$RefreshNbChildren = "Atualizar o número de subdiretórios"; $RefreshNbChildren = "Atualizar o número de subdiretórios";
$ShowTree = "Mostrar diretórios"; $ShowTree = "Mostrar diretórios";
$MetaImagePathTitle = "Caminho de imagem Meta";
$LogDeleteCat = "Categoria excluida"; $LogDeleteCat = "Categoria excluida";
$RecountChildren = "Recontar subdiretórios"; $RecountChildren = "Recontar subdiretórios";
$UpInSameLevel = "Subir para o mesmo nível"; $UpInSameLevel = "Subir para o mesmo nível";
@ -1462,6 +1466,7 @@ $CourseCreationSucceeded = "O curso foi criado com sucesso.";
$OnTheHardDisk = "no disco rígido"; $OnTheHardDisk = "no disco rígido";
$IsVirtualCourse = "É um curso virtual ?"; $IsVirtualCourse = "É um curso virtual ?";
$AnnouncementUpdated = "O anúncio foi atualizado"; $AnnouncementUpdated = "O anúncio foi atualizado";
$MetaImagePathComment = "Este caminho Imagem Meta é o caminho para um arquivo dentro do seu diretório Chamilo (por exemplo, home/image.png) que devem aparecer em um cartão ou um cartão de Twitter OpenGraph ao mostrar um link para o seu LMS. Twitter recomenda uma imagem de 120x120 pixels, o que pode por vezes pode ser recortadas com 120x90.";
$PermissionsForNewFiles = "Permissões para novos arquivos"; $PermissionsForNewFiles = "Permissões para novos arquivos";
$PermissionsForNewFilesComment = "A capacidade para definir permissões e atribuí-las aos arquivos recém criados aumenta a segurança contra ataques de hackers que podem colocar material perigoso na plataforma. O valor pré-definido (0660) deveria ser suficiente para proporcionar ao servidor um nível razoável de segurança. O formato fornecido usa a terminologia UNIX do Proprietário-Grupo-Público com as permissões de Leitura-Escrita-Execução. Se utiliza o Oogie, tome cuidado para que o usuários que iniciar o OpenOffice poderá escrever arquivos na pasta do curso."; $PermissionsForNewFilesComment = "A capacidade para definir permissões e atribuí-las aos arquivos recém criados aumenta a segurança contra ataques de hackers que podem colocar material perigoso na plataforma. O valor pré-definido (0660) deveria ser suficiente para proporcionar ao servidor um nível razoável de segurança. O formato fornecido usa a terminologia UNIX do Proprietário-Grupo-Público com as permissões de Leitura-Escrita-Execução. Se utiliza o Oogie, tome cuidado para que o usuários que iniciar o OpenOffice poderá escrever arquivos na pasta do curso.";
$Guest = "Convidado"; $Guest = "Convidado";
@ -1633,6 +1638,7 @@ $ShowOnlineUsers = "Exibir o número de de usuários online em todas as páginas
$ShowOnlineCourse = "Exibir o número de usuários online neste curso"; $ShowOnlineCourse = "Exibir o número de usuários online neste curso";
$ShowIconsInNavigationsMenuTitle = "Mostrar ícones no menu de navegação?"; $ShowIconsInNavigationsMenuTitle = "Mostrar ícones no menu de navegação?";
$SeeAllRightsAllRolesForSpecificLocation = "Ver todas as funções e permissões para uma localização específica"; $SeeAllRightsAllRolesForSpecificLocation = "Ver todas as funções e permissões para uma localização específica";
$MetaTwitterCreatorTitle = "Twitter Criador da conta";
$ClassesSubscribed = "As turmas selecionadas foram inscritas nos cursos selecionados"; $ClassesSubscribed = "As turmas selecionadas foram inscritas nos cursos selecionados";
$RoleId = "ID da função"; $RoleId = "ID da função";
$RoleName = "Nome da função"; $RoleName = "Nome da função";
@ -1710,6 +1716,7 @@ $EnableToolIntroductionTitle = "Ativa as introduções das ferramentas";
$EnableToolIntroductionComment = "Ativa a introduções em cada ferramenta da página inicial"; $EnableToolIntroductionComment = "Ativa a introduções em cada ferramenta da página inicial";
$BreadCrumbsCourseHomepageTitle = "Barra de navegação da página principal do curso"; $BreadCrumbsCourseHomepageTitle = "Barra de navegação da página principal do curso";
$BreadCrumbsCourseHomepageComment = "A barra de navegação é o sistema horizontal de ligações da navegação, normalmente localizado na parte esquerda do topo da página. Esta opção habilita a barra de navegação nas páginas dos cursos."; $BreadCrumbsCourseHomepageComment = "A barra de navegação é o sistema horizontal de ligações da navegação, normalmente localizado na parte esquerda do topo da página. Esta opção habilita a barra de navegação nas páginas dos cursos.";
$MetaTwitterSiteComment = "O site Twitter é uma conta no Twitter (por exemplo @chamilo_news) que está relacionado ao seu site. É geralmente uma conta de mais temporário do que o criador conta Twitter, ou representa uma empresa (em vez de uma pessoa). Este campo é obrigatório se você deseja que os campos do cartão meta do Twitter para mostrar.";
$LoginPageMainArea = "Área principal da página de acesso"; $LoginPageMainArea = "Área principal da página de acesso";
$LoginPageMenu = "Menu da página de acesso"; $LoginPageMenu = "Menu da página de acesso";
$CampusHomepageMainArea = "Área da página inicial da plataforma"; $CampusHomepageMainArea = "Área da página inicial da plataforma";
@ -1988,6 +1995,10 @@ $IsNotWritable = "não é editável";
$FieldMovedDown = "O campo foi movido para baixo"; $FieldMovedDown = "O campo foi movido para baixo";
$CannotMoveField = "Não se pode mover o campo"; $CannotMoveField = "Não se pode mover o campo";
$FieldMovedUp = "O campo foi movido para cima"; $FieldMovedUp = "O campo foi movido para cima";
$MetaTitleTitle = "Abrir Gráfico do título da meta";
$MetaDescriptionComment = "Isto irá mostrar e um Abrir um Gráfico de Descrição da meta (og: Descrição) nos cabeçalhos do seu site";
$MetaDescriptionTitle = "Descrição da Meta";
$MetaTitleComment = "Isto irá mostrar uma meta e Abrir um Gráfico com o título (og: título) nos cabeçalhos do seu site";
$FieldDeleted = "O campo foi excluido"; $FieldDeleted = "O campo foi excluido";
$CannotDeleteField = "Não é possível excluir o campo"; $CannotDeleteField = "Não é possível excluir o campo";
$AddUsersByCoachTitle = "Registar usuário como tutor"; $AddUsersByCoachTitle = "Registar usuário como tutor";
@ -4016,6 +4027,14 @@ $Authoring = "Autoria";
$SessionIdentifier = "Identificador da sessão"; $SessionIdentifier = "Identificador da sessão";
$SessionCategory = "Categorias das sessões"; $SessionCategory = "Categorias das sessões";
$ConvertToUniqueAnswer = "Converter para resposta única"; $ConvertToUniqueAnswer = "Converter para resposta única";
$ReportsRequiresNoSetting = "Este tipo de relatório não requer configurações";
$ShowWizard = "Mostrar assistente";
$ReportFormat = "Formato de relatório";
$ReportType = "Tipo de relatório";
$PleaseChooseReportType = "Por favor, escolha um tipo de relatório";
$PleaseFillFormToBuildReport = "Por favor, preencha o formulário para a construção do relatório";
$UnknownFormat = "Formato desconhecido";
$ErrorWhileBuildingReport = "Ocorreu um erro ao construir o relatório";
$WikiSearchResults = "Resultados da busca no Wiki"; $WikiSearchResults = "Resultados da busca no Wiki";
$StartPage = "Página principal"; $StartPage = "Página principal";
$EditThisPage = "Editar esta página"; $EditThisPage = "Editar esta página";
@ -5225,6 +5244,7 @@ $PleaseSelectInstallationProcessLanguage = "Selecione, por favor, o idioma que g
$HereAreTheValuesYouEntered = "Aqui estão os valores que introduziu"; $HereAreTheValuesYouEntered = "Aqui estão os valores que introduziu";
$PrintThisPageToRememberPassAndOthers = "Imprima esta página para se lembrar da senha e demais configurações"; $PrintThisPageToRememberPassAndOthers = "Imprima esta página para se lembrar da senha e demais configurações";
$TheInstallScriptWillEraseAllTables = "O script de instalação apagará todas as tabelas das bases de dados selecionadas. Recomendamos que faça uma cópia de todas elas antes de confirmar a última etapa da instalação."; $TheInstallScriptWillEraseAllTables = "O script de instalação apagará todas as tabelas das bases de dados selecionadas. Recomendamos que faça uma cópia de todas elas antes de confirmar a última etapa da instalação.";
$Published = "Publicados";
$ReadWarningBelow = "leia a mensagem abaixo"; $ReadWarningBelow = "leia a mensagem abaixo";
$SecurityAdvice = "Informação de segurança"; $SecurityAdvice = "Informação de segurança";
$YouHaveMoreThanXCourses = "Tem mais de %d cursos na sua plataforma Chamilo! Somente %d cursos foram atualizados. Para atualizar os outros cursos, %s clique aqui %s"; $YouHaveMoreThanXCourses = "Tem mais de %d cursos na sua plataforma Chamilo! Somente %d cursos foram atualizados. Para atualizar os outros cursos, %s clique aqui %s";
@ -7193,4 +7213,76 @@ $DataTableSearch = "Procurar";
$HideColumn = "Ocultar coluna"; $HideColumn = "Ocultar coluna";
$DisplayColumn = "Mostrar coluna"; $DisplayColumn = "Mostrar coluna";
$LegalAgreementAccepted = "Acordo legal aceitado"; $LegalAgreementAccepted = "Acordo legal aceitado";
$WorkEmailAlertActivateOnlyForTeachers = "Ative somente para alerta de professores via e-mail sobre a nova submissão de trabalhos";
$WorkEmailAlertActivateOnlyForStudents = "Ative somente para alerta de estudantes via e-mail sobre a nova submissão de trabalhos";
$Uncategorized = "Sem categoria";
$NaturalYear = "Natural ano";
$AutoWeight = "Peso automática";
$AutoWeightExplanation = "Use a distribuição de peso automático para acelerar as coisas. O sistema irá distribuir o peso total uniformemente entre os itens de avaliação abaixo.";
$EditWeight = "Editar peso";
$TheSkillHasBeenCreated = "A habilidade foi criado";
$CreateSkill = "Criar habilidade";
$CannotCreateSkill = "Não é possível criar habilidade";
$SkillEdit = "Editar habilidade";
$TheSkillHasBeenUpdated = "A habilidade foi atualizado";
$CannotUpdateSkill = "Não é possível atualizar habilidade";
$BadgesManagement = "Gestão de emblemas";
$CurrentBadges = "Emblemas atuais";
$SaveBadge = "Salvar emblema";
$BadgeMeasuresXPixelsInPNG = "Emblema mede 200x200 pixels em PNG";
$SetTutor = "Definir como treinador";
$UniqueAnswerImage = "Imagem única resposta";
$TimeSpentByStudentsInCoursesGroupedByCode = "Tempo gasto por estudantes de cursos, agrupados por código";
$TestResultsByStudentsGroupesByCode = "Testes resultados por grupos de estudantes, por código";
$TestResultsByStudents = "Testes de resultados por aluno";
$SystemCouldNotLogYouIn = "O sistema não foi capaz de fazer seu login. Por favor, contate o administrador.";
$ShibbolethLogin = "Senha para Entrar";
$NewStatus = "Novo status";
$Reason = "Razão";
$RequestStatus = "Solicite novo status";
$StatusRequestMessage = "Você tem sido registrados com as permissões padrão. Você pode solicitar mais permissões, submetendo o seguinte pedido.";
$ReasonIsMandatory = "You reason field is mandatory. Please fill it in before submitting.";
$RequestSubmitted = "Your request has been submitted.";
$RequestFailed = "Nós não somos capazes de satisfazer o seu pedido neste momento. Entre em contato com o administrador.";
$InternalLogin = "Login interno";
$AlreadyLoggedIn = "Você já está logado";
$Draggable = "Sequência de ordenação";
$Incorrect = "Incorreto";
$YouNotYetAchievedCertificates = "Você não ter conseguiu qualquer certificado ainda. Continue em sua rota de aprendizagem para obter um!";
$SearchCertificates = "Pesquisar certificados";
$TheUserXNotYetAchievedCertificates = "Usuário %s que não adquiriu qualquer certificado ainda";
$CertificatesNotPublic = "Os certificados não estão disponíveis ao público";
$MatchingDraggable = "Jogo arrastando";
$ForumThreadPeerScoring = "Tópico marcado por pares";
$ForumThreadPeerScoringComment = "Se selecionado, esta opção irá necessitar cada aluno para se qualificar pelo menos 2 outros estudantes, a fim de obter a sua pontuação maior que 0 no Boletim.";
$ForumThreadPeerScoringStudentComment = "Para obter a pontuação esperada neste fórum, a sua contribuição terá de ser marcado por um outro estudante, e você terá que marcar as contribuições de outros pelo menos 2 dos alunos. Até chegar a esse objetivo, mesmo que marcou, sua contribuição vai mostrar como uma pontuação 0 nas séries globais para este curso.";
$Readable = "Legível";
$NotReadable = "Não pode ser lido";
$DefaultInstallAdminFirstname = "João";
$DefaultInstallAdminLastname = "Bogda";
$AttendanceUpdated = "Presenças atualizadas";
$HideHomeTopContentWhenLoggedInText = "Esconder conteúdo no topo da homepage quando logado";
$HideHomeTopContentWhenLoggedInComment = "Na página inicial da plataforma, esta opção permite que você esconda o bloco de introdução (deixar apenas os anúncios, por exemplo), para todos os usuários que já estão logados. O bloco introdução geral ainda vai aparecer para os usuários ainda que não estejam conectados.";
$HideGlobalAnnouncementsWhenNotLoggedInText = "Ocultar anúncios globais para anônimos";
$HideGlobalAnnouncementsWhenNotLoggedInComment = "Ocultar anúncios de plataforma de usuários anônimos, e apenas mostrá-los aos usuários autenticados.";
$CourseCreationUsesTemplateText = "Use curso modelo para novos cursos";
$CourseCreationUsesTemplateComment = "Defina esta opção para usar o mesmo curso de modelo (identificada por seu curso de identificação numérica no banco de dados) para todos os novos cursos que serão criados na plataforma. Por favor, note que, se não for devidamente planeado, esta definição pode ter um enorme impacto sobre a utilização do espaço. O curso de modelo será usado como se o professor fez uma cópia do curso com as ferramentas de backup é claro, por isso não o conteúdo do usuário é copiado, apenas o material professor. Todas as outras regras aplicam-curso backup. Deixe em branco (ou definido como 0) para desativar.";
$EnablePasswordStrengthCheckerText = "Verificador de força de senha";
$EnablePasswordStrengthCheckerComment = "Ative essa opção para adicionar um indicador visual de força da senha, quando o usuário muda seu/sua senha. Isto não impedirá senhas ruins para ser adicionado, ele só funciona como um auxiliar visual.";
$EnableCaptchaText = "CAPTCHA";
$EnableCaptchaComment = "Ativar um CAPTCHA no formulário de login para evitar martelar senha";
$CaptchaNumberOfMistakesBeforeBlockingAccountText = "Subsídio erros CAPTCHA";
$CaptchaNumberOfMistakesBeforeBlockingAccountComment = "O número de vezes que um usuário pode cometer um erro na caixa de CAPTCHA antes de sua conta está bloqueada.";
$CaptchaTimeAccountIsLockedText = "CAPTCHA conta o tempo de bloqueio";
$CaptchaTimeAccountIsLockedComment = "Se o usuário alcança o limite máximo para os erros de login (quando se utiliza o CAPTCHA), seu/sua conta será bloqueada para este número de minutos.";
$DRHAccessToAllSessionContentText = "Diretores de RH acessar todo o conteúdo da sessão";
$DRHAccessToAllSessionContentComment = "Se ativado, diretores de recursos humanos terá acesso a todo o conteúdo e os usuários das sessões (s) que ele segue.";
$ShowGroupForaInGeneralToolText = "Fóruns de grupos de exibição no fórum geral";
$ShowGroupForaInGeneralToolComment = "Fóruns de grupos de exibição na ferramenta fórum ao nível da disciplina. Essa opção é ativada por padrão (neste caso, fórum grupo visibilidades individuais ainda agem como um critério adicional). Se os fóruns forem desativado, o grupo só será visível através da ferramenta de grupo, sejam eles públicos ou não.";
$TutorsCanAssignStudentsToSessionsText = "Os tutores podem atribuir aos alunos umas sessões";
$TutorsCanAssignStudentsToSessionsComment = "Quando ativado, treinadores de curso / tutores em sessões podem se inscrever novos usuários à sua sessão. Esta opção é outra forma apenas disponível para administradores e administradores de sessão.";
$UniqueAnswerImagePreferredSize200x150 = "As imagens serão redimensionadas (para cima ou para baixo) para 200x150 pixels. Para uma melhor prestação de questão, recomenda-se fazer o upload apenas imagens deste tamanho.";
$AllowLearningPathReturnLinkTitle = "Mostrar caminhos de aprendizagem retornar ligação";
$AllowLearningPathReturnLinkComment = "Desative esta opção para ocultar o \"Return to homepage 'botão nos percursos de aprendizagem";
$Triesleft = "Tentativas a esquerda";
?> ?>

@ -488,12 +488,12 @@ class learnpath
$prerequisites = 0, $prerequisites = 0,
$max_time_allowed = 0 $max_time_allowed = 0
) { ) {
$course_id = api_get_course_int_id(); $course_id = $this->course_info['real_id'];
if ($this->debug > 0) { if ($this->debug > 0) {
error_log('New LP - In learnpath::add_item(' . $parent . ',' . $previous . ',' . $type . ',' . $id . ',' . $title . ')', 0); error_log('New LP - In learnpath::add_item(' . $parent . ',' . $previous . ',' . $type . ',' . $id . ',' . $title . ')', 0);
} }
$tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM); $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
$_course = api_get_course_info(); $_course = $this->course_info;
$parent = intval($parent); $parent = intval($parent);
$previous = intval($previous); $previous = intval($previous);
$id = intval($id); $id = intval($id);
@ -567,7 +567,7 @@ class learnpath
$max_score = Database :: result($rsQuiz, 0, 0); $max_score = Database :: result($rsQuiz, 0, 0);
// Disabling the exercise if we add it inside a LP // Disabling the exercise if we add it inside a LP
$exercise = new Exercise(); $exercise = new Exercise($course_id);
$exercise->read($id); $exercise->read($id);
$exercise->disable(); $exercise->disable();
$exercise->save(); $exercise->save();
@ -710,7 +710,7 @@ class learnpath
* @return integer The new learnpath ID on success, 0 on failure * @return integer The new learnpath ID on success, 0 on failure
*/ */
public static function add_lp( public static function add_lp(
$course, $courseCode,
$name, $name,
$description = '', $description = '',
$learnpath = 'guess', $learnpath = 'guess',
@ -721,7 +721,15 @@ class learnpath
$categoryId = 0 $categoryId = 0
) { ) {
global $charset; global $charset;
$course_id = api_get_course_int_id();
if (!empty($courseCode)) {
$courseInfo = api_get_course_info($courseCode);
$course_id = $courseInfo['real_id'];
} else {
$course_id = api_get_course_int_id();
$courseInfo = api_get_course_info();
}
$tbl_lp = Database :: get_course_table(TABLE_LP_MAIN); $tbl_lp = Database :: get_course_table(TABLE_LP_MAIN);
// Check course code exists. // Check course code exists.
// Check lp_name doesn't exist, otherwise append something. // Check lp_name doesn't exist, otherwise append something.
@ -819,16 +827,15 @@ class learnpath
$sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id"; $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
Database::query($sql); Database::query($sql);
$course_info = api_get_course_info();
// Insert into item_property. // Insert into item_property.
api_item_property_update( api_item_property_update(
$course_info, $courseInfo,
TOOL_LEARNPATH, TOOL_LEARNPATH,
$id, $id,
'LearnpathAdded', 'LearnpathAdded',
api_get_user_id() api_get_user_id()
); );
api_set_default_visibility($id, TOOL_LEARNPATH); api_set_default_visibility($id, TOOL_LEARNPATH, 0, $courseInfo);
return $id; return $id;
} }
break; break;
@ -985,14 +992,17 @@ class learnpath
/** /**
* Static admin function allowing removal of a learnpath * Static admin function allowing removal of a learnpath
* @param string Course code * @param array $courseInfo
* @param integer Learnpath ID * @param integer Learnpath ID
* @param string Whether to delete data or keep it (default: 'keep', others: 'remove') * @param string Whether to delete data or keep it (default: 'keep', others: 'remove')
* @return boolean True on success, false on failure (might change that to return number of elements deleted) * @return boolean True on success, false on failure (might change that to return number of elements deleted)
*/ */
public function delete($course = null, $id = null, $delete = 'keep') public function delete($courseInfo = null, $id = null, $delete = 'keep')
{ {
$course_id = api_get_course_int_id(); $course_id = api_get_course_int_id();
if (!empty($courseInfo)) {
$course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
}
// TODO: Implement a way of getting this to work when the current object is not set. // TODO: Implement a way of getting this to work when the current object is not set.
// In clear: implement this in the item class as well (abstract class) and use the given ID in queries. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
@ -3219,7 +3229,7 @@ class learnpath
return $html; return $html;
} }
/** /**
* Returns an HTML-formatted string ready to display with teacher buttons * Returns an HTML-formatted string ready to display with teacher buttons
* in LP view menu * in LP view menu
* @return string HTML TOC ready to display * @return string HTML TOC ready to display
@ -5623,13 +5633,13 @@ class learnpath
$edit_icon .= '</a>'; $edit_icon .= '</a>';
if ( if (
!in_array($arrLP[$i]['item_type'], ['forum', 'thread']) !in_array($arrLP[$i]['item_type'], ['forum', 'thread'])
) { ) {
if ( if (
$this->items[$arrLP[$i]['id']]->getForumThread( $this->items[$arrLP[$i]['id']]->getForumThread(
$this->course_int_id, $this->course_int_id,
$this->lp_session_id $this->lp_session_id
) )
) { ) {
$forumIcon = Display::url( $forumIcon = Display::url(
Display::return_icon('forum.png', get_lang('CreateForum'), [], ICON_SIZE_TINY), Display::return_icon('forum.png', get_lang('CreateForum'), [], ICON_SIZE_TINY),
@ -5638,10 +5648,10 @@ class learnpath
); );
} else { } else {
$forumIconUrl = api_get_self() . '?' . api_get_cidreq() . '&' . http_build_query([ $forumIconUrl = api_get_self() . '?' . api_get_cidreq() . '&' . http_build_query([
'action' => 'create_forum', 'action' => 'create_forum',
'id' => $arrLP[$i]['id'], 'id' => $arrLP[$i]['id'],
'lp_id' => $this->lp_id 'lp_id' => $this->lp_id
]); ]);
$forumIcon = Display::url( $forumIcon = Display::url(
Display::return_icon('forum.png', get_lang('CreateForum'), [], ICON_SIZE_TINY), Display::return_icon('forum.png', get_lang('CreateForum'), [], ICON_SIZE_TINY),
$forumIconUrl, $forumIconUrl,
@ -5670,7 +5680,7 @@ class learnpath
} }
if ($update_audio != 'true') { if ($update_audio != 'true') {
$row = $move_icon . ' ' . $icon . $row = $move_icon . ' ' . $icon .
Display::span($title_cut) . Display::span($title_cut) .
Display::tag( Display::tag(
'div', 'div',
"<div class=\"btn-group btn-group-xs\">$audio $edit_icon $forumIcon $prerequisities_icon $move_item_icon $audio_icon $delete_icon</div>", "<div class=\"btn-group btn-group-xs\">$audio $edit_icon $forumIcon $prerequisities_icon $move_item_icon $audio_icon $delete_icon</div>",
@ -5908,14 +5918,24 @@ class learnpath
/** /**
* Create a new document //still needs some finetuning * Create a new document //still needs some finetuning
* @param array $_course * @param array $courseInfo
* @param string $content
* @param string $title
* @param string $extension
*
* @return string * @return string
*/ */
public function create_document($_course) public function create_document($courseInfo, $content = '', $title = '', $extension = 'html')
{ {
$course_id = api_get_course_int_id(); if (!empty($courseInfo)) {
$course_id = $courseInfo['real_id'];
} else {
$course_id = api_get_course_int_id();
}
global $charset; global $charset;
$dir = isset ($_GET['dir']) ? $_GET['dir'] : $_POST['dir']; $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
$dir = isset ($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
// Please, do not modify this dirname formatting. // Please, do not modify this dirname formatting.
if (strstr($dir, '..')) if (strstr($dir, '..'))
$dir = '/'; $dir = '/';
@ -5926,35 +5946,43 @@ class learnpath
if ($dir[strlen($dir) - 1] != '/') if ($dir[strlen($dir) - 1] != '/')
$dir .= '/'; $dir .= '/';
$filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document' . $dir; $filepath = api_get_path(SYS_COURSE_PATH) . $courseInfo['path'] . '/document' . $dir;
if (empty($_POST['dir']) && empty($_GET['dir'])) { if (empty($_POST['dir']) && empty($_GET['dir'])) {
//Generates folder //Generates folder
$result = $this->generate_lp_folder($_course); $result = $this->generate_lp_folder($courseInfo);
$dir = $result['dir']; $dir = $result['dir'];
$filepath = $result['filepath']; $filepath = $result['filepath'];
} }
if (!is_dir($filepath)) { if (!is_dir($filepath)) {
$filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document/'; $filepath = api_get_path(SYS_COURSE_PATH) . $courseInfo['path'] . '/document/';
$dir = '/'; $dir = '/';
} }
// stripslashes() before calling api_replace_dangerous_char() because $_POST['title'] // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
// is already escaped twice when it gets here. // is already escaped twice when it gets here.
$title = api_replace_dangerous_char(stripslashes($_POST['title']));
$originalTitle = !empty($title) ? $title : $_POST['title'];
if (!empty($title)) {
$title = api_replace_dangerous_char(stripslashes($title));
} else {
$title = api_replace_dangerous_char(stripslashes($_POST['title']));
}
$title = disable_dangerous_file($title); $title = disable_dangerous_file($title);
$filename = $title; $filename = $title;
$content = $_POST['content_lp'];
$content = isset($content) ? $content : $_POST['content_lp'];
$tmp_filename = $filename; $tmp_filename = $filename;
$i = 0; $i = 0;
while (file_exists($filepath . $tmp_filename . '.html')) while (file_exists($filepath . $tmp_filename . '.'.$extension))
$tmp_filename = $filename . '_' . ++ $i; $tmp_filename = $filename . '_' . ++ $i;
$filename = $tmp_filename . '.html'; $filename = $tmp_filename . '.'.$extension;
$content = stripslashes($content); $content = stripslashes($content);
$content = str_replace(api_get_path(WEB_COURSE_PATH), api_get_path(REL_PATH).'courses/', $content); $content = str_replace(api_get_path(WEB_COURSE_PATH), api_get_path(REL_PATH).'courses/', $content);
@ -5962,9 +5990,9 @@ class learnpath
// Change the path of mp3 to absolute. // Change the path of mp3 to absolute.
// The first regexp deals with :// urls. // The first regexp deals with :// urls.
$content = preg_replace("|(flashvars=\"file=)([^:/]+)/|", "$1" . api_get_path(REL_COURSE_PATH) . $_course['path'] . '/document/', $content); $content = preg_replace("|(flashvars=\"file=)([^:/]+)/|", "$1" . api_get_path(REL_COURSE_PATH) . $courseInfo['path'] . '/document/', $content);
// The second regexp deals with audio/ urls. // The second regexp deals with audio/ urls.
$content = preg_replace("|(flashvars=\"file=)([^/]+)/|", "$1" . api_get_path(REL_COURSE_PATH) . $_course['path'] . '/document/$2/', $content); $content = preg_replace("|(flashvars=\"file=)([^/]+)/|", "$1" . api_get_path(REL_COURSE_PATH) . $courseInfo['path'] . '/document/$2/', $content);
// For flv player: To prevent edition problem with firefox, we have to use a strange tip (don't blame me please). // For flv player: To prevent edition problem with firefox, we have to use a strange tip (don't blame me please).
$content = str_replace('</body>', '<style type="text/css">body{}</style></body>', $content); $content = str_replace('</body>', '<style type="text/css">body{}</style></body>', $content);
@ -5977,7 +6005,7 @@ class learnpath
$save_file_path = $dir.$filename; $save_file_path = $dir.$filename;
$document_id = add_document( $document_id = add_document(
$_course, $courseInfo,
$save_file_path, $save_file_path,
'file', 'file',
$file_size, $file_size,
@ -5986,7 +6014,7 @@ class learnpath
if ($document_id) { if ($document_id) {
api_item_property_update( api_item_property_update(
$_course, $courseInfo,
TOOL_DOCUMENT, TOOL_DOCUMENT,
$document_id, $document_id,
'DocumentAdded', 'DocumentAdded',
@ -5999,7 +6027,7 @@ class learnpath
); );
$new_comment = (isset($_POST['comment'])) ? trim($_POST['comment']) : ''; $new_comment = (isset($_POST['comment'])) ? trim($_POST['comment']) : '';
$new_title = (isset($_POST['title'])) ? trim($_POST['title']) : ''; $new_title = $originalTitle;
if ($new_comment || $new_title) { if ($new_comment || $new_title) {
$tbl_doc = Database :: get_course_table(TABLE_DOCUMENT); $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
@ -6009,8 +6037,9 @@ class learnpath
if ($new_title) if ($new_title)
$ct .= ", title='" . Database::escape_string(htmlspecialchars($new_title, ENT_QUOTES, $charset))."' "; $ct .= ", title='" . Database::escape_string(htmlspecialchars($new_title, ENT_QUOTES, $charset))."' ";
$sql_update = "UPDATE " . $tbl_doc ." SET " . substr($ct, 1)." WHERE c_id = ".$course_id." AND id = " . $document_id; $sql = "UPDATE " . $tbl_doc ." SET " . substr($ct, 1)."
Database::query($sql_update); WHERE c_id = ".$course_id." AND id = " . $document_id;
Database::query($sql);
} }
} }
return $document_id; return $document_id;
@ -6251,6 +6280,7 @@ class learnpath
// Get all the docs. // Get all the docs.
$documents = $this->get_documents(true); $documents = $this->get_documents(true);
// Get all the exercises. // Get all the exercises.
$exercises = $this->get_exercises(); $exercises = $this->get_exercises();
@ -8551,7 +8581,7 @@ class learnpath
$return .= '<li class="lp_resource_element">'; $return .= '<li class="lp_resource_element">';
$return .= '<img alt="" src="../img/new_test_small.gif" style="margin-right:5px;" title="" />'; $return .= '<img alt="" src="../img/new_test_small.gif" style="margin-right:5px;" title="" />';
$return .= '<a href="' . api_get_path(REL_CODE_PATH) . 'exercice/exercise_admin.php?'.api_get_cidreq().'&lp_id=' . $this->lp_id . '">' . $return .= '<a href="' . api_get_path(REL_CODE_PATH) . 'exercice/exercise_admin.php?'.api_get_cidreq().'&lp_id=' . $this->lp_id . '">' .
get_lang('NewExercise') . '</a>'; get_lang('NewExercise') . '</a>';
$return .= '</li>'; $return .= '</li>';
// Display hotpotatoes // Display hotpotatoes
@ -8624,7 +8654,7 @@ class learnpath
} }
$linksHtmlCode = $linksHtmlCode =
'<script> '<script>
function toggle_tool(tool, id){ function toggle_tool(tool, id){
if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){ if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
document.getElementById(tool+"_"+id+"_content").style.display = "block"; document.getElementById(tool+"_"+id+"_content").style.display = "block";
@ -8639,28 +8669,28 @@ class learnpath
<li class="lp_resource_element"> <li class="lp_resource_element">
<img alt="" src="../img/linksnew.gif" style="margin-right:5px;width:16px"/> <img alt="" src="../img/linksnew.gif" style="margin-right:5px;width:16px"/>
<a href="'.api_get_path(REL_CODE_PATH).'link/link.php?'.$courseIdReq. <a href="'.api_get_path(REL_CODE_PATH).'link/link.php?'.$courseIdReq.
'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.get_lang('LinkAdd').'</a> '&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.get_lang('LinkAdd').'</a>
</li>'; </li>';
foreach ($categorizedLinks as $categoryId => $links) { foreach ($categorizedLinks as $categoryId => $links) {
$linkNodes = null; $linkNodes = null;
foreach ($links as $key => $title) { foreach ($links as $key => $title) {
if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) { if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
$linkNodes .= $linkNodes .=
'<li class="lp_resource_element" data_id="'.$key. '<li class="lp_resource_element" data_id="'.$key.
'" data_type="'.TOOL_LINK.'" title="'.$title.'" > '" data_type="'.TOOL_LINK.'" title="'.$title.'" >
<a class="moved" href="#">'. <a class="moved" href="#">'.
$moveEverywhereIcon. $moveEverywhereIcon.
'</a> '</a>
<img alt="" src="../img/lp_link.gif" style="margin-right:5px;width:16px"/> <img alt="" src="../img/lp_link.gif" style="margin-right:5px;width:16px"/>
<a href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='. <a href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
Security::remove_XSS($title). Security::remove_XSS($title).
'</a> '</a>
</li>'; </li>';
} }
} }
$linksHtmlCode .= $linksHtmlCode .=
'<li> '<li>
<a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')"
style="vertical-align:middle"> style="vertical-align:middle">
<img src="'.api_get_path(WEB_IMG_PATH).'add.gif" id="'.TOOL_LINK.'_'.$categoryId.'_opener" <img src="'.api_get_path(WEB_IMG_PATH).'add.gif" id="'.TOOL_LINK.'_'.$categoryId.'_opener"

@ -270,9 +270,11 @@ class scorm extends learnpath
* Import the scorm object (as a result from the parse_manifest function) into the database structure * Import the scorm object (as a result from the parse_manifest function) into the database structure
* @param string $courseCode * @param string $courseCode
* @param int $userMaxScore * @param int $userMaxScore
* @param int $sessionId
*
* @return bool Returns -1 on error * @return bool Returns -1 on error
*/ */
public function import_manifest($courseCode, $userMaxScore = 1) public function import_manifest($courseCode, $userMaxScore = 1, $sessionId = 0)
{ {
if ($this->debug > 0) { if ($this->debug > 0) {
error_log('New LP - Entered import_manifest('.$courseCode.')', 0); error_log('New LP - Entered import_manifest('.$courseCode.')', 0);
@ -285,10 +287,8 @@ class scorm extends learnpath
$new_lp_item = Database::get_course_table(TABLE_LP_ITEM); $new_lp_item = Database::get_course_table(TABLE_LP_ITEM);
$userMaxScore = intval($userMaxScore); $userMaxScore = intval($userMaxScore);
$sessionId = empty($sessionId) ? api_get_session_id() : intval($sessionId);
foreach ($this->organizations as $id => $dummy) { foreach ($this->organizations as $id => $dummy) {
$is_session = api_get_session_id();
$is_session != 0 ? $session_id = $is_session : $session_id = 0;
$oOrganization = & $this->organizations[$id]; $oOrganization = & $this->organizations[$id];
// Prepare and execute insert queries: // Prepare and execute insert queries:
// -for learnpath // -for learnpath
@ -305,7 +305,7 @@ class scorm extends learnpath
$myname = api_utf8_decode($myname); $myname = api_utf8_decode($myname);
$sql = "INSERT INTO $new_lp (c_id, lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib,display_order, session_id, use_max_score)" . $sql = "INSERT INTO $new_lp (c_id, lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib,display_order, session_id, use_max_score)" .
"VALUES ($courseId , 2,'".$myname."', '".$oOrganization->get_ref()."','','".$this->subdir."', 0, 'embedded', '".$this->manifest_encoding."', 'scorm_api.php', $dsp, $session_id, $userMaxScore)"; "VALUES ($courseId , 2,'".$myname."', '".$oOrganization->get_ref()."','','".$this->subdir."', 0, 'embedded', '".$this->manifest_encoding."', 'scorm_api.php', $dsp, $sessionId, $userMaxScore)";
if ($this->debug > 1) { error_log('New LP - In import_manifest(), inserting path: '. $sql, 0); } if ($this->debug > 1) { error_log('New LP - In import_manifest(), inserting path: '. $sql, 0); }
Database::query($sql); Database::query($sql);
@ -501,16 +501,21 @@ class scorm extends learnpath
/** /**
* Imports a zip file into the Chamilo structure * Imports a zip file into the Chamilo structure
* @param string $zip_file_info Zip file info as given by $_FILES['userFile'] * @param string $zip_file_info Zip file info as given by $_FILES['userFile']
* @param string
* @param array
*
* @return string $current_dir Absolute path to the imsmanifest.xml file or empty string on error * @return string $current_dir Absolute path to the imsmanifest.xml file or empty string on error
*/ */
public function import_package($zip_file_info, $current_dir = '') public function import_package($zip_file_info, $current_dir = '', $courseInfo = array())
{ {
if ($this->debug > 0) { if ($this->debug > 0) {
error_log('In scorm::import_package('.print_r($zip_file_info,true).',"'.$current_dir.'") method', 0); error_log('In scorm::import_package('.print_r($zip_file_info,true).',"'.$current_dir.'") method', 0);
} }
$maxFilledSpace = DocumentManager :: get_course_quota(); $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
$maxFilledSpace = DocumentManager :: get_course_quota($courseInfo['code']);
$zip_file_path = $zip_file_info['tmp_name']; $zip_file_path = $zip_file_info['tmp_name'];
$zip_file_name = $zip_file_info['name']; $zip_file_name = $zip_file_info['name'];
@ -518,9 +523,10 @@ class scorm extends learnpath
if ($this->debug > 1) { if ($this->debug > 1) {
error_log('New LP - import_package() - zip file path = ' . $zip_file_path . ', zip file name = ' . $zip_file_name, 0); error_log('New LP - import_package() - zip file path = ' . $zip_file_path . ', zip file name = ' . $zip_file_name, 0);
} }
$course_rel_dir = api_get_course_path().'/scorm'; // scorm dir web path starting from /courses
$course_rel_dir = api_get_course_path($courseInfo['code']).'/scorm'; // scorm dir web path starting from /courses
$course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; // Absolute system path for this course. $course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; // Absolute system path for this course.
$current_dir = api_replace_dangerous_char(trim($current_dir)); // Current dir we are in, inside scorm/ $current_dir = api_replace_dangerous_char(trim($current_dir)); // Current dir we are in, inside scorm/
if ($this->debug > 1) { if ($this->debug > 1) {
error_log( 'New LP - import_package() - current_dir = ' . $current_dir, 0); error_log( 'New LP - import_package() - current_dir = ' . $current_dir, 0);
@ -695,11 +701,12 @@ class scorm extends learnpath
/** /**
* Sets the proximity setting in the database * Sets the proximity setting in the database
* @param string $proxy Proximity setting * @param string Proximity setting
* @param int $courseId
*/ */
public function set_proximity($proxy = '') public function set_proximity($proxy = '', $courseId = null)
{ {
$courseId = api_get_course_int_id(); $courseId = empty($courseId) ? api_get_course_int_id() : intval($courseId);
if ($this->debug > 0) { error_log('In scorm::set_proximity('.$proxy.') method', 0); } if ($this->debug > 0) { error_log('In scorm::set_proximity('.$proxy.') method', 0); }
$lp = $this->get_id(); $lp = $this->get_id();
if ($lp != 0) { if ($lp != 0) {
@ -772,11 +779,11 @@ class scorm extends learnpath
/** /**
* Sets the content maker setting in the database * Sets the content maker setting in the database
* @param string $maker * @param string Proximity setting
*/ */
public function set_maker($maker = '') public function set_maker($maker = '', $courseId = null)
{ {
$courseId = api_get_course_int_id(); $courseId = empty($courseId) ? api_get_course_int_id() : intval($courseId);
if ($this->debug > 0) { error_log('In scorm::set_maker method('.$maker.')', 0); } if ($this->debug > 0) { error_log('In scorm::set_maker method('.$maker.')', 0); }
$lp = $this->get_id(); $lp = $this->get_id();
if ($lp != 0) { if ($lp != 0) {

@ -647,7 +647,7 @@ function get_user_data($from, $number_of_items, $column, $direction)
if (api_is_allowed_to_edit(null, true)) { if (api_is_allowed_to_edit(null, true)) {
$userInfo = api_get_user_info($user_id); $userInfo = api_get_user_info($user_id);
$photo = '<img src="'.$userInfo['avatar_small'].'" alt="'.$userInfo['complete_name'].'" title="'.$userInfo['complete_name'].'" />'; $photo = Display::img($userInfo['avatar_small'], $userInfo['complete_name'], [], false);
$temp[] = $user_id; $temp[] = $user_id;
$temp[] = $photo; $temp[] = $photo;

@ -0,0 +1,633 @@
<?php
/* For licensing terms, see /license.txt */
/**
* @package chamilo.webservices
*/
require_once '../inc/global.inc.php';
$libpath = api_get_path(LIBRARY_PATH);
require_once $libpath.'nusoap/nusoap.php';
require_once $libpath.'fileManage.lib.php';
require_once $libpath.'fileUpload.lib.php';
require_once api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php';
require_once $libpath.'add_course.lib.inc.php';
$debug = true;
define('WS_ERROR_SECRET_KEY', 1);
function return_error($code) {
$fault = null;
switch ($code) {
case WS_ERROR_SECRET_KEY:
$fault = new soap_fault('Server', '', 'Secret key is not correct or params are not correctly set');
break;
}
return $fault;
}
function WSHelperVerifyKey($params)
{
global $_configuration, $debug;
if (is_array($params)) {
$secret_key = $params['secret_key'];
} else {
$secret_key = $params;
}
//error_log(print_r($params,1));
$check_ip = false;
$ip_matches = false;
$ip = trim($_SERVER['REMOTE_ADDR']);
// if we are behind a reverse proxy, assume it will send the
// HTTP_X_FORWARDED_FOR header and use this IP instead
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
list($ip1, $ip2) = split(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$ip = trim($ip1);
}
if ($debug)
error_log("ip: $ip");
// Check if a file that limits access from webservices exists and contains
// the restraining check
if (is_file('webservice-auth-ip.conf.php')) {
include 'webservice-auth-ip.conf.php';
if ($debug)
error_log("webservice-auth-ip.conf.php file included");
if (!empty($ws_auth_ip)) {
$check_ip = true;
$ip_matches = api_check_ip_in_range($ip, $ws_auth_ip);
if ($debug)
error_log("ip_matches: $ip_matches");
}
}
if ($debug) {
error_log("checkip " . intval($check_ip));
}
if ($check_ip) {
$security_key = $_configuration['security_key'];
} else {
$security_key = $ip.$_configuration['security_key'];
//error_log($secret_key.'-'.$security_key);
}
$result = api_is_valid_secret_key($secret_key, $security_key);
//error_log($secret_key.'-'.$security_key);
if ($debug)
error_log('WSHelperVerifyKey result: '.intval($result));
return $result;
}
// Create the server instance
$server = new soap_server();
//$server->soap_defencoding = 'UTF-8';
// Initialize WSDL support
$server->configureWSDL('WSLP', 'urn:WSLP');
$server->wsdl->addComplexType(
'params',
'complexType',
'struct',
'all',
'',
array(
'course_id_name' => array(
'name' => 'course_id_name',
'type' => 'xsd:string',
),
'course_id_value' => array(
'name' => 'course_id_name',
'type' => 'xsd:string',
),
'session_id_name' => array(
'name' => 'session_id_name',
'type' => 'xsd:string',
),
'session_id_value' => array(
'name' => 'session_id_value',
'type' => 'xsd:string',
),
'file_data' => array('name' => 'file', 'type' => 'xsd:string'),
'filename' => array('name' => 'filename', 'type' => 'xsd:string'),
'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string'),
)
);
// Register the method to expose
$server->register('WSImportLP', // method name
array('params' => 'tns:params'), // input parameters
array('return' => 'xsd:string'), // output parameters
'urn:WSLP', // namespace
'urn:WSLP#WSImportLP', // soapaction
'rpc', // style
'encoded', // use
'This service adds users' // documentation
);
/**
* @param array $params
* @return int|string
*/
function WSImportLP($params)
{
global $debug;
if (!WSHelperVerifyKey($params)) {
return return_error(WS_ERROR_SECRET_KEY);
}
if ($debug) error_log('WSImportLP');
$courseIdName = $params['course_id_name'];
$courseIdValue = $params['course_id_value'];
$sessionIdName = isset($params['session_id_name']) ? $params['session_id_name'] : null;
$sessionIdValue = isset($params['session_id_value']) ? $params['session_id_value'] : null;
$courseCode = CourseManager::get_course_id_from_original_id(
$courseIdValue,
$courseIdName
);
$courseInfo = api_get_course_info($courseCode);
$courseId = $courseInfo['real_id'];
if (empty($courseInfo)) {
if ($debug) error_log('Course not found');
return 'Course not found';
}
$sessionId = 0;
if (!empty($sessionIdName) && !empty($sessionIdValue)) {
$sessionId = SessionManager::get_session_id_from_original_id(
$sessionIdValue,
$sessionIdName
);
if (empty($sessionId)) {
if ($debug) error_log('Session not found');
return 'Session not found';
}
}
$proximity = 'local';
$maker = 'Scorm';
$maxScore = ''; //$_REQUEST['use_max_score']
$oScorm = new scorm();
$fileData = base64_decode($params['file_data']);
$uniqueFile = uniqid();
$filePath = api_get_path(SYS_ARCHIVE_PATH) . $uniqueFile;
file_put_contents($filePath, $fileData);
$fileName = $params['filename'];
$fileInfo = array(
'tmp_name' => $filePath,
'name' => $fileName
);
$manifest = $oScorm->import_package($fileInfo, '', $courseInfo);
if (!$manifest) {
if ($debug) error_log('manifest.xml file not found');
//if api_set_failure
return 'manifest.xml file not found';
}
$manifestData = $oScorm->parse_manifest($manifest);
if (!empty($manifestData)) {
$oScorm->import_manifest(
$courseInfo['code'],
$maxScore,
$sessionId
);
$oScorm->set_proximity($proximity, $courseId);
$oScorm->set_maker($maker, $courseId);
//$oScorm->set_jslib('scorm_api.php');
return 1;
} else {
if ($debug) error_log('manifest data empty');
return 'manifest data empty';
}
}
$server->wsdl->addComplexType(
'paramsGetLpList',
'complexType',
'struct',
'all',
'',
array(
'course_id_name' => array(
'name' => 'course_id_name',
'type' => 'xsd:string',
),
'course_id_value' => array(
'name' => 'course_id_name',
'type' => 'xsd:string',
),
'session_id_name' => array(
'name' => 'session_id_name',
'type' => 'xsd:string',
),
'session_id_value' => array(
'name' => 'session_id_value',
'type' => 'xsd:string',
),
'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string'),
)
);
$server->wsdl->addComplexType(
'lpListItem',
'complexType',
'struct',
'all',
'',
array(
'id' => array('name' => 'id', 'type' => 'xsd:string'),
'name' => array('name' => 'name', 'type' => 'xsd:string'),
)
);
$server->wsdl->addComplexType(
'lpList',
'complexType',
'array',
'',
'SOAP-ENC:Array',
array(),
array(array('ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:lpListItem[]')),
'tns:lpListItem'
);
// Register the method to expose
$server->register('WSGetLpList', // method name
array('params' => 'tns:paramsGetLpList'), // input parameters
array('return' => 'tns:lpList'), // output parameters
'urn:WSLP', // namespace
'urn:WSLP#WSGetLpList', // soapaction
'rpc', // style
'encoded', // use
'This service adds users' // documentation
);
/**
* @param array $params
* @return int|string
*/
function WSGetLpList($params)
{
global $debug;
if (!WSHelperVerifyKey($params)) {
return return_error(WS_ERROR_SECRET_KEY);
}
require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathItem.class.php';
$courseIdName = $params['course_id_name'];
$courseIdValue = $params['course_id_value'];
$sessionIdName = isset($params['session_id_name']) ? $params['session_id_name'] : null;
$sessionIdValue = isset($params['session_id_value']) ? $params['session_id_value'] : null;
$courseCode = CourseManager::get_course_id_from_original_id(
$courseIdValue,
$courseIdName
);
$courseInfo = api_get_course_info($courseCode);
//$courseId = $courseInfo['real_id'];
if (empty($courseInfo)) {
if ($debug) error_log("Course not found: $courseIdName : $courseIdValue");
return 'Course not found';
}
$sessionId = 0;
if (!empty($sessionIdName) && !empty($sessionIdValue)) {
$sessionId = SessionManager::get_session_id_from_original_id(
$sessionIdValue,
$sessionIdName
);
if (empty($sessionId)) {
if ($debug) error_log('Session not found');
return 'Session not found';
}
}
$list = new LearnpathList(null, $courseInfo['code'], $sessionId);
$flatList = $list->get_flat_list();
$result = array();
foreach ($flatList as $id => $lp) {
$result[] = array(
'id' => $id,
'name' => $lp['lp_name']
);
}
return $result;
}
$server->wsdl->addComplexType(
'paramsDeleteLp',
'complexType',
'struct',
'all',
'',
array(
'course_id_name' => array(
'name' => 'course_id_name',
'type' => 'xsd:string',
),
'course_id_value' => array(
'name' => 'course_id_name',
'type' => 'xsd:string',
),
'lp_id' => array(
'name' => 'lp_id',
'type' => 'xsd:string',
),
'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string'),
)
);
// Register the method to expose
$server->register('WSDeleteLp', // method name
array('params' => 'tns:paramsDeleteLp'), // input parameters
array('return' => 'xsd:string'), // output parameters
'urn:WSLP', // namespace
'urn:WSLP#WSDeleteLp', // soapaction
'rpc', // style
'encoded', // use
'This service deletes a LP' // documentation
);
/**
* @param array $params
* @return int|string
*/
function WSDeleteLp($params)
{
global $debug;
if (!WSHelperVerifyKey($params)) {
return return_error(WS_ERROR_SECRET_KEY);
}
require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathItem.class.php';
$courseIdName = $params['course_id_name'];
$courseIdValue = $params['course_id_value'];
$lpId = $params['lp_id'];
$sessionIdName = isset($params['session_id_name']) ? $params['session_id_name'] : null;
$sessionIdValue = isset($params['session_id_value']) ? $params['session_id_value'] : null;
$courseCode = CourseManager::get_course_id_from_original_id(
$courseIdValue,
$courseIdName
);
$courseInfo = api_get_course_info($courseCode);
//$courseId = $courseInfo['real_id'];
if (empty($courseInfo)) {
if ($debug) error_log("Course not found: $courseIdName : $courseIdValue");
return 'Course not found';
}
/*$sessionId = 0;
if (!empty($sessionIdName) && !empty($sessionIdValue)) {
$sessionId = SessionManager::get_session_id_from_original_id(
$sessionIdValue,
$sessionIdName
);
if (empty($sessionId)) {
if ($debug) error_log('Session not found');
return 'Session not found';
}
}
*/
$lp = new learnpath($courseInfo['code'], $lpId, null);
if ($lp) {
if ($debug) error_log("LP deleted $lpId");
$lp->delete($courseInfo, $lpId, 'remove');
return 1;
}
return 0;
}
$server->wsdl->addComplexType(
'lpItem',
'complexType',
'struct',
'all',
'',
array(
'data' => array('name' => 'data', 'type' => 'xsd:string'),
'title' => array('name' => 'title', 'type' => 'xsd:string'),
'filename' => array('name' => 'filename', 'type' => 'xsd:string'),
)
);
$server->wsdl->addComplexType(
'lpItemList',
'complexType',
'array',
'',
'SOAP-ENC:Array',
array(),
array(array('ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:lpItem[]')),
'tns:lpItemList'
);
$server->wsdl->addComplexType(
'paramsCreateLp',
'complexType',
'struct',
'all',
'',
array(
'course_id_name' => array(
'name' => 'course_id_name',
'type' => 'xsd:string',
),
'course_id_value' => array(
'name' => 'course_id_name',
'type' => 'xsd:string',
),
/*'session_id_name' => array(
'name' => 'session_id_name',
'type' => 'xsd:string',
),
'session_id_value' => array(
'name' => 'session_id_value',
'type' => 'xsd:string',
),*/
'lp_name' => array(
'name' => 'lp_name',
'type' => 'xsd:string',
),
'lp_item_list' => array(
'name' => 'lp_item_list',
'type' => 'tns:lpItemList',
),
'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string'),
)
);
// Register the method to expose
$server->register('WSCreateLp', // method name
array('params' => 'tns:paramsCreateLp'), // input parameters
array('return' => 'xsd:string'), // output parameters
'urn:WSLP', // namespace
'urn:WSLP#WSCreateLp', // soapaction
'rpc', // style
'encoded', // use
'This service creates a LP' // documentation
);
/**
* @param array $params
* @return null|soap_fault
*/
function WSCreateLp($params)
{
global $debug;
if (!WSHelperVerifyKey($params)) {
return return_error(WS_ERROR_SECRET_KEY);
}
if ($debug) {
error_log('WSCreateLp');
}
$courseIdName = $params['course_id_name'];
$courseIdValue = $params['course_id_value'];
$lpName = $params['lp_name'];
$lpItemList = $params['lp_item_list'];
/*$sessionIdName = isset($params['session_id_name']) ? $params['session_id_name'] : null;
$sessionIdValue = isset($params['session_id_value']) ? $params['session_id_value'] : null;*/
$courseCode = CourseManager::get_course_id_from_original_id(
$courseIdValue,
$courseIdName
);
$courseInfo = api_get_course_info($courseCode);
$courseId = $courseInfo['real_id'];
if (empty($courseInfo)) {
if ($debug) {
error_log('Course not found');
}
}
/*$sessionId = 0;
if (!empty($sessionIdName) && !empty($sessionIdValue)) {
$sessionId = SessionManager::get_session_id_from_original_id(
$sessionIdValue,
$sessionIdName
);
if (empty($sessionId)) {
if ($debug) {
error_log('Session not found');
}
return 'Session not found';
}
}*/
$lpId = learnpath::add_lp($courseCode, $lpName, '', 'chamilo', 'manual');
if ($lpId) {
if ($debug) {
error_log('LP created');
}
$lp = new learnpath($courseCode, $lpId, null);
$previousId = 0;
foreach ($lpItemList as $lpItem) {
$info = pathinfo($lpItem['filename']);
$extension = $info['extension'];
$data = base64_decode($lpItem['data']);
$documentId = $lp->create_document(
$courseInfo,
$data,
$info['filename'],
$extension
);
if ($documentId) {
if ($debug) {
error_log("Document created $documentId");
$itemId = $lp->add_item(
null,
$previousId,
'document',
$documentId,
$lpItem['title'],
'',
''
);
$previousId = $itemId;
if ($itemId) {
if ($debug) {
error_log("Item added");
}
} else {
if ($debug) {
error_log("Item not added");
}
}
}
} else {
if ($debug) {
error_log("Document NOT created");
}
}
}
return 1;
} else {
if ($debug) {
error_log('LP not created');
}
}
return 0;
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
// If you send your data in utf8 then this value must be false.
if (isset($_configuration['registration.soap.php.decode_utf8'])) {
if ($_configuration['registration.soap.php.decode_utf8']) {
$server->decode_utf8 = true;
} else {
$server->decode_utf8 = false;
}
}
$server->service($HTTP_RAW_POST_DATA);
Loading…
Cancel
Save