Browse Source

Merge remote-tracking branch 'angel/9089' into B9070

Conflicts:
	main/gradebook/gradebook_display_certificate.php
Angel Fernando Quiroz Campos 10 years ago
parent
commit
1348e30521
37 changed files with 2324 additions and 937 deletions
  1. 3 0
      .gitignore
  2. 12 0
      main/admin/course_add.php
  3. 31 9
      main/admin/course_edit.php
  4. 275 0
      main/admin/course_fields.php
  5. 74 0
      main/admin/export_certificates.php
  6. 5 0
      main/admin/index.php
  7. 70 0
      main/admin/resume_session.php
  8. 311 354
      main/admin/session_add.php
  9. 293 326
      main/admin/session_edit.php
  10. 204 0
      main/admin/session_fields.php
  11. 14 5
      main/coursecopy/classes/CourseArchiver.class.php
  12. 37 7
      main/coursecopy/classes/CourseCopyLearnpath.class.php
  13. 2 1
      main/coursecopy/classes/CourseCopyTestCategory.php
  14. 7 4
      main/coursecopy/classes/CourseDescription.class.php
  15. 53 45
      main/gradebook/gradebook_display_certificate.php
  16. 88 6
      main/gradebook/lib/be/category.class.php
  17. 1 1
      main/gradebook/lib/fe/displaygradebook.php
  18. 37 9
      main/gradebook/lib/gradebook_functions.inc.php
  19. 157 0
      main/inc/lib/CourseField.class.php
  20. 8 0
      main/inc/lib/CourseFieldOption.class.php
  21. 11 0
      main/inc/lib/CourseFieldValue.class.php
  22. 105 0
      main/inc/lib/SessionField.class.php
  23. 8 0
      main/inc/lib/SessionFieldOption.class.php
  24. 11 0
      main/inc/lib/SessionFieldValue.class.php
  25. 6 0
      main/inc/lib/autoload.class.php
  26. 6 1
      main/inc/lib/course.lib.php
  27. 2 0
      main/inc/lib/database.constants.inc.php
  28. 162 151
      main/inc/lib/extra_field.lib.php
  29. 1 1
      main/inc/lib/extra_field_option.lib.php
  30. 70 7
      main/inc/lib/extra_field_value.lib.php
  31. 30 0
      main/inc/lib/formvalidator/Element/Number.class.php
  32. 1 0
      main/inc/lib/formvalidator/FormValidator.class.php
  33. 15 2
      main/inc/lib/sessionmanager.lib.php
  34. 55 7
      main/inc/lib/usermanager.lib.php
  35. 2 0
      main/install/configuration.dist.php
  36. 1 1
      main/install/db_main.sql
  37. 156 0
      tests/scripts/insert_session_fields.php

+ 3 - 0
.gitignore

@@ -35,3 +35,6 @@ searchdb/*
 nbproject/*
 
 plugin/bbb/config.vm.php
+
+# Extrafields files
+main/upload/extrafields/*

+ 12 - 0
main/admin/course_add.php

@@ -116,6 +116,18 @@ $form->addRule('disk_quota', get_lang('ThisFieldShouldBeNumeric'), 'numeric');
 $obj = new GradeModel();
 $obj->fill_grade_model_select_in_form($form);
 
+//Extra fields
+$extra_field = new CourseField();
+$extra = $extra_field->addElements($form);
+
+$htmlHeadXtra[] ='
+<script>
+
+$(function() {
+    '.$extra['jquery_ready_content'].'
+});
+</script>';
+
 $form->add_progress_bar();
 $form->addElement('style_submit_button', 'submit', get_lang('CreateCourse'), 'class="add"');
 

+ 31 - 9
main/admin/course_edit.php

@@ -16,6 +16,8 @@ api_protect_admin_script();
 require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(LIBRARY_PATH).'course_category.lib.php';
 
+$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/jquery.fcbkcomplete.js" type="text/javascript" language="javascript"></script>';
+
 $course_table       = Database::get_main_table(TABLE_MAIN_COURSE);
 $course_user_table  = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 
@@ -227,17 +229,37 @@ $form->addRule('disk_quota', get_lang('ThisFieldShouldBeNumeric'), 'numeric');
 
 $list_course_extra_field = CourseManager::get_course_extra_field_list($course_code);
 
-//@todo this is wrong
-foreach ($list_course_extra_field as $extra_field) {
-    switch ($extra_field['field_type']) {
-        case CourseManager::COURSE_FIELD_TYPE_CHECKBOX:
-            $checked = (array_key_exists('extra_field_value', $extra_field) && $extra_field['extra_field_value'] == 1)? array('checked'=>'checked'): '';
-            $form->addElement('hidden', '_extra_'.$extra_field['field_variable'], 0);
-            $field_display_text = $extra_field['field_display_text'];
-            $form->addElement('checkbox', 'extra_'.$extra_field['field_variable'], array(null, get_lang('AllUsersAreAutomaticallyRegistered')), get_lang('SpecialCourse'), $checked);
-            break;
+$specialCourseField = new CourseField();
+$specialCourseFieldInfo = $specialCourseField->get_handler_field_info_by_field_variable('special_course');
+
+if (!empty($specialCourseFieldInfo)) {
+    $specialCourseValue = new CourseFieldValue();
+    $specialCourseValueInfo = $specialCourseValue->get_values_by_handler_and_field_variable($course_code, 'special_course');
+
+    $specialCourseAttributes = array();
+
+    if (!empty($specialCourseValueInfo) && $specialCourseValueInfo['field_value'] == 1) {
+        $specialCourseAttributes['checked'] = '';
     }
+
+    $form->addElement('hidden', '_extra_special_course', 0);
+    $form->addElement('checkbox', 'extra_special_course', array(
+        null, get_lang('AllUsersAreAutomaticallyRegistered')
+    ), get_lang('SpecialCourse'), $specialCourseAttributes);
 }
+
+//Extra fields
+$extra_field = new CourseField();
+$extra = $extra_field->addElements($form, $course_code);
+
+$htmlHeadXtra[] ='
+<script>
+
+$(function() {
+    '.$extra['jquery_ready_content'].'
+});
+</script>';
+
 $form->addElement('style_submit_button', 'button', get_lang('ModifyCourseInfo'), 'onclick="valide()"; class="save"');
 
 // Set some default values

+ 275 - 0
main/admin/course_fields.php

@@ -0,0 +1,275 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+/**
+ *  @package chamilo.admin
+ */
+// Language files that need to be included.
+$language_file = array('admin');
+
+$cidReset = true;
+require_once '../inc/global.inc.php';
+
+$this_section = SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script();
+
+//Add the JS needed to use the jqgrid
+$htmlHeadXtra[] = api_get_jqgrid_js();
+
+// setting breadcrumbs
+$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+
+$action = isset($_GET['action']) ? $_GET['action'] : null;
+
+$check = Security::check_token('request');
+$token = Security::get_token();
+
+if ($action == 'add') {
+    $interbreadcrumb[] = array('url' => 'course_fields.php', 'name' => get_lang('CourseFields'));
+    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('Add'));
+} elseif ($action == 'edit') {
+    $interbreadcrumb[] = array('url' => 'course_fields.php', 'name' => get_lang('CourseFields'));
+    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('Edit'));
+} else {
+    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('CourseFields'));
+}
+
+//jqgrid will use this URL to do the selects
+$url = api_get_path(WEB_AJAX_PATH) . 'model.ajax.php?a=get_extra_fields&type=course';
+
+//The order is important you need to check the the $column variable in the model.ajax.php file 
+$columns = array(
+    get_lang('Name'),
+    get_lang('FieldLabel'),
+    get_lang('Type'),
+    get_lang('FieldChangeability'),
+    get_lang('Visibility'),
+    get_lang('Filter'),
+    get_lang('FieldOrder'),
+    get_lang('Actions')
+);
+
+//Column config
+$column_model = array(
+    array(
+        'name' => 'field_display_text',
+        'index' => 'field_display_text',
+        'width' => '180',
+        'align' => 'left'
+    ),
+    array(
+        'name' => 'field_variable',
+        'index' => 'field_variable',
+        'width' => '',
+        'align' => 'left',
+        'sortable' => 'true'
+    ),
+    array(
+        'name' => 'field_type',
+        'index' => 'field_type',
+        'width' => '',
+        'align' => 'left',
+        'sortable' => 'true'
+    ),
+    array(
+        'name' => 'field_changeable',
+        'index' => 'field_changeable',
+        'width' => '50',
+        'align' => 'left',
+        'sortable' => 'true'
+    ),
+    array(
+        'name' => 'field_visible',
+        'index' => 'field_visible',
+        'width' => '40',
+        'align' => 'left',
+        'sortable' => 'true'
+    ),
+    array(
+        'name' => 'field_filter',
+        'index' => 'field_filter',
+        'width' => '30',
+        'align' => 'left',
+        'sortable' => 'true'
+    ),
+    array(
+        'name' => 'field_order',
+        'index' => 'field_order',
+        'width' => '40',
+        'align' => 'left',
+        'sortable' => 'true'
+    ),
+    array(
+        'name' => 'actions',
+        'index' => 'actions',
+        'width' => '100',
+        'align' => 'left',
+        'formatter' => 'action_formatter',
+        'sortable' => 'false'
+    )
+);
+
+//Autowidth             
+$extra_params['autowidth'] = 'true';
+//height auto 
+$extra_params['height'] = 'auto';
+$extra_params['sortname'] = 'field_order';
+
+//With this function we can add actions to the jgrid (edit, delete, etc)
+$actionLinks = '
+function action_formatter(cellvalue, options, rowObject) {
+    return \'<a href="?action=edit&id=\'+options.rowId+\'">'
+    . Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL) . '</a>'
+    . ' <a onclick="javascript:if(!confirm(' . "\'"
+    . addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES)) . "\'"
+    . ')); return false;"  href="?sec_token=' . $token
+    . '&action=delete&id=\'+options.rowId+\'">'
+    . Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a>\'; 
+}';
+
+$htmlHeadXtra[] = '
+<script>
+$(function() {
+    // grid definition see the $obj->display() function
+    ' . Display::grid_js('course_fields', $url, $columns, $column_model, $extra_params, array(), $actionLinks, true) . '
+
+    $("#field_type").on("change", function() {      
+        id = $(this).val();        
+        switch(id) {
+            case "1":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_text.png')) . '"); 
+                break;
+            case "2":        
+                $("#example").html("' . addslashes(Display::return_icon('userfield_text_area.png')) . '"); 
+                break;
+            case "3":     
+                $("#example").html("' . addslashes(Display::return_icon('add_user_field_howto.png')) . '");            
+                break;
+            case "4":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_drop_down.png')) . '");
+                break;
+            case "5":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_multidropdown.png')) . '");
+                break;
+            case "6":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_data.png')) . '");
+                break;
+            case "7":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_date_time.png')) . '");
+                break;
+            case "8":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_doubleselect.png')) . '");
+                break;
+            case "9":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_divider.png')) . '");
+                break;
+            case "10":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_user_tag.png')) . '");
+                break;
+            case "11":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_data.png')) . '");                                            
+                break;
+        }
+    });
+
+    var value = 1;
+    $("#advanced_parameters").on("click", function() {
+        $("#options").toggle(function() {        
+            if (value == 1) {
+                $("#advanced_parameters").addClass("btn-hide");        
+                value = 0;
+            } else {
+                $("#advanced_parameters").removeClass("btn-hide");      
+                value = 1;
+            }
+        });
+    });
+});
+</script>';
+
+// The header.
+Display::display_header(null);
+
+$obj = new CourseField();
+
+// Action handling: Add
+switch ($action) {
+    case 'add':
+        if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
+            api_not_allowed();
+        }
+
+        $url = api_get_self() . '?action=' . Security::remove_XSS($_GET['action']);
+        $form = $obj->return_form($url, 'add');
+
+        // The validation or display
+        if ($form->validate()) {
+            if ($check) {
+                $values = $form->exportValues();
+                $res = $obj->save($values);
+
+                if ($res) {
+                    Display::display_confirmation_message(get_lang('ItemAdded'));
+                }
+            }
+
+            $obj->display();
+        } else {
+            echo '<div class="actions">';
+            echo '<a href="' . api_get_self() . '">' . Display::return_icon('back.png', get_lang('Back'), '',
+                ICON_SIZE_MEDIUM) . '</a>';
+            echo '</div>';
+
+            $form->addElement('hidden', 'sec_token');
+            $form->setConstants(array('sec_token' => $token));
+            $form->display();
+        }
+        break;
+    case 'edit':
+        // Action handling: Editing 
+        $url = api_get_self() . '?action=' . Security::remove_XSS($_GET['action']) . '&id=' . intval($_GET['id']);
+        $form = $obj->return_form($url, 'edit');
+
+        // The validation or display
+        if ($form->validate()) {
+            if ($check) {
+                $values = $form->exportValues();
+                $res = $obj->update($values);
+
+                Display::display_confirmation_message(
+                    sprintf(get_lang('ItemUpdated'), $values['field_display_text']),
+                    false
+                );
+            }
+            $obj->display();
+        } else {
+            echo '<div class="actions">';
+            echo '<a href="' . api_get_self() . '">';
+            echo Display::return_icon('back.png', get_lang('Back'), '', ICON_SIZE_MEDIUM);
+            echo '</a>';
+            echo '</div>';
+
+            $form->addElement('hidden', 'sec_token');
+            $form->setConstants(array('sec_token' => $token));
+            $form->display();
+        }
+        break;
+    case 'delete':
+        // Action handling: delete
+        if ($check) {
+            $res = $obj->delete($_GET['id']);
+
+            if ($res) {
+                Display::display_confirmation_message(get_lang('ItemDeleted'));
+            }
+        }
+
+        $obj->display();
+        break;
+    default:
+        $obj->display();
+        break;
+}
+
+Display :: display_footer();

+ 74 - 0
main/admin/export_certificates.php

@@ -0,0 +1,74 @@
+<?php
+
+/* For licensing terms, see /license.txt */
+
+/**
+ *  @package chamilo.admin
+ */
+
+// Language files that need to be included.
+$language_file = array('admin');
+
+$cidReset = true;
+
+require_once '../inc/global.inc.php';
+
+require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be.inc.php';
+require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
+
+Display::display_header(null);
+
+$form = new FormValidator('export_certificate');
+$courses = CourseManager::get_courses_list(0, 0, 'title');
+$options = array();
+foreach ($courses as $course) {
+    $options[$course['id']] = $course['title'];
+}
+$form->addElement('select', 'course', get_lang('Course'), $options);
+$form->addElement('file', 'file', get_lang('File'));
+$form->add_button('submit', get_lang('Submit'));
+$form->display();
+
+if ($form->validate()) {
+    $values = $form->getSubmitValues();
+    if (isset($_FILES['file']['tmp_name']) &&
+        !empty($_FILES['file']['tmp_name'])
+    ) {
+
+        $users = Import::csv_reader($_FILES['file']['tmp_name']);
+        $courseId = $values['course'];
+        $courseInfo = api_get_course_info_by_id($courseId);
+        $courseCode = $courseInfo['code'];
+
+        $cats = Category:: load(
+            null,
+            null,
+            $courseCode,
+            null,
+            null,
+            0,
+            false
+        );
+
+        if (isset($cats[0])) {
+            /** @var Category $cat */
+            $userList = array();
+            foreach ($users as $user) {
+                $userInfo = api_get_user_info_from_official_code(
+                    $user['official_code']
+                );
+                if (!empty($userInfo)) {
+                    $userList[] = $userInfo;
+                }
+            }
+
+            Category::exportAllCertificates(
+                $cat->get_id(),
+                $userList
+            );
+        }
+    }
+
+}
+
+Display :: display_footer();

+ 5 - 0
main/admin/index.php

@@ -140,6 +140,9 @@ if (api_is_platform_admin()) {
     if (isset($extAuthSource) && isset($extAuthSource['ldap']) && count($extAuthSource['ldap']) > 0) {
         $items[] = array('url'=>'ldap_import_students.php', 'label' => get_lang('ImportLDAPUsersIntoCourse'));
     }
+
+    $items[] = array('url'=>'course_fields.php', 	'label' => get_lang('ManageCourseFields'));
+
     $blocks['courses']['items'] = $items;
     $blocks['courses']['extra'] = null;
 
@@ -220,6 +223,8 @@ if (api_is_platform_admin()) {
     $items[] = array('url'=>'career_dashboard.php', 	'label' => get_lang('CareersAndPromotions'));
 }
 
+$items[] = array('url'=>'session_fields.php', 	'label' => get_lang('ManageSessionFields'));
+
 $blocks['sessions']['items'] = $items;
 $blocks['sessions']['extra'] = null;
 

+ 70 - 0
main/admin/resume_session.php

@@ -217,6 +217,76 @@ echo Display::page_subheader(get_lang('GeneralProperties').$url);
 </tr>
 
 <?php
+$sessionField = new SessionField();
+$sessionFields = $sessionField->get_all();
+
+foreach ($sessionFields as $field) {
+    if ($field['field_visible'] != '1') {
+        continue;
+    }
+
+    $sesionFieldValue = new SessionFieldValue();
+    $sesionValueData = $sesionFieldValue->get_values_by_handler_and_field_id($sessionId, $field['id'], true);
+    ?>
+        <tr>
+            <td><?php echo $field['field_display_text'] ?></td>
+            <td>
+                <?php
+                switch ($field['field_type']) {
+                    case ExtraField::FIELD_TYPE_CHECKBOX:
+                        if ($sesionValueData !== false && $sesionValueData['field_value'] == '1') {
+                            echo get_lang('Yes');
+                        } else {
+                            echo get_lang('No');
+                        }
+                        break;
+                    case ExtraField::FIELD_TYPE_DATE:
+                        if ($sesionValueData !== false && !empty($sesionValueData['field_value'])) {
+                            echo api_format_date($sesionValueData['field_value'], DATE_FORMAT_LONG_NO_DAY);
+                        } else {
+                            echo get_lang('None');
+                        }
+                        break;
+                    case ExtraField::FIELD_TYPE_FILE_IMAGE:
+                        if ($sesionValueData !== false && !empty($sesionValueData['field_value'])) {
+                            if (file_exists(api_get_path(SYS_CODE_PATH) . $sesionValueData['field_value'])) {
+                                $image = Display::img(
+                                    api_get_path(WEB_CODE_PATH) . $sesionValueData['field_value'],
+                                    $field['field_display_text'],
+                                    array('width' => '300')
+                                );
+                                
+                                echo Display::url(
+                                    $image,
+                                    api_get_path(WEB_CODE_PATH) . $sesionValueData['field_value'],
+                                    array('target' => '_blank')
+                                );
+                            }
+                        }
+                        break;
+                    case ExtraField::FIELD_TYPE_FILE:
+                        if ($sesionValueData !== false && !empty($sesionValueData['field_value'])) {
+                            if (file_exists(api_get_path(SYS_CODE_PATH) . $sesionValueData['field_value'])) {
+                                echo Display::url(
+                                    get_lang('Download'),
+                                    api_get_path(WEB_CODE_PATH) . $sesionValueData['field_value'],
+                                    array(
+                                        'title' => $field['field_display_text'],
+                                        'target' => '_blank'
+                                    )
+                                );
+                            }
+                        }
+                        break;
+                    default:
+                        echo $sesionValueData['field_value'];
+                        break;
+                }
+                ?>
+            </td>
+        </tr>
+    <?php
+}
 
 $multiple_url_is_on = api_get_multiple_access_url();
 

+ 311 - 354
main/admin/session_add.php

@@ -3,7 +3,6 @@
 
 /**
 *	@package chamilo.admin
-* 	@todo use formvalidator for the form, remove all the select harcoded values
 */
 
 // name of the language file that needs to be included
@@ -86,361 +85,27 @@ $xajax -> processRequests();
 
 $htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
 
-$htmlHeadXtra[] = '
-<script type="text/javascript">
+$htmlHeadXtra[] = "
+<script type=\"text/javascript\">
 function fill_coach_field (username) {
-	document.getElementById("coach_username").value = username;
-	document.getElementById("ajax_list_coachs").innerHTML = "";
+	document.getElementById('coach_username').value = username;
+	document.getElementById('ajax_list_coachs').innerHTML = '';
 }
-</script>';
-
-
-if (isset($_POST['formSent']) && $_POST['formSent']) {
-	$formSent = 1;
-    $name = $_POST['name'];
-    $year_start = $_POST['year_start'];
-    $month_start = $_POST['month_start'];
-    $day_start = $_POST['day_start'];
-    $year_end = $_POST['year_end'];
-    $month_end = $_POST['month_end'];
-    $day_end = $_POST['day_end'];
-    $nb_days_acess_before = $_POST['nb_days_acess_before'];
-    $nb_days_acess_after = $_POST['nb_days_acess_after'];
-    $coach_username = $_POST['coach_username'];
-    $id_session_category = $_POST['session_category'];
-    $id_visibility = $_POST['session_visibility'];
-    $end_limit = $_POST['end_limit'];
-    $start_limit = $_POST['start_limit'];
-    $duration = isset($_POST['duration']) ? $_POST['duration'] : null;
-
-    if (empty($end_limit) && empty($start_limit)) {
-        $nolimit = 1;
-    } else {
-    	$nolimit = null;
-    }
-
-    $return = SessionManager::create_session(
-        $name,
-        $year_start,
-        $month_start,
-        $day_start,
-        $year_end,
-        $month_end,
-        $day_end,
-        $nb_days_acess_before,
-        $nb_days_acess_after,
-        $nolimit,
-        $coach_username,
-        $id_session_category,
-        $id_visibility,
-        $start_limit,
-        $end_limit,
-        $duration
-    );
-
-	if ($return == strval(intval($return))) {
-		// integer => no error on session creation
-		header('Location: add_courses_to_session.php?id_session='.$return.'&add=true&msg=');
-		exit();
-	}
-}
-
-global $_configuration;
-$defaultBeforeDays = isset($_configuration['session_days_before_coach_access']) ?
-    $_configuration['session_days_before_coach_access'] : 0;
-$defaultAfterDays = isset($_configuration['session_days_after_coach_access'])
-    ? $_configuration['session_days_after_coach_access'] : 0;
-
-$nb_days_acess_before = $defaultBeforeDays;
-$nb_days_acess_after = $defaultAfterDays;
 
-$thisYear=date('Y');
-$thisMonth=date('m');
-$thisDay=date('d');
-
-$tool_name = get_lang('AddSession');
-
-Display::display_header($tool_name);
-
-if (!empty($return)) {
-	Display::display_error_message($return,false);
-}
-echo '<div class="actions">';
-echo '<a href="../admin/index.php">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('PlatformAdmin'),'',ICON_SIZE_MEDIUM).'</a>';
-echo '</div>';
-
-?>
-<form class="form-horizontal" method="post" name="form" action="<?php echo api_get_self(); ?>" style="margin:0px;">
-    <input type="hidden" name="formSent" value="1">
-    <div class="control-group">
-        <label class="control-label">
-            <?php echo get_lang('SessionName') ?>
-        </label>
-        <div class="controls">
-            <input type="text" name="name" class="span4" maxlength="50" value="<?php if($formSent) echo api_htmlentities($name,ENT_QUOTES,$charset); ?>">
-        </div>
-    </div>
-
-    <div class="control-group">
-        <label class="control-label">
-            <?php echo get_lang('CoachName') ?>
-        </label>
-        <div class="controls">
-
-<?php
-
-$sql = 'SELECT COUNT(1) FROM '.$tbl_user.' WHERE status=1';
-$rs = Database::query($sql);
-$count_users = Database::result($rs, 0, 0);
-
-if (intval($count_users)<50) {
-	$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-	$sql="SELECT user_id, lastname,firstname,username FROM $tbl_user WHERE status='1'".$order_clause;
-
-	if (api_is_multiple_url_enabled()) {
-		$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-		$access_url_id = api_get_current_access_url_id();
-		if ($access_url_id != -1){
-			$sql = 'SELECT user.user_id, username, lastname, firstname FROM '.$tbl_user.' user
-			INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
-			WHERE access_url_id = '.$access_url_id.'  AND status=1'.$order_clause;
-		}
-	}
-	$result = Database::query($sql);
-	$Coaches = Database::store_result($result);
-
-	?>
-	<select id="coach_username" class="chzn-select" name="coach_username" style="width:350px;" title="<?php echo get_lang('Select'); ?>" >
-		<option value="0"><?php get_lang('None'); ?></option>
-		<?php foreach($Coaches as $enreg): ?>
-		<option value="<?php echo $enreg['username']; ?>"> <?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
-		<?php endforeach; ?>
-	</select>
-	<?php
-	echo Display::return_icon('synthese_view.gif',get_lang('ActivityCoach'));
-} else {
-	?>
-	<input type="text" name="coach_username" id="coach_username" onkeyup="xajax_search_coachs(document.getElementById('coach_username').value)" /><div id="ajax_list_coachs"></div>
-	<?php
-}
-$Categories = SessionManager::get_all_session_category();
-?>
-        </div>
-    </div>
-    <div class="control-group">
-        <label class="control-label">
-            <?php echo get_lang('SessionCategory') ?>
-        </label>
-        <div class="controls">
-            <select id="session_category" class="chzn-select" name="session_category" style="width:350px;" title="<?php echo get_lang('Select'); ?>">
-                <option value="0"><?php get_lang('None'); ?></option>
-            <?php
-            if (!empty($Categories)) {
-                foreach($Categories as $Rows) { ?>
-                    <option value="<?php echo $Rows['id']; ?>" <?php if($Rows['id'] == $id_session_category) echo 'selected="selected"'; ?>><?php echo $Rows['name']; ?></option>
-                <?php }
+$(document).on('ready', function () {
+    var value = 1;
+    $('#advanced_parameters').on('click', function() {
+        $('#options').toggle(function() {
+            if (value == 1) {
+                $('#advanced_parameters').addClass('btn-hide');
+                value = 0;
+            } else {
+                $('#advanced_parameters').removeClass('btn-hide');
+                value = 1;
             }
-            ?>
-        </select>
-        </div>
-    </div>
-
- <div class="control-group">
-        <div class="controls">
-            <a href="javascript://" onclick="if(document.getElementById('options').style.display == 'none'){document.getElementById('options').style.display = 'block';}else{document.getElementById('options').style.display = 'none';}"><?php echo get_lang('DefineSessionOptions') ?></a>
-        <div style="display: <?php if($formSent && ($nb_days_acess_before!=0 || $nb_days_acess_after!=0)) echo 'block'; else echo 'none'; ?>;" id="options">
-            <br />
-            <input type="text" name="nb_days_acess_before" value="<?php echo $nb_days_acess_before; ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysBefore') ?><br /><br />
-            <input type="text" name="nb_days_acess_after" value="<?php echo $nb_days_acess_after; ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysAfter') ?>
-            <br />
-        </div>
-        </div>
-</div>
-
- <div class="control-group">
-        <div class="controls">
-    <label for="start_limit">
-        <input id="start_limit" type="checkbox" name="start_limit" onchange="disable_starttime(this)" />
-    <?php echo get_lang('DateStartSession');?>
-    </label>
-
-    <div id="start_date" style="display:none">
-       <br />
-
-  <select name="day_start">
-	<option value="1">01</option>
-	<option value="2" <?php if((!$formSent && $thisDay == 2) || ($formSent && $day_start == 2)) echo 'selected="selected"'; ?> >02</option>
-	<option value="3" <?php if((!$formSent && $thisDay == 3) || ($formSent && $day_start == 3)) echo 'selected="selected"'; ?> >03</option>
-	<option value="4" <?php if((!$formSent && $thisDay == 4) || ($formSent && $day_start == 4)) echo 'selected="selected"'; ?> >04</option>
-	<option value="5" <?php if((!$formSent && $thisDay == 5) || ($formSent && $day_start == 5)) echo 'selected="selected"'; ?> >05</option>
-	<option value="6" <?php if((!$formSent && $thisDay == 6) || ($formSent && $day_start == 6)) echo 'selected="selected"'; ?> >06</option>
-	<option value="7" <?php if((!$formSent && $thisDay == 7) || ($formSent && $day_start == 7)) echo 'selected="selected"'; ?> >07</option>
-	<option value="8" <?php if((!$formSent && $thisDay == 8) || ($formSent && $day_start == 8)) echo 'selected="selected"'; ?> >08</option>
-	<option value="9" <?php if((!$formSent && $thisDay == 9) || ($formSent && $day_start == 9)) echo 'selected="selected"'; ?> >09</option>
-	<option value="10" <?php if((!$formSent && $thisDay == 10) || ($formSent && $day_start == 10)) echo 'selected="selected"'; ?> >10</option>
-	<option value="11" <?php if((!$formSent && $thisDay == 11) || ($formSent && $day_start == 11)) echo 'selected="selected"'; ?> >11</option>
-	<option value="12" <?php if((!$formSent && $thisDay == 12) || ($formSent && $day_start == 12)) echo 'selected="selected"'; ?> >12</option>
-	<option value="13" <?php if((!$formSent && $thisDay == 13) || ($formSent && $day_start == 13)) echo 'selected="selected"'; ?> >13</option>
-	<option value="14" <?php if((!$formSent && $thisDay == 14) || ($formSent && $day_start == 14)) echo 'selected="selected"'; ?> >14</option>
-	<option value="15" <?php if((!$formSent && $thisDay == 15) || ($formSent && $day_start == 15)) echo 'selected="selected"'; ?> >15</option>
-	<option value="16" <?php if((!$formSent && $thisDay == 16) || ($formSent && $day_start == 16)) echo 'selected="selected"'; ?> >16</option>
-	<option value="17" <?php if((!$formSent && $thisDay == 17) || ($formSent && $day_start == 17)) echo 'selected="selected"'; ?> >17</option>
-	<option value="18" <?php if((!$formSent && $thisDay == 18) || ($formSent && $day_start == 18)) echo 'selected="selected"'; ?> >18</option>
-	<option value="19" <?php if((!$formSent && $thisDay == 19) || ($formSent && $day_start == 19)) echo 'selected="selected"'; ?> >19</option>
-	<option value="20" <?php if((!$formSent && $thisDay == 20) || ($formSent && $day_start == 20)) echo 'selected="selected"'; ?> >20</option>
-	<option value="21" <?php if((!$formSent && $thisDay == 21) || ($formSent && $day_start == 21)) echo 'selected="selected"'; ?> >21</option>
-	<option value="22" <?php if((!$formSent && $thisDay == 22) || ($formSent && $day_start == 22)) echo 'selected="selected"'; ?> >22</option>
-	<option value="23" <?php if((!$formSent && $thisDay == 23) || ($formSent && $day_start == 23)) echo 'selected="selected"'; ?> >23</option>
-	<option value="24" <?php if((!$formSent && $thisDay == 24) || ($formSent && $day_start == 24)) echo 'selected="selected"'; ?> >24</option>
-	<option value="25" <?php if((!$formSent && $thisDay == 25) || ($formSent && $day_start == 25)) echo 'selected="selected"'; ?> >25</option>
-	<option value="26" <?php if((!$formSent && $thisDay == 26) || ($formSent && $day_start == 26)) echo 'selected="selected"'; ?> >26</option>
-	<option value="27" <?php if((!$formSent && $thisDay == 27) || ($formSent && $day_start == 27)) echo 'selected="selected"'; ?> >27</option>
-	<option value="28" <?php if((!$formSent && $thisDay == 28) || ($formSent && $day_start == 28)) echo 'selected="selected"'; ?> >28</option>
-	<option value="29" <?php if((!$formSent && $thisDay == 29) || ($formSent && $day_start == 29)) echo 'selected="selected"'; ?> >29</option>
-	<option value="30" <?php if((!$formSent && $thisDay == 30) || ($formSent && $day_start == 30)) echo 'selected="selected"'; ?> >30</option>
-	<option value="31" <?php if((!$formSent && $thisDay == 31) || ($formSent && $day_start == 31)) echo 'selected="selected"'; ?> >31</option>
-  </select>
-  /
-  <select name="month_start">
-	<option value="1">01</option>
-	<option value="2" <?php if((!$formSent && $thisMonth == 2) || ($formSent && $month_start == 2)) echo 'selected="selected"'; ?> >02</option>
-	<option value="3" <?php if((!$formSent && $thisMonth == 3) || ($formSent && $month_start == 3)) echo 'selected="selected"'; ?> >03</option>
-	<option value="4" <?php if((!$formSent && $thisMonth == 4) || ($formSent && $month_start == 4)) echo 'selected="selected"'; ?> >04</option>
-	<option value="5" <?php if((!$formSent && $thisMonth == 5) || ($formSent && $month_start == 5)) echo 'selected="selected"'; ?> >05</option>
-	<option value="6" <?php if((!$formSent && $thisMonth == 6) || ($formSent && $month_start == 6)) echo 'selected="selected"'; ?> >06</option>
-	<option value="7" <?php if((!$formSent && $thisMonth == 7) || ($formSent && $month_start == 7)) echo 'selected="selected"'; ?> >07</option>
-	<option value="8" <?php if((!$formSent && $thisMonth == 8) || ($formSent && $month_start == 8)) echo 'selected="selected"'; ?> >08</option>
-	<option value="9" <?php if((!$formSent && $thisMonth == 9) || ($formSent && $month_start == 9)) echo 'selected="selected"'; ?> >09</option>
-	<option value="10" <?php if((!$formSent && $thisMonth == 10) || ($formSent && $month_start == 10)) echo 'selected="selected"'; ?> >10</option>
-	<option value="11" <?php if((!$formSent && $thisMonth == 11) || ($formSent && $month_start == 11)) echo 'selected="selected"'; ?> >11</option>
-	<option value="12" <?php if((!$formSent && $thisMonth == 12) || ($formSent && $month_start == 12)) echo 'selected="selected"'; ?> >12</option>
-  </select>
-  /
-  <select name="year_start">
-<?php
-for ($i=$thisYear-5;$i <= ($thisYear+5);$i++) {
-?>
-	<option value="<?php echo $i; ?>" <?php if((!$formSent && $thisYear == $i) || ($formSent && $year_start == $i)) echo 'selected="selected"'; ?> ><?php echo $i; ?></option>
-<?php
-}
-?>
-    </select>
-    </div>
-
-        </div>
-    </div>
-
-
-
- <div class="control-group">
-        <div class="controls">
-            <label for="end_limit">
-                <input id="end_limit" type="checkbox" name="end_limit" onchange="disable_endtime(this)" />
-                <?php echo get_lang('DateEndSession') ?>
-            </label>
-  <div id="end_date" style="display:none">
-  <br />
-
-  <select name="day_end">
-	<option value="1">01</option>
-	<option value="2" <?php if((!$formSent && $thisDay == 2) || ($formSent && $day_end == 2)) echo 'selected="selected"'; ?> >02</option>
-	<option value="3" <?php if((!$formSent && $thisDay == 3) || ($formSent && $day_end == 3)) echo 'selected="selected"'; ?> >03</option>
-	<option value="4" <?php if((!$formSent && $thisDay == 4) || ($formSent && $day_end == 4)) echo 'selected="selected"'; ?> >04</option>
-	<option value="5" <?php if((!$formSent && $thisDay == 5) || ($formSent && $day_end == 5)) echo 'selected="selected"'; ?> >05</option>
-	<option value="6" <?php if((!$formSent && $thisDay == 6) || ($formSent && $day_end == 6)) echo 'selected="selected"'; ?> >06</option>
-	<option value="7" <?php if((!$formSent && $thisDay == 7) || ($formSent && $day_end == 7)) echo 'selected="selected"'; ?> >07</option>
-	<option value="8" <?php if((!$formSent && $thisDay == 8) || ($formSent && $day_end == 8)) echo 'selected="selected"'; ?> >08</option>
-	<option value="9" <?php if((!$formSent && $thisDay == 9) || ($formSent && $day_end == 9)) echo 'selected="selected"'; ?> >09</option>
-	<option value="10" <?php if((!$formSent && $thisDay == 10) || ($formSent && $day_end == 10)) echo 'selected="selected"'; ?> >10</option>
-	<option value="11" <?php if((!$formSent && $thisDay == 11) || ($formSent && $day_end == 11)) echo 'selected="selected"'; ?> >11</option>
-	<option value="12" <?php if((!$formSent && $thisDay == 12) || ($formSent && $day_end == 12)) echo 'selected="selected"'; ?> >12</option>
-	<option value="13" <?php if((!$formSent && $thisDay == 13) || ($formSent && $day_end == 13)) echo 'selected="selected"'; ?> >13</option>
-	<option value="14" <?php if((!$formSent && $thisDay == 14) || ($formSent && $day_end == 14)) echo 'selected="selected"'; ?> >14</option>
-	<option value="15" <?php if((!$formSent && $thisDay == 15) || ($formSent && $day_end == 15)) echo 'selected="selected"'; ?> >15</option>
-	<option value="16" <?php if((!$formSent && $thisDay == 16) || ($formSent && $day_end == 16)) echo 'selected="selected"'; ?> >16</option>
-	<option value="17" <?php if((!$formSent && $thisDay == 17) || ($formSent && $day_end == 17)) echo 'selected="selected"'; ?> >17</option>
-	<option value="18" <?php if((!$formSent && $thisDay == 18) || ($formSent && $day_end == 18)) echo 'selected="selected"'; ?> >18</option>
-	<option value="19" <?php if((!$formSent && $thisDay == 19) || ($formSent && $day_end == 19)) echo 'selected="selected"'; ?> >19</option>
-	<option value="20" <?php if((!$formSent && $thisDay == 20) || ($formSent && $day_end == 20)) echo 'selected="selected"'; ?> >20</option>
-	<option value="21" <?php if((!$formSent && $thisDay == 21) || ($formSent && $day_end == 21)) echo 'selected="selected"'; ?> >21</option>
-	<option value="22" <?php if((!$formSent && $thisDay == 22) || ($formSent && $day_end == 22)) echo 'selected="selected"'; ?> >22</option>
-	<option value="23" <?php if((!$formSent && $thisDay == 23) || ($formSent && $day_end == 23)) echo 'selected="selected"'; ?> >23</option>
-	<option value="24" <?php if((!$formSent && $thisDay == 24) || ($formSent && $day_end == 24)) echo 'selected="selected"'; ?> >24</option>
-	<option value="25" <?php if((!$formSent && $thisDay == 25) || ($formSent && $day_end == 25)) echo 'selected="selected"'; ?> >25</option>
-	<option value="26" <?php if((!$formSent && $thisDay == 26) || ($formSent && $day_end == 26)) echo 'selected="selected"'; ?> >26</option>
-	<option value="27" <?php if((!$formSent && $thisDay == 27) || ($formSent && $day_end == 27)) echo 'selected="selected"'; ?> >27</option>
-	<option value="28" <?php if((!$formSent && $thisDay == 28) || ($formSent && $day_end == 28)) echo 'selected="selected"'; ?> >28</option>
-	<option value="29" <?php if((!$formSent && $thisDay == 29) || ($formSent && $day_end == 29)) echo 'selected="selected"'; ?> >29</option>
-	<option value="30" <?php if((!$formSent && $thisDay == 30) || ($formSent && $day_end == 30)) echo 'selected="selected"'; ?> >30</option>
-	<option value="31" <?php if((!$formSent && $thisDay == 31) || ($formSent && $day_end == 31)) echo 'selected="selected"'; ?> >31</option>
-  </select>
-  /
-  <select name="month_end">
-	<option value="1">01</option>
-	<option value="2" <?php if((!$formSent && $thisMonth == 2) || ($formSent && $month_end == 2)) echo 'selected="selected"'; ?> >02</option>
-	<option value="3" <?php if((!$formSent && $thisMonth == 3) || ($formSent && $month_end == 3)) echo 'selected="selected"'; ?> >03</option>
-	<option value="4" <?php if((!$formSent && $thisMonth == 4) || ($formSent && $month_end == 4)) echo 'selected="selected"'; ?> >04</option>
-	<option value="5" <?php if((!$formSent && $thisMonth == 5) || ($formSent && $month_end == 5)) echo 'selected="selected"'; ?> >05</option>
-	<option value="6" <?php if((!$formSent && $thisMonth == 6) || ($formSent && $month_end == 6)) echo 'selected="selected"'; ?> >06</option>
-	<option value="7" <?php if((!$formSent && $thisMonth == 7) || ($formSent && $month_end == 7)) echo 'selected="selected"'; ?> >07</option>
-	<option value="8" <?php if((!$formSent && $thisMonth == 8) || ($formSent && $month_end == 8)) echo 'selected="selected"'; ?> >08</option>
-	<option value="9" <?php if((!$formSent && $thisMonth == 9) || ($formSent && $month_end == 9)) echo 'selected="selected"'; ?> >09</option>
-	<option value="10" <?php if((!$formSent && $thisMonth == 10) || ($formSent && $month_end == 10)) echo 'selected="selected"'; ?> >10</option>
-	<option value="11" <?php if((!$formSent && $thisMonth == 11) || ($formSent && $month_end == 11)) echo 'selected="selected"'; ?> >11</option>
-	<option value="12" <?php if((!$formSent && $thisMonth == 12) || ($formSent && $month_end == 12)) echo 'selected="selected"'; ?> >12</option>
-  </select>
-  /
-  <select name="year_end">
-<?php
-for ($i=$thisYear-5;$i <= ($thisYear+5);$i++) {
-?>
-	<option value="<?php echo $i; ?>" <?php if((!$formSent && ($thisYear+1) == $i) || ($formSent && $year_end == $i)) echo 'selected="selected"'; ?> ><?php echo $i; ?></option>
-<?php
-}
-?>
-    </select>
-    <br />    <br />
-    <?php echo get_lang('SessionVisibility') ?>
-    <select name="session_visibility" style="width:250px;">
-        <?php
-        $visibility_list = array(
-            SESSION_VISIBLE_READ_ONLY => get_lang('SessionReadOnly'),
-            SESSION_VISIBLE => get_lang('SessionAccessible'),
-            SESSION_INVISIBLE => api_ucfirst(get_lang('SessionNotAccessible'))
-        );
-        foreach($visibility_list as $key=>$item): ?>
-        <option value="<?php echo $key; ?>"><?php echo $item; ?></option>
-        <?php endforeach; ?>
-    </select>
-     </div>
-        </div>
-    </div>
-
-    <?php
-    if (SessionManager::durationPerUserIsEnabled()) {
-        ?>
-        <div class="control-group">
-            <label class="control-label">
-                <?php echo get_lang('SessionDurationTitle') ?> <br />
-            </label>
-            <div class="controls">
-                <input id="duration" type="text" name="duration" class="span1" maxlength="50" value="">
-                <br />
-                <?php echo get_lang('SessionDurationDescription') ?>
-            </div>
-        </div>
-
-    <?php
-    }
-    ?>
-
- <div class="control-group">
-    <div class="controls">
-        <button class="save" type="submit" value="<?php echo get_lang('NextStep') ?>"><?php echo get_lang('NextStep') ?></button>
-    </div>
-</div>
-</form>
-<script type="text/javascript">
+        });
+    });
+});
 
 function setDisable(select){
 	document.form.day_start.disabled = (select.checked) ? true : false;
@@ -491,6 +156,298 @@ function emptyDuration() {
         $('#duration').val('');
     }
 }
-</script>
-<?php
+</script>";
+
+if (isset($_POST['formSent']) && $_POST['formSent']) {
+	$formSent = 1;
+}
+
+global $_configuration;
+$defaultBeforeDays = isset($_configuration['session_days_before_coach_access']) ?
+    $_configuration['session_days_before_coach_access'] : 0;
+$defaultAfterDays = isset($_configuration['session_days_after_coach_access'])
+    ? $_configuration['session_days_after_coach_access'] : 0;
+
+$nb_days_acess_before = $defaultBeforeDays;
+$nb_days_acess_after = $defaultAfterDays;
+
+$thisYear=date('Y');
+$thisMonth=date('m');
+$thisDay=date('d');
+
+$dayList = array();
+
+for ($i = 1; $i <= 31; $i++) {
+    $day = sprintf("%02d", $i);
+    $dayList[$day] = $day;
+}
+
+$monthList = array();
+
+for ($i = 1; $i <= 12; $i++) {
+    $month = sprintf("%02d", $i);
+    
+    $monthList[$month] = $month;
+}
+
+$yearList = array();
+
+for ($i = $thisYear - 5; $i <= ($thisYear + 5); $i++) {
+    $yearList[$i] = $i;
+}
+
+$tool_name = get_lang('AddSession');
+
+$urlAction = api_get_self();
+
+$categoriesList = SessionManager::get_all_session_category();
+
+$categoriesOptions = array(
+    '0' => get_lang('None')
+);
+
+if ($categoriesList != false) {
+    foreach ($categoriesList as $categoryItem) {
+        $categoriesOptions[$categoryItem['id']] = $categoryItem['name'];
+    }
+}
+
+function check_session_name($name) {
+    $session = SessionManager::get_session_by_name($name);
+
+    return empty($session) ? true : false;
+}
+
+$form = new FormValidator('add_session', 'post', $urlAction);
+
+$form->addElement('header', $tool_name);
+
+$form->addElement('text', 'name', get_lang('SessionName'), array(
+    'class' => 'span4',
+    'maxlength' => 50,
+    'value' => $formSent ? api_htmlentities($name,ENT_QUOTES,$charset) : ''
+));
+$form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('name', get_lang('SessionNameAlreadyExists'), 'callback', 'check_session_name');
+
+$sql = "SELECT COUNT(1) FROM $tbl_user WHERE status = 1";
+$rs = Database::query($sql);
+$countUsers = Database::result($rs, 0, 0);
+
+if (intval($countUsers) < 50) {
+    $orderClause = "ORDER BY ";
+    $orderClause .= api_sort_by_first_name() ? "firstname, lastname, username"  : "lastname, firstname, username";
+
+    $sql="SELECT user_id, lastname, firstname, username FROM $tbl_user "
+        . "WHERE status = '1' "
+        . $orderClause;
+
+    if (api_is_multiple_url_enabled()) {
+        $userRelAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+        $accessUrlId = api_get_current_access_url_id();
+        
+        if ($accessUrlId != -1) {
+            $sql = "SELECT user.user_id, username, lastname, firstname FROM $tbl_user user "
+                . "INNER JOIN $userRelAccessUrlTable url_user ON (url_user.user_id = user.user_id) "
+                . "WHERE access_url_id = $accessUrlId AND status = 1 "
+                . $orderClause;
+        }
+    }
+
+    $result = Database::query($sql);
+	$coachesList = Database::store_result($result);
+
+    $coachesOptions = array();
+
+    foreach($coachesList as $coachItem){
+        $coachesOptions[$coachItem['username']] = api_get_person_name(
+            $coachItem['firstname'],
+            $coachItem['lastname']
+        ).' ('.$coachItem['username'].')';
+    }
+
+    $form->addElement('select', 'coach_username', get_lang('CoachName'), $coachesOptions, array(
+        'id' => 'coach_username',
+        'class' => 'chzn-select',
+        'style' => 'width:350px;'
+    ));
+    $form->addElement('advanced_settings', Display::return_icon('synthese_view.gif') . ' ' . get_lang('ActivityCoach'));
+} else {
+    $form->addElement('text', 'coach_username', get_lang('CoachName'), array(
+        'class' => 'span4',
+        'maxlength' => 50,
+        'onkeyup' => "xajax_search_coachs(document.getElementById('coach_username').value)",
+        'id' => 'coach_username'
+    ));
+}
+
+$form->addRule('coach_username', get_lang('ThisFieldIsRequired'), 'required');
+$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;'
+));
+
+$form->addElement('advanced_settings','<a class="btn-show" id="advanced_parameters" href="javascript://">'.get_lang('DefineSessionOptions').'</a>');
+
+$form->addElement('html','<div id="options" style="display:none">');
+
+$form->addElement('text', 'nb_days_acess_before', array('', '', get_lang('DaysBefore')), array(
+    'style' => 'width: 30px;',
+    'value' => $nb_days_acess_before
+));
+
+$form->addElement('text', 'nb_days_acess_after', array('', '', get_lang('DaysAfter')), array(
+    'style' => 'width: 30px;',
+    'value' => $nb_days_acess_after
+));
+
+$form->addElement('html','</div>');
+
+$form->addElement('checkbox', 'start_limit', '', get_lang('DateStartSession'), array(
+    'onchange' => 'disable_starttime(this)',
+    'id' => 'start_limit'
+));
+
+$form->addElement('html','<div id="start_date" style="display:none">');
+
+$startDateGroup = array ();
+$startDateGroup[] = $form->createElement('select', 'day_start', null, $dayList);
+$startDateGroup[] = $form->createElement('select', 'month_start', null, $monthList);
+$startDateGroup[] = $form->createElement('select', 'year_start', null, $yearList);
+
+$form->addGroup($startDateGroup, 'start_date_group', null, ' / ', true);
+
+$form->addElement('html','</div>');
+
+$form->addElement('checkbox', 'end_limit', '', get_lang('DateEndSession'), array(
+    'onchange' => 'disable_endtime(this)',
+    'id' => 'end_limit'
+));
+
+$form->addElement('html','<div id="end_date" style="display:none">');
+
+$endDateGroup = array();
+$endDateGroup[] = $form->createElement('select', 'day_end', null, $dayList);
+$endDateGroup[] = $form->createElement('select', 'month_end', null, $monthList);
+$endDateGroup[] = $form->createElement('select', 'year_end', null, $yearList);
+
+$form->addGroup($endDateGroup, 'end_date_group', null, ' / ', true);
+
+$visibilityGroup = array();
+$visibilityGroup[] = $form->createElement('advanced_settings', get_lang('SessionVisibility'));
+$visibilityGroup[] = $form->createElement('select', 'session_visibility', null, array(
+    SESSION_VISIBLE_READ_ONLY => get_lang('SessionReadOnly'),
+    SESSION_VISIBLE => get_lang('SessionAccessible'),
+    SESSION_INVISIBLE => api_ucfirst(get_lang('SessionNotAccessible'))
+));
+
+$form->addGroup($visibilityGroup, 'visibility_group', null, null, false);
+
+$form->addElement('html','</div>');
+
+if (SessionManager::durationPerUserIsEnabled()) {
+    $form->addElement('text', 'duration', get_lang('SessionDurationTitle'),
+        array(
+        'class' => 'span1',
+        'maxlength' => 50
+    ));
+    $form->addElement('advanced_settings', get_lang('SessionDurationDescription'));
+}
+
+//Extra fields
+$extra_field = new ExtraField('session');
+$extra = $extra_field->addElements($form, null);
+
+$htmlHeadXtra[] ='
+<script>
+
+$(function() {
+    '.$extra['jquery_ready_content'].'
+});
+</script>';
+
+$form->addElement('button', 'submit', get_lang('NextStep'), array(
+    'class' => 'save'
+));
+
+$formDefaults = array(
+    'nb_days_acess_before' => $nb_days_acess_before,
+    'nb_days_acess_after' => $nb_days_acess_after
+);
+
+if (!$formSent) {
+    $formDefaults['start_date_group[day_start]'] = $thisDay;
+    $formDefaults['start_date_group[month_start]'] = $thisMonth;
+    $formDefaults['start_date_group[year_start]'] = $thisYear;
+
+    $formDefaults['end_date_group[day_end]'] = $thisDay;
+    $formDefaults['end_date_group[month_end]'] = $thisMonth;
+    $formDefaults['end_date_group[year_end]'] = $thisYear + 1;
+} else {
+    $formDefaults['name'] = api_htmlentities($name,ENT_QUOTES,$charset);
+}
+
+$form->setDefaults($formDefaults);
+
+if ($form->validate()) {
+    $params = $form->getSubmitValues();
+ 
+    $name = $params['name'];
+    $year_start = $params['start_date_group']['year_start'];
+    $month_start = $params['start_date_group']['month_start'];
+    $day_start = $params['start_date_group']['day_start'];
+    $year_end = $params['end_date_group']['year_end'];
+    $month_end = $params['end_date_group']['month_end'];
+    $day_end = $params['end_date_group']['day_end'];
+    $nb_days_acess_before = $params['nb_days_acess_before'];
+    $nb_days_acess_after = $params['nb_days_acess_after'];
+    $coach_username = $params['coach_username'];
+    $id_session_category = $params['session_category'];
+    $id_visibility = $params['session_visibility'];
+    $end_limit = isset($params['end_limit']) ? true : false;
+    $start_limit = isset($params['start_limit']) ? true : false;
+    $duration = isset($params['duration']) ? $params['duration'] : null;
+
+    if (empty($end_limit) && empty($start_limit)) {
+        $nolimit = 1;
+    } else {
+        $nolimit = null;
+    }
+
+    $extraFields = array();
+
+    foreach ($params as $key => $value) {
+        if (strpos($key, 'extra_') === 0) {
+            $extraFields[$key] = $value;
+        }
+    }
+
+    $return = SessionManager::create_session(
+        $name, $year_start, $month_start, $day_start, $year_end, $month_end, $day_end, $nb_days_acess_before,
+        $nb_days_acess_after, $nolimit, $coach_username, $id_session_category, $id_visibility, $start_limit,
+        $end_limit, false, $duration, $extraFields
+    );
+
+    if ($return == strval(intval($return))) {
+        // integer => no error on session creation
+        header('Location: add_courses_to_session.php?id_session=' . $return . '&add=true&msg=');
+        exit();
+    }
+}
+
+Display::display_header($tool_name);
+
+if (!empty($return)) {
+	Display::display_error_message($return,false);
+}
+
+echo '<div class="actions">';
+echo '<a href="../admin/index.php">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('PlatformAdmin'),'',ICON_SIZE_MEDIUM).'</a>';
+echo '</div>';
+
+$form->display();
+
 Display::display_footer();

+ 293 - 326
main/admin/session_edit.php

@@ -52,26 +52,275 @@ $end_year_disabled = $end_month_disabled = $end_day_disabled = '';
 
 if (isset($_POST['formSent']) && $_POST['formSent']) {
 	$formSent = 1;
+}
+
+$order_clause = 'ORDER BY ';
+$order_clause .= api_sort_by_first_name() ? 'firstname, lastname, username' : 'lastname, firstname, username';
+
+$sql="SELECT user_id,lastname,firstname,username FROM $tbl_user WHERE status='1'".$order_clause;
+
+if (api_is_multiple_url_enabled()) {
+	$table_access_url_rel_user= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+	$access_url_id = api_get_current_access_url_id();
+	if ($access_url_id != -1) {
+		$sql="SELECT DISTINCT u.user_id,lastname,firstname,username FROM $tbl_user u INNER JOIN $table_access_url_rel_user url_rel_user ON (url_rel_user.user_id = u.user_id)
+			  WHERE status='1' AND access_url_id = '$access_url_id' $order_clause";
+	}
+}
+
+$result     = Database::query($sql);
+$Coaches    = Database::store_result($result);
+$thisYear   = date('Y');
+
+$daysOption = array();
+
+for ($i = 1; $i <= 31; $i++) {
+    $day = sprintf("%02d", $i);
+    $daysOption[$day] = $day;
+}
+
+$monthsOption = array();
+
+for ($i = 1; $i <= 12; $i++) {
+    $month = sprintf("%02d", $i);
+    
+    $monthsOption[$month] = $month;
+}
+
+$yearsOption = array();
+
+for ($i = $thisYear - 5; $i <= ($thisYear + 5); $i++) {
+    $yearsOption[$i] = $i;
+}
+
+$coachesOption = array(
+    '' => '----- ' . get_lang('None') . ' -----'
+);
+
+foreach ($Coaches as $coach) {
+    $personName = api_get_person_name($coach['firstname'], $coach['lastname']);
+
+    $coachesOption[$coach['user_id']] = "$personName ({$coach['username']})";
+}
+
+$Categories = SessionManager::get_all_session_category();
+
+$categoriesOption = array(
+    '0' => get_lang('None')
+);
+
+if ($Categories != false) {
+    foreach ($categoriesList as $categoryItem) {
+        $categoriesOption[$categoryItem['id']] = $categoryItem['name'];
+    }
+}
+
+$formAction = api_get_self() . '?';
+$formAction .= http_build_query(array(
+    'page' => Security::remove_XSS($_GET['page']),
+    'id' => $id
+));
+
+$form = new FormValidator('edit_session', 'post', $formAction);
+
+$form->addElement('header', $tool_name);
+
+$form->addElement('text', 'name', get_lang('SessionName'), array(
+    'class' => 'span4',
+    'maxlength' => 50,
+    'value' => $formSent ? api_htmlentities($name,ENT_QUOTES,$charset) : ''
+));
+$form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('name', get_lang('SessionNameAlreadyExists'), 'callback', 'check_session_name');
+
+$form->addElement('select', 'id_coach', get_lang('CoachName'), $coachesOption, array(
+    'id' => 'coach_username',
+    'class' => 'chzn-select',
+    'style' => 'width:370px;',
+    'title' => get_lang('Choose')
+));
+$form->addRule('id_coach', get_lang('ThisFieldIsRequired'), 'required');
+
+$form->add_select('session_category', get_lang('SessionCategory'), $categoriesOption, array(
+    'id' => 'session_category',
+    'class' => 'chzn-select',
+    'style' => 'width:370px;'
+));
+
+$form->addElement('advanced_settings','<a class="btn-show" id="show-options" href="#">'.get_lang('DefineSessionOptions').'</a>');
+
+if ($infos['nb_days_access_before_beginning'] != 0 || $infos['nb_days_access_after_end'] != 0) {
+    $form->addElement('html','<div id="options" style="display:block;">');
+} else {
+    $form->addElement('html','<div id="options" style="display:none;">');
+}
+
+$form->addElement('text', 'nb_days_access_before', array('', '', get_lang('DaysBefore')), array(
+    'style' => 'width: 30px;'
+));
+
+$form->addElement('text', 'nb_days_access_after', array('', '', get_lang('DaysAfter')), array(
+    'style' => 'width: 30px;'
+));
+
+$form->addElement('html','</div>');
+
+if ($year_start!="0000") {
+    $form->addElement('checkbox', 'start_limit', '', get_lang('DateStartSession'), array(
+        'onchange' => 'disable_starttime(this)',
+        'id' => 'start_limit',
+        'checked' => ''
+    ));
+
+    $form->addElement('html','<div id="start_date" style="display:block">');
+} else {
+    $form->addElement('checkbox', 'start_limit', '', get_lang('DateStartSession'), array(
+        'onchange' => 'disable_starttime(this)',
+        'id' => 'start_limit'
+    ));
+
+    $form->addElement('html','<div id="start_date" style="display:none">');
+}
+
+$startDateGroup = array ();
+$startDateGroup[] = $form->createElement('select', 'day_start', null, $daysOption);
+$startDateGroup[] = $form->createElement('select', 'month_start', null, $monthsOption);
+$startDateGroup[] = $form->createElement('select', 'year_start', null, $yearsOption);
+
+$form->addGroup($startDateGroup, 'start_date_group', null, ' / ', true);
+
+$form->addElement('html','</div>');
+
+if ($year_end != "0000") {
+    $form->addElement('checkbox', 'end_limit', '', get_lang('DateEndSession'), array(
+        'onchange' => 'disable_endtime(this)',
+        'id' => 'end_limit',
+        'checked' => ''
+    ));
+
+    $form->addElement('html','<div id="end_date" style="display:block">');
+} else {
+    $form->addElement('checkbox', 'end_limit', '', get_lang('DateEndSession'), array(
+        'onchange' => 'disable_endtime(this)',
+        'id' => 'end_limit'
+    ));
 
-	$name                  = $_POST['name'];
-	$year_start            = $_POST['year_start'];
-	$month_start           = $_POST['month_start'];
-	$day_start             = $_POST['day_start'];
-	$year_end              = $_POST['year_end'];
-	$month_end             = $_POST['month_end'];
-	$day_end               = $_POST['day_end'];
-	$nb_days_acess_before  = $_POST['nb_days_access_before'];
-	$nb_days_acess_after   = $_POST['nb_days_access_after'];
-	//$nolimit               = $_POST['nolimit'];
-	$id_coach              = $_POST['id_coach'];
-	$id_session_category   = $_POST['session_category'];
-	$id_visibility         = $_POST['session_visibility'];
-    $duration = isset($_POST['duration']) ? $_POST['duration'] : null;
-    $description = isset($_POST['description']) ? $_POST['description'] : null;
-    $showDescription = isset($_POST['show_description']) ? 1 : 0;
-
-    $end_limit              = $_POST['end_limit'];
-    $start_limit            = $_POST['start_limit'];
+    $form->addElement('html','<div id="end_date" style="display:none">');
+}
+
+$endDateGroup = array();
+$endDateGroup[] = $form->createElement('select', 'day_end', null, $daysOption);
+$endDateGroup[] = $form->createElement('select', 'month_end', null, $monthsOption);
+$endDateGroup[] = $form->createElement('select', 'year_end', null, $yearsOption);
+
+$form->addGroup($endDateGroup, 'end_date_group', null, ' / ', true);
+
+$visibilityGroup = array();
+$visibilityGroup[] = $form->createElement('advanced_settings', get_lang('SessionVisibility'));
+$visibilityGroup[] = $form->createElement('select', 'session_visibility', null, array(
+    SESSION_VISIBLE_READ_ONLY => get_lang('SessionReadOnly'),
+    SESSION_VISIBLE => get_lang('SessionAccessible'),
+    SESSION_INVISIBLE => api_ucfirst(get_lang('SessionNotAccessible'))
+), array(
+    'style' => 'width:250px;'
+));
+
+$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();
+
+    if (!empty($showDescriptionChecked)) {
+        $chkDescriptionAttributes['checked'] = '';
+    }
+
+    $form->addElement('checkbox', 'show_description', null, get_lang('ShowDescription'), $chkDescriptionAttributes);
+}
+
+if (SessionManager::durationPerUserIsEnabled()) {
+    $duration = empty($infos['duration']) ? null : $infos['duration'];
+
+    $form->addElement('text', 'duration', get_lang('SessionDurationTitle'), array(
+        'class' => 'span1',
+        'maxlength' => 50
+    ));
+    $form->addElement('advanced_settings', get_lang('SessionDurationDescription'));
+}
+
+//Extra fields
+$extra_field = new ExtraField('session');
+$extra = $extra_field->addElements($form, $id);
+
+$htmlHeadXtra[] ='
+<script>
+
+$(function() {
+    '.$extra['jquery_ready_content'].'
+});
+</script>';
+
+$form->addElement('button', 'submit', get_lang('ModifyThisSession'), array(
+    'class' => 'save'
+));
+
+$formDefaults = array(
+    'id_coach' => $infos['id_coach'],
+    'session_category' => $infos['session_category_id'],
+    'start_date_group[day_start]' => $day_start,
+    'start_date_group[month_start]' => $month_start,
+    'start_date_group[year_start]' => $year_start,
+    'end_date_group[day_end]' => $day_end,
+    'end_date_group[month_end]' => $month_end,
+    'end_date_group[year_end]' => $year_end,
+    'session_visibility' => $infos['visibility'],
+    'description' => array_key_exists('show_description', $infos) ? $infos['description'] : ''
+);
+
+if ($formSent) {
+    $formDefaults['name'] = api_htmlentities($name,ENT_QUOTES,$charset);
+    $formDefaults['nb_days_access_before'] = api_htmlentities($nb_days_access_before,ENT_QUOTES,$charset);
+    $formDefaults['nb_days_access_after'] = api_htmlentities($nb_days_access_after,ENT_QUOTES,$charset);
+} else {
+    $formDefaults['name'] = api_htmlentities($infos['name'],ENT_QUOTES,$charset);
+    $formDefaults['nb_days_access_before'] = api_htmlentities($infos['nb_days_access_before_beginning'],ENT_QUOTES,$charset);
+    $formDefaults['nb_days_access_after'] = api_htmlentities($infos['nb_days_access_after_end'],ENT_QUOTES,$charset);
+}
+
+if (SessionManager::durationPerUserIsEnabled()) {
+    if ($formSent) {
+        $formDefaults['duration'] = Security::remove_XSS($duration);
+    } else {
+        $formDefaults['duration'] = $duration;
+    }
+}
+
+$form->setDefaults($formDefaults);
+
+if ($form->validate()) {
+    $params = $form->getSubmitValues();
+
+    $name = $params['name'];
+    $year_start = $params['start_date_group']['year_start'];
+    $month_start = $params['start_date_group']['month_start'];
+    $day_start = $params['start_date_group']['day_start'];
+    $year_end = $params['end_date_group']['year_end'];
+    $month_end = $params['end_date_group']['month_end'];
+    $day_end = $params['end_date_group']['day_end'];
+    $nb_days_acess_before = $params['nb_days_access_before'];
+    $nb_days_acess_after = $params['nb_days_acc ess_after'];
+    $id_coach = $params['id_coach'];
+    $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;
+    $showDescription = isset($params['show_description']) ? 1: 0;
+
+    $end_limit = $params['end_limit'];
+    $start_limit = $params['start_limit'];
 
     if (empty($end_limit) && empty($start_limit)) {
         $nolimit = 1;
@@ -79,7 +328,15 @@ if (isset($_POST['formSent']) && $_POST['formSent']) {
         $nolimit = null;
     }
 
-	$return = SessionManager::edit_session(
+    $extraFields = array();
+
+    foreach ($params as $key => $value) {
+        if (strpos($key, 'extra_') === 0) {
+            $extraFields[$key] = $value;
+        }
+    }
+
+    $return = SessionManager::edit_session(
         $id,
         $name,
         $year_start,
@@ -98,325 +355,25 @@ if (isset($_POST['formSent']) && $_POST['formSent']) {
         $end_limit,
         $description,
         $showDescription,
-        $duration
+        $duration,
+        $extraFields
     );
 
-	if ($return == strval(intval($return))) {
-		header('Location: resume_session.php?id_session='.$return);
+    if ($return == strval(intval($return))) {
+		header('Location: resume_session.php?id_session=' . $return);
 		exit();
 	}
 }
 
-$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-$sql="SELECT user_id,lastname,firstname,username FROM $tbl_user WHERE status='1'".$order_clause;
-
-if (api_is_multiple_url_enabled()) {
-	$table_access_url_rel_user= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-	$access_url_id = api_get_current_access_url_id();
-	if ($access_url_id != -1) {
-		$sql="SELECT DISTINCT u.user_id,lastname,firstname,username FROM $tbl_user u INNER JOIN $table_access_url_rel_user url_rel_user ON (url_rel_user.user_id = u.user_id)
-			  WHERE status='1' AND access_url_id = '$access_url_id' $order_clause";
-	}
-}
-
-$result     = Database::query($sql);
-$Coaches    = Database::store_result($result);
-$thisYear   = date('Y');
-
 // display the header
 Display::display_header($tool_name);
 
 if (!empty($return)) {
     Display::display_error_message($return,false);
 }
-?>
-
-<form class="form-horizontal" method="post" name="form" action="<?php echo api_get_self(); ?>?page=<?php echo Security::remove_XSS($_GET['page']) ?>&id=<?php echo $id; ?>" style="margin:0px;">
-<fieldset>
-    <legend><?php echo $tool_name; ?></legend>
-    <input type="hidden" name="formSent" value="1">
-
-    <div class="control-group">
-        <label class="control-label">
-            <?php echo get_lang('SessionName') ?>
-        </label>
-        <div class="controls">
-            <input type="text" name="name" class="span4" maxlength="50" value="<?php if($formSent) echo api_htmlentities($name,ENT_QUOTES,$charset); else echo api_htmlentities($infos['name'],ENT_QUOTES,$charset); ?>">
-        </div>
-    </div>
-    <div class="control-group">
-        <label class="control-label">
-            <?php echo get_lang('CoachName') ?>
-        </label>
-        <div class="controls">
-            <select class="chzn-select" name="id_coach" style="width:380px;" title="<?php echo get_lang('Choose'); ?>" >
-                <option value="">----- <?php echo get_lang('None') ?> -----</option>
-                <?php foreach($Coaches as $enreg) { ?>
-                <option value="<?php echo $enreg['user_id']; ?>" <?php if(($enreg['user_id'] == $infos['id_coach']) || ($enreg['user_id'] == $id_coach)) echo 'selected="selected"'; ?>><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
-                <?php
-                }
-                unset($Coaches);
-                $Categories = SessionManager::get_all_session_category();
-            ?>
-        </select>
-        </div>
-    </div>
-    <div class="control-group">
-        <label class="control-label">
-            <?php echo get_lang('SessionCategory') ?>
-        </label>
-        <div class="controls">
-                <select class="chzn-select" id="session_category" name="session_category" style="width:380px;" title="<?php echo get_lang('Select'); ?>">
-        <option value="0"><?php get_lang('None'); ?></option>
-        <?php
-          if (!empty($Categories)) {
-              foreach($Categories as $Rows)  { ?>
-                <option value="<?php echo $Rows['id']; ?>" <?php if($Rows['id'] == $infos['session_category_id']) echo 'selected="selected"'; ?>><?php echo $Rows['name']; ?></option>
-        <?php }
-          }
-         ?>
-    </select>
-        </div>
-    </div>
-    <div class="control-group">
-        <div class="controls">
-            <a href="javascript://" onclick="if(document.getElementById('options').style.display == 'none'){document.getElementById('options').style.display = 'block';}else{document.getElementById('options').style.display = 'none';}"><?php echo get_lang('DefineSessionOptions') ?></a>
-        </div>
-    </div>
-    <div class="control-group">
-        <div class="controls">
-            <div style="display:
-            <?php
-                if($formSent){
-                    if($nb_days_access_before!=0 || $nb_days_access_after!=0)
-                        echo 'block';
-                    else echo 'none';
-                }
-                else{
-                    if($infos['nb_days_access_before_beginning']!=0 || $infos['nb_days_access_after_end']!=0)
-                        echo 'block';
-                    else
-                        echo 'none';
-                }
-            ?>
-                ;" id="options">
-
-            <input type="text" name="nb_days_access_before" value="<?php if($formSent) echo api_htmlentities($nb_days_access_before,ENT_QUOTES,$charset); else echo api_htmlentities($infos['nb_days_access_before_beginning'],ENT_QUOTES,$charset); ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysBefore') ?>
-            <br />
-            <br />
-            <input type="text" name="nb_days_access_after" value="<?php if($formSent) echo api_htmlentities($nb_days_access_after,ENT_QUOTES,$charset); else echo api_htmlentities($infos['nb_days_access_after_end'],ENT_QUOTES,$charset); ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysAfter') ?>
-
-            </div>
-        </div>
-    </div>
-
-    <div class="clear"></div>
-    <div class="control-group">
-        <div class="controls">
-            <label for="start_limit">
-                <input id="start_limit" type="checkbox" name="start_limit" onchange="disable_starttime(this)" <?php if ($year_start!="0000") echo "checked"; ?>/>
-            <?php echo get_lang('DateStartSession');?>
-            </label>
-            <div id="start_date" style="<?php echo ($year_start=="0000") ? "display:none" : "display:block" ; ?>">
-            <br />
-              <select name="day_start">
-                <option value="1">01</option>
-                <option value="2" <?php if($day_start == 2) echo 'selected="selected"'; ?> >02</option>
-                <option value="3" <?php if($day_start == 3) echo 'selected="selected"'; ?> >03</option>
-                <option value="4" <?php if($day_start == 4) echo 'selected="selected"'; ?> >04</option>
-                <option value="5" <?php if($day_start == 5) echo 'selected="selected"'; ?> >05</option>
-                <option value="6" <?php if($day_start == 6) echo 'selected="selected"'; ?> >06</option>
-                <option value="7" <?php if($day_start == 7) echo 'selected="selected"'; ?> >07</option>
-                <option value="8" <?php if($day_start == 8) echo 'selected="selected"'; ?> >08</option>
-                <option value="9" <?php if($day_start == 9) echo 'selected="selected"'; ?> >09</option>
-                <option value="10" <?php if($day_start == 10) echo 'selected="selected"'; ?> >10</option>
-                <option value="11" <?php if($day_start == 11) echo 'selected="selected"'; ?> >11</option>
-                <option value="12" <?php if($day_start == 12) echo 'selected="selected"'; ?> >12</option>
-                <option value="13" <?php if($day_start == 13) echo 'selected="selected"'; ?> >13</option>
-                <option value="14" <?php if($day_start == 14) echo 'selected="selected"'; ?> >14</option>
-                <option value="15" <?php if($day_start == 15) echo 'selected="selected"'; ?> >15</option>
-                <option value="16" <?php if($day_start == 16) echo 'selected="selected"'; ?> >16</option>
-                <option value="17" <?php if($day_start == 17) echo 'selected="selected"'; ?> >17</option>
-                <option value="18" <?php if($day_start == 18) echo 'selected="selected"'; ?> >18</option>
-                <option value="19" <?php if($day_start == 19) echo 'selected="selected"'; ?> >19</option>
-                <option value="20" <?php if($day_start == 20) echo 'selected="selected"'; ?> >20</option>
-                <option value="21" <?php if($day_start == 21) echo 'selected="selected"'; ?> >21</option>
-                <option value="22" <?php if($day_start == 22) echo 'selected="selected"'; ?> >22</option>
-                <option value="23" <?php if($day_start == 23) echo 'selected="selected"'; ?> >23</option>
-                <option value="24" <?php if($day_start == 24) echo 'selected="selected"'; ?> >24</option>
-                <option value="25" <?php if($day_start == 25) echo 'selected="selected"'; ?> >25</option>
-                <option value="26" <?php if($day_start == 26) echo 'selected="selected"'; ?> >26</option>
-                <option value="27" <?php if($day_start == 27) echo 'selected="selected"'; ?> >27</option>
-                <option value="28" <?php if($day_start == 28) echo 'selected="selected"'; ?> >28</option>
-                <option value="29" <?php if($day_start == 29) echo 'selected="selected"'; ?> >29</option>
-                <option value="30" <?php if($day_start == 30) echo 'selected="selected"'; ?> >30</option>
-                <option value="31" <?php if($day_start == 31) echo 'selected="selected"'; ?> >31</option>
-              </select>
-              /
-              <select name="month_start">
-                <option value="1">01</option>
-                <option value="2" <?php if($month_start == 2) echo 'selected="selected"'; ?> >02</option>
-                <option value="3" <?php if($month_start == 3) echo 'selected="selected"'; ?> >03</option>
-                <option value="4" <?php if($month_start == 4) echo 'selected="selected"'; ?> >04</option>
-                <option value="5" <?php if($month_start == 5) echo 'selected="selected"'; ?> >05</option>
-                <option value="6" <?php if($month_start == 6) echo 'selected="selected"'; ?> >06</option>
-                <option value="7" <?php if($month_start == 7) echo 'selected="selected"'; ?> >07</option>
-                <option value="8" <?php if($month_start == 8) echo 'selected="selected"'; ?> >08</option>
-                <option value="9" <?php if($month_start == 9) echo 'selected="selected"'; ?> >09</option>
-                <option value="10" <?php if($month_start == 10) echo 'selected="selected"'; ?> >10</option>
-                <option value="11" <?php if($month_start == 11) echo 'selected="selected"'; ?> >11</option>
-                <option value="12" <?php if($month_start == 12) echo 'selected="selected"'; ?> >12</option>
-              </select>
-              /
-              <select name="year_start">
-
-            <?php
-            for($i=$thisYear-5;$i <= ($thisYear+5);$i++) { ?>
-                <option value="<?php echo $i; ?>" <?php if($year_start == $i) echo 'selected="selected"'; ?> ><?php echo $i; ?></option>
-            <?php
-            }
-            ?>
-              </select>
-          </div>
-        </div>
-    </div>
-
-    <div class="control-group">
-        <div class="controls">
-            <label for="end_limit">
-                <input id="end_limit" type="checkbox" name="end_limit" onchange="disable_endtime(this)" <?php if ($year_end!="0000") echo "checked"; ?>/>
-            <?php echo get_lang('DateEndSession') ?>
-            </label>
-          <div id="end_date" style="<?php echo ($year_end=="0000") ? "display:none" : "display:block" ; ?>">
-          <br />
-
-          <select name="day_end" <?php echo $end_day_disabled; ?> >
-        	<option value="1">01</option>
-        	<option value="2" <?php if($day_end == 2) echo 'selected="selected"'; ?> >02</option>
-        	<option value="3" <?php if($day_end == 3) echo 'selected="selected"'; ?> >03</option>
-        	<option value="4" <?php if($day_end == 4) echo 'selected="selected"'; ?> >04</option>
-        	<option value="5" <?php if($day_end == 5) echo 'selected="selected"'; ?> >05</option>
-        	<option value="6" <?php if($day_end == 6) echo 'selected="selected"'; ?> >06</option>
-        	<option value="7" <?php if($day_end == 7) echo 'selected="selected"'; ?> >07</option>
-        	<option value="8" <?php if($day_end == 8) echo 'selected="selected"'; ?> >08</option>
-        	<option value="9" <?php if($day_end == 9) echo 'selected="selected"'; ?> >09</option>
-        	<option value="10" <?php if($day_end == 10) echo 'selected="selected"'; ?> >10</option>
-        	<option value="11" <?php if($day_end == 11) echo 'selected="selected"'; ?> >11</option>
-        	<option value="12" <?php if($day_end == 12) echo 'selected="selected"'; ?> >12</option>
-        	<option value="13" <?php if($day_end == 13) echo 'selected="selected"'; ?> >13</option>
-        	<option value="14" <?php if($day_end == 14) echo 'selected="selected"'; ?> >14</option>
-        	<option value="15" <?php if($day_end == 15) echo 'selected="selected"'; ?> >15</option>
-        	<option value="16" <?php if($day_end == 16) echo 'selected="selected"'; ?> >16</option>
-        	<option value="17" <?php if($day_end == 17) echo 'selected="selected"'; ?> >17</option>
-        	<option value="18" <?php if($day_end == 18) echo 'selected="selected"'; ?> >18</option>
-        	<option value="19" <?php if($day_end == 19) echo 'selected="selected"'; ?> >19</option>
-        	<option value="20" <?php if($day_end == 20) echo 'selected="selected"'; ?> >20</option>
-        	<option value="21" <?php if($day_end == 21) echo 'selected="selected"'; ?> >21</option>
-        	<option value="22" <?php if($day_end == 22) echo 'selected="selected"'; ?> >22</option>
-        	<option value="23" <?php if($day_end == 23) echo 'selected="selected"'; ?> >23</option>
-        	<option value="24" <?php if($day_end == 24) echo 'selected="selected"'; ?> >24</option>
-        	<option value="25" <?php if($day_end == 25) echo 'selected="selected"'; ?> >25</option>
-        	<option value="26" <?php if($day_end == 26) echo 'selected="selected"'; ?> >26</option>
-        	<option value="27" <?php if($day_end == 27) echo 'selected="selected"'; ?> >27</option>
-        	<option value="28" <?php if($day_end == 28) echo 'selected="selected"'; ?> >28</option>
-        	<option value="29" <?php if($day_end == 29) echo 'selected="selected"'; ?> >29</option>
-        	<option value="30" <?php if($day_end == 30) echo 'selected="selected"'; ?> >30</option>
-        	<option value="31" <?php if($day_end == 31) echo 'selected="selected"'; ?> >31</option>
-          </select>
-          /
-          <select name="month_end" <?php echo $end_month_disabled; ?> >
-        	<option value="1">01</option>
-        	<option value="2" <?php if($month_end == 2) echo 'selected="selected"'; ?> >02</option>
-        	<option value="3" <?php if($month_end == 3) echo 'selected="selected"'; ?> >03</option>
-        	<option value="4" <?php if($month_end == 4) echo 'selected="selected"'; ?> >04</option>
-        	<option value="5" <?php if($month_end == 5) echo 'selected="selected"'; ?> >05</option>
-        	<option value="6" <?php if($month_end == 6) echo 'selected="selected"'; ?> >06</option>
-        	<option value="7" <?php if($month_end == 7) echo 'selected="selected"'; ?> >07</option>
-        	<option value="8" <?php if($month_end == 8) echo 'selected="selected"'; ?> >08</option>
-        	<option value="9" <?php if($month_end == 9) echo 'selected="selected"'; ?> >09</option>
-        	<option value="10" <?php if($month_end == 10) echo 'selected="selected"'; ?> >10</option>
-        	<option value="11" <?php if($month_end == 11) echo 'selected="selected"'; ?> >11</option>
-        	<option value="12" <?php if($month_end == 12) echo 'selected="selected"'; ?> >12</option>
-          </select>
-          /
-          <select name="year_end" <?php echo $end_year_disabled; ?>>
-
-        <?php
-        for($i=$thisYear-5;$i <= ($thisYear+5);$i++) {
-        ?>
-        	<option value="<?php echo $i; ?>" <?php if($year_end == $i) echo 'selected="selected"'; ?> ><?php echo $i; ?></option>
-        <?php
-        }
-        ?>
-          </select>
-           <br />      <br />
-
-            <?php echo get_lang('SessionVisibility') ?> <br />
-            <select name="session_visibility" style="width:250px;">
-                <?php
-                $visibility_list = array(
-                    SESSION_VISIBLE_READ_ONLY => get_lang('SessionReadOnly'),
-                    SESSION_VISIBLE => get_lang('SessionAccessible'),
-                    SESSION_INVISIBLE => api_ucfirst(get_lang('SessionNotAccessible'))
-                );
-                foreach($visibility_list as $key=>$item): ?>
-                <option value="<?php echo $key; ?>" <?php if($key == $infos['visibility']) echo 'selected="selected"'; ?>><?php echo $item; ?></option>
-                <?php endforeach; ?>
-            </select>
-    </div>
-    </div>
-  </div>
-
-    <?php if (array_key_exists('show_description', $infos)) { ?>
-
-        <div class="control-group">
-            <div class="controls">
-                <?php echo get_lang('Description') ?> <br />
-                <textarea name="description"><?php  echo $infos['description']; ?></textarea>
-            </div>
-        </div>
-
-        <div class="control-group">
-            <div class="controls">
-                <label>
-                <input id="show_description" type="checkbox" name="show_description" <?php echo $showDescriptionChecked ?> />
-                <?php echo get_lang('ShowDescription') ?>
-                </label>
-            </div>
-        </div>
-
-    <?php } ?>
-
-    <?php
-        if (SessionManager::durationPerUserIsEnabled()) {
-            if (empty($infos['duration'])) {
-                $duration = null;
-            } else {
-                $duration = $infos['duration'];
-            }
-            ?>
-            <div class="control-group">
-                <label class="control-label">
-                    <?php echo get_lang('SessionDurationTitle') ?> <br />
-                </label>
-                <div class="controls">
-                    <input id="duration" type="text" name="duration" class="span1" maxlength="50" value="<?php if($formSent) echo Security::remove_XSS($duration); else echo $duration; ?>">
-                    <br />
-                    <?php echo get_lang('SessionDurationDescription') ?>
-                </div>
-            </div>
-
-        <?php
-        }
-    ?>
 
-    <div class="control-group">
-        <div class="controls">
-            <button class="save" type="submit" value="<?php echo get_lang('ModifyThisSession') ?>"><?php echo get_lang('ModifyThisSession') ?></button>
-        </div>
-    </div>
-</fieldset>
-</form>
+$form->display();
+?>
 
 <script type="text/javascript">
 
@@ -473,6 +430,16 @@ function emptyDuration() {
     }
 }
 
+$(document).on('ready', function (){
+    $('#show-options').on('click', function (e) {
+        e.preventDefault();
+
+        var display = $('#options').css('display');
+
+        display === 'block' ? $('#options').slideUp() : $('#options').slideDown() ;
+    });
+});
+
 </script>
 <?php
 Display::display_footer();

+ 204 - 0
main/admin/session_fields.php

@@ -0,0 +1,204 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+/**
+ *  @package chamilo.admin
+ */
+// Language files that need to be included.
+$language_file = array('admin');
+
+$cidReset = true;
+require_once '../inc/global.inc.php';
+
+$this_section = SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script();
+
+//Add the JS needed to use the jqgrid
+$htmlHeadXtra[] = api_get_jqgrid_js();
+
+// setting breadcrumbs
+$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+
+$tool_name = null;
+
+$action = isset($_GET['action']) ? $_GET['action'] : null;
+
+$check = Security::check_token('request');
+$token = Security::get_token();
+
+if ($action == 'add') {
+    $interbreadcrumb[] = array('url' => 'session_fields.php', 'name' => get_lang('SessionFields'));
+    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('Add'));
+} elseif ($action == 'edit') {
+    $interbreadcrumb[] = array('url' => 'session_fields.php', 'name' => get_lang('SessionFields'));
+    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('Edit'));
+} else {
+    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('SessionFields'));
+}
+
+//jqgrid will use this URL to do the selects
+$url = api_get_path(WEB_AJAX_PATH) . 'model.ajax.php?a=get_extra_fields&type=session';
+
+//The order is important you need to check the the $column variable in the model.ajax.php file 
+$columns = array(get_lang('Name'), get_lang('FieldLabel'), get_lang('Type'), get_lang('FieldChangeability'), get_lang('Visibility'), get_lang('Filter'), get_lang('FieldOrder'), get_lang('Actions'));
+
+//Column config
+$column_model = array(
+    array('name' => 'field_display_text', 'index' => 'field_display_text', 'width' => '180', 'align' => 'left'),
+    array('name' => 'field_variable', 'index' => 'field_variable', 'width' => '', 'align' => 'left', 'sortable' => 'true'),
+    array('name' => 'field_type', 'index' => 'field_type', 'width' => '', 'align' => 'left', 'sortable' => 'true'),
+    array('name' => 'field_changeable', 'index' => 'field_changeable', 'width' => '50', 'align' => 'left', 'sortable' => 'true'),
+    array('name' => 'field_visible', 'index' => 'field_visible', 'width' => '40', 'align' => 'left', 'sortable' => 'true'),
+    array('name' => 'field_filter', 'index' => 'field_filter', 'width' => '30', 'align' => 'left', 'sortable' => 'true'),
+    array('name' => 'field_order', 'index' => 'field_order', 'width' => '40', 'align' => 'left', 'sortable' => 'true'),
+    array('name' => 'actions', 'index' => 'actions', 'width' => '100', 'align' => 'left', 'formatter' => 'action_formatter', 'sortable' => 'false')
+);
+
+//Autowidth             
+$extra_params['autowidth'] = 'true';
+//height auto 
+$extra_params['height'] = 'auto';
+$extra_params['sortname'] = 'field_order';
+
+//With this function we can add actions to the jgrid (edit, delete, etc)
+$action_links = 'function action_formatter(cellvalue, options, rowObject) {
+                         return \'<a href="?action=edit&id=\'+options.rowId+\'">' . Display::return_icon('edit.png',
+        get_lang('Edit'), '', ICON_SIZE_SMALL) . '</a>' .
+    '&nbsp;<a onclick="javascript:if(!confirm(' . "\'" . addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),
+            ENT_QUOTES)) . "\'" . ')) return false;"  href="?sec_token=' . $token . '&action=delete&id=\'+options.rowId+\'">' . Display::return_icon('delete.png',
+        get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a>' .
+    '\'; 
+                 }';
+$htmlHeadXtra[] = '
+<script>
+$(function() {
+    // grid definition see the $obj->display() function
+    ' . Display::grid_js('session_fields', $url, $columns, $column_model, $extra_params, array(), $action_links, true) . '
+            
+    $("#field_type").on("change", function() {      
+        id = $(this).val();        
+        switch(id) {
+            case "1":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_text.png')) . '"); 
+                break;
+            case "2":        
+                $("#example").html("' . addslashes(Display::return_icon('userfield_text_area.png')) . '"); 
+                break;
+            case "3":     
+                $("#example").html("' . addslashes(Display::return_icon('add_user_field_howto.png')) . '");            
+                break;
+            case "4":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_drop_down.png')) . '");
+                break;
+            case "5":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_multidropdown.png')) . '");
+                break;
+            case "6":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_data.png')) . '");
+                break;
+            case "7":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_date_time.png')) . '");
+                break;
+            case "8":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_doubleselect.png')) . '");
+                break;
+            case "9":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_divider.png')) . '");
+                break;
+            case "10":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_user_tag.png')) . '");
+                break;
+            case "11":
+                $("#example").html("' . addslashes(Display::return_icon('userfield_data.png')) . '");                                            
+                break;
+        }
+    });
+
+    var value = 1;
+    $("#advanced_parameters").on("click", function() {
+        $("#options").toggle(function() {        
+            if (value == 1) {
+                $("#advanced_parameters").addClass("btn-hide");        
+                value = 0;
+            } else {
+                $("#advanced_parameters").removeClass("btn-hide");      
+                value = 1;
+            }
+        });
+    });
+});
+</script>';
+
+// The header.
+Display::display_header($tool_name);
+
+$obj = new SessionField();
+
+// Action handling: Add
+switch ($action) {
+    case 'add':
+        if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
+            api_not_allowed();
+        }
+        $url = api_get_self() . '?action=' . Security::remove_XSS($_GET['action']);
+        $form = $obj->return_form($url, 'add');
+
+        // The validation or display
+        if ($form->validate()) {
+            if ($check) {
+                $values = $form->exportValues();
+                $res = $obj->save($values);
+                if ($res) {
+                    Display::display_confirmation_message(get_lang('ItemAdded'));
+                }
+            }
+            $obj->display();
+        } else {
+            echo '<div class="actions">';
+            echo '<a href="' . api_get_self() . '">' . Display::return_icon('back.png', get_lang('Back'), '',
+                ICON_SIZE_MEDIUM) . '</a>';
+            echo '</div>';
+            $form->addElement('hidden', 'sec_token');
+            $form->setConstants(array('sec_token' => $token));
+            $form->display();
+        }
+        break;
+    case 'edit':
+        // Action handling: Editing 
+        $url = api_get_self() . '?action=' . Security::remove_XSS($_GET['action']) . '&id=' . intval($_GET['id']);
+        $form = $obj->return_form($url, 'edit');
+
+        // The validation or display
+        if ($form->validate()) {
+            if ($check) {
+                $values = $form->exportValues();
+                $res = $obj->update($values);
+                Display::display_confirmation_message(sprintf(get_lang('ItemUpdated'), $values['field_display_text']), false);
+            }
+            $obj->display();
+        } else {
+            echo '<div class="actions">';
+            echo '<a href="' . api_get_self() . '">' . Display::return_icon('back.png', get_lang('Back'), '',
+                ICON_SIZE_MEDIUM) . '</a>';
+            echo '</div>';
+            $form->addElement('hidden', 'sec_token');
+            $form->setConstants(array('sec_token' => $token));
+            $form->display();
+        }
+        break;
+    case 'delete':
+        // Action handling: delete
+        if ($check) {
+            $res = $obj->delete($_GET['id']);
+            if ($res) {
+                Display::display_confirmation_message(get_lang('ItemDeleted'));
+            }
+        }
+        $obj->display();
+        break;
+    default:
+        $obj->display();
+        break;
+}
+Display :: display_footer();

+ 14 - 5
main/coursecopy/classes/CourseArchiver.class.php

@@ -1,5 +1,4 @@
 <?php
-
 /* For licensing terms, see /license.txt */
 
 require_once 'Course.class.php';
@@ -22,7 +21,10 @@ class CourseArchiver
         $dir = api_get_path(SYS_ARCHIVE_PATH);
         if ($handle = @ opendir($dir)) {
             while (($file = readdir($handle)) !== false) {
-                if ($file != "." && $file != ".." && strpos($file, 'CourseArchiver_') === 0 && is_dir($dir . '/' . $file)) {
+                if ($file != "." && $file != ".." &&
+                    strpos($file, 'CourseArchiver_') === 0 &&
+                    is_dir($dir . '/' . $file)
+                ) {
                     rmdirr($dir . '/' . $file);
                 }
             }
@@ -152,15 +154,20 @@ class CourseArchiver
                     $course_code = $file_parts[1];
                     $file_parts = explode('.', $file_parts[2]);
                     $date = $file_parts[0];
-                    $ext = $file_parts[1];
+                    $ext = isset($file_parts[1]) ? $file_parts[1] : null;
                     if ($ext == 'zip' && ($user_id != null && $owner_id == $user_id || $user_id == null)) {
                         $date = substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-' . substr($date, 6, 2) . ' ' . substr($date, 9, 2) . ':' . substr($date, 11, 2) . ':' . substr($date, 13, 2);
-                        $backup_files[] = array('file' => $file, 'date' => $date, 'course_code' => $course_code);
+                        $backup_files[] = array(
+                            'file' => $file,
+                            'date' => $date,
+                            'course_code' => $course_code
+                        );
                     }
                 }
             }
             closedir($dir);
         }
+
         return $backup_files;
     }
 
@@ -174,8 +181,10 @@ class CourseArchiver
         $new_dir = api_get_path(SYS_ARCHIVE_PATH);
         if (is_dir($new_dir) && is_writable($new_dir)) {
             move_uploaded_file($file, api_get_path(SYS_ARCHIVE_PATH).$new_filename);
+
             return $new_filename;
         }
+
         return false;
     }
 
@@ -218,7 +227,7 @@ class CourseArchiver
             return new Course();
         }
         $course->backup_path = $unzip_dir;
+
         return $course;
     }
-
 }

+ 37 - 7
main/coursecopy/classes/CourseCopyLearnpath.class.php

@@ -1,11 +1,13 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
- * A learnpath
+ * Class CourseCopyLearnpath
  * @author Bart Mollet <bart.mollet@hogent.be>
  * @package chamilo.backup
  */
-class CourseCopyLearnpath extends Resource {
+class CourseCopyLearnpath extends Resource
+{
 	/**
 	 * Type of learnpath (can be dokeos (1), scorm (2), aicc (3))
 	 */
@@ -106,9 +108,35 @@ class CourseCopyLearnpath extends Resource {
 	 * @param string $visibility
 	 * @param array  $items
 	 */
-	function CourseCopyLearnpath($id,$type,$name, $path,$ref,$description,$content_local,$default_encoding,$default_view_mode,$prevent_reinit,$force_commit,
-	                             $content_maker, $display_order,$js_lib,$content_license,$debug, $visibility, $author, $preview_image,
-	                             $use_max_score, $autolunch, $created_on, $modified_on, $publicated_on, $expired_on, $session_id, $items) {
+	public function CourseCopyLearnpath(
+		$id,
+		$type,
+		$name,
+		$path,
+		$ref,
+		$description,
+		$content_local,
+		$default_encoding,
+		$default_view_mode,
+		$prevent_reinit,
+		$force_commit,
+		$content_maker,
+		$display_order,
+		$js_lib,
+		$content_license,
+		$debug,
+		$visibility,
+		$author,
+		$preview_image,
+		$use_max_score,
+		$autolunch,
+		$created_on,
+		$modified_on,
+		$publicated_on,
+		$expired_on,
+		$session_id,
+		$items
+	) {
 		parent::Resource($id,RESOURCE_LEARNPATH);
 		$this->lp_type = $type;
 		$this->name = $name;
@@ -147,6 +175,7 @@ class CourseCopyLearnpath extends Resource {
 	{
 		return $this->items;
 	}
+
 	/**
 	 * Check if a given resource is used as an item in this chapter
 	 */
@@ -154,13 +183,14 @@ class CourseCopyLearnpath extends Resource {
 	{
 		foreach ($this->items as $item) {
 			if ($item['id'] == $resource->get_id() &&
-                isset($item['type']) && $item['type'] == $resource->get_type()
-            ) {
+				isset($item['type']) && $item['type'] == $resource->get_type()
+			) {
 				return true;
 			}
 		}
 		return false;
 	}
+
 	/**
 	 * Show this learnpath
 	 */

+ 2 - 1
main/coursecopy/classes/CourseCopyTestCategory.php

@@ -34,7 +34,8 @@ class CourseCopyTestcategory extends Resource
     /**
      * Show the test_category title, used in the partial recycle_course.php form
      */
-    function show() {
+    function show()
+    {
         parent::show();
         echo $this->title;
     }

+ 7 - 4
main/coursecopy/classes/CourseDescription.class.php

@@ -21,24 +21,27 @@ class CourseDescription extends Resource
 	/**
 	 * The description type
 	 */
-	var $description_type;	
+	var $description_type;
 	/**
 	 * Create a new course description
 	 * @param int $id
 	 * @param string $title
 	 * @param string $content
 	 */
-	function __construct($id,$title,$content,$description_type) {
+	function __construct($id,$title,$content,$description_type)
+	{
 		parent::Resource($id,RESOURCE_COURSEDESCRIPTION);
 		$this->title = $title;
 		$this->content = $content;
 		$this->description_type = $description_type;
 	}
+
 	/**
 	 * Show this Event
 	 */
-	function show() {
+	function show()
+	{
 		parent::show();
 		echo $this->title;
 	}
-}
+}

+ 53 - 45
main/gradebook/gradebook_display_certificate.php

@@ -35,36 +35,16 @@ if (!api_is_allowed_to_edit()) {
 
 $cat_id = isset($_GET['cat_id']) ? (int)$_GET['cat_id'] : null;
 $action = isset($_GET['action']) && $_GET['action'] ? $_GET['action'] : null;
+$filterOfficialCode = isset($_POST['filter']) ? Security::remove_XSS($_POST['filter']) : null;
+$filterOfficialCodeGet = isset($_GET['filter']) ? Security::remove_XSS($_GET['filter']) : null;
+
 switch ($action) {
     case 'export_all_certificates':
-        $params['orientation'] = 'landscape';
-        $params['left'] = 0;
-        $params['right'] = 0;
-        $params['top'] = 0;
-        $params['bottom'] = 0;
-        $page_format = $params['orientation'] == 'landscape' ? 'A4-L' : 'A4';
-        $pdf = new PDF($page_format, $params['orientation'], $params);
-
-        $certificate_list = get_list_users_certificates($cat_id);
-        $certificate_path_list = array();
-
-        if (!empty($certificate_list)) {
-            foreach ($certificate_list as $index=>$value) {
-                $list_certificate = get_list_gradebook_certificates_by_user_id($value['user_id'], $cat_id);
-                foreach ($list_certificate as $value_certificate) {
-                    $certificate_obj = new Certificate($value_certificate['id']);
-                    $certificate_obj->generate(array('hide_print_button' => true));
-                    if ($certificate_obj->html_file_is_generated()) {
-                        $certificate_path_list[]= $certificate_obj->html_file;
-                    }
-                }
-            }
-        }
-        if (!empty($certificate_path_list)) {
-            // Print certificates (without the common header/footer/watermark
-            //  stuff) and return as one multiple-pages PDF
-            $pdf->html_to_pdf($certificate_path_list, get_lang('Certificates'), null, false, false);
+        $userList = array();
+        if (!empty($filterOfficialCodeGet)) {
+            $userList = UserManager::getUsersByOfficialCode($filterOfficialCodeGet);
         }
+        Category::exportAllCertificates($cat_id, $userList);
         break;
     case 'generate_all_certificates':
         $user_list = CourseManager::get_user_list_from_course_code(api_get_course_id(), api_get_session_id());
@@ -79,23 +59,14 @@ switch ($action) {
         }
         break;
     case 'delete_all_certificates':
-        $certificate_list = get_list_users_certificates($cat_id);
-        if (!empty($certificate_list)) {
-            foreach ($certificate_list as $index=>$value) {
-                $list_certificate = get_list_gradebook_certificates_by_user_id($value['user_id'], $cat_id);
-                foreach ($list_certificate as $value_certificate) {
-                    $certificate_obj = new Certificate($value_certificate['id']);
-                    $certificate_obj->delete(true);
-                }
-            }
-        }
+        Category::deleteAllCertificates($cat_id);
         break;
 }
 
 $course_code = api_get_course_id();
 
-$interbreadcrumb[] = array ('url' => Security::remove_XSS($_SESSION['gradebook_dest']).'?',	'name' => get_lang('Gradebook'));
-$interbreadcrumb[] = array ('url' => '#','name' => get_lang('GradebookListOfStudentsCertificates'));
+$interbreadcrumb[] = array('url' => Security::remove_XSS($_SESSION['gradebook_dest']).'?',	'name' => get_lang('Gradebook'));
+$interbreadcrumb[] = array('url' => '#','name' => get_lang('GradebookListOfStudentsCertificates'));
 
 $this_section = SECTION_COURSES;
 
@@ -109,7 +80,7 @@ if (isset($_GET['action']) && $_GET['action'] == 'delete') {
         Security::clear_token();
         if ($result ==true) {
             Display::display_confirmation_message(get_lang('CertificateRemoved'));
-        } else  {
+        } else {
             Display::display_error_message(get_lang('CertificateNotRemoved'));
         }
     }
@@ -160,22 +131,59 @@ if (!empty($cats)) {
     }
 }
 
-$certificate_list = get_list_users_certificates($cat_id);
+$filter = api_get_configuration_value('certificate_filter_by_official_code');
+$userList = array();
+$filterForm = null;
+$certificate_list = array();
+if ($filter) {
+    echo '<br />';
+    $options = UserManager::getOfficialCodeGrouped();
+    $options =array_merge(array('all' => get_lang('All')), $options);
+    $form = new FormValidator(
+        'official_code_filter',
+        'POST',
+        api_get_self().'?'.api_get_cidreq().'&cat_id='.$cat_id
+    );
+    $form->addElement('select', 'filter', get_lang('OfficialCode'), $options);
+    $form->add_button('submit', get_lang('Submit'));
+    $filterForm = '<br />'.$form->return_form();
+
+    if ($form->validate()) {
+        $officialCode = $form->getSubmitValue('filter');
+         if ($officialCode == 'all') {
+            $certificate_list = get_list_users_certificates($cat_id);
+        } else {
+             $userList = UserManager::getUsersByOfficialCode($officialCode);
+             if (!empty($userList)) {
+                 $certificate_list = get_list_users_certificates(
+                     $cat_id,
+                     $userList
+                 );
+             }
+         }
+    } else {
+        $certificate_list = get_list_users_certificates($cat_id);
+    }
+} else {
+    $certificate_list = get_list_users_certificates($cat_id);
+}
 
 echo '<div class="btn-group">';
-$url = api_get_self().'?action=generate_all_certificates'.'&'.api_get_cidReq().'&cat_id='.$cat_id;
+$url = api_get_self().'?action=generate_all_certificates'.'&'.api_get_cidReq().'&cat_id='.$cat_id.'&filter='.$filterOfficialCode;
 echo Display::url(get_lang('GenerateCertificates'), $url, array('class' => 'btn'));
 
-$url = api_get_self().'?action=delete_all_certificates'.'&'.api_get_cidReq().'&cat_id='.$cat_id;
+$url = api_get_self().'?action=delete_all_certificates'.'&'.api_get_cidReq().'&cat_id='.$cat_id.'&filter='.$filterOfficialCode;
 echo Display::url(get_lang('DeleteAllCertificates'), $url, array('class' => 'btn'));
 
 if (count($certificate_list) > 0) {
-    $url = api_get_self().'?action=export_all_certificates'.'&'.api_get_cidReq().'&cat_id='.$cat_id;
+    $url = api_get_self().'?action=export_all_certificates'.'&'.api_get_cidReq().'&cat_id='.$cat_id.'&filter='.$filterOfficialCode;
     echo Display::url(get_lang('ExportAllCertificatesToPDF'), $url, array('class' => 'btn'));
 }
 echo '</div>';
 
-if (count($certificate_list)==0) {
+echo $filterForm;
+
+if (count($certificate_list) == 0 ) {
     echo Display::display_warning_message(get_lang('NoResultsAvailable'));
 } else {
 

+ 88 - 6
main/gradebook/lib/be/category.class.php

@@ -29,8 +29,6 @@ class Category implements GradebookItem
     {
     }
 
-    // GETTERS AND SETTERS
-
     public function get_id()
     {
         return $this->id;
@@ -1456,12 +1454,11 @@ class Category implements GradebookItem
     public function getCategories($catId)
     {
         $tblGradeCategories = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
-        $courseInfo = api_get_course_info(api_get_course_id());
-        $courseCode = $courseInfo['code'];
         $sql='SELECT * FROM '.$tblGradeCategories.' WHERE parent_id = '.intval($catId);
 
         $result = Database::query($sql);
         $allcats = Category::create_category_objects_from_sql_result($result);
+
         return $allcats;
     }
 
@@ -1614,10 +1611,17 @@ class Category implements GradebookItem
         // A student always sees only the teacher's repartition
         $scoretotal_display = $scoredisplay->display_score($scoretotal, SCORE_DIV_PERCENT);
 
-        if (isset($certificate_min_score) && $item_total_value >= $certificate_min_score) {
+        if (isset($certificate_min_score) &&
+            $item_total_value >= $certificate_min_score
+        ) {
             $my_certificate = get_certificate_by_user_id($cats_course[0]->get_id(), $user_id);
             if (empty($my_certificate)) {
-                register_user_info_about_certificate($category_id, $user_id, $my_score_in_gradebook, api_get_utc_datetime());
+                register_user_info_about_certificate(
+                    $category_id,
+                    $user_id,
+                    $my_score_in_gradebook,
+                    api_get_utc_datetime()
+                );
                 $my_certificate = get_certificate_by_user_id($cats_course[0]->get_id(), $user_id);
             }
             $html = array();
@@ -1656,4 +1660,82 @@ class Category implements GradebookItem
             return false;
         }
     }
+
+    /**
+     * @param int $catId
+     * @param array $userList
+     */
+    public static function generateCertificatesInUserList($catId, $userList)
+    {
+        if (!empty($userList)) {
+            foreach ($userList as $userInfo) {
+                self::register_user_certificate($catId, $userInfo['user_id']);
+            }
+        }
+    }
+
+    /**
+     * @param int $catId
+     * @param array $userList
+     */
+    public static function exportAllCertificates(
+        $catId,
+        $userList = array()
+    ) {
+        $params['orientation'] = 'landscape';
+        $params['left'] = 0;
+        $params['right'] = 0;
+        $params['top'] = 0;
+        $params['bottom'] = 0;
+        $page_format = $params['orientation'] == 'landscape' ? 'A4-L' : 'A4';
+        $pdf = new PDF($page_format, $params['orientation'], $params);
+
+        $certificate_list = get_list_users_certificates($catId, $userList);
+        $certificate_path_list = array();
+
+        if (!empty($certificate_list)) {
+            foreach ($certificate_list as $index=>$value) {
+                $list_certificate = get_list_gradebook_certificates_by_user_id(
+                    $value['user_id'],
+                    $catId
+                );
+                foreach ($list_certificate as $value_certificate) {
+                    $certificate_obj = new Certificate($value_certificate['id']);
+                    $certificate_obj->generate(array('hide_print_button' => true));
+                    if ($certificate_obj->html_file_is_generated()) {
+                        $certificate_path_list[]= $certificate_obj->html_file;
+                    }
+                }
+            }
+        }
+
+        if (!empty($certificate_path_list)) {
+            // Print certificates (without the common header/footer/watermark
+            //  stuff) and return as one multiple-pages PDF
+            $pdf->html_to_pdf(
+                $certificate_path_list,
+                get_lang('Certificates'),
+                null,
+                false,
+                false
+            );
+        }
+    }
+
+    /**
+     * @param int $catId
+     */
+    public static function deleteAllCertificates($catId)
+    {
+        $certificate_list = get_list_users_certificates($catId);
+        if (!empty($certificate_list)) {
+            foreach ($certificate_list as $index=>$value) {
+                $list_certificate = get_list_gradebook_certificates_by_user_id($value['user_id'], $catId);
+                foreach ($list_certificate as $value_certificate) {
+                    $certificate_obj = new Certificate($value_certificate['id']);
+                    $certificate_obj->delete(true);
+                }
+            }
+        }
+    }
 }

+ 1 - 1
main/gradebook/lib/fe/displaygradebook.php

@@ -455,7 +455,7 @@ class DisplayGradebook
                 if (!empty($certificateLinkInfo) && isset($certificateLinkInfo['certificate_link'])) {
                     $certificateLink .= '<span style="float:right"> ' . $certificateLinkInfo['certificate_link']."</span>";
                 }
-                $scoreinfo .= '<h2>' . get_lang('Total') . ' : ' . $scorecourse_display . $certificateLink. '</h2>';
+                $scoreinfo .= '<h3>' . get_lang('Total') . ' : ' . $scorecourse_display . $certificateLink. '</h3>';
 
             }
             Display :: display_normal_message($scoreinfo, false);

+ 37 - 9
main/gradebook/lib/gradebook_functions.inc.php

@@ -224,14 +224,14 @@ function build_edit_icons_cat($cat, $selectcat)
                 if ($cat->is_locked()) {
                     if (api_is_platform_admin()) {
                         $modify_icons .= '&nbsp;<a onclick="javascript:if (!confirm(\'' . addslashes(get_lang('ConfirmToUnlockElement')) . '\')) return false;" href="' . api_get_self() . '?' . api_get_cidreq() . '&category_id=' . $cat->get_id() . '&action=unlock">' .
-                                Display::return_icon('lock.png', get_lang('UnLockEvaluation'), '', ICON_SIZE_SMALL) . '</a>';
+                            Display::return_icon('lock.png', get_lang('UnLockEvaluation'), '', ICON_SIZE_SMALL) . '</a>';
                     } else {
                         $modify_icons .= '&nbsp;<a href="#">' . Display::return_icon('lock_na.png', get_lang('GradebookLockedAlert'), '', ICON_SIZE_SMALL) . '</a>';
                     }
                     $modify_icons .= '&nbsp;<a href="gradebook_flatview.php?export_pdf=category&selectcat=' . $cat->get_id() . '" >' . Display::return_icon('pdf.png', get_lang('ExportToPDF'), '', ICON_SIZE_SMALL) . '</a>';
                 } else {
                     $modify_icons .= '&nbsp;<a onclick="javascript:if (!confirm(\'' . addslashes(get_lang('ConfirmToLockElement')) . '\')) return false;" href="' . api_get_self() . '?' . api_get_cidreq() . '&category_id=' . $cat->get_id() . '&action=lock">' .
-                            Display::return_icon('unlock.png', get_lang('LockEvaluation'), '', ICON_SIZE_SMALL) . '</a>';
+                        Display::return_icon('unlock.png', get_lang('LockEvaluation'), '', ICON_SIZE_SMALL) . '</a>';
                     $modify_icons .= '&nbsp;<a href="#" >' . Display::return_icon('pdf_na.png', get_lang('ExportToPDF'), '', ICON_SIZE_SMALL) . '</a>';
                     //$modify_icons .= '&nbsp;<a href="gradebook_flatview.php?export_pdf=category&selectcat=' . $cat->get_id() . '" >'.Display::return_icon('pdf.png', get_lang('ExportToPDF'),'',ICON_SIZE_SMALL).'</a>';
                 }
@@ -363,7 +363,7 @@ function build_edit_icons_link($link, $selectcat)
             $modify_icons = Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
         } else {
             $modify_icons = '<a href="gradebook_edit_link.php?editlink=' . $link->get_id() . '&amp;cidReq=' . $link->get_course_code() . '">' .
-                    Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
+                Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
         }
 
         //$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?movelink=' . $link->get_id() . '&selectcat=' . $selectcat . '"><img src="../img/deplacer_fichier.gif" border="0" title="' . get_lang('Move') . '" alt="" /></a>';
@@ -617,8 +617,8 @@ function register_user_info_about_certificate($cat_id, $user_id, $score_certific
 
 /**
  * Get date of user certificate
- * @param int The category id
- * @param int The user id
+ * @param int $cat_id The category id
+ * @param int $user_id The user id
  * @return Datetime The date when you obtained the certificate
  */
 function get_certificate_by_user_id($cat_id, $user_id)
@@ -633,10 +633,11 @@ function get_certificate_by_user_id($cat_id, $user_id)
 
 /**
  * Get list of users certificates
- * @param int The category id
+ * @param int $cat_id The category id
+ * @param array $userList Only users in this list
  * @return array
  */
-function get_list_users_certificates($cat_id = null)
+function get_list_users_certificates($cat_id = null, $userList = array())
 {
     $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
     $table_user = Database::get_main_table(TABLE_MAIN_USER);
@@ -646,19 +647,26 @@ function get_list_users_certificates($cat_id = null)
     if (!is_null($cat_id) && $cat_id > 0) {
         $sql.=' WHERE cat_id=' . Database::escape_string($cat_id);
     }
+    if (!empty($userList)) {
+        $userList = array_map('intval', $userList);
+        $userListCondition = implode("','", $userList);
+        $sql .= " AND u.user_id IN ('$userListCondition')";
+    }
     $sql.=' ORDER BY u.firstname';
     $rs = Database::query($sql);
+
     $list_users = array();
     while ($row = Database::fetch_array($rs)) {
         $list_users[] = $row;
     }
+
     return $list_users;
 }
 
 /**
  * Gets the certificate list by user id
- * @param int The user id
- * @param int The category id
+ * @param int $user_id The user id
+ * @param int $cat_id The category id
  * @return array
  */
 function get_list_gradebook_certificates_by_user_id($user_id, $cat_id = null)
@@ -679,6 +687,13 @@ function get_list_gradebook_certificates_by_user_id($user_id, $cat_id = null)
     return $list_certificate;
 }
 
+/**
+ * @param $user_id
+ * @param $course_code
+ * @param bool $is_preview
+ * @param bool $hide_print_button
+ * @return array
+ */
 function get_user_certificate_content($user_id, $course_code, $is_preview = false, $hide_print_button = false)
 {
     // Generate document HTML
@@ -719,6 +734,11 @@ function get_user_certificate_content($user_id, $course_code, $is_preview = fals
     );
 }
 
+/**
+ * @param null $course_code
+ * @param int $gradebook_model_id
+ * @return mixed
+ */
 function create_default_course_gradebook($course_code = null, $gradebook_model_id = 0)
 {
     if (api_is_allowed_to_edit(true, true)) {
@@ -767,9 +787,13 @@ function create_default_course_gradebook($course_code = null, $gradebook_model_i
             $category_id = $row['id'];
         }
     }
+
     return $category_id;
 }
 
+/**
+ * @param FormValidator $form
+ */
 function load_gradebook_select_in_tool($form)
 {
     $course_code = api_get_course_id();
@@ -924,6 +948,10 @@ function export_pdf_flatview($flatviewtable, $cat, $users, $alleval, $alllinks,
     exit;
 }
 
+/**
+ * @param array $list_values
+ * @return string
+ */
 function score_badges($list_values)
 {
     $counter = 1;

+ 157 - 0
main/inc/lib/CourseField.class.php

@@ -0,0 +1,157 @@
+<?php
+
+/* For licensing terms, see /license.txt */
+
+class CourseField extends ExtraField {
+
+    const SPECIAL_COURSE_FIELD = 'special_course';
+
+    public function __construct() {
+        parent::__construct('course');
+    }
+
+    function display() {
+        // action links
+        echo '<div class="actions">';
+        echo '<a href="../admin/index.php">' . Display::return_icon('back.png', get_lang('BackTo') . ' ' . get_lang('PlatformAdmin'), '', ICON_SIZE_MEDIUM) . '</a>';
+        echo '<a href="' . api_get_self() . '?action=add">' . Display::return_icon('add_user_fields.png', get_lang('Add'), '', ICON_SIZE_MEDIUM) . '</a>';
+
+        echo '</div>';
+        echo Display::grid_html('course_fields');
+    }
+
+    public function return_form($url, $action) {
+        $form = new FormValidator('course_field', 'post', $url);
+        $id = isset($_GET['id']) ? intval($_GET['id']) : null;
+        $form->addElement('hidden', 'id', $id);
+        
+        // Settting the form elements
+        $header = get_lang('Add');        
+        $defaults = array();
+        
+        if ($action == 'edit') {
+            $header = get_lang('Modify');
+            // Setting the defaults
+            $defaults = $this->get($id);            
+        }
+
+        $form->addElement('header', $header);
+        $form->addElement('text', 'field_display_text', get_lang('Name'), array('class' => 'span5'));
+
+        // Field type
+        $types = self::get_field_types();
+
+        $form->addElement('select', 'field_type', get_lang('FieldType'), $types, array('id' => 'field_type', 'class' => 'chzn-select', 'data-placeholder' => get_lang('Select')));
+        $form->addElement('label', get_lang('Example'), '<div id="example">-</div>');
+
+        //$form->addElement('advanced_settings','<a class="btn btn-show" id="advanced_parameters" href="javascript://">'.get_lang('AdvancedParameters').'</a>');
+        //$form->addElement('html','<div id="options" style="display:none">');
+
+        $form->addElement('text', 'field_variable', get_lang('FieldLabel'), array('class' => 'span5'));
+        $form->addElement('text', 'field_options', get_lang('FieldPossibleValues'), array('id' => 'field_options', 'class' => 'span6'));
+        if ($action == 'edit') {            
+            if (in_array($defaults['field_type'], array(ExtraField::FIELD_TYPE_SELECT, ExtraField::FIELD_TYPE_DOUBLE_SELECT))) {
+                $url = Display::url(get_lang('EditExtraFieldOptions'), 'extra_field_options.php?type=course&field_id=' . $id);
+                $form->addElement('label', null, $url);
+                $form->freeze('field_options');
+            }
+        }
+        $form->addElement('text', 'field_default_value', get_lang('FieldDefaultValue'), array('id' => 'field_default_value', 'class' => 'span5'));
+
+        $group = array();
+        $group[] = $form->createElement('radio', 'field_visible', null, get_lang('Yes'), 1);
+        $group[] = $form->createElement('radio', 'field_visible', null, get_lang('No'), 0);
+        $form->addGroup($group, '', get_lang('Visible'), '', false);
+
+        $group = array();
+        $group[] = $form->createElement('radio', 'field_changeable', null, get_lang('Yes'), 1);
+        $group[] = $form->createElement('radio', 'field_changeable', null, get_lang('No'), 0);
+        $form->addGroup($group, '', get_lang('FieldChangeability'), '', false);
+
+        $group = array();
+        $group[] = $form->createElement('radio', 'field_filter', null, get_lang('Yes'), 1);
+        $group[] = $form->createElement('radio', 'field_filter', null, get_lang('No'), 0);
+        $form->addGroup($group, '', get_lang('FieldFilter'), '', false);        
+        
+        $form->addElement('text', 'field_order', get_lang('FieldOrder'), array('class' => 'span1'));
+
+        if ($action == 'edit') {            
+            $option = new CourseFieldOption('course');
+            if ($defaults['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
+                $form->freeze('field_options');
+            }
+            $defaults['field_options'] = $option->get_field_options_by_field_to_string($id);
+            $form->addElement('button', 'submit', get_lang('Modify'), 'class="save"');
+        } else {
+            $defaults['field_visible'] = 0;
+            $defaults['field_changeable'] = 0;
+            $defaults['field_filter'] = 0;
+            $form->addElement('button', 'submit', get_lang('Add'), 'class="save"');
+        }
+
+        /*if (!empty($defaults['created_at'])) {
+            $defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
+        }
+        if (!empty($defaults['updated_at'])) {
+            $defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
+        }*/
+        $form->setDefaults($defaults);
+
+        // Setting the rules
+        $form->addRule('field_display_text', get_lang('ThisFieldIsRequired'), 'required');
+        //$form->addRule('field_variable', get_lang('ThisFieldIsRequired'), 'required');
+        $form->addRule('field_type', get_lang('ThisFieldIsRequired'), 'required');
+
+        return $form;
+    }
+
+    /**
+     * Add elements to a form
+     *
+     * @param FormValidator $form
+     * @param int $courseCode
+     *
+     * @return array|bool
+     */
+    public function addElements($form, $courseCode = null)
+    {
+        if (empty($form)) {
+            return false;
+        }
+
+        $extra_data = false;
+        if (!empty($courseCode)) {
+            $extra_data = self::get_handler_extra_data($courseCode);
+
+            if ($form) {
+                $form->setDefaults($extra_data);
+            }
+        }
+
+        $extra_fields = $this->get_all(null, 'option_order');
+
+        $specilCourseFieldId = -1;
+
+        foreach ($extra_fields as $id => $extraField) {
+            if ($extraField['field_variable'] === self::SPECIAL_COURSE_FIELD) {
+                $specilCourseFieldId = $id;
+            }
+        }
+
+        if (isset($extra_fields[$specilCourseFieldId])) {
+            unset($extra_fields[$specilCourseFieldId]);
+        }
+
+        $extra = $this->set_extra_fields_in_form(
+            $form,
+            $extra_data,
+            $this->type.'_field',
+            false,
+            false,
+            $extra_fields,
+            $courseCode
+        );
+
+        return $extra;
+    }
+}

+ 8 - 0
main/inc/lib/CourseFieldOption.class.php

@@ -0,0 +1,8 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+class CourseFieldOption extends ExtraFieldOption {
+    public function __construct() {
+        parent::__construct('course');        
+    }     
+}

+ 11 - 0
main/inc/lib/CourseFieldValue.class.php

@@ -0,0 +1,11 @@
+<?php
+
+class CourseFieldValue extends ExtraFieldValue
+{
+
+    public function __construct()
+    {
+        parent::__construct('course');
+    }
+
+}

+ 105 - 0
main/inc/lib/SessionField.class.php

@@ -0,0 +1,105 @@
+<?php
+
+/* For licensing terms, see /license.txt */
+
+class SessionField extends ExtraField {
+
+    public function __construct() {
+        parent::__construct('session');
+    }
+
+    function display() {
+        // action links
+        echo '<div class="actions">';
+        echo '<a href="../admin/index.php">' . Display::return_icon('back.png', get_lang('BackTo') . ' ' . get_lang('PlatformAdmin'), '', ICON_SIZE_MEDIUM) . '</a>';
+        echo '<a href="' . api_get_self() . '?action=add">' . Display::return_icon('add_user_fields.png', get_lang('Add'), '', ICON_SIZE_MEDIUM) . '</a>';
+
+        echo '</div>';
+        echo Display::grid_html('session_fields');
+    }
+
+    public function return_form($url, $action) {
+        $form = new FormValidator('session_field', 'post', $url);
+        $id = isset($_GET['id']) ? intval($_GET['id']) : null;
+        $form->addElement('hidden', 'id', $id);
+        
+        // Settting the form elements
+        $header = get_lang('Add');        
+        $defaults = array();
+        
+        if ($action == 'edit') {
+            $header = get_lang('Modify');
+            // Setting the defaults
+            $defaults = $this->get($id);            
+        }
+
+        $form->addElement('header', $header);
+        $form->addElement('text', 'field_display_text', get_lang('Name'), array('class' => 'span5'));
+
+        // Field type
+        $types = self::get_field_types();
+
+        $form->addElement('select', 'field_type', get_lang('FieldType'), $types, array('id' => 'field_type', 'class' => 'chzn-select', 'data-placeholder' => get_lang('Select')));
+        $form->addElement('label', get_lang('Example'), '<div id="example">-</div>');
+
+        //$form->addElement('advanced_settings','<a class="btn btn-show" id="advanced_parameters" href="javascript://">'.get_lang('AdvancedParameters').'</a>');
+        //$form->addElement('html','<div id="options" style="display:none">');
+
+        $form->addElement('text', 'field_variable', get_lang('FieldLabel'), array('class' => 'span5'));
+        $form->addElement('text', 'field_options', get_lang('FieldPossibleValues'), array('id' => 'field_options', 'class' => 'span6'));
+        if ($action == 'edit') {            
+            if (in_array($defaults['field_type'], array(ExtraField::FIELD_TYPE_SELECT, ExtraField::FIELD_TYPE_DOUBLE_SELECT))) {
+                $url = Display::url(get_lang('EditExtraFieldOptions'), 'extra_field_options.php?type=session&field_id=' . $id);
+                $form->addElement('label', null, $url);
+                $form->freeze('field_options');
+            }
+        }
+        $form->addElement('text', 'field_default_value', get_lang('FieldDefaultValue'), array('id' => 'field_default_value', 'class' => 'span5'));
+
+        $group = array();
+        $group[] = $form->createElement('radio', 'field_visible', null, get_lang('Yes'), 1);
+        $group[] = $form->createElement('radio', 'field_visible', null, get_lang('No'), 0);
+        $form->addGroup($group, '', get_lang('Visible'), '', false);
+
+        $group = array();
+        $group[] = $form->createElement('radio', 'field_changeable', null, get_lang('Yes'), 1);
+        $group[] = $form->createElement('radio', 'field_changeable', null, get_lang('No'), 0);
+        $form->addGroup($group, '', get_lang('FieldChangeability'), '', false);
+
+        $group = array();
+        $group[] = $form->createElement('radio', 'field_filter', null, get_lang('Yes'), 1);
+        $group[] = $form->createElement('radio', 'field_filter', null, get_lang('No'), 0);
+        $form->addGroup($group, '', get_lang('FieldFilter'), '', false);        
+        
+        $form->addElement('text', 'field_order', get_lang('FieldOrder'), array('class' => 'span1'));
+
+        if ($action == 'edit') {            
+            $option = new SessionFieldOption('session');
+            if ($defaults['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
+                $form->freeze('field_options');
+            }
+            $defaults['field_options'] = $option->get_field_options_by_field_to_string($id);
+            $form->addElement('button', 'submit', get_lang('Modify'), 'class="save"');
+        } else {
+            $defaults['field_visible'] = 0;
+            $defaults['field_changeable'] = 0;
+            $defaults['field_filter'] = 0;
+            $form->addElement('button', 'submit', get_lang('Add'), 'class="save"');
+        }
+
+        /*if (!empty($defaults['created_at'])) {
+            $defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
+        }
+        if (!empty($defaults['updated_at'])) {
+            $defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
+        }*/
+        $form->setDefaults($defaults);
+
+        // Setting the rules
+        $form->addRule('field_display_text', get_lang('ThisFieldIsRequired'), 'required');
+        //$form->addRule('field_variable', get_lang('ThisFieldIsRequired'), 'required');
+        $form->addRule('field_type', get_lang('ThisFieldIsRequired'), 'required');
+
+        return $form;
+    }
+}

+ 8 - 0
main/inc/lib/SessionFieldOption.class.php

@@ -0,0 +1,8 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+class SessionFieldOption extends ExtraFieldOption {
+    public function __construct() {
+        parent::__construct('session');        
+    }     
+}

+ 11 - 0
main/inc/lib/SessionFieldValue.class.php

@@ -0,0 +1,11 @@
+<?php
+
+class SessionFieldValue extends ExtraFieldValue
+{
+
+    public function __construct()
+    {
+        parent::__construct('session');
+    }
+
+}

+ 6 - 0
main/inc/lib/autoload.class.php

@@ -134,6 +134,9 @@ class Autoload
         $result['CourseDescription\UploadFileForm'] = '/main/course_description/upload_file_form.class.php';
         $result['CourseEntity'] = '/main/inc/lib/course_entity.class.php';
         $result['CourseEntityRepository'] = '/main/inc/lib/course_entity_repository.class.php';
+        $result['CourseField'] = '/main/inc/lib/CourseField.class.php';
+        $result['CourseFieldOption'] = '/main/inc/lib/CourseFieldOption.class.php';
+        $result['CourseFieldValue'] = '/main/inc/lib/CourseFieldValue.class.php';
         $result['CourseHome'] = '/main/inc/lib/course_home.lib.php';
         $result['CourseManager'] = '/main/inc/lib/course.lib.php';
         $result['CourseNoticeController'] = '/main/course_notice/course_notice_controller.class.php';
@@ -824,6 +827,9 @@ class Autoload
         $result['SessionHandlerDatabase'] = '/main/inc/lib/session_handler.class.php';
         $result['SessionHandlerMemcache'] = '/main/inc/lib/session_handler_memcache.class.php';
         $result['SessionManager'] = '/main/inc/lib/sessionmanager.lib.php';
+        $result['SessionField'] = '/main/inc/lib/SessionField.class.php';
+        $result['SessionFieldOption'] = '/main/inc/lib/SessionFieldOption.class.php';
+        $result['SessionFieldValue'] = '/main/inc/lib/SessionFieldValue.class.php';
         $result['Shibboleth\Admin'] = '/main/auth/shibboleth/app/model/admin.class.php';
         $result['Shibboleth\AdminStore'] = '/main/auth/shibboleth/app/model/admin.class.php';
         $result['Shibboleth\Model'] = '/main/auth/shibboleth/lib/model.class.php';

+ 6 - 1
main/inc/lib/course.lib.php

@@ -36,7 +36,7 @@ class CourseManager
      *
      * @return  mixed  false if the course was not created, array with the course info
      */
-    public static function create_course($params)
+    public static function create_course($params, $extraFields = array())
     {
         global $_configuration;
         // Check portal limits
@@ -130,6 +130,11 @@ class CourseManager
                         $cr->restore($course_info['id']); //course_info[id] is the course.code value (I know...)
                     }
 
+                    $params['course_code'] = $course_info['code'];
+
+                    $courseFieldValue = new CourseFieldValue();
+                    $courseFieldValue->save_field_values($params);
+
                     return $course_info;
                 }
             }

+ 2 - 0
main/inc/lib/database.constants.inc.php

@@ -110,8 +110,10 @@ define('TABLE_MAIN_USER_FRIEND_RELATION_TYPE', 'user_friend_relation_type');
 // Web services
 define('TABLE_MAIN_USER_API_KEY',           'user_api_key');
 define('TABLE_MAIN_COURSE_FIELD',           'course_field');
+define('TABLE_MAIN_COURSE_FIELD_OPTIONS',    'course_field_options');
 define('TABLE_MAIN_COURSE_FIELD_VALUES',    'course_field_values');
 define('TABLE_MAIN_SESSION_FIELD',          'session_field');
+define('TABLE_MAIN_SESSION_FIELD_OPTIONS',  'session_field_options');
 define('TABLE_MAIN_SESSION_FIELD_VALUES',   'session_field_values');
 
 // Message

+ 162 - 151
main/inc/lib/extra_field.lib.php

@@ -51,6 +51,10 @@ class ExtraField extends Model
     const FIELD_TYPE_SOCIAL_PROFILE = 12;
     const FIELD_TYPE_CHECKBOX = 13;
     const FIELD_TYPE_MOBILE_PHONE_NUMBER = 14;
+    const FIELD_TYPE_INTEGER = 15;
+    const FIELD_TYPE_FILE_IMAGE = 16;
+    const FIELD_TYPE_FLOAT = 17;
+    const FIELD_TYPE_FILE = 18;
 
     public $type = 'user'; //or session or course
     public $handler_id = 'user_id';
@@ -238,6 +242,11 @@ class ExtraField extends Model
         $types[self::FIELD_TYPE_TIMEZONE] = get_lang('FieldTypeTimezone');
         $types[self::FIELD_TYPE_SOCIAL_PROFILE] = get_lang('FieldTypeSocialProfile');
         $types[self::FIELD_TYPE_MOBILE_PHONE_NUMBER] = get_lang('FieldTypeMobilePhoneNumber');
+        $types[self::FIELD_TYPE_CHECKBOX]       = get_lang('FieldTypeCheckbox');
+        $types[self::FIELD_TYPE_INTEGER]           = get_lang('FieldTypeInteger');
+        $types[self::FIELD_TYPE_FILE_IMAGE]           = get_lang('FieldTypeFileImage');
+        $types[self::FIELD_TYPE_FLOAT]           = get_lang('FieldTypeFloat');
+        $types[self::FIELD_TYPE_FILE]           = get_lang('FieldTypeFFile');
 
         switch ($handler) {
             case 'course':
@@ -677,14 +686,22 @@ class ExtraField extends Model
                                 );
                             }
                         } else {
+                            $fieldVariable = "extra_{$field_details['field_variable']}";
+
+                            $checkboxAttributes = array();
+
+                            if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) {
+                                $checkboxAttributes['checked'] = true;
+                            }
+
                             // We assume that is a switch on/off with 1 and 0 as values
                             $group[] = $form->createElement(
                                 'checkbox',
                                 'extra_'.$field_details['field_variable'],
                                 null,
                                 //$field_details['field_display_text'].'<br />',
-                                'Yes <br />',
-                                null
+                                get_lang('Yes'),
+                                $checkboxAttributes
                             );
                         }
                         $form->addGroup(
@@ -703,89 +720,20 @@ class ExtraField extends Model
                         break;
                     case ExtraField::FIELD_TYPE_SELECT:
                         $get_lang_variables = false;
-                        if (in_array(
-                            $field_details['field_variable'],
-                            array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message')
-                        )
-                        ) {
-                            $get_lang_variables = true;
-                        }
-
-                        // Get extra field workflow
-                        $userInfo = api_get_user_info();
 
-                        $addOptions = array();
-
-                        global $app;
-                        $optionsExists = $app['orm.em']->getRepository('ChamiloLMS\Entity\ExtraFieldOptionRelFieldOption')->
-                        findOneBy(array('fieldId' => $field_details['id']));
-
-                        if ($optionsExists) {
-                            if (isset($userInfo['status']) && !empty($userInfo['status'])) {
-
-                                $fieldWorkFlow = $app['orm.em']->getRepository('ChamiloLMS\Entity\ExtraFieldOptionRelFieldOption')
-                                    ->findBy(
-                                        array(
-                                            'fieldId' => $field_details['id'],
-                                            'relatedFieldOptionId' => $defaultValueId,
-                                            'roleId' => $userInfo['status']
-                                        )
-                                    );
-                                foreach ($fieldWorkFlow as $item) {
-                                    $addOptions[] = $item->getFieldOptionId();
-                                }
-                            }
+                        if (in_array($field_details['field_variable'],
+                                array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message'))) {
+                            $get_lang_variables = true;
                         }
 
                         $options = array();
-                        if (empty($defaultValueId)) {
-                            $options[''] = get_lang('SelectAnOption');
-                        }
-
-                        $optionList = array();
-                        if (!empty($field_details['options'])) {
-                            foreach ($field_details['options'] as $option_details) {
-                                $optionList[$option_details['id']] = $option_details;
-                                if ($get_lang_variables) {
-                                    $options[$option_details['option_value']] = get_lang($option_details['option_display_text']);
-                                } else {
-                                    if ($optionsExists) {
-                                        // Adding always the default value
-                                        if ($option_details['id'] == $defaultValueId) {
-                                            $options[$option_details['option_value']] = $option_details['option_display_text'];
-                                        } else {
-                                            if (isset($addOptions) && !empty($addOptions)) {
-                                                // Parsing filters
-                                                if (in_array($option_details['id'], $addOptions)) {
-                                                    $options[$option_details['option_value']] = $option_details['option_display_text'];
-                                                }
-                                            }
-                                        }
-                                    } else {
-                                        // Normal behaviour
-                                        $options[$option_details['option_value']] = $option_details['option_display_text'];
-                                    }
-                                }
-                            }
-
-                            if (isset($optionList[$defaultValueId])) {
-
-                                if (isset($optionList[$defaultValueId]['option_value']) && $optionList[$defaultValueId]['option_value'] == 'aprobada') {
-                                    if (api_is_question_manager() == false) {
-                                        $form->freeze();
-                                    }
-                                }
-                            }
-
-                            // Setting priority message
-                            if (isset($optionList[$defaultValueId]) && isset($optionList[$defaultValueId]['priority'])) {
 
-                                if (!empty($optionList[$defaultValueId]['priority'])) {
-                                    $priorityId = $optionList[$defaultValueId]['priority'];
-                                    $option = new ExtraFieldOption($this->type);
-                                    $messageType = $option->getPriorityMessageType($priorityId);
-                                    $form->addElement('label', null, Display::return_message($optionList[$defaultValueId]['priority_message'], $messageType));
-                                }
+                        foreach ($field_details['options'] as $option_id => $option_details) {
+                            //$options[$option_details['option_value']] = $option_details['option_display_text'];
+                            if ($get_lang_variables) {
+                                $options[$option_details['option_value']] = get_lang($option_details['option_display_text']);
+                            } else {
+                                $options[$option_details['option_value']] = $option_details['option_display_text'];
                             }
                         }
 
@@ -793,67 +741,15 @@ class ExtraField extends Model
                             $field_details['field_display_text'] = get_lang($field_details['field_display_text']);
                         }
 
-                        // chzn-select doesn't work for sessions??
-                        $form->addElement(
-                            'select',
-                            'extra_'.$field_details['field_variable'],
-                            $field_details['field_display_text'],
-                            $options,
-                            array('id' => 'extra_'.$field_details['field_variable'])
+                        //chzn-select doesn't work for sessions??
+                        $form->addElement('select', 'extra_' . $field_details['field_variable'],
+                            $field_details['field_display_text'], $options,
+                            array('class' => 'chzn-select', 'id' => 'extra_' . $field_details['field_variable'])
                         );
 
-                        if ($optionsExists && $field_details['field_loggeable'] && !empty($defaultValueId)) {
-
-                            $form->addElement(
-                                'textarea',
-                                'extra_'.$field_details['field_variable'].'_comment',
-                                $field_details['field_display_text'].' '.get_lang('Comment')
-                            );
-
-                            $extraFieldValue = new ExtraFieldValue($this->type);
-                            $repo = $app['orm.em']->getRepository($extraFieldValue->entityName);
-                            $repoLog = $app['orm.em']->getRepository('Gedmo\Loggable\Entity\LogEntry');
-                            $newEntity = $repo->findOneBy(
-                                array(
-                                    $this->handlerEntityId => $itemId,
-                                    'fieldId' => $field_details['id']
-                                )
-                            );
-                            // @todo move this in a function inside the class
-                            if ($newEntity) {
-                                $logs = $repoLog->getLogEntries($newEntity);
-                                if (!empty($logs)) {
-                                    $html = '<b>'.get_lang('LatestChanges').'</b><br /><br />';
-
-                                    $table = new HTML_Table(array('class' => 'data_table'));
-                                    $table->setHeaderContents(0, 0, get_lang('Value'));
-                                    $table->setHeaderContents(0, 1, get_lang('Comment'));
-                                    $table->setHeaderContents(0, 2, get_lang('ModifyDate'));
-                                    $table->setHeaderContents(0, 3, get_lang('Username'));
-                                    $row = 1;
-                                    foreach ($logs as $log) {
-                                        $column = 0;
-                                        $data = $log->getData();
-                                        $fieldValue = isset($data['fieldValue']) ? $data['fieldValue'] : null;
-                                        $comment = isset($data['comment']) ? $data['comment'] : null;
-
-                                        $table->setCellContents($row, $column, $fieldValue);
-                                        $column++;
-                                        $table->setCellContents($row, $column, $comment);
-                                        $column++;
-                                        $table->setCellContents($row, $column, api_get_local_time($log->getLoggedAt()->format('Y-m-d H:i:s')));
-                                        $column++;
-                                        $table->setCellContents($row, $column, $log->getUsername());
-                                        $row++;
-                                    }
-                                    $form->addElement('label', null, $html.$table->toHtml());
-                                }
-                            }
-                        }
-
                         if (!$admin_permissions) {
                             if ($field_details['field_visible'] == 0) {
-                                $form->freeze('extra_'.$field_details['field_variable']);
+                                $form->freeze('extra_' . $field_details['field_variable']);
                             }
                         }
                         break;
@@ -876,25 +772,17 @@ class ExtraField extends Model
                         }
                         break;
                     case ExtraField::FIELD_TYPE_DATE:
-                        $form->addElement(
-                            'datepickerdate',
-                            'extra_'.$field_details['field_variable'],
-                            $field_details['field_display_text'],
-                            array('form_name' => $form_name)
-                        );
-                        $form->_elements[$form->_elementIndex['extra_'.$field_details['field_variable']]]->setLocalOption(
-                            'minYear',
-                            1900
-                        );
-                        $defaults['extra_'.$field_details['field_variable']] = date('Y-m-d 12:00:00');
-                        if (!isset($form->_defaultValues['extra_'.$field_details['field_variable']])) {
-                            $form->setDefaults($defaults);
-                        }
+                        $form->addElement('date_picker', 'extra_'.$field_details['field_variable'], $field_details['field_display_text']);
+                        //$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
+                        //$defaults['extra_'.$field_details['field_variable']] = date('Y-m-d 12:00:00');
+                        //$form->setDefaults($defaults);
+
                         if (!$admin_permissions) {
                             if ($field_details['field_visible'] == 0) {
                                 $form->freeze('extra_'.$field_details['field_variable']);
                             }
                         }
+
                         $form->applyFilter('theme', 'trim');
                         break;
                     case ExtraField::FIELD_TYPE_DATETIME:
@@ -1128,6 +1016,129 @@ EOF;
                             $form->freeze('extra_'.$field_details['field_variable']);
                         }
                         break;
+                    case ExtraField::FIELD_TYPE_INTEGER:
+                        $form->addElement(
+                            'number',
+                            'extra_'.$field_details['field_variable'],
+                            $field_details['field_display_text'],
+                            array('class' => 'span1', 'step' => 1)
+                        );
+
+                        $form->applyFilter('extra_'.$field_details['field_variable'], 'stripslashes');
+                        $form->applyFilter('extra_'.$field_details['field_variable'], 'trim');
+                        $form->applyFilter('extra_'.$field_details['field_variable'], 'intval');
+
+                        if (!$admin_permissions) {
+                            if ($field_details['field_visible'] == 0) {
+                                $form->freeze(
+                                    'extra_'.$field_details['field_variable']
+                                );
+                            }
+                        }
+                        break;
+                    case ExtraField::FIELD_TYPE_FILE_IMAGE:
+                        $fieldVariable = "extra_{$field_details['field_variable']}";
+
+                        $fieldTexts = array(
+                            $field_details['field_display_text']
+                        );
+
+                        if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) {
+                            if (file_exists(api_get_path(SYS_CODE_PATH) . $extraData[$fieldVariable])) {
+                                $fieldTexts[] = Display::img(
+                                    api_get_path(WEB_CODE_PATH) . $extraData[$fieldVariable],
+                                    $field_details['field_display_text'],
+                                    array('width' => '300')
+                                );
+                            }
+                        }
+
+                        $form->addElement(
+                            'file',
+                            $fieldVariable,
+                            $fieldTexts,
+                            array('class' => 'span8', 'accept' => 'image/*')
+                        );
+
+                        $form->applyFilter('extra_'.$field_details['field_variable'], 'stripslashes');
+                        $form->applyFilter('extra_'.$field_details['field_variable'], 'trim');
+
+                        $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
+                        $form->addRule(
+                            'extra_'.$field_details['field_variable'],
+                            get_lang('OnlyImagesAllowed') . ' ('.implode(',', $allowed_picture_types).')',
+                            'filetype',
+                            $allowed_picture_types
+                        );
+
+                        if (!$admin_permissions) {
+                            if ($field_details['field_visible'] == 0) {
+                                $form->freeze(
+                                    'extra_'.$field_details['field_variable']
+                                );
+                            }
+                        }
+                        break;
+                    case ExtraField::FIELD_TYPE_FLOAT:
+                        $form->addElement(
+                            'number',
+                            'extra_'.$field_details['field_variable'],
+                            $field_details['field_display_text'],
+                            array('class' => 'span1', 'step' => '0.01')
+                        );
+
+                        $form->applyFilter('extra_'.$field_details['field_variable'], 'stripslashes');
+                        $form->applyFilter('extra_'.$field_details['field_variable'], 'trim');
+                        $form->applyFilter('extra_'.$field_details['field_variable'], 'floatval');
+
+                        if (!$admin_permissions) {
+                            if ($field_details['field_visible'] == 0) {
+                                $form->freeze(
+                                    'extra_'.$field_details['field_variable']
+                                );
+                            }
+                        }
+                        break;
+                    case ExtraField::FIELD_TYPE_FILE:
+                        require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php';
+
+                        $fieldVariable = "extra_{$field_details['field_variable']}";
+
+                        $fieldTexts = array(
+                            $field_details['field_display_text']
+                        );
+
+                        if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) {
+                            if (file_exists(api_get_path(SYS_CODE_PATH) . $extraData[$fieldVariable])) {
+                                $fieldTexts[] = Display::url(
+                                    api_get_path(WEB_CODE_PATH) . $extraData[$fieldVariable],
+                                    api_get_path(WEB_CODE_PATH) . $extraData[$fieldVariable],
+                                    array(
+                                        'title' => $field_details['field_display_text'],
+                                        'target' => '_blank'
+                                    )
+                                );
+                            }
+                        }
+
+                        $form->addElement(
+                            'file',
+                            $fieldVariable,
+                            $fieldTexts,
+                            array('class' => 'span8')
+                        );
+
+                        $form->applyFilter('extra_'.$field_details['field_variable'], 'stripslashes');
+                        $form->applyFilter('extra_'.$field_details['field_variable'], 'trim');
+
+                        if (!$admin_permissions) {
+                            if ($field_details['field_visible'] == 0) {
+                                $form->freeze(
+                                    'extra_'.$field_details['field_variable']
+                                );
+                            }
+                        }
+                        break;
                 }
             }
         }

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

@@ -244,7 +244,7 @@ class ExtraFieldOption extends Model
                 foreach ($list as $option) {
                     $option_info = self::get_field_option_by_field_and_option($field_id, $option);
                     // Use URLify only for new items
-                    $optionValue = URLify::filter($option);
+                    $optionValue = $option;
                     $option = trim($option);
 
                     if ($option_info == false) {

+ 70 - 7
main/inc/lib/extra_field_value.lib.php

@@ -160,14 +160,74 @@ class ExtraFieldValue extends Model
                                 }
                             }
                             break;
+                        case ExtraField::FIELD_TYPE_FILE_IMAGE:
+                            $dirPermissions = api_get_permissions_for_new_directories();
+                            $sysCodePath = api_get_path(SYS_CODE_PATH);
+
+                            $fileDir = "upload/extrafields/{$this->type}/";
+                            $fileName = ExtraField::FIELD_TYPE_FILE_IMAGE . "_{$params[$this->handler_id]}.png";
+
+                            if (!file_exists($sysCodePath . $fileDir)) {
+                                mkdir($sysCodePath . $fileDir, $dirPermissions, true);
+                            }
+
+                            if ($value['error'] == 0) {
+                                $imageExtraField = new Image($value['tmp_name']);
+                                $imageExtraField->send_image($sysCodePath . $fileDir . $fileName, -1, 'png');
+
+                                $new_params = array(
+                                    $this->handler_id => $params[$this->handler_id],
+                                    'field_id' => $extra_field_info['id'],
+                                    'field_value' => $fileDir . $fileName
+                                );
+
+                                if ($this->type !== 'session' && $this->type !== 'course') {
+                                    $new_params['comment'] = $comment;
+                                }
+
+                                self::save($new_params);
+                            }
+                            break;
+                        case ExtraField::FIELD_TYPE_FILE:
+                            $dirPermissions = api_get_permissions_for_new_directories();
+                            $sysCodePath = api_get_path(SYS_CODE_PATH);
+
+                            $fileDir = "upload/extrafields/{$this->type}/";
+                            $cleanedName = replace_dangerous_char($value['name']);
+                            $fileName = ExtraField::FIELD_TYPE_FILE . "_{$params[$this->handler_id]}_$cleanedName";
+
+                            if (!file_exists($sysCodePath . $fileDir)) {
+                                mkdir($sysCodePath . $fileDir, $dirPermissions, true);
+                            }
+
+                            if ($value['error'] == 0) {
+                                moveUploadedFile($value, $sysCodePath . $fileDir . $fileName);
+
+                                $new_params = array(
+                                    $this->handler_id => $params[$this->handler_id],
+                                    'field_id' => $extra_field_info['id'],
+                                    'field_value' => $fileDir . $fileName
+                                );
+
+                                if ($this->type !== 'session' && $this->type !== 'course') {
+                                    $new_params['comment'] = $comment;
+                                }
+
+                                self::save($new_params);
+                            }
+                            break;
                         default;
-                            $newParams = array(
-                                $this->handler_id => $params[$this->handler_id],
-                                'field_id' => $extra_field_info['id'],
-                                'field_value' => $value,
-                                'comment' => $comment
+                            $new_params = array(
+                                $this->handler_id   => $params[$this->handler_id],
+                                'field_id'          => $extra_field_info['id'],
+                                'field_value'       => $value
                             );
-                            self::save($newParams);
+
+                            if ($this->handler_id !== 'session_id' && $this->handler_id !== 'course_code') {
+                                $new_params['comment'] = $comment;
+                            }
+
+                            self::save($new_params);
                     }
                 }
             }
@@ -256,7 +316,10 @@ class ExtraFieldValue extends Model
 
             $params['field_value'] = $value_to_insert;
             $params['tms'] = api_get_utc_datetime();
-            $params[$this->author_id] = api_get_user_id();
+
+            if ($this->handler_id !== 'session_id' && $this->handler_id !== 'course_code') {
+                $params[$this->author_id] = api_get_user_id();
+            }
 
             // Insert
             if (empty($field_values)) {

+ 30 - 0
main/inc/lib/formvalidator/Element/Number.class.php

@@ -0,0 +1,30 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+require_once 'HTML/QuickForm/text.php';
+
+/**
+ * Form element to select a date and hour (with popup datepicker)
+ *
+ * Class DatePicker
+ */
+class Number extends HTML_QuickForm_text
+{
+    /**
+     * @param string $elementName
+     * @param string $elementLabel
+     * @param array  $attributes
+     */
+    public function Number($elementName = null, $elementLabel = null, $attributes = null)
+    {
+        if (!isset($attributes['id'])) {
+            $attributes['id'] = $elementName;
+        }
+        
+        $attributes['type'] = 'number';
+
+        HTML_QuickForm_element::HTML_QuickForm_element($elementName, $elementLabel, $attributes);
+        $this->_appendName = true;
+        $this->_type = 'number';
+    }
+}

+ 1 - 0
main/inc/lib/formvalidator/FormValidator.class.php

@@ -140,6 +140,7 @@ class FormValidator extends HTML_QuickForm
         $this->registerElementType('button', $dir . 'Element/style_submit_button.php', 'HTML_QuickForm_stylesubmitbutton');
         $this->registerElementType('captcha', 'HTML/QuickForm/CAPTCHA.php', 'HTML_QuickForm_CAPTCHA');
         $this->registerElementType('CAPTCHA_Image', 'HTML/QuickForm/CAPTCHA/Image.php', 'HTML_QuickForm_CAPTCHA_Image');
+        $this->registerElementType('number', $dir . 'Element/Number.class.php', 'Number');
 
         $this->registerRule('date', null, 'HTML_QuickForm_Rule_Date', $dir . 'Rule/Date.php');
         $this->registerRule('datetime', null, 'DateTimeRule', $dir . 'Rule/DateTimeRule.php');

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

@@ -83,7 +83,8 @@ class SessionManager
         $start_limit = true,
         $end_limit = true,
         $fix_name = false,
-        $duration = null
+        $duration = null,
+        $extraFields = array()
     ) {
         global $_configuration;
 
@@ -204,6 +205,11 @@ class SessionManager
                 }
 
                 if (!empty($session_id)) {
+                    $extraFields['session_id'] = $session_id;
+
+                    $sessionFieldValue = new SessionFieldValue();
+                    $sessionFieldValue->save_field_values($extraFields);
+
                     /*
                       Sends a message to the user_id = 1
 
@@ -1345,7 +1351,8 @@ class SessionManager
         $end_limit = true,
         $description = null,
         $showDescription = null,
-        $duration = null
+        $duration = null,
+        $extraFields = array()
     ) {
         $name = trim(stripslashes($name));
         $year_start = intval($year_start);
@@ -1455,6 +1462,12 @@ class SessionManager
 					  WHERE id='$id'";
 
                 Database::query($sql);
+
+                $extraFields['session_id'] = $id;
+
+                $sessionFieldValue = new SessionFieldValue();
+                $sessionFieldValue->save_field_values($extraFields);
+
                 return $id;
             }
         }

+ 55 - 7
main/inc/lib/usermanager.lib.php

@@ -3557,7 +3557,7 @@ class UserManager
     }
 
     /**
-     * Returns a list of all admninistrators
+     * Returns a list of all administrators
      * @author jmontoya
      * @return array
      */
@@ -3568,13 +3568,18 @@ class UserManager
         $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
         $access_url_id = api_get_current_access_url_id();
         if (api_get_multiple_access_url()) {
-            $access_url_id = api_get_current_access_url_id();
-            $sql = "SELECT admin.user_id, username, firstname, lastname, email FROM $tbl_url_rel_user as url INNER JOIN $table_admin as admin
-                                 ON (admin.user_id=url.user_id) INNER JOIN $table_user u ON (u.user_id=admin.user_id)
-                                 WHERE access_url_id ='".$access_url_id."'";
+            $sql = "SELECT admin.user_id, username, firstname, lastname, email
+                    FROM $tbl_url_rel_user as url
+                    INNER JOIN $table_admin as admin
+                    ON (admin.user_id=url.user_id)
+                    INNER JOIN $table_user u
+                    ON (u.user_id=admin.user_id)
+                    WHERE access_url_id ='".$access_url_id."'";
         } else {
-            $sql = "SELECT admin.user_id, username, firstname, lastname, email FROM $table_admin as admin
-                    INNER JOIN $table_user u ON (u.user_id=admin.user_id)";
+            $sql = "SELECT admin.user_id, username, firstname, lastname, email
+                    FROM $table_admin as admin
+                    INNER JOIN $table_user u
+                    ON (u.user_id=admin.user_id)";
         }
         $result = Database::query($sql);
         $return = array();
@@ -3583,6 +3588,7 @@ class UserManager
                 $return[$row['user_id']] = $row;
             }
         }
+
         return $return;
     }
 
@@ -4899,4 +4905,46 @@ EOF;
             Database::query($sql);
         }
     }
+
+    /**
+     * @return array
+     */
+    public static function getOfficialCodeGrouped()
+    {
+        $user = Database::get_main_table(TABLE_MAIN_USER);
+        $sql = "SELECT DISTINCT official_code
+                FROM $user
+                GROUP BY official_code";
+        $result = Database::query($sql);
+
+        $values = Database::store_result($result, 'ASSOC');
+
+        $result = array();
+        foreach ($values as $value) {
+            $result[$value['official_code']] = $value['official_code'];
+        }
+        return $result;
+    }
+
+    /**
+     * @param string $officialCode
+     * @return array
+     */
+    public static function getUsersByOfficialCode($officialCode)
+    {
+        $user = Database::get_main_table(TABLE_MAIN_USER);
+        $officialCode = Database::escape_string($officialCode);
+
+        $sql = "SELECT DISTINCT user_id
+                FROM $user
+                WHERE official_code = '$officialCode'
+                ";
+        $result = Database::query($sql);
+
+        $users = array();
+        while ($row = Database::fetch_array($result)) {
+            $users[] = $row['user_id'];
+        }
+        return $users;
+    }
 }

+ 2 - 0
main/install/configuration.dist.php

@@ -271,3 +271,5 @@ $_configuration['system_stable']     = NEW_VERSION_STABLE;
 //$_configuration['course_images_in_courses_list'] = false;
 // Which student publication will be taken when connected to the gradebook: first|last
 //$_configuration['student_publication_to_take_in_gradebook'] = 'first';
+// Show a filter by official code
+//$_configuration['certificate_filter_by_official_code'] = false;

+ 1 - 1
main/install/db_main.sql

@@ -2714,7 +2714,7 @@ CREATE TABLE IF NOT EXISTS message_attachment (
 
 
 
-INSERT INTO course_field (field_type, field_variable, field_display_text, field_default_value, field_visible, field_changeable) values (10, 'special_course','Special course', 'Yes', 1 , 1);
+INSERT INTO course_field (field_type, field_variable, field_display_text, field_default_value, field_visible, field_changeable) values (10, 'special_course','Special course', '', 1 , 1);
 
 --
 -- Table structure for table block

+ 156 - 0
tests/scripts/insert_session_fields.php

@@ -0,0 +1,156 @@
+<?php
+/*
+ * This script insert session extra fields
+ */
+
+//exit;
+
+require_once '../../main/inc/global.inc.php';
+
+api_protect_admin_script();
+
+$horasLectivas = new ExtraField('session');
+$horasLectivas->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_INTEGER,
+    'field_variable' => 'horas_lectivas',
+    'field_display_text' => 'Horas lectivas',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));
+
+$costo = new ExtraField('session');
+$costo->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_FLOAT,
+    'field_variable' => 'costo',
+    'field_display_text' => 'Costo',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));
+
+$vacantes = new ExtraField('session');
+$vacantes->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_INTEGER,
+    'field_variable' => 'vacantes',
+    'field_display_text' => 'Vacantes',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));
+
+$numeroRecomendadoParticipantes = new ExtraField('session');
+$numeroRecomendadoParticipantes->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_INTEGER,
+    'field_variable' => 'numero_recomendado_participantes',
+    'field_display_text' => 'Número recomendado de participantes',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));
+
+$lugar = new ExtraField('session');
+$lugar->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_TEXT,
+    'field_variable' => 'lugar',
+    'field_display_text' => 'Lugar',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));
+
+$horario = new ExtraField('session');
+$horario->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_TEXT,
+    'field_variable' => 'horario',
+    'field_display_text' => 'Horario',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));
+
+$permitirVisitantes = new ExtraField('session');
+$permitirVisitantes->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_CHECKBOX,
+    'field_variable' => 'permitir_visitantes',
+    'field_display_text' => 'Permitir visitantes',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));
+
+$modalidad = new ExtraField('session');
+$modalidad->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_SELECT,
+    'field_variable' => 'modalidad',
+    'field_display_text' => 'Modalidad',
+    'field_visible' => 1,
+    'field_changeable' => 1,
+    'field_options' => 'Online; Presencial; B-Learning'
+));
+
+$esSesionInduccion = new ExtraField('session');
+$esSesionInduccion->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_CHECKBOX,
+    'field_variable' => 'es_induccion',
+    'field_display_text' => 'Es sesión de inducción',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));
+
+$esSesionAbierta = new ExtraField('session');
+$esSesionAbierta->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_CHECKBOX,
+    'field_variable' => 'es_abierta',
+    'field_display_text' => 'Es sesión abierta',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));
+
+$duracion = new ExtraField('session');
+$duracion->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_INTEGER,
+    'field_variable' => 'duracion',
+    'field_display_text' => 'Duración',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));
+
+$mostrarEstado = new ExtraField('session');
+$mostrarEstado->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_SELECT,
+    'field_variable' => 'mostrar_estado',
+    'field_display_text' => 'Mostrar estado',
+    'field_visible' => 1,
+    'field_changeable' => 1,
+    'field_options' => 'Abierto; En proceso; Cerrado'
+));
+
+$inicioPublicacion = new ExtraField('session');
+$inicioPublicacion->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_DATE,
+    'field_variable' => 'inicio_publicacion',
+    'field_display_text' => 'Inicio de publicación',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));
+
+$finPublicacion = new ExtraField('session');
+$finPublicacion->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_DATE,
+    'field_variable' => 'fin_publicacion',
+    'field_display_text' => 'Fin de publicación',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));
+
+$banner = new ExtraField('session');
+$banner->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_FILE_IMAGE,
+    'field_variable' => 'banner',
+    'field_display_text' => 'Banner de la sesión',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));
+
+$brochure = new ExtraField('session');
+$brochure->save(array(
+    'field_type' => ExtraField::FIELD_TYPE_FILE,
+    'field_variable' => 'brochure',
+    'field_display_text' => 'Brochure',
+    'field_visible' => 1,
+    'field_changeable' => 1
+));