Browse Source

Notebook teacher - Minor improvements

- Format code
- readme is now a markdown
- Use ChamiloSession instead of $_SESSION
- Rename classes
- Use api_get_plugin_setting
- deleted unused file

See #2463
jmontoyaa 7 years ago
parent
commit
034656cc41

+ 1 - 3
main/mySpace/myStudents.php

@@ -419,9 +419,7 @@ if (!empty($student_id) && !empty($course_code)) {
         '</a>';
 }
 
-$notebookTeacherPlugin = NotebookTeacherPlugin::create();
-$notebookTeacherEnable = $notebookTeacherPlugin->get('enable_plugin_notebookteacher') === 'true';
-
+$notebookTeacherEnable = api_get_plugin_setting('notebookteacher', 'enable_plugin_notebookteacher') === 'true';
 if ($notebookTeacherEnable && !empty($student_id) && !empty($course_code)) {
     // link notebookteacher
     $optionsLink = 'student_id='.$student_id.'&origin='.$origin.'&cidReq='.$course_code.'&id_session='.$sessionId;

+ 20 - 0
plugin/notebookteacher/README.md

@@ -0,0 +1,20 @@
+Este plugin da la posibilidad a los profesores de un curso escribir en un bloc de notas compartido.
+
+Los estudiantes no tienen acceso a las notas compartidas de los profesores.
+
+**Instrucciones de puesta en funcionamiento**
+
+- Subir la carpeta **notebookteacher** a la carpeta plugin de chamilo.
+
+- Habilitar el plugin en la administraci&oacute;n de Chamilo.
+- El icono de la herramienta aparecer&aacute; en pantalla de los cursos con el resto de herramientas
+- Si no se visualiza el icono en el cursos correctamente y sale el icono de plugin gen&eacute;rico:
+    - Copiar los iconos de la carpeta resources/img/64 dentro de /main/img/icons/64
+    - Copiar el icono de la carpeta resources/img/22 dentro de /main/img
+
+**Solo si ya tiene instalado el plugin previamente:**
+
+Para actualizar la base de datos del plugin con los &uacute;ltimos cambios de la estructura deber&aacute; poner en su
+navegador la siguiente direcci&oacute;n cambiando el nombre del dominio con el que proceda en su caso.
+
+http://*sudominio.com*/**plugin/notebookteacher/update.php**

+ 0 - 2
plugin/notebookteacher/config.php

@@ -8,5 +8,3 @@
  * @author Jose Angel Ruiz <desarrollo@nosolored.com>
  */
 require_once __DIR__.'/../../main/inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'plugin.class.php';
-require_once api_get_path(SYS_PLUGIN_PATH).'notebookteacher/src/notebookteacher_plugin.class.php';

+ 5 - 0
plugin/notebookteacher/database.php

@@ -1,5 +1,6 @@
 <?php
 /* For license terms, see /license.txt */
+
 /**
  * Plugin database installation script. Can only be executed if included
  * inside another script loading global.inc.php.
@@ -18,6 +19,10 @@ $pluginSchema = new \Doctrine\DBAL\Schema\Schema();
 $connection = $entityManager->getConnection();
 $platform = $connection->getDatabasePlatform();
 
+if ($pluginSchema->hasTable(NotebookTeacherPlugin::TABLE_NOTEBOOKTEACHER)) {
+    return;
+}
+
 //Create tables
 $notebookTable = $pluginSchema->createTable(NotebookTeacherPlugin::TABLE_NOTEBOOKTEACHER);
 $notebookTable->addColumn('id', \Doctrine\DBAL\Types\Type::INTEGER, ['autoincrement' => true, 'unsigned' => true]);

+ 2 - 3
plugin/notebookteacher/install.php

@@ -1,14 +1,13 @@
 <?php
 /* For license terms, see /license.txt */
+
 /**
  * This script is included by main/admin/settings.lib.php and generally
  * includes things to execute in the main database (settings_current table).
  *
  * @package chamilo.plugin.notebookteacher
  */
-/**
- * Initialization.
- */
+
 require_once __DIR__.'/config.php';
 if (!api_is_platform_admin()) {
     die('You must have admin permissions to install plugins');

+ 2 - 0
plugin/notebookteacher/plugin.php

@@ -1,5 +1,6 @@
 <?php
 /* For license terms, see /license.txt */
+
 /**
  * This script is a configuration file for the date plugin.
  * You can use it as a master for other platform plugins (course plugins are slightly different).
@@ -7,6 +8,7 @@
  *
  * @package chamilo.plugin.notebookteacher
  */
+
 /**
  * Plugin details (must be present).
  */

+ 0 - 19
plugin/notebookteacher/readme.txt

@@ -1,19 +0,0 @@
-Este plugin da la posibilidad a los profesores de un curso escribir en un bloc de notas compartido.<br>
-Los estudiantes no tienen acceso a las notas compartidas de los profesores.<br/><br/>
-<b>Instrucciones de puesta en funcionamiento:</b><br>
-- Subir la carpeta <b>notebookteacher</b> a la carpeta plugin de chamilo.<br>
-
-- Habilitar el plugin en la administraci&oacute;n de Chamilo.<br>
-- El icono de la herramienta aparecer&aacute; en pantalla de los cursos con el resto de herramientas<br>
-- Si no se visualiza el icono en el cursos correctamente y sale el icono de plugin gen&eacute;rico:<br>
-<ul>
-    <li>Copiar los iconos de la carpeta resources/img/64 dentro de /main/img/icons/64</li>
-    <li>Copiar el icono de la carpeta resources/img/22 dentro de /main/img</li>
-</ul>
-<br>
-<b>Solo si ya tiene instalado el plugin previamente:</b><br>
-Para actualizar la base de datos del plugin con los &uacute;ltimos cambios de la estructura deber&aacute; poner en su
-navegador la siguiente direcci&oacute;n cambiando el nombre del dominio con el que proceda en su caso.<br>
-http://<i>sudominio.com/</i><b>plugin/notebookteacher/update.php</b>
-</p>
-<br>

+ 39 - 44
plugin/notebookteacher/src/notebookteacher.lib.php → plugin/notebookteacher/src/NotebookTeacher.php

@@ -2,7 +2,9 @@
 /* For licensing terms, see /license.txt */
 
 use ChamiloSession as Session;
+
 require_once __DIR__.'/../config.php';
+
 /**
  * This class provides methods for the notebook management.
  * Include/require it in your code to use its features.
@@ -48,8 +50,8 @@ class NotebookTeacher
      *
      * @param array $values
      * @param int   $userId    Optional. The user ID
-+    * @param int   $courseId  Optional. The course ID
-+    * @param int   $sessionId Optional. The session ID
+     * @param int   $courseId  Optional. The course ID
+     * @param int   $sessionId Optional. The session ID
      *
      * @return bool
      */
@@ -154,6 +156,7 @@ class NotebookTeacher
                 ],
             ]
         );
+
         return true;
     }
 
@@ -196,7 +199,7 @@ class NotebookTeacher
         if (!isset($_GET['direction'])) {
             $sortDirection = 'ASC';
             $linkSortDirection = 'DESC';
-        } else if ($_GET['direction'] == 'ASC') {
+        } elseif ($_GET['direction'] == 'ASC') {
             $sortDirection = 'ASC';
             $linkSortDirection = 'DESC';
         } else {
@@ -205,7 +208,6 @@ class NotebookTeacher
         }
 
         $studentId = isset($_GET['student_id']) ? $_GET['student_id'] : null;
-        $selectStudent = '';
         $sessionId = api_get_session_id();
         $courseCode = api_get_course_id();
         $active = isset($_GET['active']) ? $_GET['active'] : null;
@@ -242,9 +244,9 @@ class NotebookTeacher
             } else {
                 $sql .= " AND session_course_user.status = 0 ";
             }
-            $sql .= $sortByfirstName 
-                    ? ' ORDER BY user.firstname, user.lastname'
-                    : ' ORDER BY user.lastname, user.firstname';
+            $sql .= $sortByfirstName
+                ? ' ORDER BY user.firstname, user.lastname'
+                : ' ORDER BY user.lastname, user.firstname';
 
             $rs = Database::query($sql);
 
@@ -331,25 +333,28 @@ class NotebookTeacher
         echo '</div>';
         echo '<div class="row">'.$selectStudent.'</div>';
 
-        if (!isset($_SESSION['notebook_view']) ||
-            !in_array($_SESSION['notebook_view'], ['creation_date', 'update_date', 'title'])
+        $view = Session::read('notebook_view');
+        if (!isset($view) ||
+            !in_array($view, ['creation_date', 'update_date', 'title'])
         ) {
-            $_SESSION['notebook_view'] = 'creation_date';
+            Session::write('notebook_view', 'creation_date');
         }
 
+        $view = Session::read('notebook_view');
+
         // Database table definition
         $tableNotebook = Database::get_main_table(NotebookTeacherPlugin::TABLE_NOTEBOOKTEACHER);
-        if ($_SESSION['notebook_view'] == 'creation_date' || $_SESSION['notebook_view'] == 'update_date') {
-            $orderBy = " ORDER BY ".$_SESSION['notebook_view']." $sortDirection ";
+        if ($view == 'creation_date' || $view == 'update_date') {
+            $orderBy = " ORDER BY $view $sortDirection ";
         } else {
-            $orderBy = " ORDER BY ".$_SESSION['notebook_view']." $sortDirection ";
+            $orderBy = " ORDER BY $view $sortDirection ";
         }
 
         //condition for the session
         $session_id = api_get_session_id();
         $conditionSession = api_get_session_condition($session_id);
 
-        $condExtra = ($_SESSION['notebook_view'] == 'update_date') ? " AND update_date <> ''" : " ";
+        $condExtra = $view == 'update_date' ? " AND update_date <> ''" : " ";
         $courseId = api_get_course_int_id();
 
         if ($studentId > 0) {
@@ -368,11 +373,10 @@ class NotebookTeacher
             if (Database::num_rows($result) > 0) {
                 while ($row = Database::fetch_array($result)) {
                     if ($first) {
+                        $studentText = '';
                         if ($row['student_id'] > 0) {
                             $studentInfo = api_get_user_info($row['student_id']);
                             $studentText = $studentInfo['complete_name'];
-                        } else {
-                            $studentText = '';
                         }
                         echo Display::page_subheader($studentText);
                         $first = false;
@@ -386,7 +390,7 @@ class NotebookTeacher
                     }
                     $userInfo = api_get_user_info($row['user_id']);
                     $author = ', '.get_lang('Teacher').': '.$userInfo['complete_name'];
-
+                    $actions = '';
                     if (intval($row['user_id']) == api_get_user_id()) {
                         $actions = '<a href="'.
                                 api_get_self().'?'.
@@ -397,15 +401,12 @@ class NotebookTeacher
                                 '?action=deletenote&notebook_id='.$row['id'].
                                 '" onclick="return confirmation(\''.$row['title'].'\');">'.
                                 Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
-                    } else {
-                        $actions = '';
                     }
-
                     echo Display::panel(
-                            $row['description'],
-                            $row['title'].$sessionImg.' <div class="pull-right">'.$actions.'</div>',
-                            get_lang('CreationDate').': '.
-                            Display::dateToStringAgoAndLongDate($row['creation_date']).$updateValue.$author
+                        $row['description'],
+                        $row['title'].$sessionImg.' <div class="pull-right">'.$actions.'</div>',
+                        get_lang('CreationDate').': '.
+                        Display::dateToStringAgoAndLongDate($row['creation_date']).$updateValue.$author
                     );
                 }
             } else {
@@ -416,7 +417,6 @@ class NotebookTeacher
             foreach ($courseUsersList as $key => $userItem) {
                 $studentId = $key;
                 $studentText = $userItem['firstname'].' '.$userItem['lastname'];
-
                 $conditionStudent = " AND student_id = $studentId";
 
                 $sql = "SELECT * FROM $tableNotebook
@@ -431,7 +431,6 @@ class NotebookTeacher
                 if (Database::num_rows($result) > 0) {
                     echo Display::page_subheader($studentText);
                     while ($row = Database::fetch_array($result)) {
-
                         // Validation when belongs to a session
                         $sessionImg = api_get_session_image($row['session_id'], $userInfo['status']);
                         $updateValue = '';
@@ -446,26 +445,26 @@ class NotebookTeacher
 
                         if (intval($row['user_id']) == api_get_user_id()) {
                             $actions = '<a href="'.api_get_self().
-                                    '?action=editnote&notebook_id='.$row['id'].'&'.api_get_cidreq().'">'.
+                                '?action=editnote&notebook_id='.$row['id'].'&'.api_get_cidreq().'">'.
                                     Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL).'</a>';
                             $actions .= '<a href="'.api_get_self().
                                     '?action=deletenote&notebook_id='.$row['id'].
                                     '" onclick="return confirmation(\''.$row['title'].'\');">'.
                                     Display::return_icon(
-                                            'delete.png',
-                                            get_lang('Delete'),
-                                            '',
-                                            ICON_SIZE_SMALL
+                                        'delete.png',
+                                        get_lang('Delete'),
+                                        '',
+                                        ICON_SIZE_SMALL
                                     ).'</a>';
                         } else {
                             $actions = '';
                         }
 
                         echo Display::panel(
-                                $row['description'],
-                                $row['title'].$sessionImg.' <div class="pull-right">'.$actions.'</div>',
-                                get_lang('CreationDate').': '.
-                                Display::dateToStringAgoAndLongDate($row['creation_date']).$updateValue.$author
+                            $row['description'],
+                            $row['title'].$sessionImg.' <div class="pull-right">'.$actions.'</div>',
+                            get_lang('CreationDate').': '.
+                            Display::dateToStringAgoAndLongDate($row['creation_date']).$updateValue.$author
                         );
                     }
                 }
@@ -485,7 +484,6 @@ class NotebookTeacher
             if (Database::num_rows($result) > 0) {
                 echo Display::page_subheader($plugin->get_lang('NotebookNoStudentAssigned'));
                 while ($row = Database::fetch_array($result)) {
-
                     // Validation when belongs to a session
                     $sessionImg = api_get_session_image($row['session_id'], $userInfo['status']);
                     $updateValue = '';
@@ -497,7 +495,7 @@ class NotebookTeacher
 
                     $userInfo = api_get_user_info($row['user_id']);
                     $author = ', '.get_lang('Teacher').': '.$userInfo['complete_name'];
-
+                    $actions = '';
                     if (intval($row['user_id']) == api_get_user_id()) {
                         $actions = '<a href="'.api_get_self().
                                 '?action=editnote&notebook_id='.$row['id'].'&'.api_get_cidreq().'">'.
@@ -506,15 +504,12 @@ class NotebookTeacher
                                 '?action=deletenote&notebook_id='.$row['id'].
                                 '" onclick="return confirmation(\''.$row['title'].'\');">'.
                                 Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
-                    } else {
-                        $actions = '';
                     }
-
                     echo Display::panel(
-                            $row['description'],
-                            $row['title'].$sessionImg.' <div class="pull-right">'.$actions.'</div>',
-                            get_lang('CreationDate').': '.
-                            Display::dateToStringAgoAndLongDate($row['creation_date']).$updateValue.$author
+                        $row['description'],
+                        $row['title'].$sessionImg.' <div class="pull-right">'.$actions.'</div>',
+                        get_lang('CreationDate').': '.
+                        Display::dateToStringAgoAndLongDate($row['creation_date']).$updateValue.$author
                     );
                 }
             }

+ 7 - 14
plugin/notebookteacher/src/notebookteacher_plugin.class.php → plugin/notebookteacher/src/NotebookTeacherPlugin.php

@@ -1,15 +1,12 @@
 <?php
 /* For license terms, see /license.txt */
+
 /**
- * Description of notebookteacher_plugin.
- *
+ * Plugin class for the NotebookTeacher plugin.
  * @package chamilo.plugin.notebookteacher
  *
  * @author Jose Angel Ruiz <desarrollo@nosolored.com>
  */
-/**
- * Plugin class for the NotebookTeacher plugin.
- */
 class NotebookTeacherPlugin extends Plugin
 {
     const TABLE_NOTEBOOKTEACHER = 'plugin_notebook_teacher';
@@ -19,7 +16,7 @@ class NotebookTeacherPlugin extends Plugin
     {
         parent::__construct(
             '1.1',
-            'Jose Angel Ruiz - NoSoloRed (original author)',
+            'Jose Angel Ruiz - NoSoloRed (original author), Julio Montoya',
             [
                 'enable_plugin_notebookteacher' => 'boolean',
             ]
@@ -29,7 +26,7 @@ class NotebookTeacherPlugin extends Plugin
     }
 
     /**
-     * @return StaticPlugin
+     * @return NotebookTeacherPlugin
      */
     public static function create()
     {
@@ -46,9 +43,7 @@ class NotebookTeacherPlugin extends Plugin
         //Installing course settings
         $this->install_course_fields_in_all_courses();
 
-        $tablesToBeCompared = [
-                self::TABLE_NOTEBOOKTEACHER,
-        ];
+        $tablesToBeCompared = [self::TABLE_NOTEBOOKTEACHER];
         $em = Database::getManager();
         $cn = $em->getConnection();
         $sm = $cn->getSchemaManager();
@@ -79,12 +74,10 @@ class NotebookTeacherPlugin extends Plugin
      */
     public function uninstall()
     {
-        //Deleting course settings
+        // Deleting course settings.
         $this->uninstall_course_fields_in_all_courses($this->course_settings);
 
-        $tablesToBeDeleted = [
-            TABLE_NOTEBOOKTEACHER,
-        ];
+        $tablesToBeDeleted = [TABLE_NOTEBOOKTEACHER];
         foreach ($tablesToBeDeleted as $tableToBeDeleted) {
             $table = Database::get_main_table($tableToBeDeleted);
             $sql = "DROP TABLE IF EXISTS $table";

+ 0 - 7
plugin/notebookteacher/src/index.notebookteacher.php

@@ -1,7 +0,0 @@
-<?php
-/* For license terms, see /license.txt */
-/**
- * Index of the Test to pdf plugin courses list.
- *
- * @package chamilo.plugin.notebookteacher
- */

+ 38 - 40
plugin/notebookteacher/src/index.php

@@ -1,9 +1,10 @@
 <?php
 /* For licensing terms, see /license.txt */
 
+use ChamiloSession as Session;
+
 $course_plugin = 'notebookteacher';
 require_once __DIR__.'/../config.php';
-require_once __DIR__.'/notebookteacher.lib.php';
 
 $_setting['student_view_enabled'] = 'false';
 
@@ -56,7 +57,7 @@ if ($enable) {
             $tool = 'ModifyNote';
             $interbreadcrumb[] = [
                 'url' => 'index.php?'.api_get_cidreq(),
-                'name' => $plugin->get_lang('NotebookTeacher')
+                'name' => $plugin->get_lang('NotebookTeacher'),
             ];
         }
 
@@ -68,11 +69,11 @@ if ($enable) {
 
         // Action handling: Adding a note
         if ($action === 'addnote') {
-            if ((api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true) || api_is_drh())) {
+            if ((api_get_session_id() != 0 &&
+                !api_is_allowed_to_session_edit(false, true) || api_is_drh())) {
                 api_not_allowed();
             }
-
-            $_SESSION['notebook_view'] = 'creation_date';
+            Session::write('notebook_view', 'creation_date');
 
             $form = new FormValidator(
                 'note',
@@ -152,13 +153,13 @@ if ($enable) {
             }
 
             $form->addElement(
-                    'select',
-                    'student_id',
-                    get_lang('Student'),
-                    $studentList,
-                    [
-                        'id' => 'student_id',
-                    ]
+                'select',
+                'student_id',
+                get_lang('Student'),
+                $studentList,
+                [
+                    'id' => 'student_id',
+                ]
             );
 
             $form->addElement(
@@ -264,19 +265,19 @@ if ($enable) {
                 }
             } else {
                 $a_course_users = CourseManager::get_user_list_from_course_code(
-                        $courseCode,
-                        0,
-                        null,
-                        null,
-                        $status,
-                        null,
-                        false,
-                        false,
-                        null,
-                        null,
-                        null,
-                        $active
-                        );
+                    $courseCode,
+                    0,
+                    null,
+                    null,
+                    $status,
+                    null,
+                    false,
+                    false,
+                    null,
+                    null,
+                    null,
+                    $active
+                );
             }
 
             $studentList = [];
@@ -286,13 +287,13 @@ if ($enable) {
             }
 
             $form->addElement(
-                    'select',
-                    'student_id',
-                    get_lang('Student'),
-                    $studentList,
-                    [
-                       'id' => 'student_id',
-                    ]
+                'select',
+                'student_id',
+                get_lang('Student'),
+                $studentList,
+                [
+                    'id' => 'student_id',
+                ]
             );
 
             $form->addElement(
@@ -343,9 +344,7 @@ if ($enable) {
             }
 
             NotebookTeacher::displayNotes();
-        } elseif (
-            $action === 'changeview' && in_array($_GET['view'], ['creation_date', 'update_date', 'title'])) {
-
+        } elseif ($action === 'changeview' && in_array($_GET['view'], ['creation_date', 'update_date', 'title'])) {
             // Action handling: changing the view (sorting order)
             switch ($_GET['view']) {
                 case 'creation_date':
@@ -370,17 +369,15 @@ if ($enable) {
                     }
                     break;
             }
-            $_SESSION['notebook_view'] = $_GET['view'];
+            Session::write('notebook_view', Security::remove_XSS($_GET['view']));
             NotebookTeacher::displayNotes();
         } else {
             NotebookTeacher::displayNotes();
         }
-        
+
         Display::display_footer();
     } else {
-        /** @var \Chamilo\CoreBundle\Entity\Session $session */
-        $session = Database::getManager()
-            ->find('ChamiloCoreBundle:Session', api_get_session_id());
+        $session = api_get_session_entity(api_get_session_id());
         $_course = api_get_course_info();
         $web_course_path = api_get_path(WEB_COURSE_PATH);
         $url = $web_course_path.$_course['path'].'/index.php'.($session ? '?id_session='.$session->getId() : '');
@@ -390,6 +387,7 @@ if ($enable) {
         );
 
         header('Location: '.$url);
+        exit;
     }
 } else {
     echo $plugin->get_lang('ToolDisabled');

+ 4 - 5
plugin/notebookteacher/start.php

@@ -17,19 +17,18 @@ if ($enable) {
         header('Location: '.$url);
         exit;
     } else {
-        /** @var \Chamilo\CoreBundle\Entity\Session $session */
-        $session = Database::getManager()
-        ->find('ChamiloCoreBundle:Session', api_get_session_id());
+        $session = api_get_session_entity(api_get_session_id());
         $_course = api_get_course_info();
         $webCoursePath = api_get_path(WEB_COURSE_PATH);
         $url = $webCoursePath.$_course['path'].'/index.php'.($session ? '?id_session='.$session->getId() : '');
-        
+
         Display::addFlash(
             Display::return_message($plugin->get_lang('ToolForTeacher'))
         );
 
         header('Location: '.$url);
+        exit;
     }
 } else {
-    echo $plugin->get_lang('ToolDisabled');
+    api_not_allowed(true, $plugin->get_lang('ToolDisabled'));
 }

+ 2 - 3
plugin/notebookteacher/uninstall.php

@@ -1,5 +1,6 @@
 <?php
 /* For license terms, see /license.txt */
+
 /**
  * This script is included by main/admin/settings.lib.php when unselecting a plugin
  * and is meant to remove things installed by the install.php script in both
@@ -7,8 +8,6 @@
  *
  * @package chamilo.plugin.notebookteacher
  */
-/**
- * Queries.
- */
+
 require_once __DIR__.'/config.php';
 NotebookTeacherPlugin::create()->uninstall();

+ 3 - 4
plugin/notebookteacher/update.php

@@ -6,10 +6,9 @@
  *
  * @package chamilo.plugin.notebookteacher
  */
-/**
- * Initialization.
- */
-require_once __DIR__ . '/config.php';
+
+require_once __DIR__.'/config.php';
+
 if (!api_is_platform_admin()) {
     die('You must have admin permissions to install plugins');
 }