Adding course icon editions see BT#7204

1.10.x
Julio Montoya 12 years ago
parent def293c680
commit ea4a6dbfd6
  1. 103
      main/course_home/activity.php
  2. 222
      main/course_home/course_home.php
  3. 571
      main/inc/Entity/CTool.php
  4. 8
      main/inc/Entity/Course.php
  5. 170
      main/inc/ajax/course_home.ajax.php
  6. 16
      main/inc/lib/api.lib.php
  7. 113
      main/inc/lib/course_home.lib.php
  8. 35
      main/inc/lib/display.lib.php
  9. 57
      main/inc/routes.php
  10. 32
      main/inc/services.php
  11. 9
      main/template/default/layout/footer.tpl
  12. 97
      main/template/default/tool/course_home/index.tpl
  13. 7
      main/template/default/tool/course_home/tool/edit.tpl
  14. 34
      main/template/default/tool/course_home/tool/list.tpl
  15. 13
      src/ChamiloLMS/Component/DataFilesystem/DataFilesystem.php
  16. 5
      src/ChamiloLMS/Controller/BaseController.php
  17. 125
      src/ChamiloLMS/Controller/CourseHomeController.php
  18. 18
      src/ChamiloLMS/Controller/IndexController.php
  19. 469
      src/ChamiloLMS/Controller/Tool/CourseHome/CourseHomeController.php
  20. 61
      src/ChamiloLMS/Controller/Tool/Introduction/IntroductionController.php
  21. 48
      src/ChamiloLMS/Form/CourseHomeToolType.php

@ -12,113 +12,54 @@
*
* @package chamilo.course_home
*/
$id = isset($_GET['id']) ? intval($_GET['id']) : null;
$course_id = api_get_course_int_id();
$session_id = api_get_session_id();
// MAIN CODE
if (api_is_allowed_to_edit(null, true)) {
// HIDE
if (!empty($_GET['hide'])) {
$sql = "UPDATE $tool_table SET visibility=0 WHERE c_id = $course_id AND id=".$id;
Database::query($sql);
$show_message = Display::return_message(get_lang('ToolIsNowHidden'), 'confirmation');
} elseif (!empty($_GET['restore'])) {
// visibility 0,2 -> 1
// REACTIVATE
$sql = "UPDATE $tool_table SET visibility=1 WHERE c_id = $course_id AND id=".$id;
Database::query($sql);
}
function return_block($title, $content)
{
$html = '<div class="page-header">
<h3>'.$title.'</h3>
</div>
'.$content.'</div>';
return $html;
}
// Work with data post askable by admin of course
if (api_is_platform_admin()) {
// Show message to confirm that a tool it to be hidden from available tools
// visibility 0,1->2
if (!empty($_GET['askDelete'])) {
$content .='<div id="toolhide">'.get_lang('DelLk').'<br />&nbsp;&nbsp;&nbsp;
<a href="'.api_get_self().'">'.get_lang('No').'</a>&nbsp;|&nbsp;
<a href="'.api_get_self().'?delete=yes&id='.$id.'">'.get_lang('Yes').'</a>
</div>';
} elseif (isset($_GET['delete']) && $_GET['delete']) {
/*
* Process hiding a tools from available tools.
*/
//where $id is set?
$id = intval($id);
Database::query("DELETE FROM $tool_table WHERE c_id = $course_id AND id='$id' AND added_tool=1");
}
}
$session_id = api_get_session_id();
global $app;
$urlGenerator = $app['url_generator'];
// COURSE ADMIN ONLY VIEW
$content = null;
// Start of tools for CourseAdmins (teachers/tutors)
if ($session_id == 0 && api_is_course_admin() && api_is_allowed_to_edit(null, true)) {
$content .= '<div class="courseadminview" style="border:0px; margin-top: 0px;padding:0px;">
<div class="normal-message" id="id_normal_message" style="display:none">';
$content .= '<img src="'.api_get_path(WEB_PATH).'main/inc/lib/javascript/indicator.gif"/>&nbsp;&nbsp;';
$content .= get_lang('PleaseStandBy');
$content .= '</div>
<div class="confirmation-message" id="id_confirmation_message" style="display:none"></div>
</div>';
if (api_get_setting('show_session_data') == 'true' && $session_id > 0) {
$content .= '<div class="courseadminview">
<span class="viewcaption">'.get_lang('SessionData').'</span>
<table class="course_activity_home">'.CourseHome::show_session_data($session_id).'
</table>
</div>';
}
$my_list = CourseHome::get_tools_category(TOOL_AUTHORING);
$items = CourseHome::show_tools_category($my_list);
$content .= return_block(get_lang('Authoring'), $items);
$items = CourseHome::show_tools_category($urlGenerator, $my_list);
$content .= return_block(get_lang('Authoring'), $items);
$my_list = CourseHome::get_tools_category(TOOL_INTERACTION);
$list2 = CourseHome::get_tools_category(TOOL_COURSE_PLUGIN);
$my_list = array_merge($my_list,$list2);
$items = CourseHome::show_tools_category($my_list);
$my_list = array_merge($my_list, $list2);
$items = CourseHome::show_tools_category($urlGenerator, $my_list);
$content .= return_block(get_lang('Interaction'), $items);
$content .= return_block(get_lang('Interaction'), $items);
$my_list = CourseHome::get_tools_category(TOOL_ADMIN_PLATFORM);
$items = CourseHome::show_tools_category($my_list);
$items = CourseHome::show_tools_category($urlGenerator, $my_list);
$content .= return_block(get_lang('Administration'), $items);
$content .= return_block(get_lang('Administration'), $items);
} elseif (api_is_coach()) {
if (api_get_setting('show_session_data') == 'true' && $session_id > 0) {
$content .= '<div class="row">
<span class="viewcaption">'.get_lang('SessionData').'</span>
<table class="course_activity_home">';
$content .= CourseHome::show_session_data($session_id);
$content .= '</table></div>';
}
$content .= '<div class="row">';
$my_list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
$content .= CourseHome::show_tools_category($my_list);
$my_list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
$content .= CourseHome::show_tools_category($urlGenerator, $my_list);
$content .= '</div>';
} else {
$my_list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
if (count($my_list) > 0) {
$content .= '<div class="row">';
$content .= CourseHome::show_tools_category($my_list);
$content .= CourseHome::show_tools_category($urlGenerator, $my_list);
$content .= '</div>';
}
}
function return_block($title, $content)
{
$html = '<div class="page-header">
<h3>'.$title.'</h3>
</div>
'.$content.'</div>';
return $html;
}
return $content;

@ -1,14 +1,8 @@
<?php
/* For licensing terms, see /license.txt */
/**
HOME PAGE FOR EACH COURSE
* HOME PAGE FOR EACH COURSE
*
* This page, included in every course's index.php is the home
* page. To make administration simple, the teacher edits his
* course from the home page. Only the login detects that the
* visitor is allowed to activate, deactivate home page links,
* access to the teachers tools (statistics, edit forums...).
*
* Edit visibility of tools
*
@ -28,56 +22,7 @@
* @package chamilo.course_home
*/
/* INIT SECTION */
use \ChamiloSession as Session;
// Name of the language file that needs to be included.
$language_file = array('course_home','courses');
$use_anonymous = true;
// Including the global initialization file.
require_once dirname(__FILE__).'/../inc/global.inc.php';
// Delete LP sessions - commented out after seeing that normal
// users in their first learnpath step (1st SCO of a SCORM)
// cannot have their data saved if they "Return to course homepage"
// before any LMSFinish()
//unset($_SESSION['oLP']);
//unset($_SESSION['lpobject']);
// The section for the tabs
$this_section = SECTION_COURSES;
/* Constants */
define('TOOL_PUBLIC', 'Public');
define('TOOL_PUBLIC_BUT_HIDDEN', 'PublicButHide');
define('TOOL_COURSE_ADMIN', 'courseAdmin');
define('TOOL_PLATFORM_ADMIN', 'platformAdmin');
define('TOOL_AUTHORING', 'toolauthoring');
define('TOOL_INTERACTION', 'toolinteraction');
define('TOOL_COURSE_PLUGIN', 'toolcourseplugin'); //all plugins that can be enabled in courses
define('TOOL_ADMIN', 'tooladmin');
define('TOOL_ADMIN_PLATFORM', 'tooladminplatform');
define('TOOL_STUDENT_VIEW', 'toolstudentview');
define('TOOL_ADMIN_VISIBLE', 'tooladminvisible');
$user_id = api_get_user_id();
$show_message = '';
//Deleting group session
Session::erase('toolgroup');
Session::erase('_gid');
$is_specialcourse = CourseManager::is_special_course($course_code);
if ($is_specialcourse) {
$autoreg = isset($_GET['autoreg']) ? Security::remove_XSS($_GET['autoreg']) : null;
if ($autoreg == 1) {
CourseManager::subscribe_user($user_id, $course_code, $status = STUDENT);
}
}
/*
if (isset($_GET['action']) && $_GET['action'] == 'subscribe') {
if (Security::check_token('get')) {
Security::clear_token();
@ -87,171 +32,16 @@ if (isset($_GET['action']) && $_GET['action'] == 'subscribe') {
$show_message .= Display::return_message(get_lang($msg));
}
}
}
}*/
/* Is the user allowed here? */
api_protect_course_script(true);
//api_protect_course_script(true);
/* STATISTICS */
/*
if (!isset($coursesAlreadyVisited[$course_code])) {
event_access_course();
$coursesAlreadyVisited[$course_code] = 1;
Session::write('coursesAlreadyVisited', $coursesAlreadyVisited);
}
$show_autolaunch_exercise_warning = false;
// Exercise auto-launch
$auto_launch = api_get_course_setting('enable_exercise_auto_launch');
if (!empty($auto_launch)) {
$session_id = api_get_session_id();
//Exercise list
if ($auto_launch == 2) {
if (api_is_platform_admin() || api_is_allowed_to_edit()) {
$show_autolaunch_exercise_warning = true;
} else {
$session_key = 'exercise_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
if (!isset($_SESSION[$session_key])) {
//redirecting to the Exercise
$url = api_get_path(WEB_CODE_PATH).'exercice/exercice.php?'.api_get_cidreq().'&id_session='.$session_id;
$_SESSION[$session_key] = true;
header("Location: $url");
exit;
}
}
} else {
$table = Database::get_course_table(TABLE_QUIZ_TEST);
$course_id = api_get_course_int_id();
$condition = '';
if (!empty($session_id)) {
$condition = api_get_session_condition($session_id);
$sql = "SELECT iid FROM $table WHERE c_id = $course_id AND autolaunch = 1 $condition LIMIT 1";
$result = Database::query($sql);
//If we found nothing in the session we just called the session_id = 0 autolaunch
if (Database::num_rows($result) == 0) {
$condition = '';
} else {
//great, there is an specific auto lunch for this session we leave the $condition
}
}
$sql = "SELECT iid FROM $table WHERE c_id = $course_id AND autolaunch = 1 $condition LIMIT 1";
$result = Database::query($sql);
if (Database::num_rows($result) > 0) {
$data = Database::fetch_array($result,'ASSOC');
if (!empty($data['iid'])) {
if (api_is_platform_admin() || api_is_allowed_to_edit()) {
$show_autolaunch_exercise_warning = true;
} else {
$session_key = 'exercise_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
if (!isset($_SESSION[$session_key])) {
//redirecting to the LP
$url = api_get_path(WEB_CODE_PATH).'exercice/overview.php?'.api_get_cidreq().'&exerciseId='.$data['iid'];
$_SESSION[$session_key] = true;
header("Location: $url");
exit;
}
}
}
}
}
}
/* Auto launch code */
$show_autolaunch_lp_warning = false;
$auto_launch = api_get_course_setting('enable_lp_auto_launch');
if (!empty($auto_launch)) {
$session_id = api_get_session_id();
//LP list
if ($auto_launch == 2) {
if (api_is_platform_admin() || api_is_allowed_to_edit()) {
$show_autolaunch_lp_warning = true;
} else {
$session_key = 'lp_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
if (!isset($_SESSION[$session_key])) {
//redirecting to the LP
$url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?'.api_get_cidreq().'&id_session='.$session_id;
$_SESSION[$session_key] = true;
header("Location: $url");
exit;
}
}
} else {
$lp_table = Database::get_course_table(TABLE_LP_MAIN);
$course_id = api_get_course_int_id();
$condition = '';
if (!empty($session_id)) {
$condition = api_get_session_condition($session_id);
$sql = "SELECT id FROM $lp_table WHERE c_id = $course_id AND autolunch = 1 $condition LIMIT 1";
$result = Database::query($sql);
//If we found nothing in the session we just called the session_id = 0 autolunch
if (Database::num_rows($result) == 0) {
$condition = '';
} else {
//great, there is an specific auto lunch for this session we leave the $condition
}
}
$sql = "SELECT id FROM $lp_table WHERE c_id = $course_id AND autolunch = 1 $condition LIMIT 1";
$result = Database::query($sql);
if (Database::num_rows($result) > 0) {
$lp_data = Database::fetch_array($result,'ASSOC');
if (!empty($lp_data['id'])) {
if (api_is_platform_admin() || api_is_allowed_to_edit()) {
$show_autolaunch_lp_warning = true;
} else {
$session_key = 'lp_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
if (!isset($_SESSION[$session_key])) {
//redirecting to the LP
$url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['id'];
$_SESSION[$session_key] = true;
header("Location: $url");
exit;
}
}
}
}
}
}
$tool_table = Database::get_course_table(TABLE_TOOL_LIST);
$temps = time();
$reqdate = "&reqdate=$temps";
/* MAIN CODE */
/* Introduction section (editable by course admins) */
$content = Display::return_introduction_section(TOOL_COURSE_HOMEPAGE, array(
'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
'CreateDocumentDir' => 'document/',
'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/'
));
/* SWITCH TO A DIFFERENT HOMEPAGE VIEW
the setting homepage_view is adjustable through
the platform administration section */
if ($show_autolaunch_lp_warning) {
$show_message .= Display::return_message(get_lang('TheLPAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificLP'),'warning');
}
if ($show_autolaunch_exercise_warning) {
$show_message .= Display::return_message(get_lang('TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise'),'warning');
}
if (api_get_setting('homepage_view') == 'activity' || api_get_setting('homepage_view') == 'activity_big') {
require 'activity.php';
} elseif (api_get_setting('homepage_view') == '2column') {
require '2column.php';
} elseif (api_get_setting('homepage_view') == '3column') {
require '3column.php';
} elseif (api_get_setting('homepage_view') == 'vertical_activity') {
require 'vertical_activity.php';
}
$content = '<div id="course_tools">'.$content.'</div>';
Session::erase('_gid');
}*/
return array('content' => $content, 'message' => $show_message);

@ -0,0 +1,571 @@
<?php
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* CTool
* @ORM\HasLifecycleCallbacks
* @ORM\Table(name="c_tool", indexes={@ORM\Index(name="session_id", columns={"session_id"})})
* @ORM\Entity
*/
class CTool
{
/**
* @var integer
*
* @ORM\Column(name="c_id", type="integer", precision=0, scale=0, nullable=false, unique=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="NONE")
*/
private $cId;
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", precision=0, scale=0, nullable=false, unique=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="NONE")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255, precision=0, scale=0, nullable=false, unique=false)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="link", type="string", length=255, precision=0, scale=0, nullable=false, unique=false)
*/
private $link;
/**
* @var string
* @ORM\Column(name="image", type="string", length=255, precision=0, scale=0, nullable=true, unique=false)
*/
private $image;
/**
* @var string
* @ORM\Column(name="custom_icon", type="string", length=255, precision=0, scale=0, nullable=true, unique=false)
*/
private $customIcon;
/**
* @var boolean
*
* @ORM\Column(name="visibility", type="boolean", precision=0, scale=0, nullable=true, unique=false)
*/
private $visibility;
/**
* @var string
*
* @ORM\Column(name="admin", type="string", length=255, precision=0, scale=0, nullable=true, unique=false)
*/
private $admin;
/**
* @var string
*
* @ORM\Column(name="address", type="string", length=255, precision=0, scale=0, nullable=true, unique=false)
*/
private $address;
/**
* @var boolean
*
* @ORM\Column(name="added_tool", type="boolean", precision=0, scale=0, nullable=true, unique=false)
*/
private $addedTool;
/**
* @var string
*
* @ORM\Column(name="target", type="string", precision=0, scale=0, nullable=false, unique=false)
*/
private $target;
/**
* @var string
*
* @ORM\Column(name="category", type="string", length=20, precision=0, scale=0, nullable=false, unique=false)
*/
private $category;
/**
* @var integer
*
* @ORM\Column(name="session_id", type="integer", precision=0, scale=0, nullable=true, unique=false)
*/
private $sessionId;
/**
* @var string
*
* @ORM\Column(name="description", type="text", precision=0, scale=0, nullable=true, unique=false)
*/
private $description;
/**
* @ORM\ManyToOne(targetEntity="Course")
* @ORM\JoinColumn(name="c_id", referencedColumnName="id")
*/
private $course;
protected $originalImage;
/**
*/
public function __construct()
{
}
/**
* @param ClassMetadata $metadata
*/
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint(
'customIcon',
new Assert\File(array('mimeTypes' => array("image/png")))
);
$metadata->addPropertyConstraint(
'customIcon',
new Assert\Image(array('maxWidth' => 64, 'minHeight' => 64))
);
$metadata->addPropertyConstraint('cId', new Assert\NotBlank());
}
/**
* @return Course
*/
public function getCourse()
{
return $this->course;
}
/**
* @return null|string
*/
public function getAbsolutePath()
{
return null === $this->getCustomIcon()
? null
: $this->getUploadRootDir().'/'.$this->getCustomIcon();
}
/**
* @return string
*/
protected function getUploadRootDir()
{
// the absolute directory path where uploaded
// documents should be saved
$dir = $this->getCourse()->getAbsoluteSysCoursePath().$this->getUploadDir();
if (is_dir($dir)) {
return $dir;
} else {
mkdir($dir);
return $dir;
}
}
/**
* @return string
*/
protected function getUploadDir()
{
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view.
return 'upload/course_home_icons';
}
/**
* Called before saving the entity
*
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->getCustomIcon()) {
// do whatever you want to generate a unique name
//$filename = sha1(uniqid(mt_rand(), true));
$this->originalImage = $this->getCustomIcon();
$this->customIcon = $this->getName().'_'.$this->getSessionId().'.'.$this->getCustomIcon()->guessExtension();
}
}
/**
* Called before entity removal
*
* @ORM\PostRemove()
*/
public function removeUpload()
{
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
/**
* Called after entity persistence
*
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
// the file property can be empty if the field is not required
if (null === $this->getCustomIcon()) {
return;
}
// use the original file name here but you should
// sanitize it at least to avoid any security issues
// move takes the target directory and then the
// target filename to move to
$this->originalImage->move(
$this->getUploadRootDir(),
$this->customIcon
);
// clean up the file property as you won't need it anymore
$this->originalImage = null;
}
/**
* Set cId
*
* @param integer $cId
* @return CTool
*/
public function setCId($cId)
{
$this->cId = $cId;
return $this;
}
/**
* Get cId
*
* @return integer
*/
public function getCId()
{
return $this->cId;
}
/**
* Set id
*
* @param integer $id
* @return CTool
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return CTool
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set link
*
* @param string $link
* @return CTool
*/
public function setLink($link)
{
$this->link = $link;
return $this;
}
/**
* Get link
*
* @return string
*/
public function getLink()
{
return $this->link;
}
/**
* Set image
*
* @param string $image
* @return CTool
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* @return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set visibility
*
* @param boolean $visibility
* @return CTool
*/
public function setVisibility($visibility)
{
$this->visibility = $visibility;
return $this;
}
/**
* Get visibility
*
* @return boolean
*/
public function getVisibility()
{
return $this->visibility;
}
/**
* Set admin
*
* @param string $admin
* @return CTool
*/
public function setAdmin($admin)
{
$this->admin = $admin;
return $this;
}
/**
* Get admin
*
* @return string
*/
public function getAdmin()
{
return $this->admin;
}
/**
* Set address
*
* @param string $address
* @return CTool
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set addedTool
*
* @param boolean $addedTool
* @return CTool
*/
public function setAddedTool($addedTool)
{
$this->addedTool = $addedTool;
return $this;
}
/**
* Get addedTool
*
* @return boolean
*/
public function getAddedTool()
{
return $this->addedTool;
}
/**
* Set target
*
* @param string $target
* @return CTool
*/
public function setTarget($target)
{
$this->target = $target;
return $this;
}
/**
* Get target
*
* @return string
*/
public function getTarget()
{
return $this->target;
}
/**
* Set category
*
* @param string $category
* @return CTool
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* @return string
*/
public function getCategory()
{
return $this->category;
}
/**
* Set sessionId
*
* @param integer $sessionId
* @return CTool
*/
public function setSessionId($sessionId)
{
$this->sessionId = $sessionId;
return $this;
}
/**
* Get sessionId
*
* @return integer
*/
public function getSessionId()
{
return $this->sessionId;
}
public function getCustomIcon()
{
return $this->customIcon;
}
public function setCustomIcon($customIcon)
{
$this->customIcon = $customIcon;
return $this;
}
public function getDescription()
{
return $this->description;
}
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* @param \Imagine\Image\ImagineInterface $imagine
* @return bool
*/
public function createGrayIcon($imagine)
{
if (empty($this->getCustomIcon())) {
return false;
}
if (file_exists($this->getAbsolutePath())) {
$image = $imagine->open($this->getAbsolutePath());
$fileInfo = pathinfo($this->getAbsolutePath());
$originalFilename = $fileInfo['basename'];
$filename = $fileInfo['filename'].'_na.'.$fileInfo['extension'];
$newPath = str_replace($originalFilename, $filename, $this->getAbsolutePath());
$transformation = new \Imagine\Filter\Advanced\Grayscale();
$transformation->apply($image)->save($newPath);
}
}
public function imageGifToPng()
{
return str_replace('.gif', '.png', $this->getImage());
}
}

@ -818,4 +818,12 @@ class Course
{
return $this->courseTypeId;
}
/**
* @return string
*/
public function getAbsoluteSysCoursePath()
{
return realpath(__DIR__.'/../../../data/courses/'.$this->getDirectory()).'/';
}
}

@ -8,95 +8,103 @@ $action = $_GET['a'];
$now = time();
switch ($action) {
case 'set_visibility':
require_once '../global.inc.php';
case 'set_visibility':
require_once '../global.inc.php';
$course_id = api_get_course_int_id();
if (api_is_allowed_to_edit(null,true)) {
$tool_table = Database::get_course_table(TABLE_TOOL_LIST);
$tool_info = api_get_tool_information($_GET["id"]);
$tool_visibility = $tool_info['visibility'];
$tool_image = $tool_info['image'];
if (api_get_setting('homepage_view') != 'activity_big') {
$new_image = Display::return_icon(str_replace('.gif','_na.gif',$tool_image), null, null, null, null, true);
$tool_image = Display::return_icon($tool_image, null, null, null, null, true);
} else {
$tool_image = $tool_info['image'];
$tool_image = (substr($tool_info['image'], 0, strpos($tool_info['image'], '.'))).'.png';
$new_image = str_replace('.png','_na.png',$tool_image);
$courseInfo = api_get_course_info();
if (api_is_allowed_to_edit(null, true)) {
$tool_table = Database::get_course_table(TABLE_TOOL_LIST);
$tool_info = api_get_tool_information($_GET["id"]);
$tool_visibility = $tool_info['visibility'];
$tool_image = $tool_info['image'];
if (api_get_setting('homepage_view') != 'activity_big') {
$new_image = Display::return_icon(str_replace('.gif','_na.gif', $tool_image), null, null, null, null, true);
$tool_image = Display::return_icon($tool_image, null, null, null, null, true);
} else {
$tool_image = $tool_info['image'];
$tool_image = (substr($tool_info['image'], 0, strpos($tool_info['image'], '.'))).'.png';
$new_image = str_replace('.png', '_na.png', $tool_image);
$new_image = api_get_path(WEB_IMG_PATH).'icons/64/'.$new_image;
$tool_image = api_get_path(WEB_IMG_PATH).'icons/64/'.$tool_image;
}
$requested_image = ($tool_visibility == 0 ) ? $tool_image : $new_image;
$requested_clase = ($tool_visibility == 0 ) ? 'visible' : 'invisible';
$requested_message = ($tool_visibility == 0 ) ? 'is_active' : 'is_inactive';
$requested_view = ($tool_visibility == 0 ) ? 'visible.gif' : 'invisible.gif';
$requested_visible = ($tool_visibility == 0 ) ? 1 : 0;
$requested_view = ($tool_visibility == 0 ) ? 'visible.gif' : 'invisible.gif';
$requested_visible = ($tool_visibility == 0 ) ? 1 : 0;
//HIDE AND REACTIVATE TOOL
if ($_GET["id"]==strval(intval($_GET["id"]))) {
/* -- session condition for visibility
if (!empty($session_id)) {
$sql = "select session_id FROM $tool_table WHERE id='".$_GET["id"]."' AND session_id = '$session_id'";
$rs = Database::query($sql);
if (Database::num_rows($rs) > 0) {
$sql="UPDATE $tool_table SET visibility=$requested_visible WHERE id='".$_GET["id"]."' AND session_id = '$session_id'";
} else {
$sql_select = "select * FROM $tool_table WHERE id='".$_GET["id"]."'";
$res_select = Database::query($sql_select);
$row_select = Database::fetch_array($res_select);
$sql = "INSERT INTO $tool_table(name,link,image,visibility,admin,address,added_tool,target,category,session_id)
VALUES('{$row_select['name']}','{$row_select['link']}','{$row_select['image']}','0','{$row_select['admin']}','{$row_select['address']}','{$row_select['added_tool']}','{$row_select['target']}','{$row_select['category']}','$session_id')";
}
} else $sql="UPDATE $tool_table SET visibility=$requested_visible WHERE id='".$_GET["id"]."'";
*/
$sql="UPDATE $tool_table SET visibility=$requested_visible WHERE c_id = $course_id AND id='".intval($_GET['id'])."'";
Database::query($sql);
}
$response_data = array(
'image' => $requested_image,
'tclass' => $requested_clase,
'message' => $requested_message,
'view' => $requested_view
);
echo json_encode($response_data);
}
break;
case 'show_course_information' :
if (!empty($tool_info['custom_icon'])) {
$tool_image = CourseHome::getCustomIconPath($courseInfo).$tool_info['custom_icon'];
$new_image = str_replace('.png', '_na.png', $tool_info['custom_icon']);
$new_image = CourseHome::getCustomIconPath($courseInfo).$new_image;
}
}
$language_file = array('course_description');
require_once '../global.inc.php';
$requested_image = ($tool_visibility == 0 ) ? $tool_image : $new_image;
$requested_clase = ($tool_visibility == 0 ) ? 'visible' : 'invisible';
$requested_message = ($tool_visibility == 0 ) ? 'is_active' : 'is_inactive';
$requested_view = ($tool_visibility == 0 ) ? 'visible.gif' : 'invisible.gif';
$requested_visible = ($tool_visibility == 0 ) ? 1 : 0;
$requested_view = ($tool_visibility == 0 ) ? 'visible.gif' : 'invisible.gif';
$requested_visible = ($tool_visibility == 0 ) ? 1 : 0;
//HIDE AND REACTIVATE TOOL
if ($_GET["id"]==strval(intval($_GET["id"]))) {
/* -- session condition for visibility
if (!empty($session_id)) {
$sql = "select session_id FROM $tool_table WHERE id='".$_GET["id"]."' AND session_id = '$session_id'";
$rs = Database::query($sql);
if (Database::num_rows($rs) > 0) {
$sql="UPDATE $tool_table SET visibility=$requested_visible WHERE id='".$_GET["id"]."' AND session_id = '$session_id'";
} else {
$sql_select = "select * FROM $tool_table WHERE id='".$_GET["id"]."'";
$res_select = Database::query($sql_select);
$row_select = Database::fetch_array($res_select);
$sql = "INSERT INTO $tool_table(name,link,image,visibility,admin,address,added_tool,target,category,session_id)
VALUES('{$row_select['name']}','{$row_select['link']}','{$row_select['image']}','0','{$row_select['admin']}','{$row_select['address']}','{$row_select['added_tool']}','{$row_select['target']}','{$row_select['category']}','$session_id')";
}
} else $sql="UPDATE $tool_table SET visibility=$requested_visible WHERE id='".$_GET["id"]."'";
*/
// Get the name of the database course.
$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
$sql = "UPDATE $tool_table SET visibility=$requested_visible
WHERE c_id = $course_id AND id='".intval($_GET['id'])."'";
Database::query($sql);
}
$response_data = array(
'image' => $requested_image,
'tclass' => $requested_clase,
'message' => $requested_message,
'view' => $requested_view
);
echo json_encode($response_data);
}
break;
case 'show_course_information':
$language_file = array('course_description');
require_once '../global.inc.php';
$course_info = api_get_course_info($_GET['code']);
// Get the name of the database course.
$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
if ($course_info['visibility'] != COURSE_VISIBILITY_OPEN_WORLD) {
if (api_is_anonymous()) {
exit;
}
}
echo Display::tag('h2', $course_info['name']);
echo '<br />';
$course_info = api_get_course_info($_GET['code']);
$sql = "SELECT * FROM $tbl_course_description WHERE c_id = ".$course_info['real_id']." AND session_id = 0 ORDER BY id";
$result = Database::query($sql);
if (Database::num_rows($result) > 0 ) {
while ($description = Database::fetch_object($result)) {
$descriptions[$description->id] = $description;
}
if ($course_info['visibility'] != COURSE_VISIBILITY_OPEN_WORLD) {
if (api_is_anonymous()) {
exit;
}
}
echo Display::tag('h2', $course_info['name']);
echo '<br />';
$sql = "SELECT * FROM $tbl_course_description WHERE c_id = ".$course_info['real_id']." AND session_id = 0 ORDER BY id";
$result = Database::query($sql);
if (Database::num_rows($result) > 0 ) {
while ($description = Database::fetch_object($result)) {
$descriptions[$description->id] = $description;
}
// Function that displays the details of the course description in html.
echo CourseManager::get_details_course_description_html($descriptions, api_get_system_encoding(), false);
} else {
echo get_lang('NoDescription');
}
break;
echo CourseManager::get_details_course_description_html($descriptions, api_get_system_encoding(), false);
} else {
echo get_lang('NoDescription');
}
break;
/**
* @todo this functions need to belong to a class or a special wrapper to process the AJAX petitions from the jqgrid
*/
@ -108,7 +116,7 @@ switch ($action) {
$limit = intval($_REQUEST['rows']); // quantity of rows
$sidx = $_REQUEST['sidx']; //index to filter
$sord = $_REQUEST['sord']; //asc or desc
if (!in_array($sord, array('asc','desc'))) {
if (!in_array($sord, array('asc', 'desc'))) {
$sord = 'desc';
}
$session_id = intval($_REQUEST['session_id']);
@ -328,7 +336,7 @@ switch ($action) {
}
}
if($count > 0 && $limit > 0) {
if ($count > 0 && $limit > 0) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;

@ -427,11 +427,25 @@ define('SOCIAL_CENTER_PLUGIN', 2);
define('SOCIAL_RIGHT_PLUGIN', 3);
define('CUT_GROUP_NAME', 50);
//Skills
// Skills
define ('SKILL_TYPE_REQUIREMENT', 'required');
define ('SKILL_TYPE_ACQUIRED', 'acquired');
define ('SKILL_TYPE_BOTH', 'both');
// Tool
define('TOOL_PUBLIC', 'Public');
define('TOOL_PUBLIC_BUT_HIDDEN', 'PublicButHide');
define('TOOL_COURSE_ADMIN', 'courseAdmin');
define('TOOL_PLATFORM_ADMIN', 'platformAdmin');
define('TOOL_AUTHORING', 'toolauthoring');
define('TOOL_INTERACTION', 'toolinteraction');
define('TOOL_COURSE_PLUGIN', 'toolcourseplugin'); //all plugins that can be enabled in courses
define('TOOL_ADMIN', 'tooladmin');
define('TOOL_ADMIN_PLATFORM', 'tooladminplatform');
define('TOOL_STUDENT_VIEW', 'toolstudentview');
define('TOOL_ADMIN_VISIBLE', 'tooladminvisible');
/* PATHS & FILES - ROUTINES */
/**

@ -3,11 +3,11 @@
class CourseHome
{
/**
* Gets the html content to show in the 3 column view
*/
public static function show_tool_3column($cat) {
public static function show_tool_3column($cat)
{
global $_user;
$TBL_ACCUEIL = Database :: get_course_table(TABLE_TOOL_LIST);
$TABLE_TOOLS = Database :: get_main_table(TABLE_MAIN_COURSE_MODULE);
@ -196,8 +196,7 @@ class CourseHome
$cell_number ++;
}
return $table->toHtml();
} // end
}
/**
* Displays the tools of a certain category.
@ -404,7 +403,6 @@ class CourseHome
* display: "toolauthoring", "toolinteraction", "tooladmin", "tooladminplatform", "toolplugin"
* @return array
*/
public static function get_tools_category($course_tool_category)
{
$course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
@ -424,7 +422,7 @@ class CourseHome
if ((api_is_coach() || api_is_course_tutor()) && $studentView != 'studentview') {
$condition_display_tools = ' WHERE (visibility = 1 AND (category = "authoring" OR category = "interaction" OR category = "plugin") OR (name = "'.TOOL_TRACKING.'") ) ';
}
$sql = "SELECT * FROM $course_tool_table $condition_display_tools AND c_id = $course_id $condition_session ORDER BY id";
$sql = "SELECT * FROM $course_tool_table $condition_display_tools AND c_id = $course_id $condition_session ORDER BY id";
$result = Database::query($sql);
$col_link ="##003399";
break;
@ -576,14 +574,16 @@ class CourseHome
/**
* Displays the tools of a certain category.
* @param Symfony\Component\Routing\RouterInterface $urlGenerator
* @param array List of tools as returned by get_tools_category()
* @param int rows
* @return void
*/
public static function show_tools_category($all_tools_list, $rows = false)
public static function show_tools_category($urlGenerator, $all_tools_list, $rows = false)
{
$rowDiv = '<div class="row">';
$theme = api_get_setting('homepage_view');
if ($theme == 'vertical_activity') {
//ordering by get_lang name
$order_tool_list = array();
@ -654,16 +654,23 @@ class CourseHome
$item['extra'] = null;
if ($is_allowed_to_edit && !api_is_coach()) {
if (empty($session_id)) {
if ($tool['visibility'] == '1' && $tool['admin'] != '1') {
$link['name'] = Display::return_icon('visible.gif', get_lang('Deactivate'), array('id' => 'linktool_'.$tool['id']), ICON_SIZE_MEDIUM, false);
$link['cmd'] = 'hide=yes';
$link['cmd'] = $urlGenerator->generate(
'course_home.controller:hideIconAction',
array('course' => api_get_course_id(), 'iconId' => $tool['id'])
);
//'hide=yes';
$lnk[] = $link;
}
if ($tool['visibility'] == '0' && $tool['admin'] != '1') {
$link['name'] = Display::return_icon('invisible.gif', get_lang('Activate'), array('id' => 'linktool_'.$tool['id']), ICON_SIZE_MEDIUM, false);
$link['cmd'] = 'restore=yes';
//$link['cmd'] = 'restore=yes';
$link['cmd'] = $urlGenerator->generate(
'course_home.controller:showIconAction',
array('course' => api_get_course_id(), 'iconId' => $tool['id'])
);
$lnk[] = $link;
}
}
@ -685,7 +692,7 @@ class CourseHome
if (isset($lnk) && is_array($lnk)) {
foreach ($lnk as $this_link) {
if (empty($tool['adminlink'])) {
$item['visibility'] .= '<a class="make_visible_and_invisible" href="'.api_get_self().'?'.api_get_cidreq().'&amp;id='.$tool['id'].'&amp;'.$this_link['cmd'].'">'.$this_link['name'].'</a>';
$item['visibility'] .= '<a class="make_visible_and_invisible" href="'.$this_link['cmd'].'">'.$this_link['name'].'</a>';
}
}
} else {
@ -693,14 +700,26 @@ class CourseHome
}
// NOTE : Table contains only the image file name, not full path
if (stripos($tool['link'], 'http://') === false && stripos($tool['link'], 'https://') === false && stripos($tool['link'], 'ftp://') === false) {
if (stripos($tool['link'], 'http://') === false &&
stripos($tool['link'], 'https://') === false &&
stripos($tool['link'], 'ftp://') === false
) {
$tool['link'] = $web_code_path.$tool['link'];
}
if (!empty($tool['custom_icon'])) {
$tool['image'] = self::getCustomIconPath($courseInfo).$tool['custom_icon'];
}
if ($tool['visibility'] == '0' && $tool['admin'] != '1') {
$class = 'invisible';
$info = pathinfo($tool['image']);
$dirName = null;
if ($info['dirname'] != '.') {
$dirName = $info['dirname'].'/';
}
$basename = basename($tool['image'], '.'.$info['extension']); // $file is set to "index"
$tool['image'] = $basename.'_na.'.$info['extension'];
$tool['image'] = $dirName.$basename.'_na.'.$info['extension'];
} else {
$class = '';
}
@ -722,34 +741,45 @@ class CourseHome
'href' => '"javascript: void(0);"',
'class' => $class,
'onclick' => 'javascript: window.open(\'' . $tool['link'] . '\',\'window_visio'.$_SESSION['_cid'].'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')',
'target' => $tool['target']);
'target' => $tool['target']
);
} elseif (strpos($tool['name'], 'chat') !== false && api_get_course_setting('allow_open_chat_window')) {
$tool_link_params = array(
'id' => 'tooldesc_'.$tool["id"],
'class' => $class,
'href' => 'javascript: void(0);',
'onclick' => 'javascript: window.open(\'' . $tool['link'] . '\',\'window_chat'.$_SESSION['_cid'].'\',config=\'height=\'+380+\', width=\'+625+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')',
'target' => $tool['target']);
'target' => $tool['target']
);
} else {
if (count(explode('type=classroom',$tool['link'])) == 2 || count(explode('type=conference', $tool['link'])) == 2) {
$tool_link_params = array(
'id' => 'tooldesc_'.$tool["id"],
'href' => $tool['link'],
'class' => $class,
'target' => '_blank');
'target' => '_blank'
);
} else {
$tool_link_params = array(
'id' => 'tooldesc_'.$tool["id"],
'href' => $tool['link'],
'class' => $class,
'target' => $tool['target']);
'target' => $tool['target']
);
}
}
$tool_name = self::translate_tool_name($tool);
$toolTip = $tool_name;
if (!empty($tool['description'])) {
$toolTip = $tool['description'];
}
$tool_link_params['data-original-title'] = $toolTip;
$tool_link_params['data-toggle'] = 'tooltip';
//$tool_link_params['title'] = $toolTip;
// Including Courses Plugins
// Creating title and the link
@ -761,7 +791,22 @@ class CourseHome
$tool_link_params['href'] = api_get_path(WEB_PLUGIN_PATH).$tool['original_link'].'?'.api_get_cidreq();
}
$icon = Display::return_icon($tool['image'], $tool_name, array('class' => 'tool-icon', 'id' => 'toolimage_'.$tool['id']), ICON_SIZE_BIG, false);
if (!empty($tool['custom_icon'])) {
$icon = Display::img(
self::getCustomIconPath($courseInfo).$tool['image'],
null,
array('class' => 'tool-icon', 'id' => 'toolimage_'.$tool['id'])
);
} else {
$icon = Display::return_icon(
$tool['image'],
null,
array('class' => 'tool-icon', 'id' => 'toolimage_'.$tool['id']),
ICON_SIZE_BIG,
false
);
}
$userInfo = api_get_user_info();
$userStatus = isset($userInfo['status']) ? $userInfo['status'] : null;
@ -791,15 +836,27 @@ class CourseHome
switch ($theme) {
case 'activity_big':
$data = '';
if ($counter == 0) {
$html .= $rowDiv;
}
$html .= '<div class="col-xs-4 col-md-4 course-tool">';
$image = (substr($item['tool']['image'], 0, strpos($item['tool']['image'], '.'))).'.png';
$original_image = Display::return_icon($image, $item['name'], array('id'=>'toolimage_'.$item['tool']['id']), ICON_SIZE_BIG, false);
if (!empty($item['tool']['custom_icon'])) {
$original_image = Display::img(
$item['tool']['image'],
null,
array('id'=>'toolimage_'.$item['tool']['id'])
);
} else {
$original_image = Display::return_icon(
$image,
null,
array('id'=>'toolimage_'.$item['tool']['id']),
ICON_SIZE_BIG,
false
);
}
switch ($image) {
case 'scormbuilder.png':
@ -1113,4 +1170,14 @@ class CourseHome
}
return $html;
}
/**
* @param array $courseInfo
* @return string
*/
public static function getCustomIconPath($courseInfo)
{
return api_get_path(WEB_DATA_COURSE_PATH).$courseInfo['directory'].'/upload/course_home_icons/';
}
}

@ -106,14 +106,20 @@ class Display
*/
public static function display_introduction_section($tool, $editor_config = null)
{
echo self::return_introduction_section($tool, $editor_config);
global $app;
$urlGenerator = $app['url_generator'];
echo self::return_introduction_section($urlGenerator, $tool, $editor_config);
}
public static function return_introduction_section($tool, $editor_config = null)
/**
* @param Symfony\Component\Routing\RouterInterface $urlGenerator
* @param string $tool
* @param array $editor_config
* @return null|string
*/
public static function return_introduction_section($urlGenerator, $tool, $editor_config = null)
{
global $charset;
$is_allowed_to_edit = api_is_allowed_to_edit();
$moduleId = $tool;
$courseInfo = api_get_course_info();
$introduction_section = null;
@ -216,7 +222,11 @@ class Display
// Displays "Add intro" commands
$introduction_section .= '<div id="introduction_block_action" class="col-md-2 col-md-offset-10">';
$url = api_get_path(WEB_PUBLIC_PATH).'introduction/edit/'.$tool;
$url = $urlGenerator->generate(
'introduction.controller:editAction',
array('tool' => $tool, 'course' => api_get_course_id())
);
$introduction_section .= "<a href=\"".$url."?".api_get_cidreq()."\">";
$introduction_section .= Display::return_icon('introduction_add.gif', get_lang('AddIntro')).' ';
$introduction_section .= "</a>";
@ -226,15 +236,19 @@ class Display
} else {
// Displays "edit intro && delete intro" commands
$introduction_section .= '<div id="introduction_block_action" class="col-md-2 col-md-offset-10">';
//$url = $app['url_generator']->generate('introduction_edit', array('tool' => $moduleId));
$url = api_get_path(WEB_PUBLIC_PATH).'introduction/edit/'.$tool;
$url = $urlGenerator->generate(
'introduction.controller:editAction',
array('tool' => $tool, 'course' => api_get_course_id())
);
$introduction_section .= "<a href=\"".$url."?".api_get_cidreq()."\">";
$introduction_section .= Display::return_icon('edit.png', get_lang('Modify')).' ';
$introduction_section .= "</a>";
//$url = $app['url_generator']->generate('introduction_delete', array('tool' => $moduleId));
$url = api_get_path(WEB_PUBLIC_PATH).'introduction/delete/'.$tool;
$url = $urlGenerator->generate(
'introduction.controller:deleteAction',
array('tool' => $tool, 'course' => api_get_course_id())
);
$introduction_section .= "<a onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES,$charset))."')) return false;\" href=\"".$url."?".api_get_cidreq()."\">";
$introduction_section .= Display::return_icon('delete.png', get_lang('AddIntro')).' ';
@ -814,9 +828,10 @@ class Display
/**
* 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 array additional attributes (for instance height, width, onclick, ...)
* @param bool $applyFilter
* @author Julio Montoya 2010
*/
public static function img($image_path, $alt_text = '', $additional_attributes = array(), $applyFilter = true)

@ -544,19 +544,6 @@ $app->match('/courses/{cidReq}/', 'course_home.controller:indexAction', 'GET|POS
->before($settingCourseConditions)
->before($userPermissionsInsideACourse);
// Introduction
$app->match('/introduction/edit/{tool}', 'introduction_tool.controller:editAction', 'GET|POST')
->assert('type', '.+')
->before($settingCourseConditions)
->before($userPermissionsInsideACourse)
->bind('introduction_edit');
$app->match('/introduction/delete/{tool}', 'introduction_tool.controller:deleteAction', 'GET|POST')
->assert('type', '.+')
->before($settingCourseConditions)
->before($userPermissionsInsideACourse)
->bind('introduction_delete');
/** Course documents */
$app->get('/data/courses/{courseCode}/document/{file}', 'index.controller:getDocumentAction')
->assert('file', '.+')
@ -569,6 +556,12 @@ $app->get('/data/courses/{courseCode}/scorm/{file}', 'index.controller:getScormD
->assert('type', '.+')
->bind('get_scorm_document');
/** Course documents */
$app->get('/data/courses/{courseCode}/upload/{file}', 'index.controller:getCourseUploadFileAction')
->assert('file', '.+')
->assert('type', '.+')
->bind('getCourseUploadFileAction');
/** Certificates */
$app->match('/certificates/{id}', 'certificate.controller:indexAction', 'GET');
@ -722,21 +715,27 @@ $app->match('/ajax', 'model_ajax.controller:indexAction', 'GET')
->bind('model_ajax');
if ($alreadyInstalled) {
$app->mount('/admin/', new ChamiloLMS\Provider\ReflectionControllerProvider('admin.controller'));
$app->mount('/admin/administrator/upgrade', new ChamiloLMS\Provider\ReflectionControllerProvider('upgrade.controller'));
$app->mount('/admin/administrator/roles', new ChamiloLMS\Provider\ReflectionControllerProvider('role.controller'));
$app->mount('/admin/administrator/question_scores', new ChamiloLMS\Provider\ReflectionControllerProvider('question_score.controller'));
$app->mount('/admin/administrator/question_score_names', new ChamiloLMS\Provider\ReflectionControllerProvider('question_score_name.controller'));
$app->mount('/editor/', new ChamiloLMS\Provider\ReflectionControllerProvider('editor.controller'));
$app->mount('/user/', new ChamiloLMS\Provider\ReflectionControllerProvider('profile.controller'));
$app->mount('/app/session_path', new ChamiloLMS\Provider\ReflectionControllerProvider('session_path.controller'));
$app->mount('/app/session_path/tree', new ChamiloLMS\Provider\ReflectionControllerProvider('session_tree.controller'));
$app->mount('/courses/{course}/curriculum/category', new ChamiloLMS\Provider\ReflectionControllerProvider('curriculum_category.controller'));
$app->mount('/courses/{course}/curriculum/item', new ChamiloLMS\Provider\ReflectionControllerProvider('curriculum_item.controller'));
$app->mount('/courses/{course}/curriculum/user', new ChamiloLMS\Provider\ReflectionControllerProvider('curriculum_user.controller'));
$app->mount('/courses/{course}/curriculum', new ChamiloLMS\Provider\ReflectionControllerProvider('curriculum.controller'));
// Mount controllers.
$controllers = array(
'/admin/' => 'admin.controller',
'/admin/administrator/upgrade' => 'upgrade.controller',
'/admin/administrator/roles' => 'role.controller',
'/admin/administrator/question_scores' => 'question_score.controller',
'/admin/administrator/question_score_names' => 'question_score_name.controller',
'/editor/' => 'editor.controller',
'/user/' => 'profile.controller',
'/app/session_path' => 'session_path.controller',
'/app/session_path/tree' => 'session_tree.controller',
'/courses/{course}/curriculum/category' => 'curriculum_category.controller',
'/courses/{course}/curriculum/item' => 'curriculum_item.controller',
'/courses/{course}/curriculum/user' => 'curriculum_user.controller',
'/courses/{course}/curriculum' => 'curriculum.controller',
'/courses/{course}/course_home' => 'course_home.controller',
'/courses/{course}/introduction' => 'introduction.controller',
);
foreach ($controllers as $route => $controller) {
$app->mount($route, new ChamiloLMS\Provider\ReflectionControllerProvider($controller));
}
}

@ -287,7 +287,7 @@ $app['form.extensions'] = $app->share($app->extend('form.extensions', function (
return $extensions;
}));
// Needed to use the "UniqueEntity" validator
// Needed to use the "UniqueEntity" validator.
$app['validator.validator_factory'] = $app->share(function ($app) {
$uniqueValidator = new Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator($app['manager_registry']);
$factory = new ChamiloLMS\Component\Validator\ConstraintValidatorFactory();
@ -699,24 +699,6 @@ $app['learnpath.controller'] = $app->share(
}
);
$app['course_home.controller'] = $app->share(
function () use ($app) {
return new ChamiloLMS\Controller\CourseHomeController();
}
);
$app['course_home.controller'] = $app->share(
function () use ($app) {
return new ChamiloLMS\Controller\CourseHomeController();
}
);
$app['introduction_tool.controller'] = $app->share(
function () use ($app) {
return new ChamiloLMS\Controller\IntroductionToolController();
}
);
$app['certificate.controller'] = $app->share(
function () use ($app) {
return new ChamiloLMS\Controller\CertificateController();
@ -833,6 +815,18 @@ $app['upgrade.controller'] = $app->share(
}
);
$app['course_home.controller'] = $app->share(
function () use ($app) {
return new ChamiloLMS\Controller\Tool\CourseHome\CourseHomeController($app);
}
);
$app['introduction.controller'] = $app->share(
function () use ($app) {
return new ChamiloLMS\Controller\Tool\Introduction\IntroductionController($app);
}
);
$app['html_editor'] = $app->share(function($app) {
return new ChamiloLMS\Component\Editor\CkEditor\CkEditor($app['translator'], $app['url_generator'], $app['course']);
//return new ChamiloLMS\Component\Editor\TinyMce\TinyMce($app['translator'], $app['url_generator']);

@ -144,6 +144,15 @@ $("form").on("click", ' .advanced_parameters', function() {
/** Makes row highlighting possible */
$(document).ready( function() {
$(function() {
$('a').tooltip({
placement: 'right',
show: 500,
hide: 500
});
});
$('.advanced_parameters').addClass('btn-default');
//$('.btn').addClass('btn-default');

@ -0,0 +1,97 @@
{% extends app.template_style ~ "/layout/layout_1_col.tpl" %}
{% block content %}
<script>
$(document).ready(function() {
$(".make_visible_and_invisible").attr("href", "javascript:void(0);");
$(".make_visible_and_invisible > img").click(function () {
var make_visible = "visible.gif";
var make_invisible = "invisible.gif";
var path_name = $(this).attr("src");
var list_path_name = path_name.split("/");
var image_link = list_path_name[list_path_name.length - 1];
var tool_id = $(this).attr("id");
var tool_info = tool_id.split("_");
var my_tool_id = tool_info[1];
$.ajax({
contentType: "application/x-www-form-urlencoded",
beforeSend: function(data) {
$(".normal-message").show();
$("#id_confirmation_message").hide();
},
type: "GET",
url: "{{ _p.web_ajax }}course_home.ajax.php?cidReq={{ course.code }}&a=set_visibility",
data: "id=" + my_tool_id + "&sent_http_request=1",
success: function(data) {
eval("var info=" + data);
var new_current_tool_image = info.image;
var new_current_view = "{{ _p.web_img}}" + info.view;
// Eyes
$("#" + tool_id).attr("src", new_current_view);
// Tool
$("#toolimage_" + my_tool_id).attr("src", new_current_tool_image);
// Class
$("#tooldesc_" + my_tool_id).attr("class", info.tclass);
$("#istooldesc_" + my_tool_id).attr("class", info.tclass);
if (image_link == "visible.gif") {
$("#" + tool_id).attr("alt", "{{ 'Activate' | trans }}");
$("#" + tool_id).attr("title", "{{ 'Activate' | trans }}");
} else {
$("#" + tool_id).attr("alt", "{{ 'Deactivate' | trans }}");
$("#" + tool_id).attr("title", "{{ 'Deactivate' | trans }}");
}
if (info.message == "is_active") {
message = "{{ 'ToolIsNowVisible' | trans }}";
} else {
message = "{{ 'ToolIsNowHidden' | trans }}";
}
$(".normal-message").hide();
$("#id_confirmation_message").html(message);
$("#id_confirmation_message").show();
}
});
});
});
/* toogle for post-it in course home */
$(function() {
$(".thematic-postit-head").click(function() {
$(".thematic-postit-center").slideToggle("fast");
});
});
</script>
<div class="courseadminview" style="border:0px; margin-top: 0px;padding:0px;">
<div class="normal-message" id="id_normal_message" style="display:none">
<img src="{{ _p.web_img }}loading1.gif" />
{{ 'PleaseStandBy' | trans }}
</div>
<div class="confirmation-message" id="id_confirmation_message" style="display:none">
</div>
</div>
{% if session_info %}
<div class="courseadminview">
<span class="viewcaption">{{ 'SessionData' | trans }}</span>
<table class="course_activity_home">
{{ session_info }}
</table>
</div>
{% endif %}
{{ lp_warning }}
{{ exercise_warning }}
{{ introduction_text }}
{{ edit_icons }}
<div id="course_tools">
{{ icons }}
</div>
{% endblock %}

@ -0,0 +1,7 @@
{% extends app.template_style ~ "/layout/layout_1_col.tpl" %}
{% block content %}
{% import app.template_style ~ "/crud_macros/course_crud.tpl" as actions %}
<form action="{{ url('course_home.controller:editIconAction', {'course': course.code, 'id_session' : session.id, itemId : item.id }) }}" method = "post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
</form>
{% endblock %}

@ -0,0 +1,34 @@
{% extends app.template_style ~ "/layout/layout_1_col.tpl" %}
{% block content %}
<table class="table">
{% for item in items %}
<tr>
<td>
<a href="{{ url(links.read_link, {'course' : course.code, 'id_session': course_session.id, id: item.id }) }}">
{% if item.customIcon %}
<img src="{{ url('getCourseUploadFileAction', { courseCode:course.code, file: 'course_home_icons/'~item.customIcon}) }}"/>
{% else %}
<img src="{{ _p.web_img ~ 'icons/64/' ~ item.imageGifToPng }}"/>
{% endif %}
</a>
</td>
<td>
<a href="{{ url(links.read_link, {'course' : course.code, 'id_session': course_session.id, id: item.id }) }}">
{{ item.name }}
</a>
</td>
<td>
<a class="btn" href="{{ url(links.update_link, {'course' : course.code, 'id_session': course_session.id, id: item.id }) }}">
{{ 'Edit' | trans }}
</a>
{% if item.customIcon %}
<a class="btn" href="{{ url('course_home.controller:deleteIconAction', {'course' : course.code, 'id_session': course_session.id, itemId: item.id }) }}">
{{ 'Delete' |trans }}
</a>
{% endif %}
</td>
</tr>
{% endfor %}
</table>
{% endblock %}

@ -9,6 +9,7 @@ use Symfony\Component\Console;
/**
* @todo use Gaufrette to manage course files (some day)
* @todo add security restrictions.
* Class DataFilesystem
* @package ChamiloLMS\Component\DataFilesystem
*/
@ -75,6 +76,18 @@ class DataFilesystem
return $this->get($file);
}
/**
* Gets a file from the data/courses/MATHS/document directory
* @param $courseCode
* @param $file
* @return SplFileInfo
*/
public function getCourseUploadFile($courseCode, $file)
{
$file = 'courses/'.$courseCode.'/upload/'.$file;
return $this->get($file);
}
/**
* Create folders
* @param array $folderList

@ -151,6 +151,11 @@ abstract class BaseController extends FlintController
return $this->get('orm.em');
}
public function sendFile($file, $status = 200, $headers = array(), $contentDisposition = null)
{
return $this->pimple->sendFile($file, $status, $headers, $contentDisposition);
}
/**
* Converts an array of URL to absolute URLs using the url_generator service
* @param string $label

@ -1,125 +0,0 @@
<?php
/* For licensing terms, see /license.txt */
namespace ChamiloLMS\Controller;
use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
/**
* Class CourseHomeController
* @package ChamiloLMS\Controller
* @author Julio Montoya <gugli100@gmail.com>
*/
class CourseHomeController
{
public $language_files = array('course_home','courses');
public function indexAction(Application $app, $cidReq, $idSession = null)
{
$extraJS = array();
//@todo improve this JS includes should be added using twig
$extraJS[] ='<script>
$(document).ready(function() {
$(".make_visible_and_invisible").attr("href", "javascript:void(0);");
$(".make_visible_and_invisible > img").click(function () {
make_visible = "visible.gif";
make_invisible = "invisible.gif";
path_name = $(this).attr("src");
list_path_name = path_name.split("/");
image_link = list_path_name[list_path_name.length - 1];
tool_id = $(this).attr("id");
tool_info = tool_id.split("_");
my_tool_id = tool_info[1];
$.ajax({
contentType: "application/x-www-form-urlencoded",
beforeSend: function(objeto) {
$(".normal-message").show();
$("#id_confirmation_message").hide();
},
type: "GET",
url: "'.api_get_path(WEB_AJAX_PATH).'course_home.ajax.php?'.api_get_cidreq().'&a=set_visibility",
data: "id=" + my_tool_id + "&sent_http_request=1",
success: function(data) {
eval("var info=" + data);
new_current_tool_image = info.image;
new_current_view = "'.api_get_path(WEB_IMG_PATH).'" + info.view;
//eyes
$("#" + tool_id).attr("src", new_current_view);
//tool
$("#toolimage_" + my_tool_id).attr("src", new_current_tool_image);
//clase
$("#tooldesc_" + my_tool_id).attr("class", info.tclass);
$("#istooldesc_" + my_tool_id).attr("class", info.tclass);
if (image_link == "visible.gif") {
$("#" + tool_id).attr("alt", "'.get_lang('Activate', '').'");
$("#" + tool_id).attr("title", "'.get_lang('Activate', '').'");
} else {
$("#" + tool_id).attr("alt", "'.get_lang('Deactivate', '').'");
$("#" + tool_id).attr("title", "'.get_lang('Deactivate', '').'");
}
if (info.message == "is_active") {
message = "'.get_lang('ToolIsNowVisible', '').'";
} else {
message = "'.get_lang('ToolIsNowHidden', '').'";
}
$(".normal-message").hide();
$("#id_confirmation_message").html(message);
$("#id_confirmation_message").show();
}
});
});
});
/* toogle for post-it in course home */
$(function() {
$(".thematic-postit-head").click(function() {
$(".thematic-postit-center").slideToggle("fast");
});
});
</script>';
$app['extraJS'] = $extraJS;
//Needed because of this script:
$course_code = $cidReq;
$result = require_once api_get_path(SYS_CODE_PATH).'course_home/course_home.php';
$app['template']->assign('content', $result['content']);
$app['template']->assign('message', $result['message']);
$response = $app['template']->renderLayout('layout_1_col.tpl');
return new Response($response, 200, array());
}
/**
* @param Application $app
* @param $courseCode
* @param $fileName
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse
*/
public function getFileAction(Application $app, $courseCode, $fileName)
{
$courseInfo = api_get_course_info($courseCode);
$sessionId = $app['request']->get('id_session');
$docId = \DocumentManager::get_document_id($courseInfo, "/".$fileName);
$filePath = null;
if ($docId) {
$isVisible = \DocumentManager::is_visible_by_id($docId, $courseInfo, $sessionId, api_get_user_id());
$documentData = \DocumentManager::get_document_data_by_id($docId, $courseCode);
$filePath = $documentData['absolute_path'];
event_download($filePath);
}
if (!api_is_allowed_to_edit() && !$isVisible) {
$app->abort(500);
}
//DocumentManager::file_send_for_download($full_file_name);
return $app->sendFile($filePath);
}
}

@ -324,6 +324,24 @@ class IndexController extends CommonController
}
}
/**
* Gets a document from the data/courses/MATHS/document/file.jpg to the user
* @todo check permissions
* @param Application $app
* @param string $courseCode
* @param string $file
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse|void
*/
public function getCourseUploadFileAction(Application $app, $courseCode, $file)
{
try {
$file = $app['chamilo.filesystem']->getCourseUploadFile($courseCode, $file);
return $app->sendFile($file->getPathname());
} catch (\InvalidArgumentException $e) {
return $app->abort(404, 'File not found');
}
}
/**
* Gets a document from the data/courses/MATHS/scorm/file.jpg to the user
* @todo check permissions

@ -0,0 +1,469 @@
<?php
/* For licensing terms, see /license.txt */
namespace ChamiloLMS\Controller\Tool\CourseHome;
use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
use ChamiloLMS\Controller\CommonController;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Entity\CTool;
use ChamiloLMS\Form\CourseHomeToolType;
use \Display;
/**
* Class CourseHomeController
* @package ChamiloLMS\Controller
* @author Julio Montoya <gugli100@gmail.com>
*/
class CourseHomeController extends CommonController
{
/**
* @Route("/courses/{cidReq}/{sessionId}")
* @Method({"GET"})
*
* @param string $cidReq
* @param int $id_session
* @return Response
*/
public function indexAction($cidReq, $id_session = null)
{
api_protect_course_script(true);
$courseCode = api_get_course_id();
$sessionId = api_get_session_id();
$userId = $this->getUser()->getUserId();
$coursesAlreadyVisited = $this->getRequest()->getSession()->get('coursesAlreadyVisited');
$result = $this->autolaunch();
$show_autolaunch_lp_warning = $result['show_autolaunch_lp_warning'];
$show_autolaunch_exercise_warning = $result['show_autolaunch_exercise_warning'];
if ($show_autolaunch_lp_warning) {
$this->getTemplate()->assign(
'lp_warning',
Display::return_message(get_lang('TheLPAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificLP'), 'warning')
);
}
if ($show_autolaunch_exercise_warning) {
$this->getTemplate()->assign(
'exercise_warning',
Display::return_message(get_lang('TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise'), 'warning')
);
}
$editIcons = Display::url(
Display::return_icon('edit.png'),
$this->generateUrl('course_home.controller:iconListAction', array('course' => api_get_course_id()))
);
$this->getTemplate()->assign('edit_icons', $editIcons);
if (!isset($coursesAlreadyVisited[$courseCode])) {
event_access_course();
$coursesAlreadyVisited[$courseCode] = 1;
$this->getRequest()->getSession()->set('coursesAlreadyVisited', $coursesAlreadyVisited);
}
$introduction = Display::return_introduction_section(
$this->get('url_generator'),
TOOL_COURSE_HOMEPAGE,
array(
'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
'CreateDocumentDir' => 'document/',
'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/'
)
);
$this->getTemplate()->assign('introduction_text', $introduction);
$this->getRequest()->getSession()->remove('toolgroup');
$this->getRequest()->getSession()->remove('_gid');
$isSpecialCourse = \CourseManager::is_special_course($courseCode);
if ($isSpecialCourse) {
$autoreg = $this->getRequest()->get('autoreg');
if ($autoreg == 1) {
\CourseManager::subscribe_user($userId, $courseCode, STUDENT);
}
}
$script = 'activity.php';
if (api_get_setting('homepage_view') == 'activity' || api_get_setting('homepage_view') == 'activity_big') {
$script = 'activity.php';
} elseif (api_get_setting('homepage_view') == '2column') {
$script = '2column.php';
} elseif (api_get_setting('homepage_view') == '3column') {
$script = '3column.php';
} elseif (api_get_setting('homepage_view') == 'vertical_activity') {
$script = 'vertical_activity.php';
}
$result = require_once api_get_path(SYS_CODE_PATH).'course_home/'.$script;
$this->getTemplate()->assign('icons', $result);
if (api_get_setting('show_session_data') == 'true' && $sessionId) {
$sessionInfo = \CourseHome::show_session_data($sessionId);
$this->getTemplate()->assign('session_info', $sessionInfo);
}
$response = $this->get('template')->render_template($this->getTemplatePath().'index.tpl');
return new Response($response, 200, array());
}
private function autolaunch()
{
$show_autolaunch_exercise_warning = false;
// Exercise auto-launch
$auto_launch = api_get_course_setting('enable_exercise_auto_launch');
if (!empty($auto_launch)) {
$session_id = api_get_session_id();
//Exercise list
if ($auto_launch == 2) {
if (api_is_platform_admin() || api_is_allowed_to_edit()) {
$show_autolaunch_exercise_warning = true;
} else {
$session_key = 'exercise_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
if (!isset($_SESSION[$session_key])) {
//redirecting to the Exercise
$url = api_get_path(WEB_CODE_PATH).'exercice/exercice.php?'.api_get_cidreq().'&id_session='.$session_id;
$_SESSION[$session_key] = true;
header("Location: $url");
exit;
}
}
} else {
$table = Database::get_course_table(TABLE_QUIZ_TEST);
$course_id = api_get_course_int_id();
$condition = '';
if (!empty($session_id)) {
$condition = api_get_session_condition($session_id);
$sql = "SELECT iid FROM $table WHERE c_id = $course_id AND autolaunch = 1 $condition LIMIT 1";
$result = Database::query($sql);
//If we found nothing in the session we just called the session_id = 0 autolaunch
if (Database::num_rows($result) == 0) {
$condition = '';
} else {
//great, there is an specific auto lunch for this session we leave the $condition
}
}
$sql = "SELECT iid FROM $table WHERE c_id = $course_id AND autolaunch = 1 $condition LIMIT 1";
$result = Database::query($sql);
if (Database::num_rows($result) > 0) {
$data = Database::fetch_array($result,'ASSOC');
if (!empty($data['iid'])) {
if (api_is_platform_admin() || api_is_allowed_to_edit()) {
$show_autolaunch_exercise_warning = true;
} else {
$session_key = 'exercise_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
if (!isset($_SESSION[$session_key])) {
//redirecting to the LP
$url = api_get_path(WEB_CODE_PATH).'exercice/overview.php?'.api_get_cidreq().'&exerciseId='.$data['iid'];
$_SESSION[$session_key] = true;
header("Location: $url");
exit;
}
}
}
}
}
}
/* Auto launch code */
$show_autolaunch_lp_warning = false;
$auto_launch = api_get_course_setting('enable_lp_auto_launch');
if (!empty($auto_launch)) {
$session_id = api_get_session_id();
//LP list
if ($auto_launch == 2) {
if (api_is_platform_admin() || api_is_allowed_to_edit()) {
$show_autolaunch_lp_warning = true;
} else {
$session_key = 'lp_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
if (!isset($_SESSION[$session_key])) {
//redirecting to the LP
$url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?'.api_get_cidreq().'&id_session='.$session_id;
$_SESSION[$session_key] = true;
header("Location: $url");
exit;
}
}
} else {
$lp_table = Database::get_course_table(TABLE_LP_MAIN);
$course_id = api_get_course_int_id();
$condition = '';
if (!empty($session_id)) {
$condition = api_get_session_condition($session_id);
$sql = "SELECT id FROM $lp_table WHERE c_id = $course_id AND autolunch = 1 $condition LIMIT 1";
$result = Database::query($sql);
//If we found nothing in the session we just called the session_id = 0 autolunch
if (Database::num_rows($result) == 0) {
$condition = '';
} else {
//great, there is an specific auto lunch for this session we leave the $condition
}
}
$sql = "SELECT id FROM $lp_table WHERE c_id = $course_id AND autolunch = 1 $condition LIMIT 1";
$result = Database::query($sql);
if (Database::num_rows($result) > 0) {
$lp_data = Database::fetch_array($result,'ASSOC');
if (!empty($lp_data['id'])) {
if (api_is_platform_admin() || api_is_allowed_to_edit()) {
$show_autolaunch_lp_warning = true;
} else {
$session_key = 'lp_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
if (!isset($_SESSION[$session_key])) {
//redirecting to the LP
$url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['id'];
$_SESSION[$session_key] = true;
header("Location: $url");
exit;
}
}
}
}
}
}
return array(
'show_autolaunch_exercise_warning' => $show_autolaunch_exercise_warning,
'show_autolaunch_lp_warning' => $show_autolaunch_lp_warning
);
}
/**
* @param string $courseCode
* @param string $fileName
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse
*/
public function getFileAction($courseCode, $fileName)
{
$courseInfo = api_get_course_info($courseCode);
$sessionId = $this->getRequest()->get('id_session');
$docId = \DocumentManager::get_document_id($courseInfo, "/".$fileName);
$filePath = null;
if ($docId) {
$isVisible = \DocumentManager::is_visible_by_id($docId, $courseInfo, $sessionId, api_get_user_id());
$documentData = \DocumentManager::get_document_data_by_id($docId, $courseCode);
$filePath = $documentData['absolute_path'];
event_download($filePath);
}
if (!api_is_allowed_to_edit() && !$isVisible) {
$this->abort(500);
}
return $this->sendFile($filePath);
}
/**
* @Route("/show/{iconId}")
* @Method({"GET"})
* @param $iconId
* @return null|string
*/
public function showIconAction($iconId)
{
if (!api_is_allowed_to_edit(null, true)) {
return null;
}
$entityManager = $this->getManager();
$criteria = array('cId' => api_get_course_int_id(), 'id' => $iconId);
$tool = $this->getRepository('Entity\CTool')->findOneBy($criteria);
if ($tool) {
$tool->setVisibility(1);
}
$entityManager->persist($tool);
//$entityManager->flush();
return Display::return_message(get_lang('Visible'), 'confirmation');
}
/**
* @Route("/hide/{iconId}")
* @Method({"GET"})
* @param $iconId
* @return null|string
*/
public function hideIconAction($iconId)
{
if (!api_is_allowed_to_edit(null, true)) {
return null;
}
$entityManager = $this->getManager();
$criteria = array('cId' => api_get_course_int_id(), 'id' => $iconId);
$tool = $this->getRepository('Entity\CTool')->findOneBy($criteria);
if ($tool) {
$tool->setVisibility(0);
}
$entityManager->persist($tool);
//$entityManager->flush();
return Display::return_message(get_lang('ToolIsNowHidden'), 'confirmation');
}
/**
* @Route("/delete/{iconId}")
* @Method({"GET"})
* @param $iconId
* @return null|string
*/
public function deleteIcon($iconId)
{
if (!api_is_allowed_to_edit(null, true)) {
return null;
}
$entityManager = $this->getManager();
$criteria = array('cId' => api_get_course_int_id(), 'id' => $iconId, 'added_tool' => 1);
$tool = $this->getRepository('Entity\CTool')->findOneBy($criteria);
$entityManager->remove($tool);
//$entityManager->flush();
return Display::return_message(get_lang('Deleted'), 'confirmation');
}
/**
* @Route("/icon_list")
* @Method({"GET"})
*/
public function iconListAction()
{
$criteria = array('cId' => $this->getCourse()->getId(), 'sessionId' => 0);
$items = $this->getRepository()->findBy($criteria);
$this->getTemplate()->assign('items', $items);
$this->getTemplate()->assign('links', $this->generateLinks());
return $this->get('template')->render_template($this->getTemplatePath().'tool/list.tpl');
}
/**
* @Route("/{itemId}/edit")
* @Method({"GET"})
*/
public function editIconAction($itemId)
{
$sessionId = $this->getRequest()->get('id_session');
$criteria = array('cId' => $this->getCourse()->getId(), 'sessionId' => 0, 'id' => $itemId);
/** @var CTool $item */
$item = $this->getRepository()->findOneBy($criteria);
$item->setSessionId($sessionId);
$form = $this->createForm($this->getFormType(), $item);
$form->handleRequest($this->getRequest());
if ($form->isValid()) {
$sessionId = $item->getSessionId();
$entityManager = $this->getManager();
if (!empty($sessionId)) {
$criteria = array('cId' => $this->getCourse()->getId(), 'sessionId' => $sessionId, 'id' => $itemId);
/** @var CTool $item */
$itemFromDb = $this->getRepository()->findOneBy($criteria);
if (empty($itemFromDb)) {
$newTool = clone $item;
$query = $this->getManager()->createQueryBuilder('a');
$query->select('MAX(s.id) as id');
$query->from('Entity\CTool', 's');
$query->where('s.cId = :courseId')->setParameter('courseId', $this->getCourse()->getId());
$result = $query->getQuery()->getArrayResult();
$maxId = $result[0]['id'] + 1;
$newTool->setId($maxId);
} else {
$newTool = $item;
}
$entityManager->persist($newTool);
} else {
$entityManager->persist($item);
}
$entityManager->flush();
if (!empty($item->getCustomIcon())) {
$item->createGrayIcon($this->get('imagine'));
}
$this->get('session')->getFlashBag()->add('success', "Updated");
$url = $this->generateUrl('course_home.controller:iconListAction');
return $this->redirect($url);
}
$this->getTemplate()->assign('item', $item);
$this->getTemplate()->assign('form', $form->createView());
$this->getTemplate()->assign('links', $this->generateLinks());
return $this->get('template')->render_template($this->getTemplatePath().'tool/edit.tpl');
}
/**
* @Route("/{itemId}/delete")
* @Method({"GET"})
*/
public function deleteIconAction($itemId)
{
$criteria = array('cId' => $this->getCourse()->getId(), 'sessionId' => 0, 'id' => $itemId);
/** @var CTool $item */
$item = $this->getRepository()->findOneBy($criteria);
$item->setCustomIcon(null);
$entityManager = $this->getManager();
$entityManager->persist($item);
$entityManager->flush();
$this->get('session')->getFlashBag()->add('success', "Deleted");
$this->getTemplate()->assign('links', $this->generateLinks());
$url = $this->generateUrl('course_home.controller:iconListAction');
return $this->redirect($url);
}
protected function getControllerAlias()
{
return 'course_home.controller';
}
/**
* {@inheritdoc}
*/
protected function getTemplatePath()
{
return 'tool/course_home/';
}
/**
* {@inheritdoc}
*/
protected function getRepository()
{
return $this->get('orm.em')->getRepository('Entity\CTool');
}
/**
* {@inheritdoc}
*/
protected function getNewEntity()
{
return new CTool();
}
/**
* {@inheritdoc}
*/
protected function getFormType()
{
return new CourseHomeToolType();
}
}

@ -1,40 +1,51 @@
<?php
/* For licensing terms, see /license.txt */
namespace ChamiloLMS\Controller;
namespace ChamiloLMS\Controller\Tool\Introduction;
use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
use ChamiloLMS\Controller\CommonController;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
/**
* Class IntroductionToolController
* @package ChamiloLMS\Controller
* @todo use dbal
* @author Julio Montoya <gugli100@gmail.com>
*/
class IntroductionToolController
class IntroductionController extends CommonController
{
/**
* @param Application $app
* @Route("/edit/{tool}")
* @Method({"GET"})
*
* @param string $tool
* @return Response
*/
public function editAction(Application $app, $tool)
public function editAction($tool)
{
$message = null;
$request = $app['request'];
$courseId = $request->get('courseId');
$sessionId = $request->get('sessionId');
// @todo use proper functions not api functions.
$courseId = api_get_course_int_id();
$sessionId = api_get_session_id();
$tool = \Database::escape_string($tool);
$TBL_INTRODUCTION = \Database::get_course_table(TABLE_TOOL_INTRO);
$url = $app['url_generator']->generate('introduction_edit', array('tool' => $tool)).'?'.api_get_cidreq();
$url = $this->generateUrl(
'introduction.controller:editAction',
array('tool' => $tool, 'course' => api_get_course_id())
);
$form = $this->getForm($url);
if ($form->validate()) {
$values = $form->exportValues();
$content = $values['content'];
$sql = "REPLACE $TBL_INTRODUCTION SET c_id = $courseId, id='$tool', intro_text='".\Database::escape_string($content)."', session_id='".intval($sessionId)."'";
$sql = "REPLACE $TBL_INTRODUCTION
SET c_id = $courseId, id='$tool', intro_text='".\Database::escape_string($content)."', session_id='".intval($sessionId)."'";
\Database::query($sql);
$message = \Display::return_message(get_lang('IntroductionTextUpdated'), 'confirmation', false);
} else {
@ -50,35 +61,41 @@ class IntroductionToolController
$form->setDefaults(array('content' => $content));
}
$app['template']->assign('content', $form->return_form());
$app['template']->assign('message', $message);
$response = $app['template']->renderLayout('layout_1_col.tpl');
$this->getTemplate()->assign('content', $form->return_form());
$this->getTemplate()->assign('message', $message);
$response = $this->getTemplate()->renderLayout('layout_1_col.tpl');
return new Response($response, 200, array());
}
/**
* @param Application $app
* @Route("/delete/{tool}")
* @Method({"GET"})
*
* @param string $tool
* @return Response
*/
public function deleteAction(Application $app, $tool)
public function deleteAction($tool)
{
/** @var \Request $request */
$request = $app['request'];
$request = $this->getRequest();
$courseId = $request->get('courseId');
$sessionId = $request->get('sessionId');
$tool = \Database::escape_string($tool);
$TBL_INTRODUCTION = \Database::get_course_table(TABLE_TOOL_INTRO);
\Database::query("DELETE FROM $TBL_INTRODUCTION WHERE c_id = $courseId AND id='".$tool."' AND session_id='".intval($sessionId)."'");
\Database::query("DELETE FROM $TBL_INTRODUCTION
WHERE c_id = $courseId AND id='".$tool."' AND session_id='".intval($sessionId)."'");
$message = \Display::return_message(get_lang('IntroductionTextDeleted'), 'confirmation');
$url = $app['url_generator']->generate('introduction_edit', array('tool' => $tool)).'?'.api_get_cidreq();
$url = $this->generateUrl(
'introduction.controller:editAction',
array('tool' => $tool, 'course' => api_get_course_id())
);
$form = $this->getForm($url);
$app['template']->assign('content', $form->return_form());
$app['template']->assign('message', $message);
$response = $app['template']->renderLayout('layout_1_col.tpl');
$this->getTemplate()->assign('content', $form->return_form());
$this->getTemplate()->assign('message', $message);
$response = $this->getTemplate()->renderLayout('layout_1_col.tpl');
return new Response($response, 200, array());
}

@ -0,0 +1,48 @@
<?php
namespace ChamiloLMS\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Entity;
use Symfony\Component\Validator\Constraints as Assert;
class CourseHomeToolType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', 'text');
$builder->add('link', 'text');
$builder->add(
'custom_icon',
'file',
array('required' => false, 'data_class' => null)
);
$builder->add('target', 'choice', array('choices' => array('_self', '_blank')));
$builder->add('visibility', 'choice', array('choices' => array('1', '0')));
$builder->add('c_id', 'hidden');
$builder->add('session_id', 'hidden');
$builder->add('description', 'textarea');
$builder->add('submit', 'submit');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'data_class' => 'Entity\CTool'
)
);
}
public function getName()
{
return 'courseHomeTool';
}
}
Loading…
Cancel
Save