Browse Source

Merge pull request #17 from chamilo/1.9.x

1.9.x
ycastillo 11 years ago
parent
commit
d0593a750b
56 changed files with 2076 additions and 1982 deletions
  1. 66 51
      index.php
  2. 2 2
      main/admin/add_students_to_session.php
  3. 42 20
      main/admin/settings.lib.php
  4. 1 1
      main/admin/usergroups.php
  5. 11 2
      main/calendar/agenda.lib.php
  6. 33 32
      main/coursecopy/classes/CourseRestorer.class.php
  7. 6 2
      main/coursecopy/classes/CourseSelectForm.class.php
  8. 34 39
      main/coursecopy/copy_course.php
  9. 1 1
      main/cron/import_csv.php
  10. 3 3
      main/exercice/exercise.lib.php
  11. 27 7
      main/gradebook/lib/gradebook_functions.inc.php
  12. 45 38
      main/inc/ajax/model.ajax.php
  13. 11 5
      main/inc/ajax/work.ajax.php
  14. 7 7
      main/inc/lib/career.lib.php
  15. 35 33
      main/inc/lib/course.lib.php
  16. 1 0
      main/inc/lib/database.lib.php
  17. 21 5
      main/inc/lib/display.lib.php
  18. 35 1
      main/inc/lib/main_api.lib.php
  19. 213 199
      main/inc/lib/pdf.lib.php
  20. 69 37
      main/inc/lib/plugin.class.php
  21. 121 68
      main/inc/lib/plugin.lib.php
  22. 8 6
      main/inc/lib/sessionmanager.lib.php
  23. 383 307
      main/inc/lib/skill.lib.php
  24. 3 2
      main/inc/lib/usergroup.lib.php
  25. 20 16
      main/inc/lib/userportal.lib.php
  26. 47 25
      main/newscorm/learnpath.class.php
  27. 2 3
      main/newscorm/lp_content.php
  28. 7 7
      main/newscorm/resourcelinker.inc.php
  29. 7 3
      main/newscorm/scorm_api.php
  30. 15 1
      main/template/default/layout/layout_1_col.tpl
  31. 67 53
      main/template/default/layout/layout_2_col.tpl
  32. 19 16
      main/template/default/layout/login_form.tpl
  33. 3 3
      main/template/default/layout/main.tpl
  34. 1 1
      main/webservices/testip.php
  35. 1 1
      main/webservices/webservice.php
  36. 18 14
      main/work/add_user.php
  37. 1 5
      main/work/edit.php
  38. 125 0
      main/work/edit_work.php
  39. 283 444
      main/work/work.lib.php
  40. 56 448
      main/work/work.php
  41. 26 10
      main/work/work_list.php
  42. 0 2
      main/work/work_list_others.php
  43. 2 4
      plugin/add_cas_logout_button/plugin.php
  44. 2 4
      plugin/add_facebook_login_button/plugin.php
  45. 80 0
      plugin/before_login/index.php
  46. 51 0
      plugin/before_login/plugin.php
  47. 10 0
      plugin/before_login/readme.txt
  48. 14 0
      plugin/before_login/template.tpl
  49. 2 2
      plugin/ext_auth_chamilo_logout_button_behaviour/plugin.php
  50. 2 2
      plugin/hello_world/index.php
  51. 7 7
      plugin/hello_world/plugin.php
  52. 7 7
      plugin/share_buttons/plugin.php
  53. 2 2
      plugin/show_regions/index.php
  54. 10 10
      plugin/show_user_info/index.php
  55. 6 8
      plugin/show_user_info/plugin.php
  56. 5 16
      tests/main/work/work.lib.test.php

+ 66 - 51
index.php

@@ -5,7 +5,6 @@
  * @package chamilo.main
  */
 
-
 use \ChamiloSession as Session;
 
 define('CHAMILO_HOMEPAGE', true);
@@ -51,7 +50,7 @@ $controller = new IndexManager($header_title);
 $loginFailed = isset($_GET['loginFailed']) ? true : isset($loginFailed);
 
 if (!empty($_GET['logout'])) {
-	$controller->logout();
+    $controller->logout();
 }
 
 /* Table definitions */
@@ -67,19 +66,21 @@ $_setting['display_courses_to_anonymous_users'] = 'true';
 /**
  * Registers in the track_e_default table (view in important activities in admin
  * interface) a possible attempted break in, sending auth data through get.
- * @todo This piece of code should probably move to local.inc.php where the actual login / logout procedure is handled. The real use of this code block should be seriously considered as well. This form should just use a security token and get done with it.
+ * @todo This piece of code should probably move to local.inc.php where the actual login / logout procedure is handled.
+ * The real use of this code block should be seriously considered as well.
+ * This form should just use a security token and get done with it.
  */
 if (isset($_GET['submitAuth']) && $_GET['submitAuth'] == 1) {
-        $i = api_get_anonymous_id();
-        event_system(LOG_ATTEMPTED_FORCED_LOGIN, 'tried_hacking_get', $_SERVER['REMOTE_ADDR'].(empty($_POST['login'])?'':'/'.$_POST['login']),null,$i);
-	echo 'Attempted breakin - sysadmins notified.';
-	session_destroy();
-	die();
+    $i = api_get_anonymous_id();
+    event_system(LOG_ATTEMPTED_FORCED_LOGIN, 'tried_hacking_get', $_SERVER['REMOTE_ADDR'].(empty($_POST['login'])?'':'/'.$_POST['login']),null,$i);
+    echo 'Attempted breakin - sysadmins notified.';
+    session_destroy();
+    die();
 }
 
 // Delete session neccesary for legal terms
 if (api_get_setting('allow_terms_conditions') == 'true') {
-	unset($_SESSION['term_and_condition']);
+    unset($_SESSION['term_and_condition']);
 }
 //If we are not logged in and customapages activated
 if (!api_get_user_id() && CustomPages::enabled()) {
@@ -98,38 +99,38 @@ if (!api_get_user_id() && CustomPages::enabled()) {
  */
 
 if (!empty($_POST['submitAuth'])) {
-	// The user has been already authenticated, we are now to find the last login of the user.
-	if (isset ($_user['user_id'])) {
-		$track_login_table      = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-		$sql_last_login = "SELECT UNIX_TIMESTAMP(login_date)
+    // The user has been already authenticated, we are now to find the last login of the user.
+    if (isset ($_user['user_id'])) {
+        $track_login_table      = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+        $sql_last_login = "SELECT UNIX_TIMESTAMP(login_date)
                                 FROM $track_login_table
                                 WHERE login_user_id = '".$_user['user_id']."'
                                 ORDER BY login_date DESC LIMIT 1";
-		$result_last_login = Database::query($sql_last_login);
-		if (!$result_last_login) {
-			if (Database::num_rows($result_last_login) > 0) {
-				$user_last_login_datetime = Database::fetch_array($result_last_login);
-				$user_last_login_datetime = $user_last_login_datetime[0];
-				Session::write('user_last_login_datetime',$user_last_login_datetime);
-			}
-		}
-		Database::free_result($result_last_login);
-
-		//event_login();
-		if (api_is_platform_admin()) {
-			// decode all open event informations and fill the track_c_* tables
-			include api_get_path(LIBRARY_PATH).'stats.lib.inc.php';
-			decodeOpenInfos();
-		}
-	}
-	// End login -- if ($_POST['submitAuth'])
+        $result_last_login = Database::query($sql_last_login);
+        if (!$result_last_login) {
+            if (Database::num_rows($result_last_login) > 0) {
+                $user_last_login_datetime = Database::fetch_array($result_last_login);
+                $user_last_login_datetime = $user_last_login_datetime[0];
+                Session::write('user_last_login_datetime', $user_last_login_datetime);
+            }
+        }
+        Database::free_result($result_last_login);
+
+        //event_login();
+        if (api_is_platform_admin()) {
+            // decode all open event informations and fill the track_c_* tables
+            include api_get_path(LIBRARY_PATH).'stats.lib.inc.php';
+            decodeOpenInfos();
+        }
+    }
+    // End login -- if ($_POST['submitAuth'])
 } else {
-	// Only if login form was not sent because if the form is sent the user was already on the page.
-	event_open();
+    // Only if login form was not sent because if the form is sent the user was already on the page.
+    event_open();
 }
 
 if (api_get_setting('display_categories_on_homepage') == 'true') {
-	$controller->tpl->assign('course_category_block', $controller->return_courses_in_categories());
+    $controller->tpl->assign('course_category_block', $controller->return_courses_in_categories());
 }
 
 // Facebook connexion, if activated
@@ -137,18 +138,32 @@ if (api_is_facebook_auth_activated() && !api_get_user_id()) {
     facebook_connect();
 }
 
-$controller->set_login_form();
+// before login plugin conditions
+$showLoginForm = true;
+if (api_is_anonymous()) {
+    if (!isset($_SESSION['before_login_accepted'])) {
+        if (in_array('before_login', $controller->tpl->plugin->get_installed_plugins())) {
+            $languageToActivate = api_get_plugin_setting('before_login', 'language');
+            if (api_get_interface_language() == $languageToActivate) {
+                $showLoginForm = false;
+            }
+        }
+    }
+}
+
+
+$controller->set_login_form($showLoginForm);
 
 //@todo move this inside the IndexManager
 if (!api_is_anonymous()) {
-	$controller->tpl->assign('profile_block', $controller->return_profile_block());
-    $controller->tpl->assign('user_image_block', $controller->return_user_image_block());    
-
-	if (api_is_platform_admin()) {
-		$controller->tpl->assign('course_block',			$controller->return_course_block());
-	} else {
-		$controller->tpl->assign('teacher_block', 			$controller->return_teacher_link());
-	}
+    $controller->tpl->assign('profile_block', $controller->return_profile_block());
+    $controller->tpl->assign('user_image_block', $controller->return_user_image_block());
+
+    if (api_is_platform_admin()) {
+        $controller->tpl->assign('course_block', $controller->return_course_block());
+    } else {
+        $controller->tpl->assign('teacher_block', $controller->return_teacher_link());
+    }
 }
 
 $hot_courses = null;
@@ -163,18 +178,18 @@ if (!isset($_REQUEST['include'])) {
     $announcements_block = $controller->return_announcements();
 }
 
-$controller->tpl->assign('hot_courses',             $hot_courses);
-$controller->tpl->assign('announcements_block', 	$announcements_block);
-$controller->tpl->assign('home_page_block', 		$controller->return_home_page());
+$controller->tpl->assign('hot_courses', $hot_courses);
+$controller->tpl->assign('announcements_block', $announcements_block);
+$controller->tpl->assign('home_page_block', $controller->return_home_page());
 
-$controller->tpl->assign('navigation_course_links', 	$controller->return_navigation_links());
+$controller->tpl->assign('navigation_course_links', $controller->return_navigation_links());
 
-$controller->tpl->assign('notice_block',			$controller->return_notice());
-$controller->tpl->assign('main_navigation_block',	$controller->return_navigation_links());
-$controller->tpl->assign('help_block',              $controller->return_help());
+$controller->tpl->assign('notice_block', $controller->return_notice());
+$controller->tpl->assign('main_navigation_block', $controller->return_navigation_links());
+$controller->tpl->assign('help_block', $controller->return_help());
 
 if (api_is_platform_admin() || api_is_drh()) {
-    $controller->tpl->assign('skills_block',            $controller->return_skills_links());
+    $controller->tpl->assign('skills_block', $controller->return_skills_links());
 }
 
 $controller->tpl->display_two_col_template();

+ 2 - 2
main/admin/add_students_to_session.php

@@ -80,7 +80,7 @@ echo Display::input('hidden', 'form_sent', '1');
                      'sessions[]',
                      $sessionList,
                      '',
-                     array('style'=>'width:360px',  'id'=>'sessions', 'size'=>'15px'),
+                     array('style'=>'width:360px', 'multiple'=>'multiple', 'id'=>'sessions', 'size'=>'15px'),
                      false
                  );
                 ?>
@@ -93,7 +93,7 @@ echo Display::input('hidden', 'form_sent', '1');
                     'sessions_destination[]',
                     $sessionList,
                     '',
-                    array('style'=>'width:360px', 'multiple'=>'multiple', 'id'=>'courses', 'size'=>'15px'),
+                    array('style'=>'width:360px', 'id'=>'courses', 'size'=>'15px'),
                     false
                 );
                 ?>

+ 42 - 20
main/admin/settings.lib.php

@@ -15,14 +15,21 @@
  * This function allows easy activating and inactivating of regions
  * @author Julio Montoya <gugli100@gmail.com> Beeznest 2012
  */
-function handle_regions() {
+function handle_regions()
+{
 
     if (isset($_POST['submit_plugins'])) {
         store_regions();
         // Add event to the system log.
         $user_id = api_get_user_id();
         $category = $_GET['category'];
-        event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
+        event_system(
+            LOG_CONFIGURATION_SETTINGS_CHANGE,
+            LOG_CONFIGURATION_SETTINGS_CATEGORY,
+            $category,
+            api_get_utc_datetime(),
+            $user_id
+        );
         Display :: display_confirmation_message(get_lang('SettingsStored'));
     }
 
@@ -30,11 +37,12 @@ function handle_regions() {
     $possible_plugins  = $plugin_obj->read_plugins_from_path();
     $installed_plugins = $plugin_obj->get_installed_plugins();
 
-    if (!empty($installed_plugins)) {
+    /*if (!empty($installed_plugins)) {
         $not_installed = array_diff($possible_plugins, $installed_plugins);
     } else {
         $not_installed = $possible_plugins;
-    }
+    }*/
+
     echo '<form name="plugins" method="post" action="'.api_get_self().'?category='.Security::remove_XSS($_GET['category']).'">';
     echo '<table class="data_table">';
     echo '<tr>';
@@ -54,7 +62,7 @@ function handle_regions() {
         $plugin_region_list[$plugin_item] = $plugin_item;
     }
 
-    //Removing course tool
+    // Removing course tool
     unset($plugin_region_list['course_tool_plugin']);
 
     foreach ($installed_plugins as $plugin) {
@@ -88,7 +96,8 @@ function handle_regions() {
     echo '<button class="save" type="submit" name="submit_plugins">'.get_lang('EnablePlugins').'</button></form>';
 }
 
-function handle_extensions() {
+function handle_extensions()
+{
     echo Display::page_subheader(get_lang('ConfigureExtensions'));
     echo '<a class="btn" href="configure_extensions.php?display=ppt2lp">'.get_lang('Ppt2lp').'</a>';
 
@@ -99,7 +108,8 @@ function handle_extensions() {
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  * @author Julio Montoya <gugli100@gmail.com> Beeznest 2012
  */
-function handle_plugins() {
+function handle_plugins()
+{
     $plugin_obj = new AppPlugin();
 
      if (isset($_POST['submit_plugins'])) {
@@ -183,7 +193,8 @@ function handle_plugins() {
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  * @author Julio Montoya <gugli100@gmail.com>, Chamilo
 */
-function handle_stylesheets() {
+function handle_stylesheets()
+{
     global $_configuration;
 
     // Current style.
@@ -287,10 +298,10 @@ function handle_stylesheets() {
                 }
             }
         }
-        @closedir($handle);
+        closedir($handle);
     }
 
-    //Sort styles in alphabetical order
+    // Sort styles in alphabetical order.
     asort($list_of_names);
     $select_list = array();
     foreach ($list_of_names as $style_dir=>$item) {
@@ -351,7 +362,8 @@ function handle_stylesheets() {
  * @version May 2008
  * @since Dokeos 1.8.5
  */
-function upload_stylesheet($values, $picture) {
+function upload_stylesheet($values, $picture)
+{
     $result = false;
     // Valid name for the stylesheet folder.
     $style_name = api_preg_replace('/[^A-Za-z0-9]/', '', $values['name_stylesheet']);
@@ -403,7 +415,8 @@ function upload_stylesheet($values, $picture) {
                     $extraction_path = api_get_path(SYS_CODE_PATH).'css/'.$style_name.'/';
                     for ($i = 0; $i < $num_files; $i++) {
                         $entry = $zip->getNameIndex($i);
-                        if (substr($entry, -1) == '/') continue;
+                        if (substr($entry, -1) == '/')
+                            continue;
 
                         $pos_slash = strpos($entry, '/');
                         $entry_without_first_dir = substr($entry, $pos_slash + 1);
@@ -440,7 +453,11 @@ function upload_stylesheet($values, $picture) {
     return $result;
 }
 
-function store_regions() {
+/**
+ * Store plugin regions.
+ */
+function store_regions()
+{
      $plugin_obj = new AppPlugin();
 
     // Get a list of all current 'Plugins' settings
@@ -477,7 +494,8 @@ function store_regions() {
  * This function allows easy activating and inactivating of plugins
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 */
-function store_plugins() {
+function store_plugins()
+{
     $plugin_obj = new AppPlugin();
 
     // Get a list of all current 'Plugins' settings
@@ -506,7 +524,8 @@ function store_plugins() {
  * This function allows the platform admin to choose which should be the default stylesheet
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 */
-function store_stylesheets() {
+function store_stylesheets()
+{
     // Insert the stylesheet.
     $style = Database::escape_string($_POST['style']);
     if (is_style($style)) {
@@ -521,7 +540,8 @@ function store_stylesheets() {
  * @param string    Style
  * @return bool     True if this style is recognized, false otherwise
  */
-function is_style($style) {
+function is_style($style)
+{
     $dir = api_get_path(SYS_PATH).'main/css/';
     $dirs = scandir($dir);
     $style = str_replace(array('/', '\\'), array('', ''), $style); // Avoid slashes or backslashes.
@@ -536,7 +556,8 @@ function is_style($style) {
  * TODO: support for multiple site. aka $_configuration['access_url'] == 1
  * @author Marco Villegas <marvil07@gmail.com>
  */
-function handle_search() {
+function handle_search()
+{
     global $SettingsStored, $_configuration;
 
     require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
@@ -1281,7 +1302,7 @@ function generate_settings_form($settings, $settings_by_access_list) {
                 }
 
                 $form->addElement('file', 'pdf_export_watermark_path', get_lang('AddWaterMark'));
-                $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
+                $allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
                 $form->addRule('pdf_export_watermark_path', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
 
                 break;
@@ -1303,11 +1324,12 @@ function generate_settings_form($settings, $settings_by_access_list) {
 }
 
 /**
- * Searchs a platform setting in all categories except from the Plugins category
+ * Searches a platform setting in all categories except from the Plugins category
  * @param string $search
  * @return array
  */
-function search_setting($search) {
+function search_setting($search)
+{
     if (empty($search)) {
         return array();
     }

+ 1 - 1
main/admin/usergroups.php

@@ -57,7 +57,7 @@ $column_model   = array(
     array('name'=>'users',    		'index'=>'users', 		'width'=>'15',  'align'=>'left'),
     array('name'=>'courses',    	'index'=>'courses', 	'width'=>'15',  'align'=>'left'),
     array('name'=>'sessions',    	'index'=>'sessions', 	'width'=>'15',  'align'=>'left'),
-    array('name'=>'actions',        'index'=>'actions',     'width'=>'20',  'align'=>'left','sortable'=>'false','formatter'=>'action_formatter'),
+    array('name'=>'actions',        'index'=>'actions',     'width'=>'20',  'align'=>'left', 'sortable'=>'false','formatter'=>'action_formatter'),
 );
 
 //Autowidth

+ 11 - 2
main/calendar/agenda.lib.php

@@ -56,10 +56,19 @@ class Agenda
      * @param   string  content
      * @param   array   users to send array('everyone') or a list of user ids
      * @param   bool    add event as a *course* announcement
+     * @return int
      *
      */
-    public function add_event($start, $end, $all_day, $view, $title, $content, $users_to_send = array(), $add_as_announcement = false)
-    {
+    public function add_event(
+        $start,
+        $end,
+        $all_day,
+        $view,
+        $title,
+        $content,
+        $users_to_send = array(),
+        $add_as_announcement = false
+    ) {
         $start = api_get_utc_datetime($start);
         $end = api_get_utc_datetime($end);
         $all_day = isset($all_day) && $all_day == 'true' ? 1 : 0;

+ 33 - 32
main/coursecopy/classes/CourseRestorer.class.php

@@ -30,10 +30,10 @@ require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(LIBRARY_PATH).'document.lib.php';
 
-define('FILE_SKIP',             1);
-define('FILE_RENAME',           2);
-define('FILE_OVERWRITE',        3);
-define('UTF8_CONVERT', 		false); //false by default
+define('FILE_SKIP', 1);
+define('FILE_RENAME', 2);
+define('FILE_OVERWRITE', 3);
+define('UTF8_CONVERT', false); //false by default
 
 /**
  * Class to restore items from a course object to a Chamilo-course
@@ -43,16 +43,17 @@ define('UTF8_CONVERT', 		false); //false by default
  */
 class CourseRestorer
 {
-	/**
-	 * The course-object
-	 */
+    /**
+     * The course-object
+     */
+    /** @var Course */
     public $course;
     public $destination_course_info;
 
-	/**
-	 * What to do with files with same name (FILE_SKIP, FILE_RENAME or
-	 * FILE_OVERWRITE)
-	 */
+    /**
+     * What to do with files with same name (FILE_SKIP, FILE_RENAME or
+     * FILE_OVERWRITE)
+     */
     public $file_option;
     public $set_tools_invisible_by_default;
     public $skip_content;
@@ -91,26 +92,26 @@ class CourseRestorer
 	 */
     public function __construct($course)
     {
-		$this->course							= $course;
-		$course_info 							= api_get_course_info($this->course->code);
+        $this->course							= $course;
+        $course_info 							= api_get_course_info($this->course->code);
         if (!empty($course_info)) {
-		    $this->course_origin_id 				= $course_info['real_id'];
+            $this->course_origin_id 				= $course_info['real_id'];
         } else {
             $this->course_origin_id = null;
         }
-		$this->file_option 						= FILE_RENAME;
-		$this->set_tools_invisible_by_default 	= false;
-		$this->skip_content 					= array();
-	}
+        $this->file_option 						= FILE_RENAME;
+        $this->set_tools_invisible_by_default 	= false;
+        $this->skip_content 					= array();
+    }
 
-	/**
-	 * Set the file-option
-	 * @param constant $options What to do with files with same name (FILE_SKIP, FILE_RENAME or FILE_OVERWRITE)
-	 */
+    /**
+     * Set the file-option
+     * @param constant $options What to do with files with same name (FILE_SKIP, FILE_RENAME or FILE_OVERWRITE)
+     */
     function set_file_option($option)
     {
-		$this->file_option = $option;
-	}
+        $this->file_option = $option;
+    }
     function set_add_text_in_items($status)
     {
         $this->add_text_in_items = $status;
@@ -120,13 +121,13 @@ class CourseRestorer
         $this->tool_copy_settings = $array;
     }
 
-	/**
-	 * Restore a course.
-	 * @param 	string 	The code of the Chamilo-course in
-	 * @param	int		The session id
-	 * @param	bool	Course settings are going to be restore?
-
-	 */
+    /**
+     * Restore a course.
+     * @param 	string 	The code of the Chamilo-course in
+     * @param	int		The session id
+     * @param	bool	Course settings are going to be restore.
+     * @param bool $respect_base_content
+     */
     public function restore(
         $destination_course_code = '',
         $session_id = 0,
@@ -144,7 +145,7 @@ class CourseRestorer
 		}
 		$this->destination_course_id = $course_info['real_id'];
 
-        //Getting first teacher (for the forums)
+        // Getting first teacher (for the forums)
         $teacher_list = CourseManager::get_teacher_list_from_course_code($course_info['code']);
         $this->first_teacher_id = api_get_user_id();
 

+ 6 - 2
main/coursecopy/classes/CourseSelectForm.class.php

@@ -16,7 +16,7 @@ class CourseSelectForm
 	 * @param array $hidden_fiels Hidden fields to add to the form.
 	 * @param boolean the document array will be serialize. This is used in the course_copy.php file
 	 */
-	static function display_form($course, $hidden_fields = null, $avoid_serialize=false)
+	static function display_form($course, $hidden_fields = null, $avoid_serialize = false)
     {
         global $charset;
 		$resource_titles[RESOURCE_EVENT]                = get_lang('Events');
@@ -141,6 +141,7 @@ class CourseSelectForm
 		}
         echo '<script src="'.api_get_path(WEB_CODE_PATH).'inc/lib/javascript/upload.js" type="text/javascript"></script>';
 		echo '<script type="text/javascript">var myUpload = new upload(1000);</script>';
+
 		echo '<form method="post" id="upload_form" name="course_select_form" onsubmit="javascript: myUpload.start(\'dynamic_div\',\''.api_get_path(WEB_CODE_PATH).'img/progress_bar.gif\',\''.get_lang('PleaseStandBy', '').'\',\'upload_form\')">';
 		echo '<input type="hidden" name="action" value="course_select_form"/>';
 
@@ -348,10 +349,13 @@ class CourseSelectForm
 	/**
 	 * Get the posted course
 	 * @param string who calls the function? It can be copy_course, create_backup, import_backup or recycle_course
+     * @param int
+     * @param string
 	 * @return course The course-object with all resources selected by the user
 	 * in the form given by display_form(...)
 	 */
-	static function get_posted_course($from = '', $session_id = 0, $course_code = '') {
+	static function get_posted_course($from = '', $session_id = 0, $course_code = '')
+    {
         $course = null;
 
         if (isset($_POST['course'])) {

+ 34 - 39
main/coursecopy/copy_course.php

@@ -22,13 +22,13 @@ require_once 'classes/CourseSelectForm.class.php';
 
 // Notice for unauthorized people.
 if (!api_is_allowed_to_edit()) {
-	api_not_allowed(true);
+    api_not_allowed(true);
 }
 
 // Remove memory and time limits as much as possible as this might be a long process...
 if (function_exists('ini_set')) {
-	api_set_memory_limit('256M');
-	ini_set('max_execution_time', 1800);
+    api_set_memory_limit('256M');
+    ini_set('max_execution_time', 1800);
     //ini_set('post_max_size', "512M");
 }
 
@@ -46,46 +46,45 @@ echo Display::page_header(get_lang('CopyCourse'));
 
 // If a CourseSelectForm is posted or we should copy all resources, then copy them
 if ((isset($_POST['action']) && $_POST['action'] == 'course_select_form') || (isset($_POST['copy_option']) && $_POST['copy_option'] == 'full_copy')) {
-	if (isset($_POST['action']) && $_POST['action'] == 'course_select_form') {
-		$course = CourseSelectForm :: get_posted_course('copy_course');
-	} else {
-		$cb = new CourseBuilder();
-		$course = $cb->build();
-	}
-	$cr = new CourseRestorer($course);
-	$cr->set_file_option($_POST['same_file_name_option']);
-	$cr->restore($_POST['destination_course']);
-	Display::display_normal_message(get_lang('CopyFinished').': <a href="'.api_get_course_url($_POST['destination_course']).'">'.$_POST['destination_course'].'</a>',false);
+    if (isset($_POST['action']) && $_POST['action'] == 'course_select_form') {
+        $course = CourseSelectForm::get_posted_course('copy_course');
+    } else {
+        $cb = new CourseBuilder();
+        $course = $cb->build();
+    }
+    $cr = new CourseRestorer($course);
+    $cr->set_file_option($_POST['same_file_name_option']);
+    $cr->restore($_POST['destination_course']);
+    Display::display_normal_message(get_lang('CopyFinished').': <a href="'.api_get_course_url($_POST['destination_course']).'">'.$_POST['destination_course'].'</a>', false);
 } elseif (isset ($_POST['copy_option']) && $_POST['copy_option'] == 'select_items') {
-	$cb = new CourseBuilder();
-	$course = $cb->build();
-
+    $cb = new CourseBuilder();
+    $course = $cb->build();
     $hidden_fields = array();
-	$hidden_fields['same_file_name_option'] = $_POST['same_file_name_option'];
-	$hidden_fields['destination_course']    = $_POST['destination_course'];
-	CourseSelectForm :: display_form($course, $hidden_fields, true);
+    $hidden_fields['same_file_name_option'] = $_POST['same_file_name_option'];
+    $hidden_fields['destination_course']    = $_POST['destination_course'];
+    CourseSelectForm::display_form($course, $hidden_fields, true);
 } else {
-	$table_c = Database :: get_main_table(TABLE_MAIN_COURSE);
-	$table_cu = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-	$user_info = api_get_user_info();
-	$course_info = api_get_course_info();
-	$sql = 'SELECT * FROM '.$table_c.' c, '.$table_cu.' cu WHERE cu.course_code = c.code';
-	if (!api_is_platform_admin()) {
-		$sql .= ' AND cu.status=1 ';
-	}
-	$sql .= ' AND target_course_code IS NULL AND cu.user_id = '.$user_info['user_id'].' AND c.code != '."'".$course_info['sysCode']."'".' ORDER BY title ASC';
-	$res = Database::query($sql);
-	if (Database::num_rows($res) == 0) {
-		Display::display_normal_message(get_lang('NoDestinationCoursesAvailable'));
-	} else {
+    $table_c = Database :: get_main_table(TABLE_MAIN_COURSE);
+    $table_cu = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+    $user_info = api_get_user_info();
+    $course_info = api_get_course_info();
+    $sql = 'SELECT * FROM '.$table_c.' c, '.$table_cu.' cu WHERE cu.course_code = c.code';
+    if (!api_is_platform_admin()) {
+        $sql .= ' AND cu.status=1 ';
+    }
+    $sql .= ' AND target_course_code IS NULL AND cu.user_id = '.$user_info['user_id'].' AND c.code != '."'".$course_info['sysCode']."'".' ORDER BY title ASC';
+    $res = Database::query($sql);
+    if (Database::num_rows($res) == 0) {
+        Display::display_normal_message(get_lang('NoDestinationCoursesAvailable'));
+    } else {
         $options = array();
         while ($obj = Database::fetch_object($res)) {
             $options[$obj->code] = $obj->title;
         }
 
         $form = new FormValidator('copy_course', 'post', 'copy_course.php?'.api_get_cidreq());
-        $form->addElement('header','' );
-        $form->addElement('select','destination_course', get_lang('SelectDestinationCourse'), $options);
+        $form->addElement('header', '');
+        $form->addElement('select', 'destination_course', get_lang('SelectDestinationCourse'), $options);
 
         $group = array();
         $group[] = $form->createElement('radio', 'copy_option', null, get_lang('FullCopy'), 'full_copy');
@@ -97,14 +96,10 @@ if ((isset($_POST['action']) && $_POST['action'] == 'course_select_form') || (is
         $group[] = $form->createElement('radio', 'same_file_name_option', null, get_lang('SameFilenameRename'), FILE_RENAME);
         $group[] = $form->createElement('radio', 'same_file_name_option', null, get_lang('SameFilenameOverwrite'), FILE_OVERWRITE);
         $form->addGroup($group, '', get_lang('SameFilename'));
-
-        $form->addElement('style_submit_button', 'submit', get_lang('CopyCourse'),'class="save"');
-
+        $form->addElement('style_submit_button', 'submit', get_lang('CopyCourse'), 'class="save"');
         $form->setDefaults(array('copy_option' =>'select_items','same_file_name_option' => FILE_OVERWRITE));
         $form->display();
-
 	}
 }
 
-/*	FOOTER	*/
 Display::display_footer();

+ 1 - 1
main/cron/import_csv.php

@@ -621,7 +621,7 @@ class ImportCsv
                 $chamiloUserName = $row['UserName'];
                 $chamiloCourseCode = $row['CourseCode'];
                 //$systemSessionId= $row['SessionID'];
-                $chamiloSessionId= $row['SessionID'];
+                $chamiloSessionId = $row['SessionID'];
 
                 //$sessionId = SessionManager::get_session_id_from_original_id($systemSessionId, $this->extraFieldIdNameList['session']);
                 $sessionInfo = api_get_session_info($chamiloSessionId);

+ 3 - 3
main/exercice/exercise.lib.php

@@ -870,11 +870,9 @@ function get_exam_results_hotpotatoes_data($in_from, $in_number_of_items, $in_co
     }
 
     $TBL_TRACK_HOTPOTATOES      = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
-    $TBL_GROUP_REL_USER         = Database :: get_course_table(TABLE_GROUP_USER);
-    $TBL_GROUP                  = Database :: get_course_table(TABLE_GROUP);
     $TBL_USER                   = Database :: get_main_table(TABLE_MAIN_USER);
 
-    $sql .= "SELECT * FROM $TBL_TRACK_HOTPOTATOES thp JOIN $TBL_USER u ON thp.exe_user_id = u.user_id WHERE thp.exe_cours_id = '$course_code' AND exe_name LIKE '$in_hotpot_path%'";
+    $sql = "SELECT * FROM $TBL_TRACK_HOTPOTATOES thp JOIN $TBL_USER u ON thp.exe_user_id = u.user_id WHERE thp.exe_cours_id = '$course_code' AND exe_name LIKE '$in_hotpot_path%'";
 
     // just count how many answers
     if ($in_get_count) {
@@ -882,6 +880,8 @@ function get_exam_results_hotpotatoes_data($in_from, $in_number_of_items, $in_co
         return Database::num_rows($res);
     }
 
+    $in_column = Database::escape_string($in_column);
+
     // get a number of sorted results
     $sql .= " $where_condition ORDER BY $in_column $in_direction  LIMIT $in_from, $in_number_of_items";
 

+ 27 - 7
main/gradebook/lib/gradebook_functions.inc.php

@@ -17,6 +17,7 @@ require_once 'gradebook_functions_users.inc.php';
 
 /**
  * Adds a resource to the unique gradebook of a given course
+ * @param   int
  * @param   string  Course code
  * @param   int     Resource type (use constants defined in linkfactory.class.php)
  * @param   int     Resource ID in the corresponding tool
@@ -24,12 +25,24 @@ require_once 'gradebook_functions_users.inc.php';
  * @param   int     Resource weight to set in the gradebook
  * @param   int     Resource max
  * @param   string  Resource description
- * @param   string  Date
  * @param   int     Visibility (0 hidden, 1 shown)
  * @param   int     Session ID (optional or 0 if not defined)
+ * @param   int
  * @return  boolean True on success, false on failure
  */
-function add_resource_to_course_gradebook($category_id, $course_code, $resource_type, $resource_id, $resource_name = '', $weight = 0, $max = 0, $resource_description = '', $visible = 0, $session_id = 0, $link_id = null) {
+function add_resource_to_course_gradebook(
+    $category_id,
+    $course_code,
+    $resource_type,
+    $resource_id,
+    $resource_name = '',
+    $weight = 0,
+    $max = 0,
+    $resource_description = '',
+    $visible = 0,
+    $session_id = 0,
+    $link_id = null
+) {
     $link = LinkFactory :: create($resource_type);
     $link->set_user_id(api_get_user_id());
     $link->set_course_code($course_code);
@@ -64,9 +77,12 @@ function add_resource_to_course_gradebook($category_id, $course_code, $resource_
 /**
  * Update a resource weight
  * @param    int     Link/Resource ID
+ * @param   string
+ * @param float
  * @return   bool    false on error, true on success
  */
-function update_resource_from_course_gradebook($link_id, $course_code, $weight) {
+function update_resource_from_course_gradebook($link_id, $course_code, $weight)
+{
     $course_code = Database::escape_string($course_code);
     if (!empty($link_id)) {
         $link_id = intval($link_id);
@@ -83,18 +99,21 @@ function update_resource_from_course_gradebook($link_id, $course_code, $weight)
  * @param    int     Link/Resource ID
  * @return   bool    false on error, true on success
  */
-function remove_resource_from_course_gradebook($link_id) {
+function remove_resource_from_course_gradebook($link_id)
+{
     if (empty($link_id)) {
         return false;
     }
+
     // TODO find the corresponding category (the first one for this course, ordered by ID)
     $l = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
-    $sql = "DELETE FROM $l WHERE id = " . (int) $link_id;
+    $sql = "DELETE FROM $l WHERE id = ".(int)$link_id;
     Database::query($sql);
     return true;
 }
 
-function block_students() {
+function block_students()
+{
     if (!api_is_allowed_to_edit()) {
         api_not_allowed();
     }
@@ -104,7 +123,8 @@ function block_students() {
  * Returns the course name from a given code
  * @param string $code
  */
-function get_course_name_from_code($code) {
+function get_course_name_from_code($code)
+{
     $tbl_main_categories = Database :: get_main_table(TABLE_MAIN_COURSE);
     $sql = 'SELECT title, code FROM ' . $tbl_main_categories . 'WHERE code = "' . Database::escape_string($code) . '"';
     $result = Database::query($sql);

+ 45 - 38
main/inc/ajax/model.ajax.php

@@ -36,6 +36,8 @@ if (!in_array(
     array(
         'get_exercise_results',
         'get_hotpotatoes_exercise_results',
+        'get_work_teacher',
+        'get_work_student',
         'get_work_user_list',
         'get_work_user_list_others',
         'get_work_user_list_all',
@@ -47,7 +49,7 @@ if (!in_array(
     api_protect_admin_script(true);
 }
 
-//Search features
+// Search features
 
 $ops = array (
     'eq' => '=',        //equal
@@ -116,7 +118,9 @@ if ($_REQUEST['_search'] == 'true') {
 
 // get index row - i.e. user click to sort $sord = $_GET['sord'];
 // get the direction
-if (!$sidx) $sidx = 1;
+if (!$sidx) {
+    $sidx = 1;
+}
 
 //2. Selecting the count FIRST
 //@todo rework this
@@ -135,6 +139,15 @@ switch ($action) {
     case 'get_user_skill_ranking':
         $skill = new Skill();
         $count = $skill->get_user_list_skill_ranking_count();
+        break;
+    case 'get_work_teacher':
+        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
+        $count = getWorkListTeacher($start, $limit, $sidx, $sord, $where_condition, true);
+        break;
+    case 'get_work_student':
+        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
+        $count = getWorkListStudent($start, $limit, $sidx, $sord, $where_condition, true);
+
         break;
     case 'get_work_user_list_all':
         require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
@@ -246,7 +259,7 @@ if ($page > $total_pages) {
 }
 
 $start = $limit * $page - $limit;
-if ($start < 0 ) {
+if ($start < 0) {
 	$start = 0;
 }
 
@@ -293,17 +306,16 @@ switch ($action) {
         break;
 	case 'get_user_skill_ranking':
         $columns = array('photo', 'firstname', 'lastname', 'skills_acquired', 'currently_learning', 'rank');
-	    $result = $skill->get_user_list_skill_ranking($start, $limit, $sidx, $sord, $where_condition);
+        $result = $skill->get_user_list_skill_ranking($start, $limit, $sidx, $sord, $where_condition);
         $result = msort($result, 'skills_acquired', 'asc');
 
         $skills_in_course = array();
-	    if (!empty($result)) {
-    	    //$counter = 1;
-	        foreach ($result as &$item) {
+        if (!empty($result)) {
+            foreach ($result as &$item) {
                 $user_info = api_get_user_info($item['user_id']);
                 $personal_course_list = UserManager::get_personal_session_course_list($item['user_id']);
                 $count_skill_by_course = array();
-                foreach ($personal_course_list  as $course_item) {
+                foreach ($personal_course_list as $course_item) {
                     if (!isset($skills_in_course[$course_item['code']])) {
                         $count_skill_by_course[$course_item['code']] = $skill->get_count_skills_by_course($course_item['code']);
                         $skills_in_course[$course_item['code']] = $count_skill_by_course[$course_item['code']];
@@ -311,17 +323,23 @@ switch ($action) {
                         $count_skill_by_course[$course_item['code']] = $skills_in_course[$course_item['code']];
                     }
                 }
-	            $item['photo'] = Display::img($user_info['avatar_small']);
-	            $item['currently_learning'] = !empty($count_skill_by_course) ? array_sum($count_skill_by_course) : 0;
-	        }
-	    }
-    	break;
+                $item['photo'] = Display::img($user_info['avatar_small']);
+                $item['currently_learning'] = !empty($count_skill_by_course) ? array_sum($count_skill_by_course) : 0;
+            }
+        }
+        break;
+    case 'get_work_teacher':
+        $columns = array('type', 'title', 'expires_on', 'ends_on', 'actions');
+        $result = getWorkListTeacher($start, $limit, $sidx, $sord, $where_condition);
+        break;
+    case 'get_work_student':
+        $columns = array('type', 'title', 'expires_on', 'others', 'actions');
+        $result = getWorkListStudent($start, $limit, $sidx, $sord, $where_condition);
+        break;
     case 'get_work_user_list_all':
         if (isset($_GET['type'])  && $_GET['type'] == 'simple') {
-            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
             $columns = array('type', 'firstname', 'lastname', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
         } else {
-            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'sent_date', 'actions');
             $columns = array('type', 'firstname', 'lastname', 'title', 'sent_date', 'actions');
         }
         $result = get_work_user_list($start, $limit, $sidx, $sord, $work_id, $where_condition);
@@ -337,29 +355,24 @@ switch ($action) {
         break;
     case 'get_work_user_list':
         if (isset($_GET['type'])  && $_GET['type'] == 'simple') {
-            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
             $columns = array('type', 'firstname', 'lastname', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
         } else {
-            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'sent_date', 'actions');
             $columns = array('type', 'firstname', 'lastname', 'title', 'sent_date', 'actions');
         }
         $where_condition .= " AND u.user_id = ".api_get_user_id();
         $result = get_work_user_list($start, $limit, $sidx, $sord, $work_id, $where_condition);
         break;
 	case 'get_exercise_results':
-		$course = api_get_course_info();
+        $course = api_get_course_info();
         //used inside get_exam_results_data()
 		$documentPath = api_get_path(SYS_COURSE_PATH) . $course['path'] . "/document";
 		if ($is_allowedToEdit) {
 			$columns = array('firstname', 'lastname', 'username', 'group_name', 'exe_duration', 'start_date', 'exe_date', 'score', 'status', 'lp', 'actions');
-		} else {
-			//$columns = array('exe_duration', 'start_date', 'exe_date', 'score', 'status', 'actions');
 		}
 		$result = get_exam_results_data($start, $limit, $sidx, $sord, $exercise_id, $where_condition);
 		break;
 	case 'get_hotpotatoes_exercise_results':
 		$course = api_get_course_info();
-        //used inside get_exam_results_data()
 		$documentPath = api_get_path(SYS_COURSE_PATH) . $course['path'] . "/document";
 		$columns = array('firstname', 'lastname', 'username', 'group_name', 'exe_date',  'score', 'actions');
 		$result = get_exam_results_hotpotatoes_data($start, $limit, $sidx, $sord, $hotpot_path, $where_condition); //get_exam_results_data($start, $limit, $sidx, $sord, $exercise_id, $where_condition);
@@ -370,7 +383,6 @@ switch ($action) {
         break;
      case 'get_timelines':
         $columns = array('headline', 'actions');
-        //$columns = array('headline', 'type', 'start_date', 'end_date', 'text', 'media', 'media_credit', 'media_caption', 'title_slide', 'parent_id');
 
         if(!in_array($sidx, $columns)) {
         	$sidx = 'headline';
@@ -407,8 +419,6 @@ switch ($action) {
             //Fixes bug when gradebook doesn't have names
             if (empty($item['name'])) {
                 $item['name'] = $item['course_code'];
-            } else {
-                //$item['name'] =  $item['name'].' ['.$item['course_code'].']';
             }
 
             $item['name'] = Display::url($item['name'], api_get_path(WEB_CODE_PATH).'gradebook/index.php?id_session=0&cidReq='.$item['course_code']);
@@ -451,7 +461,7 @@ switch ($action) {
         break;
     case 'get_careers':
         $columns = array('name', 'description', 'actions');
-        if(!in_array($sidx, $columns)) {
+        if (!in_array($sidx, $columns)) {
         	$sidx = 'name';
         }
         $result     = Database::select('*', $obj->table, array('order'=>"$sidx $sord", 'LIMIT'=> "$start , $limit"));
@@ -469,7 +479,13 @@ switch ($action) {
         if(!in_array($sidx, $columns)) {
             $sidx = 'name';
         }
-        $result     = Database::select('p.id,p.name, p.description, c.name as career, p.status', "$obj->table p LEFT JOIN ".Database::get_main_table(TABLE_CAREER)." c  ON c.id = p.career_id ", array('order' =>"$sidx $sord", 'LIMIT'=> "$start , $limit"));
+
+        $result = Database::select(
+            'p.id,p.name, p.description, c.name as career, p.status',
+            "$obj->table p LEFT JOIN ".Database::get_main_table(TABLE_CAREER)." c  ON c.id = p.career_id ",
+            array('order' => "$sidx $sord", 'LIMIT'=> "$start , $limit")
+        );
+
         $new_result = array();
         foreach($result as $item) {
             if (!$item['status']) {
@@ -515,17 +531,6 @@ switch ($action) {
         $obj = new ExtraFieldOption($type);
         $columns = array('option_display_text', 'option_value', 'option_order');
         $result  = Database::select('*', $obj->table, array('where' => array("field_id = ? " => $field_id),'order'=>"$sidx $sord", 'LIMIT'=> "$start , $limit"));
-        /*$new_result = array();
-        if (!empty($result)) {
-            foreach ($result as $item) {
-                $item['field_type']         = $obj->get_field_type_by_id($item['field_type']);
-                $item['field_changeable']   = $item['field_changeable'] ? Display::return_icon('right.gif') : Display::return_icon('wrong.gif');
-                $item['field_visible']      = $item['field_visible'] ? Display::return_icon('right.gif') : Display::return_icon('wrong.gif');
-                $item['field_filter']       = $item['field_filter'] ? Display::return_icon('right.gif') : Display::return_icon('wrong.gif');
-                $new_result[]        = $item;
-            }
-            $result = $new_result;
-        }*/
         break;
     case 'get_usergroups_teacher':
         $columns = array('name', 'users', 'actions');
@@ -562,7 +567,7 @@ switch ($action) {
             $sidx = 'name';
         }
         //Multidimensional sort
-        msort($result, $sidx);
+        $result = msort($result, $sidx, $sord);
         break;
     default:
         exit;
@@ -577,6 +582,8 @@ $allowed_actions = array(
     'get_sessions',
     'get_exercise_results',
     'get_hotpotatoes_exercise_results',
+    'get_work_teacher',
+    'get_work_student',
     'get_work_user_list',
     'get_work_user_list_others',
     'get_work_user_list_all',

+ 11 - 5
main/inc/ajax/work.ajax.php

@@ -8,15 +8,21 @@ require_once '../global.inc.php';
 
 require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
 
-
 $action = isset($_REQUEST['a']) ? $_REQUEST['a'] : null;
 
-switch ($action) {
-	case 'get_work_user_list':        
-       
+$is_allowed_to_edit = api_is_allowed_to_edit();
 
-		break;	
+switch ($action) {
+    case 'delete_work':
+        if ($is_allowed_to_edit) {
+            $workList = explode(',', $_REQUEST['id']);
+            foreach ($workList as $workId) {
+                deleteDirWork($workId);
+            }
+        }
+        break;
     default:
         echo '';
+        break;
 }
 exit;

+ 7 - 7
main/inc/lib/career.lib.php

@@ -88,15 +88,15 @@ class Career extends Model
     }
 
     /**
-     * Returns a Form validator Obj
-     * @todo the form should be auto generated
-     * @param   string  url
-     * @param   string  action add, edit
-     * @return  obj     form validator obj
-     */
+    * Returns a Form validator Obj
+    * @todo the form should be auto generated
+    * @param   string  url
+    * @param   string  action add, edit
+    * @return  obj     form validator obj
+    */
     public function return_form($url, $action)
     {
-		$oFCKeditor = new FCKeditor('description') ;
+		$oFCKeditor = new FCKeditor('description');
 		$oFCKeditor->ToolbarSet = 'careers';
 		$oFCKeditor->Width		= '100%';
 		$oFCKeditor->Height		= '200';

+ 35 - 33
main/inc/lib/course.lib.php

@@ -26,16 +26,13 @@ require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
  *    CourseManager Class
  *    @package chamilo.library
  */
-class CourseManager {
-
-    CONST MAX_COURSE_LENGTH_CODE = 40;
-
-    //This constant is used to show separate user names in the course list (userportal), footer, etc
-    CONST USER_SEPARATOR = ' |';
-
-    CONST COURSE_FIELD_TYPE_CHECKBOX = 10;
-
-    var $columns = array();
+class CourseManager
+{
+    const MAX_COURSE_LENGTH_CODE = 40;
+    /** This constant is used to show separate user names in the course list (userportal), footer, etc */
+    const USER_SEPARATOR = ' |';
+    const COURSE_FIELD_TYPE_CHECKBOX = 10;
+    public $columns = array();
 
     /**
      * Creates a course
@@ -102,7 +99,7 @@ class CourseManager {
     }
 
     /**
-     * Returns all the information of a given coursecode
+     * Returns all the information of a given course code
      * @param string $course_code, the course code
      * @return an array with all the fields of the course table
      * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
@@ -225,13 +222,14 @@ class CourseManager {
     /**
      * Unsubscribe one or more users from a course
      *
-     * @param   mixed   user_id or an array with user ids
-     * @param   int     session id
+     * @param   int   user_id or an array with user ids
      * @param   string  course code
+     * @param   int     session id
      * @assert ('', '') === false
      *
      */
-    public static function unsubscribe_user($user_id, $course_code, $session_id = 0) {
+    public static function unsubscribe_user($user_id, $course_code, $session_id = 0)
+    {
 
         if (!is_array($user_id)) {
             $user_id = array($user_id);
@@ -239,20 +237,20 @@ class CourseManager {
         if (count($user_id) == 0) {
             return;
         }
-        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
+        $table_user = Database::get_main_table(TABLE_MAIN_USER);
 
         if (!empty($session_id)) {
             $session_id = intval($session_id);
         } else {
-            $session_id = intval($_SESSION['id_session']);
+            $session_id = api_get_session_id();
         }
 
         $user_list = array();
 
-        //Cleaning the $user_id variable
+        // Cleaning the $user_id variable
         if (is_array($user_id)) {
             $new_user_id_list = array();
-            foreach($user_id as $my_user_id) {
+            foreach ($user_id as $my_user_id) {
                 $new_user_id_list[]= intval($my_user_id);
             }
             $new_user_id_list = array_filter($new_user_id_list);
@@ -285,7 +283,6 @@ class CourseManager {
         $sql = "DELETE FROM $table_course_user_publication WHERE c_id = $course_id AND author = '".Database::escape_string($publication_name)."'";
         Database::query($sql);
 
-
         // Unsubscribe user from all blogs in the course.
         Database::query("DELETE FROM ".Database::get_course_table(TABLE_BLOGS_REL_USER)." WHERE c_id = $course_id AND  user_id IN (".$user_ids.")");
         Database::query("DELETE FROM ".Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER)." WHERE c_id = $course_id AND  user_id IN (".$user_ids.")");
@@ -365,6 +362,7 @@ class CourseManager {
         }
 
         $course_code = Database::escape_string($course_code);
+
         if (empty ($user_id) || empty ($course_code)) {
             return false;
         }
@@ -396,7 +394,7 @@ class CourseManager {
 
             // Check whether the user has not already been stored in the session_rel_course_user table
             if (Database::num_rows(@Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
-                    WHERE course_code = '".$_SESSION['_course']['id']."'
+                    WHERE course_code = '".$course_code."'
                     AND id_session ='".$session_id."'
                     AND id_user = '".$user_id."'")) > 0) {
                 return false;
@@ -417,7 +415,7 @@ class CourseManager {
             // Add him/her in the table session_rel_course_rel_user
             @Database::query("INSERT INTO ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
                     SET id_session ='".$session_id."',
-                    course_code = '".$_SESSION['_course']['id']."',
+                    course_code = '".$course_code."',
                     id_user = '".$user_id."'");
 
             // Add him/her in the table session_rel_user
@@ -1029,13 +1027,13 @@ class CourseManager {
     }
 
     /**
-     *    Is the user subscribed in the real course or linked courses?
-     *
-     *    @param int the id of the user
-     *    @param array info about the course (comes from course table, see database lib)
-     *
-     *    @return true if the user is registered in the real course or linked courses, false otherwise
-     */
+    *    Is the user subscribed in the real course or linked courses?
+    *
+    *    @param int the id of the user
+    *    @param array info about the course (comes from course table, see database lib)
+    *
+    *    @return true if the user is registered in the real course or linked courses, false otherwise
+    */
     public static function is_user_subscribed_in_real_or_linked_course($user_id, $course_code, $session_id = '') {
 
         if ($user_id != strval(intval($user_id))) {
@@ -1045,7 +1043,8 @@ class CourseManager {
         $course_code = Database::escape_string($course_code);
 
         if ($session_id == '') {
-            $result = Database::fetch_array(Database::query("SELECT *
+            $result = Database::fetch_array(
+                Database::query("SELECT *
                     FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." course
                     LEFT JOIN ".Database::get_main_table(TABLE_MAIN_COURSE_USER)." course_user
                     ON course.code = course_user.course_code
@@ -1053,6 +1052,8 @@ class CourseManager {
             return !empty($result);
         }
 
+        $session_id = intval($session_id);
+
         // From here we trust session id.
 
         // Is he/she subscribed to the session's course?
@@ -1060,7 +1061,7 @@ class CourseManager {
         // A user?
         if (Database::num_rows(Database::query("SELECT id_user
                     FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
-                    WHERE id_session='".$_SESSION['id_session']."'
+                    WHERE id_session='".$session_id."'
                     AND id_user='$user_id'"))) {
             return true;
         }
@@ -1068,7 +1069,7 @@ class CourseManager {
         // A course coach?
         if (Database::num_rows(Database::query("SELECT id_user
                     FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)."
-                    WHERE id_session='".$_SESSION['id_session']."'
+                    WHERE id_session='".$session_id."'
                     AND id_user = '$user_id' AND status = 2
                     AND course_code='$course_code'"))) {
             return true;
@@ -1077,7 +1078,7 @@ class CourseManager {
         // A session coach?
         if (Database::num_rows(Database::query("SELECT id_coach
                     FROM ".Database::get_main_table(TABLE_MAIN_SESSION)." AS session
-                    WHERE session.id='".$_SESSION['id_session']."'
+                    WHERE session.id='".$session_id."'
                     AND id_coach='$user_id'"))) {
             return true;
         }
@@ -1116,6 +1117,7 @@ class CourseManager {
         // if the $order_by does not contain 'ORDER BY' we have to check if it is a valid field that can be sorted on
         if (!strstr($order_by,'ORDER BY')) {
             //if (!empty($order_by) AND in_array($order_by, array('lastname', 'firstname', 'username', 'email', 'official_code'))) {
+            $order_by = Database::escape_string($order_by);
             if (!empty($order_by)) {
                 $order_by = 'ORDER BY '.$order_by;
             } else {
@@ -3886,7 +3888,6 @@ class CourseManager {
     }
 
     /**
-     *
      * @deprecated seems not to be used
      * @return ResultSet
      */
@@ -3991,6 +3992,7 @@ class CourseManager {
     /**
      * @param string $course_code
      * @param array $teachers
+     * @param bool $deleteTeachersNotInList
      * @param bool $editTeacherInSessions
      * @param bool $deleteSessionTeacherNotInList
      * @return bool

+ 1 - 0
main/inc/lib/database.lib.php

@@ -1174,6 +1174,7 @@ class Database {
         }
 
         $sql    = "SELECT $clean_columns FROM $table_name $conditions";
+
         $result = self::query($sql);
         $array = array();
         //if (self::num_rows($result) > 0 ) {

+ 21 - 5
main/inc/lib/display.lib.php

@@ -828,13 +828,20 @@ class Display {
      * @return  string  html
      *
      */
-    public static function grid_html($div_id){
-        $table  = self::tag('table','',array('id'=>$div_id));
-        $table .= self::tag('div','',array('id'=>$div_id.'_pager'));
+    public static function grid_html($div_id)
+    {
+        $table  = self::tag('table','', array('id' => $div_id));
+        $table .= self::tag('div','', array('id' => $div_id.'_pager'));
         return $table;
     }
 
-    public static function form_row($label, $form_item) {
+    /**
+     * @param string $label
+     * @param string $form_item
+     * @return string
+     */
+    public static function form_row($label, $form_item)
+    {
         $label = self::span($label, array('class' =>'control-label'));
         $form_item = self::div($form_item, array('class' =>'controls'));
         return self::div($label.$form_item, array('class'=>'control-group'));
@@ -857,7 +864,16 @@ class Display {
      * @return  string  the js code
      *
      */
-    public static function grid_js($div_id, $url, $column_names, $column_model, $extra_params, $data = array(), $formatter = '', $width_fix = false) {
+    public static function grid_js(
+        $div_id,
+        $url,
+        $column_names,
+        $column_model,
+        $extra_params,
+        $data = array(),
+        $formatter = '',
+        $width_fix = false
+    ) {
         $obj = new stdClass();
 
         if (!empty($url)) {

+ 35 - 1
main/inc/lib/main_api.lib.php

@@ -2097,7 +2097,8 @@ function api_get_coachs_from_course($session_id=0,$course_code='') {
  * @author René Haentjens
  * @author Bart Mollet
  */
-function api_get_setting($variable, $key = null) {
+function api_get_setting($variable, $key = null)
+{
     global $_setting;
     if ($variable == 'header_extra_content') {
         $filename = api_get_path(SYS_PATH).api_get_home_path().'header_extra_content.txt';
@@ -2128,6 +2129,21 @@ function api_get_setting($variable, $key = null) {
     return $value;
 }
 
+/**
+ * @param string $plugin
+ * @param string $variable
+ * @return string
+ */
+function api_get_plugin_setting($plugin, $variable)
+{
+    $variableName = $plugin.'_'.$variable;
+    $result = api_get_setting($variableName);
+    if (isset($result[$plugin])) {
+        return $result[$plugin];
+    }
+    return null;
+}
+
 /**
  * Returns the value of a setting from the web-adjustable admin config settings.
  **/
@@ -2240,6 +2256,9 @@ function api_is_allowed_to_create_course() {
  * @return boolean True if current user is a course administrator
  */
 function api_is_course_admin() {
+    if (api_is_platform_admin()) {
+        return true;
+    }
     return $_SESSION['is_courseAdmin'];
 }
 
@@ -3474,6 +3493,21 @@ function api_get_languages() {
     return $language_list;
 }
 
+/**
+ * Returns a list of all the languages that are made available by the admin.
+ * @return array
+ */
+function api_get_languages_to_array() {
+    $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
+    $sql = "SELECT * FROM $tbl_language WHERE available='1' ORDER BY original_name ASC";
+    $result = Database::query($sql);
+    $languages = array();
+    while ($row = Database::fetch_array($result)) {
+        $languages[$row['dokeos_folder']] = $row['original_name'];
+    }
+    return $languages;
+}
+
 /**
  * Returns the id (the database id) of a language
  * @param   string  language name (the corresponding name of the language-folder in the filesystem)

+ 213 - 199
main/inc/lib/pdf.lib.php

@@ -9,14 +9,13 @@
 define('_MPDF_PATH', api_get_path(LIBRARY_PATH).'mpdf/');
 require_once _MPDF_PATH.'mpdf.php';
 
-class PDF {
-    
-    public $pdf;    
+class PDF
+{
+    public $pdf;
     public $custom_header = '';
     public $custom_footer = '';
     public $params = array();
-    
-    
+
     /**
      * Creates the mPDF object
      * @param   string  format A4 A4-L see  http://mpdf1.com/manual/index.php?tid=184&searchstring=format
@@ -26,46 +25,47 @@ class PDF {
     {
         /* More info @ http://mpdf1.com/manual/index.php?tid=184&searchstring=mPDF
          * mPDF ([ string $mode [, mixed $format [, float $default_font_size [, string $default_font [, float $margin_left , float $margin_right , float $margin_top , float $margin_bottom , float $margin_header , float $margin_footer [, string $orientation ]]]]]])
-         */         
+         */
         if (!in_array($orientation, array('P','L'))) {
             $orientation = 'P';
         }
         //$this->pdf = $pdf = new mPDF('UTF-8', $page_format, '', '', 30, 20, 27, 25, 16, 13, $orientation);
         //left, right, top, bottom, margin_header, margin footer
-        
+
         $params['left']     = isset($params['left'])    ? $params['left']   : 15;
         $params['right']    = isset($params['right'])   ? $params['right']  : 15;
         $params['top']      = isset($params['top'])     ? $params['top']    : 20;
         $params['bottom']   = isset($params['bottom'])  ? $params['bottom'] : 15;
-        
+
         $this->params['filename'] = isset($params['filename']) ? $params['filename'] : api_get_local_time();
         $this->params['pdf_title'] = isset($params['pdf_title']) ? $params['pdf_title'] : get_lang('Untitled');
         $this->params['course_info'] = isset($params['course_info']) ? $params['course_info'] : api_get_course_info();
         $this->params['session_info'] = isset($params['session_info']) ? $params['session_info'] : api_get_session_info(api_get_session_id());
         $this->params['course_code'] = isset($params['course_code']) ? $params['course_code'] : api_get_course_id();
-        $this->params['add_signatures'] = isset($params['add_signatures']) ? $params['add_signatures'] : false;        
-        
-        $this->pdf = new mPDF('UTF-8', $page_format, '', '', $params['left'], $params['right'], $params['top'], $params['bottom'], 8, 8, $orientation); 
+        $this->params['add_signatures'] = isset($params['add_signatures']) ? $params['add_signatures'] : false;
+
+        $this->pdf = new mPDF('UTF-8', $page_format, '', '', $params['left'], $params['right'], $params['top'], $params['bottom'], 8, 8, $orientation);
     }
+
     /**
      * Export the given HTML to PDF, using a global template
      * @param string the HTML content
      * @uses export/table_pdf.tpl
      */
-    function html_to_pdf_with_template($content)
+    public function html_to_pdf_with_template($content)
     {
         Display :: display_no_header();
-        
+
         //Assignments
         Display::$global_template->assign('pdf_content', $content);
-        
+
         $organization = api_get_setting('Institution');
-        $img = api_get_path(SYS_CODE_PATH).'css/'.api_get_visual_theme().'/images/header-logo.png';    
+        $img = api_get_path(SYS_CODE_PATH).'css/'.api_get_visual_theme().'/images/header-logo.png';
         if (file_exists($img)) {
             $img = api_get_path(WEB_CODE_PATH).'css/'.api_get_visual_theme().'/images/header-logo.png';
-            $organization = "<img src='$img'>";			
+            $organization = "<img src='$img'>";
         } else {
-            if (!empty($organization)) {			  
+            if (!empty($organization)) {
                 $organization = '<h2 align="left">'.$organization.'</h2>';
             }
         }
@@ -82,38 +82,47 @@ class PDF {
         Display::$global_template->assign('pdf_course_info', $this->params['course_info']);
         Display::$global_template->assign('pdf_session_info', $this->params['session_info']);
         Display::$global_template->assign('pdf_date', api_format_date(api_get_utc_datetime(), DATE_TIME_FORMAT_LONG));
-        Display::$global_template->assign('pdf_teachers', $teacher_list);        
+        Display::$global_template->assign('pdf_teachers', $teacher_list);
         Display::$global_template->assign('pdf_title', $this->params['pdf_title']);
         Display::$global_template->assign('add_signatures', $this->params['add_signatures']);
-        
+
         //Getting template
-        $tpl = Display::$global_template->get_template('export/table_pdf.tpl');     
-        $html = Display::$global_template->fetch($tpl);    
+        $tpl = Display::$global_template->get_template('export/table_pdf.tpl');
+        $html = Display::$global_template->fetch($tpl);
         $html = api_utf8_encode($html);
-        
+
         $css_file = api_get_path(TO_SYS, WEB_CSS_PATH).'/print.css';
         $css = file_exists($css_file) ? @file_get_contents($css_file) : '';
-        self::content_to_pdf($html, $css, $this->params['filename'], $this->params['course_code']);        
+        self::content_to_pdf($html, $css, $this->params['filename'], $this->params['course_code']);
     }
-    
+
     /**
      * Converts HTML files to PDF
-     * @param   mixed   could be an html file path or an array with paths example: /var/www/myfile.html or array('/myfile.html','myotherfile.html') or even an indexed array with both 'title' and 'path' indexes for each element like array(0=>array('title'=>'Hello','path'=>'file.html'),1=>array('title'=>'Bye','path'=>'file2.html'));
-     * @param   string  pdf name   
-     * @param   string  course code (if you are using html that are located in the document tool you must provide this) 
+     * @param   mixed   could be an html file path or an array with paths example:
+           /var/www/myfile.html or
+           array('/myfile.html','myotherfile.html') or even an indexed array with both 'title' and 'path' indexes
+          for each element like
+     * array(0=>array('title'=>'Hello','path'=>'file.html'),1=>array('title'=>'Bye','path'=>'file2.html'));
+     * @param   string  pdf name
+     * @param   string  course code (if you are using html that are located in the document tool you must provide this)
      * @param bool Whether to print the header, footer and watermark (true) or just the content (false)
-     * @return void
-     */    
-    public function html_to_pdf($html_file_array, $pdf_name = '', $course_code = null, $print_title = false, $complete_style = true) {
-        
-if($complete_style === false) { error_log(__FUNCTION__.' with no style'); }
+     * @return bool
+     */
+    public function html_to_pdf($html_file_array, $pdf_name = '', $course_code = null, $print_title = false, $complete_style = true)
+    {
+
+        if ($complete_style === false) {
+            error_log(__FUNCTION__.' with no style');
+        }
+
         if (empty($html_file_array)) {
-        	return false;
-        }  
-              
+            return false;
+        }
+
         if (is_array($html_file_array)) {
-            if (count($html_file_array) == 0)
-        	   return false;
+            if (count($html_file_array) == 0) {
+            return false;
+            }
         } else {
             if (!file_exists($html_file_array)) {
                 return false;
@@ -121,97 +130,93 @@ if($complete_style === false) { error_log(__FUNCTION__.' with no style'); }
             //Converting the string into an array
             $html_file_array = array($html_file_array);
         }
-        
-        $course_data = array();
-        
+
         if (!empty($course_code)) {
-        	$course_data = api_get_course_info($course_code);
+            $course_data = api_get_course_info($course_code);
         } else {
             $course_data = api_get_course_info();
         }
-        
+
         //clean styles and javascript document
         $clean_search = array (
             '@<script[^>]*?>.*?</script>@si',
-            '@<style[^>]*?>.*?</style>@si'                    
+            '@<style[^>]*?>.*?</style>@si'
             );
-            
+
         //Formatting the pdf
         self::format_pdf($course_data, $complete_style);
-        
+
         $counter = 1;
-        
-        foreach ($html_file_array as $file) {            
-            
+
+        foreach ($html_file_array as $file) {
+
             //Add a page break per file
             $page_break = '<pagebreak>';
             if ($counter == count($html_file_array)) {
                 $page_break = '';
             }
-            $counter++;            
-            
-            $html_title = '';
-            
+            $counter++;
+
             //if the array provided contained subarrays with 'title' entry,
             // then print the title in the PDF
             if (is_array($file) && isset($file['title'])) {
-            	$html_title = $file['title'];
+                $html_title = $file['title'];
                 $file  = $file['path'];
             } else {
                 //we suppose we've only been sent a file path
-            	$html_title = basename($file);
+                $html_title = basename($file);
             }
-            
+
             if (empty($file) && !empty($html_title)) {
             	//this is a chapter, print title & skip the rest
                 if ($print_title) {
                     $this->pdf->WriteHTML('<html><body><h3>'.$html_title.'</h3></body></html>'.$page_break, 2);
                 }
                 continue;
-            }         
-            
+            }
+
             if (!file_exists($file)) {
                 //the file doesn't exist, skip
             	continue;
             }
-       
+
             //it's not a chapter but the file exists, print its title
             if ($print_title) {
                 $this->pdf->WriteHTML('<html><body><h3>'.$html_title.'</h3></body></html>',2);
             }
-            
+
             $file_info = pathinfo($file);
             $extension = $file_info['extension'];
-            
-            if (in_array($extension, array('html', 'htm'))) {            
+
+            if (in_array($extension, array('html', 'htm'))) {
                 $filename = $file_info['basename'];
                 $filename = str_replace('_',' ',$filename);
-                
+
                 if ($extension == 'html') {
                     $filename = basename($filename,'.html');
                 } elseif($extension == 'htm'){
                     $filename = basename($filename,'.htm');
                 }
-                
+
                 $document_html = @file_get_contents($file);
-                $document_html = preg_replace($clean_search, '', $document_html);                  
-                                
+                $document_html = preg_replace($clean_search, '', $document_html);
+
                 //absolute path for frames.css //TODO: necessary?
                 $absolute_css_path = api_get_path(WEB_CODE_PATH).'css/'.api_get_setting('stylesheets').'/frames.css';
                 $document_html = str_replace('href="./css/frames.css"', $absolute_css_path, $document_html);
- 
+
                 if (!empty($course_data['path'])) {
-                    $document_html= str_replace('../','',$document_html);                    
+                    $document_html= str_replace('../','', $document_html);
                     $document_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document/';
-                               
-                    $doc = new DOMDocument();           
+
+                    $doc = new DOMDocument();
                     $result = @$doc->loadHTML($document_html);
-                                         
+
                     //Fixing only images @todo do the same thing with other elements
-                    $elements = $doc->getElementsByTagName('img');                    
+                    $elements = $doc->getElementsByTagName('img');
                     if (!empty($elements)) {
-                        foreach ($elements as $item) {                    
-                            $old_src = $item->getAttribute('src');                                                        
+                        foreach ($elements as $item) {
+                            $old_src = $item->getAttribute('src');
                             if (strpos($old_src, 'http') === false) {
                                 if (strpos($old_src, '/main/default_course_document') === false) {
                                     $old_src_fixed = '';
@@ -222,60 +227,60 @@ if($complete_style === false) { error_log(__FUNCTION__.' with no style'); }
                                     }
                                     $new_path = $document_path.$old_src_fixed;
                                     $document_html= str_replace($old_src, $new_path, $document_html);
-                                }                                                       	
+                                }
                             } else {
                                 //Check if this is a complete URL
-                                /*if (strpos($old_src, 'courses/'.$course_data['path'].'/document/') === false) {                                    
-                                    
+                                /*if (strpos($old_src, 'courses/'.$course_data['path'].'/document/') === false) {
+
                                 } else {
                                     $old_src_fixed = str_replace(api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document/', '', $old_src);
                                     $new_path = $document_path.$old_src_fixed;
                                     $document_html= str_replace($old_src, $new_path, $document_html);
                                 }*/
-                            }                        
+                            }
                         }
                     }
                 }
-                
-                api_set_encoding_html($document_html, 'UTF-8'); // The library mPDF expects UTF-8 encoded input data.        
+
+                api_set_encoding_html($document_html, 'UTF-8'); // The library mPDF expects UTF-8 encoded input data.
                 $title = api_get_title_html($document_html, 'UTF-8', 'UTF-8');  // TODO: Maybe it is better idea the title to be passed through
                                                                                 // $_GET[] too, as it is done with file name.
                                                                          // At the moment the title is retrieved from the html document itself.
                 //echo $document_html;exit;
                 if (empty($title)) {
                     $title = $filename; // Here file name is expected to contain ASCII symbols only.
-                }                
-                if (!empty($document_html)) {                	
+                }
+                if (!empty($document_html)) {
                     $this->pdf->WriteHTML($document_html.$page_break, 2);
                 }
             } elseif (in_array($extension, array('jpg','jpeg','png','gif'))) {
                 //Images
                 $image = Display::img($file);
-                $this->pdf->WriteHTML('<html><body>'.$image.'</body></html>'.$page_break,2);
-            }            
+                $this->pdf->WriteHTML('<html><body>'.$image.'</body></html>'.$page_break, 2);
+            }
         }
-       
+
         if (empty($pdf_name)) {
             $output_file = 'pdf_'.date('Y-m-d-his').'.pdf';
         } else {
             $pdf_name = replace_dangerous_char($pdf_name);
         	$output_file = $pdf_name.'.pdf';
         }
-        $result = $this->pdf->Output($output_file, 'D');       /// F to save the pdf in a file              
+        $result = $this->pdf->Output($output_file, 'D');       /// F to save the pdf in a file
         exit;
-    }   
-    
-     
+    }
+
     /**
      * Converts an html string to PDF
      * @param   string  valid html
      * @param   string  CSS content of a CSS file
-     * @param   string  pdf name   
-     * @param   string  course code (if you are using html that are located in the document tool you must provide this) 
+     * @param   string  pdf name
+     * @param   string  course code (if you are using html that are located in the document tool you must provide this)
      * @return  string Web path
-     */    
-    public function content_to_pdf($document_html, $css = '', $pdf_name = '', $course_code = null) {
-        
+     */
+    public function content_to_pdf($document_html, $css = '', $pdf_name = '', $course_code = null)
+    {
+
         if (empty($document_html)) {
             return false;
         }
@@ -285,125 +290,123 @@ if($complete_style === false) { error_log(__FUNCTION__.' with no style'); }
             '@<script[^>]*?>.*?</script>@si',
             '@<style[^>]*?>.*?</style>@siU'
             );
-            
-        //Formatting the pdf          
+
+        //Formatting the pdf
        	$course_data = api_get_course_info($course_code);
-        
+
         self::format_pdf($course_data);
-        
-        $document_html = preg_replace($clean_search, '', $document_html);   
-        
+
+        $document_html = preg_replace($clean_search, '', $document_html);
+
         //absolute path for frames.css //TODO: necessary?
         $absolute_css_path 	= api_get_path(WEB_CODE_PATH).'css/'.api_get_setting('stylesheets').'/frames.css';
         $document_html		= str_replace('href="./css/frames.css"','href="'.$absolute_css_path.'"', $document_html);
-        
+
         //$document_html=str_replace('<link rel="stylesheet" http://my.chamilo.net/main/css/chamilo/frames.css type="text/css" />','', $document_html);
-    
+
         $document_html= str_replace('../../','',$document_html);
-        $document_html= str_replace('../','',$document_html);        
+        $document_html= str_replace('../','',$document_html);
         $document_html= str_replace('courses/'.$course_code.'/document/','',$document_html);
-        
+
         if (!empty($course_data['path'])) {
             $document_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document/';
-                       
-            $doc = new DOMDocument();           
+
+            $doc = new DOMDocument();
             $result = @$doc->loadHTML($document_html);
-                                 
+
             //Fixing only images @todo do the same thing with other elements
-            $elements = $doc->getElementsByTagName('img');            
+            $elements = $doc->getElementsByTagName('img');
             if (!empty($elements)) {
-                foreach ($elements as $item) {                    
+                foreach ($elements as $item) {
                     $old_src = $item->getAttribute('src');
                     //$old_src= str_replace('../','',$old_src);
                     if (strpos($old_src, 'http') === false) {
                         if (strpos($old_src, '/main/default_course_document') === false) {
                             if (strpos($old_src, '/main/inc/lib/') === false) {
-                                
+
                                 $old_src_fixed = str_replace('/courses/'.$course_data['path'].'/document/', '', $old_src);
-                                $old_src_fixed = str_replace('courses/'.$course_data['path'].'/document/', '', $old_src_fixed);                                    
-                                $new_path = $document_path.$old_src_fixed;                                    
-                                $document_html= str_replace($old_src, $new_path, $document_html);  
-                               
-                            }              
-                        }                                                           
-                    }                                    
+                                $old_src_fixed = str_replace('courses/'.$course_data['path'].'/document/', '', $old_src_fixed);
+                                $new_path = $document_path.$old_src_fixed;
+                                $document_html= str_replace($old_src, $new_path, $document_html);
+
+                            }
+                        }
+                    }
                 }
             }
         }
-          
+
         //replace relative path by absolute path for resources
         //$document_html= str_replace('src="/chamilo/main/default_course_document/', 'temp_template_path', $document_html);// before save src templates not apply
         //$document_html= str_replace('src="/', 'temp_template_path', $document_html);// before save src templates not apply
         //$document_html= str_replace('src="/chamilo/main/default_course_document/', 'temp_template_path', $document_html);// before save src templates not apply
-        
+
         //$src_http_www= 'src="'.api_get_path(WEB_COURSE_PATH).$course_data['path'].'/document/';
         //$document_html= str_replace('src="',$src_http_www, $document_html);
         //$document_html= str_replace('temp_template_path', 'src="/main/default_course_document/', $document_html);// restore src templates
-        
-        api_set_encoding_html($document_html, 'UTF-8'); // The library mPDF expects UTF-8 encoded input data.        
+
+        api_set_encoding_html($document_html, 'UTF-8'); // The library mPDF expects UTF-8 encoded input data.
         $title = api_get_title_html($document_html, 'UTF-8', 'UTF-8');  // TODO: Maybe it is better idea the title to be passed through
                                                                         // $_GET[] too, as it is done with file name.
                                                                         // At the moment the title is retrieved from the html document itself.
-       /* if (empty($title)) {
-            $title = $filename; // Here file name is expected to contain ASCII symbols only.
-        }*/      
-                       
+
         if (!empty($css)) {
-            $this->pdf->WriteHTML($css, 1);            
-        } 
-        $this->pdf->WriteHTML($document_html,2);    
-        
+            $this->pdf->WriteHTML($css, 1);
+        }
+        $this->pdf->WriteHTML($document_html,2);
+
         if (empty($pdf_name)) {
             $output_file = 'pdf_'.date('Y-m-d-his').'.pdf';
         } else {
             $pdf_name = replace_dangerous_char($pdf_name);
             $output_file = $pdf_name.'.pdf';
         }
-        $result = $this->pdf->Output($output_file, 'D'); // F to save the pdf in a file                      
+        $result = $this->pdf->Output($output_file, 'D'); // F to save the pdf in a file
         exit;
     }
-    
+
     /**
      * Gets the watermark from the platform or a course
      * @param   string  course code (optional)
      * @param   mixed   web path of the watermark image, false if there is nothing to return
      */
-    public static function get_watermark($course_code = null) {
+    public static function get_watermark($course_code = null)
+    {
         $web_path = false;
         if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
             $course_info = api_get_course_info($course_code);
             $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/'.api_get_current_access_url_id().'_pdf_watermark.png';   // course path
             if (file_exists($store_path)) {
-                $web_path   = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/'.api_get_current_access_url_id().'_pdf_watermark.png';                 
+                $web_path   = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/'.api_get_current_access_url_id().'_pdf_watermark.png';
             }
         } else {
             $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images/'.api_get_current_access_url_id().'_pdf_watermark.png';   // course path
-            if (file_exists($store_path))                   
+            if (file_exists($store_path))
                 $web_path   = api_get_path(WEB_CODE_PATH).'default_course_document/images/'.api_get_current_access_url_id().'_pdf_watermark.png';
         }
-        return $web_path;        
+        return $web_path;
     }
-    
+
     /**
      * Deletes the watermark from the Platform or Course
      * @param   string  course code (optional)
      * @param   mixed   web path of the watermark image, false if there is nothing to return
      */
-     
-    public function delete_watermark($course_code = null) {        
+    public function delete_watermark($course_code = null)
+    {
         if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
             $course_info = api_get_course_info($course_code);
-            $store_path  = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/'.api_get_current_access_url_id().'_pdf_watermark.png';   // course path            
+            $store_path  = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/'.api_get_current_access_url_id().'_pdf_watermark.png';   // course path
         } else {
-            $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images/'.api_get_current_access_url_id().'_pdf_watermark.png';   // course path              
-        }        
+            $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images/'.api_get_current_access_url_id().'_pdf_watermark.png';   // course path
+        }
         if (file_exists($store_path)) {
             @unlink($store_path);
             return true;
         }
     	return false;
     }
-    
+
     /**
      * Uploads the pdf watermark in the main/default_course_document directory or in the course directory
      * @param	string	filename
@@ -411,42 +414,47 @@ if($complete_style === false) { error_log(__FUNCTION__.' with no style'); }
      * @param	string	course code
      * @return 	mixed	web path of the file if sucess, false otherwise
      */
-    public function upload_watermark($filename, $source_file, $course_code = null) {        
+    public function upload_watermark($filename, $source_file, $course_code = null)
+    {
         if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
-            $course_info = api_get_course_info($course_code);            
+            $course_info = api_get_course_info($course_code);
             $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path'];   // course path
             $web_path   = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/pdf_watermark.png';
         } else {
-            $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images';   // course path	
+            $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images';   // course path
             $web_path   = api_get_path(WEB_CODE_PATH).'default_course_document/images/'.api_get_current_access_url_id().'_pdf_watermark.png';
-        }        
+        }
         $course_image = $store_path.'/'.api_get_current_access_url_id().'_pdf_watermark.png';
         $extension = strtolower(substr(strrchr($filename, '.'), 1));
         $result = false;
-        
+
         if (file_exists($course_image)) {
             @unlink($course_image);
         }
         $my_image = new Image($source_file);
-        $result = $my_image->send_image($course_image, -1, 'png');        
+        $result = $my_image->send_image($course_image, -1, 'png');
         if ($result) {
         	$result = $web_path;
         }
         return $result;
     }
-    
+
     /**
      * Returns the default header
      */
-    public function get_header($course_code = null) {
-        /*$header = api_get_setting('pdf_export_watermark_text');        
+    public function get_header($course_code = null)
+    {
+        /*$header = api_get_setting('pdf_export_watermark_text');
     	if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
-            $header = api_get_course_setting('pdf_export_watermark_text');                        
+            $header = api_get_course_setting('pdf_export_watermark_text');
         }
-        return $header;*/        
+        return $header;*/
     }
-    
-    public function set_footer() {    	 
+
+    /**
+     *
+     */
+    public function set_footer() {
         $this->pdf->defaultfooterfontsize = 12;   // in pts
         $this->pdf->defaultfooterfontstyle = B;   // blank, B, I, or BI
         $this->pdf->defaultfooterline = 1;        // 1 to include line below header/above footer
@@ -454,7 +462,7 @@ if($complete_style === false) { error_log(__FUNCTION__.' with no style'); }
         $left_content    = $platform_name;
         $center_content  = '';
         $right_content   = '{PAGENO} / {nb}';
-        
+
         //@todo remove this and use a simpler way
         $footer = array (
               'odd' => array (
@@ -475,41 +483,44 @@ if($complete_style === false) { error_log(__FUNCTION__.' with no style'); }
                   'content' => $right_content, 'font-size' => 10,'font-style' => 'B','font-family' => 'serif','color'=>'#000000'),
                 'line' => 1,
               ),
-            );       
+            );
         // defines footer for Odd and Even Pages - placed at Outer margin see http://mpdf1.com/manual/index.php?tid=151&searchstring=setfooter
-        $this->pdf->SetFooter($footer);      
+        $this->pdf->SetFooter($footer);
     }
-    
-    
-    public function set_header($course_data) {    	
-                
+
+    /**
+     * @param $course_data
+     */
+    public function set_header($course_data)
+    {
+
         $this->pdf->defaultheaderfontsize   = 10;   // in pts
         $this->pdf->defaultheaderfontstyle  = BI;   // blank, B, I, or BI
-        $this->pdf->defaultheaderline       = 1;    // 1 to include line below header/above footer              
-        
+        $this->pdf->defaultheaderline       = 1;    // 1 to include line below header/above footer
+
         if (!empty($course_data['code'])) {
             $teacher_list = CourseManager::get_teacher_list_from_course_code($course_data['code']);
             $teachers = '';
-            if (!empty($teacher_list)) {                
+            if (!empty($teacher_list)) {
                 foreach ($teacher_list as $teacher) {
                     //$teachers[]= api_get_person_name($teacher['firstname'], $teacher['lastname']);
                     $teachers[]= $teacher['firstname'].' '.$teacher['lastname'];
-                }                              
+                }
                 if (count($teachers) > 1) {
                     $teachers = get_lang('Teachers').': '.implode(', ', $teachers);
                 } else {
                     $teachers = get_lang('Teacher').': '.implode('', $teachers);
                 }
-                
+
                 //do not show the teacher list see BT#4080 only the current teacher name
                 $user_info = api_get_user_info();
-                $teachers = $user_info['complete_name'];                
-            }           
-            
+                $teachers = $user_info['complete_name'];
+            }
+
             $left_content    = '';
             $center_content  = '';
             $right_content   = $teachers;
-        
+
             $header = array (
               'odd' => array (
                 'L' => array (
@@ -530,53 +541,56 @@ if($complete_style === false) { error_log(__FUNCTION__.' with no style'); }
                 'line' => 1,
               ),
             );
-            $this->pdf->SetHeader($header);// ('{DATE j-m-Y}|{PAGENO}/{nb}|'.$title);       
-        }               
+            $this->pdf->SetHeader($header);// ('{DATE j-m-Y}|{PAGENO}/{nb}|'.$title);
+        }
     }
-    
+
     public function set_custom_header($header) {
         $this->custom_header = $header;
     }
-    
+
     public function set_custom_footer($footer) {
         $this->custom_footer = $footer;
     }
-    
+
     /**
      * Pre-formats a PDF to the right size and, if not stated otherwise, with
      * header, footer and watermark (if any)
      * @param array General course information (to fill headers)
      * @param bool Whether we want headers, footers and watermark or not
      */
-    public function format_pdf($course_data, $complete = true) {
-if($complete === false) {error_log('Asked with no decoration');}
+    public function format_pdf($course_data, $complete = true)
+    {
+        if ($complete === false) {
+            error_log('Asked with no decoration');
+        }
         $course_code = null;
-        if (!empty( $course_data)) {    
-            $course_code = $course_data['code'];   
+        if (!empty( $course_data)) {
+            $course_code = $course_data['code'];
         }
-        
+
         /*$pdf->SetAuthor('Documents Chamilo');
         $pdf->SetTitle('title');
         $pdf->SetSubject('Exported from Chamilo Documents');
         $pdf->SetKeywords('Chamilo Documents');
-        */                      
-        $this->pdf->directionality      = api_get_text_direction(); // TODO: To be read from the html document.        
-        $this->pdf->useOnlyCoreFonts    = true;        
-        $this->pdf->mirrorMargins       = 1;            // Use different Odd/Even headers and footers and mirror margins       
-        
+        */
+        $this->pdf->directionality      = api_get_text_direction(); // TODO: To be read from the html document.
+        $this->pdf->useOnlyCoreFonts    = true;
+        $this->pdf->mirrorMargins       = 1;            // Use different Odd/Even headers and footers and mirror margins
+
         // Add decoration only if not stated otherwise
         if ($complete) {
             //Adding watermark
             if (api_get_setting('pdf_export_watermark_enable') == 'true') {
-                $watermark_file = self::get_watermark($course_code);      
-                      
-                if ($watermark_file) {                
-                    //http://mpdf1.com/manual/index.php?tid=269&searchstring=watermark                
+                $watermark_file = self::get_watermark($course_code);
+
+                if ($watermark_file) {
+                    //http://mpdf1.com/manual/index.php?tid=269&searchstring=watermark
                     $this->pdf->SetWatermarkImage($watermark_file);
                     $this->pdf->showWatermarkImage = true;
                 } else {
-                    $watermark_file = self::get_watermark(null);      
-                    if ($watermark_file) {   
+                    $watermark_file = self::get_watermark(null);
+                    if ($watermark_file) {
                         $this->pdf->SetWatermarkImage($watermark_file);
                         $this->pdf->showWatermarkImage = true;
                     }
@@ -584,7 +598,7 @@ if($complete === false) {error_log('Asked with no decoration');}
                 if ($course_code) {
                     $watermark_text = api_get_course_setting('pdf_export_watermark_text');
                     if (empty($watermark_text)) {
-                        $watermark_text = api_get_setting('pdf_export_watermark_text');    
+                        $watermark_text = api_get_setting('pdf_export_watermark_text');
                     }
                 } else {
                     $watermark_text = api_get_setting('pdf_export_watermark_text');
@@ -593,20 +607,20 @@ if($complete === false) {error_log('Asked with no decoration');}
                     $this->pdf->SetWatermarkText(strcode2utf($watermark_text),0.1);
                     $this->pdf->showWatermarkText = true;
                 }
-            }        
-            
+            }
+
             if (empty($this->custom_header)) {
-                self::set_header($course_data);   
+                self::set_header($course_data);
             } else {
                 $this->pdf->SetHTMLHeader($this->custom_header,'E');
                 $this->pdf->SetHTMLHeader($this->custom_header,'O');
             }
-            
+
             if (empty($this->custom_footer)) {
-                self::set_footer();    
+                self::set_footer();
             } else {
-                $this->pdf->SetHTMLFooter($this->custom_footer);	
-            }        
+                $this->pdf->SetHTMLFooter($this->custom_footer);
+            }
         }
     }
 }

+ 69 - 37
main/inc/lib/plugin.class.php

@@ -3,7 +3,7 @@
 
 /**
  * Base class for plugins
- * 
+ *
  * This class has to be extended by every plugin. It defines basic methods
  * to install/uninstall and get information about a plugin
  *
@@ -14,18 +14,18 @@
  * @author Yannick Warnier <ywarnier@beeznest.org> added documentation
  *
  */
-class Plugin {
-
+class Plugin
+{
     protected $version = '';
     protected $author = '';
     protected $fields = array();
 
     private $settings = null;
     private $strings = null; //translation strings
-    public  $is_course_plugin = false;
+    public $is_course_plugin = false;
 
     /**
-     * When creating a new course, these settings are added to the course, in 
+     * When creating a new course, these settings are added to the course, in
      * the course_info/infocours.php
      * To show the plugin course icons you need to add these icons:
      * main/img/icons/22/plugin_name.png
@@ -37,12 +37,12 @@ class Plugin {
                     array('name' => 'big_blue_button_record_and_store', 'type' => 'checkbox')
         );
      */
-    public  $course_settings = array();
+    public $course_settings = array();
     /**
      * This indicates whether changing the setting should execute the callback
      * function.
      */
-    public  $course_settings_callback = false;
+    public $course_settings_callback = false;
 
     /**
      * Default constructor for the plugin class. By default, it only sets
@@ -50,9 +50,9 @@ class Plugin {
      * @param  string  Version of this plugin
      * @param  string  Author of this plugin
      * @param  array   Array of global settings to be proposed to configure the plugin
-     * @return void
      */
-    protected function __construct($version, $author, $settings = array()) {
+    protected function __construct($version, $author, $settings = array())
+    {
         $this->version = $version;
         $this->author = $author;
         $this->fields = $settings;
@@ -60,11 +60,13 @@ class Plugin {
         global $language_files;
         $language_files[] = 'plugin_' . $this->get_name();
     }
+
     /**
      * Gets an array of information about this plugin (name, version, ...)
      * @return  array Array of information elements about this plugin
      */
-    function get_info() {
+    public function get_info()
+    {
         $result = array();
 
         $result['title']            = $this->get_title();
@@ -72,7 +74,7 @@ class Plugin {
         $result['version']          = $this->get_version();
         $result['author']           = $this->get_author();
         $result['plugin_class']     = get_class($this);
-        $result['is_course_plugin'] = $this->is_course_plugin;        
+        $result['is_course_plugin'] = $this->is_course_plugin;
 
         if ($form = $this->get_settings_form()) {
             $result['settings_form'] = $form;
@@ -83,11 +85,14 @@ class Plugin {
         }
         return $result;
     }
+
     /**
      * Returns the "system" name of the plugin in lowercase letters
      * @param string Name of the plugin
+     * @return string
      */
-    function get_name() {
+    public function get_name()
+    {
         $result = get_class($this);
         $result = str_replace('Plugin', '', $result);
         $result = strtolower($result);
@@ -96,41 +101,51 @@ class Plugin {
 
     /**
      * Returns the title of the plugin
-     * @param string Title of the plugin
+     * @param string title of the plugin
+     * @return string
      */
-    function get_title() {
+    public function get_title()
+    {
         return $this->get_lang('plugin_title');
     }
 
     /**
      * Returns the description of the plugin
-     * @param string Description of the plugin
+     * @param string description of the plugin
+     * @return string
      */
-    function get_comment() {
+    public function get_comment()
+    {
         return $this->get_lang('plugin_comment');
     }
 
     /**
      * Returns the version of the plugin
      * @param string Version of the plugin
+     * @return string
      */
-    function get_version() {
+    public function get_version()
+    {
         return $this->version;
     }
 
     /**
      * Returns the author of the plugin
      * @param string Author(s) of the plugin
+     * @return string
      */
-    function get_author() {
+    public function get_author()
+    {
         return $this->author;
     }
 
     /**
      * Returns the contents of the CSS defined by the plugin
      * @param string The CSS string
+     * @return array
      */
-    function get_css() {
+    public function get_css()
+    {
         $name = $this->get_name();
         $path = api_get_path(SYS_PLUGIN_PATH)."$name/resources/$name.css";
         if (!is_readable($path)) {
@@ -146,7 +161,8 @@ class Plugin {
      * Returns an HTML form (generated by FormValidator) of the plugin settings
      * @return string FormValidator-generated form
      */
-    function get_settings_form() {
+    public function get_settings_form()
+    {
         $result = new FormValidator($this->get_name());
 
         $defaults = array();
@@ -174,7 +190,7 @@ class Plugin {
                 case 'boolean':
                     $group = array();
                     $group[] = $result->createElement('radio', $name, '', get_lang('Yes'), 'true');
-                    $group[] = $result->createElement('radio', $name, '', get_lang('No'),  'false');
+                    $group[] = $result->createElement('radio', $name, '', get_lang('No'), 'false');
                     $result->addGroup($group, null, array($this->get_lang($name), $help));
                     break;
             }
@@ -189,7 +205,8 @@ class Plugin {
      * @param string Name of the plugin
      * @return string Value of the plugin
      */
-    function get($name) {
+    public function get($name)
+    {
         $settings = $this->get_settings();
         foreach ($settings as $setting) {
             if ($setting['variable'] == ($this->get_name() . '_' . $name)) {
@@ -203,7 +220,8 @@ class Plugin {
      * Returns an array with the global settings for this plugin
      * @return array Plugin settings as an array
      */
-    public function get_settings() {
+    public function get_settings()
+    {
         if (is_null($this->settings)) {
             $settings = api_get_settings_params(array("subkey = ? AND category = ? AND type = ? " => array($this->get_name(), 'Plugins', 'setting')));
             $this->settings = $settings;
@@ -214,9 +232,10 @@ class Plugin {
     /**
      * Tells whether language variables are defined for this plugin or not
      * @param string System name of the plugin
-     * @return boolean True if the plugin has languag variables defined, false otherwise
+     * @return boolean True if the plugin has language variables defined, false otherwise
      */
-    public function get_lang_plugin_exists($name) {
+    public function get_lang_plugin_exists($name)
+    {
         return isset($this->strings[$name]);
     }
 
@@ -225,7 +244,8 @@ class Plugin {
      * @param string Name of the language variable we are looking for
      * @return string The translated language term of the plugin
      */
-    public function get_lang($name) {
+    public function get_lang($name)
+    {
         // Check whether the language strings for the plugin have already been
         // loaded. If so, no need to load them again.
         if (is_null($this->strings)) {
@@ -249,7 +269,7 @@ class Plugin {
                         $this->strings[$key] = $string;
                     }
                 }
-            } 
+            }
         }
 
         if (isset($this->strings[$name])) {
@@ -264,18 +284,19 @@ class Plugin {
      * @param boolean Whether to add a tool link on the course homepage
      * @return void
      */
-    function course_install($course_id, $add_tool_link = true) {
+    public function course_install($course_id, $add_tool_link = true)
+    {
         $this->install_course_fields($course_id, $add_tool_link);
     }
 
-
     /**
      * Add course settings and, if not asked otherwise, add a tool link on the course homepage
      * @param int Course integer ID
      * @param boolean Whether to add a tool link or not (some tools might just offer a configuration section and act on the backend)
      * @return boolean  False on error, null otherwise
      */
-    public function install_course_fields($course_id, $add_tool_link = true) {
+    public function install_course_fields($course_id, $add_tool_link = true)
+    {
         $plugin_name = $this->get_name();
         $t_course = Database::get_course_table(TABLE_COURSE_SETTING);
 
@@ -313,8 +334,12 @@ class Plugin {
                 }
             }
         }
+
         // Stop here if we don't want a tool link on the course homepage
-        if (!$add_tool_link) { return true; }
+        if (!$add_tool_link) {
+            return true;
+        }
+
         //Add an icon in the table tool list
         $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
         $sql = "SELECT name FROM $t_tool WHERE c_id = $course_id AND name = '$plugin_name' ";
@@ -322,8 +347,9 @@ class Plugin {
         if (!Database::num_rows($result)) {
             $tool_link = "$plugin_name/start.php";
             $visibility = string2binary(api_get_setting('course_create_active_tools', $plugin_name));
-            $sql_course = "INSERT INTO $t_tool VALUES ($course_id, NULL, '$plugin_name', '$tool_link', '$plugin_name.png',' ".$visibility."','0', 'squaregrey.gif','NO','_self','plugin','0')";
-            $r = Database::query($sql_course);
+            $sql_course = "INSERT INTO $t_tool
+            VALUES ($course_id, NULL, '$plugin_name', '$tool_link', '$plugin_name.png',' ".$visibility."','0', 'squaregrey.gif','NO','_self','plugin','0')";
+            Database::query($sql_course);
         }
     }
 
@@ -333,7 +359,8 @@ class Plugin {
      * @param int The integer course ID
      * @return void
      */
-    public function uninstall_course_fields($course_id) {
+    public function uninstall_course_fields($course_id)
+    {
         $course_id = intval($course_id);
         if (empty($course_id)) {
             return false;
@@ -363,7 +390,8 @@ class Plugin {
      * @param boolean Whether we want to add a plugin link on the course homepage
      * @return void
      */
-    function install_course_fields_in_all_courses($add_tool_link = true) {
+    public function install_course_fields_in_all_courses($add_tool_link = true)
+    {
         // Update existing courses to add conference settings
         $t_courses = Database::get_main_table(TABLE_MAIN_COURSE);
         $sql = "SELECT id, code FROM $t_courses ORDER BY id";
@@ -377,7 +405,8 @@ class Plugin {
      * Uninstall the plugin settings fields from all courses
      * @return void
      */
-    function uninstall_course_fields_in_all_courses() {
+    public function uninstall_course_fields_in_all_courses()
+    {
         // Update existing courses to add conference settings
         $t_courses = Database::get_main_table(TABLE_MAIN_COURSE);
         $sql = "SELECT id, code FROM $t_courses ORDER BY id";
@@ -386,12 +415,15 @@ class Plugin {
             $this->uninstall_course_fields($row['id']);
         }
     }
+
     /**
      * Method to be extended when changing the setting in the course
      * configuration should trigger the use of a callback method
      * @param array Values sent back from the course configuration script
      * @return void
      */
-    public function course_settings_updated($values = array()) {
+    public function course_settings_updated($values = array())
+    {
+
     }
 }

+ 121 - 68
main/inc/lib/plugin.lib.php

@@ -1,34 +1,36 @@
 <?php
 /* See license terms in /license.txt */
 
-class AppPlugin {
-    var $plugin_regions = array (
- //           'loginpage_main',
-            'login_top',
-            'login_bottom',
-            'menu_top',
-            'menu_bottom',
-/*            'campushomepage_main',
-            'campushomepage_menu',
-            'mycourses_main',
-            'mycourses_menu',*/
-            'content_top',
-            'content_bottom',
-            'header_main',
-            'header_center',
-            'header_left',
-            'header_right',
-            //'footer',
-            'footer_left',
-            'footer_center',
-            'footer_right',
-            'course_tool_plugin'
+class AppPlugin
+{
+    public $plugin_regions = array(
+        'main_top',
+        'main_bottom',
+        'login_top',
+        'login_bottom',
+        'menu_top',
+        'menu_bottom',
+        'content_top',
+        'content_bottom',
+        'header_main',
+        'header_center',
+        'header_left',
+        'header_right',
+        'footer_left',
+        'footer_center',
+        'footer_right',
+        'course_tool_plugin'
     );
 
-    function __construct() {
+    public function __construct()
+    {
     }
 
-    function read_plugins_from_path() {
+    /**
+     * @return array
+     */
+    function read_plugins_from_path()
+    {
         /* We scan the plugin directory. Each folder is a potential plugin. */
         $pluginpath = api_get_path(SYS_PLUGIN_PATH);
         $possible_plugins = array();
@@ -43,7 +45,11 @@ class AppPlugin {
         return $possible_plugins;
     }
 
-    function get_installed_plugins_by_region(){
+    /**
+     * @return array
+     */
+    function get_installed_plugins_by_region()
+    {
         $used_plugins = array();
         /* We retrieve all the active plugins. */
         $result = api_get_settings('Plugins');
@@ -53,7 +59,11 @@ class AppPlugin {
         return $used_plugins;
     }
 
-    function get_installed_plugins() {
+    /**
+     * @return array
+     */
+    function get_installed_plugins()
+    {
         $installed_plugins = array();
         $plugin_array = api_get_settings_params(array("variable = ? AND selected_value = ? AND category = ? " =>
                                                 array('status', 'installed', 'Plugins')));
@@ -67,7 +77,12 @@ class AppPlugin {
         return $installed_plugins;
     }
 
-    function install($plugin_name, $access_url_id = null) {
+    /**
+     * @param string $plugin_name
+     * @param int $access_url_id
+     */
+    function install($plugin_name, $access_url_id = null)
+    {
         if (empty($access_url_id)) {
             $access_url_id = api_get_current_access_url_id();
         } else {
@@ -84,7 +99,12 @@ class AppPlugin {
         }
     }
 
-    function uninstall($plugin_name, $access_url_id = null) {
+    /**
+     * @param string $plugin_name
+     * @param int $access_url_id
+     */
+    public function uninstall($plugin_name, $access_url_id = null)
+    {
         if (empty($access_url_id)) {
             $access_url_id = api_get_current_access_url_id();
         } else {
@@ -99,7 +119,12 @@ class AppPlugin {
         }
     }
 
-    function get_areas_by_plugin($plugin_name) {
+    /**
+     * @param string $plugin_name
+     * @return array
+     */
+    public function get_areas_by_plugin($plugin_name)
+    {
         $result = api_get_settings('Plugins');
         $areas = array();
         foreach ($result as $row) {
@@ -110,11 +135,13 @@ class AppPlugin {
         return $areas;
     }
 
-    function is_valid_plugin_location($location) {
+    function is_valid_plugin_location($location)
+    {
         return in_array($location, $this->plugin_list);
     }
 
-    function is_valid_plugin($plugin_name) {
+    function is_valid_plugin($plugin_name)
+    {
         if (is_dir(api_get_path(SYS_PLUGIN_PATH).$plugin_name)) {
             if (is_file(api_get_path(SYS_PLUGIN_PATH).$plugin_name.'/index.php')) {
                 return true;
@@ -123,19 +150,21 @@ class AppPlugin {
         return false;
     }
 
-    function get_plugin_regions() {
+    function get_plugin_regions()
+    {
         sort($this->plugin_regions);
         return $this->plugin_regions;
     }
 
-    function load_region($region, $main_template, $forced = false) {        
-        if ($region == 'course_tool_plugin') {                        
-            return null;       
+    function load_region($region, $main_template, $forced = false)
+    {
+        if ($region == 'course_tool_plugin') {
+            return null;
         }
         ob_start();
         $this->get_all_plugin_contents_by_region($region, $main_template, $forced);
         $content = ob_get_contents();
-        ob_end_clean();        
+        ob_end_clean();
         return $content;
     }
 
@@ -145,29 +174,30 @@ class AppPlugin {
      * @todo add caching
      * @param string $plugin_name
      */
-    function load_plugin_lang_variables($plugin_name) {
+    function load_plugin_lang_variables($plugin_name)
+    {
         global $language_interface;
         $root = api_get_path(SYS_PLUGIN_PATH);
 
-        //1. Loading english if exists
-        $english_path = $root.$plugin_name."/lang/english.php";     
+        // 1. Loading english if exists
+        $english_path = $root.$plugin_name."/lang/english.php";
 
         if (is_readable($english_path)) {
             include $english_path;
-   
-            foreach ($strings as $key => $string) {                
+
+            foreach ($strings as $key => $string) {
                 $GLOBALS[$key] = $string;
             }
         }
 
-        //2. Loading the system language
+        // 2. Loading the system language
         if ($language_interface != 'english') {
             $path = $root.$plugin_name."/lang/$language_interface.php";
 
             if (is_readable($path)) {
                 include $path;
                 if (!empty($strings)) {
-                    foreach ($strings as $key => $string) {                        
+                    foreach ($strings as $key => $string) {
                         $GLOBALS[$key] = $string;
                     }
                 }
@@ -176,21 +206,21 @@ class AppPlugin {
     }
 
     /**
-     *
      *
      * @param string $block
      * @param obj   template obj
      * @todo improve this function
      */
-    function get_all_plugin_contents_by_region($region, $template, $forced = false) {
-        global $_plugins;                
+    function get_all_plugin_contents_by_region($region, $template, $forced = false)
+    {
+        global $_plugins;
         if (isset($_plugins[$region]) && is_array($_plugins[$region])) {
-        //if (1) {        
+        //if (1) {
             //Load the plugin information
             foreach ($_plugins[$region] as $plugin_name) {
 
                 //The plugin_info variable is available inside the plugin index
-                $plugin_info = $this->get_plugin_info($plugin_name, $forced);                
+                $plugin_info = $this->get_plugin_info($plugin_name, $forced);
 
                 //We also know where the plugin is
                 $plugin_info['current_region'] = $region;
@@ -247,14 +277,15 @@ class AppPlugin {
      * @todo filter setting_form
      * @return array
      */
-    function get_plugin_info($plugin_name, $forced = false) {
+    function get_plugin_info($plugin_name, $forced = false)
+    {
         static $plugin_data = array();
-        
+
         if (isset($plugin_data[$plugin_name]) && $forced == false) {
             return $plugin_data[$plugin_name];
         } else {
             $plugin_file = api_get_path(SYS_PLUGIN_PATH)."$plugin_name/plugin.php";
-            
+
             $plugin_info = array();
             if (file_exists($plugin_file)) {
                 require $plugin_file;
@@ -268,15 +299,18 @@ class AppPlugin {
                 $settings_filtered[$item['variable']] = $item['selected_value'];
             }
             $plugin_info['settings'] = $settings_filtered;
-            $plugin_data[$plugin_name] = $plugin_info;            
+            $plugin_data[$plugin_name] = $plugin_info;
             return $plugin_info;
         }
     }
 
-    /*
+    /**
      * Get the template list
+     * @param  string $plugin_name
+     * @return bool
      */
-    function get_templates_list($plugin_name) {
+    function get_templates_list($plugin_name)
+    {
         $plugin_info = $this->get_plugin_info($plugin_name);
         if (isset($plugin_info) && isset($plugin_info['templates'])) {
             return $plugin_info['templates'];
@@ -285,10 +319,11 @@ class AppPlugin {
         }
     }
 
-    /* *
+    /**
      * Remove all regions of an specific plugin
      */
-    function remove_all_regions($plugin) {
+    public function remove_all_regions($plugin)
+    {
         $access_url_id = api_get_current_access_url_id();
         if (!empty($plugin)) {
             api_delete_settings_params(array('category = ? AND type = ? AND access_url = ? AND subkey = ? ' =>
@@ -297,15 +332,22 @@ class AppPlugin {
         }
     }
 
-    /*
+    /**
      * Add a plugin to a region
+     * @param string $plugin
+     * @param string $region
      */
-    function add_to_region($plugin, $region) {
+    function add_to_region($plugin, $region)
+    {
         $access_url_id = api_get_current_access_url_id();
         api_add_setting($plugin, $region, $plugin, 'region', 'Plugins', $plugin, null, null, null, $access_url_id, 1);
     }
 
-    function install_course_plugins($course_id) {
+    /**
+     * @param int $course_id
+     */
+    function install_course_plugins($course_id)
+    {
         $plugin_list = $this->get_installed_plugins();
 
         if (!empty($plugin_list)) {
@@ -321,7 +363,11 @@ class AppPlugin {
         }
     }
 
-    function add_course_settings_form($form) {
+    /**
+     * @param FormValidator $form
+     */
+    function add_course_settings_form($form)
+    {
         $plugin_list = $this->get_installed_plugins();
         foreach ($plugin_list as $plugin_name) {
             $plugin_info = $this->get_plugin_info($plugin_name);
@@ -357,7 +403,11 @@ class AppPlugin {
         }
     }
 
-    function set_course_settings_defaults(& $values) {
+    /**
+     * @param array $values
+     */
+    function set_course_settings_defaults(& $values)
+    {
         $plugin_list = $this->get_installed_plugins();
         foreach ($plugin_list as $plugin_name) {
             $plugin_info = $this->get_plugin_info($plugin_name);
@@ -376,13 +426,15 @@ class AppPlugin {
             }
         }
     }
+
     /**
-     * When saving the plugin values in the course settings, check whether 
+     * When saving the plugin values in the course settings, check whether
      * a callback method should be called and send it the updated settings
      * @param array The new settings the user just saved
      * @return void
      */
-    function save_course_settings($values) {
+    function save_course_settings($values)
+    {
         $plugin_list = $this->get_installed_plugins();
         foreach ($plugin_list as $plugin_name) {
             $settings = $this->get_plugin_course_settings($plugin_name);
@@ -396,7 +448,7 @@ class AppPlugin {
             }
             if ($i>0) {
                 $plugin_info = $this->get_plugin_info($plugin_name);
-                
+
                 if (isset($plugin_info['plugin_class'])) {
                     $obj = $plugin_info['plugin_class']::create();
                     $obj->course_settings_updated($subvalues);
@@ -404,17 +456,18 @@ class AppPlugin {
             }
         }
     }
-    
+
     /**
      * Gets a nice array of keys for just the plugin's course settings
      * @param string The plugin ID
      * @return array Nice array of keys for course settings
-     */ 
-    public function get_plugin_course_settings($plugin_name) {
+     */
+    public function get_plugin_course_settings($plugin_name)
+    {
         $settings = array();
         if (empty($plugin_name)) { return $settings; }
         $plugin_info = $this->get_plugin_info($plugin_name);
-        
+
         if (isset($plugin_info['plugin_class'])) {
             $obj = $plugin_info['plugin_class']::create();
             if (is_array($obj->course_settings)) {

+ 8 - 6
main/inc/lib/sessionmanager.lib.php

@@ -16,9 +16,9 @@
  */
 class SessionManager
 {
-	private function __construct()
+    private function __construct()
     {
-	}
+    }
 
     /**
     * Fetches a session from the database
@@ -27,7 +27,7 @@ class SessionManager
     */
     public static function fetch($id)
     {
-    	$t = Database::get_main_table(TABLE_MAIN_SESSION);
+        $t = Database::get_main_table(TABLE_MAIN_SESSION);
         if ($id != strval(intval($id))) {
             return array();
         }
@@ -60,7 +60,7 @@ class SessionManager
     * @todo use an array to replace all this parameters or use the model.lib.php ...
     * @return mixed       Session ID on success, error message otherwise
     **/
-	public static function create_session($sname,$syear_start,$smonth_start,$sday_start,$syear_end,$smonth_end,$sday_end,$snb_days_acess_before,$snb_days_acess_after, $nolimit,$coach_username, $id_session_category,$id_visibility, $start_limit = true, $end_limit = true, $fix_name = false)
+    public static function create_session($sname,$syear_start,$smonth_start,$sday_start,$syear_end,$smonth_end,$sday_end,$snb_days_acess_before,$snb_days_acess_after, $nolimit,$coach_username, $id_session_category,$id_visibility, $start_limit = true, $end_limit = true, $fix_name = false)
     {
 		global $_configuration;
 
@@ -888,7 +888,8 @@ class SessionManager
 	 * @param int User id
 	 * @return bool True in case of success, false in case of error
 	 */
-	public static function unsubscribe_user_from_session($session_id, $user_id) {
+	public static function unsubscribe_user_from_session($session_id, $user_id)
+    {
 		$session_id = (int)$session_id;
 		$user_id = (int)$user_id;
 
@@ -1710,7 +1711,7 @@ class SessionManager
                 WHERE id_coach = $user_id";
 
         if (api_is_multiple_url_enabled()) {
-            $tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+            $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
             $access_url_id = api_get_current_access_url_id();
             if ($access_url_id != -1) {
                 $sql = 'SELECT DISTINCT session.*
@@ -2672,6 +2673,7 @@ class SessionManager
     /**
      * @param array $sessions
      * @param array $courses
+     * @return string
      */
     public static function copyCoachesFromSessionToCourse($sessions, $courses)
     {

+ 383 - 307
main/inc/lib/skill.lib.php

@@ -1,41 +1,46 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
-*   This class provides methods for the notebook management.
-*   Include/require it in your code to use its features.
-*   @package chamilo.library
-*/
+ *   This class provides methods for the notebook management.
+ *   Include/require it in your code to use its features.
+ * @package chamilo.library
+ */
 /**
  * Code
  */
-define ('SKILL_TYPE_REQUIREMENT',   'required');
-define ('SKILL_TYPE_ACQUIRED',      'acquired');
-define ('SKILL_TYPE_BOTH',          'both');
+define ('SKILL_TYPE_REQUIREMENT', 'required');
+define ('SKILL_TYPE_ACQUIRED', 'acquired');
+define ('SKILL_TYPE_BOTH', 'both');
 
 require_once api_get_path(LIBRARY_PATH).'model.lib.php';
 
-class SkillProfile extends Model {
-    var $columns = array('id', 'name', 'description');
-    public function __construct() {
-        $this->table = Database::get_main_table(TABLE_MAIN_SKILL_PROFILE);
+class SkillProfile extends Model
+{
+    public $columns = array('id', 'name', 'description');
+
+    public function __construct()
+    {
+        $this->table             = Database::get_main_table(TABLE_MAIN_SKILL_PROFILE);
         $this->table_rel_profile = Database::get_main_table(TABLE_MAIN_SKILL_REL_PROFILE);
     }
 
-    public function get_profiles() {
-        $sql = "SELECT * FROM $this->table p INNER JOIN $this->table_rel_profile sp ON(p.id = sp.profile_id) ";
-        $result     = Database::query($sql);
-        $profiles   = Database::store_result($result,'ASSOC');
+    public function get_profiles()
+    {
+        $sql      = "SELECT * FROM $this->table p INNER JOIN $this->table_rel_profile sp ON(p.id = sp.profile_id) ";
+        $result   = Database::query($sql);
+        $profiles = Database::store_result($result, 'ASSOC');
         return $profiles;
     }
 
-    public function save($params, $show_query = false) {
+    public function save($params, $show_query = false)
+    {
         if (!empty($params)) {
-           $profile_id = parent::save($params, $show_query);
+            $profile_id = parent::save($params, $show_query);
             if ($profile_id) {
                 $skill_rel_profile = new SkillRelProfile();
                 if (isset($params['skills'])) {
-                    foreach($params['skills'] as $skill_id) {
-                        $attributes = array('skill_id' => $skill_id, 'profile_id'=>$profile_id);
+                    foreach ($params['skills'] as $skill_id) {
+                        $attributes = array('skill_id' => $skill_id, 'profile_id' => $profile_id);
                         $skill_rel_profile->save($attributes);
                     }
                 }
@@ -46,17 +51,21 @@ class SkillProfile extends Model {
     }
 }
 
-class SkillRelProfile extends Model {
-    var $columns = array('id', 'skill_id', 'profile_id');
-    public function __construct() {
+class SkillRelProfile extends Model
+{
+    public $columns = array('id', 'skill_id', 'profile_id');
+
+    public function __construct()
+    {
         $this->table = Database::get_main_table(TABLE_MAIN_SKILL_REL_PROFILE);
     }
 
-    public function get_skills_by_profile($profile_id) {
-        $skills =  $this->get_all(array('where'=>array('profile_id = ? ' => $profile_id)));
+    public function get_skills_by_profile($profile_id)
+    {
+        $skills       = $this->get_all(array('where' => array('profile_id = ? ' => $profile_id)));
         $return_array = array();
         if (!empty($skills)) {
-            foreach($skills as $skill_data) {
+            foreach ($skills as $skill_data) {
                 $return_array[] = $skill_data['skill_id'];
             }
         }
@@ -64,29 +73,36 @@ class SkillRelProfile extends Model {
     }
 }
 
-class SkillRelSkill extends Model {
-    var $columns = array('skill_id', 'parent_id','relation_type', 'level');
-    public function __construct() {
+class SkillRelSkill extends Model
+{
+    public $columns = array('skill_id', 'parent_id', 'relation_type', 'level');
+
+    public function __construct()
+    {
         $this->table = Database::get_main_table(TABLE_MAIN_SKILL_REL_SKILL);
     }
 
     /**
      * Gets an element
      */
-    public function get_skill_info($id) {
-        if (empty($id)) { return array(); }
-        $result = Database::select('*',$this->table, array('where'=>array('skill_id = ?'=>intval($id))), 'first');
+    public function get_skill_info($id)
+    {
+        if (empty($id)) {
+            return array();
+        }
+        $result = Database::select('*', $this->table, array('where' => array('skill_id = ?' => intval($id))), 'first');
         return $result;
     }
 
-    public function get_skill_parents($skill_id, $add_child_info = true) {
+    public function get_skill_parents($skill_id, $add_child_info = true)
+    {
         $skill_id = intval($skill_id);
-        $sql = 'SELECT child.* FROM '.$this->table.' child LEFT JOIN '.$this->table.' parent
+        $sql      = 'SELECT child.* FROM '.$this->table.' child LEFT JOIN '.$this->table.' parent
                 ON child.parent_id = parent.skill_id
                 WHERE child.skill_id = '.$skill_id.' ';
-        $result = Database::query($sql);
-        $skill  = Database::store_result($result,'ASSOC');
-        $skill  = isset($skill[0]) ? $skill[0] : null;
+        $result   = Database::query($sql);
+        $skill    = Database::store_result($result, 'ASSOC');
+        $skill    = isset($skill[0]) ? $skill[0] : null;
 
         $parents = array();
         if (!empty($skill)) {
@@ -100,62 +116,69 @@ class SkillRelSkill extends Model {
         return $parents;
     }
 
-    public function get_direct_parents($skill_id) {
+    public function get_direct_parents($skill_id)
+    {
         $skill_id = intval($skill_id);
-        $sql = 'SELECT parent_id as skill_id FROM '.$this->table.'
+        $sql      = 'SELECT parent_id as skill_id FROM '.$this->table.'
                 WHERE skill_id = '.$skill_id.' ';
-        $result = Database::query($sql);
-        $skill  = Database::store_result($result,'ASSOC');
-        $skill  = isset($skill[0]) ? $skill[0] : null;
-        $parents = array();
+        $result   = Database::query($sql);
+        $skill    = Database::store_result($result, 'ASSOC');
+        $skill    = isset($skill[0]) ? $skill[0] : null;
+        $parents  = array();
         if (!empty($skill)) {
             $parents[] = $skill;
         }
         return $parents;
     }
-    
 
-    public function get_children($skill_id, $load_user_data = false, $user_id = false) {
-        $skills = $this->find('all', array('where'=> array('parent_id = ? '=> $skill_id)));
-        $skill_obj = new Skill();
+
+    public function get_children($skill_id, $load_user_data = false, $user_id = false)
+    {
+        $skills         = $this->find('all', array('where' => array('parent_id = ? ' => $skill_id)));
+        $skill_obj      = new Skill();
         $skill_rel_user = new SkillRelUser();
 
         if ($load_user_data) {
             $passed_skills = $skill_rel_user->get_user_skills($user_id);
-            $done_skills = array();
+            $done_skills   = array();
             foreach ($passed_skills as $done_skill) {
                 $done_skills[] = $done_skill['skill_id'];
             }
         }
-        
+
         if (!empty($skills)) {
             foreach ($skills as &$skill) {
                 $skill['data'] = $skill_obj->get($skill['skill_id']);
                 if (isset($skill['data']) && !empty($skill['data'])) {
                     if (!empty($done_skills)) {
-                        $skill['data']['passed'] =  0;
+                        $skill['data']['passed'] = 0;
                         if (in_array($skill['skill_id'], $done_skills)) {
-                            $skill['data']['passed'] =  1;
+                            $skill['data']['passed'] = 1;
                         }
                     }
                 } else {
-                    $skill  = null;
+                    $skill = null;
                 }
             }
         }
         return $skills;
     }
 
-    function update_by_skill($params) {
-        $result = Database::update($this->table, $params, array('skill_id = ? '=> $params['skill_id']));
+    function update_by_skill($params)
+    {
+        $result = Database::update($this->table, $params, array('skill_id = ? ' => $params['skill_id']));
         if ($result) {
             return true;
         }
         return false;
     }
 
-    function relation_exists($skill_id, $parent_id) {
-        $result = $this->find('all', array('where'=>array('skill_id = ? AND parent_id = ?' => array($skill_id, $parent_id))));
+    function relation_exists($skill_id, $parent_id)
+    {
+        $result = $this->find(
+            'all',
+            array('where' => array('skill_id = ? AND parent_id = ?' => array($skill_id, $parent_id)))
+        );
         if (!empty($result)) {
             return true;
         }
@@ -163,18 +186,24 @@ class SkillRelSkill extends Model {
     }
 }
 
- /**
+/**
  * @package chamilo.library
  */
-class SkillRelGradebook extends Model {
-    var $columns = array('id', 'gradebook_id','skill_id');
+class SkillRelGradebook extends Model
+{
+    public $columns = array('id', 'gradebook_id', 'skill_id');
 
-    public function __construct() {
+    public function __construct()
+    {
         $this->table = Database::get_main_table(TABLE_MAIN_SKILL_REL_GRADEBOOK);
     }
 
-    public function exists_gradebook_skill($gradebook_id, $skill_id) {
-        $result = $this->find('all', array('where'=>array('gradebook_id = ? AND skill_id = ?' => array($gradebook_id, $skill_id))));
+    public function exists_gradebook_skill($gradebook_id, $skill_id)
+    {
+        $result = $this->find(
+            'all',
+            array('where' => array('gradebook_id = ? AND skill_id = ?' => array($gradebook_id, $skill_id)))
+        );
         if (!empty($result)) {
             return true;
         }
@@ -184,16 +213,25 @@ class SkillRelGradebook extends Model {
     /**
      * Gets an element
      */
-    public function get_skill_info($skill_id, $gradebook_id) {
-        if (empty($skill_id)) { return array(); }
-        $result = Database::select('*',$this->table, array('where'=>array('skill_id = ? AND gradebook_id = ? '=>array($skill_id, $gradebook_id))),'first');
+    public function get_skill_info($skill_id, $gradebook_id)
+    {
+        if (empty($skill_id)) {
+            return array();
+        }
+        $result = Database::select(
+            '*',
+            $this->table,
+            array('where' => array('skill_id = ? AND gradebook_id = ? ' => array($skill_id, $gradebook_id))),
+            'first'
+        );
         return $result;
     }
 
-    public function update_gradebooks_by_skill($skill_id, $gradebook_list) {
-        $original_gradebook_list = $this->find('all', array('where'=>array('skill_id = ?' => array($skill_id))));
-        $gradebooks_to_remove = array();
-        $gradebooks_to_add = array();
+    public function update_gradebooks_by_skill($skill_id, $gradebook_list)
+    {
+        $original_gradebook_list     = $this->find('all', array('where' => array('skill_id = ?' => array($skill_id))));
+        $gradebooks_to_remove        = array();
+        $gradebooks_to_add           = array();
         $original_gradebook_list_ids = array();
 
         if (!empty($original_gradebook_list)) {
@@ -202,33 +240,35 @@ class SkillRelGradebook extends Model {
                     $gradebooks_to_remove[] = $gradebook['id'];
                 }
             }
-            foreach($original_gradebook_list as $gradebook_item) {
+            foreach ($original_gradebook_list as $gradebook_item) {
                 $original_gradebook_list_ids[] = $gradebook_item['gradebook_id'];
             }
         }
 
-        if (!empty($gradebook_list))
-        foreach($gradebook_list as $gradebook_id) {
-            if (!in_array($gradebook_id, $original_gradebook_list_ids)) {
-                $gradebooks_to_add[] = $gradebook_id;
+        if (!empty($gradebook_list)) {
+            foreach ($gradebook_list as $gradebook_id) {
+                if (!in_array($gradebook_id, $original_gradebook_list_ids)) {
+                    $gradebooks_to_add[] = $gradebook_id;
+                }
             }
         }
         //var_dump($gradebooks_to_add, $gradebooks_to_remove);
         if (!empty($gradebooks_to_remove)) {
-            foreach($gradebooks_to_remove as $id) {
-               $this->delete($id);
+            foreach ($gradebooks_to_remove as $id) {
+                $this->delete($id);
             }
         }
 
         if (!empty($gradebooks_to_add)) {
-            foreach($gradebooks_to_add as $gradebook_id) {
-               $attributes = array('skill_id' => $skill_id, 'gradebook_id' => $gradebook_id);
-               $this->save($attributes);
+            foreach ($gradebooks_to_add as $gradebook_id) {
+                $attributes = array('skill_id' => $skill_id, 'gradebook_id' => $gradebook_id);
+                $this->save($attributes);
             }
         }
     }
 
-    function update_by_skill($params) {
+    function update_by_skill($params)
+    {
         $skill_info = $this->exists_gradebook_skill($params['gradebook_id'], $params['skill_id']);
 
         if ($skill_info) {
@@ -243,17 +283,21 @@ class SkillRelGradebook extends Model {
     }
 }
 
- /**
+/**
  * @package chamilo.library
  */
-class SkillRelUser extends Model {
-    var $columns = array('id', 'user_id','skill_id','acquired_skill_at','assigned_by');
-    public function __construct() {
-        $this->table        = Database::get_main_table(TABLE_MAIN_SKILL_REL_USER);
+class SkillRelUser extends Model
+{
+    public $columns = array('id', 'user_id', 'skill_id', 'acquired_skill_at', 'assigned_by');
+
+    public function __construct()
+    {
+        $this->table = Database::get_main_table(TABLE_MAIN_SKILL_REL_USER);
         //$this->table_user   = Database::get_main_table(TABLE_MAIN_USER);
     }
 
-    public function get_user_by_skills($skill_list) {
+    public function get_user_by_skills($skill_list)
+    {
         $users = array();
         if (!empty($skill_list)) {
             $skill_list = array_map('intval', $skill_list);
@@ -267,18 +311,27 @@ class SkillRelUser extends Model {
         return $users;
     }
 
-    public function get_user_skills($user_id) {
-        if (empty($user_id)) { return array(); }
-        $result = Database::select('skill_id',$this->table, array('where'=>array('user_id = ?'=>intval($user_id))), 'all');
+    public function get_user_skills($user_id)
+    {
+        if (empty($user_id)) {
+            return array();
+        }
+        $result = Database::select(
+            'skill_id',
+            $this->table,
+            array('where' => array('user_id = ?' => intval($user_id))),
+            'all'
+        );
         return $result;
     }
 }
 
 
-class Skill extends Model {
-    var $columns  = array('id', 'name','description', 'access_url_id', 'short_code');
-    var $required = array('name');
-    
+class Skill extends Model
+{
+    public $columns = array('id', 'name', 'description', 'access_url_id', 'short_code');
+    public $required = array('name');
+
     /** Array of colours by depth, for the coffee wheel. Each depth has 4 col */
     /*var $colours = array(
       0 => array('#f9f0ab', '#ecc099', '#e098b0', '#ebe378'),
@@ -294,27 +347,30 @@ class Skill extends Model {
      10 => array('#393e64', '#393e64', '#393e64', '#393e64'),
     );*/
 
-    public function __construct() {
-        $this->table                      = Database::get_main_table(TABLE_MAIN_SKILL);
-        $this->table_user                      = Database::get_main_table(TABLE_MAIN_USER);
-        $this->table_skill_rel_gradebook  = Database::get_main_table(TABLE_MAIN_SKILL_REL_GRADEBOOK);
-        $this->table_skill_rel_user       = Database::get_main_table(TABLE_MAIN_SKILL_REL_USER);
-        $this->table_course               = Database::get_main_table(TABLE_MAIN_COURSE);
-        $this->table_skill_rel_skill      = Database::get_main_table(TABLE_MAIN_SKILL_REL_SKILL);
-        $this->table_gradebook            = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
+    public function __construct()
+    {
+        $this->table                     = Database::get_main_table(TABLE_MAIN_SKILL);
+        $this->table_user                = Database::get_main_table(TABLE_MAIN_USER);
+        $this->table_skill_rel_gradebook = Database::get_main_table(TABLE_MAIN_SKILL_REL_GRADEBOOK);
+        $this->table_skill_rel_user      = Database::get_main_table(TABLE_MAIN_SKILL_REL_USER);
+        $this->table_course              = Database::get_main_table(TABLE_MAIN_COURSE);
+        $this->table_skill_rel_skill     = Database::get_main_table(TABLE_MAIN_SKILL_REL_SKILL);
+        $this->table_gradebook           = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
     }
 
-    function get_skill_info($id) {
+    function get_skill_info($id)
+    {
         $skill_rel_skill = new SkillRelSkill();
-        $skill_info = $this->get($id);
+        $skill_info      = $this->get($id);
         if (!empty($skill_info)) {
-            $skill_info['extra']        = $skill_rel_skill->get_skill_info($id);
-            $skill_info['gradebooks']   = self::get_gradebooks_by_skill($id);
+            $skill_info['extra']      = $skill_rel_skill->get_skill_info($id);
+            $skill_info['gradebooks'] = self::get_gradebooks_by_skill($id);
         }
         return $skill_info;
     }
 
-    function get_skills_info($skill_list) {
+    function get_skills_info($skill_list)
+    {
         $skill_list = array_map('intval', $skill_list);
         $skill_list = implode("', '", $skill_list);
 
@@ -325,10 +381,11 @@ class Skill extends Model {
         return $users;
     }
 
-    function get_all($load_user_data = false, $user_id = false, $id = null, $parent_id = null) {
-        $id_condition = '';        
+    function get_all($load_user_data = false, $user_id = false, $id = null, $parent_id = null)
+    {
+        $id_condition = '';
         if (isset($id) && !empty($id)) {
-            $id = intval($id);
+            $id           = intval($id);
             $id_condition = " WHERE s.id = $id";
         }
 
@@ -340,27 +397,27 @@ class Skill extends Model {
                 $id_condition = " AND ss.parent_id = $parent_id";
             }
         }
-        
-        $sql = "SELECT s.id, s.name, s.description, ss.parent_id, ss.relation_type 
+
+        $sql = "SELECT s.id, s.name, s.description, ss.parent_id, ss.relation_type
                 FROM {$this->table} s INNER JOIN {$this->table_skill_rel_skill} ss ON (s.id = ss.skill_id) $id_condition
                 ORDER BY ss.id, ss.parent_id";
-                        
+
         $result = Database::query($sql);
         $skills = array();
 
         if (Database::num_rows($result)) {
             while ($row = Database::fetch_array($result, 'ASSOC')) {
-                $skill_rel_skill = new SkillRelSkill();
-                $a = $skill_rel_skill->get_skill_parents($row['id']);
-                $row['level'] = count($a)-1;
-                $row['gradebooks'] = self::get_gradebooks_by_skill($row['id']);
+                $skill_rel_skill    = new SkillRelSkill();
+                $a                  = $skill_rel_skill->get_skill_parents($row['id']);
+                $row['level']       = count($a) - 1;
+                $row['gradebooks']  = self::get_gradebooks_by_skill($row['id']);
                 $skills[$row['id']] = $row;
             }
         }
-        
+
         /*
         if ($load_user_data && $user_id) {
-            $passed_skills = $this->get_user_skills($user_id);            
+            $passed_skills = $this->get_user_skills($user_id);
             foreach ($skills as &$skill) {
                 $skill['done_by_user'] = 0;
                 if (in_array($skill['id'], $passed_skills)) {
@@ -368,64 +425,68 @@ class Skill extends Model {
                 }
             }
         }*/
-  
-            
+
+
         //Load all children of the parent_id
-        if (!empty($skills) && !empty($parent_id)) {           
+        if (!empty($skills) && !empty($parent_id)) {
             foreach ($skills as $skill) {
-                $children = self::get_all($load_user_data, $user_id, $id, $skill['id']);               
-                 if (!empty($children)) {
+                $children = self::get_all($load_user_data, $user_id, $id, $skill['id']);
+                if (!empty($children)) {
                     //$skills = array_merge($skills, $children);
                     $skills = $skills + $children;
-                } 
-            }                  
+                }
+            }
         }
         return $skills;
     }
 
-    function get_gradebooks_by_skill($skill_id) {
+    function get_gradebooks_by_skill($skill_id)
+    {
         $skill_id = intval($skill_id);
-        $sql = "SELECT g.* FROM {$this->table_gradebook} g INNER JOIN {$this->table_skill_rel_gradebook} sg
+        $sql      = "SELECT g.* FROM {$this->table_gradebook} g INNER JOIN {$this->table_skill_rel_gradebook} sg
                     ON g.id = sg.gradebook_id
                  WHERE sg.skill_id = $skill_id";
-        $result = Database::query($sql);
-        $result = Database::store_result($result,'ASSOC');
+        $result   = Database::query($sql);
+        $result   = Database::store_result($result, 'ASSOC');
         return $result;
     }
-    
+
     /* Get one level childrens */
-    function get_children($skill_id, $load_user_data = false) {
+    function get_children($skill_id, $load_user_data = false)
+    {
         $skill_rel_skill = new SkillRelSkill();
         if ($load_user_data) {
             $user_id = api_get_user_id();
-            $skills = $skill_rel_skill->get_children($skill_id, true, $user_id);
+            $skills  = $skill_rel_skill->get_children($skill_id, true, $user_id);
         } else {
             $skills = $skill_rel_skill->get_children($skill_id);
         }
         return $skills;
     }
-    
+
     /* Get all children of the current node (recursive)*/
-    function get_all_children($skill_id) {
-        $skill_rel_skill = new SkillRelSkill();        
-        $children = $skill_rel_skill->get_children($skill_id);       
-        foreach ($children as $child) {             
-            $sub_children = $this->get_all_children($child['skill_id']);            
+    function get_all_children($skill_id)
+    {
+        $skill_rel_skill = new SkillRelSkill();
+        $children        = $skill_rel_skill->get_children($skill_id);
+        foreach ($children as $child) {
+            $sub_children = $this->get_all_children($child['skill_id']);
         }
         if (!empty($sub_children)) {
             $children = array_merge($children, $sub_children);
-        }        
+        }
         return $children;
     }
-    
+
 
     /**
      * Gets all parents from from the wanted skill
      */
-    function get_parents($skill_id) {
+    function get_parents($skill_id)
+    {
         $skill_rel_skill = new SkillRelSkill();
-        $skills = $skill_rel_skill->get_skill_parents($skill_id, true);
-        foreach($skills as &$skill) {
+        $skills          = $skill_rel_skill->get_skill_parents($skill_id, true);
+        foreach ($skills as &$skill) {
             $skill['data'] = self::get($skill['skill_id']);
         }
         return $skills;
@@ -434,29 +495,31 @@ class Skill extends Model {
     /**
      * All direct parents
      */
-    function get_direct_parents($skill_id) {
+    function get_direct_parents($skill_id)
+    {
         $skill_rel_skill = new SkillRelSkill();
-        $skills = $skill_rel_skill->get_direct_parents($skill_id, true);
-        foreach($skills as &$skill) {
-            $skill['data'] = self::get($skill['skill_id']);
-            $skill_info2 = $skill_rel_skill->get_skill_info($skill['skill_id']);
+        $skills          = $skill_rel_skill->get_direct_parents($skill_id, true);
+        foreach ($skills as &$skill) {
+            $skill['data']              = self::get($skill['skill_id']);
+            $skill_info2                = $skill_rel_skill->get_skill_info($skill['skill_id']);
             $skill['data']['parent_id'] = $skill_info2['parent_id'];
         }
         return $skills;
     }
-    
-    /* 
-     * Adds a new skill 
+
+    /*
+     * Adds a new skill
      */
-    public function add($params) {
+    public function add($params)
+    {
         if (!isset($params['parent_id'])) {
             $params['parent_id'] = 1;
         }
-        
+
         if (!is_array($params['parent_id'])) {
             $params['parent_id'] = array($params['parent_id']);
         }
-        
+
         $skill_rel_skill     = new SkillRelSkill();
         $skill_rel_gradebook = new SkillRelGradebook();
 
@@ -465,23 +528,23 @@ class Skill extends Model {
         $skill_id = $this->save($params);
         if ($skill_id) {
             //Saving skill_rel_skill (parent_id, relation_type)
-            
-            foreach ($params['parent_id'] as $parent_id) {   
-                $relation_exists = $skill_rel_skill->relation_exists($skill_id, $parent_id);                
+
+            foreach ($params['parent_id'] as $parent_id) {
+                $relation_exists = $skill_rel_skill->relation_exists($skill_id, $parent_id);
                 if (!$relation_exists) {
                     $attributes = array(
-                                    'skill_id'      => $skill_id,
-                                    'parent_id'     => $parent_id,
-                                    'relation_type' => $params['relation_type'],
-                                    //'level'         => $params['level'],
+                        'skill_id'      => $skill_id,
+                        'parent_id'     => $parent_id,
+                        'relation_type' => $params['relation_type'],
+                        //'level'         => $params['level'],
                     );
                     $skill_rel_skill->save($attributes);
                 }
-            }   
+            }
 
             if (!empty($params['gradebook_id'])) {
                 foreach ($params['gradebook_id'] as $gradebook_id) {
-                    $attributes = array();
+                    $attributes                 = array();
                     $attributes['gradebook_id'] = $gradebook_id;
                     $attributes['skill_id']     = $skill_id;
                     $skill_rel_gradebook->save($attributes);
@@ -491,71 +554,75 @@ class Skill extends Model {
         }
         return null;
     }
-    
-    public function add_skill_to_user($user_id, $gradebook_id) {
+
+    public function add_skill_to_user($user_id, $gradebook_id)
+    {
         $skill_gradebook = new SkillRelGradebook();
         $skill_rel_user  = new SkillRelUser();
 
-        $skill_gradebooks = $skill_gradebook->get_all(array('where'=>array('gradebook_id = ?' =>$gradebook_id)));
+        $skill_gradebooks = $skill_gradebook->get_all(array('where' => array('gradebook_id = ?' => $gradebook_id)));
         if (!empty($skill_gradebooks)) {
             foreach ($skill_gradebooks as $skill_gradebook) {
                 $user_has_skill = $this->user_has_skill($user_id, $skill_gradebook['skill_id']);
                 if (!$user_has_skill) {
-                    $params = array(    'user_id'   => $user_id,
-                                        'skill_id'  => $skill_gradebook['skill_id'],
-                                        'acquired_skill_at'  => api_get_utc_datetime(),
-                                   );
+                    $params = array(
+                        'user_id'           => $user_id,
+                        'skill_id'          => $skill_gradebook['skill_id'],
+                        'acquired_skill_at' => api_get_utc_datetime(),
+                    );
                     $skill_rel_user->save($params);
                 }
             }
         }
     }
-    
+
     /* Deletes a skill */
-    public function delete($skill_id) {
+    public function delete($skill_id)
+    {
         /*$params = array('skill_id' => $skill_id);
-        
+
         $skill_rel_skill     = new SkillRelSkill();
         $skills = $skill_rel_skill->get_all(array('where'=>array('skill_id = ?' =>$skill_id)));
-        
+
         $skill_rel_profile     = new SkillRelProfile();
         $skill_rel_gradebook = new SkillRelGradebook();
         $skill_rel_user     = new SkillRelUser();
-        
+
         $this->delete($skill_id);
-        
+
         $skill_rel_gradebook->delete($params);*/
-        
-    
+
+
     }
 
-    public function edit($params) {        
+    public function edit($params)
+    {
         if (!isset($params['parent_id'])) {
             $params['parent_id'] = 1;
         }
         $skill_rel_skill     = new SkillRelSkill();
         $skill_rel_gradebook = new SkillRelGradebook();
 
-        //Saving name, description        
+        //Saving name, description
         $this->update($params);
-        
+
         $skill_id = $params['id'];
 
         if ($skill_id) {
             //Saving skill_rel_skill (parent_id, relation_type)
-            
+
             if (!is_array($params['parent_id'])) {
                 $params['parent_id'] = array($params['parent_id']);
             }
-            
-            foreach ($params['parent_id'] as $parent_id) {   
-                $relation_exists = $skill_rel_skill->relation_exists($skill_id, $parent_id);                
+
+            foreach ($params['parent_id'] as $parent_id) {
+                $relation_exists = $skill_rel_skill->relation_exists($skill_id, $parent_id);
                 if (!$relation_exists) {
                     $attributes = array(
-                                    'skill_id'      => $skill_id,
-                                    'parent_id'     => $parent_id,
-                                    'relation_type' => $params['relation_type'],
-                                    //'level'         => $params['level'],
+                        'skill_id'      => $skill_id,
+                        'parent_id'     => $parent_id,
+                        'relation_type' => $params['relation_type'],
+                        //'level'         => $params['level'],
                     );
                     $skill_rel_skill->update_by_skill($attributes);
                 }
@@ -567,21 +634,21 @@ class Skill extends Model {
         return null;
     }
 
-
     /**
-    * Get user's skills
-    *
-    * @param int $userId User's id
-    */
+     * Get user's skills
+     *
+     * @param int $userId User's id
+     */
 
-    public function get_user_skills($user_id, $get_skill_data = false) {
+    public function get_user_skills($user_id, $get_skill_data = false)
+    {
         $user_id = intval($user_id);
-        $sql = 'SELECT DISTINCT s.id, s.name FROM '.$this->table_skill_rel_user.' u INNER JOIN '.$this->table.' s
+        $sql     = 'SELECT DISTINCT s.id, s.name FROM '.$this->table_skill_rel_user.' u INNER JOIN '.$this->table.' s
                 ON u.skill_id = s.id
                 WHERE user_id = '.$user_id;
 
-        $result = Database::query($sql);
-        $skills = Database::store_result($result, 'ASSOC');
+        $result      = Database::query($sql);
+        $skills      = Database::store_result($result, 'ASSOC');
         $clean_skill = array();
         if (!empty($skills)) {
             foreach ($skills as $skill) {
@@ -593,10 +660,11 @@ class Skill extends Model {
             }
         }
         return $clean_skill;
-    }    
+    }
 
-    public function get_skills_tree($user_id = null, $skill_id = null, $return_flat_array = false, $add_root = false) {
-        if ($skill_id == 1 ) {
+    public function get_skills_tree($user_id = null, $skill_id = null, $return_flat_array = false, $add_root = false)
+    {
+        if ($skill_id == 1) {
             $skill_id = 0;
         }
         if (isset($user_id) && !empty($user_id)) {
@@ -604,264 +672,272 @@ class Skill extends Model {
         } else {
             $skills = $this->get_all(false, false, null, $skill_id);
         }
-   
+
         $original_skill = $skills;
 
         //var_dump($skills);
-   
+
         //Show 1 item
         if (!empty($skill_id)) {
             if ($add_root) {
                 if (!empty($skill_id)) {
                     //Default root node
-                    $skills[1] = array('id' => '1', 'name' => get_lang('Root'), 'parent_id' => '0');
+                    $skills[1]  = array('id' => '1', 'name' => get_lang('Root'), 'parent_id' => '0');
                     $skill_info = $this->get_skill_info($skill_id);
-                    
+
                     //2nd node
                     $skills[$skill_id] = $skill_info;
                     //Uncomment code below to hide the searched skill
-                    $skills[$skill_id]['data']['parent_id'] =  $skill_info['parent_id'];                    
-                    $skills[$skill_id]['parent_id'] =  1;
-                    
+                    $skills[$skill_id]['data']['parent_id'] = $skill_info['parent_id'];
+                    $skills[$skill_id]['parent_id']         = 1;
+
                 }
             }
         }
-                
-        $refs = array();
+
+        $refs        = array();
         $skills_tree = null;
 
         // Create references for all nodes
-        $flat_array = array();      
-        $family = array();
-        
+        $flat_array = array();
+        $family     = array();
+
         if (!empty($skills)) {
             foreach ($skills as &$skill) {
                 if ($skill['parent_id'] == 0) {
                     $skill['parent_id'] = 'root';
                 }
-                                
+
                 // because except main keys (id, name, children) others keys are not saved while in the space tree
                 $skill['data'] = array('parent_id' => $skill['parent_id']);
-                  
+
                 //In order to paint all members of a family with the same color
-                if (empty($skill_id)) {                    
+                if (empty($skill_id)) {
                     if ($skill['parent_id'] == 1) {
-                        $family[$skill['id']] = $this->get_all_children($skill['id']);        
+                        $family[$skill['id']] = $this->get_all_children($skill['id']);
                     }
-                } else {                    
+                } else {
                     if ($skill['parent_id'] == $skill_id) {
-                        $family[$skill['id']] = $this->get_all_children($skill['id']);        
+                        $family[$skill['id']] = $this->get_all_children($skill['id']);
                     }
-                    
+
                     /*if ($skill_id == $skill['id']) {
-                        $skill['parent_id'] = 1;   
+                        $skill['parent_id'] = 1;
                     }*/
                 }
-                
-                
+
+
                 if (!isset($skill['data']['real_parent_id'])) {
                     $skill['data']['real_parent_id'] = $skill['parent_id'];
                 }
-                
+
                 //User achieved the skill (depends in the gradebook with certification)
-                $skill['data']['achieved'] = false;             
+                $skill['data']['achieved'] = false;
                 if ($user_id) {
-                    $skill['data']['achieved'] = $this->user_has_skill($user_id, $skill['id']);                    
+                    $skill['data']['achieved'] = $this->user_has_skill($user_id, $skill['id']);
                 }
-                
+
                 //Check if the skill has related gradebooks
-                $skill['data']['skill_has_gradebook'] = false;                
+                $skill['data']['skill_has_gradebook'] = false;
                 if (isset($skill['gradebooks']) && !empty($skill['gradebooks'])) {
                     $skill['data']['skill_has_gradebook'] = true;
                 }
-                $refs[$skill['id']] = &$skill;
-                $flat_array[$skill['id']] =  &$skill;
+                $refs[$skill['id']]       = & $skill;
+                $flat_array[$skill['id']] =  & $skill;
             }
             //var_dump($skills);
             //var_dump($refs);
-            
+
             //Checking family value
-            
-            $family_id = 1;
+
+            $family_id        = 1;
             $new_family_array = array();
-            foreach ($family as $main_family_id => $family_items) {                
+            foreach ($family as $main_family_id => $family_items) {
                 if (!empty($family_items)) {
                     foreach ($family_items as $item) {
                         $new_family_array[$item['skill_id']] = $family_id;
                     }
                 }
-                $new_family_array[$main_family_id] = $family_id;                
+                $new_family_array[$main_family_id] = $family_id;
                 $family_id++;
-            }  
+            }
 
             if (empty($original_skill)) {
-                $refs['root']['children'][0] = $skills[1];
-                $skills[$skill_id]['data']['family_id'] = 1;
+                $refs['root']['children'][0]                = $skills[1];
+                $skills[$skill_id]['data']['family_id']     = 1;
                 $refs['root']['children'][0]['children'][0] = $skills[$skill_id];
-                $flat_array[$skill_id] =  $skills[$skill_id];                
+                $flat_array[$skill_id]                      = $skills[$skill_id];
             } else {
                 // Moving node to the children index of their parents
-                foreach ($skills as $my_skill_id => &$skill) {                
-                    $skill['data']['family_id'] = $new_family_array[$skill['id']];
-                    $refs[$skill['parent_id']]['children'][] = &$skill;
-                    $flat_array[$my_skill_id] =  $skill;
-                }                
+                foreach ($skills as $my_skill_id => &$skill) {
+                    $skill['data']['family_id']              = $new_family_array[$skill['id']];
+                    $refs[$skill['parent_id']]['children'][] = & $skill;
+                    $flat_array[$my_skill_id]                = $skill;
+                }
             }
-            
+
             $skills_tree = array(
-                'name'      => get_lang('SkillRootName'),
-                'id'        => 'root',
-                'children'  => $refs['root']['children'],
-                'data'      => array()
-            );            
-        }                
+                'name'     => get_lang('SkillRootName'),
+                'id'       => 'root',
+                'children' => $refs['root']['children'],
+                'data'     => array()
+            );
+        }
         if ($return_flat_array) {
             return $flat_array;
         }
         unset($skills);
         return $skills_tree;
     }
-    
+
     /**
      * Get skills tree as a simplified JSON structure
      * @param int user id
      * @param int skill id
      * @param bool return a flat array or not
      * @param int depth of the skills
-     * 
+     *
      */
-    public function get_skills_tree_json($user_id = null, $skill_id = null, $return_flat_array = false, $main_depth = 2) {        
-        $tree = $this->get_skills_tree($user_id, $skill_id, $return_flat_array, true);
+    public function get_skills_tree_json($user_id = null, $skill_id = null, $return_flat_array = false, $main_depth = 2)
+    {
+        $tree        = $this->get_skills_tree($user_id, $skill_id, $return_flat_array, true);
         $simple_tree = array();
         if (!empty($tree['children'])) {
             foreach ($tree['children'] as $element) {
-                $simple_tree[] = array( 'name'      => $element['name'], 
-                                        'children'  => $this->get_skill_json($element['children'], 1, $main_depth),                                        
-                                        );
+                $simple_tree[] = array(
+                    'name'     => $element['name'],
+                    'children' => $this->get_skill_json($element['children'], 1, $main_depth),
+                );
             }
         }
         //var_dump($simple_tree[0]['children']);
         return json_encode($simple_tree[0]['children']);
     }
-    
+
     /**
      * Get JSON element
      */
-    public function get_skill_json($subtree, $depth = 1, $max_depth = 2) {
+    public function get_skill_json($subtree, $depth = 1, $max_depth = 2)
+    {
         $simple_sub_tree = array();
         if (is_array($subtree)) {
-            $counter = 1;            
+            $counter = 1;
             foreach ($subtree as $elem) {
-                $tmp = array();
+                $tmp         = array();
                 $tmp['name'] = $elem['name'];
-                $tmp['id'] = $elem['id'];
+                $tmp['id']   = $elem['id'];
 
                 if (is_array($elem['children'])) {
-                    $tmp['children'] = $this->get_skill_json($elem['children'], $depth+1, $max_depth);                                        
+                    $tmp['children'] = $this->get_skill_json($elem['children'], $depth + 1, $max_depth);
                 } else {
                     //$tmp['colour'] = $this->colours[$depth][rand(0,3)];
                 }
                 if ($depth > $max_depth) {
                     continue;
                 }
-                                
-                $tmp['depth'] = $depth;
+
+                $tmp['depth']   = $depth;
                 $tmp['counter'] = $counter;
                 $counter++;
-                
+
                 if (isset($elem['data']) && is_array($elem['data'])) {
                     foreach ($elem['data'] as $key => $item) {
                         $tmp[$key] = $item;
                     }
-                }                
+                }
                 $simple_sub_tree[] = $tmp;
             }
             return $simple_sub_tree;
         }
         return null;
     }
-    
-    function get_user_skill_ranking($user_id) {
-        $user_id = intval($user_id);        
-        $sql = "SELECT count(skill_id) count FROM {$this->table} s INNER JOIN {$this->table_skill_rel_user} su ON (s.id = su.skill_id)
+
+    function get_user_skill_ranking($user_id)
+    {
+        $user_id = intval($user_id);
+        $sql     = "SELECT count(skill_id) count FROM {$this->table} s INNER JOIN {$this->table_skill_rel_user} su ON (s.id = su.skill_id)
                 WHERE user_id = $user_id";
-        $result = Database::query($sql);        
+        $result  = Database::query($sql);
         if (Database::num_rows($result)) {
             $result = Database::fetch_row($result);
             return $result[0];
         }
-        return false;        
+        return false;
     }
-    
-    function get_user_list_skill_ranking($start, $limit, $sidx, $sord, $where_condition) {
+
+    function get_user_list_skill_ranking($start, $limit, $sidx, $sord, $where_condition)
+    {
         $start = intval($start);
         $limit = intval($limit);
         /*  ORDER BY $sidx $sord */
-        $sql = "SELECT *, @rownum:=@rownum+1 rank FROM (
-                        SELECT u.user_id, firstname, lastname, count(username) skills_acquired 
+        $sql    = "SELECT *, @rownum:=@rownum+1 rank FROM (
+                        SELECT u.user_id, firstname, lastname, count(username) skills_acquired
                         FROM {$this->table} s INNER JOIN {$this->table_skill_rel_user} su ON (s.id = su.skill_id)
                         INNER JOIN {$this->table_user} u ON u.user_id = su.user_id, (SELECT @rownum:=0) r
                         WHERE 1=1 $where_condition
                         GROUP BY username
-                        ORDER BY skills_acquired desc                   
-                        LIMIT $start , $limit)  AS T1, (SELECT @rownum:=0) r";        
-        $result = Database::query($sql);        
+                        ORDER BY skills_acquired desc
+                        LIMIT $start , $limit)  AS T1, (SELECT @rownum:=0) r";
+        $result = Database::query($sql);
         if (Database::num_rows($result)) {
             return Database::store_result($result, 'ASSOC');
         }
-        return array();       
+        return array();
     }
-    
-    function get_user_list_skill_ranking_count() {
-        $sql = "SELECT count(*) FROM (
+
+    function get_user_list_skill_ranking_count()
+    {
+        $sql    = "SELECT count(*) FROM (
                         SELECT count(distinct 1)
-                        FROM {$this->table} s INNER JOIN {$this->table_skill_rel_user} su ON (s.id = su.skill_id) 
+                        FROM {$this->table} s INNER JOIN {$this->table_skill_rel_user} su ON (s.id = su.skill_id)
                         INNER JOIN {$this->table_user} u ON u.user_id = su.user_id
                         GROUP BY username
                      ) as T1";
         $result = Database::query($sql);
         if (Database::num_rows($result)) {
             $result = Database::fetch_row($result);
-        
+
             return $result[0];
         }
         return 0;
     }
-    
-    function get_count_skills_by_course($course_code) {
+
+    function get_count_skills_by_course($course_code)
+    {
         $sql = "SELECT count(skill_id) as count FROM {$this->table_gradebook} g INNER JOIN {$this->table_skill_rel_gradebook} sg ON g.id = sg.gradebook_id
                 WHERE course_code = '$course_code'";
-        
+
         $result = Database::query($sql);
         if (Database::num_rows($result)) {
-            $result = Database::fetch_row($result);            
+            $result = Database::fetch_row($result);
             return $result[0];
         }
         return 0;
     }
-    
-    function get_courses_by_skill($skill_id) {
+
+    function get_courses_by_skill($skill_id)
+    {
         $skill_id = intval($skill_id);
-        $sql = "SELECT c.title, c.code FROM {$this->table_gradebook} g INNER JOIN {$this->table_skill_rel_gradebook} sg ON g.id = sg.gradebook_id
+        $sql      = "SELECT c.title, c.code FROM {$this->table_gradebook} g INNER JOIN {$this->table_skill_rel_gradebook} sg ON g.id = sg.gradebook_id
                  INNER JOIN {$this->table_course} c ON c.code = g.course_code
                  WHERE sg.skill_id = $skill_id";
-        $result = Database::query($sql);        
-        return Database::store_result($result, 'ASSOC');                 
+        $result   = Database::query($sql);
+        return Database::store_result($result, 'ASSOC');
     }
-    
-    
+
     /**
-    * Return true if the user has the skill
-    *
-    * @param int $userId User's id
-    * @param int $skillId Skill's id
-    * @param int $checkInParents if true, function will search also in parents of the given skill id
-    *
-    * @return bool
-    */
-    public function user_has_skill($user_id, $skill_id) {
+     * Return true if the user has the skill
+     *
+     * @param int $userId User's id
+     * @param int $skillId Skill's id
+     * @param int $checkInParents if true, function will search also in parents of the given skill id
+     *
+     * @return bool
+     */
+    public function user_has_skill($user_id, $skill_id)
+    {
         $skills = $this->get_user_skills($user_id);
-        foreach($skills as $my_skill_id) {
+        foreach ($skills as $my_skill_id) {
             if ($my_skill_id == $skill_id) {
                 return true;
             }

+ 3 - 2
main/inc/lib/usergroup.lib.php

@@ -597,7 +597,8 @@ class UserGroup extends Model
      */
     public function getUsergroupsPagination($sidx, $sord, $start, $limit)
     {
-        $sord = intval($sord);
+        $sord = in_array(strtolower($sord), array('asc', 'desc')) ? $sord : 'desc';
+
         $start = intval($start);
         $limit = intval($limit);
         if ($this->useMultipleUrl) {
@@ -632,7 +633,7 @@ class UserGroup extends Model
         }
 
         // Multidimensional sort
-        msort($result, $sidx);
+        $result = msort($result, $sidx, $sord);
         return $result;
     }
 

+ 20 - 16
main/inc/lib/userportal.lib.php

@@ -21,7 +21,7 @@ class IndexManager {
 		}
 	}
 
-	function set_login_form() {
+	function set_login_form($setLoginForm = true) {
 		global $loginFailed;
 
 		$login_form = '';
@@ -30,23 +30,27 @@ class IndexManager {
 
 			// Only display if the user isn't logged in.
 			$this->tpl->assign('login_language_form', api_display_language_form(true));
-			$this->tpl->assign('login_form',  self::display_login_form());
 
-			if ($loginFailed) {
-				$this->tpl->assign('login_failed',  self::handle_login_failed());
-			}
+            if ($setLoginForm) {
 
-			if (api_get_setting('allow_lostpassword') == 'true' || api_get_setting('allow_registration') == 'true') {
-				$login_form .= '<ul class="nav nav-list">';
-				if (api_get_setting('allow_registration') != 'false') {
-					$login_form .= '<li><a href="main/auth/inscription.php">'.get_lang('Reg').'</a></li>';
-				}
-				if (api_get_setting('allow_lostpassword') == 'true') {
-					$login_form .= '<li><a href="main/auth/lostPassword.php">'.get_lang('LostPassword').'</a></li>';
-				}
-				$login_form .= '</ul>';
-			}
-			$this->tpl->assign('login_options',  $login_form);
+                $this->tpl->assign('login_form',  self::display_login_form());
+
+                if ($loginFailed) {
+                    $this->tpl->assign('login_failed',  self::handle_login_failed());
+                }
+
+                if (api_get_setting('allow_lostpassword') == 'true' || api_get_setting('allow_registration') == 'true') {
+                    $login_form .= '<ul class="nav nav-list">';
+                    if (api_get_setting('allow_registration') != 'false') {
+                        $login_form .= '<li><a href="main/auth/inscription.php">'.get_lang('Reg').'</a></li>';
+                    }
+                    if (api_get_setting('allow_lostpassword') == 'true') {
+                        $login_form .= '<li><a href="main/auth/lostPassword.php">'.get_lang('LostPassword').'</a></li>';
+                    }
+                    $login_form .= '</ul>';
+                }
+                $this->tpl->assign('login_options',  $login_form);
+            }
 		}
 	}
 

+ 47 - 25
main/newscorm/learnpath.class.php

@@ -13,7 +13,8 @@
  * @package chamilo.learnpath
  */
 
-class learnpath {
+class learnpath
+{
 
     public $attempt = 0; // The number for the current ID view.
     public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
@@ -76,27 +77,17 @@ class learnpath {
     public $course_int_id;
     public $course_info = array();
 
-    public function get_course_int_id() {
-        return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
-    }
-
-    public function set_course_int_id($course_id) {
-        return $this->course_int_id = intval($course_id);
-    }
-
     /**
-     * Class constructor. Needs a database handler, a course code and a learnpath id from the database.
-     * Also builds the list of items into $this->items.
-     * @param	string		Course code
-     * @param	integer		Learnpath ID
-     * @param	integer		User ID
-     * @return	boolean		True on success, false on error
-     */
-    public function __construct($course, $lp_id, $user_id) {
+    * Class constructor. Needs a database handler, a course code and a learnpath id from the database.
+    * Also builds the list of items into $this->items.
+    * @param	string		Course code
+    * @param	integer		Learnpath ID
+    * @param	integer		User ID
+    * @return	boolean		True on success, false on error
+    */
+    public function __construct($course, $lp_id, $user_id)
+    {
         $this->encoding = api_get_system_encoding(); // Chamilo 1.8.8: We intend always to use the system encoding.
-        // Check course code.
-        $course_id = api_get_course_int_id();
-
         if ($this->debug > 0) { error_log('New LP - In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')', 0); }
         if (empty($course)) {
             $this->error = 'Course code is empty';
@@ -108,7 +99,7 @@ class learnpath {
                 $this->course_info  = $course_info;
                 $course_id 	        = $course_info['real_id'];
             } else {
-                $this->error = 'Course code does not exist in database ('.$sql.')';
+                $this->error = 'Course code does not exist in database.';
                 return false;
             }
         }
@@ -380,8 +371,35 @@ class learnpath {
     }
 
     /**
-     * Function rewritten based on old_add_item() from Yannick Warnier. Due the fact that users can decide where the item should come, I had to overlook this function and
-     * I found it better to rewrite it. Old function is still available. Added also the possibility to add a description.
+     * @return string
+     */
+    public function getCourseCode()
+    {
+        return $this->cc;
+    }
+
+    /**
+     * @return int
+     */
+    public function get_course_int_id()
+    {
+        return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
+    }
+
+    /**
+     * @param $course_id
+     * @return int
+     */
+    public function set_course_int_id($course_id)
+    {
+        return $this->course_int_id = intval($course_id);
+    }
+
+    /**
+     * Function rewritten based on old_add_item() from Yannick Warnier.
+     * Due the fact that users can decide where the item should come, I had to overlook this function and
+     * I found it better to rewrite it. Old function is still available.
+     * Added also the possibility to add a description.
      *
      * @param int $parent
      * @param int $previous
@@ -389,9 +407,12 @@ class learnpath {
      * @param int  resource ID (ref)
      * @param string $title
      * @param string $description
+     * @param int $prerequisites
+     * @param int $max_time_allowed
      * @return int
      */
-    public function add_item($parent, $previous, $type = 'dokeos_chapter', $id, $title, $description, $prerequisites = 0, $max_time_allowed = 0) {
+    public function add_item($parent, $previous, $type = 'dokeos_chapter', $id, $title, $description, $prerequisites = 0, $max_time_allowed = 0)
+    {
         $course_id = api_get_course_int_id();
         if ($this->debug > 0) {
             error_log('New LP - In learnpath::add_item(' . $parent . ',' . $previous . ',' . $type . ',' . $id . ',' . $title . ')', 0);
@@ -621,7 +642,8 @@ class learnpath {
      * @param	string	Zip file containing the learnpath or directory containing the learnpath
      * @return	integer	The new learnpath ID on success, 0 on failure
      */
-    public static function add_lp($course, $name, $description = '', $learnpath = 'guess', $origin = 'zip', $zipname = '', $publicated_on = '', $expired_on = '') {
+    public static function add_lp($course, $name, $description = '', $learnpath = 'guess', $origin = 'zip', $zipname = '', $publicated_on = '', $expired_on = '')
+    {
         global $charset;
         $course_id = api_get_course_int_id();
         $tbl_lp = Database :: get_course_table(TABLE_LP_MAIN);

+ 2 - 3
main/newscorm/lp_content.php

@@ -21,10 +21,9 @@ if (empty($lp_controller_touched)) {
     if ($debug > 0) {
         error_log('New lp - In lp_content.php - Redirecting to lp_controller', 0);
     }
-    header('location: lp_controller.php?action=content&lp_id='.Security::remove_XSS($_REQUEST['lp_id']).'&item_id='.Security::remove_XSS($_REQUEST['item_id']));
+    header('location: lp_controller.php?action=content&lp_id='.Security::remove_XSS($_REQUEST['lp_id']).'&item_id='.Security::remove_XSS($_REQUEST['item_id']).'&'.api_get_cidreq());
     exit;
 }
-
 $_SESSION['oLP']->error = '';
 $lp_type = $_SESSION['oLP']->get_type();
 $lp_item_id = $_SESSION['oLP']->get_current_item_id();
@@ -112,5 +111,5 @@ $_setting['show_navigation_menu'] = false;
 if ($debug > 0) {
     error_log('New LP - In lp_content.php - Loading '.$src, 0);
 }
-
 header("Location: ".urldecode($src));
+exit;

+ 7 - 7
main/newscorm/resourcelinker.inc.php

@@ -1602,13 +1602,12 @@ function rl_get_html_resource_link($course_code, $type, $id, $style='', $new_win
  * In each case, we query the corresponding table for information and build the link
  * with that information.
  * @author	Yannick Warnier <ywarnier@beeznest.org> - rebranding based on previous work (display_addedresource_link_in_learnpath())
- * @param	string	Course code
- * @param	integer	The learning path ID (in lp table)
- * @param	integer	The database ID for that item in the lp_item table
- * @param id          - that is the correspondent id in the mirror tool (like Agenda item 2)
- * @param id_in_path  - the unique index in the items table
+ * @param	int	Course code
+ * @param	int The learning path ID (in lp table)
+ * @param   int id_in_path  - the unique index in the items table
  */
-function rl_get_resource_link_for_learnpath($course_id, $learnpath_id, $id_in_path) {
+function rl_get_resource_link_for_learnpath($course_id, $learnpath_id, $id_in_path)
+{
     $tbl_lp_item 	= Database::get_course_table(TABLE_LP_ITEM);
 
     $course_info = api_get_course_info_by_id($course_id);
@@ -1746,7 +1745,8 @@ function rl_get_resource_link_for_learnpath($course_id, $learnpath_id, $id_in_pa
  * @param string 	The tool type (using constants declared in main_api.lib.php)
  * @param integer 	The resource ID
  */
-function rl_get_resource_name($course_code, $learnpath_id, $id_in_path) {
+function rl_get_resource_name($course_code, $learnpath_id, $id_in_path)
+{
     $_course = Database::get_course_info($course_code);
     $course_id = $_course['real_id'];
     $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);

+ 7 - 3
main/newscorm/scorm_api.php

@@ -35,6 +35,7 @@ require_once 'learnpathItem.class.php';
 require_once 'scorm.class.php';
 
 $file   = (empty($_SESSION['file'])?'':$_SESSION['file']);
+/** @var Learnpath $oLP */
 $oLP    = unserialize($_SESSION['lpobject']);
 $oItem 	= $oLP->items[$oLP->current];
 
@@ -157,7 +158,7 @@ olms.launch_data = '<?php echo $oItem->get_launch_data();?>';
 olms.max_time_allowed = '<?php echo $oItem->get_max_time_allowed();?>';
 olms.interactions = new Array(<?php echo $oItem->get_interactions_js_array();?>);
 olms.item_objectives = new Array();
-olms.info_lms_item=new Array();
+olms.info_lms_item = new Array();
 
 // Chamilo internal variables (not SCORM)
 // olms.saved_lesson_status = 'not attempted';
@@ -181,6 +182,9 @@ olms.lms_item_credit = '<?php echo $oItem->get_credit();?>';
 olms.lms_item_lesson_mode = '<?php echo $oItem->get_lesson_mode();?>';
 olms.lms_item_launch_data = '<?php echo $oItem->get_launch_data();?>';
 olms.lms_item_core_exit = '<?php echo $oItem->get_core_exit();?>';
+olms.lms_course_id = '<?php echo $oLP->get_course_int_id(); ?>';
+olms.lms_course_code = '<?php echo $oLP->getCourseCode(); ?>';
+
 <?php echo $oLP->get_items_details_as_js('olms.lms_item_types');?>
 
 olms.asset_timer = 0;
@@ -1462,10 +1466,10 @@ function switch_item(current_item, next_item){
             break;
     }
 
-    var mysrc = 'lp_controller.php?action=content&lp_id='+olms.lms_lp_id+'&item_id='+next_item;
+    var mysrc = 'lp_controller.php?action=content&lp_id='+olms.lms_lp_id+'&item_id='+next_item+'&cidReq='+olms.lms_course_code;
     var cont_f = $("#content_id");
 
-    <?php if($oLP->mode == 'fullscreen'){ ?>
+    <?php if($oLP->mode == 'fullscreen') { ?>
     cont_f = window.open(''+mysrc,'content_id','toolbar=0,location=0,status=0,scrollbars=1,resizable=1');
     cont_f.onload=function(){
         olms.info_lms_item[0]=olms.info_lms_item[1];

+ 15 - 1
main/template/default/layout/layout_1_col.tpl

@@ -3,10 +3,17 @@
 {#  1 column  #}
 {% block body %}
 
+    {# Plugin main top #}
+    {% if plugin_main_top %}
+        <div id="plugin_main_top" class="span12">
+            {{ plugin_main_top }}
+        </div>
+    {% endif %}
+
     {#  Plugin top  #}
     {% if plugin_content_top %}
         <div id="plugin_content_top" class="span12">
-            {{ plugin_content_top}}
+            {{ plugin_content_top }}
         </div>
     {% endif %}
 
@@ -29,4 +36,11 @@
             {{ plugin_content_bottom }}
         </div>
     {% endif %}
+
+    {# Plugin main bottom #}
+    {% if plugin_main_bottom %}
+        <div id="plugin_main_bottom" class="span12">
+            {{ plugin_main_bottom }}
+        </div>
+    {% endif %}
 {% endblock %}

+ 67 - 53
main/template/default/layout/layout_2_col.tpl

@@ -1,73 +1,80 @@
 {% extends "default/layout/main.tpl" %}
 
-{% block body %}	
+{% block body %}
 	{# Main content #}
-   
-	{#  Right column  #}
-	<div class="span3 menu-column">		        
+
+    {# Plugin main top #}
+    {% if plugin_main_top %}
+        <div id="plugin_main_top" class="span12">
+            {{ plugin_main_top }}
+        </div>
+    {% endif %}
+
+	{#  Right column #}
+	<div class="span3 menu-column">
         {% if plugin_menu_top %}
             <div id="plugin_menu_top">
                 {{plugin_menu_top}}
             </div>
-        {% endif %}  	
-        
+        {% endif %}
+
 	    {# if user is not login show the login form #}
 		{% if _u.logged  == 0 %}
 			{% include "default/layout/login_form.tpl" %}
 		{% endif %}
 
-		{#  User picture  #}
+		{# User picture #}
         {{ user_image_block }}
-        
-        {#  User Profile links #}
+
+        {# User Profile links #}
 		{{ profile_block }}
-        
-        {#  Course block - admin #}
+
+        {# Course block - admin #}
 		{{ course_block }}
-        
-        {#  Course block - teacher #}
+
+        {# Course block - teacher #}
 		{{ teacher_block }}
-		
-		{#  Notice  #}
+
+		{# Notice #}
 		{{ notice_block }}
-                    
-        {#  Help #}
+
+        {# Help #}
 		{{ help_block }}
-		
-		{#  Links that are not added in the tabs #}
+
+		{# Links that are not added in the tabs #}
 		{{ navigation_course_links }}
-		
-		{#  Reservation block  #}
+
+		{# Reservation block  #}
 		{{ reservation_block }}
-		
-		{#  Search (xapian) #}
+
+		{# Search (xapian) #}
 		{{ search_block }}
-		
-		{#  Classes  #}
+
+		{# Classes #}
 		{{ classes_block }}
-		
-		{#  Skills #}
+
+		{# Skills #}
 		{{ skills_block }}
-        	
-		{#  Plugin courses sidebar  #}		
-        {#  Plugins for footer section  #}		
-        
+
+		{# Plugin courses sidebar #}
+        {# Plugins for footer section #}
+
         {% if plugin_menu_bottom %}
             <div id="plugin_menu_bottom">
                 {{ plugin_menu_bottom }}
             </div>
-        {% endif %}        
+        {% endif %}
 	</div>
+
 	<div class="span9 content-column">
-        
-        {#  Plugin bottom  #}
+        {# Plugin bottom #}
         {% if plugin_content_top %}
             <div id="plugin_content_top">
                 {{ plugin_content_top }}
             </div>
         {% endif %}
-        
-		{#  Portal homepage  #}
+
+		{# Portal homepage #}
         {% if home_page_block %}
             <section id="homepage">
                 <div class="row">
@@ -77,32 +84,32 @@
                 </div>
             </section>
         {% endif %}
-        
+
 		{#  ??  #}
 		{{ sniff_notification }}
-		
+
         {% include "default/layout/page_body.tpl" %}
-                
-        {#  Welcome to course block  #}
-        {% if welcome_to_course_block %}      
+
+        {# Welcome to course block  #}
+        {% if welcome_to_course_block %}
             <section id="welcome_to_course">
             {{ welcome_to_course_block }}
             </section>
         {% endif %}
-                
+
         {% if content is not null %}
             <section id="main_content">
                 {{ content }}
             </section>
         {% endif %}
-        		
-		{#  Announcements  #}
-        {% if announcements_block %}      
+
+		{# Announcements  #}
+        {% if announcements_block %}
             <section id="announcements">
             {{ announcements_block }}
             </section>
         {% endif %}
-        
+
         {# Course categories (must be turned on in the admin settings) #}
         {% if course_category_block %}
             <section id="course_category">
@@ -113,17 +120,24 @@
                 </div>
             </section>
         {% endif %}
-                	
-		{#  Hot courses template  #}		
-		{% include "default/layout/hot_courses.tpl" %}        
-        
-        {#  Content bottom  #}
-        {% if plugin_content_bottom %}       
+
+		{# Hot courses template  #}
+		{% include "default/layout/hot_courses.tpl" %}
+
+        {# Content bottom  #}
+        {% if plugin_content_bottom %}
             <div id="plugin_content_bottom">
                 {{plugin_content_bottom}}
             </div>
         {% endif %}
         &nbsp;
 	</div>
-		
+
+    {# Plugin main bottom #}
+    {% if plugin_main_bottom %}
+        <div id="plugin_main_bottom" class="span12">
+            {{ plugin_main_bottom }}
+        </div>
+    {% endif %}
+
 {% endblock %}

+ 19 - 16
main/template/default/layout/login_form.tpl

@@ -1,22 +1,25 @@
-<div id="login_block" class="well sidebar-nav">
+{% if login_language_form %}
 
-	{{ login_language_form }}
+    <div id="login_block" class="well sidebar-nav">
 
-    {% if plugin_login_top is not null %}
-        <div id="plugin_login_top">
-            {{ plugin_login_top }}
-        </div>
-    {% endif %}
+        {{ login_language_form }}
 
-    {{login_failed}}
+        {% if plugin_login_top is not null %}
+            <div id="plugin_login_top">
+                {{ plugin_login_top }}
+            </div>
+        {% endif %}
 
-	{{login_form}}
+        {{ login_failed }}
 
-	{{login_options}}
+        {{ login_form }}
 
-    {% if plugin_login_bottom is not null %}
-        <div id="plugin_login_bottom">
-            {{ plugin_login_bottom }}
-        </div>
-    {% endif %}
-</div>
+        {{ login_options }}
+
+        {% if plugin_login_bottom is not null %}
+            <div id="plugin_login_bottom">
+                {{ plugin_login_bottom }}
+            </div>
+        {% endif %}
+    </div>
+{% endif %}

+ 3 - 3
main/template/default/layout/main.tpl

@@ -1,8 +1,8 @@
 {% block header %}
-{% include "default/layout/main_header.tpl" %}    
+    {% include "default/layout/main_header.tpl" %}
 {% endblock %}
 
-{% block body %}	
+{% block body %}
 	{% if show_sniff == 1 %}
 	 	{% include "default/layout/sniff.tpl" %}
 	{% endif %}
@@ -16,5 +16,5 @@
         <div class="push"></div>
         </div> <!-- end of #wrapper section -->
     {% endif %}
-{% include "default/layout/main_footer.tpl" %}
+    {% include "default/layout/main_footer.tpl" %}
 {% endblock %}

+ 1 - 1
main/webservices/testip.php

@@ -5,7 +5,7 @@
  */
 $ip = trim($_SERVER['REMOTE_ADDR']);
 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
-  list($ip1,$ip2) = split(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
+  list($ip1,$ip2) = preg_split('/,/',$_SERVER['HTTP_X_FORWARDED_FOR']);
   $ip = trim($ip1);
 }
 echo htmlentities($ip);

+ 1 - 1
main/webservices/webservice.php

@@ -112,7 +112,7 @@ class WS {
 		// if we are behind a reverse proxy, assume it will send the 
 		// HTTP_X_FORWARDED_FOR header and use this IP instead
 		if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
-			list($ip1,$ip2) = split(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
+			list($ip1,$ip2) = preg_split('/,/',$_SERVER['HTTP_X_FORWARDED_FOR']);
 			$ip = trim($ip1);
 		}
 		$security_key = $ip.$this->_configuration['security_key'];

+ 18 - 14
main/work/add_user.php

@@ -1,11 +1,10 @@
 <?php
 /* For licensing terms, see /license.txt */
 
-use ChamiloSession as Session;
-
 $language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
 
 require_once '../inc/global.inc.php';
+
 // Including necessary files
 require_once 'work.lib.php';
 
@@ -38,7 +37,7 @@ $courseInfo = api_get_course_info();
 
 $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq(), 'name' => get_lang('StudentPublications'));
 $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$workId, 'name' => $my_folder_data['title']);
-$interbreadcrumb[] = array('url' => '#', 'name' => get_lang('AddUser'));
+$interbreadcrumb[] = array('url' => '#', 'name' => get_lang('AddUsers'));
 
 $error_message = null;
 
@@ -74,28 +73,33 @@ if (!empty($items)) {
         $usersAdded[] = $myUserId;
         $userInfo = api_get_user_info($myUserId);
         $url = api_get_path(WEB_CODE_PATH).'work/add_user.php?action=delete&id='.$workId.'&user_id='.$myUserId;
-        $link = Display::url(get_lang('Delete'), $url);
-        echo $userInfo['complete_name'].' '.$link.'<br />';
+        $link = Display::url(get_lang('Delete'), $url, array('class' => 'btn btn-danger'));
+        echo $userInfo['complete_name_with_username'].' '.$link.'<br />';
     }
     echo '</div>';
 }
 
 $userList = CourseManager::get_user_list_from_course_code($courseInfo['code'], api_get_session_id(), null, null, STUDENT);
 
-echo Display::page_subheader(get_lang('UserToAdd'));
-if (!empty($userList)) {
+$userToAddList = array();
+foreach ($userList as $user) {
+    if (!in_array($user['user_id'], $usersAdded)) {
+        $userToAddList[] = $user;
+    }
+}
+
+if (!empty($userToAddList)) {
+    echo Display::page_subheader(get_lang('UsersToAdd'));
     echo '<div class="well">';
-    foreach ($userList as $user) {
-        if (in_array($user['user_id'], $usersAdded)) {
-            continue;
-        }
-        $userName = api_get_person_name($user['firstname'], $user['lastname']);
+    foreach ($userToAddList as $user) {
+        $userName = api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].') ';
         $url = api_get_path(WEB_CODE_PATH).'work/add_user.php?action=add&id='.$workId.'&user_id='.$user['user_id'];
-        $link = Display::url(get_lang('Add'), $url);
+        $link = Display::url(get_lang('Add'), $url, array('class' => 'btn btn-primary'));
         echo $userName.' '.$link.'<br />';
     }
     echo '</div>';
+} else {
+    Display::display_warning_message(get_lang('NoUsersToAdd'));
 }
 
-
 echo '<hr /><div class="clear"></div>';

+ 1 - 5
main/work/edit.php

@@ -1,8 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
 
-use ChamiloSession as Session;
-
 $language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
 
 require_once '../inc/global.inc.php';
@@ -52,9 +50,7 @@ $token = Security::get_token();
 
 $student_can_edit_in_session = api_is_allowed_to_session_edit(false, true);
 $has_ended   = false;
-
 $is_author = false;
-
 $work_item = get_work_data_by_id($item_id);
 
 // Get the author ID for that document from the item_property table
@@ -142,7 +138,7 @@ $defaults["description"] 	= $work_item['description'];
 $defaults['qualification']  = $work_item['qualification'];
 
 if ($is_allowed_to_edit && !empty($item_id)) {
-    // Get qualification from parent_id that'll allow the validation qualification over
+    // Get qualification from parent_id that will allow the validation qualification over
     $sql = "SELECT qualification FROM $work_table WHERE c_id = $course_id AND id ='$work_id' ";
     $result = Database::query($sql);
     $row = Database::fetch_array($result);

+ 125 - 0
main/work/edit_work.php

@@ -0,0 +1,125 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+$language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
+
+require_once '../inc/global.inc.php';
+require_once 'work.lib.php';
+
+// Section (for the tabs)
+$this_section = SECTION_COURSES;
+
+if (!api_is_allowed_to_edit()) {
+    api_not_allowed(true);
+}
+
+$courseInfo = api_get_course_info();
+$workId = isset($_GET['id']) ? intval($_GET['id']) : null;
+$workData = get_work_data_by_id($workId);
+$homework = get_work_assignment_by_id($workId);
+$locked = api_resource_is_locked_by_gradebook($workId, LINK_STUDENTPUBLICATION);
+
+if (api_is_platform_admin() == false && $locked == true) {
+    api_not_allowed(true);
+}
+
+$htmlHeadXtra[] = to_javascript_work();
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq(), 'name' => get_lang('StudentPublications'));
+$interbreadcrumb[] = array('url' => '#', 'name' => get_lang('Edit'));
+
+Display::display_header();
+
+$form = new FormValidator('edit_dir', 'post', api_get_path(WEB_CODE_PATH).'work/edit_work.php?id='.$workId.'&'. api_get_cidreq());
+$form->addElement('header', get_lang('Edit'));
+
+$title = !empty($workData['title']) ? $workData['title'] : basename($workData['url']);
+
+$defaults = $workData;
+$defaults['new_dir'] = Security::remove_XSS($title);
+
+$there_is_a_end_date = false;
+
+if (Gradebook::is_active()) {
+    $link_info = is_resource_in_course_gradebook(api_get_course_id(), LINK_STUDENTPUBLICATION, $workId);
+    if (!empty($link_info)) {
+        $defaults['weight'] = $link_info['weight'];
+        $defaults['category_id'] = $link_info['category_id'];
+        $defaults['make_calification'] = 1;
+    }
+} else {
+    $defaults['category_id'] = '';
+}
+
+if ($homework['expires_on'] != '0000-00-00 00:00:00') {
+    $homework['expires_on'] = api_get_local_time($homework['expires_on']);
+    $there_is_a_expire_date = true;
+    $defaults['enableExpiryDate'] = true;
+} else {
+    $homework['expires_on'] = api_get_local_time();
+    $expires_date_array = convert_date_to_array(api_get_local_time(), 'expires');
+    $defaults 			= array_merge($defaults, $expires_date_array);
+    $there_is_a_expire_date = false;
+}
+
+if ($homework['ends_on'] != '0000-00-00 00:00:00') {
+    $homework['ends_on'] = api_get_local_time($homework['ends_on']);
+    $there_is_a_end_date = true;
+    $defaults['enableEndDate'] = true;
+
+} else {
+    $homework['ends_on'] = api_get_local_time();
+    $expires_date_array = convert_date_to_array(api_get_local_time(), 'ends');
+    $defaults 			= array_merge($defaults, $expires_date_array);
+    $there_is_a_end_date = false;
+}
+
+if ($there_is_a_end_date) {
+    $end_date_array = convert_date_to_array($homework['ends_on'], 'ends');
+    $defaults = array_merge($defaults, $end_date_array);
+}
+
+if ($there_is_a_expire_date) {
+    $expires_date_array = convert_date_to_array($homework['expires_on'], 'expires');
+    $defaults = array_merge($defaults, $expires_date_array);
+}
+
+$defaults['add_to_calendar'] = isset($homework['add_to_calendar']) ? $homework['add_to_calendar'] : null;
+$form = getFormWork($form, $defaults);
+$form->addElement('hidden', 'work_id', $workId);
+$form->addElement('style_submit_button', 'submit', get_lang('ModifyDirectory'), 'class="save"');
+
+$display_edit_form = true;
+
+if ($form->validate()) {
+    $params = $form->exportValues();
+    $workId = $params['work_id'];
+
+    $dir_name = replace_dangerous_char($params['dir_name']);
+    $dir_name = disable_dangerous_file($dir_name);
+
+    $edit_check = false;
+
+    $workData = get_work_data_by_id($workId);
+
+    if (!empty($workData)) {
+        $edit_check = true;
+    } else {
+        $edit_check = true;
+    }
+
+    if ($edit_check) {
+
+        updatePublicationAssignment($workId, $params, $courseInfo, $group_id);
+        updateDirName($workData, $dir_name, $params['dir_name'], $courseInfo);
+
+        $dir = $dir_name;
+
+        Display::display_confirmation_message(get_lang('FolderEdited'));
+    } else {
+        Display::display_warning_message(get_lang('FileExists'));
+    }
+}
+
+$form->display();
+
+Display :: display_footer();

File diff suppressed because it is too large
+ 283 - 444
main/work/work.lib.php


+ 56 - 448
main/work/work.php

@@ -1,45 +1,8 @@
 <?php
 /* For licensing terms, see /license.txt */
-
-use ChamiloSession as Session;
-
 /**
  *	@package chamilo.work
- * 	@author Thomas, Hugues, Christophe - original version
- * 	@author Patrick Cool <patrick.cool@UGent.be>, Ghent University - ability for course admins to specify wether uploaded documents are visible or invisible by default.
- * 	@author Roan Embrechts, code refactoring and virtual course support
- * 	@author Frederic Vauthier, directories management
- *   @author Julio Montoya <gugli100@gmail.com> BeezNest 2011 LOTS of bug fixes
- *
- * 	@todo refactor more code into functions, use quickforms, coding standards, ... jm
- */
-
-/**
- * 	STUDENT PUBLICATIONS MODULE
- *
- * Note: for a more advanced module, see the dropbox tool.
- * This one is easier with less options.
- * This tool is better used for publishing things,
- * sending in assignments is better in the dropbox.
- *
- * GOALS
- * *****
- * Allow student to quickly send documents immediately visible on the Course
- *
- * The script does 5 things:
- *
- * 	1. Upload documents
- * 	2. Give them a name
- * 	3. Modify data about documents
- * 	4. Delete link to documents and simultaneously remove them
- * 	5. Show documents list to students and visitors
- *
- * On the long run, the idea is to allow sending realvideo . Which means only
- * establish a correspondence between RealServer Content Path and the user's
- * documents path.
- *
- *
- */
+ **/
 
 /* INIT SECTION */
 
@@ -48,11 +11,8 @@ $language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
 require_once '../inc/global.inc.php';
 $current_course_tool  = TOOL_STUDENTPUBLICATION;
 
-/*	Configuration settings */
-
 api_protect_course_script(true);
 
-// Including necessary files
 require_once 'work.lib.php';
 
 require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
@@ -74,7 +34,7 @@ $curdirpath = '';
 $htmlHeadXtra[] = api_get_jqgrid_js();
 $htmlHeadXtra[] = to_javascript_work();
 $htmlHeadXtra[] = '<script>
-function setFocus(){
+function setFocus() {
     $("#work_title").focus();
 }
 $(document).ready(function () {
@@ -82,29 +42,14 @@ $(document).ready(function () {
 });
 </script>';
 
-// Table definitions
-$main_course_table 	= Database :: get_main_table(TABLE_MAIN_COURSE);
-$work_table 		= Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
-$TSTDPUBASG			= Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
-$table_course_user	= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-$table_user			= Database :: get_main_table(TABLE_MAIN_USER);
-$table_session		= Database :: get_main_table(TABLE_MAIN_SESSION);
-$table_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
 $_course = api_get_course_info();
 
 /*	Constants and variables */
 
-$tool_name 		= get_lang('StudentPublications');
-$course_code 	= api_get_course_id();
-$session_id 	= api_get_session_id();
-
-$currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/';
-$currentCourseRepositoryWeb = api_get_path(WEB_COURSE_PATH) . $_course['path'] . '/';
-
-$currentUserFirstName 	= $_user['firstName'];
-$currentUserLastName 	= $_user['lastName'];
-$currentUserEmail 		= $_user['mail'];
+$tool_name = get_lang('StudentPublications');
+$course_code = api_get_course_id();
+$session_id = api_get_session_id();
+$group_id = api_get_group_id();
 
 $item_id 		        = isset($_REQUEST['item_id']) ? intval($_REQUEST['item_id']) : null;
 $parent_id 		        = isset($_REQUEST['parent_id']) ? Database::escape_string($_REQUEST['parent_id']) : '';
@@ -114,9 +59,7 @@ $title 			        = isset($_REQUEST['title']) ? $_REQUEST['title'] : '';
 $description 	        = isset($_REQUEST['description']) ? $_REQUEST['description'] : '';
 $uploadvisibledisabled  = isset($_REQUEST['uploadvisibledisabled']) ? Database::escape_string($_REQUEST['uploadvisibledisabled']) : $course_info['show_score'];
 
-//directories management
-$sys_course_path 	= api_get_path(SYS_COURSE_PATH);
-$course_dir 		= $sys_course_path . $_course['path'];
+$course_dir 		= api_get_path(SYS_COURSE_PATH).$_course['path'];
 $base_work_dir 		= $course_dir . '/work';
 
 $link_target_parameter = ""; // e.g. "target=\"_blank\"";
@@ -130,35 +73,12 @@ if ($action == 'downloadfolder') {
     require 'downloadfolder.inc.php';
 }
 
-/*	More init stuff */
-
-if (isset ($_POST['cancelForm']) && !empty ($_POST['cancelForm'])) {
-    header('Location: '.api_get_self().'?origin='.$origin.'&amp;gradebook='.$gradebook);
-    exit;
-}
-
-// If the POST's size exceeds 8M (default value in php.ini) the $_POST array is emptied
-// If that case happens, we set $submitWork to 1 to allow displaying of the error message
-// The redirection with header() is needed to avoid apache to show an error page on the next request
-if ($_SERVER['REQUEST_METHOD'] == 'POST' && !sizeof($_POST)) {
-    if (strstr($_SERVER['REQUEST_URI'], '?')) {
-        header('Location: ' . $_SERVER['REQUEST_URI'] . '&submitWork=1');
-        exit();
-    } else {
-        header('Location: ' . $_SERVER['REQUEST_URI'] . '?submitWork=1');
-        exit();
-    }
-}
-
-$group_id = api_get_group_id();
-
 $display_upload_form = false;
 if ($action == 'upload_form') {
     $display_upload_form = true;
 }
 
 /*	Header */
-
 if (!empty($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
     $_SESSION['gradebook'] = Security::remove_XSS($_GET['gradebook']);
     $gradebook =	$_SESSION['gradebook'];
@@ -188,12 +108,9 @@ if (!empty($group_id)) {
 
     $interbreadcrumb[] = array ('url' => '../group/group.php', 'name' => get_lang('Groups'));
     $interbreadcrumb[] = array ('url' => '../group/group_space.php?gidReq='.$group_id, 'name' => get_lang('GroupSpace').' '.$group_properties['name']);
-
-    $url_dir ='';
     $interbreadcrumb[] = array ('url' =>'work.php?gidReq='.$group_id,'name' => get_lang('StudentPublications'));
-
     $url_dir = 'work.php?&id=' . $work_id;
-    $interbreadcrumb[] = array ('url' => $url_dir,'name' =>  $my_folder_data['title']);
+    $interbreadcrumb[] = array ('url' => $url_dir, 'name' =>  $my_folder_data['title']);
 
     if ($action == 'upload_form') {
         $interbreadcrumb[] = array ('url' => 'work.php','name' => get_lang('UploadADocument'));
@@ -202,7 +119,7 @@ if (!empty($group_id)) {
     if ($action == 'create_dir') {
         $interbreadcrumb[] = array ('url' => 'work.php','name' => get_lang('CreateAssignment'));
     }
-    Display :: display_header(null);
+    Display::display_header(null);
 } else {
     if (isset($origin) && $origin != 'learnpath') {
 
@@ -211,7 +128,6 @@ if (!empty($group_id)) {
         } else {
             $interbreadcrumb[] = array ('url' => '#', 'name' => get_lang('StudentPublications'));
         }
-
         $url_dir = 'work.php?id=' . $work_id;
         $interbreadcrumb[] = array ('url' => $url_dir,'name' =>  $my_folder_data['title']);
 
@@ -225,76 +141,46 @@ if (!empty($group_id)) {
             $interbreadcrumb[] = array ('url' => '#','name' => get_lang('CreateAssignment'));
         }
         Display :: display_header(null);
-
     } else {
         //we are in the learnpath tool
         Display::display_reduced_header();
     }
 }
 
-//stats
+// Stats
 event_access_tool(TOOL_STUDENTPUBLICATION);
 
 $is_allowed_to_edit = api_is_allowed_to_edit();
-
 $student_can_edit_in_session = api_is_allowed_to_session_edit(false, true);
 
 Display::display_introduction_section(TOOL_STUDENTPUBLICATION);
 
-// introduction section
-
 if ($origin == 'learnpath') {
     echo '<div style="height:15px">&nbsp;</div>';
 }
 
 /*	Display links to upload form and tool options */
-
 if (!in_array($action, array('add', 'create_dir'))) {
     $token = Security::get_token();
 }
-
+$courseInfo = api_get_course_info();
 display_action_links($work_id, $curdirpath, $action);
-
-// for teachers
-
+// For teachers
 switch ($action) {
     case 'settings':
         //if posts
         if ($is_allowed_to_edit && !empty($_POST['changeProperties'])) {
-            // Changing the tool setting: default visibility of an uploaded document
-            // @todo
-            $query = "UPDATE ".$main_course_table." SET show_score='" . $uploadvisibledisabled . "' WHERE code='" . api_get_course_id() . "'";
-            $res = Database::query($query);
-
-            /**
-             * Course data are cached in session so we need to update both the database
-             * and the session data
-             */
-            $_course['show_score'] = $uploadvisibledisabled;
-            Session::write('_course', $course);
-
-            // changing the tool setting: is a student allowed to delete his/her own document
-            // database table definition
-            $table_course_setting = Database :: get_course_table(TOOL_COURSE_SETTING);
-
-            // counting the number of occurrences of this setting (if 0 => add, if 1 => update)
-            $query = "SELECT * FROM " . $table_course_setting . " WHERE c_id = $course_id AND variable = 'student_delete_own_publication'";
-            $result = Database::query($query);
-            $number_of_setting = Database::num_rows($result);
-
-            if ($number_of_setting == 1) {
-                $query = "UPDATE " . $table_course_setting . " SET value='" . Database::escape_string($_POST['student_delete_own_publication']) . "'
-                        WHERE variable='student_delete_own_publication' AND c_id = $course_id";
-                Database::query($query);
-            } else {
-                $query = "INSERT INTO " . $table_course_setting . " (c_id, variable, value, category) VALUES
-                ($course_id, 'student_delete_own_publication','" . Database::escape_string($_POST['student_delete_own_publication']) . "','work')";
-                Database::query($query);
-            }
+            updateSettings($course, $_POST['show_score'], $_POST['student_delete_own_publication']);
             Display::display_confirmation_message(get_lang('Saved'));
         }
+        $studentDeleteOwnPublication = api_get_course_setting('student_delete_own_publication') == 1 ? 1 : 0;
         /*	Display of tool options */
-        display_tool_options($uploadvisibledisabled, $origin);
+        settingsForm(
+            array(
+                'show_score' => $course_info['show_score'],
+                'student_delete_own_publication' =>  $studentDeleteOwnPublication
+            )
+        );
         break;
     case 'mark_work':
         if (!api_is_allowed_to_edit()) {
@@ -304,180 +190,21 @@ switch ($action) {
         break;
     case 'create_dir':
     case 'add':
-        //$check = Security::check_token('post');
-        //show them the form for the directory name
+        // Show them the form for the directory name
+        if ($is_allowed_to_edit && in_array($action, array('create_dir', 'add'))) {
 
-        if ($is_allowed_to_edit && in_array($action, array('create_dir','add'))) {
-            //create the form that asks for the directory name
-            $form = new FormValidator('form1', 'post', api_get_self().'?action=create_dir&'. api_get_cidreq());
-
-            $form->addElement('header', get_lang('CreateAssignment').$token);
+            $form = new FormValidator('form1', 'post', api_get_path(WEB_CODE_PATH).'work/work.php?action=create_dir&'. api_get_cidreq());
+            $form->addElement('header', get_lang('CreateAssignment'));
             $form->addElement('hidden', 'action', 'add');
-            $form->addElement('hidden', 'curdirpath', Security :: remove_XSS($curdirpath));
-            $form->addElement('text', 'new_dir', get_lang('AssignmentName'));
-            $form->addRule('new_dir', get_lang('ThisFieldIsRequired'), 'required');
-            $form->add_html_editor('description', get_lang('Description'), false, false, getWorkDescriptionToolbar());
-            $form->addElement('advanced_settings', '<a href="javascript: void(0);" onclick="javascript: return plus();">
-                <span id="plus">'.Display::return_icon('div_show.gif',get_lang('AdvancedParameters'), array('style' => 'vertical-align:center')).' '.get_lang('AdvancedParameters').'</span></a>');
-            $form->addElement('html', '<div id="options" style="display: none;">');
-
-            // QualificationOfAssignment
-            $form->addElement('text', 'qualification_value', get_lang('QualificationNumeric'));
-
-            if ((api_get_session_id() != 0 && Gradebook::is_active()) || api_get_session_id() == 0) {   
-                $form->addElement('checkbox', 'make_calification', null, get_lang('MakeQualifiable'), array('id' =>'make_calification_id', 'onclick' => "javascript: if(this.checked){document.getElementById('option1').style.display='block';}else{document.getElementById('option1').style.display='none';}"));
-            } else {
-                // QualificationOfAssignment
-                $form->addElement('hidden', 'make_calification', false);
-            }
-
-            $form->addElement('html', '<div id="option1" style="display: none;">');
-
-            //Loading gradebook select
-            load_gradebook_select_in_tool($form);
-
-            $form->addElement('text', 'weight', get_lang('WeightInTheGradebook'));
-            $form->addElement('html', '</div>');
-
-            $form->addElement('checkbox', 'type1', null, get_lang('EnableExpiryDate'), array('id' =>'make_calification_id', 'onclick' => "javascript: if(this.checked){document.getElementById('option2').style.display='block';}else{document.getElementById('option2').style.display='none';}"));
-
-            $form->addElement('html', '<div id="option2" style="display: none;">');
-            $form->addElement('advanced_settings', draw_date_picker('expires'));
-            $form->addElement('html', '</div>');
-
-            $form->addElement('checkbox', 'type2', null, get_lang('EnableEndDate'), array('id' =>'make_calification_id', 'onclick' => "javascript: if(this.checked){document.getElementById('option3').style.display='block';}else{document.getElementById('option3').style.display='none';}"));
-
-            $form->addElement('html', '<div id="option3" style="display: none;">');
-            $form->addElement('advanced_settings', draw_date_picker('ends'));
-            $form->addElement('html', '</div>');
-
-            $form->addElement('checkbox', 'add_to_calendar', null, get_lang('AddToCalendar'));
-            $form->addElement('checkbox', 'allow_text_assignment', null, get_lang('AllowTextAssignments'));
-            $form->addElement('html', '</div>');
+            $form = getFormWork($form, array());
             $form->addElement('style_submit_button', 'submit', get_lang('CreateDirectory'));
 
             if ($form->validate()) {
-
-                $directory 		= Security::remove_XSS($_POST['new_dir']);
-                $directory 		= replace_dangerous_char($directory);
-                $directory 		= disable_dangerous_file($directory);
-                $dir_name 		= $curdirpath.$directory;
-                $created_dir 	= create_unexisting_work_directory($base_work_dir, $dir_name);
-
-                // we insert here the directory in the table $work_table
-                $dir_name_sql = '';
-
-                if (!empty($created_dir)) {
-                    if ($curdirpath == '/') {
-                        $dir_name_sql = $created_dir;
-                    } else {
-                        $dir_name_sql = '/'.$created_dir;
-                    }
-                    $time = time();
-                    $today = api_get_utc_datetime($time);
-
-                    $sql_add_publication = "INSERT INTO " . $work_table . " SET
-                                            c_id				= $course_id,
-                                            url         		= '".Database::escape_string($dir_name_sql)."',
-                                            title               = '".Database::escape_string($_POST['new_dir'])."',
-                                            description 		= '".Database::escape_string($_POST['description'])."',
-                                            author      		= '',
-                                            active              = '1',
-                                            accepted			= '1',
-                                            filetype            = 'folder',
-                                            post_group_id       = '".$group_id."',
-                                            sent_date           = '".$today."',
-                                            qualification       = '".(($_POST['qualification_value']!='') ? Database::escape_string($_POST['qualification_value']) : '') ."',
-                                            parent_id           = '',
-                                            qualificator_id     = '',
-                                            date_of_qualification	= '0000-00-00 00:00:00',
-                                            weight              = '".Database::escape_string($_POST['weight'])."',
-                                            session_id          = '".intval($id_session)."',
-                                            allow_text_assignment = '".Database::escape_string($_POST['allow_text_assignment'])."',
-                                            contains_file       = 0,
-                                            user_id 			= '".$user_id."'";
-
-                    Database::query($sql_add_publication);
-
-                    // add the directory
-                    $id = Database::insert_id();
-                    if ($id) {
-                        // Insert into agenda
-                        $agenda_id = 0;
-                        $end_date = '';
-                        if (isset($_POST['add_to_calendar']) && $_POST['add_to_calendar'] == 1) {
-                            require_once api_get_path(SYS_CODE_PATH).'calendar/agenda.inc.php';
-                            require_once api_get_path(SYS_CODE_PATH).'resourcelinker/resourcelinker.inc.php';
-
-                            // Setting today date
-                            $date = $end_date = $time;
-
-                            $title = sprintf(get_lang('HandingOverOfTaskX'), $_POST['new_dir']);
-                            if (!empty($_POST['type1'])) {
-                                $end_date = get_date_from_select('expires');
-                                $date	  = $end_date;
-                            }
-                            $description = isset($_POST['description']) ? $_POST['description'] : '';
-                            $content = '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;curdirpath='.api_substr($dir_name_sql, 1).'" >'.$_POST['new_dir'].'</a>'.$description;
-
-                            $agenda_id = agenda_add_item($course_info, $title, $content, $date, $end_date, array('GROUP:'.$group_id), 0);
-                        }
-                    }
-
-                    //Folder created
-                    api_item_property_update($course_info, 'work', $id, 'DirectoryCreated', $user_id, $group_id);
-                    Display :: display_confirmation_message(get_lang('DirectoryCreated'), false);
-
-                    // insert into student_publication_assignment
-                    //return something like this: 2008-02-45 00:00:00
-
-                    $enable_calification = isset($_POST['qualification_value']) && !empty($_POST['qualification_value']) ? 1 : 0;
-
-                    if (!empty($_POST['type1']) || !empty($_POST['type2'])) {
-
-                        $sql_add_homework = "INSERT INTO $TSTDPUBASG SET
-                                                c_id = $course_id ,
-                                                expires_on       		= '".((isset($_POST['type1']) && $_POST['type1']==1) ? api_get_utc_datetime(get_date_from_select('expires')) : '0000-00-00 00:00:00'). "',
-                                                ends_on        	 		= '".((isset($_POST['type2']) && $_POST['type2']==1) ? api_get_utc_datetime(get_date_from_select('ends')) : '0000-00-00 00:00:00')."',
-                                                add_to_calendar  		= '$agenda_id',
-                                                enable_qualification 	= '$enable_calification',
-                                                publication_id 			= '$id'";
-                        Database::query($sql_add_homework);
-                        $my_last_id = Database::insert_id();
-                        $sql_add_publication = "UPDATE $work_table SET has_properties  = $my_last_id , view_properties = 1  WHERE c_id = $course_id AND id = $id";
-                        Database::query($sql_add_publication);
-                    } else {
-                        $sql_add_homework = "INSERT INTO $TSTDPUBASG SET
-                                                c_id = $course_id ,
-                                                expires_on     = '0000-00-00 00:00:00',
-                                                ends_on        = '0000-00-00 00:00:00',
-                                                add_to_calendar  = '$agenda_id',
-                                                enable_qualification = '".$enable_calification."',
-                                                publication_id = '".$id."'";
-                        Database::query($sql_add_homework);
-                        $inserted_id = Database::insert_id();
-                        $sql_add_publication = "UPDATE $work_table SET has_properties  = $inserted_id, view_properties = 0 WHERE c_id = $course_id AND id = $id";
-                        Database::query($sql_add_publication);
-                    }
-                    if (!empty($_POST['category_id'])) {
-
-                        if (isset($_POST['make_calification']) && $_POST['make_calification'] == 1) {
-
-                            require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/gradebookitem.class.php';
-                            require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/evaluation.class.php';
-                            require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/abstractlink.class.php';
-                            require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
-
-                            $resource_name = $_POST['new_dir'];
-                            add_resource_to_course_gradebook($_POST['category_id'], api_get_course_id(), 3, $id, $resource_name, $_POST['weight'], $_POST['qualification_value'], $_POST['description'], 1, api_get_session_id());
-                        }
-                    }
-
-                    if (api_get_course_setting('email_alert_students_on_new_homework') == 1) {
-                        send_email_on_homework_creation(api_get_course_id());
-                    }
+                $result = addDir($_POST, $user_id, $_course, $group_id, $id_session);
+                if ($result) {
+                    Display::display_confirmation_message(get_lang('DirectoryCreated'), false);
                 } else {
-                    Display :: display_error_message(get_lang('CannotCreateDir'));
+                    Display::display_error_message(get_lang('CannotCreateDir'));
                 }
             } else {
                 $form->display();
@@ -485,6 +212,7 @@ switch ($action) {
         }
     case 'make_visible':
     case 'delete':
+    case 'delete_dir':
     case 'make_invisible':
     case 'move':
     case 'move_to':
@@ -504,12 +232,12 @@ switch ($action) {
 
                 if (move($course_dir.'/'.$path, $base_work_dir . $move_to_path)) {
                     // Update db
-                    update_work_url($item_id, 'work' . $move_to_path, $_REQUEST['move_to_id']);
+                    updateWorkUrl($item_id, 'work' . $move_to_path, $_REQUEST['move_to_id']);
                     api_item_property_update($_course, 'work', $_REQUEST['move_to_id'], 'FolderUpdated', $user_id);
 
-                    Display :: display_confirmation_message(get_lang('DirMv'));
+                    Display::display_confirmation_message(get_lang('DirMv'));
                 } else {
-                    Display :: display_error_message(get_lang('Impossible'));
+                    Display::display_error_message(get_lang('Impossible'));
                 }
             } else {
                 Display :: display_error_message(get_lang('Impossible'));
@@ -519,27 +247,16 @@ switch ($action) {
         /*	Move file form request */
         if ($is_allowed_to_edit && $action == 'move') {
             if (!empty($item_id)) {
-                $folders = array();
-                $session_id = api_get_session_id();
-                $session_id == 0 ? $withsession = " AND session_id = 0 " : $withsession = " AND session_id='".$session_id."'";
-                $sql = "SELECT id, url, title FROM $work_table
-                        WHERE c_id = $course_id AND active IN (0, 1) AND url LIKE '/%' AND post_group_id = '".$group_id."'".$withsession;
-                $res = Database::query($sql);
-                while ($folder = Database::fetch_array($res)) {
-                    $folders[$folder['id']] = $folder['title'];
-                }
-                echo build_work_move_to_selector($folders, $curdirpath, $item_id);
+                echo generateMoveForm($item_id, $curdirpath, $course_info, $group_id, $session_id);
             }
         }
 
-        /*	MAKE VISIBLE WORK COMMAND */
+        /*	Visible */
         if ($is_allowed_to_edit && $action == 'make_visible') {
             if (!empty($item_id)) {
                 if (isset($item_id) && $item_id == 'all') {
                 } else {
-                    $sql = "UPDATE " . $work_table . "	SET accepted = 1 WHERE c_id = $course_id AND id = '" . $item_id . "'";
-                    Database::query($sql);
-                    api_item_property_update($course_info, 'work', $item_id, 'visible', api_get_user_id());
+                    makeVisible($item_id, $course_info);
                     Display::display_confirmation_message(get_lang('FileVisible'));
                 }
             }
@@ -547,112 +264,42 @@ switch ($action) {
 
         if ($is_allowed_to_edit && $action == 'make_invisible') {
 
-            /*	MAKE INVISIBLE WORK COMMAND */
+            /*	Invisible */
             if (!empty($item_id)) {
                 if (isset($item_id) && $item_id == 'all') {
                 } else {
-                    $sql = "UPDATE  " . $work_table . " SET accepted = 0
-                            WHERE c_id = $course_id AND id = '" . $item_id . "'";
-                    Database::query($sql);
-                    api_item_property_update($course_info, 'work', $item_id, 'invisible', api_get_user_id());
+                    makeInvisible($item_id, $course_info);
                     Display::display_confirmation_message(get_lang('FileInvisible'));
                 }
             }
         }
 
-        /*	Delete dir command */
+        /*	Delete dir */
 
-        if ($is_allowed_to_edit && !empty($_REQUEST['delete_dir'])) {
-            $delete_dir_id = intval($_REQUEST['delete_dir']);
-            $locked = api_resource_is_locked_by_gradebook($delete_dir_id, LINK_STUDENTPUBLICATION);
+        if ($is_allowed_to_edit && $action == 'delete_dir') {
+            $work_to_delete = get_work_data_by_id($_REQUEST['id']);
+            $result = deleteDirWork($_REQUEST['id']);
 
-            if ($locked == false) {
-
-                $work_to_delete = get_work_data_by_id($delete_dir_id);
-                del_dir($delete_dir_id);
-
-                // gets calendar_id from student_publication_assigment
-                $sql = "SELECT add_to_calendar FROM $TSTDPUBASG WHERE c_id = $course_id AND publication_id ='$delete_dir_id'";
-                $res = Database::query($sql);
-                $calendar_id = Database::fetch_row($res);
-
-                // delete from agenda if it exists
-                if (!empty($calendar_id[0])) {
-                    $t_agenda   = Database::get_course_table(TABLE_AGENDA);
-                    $sql = "DELETE FROM $t_agenda WHERE c_id = $course_id AND id ='".$calendar_id[0]."'";
-                    Database::query($sql);
-                }
-                $sql = "DELETE FROM $TSTDPUBASG WHERE c_id = $course_id AND publication_id ='$delete_dir_id'";
-                Database::query($sql);
-
-                $link_info = is_resource_in_course_gradebook(api_get_course_id(), 3 , $delete_dir_id, api_get_session_id());
-                $link_id = $link_info['id'];
-                if ($link_info !== false) {
-                    remove_resource_from_course_gradebook($link_id);
-                }
-                Display :: display_confirmation_message(get_lang('DirDeleted') . ': '.$work_to_delete['title']);
-            } else {
-                Display::display_warning_message(get_lang('ResourceLockedByGradebook'));
+            if ($result) {
+                Display::display_confirmation_message(get_lang('DirDeleted') . ': '.$work_to_delete['title']);
             }
         }
 
-        /*	DELETE WORK COMMAND */
-
+        /*	Delete document */
         if ($action == 'delete' && $item_id) {
-
-            $file_deleted = false;
-            $is_author = user_is_author($item_id);
-            $work_data = get_work_data_by_id($item_id);
-            $locked = api_resource_is_locked_by_gradebook($work_data['parent_id'], LINK_STUDENTPUBLICATION);
-
-            if (($is_allowed_to_edit && $locked == false) || ($locked == false AND $is_author && api_get_course_setting('student_delete_own_publication') == 1 && $work_data['qualificator_id'] == 0)) {
-                //we found the current user is the author
-                $queryString1 	= "SELECT url, contains_file FROM ".$work_table." WHERE c_id = $course_id AND id = $item_id";
-                $result1 		= Database::query($queryString1);
-                $row 			= Database::fetch_array($result1);
-
-
-                if (Database::num_rows($result1) > 0) {
-                    $queryString2 	= "UPDATE " . $work_table . "  SET active = 2 WHERE c_id = $course_id AND id = $item_id";
-                    $queryString3 	= "DELETE FROM  ".$TSTDPUBASG ." WHERE c_id = $course_id AND publication_id = $item_id";
-                    Database::query($queryString2);
-                    Database::query($queryString3);
-
-                    api_item_property_update($_course, 'work', $item_id, 'DocumentDeleted', $user_id);
-                    $work = $row['url'];
-
-                    if ($row['contains_file'] == 1) {
-                        if (!empty($work)) {
-                            if (api_get_setting('permanently_remove_deleted_files') == 'true') {
-                                my_delete($currentCourseRepositorySys.'/'.$work);
-                                Display::display_confirmation_message(get_lang('TheDocumentHasBeenDeleted'));
-                                $file_deleted = true;
-                            } else {
-                                $extension = pathinfo($work, PATHINFO_EXTENSION);
-                                $new_dir = $work.'_DELETED_'.$item_id.'.'.$extension;
-
-                                if (file_exists($currentCourseRepositorySys.'/'.$work)) {
-                                    rename($currentCourseRepositorySys.'/'.$work, $currentCourseRepositorySys.'/'.$new_dir);
-                                    Display::display_confirmation_message(get_lang('TheDocumentHasBeenDeleted'));
-                                    $file_deleted = true;
-                                }
-                            }
-                        }
-                    } else {
-                        $file_deleted = true;
-                    }
-                }
-            }
-
+            $file_deleted = deleteWorkItem($item_id, $_course);
             if (!$file_deleted) {
                 Display::display_error_message(get_lang('YouAreNotAllowedToDeleteThisDocument'));
+            } else {
+                Display::display_confirmation_message(get_lang('TheDocumentHasBeenDeleted'));
             }
         }
 
         /*	Display list of student publications */
-
         if (!empty($my_folder_data['description'])) {
-            echo '<p><div><strong>'.get_lang('Description').':</strong><p>'.Security::remove_XSS($my_folder_data['description'], STUDENT).'</p></div></p>';
+            echo '<p><div><strong>'.
+                get_lang('Description').':</strong><p>'.Security::remove_XSS($my_folder_data['description'], STUDENT).
+                '</p></div></p>';
         }
 
         $my_folder_data = get_work_data_by_id($work_id);
@@ -663,58 +310,19 @@ switch ($action) {
         }
 
         if (api_is_allowed_to_edit()) {
+            $userList = getWorkUserList($course_code, $session_id);
 
             // Work list
             echo '<div class="row">';
             echo '<div class="span9">';
-
-            if (!empty($group_id)) {
-                $userList = GroupManager::get_users($group_id);
-            } else {
-                if (empty($session_id)) {
-                    $userList = CourseManager::get_user_list_from_course_code($course_code, $session_id, null, null, STUDENT);
-                } else {
-                    $userList = CourseManager::get_user_list_from_course_code($course_code, $session_id, null, null, 0);
-                }
-                $userList = array_keys($userList);
-            }
-
-            display_student_publications_list($work_id, $my_folder_data, $work_parents, $origin, $add_query, $userList);
-
+            $grid = showTeacherWorkGrid();
+            echo $grid ;
             echo '</div>';
             echo '<div class="span3">';
-
-            $table = new HTML_Table(array('class' => 'data_table'));
-            $column = 0;
-            $row = 0;
-            $headers = array(get_lang('Students'), get_lang('Works'));
-            foreach ($headers as $header) {
-                $table->setHeaderContents($row, $column, $header);
-                $column++;
-            }
-            $row++;
-            $column = 0;
-
-            foreach ($userList as $userId) {
-                $user = api_get_user_info($userId);
-                $link = api_get_path(WEB_CODE_PATH).'work/student_work.php?'.api_get_cidreq().'&studentId='.$user['user_id'];
-                $url = Display::url(api_get_person_name($user['firstname'], $user['lastname']), $link);
-                $table->setCellContents($row, $column, $url);
-                $column++;
-                $userWorks = 0;
-                foreach ($work_parents as $work) {
-                    $userWorks += getUniqueStudentAttempts($work->id, $group_id, $course_id, $session_id, $user['user_id']);
-                }
-                $cell = $userWorks." / ".count($work_parents);
-                $table->setCellContents($row, $column, $cell);
-                $row++;
-                $column = 0;
-            }
-
-            echo $table->toHtml();
+            echo showStudentList($userList, $work_parents, $group_id, $course_id, $session_id);
             echo '</div>';
         } else {
-            display_student_publications_list($work_id, $my_folder_data, $work_parents, $origin, $add_query, null);
+            echo showStudentWorkGrid();
         }
     break;
 }

+ 26 - 10
main/work/work_list.php

@@ -1,8 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
 
-use ChamiloSession as Session;
-
 $language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
 
 require_once '../inc/global.inc.php';
@@ -58,6 +56,7 @@ $interbreadcrumb[] = array ('url' => api_get_path(WEB_CODE_PATH).'work/work.php?
 $interbreadcrumb[] = array ('url' => api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq().'&id='.$workId, 'name' =>  $my_folder_data['title']);
 
 Display :: display_header(null);
+
 $documentsAddedInWork = getAllDocumentsFromWorkToString($workId, $courseInfo);
 
 echo '<div class="actions">';
@@ -83,18 +82,30 @@ if (!empty($my_folder_data['description'])) {
 
 echo $documentsAddedInWork;
 
+$result = getWorkDateValidationStatus($work_data);
+echo $result['message'];
+
 $check_qualification = intval($my_folder_data['qualification']);
 
 if (!empty($work_data['enable_qualification']) && !empty($check_qualification)) {
     $type = 'simple';
-    $columns        = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('Title'), get_lang('Qualification'), get_lang('Date'), get_lang('Status'), get_lang('Actions'));
+
+    $columns = array(
+        get_lang('Type'),
+        get_lang('FirstName'),
+        get_lang('LastName'),
+        get_lang('Title'),
+        get_lang('Qualification'),
+        get_lang('Date'),
+        get_lang('Status'),
+        get_lang('Actions')
+    );
+
     $column_model   = array (
         array('name'=>'type',           'index'=>'file',            'width'=>'12',   'align'=>'left', 'search' => 'false'),
         array('name'=>'firstname',      'index'=>'firstname',       'width'=>'35',   'align'=>'left', 'search' => 'true'),
         array('name'=>'lastname',		'index'=>'lastname',        'width'=>'35',   'align'=>'left', 'search' => 'true'),
-        //array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
         array('name'=>'title',          'index'=>'title',           'width'=>'40',   'align'=>'left', 'search' => 'false', 'wrap_cell' => 'true'),
-        //                array('name'=>'file',           'index'=>'file',            'width'=>'20',   'align'=>'left', 'search' => 'false'),
         array('name'=>'qualification',	'index'=>'qualification',	'width'=>'20',   'align'=>'left', 'search' => 'true'),
         array('name'=>'sent_date',           'index'=>'sent_date',            'width'=>'50',   'align'=>'left', 'search' => 'true', 'wrap_cell' => 'true'),
         array('name'=>'qualificator_id','index'=>'qualificator_id', 'width'=>'30',   'align'=>'left', 'search' => 'true'),
@@ -102,17 +113,22 @@ if (!empty($work_data['enable_qualification']) && !empty($check_qualification))
     );
 } else {
     $type = 'complex';
-    $columns  = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('Title'), get_lang('Date'),  get_lang('Actions'));
+
+    $columns  = array(
+        get_lang('Type'),
+        get_lang('FirstName'),
+        get_lang('LastName'),
+        get_lang('Title'),
+        get_lang('Date'),
+        get_lang('Actions')
+    );
+
     $column_model   = array (
         array('name'=>'type',           'index'=>'file',            'width'=>'12',   'align'=>'left', 'search' => 'false'),
         array('name'=>'firstname',      'index'=>'firstname',       'width'=>'35',   'align'=>'left', 'search' => 'true'),
         array('name'=>'lastname',		'index'=>'lastname',        'width'=>'35',   'align'=>'left', 'search' => 'true'),
-        //array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
         array('name'=>'title',          'index'=>'title',           'width'=>'40',   'align'=>'left', 'search' => 'false', 'wrap_cell' => "true"),
-        //                array('name'=>'file',           'index'=>'file',            'width'=>'20',   'align'=>'left', 'search' => 'false'),
-        //array('name'=>'qualification',	'index'=>'qualification',	'width'=>'20',   'align'=>'left', 'search' => 'true'),
         array('name'=>'sent_date',       'index'=>'sent_date',            'width'=>'50',   'align'=>'left', 'search' => 'true', 'wrap_cell' => 'true'),
-        //array('name'=>'qualificator_id','index'=>'qualificator_id', 'width'=>'30',   'align'=>'left', 'search' => 'true'),
         array('name'=>'actions',        'index'=>'actions',         'width'=>'40',   'align'=>'left', 'search' => 'false', 'sortable'=>'false')
     );
 }

+ 0 - 2
main/work/work_list_others.php

@@ -1,8 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
 
-use ChamiloSession as Session;
-
 $language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
 
 require_once '../inc/global.inc.php';

+ 2 - 4
plugin/add_cas_logout_button/plugin.php

@@ -9,8 +9,6 @@
  * Plugin details (must be present)
  */
 
-
-
 //the plugin title
 $plugin_info['title']      = 'Add a button to logout from CAS';
 
@@ -25,7 +23,7 @@ $form = new FormValidator('add_cas_button_form');
 $form->addElement('text', 'cas_logout_label', 'CAS logout title', '');
 $form->addElement('text', 'cas_logout_comment', 'CAS logout description', '');
 $form->addElement('text', 'cas_logout_image_url', 'Logo URL if any (image, 50px height)');
-$form->addElement('style_submit_button', 'submit_button', get_lang('Save'));  
+$form->addElement('style_submit_button', 'submit_button', get_lang('Save'));
 //get default value for form
 $tab_default_add_cas_logout_button_cas_logout_label = api_get_setting('add_cas_logout_button_cas_logout_label');
 $tab_default_add_cas_logout_button_cas_logout_comment = api_get_setting('add_cas_logout_button_cas_logout_comment');
@@ -37,5 +35,5 @@ $form->setDefaults($defaults);
 //display form
 $plugin_info['settings_form'] = $form;
 
-//set the smarty templates that are going to be used
+// Set the templates that are going to be used
 $plugin_info['templates']   = array('template.tpl');

+ 2 - 4
plugin/add_facebook_login_button/plugin.php

@@ -9,8 +9,6 @@
  * Plugin details (must be present)
  */
 
-
-
 //the plugin title
 $plugin_info['title']      = 'Add a button to login using FACEBOOK account';
 
@@ -23,7 +21,7 @@ $plugin_info['author']      = 'Hubert Borderiou';
 //the plugin configuration
 $form = new FormValidator('add_facebook_button_form');
 $form->addElement('text', 'facebook_button_url', 'Facebook connexion image URL', '');
-$form->addElement('style_submit_button', 'submit_button', get_lang('Save'));  
+$form->addElement('style_submit_button', 'submit_button', get_lang('Save'));
 //get default value for form
 $tab_default_add_facebook_login_button_facebook_button_url = api_get_setting('add_facebook_login_button_facebook_button_url');
 $defaults['facebook_button_url'] = $tab_default_add_facebook_login_button_facebook_button_url['add_facebook_login_button'];
@@ -31,5 +29,5 @@ $form->setDefaults($defaults);
 //display form
 $plugin_info['settings_form'] = $form;
 
-//set the smarty templates that are going to be used
+// Set the templates that are going to be used
 $plugin_info['templates']   = array('template.tpl');

+ 80 - 0
plugin/before_login/index.php

@@ -0,0 +1,80 @@
+<?php
+/**
+ * @package chamilo.plugin.before_login
+ */
+
+if (api_is_anonymous()) {
+
+    // Only available in the index.php page
+    $loginAccepted = isset($_SESSION['before_login_accepted']) ? $_SESSION['before_login_accepted'] : null;
+    $parsedUrl = parse_url($_SERVER['REQUEST_URI']);
+    $currentPage = str_replace('index.php', '', $parsedUrl['path']);
+
+    if (api_get_path(REL_PATH) !== $currentPage) {
+        return null;
+    }
+
+    // Hide only if the before_login_accepted session was set to ON.
+    if ($loginAccepted) {
+        return null;
+    }
+
+    // Only available for the selected language.
+    $languageToActivate = api_get_plugin_setting('before_login', 'language');
+
+    if (api_get_interface_language() != $languageToActivate) {
+        return null;
+    }
+
+    $option1 = api_get_plugin_setting('before_login', 'option1');
+    $urlOption1 = api_get_plugin_setting('before_login', 'option1_url');
+
+    $option2 = api_get_plugin_setting('before_login', 'option2');
+    $urlOption2 = api_get_plugin_setting('before_login', 'option2_url');
+
+    $form = new FormValidator('form');
+
+    $renderer =& $form->defaultRenderer();
+    $renderer->setFormTemplate('<form{attributes}><table border="0" cellpadding="5" cellspacing="0" width="100%">{content}</table></form>');
+    $renderer->setElementTemplate('<tr><td>{element}</td></tr>');
+
+    $form->addElement('html', $option1);
+    $form->addElement('checkbox', 'left', null, get_lang('Yes'));
+    $form->addElement('button', 'submit', get_lang('Confirm'), array('class' => 'btn btn-primary'));
+    $formHtml = $form->return_form();
+    if ($form->validate()) {
+        $result = $form->getSubmitValues();
+        if (isset($result['left']) && $result['left']) {
+            $_SESSION['before_login_accepted'] = 1;
+            header('Location: '.$urlOption1);
+            exit;
+        }
+    }
+
+    $form2 = new FormValidator('form');
+
+    if (!empty($option2) && !empty($urlOption2)) {
+        $renderer =& $form2->defaultRenderer();
+        $renderer->setHeaderTemplate('');
+        $renderer->setFormTemplate('<form{attributes}><table border="0" cellpadding="5" cellspacing="0" width="100%">{content}</table></form>');
+        $renderer->setElementTemplate('<tr><td>{element}</td></tr>');
+
+        $form2->addElement('html', $option2);
+        $form2->addElement('checkbox', 'right', null, get_lang('Yes'));
+        $form2->addElement('button', 'submit', get_lang('Send'));
+        $formHtml2 = $form2->return_form();
+
+        if ($form2->validate()) {
+            $result = $form2->getSubmitValues();
+            if (isset($result['right']) && $result['right']) {
+                header('Location: '.$urlOption2);
+                exit;
+            }
+        }
+    }
+
+    //$_template['option1'] = api_get_plugin_setting('before_login', 'option1');
+    //$_template['option2'] = api_get_plugin_setting('before_login', 'option2');
+    $_template['form_option1'] = $formHtml;
+    $_template['form_option2'] = $formHtml2;
+}

+ 51 - 0
plugin/before_login/plugin.php

@@ -0,0 +1,51 @@
+<?php
+/**
+ * This script is a configuration file for the add_this plugin.
+ * These settings will be used in the administration interface for plugins
+ * (Chamilo configuration settings->Plugins)
+ * @package chamilo.plugin
+ * @author Julio Montoya <gugli100@gmail.com>
+ */
+
+/* Plugin config */
+
+// The plugin title.
+$plugin_info['title']       = 'Show HTML before login';
+// The comments that go with the plugin.
+$plugin_info['comment']     = "Show a content before loading the login page.";
+// The plugin version.
+$plugin_info['version']     = '1.0';
+// The plugin author.
+$plugin_info['author']      = 'Julio Montoya';
+
+// The plugin configuration.
+$form = new FormValidator('form');
+$form->addElement('select', 'language', get_lang('Language'), api_get_languages_to_array());
+
+$form->addElement('header', 'Option 1');
+$form->addElement('textarea', 'option1', get_lang('Description'), array('rows' => 10, 'class' => 'span6'));
+$form->addElement('text', 'option1_url', get_lang('RedirectTo'));
+
+$form->addElement('header', 'Option 2');
+$form->addElement('textarea', 'option2', get_lang('Description'), array('rows' => 10, 'class' => 'span6'));
+$form->addElement('text', 'option2_url', get_lang('RedirectTo'));
+$form->addElement('button', 'submit_button', get_lang('Save'));
+
+// Get default value for form
+
+$defaults = array();
+$defaults['language'] = api_get_plugin_setting('before_login', 'language');
+$defaults['option1'] = api_get_plugin_setting('before_login', 'option1');
+$defaults['option2'] = api_get_plugin_setting('before_login', 'option2');
+
+$defaults['option1_url'] = api_get_plugin_setting('before_login', 'option1_url');
+$defaults['option2_url'] = api_get_plugin_setting('before_login', 'option2_url');
+
+$plugin_info['templates']   = array('template.tpl');
+if (file_exists(__DIR__.'/custom.template.tpl')) {
+    $plugin_info['templates']   = array( 'custom.template.tpl');
+}
+$form->setDefaults($defaults);
+
+// Display form
+$plugin_info['settings_form'] = $form;

+ 10 - 0
plugin/before_login/readme.txt

@@ -0,0 +1,10 @@
+README
+<br/><br/>
+This plugins shows page before showing the login page.
+This is useful if you want a question before a user has the opportunity to login.
+<br/>
+Example:
+You're old enough to enter this site? If you accept the "option 1" then
+you can enter to the campus (the login will appeared).
+
+If you select "option 2" then you're redirected to another page.

+ 14 - 0
plugin/before_login/template.tpl

@@ -0,0 +1,14 @@
+{% if before_login.form_option1 %}
+    <div class="span12">
+        <div class="row">
+            <div class="span6">
+                {{ before_login.form_option1 }}
+            </div>
+            <div class="span6">
+                {{ before_login.form_option2 }}
+            </div>
+        </div>
+    </div>
+{% else %}
+
+{% endif %}

+ 2 - 2
plugin/ext_auth_chamilo_logout_button_behaviour/plugin.php

@@ -28,7 +28,7 @@ $form->addElement('checkbox', 'eaclbb_form_link_image', "Display the logout butt
 $form->addElement('checkbox', 'eaclbb_form_alert_onoff', "Display an alert when clicking on the logout button", "",  array('checked' => true));
 $form->addElement('text', 'eaclbb_form_alert_text', "Text displayed in the alert box when clickng on the logout button (if checkbox above has been checked).");
 
-$form->addElement('style_submit_button', 'submit_button', get_lang('Save'));  
+$form->addElement('style_submit_button', 'submit_button', get_lang('Save'));
 //get default value for form
 $tab_default_ext_auth_chamilo_logout_button_behaviour_eaclbb_form_link_url = api_get_setting('ext_auth_chamilo_logout_button_behaviour_eaclbb_form_link_url');
 $tab_default_ext_auth_chamilo_logout_button_behaviour_eaclbb_form_link_infobulle = api_get_setting('ext_auth_chamilo_logout_button_behaviour_eaclbb_form_link_infobulle');
@@ -44,5 +44,5 @@ $form->setDefaults($defaults);
 //display form
 $plugin_info['settings_form'] = $form;
 
-//set the smarty templates that are going to be used
+// Set the templates that are going to be used
 $plugin_info['templates']   = array('template.tpl');

+ 2 - 2
plugin/hello_world/index.php

@@ -3,13 +3,13 @@
  * @package chamilo.plugin.hello_world
  */
 
-// See also the share_user_info plugin 
+// See also the share_user_info plugin
 
 echo '<div class="well">';
 if (!empty($plugin_info['settings']['hello_world_show_type'])) {
     echo "<h2>".$plugin_info['settings']['hello_world_show_type']."</h2>";
 } else {
-    echo "<h2>Hello world</h2>";  
+    echo "<h2>Hello world</h2>";
 }
 
 //Using get_lang inside a plugin

+ 7 - 7
plugin/hello_world/plugin.php

@@ -1,6 +1,7 @@
 <?php
 /**
- * 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).
+ * 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).
  * These settings will be used in the administration interface for plugins (Chamilo configuration settings->Plugins)
  * @package chamilo.plugin
  * @author Julio Montoya <gugli100@gmail.com>
@@ -20,11 +21,10 @@ $plugin_info['version']     = '1.0';
 //the plugin author
 $plugin_info['author']      = 'Julio Montoya';
 
+/* Plugin optional settings */
 
-/* Plugin optional settings */ 
-
-/* 
- * This form will be showed in the plugin settings once the plugin was installed 
+/*
+ * This form will be showed in the plugin settings once the plugin was installed
  * in the plugin/hello_world/index.php you can have access to the value: $plugin_info['settings']['hello_world_show_type']
 */
 
@@ -33,6 +33,6 @@ $form = new FormValidator('hello_world_form');
 //A simple select
 $options = array('hello_world' => 'Hello World', 'hello' =>'Hello', 'hi' =>'Hi!');
 $form->addElement('select', 'show_type', 'Hello world types', $options);
-$form->addElement('style_submit_button', 'submit_button', get_lang('Save'));  
+$form->addElement('style_submit_button', 'submit_button', get_lang('Save'));
 
-$plugin_info['settings_form'] = $form;
+$plugin_info['settings_form'] = $form;

+ 7 - 7
plugin/share_buttons/plugin.php

@@ -1,20 +1,20 @@
 <?php
 /**
  * This script is a configuration file for the add_this plugin.
- * These settings will be used in the administration interface for plugins 
+ * These settings will be used in the administration interface for plugins
  * (Chamilo configuration settings->Plugins)
  * @package chamilo.plugin
  * @author Julio Montoya <gugli100@gmail.com>
  */
 /* Plugin config */
 
-//the plugin title
+// The plugin title.
 $plugin_info['title']       = 'Share this page';
-//the comments that go with the plugin
+// The comments that go with the plugin.
 $plugin_info['comment']     = "Show social icons to share a page using addthis.com";
-//the plugin version
+// The plugin version.
 $plugin_info['version']     = '1.0';
-//the plugin author
+// The plugin author.
 $plugin_info['author']      = 'Julio Montoya';
-//For bigger icons change this value to addthis_32x32_style
-$plugin_info['icon_class']   = ''; 
+// For bigger icons change this value to addthis_32x32_style
+$plugin_info['icon_class']   = '';

+ 2 - 2
plugin/show_regions/index.php

@@ -1,9 +1,9 @@
 <?php
 
-//only show the region information if the admin is logged in
+// Only show the region information if the admin is logged in.
 if (api_is_platform_admin()) {
     echo '<div style="color:black;height:50px;width:200px;background-color:#FFE378">';
     //We can have access to the current block and the block information with the variable $plugin_info (see your plugin.php)
     echo $plugin_info['current_region'];
-    echo '</div>';    
+    echo '</div>';
 }

+ 10 - 10
plugin/show_user_info/index.php

@@ -1,18 +1,18 @@
 <?php
 
-//A user must be logged in
+// A user must be logged in.
 $_template['show_message']   = false;
 
 if (!api_is_anonymous()) {
     $_template['show_message']   = true;
-    
-    //Getting the current user id
-    $user_id = api_get_user_id();    
-    
-    //Getting the current user info
+
+    // Getting the current user id.
+    $user_id = api_get_user_id();
+
+    //Getting the current user info.
     $user_info = api_get_user_info($user_id);
-            
-    //You can also use template setting variables in the special variable called template
-    $_template['user_info']   = $user_info;
-    $_template['username']    = $user_info['username'];
+
+    // You can also use template setting variables in the special variable called template.
+    $_template['user_info'] = $user_info;
+    $_template['username'] = $user_info['username'];
 }

+ 6 - 8
plugin/show_user_info/plugin.php

@@ -9,15 +9,13 @@
  * Plugin details (must be present)
  */
 
-//the plugin title
+// The plugin title
 $plugin_info['title']      = 'Show user information';
-
-//the comments that go with the plugin
+// The comments that go with the plugin
 $plugin_info['comment']     = "Shows a welcome message, (this is an example to uses the template system: Twig)";
-//the plugin version
+// The plugin version
 $plugin_info['version']     = '1.0';
-//the plugin author
+// The plugin author
 $plugin_info['author']      = 'Julio Montoya';
-
-//set the smarty templates that are going to be used
-$plugin_info['templates']   = array('template.tpl');
+// Set the templates that are going to be used
+$plugin_info['templates']   = array('template.tpl');

+ 5 - 16
tests/main/work/work.lib.test.php

@@ -5,7 +5,7 @@ require_once(api_get_path(LIBRARY_PATH).'course.lib.php');
 
 class TestWork extends UnitTestCase {
 
-	 
+
 	/**
 	 * @param	string	Base work dir (.../work)
 	 * @param 	string $desiredDirName complete path of the desired name
@@ -20,8 +20,8 @@ class TestWork extends UnitTestCase {
 		$res=create_unexisting_work_directory($base_work_dir,$desired_dir_name);
 		$this->assertTrue(is_bool($res));
 	}
-	 
-	 
+
+
 	 /**
 	 * Builds the form thats enables the user to
 	 * select a directory to browse/upload in
@@ -71,17 +71,6 @@ class TestWork extends UnitTestCase {
 		//var_dump($res);
 	}
 
-	/**
-	 * @param string e.g converts "2008-10-06 12:45:00" to timestamp
-	 */
-
-	function testconvert_date_to_number() {
-		$default='2008-10-06 12:45:00';
-		$res=convert_date_to_number($default);
-		$this->assertTrue(is_numeric($res));
-		//var_dump($res);
-	}
-
 	/**
 	* This function displays the number of files contained in a directory
 	* @param	string the path of the directory complete e.g. /var/www/dokeos
@@ -180,7 +169,7 @@ class TestWork extends UnitTestCase {
 		$origin='learnpath';
 		$add_in_where_query='';
 		ob_start();
-		$res=display_student_publications_list($work_dir,$sub_course_dir,$currentCourseRepositoryWeb, $link_target_parameter, $dateFormatLong, $origin,$add_in_where_query='');
+		$res=display_student_publications_list($work_dir,$sub_course_dir,$currentCourseRepositoryWeb, $link_target_parameter, $dateFormatLong, $origin);
 		$this->assertTrue(is_null($res));
 		ob_end_clean();
 		//var_dump($res);
@@ -386,7 +375,7 @@ class TestWork extends UnitTestCase {
 		$this->assertTrue(is_numeric($res));
 		//var_dump($res);
 	}
-	
+
 		/**
 	 * Delete a work-tool directory
 	 * @param	string	Base "work" directory for this course as /var/www/dokeos/courses/ABCD/work/

Some files were not shown because too many files changed in this diff