Lp: Fix php errors, use resources, entities

pull/3733/head
Julio Montoya 5 years ago
parent 212aa3e1bd
commit fb311176cb
  1. 113
      public/main/forum/forumfunction.inc.php
  2. 6
      public/main/inc/ajax/lp.ajax.php
  3. 4
      public/main/inc/lib/add_course.lib.inc.php
  4. 6
      public/main/inc/lib/document.lib.php
  5. 2
      public/main/inc/lib/webservices/Rest.php
  6. 17
      public/main/lp/learnpath.class.php
  7. 29
      public/main/lp/learnpathItem.class.php
  8. 12
      public/main/lp/lp_add_audio.php
  9. 98
      public/main/lp/lp_controller.php
  10. 104
      src/CoreBundle/Resources/views/LearnPath/record_voice.html.twig
  11. 2
      src/CourseBundle/Entity/CForumForum.php

@ -638,6 +638,8 @@ function editForumCategoryForm(CForumCategory $category)
* @param array $values
* @param array $courseInfo
* @param bool $showMessage
*
* @return CForumCategory
*/
function store_forumcategory($values, $courseInfo = [], $showMessage = true)
{
@ -657,6 +659,7 @@ function store_forumcategory($values, $courseInfo = [], $showMessage = true)
$last_id = null;
$repo = Container::getForumCategoryRepository();
$message = '';
if (isset($values['forum_category_id'])) {
/** @var CForumCategory $category */
$category = $repo->find($values['forum_category_id']);
@ -664,7 +667,7 @@ function store_forumcategory($values, $courseInfo = [], $showMessage = true)
->setCatComment(isset($values['forum_category_comment']) ? $values['forum_category_comment'] : '')
->setCatTitle($values['forum_category_title'])
;
$repo->updateResource($category);
$repo->update($category);
$message = get_lang('The forum category has been modified');
$logInfo = [
@ -717,7 +720,7 @@ function store_forumcategory($values, $courseInfo = [], $showMessage = true)
Display::addFlash(Display::return_message($message, 'confirmation'));
}
return $last_id;
return $category;
}
/**
@ -1722,7 +1725,7 @@ function get_threads($forumId, $courseId = null, $sessionId = null)
return $qb->getQuery()->getResult();
$groupId = api_get_group_id();
/*$groupId = api_get_group_id();
$sessionId = null !== $sessionId ? (int) $sessionId : api_get_session_id();
$table_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
$table_threads = Database::get_course_table(TABLE_FORUM_THREAD);
@ -1776,7 +1779,7 @@ function get_threads($forumId, $courseId = null, $sessionId = null)
item_properties.*,
users.firstname,
users.lastname,
users.user_id,
users.id as user_id,
thread.locked as locked,
thread.*
FROM $table_threads thread
@ -1806,7 +1809,7 @@ function get_threads($forumId, $courseId = null, $sessionId = null)
$alreadyAdded[] = $row['thread_id'];
}
return $list;
return $list;*/
}
/**
@ -2346,34 +2349,19 @@ function updateThread($values)
Display::addFlash(Display::return_message($message, 'confirmation', false));
}
/**
* This function stores a new thread. This is done through an entry in the forum_thread table AND
* in the forum_post table because. The threads are also stored in the item_property table. (forum posts are not (yet)).
*
* @param bool $showMessage
* @param int $userId Optional. The user ID
* @param int $sessionId
*
* @return CForumThread
*
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
*
* @version february 2006, dokeos 1.8
*/
function store_thread(
function saveThread(
CForumForum $forum,
array $values,
array $courseInfo = [],
$showMessage = true,
$userId = 0,
$sessionId = 0
) {
): ?CForumThread {
$courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
$userId = $userId ?: api_get_user_id();
$course_id = $courseInfo['real_id'];
$courseCode = $courseInfo['code'];
$sessionId = $sessionId ?: api_get_session_id();
$table_threads = Database::get_course_table(TABLE_FORUM_THREAD);
$post_date = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
@ -2393,23 +2381,17 @@ function store_thread(
->setCId($course_id)
->setThreadTitle($clean_post_title)
->setForum($forum)
->setThreadPosterId($userId)
->setThreadPosterName(isset($values['poster_name']) ? $values['poster_name'] : null)
->setUser($user)
->setThreadDate($post_date)
->setThreadSticky(isset($values['thread_sticky']) ? $values['thread_sticky'] : 0)
->setThreadTitleQualify(
isset($values['calification_notebook_title']) ? $values['calification_notebook_title'] : null
)
->setThreadQualifyMax(isset($values['numeric_calification']) ? (int) $values['numeric_calification'] : 0)
->setThreadSticky($values['thread_sticky'] ?? 0)
->setThreadTitleQualify($values['calification_notebook_title'] ?? '')
->setThreadQualifyMax($values['numeric_calification'] ?? 0)
->setThreadWeight(isset($values['weight_calification']) ? (int) $values['weight_calification'] : 0)
->setThreadPeerQualify(isset($values['thread_peer_qualify']) ? (bool) $values['thread_peer_qualify'] : false)
->setSessionId($sessionId)
->setLpItemId(isset($values['lp_item_id']) ? (int) $values['lp_item_id'] : 0)
->setParent($forum)
->addCourseLink(
$course,
$session
)
->addCourseLink($course, $session)
;
$repo = Container::getForumThreadRepository();
@ -2498,17 +2480,14 @@ function store_thread(
->setPostText($values['post_text'])
->setThread($thread)
->setForum($forum)
->setPosterId($userId)
->setPosterName(isset($values['poster_name']) ? $values['poster_name'] : null)
->setUser(api_get_user_entity($userId))
//->setPosterName(isset($values['poster_name']) ? $values['poster_name'] : null)
->setPostDate($post_date)
->setPostNotification(isset($values['post_notification']) ? (int) $values['post_notification'] : null)
->setVisible($visible)
->setStatus(CForumPost::STATUS_VALIDATED)
->setParent($thread)
->addCourseLink(
$course,
$session
)
->addCourseLink($course, $session)
;
if ($forum->isModerated()) {
@ -2561,12 +2540,15 @@ function store_thread(
!api_is_allowed_to_edit(null, true)
) {
$message .= get_lang('Your message has to be approved before people can view it.').'<br />';
$message .= get_lang('You can now return to the').' <a href="viewforum.php?'.api_get_cidreq().'&forum='.$values['forum_id'].'">'.
$message .= get_lang('You can now return to the').
' <a href="viewforum.php?'.api_get_cidreq().'&forum='.$values['forum_id'].'">'.
get_lang('Forum').'</a><br />';
} else {
$message .= get_lang('You can now return to the').' <a href="viewforum.php?'.api_get_cidreq().'&forum='.$values['forum_id'].'">'.
$message .= get_lang('You can now return to the').
' <a href="viewforum.php?'.api_get_cidreq().'&forum='.$values['forum_id'].'">'.
get_lang('Forum').'</a><br />';
$message .= get_lang('You can now return to the').' <a href="viewthread.php?'.api_get_cidreq().'&forum='.$values['forum_id'].'&thread='.$thread->getIid().'">'.
$message .= get_lang('You can now return to the').
' <a href="viewthread.php?'.api_get_cidreq().'&forum='.$values['forum_id'].'&thread='.$thread->getIid().'">'.
get_lang('Message').'</a>';
}
$reply_info['new_post_id'] = $postId;
@ -2754,11 +2736,7 @@ function show_add_post_form(CForumForum $forum, CForumThread $thread, CForumPost
// we are quoting or replying to a message (<> reply to a thread !!!)
$form->addHidden('post_parent_id', $post->getIid());
// If we are replying or are quoting then we display a default title.
$posterInfo = api_get_user_info($post->getPosterId());
$posterName = '';
if ($posterInfo) {
$posterName = $posterInfo['complete_name'];
}
$posterName = UserManager::formatUserFullName($post->getUser());
$defaults['post_title'] = get_lang('Re:').api_html_entity_decode($post->getPostTitle(), ENT_QUOTES);
// When we are quoting a message then we have to put that message into the wysiwyg editor.
// Note: The style has to be hardcoded here because using class="quote" didn't work.
@ -3065,7 +3043,7 @@ function newThread(CForumForum $forum, $form_values = '', $showPreview = true)
return false;
}
$newThread = store_thread($forum, $values);
$newThread = saveThread($forum, $values);
if ($newThread) {
Skill::saveSkills($form, ITEM_TYPE_FORUM_THREAD, $newThread->getIid());
$postId = $newThread->getThreadLastPost();
@ -3453,16 +3431,14 @@ function store_reply(CForumForum $forum, CForumThread $thread, $values, $courseI
->setPostText(isset($values['post_text']) ?: null)
->setThread($thread)
->setForum($forum)
->setPosterId($userId)
->setUser(api_get_user_entity($userId))
->setPostNotification(isset($values['post_notification']) ? $values['post_notification'] : null)
->setPostParentId(isset($values['post_parent_id']) ? $values['post_parent_id'] : null)
->setVisible($visible)
->setPostDate(api_get_utc_datetime(null, false, true))
->setParent($thread)
->addCourseLink(
$course,
$session
);
->addCourseLink($course, $session)
;
$repo = Container::getForumPostRepository();
$repo->create($post);
@ -4121,7 +4097,7 @@ function handle_mail_cue($content, $id)
}
} elseif ('thread' === $content) {
// Sending the mail to all the users that wanted to be informed for replies on this thread.
$sql = "SELECT users.firstname, users.lastname, users.user_id, users.email, posts.forum_id
$sql = "SELECT users.firstname, users.lastname, users.id as user_id, users.email, posts.forum_id
FROM $table_mailcue mailcue, $table_posts posts, $table_users users
WHERE
posts.c_id = $course_id AND
@ -4129,7 +4105,7 @@ function handle_mail_cue($content, $id)
posts.thread_id = $id AND
posts.post_notification = '1' AND
mailcue.thread_id = $id AND
users.user_id = posts.poster_id AND
users.id = posts.poster_id AND
users.active = 1
GROUP BY users.email";
$result = Database::query($sql);
@ -4492,7 +4468,7 @@ function store_move_thread($values)
// Change the thread table: Setting the forum_id to the new forum.
$sql = "UPDATE $table_threads SET forum_id = $forumId
WHERE c_id = $courseId AND thread_id = $threadId";
WHERE c_id = $courseId AND iid = $threadId";
Database::query($sql);
// Changing all the posts of the thread: setting the forum_id to the new forum.
@ -5557,7 +5533,7 @@ function get_thread_user_post($course_code, $thread_id, $user_id)
}
$sql = "SELECT * FROM $table_posts posts
LEFT JOIN $table_users users
ON posts.poster_id=users.user_id
ON posts.poster_id=users.id
WHERE
posts.c_id = $course_id AND
posts.thread_id='$thread_id'
@ -5571,7 +5547,7 @@ function get_thread_user_post($course_code, $thread_id, $user_id)
$post_list[] = $row;
$sql = "SELECT * FROM $table_posts posts
LEFT JOIN $table_users users
ON (posts.poster_id=users.user_id)
ON (posts.poster_id=users.id)
WHERE
posts.c_id = $course_id AND
posts.thread_id='$thread_id'
@ -5603,7 +5579,7 @@ function get_name_thread_by_id($thread_id)
$course_id = api_get_course_int_id();
$sql = "SELECT thread_title
FROM $t_forum_thread
WHERE c_id = $course_id AND thread_id = '".(int) $thread_id."' ";
WHERE c_id = $course_id AND iid = '".(int) $thread_id."' ";
$result = Database::query($sql);
$row = Database::fetch_array($result);
@ -5710,7 +5686,7 @@ function get_thread_user_post_limit($courseId, $thread_id, $user_id, $limit = 10
$sql = "SELECT * FROM $table_posts posts
LEFT JOIN $table_users users
ON posts.poster_id=users.user_id
ON posts.poster_id=users.id
WHERE
posts.c_id = $courseId AND
posts.thread_id='".Database::escape_string($thread_id)."' AND
@ -6125,7 +6101,18 @@ function getAttachmentIdsByPostId($postId, $courseId = 0)
*/
function getForumCategoryByTitle($title, $courseId, $sessionId = 0)
{
$sessionId = (int) $sessionId;
$repo = Container::getForumCategoryRepository();
$course = api_get_course_entity($courseId);
$session = api_get_session_entity($sessionId);
return $repo->findResourceByTitle(
$title,
$course->getResourceNode(),
$course,
$session
);
/*$sessionId = (int) $sessionId;
$courseId = (int) $courseId;
$forumCategoryTable = Database::get_course_table(TABLE_FORUM_CATEGORY);
$itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
@ -6166,7 +6153,7 @@ function getForumCategoryByTitle($title, $courseId, $sessionId = 0)
return false;
}
return $resultData;
return $resultData;*/
}
/**
@ -6305,7 +6292,7 @@ function savePostRevision(CForumPost $post)
{
$userId = api_get_user_id();
if ($post->getPosterId() != $userId) {
if ($post->getUser()->getId() != $userId) {
return false;
}

@ -219,7 +219,7 @@ switch ($action) {
);
if (empty($forumCategory)) {
$forumCategoryId = store_forumcategory(
$forumCategory = store_forumcategory(
[
'lp_id' => 0,
'forum_category_title' => get_lang('Learning paths'),
@ -228,11 +228,9 @@ switch ($action) {
[],
false
);
} else {
$forumCategoryId = $forumCategory['cat_id'];
}
$forumId = $learningPath->createForum($forumCategoryId);
$forumId = $learningPath->createForum($forumCategory);
} else {
$forumId = $forum['forum_id'];
}

@ -563,7 +563,7 @@ class AddCourse
'thread_peer_qualify' => 0,
];
store_thread($forumEntity, $params, $courseInfo, false);
saveThread($forumEntity, $params, $courseInfo, false);
/* Gradebook tool */
$course_code = $courseInfo['code'];
@ -572,7 +572,7 @@ class AddCourse
"INSERT INTO $TABLEGRADEBOOK (name, locked, generate_certificates, description, user_id, c_id, parent_id, weight, visible, certif_min_score, session_id, document_id)
VALUES ('$course_code','0',0,'',1,$course_id,0,100,0,75,NULL,$certificateId)"
);
$gbid = Database:: insert_id();
$gbid = Database::insert_id();
Database::query(
"INSERT INTO $TABLEGRADEBOOK (name, locked, generate_certificates, description, user_id, c_id, parent_id, weight, visible, certif_min_score, session_id, document_id)
VALUES ('$course_code','0',0,'',1,$course_id,$gbid,100,1,75,NULL,$certificateId)"

@ -4138,7 +4138,7 @@ class DocumentManager
/**
* @param array $_course
*
* @return int
* @return CDocument
*/
public static function createDefaultAudioFolder($_course)
{
@ -4146,7 +4146,7 @@ class DocumentManager
return false;
}
self::addDocument($_course, '/audio', 'folder', 0, 'Audio');
return self::addDocument($_course, '/audio', 'folder', 0, 'Audio');
}
/**
@ -6238,7 +6238,7 @@ This folder contains all sessions that have been opened in the chat. Although th
}
}
$document = $documentRepo->findOneByTitle(
$document = $documentRepo->findResourceByTitle(
$title,
$parentResource->getResourceNode(),
$courseEntity,

@ -1136,7 +1136,7 @@ class Rest extends WebService
$sessionId = $this->session ? $this->session->getId() : 0;
$forum = get_forums($forumId, $this->course->getCode(), true, $sessionId);
$courseInfo = api_get_course_info($this->course->getCode());
$thread = store_thread($forum, $values, $courseInfo, false, $this->user->getId(), $sessionId);
$thread = saveThread($forum, $values, $courseInfo, false, $this->user->getId(), $sessionId);
return [
'registered' => $thread->getIid(),

@ -9,6 +9,7 @@ use Chamilo\CourseBundle\Component\CourseCopy\CourseArchiver;
use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
use Chamilo\CourseBundle\Entity\CDocument;
use Chamilo\CourseBundle\Entity\CForumCategory;
use Chamilo\CourseBundle\Entity\CLink;
use Chamilo\CourseBundle\Entity\CLp;
use Chamilo\CourseBundle\Entity\CLpCategory;
@ -2455,7 +2456,7 @@ class learnpath
*/
public function getProgressBar($mode = null)
{
list($percentage, $text_add) = $this->get_progress_bar_text($mode);
[$percentage, $text_add] = $this->get_progress_bar_text($mode);
return self::get_progress_bar($percentage, $text_add);
}
@ -3484,7 +3485,7 @@ class learnpath
$lp_item_params = $row['liparams'];
if (empty($lp_item_params) && false !== strpos($lp_item_path, '?')) {
list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
[$lp_item_path, $lp_item_params] = explode('?', $lp_item_path);
}
//$sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
if ('http' === $type) {
@ -3651,7 +3652,7 @@ class learnpath
if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
// if file not found.
$decoded = html_entity_decode($lp_item_path);
list($decoded) = explode('?', $decoded);
[$decoded] = explode('?', $decoded);
if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
$file = self::rl_get_resource_link_for_learnpath(
$course_id,
@ -4903,7 +4904,7 @@ class learnpath
if (!api_is_invitee()) {
// Save progress.
list($progress) = $this->get_progress_bar_text('%');
[$progress] = $this->get_progress_bar_text('%');
$scoreAsProgressSetting = api_get_configuration_value('lp_score_as_progress_enable');
$scoreAsProgress = $this->getUseScoreAsProgress();
if ($scoreAsProgress && $scoreAsProgressSetting && (null === $score || empty($score) || -1 == $score)) {
@ -7073,7 +7074,7 @@ class learnpath
}
$item_id = $lpItem->getIid();
$itemType = $lpItem->getItemType();
$lpId = $lpItem->getLpId();
$lpId = $lpItem->getLp()->getIid();
$path = $lpItem->getPath();
Session::write('parent_item_id', 'dir' === $itemType ? $item_id : 0);
@ -10820,11 +10821,9 @@ EOD;
/**
* Create a forum for this learning path.
*
* @param int $forumCategoryId
*
* @return int The forum ID if was created. Otherwise return false
*/
public function createForum($forumCategoryId)
public function createForum(CForumCategory $forumCategory)
{
require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
@ -10833,7 +10832,7 @@ EOD;
'lp_id' => $this->lp_id,
'forum_title' => $this->name,
'forum_comment' => null,
'forum_category' => (int) $forumCategoryId,
'forum_category' => $forumCategory->getIid(),
'students_can_edit_group' => ['students_can_edit' => 0],
'allow_new_threads_group' => ['allow_new_threads' => 0],
'default_view_type_group' => ['default_view_type' => 'flat'],

@ -2,6 +2,8 @@
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CourseBundle\Entity\CForumForum;
use Chamilo\CourseBundle\Entity\CForumThread;
/**
* Class learnpathItem
@ -4256,13 +4258,15 @@ class learnpathItem
* @param int $courseId The course ID from the learning path
* @param int $sessionId Optional. The session ID from the learning path
*
* @return \Chamilo\CourseBundle\Entity\CForumThread
*/
public function getForumThread($courseId, $sessionId = 0)
public function getForumThread($courseId, $sessionId = 0): ?CForumThread
{
$repo = Container::getForumThreadRepository();
$qb = $repo->getResourcesByCourse(api_get_course_entity($courseId), api_get_session_entity($sessionId));
$qb->andWhere('resource.threadTitle = :title')->setParameter('title', "{$this->title} - {$this->db_id}");
$qb
->andWhere('resource.threadTitle = :title')
->setParameter('title', "{$this->title} - {$this->db_id}")
;
return $qb->getQuery()->getFirstResult();
@ -4319,30 +4323,23 @@ class learnpathItem
/**
* Create a forum thread for this learning path item.
*
* @param int $currentForumId The forum ID to add the new thread
*
* @return int The forum thread if was created. Otherwise return false
*/
public function createForumThread($currentForumId)
public function createForumThread(CForumForum $forum)
{
require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
$currentForumId = (int) $currentForumId;
$em = Database::getManager();
$threadRepo = $em->getRepository('ChamiloCourseBundle:CForumThread');
$threadRepo = Container::getForumThreadRepository();
$forumThread = $threadRepo->findOneBy([
'threadTitle' => "{$this->title} - {$this->db_id}",
'forumId' => $currentForumId,
'forum' => $forum,
]);
if (!$forumThread) {
$repo = Container::getForumRepository();
$forumInfo = $repo->find($currentForumId);
store_thread(
$forumInfo,
if (null === $forumThread) {
saveThread(
$forum,
[
'forum_id' => $currentForumId,
'thread_id' => 0,
'gradebook' => 0,
'post_title' => "{$this->name} - {$this->db_id}",

@ -94,9 +94,9 @@ $form = new FormValidator(
$suredel = trim(get_lang('AreYouSureToDeleteJS'));
$lpPathInfo = $lp->generate_lp_folder($courseInfo);
DocumentManager::createDefaultAudioFolder($courseInfo);
$document = DocumentManager::createDefaultAudioFolder($courseInfo);
$currentDir = '/audio';
$audioFolderId = DocumentManager::get_document_id($courseInfo, $currentDir);
$audioFolderId = $document->getIid();
if (isset($_REQUEST['folder_id'])) {
$folderIdFromRequest = isset($_REQUEST['folder_id']) ? (int) $_REQUEST['folder_id'] : 0;
@ -112,7 +112,7 @@ if (isset($_REQUEST['folder_id'])) {
$file = null;
if (!empty($lp_item->audio)) {
$file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$lp_item->audio;
//$file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$lp_item->audio;
$urlFile = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/'.$lp_item->audio.'?'.api_get_cidreq();
}
@ -145,8 +145,7 @@ $tpl->assign('enable_record_audio', 'true' === api_get_setting('enable_record_au
$tpl->assign('cur_dir_path', '/audio');
$tpl->assign('lp_item_id', $lp_item_id);
$tpl->assign('lp_dir', api_remove_trailing_slash($lpPathInfo['dir']));
$template = $tpl->get_template('learnpath/record_voice.tpl');
$recordVoiceForm .= $tpl->fetch($template);
$recordVoiceForm .= $tpl->fetch('@ChamiloCore/LearnPath/record_voice.html.twig');
$form->addElement('header', '<small class="text-muted">'.get_lang('Or').'</small> '.get_lang('AudioFile'));
$audioLabel = '';
@ -161,7 +160,8 @@ if (!empty($file)) {
Display::getMediaPlayer($file, ['url' => $urlFile]).
"</div>";
$form->addElement('label', get_lang('Listen'), $audioPlayer);
$url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?lp_id='.$lp->get_id().'&action=add_audio&id='.$lp_item_id.'&delete_file=1&'.api_get_cidreq();
$url = api_get_path(WEB_CODE_PATH).
'lp/lp_controller.php?lp_id='.$lp->get_id().'&action=add_audio&id='.$lp_item_id.'&delete_file=1&'.api_get_cidreq();
$form->addElement(
'label',
null,

@ -2,6 +2,7 @@
/* For licensing terms, see /license.txt */
use Chamilo\CourseBundle\Entity\CLpItem;
use ChamiloSession as Session;
/**
@ -266,7 +267,6 @@ $htmlHeadXtra[] = '
</script>';
$session_id = api_get_session_id();
$lpfound = false;
$myrefresh = 0;
$myrefresh_id = 0;
@ -315,6 +315,12 @@ if (!empty($lpObject)) {
}
$course_id = api_get_course_int_id();
$lpItemId = $_REQUEST['id'] ?? 0;
$lpItem = null;
if (!empty($lpItemId)) {
$lpItemRepo = Database::getManager()->getRepository(CLpItem::class);
$lpItem = $lpItemRepo->find($lpItemId);
}
if (!$lp_found || (!empty($_REQUEST['lp_id']) && $_SESSION['oLP']->get_id() != $_REQUEST['lp_id'])) {
if ($debug > 0) {
@ -650,7 +656,8 @@ switch ($action) {
$lp_item_obj->removeAudio();
Display::addFlash(Display::return_message(get_lang('FileDeleted')));
$url = api_get_self().'?action=add_audio&lp_id='.intval($_SESSION['oLP']->lp_id).'&id='.$lp_item_obj->get_id().'&'.api_get_cidreq();
$url = api_get_self().
'?action=add_audio&lp_id='.intval($_SESSION['oLP']->lp_id).'&id='.$lp_item_obj->get_id().'&'.api_get_cidreq();
header('Location: '.$url);
exit;
}
@ -658,14 +665,14 @@ switch ($action) {
// Upload audio
if (isset($_FILES['file']) && !empty($_FILES['file'])) {
// Updating the lp.modified_on
$_SESSION['oLP']->set_modified_on();
$oLP->set_modified_on();
$lp_item_obj->addAudio();
Display::addFlash(Display::return_message(get_lang('UplUploadSucceeded')));
}
//Add audio file from documents
if (isset($_REQUEST['document_id']) && !empty($_REQUEST['document_id'])) {
$_SESSION['oLP']->set_modified_on();
$oLP->set_modified_on();
$lp_item_obj->add_audio_from_documents($_REQUEST['document_id']);
Display::addFlash(Display::return_message(get_lang('Updated')));
}
@ -771,7 +778,7 @@ switch ($action) {
$subscribeUsers = isset($_REQUEST['subscribe_users']) ? 1 : 0;
$_SESSION['oLP']->setSubscribeUsers($subscribeUsers);
$accumulateScormTime = isset($_REQUEST['accumulate_scorm_time']) ? $_REQUEST['accumulate_scorm_time'] : 'true';
$accumulateScormTime = $_REQUEST['accumulate_scorm_time'] ?? 'true';
$_SESSION['oLP']->setAccumulateScormTime($accumulateScormTime);
$url = api_get_self().'?action=add_item&type=step&lp_id='.intval($new_lp_id).'&'.api_get_cidreq();
@ -1364,13 +1371,13 @@ switch ($action) {
case 'mode':
// Switch between fullscreen and embedded mode.
$mode = $_REQUEST['mode'];
if ('fullscreen' == $mode) {
if ('fullscreen' === $mode) {
$_SESSION['oLP']->mode = 'fullscreen';
} elseif ('embedded' == $mode) {
} elseif ('embedded' === $mode) {
$_SESSION['oLP']->mode = 'embedded';
} elseif ('embedframe' == $mode) {
} elseif ('embedframe' === $mode) {
$_SESSION['oLP']->mode = 'embedframe';
} elseif ('impress' == $mode) {
} elseif ('impress' === $mode) {
$_SESSION['oLP']->mode = 'impress';
}
require 'lp_view.php';
@ -1423,10 +1430,6 @@ switch ($action) {
} else {
$_SESSION['oLP']->save_current();
$_SESSION['oLP']->save_last();
if ($debug > 0) {
error_log('save_current()');
error_log('save_last()');
}
$url = $_course['course_public_url'].'?sid='.api_get_session_id();
$redirectTo = isset($_GET['redirectTo']) ? $_GET['redirectTo'] : '';
switch ($redirectTo) {
@ -1494,31 +1497,27 @@ switch ($action) {
}
$selectedItem = null;
foreach ($_SESSION['oLP']->items as $item) {
/** @var learnpathItem $selectedItem */
foreach ($oLP->items as $item) {
if ($item->db_id == $_GET['id']) {
$selectedItem = $item;
}
}
if (!empty($selectedItem)) {
$forumThread = $selectedItem->getForumThread(
$_SESSION['oLP']->course_int_id,
$_SESSION['oLP']->lp_session_id
);
$forumThread = $selectedItem->getForumThread($oLP->course_int_id, $oLP->lp_session_id);
if (empty($forumThread)) {
require '../forum/forumfunction.inc.php';
require_once '../forum/forumfunction.inc.php';
$forumCategory = getForumCategoryByTitle(
get_lang('Learning paths'),
$_SESSION['oLP']->course_int_id,
$_SESSION['oLP']->lp_session_id
$oLP->course_int_id,
$oLP->lp_session_id
);
$forumCategoryId = !empty($forumCategory) ? $forumCategory['cat_id'] : 0;
if (empty($forumCategoryId)) {
$forumCategoryId = store_forumcategory(
if (null === $forumCategory) {
$forumCategory = store_forumcategory(
[
'lp_id' => 0,
'forum_category_title' => get_lang('Learning paths'),
@ -1529,29 +1528,22 @@ switch ($action) {
);
}
if (!empty($forumCategoryId)) {
$forum = $_SESSION['oLP']->getForum(
$_SESSION['oLP']->lp_session_id
);
$forumId = !empty($forum) ? $forum['forum_id'] : 0;
if (empty($forumId)) {
$forumId = $_SESSION['oLP']->createForum($forumCategoryId);
}
if (!empty($forumId)) {
$selectedItem->createForumThread($forumId);
if ($forumCategory) {
$forum = $oLP->getEntity()->getForum();
if ($forum) {
$selectedItem->createForumThread($forum);
} else {
$oLP->createForum($forumCategory);
}
}
}
}
header('Location:'.api_get_self().'?'.http_build_query([
'action' => 'add_item',
'type' => 'step',
'lp_id' => $_SESSION['oLP']->lp_id,
]));
'action' => 'add_item',
'type' => 'step',
'lp_id' => $oLP->lp_id,
]));
exit;
break;
@ -1564,7 +1556,7 @@ switch ($action) {
}
$selectedItem = null;
foreach ($_SESSION['oLP']->items as $item) {
foreach ($oLP->items as $item) {
if ($item->db_id != $_GET['id']) {
continue;
}
@ -1573,8 +1565,8 @@ switch ($action) {
if (!empty($selectedItem)) {
$forumThread = $selectedItem->getForumThread(
$_SESSION['oLP']->course_int_id,
$_SESSION['oLP']->lp_session_id
$oLP->course_int_id,
$oLP->lp_session_id
);
if (!empty($forumThread)) {
@ -1589,10 +1581,10 @@ switch ($action) {
}
header('Location:'.api_get_self().'?'.http_build_query([
'action' => 'add_item',
'type' => 'step',
'lp_id' => $_SESSION['oLP']->lp_id,
]));
'action' => 'add_item',
'type' => 'step',
'lp_id' => $_SESSION['oLP']->lp_id,
]));
exit;
break;
case 'add_final_item':
@ -1610,10 +1602,10 @@ switch ($action) {
$_SESSION['oLP']->getFinalItemForm();
$redirectTo = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
'action' => 'add_item',
'type' => 'step',
'lp_id' => intval($_SESSION['oLP']->lp_id),
]);
'action' => 'add_item',
'type' => 'step',
'lp_id' => $oLP->lp_id,
]);
break;
default:
require 'lp_list.php';

@ -2,7 +2,23 @@
<p>
<span class="fa fa-microphone fa-5x fa-fw" aria-hidden="true"></span>
<span class="sr-only">{{ 'RecordAudio'|trans }}</span>
<div id="timer" style="display: none">
<h2>
<div class="label label-danger">
<span id="hour">00</span>
<span class="divider">:</span>
<span id="minute">00</span>
<span class="divider">:</span>
<span id="second">00</span>
</div>
</h2>
<br />
</div>
<div class="form-group">
<input type="text" name="audio_title" id="audio-title-rtc" class="form-control" placeholder="{{ 'InputNameHere'|trans }}" />
</div>
</p>
<button class="btn btn-primary" type="button" id="btn-start-record">
<span class="fa fa-circle fa-fw" aria-hidden="true"></span> {{ 'StartRecordingAudio'|trans }}
</button>
@ -14,30 +30,70 @@
<div id="record-audio-wami" class="wami-container"></div>
<script>
$(function () {
$(function() {
var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
function startTimer() {
$("#timer").show();
var timerData = {
hour: parseInt($("#hour").text()),
minute: parseInt($("#minute").text()),
second: parseInt($("#second").text())
};
clearInterval(window.timerInterval);
window.timerInterval = setInterval(function(){
// Seconds
timerData.second++;
if (timerData.second >= 60) {
timerData.second = 0;
timerData.minute++;
}
// Minutes
if (timerData.minute >= 60) {
timerData.minute = 0;
timerData.hour++;
}
$("#hour").text(timerData.hour < 10 ? '0' + timerData.hour : timerData.hour);
$("#minute").text(timerData.minute < 10 ? '0' + timerData.minute : timerData.minute);
$("#second").text(timerData.second < 10 ? '0' + timerData.second : timerData.second);
}, 1000);
}
function stopTimer() {
$("#hour").text('00');
$("#minute").text('00');
$("#second").text('00');
$("#timer").hide();
}
function pauseTimer() {
clearInterval(window.timerInterval);
}
function useRecordRTC(){
$('#record-audio-recordrtc').show();
var audioTitle = $('#audio-title-rtc');
var mediaConstraints = {audio: true},
recordRTC = null,
btnStart = $('#btn-start-record'),
btnStop = $('#btn-stop-record');
btnStart.on('click', function () {
navigator.getUserMedia = navigator.getUserMedia ||
navigator.mozGetUserMedia ||
navigator.webkitGetUserMedia;
if ('' === audioTitle.val()) {
alert('{{ 'TitleIsRequired'|trans | escape }} ');
if (navigator.getUserMedia) {
navigator.getUserMedia(mediaConstraints, successCallback, errorCallback);
} else if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then(successCallback).error(errorCallback);
return false;
}
function successCallback(stream) {
stopTimer();
startTimer();
recordRTC = RecordRTC(stream, {
numberOfAudioChannels: 1,
recorderType: isSafari ? RecordRTC.StereoAudioRecorder : RecordRTC.MediaStreamRecorder,
type: 'audio'
});
recordRTC.startRecording();
@ -47,8 +103,19 @@
}
function errorCallback(error) {
alert(error.message);
stopTimer();
alert(error);
}
if(!!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia)) {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
navigator.getUserMedia(mediaConstraints, successCallback, errorCallback);
return;
}
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then(successCallback)
.catch(errorCallback);
});
btnStop.on('click', function () {
@ -56,6 +123,7 @@
return;
}
stopTimer();
recordRTC.stopRecording(function (audioURL) {
var recordedBlob = recordRTC.getBlob(),
fileName = Math.round(Math.random() * 99999999) + 99999999,
@ -64,9 +132,10 @@
var formData = new FormData();
formData.append('audio-filename', fileName + fileExtension);
formData.append('audio-blob', recordedBlob, 'audio' + fileExtension);
formData.append('audio-title', audioTitle.val());
$.ajax({
url: '{{ _p.web_ajax }}lp.ajax.php?a=record_audio&lp_item_id={{ lp_item_id }}',
url: '{{ url('legacy_main', {name: 'inc/ajax/lp.ajax.php'}) ~ "?" ~ course_url_params ~ "&a=record_audio&lp_item_id="~ lp_item_id }}',
data: formData,
processData: false,
contentType: false,
@ -93,14 +162,14 @@
var gui = new Wami.GUI({
id : 'record-audio-wami',
singleButton : true,
recordUrl : '{{ _p.web_ajax }}record_audio_wami.ajax.php?' + $.param({
recordUrl : '{{ url('legacy_main', {name: 'inc/ajax/record_audio_wami.ajax.php'}) }}?' + $.param({
waminame: 'rec_' + (new Date()).getTime() + '.wav',
wamidir: '{{ cur_dir_path }}',
wamiuserid: {{ _u.user_id }},
wamiuserid: {{ app.user.id }},
lp_item_id: {{ lp_item_id }}
}),
buttonUrl : '{{ _p.web_lib }}wami-recorder/buttons.png',
buttonNoUrl: '{{ _p.web_img }}blank.gif',
buttonUrl : 'wami-recorder/buttons.png',
buttonNoUrl: 'blank.gif',
onRecordFinish: function() {
$('#start-recording').hide();
window.location.reload();
@ -113,12 +182,11 @@
Wami.setup({
id : "record-audio-wami",
onReady : setupGUI,
swfUrl: '{{ _p.web_lib }}wami-recorder/Wami.swf'
swfUrl: '{{ url('legacy_main', {name: 'inc/lib/wami-recorder/Wami.swf'}) }}'
});
}
$('#record-audio-recordrtc, #record-audio-wami').hide();
var webRTCIsEnabled = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia ||
navigator.mediaDevices.getUserMedia;

@ -189,7 +189,7 @@ class CForumForum extends AbstractResource implements ResourceInterface
/**
* @ORM\OneToOne(targetEntity="Chamilo\CourseBundle\Entity\CLp", inversedBy="forum")
* @ORM\JoinColumn(name="lp_id", referencedColumnName="iid")
* @ORM\JoinColumn(name="lp_id", referencedColumnName="iid", nullable=true)
*/
protected $lp;

Loading…
Cancel
Save