Эх сурвалжийг харах

Merge branch '1.10.x' into advsub

Conflicts:
	main/inc/lib/sessionmanager.lib.php
	plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php
	plugin/advanced_subscription/src/HookAdvancedSubscription.php
Daniel Barreto 10 жил өмнө
parent
commit
2694c82879
55 өөрчлөгдсөн 1290 нэмэгдсэн , 776 устгасан
  1. 1 1
      main/admin/add_courses_to_usergroup.php
  2. 1 1
      main/admin/add_users_to_usergroup.php
  3. 3 4
      main/admin/course_category.php
  4. 1 1
      main/admin/course_import.php
  5. 1 1
      main/admin/dashboard_add_users_to_user.php
  6. 32 5
      main/admin/session_add.php
  7. 16 21
      main/admin/session_edit.php
  8. 1 1
      main/admin/session_user_edit.php
  9. 1 1
      main/admin/user_add.php
  10. 1 1
      main/admin/user_edit.php
  11. 119 94
      main/blog/blog.php
  12. 5 11
      main/blog/blog_admin.php
  13. 1 1
      main/course_description/course_description_form.class.php
  14. 1 1
      main/course_description/upload_file_form.class.php
  15. 1 1
      main/course_progress/thematic_advance.php
  16. 1 1
      main/document/showinframes.php
  17. 1 1
      main/document/showinframesmin.php
  18. 1 1
      main/glossary/glossary_form.class.php
  19. 1 1
      main/glossary/upload_file_form.class.php
  20. 1 1
      main/inc/lib/auth.lib.php
  21. 168 207
      main/inc/lib/blog.lib.php
  22. 3 3
      main/inc/lib/course_category.lib.php
  23. 1 1
      main/inc/lib/document.lib.php
  24. 2 0
      main/inc/lib/elfinder/templates.php
  25. 1 1
      main/inc/lib/extra_field.lib.php
  26. 4 3
      main/inc/lib/formvalidator/FormValidator.class.php
  27. 14 9
      main/inc/lib/grade_model.lib.php
  28. 135 0
      main/inc/lib/javascript/ckeditor/plugins/glossary/fck_glossary_automatic.js
  29. 73 0
      main/inc/lib/javascript/ckeditor/plugins/glossary/fck_glossary_manual.js
  30. 7 8
      main/inc/lib/pear/HTML/Common.php
  31. 43 16
      main/inc/lib/promotion.lib.php
  32. 24 15
      main/inc/lib/sessionmanager.lib.php
  33. 300 6
      main/inc/lib/text.lib.php
  34. 8 10
      main/link/category_form.class.php
  35. 1 2
      main/link/link_form.class.php
  36. 1 1
      main/link/upload_file_form.class.php
  37. 1 1
      main/mySpace/user_add.php
  38. 2 2
      main/newscorm/lp_add.php
  39. 2 70
      main/newscorm/lp_add_item.php
  40. 2 2
      main/newscorm/lp_edit.php
  41. 6 26
      main/newscorm/lp_edit_item.php
  42. 1 1
      main/notebook/notebook_form.class.php
  43. 1 1
      main/notebook/upload_file_form.class.php
  44. 6 6
      main/social/group_topics.php
  45. 2 2
      main/social/groups.php
  46. 64 72
      main/social/message_for_group_form.inc.php
  47. 10 5
      main/template/default/layout/head.tpl
  48. 2 2
      main/wiki/wiki.inc.php
  49. 21 15
      plugin/advanced_subscription/README.md
  50. 10 10
      plugin/advanced_subscription/lang/english.php
  51. 24 9
      plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php
  52. 103 57
      plugin/advanced_subscription/src/HookAdvancedSubscription.php
  53. 1 3
      plugin/ticket/src/myticket.php
  54. 25 28
      plugin/ticket/src/new_ticket.php
  55. 32 32
      plugin/ticket/src/ticket_details.php

+ 1 - 1
main/admin/add_courses_to_usergroup.php

@@ -100,7 +100,7 @@ $filters = array(
 );
 
 $searchForm = new FormValidator('search', 'get', api_get_self().'?id='.$id);
-$searchForm->add_header(get_lang('AdvancedSearch'));
+$searchForm->addHeader(get_lang('AdvancedSearch'));
 $renderer =& $searchForm->defaultRenderer();
 $searchForm->addElement('hidden', 'id', $id);
 foreach ($filters as $param) {

+ 1 - 1
main/admin/add_users_to_usergroup.php

@@ -184,7 +184,7 @@ $filters = array(
 );
 
 $searchForm = new FormValidator('search', 'get', api_get_self().'?id='.$id);
-$searchForm->add_header(get_lang('AdvancedSearch'));
+$searchForm->addHeader(get_lang('AdvancedSearch'));
 $renderer =& $searchForm->defaultRenderer();
 
 $searchForm->addElement('hidden', 'id', $id);

+ 3 - 4
main/admin/course_category.php

@@ -3,9 +3,7 @@
 /**
  * 	@package chamilo.admin
  */
-/**
- * Code
- */
+
 // name of the language file that needs to be included
 $language_file = 'admin';
 $cidReset = true;
@@ -82,10 +80,11 @@ if ($action == 'add' || $action == 'edit') {
         if (!empty($category)) {
             $form_title .= ' ' . get_lang('Into') . ' ' . Security::remove_XSS($category);
         }
-        $url = api_get_self().'?action='.Security::remove_XSS($action).'&category='.Security::remove_XSS($category).'&id='.$categoryId;
+        $url = api_get_self().'?action='.Security::remove_XSS($action).'&category='.Security::remove_XSS($category).'&id='.$category;
         $form = new FormValidator('course_category', 'post', $url);
         $form->addElement('header', '', $form_title);
         $form->addElement('hidden', 'formSent', 1);
+
         $form->addElement('text', 'code', get_lang("CategoryCode"));
         $form->addElement('text', 'name', get_lang("CategoryName"));
         $form->addRule('name', get_lang('PleaseEnterCategoryInfo'), 'required');

+ 1 - 1
main/admin/course_import.php

@@ -210,7 +210,7 @@ if (isset($errors) && count($errors) != 0) {
 }
 
 $form = new FormValidator('import', 'post', api_get_self(), null, array('enctype' => 'multipart/form-data'));
-$form->add_header($tool_name);
+$form->addHeader($tool_name);
 $form->addElement('file', 'import_file', get_lang('ImportCSVFileLocation'));
 $form->addElement('checkbox', 'add_me_as_teacher', null, get_lang('AddMeAsTeacherInCourses'));
 $form->addElement('button', 'save', get_lang('Import'));

+ 1 - 1
main/admin/dashboard_add_users_to_user.php

@@ -259,7 +259,7 @@ $filters = array(
 );
 
 $searchForm = new FormValidator('search', 'get', api_get_self().'?user='.$user_id);
-$searchForm->add_header(get_lang('AdvancedSearch'));
+$searchForm->addHeader(get_lang('AdvancedSearch'));
 $renderer =& $searchForm->defaultRenderer();
 
 $searchForm->addElement('hidden', 'user', $user_id);

+ 32 - 5
main/admin/session_add.php

@@ -258,7 +258,7 @@ if (intval($countUsers) < 50) {
     $form->addElement('select', 'coach_username', get_lang('CoachName'), $coachesOptions, array(
         'id' => 'coach_username',
         'class' => 'chzn-select',
-        'style' => 'width:350px;'
+        'style' => 'width:370px;'
     ));
     $form->addElement('advanced_settings', Display::return_icon('synthese_view.gif') . ' ' . get_lang('ActivityCoach'));
 } else {
@@ -276,7 +276,7 @@ $form->add_html('<div id="ajax_list_coachs"></div>');
 $form->add_select('session_category', get_lang('SessionCategory'), $categoriesOptions, array(
     'id' => 'session_category',
     'class' => 'chzn-select',
-    'style' => 'width:350px;'
+    'style' => 'width:370px;'
 ));
 
 $form->addElement('advanced_settings','<a class="btn-show" id="advanced_parameters" href="javascript://">'.get_lang('DefineSessionOptions').'</a>');
@@ -327,6 +327,18 @@ $form->addGroup($visibilityGroup, 'visibility_group', null, null, false);
 
 $form->addElement('html','</div>');
 
+$form->addElement(
+    'textarea',
+    'description',
+    get_lang('Description'),
+    array(
+        'class' => 'span4',
+        'rows' => 3
+    )
+);
+
+$form->addElement('checkbox', 'show_description', null, get_lang('ShowDescription'));
+
 $form->addElement(
     'text',
     'duration',
@@ -385,6 +397,8 @@ if ($form->validate()) {
     $end_limit = isset($params['end_limit']) ? true : false;
     $start_limit = isset($params['start_limit']) ? true : false;
     $duration = isset($params['duration']) ? $params['duration'] : null;
+    $description = $params['description'];
+    $showDescription = isset($params['show_description']) ? 1: 0;
 
     if (empty($end_limit) && empty($start_limit)) {
         $nolimit = 1;
@@ -401,9 +415,22 @@ if ($form->validate()) {
     }
 
     $return = SessionManager::create_session(
-        $name, $startDate, $endDate, $nb_days_acess_before,
-        $nb_days_acess_after, $nolimit, $coach_username, $id_session_category, $id_visibility, $start_limit,
-        $end_limit, false, $duration, $extraFields
+        $name,
+        $startDate,
+        $endDate,
+        $nb_days_acess_before,
+        $nb_days_acess_after,
+        $nolimit,
+        $coach_username,
+        $id_session_category,
+        $id_visibility,
+        $start_limit,
+        $end_limit,
+        false,
+        $duration,
+        $description,
+        $showDescription,
+        $extraFields
     );
 
     if ($return == strval(intval($return))) {

+ 16 - 21
main/admin/session_edit.php

@@ -37,17 +37,6 @@ $interbreadcrumb[] = array('url' => "resume_session.php?id_session=".$id,"name"
 list($year_start, $month_start, $day_start) = explode('-', $infos['date_start']);
 list($year_end, $month_end, $day_end) = explode('-', $infos['date_end']);
 
-// Default value
-$showDescriptionChecked = 'checked';
-
-if (isset($infos['show_description'])) {
-    if (!empty($infos['show_description'])) {
-        $showDescriptionChecked = 'checked';
-    } else {
-        $showDescriptionChecked = null;
-    }
-}
-
 $end_year_disabled = $end_month_disabled = $end_day_disabled = '';
 
 if (isset($_POST['formSent']) && $_POST['formSent']) {
@@ -219,18 +208,24 @@ $form->addGroup($visibilityGroup, 'visibility_group', null, null, false);
 
 $form->addElement('html','</div>');
 
-if (array_key_exists('show_description', $infos)) {
-    $form->addElement('textarea', 'description', get_lang('Description'));
-
-    $chkDescriptionAttributes = array();
+$form->addElement(
+    'textarea',
+    'description',
+    get_lang('Description'),
+    array(
+        'class' => 'span4',
+        'rows' => 3
+    )
+);
 
-    if (!empty($showDescriptionChecked)) {
-        $chkDescriptionAttributes['checked'] = '';
-    }
+$chkDescriptionAttributes = array();
 
-    $form->addElement('checkbox', 'show_description', null, get_lang('ShowDescription'), $chkDescriptionAttributes);
+if (!empty($infos['show_description'])) {
+    $chkDescriptionAttributes['checked'] = '';
 }
 
+$form->addElement('checkbox', 'show_description', null, get_lang('ShowDescription'), $chkDescriptionAttributes);
+
 $duration = empty($infos['duration']) ? null : $infos['duration'];
 
 $form->addElement(
@@ -268,7 +263,7 @@ $formDefaults = array(
     'date_start' => $infos['date_start'],
     'date_end' => $infos['date_end'],
     'session_visibility' => $infos['visibility'],
-    'description' => array_key_exists('show_description', $infos) ? $infos['description'] : ''
+    'description' => $infos['description']
 );
 
 if ($formSent) {
@@ -297,7 +292,7 @@ if ($form->validate()) {
     $id_session_category = $params['session_category'];
     $id_visibility = $params['session_visibility'];
     $duration = isset($params['duration']) ? $params['duration'] : null;
-    $description = isset($params['description']) ? $params['description'] : null;
+    $description = $params['description'];
     $showDescription = isset($params['show_description']) ? 1: 0;
 
     $end_limit = $params['end_limit'];

+ 1 - 1
main/admin/session_user_edit.php

@@ -33,7 +33,7 @@ $interbreadcrumb[] = array('url' => 'session_list.php','name' => get_lang('Sessi
 $interbreadcrumb[] = array('url' => "resume_session.php?id_session=".$sessionId, "name" => get_lang('SessionOverview'));
 
 $form = new FormValidator('edit', 'post', api_get_self().'?session_id='.$sessionId.'&user_id='.$userId);
-$form->add_header(get_lang('EditUserSessionDuration'));
+$form->addHeader(get_lang('EditUserSessionDuration'));
 $data = SessionManager::getUserSession($userId, $sessionId);
 $userInfo = api_get_user_info($userId);
 

+ 1 - 1
main/admin/user_add.php

@@ -235,7 +235,7 @@ $form->addGroup($group, 'mail', get_lang('SendMailToNewUser'), '&nbsp;');
 $form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
 $group = array ();
 $group[] = $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
-$group[] = $form->createElement('datepicker', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
+$group[] = $form->createElement('DatePicker', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
 $form->addGroup($group, 'max_member_group', null, '', false);
 // Active account or inactive account
 $form->addElement('radio', 'active', get_lang('ActiveAccount'), get_lang('Active'), 1);

+ 1 - 1
main/admin/user_edit.php

@@ -263,7 +263,7 @@ if (!$user_data['platform_admin']) {
 	$form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
 	$group = array ();
 	$group[] = $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
-	$group[] = $form->createElement('datepicker', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
+	$group[] = $form->createElement('DatePickerDate', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
 	$form->addGroup($group, 'max_member_group', null, '', false);
 
 	// Active account or inactive account

+ 119 - 94
main/blog/blog.php

@@ -6,9 +6,6 @@
  * @package chamilo.blogs
  */
 
-/**
- *	INIT
- */
 // name of the language file that needs to be included
 $language_file = "blog";
 require_once '../inc/global.inc.php';
@@ -22,18 +19,11 @@ if (empty($blog_id)) {
 $this_section   = SECTION_COURSES;
 $current_course_tool  = TOOL_BLOGS;
 
-
 /* 	ACCESS RIGHTS */
 // notice for unauthorized people.
 api_protect_course_script(true);
 
-//session
-if(isset($_GET['id_session'])) {
-	$_SESSION['id_session'] = intval($_GET['id_session']);
-}
-
 $lib_path = api_get_path(LIBRARY_PATH);
-
 $blog_table_attachment 	= Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
 
 $nameTools  = get_lang('Blogs');
@@ -41,95 +31,146 @@ $DaysShort  = api_get_week_days_short();
 $DaysLong   = api_get_week_days_long();
 $MonthsLong = api_get_months_long();
 
-$current_page = $_GET['action'];
+$action = isset($_GET['action']) ? $_GET['action'] : null;
 
 /*
 	PROCESSING
 */
 
-$safe_post_title            = Security::remove_XSS($_POST['post_title']);
-$safe_post_file_comment     = Security::remove_XSS($_POST['post_file_comment']);
-$safe_post_full_text        = Security::remove_XSS(stripslashes(api_html_entity_decode($_POST['post_full_text'])), COURSEMANAGERLOWSECURITY);
-$safe_comment_text          = Security::remove_XSS(stripslashes(api_html_entity_decode($_POST['comment_text'])), COURSEMANAGERLOWSECURITY);
-$safe_comment_title         = Security::remove_XSS($_POST['comment_title']);
-$safe_task_name             = Security::remove_XSS($_POST['task_name']);
-$safe_task_description      = Security::remove_XSS($_POST['task_description']);
-
-if (!empty($_POST['new_post_submit']) AND !empty($_POST['post_title'])) {
-	Blog :: create_post($safe_post_title, $safe_post_full_text, $safe_post_file_comment,$blog_id);
+$safe_post_file_comment = isset($_GET['post_file_comment']) ? Security::remove_XSS($_POST['post_file_comment']) : null;
+$safe_comment_text      = isset($_GET['comment_text']) ? Security::remove_XSS(stripslashes(api_html_entity_decode($_POST['comment_text'])), COURSEMANAGERLOWSECURITY) : null;
+$safe_comment_title     = isset($_GET['comment_title']) ? Security::remove_XSS($_POST['comment_title']) : null;
+$safe_task_name         = isset($_GET['task_name']) ? Security::remove_XSS($_POST['task_name']) : null;
+$safe_task_description  = isset($_GET['task_description']) ? Security::remove_XSS($_POST['task_description']) : null;
+
+if (!empty($_POST['new_post_submit'])) {
+	Blog:: create_post(
+		$_POST['title'],
+		$_POST['full_text'],
+		$_POST['post_file_comment'],
+		$blog_id
+	);
 	$return_message = array('type' => 'confirmation', 'message' => get_lang('BlogAdded'));
 }
-if (!empty($_POST['edit_post_submit']))
-{
-	$safe_post_title = Security::remove_XSS($_POST['post_title']);
-	Blog :: edit_post($_POST['post_id'], $safe_post_title, $safe_post_full_text, $blog_id);
+if (!empty($_POST['edit_post_submit'])) {
+	Blog:: edit_post(
+		$_POST['post_id'],
+		$_POST['title'],
+		$_POST['full_text'],
+		$blog_id
+	);
 	$return_message = array('type' => 'confirmation', 'message' => get_lang('BlogEdited'));
 }
-if (!empty($_POST['new_comment_submit']))
-{
-	Blog :: create_comment($safe_comment_title, $safe_comment_text, $safe_post_file_comment,$blog_id, (int)$_GET['post_id'], $_POST['comment_parent_id']);
+
+if (!empty($_POST['new_comment_submit'])) {
+	Blog:: create_comment(
+		$_POST['title'],
+		$_POST['comment'],
+		$_POST['post_file_comment'],
+		$blog_id,
+		$_GET['post_id'],
+		$_POST['comment_parent_id']
+	);
 	$return_message = array('type' => 'confirmation', 'message' => get_lang('CommentAdded'));
 }
 
-if (!empty($_POST['new_task_submit']))
-{
-	Blog :: create_task($blog_id, $safe_task_name, $safe_task_description, $_POST['chkArticleDelete'], $_POST['chkArticleEdit'], $_POST['chkCommentsDelete'], $_POST['task_color']);
+if (!empty($_POST['new_task_submit'])) {
+	Blog:: create_task(
+		$blog_id,
+		$safe_task_name,
+		$safe_task_description,
+		$_POST['chkArticleDelete'],
+		$_POST['chkArticleEdit'],
+		$_POST['chkCommentsDelete'],
+		$_POST['task_color']
+	);
 	$return_message = array('type' => 'confirmation', 'message' => get_lang('TaskCreated'));
 }
 
-if (isset($_POST['edit_task_submit']))
-{
-	Blog :: edit_task($_POST['blog_id'], $_POST['task_id'], $safe_task_name, $safe_task_description, $_POST['chkArticleDelete'], $_POST['chkArticleEdit'],$_POST['chkCommentsDelete'], $_POST['task_color']);
-	$return_message = array('type' => 'confirmation', 'message' => get_lang('TaskEdited'));
+if (isset($_POST['edit_task_submit'])) {
+	Blog:: edit_task(
+		$_POST['blog_id'],
+		$_POST['task_id'],
+		$safe_task_name,
+		$safe_task_description,
+		$_POST['chkArticleDelete'],
+		$_POST['chkArticleEdit'],
+		$_POST['chkCommentsDelete'],
+		$_POST['task_color']
+	);
+	$return_message = array(
+		'type' => 'confirmation',
+		'message' => get_lang('TaskEdited')
+	);
 }
-if (!empty($_POST['assign_task_submit']))
-{
-	Blog :: assign_task($blog_id, $_POST['task_user_id'], $_POST['task_task_id'], $_POST['task_year']."-".$_POST['task_month']."-".$_POST['task_day']);
-	$return_message = array('type' => 'confirmation', 'message' => get_lang('TaskAssigned'));
+
+if (!empty($_POST['assign_task_submit'])) {
+	Blog:: assign_task(
+		$blog_id,
+		$_POST['task_user_id'],
+		$_POST['task_task_id'],
+		$_POST['task_year'] . "-" . $_POST['task_month'] . "-" . $_POST['task_day']
+	);
+	$return_message = array(
+		'type' => 'confirmation',
+		'message' => get_lang('TaskAssigned')
+	);
 }
 
-if (isset($_POST['assign_task_edit_submit']))
-{
-    Blog :: edit_assigned_task($blog_id, $_POST['task_user_id'], $_POST['task_task_id'], $_POST['task_year']."-".$_POST['task_month']."-".$_POST['task_day'], $_POST['old_user_id'], $_POST['old_task_id'], $_POST['old_target_date']);
-    $return_message = array('type' => 'confirmation', 'message' => get_lang('AssignedTaskEdited'));
+if (isset($_POST['assign_task_edit_submit'])) {
+	Blog:: edit_assigned_task(
+		$blog_id,
+		$_POST['task_user_id'],
+		$_POST['task_task_id'],
+		$_POST['task_year'] . "-" . $_POST['task_month'] . "-" . $_POST['task_day'],
+		$_POST['old_user_id'],
+		$_POST['old_task_id'],
+		$_POST['old_target_date']
+	);
+	$return_message = array(
+		'type' => 'confirmation',
+		'message' => get_lang('AssignedTaskEdited')
+	);
 }
-if (!empty($_POST['new_task_execution_submit']))
-{
-	Blog :: create_comment($safe_comment_title, $safe_comment_text, $blog_id, (int)$_GET['post_id'], $_POST['comment_parent_id'], $_POST['task_id']);
-	$return_message = array('type' => 'confirmation', 'message' => get_lang('CommentCreated'));
+if (!empty($_POST['new_task_execution_submit'])) {
+	Blog:: create_comment(
+		$safe_comment_title,
+		$safe_comment_text,
+		$blog_id,
+		(int)$_GET['post_id'],
+		$_POST['comment_parent_id'],
+		$_POST['task_id']
+	);
+	$return_message = array(
+		'type' => 'confirmation',
+		'message' => get_lang('CommentCreated')
+	);
 }
-if (!empty($_POST['register']))
-{
+if (!empty($_POST['register'])) {
 	if (is_array($_POST['user'])) {
-		foreach ($_POST['user'] as $index => $user_id)
-		{
+		foreach ($_POST['user'] as $index => $user_id) {
 			Blog :: set_user_subscribed((int)$_GET['blog_id'], $user_id);
 		}
 	}
 }
-if (!empty($_POST['unregister']))
-{
+if (!empty($_POST['unregister'])) {
 	if (is_array($_POST['user'])) {
-		foreach ($_POST['user'] as $index => $user_id)
-		{
+		foreach ($_POST['user'] as $index => $user_id) {
 			Blog :: set_user_unsubscribed((int)$_GET['blog_id'], $user_id);
 		}
 	}
 }
-if (!empty($_GET['register']))
-{
+if (!empty($_GET['register'])) {
 	Blog :: set_user_subscribed((int)$_GET['blog_id'], (int)$_GET['user_id']);
 	$return_message = array('type' => 'confirmation', 'message' => get_lang('UserRegistered'));
 	$flag = 1;
 }
-if (!empty($_GET['unregister']))
-{
+if (!empty($_GET['unregister'])) {
 	Blog :: set_user_unsubscribed((int)$_GET['blog_id'], (int)$_GET['user_id']);
 }
 
 if (isset($_GET['action']) && $_GET['action'] == 'manage_tasks') {
-	if (isset($_GET['do']) && $_GET['do'] == 'delete')
-	{
+	if (isset($_GET['do']) && $_GET['do'] == 'delete') {
 		Blog :: delete_task($blog_id, (int)$_GET['task_id']);
 		$return_message = array('type' => 'confirmation', 'message' => get_lang('TaskDeleted'));
 	}
@@ -138,54 +179,40 @@ if (isset($_GET['action']) && $_GET['action'] == 'manage_tasks') {
 		Blog :: delete_assigned_task($blog_id, intval($_GET['task_id']), intval($_GET['user_id']));
 		$return_message = array('type' => 'confirmation', 'message' => get_lang('TaskAssignmentDeleted'));
 	}
-
 }
 
 if (isset($_GET['action']) && $_GET['action'] == 'view_post') {
 	$task_id = (isset ($_GET['task_id']) && is_numeric($_GET['task_id'])) ? $_GET['task_id'] : 0;
 
-	if (isset($_GET['do']) && $_GET['do'] == 'delete_comment')
-	{
-		if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_delete', $task_id))
-		{
+	if (isset($_GET['do']) && $_GET['do'] == 'delete_comment')	{
+		if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_delete', $task_id)) {
 			Blog :: delete_comment($blog_id, (int)$_GET['post_id'],(int)$_GET['comment_id']);
 			$return_message = array('type' => 'confirmation', 'message' => get_lang('CommentDeleted'));
-		}
-		else
-		{
+		} else {
 			$error = true;
 			$message = get_lang('ActionNotAllowed');
 		}
 	}
 
-	if (isset($_GET['do']) && $_GET['do'] == 'delete_article')
-	{
-		if (api_is_allowed('BLOG_'.$blog_id, 'article_delete', $task_id))
-		{
+	if (isset($_GET['do']) && $_GET['do'] == 'delete_article')	{
+		if (api_is_allowed('BLOG_'.$blog_id, 'article_delete', $task_id)) {
 			Blog :: delete_post($blog_id, (int)$_GET['article_id']);
-			$current_page = ''; // Article is gone, go to blog home
+			$action = ''; // Article is gone, go to blog home
 			$return_message = array('type' => 'confirmation', 'message' => get_lang('BlogDeleted'));
-		}
-		else
-		{
+		} else {
 			$error = true;
 			$message = get_lang('ActionNotAllowed');
 		}
 	}
-	if (isset($_GET['do']) && $_GET['do'] == 'rate')
-	{
-		if (isset($_GET['type']) && $_GET['type'] == 'post')
-		{
-			if (api_is_allowed('BLOG_'.$blog_id, 'article_rate'))
-			{
+	if (isset($_GET['do']) && $_GET['do'] == 'rate') {
+		if (isset($_GET['type']) && $_GET['type'] == 'post') {
+			if (api_is_allowed('BLOG_'.$blog_id, 'article_rate')) {
 				Blog :: add_rating('post', $blog_id, (int)$_GET['post_id'], (int)$_GET['rating']);
 				$return_message = array('type' => 'confirmation', 'message' => get_lang('RatingAdded'));
 			}
 		}
-		if (isset($_GET['type']) && $_GET['type'] == 'comment')
-		{
-			if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_add'))
-			{
+		if (isset($_GET['type']) && $_GET['type'] == 'comment') {
+			if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_add')) {
 				Blog :: add_rating('comment', $blog_id, (int)$_GET['comment_id'], (int)$_GET['rating']);
 				$return_message = array('type' => 'confirmation', 'message' => get_lang('RatingAdded'));
 			}
@@ -198,7 +225,7 @@ if (isset($_GET['action']) && $_GET['action'] == 'view_post') {
 $htmlHeadXtra[] = '<script src="tbl_change.js" type="text/javascript"></script>';
 
 // Set bredcrumb
-switch ($current_page) {
+switch ($action) {
 	case 'new_post' :
 		$nameTools = get_lang('NewPost');
 		$interbreadcrumb[] = array ('url' => "blog.php?blog_id=$blog_id", "name" => Blog :: get_blog_title($blog_id));
@@ -244,7 +271,6 @@ if (!empty($return_message)) {
 	}
 }
 
-
 // actions
 echo '<div class=actions>';
 ?>
@@ -258,7 +284,6 @@ echo '</div>';
 // Tool introduction
 Display::display_introduction_section(TOOL_BLOGS);
 
-//Display::display_header($nameTools,'Blogs');
 ?>
 <div class="sectiontitle"><?php echo Blog::get_blog_title($blog_id); ?></div>
 <div class="sectioncomment"><?php echo Blog::get_blog_subtitle($blog_id); ?></div>
@@ -309,7 +334,7 @@ if (isset($error)) {
 }
 
 if (isset($flag) && $flag == '1') {
-	$current_page = "manage_tasks";
+	$action = "manage_tasks";
 	Blog :: display_assign_task_form($blog_id);
 }
 
@@ -338,13 +363,13 @@ if (isset ($_GET['task_id']) && is_numeric($_GET['task_id'])) {
 		$user_task = true;
 }
 
-switch ($current_page) {
-	case 'new_post' :
+switch ($action) {
+	case 'new_post':
 		if (api_is_allowed('BLOG_'.$blog_id, 'article_add', $user_task ? $task_id : 0)) {
 			// we show the form if
 			// 1. no post data
 			// 2. there is post data and the required field is empty
-			if (!$_POST OR (!empty($_POST) AND empty($_POST['post_title']))) {
+			if (!$_POST OR (!empty($_POST) AND empty($_POST['title']))) {
 				// if there is post data there is certainly an error in the form
 				if ($_POST) {
 					Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));

+ 5 - 11
main/blog/blog_admin.php

@@ -1,5 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
  *    BLOG HOMEPAGE
  *	This file takes care of all blog navigation and displaying.
@@ -52,22 +53,15 @@ if (api_is_allowed_to_edit()) {
 		Display::return_icon('new_blog.png',get_lang('AddBlog'),'',ICON_SIZE_MEDIUM)."</a>";
 	echo '</div>';
 
-	/*
-			PROCESSING..
-	*/
-	$get_blog_name	   = Security::remove_XSS($_POST['blog_name']);
-	$get_blog_subtitle = Security::remove_XSS($_POST['blog_subtitle']);
-	$get_blog_id       = Security::remove_XSS($_POST['blog_id']);
-
 	if (!empty($_POST['new_blog_submit']) AND !empty($_POST['blog_name'])) {
 		if (isset($_POST['blog_name']))  {
-			Blog::create_blog($get_blog_name,$get_blog_subtitle);
+			Blog::create_blog($_POST['blog_name'], $_POST['blog_subtitle']);
 			Display::display_confirmation_message(get_lang('BlogStored'));
 		}
 	}
 	if (!empty($_POST['edit_blog_submit']) AND !empty($_POST['blog_name'])) {
 		if (strlen(trim($_POST['blog_name']))>0) {
-			Blog::edit_blog($get_blog_id,$get_blog_name,$get_blog_subtitle);
+			Blog::edit_blog($_POST['blog_id'], $_POST['blog_name'], $_POST['blog_subtitle']);
 			Display::display_confirmation_message(get_lang('BlogEdited'));
 		}
 	}
@@ -94,11 +88,11 @@ if (api_is_allowed_to_edit()) {
 			/*if ($_POST){
 				Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));
 			}*/
-			if (strlen($_POST['blog_name'])==0) {
+			/*if (strlen($_POST['blog_name'])==0) {
 				if (count($_POST)>0) {
 					Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));
 				}
-			}
+			}*/
 			Blog::display_new_blog_form();
 		}
 	}

+ 1 - 1
main/course_description/course_description_form.class.php

@@ -70,7 +70,7 @@ class CourseDescriptionForm extends \FormValidator
         $defaults['title'] = $description->title;
         $defaults['content'] = $description->content;
 
-        $this->add_header($description->get_title());
+        $this->addHeader($description->get_title());
         $this->addHidden('description_type', $description->get_description_type());
         $this->addHidden('c_id', $description->c_id);
         $this->addHidden('id', $description->id);

+ 1 - 1
main/course_description/upload_file_form.class.php

@@ -33,7 +33,7 @@ class UploadFileForm extends \FormValidator
     function init()
     {
         $form_name = get_lang('UploadFile');
-        $this->add_header($form_name);
+        $this->addHeader($form_name);
 
         $label = get_lang('File');
         $this->add_file('file', $label);

+ 1 - 1
main/course_progress/thematic_advance.php

@@ -47,7 +47,7 @@ if ($action == 'thematic_advance_add' || $action == 'thematic_advance_edit') {
         $form->addElement('html', '<div id="div_custom_datetime" style="display:none">');
     }
 
-    $form->addElement('datepicker', 'custom_start_date', get_lang('StartDate'), array('form_name'=>'thematic_advance'));
+    $form->addElement('DatePicker', 'custom_start_date', get_lang('StartDate'), array('form_name'=>'thematic_advance'));
     $form->addElement('html', '</div>');
 
     if (isset($thematic_advance_data['attendance_id']) && $thematic_advance_data['attendance_id'] == 0) {

+ 1 - 1
main/document/showinframes.php

@@ -173,7 +173,7 @@ if (api_get_setting('show_glossary_in_documents') == 'ismanual') {
                                                 {type:"script", id:"_fr4", src:"'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery-ui/smoothness/jquery-ui-1.8.21.custom.min.js"},
                                                 {type:"stylesheet", id:"_fr5", src:"'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery-ui/smoothness/jquery-ui-1.8.21.custom.css"},
                                                 {type:"script", id:"_fr2", src:"'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.highlight.js"},
-                                                {type:"script", id:"_fr3", src:"'.api_get_path(WEB_LIBRARY_PATH).'fckeditor/editor/plugins/glossary/fck_glossary_manual.js"}
+                                                {type:"script", id:"_fr3", src:"'.api_get_path(WEB_LIBRARY_PATH).'javascript/ckeditor/plugins/glossary/fck_glossary_manual.js"}
                                            ]
                                       }
                                       );

+ 1 - 1
main/document/showinframesmin.php

@@ -98,7 +98,7 @@ if (api_get_setting('show_glossary_in_documents') == 'ismanual') {
                                       { load: [
                                               {type:"script", id:"_fr1", src:"'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.min.js"},
                                             {type:"script", id:"_fr2", src:"'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.highlight.js"},
-                                            {type:"script", id:"_fr3", src:"'.api_get_path(WEB_LIBRARY_PATH).'fckeditor/editor/plugins/glossary/fck_glossary_manual.js"}
+                                            {type:"script", id:"_fr3", src:"'.api_get_path(WEB_LIBRARY_PATH).'javascript/ckeditor/plugins/glossary/fck_glossary_manual.js"}
                                            ]
                                       }
                                       );

+ 1 - 1
main/glossary/glossary_form.class.php

@@ -74,7 +74,7 @@ class GlossaryForm extends \FormValidator
         $this->addHidden(Request::PARAM_SEC_TOKEN, Access::instance()->get_token());
 
         $form_name = $glossary->id ? get_lang('TermEdit') : get_lang('TermAddNew');
-        $this->add_header($form_name);
+        $this->addHeader($form_name);
 
         $this->add_textfield('name', get_lang('TermName'), $required = true, array('class' => 'span3'));
         $this->add_html_editor('description', get_lang('TermDefinition'), true, array('ToolbarSet' => 'Glossary', 'Width' => '90%', 'Height' => '300'));

+ 1 - 1
main/glossary/upload_file_form.class.php

@@ -42,7 +42,7 @@ class UploadFileForm extends \FormValidator
     function init()
     {
         $form_name = get_lang('ImportGlossary');
-        $this->add_header($form_name);
+        $this->addHeader($form_name);
 
         $this->addHidden(Request::PARAM_SEC_TOKEN, Access::instance()->get_token());
         $label = get_lang('ImportCSVFileLocation');

+ 1 - 1
main/inc/lib/auth.lib.php

@@ -630,7 +630,7 @@ class Auth
                 if ($session['nbr_courses'] > 0) {
                     $session['coach_name'] = api_get_person_name($session['firstname'], $session['lastname']);
                     $session['coach_name'] .= " ({$session['username']})";
-                    $session['is_subscribed'] = SessionManager::isUserSusbcribedAsStudent($session['id'], $userId);
+                    $session['is_subscribed'] = SessionManager::isUserSubscribedAsStudent($session['id'], $userId);
 
                     $sessionsToBrowse[] = $session;
                 }

+ 168 - 207
main/inc/lib/blog.lib.php

@@ -15,7 +15,8 @@
  * Class
  * @package chamilo.blogs
  */
-class Blog {
+class Blog
+{
 	/**
 	 * Get the title of a blog
 	 * @author Toon Keppens
@@ -227,19 +228,18 @@ class Blog {
 	 * @param String $full_text
 	 * @param Integer $blog_id
 	 */
-	public static function create_post ($title, $full_text, $file_comment, $blog_id) {
-		global $_user;
-		global $_course;
+	public static function create_post($title, $full_text, $file_comment, $blog_id)
+	{
+		$_user = api_get_user_info();
+		$_course = api_get_course_info();
+		$course_id = api_get_course_int_id();
 
 		$blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
 		$upload_ok=true;
 		$has_attachment=false;
-		$current_date=date('Y-m-d H:i:s',time());
-
-		$course_id = api_get_course_int_id();
-
+		$current_date = api_get_utc_datetime();
 
-		if(!empty($_FILES['user_upload']['name'])) {
+		if (!empty($_FILES['user_upload']['name'])) {
 			$upload_ok = process_uploaded_file($_FILES['user_upload']);
 			$has_attachment=true;
 		}
@@ -270,16 +270,16 @@ class Blog {
 					Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
 				} else {
 					$new_file_name = uniqid('');
-					$new_path=$updir.'/'.$new_file_name;
+					$new_path = $updir.'/'.$new_file_name;
 					$result= @move_uploaded_file($_FILES['user_upload']['tmp_name'], $new_path);
-					$comment=Database::escape_string($file_comment);
+					$comment = Database::escape_string($file_comment);
 
 					// Storing the attachments if any
 					if ($result) {
-						$sql='INSERT INTO '.$blog_table_attachment.'(c_id, filename,comment, path, post_id,size, blog_id,comment_id) '.
-							 "VALUES ($course_id, '".Database::escape_string($file_name)."', '".$comment."', '".Database::escape_string($new_file_name)."' , '".$last_post_id."', '".intval($_FILES['user_upload']['size'])."',  '".$blog_id."', '0' )";
-						$result=Database::query($sql);
-						$message.=' / '.get_lang('AttachmentUpload');
+						$sql = 'INSERT INTO '.$blog_table_attachment.'(c_id, filename,comment, path, post_id,size, blog_id,comment_id) '.
+							   "VALUES ($course_id, '".Database::escape_string($file_name)."', '".$comment."', '".Database::escape_string($new_file_name)."' , '".$last_post_id."', '".intval($_FILES['user_upload']['size'])."',  '".$blog_id."', '0' )";
+						Database::query($sql);
+						//Display::display_confirmation_message(get_lang('AttachmentUpload'));
 					}
 				}
 			}
@@ -346,9 +346,10 @@ class Blog {
 	 * @param Integer $post_id
 	 * @param Integer $parent_id
 	 */
-	public static function create_comment($title, $full_text, $file_comment,$blog_id, $post_id, $parent_id, $task_id = 'NULL') {
-		global $_user;
-		global $_course;
+	public static function create_comment($title, $full_text, $file_comment, $blog_id, $post_id, $parent_id, $task_id = 'NULL')
+	{
+		$_user = api_get_user_info();
+		$_course = api_get_course_info();
 		global $blog_table_attachment;
 
 		$upload_ok			= true;
@@ -356,7 +357,7 @@ class Blog {
 		$current_date		= date('Y-m-d H:i:s',time());
 		$course_id 			= api_get_course_int_id();
 
-		if(!empty($_FILES['user_upload']['name'])) {
+		if (!empty($_FILES['user_upload']['name'])) {
 			$upload_ok = process_uploaded_file($_FILES['user_upload']);
 			$has_attachment=true;
 		}
@@ -371,10 +372,7 @@ class Blog {
 			Database::query($sql);
 
 			// Empty post values, or they are shown on the page again
-			$_POST['comment_title'] = "";
-			$_POST['comment_text'] = "";
-
-			$last_id=Database::insert_id();
+			$last_id = Database::insert_id();
 
 			if ($has_attachment) {
 				$courseDir   = $_course['path'].'/upload/blog';
@@ -382,29 +380,28 @@ class Blog {
 				$updir = $sys_course_path.$courseDir;
 
 				// Try to add an extension to the file if it hasn't one
-				$new_file_name = add_ext_on_mime(stripslashes($_FILES['user_upload']['name']), $_FILES['user_upload']['type']);
+				$new_file_name = add_ext_on_mime(
+					stripslashes($_FILES['user_upload']['name']),
+					$_FILES['user_upload']['type']
+				);
 
 				// user's file name
 				$file_name =$_FILES['user_upload']['name'];
 
-				if (!filter_extension($new_file_name))
-				{
+				if (!filter_extension($new_file_name)) {
 					Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
-				}
-				else
-				{
+				} else {
 					$new_file_name = uniqid('');
 					$new_path=$updir.'/'.$new_file_name;
 					$result= @move_uploaded_file($_FILES['user_upload']['tmp_name'], $new_path);
-					$comment=Database::escape_string($file_comment);
+					$comment = Database::escape_string($file_comment);
 
 					// Storing the attachments if any
-					if ($result)
-					{
+					if ($result) {
 						$sql='INSERT INTO '.$blog_table_attachment.'(c_id, filename,comment, path, post_id,size,blog_id,comment_id) '.
 							 "VALUES ($course_id, '".Database::escape_string($file_name)."', '".$comment."', '".Database::escape_string($new_file_name)."' , '".$post_id."', '".$_FILES['user_upload']['size']."',  '".$blog_id."', '".$last_id."'  )";
-						$result=Database::query($sql);
-						$message.=' / '.get_lang('AttachmentUpload');
+						Database::query($sql);
+						//$message.=' / '.get_lang('AttachmentUpload');
 					}
 				}
 			}
@@ -417,24 +414,25 @@ class Blog {
 	 * @param Integer $blog_id
 	 * @param Integer $comment_id
 	 */
-	public static function delete_comment ($blog_id, $post_id, $comment_id) {
-		// Init
+	public static function delete_comment ($blog_id, $post_id, $comment_id)
+	{
 		$tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
 		$tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
 		$blog_id = intval($blog_id);
 		$post_id = intval($post_id);
 		$comment_id = intval($comment_id);
-
         $course_id = api_get_course_int_id();
 
-		delete_all_blog_attachment($blog_id,$post_id,$comment_id);
+		delete_all_blog_attachment($blog_id, $post_id, $comment_id);
 
 		// Delete ratings on this comment
-		$sql = "DELETE FROM $tbl_blogs_rating WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND item_id = '".(int)$comment_id."' AND rating_type = 'comment'";
+		$sql = "DELETE FROM $tbl_blogs_rating
+				WHERE c_id = $course_id AND blog_id = '".$blog_id."' AND item_id = '".$comment_id."' AND rating_type = 'comment'";
 		Database::query($sql);
 
 		// select comments that have the selected comment as their parent
-		$sql = "SELECT comment_id FROM $tbl_blogs_comments WHERE c_id = $course_id AND parent_comment_id = '".(int)$comment_id."'";
+		$sql = "SELECT comment_id FROM $tbl_blogs_comments
+				WHERE c_id = $course_id AND parent_comment_id = '".$comment_id."'";
 		$result = Database::query($sql);
 
 		// Delete them recursively
@@ -443,7 +441,8 @@ class Blog {
 		}
 
 		// Finally, delete the selected comment to
-		$sql = "DELETE FROM $tbl_blogs_comments WHERE c_id = $course_id AND comment_id = '".(int)$comment_id."'";
+		$sql = "DELETE FROM $tbl_blogs_comments
+				WHERE c_id = $course_id AND comment_id = '".$comment_id."'";
 		Database::query($sql);
 	}
 
@@ -455,9 +454,10 @@ class Blog {
 	 * @param String $description
 	 * @param String $color
 	 */
-	public static function create_task ($blog_id, $title, $description, $articleDelete, $articleEdit, $commentsDelete, $color) {
+	public static function create_task ($blog_id, $title, $description, $articleDelete, $articleEdit, $commentsDelete, $color)
+	{
 		// Init
-		$tbl_blogs_tasks       = Database::get_course_table(TABLE_BLOGS_TASKS);
+		$tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
 		$tbl_tasks_permissions = Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS);
 
 		$course_id = api_get_course_int_id();
@@ -491,7 +491,7 @@ class Blog {
 			Database::query($sql);
 		}
 
-		if($commentsDelete == 'on') {
+		if ($commentsDelete == 'on') {
 			$sql = "
 				INSERT INTO " . $tbl_tasks_permissions . " (c_id, task_id, tool, action ) VALUES (
 					'" . (int)$course_id . "',
@@ -512,14 +512,13 @@ class Blog {
 	 * @param String $description
 	 * @param String $color
 	 */
-	public static function edit_task($blog_id, $task_id, $title, $description, $articleDelete, $articleEdit, $commentsDelete, $color) {
-		// Init
+	public static function edit_task($blog_id, $task_id, $title, $description, $articleDelete, $articleEdit, $commentsDelete, $color)
+	{
 		$tbl_blogs_tasks       = Database::get_course_table(TABLE_BLOGS_TASKS);
 		$tbl_tasks_permissions = Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS);
 
         $course_id = api_get_course_int_id();
 
-
 		// Create the task
 		$sql = "UPDATE $tbl_blogs_tasks SET
 					title = '".Database::escape_string($title)."',
@@ -530,7 +529,8 @@ class Blog {
 
 		$tool = 'BLOG_' . $blog_id;
 
-		$sql = "DELETE FROM " . $tbl_tasks_permissions . " WHERE c_id = $course_id AND task_id = '" . (int)$task_id."'";
+		$sql = "DELETE FROM " . $tbl_tasks_permissions . "
+				WHERE c_id = $course_id AND task_id = '" . (int)$task_id."'";
 		Database::query($sql);
 
 		if ($articleDelete == 'on') {
@@ -575,7 +575,8 @@ class Blog {
 		$course_id = api_get_course_int_id();
 
 		// Delete posts
-		$sql = "DELETE FROM $tbl_blogs_tasks WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND task_id = '".(int)$task_id."'";
+		$sql = "DELETE FROM $tbl_blogs_tasks
+				WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND task_id = '".(int)$task_id."'";
 		Database::query($sql);
 	}
 
@@ -584,12 +585,14 @@ class Blog {
 	 * @param Integer $blog_id
 	 * @param Integer $assignment_id
 	 */
-	public static function delete_assigned_task ($blog_id, $task_id,$user_id) {
+	public static function delete_assigned_task ($blog_id, $task_id, $user_id)
+	{
 		$tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
         $course_id = api_get_course_int_id();
 
 		// Delete posts
-		$sql = "DELETE FROM $tbl_blogs_tasks_rel_user WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND task_id = '".(int)$task_id."' AND user_id = '".(int)$user_id."'";
+		$sql = "DELETE FROM $tbl_blogs_tasks_rel_user
+				WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND task_id = '".(int)$task_id."' AND user_id = '".(int)$user_id."'";
 		Database::query($sql);
 	}
 
@@ -628,17 +631,12 @@ class Blog {
 					echo '<li><a href="blog.php?action=execute_task&amp;blog_id=' . $mytask['blog_id'] . '&amp;task_id='.stripslashes($mytask['task_id']) . '" title="[Blog: '.stripslashes($mytask['blog_name']) . '] ' . get_lang('ExecuteThisTask') . '">'.stripslashes($mytask['title']) . '</a></li>';
 				}
 				echo '<ul>';
-			}
-			else
-			{
+			} else {
 				echo get_lang('NoTasks');
 			}
-		}
-		else
-		{
+		} else {
 			echo get_lang('NoTasks');
 		}
-
 	}
 
 	/**
@@ -646,14 +644,16 @@ class Blog {
 	 * @author Toon Keppens
 	 * @param Integer $blog_id
 	 */
-	public static function change_blog_visibility ($blog_id) {
+	public static function change_blog_visibility($blog_id)
+	{
 		// Init
 		$tbl_blogs = Database::get_course_table(TABLE_BLOGS);
 		$tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
 		$course_id = api_get_course_int_id();
 
 		// Get blog properties
-		$sql = "SELECT blog_name, visibility FROM $tbl_blogs WHERE c_id = $course_id AND blog_id='".(int)$blog_id."'";
+		$sql = "SELECT blog_name, visibility FROM $tbl_blogs
+				WHERE c_id = $course_id AND blog_id='".(int)$blog_id."'";
 		$result = Database::query($sql);
 		$blog = Database::fetch_array($result);
 		$visibility = $blog['visibility'];
@@ -672,11 +672,11 @@ class Blog {
 		{
 			// Change visibility state, add to course home.
 			$sql = "UPDATE $tbl_blogs SET visibility = '1' WHERE c_id = $course_id AND blog_id ='".(int)$blog_id."' LIMIT 1";
-			$result = Database::query($sql);
+			Database::query($sql);
 
 			$sql = "INSERT INTO $tbl_tool (c_id, name, link, image, visibility, admin, address, added_tool, target )
 					VALUES ($course_id, '".Database::escape_string($title)."', 'blog/blog.php?blog_id=".(int)$blog_id."', 'blog.gif', '1', '0', 'pastillegris.gif', '0', '_self')";
-			$result = Database::query($sql);
+			Database::query($sql);
 		}
 	}
 
@@ -720,8 +720,6 @@ class Blog {
 				$blog_post_date = api_convert_and_format_date($blog_post['date_creation'], null, date_default_timezone_get());
 
 				// Create an introduction text (but keep FULL sentences)
-
-				$introduction_text = "";
 				$words = 0;
 				$blog_post_text_cut = cut($blog_post_text, $limit) ;
 				$words = strlen($blog_post_text);
@@ -742,8 +740,7 @@ class Blog {
 				echo '<div class="blogpost_introduction" id="blogpost_introduction_'.$blog_post_id.'">' . $introduction_text.$readMoreLink.'</div>';
 				echo '<div class="blogpost_text" id="blogpost_text_' . $blog_post_id . '" style="display: none">' . $blog_post_text . '</div>';
 
-
-				$file_name_array=get_blog_attachment($blog_id,$blog_post_id,0);
+				$file_name_array = get_blog_attachment($blog_id,$blog_post_id,0);
 
 				if (!empty($file_name_array)) {
 					echo '<br /><br />';
@@ -1107,24 +1104,26 @@ class Blog {
 	 *
 	 * @param Integer $blog_id
 	 */
-	public static function display_form_new_post ($blog_id)
+	public static function display_form_new_post($blog_id)
 	{
 		if (api_is_allowed('BLOG_' . $blog_id, 'article_add')) {
 			$form = new FormValidator(
 				'add_post',
 				'post',
-				api_get_path(WEB_CODE_PATH)."blog/blog.php?action=new_post&blog_id=" . $blog_id . "&" . api_get_cidreq()
+				api_get_path(WEB_CODE_PATH)."blog/blog.php?action=new_post&blog_id=" . $blog_id . "&" . api_get_cidreq(),
+				null,
+				array('enctype' => 'multipart/form-data')
 			);
 			$form->addHidden('post_title_edited', 'false');
-			$form->add_header(get_lang('NewPost'));
-			$form->add_textfield('post_title', get_lang('Title'));
+			$form->addHeader(get_lang('NewPost'));
+			$form->add_textfield('title', get_lang('Title'));
 			$config = array();
 			if (!api_is_allowed_to_edit()) {
 				$config['ToolbarSet'] = 'ProjectStudent';
 			} else {
 				$config['ToolbarSet'] = 'Project';
 			}
-			$form->add_html_editor('post_full_text', get_lang('Content'), false, false, $config);
+			$form->add_html_editor('full_text', get_lang('Content'), false, false, $config);
 			$form->add_file('user_upload', get_lang('AddAnAttachment'));
 			$form->add_textarea('post_file_comment', get_lang('FileComment'));
 			$form->addHidden('new_post_submit', 'true');
@@ -1142,16 +1141,16 @@ class Blog {
 	 *
 	 * @param Integer $blog_id
 	 */
-	public static function display_form_edit_post ($blog_id, $post_id)
+	public static function display_form_edit_post($blog_id, $post_id)
 	{
-		// Init
 		$tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
 		$tbl_users = Database::get_main_table(TABLE_MAIN_USER);
 
 		$course_id = api_get_course_int_id();
 
 		// Get posts and author
-		$sql = "SELECT post.*, user.lastname, user.firstname FROM $tbl_blogs_posts post
+		$sql = "SELECT post.*, user.lastname, user.firstname
+				FROM $tbl_blogs_posts post
 				INNER JOIN $tbl_users user ON post.author_id = user.user_id
 				WHERE
 				post.c_id 			= $course_id AND
@@ -1161,48 +1160,30 @@ class Blog {
 		$result = Database::query($sql);
 		$blog_post = Database::fetch_array($result);
 
-		// Prepare data
-		$blog_post_text = stripslashes($blog_post['full_text']);
-
-		echo '<form name="edit_post" method="post" action="blog.php?action=edit_post&post_id=' . Security::remove_XSS($_GET['post_id']) . '&blog_id=' . Security::remove_XSS($blog_id) . '&article_id='.Security::remove_XSS($_GET['article_id']).'&task_id='.Security::remove_XSS($_GET['task_id']).'">';
+		// Form
 
-		// form title
-		echo '<legend>' . get_lang('EditPost') . '</legend>';
-
-		// article title
-		echo '<div><span class="form_required">*</span>' . get_lang('Title') . ': <input name="post_title" id="post_title" type="text" size="60" value="'.stripslashes($blog_post['title']) . '" /><br /></div>';
+		$form = new FormValidator(
+			'edit_post',
+			'post',
+			api_get_path(WEB_CODE_PATH).'blog/blog.php?action=edit_post&post_id=' . intval($_GET['post_id']) . '&blog_id=' . intval($blog_id) . '&article_id='.intval($_GET['article_id']).'&task_id='.intval($_GET['task_id'])
+		);
 
-		// article text
-		//$oFCKeditor = new FCKeditor('post_full_text') ;
-        $oFCKeditor = new CKeditor();
+		$form->addHeader(get_lang('EditPost'));
+		$form->add_textfield('title', get_lang('Title'));
 
-		$oFCKeditor->Width		= '100%';
-		$oFCKeditor->Height		= '200';
-
-		if(!api_is_allowed_to_edit()) {
-			$oFCKeditor->ToolbarSet = 'Project_Student';
+		if (!api_is_allowed_to_edit()) {
+			$config['ToolbarSet'] = 'ProjectStudent';
 		} else {
-			$oFCKeditor->ToolbarSet = 'Project';
+			$config['ToolbarSet'] = 'Project';
 		}
-		$oFCKeditor->Value		= isset($_POST['post_full_text'])?stripslashes($_POST['post_full_text']):$blog_post_text;
-		echo '<div class="controls">';
-		//echo $oFCKeditor->Create();
-        $oFCKeditor->editor('post_full_text', $oFCKeditor->Value);
-		echo '</div>';
-
-		// submit
-		echo '	<div class="control-group">
-
-					<div class="controls">
-							 <input type="hidden" name="action" value="" />
-							 <input type="hidden" name="edit_post_submit" value="true" />
-							 <input type="hidden" name="post_id" value="' . (int)$_GET['post_id'] . '" />
-							 <button class="save" type="submit" name="Submit">' . get_lang('Save') . '</button>
-					</div>
-				</div>';
-
-
-		echo '</form>';
+		$form->add_html_editor('full_text', get_lang('Content'), false, false, $config);
+
+		$form->addHidden('action', '');
+		$form->addHidden('edit_post_submit', 'true');
+		$form->addHidden('post_id', intval($_GET['post_id']));
+		$form->addButton('save', get_lang('Save'));
+		$form->setDefaults($blog_post);
+		$form->display();
 	}
 
 	/**
@@ -2221,75 +2202,45 @@ class Blog {
 	 *
 	 * @param Integer $blog_id
 	 */
-	public static function display_new_comment_form ($blog_id, $post_id, $title) {
-		echo '<form name="add_post" enctype="multipart/form-data" method="post" action="blog.php?action=view_post&amp;blog_id=' . intval($blog_id) . '&amp;post_id=' . intval($post_id) . '">';
-
-		// form title
-		echo '<legend>';
-		echo (isset($_GET['task_id']) ? get_lang('ExecuteThisTask') : get_lang('AddNewComment'));
-		echo '</legend>';
-
-		// comment title
-		echo '<div><span class="form_required">*</span>' . get_lang('Title') . ': <input name="comment_title" id="comment_title" type="text" size="60" value="Re: '.stripslashes($title) . '" /></div><br />';
-
-		// comment text
-		//$oFCKeditor = new FCKeditor('comment_text') ;
-        $oFCKeditor = new CKeditor();
-		$oFCKeditor->Width		= '100%';
-		$oFCKeditor->Height		= '200';
-		if(!api_is_allowed_to_edit())
-		{
-			$oFCKeditor->ToolbarSet = 'Project_Comment_Student';
+	public static function display_new_comment_form($blog_id, $post_id, $title)
+	{
+		$form = new FormValidator(
+			'add_post',
+			'post',
+			api_get_path(WEB_CODE_PATH)."blog/blog.php?action=view_post&blog_id=" . intval($blog_id)  . "&post_id=".intval($post_id)."&".api_get_cidreq(),
+			null,
+			array('enctype' => 'multipart/form-data')
+		);
+
+		$header = get_lang('AddNewComment');
+		if (isset($_GET['task_id'])) {
+			$header = get_lang('ExecuteThisTask');
 		}
-		else
-		{
-			$oFCKeditor->ToolbarSet = 'Project_Comment';
+		$form->addHeader($header);
+		$form->add_textfield('title', get_lang('Title'));
+
+		$config = array();
+		if (!api_is_allowed_to_edit()) {
+			$config['ToolbarSet'] = 'ProjectComment';
+		} else {
+			$config['ToolbarSet'] = 'ProjectCommentStudent';
 		}
-		$oFCKeditor->Value		= isset($_POST['comment_text'])?stripslashes($_POST['comment_text']):'';
-		echo '<div class="controls">';
-		//echo $oFCKeditor->Create() ;
-        $oFCKeditor->editor('comment_text');
-		echo '
-				</div>';
+		$form->add_html_editor('comment', get_lang('Comment'), false, false, $config);
+		$form->add_file('user_upload', get_lang('AddAnAttachment'));
 
-		// attachment
-		echo '	<div class="control-group">
-					<label class="control-label">
-						' . get_lang('AddAnAttachment') . '
-					</label>
-					<div class="controls">
-						<input type="file" name="user_upload"/>
-					</div>
-				</div>';
+		$form->add_textarea('post_file_comment', get_lang('FileComment'));
 
-		// attachment comment
-		echo '	<div class="control-group">
-					<label class="control-label">
-						' . get_lang('FileComment') . '
-					</label>
-					<div class="controls">
-						<textarea name="post_file_comment" cols="34" /></textarea>
-					</div>
-				</div>';
+		$form->addHidden('action', null);
+		$form->addHidden('comment_parent_id', 0);
 
-		// attachment comment
-		echo '	<div class="control-group">
-					<div class="controls">
-							 <input type="hidden" name="action" value="" />
-							 <input type="hidden" name="comment_parent_id" id="comment_parent_id" value="0" />';
-									if(isset($_GET['task_id']))
-									{
-										echo ' <input type="hidden" name="new_task_execution_submit" value="true" />';
-										echo ' <input type="hidden" name="task_id" value="' . intval($_GET['task_id']) . '" />';
-									}
-									else
-									{
-										echo ' <input type="hidden" name="new_comment_submit" value="true" />';
-									}
-		echo '					<button class="save" type="submit" name="Submit">' . get_lang('Save') . '</button>
-					</div>
-				</div>';
-		echo '</form>';
+		if (isset($_GET['task_id'])) {
+			$form->addHidden('new_task_execution_submit', 'true');
+			$form->addHidden('task_id', intval($_GET['task_id']));
+		} else {
+			$form->addHidden('new_comment_submit', 'true');
+		}
+		$form->addButton('save', get_lang('Save'));
+		$form->display();
 	}
 
 
@@ -2305,7 +2256,8 @@ class Blog {
 	 *
 	 * @return html code
 	*/
-	public static function display_minimonthcalendar ($month, $year, $blog_id) {
+	public static function display_minimonthcalendar ($month, $year, $blog_id)
+	{
 		// Init
 		global $_user;
 		global $DaysShort;
@@ -2334,17 +2286,21 @@ class Blog {
 
 		//Start the week on monday
 		$startdayofweek = $dayone['wday'] <> 0 ? ($dayone['wday'] - 1) : 6;
-		$backwardsURL = api_get_self()."?blog_id=" . (int)$_GET['blog_id']."&amp;filter=" . Security::remove_XSS($_GET['filter'])."&amp;month=". ($month == 1 ? 12 : $month -1)."&amp;year=". ($month == 1 ? $year -1 : $year);
-		$forewardsURL = api_get_self()."?blog_id=" . (int)$_GET['blog_id']."&amp;filter=" . Security::remove_XSS($_GET['filter'])."&amp;month=". ($month == 12 ? 1 : $month +1)."&amp;year=". ($month == 12 ? $year +1 : $year);
+		$blogId = isset($_GET['blog_id']) ? intval($_GET['blog_id']) : null;
+		$filter = isset($_GET['filter']) ? Security::remove_XSS($_GET['filter']) : null;
+		$backwardsURL = api_get_self()."?blog_id=" . $blogId."&amp;filter=" . $filter."&amp;month=". ($month == 1 ? 12 : $month -1)."&amp;year=". ($month == 1 ? $year -1 : $year);
+		$forewardsURL = api_get_self()."?blog_id=" . $blogId."&amp;filter=" . $filter."&amp;month=". ($month == 12 ? 1 : $month +1)."&amp;year=". ($month == 12 ? $year +1 : $year);
 
 		// Get posts for this month
-		$sql = "SELECT post.*, DAYOFMONTH(date_creation) as post_day, user.lastname, user.firstname FROM $tbl_blogs_posts post
+		$sql = "SELECT post.*, DAYOFMONTH(date_creation) as post_day, user.lastname, user.firstname
+				FROM $tbl_blogs_posts post
 				INNER JOIN $tbl_users user
 				ON post.author_id = user.user_id
-				WHERE 	post.c_id = $course_id AND
-						post.blog_id = '".(int)$blog_id."' AND
-						MONTH(date_creation) = '".(int)$month."' AND
-						YEAR(date_creation) = '".(int)$year."'
+				WHERE
+					post.c_id = $course_id AND
+					post.blog_id = '".(int)$blog_id."' AND
+					MONTH(date_creation) = '".(int)$month."' AND
+					YEAR(date_creation) = '".(int)$year."'
 				ORDER BY date_creation";
 		$result = Database::query($sql);
 
@@ -2461,9 +2417,9 @@ class Blog {
 	 * Blog admin | Display the form to add a new blog.
 	 *
 	 */
-	public static function display_new_blog_form () {
-
-        $form = new FormValidator('add_blog', 'post','blog_admin.php?action=add');
+	public static function display_new_blog_form()
+	{
+        $form = new FormValidator('add_blog', 'post', 'blog_admin.php?action=add');
         $form->addElement('header', get_lang('AddBlog'));
         $form->addElement('text', 'blog_name', get_lang('Title'));
         $form->addElement('textarea', 'blog_subtitle', get_lang('Subtitle'));
@@ -2471,9 +2427,10 @@ class Blog {
         $form->addElement('hidden', 'new_blog_submit', 'true');
         $form->addElement('style_submit_button', null, get_lang('SaveProject'));
 
-        $defaults = array();
-        $defaults['blog_name'] = Security::remove_XSS($_POST['blog_name']);
-        $defaults['blog_subtitle'] = Security::remove_XSS($_POST['blog_subtitle']);
+        $defaults = array(
+			'blog_name' => isset($_POST['blog_name']) ? Security::remove_XSS($_POST['blog_name']) : null,
+        	'blog_subtitle' => isset($_POST['blog_subtitle']) ? Security::remove_XSS($_POST['blog_subtitle']) : null
+		);
         $form->setDefaults($defaults);
         $form->display();
 	}
@@ -2482,11 +2439,13 @@ class Blog {
 	 * Blog admin | Display the form to edit a blog.
 	 *
 	 */
-	public static function display_edit_blog_form ($blog_id) {
+	public static function display_edit_blog_form($blog_id)
+	{
 	    $course_id = api_get_course_int_id();
+		$blog_id= intval($blog_id);
 		$tbl_blogs = Database::get_course_table(TABLE_BLOGS);
 
-		$sql = "SELECT blog_id, blog_name, blog_subtitle FROM $tbl_blogs WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."'";
+		$sql = "SELECT blog_id, blog_name, blog_subtitle FROM $tbl_blogs WHERE c_id = $course_id AND blog_id = '".$blog_id."'";
 		$result = Database::query($sql);
 		$blog = Database::fetch_array($result);
 
@@ -2496,7 +2455,7 @@ class Blog {
 			$blog['blog_subtitle'] 	= Security::remove_XSS($_POST['blog_subtitle']);
 		}
 
-        $form = new FormValidator('edit_blog', 'post','blog_admin.php?action=edit&blog_id='.Security::remove_XSS($_GET['blog_id']));
+        $form = new FormValidator('edit_blog', 'post','blog_admin.php?action=edit&blog_id='.intval($_GET['blog_id']));
         $form->addElement('header', get_lang('EditBlog'));
         $form->addElement('text', 'blog_name', get_lang('Title'));
         $form->addElement('textarea', 'blog_subtitle', get_lang('Subtitle'));
@@ -2527,21 +2486,24 @@ class Blog {
 		$session_id = api_get_session_id();
 		$condition_session = api_get_session_condition($session_id, false);
 
-		$sql = "SELECT blog_name,blog_subtitle,visibility,blog_id FROM $tbl_blogs WHERE c_id = $course_id ORDER BY date_creation DESC";
+		$sql = "SELECT blog_name, blog_subtitle, visibility, blog_id, session_id
+				FROM $tbl_blogs WHERE c_id = $course_id
+				ORDER BY date_creation DESC";
 		$result = Database::query($sql);
+		$list_info = array();
 		if (Database::num_rows($result)) {
 			while ($row_project=Database::fetch_row($result)) {
 				$list_info[]=$row_project;
 			}
 		}
 
-
 		$list_content_blog = array();
 		$list_body_blog = array();
+		$_user = api_get_user_info();
 
 		if (is_array($list_info)) {
-			foreach($list_info as $key => $info_log) {
-				//validacion when belongs to a session
+			foreach ($list_info as $key => $info_log) {
+				// Validation when belongs to a session
 				$session_img = api_get_session_image($info_log[4], $_user['status']);
 
 				$url_start_blog = 'blog.php' ."?". "blog_id=".$info_log[3]. "&amp;".api_get_cidreq();
@@ -2554,19 +2516,18 @@ class Blog {
 
 				$visibility_icon=($info_log[2]==0) ? 'invisible' : 'visible';
 				$visibility_info=($info_log[2]==0) ? 'Visible' : 'Invisible';
-			 	$my_image.='<a href="' .api_get_self(). '?action=edit&amp;blog_id=' . $info_log[3] . '">';
-				$my_image.='<img src="../img/edit.gif" border="0" title="' . get_lang('EditBlog') . '" />';
-				$my_image.="</a>\n";
-				$my_image.='<a href="' .api_get_self(). '?action=delete&amp;blog_id=' . $info_log[3] . '" ';
-				$my_image.='onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset)). '\')) return false;" >';
-				$my_image.='<img src="../img/delete.gif" border="0" title="' . get_lang('DeleteBlog') . '" />';
-				$my_image.="</a>\n";
-				$my_image.='<a href="' .api_get_self(). '?action=visibility&amp;blog_id=' . $info_log[3] . '">';
-				$my_image.='<img src="../img/' . $visibility_icon . '.gif" border="0" title="' . get_lang($visibility_info) . '" />';
-				$my_image.="</a>\n";
+			 	$my_image = '<a href="' .api_get_self(). '?action=edit&amp;blog_id=' . $info_log[3] . '">';
+				$my_image.= '<img src="../img/edit.gif" border="0" title="' . get_lang('EditBlog') . '" />';
+				$my_image.= "</a>\n";
+				$my_image.= '<a href="' .api_get_self(). '?action=delete&amp;blog_id=' . $info_log[3] . '" ';
+				$my_image.= 'onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset)). '\')) return false;" >';
+				$my_image.= '<img src="../img/delete.gif" border="0" title="' . get_lang('DeleteBlog') . '" />';
+				$my_image.= "</a>\n";
+				$my_image.= '<a href="' .api_get_self(). '?action=visibility&amp;blog_id=' . $info_log[3] . '">';
+				$my_image.= '<img src="../img/' . $visibility_icon . '.gif" border="0" title="' . get_lang($visibility_info) . '" />';
+				$my_image.= "</a>\n";
 
 				$list_body_blog[]=$my_image;
-				$my_image='';
 
 				$list_content_blog[]=$list_body_blog;
 				$list_body_blog = array();

+ 3 - 3
main/inc/lib/course_category.lib.php

@@ -101,7 +101,7 @@ function addNode($code, $name, $canHaveCourses, $parent_id)
     $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
     $code = trim(Database::escape_string($code));
     $name = trim(Database::escape_string($name));
-    $parent_id = intval($parent_id);
+    $parent_id = trim(Database::escape_string($parent_id));
     $canHaveCourses = Database::escape_string($canHaveCourses);
     $code = CourseManager::generate_course_code($code);
 
@@ -109,7 +109,6 @@ function addNode($code, $name, $canHaveCourses, $parent_id)
     if (Database::num_rows($result)) {
         return false;
     }
-
     $result = Database::query("SELECT MAX(tree_pos) AS maxTreePos FROM $tbl_category");
     $row = Database::fetch_array($result);
     $tree_pos = $row['maxTreePos'] + 1;
@@ -142,7 +141,8 @@ function updateCategoryChildren($category)
     }
 
     $children_count = compterFils($category, 0) - 1;
-    Database::query("UPDATE $tbl_category SET children_count='$children_count' WHERE code='$category'");
+    $sql = "UPDATE $tbl_category SET children_count='$children_count' WHERE code='$category'";
+    Database::query($sql);
 }
 
 /**

+ 1 - 1
main/inc/lib/document.lib.php

@@ -1446,7 +1446,7 @@ class DocumentManager
     }
 
     /**
-     * Allow to set a specific document as a new template for FCKEditor
+     * Allow to set a specific document as a new template for CKeditor
      * for a particular user in a particular course
      *
      * @param string $title

+ 2 - 0
main/inc/lib/elfinder/templates.php

@@ -1,6 +1,8 @@
 <?php
 /* For licensing terms, see /license.txt */
 
+$language_file = 'document';
+
 require_once '../../global.inc.php';
 
 use Chamilo\CoreBundle\Component\Editor\CkEditor\CkEditor;

+ 1 - 1
main/inc/lib/extra_field.lib.php

@@ -917,7 +917,7 @@ class ExtraField extends Model
                         break;
                     case ExtraField::FIELD_TYPE_DATETIME:
                         $form->addElement(
-                            'datepicker',
+                            'DatePicker',
                             'extra_'.$field_details['field_variable'],
                             $field_details['field_display_text'],
                             array('form_name' => $form_name)

+ 4 - 3
main/inc/lib/formvalidator/FormValidator.class.php

@@ -294,6 +294,7 @@ EOT;
      */
     public function addButton($name, $label, $attributes = array())
     {
+        //$attributes['class'] = isset($attributes['class']) ? $attributes['class'] : 'btn btn-default';
         $this->addElement('button', $name, $label, $attributes);
     }
 
@@ -345,7 +346,7 @@ EOT;
     /**
      * @param string $text
      */
-    public function add_header($text)
+    public function addHeader($text)
     {
         $this->addElement('header', $text);
     }
@@ -409,7 +410,7 @@ EOT;
      */
     function add_datepicker($name, $label)
     {
-        $this->addElement('datepicker', $name, $label, array('form_name' => $this->getAttribute('name')));
+        $this->addElement('DatePicker', $name, $label, array('form_name' => $this->getAttribute('name')));
         $this->_elements[$this->_elementIndex[$name]]->setLocalOption('minYear', 1900); // TODO: Now - 9 years
         $this->addRule($name, get_lang('InvalidDate'), 'date');
     }
@@ -423,7 +424,7 @@ EOT;
      */
     public function add_datepickerdate($name, $label)
     {
-        $this->addElement('datepickerdate', $name, $label, array('form_name' => $this->getAttribute('name')));
+        $this->addElement('DatePickerDate', $name, $label, array('form_name' => $this->getAttribute('name')));
         $this->_elements[$this->_elementIndex[$name]]->setLocalOption('minYear', 1900); // TODO: Now - 9 years
         $this->addRule($name, get_lang('InvalidDate'), 'date');
     }

+ 14 - 9
main/inc/lib/grade_model.lib.php

@@ -10,6 +10,9 @@ class GradeModel extends Model
     public $table;
     public $columns = array('id', 'name', 'description');
 
+    /**
+     * Constructor
+     */
 	public function __construct()
     {
         $this->table =  Database::get_main_table(TABLE_GRADE_MODEL);
@@ -55,14 +58,6 @@ class GradeModel extends Model
      */
     public function return_form($url, $action)
     {
-        /*
-        $oFCKeditor = new FCKeditor('description') ;
-        $oFCKeditor->ToolbarSet = 'grade_model';
-        $oFCKeditor->Width		= '100%';
-        $oFCKeditor->Height		= '200';
-        $oFCKeditor->Value		= '';
-        $oFCKeditor->CreateHtml();
-        */
         $form = new FormValidator('grades', 'post', $url);
 
         // Setting the form elements
@@ -77,7 +72,17 @@ class GradeModel extends Model
         $form->addElement('hidden', 'id', $id);
 
         $form->addElement('text', 'name', get_lang('Name'), array('size' => '70'));
-        $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));
+        $form->add_html_editor(
+            'description',
+            get_lang('Description'),
+            false,
+            false,
+            array(
+                'ToolbarSet' => 'careers',
+                'Width' => '100%',
+                'Height' => '250'
+            )
+        );
 
         $form->addElement('label', get_lang('Components'));
 

+ 135 - 0
main/inc/lib/javascript/ckeditor/plugins/glossary/fck_glossary_automatic.js

@@ -0,0 +1,135 @@
+/**
+* Makes posible to load glossary items from the Glossary Tool
+*   This library will be loaded in:
+*
+*    document/showinframes.php
+*    newscorm/lp_view.php
+*    newscorm/scorm_api.php
+*    
+*/
+
+/*$(document).ready(function() {
+    $(window).load(function() {
+	*/	
+    my_protocol = location.protocol;
+    my_pathname=location.pathname;
+    work_path = my_pathname.substr(0,my_pathname.indexOf('/courses/'));
+
+    $.ajax({
+        contentType: "application/x-www-form-urlencoded",
+        beforeSend: function(content_object) {},
+        type: "POST",
+        url: my_protocol+"//"+location.host+work_path+"/main/glossary/glossary_ajax_request.php",
+        data: "glossary_data=true",
+        success: function(datas) {
+            if (datas.length==0) {
+                return false;
+            }
+            // glossary terms 
+            data_terms=datas.split("[|.|_|.|-|.|]");
+            var complex_array = new Array();
+            var cp_complex_array = new Array();
+            for(i=0;i<data_terms.length;i++) {
+                specific_terms=data_terms[i].split("__|__|");
+                var real_term = specific_terms[1]; // glossary term 
+                var real_code = specific_terms[0]; // glossary id
+                complex_array[real_code] = real_term;
+                cp_complex_array[real_code] = real_term;
+            }
+
+            complex_array.reverse();
+
+            for (var my_index in complex_array) {
+                n = complex_array[my_index];
+                if (n == null) {
+                    n = '';
+                } else {
+                    for (var cp_my_index in cp_complex_array) {
+                        cp_data = cp_complex_array[cp_my_index];
+                        if (cp_data == null) {
+                            cp_data = '';
+                        } else {
+                            if (cp_data == n) {
+                                my_index = cp_my_index;
+                            }
+                        }
+                    }
+                    //alert(n + ' ' + my_index);
+                    $('body').removeHighlight().highlight(n,my_index) 
+                }                   
+            }
+
+            var complex_array = new Array();
+
+            //mouse over event
+            //$("body .glossary-ajax").mouseover(function(){
+            //
+            //mouse on click
+            $("body").on("click", ".glossary-ajax", function(e) {
+                random_id = Math.round(Math.random()*100);
+                
+                //div_show_id = "div_show_id"+random_id;
+                //div_content_id = "div_content_id"+random_id;
+                div_show_id = "div_show_id";
+                div_content_id = "div_content_id";
+                
+                $(this).append("<div id="+div_show_id+"><div id="+div_content_id+">&nbsp;</div></div>");
+                
+                //$("div#"+div_show_id).attr("style","z-index:99;display:inline;float:left;position:absolute;background-color:#F2F2F2;border-bottom: 1px solid #2E2E2E;border-right: 1px solid #2E2E2E;border-left: 1px solid #2E2E2E;border-top: 1px solid #2E2E2E;color:#305582;margin-left:5px;margin-right:5px;");
+                //$("div#"+div_content_id).attr("style","z-index:99;background-color:#F2F2F2;color:#0B3861;margin-left:8px;margin-right:8px;margin-top:5px;margin-bottom:5px;");
+                
+                var $target = $(this);                
+                
+                $("#"+div_show_id).dialog("destroy");
+                $("#"+div_show_id).dialog({
+                    autoOpen: false,
+                    width: 600,
+                    height: 200,
+                    position:  { my: 'left top', at: 'right top', of: $target },
+                    close: function(){
+                         $("div#"+div_show_id).remove();
+                         $("div#"+div_content_id).remove();
+                    }
+                });
+                
+                notebook_id = $(this).attr("name");
+                data_notebook = notebook_id.split("link");
+                my_glossary_id = data_notebook[1];
+                
+                $.ajax({
+                    contentType: "application/x-www-form-urlencoded",
+                    beforeSend: function(content_object) {
+                        $("div#"+div_content_id).html("<img src='../../../../../../../main/inc/lib/javascript/indicator.gif' />");
+                    },
+                    type: "POST",
+                    url: "../../../../../../../main/glossary/glossary_ajax_request.php",
+                    data: "glossary_id="+my_glossary_id,
+                    success: function(datas) {
+                        $("div#"+div_content_id).html(datas);
+                        $("#"+div_show_id).dialog("open");
+                    }
+                });
+                
+            });
+
+            //mouse out event
+            /*$("body .glossary-ajax").mouseout(function(){
+                var current_element = $(this);
+                div_show_id=current_element.find("div").attr("id");
+                $("div#"+div_show_id).remove();
+            });*/
+            
+            //mouse click
+            
+            /*$("body").on("click", ".glossary-ajax", function(){
+                var current_element = $(this);
+                div_show_id=current_element.find("div").attr("id");
+                $("div#"+div_show_id).remove();
+            });*/
+            
+        }
+
+    });
+/*			
+        });
+});*/

+ 73 - 0
main/inc/lib/javascript/ckeditor/plugins/glossary/fck_glossary_manual.js

@@ -0,0 +1,73 @@
+/**
+
+Makes posible to load glossary items from the Glossary Tool
+This library will be loaded in:
+
+document/showinframes.php
+newscorm/lp_view.php
+newscorm/scorm_api.php
+
+ */
+//$(document).ready(function() {
+//    $(window).load(function () {
+    my_protocol = location.protocol;
+    my_pathname=location.pathname;
+    work_path = my_pathname.substr(0,my_pathname.indexOf('/courses/'));      
+
+    //$("body .glossary").mouseover(function(){
+    $("body").on("click", ".glossary", function() {
+        is_glossary_name = $(this).html();	        
+        random_id = Math.round(Math.random()*100);
+
+        /*div_show_id="div_show_id"+random_id;
+                div_content_id="div_content_id"+random_id;*/
+
+        div_show_id="div_show_id";
+        div_content_id="div_content_id";
+        
+        $(this).append("<div id="+div_show_id+" ><div id="+div_content_id+">&nbsp;</div></div>");
+
+        var $target = $(this);             
+
+        $("#"+div_show_id).dialog("destroy");
+        $("#"+div_show_id).dialog({
+            autoOpen: false,
+            width: 600,
+            height: 200,
+            position:  { my: 'left top', at: 'right top', of: $target },
+            close: function(){
+                $("div#"+div_show_id).remove();
+                $("div#"+div_content_id).remove();
+            }
+        });
+
+
+        
+        /* $("div#"+div_show_id).attr("style","z-index:99;display:inline;float:left;position:absolute;background-color:#F2F2F2;border-bottom: 1px solid #2E2E2E;border-right: 1px solid #2E2E2E;border-left: 1px solid #2E2E2E;border-top: 1px solid #2E2E2E;color:#305582;margin-left:5px;margin-right:5px;");
+                 $("div#"+div_content_id).attr("style","z-index:99;background-color:#F2F2F2;color:#0B3861;margin-left:8px;margin-right:8px;margin-top:5px;margin-bottom:5px;");*/
+
+        $.ajax({
+            contentType: "application/x-www-form-urlencoded",
+            beforeSend: function(result) {
+                $("div#"+div_content_id).html("<img src='../../../../../../../main/inc/lib/javascript/indicator.gif' />"); 
+            },        
+            type: "POST",
+            url: "../../../../../../../main/glossary/glossary_ajax_request.php",
+            data: "glossary_name="+is_glossary_name,
+            success: function(data) {
+                $("div#"+div_content_id).html(data);
+                $("#"+div_show_id).dialog("open");
+            }
+        });
+    });
+        
+/*
+	    $("body .glossary").mouseout(function(){
+	        current_element=$(this);
+	        div_show_id=current_element.find("div").attr("id");
+	        $("div#"+div_show_id).remove();
+	    });
+*/
+		
+//    });
+//});

+ 7 - 8
main/inc/lib/pear/HTML/Common.php

@@ -77,7 +77,7 @@ class HTML_Common
      * @param    int     $tabOffset      Indent offset in tabs
      * @access   public
      */
-    function HTML_Common($attributes = null, $tabOffset = 0)
+    public function HTML_Common($attributes = null, $tabOffset = 0)
     {
         $this->setAttributes($attributes);
         $this->setTabOffset($tabOffset);
@@ -134,7 +134,7 @@ class HTML_Common
      * @return   string
      * @access   private
      */
-    function _getAttrString($attributes)
+    public function _getAttrString($attributes)
     {
         $strAttr = '';
 
@@ -143,15 +143,15 @@ class HTML_Common
             foreach ($attributes as $key => $value) {
             	// Modified by Ivan Tcholakov, 16-MAR-2010
                 $value = @htmlspecialchars($value, ENT_COMPAT, $charset);
-                $strAttr .= ' ' . $key . '="' . $value. '"';
+                $strAttr .= ' ' . $key . '= "' . $value. '"';
             }
         }
         return $strAttr;
-    } // end func _getAttrString
+    }
 
     /**
-     * Returns a valid atrributes array from either a string or array
-     * @param    mixed   $attributes     Either a typical HTML attribute string or an associative array
+     * Returns a valid attributes array from either a string or array
+     * @param    mixed   $attributes  Either a typical HTML attribute string or an associative array
      * @access   private
      * @return   array
      */
@@ -469,5 +469,4 @@ class HTML_Common
         }
         return $charset;
     } // end func charset
-} // end class HTML_Common
-?>
+}

+ 43 - 16
main/inc/lib/promotion.lib.php

@@ -12,6 +12,9 @@ class Promotion extends Model
     public $table;
     public $columns = array('id','name','description','career_id','status','created_at','updated_at');
 
+    /**
+     * Constructor
+     */
 	public function __construct()
     {
         $this->table =  Database::get_main_table(TABLE_PROMOTION);
@@ -57,9 +60,10 @@ class Promotion extends Model
                             $val = (int)$career_id;
                         }
                         $new[$key] = $val;
+                        break;
                     default:
                         $new[$key] = $val;
-                    break;
+                        break;
                 }
             }
 
@@ -117,7 +121,8 @@ class Promotion extends Model
      * Displays the title + grid
      * @return  string  html code
      */
-	function display() {
+	public function display()
+    {
 		// action links
 		echo '<div class="actions" style="margin-bottom:20px">';
         echo '<a href="career_dashboard.php">'.Display::return_icon('back.png',get_lang('Back'),'','32').'</a>';
@@ -142,24 +147,15 @@ class Promotion extends Model
         }
     }
 
-
     /**
      * Returns a Form validator Obj
      * @todo the form should be auto generated
      * @param   string  url
      * @param   string  header name
-     * @return  obj     form validator obj
+     * @return  FormValidator
      */
-
-    function return_form($url, $action = 'add')
+    public function return_form($url, $action = 'add')
     {
-		/*$oFCKeditor = new FCKeditor('description') ;
-		$oFCKeditor->ToolbarSet = 'careers';
-		$oFCKeditor->Width		= '100%';
-		$oFCKeditor->Height		= '200';
-		$oFCKeditor->Value		= '';
-		$oFCKeditor->CreateHtml();*/
-
 		$form = new FormValidator('promotion', 'post', $url);
         // Setting the form elements
         $header = get_lang('Add');
@@ -171,7 +167,17 @@ class Promotion extends Model
         $form->addElement('header', '', $header);
         $form->addElement('hidden', 'id', $id);
         $form->addElement('text', 'name', get_lang('Name'), array('size' => '70','id' => 'name'));
-        $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));
+        $form->add_html_editor(
+            'description',
+            get_lang('Description'),
+            false,
+            false,
+            array(
+                'ToolbarSet' => 'careers',
+                'Width' => '100%',
+                'Height' => '250'
+            )
+        );
         $career = new Career();
         $careers = $career->get_all();
         $career_list = array();
@@ -207,20 +213,41 @@ class Promotion extends Model
         return $form;
     }
 
+    /**
+     * @param $params
+     * @param bool $show_query
+     * @return bool
+     */
     public function save($params, $show_query = false)
     {
     	$id = parent::save($params, $show_query);
     	if (!empty($id)) {
-    		Event::addEvent(LOG_PROMOTION_CREATE, LOG_PROMOTION_ID, $id, api_get_utc_datetime(), api_get_user_id());
+            Event::addEvent(
+                LOG_PROMOTION_CREATE,
+                LOG_PROMOTION_ID,
+                $id,
+                api_get_utc_datetime(),
+                api_get_user_id()
+            );
     	}
     	return $id;
     }
 
+    /**
+     * @param $id
+     * @return bool
+     */
     public function delete($id)
     {
     	if (parent::delete($id)) {
            SessionManager::clear_session_ref_promotion($id);
-    	   Event::addEvent(LOG_PROMOTION_DELETE, LOG_PROMOTION_ID, $id, api_get_utc_datetime(), api_get_user_id());
+            Event::addEvent(
+                LOG_PROMOTION_DELETE,
+                LOG_PROMOTION_ID,
+                $id,
+                api_get_utc_datetime(),
+                api_get_user_id()
+            );
         } else {
             return false;
         }

+ 24 - 15
main/inc/lib/sessionmanager.lib.php

@@ -66,6 +66,7 @@ class SessionManager
      * @param string $duration
      * @param string $description Optional. The session description
      * @param int $showDescription Optional. Whether show the session description
+     * @param array $extrafields 
      * @todo use an array to replace all this parameters or use the model.lib.php ...
      * @return mixed       Session ID on success, error message otherwise
      * */
@@ -84,7 +85,8 @@ class SessionManager
         $fix_name = false,
         $duration = null,
         $description = null,
-        $showDescription = 0
+        $showDescription = 0,
+        $extraFields = array()
     ) {
         global $_configuration;
 
@@ -2110,7 +2112,7 @@ class SessionManager
 
         if ($nb_affected > 0) {
             // Update number of courses in the session
-            $sql = "UPDATE $tbl_session SET nbr_courses= nbr_courses + $nb_affected WHERE id='$session_id' ";
+            $sql = "UPDATE $tbl_session SET nbr_courses= nbr_courses - $nb_affected WHERE id='$session_id' ";
             Database::query($sql);
             return true;
         } else {
@@ -5222,13 +5224,15 @@ class SessionManager
      * @param int $userId The user id
      * @return boolean Whether is subscribed
      */
-    public static function isUserSusbcribedAsStudent($sessionId, $userId)
+    public static function isUserSubscribedAsStudent($sessionId, $userId)
     {
         $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
 
         $sessionId = intval($sessionId);
         $userId = intval($userId);
 
+        // COUNT(1) actually returns the number of rows from the table (as if
+        // counting the results from the first column)
         $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable "
             . "WHERE id_session = $sessionId AND id_user = $userId AND relation_type = 0";
 
@@ -5434,16 +5438,15 @@ class SessionManager
     }
 
     /**
-     * Returns list of a few data from session (name, short description, start date, end date)
-     * And the next extra fields
-     * short_description, mode, human_text_duration, vacancies, brochure, target, schedule
-     * from Session category Id.
-     * @param int $categoryId
-     * @param string $target
-     * @param array $fieldsArray, array of session extra fields
+     * Returns list of a few data from session (name, short description, start 
+     * date, end date) and the given extra fields if defined based on a 
+     * session category Id.
+     * @param int $categoryId The internal ID of the session category
+     * @param string $target Value to search for in the session field values
+     * @param array $extraFields A list of fields to be scanned and returned
      * @return mixed
      */
-    public static function getBriefSessionListAndExtraByCategory($categoryId, $target, $fieldsArray) {
+    public static function getShortSessionListAndExtraByCategory($categoryId, $target, $extraFields = null) {
         // Init variables
         $categoryId = (int) $categoryId;
         $sessionList = array();
@@ -5455,6 +5458,10 @@ class SessionManager
             $sfvTable = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
             // Join session field and session field values tables
             $joinTable = $sfTable . ' sf INNER JOIN ' . $sfvTable . ' sfv ON sf.id = sfv.field_id';
+            $fieldsArray = array();
+            foreach ($extraFields as $field) {
+                $fieldsArray[] = Database::escape_string($field);
+            }
             // Get the session list from session category and target
             $sessionList = Database::select(
                 'id, name, date_start, date_end',
@@ -5485,15 +5492,17 @@ class SessionManager
             }
             // Get session fields
             $extraField = new ExtraField('session');
-            $fieldList = $extraField->get_all(array($whereFieldVariables => $fieldsArray));
+            $questionMarks = substr(str_repeat('?, ', count($fieldsArray)), 0, -2);
+            $fieldsList = $extraField->get_all(array(
+                'field_variable IN ( ' . $questionMarks . ' )' => $fieldsArray
+            ));
             // Index session fields
-            $fields = array();
-            foreach ($fieldList as $field) {
+            foreach ($fieldsList as $field) {
                 $fields[$field['id']] = $field['field_variable'];
             }
             // Get session field values
             $extra = new ExtraFieldValue('session');
-            $sessionFieldValueList = $extra->get_all(array($whereFieldIds => array_keys($fields)));
+            $sessionFieldValueList = $extra->get_all(array('field_id IN ( ' . $questionMarks . ' )' => array_keys($fields)));
             // Add session fields values to session list
             foreach ($sessionList as $id => &$session) {
                 foreach ($sessionFieldValueList as $sessionFieldValue) {

+ 300 - 6
main/inc/lib/text.lib.php

@@ -411,15 +411,309 @@ function domesticate($input) {
  * have it require something like xxxx@yyyy.zzzz or such. We'll see.
  */
 
-function make_clickable($string) {
-    // TODO: eregi_replace() is deprecated as of PHP 5.3
-    if (!stristr($string, ' src=') && !stristr($string, ' href=')) {
-        $string = eregi_replace("(https?|ftp)://([a-z0-9#?/&=._+:~%-]+)", "<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>", $string);
-        $string = eregi_replace("([a-z0-9_.-]+@[a-z0-9.-]+)", "<a href=\"mailto:\\1\">\\1</a>", $string);
+/**
+ * Callback to convert URI match to HTML A element.
+ *
+ * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
+ * make_clickable()}.
+ *
+ * @since Wordpress 2.3.2
+ * @access private
+ *
+ * @param array $matches Single Regex Match.
+ * @return string HTML A element with URI address.
+ */
+function _make_url_clickable_cb($matches) {
+    $url = $matches[2];
+
+    if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
+        // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
+        // Then we can let the parenthesis balancer do its thing below.
+        $url .= $matches[3];
+        $suffix = '';
+    } else {
+        $suffix = $matches[3];
+    }
+
+    // Include parentheses in the URL only if paired
+    while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
+        $suffix = strrchr( $url, ')' ) . $suffix;
+        $url = substr( $url, 0, strrpos( $url, ')' ) );
+    }
+
+    $url = esc_url($url);
+    if ( empty($url) )
+        return $matches[0];
+
+    return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
+}
+
+/**
+ * Checks and cleans a URL.
+ *
+ * A number of characters are removed from the URL. If the URL is for displaying
+ * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
+ * is applied to the returned cleaned URL.
+ *
+ * @since wordpress 2.8.0
+ * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
+ *		via $protocols or the common ones set in the function.
+ *
+ * @param string $url The URL to be cleaned.
+ * @param array $protocols Optional. An array of acceptable protocols.
+ *		Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
+ * @param string $_context Private. Use esc_url_raw() for database usage.
+ * @return string The cleaned $url after the 'clean_url' filter is applied.
+ */
+function esc_url( $url, $protocols = null, $_context = 'display' ) {
+    //$original_url = $url;
+
+    if ( '' == $url )
+        return $url;
+    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
+    $strip = array('%0d', '%0a', '%0D', '%0A');
+    $url = _deep_replace($strip, $url);
+    $url = str_replace(';//', '://', $url);
+    /* If the URL doesn't appear to contain a scheme, we
+     * presume it needs http:// appended (unless a relative
+     * link starting with /, # or ? or a php file).
+     */
+    if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
+        ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
+        $url = 'http://' . $url;
+
+    return Security::remove_XSS($url);
+
+    /*// Replace ampersands and single quotes only when displaying.
+    if ( 'display' == $_context ) {
+        $url = wp_kses_normalize_entities( $url );
+        $url = str_replace( '&amp;', '&#038;', $url );
+        $url = str_replace( "'", '&#039;', $url );
+    }
+
+    if ( '/' === $url[0] ) {
+        $good_protocol_url = $url;
+    } else {
+        if ( ! is_array( $protocols ) )
+            $protocols = wp_allowed_protocols();
+        $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
+        if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
+            return '';
+    }
+
+    /**
+     * Filter a string cleaned and escaped for output as a URL.
+     *
+     * @since 2.3.0
+     *
+     * @param string $good_protocol_url The cleaned URL to be returned.
+     * @param string $original_url      The URL prior to cleaning.
+     * @param string $_context          If 'display', replace ampersands and single quotes only.
+     */
+    //return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );98
+}
+
+
+/**
+ * Perform a deep string replace operation to ensure the values in $search are no longer present
+ *
+ * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
+ * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
+ * str_replace would return
+ *
+ * @since wordpress  2.8.1
+ * @access private
+ *
+ * @param string|array $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
+ * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
+ * @return string The string with the replaced svalues.
+ */
+function _deep_replace( $search, $subject ) {
+    $subject = (string) $subject;
+
+    $count = 1;
+    while ( $count ) {
+        $subject = str_replace( $search, '', $subject, $count );
+    }
+
+    return $subject;
+}
+
+
+/**
+ * Callback to convert URL match to HTML A element.
+ *
+ * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
+ * make_clickable()}.
+ *
+ * @since wordpress  2.3.2
+ * @access private
+ *
+ * @param array $matches Single Regex Match.
+ * @return string HTML A element with URL address.
+ */
+function _make_web_ftp_clickable_cb($matches) {
+    $ret = '';
+    $dest = $matches[2];
+    $dest = 'http://' . $dest;
+    $dest = esc_url($dest);
+    if ( empty($dest) )
+        return $matches[0];
+
+    // removed trailing [.,;:)] from URL
+    if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
+        $ret = substr($dest, -1);
+        $dest = substr($dest, 0, strlen($dest)-1);
+    }
+    return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
+}
+
+/**
+ * Callback to convert email address match to HTML A element.
+ *
+ * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
+ * make_clickable()}.
+ *
+ * @since wordpress  2.3.2
+ * @access private
+ *
+ * @param array $matches Single Regex Match.
+ * @return string HTML A element with email address.
+ */
+function _make_email_clickable_cb($matches) {
+    $email = $matches[2] . '@' . $matches[3];
+    return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
+}
+
+/**
+ * Convert plaintext URI to HTML links.
+ *
+ * Converts URI, www and ftp, and email addresses. Finishes by fixing links
+ * within links.
+ *
+ * @since wordpress  0.71
+ *
+ * @param string $text Content to convert URIs.
+ * @return string Content with converted URIs.
+ */
+function make_clickable( $text ) {
+    $r = '';
+    $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
+    $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
+    foreach ( $textarr as $piece ) {
+
+        if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) )
+            $nested_code_pre++;
+        elseif ( ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) ) && $nested_code_pre )
+            $nested_code_pre--;
+
+        if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
+            $r .= $piece;
+            continue;
+        }
+
+        // Long strings might contain expensive edge cases ...
+        if ( 10000 < strlen( $piece ) ) {
+            // ... break it up
+            foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
+                if ( 2101 < strlen( $chunk ) ) {
+                    $r .= $chunk; // Too big, no whitespace: bail.
+                } else {
+                    $r .= make_clickable( $chunk );
+                }
+            }
+        } else {
+            $ret = " $piece "; // Pad with whitespace to simplify the regexes
+
+            $url_clickable = '~
+				([\\s(<.,;:!?])                                        # 1: Leading whitespace, or punctuation
+				(                                                      # 2: URL
+					[\\w]{1,20}+://                                # Scheme and hier-part prefix
+					(?=\S{1,2000}\s)                               # Limit to URLs less than about 2000 characters long
+					[\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+         # Non-punctuation URL character
+					(?:                                            # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
+						[\'.,;:!?)]                            # Punctuation URL character
+						[\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
+					)*
+				)
+				(\)?)                                                  # 3: Trailing closing parenthesis (for parethesis balancing post processing)
+			~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
+            // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
+
+            $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
+
+            $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
+            $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
+
+            $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
+            $r .= $ret;
+        }
     }
-    return $string;
+
+    // Cleanup of accidental links within links
+    $r = preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
+    return $r;
 }
 
+/**
+ * Breaks a string into chunks by splitting at whitespace characters.
+ * The length of each returned chunk is as close to the specified length goal as possible,
+ * with the caveat that each chunk includes its trailing delimiter.
+ * Chunks longer than the goal are guaranteed to not have any inner whitespace.
+ *
+ * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
+ *
+ * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
+ *
+ * <code>
+ * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234   890 123456789 1234567890a    45678   1 3 5 7 90 ", 10 ) ==
+ * array (
+ *   0 => '1234 67890 ',  // 11 characters: Perfect split
+ *   1 => '1234 ',        //  5 characters: '1234 67890a' was too long
+ *   2 => '67890a cd ',   // 10 characters: '67890a cd 1234' was too long
+ *   3 => '1234   890 ',  // 11 characters: Perfect split
+ *   4 => '123456789 ',   // 10 characters: '123456789 1234567890a' was too long
+ *   5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
+ *   6 => '   45678   ',  // 11 characters: Perfect split
+ *   7 => '1 3 5 7 9',    //  9 characters: End of $string
+ * );
+ * </code>
+ *
+ * @since wordpress  3.4.0
+ * @access private
+ *
+ * @param string $string The string to split.
+ * @param int $goal The desired chunk length.
+ * @return array Numeric array of chunks.
+ */
+function _split_str_by_whitespace( $string, $goal ) {
+    $chunks = array();
+
+    $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
+
+    while ( $goal < strlen( $string_nullspace ) ) {
+        $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
+
+        if ( false === $pos ) {
+            $pos = strpos( $string_nullspace, "\000", $goal + 1 );
+            if ( false === $pos ) {
+                break;
+            }
+        }
+
+        $chunks[] = substr( $string, 0, $pos + 1 );
+        $string = substr( $string, $pos + 1 );
+        $string_nullspace = substr( $string_nullspace, $pos + 1 );
+    }
+
+    if ( $string ) {
+        $chunks[] = $string;
+    }
+
+    return $chunks;
+}
+
+
 /**
  * @desc This function does some parsing on the text that gets inputted. This parsing can be of any kind
  *       LaTeX notation, Word Censoring, Glossary Terminology (extension will available soon), Musical Notations, ...

+ 8 - 10
main/link/category_form.class.php

@@ -12,7 +12,7 @@ namespace Link;
 
 /**
  * Edit/create a LinkCategory.
- * 
+ *
  * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Genevas
  * @license /license.txt
  */
@@ -25,7 +25,7 @@ class CategoryForm extends \FormValidator
     {
         parent::__construct($form_name, $method, $action, $target, $attributes, $track_submit);
     }
-    
+
     /**
      *
      * @return object
@@ -41,32 +41,30 @@ class CategoryForm extends \FormValidator
     }
     /**
      *
-     * @param \Link\LinkCategory $category 
+     * @param \Link\LinkCategory $category
      */
     function init($category = null)
     {
         $this->set_category($category);
-        
+
         $defaults = array();
         $defaults['category_title'] = $category->category_title;
         $defaults['category_description'] =  $category->description;
-        
+
         $this->addElement('hidden', 'c_id', $category->c_id);
         $this->addElement('hidden', 'id', $category->id);
         $this->addElement('hidden', 'session_id', $category->session_id);
 
         $form_name = $category->id ? get_lang('ModifyCategory') : get_lang('AddCategory');
-        $this->add_header($form_name);
-
-
+        $this->addHeader($form_name);
         $this->add_textfield('category_title', get_lang('Title'));
         $this->addRule('category_title', get_lang('Required'), 'required');
-        
+
         $this->addElement('textarea', 'category_description', get_lang('Description'));
         $this->addElement('button', 'save', get_lang('Save'), array('class' => 'btn save'));
         $this->setDefaults($defaults);
     }
-    
+
     function update_model()
     {
         $values = $this->exportValues();

+ 1 - 2
main/link/link_form.class.php

@@ -63,8 +63,7 @@ class LinkForm extends \FormValidator
         $this->add_hidden('session_id', $link->session_id);
 
         $form_name = $category->id ? get_lang('LinkMod') : get_lang('LinkAdd');
-        $this->add_header($form_name);
-
+        $this->addHeader($form_name);
 
         $this->add_textfield('url', get_lang('Url'), $required = true, array('class' => 'span6'));
         $this->addRule('url', get_lang('MalformedUrl'), 'regex', '|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i');

+ 1 - 1
main/link/upload_file_form.class.php

@@ -33,7 +33,7 @@ class UploadFileForm extends \FormValidator
     function init()
     {
         $form_name = get_lang('UploadFile');
-        $this->add_header($form_name);
+        $this->addHeader($form_name);
 
         $label = get_lang('File');
         $this->add_file('file', $label);

+ 1 - 1
main/mySpace/user_add.php

@@ -169,7 +169,7 @@ $form->addGroup($group, 'mail', get_lang('SendMailToNewUser'), '&nbsp;');
 $form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
 $group = array ();
 $group[] = $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
-$group[] = $form->createElement('datepicker', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
+$group[] = $form->createElement('DatePicker', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
 $form->addGroup($group, 'max_member_group', null, '', false);
 // Active account or inactive account
 $form->addElement('radio', 'active', get_lang('ActiveAccount'), get_lang('Active'), 1);

+ 2 - 2
main/newscorm/lp_add.php

@@ -132,13 +132,13 @@ $form -> addElement('html','<div id="options" style="display:none">');
 //Start date
 $form->addElement('checkbox', 'activate_start_date_check', null, get_lang('EnableStartTime'), array('onclick' => 'activate_start_date()'));
 $form->addElement('html','<div id="start_date_div" style="display:block;">');
-$form->addElement('datepicker', 'publicated_on', get_lang('PublicationDate'), array('form_name'=>'lp_add'), 5);
+$form->addElement('DatePicker', 'publicated_on', get_lang('PublicationDate'), array('form_name'=>'lp_add'), 5);
 $form->addElement('html','</div>');
 
 //End date
 $form->addElement('checkbox', 'activate_end_date_check', null, get_lang('EnableEndTime'), array('onclick' => 'activate_end_date()'));
 $form->addElement('html','<div id="end_date_div" style="display:none;">');
-$form->addElement('datepicker', 'expired_on', get_lang('ExpirationDate'), array('form_name'=>'lp_add'), 5);
+$form->addElement('DatePicker', 'expired_on', get_lang('ExpirationDate'), array('form_name'=>'lp_add'), 5);
 $form->addElement('html','</div>');
 
 $form->addElement('html','</div>');

+ 2 - 70
main/newscorm/lp_add_item.php

@@ -24,75 +24,7 @@ $learnPath = $_SESSION['oLP'];
 
 $language_file = 'learnpath';
 
-$htmlHeadXtra[] = '
-<script>
-var temp = false;
-var load_default_template = '. ((isset($_POST['submit']) || empty($_SERVER['QUERY_STRING'])) ? 'false' : 'true' ) .';
-
-function FCKeditor_OnComplete( editorInstance ) {
-    editorInstance.Events.AttachEvent( \'OnSelectionChange\', check_for_title) ;
-    document.getElementById(\'frmModel\').innerHTML = "<iframe id=\'frame_template\' name=\'my_frame_template\' height=890px width=220px; frameborder=0 src=\''.api_get_path(WEB_LIBRARY_PATH).'fckeditor/editor/fckdialogframe.html \'>";
-    loaded = true;
-}
-
-function check_for_title() {
-    if (temp) {
-
-        // This functions shows that you can interact directly with the editor area
-        // DOM. In this way you have the freedom to do anything you want with it.
-
-        // Get the editor instance that we want to interact with.
-        var oEditor = FCKeditorAPI.GetInstance(\'content_lp\') ;
-
-        // Get the Editor Area DOM (Document object).
-        var oDOM = oEditor.EditorDocument ;
-
-        var iLength ;
-        var contentText ;
-        var contentTextArray;
-        var bestandsnaamNieuw = "";
-        var bestandsnaamOud = "";
-
-        // The are two diffent ways to get the text (without HTML markups).
-        // It is browser specific.
-
-        if( document.all )		// If Internet Explorer.
-        {
-            contentText = oDOM.body.innerText ;
-        }
-        else					// If Gecko.
-        {
-            var r = oDOM.createRange() ;
-            r.selectNodeContents( oDOM.body ) ;
-            contentText = r.toString() ;
-        }
-
-        var index=contentText.indexOf("/*<![CDATA");
-        contentText=contentText.substr(0,index);
-
-        // Compose title if there is none
-        contentTextArray = contentText.split(\' \') ;
-        var x=0;
-        for(x=0; (x<5 && x<contentTextArray.length); x++) {
-            if(x < 4) {
-                bestandsnaamNieuw += contentTextArray[x] + \' \';
-            } else {
-                bestandsnaamNieuw += contentTextArray[x];
-            }
-        }
-    }
-    temp=true;
-}
-
-function InnerDialogLoaded() {
-    if (document.all) {
-        // if is iexplorer
-        var B=new window.frames.content_lp___Frame.FCKToolbarButton(\'Templates\',window.content_lp___Frame.FCKLang.Templates);
-    } else {
-        var B=new window.frames[0].FCKToolbarButton(\'Templates\',window.frames[0].FCKLang.Templates);
-    }
-    return 	B.ClickFrame();
-};'."\n".
+$htmlHeadXtra[] = '<script>'.
 
 $learnPath->get_js_dropdown_array() .
 
@@ -128,7 +60,7 @@ $(function() {
 
 $(document).on("ready", function() {
     CKEDITOR.on("instanceReady", function (e) {
-        showTemplates();
+        showTemplates("content_lp");
     });
 });
 </script>';

+ 2 - 2
main/newscorm/lp_edit.php

@@ -173,7 +173,7 @@ if ($publicated_on!='0000-00-00 00:00:00' && !empty($publicated_on)) {
 }
 
 $form->addElement('html','<div id="start_date_div" style="display:'.$display_date.';">');
-$form->addElement('datepicker', 'publicated_on', get_lang('PublicationDate'), array('form_name'=>'form1'), 5);
+$form->addElement('DatePicker', 'publicated_on', get_lang('PublicationDate'), array('form_name'=>'form1'), 5);
 $form->addElement('html','</div>');
 
 //End date
@@ -185,7 +185,7 @@ if ($expired_on!='0000-00-00 00:00:00' && !empty($expired_on)) {
 }
 
 $form->addElement('html','<div id="end_date_div" style="display:'.$display_date.';">');
-$form->addElement('datepicker', 'expired_on', get_lang('ExpirationDate'), array('form_name'=>'exercise_admin'), 5);
+$form->addElement('DatePicker', 'expired_on', get_lang('ExpirationDate'), array('form_name'=>'exercise_admin'), 5);
 $form->addElement('html','</div>');
 
 if (api_is_platform_admin()) {

+ 6 - 26
main/newscorm/lp_edit_item.php

@@ -11,9 +11,6 @@
  * @author Julio Montoya  - Improving the list of templates
  * @package chamilo.learnpath
 */
-/**
- * INIT SECTION
- */
 
 $this_section = SECTION_COURSES;
 
@@ -31,25 +28,11 @@ $language_file = 'learnpath';
 /* Header and action code */
 
 $htmlHeadXtra[] = '
-<script>
-
-function FCKeditor_OnComplete( editorInstance ) {
-    document.getElementById(\'frmModel\').innerHTML = "<iframe height=890px; width=230px; frameborder=0 src=\''.api_get_path(WEB_LIBRARY_PATH).'fckeditor/editor/fckdialogframe.html \'>";
-}
-
-function InnerDialogLoaded() {
-    if (document.all) {
-        // if is iexplorer
-        var B=new window.frames.content_lp___Frame.FCKToolbarButton(\'Templates\',window.content_lp___Frame.FCKLang.Templates);
-    } else {
-        var B=new window.frames[0].FCKToolbarButton(\'Templates\',window.frames[0].FCKLang.Templates);
-    }
-    return B.ClickFrame();
-$};'.$_SESSION['oLP']->get_js_dropdown_array().'
+<script>'.$_SESSION['oLP']->get_js_dropdown_array().'
 
 $(document).on("ready", function() {
     CKEDITOR.on("instanceReady", function (e) {
-        showTemplates();
+        showTemplates("content_lp");
     });
 });
 </script>';
@@ -57,12 +40,11 @@ $(document).on("ready", function() {
 /* Constants and variables */
 
 $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
-
 $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
 
-$isStudentView  = (int) $_REQUEST['isStudentView'];
-$learnpath_id   = (int) $_REQUEST['lp_id'];
-$submit			= $_POST['submit_button'];
+$isStudentView = isset($_REQUEST['isStudentView']) ? intval($_REQUEST['isStudentView']) : null;
+$learnpath_id = (int) $_REQUEST['lp_id'];
+$submit = isset($_POST['submit_button']) ? $_POST['submit_button'] : null;
 
 /* MAIN CODE */
 
@@ -151,9 +133,7 @@ if (Database::num_rows($res_doc) > 0 && $path_parts['extension'] == 'html') {
     echo $_SESSION['oLP']->return_new_tree();
 
     // Show the template list
-    echo '<p style="border-bottom:1px solid #999999; margin:0; padding:2px;"></p>';
-    echo '<br />';
-    echo '<div id="frmModel" style="display:block; height:890px;width:100px; position:relative;"></div>';
+    echo '<div id="frmModel" class="lp-add-item"></div>';
 } else {
     echo $_SESSION['oLP']->return_new_tree();
 }

+ 1 - 1
main/notebook/notebook_form.class.php

@@ -67,7 +67,7 @@ class NotebookForm extends \FormValidator
         $this->add_hidden(Request::PARAM_SEC_TOKEN, Access::instance()->get_token());
 
         $form_name = $notebook->id ? get_lang('ModifyNote') : get_lang('NoteAddNew');
-        $this->add_header($form_name);
+        $this->addHeader($form_name);
 
         $this->add_textfield('title', get_lang('NoteTitle'), $required = true, array('class' => 'span3'));
 

+ 1 - 1
main/notebook/upload_file_form.class.php

@@ -35,7 +35,7 @@ class UploadFileForm extends \FormValidator
     function init()
     {
         $form_name = get_lang('Import');
-        $this->add_header($form_name);
+        $this->addHeader($form_name);
 
         $this->add_hidden(Request::PARAM_SEC_TOKEN, Access::instance()->get_token());
         $label = get_lang('File');

+ 6 - 6
main/social/group_topics.php

@@ -16,8 +16,8 @@ if (api_get_setting('allow_social_tool') != 'true') {
 }
 
 $group_id = intval($_GET['id']);
-$topic_id = intval($_GET['topic_id']);
-$message_id = intval($_GET['msg_id']);
+$topic_id = isset($_GET['topic_id']) ? intval($_GET['topic_id']) : null;
+$message_id = isset($_GET['msg_id']) ? intval($_GET['msg_id']) : null;
 
 //todo @this validation could be in a function in group_portal_manager
 if (empty($group_id)) {
@@ -101,7 +101,7 @@ if (isset($_POST['token']) && $_POST['token'] === $_SESSION['sec_token']) {
                 'error'
             );
         }
-        $topic_id = intval($_GET['topic_id']);
+        $topic_id = isset($_GET['topic_id']) ? intval($_GET['topic_id']) : null;
         if ($_POST['action'] == 'add_message_group') {
             $topic_id = $res;
         }
@@ -242,13 +242,13 @@ $social_right_content .= MessageManager::display_message_for_group(
 
 $social_right_content = '<div class="span9">' . $social_right_content . '</div>';
 
-$tpl = new Template($tool_name);
+$tpl = new Template(null);
 $tpl->set_help('Groups');
 $tpl->assign('social_avatar_block', $social_avatar_block);
 $tpl->assign('social_menu_block', $social_menu_block);
 $tpl->assign('social_right_content', $social_right_content);
-$tpl->assign('actions', $actions);
-$tpl->assign('message', $show_message);
+//$tpl->assign('actions', $actions);
+//$tpl->assign('message', $show_message);
 $tpl->assign('content', $content);
 $social_layout = $tpl->get_template('layout/social_layout.tpl');
 $tpl->display($social_layout);

+ 2 - 2
main/social/groups.php

@@ -59,11 +59,11 @@ function add_image_form() {
 		counter_image = counter_image;
 	}
 	var elem1 = document.createElement("div");
-	elem1.setAttribute("id","filepath_"+counter_image);
+	elem1.setAttribute("id", "filepath_"+counter_image);
 	filepaths.appendChild(elem1);
 	id_elem1 = "filepath_"+counter_image;
 	id_elem1 = "\'"+id_elem1+"\'";
-	document.getElementById("filepath_"+counter_image).innerHTML = "<input type=\"file\" name=\"attach_"+counter_image+"\"  size=\"20\" />&nbsp;<a href=\"javascript:remove_image_form("+id_elem1+")\"><img src=\"' . api_get_path(WEB_CODE_PATH) . 'img/delete.gif\"></a>";
+	document.getElementById("filepath_"+counter_image).innerHTML = "<div class=\"control-group\"><div class=\"controls\"><input type=\"file\" name=\"attach_"+counter_image+"\"  size=\"20\" />&nbsp;<a href=\"javascript:remove_image_form("+id_elem1+")\"><img src=\"' . api_get_path(WEB_CODE_PATH) . 'img/delete.gif\"></a></div></div>";
 	if (filepaths.childNodes.length == 3) {
 		var link_attach = document.getElementById("link-more-attach");
 		if (link_attach) {

+ 64 - 72
main/social/message_for_group_form.inc.php

@@ -1,5 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
  * Form for group message
  * @package chamilo.social
@@ -68,80 +69,70 @@ if (!empty($group_id) && $allowed_action) {
 
 $page_item = !empty($_GET['topics_page_nr']) ? intval($_GET['topics_page_nr']) : 1;
 $param_item_page = isset($_GET['items_page_nr']) && isset($_GET['topic_id']) ? ('&items_' . intval($_GET['topic_id']) . '_page_nr=' . (!empty($_GET['topics_page_nr']) ? intval($_GET['topics_page_nr']) : 1)) : '';
-$param_item_page .= '&topic_id=' . intval($_GET['topic_id']);
+$param_item_page .= isset($_GET['topic_id']) ? '&topic_id=' . intval($_GET['topic_id']) : null;
 $page_topic = !empty($_GET['topics_page_nr']) ? intval($_GET['topics_page_nr']) : 1;
 $anchor = isset($_GET['anchor_topic']) ? Security::remove_XSS($_GET['anchor_topic']) : null;
-?>
-
-<form name="form"
-      action="group_topics.php?id=<?php echo $group_id ?>&anchor_topic=<?php echo $anchor; ?>&topics_page_nr=<?php echo $page_topic . $param_item_page ?>"
-      method="POST" enctype="multipart/form-data">
-    <input type="hidden" name="action" value="<?php echo $allowed_action ?>"/>
-    <input type="hidden" name="group_id" value="<?php echo $group_id ?>"/>
-    <input type="hidden" name="parent_id" value="<?php echo $message_id ?>"/>
-    <input type="hidden" name="message_id" value="<?php echo $message_id ?>"/>
-    <input type="hidden" name="token" value="<?php echo $tok ?>"/>
-    <table width="500px" border="0" height="220px">
-        <tr height="180">
-            <td align="left">
-                <div id="id_content_panel_init">
-                    <dl>
-                        <?php
-                        if (api_get_setting('allow_message_tool') == 'true') {
-                            //normal message
-                            $user_info = api_get_user_info($userfriend_id);
-                            //echo api_xml_http_response_encode(get_lang('To')).":&nbsp;&nbsp;".api_xml_http_response_encode($to_group);
-                            $height = 180;
-                            if ($allowed_action == 'add_message_group') {
-                                $height = 140;
-                                echo '<span style="color:red">*</span> ' . api_xml_http_response_encode(
-                                        get_lang('Title')
-                                    ) . ' :<br />';
-                                echo '<input id="txt_subject_id" name="title" type="text" style="width:450px;" value="' . $subject . '"><br /><br />';
-                            }
-                            //echo api_xml_http_response_encode(get_lang('Description')).' :<br />';
-                            //@todo use formvalidator
-                            $oFCKeditor = new CKeditor();
-                            $oFCKeditor->ToolbarSet = 'messages';
-                            $oFCKeditor->Width = '95%';
-                            $oFCKeditor->Height = $height;
-                            $oFCKeditor->Value = $message;
-
-                            //$return = $oFCKeditor->CreateHtml();
-                            $return = $oFCKeditor->editor('content');
-                            echo $return;
-                            if ($allowed_action == 'add_message_group') {
-                                echo '<div><span style="color:red"> * </span>' . get_lang(
-                                        'FieldRequired'
-                                    ) . '</div>';
-                            }
-                            ?>
-                            <br/><br/>
-                            <?php echo api_xml_http_response_encode(
-                                get_lang('AttachmentFiles')
-                            ); ?> :<br/>
-                            <span id="filepaths"><div id="filepath_1"><input
-                                        type="file" name="attach_1" size="20"/>
-                                </div></span>
-                            <div id="link-more-attach">
-                                <a href="javascript://"
-                                   onclick="return add_image_form()">
-                                    <?php echo get_lang('AddOneMoreFile') ?></a>
-                            </div>
-                            (<?php echo api_xml_http_response_encode(
-                                sprintf(
-                                    get_lang('MaximunFileSizeX'),
-                                    format_file_size(
-                                        api_get_setting(
-                                            'message_max_upload_filesize'
-                                        )
-                                    )
-                                )
-                            ) ?>)
-                            <br/>
-                            <br/>
-
-                            <?php if ($allowed_action == 'add_message_group') { ?>
+
+
+$form = new FormValidator(
+    'add_post',
+    'post',
+    api_get_path(WEB_CODE_PATH)."social/group_topics.php?id=$group_id&anchor_topic=$anchor&topics_page_nr=$page_topic"."$param_item_page",
+    null,
+    array('enctype' => 'multipart/form-data')
+);
+$form->addHidden('action', $allowed_action);
+$form->addHidden('group_id', $group_id);
+$form->addHidden('parent_id', $message_id);
+$form->addHidden('message_id',$message_id );
+$form->addHidden('token', $tok);
+
+if (api_get_setting('allow_message_tool') == 'true') {
+    //normal message
+    $user_info = api_get_user_info($userfriend_id);
+    $height = 180;
+    if ($allowed_action == 'add_message_group') {
+        $form->add_textfield('title', get_lang('Title'));
+        $height = 140;
+    }
+
+    $config = array();
+    $config['ToolbarSet'] = 'Messages';
+    $form->add_html_editor(
+        'content',
+        get_lang('Content'),
+        false,
+        false,
+        $config
+    );
+    $form->add_html('<span id="filepaths"><div id="filepath_1">');
+    $form->add_file('attach_1', get_lang('AttachmentFiles'));
+    $form->add_html('</div></span>');
+
+    $form->add_label(null,
+        ' <div id="link-more-attach">
+        <a href="javascript://" onclick="return add_image_form()">
+            ' . get_lang('AddOneMoreFile') . '</a>
+        </div>'
+    );
+    $form->add_label(null,
+        api_xml_http_response_encode(
+            sprintf(
+                get_lang('MaximunFileSizeX'),
+                format_file_size(
+                    api_get_setting('message_max_upload_filesize')
+                )
+            )
+        )
+    );
+
+    $form->addElement('style_submit_button', 'submit', get_lang('SendMessage'));
+    Display::display_no_header();
+    //Display::display_reduced_header();
+    $form->display();
+}
+/*
+                                ?>
                                 <button class="btn save"
                                         onclick="if(validate_text_empty(this.form.title.value,'<?php echo get_lang(
                                             'YouShouldWriteASubject'
@@ -166,3 +157,4 @@ $anchor = isset($_GET['anchor_topic']) ? Security::remove_XSS($_GET['anchor_topi
         </div>
     </table>
 </form>
+*/

+ 10 - 5
main/template/default/layout/head.tpl

@@ -39,7 +39,11 @@ plugins.forEach(function(plugin) {
 /**
  * Function use to load templates in a div
 **/
-var showTemplates = function () {
+var showTemplates = function (ckeditorName) {
+    var editorName = 'content';
+    if (ckeditorName && ckeditorName.length > 0) {
+        editorName = ckeditorName;
+    }
     CKEDITOR.editorConfig(CKEDITOR.config);
     CKEDITOR.loadTemplates(CKEDITOR.config.templates_files, function (a){
         var templatesConfig = CKEDITOR.getTemplates("default");
@@ -64,10 +68,11 @@ var showTemplates = function () {
                 html: templateHTML,
                 click: function (e) {
                     e.preventDefault();
-
-                    CKEDITOR.instances.content.setData(template.html, function () {
-                        this.checkDirty();
-                    });
+                    if (CKEDITOR.instances[editorName]) {
+                        CKEDITOR.instances[editorName].setData(template.html, function () {
+                            this.checkDirty();
+                        });
+                    }
                 }
             }).appendTo($templateLi);
 

+ 2 - 2
main/wiki/wiki.inc.php

@@ -640,7 +640,7 @@ class Wiki
             }
 
             $form->addElement('html', '<div id="start_date" style="'.$style.'">');
-            $form->addElement('datepicker', 'startdate_assig');
+            $form->addElement('DatePicker', 'startdate_assig');
             $form->addElement('html', '</div>');
             $form->addElement('checkbox', 'initenddate', null, get_lang('EndDate'), array('id' => 'end_date_toggle'));
 
@@ -652,7 +652,7 @@ class Wiki
             }
 
             $form->addElement('html', '<div id="end_date" style="'.$style.'">');
-            $form->addElement('datepicker', 'enddate_assig');
+            $form->addElement('DatePicker', 'enddate_assig');
             $form->addElement('html', '</div>');
             $form->addElement('checkbox', 'delayedsubmit', null, get_lang('AllowLaterSends'));
             $form->addElement('text', 'max_text', get_lang('NMaxWords'));

+ 21 - 15
plugin/advanced_subscription/README.md

@@ -1,13 +1,16 @@
 Advanced subscription plugin for Chamilo LMS
 =======================================
-Plugin for managing the registration queue and communication to sessions
+Plugin to manage the registration queue and communication to sessions
 from an external website creating a queue to control session subscription
-and sending emails to approve student subscription request
+and sending emails to approve student subscription requests
+
 # Requirements
-Chamilo LMS 1.10 or greater
+Chamilo LMS 1.10.0 or greater
 
 # Settings
 
+These settings have to be configured in the Configuration screen for the plugin
+
 Parameters    | Description
 ------------- |-------------
 Webservice url | Url to external website to get user profile (SOAP)
@@ -21,7 +24,7 @@ Minimum percentage profile | Minimum percentage required from external website p
 
 # Hooks
 
-This plugin use the next hooks:
+This plugin uses the following hooks (defined since Chamilo LMS 1.10.0):
 
 * HookAdminBlock
 * HookWSRegistration
@@ -31,23 +34,26 @@ This plugin use the next hooks:
 
 # Web services
 
+This plugin also enables new webservices that can be used from registration.soap.php
+
 * HookAdvancedSubscription..WSSessionListInCategory
 * HookAdvancedSubscription..WSSessionGetDetailsByUser
 * HookAdvancedSubscription..WSListSessionsDetailsByCategory
 
 See `/plugin/advanced_subscription/src/HookAdvancedSubscription.php` to check Web services inputs and outputs
 
-# How plugin works?
+# How does this plugin works?
+
+After install, fill the required parameters (described above)
+Use web services to communicate course session inscription from external website
+This allows students to search course sessions and subscribe if they match
+the requirements.
 
-After install plugin, fill the parameters needed (described above)
-Use Web services to communicate course session inscription from external website
-This allow to student to search course session and subscribe if is qualified
-and allowed to subscribe.
 The normal process is:
-* Student search course session
-* Student read session info depending student data
-* Student request a subscription
-* A confirmation email is send to student
-* An email is send to users (superior or admins) who will accept or reject student request
-* When the user aceept o reject, an email will be send to student, superior or admins respectively
+* Student searches course session
+* Student reads session info depending student data
+* Student requests to be subscribed
+* A confirmation email is sent to student
+* An authorization email is sent to student's superior (STUDENT BOSS role) or admins (when there is no superior) who will accept or reject the student request
+* When the superior accepts or rejects, an email will be sent to the student and superior (or admin), respectively
 * To complete the subscription, the request must be validated and accepted by an admin

+ 10 - 10
plugin/advanced_subscription/lang/english.php

@@ -4,17 +4,17 @@
 $strings['plugin_title'] = 'Advanced Subscription';
 $strings['plugin_comment'] = 'Plugin for managing the registration queue and communication to sessions from an external website';
 $strings['ws_url'] = 'Webservice url';
-$strings['ws_url_help'] = 'La URL de la cual se solicitará información para el proceso de la inscripción avanzada';
-$strings['check_induction'] = 'Activate induction course requirement';
-$strings['check_induction_help'] = 'Check to require induction course';
-$strings['yearly_cost_limit'] = 'Yearly limit TUV for courses (measured in Taxation units)';
-$strings['yearly_cost_limit_help'] = "How much TUV the student courses should cost at most.";
-$strings['yearly_hours_limit'] = 'Yearly limit teaching hours for courses';
-$strings['yearly_hours_limit_help'] = "How many teching hours the student may learn by year.";
+$strings['ws_url_help'] = 'The URL from which ingormation will be requested for the advanced subscription process';
+$strings['check_induction'] = 'Enable induction course requirement';
+$strings['check_induction_help'] = 'Check to make induction course mandatory';
+$strings['yearly_cost_limit'] = 'Yearly TUV limit for courses (measured in Taxation units)';
+$strings['yearly_cost_limit_help'] = "How much TUVs the student courses should cost at most.";
+$strings['yearly_hours_limit'] = 'Yearly teaching hours limit for courses';
+$strings['yearly_hours_limit_help'] = "How many teaching hours the student may follow by year.";
 $strings['yearly_cost_unit_converter'] = 'Taxation unit value (TUV)';
-$strings['yearly_cost_unit_converter_help'] = "The taxation unit value for current year in local currency";
-$strings['courses_count_limit'] = 'Yearly limit times for courses';
-$strings['courses_count_limit_help'] = "How many times a student can course, this does <strong>not</strong> include induction courses";
+$strings['yearly_cost_unit_converter_help'] = "The taxation unit value for the current year, in local currency";
+$strings['courses_count_limit'] = 'Yearly courses limit';
+$strings['courses_count_limit_help'] = "How many times a student can take courses. This value does <strong>not</strong> include induction courses";
 $strings['course_session_credit_year_start_date'] = 'Year start date';
 $strings['course_session_credit_year_start_date_help'] = "a date (dd/mm)";
 $strings['min_profile_percentage'] = "Minimum required of completed percentage profile";

+ 24 - 9
plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php

@@ -13,7 +13,7 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
     /**
      * Constructor
      */
-    function __construct()
+    public function __construct()
     {
         $parameters = array(
             'yearly_cost_limit' => 'text',
@@ -35,7 +35,7 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
      * @staticvar null $result
      * @return AdvancedSubscriptionPlugin
      */
-    static function create()
+    public static function create()
     {
         static $result = null;
 
@@ -111,7 +111,7 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
      */
     public function isAllowedToDoRequest($userId, $params = array())
     {
-        $isAllowed = false;
+        $isAllowed = null;
         if (isset($params['is_connected']) && isset($params['profile_completed'])) {
             $plugin = self::create();
             // WS URL is not yet implemented
@@ -264,7 +264,7 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
      */
     public function startSubscription($userId, $sessionId, $params)
     {
-        $result = false;
+        $result = null;
         if (!empty($sessionId) && !empty($userId)) {
             $plugin = self::create();
             try {
@@ -360,7 +360,7 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
             $where = array(
                 'id = ?' => intval($params['queue']['id']),
             );
-        } elseif(isset($params['studentUserId']) && isset($params['sessionId'])) {
+        } elseif (isset($params['studentUserId']) && isset($params['sessionId'])) {
             $where = array(
                 'user_id = ? AND session_id = ? AND status <> ? AND status <> ?' => array(
                     intval($params['studentUserId']),
@@ -754,7 +754,8 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
     }
 
     /**
-     * Return the session details data from session extra field value
+     * Return the session details data from a session ID (including the extra
+     * fields used for the advanced subscription mechanism)
      * @param $sessionId
      * @return bool|mixed
      */
@@ -776,7 +777,11 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
             }
 
             $mergedArray = array_merge(array($sessionId), array_keys($fields));
-            $sessionFieldValueList = $extraSession->get_all(array('session_id = ? field_id IN ( ?, ?, ?, ?, ?, ?, ? )' => $mergedArray));
+            $sessionFieldValueList = $extraSession->get_all(
+                array(
+                    'session_id = ? field_id IN ( ?, ?, ?, ?, ?, ?, ? )' => $mergedArray
+                )
+            );
             foreach ($sessionFieldValueList as $sessionFieldValue) {
                 // Check if session field value is set in session field list
                 if (isset($fields[$sessionFieldValue['field_id']])) {
@@ -876,7 +881,13 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
         // Filter input variable
         $sessionId = intval($sessionId);
         // Assign variables
-        $fieldsArray = array('target', 'publication_end_date', 'mode', 'recommended_number_of_participants', 'vacancies');
+        $fieldsArray = array(
+            'target',
+            'publication_end_date',
+            'mode',
+            'recommended_number_of_participants',
+            'vacancies'
+        );
         $sessionArray = api_get_session_info($sessionId);
         $extraSession = new ExtraFieldValue('session');
         $extraField = new ExtraField('session');
@@ -891,7 +902,11 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
         }
 
         $mergedArray = array_merge(array($sessionId), array_keys($fields));
-        $sessionFieldValueList = $extraSession->get_all(array('session_id = ? field_id IN ( ?, ?, ?, ?, ?, ?, ? )' => $mergedArray));
+        $sessionFieldValueList = $extraSession->get_all(
+            array(
+                'session_id = ? field_id IN ( ?, ?, ?, ?, ?, ?, ? )' => $mergedArray
+            )
+        );
         foreach ($sessionFieldValueList as $sessionFieldValue) {
             // Check if session field value is set in session field list
             if (isset($fields[$sessionFieldValue['field_id']])) {

+ 103 - 57
plugin/advanced_subscription/src/HookAdvancedSubscription.php

@@ -8,6 +8,10 @@
 
 require_once __DIR__ . '/../config.php';
 
+/**
+ * Class HookAdvancedSubscription extends the HookObserver to implements
+ * specific behaviour when the AdvancedSubscription plugin is enabled
+ */
 class HookAdvancedSubscription extends HookObserver implements
     HookAdminBlockObserverInterface,
     HookWSRegistrationObserverInterface,
@@ -15,6 +19,9 @@ class HookAdvancedSubscription extends HookObserver implements
 {
     public static $plugin;
 
+    /**
+     * Constructor. Calls parent, mainly.
+     */
     protected function __construct()
     {
         self::$plugin = AdvancedSubscriptionPlugin::create();
@@ -52,7 +59,7 @@ class HookAdvancedSubscription extends HookObserver implements
     /**
      * Add Webservices to registration.soap.php
      * @param HookWSRegistrationEventInterface $hook
-     * @return int
+     * @return mixed (int or false)
      */
     public function hookWSRegistration(HookWSRegistrationEventInterface $hook)
     {
@@ -73,15 +80,24 @@ class HookAdvancedSubscription extends HookObserver implements
                 'all',
                 '',
                 array(
-                    'id' => array('name' => 'id', 'type' => 'xsd:string'), // session.id
-                    'name' => array('name' => 'name', 'type' => 'xsd:string'), // session.name
-                    'short_description' => array('name' => 'short_description', 'type' => 'xsd:string'), // session.short_description
-                    'mode' => array('name' => 'mode', 'type' => 'xsd:string'), // session.mode
-                    'date_start' => array('name' => 'date_start', 'type' => 'xsd:string'), // session.date_start
-                    'date_end' => array('name' => 'date_end', 'type' => 'xsd:string'), // session.date_end
-                    'human_text_duration' => array('name' => 'human_text_duration', 'type' => 'xsd:string'), // session.human_text_duration
-                    'vacancies' => array('name' => 'vacancies', 'type' => 'xsd:string'), // session.vacancies
-                    'schedule' => array('name' => 'schedule', 'type' => 'xsd:string'), // session.schedule
+                    // session.id
+                    'id' => array('name' => 'id', 'type' => 'xsd:int'),
+                    // session.name
+                    'name' => array('name' => 'name', 'type' => 'xsd:string'),
+                    // session.short_description
+                    'short_description' => array('name' => 'short_description', 'type' => 'xsd:string'),
+                    // session.mode
+                    'mode' => array('name' => 'mode', 'type' => 'xsd:string'),
+                    // session.date_start
+                    'date_start' => array('name' => 'date_start', 'type' => 'xsd:string'),
+                    // session.date_end
+                    'date_end' => array('name' => 'date_end', 'type' => 'xsd:string'),
+                    // session.human_text_duration
+                    'human_text_duration' => array('name' => 'human_text_duration', 'type' => 'xsd:string'),
+                    // session.vacancies
+                    'vacancies' => array('name' => 'vacancies', 'type' => 'xsd:string'),
+                    // session.schedule
+                    'schedule' => array('name' => 'schedule', 'type' => 'xsd:string'),
                 )
             );
 
@@ -123,10 +139,14 @@ class HookAdvancedSubscription extends HookObserver implements
                 'all',
                 '',
                 array(
-                    'user_id' => array('name' => 'user_id', 'type' => 'xsd:int'), // user.user_id
-                    'session_id' => array('name' => 'session_id', 'type' => 'xsd:int'), // session.id
-                    'profile_completed' => array('name' => 'profile_completed', 'type' => 'xsd:float'), // user.profile_completes
-                    'is_connected' => array('name' => 'is_connected', 'type' => 'xsd:boolean'), // user.is_connected
+                    // user.user_id
+                    'user_id' => array('name' => 'user_id', 'type' => 'xsd:int'),
+                    // session.id
+                    'session_id' => array('name' => 'session_id', 'type' => 'xsd:int'),
+                    // user.profile_completes
+                    'profile_completed' => array('name' => 'profile_completed', 'type' => 'xsd:float'),
+                    // user.is_connected
+                    'is_connected' => array('name' => 'is_connected', 'type' => 'xsd:boolean'),
                     'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string'),
                 )
             );
@@ -139,17 +159,28 @@ class HookAdvancedSubscription extends HookObserver implements
                 'all',
                 '',
                 array(
-                    'id' => array('name' => 'id', 'type' => 'xsd:string'), // session.id
-                    'cost' => array('name' => 'cost', 'type' => 'xsd:float'), // session.cost
-                    'place' => array('name' => 'place', 'type' => 'xsd:string'), // session.place
-                    'allow_visitors' => array('name' => 'allow_visitors', 'type' => 'xsd:string'), // session.allow_visitors
-                    'teaching_hours' => array('name' => 'teaching_hours', 'type' => 'xsd:int'), // session.human_text_duration
-                    'brochure' => array('name' => 'brochure', 'type' => 'xsd:string'), // session.brochure
-                    'banner' => array('name' => 'banner', 'type' => 'xsd:string'), // session.banner
-                    'description' => array('name' => 'description', 'type' => 'xsd:string'), // session.description
-                    'status' => array('name' => 'status', 'type' => 'xsd:string'), // status
-                    'action_url' => array('name' => 'action_url', 'type' => 'xsd:string'), // action_url
-                    'message' => array('name' => 'error_message', 'type' => 'xsd:string'), // message
+                    // session.id
+                    'id' => array('name' => 'id', 'type' => 'xsd:string'),
+                    // session.cost
+                    'cost' => array('name' => 'cost', 'type' => 'xsd:float'),
+                    // session.place
+                    'place' => array('name' => 'place', 'type' => 'xsd:string'),
+                    // session.allow_visitors
+                    'allow_visitors' => array('name' => 'allow_visitors', 'type' => 'xsd:string'),
+                    // session.teaching_hours
+                    'teaching_hours' => array('name' => 'teaching_hours', 'type' => 'xsd:int'),
+                    // session.brochure
+                    'brochure' => array('name' => 'brochure', 'type' => 'xsd:string'),
+                    // session.banner
+                    'banner' => array('name' => 'banner', 'type' => 'xsd:string'),
+                    // session.description
+                    'description' => array('name' => 'description', 'type' => 'xsd:string'),
+                    // status
+                    'status' => array('name' => 'status', 'type' => 'xsd:string'),
+                    // action_url
+                    'action_url' => array('name' => 'action_url', 'type' => 'xsd:string'),
+                    // message
+                    'message' => array('name' => 'error_message', 'type' => 'xsd:string'),
                 )
             );
 
@@ -163,10 +194,14 @@ class HookAdvancedSubscription extends HookObserver implements
                 'all',
                 '',
                 array(
-                    'id' => array('name' => 'id', 'type' => 'xsd:string'), // session_category.id
-                    'category_name' => array('name' => 'category_name', 'type' => 'xsd:string'), // session_category.name
-                    'access_url_id' => array('name' => 'access_url_id', 'type' => 'xsd:int'), // session_category.access_url_id
-                    'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string') // secret key
+                    // session_category.id
+                    'id' => array('name' => 'id', 'type' => 'xsd:string'),
+                    // session_category.access_url_id
+                    'access_url_id' => array('name' => 'access_url_id', 'type' => 'xsd:int'),
+                    // session_category.name
+                    'category_name' => array('name' => 'category_name', 'type' => 'xsd:string'),
+                    // secret key
+                    'secret_key' => array('name' => 'secret_key', 'type' => 'xsd:string'),
                 ),
                 array(),
                 'tns:listSessionsDetailsByCategory'
@@ -367,6 +402,8 @@ class HookAdvancedSubscription extends HookObserver implements
         } else {
             // Nothing to do
         }
+
+        return false;
     }
 
     /**
@@ -377,8 +414,10 @@ class HookAdvancedSubscription extends HookObserver implements
     {
         global $debug;
 
-        if ($debug) error_log('WSUserSubscribedInCourse');
-        if ($debug) error_log('Params '. print_r($params, 1));
+        if ($debug) {
+            error_log('WSUserSubscribedInCourse');
+            error_log('Params ' . print_r($params, 1));
+        }
         if (!WSHelperVerifyKey($params)) {
 
            //return return_error(WS_ERROR_SECRET_KEY);
@@ -399,17 +438,18 @@ class HookAdvancedSubscription extends HookObserver implements
         }
 
         // Get the session brief List by category
-        $sessionList = SessionManager::getBriefSessionListAndExtraByCategory(
+        $fields = array(
+            'id',
+            'short_description',
+            'mode',
+            'human_text_duration',
+            'vacancies',
+            'schedule',
+        );
+        $sessionList = SessionManager::getShortSessionListAndExtraByCategory(
             $sessionCategoryId,
             $params['target'],
-            array(
-                'id',
-                'short_description',
-                'mode',
-                'human_text_duration',
-                'vacancies',
-                'schedule',
-            )
+            $fields
         );
 
         return $sessionList;
@@ -423,10 +463,11 @@ class HookAdvancedSubscription extends HookObserver implements
     {
         global $debug;
 
-        if ($debug) error_log('WSUserSubscribedInCourse');
-        if ($debug) error_log('Params '. print_r($params, 1));
+        if ($debug) {
+            error_log('WSUserSubscribedInCourse');
+            error_log('Params ' . print_r($params, 1));
+        }
         if (!WSHelperVerifyKey($params)) {
-
             return return_error(WS_ERROR_SECRET_KEY);
         }
         $result = return_error(WS_ERROR_NOT_FOUND_RESULT);
@@ -435,10 +476,11 @@ class HookAdvancedSubscription extends HookObserver implements
             $userId = (int) $params['user_id'];
             $sessionId = (int) $params['session_id'];
             // Check if student is already subscribed
-            $isOpen = self::$plugin->isSessionOpen($sessionId);
-            $status = self::$plugin->getQueueStatus($userId, $sessionId);
-            $vacancy = self::$plugin->getVacancy($sessionId);
-            $data = self::$plugin->getSessionDetails($sessionId);
+            $plugin = AdvancedSubscriptionPlugin::create();
+            $isOpen = $plugin->isSessionOpen($sessionId);
+            $status = $plugin->getQueueStatus($userId, $sessionId);
+            $vacancy = $plugin->getVacancy($sessionId);
+            $data = $plugin->getSessionDetails($sessionId);
             if (!empty($data) && is_array($data)) {
                 $data['status'] = $status;
                 // 5 Cases:
@@ -499,20 +541,21 @@ class HookAdvancedSubscription extends HookObserver implements
      * The extra data (field_name, field_value)
      * The course data (course_id, course_code, course_title,
      * coach_username, coach_firstname, coach_lastname)
-     * @param array List of parameters (id, category_name, access_url_id, secret_key)
+     * @param array $params List of parameters (id, category_name, access_url_id, secret_key)
      * @return array|soap_fault Sessions list (id=>[title=>'title',url='http://...',date_start=>'...',date_end=>''])
      */
     public static function WSListSessionsDetailsByCategory($params)
     {
         global $debug;
 
-        if ($debug) error_log('WSListSessionsDetailsByCategory');
-        if ($debug) error_log('Params '. print_r($params, 1));
+        if ($debug) {
+            error_log('WSListSessionsDetailsByCategory');
+            error_log('Params ' . print_r($params, 1));
+        }
         $secretKey = $params['secret_key'];
 
         // Check if secret key is valid
-        if(!WSHelperVerifyKey($secretKey)) {
-
+        if (!WSHelperVerifyKey($secretKey)) {
             return return_error(WS_ERROR_SECRET_KEY);
         }
 
@@ -541,6 +584,7 @@ class HookAdvancedSubscription extends HookObserver implements
         }
 
         // Get validated and waiting queue users count for each session
+        $plugin = AdvancedSubscriptionPlugin::create();
         foreach ($sessionList as &$session) {
             // Add validated and queue users count
             $session['validated_user_num'] = self::$plugin->countQueueByParams(
@@ -565,8 +609,9 @@ class HookAdvancedSubscription extends HookObserver implements
     }
 
     /**
+     * Return notification content when the hook has been triggered
      * @param HookNotificationContentEventInterface $hook
-     * @return int
+     * @return mixed (int or false)
      */
     public function hookNotificationContent(HookNotificationContentEventInterface $hook)
     {
@@ -576,8 +621,7 @@ class HookAdvancedSubscription extends HookObserver implements
 
             return $data;
         } elseif ($data['type'] === HOOK_EVENT_TYPE_POST) {
-            if (
-                isset($data['content']) &&
+            if (isset($data['content']) &&
                 !empty($data['content']) &&
                 isset($data['advanced_subscription_pre_content']) &&
                 !empty($data['advanced_subscription_pre_content'])
@@ -598,9 +642,11 @@ class HookAdvancedSubscription extends HookObserver implements
             // Hook type is not valid
             // Nothing to do
         }
+        return false;
     }
 
     /**
+     * Return the notification data title if the hook was triggered
      * @param HookNotificationTitleEventInterface $hook
      * @return int
      */
@@ -612,8 +658,7 @@ class HookAdvancedSubscription extends HookObserver implements
 
             return $data;
         } elseif ($data['type'] === HOOK_EVENT_TYPE_POST) {
-            if (
-                isset($data['advanced_subscription_pre_title']) &&
+            if (isset($data['advanced_subscription_pre_title']) &&
                 !empty($data['advanced_subscription_pre_title'])
             ) {
                 $data['title'] = $data['advanced_subscription_pre_title'];
@@ -624,5 +669,6 @@ class HookAdvancedSubscription extends HookObserver implements
             // Hook type is not valid
             // Nothing to do
         }
+        return false;
     }
 }

+ 1 - 3
plugin/ticket/src/myticket.php

@@ -5,9 +5,7 @@
  * This script is the Tickets plugin main entry point
  * @package chamilo.plugin.ticket
  */
-/**
- * Initialization
- */
+
 $language_file = array('messages', 'userInfo', 'admin');
 $cidReset = true;
 //needed in order to load the plugin lang variables

+ 25 - 28
plugin/ticket/src/new_ticket.php

@@ -1,12 +1,9 @@
 <?php
-
 /* For licensing terms, see /license.txt */
+
 /**
  * @package chamilo.plugin.ticket
  */
-/**
- * INIT SECTION
- */
 $language_file = array('messages', 'userInfo', 'admin');
 $cidReset = true;
 require_once '../config.php';
@@ -30,17 +27,17 @@ $htmlHeadXtra[] = '
 <script>
 function load_course_list (div_course, my_user_id, user_email) {
     $.ajax({
-            contentType: "application/x-www-form-urlencoded",
-            type: "GET",
-            url: "course_user_list.php",
-            data: "user_id="+my_user_id,
-            success: function(datos) {
-                $("#user_request").html(datos);
-                $("#user_id_request").val(my_user_id);
-                $("#personal_email").val(user_email);
-                $("#btnsubmit").attr("disabled", false);
-                ' . $scrollTol . '
-            }
+        contentType: "application/x-www-form-urlencoded",
+        type: "GET",
+        url: "course_user_list.php",
+        data: "user_id="+my_user_id,
+        success: function(datos) {
+            $("#user_request").html(datos);
+            $("#user_id_request").val(my_user_id);
+            $("#personal_email").val(user_email);
+            $("#btnsubmit").attr("disabled", false);
+            ' . $scrollTol . '
+        }
     });
 }
 function changeType() {
@@ -49,18 +46,18 @@ function changeType() {
     $("#project_id").val(projects[id]);
     $("#other_area").val(other_area[id]);
     $("#email").val(email[id]);
-	if(parseInt(course_required[id]) == 0){
-            $("#divCourse").css("display", "none");
-            if( id != "CUR"){
-                $("#divEmail").css("display", "block");
-                $("#personal_email").attr("required","required");
-            }
-            $("#course_id").disabled = true;
-            $("#course_id").value = 0;
-	}else{
-            $("#divCourse").css("display", "block");
-            $("#course_id").prop("disabled", false);
-            $("#course_id").val(0);
+	if (parseInt(course_required[id]) == 0){
+        $("#divCourse").css("display", "none");
+        if( id != "CUR"){
+            $("#divEmail").css("display", "block");
+            $("#personal_email").attr("required","required");
+        }
+        $("#course_id").disabled = true;
+        $("#course_id").value = 0;
+	} else {
+        $("#divCourse").css("display", "block");
+        $("#course_id").prop("disabled", false);
+        $("#course_id").val(0);
 	}
 }
 function handleClick2(myRadio) {
@@ -70,7 +67,7 @@ function handleClick2(myRadio) {
 }
 function validate() {
     var re  = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
-    fckEditor1val = FCKeditorAPI.__Instances["content"].GetHTML();
+    fckEditor1val = CKEDITOR.instances["content"].getData();
     document.getElementById("content").value= fckEditor1val;
     var selected = document.getElementById("category_id").selectedIndex;
     var id = document.getElementById("category_id").options[selected].value;

+ 32 - 32
plugin/ticket/src/ticket_details.php

@@ -40,11 +40,11 @@ $(document).ready(function(){
                     }
                 }
         });
-        
+
         $("a#assign").click(function () {
             $( "#dialog-form" ).dialog( "open" );
         });
-        
+
         $("input#responseyes").click(function () {
             if(!confirm("' . $plugin->get_lang('AreYouSure') . ' : ' . strtoupper(get_lang('Yes')) . '. ' . $plugin->get_lang('IfYouAreSureTheTicketWillBeClosed') . '")){
                 return false;
@@ -73,7 +73,7 @@ $(document).ready(function(){
 });
 
 function validate() {
-    fckEditor1val = FCKeditorAPI.__Instances["content"].GetHTML();
+    fckEditor1val = CKEDITOR.instances["content"].getData();
     document.getElementById("content").value= fckEditor1val;
     if(fckEditor1val == ""){
         alert("' . $plugin->get_lang('YouMustWriteAMessage') . '");
@@ -106,7 +106,7 @@ function add_image_form() {
         id: new_elem,
         class: "controls"
     }).appendTo(filepaths);
-    
+
     input_file = $("<input/>", {
         type: "file",
         name: "attach_" + counter_image,
@@ -124,7 +124,7 @@ function add_image_form() {
 
     new_filepath_id = $("#filepath_" + counter_image);
     new_filepath_id.append(input_file, link_remove.append(img_remove));
-    
+
     if (counter_image === 6) {
         var link_attach = $("#link-more-attach");
         if (link_attach) {
@@ -330,7 +330,7 @@ if (!isset($_POST['compose'])) {
     echo "<div class='span8 offset2'>";
     foreach ($messages as $message) {
         $type = "success";
-        
+
         if ($message['admin']) {
             $type = "normal";
             if ($isAdmin) {
@@ -339,10 +339,10 @@ if (!isset($_POST['compose'])) {
         }else {
             $message['message'].='<b>' . get_lang('Sent') . ': ' . api_convert_and_format_date(api_get_local_time($message['sys_insert_datetime']), DATE_TIME_FORMAT_LONG, _api_get_timezone()) . "</b>";
         }
-        
+
         $receivedMessage = '<b>' . get_lang('Subject') . ': </b> ' . $message['subject'] . '<br/> <b>' . get_lang('Message') . ':</b>' . $message['message'] . '<br/>';
         $attachementLinks = "";
-        
+
         if (isset($message['atachments'])) {
             $attributeClass = array(
                 'class' => 'attachment-link'
@@ -351,7 +351,7 @@ if (!isset($_POST['compose'])) {
                 $attachementLinks .= Display::tag('div', $attach['attachment_link'], $attributeClass);
             }
         }
-        
+
         $entireMessage = $receivedMessage . $attachementLinks;
         echo Display::return_message($entireMessage, $type, false);
     }
@@ -386,11 +386,11 @@ function show_form_send_message()
     global $ticket;
     global $subject;
     global $plugin;
-    
+
     Display::div('', array('span2'));
-    
+
     $form = new FormValidator(
-        'send_ticket', 
+        'send_ticket',
         'POST',
         api_get_self() . '?ticket_id=' . $ticket['ticket']['ticket_id'],
         '',
@@ -400,32 +400,32 @@ function show_form_send_message()
             'class' => 'span9 offset1 form-horizontal'
         )
     );
-    
+
     $form->addElement(
-        'text', 
-        'subject', 
-        get_lang('Subject'), 
+        'text',
+        'subject',
+        get_lang('Subject'),
         array(
-            'for' => 'subject', 
+            'for' => 'subject',
             'value' => $subject,
             'style' => 'width: 540px;'
         )
     );
-    
+
     $form->addElement('hidden', 'ticket_id', $_GET['ticket_id']);
-    
+
     $form->add_html_editor(
-        'content', 
+        'content',
         get_lang('Message'),
-        false, 
-        false, 
+        false,
+        false,
         array(
-            'ToolbarSet' => 'Profile', 
-            'Width' => '550', 
+            'ToolbarSet' => 'Profile',
+            'Width' => '550',
             'Height' => '250'
         )
     );
-    
+
     if ($isAdmin) {
         $form->addElement(
             'checkbox',
@@ -434,29 +434,29 @@ function show_form_send_message()
             $plugin->get_lang('RequestConfirmation')
         );
     }
-    
+
     $form->addElement('html', '<span id="filepaths">');
     $form->addElement('html', '<div id="filepath_1">');
     $form->addElement('file', 'attach_1', get_lang('FilesAttachment'));
     $form->addElement('html', '</div>');
     $form->addElement('html', '</span>');
-    
+
     $form->addElement('html', '<div class="controls">');
     $form->addElement('html', '<span id="link-more-attach" >');
     $form->addElement('html', '<span class="label label-info" onclick="return add_image_form()">' . get_lang('AddOneMoreFile') . '</span>');
     $form->addElement('html', '</span>');
     $form->addElement('html', '(' . sprintf(get_lang('MaximunFileSizeX'), format_file_size(api_get_setting('message_max_upload_filesize'))) . ')');
-    
+
     $form->addElement('html', '<br/>');
     $form->addElement(
-        'button', 
-        'compose', 
-        get_lang('SendMessage'), 
+        'button',
+        'compose',
+        get_lang('SendMessage'),
         array(
             'class' => 'save'
         )
     );
-    
+
     $form->display();
 }