Browse Source

Merging with 19x

Julio Montoya 12 years ago
parent
commit
34c9a9882c
100 changed files with 6528 additions and 6621 deletions
  1. 3 1
      .hgignore
  2. 43 0
      composer.json
  3. 1937 0
      composer.lock
  4. 17 2
      documentation/changelog.html
  5. 2 4
      htaccess
  6. 210 133
      index.php
  7. 1 1
      main/admin/access_url_add_courses_to_url.php
  8. 1 2
      main/admin/access_url_add_users_to_url.php
  9. 0 2
      main/admin/access_url_check_user_session.php
  10. 115 103
      main/admin/access_url_edit.php
  11. 0 2
      main/admin/access_url_edit_courses_to_url.php
  12. 154 156
      main/admin/access_url_edit_users_to_url.php
  13. 91 72
      main/admin/access_urls.php
  14. 0 2
      main/admin/add_courses_to_usergroup.php
  15. 0 2
      main/admin/add_many_session_to_category.php
  16. 0 4
      main/admin/add_sessions_to_promotion.php
  17. 0 2
      main/admin/add_sessions_to_usergroup.php
  18. 0 1
      main/admin/add_users_to_group.php
  19. 116 87
      main/admin/add_users_to_session.php
  20. 0 1
      main/admin/add_users_to_usergroup.php
  21. 0 2
      main/admin/career_dashboard.php
  22. 0 3
      main/admin/careers.php
  23. 88 0
      main/admin/change_user_session.php
  24. 0 1
      main/admin/class_user_import.php
  25. 2 2
      main/admin/configure_homepage.php
  26. 1 2
      main/admin/configure_inscription.php
  27. 4 4
      main/admin/configure_plugin.php
  28. 0 2
      main/admin/course_add.php
  29. 5 5
      main/admin/course_category.php
  30. 19 119
      main/admin/course_edit.php
  31. 1 2
      main/admin/course_import.php
  32. 47 51
      main/admin/course_information.php
  33. 1 11
      main/admin/course_request_accepted.php
  34. 0 11
      main/admin/course_request_edit.php
  35. 3 14
      main/admin/course_request_rejected.php
  36. 1 12
      main/admin/course_request_review.php
  37. 0 5
      main/admin/course_user_import.php
  38. 0 3
      main/admin/dashboard_add_courses_to_user.php
  39. 0 1
      main/admin/dashboard_add_sessions_to_user.php
  40. 0 1
      main/admin/dashboard_add_users_to_user.php
  41. 2 2
      main/admin/example_session.csv
  42. 2 2
      main/admin/example_session.xml
  43. 164 0
      main/admin/extra_field_options.php
  44. 6 1
      main/admin/filler.php
  45. 0 1
      main/admin/grade_models.php
  46. 1 2
      main/admin/group_add.php
  47. 0 3
      main/admin/group_edit.php
  48. 0 2
      main/admin/group_list.php
  49. 0 4
      main/admin/inactive_user_list.php
  50. 12 15
      main/admin/index.php
  51. 4 12
      main/admin/ldap_import_students_to_session.php
  52. 220 204
      main/admin/resume_session.php
  53. 261 403
      main/admin/session_add.php
  54. 0 2
      main/admin/session_category_add.php
  55. 12 12
      main/admin/session_course_edit.php
  56. 3 1
      main/admin/session_course_user.php
  57. 61 73
      main/admin/session_course_user_list.php
  58. 0 404
      main/admin/session_edit.php
  59. 185 206
      main/admin/session_export.php
  60. 200 0
      main/admin/session_fields.php
  61. 71 105
      main/admin/session_import.php
  62. 226 89
      main/admin/session_list.php
  63. 1 4
      main/admin/session_user_import.php
  64. 24 19
      main/admin/settings.lib.php
  65. 4 3
      main/admin/settings.php
  66. 2 1
      main/admin/skills.php
  67. 0 3
      main/admin/skills_import.php
  68. 2 1
      main/admin/skills_wheel.php
  69. 0 2
      main/admin/statistics.php
  70. 3 7
      main/admin/statistics/index.php
  71. 0 722
      main/admin/statistics/statistics.lib.php
  72. 0 181
      main/admin/style_preview.php
  73. 1 3
      main/admin/user_add.php
  74. 1 3
      main/admin/user_edit.php
  75. 266 280
      main/admin/user_fields.php
  76. 108 144
      main/admin/user_fields_options.php
  77. 2 6
      main/admin/user_import.php
  78. 20 13
      main/admin/user_information.php
  79. 104 144
      main/admin/user_list.php
  80. 1 1
      main/admin/user_move_stats.php
  81. 0 1
      main/admin/usergroup_export.php
  82. 20 20
      main/admin/usergroup_import.php
  83. 0 1132
      main/announcements/announcements.inc.php
  84. 390 410
      main/announcements/announcements.php
  85. 34 25
      main/attendance/attendance_controller.php
  86. 46 2
      main/attendance/attendance_list.php
  87. 237 164
      main/attendance/attendance_sheet.php
  88. 85 70
      main/attendance/index.php
  89. 1 1
      main/auth/inscription.php
  90. 341 339
      main/auth/profile.php
  91. 7 9
      main/auth/shibboleth/app/controller/shibboleth_controller.class.php
  92. 54 46
      main/auth/sso/sso.class.php
  93. 416 420
      main/calendar/agenda.lib.php
  94. 42 48
      main/calendar/agenda_js.php
  95. 0 2
      main/course_home/activity.php
  96. 1 3
      main/course_home/course_home.php
  97. 0 1
      main/course_info/infocours.php
  98. 1 1
      main/course_info/legal.php
  99. 21 16
      main/course_info/maintenance.php
  100. 1 3
      main/course_progress/index.php

+ 3 - 1
.hgignore

@@ -14,7 +14,6 @@ courses/*
 main/garbage/*
 !main/garbage/index.html
 !main/garbage/Serializer
-
 #Home
 home/*
 #!home/default_platform_document
@@ -123,3 +122,6 @@ syntax: regexp
 ^\.settings$
 
 nbproject/*
+
+.git
+tests/doctrine_console/

+ 43 - 0
composer.json

@@ -0,0 +1,43 @@
+{
+    "autoload": {
+        "psr-0": {
+            "Entity" : "main/inc/",
+            "Gedmo": "vendor/gedmo/doctrine-extensions/lib'"
+        },
+        "classmap": [
+            "main/auth",
+            "main/admin",
+            "main/cron/lang",
+            "main/coursecopy",
+            "main/exercice",
+            "main/gradebook/lib",
+            "main/newscorm",
+            "main/inc/lib",
+            "main/install",
+            "main/inc/lib/getid3",
+            "main/survey"
+        ]
+    },
+    "require": {
+        "php": ">=5.3.2",
+        "silex/silex"           : "dev-master",
+        "symfony/config"        : "dev-master",
+        "symfony/yaml"          : "2.1.*",
+        "symfony/console"  : "dev-master",
+        "twig/twig": ">=1.8,<2.0-dev",
+        "symfony/twig-bridge": "2.2.*@dev",
+        "symfony/security": "2.1.*",
+        "monolog/monolog"       : ">=1.0.0",
+        "symfony/form": "2.1.*",
+        "symfony/validator": "2.1.*",
+        "symfony/translation": "2.1.*",
+        "symfony/dependency-injection": "dev-master",
+        "dflydev/doctrine-orm-service-provider": "1.0.*@dev",
+        "doctrine/migrations": "dev-master",
+        "swiftmailer/swiftmailer": ">=4.1.2,<4.2-dev",
+        "pagerfanta/pagerfanta": "dev-master",
+        "knplabs/knp-menu": "2.0.*@dev",
+        "gedmo/doctrine-extensions": "2.3.*@dev"
+    },
+    "minimum-stability": "dev"
+}

+ 1937 - 0
composer.lock

@@ -0,0 +1,1937 @@
+{
+    "hash": "00969618f2f0b10a233fb67916e231af",
+    "packages": [
+        {
+            "name": "dflydev/doctrine-orm-service-provider",
+            "version": "dev-master",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/dflydev/dflydev-doctrine-orm-service-provider",
+                "reference": "b925a32d4657f34b33fb7c7406f6e830aee28192"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/dflydev/dflydev-doctrine-orm-service-provider/archive/b925a32d4657f34b33fb7c7406f6e830aee28192.zip",
+                "reference": "b925a32d4657f34b33fb7c7406f6e830aee28192",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3",
+                "doctrine/orm": ">=2.3,<3.0",
+                "pimple/pimple": "1.*@dev"
+            },
+            "require-dev": {
+                "cilex/cilex": "1.*@dev",
+                "silex/silex": "1.*@dev"
+            },
+            "suggest": {
+                "dflydev/psr0-resource-locator-service-provider": "1.0.*@dev"
+            },
+            "time": "2012-12-30 23:41:22",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.0-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Dflydev\\Cilex\\Provider\\DoctrineOrm": "src",
+                    "Dflydev\\Pimple\\Provider\\DoctrineOrm": "src",
+                    "Dflydev\\Silex\\Provider\\DoctrineOrm": "src"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Dragonfly Development Inc.",
+                    "email": "info@dflydev.com",
+                    "homepage": "http://dflydev.com"
+                },
+                {
+                    "name": "Beau Simensen",
+                    "email": "beau@dflydev.com",
+                    "homepage": "http://beausimensen.com"
+                }
+            ],
+            "description": "Doctrine ORM Service Provider",
+            "keywords": [
+                "silex",
+                "orm",
+                "doctrine",
+                "pimple",
+                "cilex"
+            ]
+        },
+        {
+            "name": "doctrine/annotations",
+            "version": "v1.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/doctrine/annotations.git",
+                "reference": "v1.0"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/doctrine/annotations/archive/v1.0.zip",
+                "reference": "v1.0",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.2",
+                "doctrine/lexer": "1.*"
+            },
+            "require-dev": {
+                "doctrine/cache": "1.*"
+            },
+            "time": "2013-01-12 19:23:32",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Doctrine\\Common\\Annotations\\": "lib/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Jonathan Wage",
+                    "email": "jonwage@gmail.com",
+                    "homepage": "http://www.jwage.com/"
+                },
+                {
+                    "name": "Guilherme Blanco",
+                    "email": "guilhermeblanco@gmail.com",
+                    "homepage": "http://www.instaclick.com"
+                },
+                {
+                    "name": "Roman Borschel",
+                    "email": "roman@code-factory.org"
+                },
+                {
+                    "name": "Benjamin Eberlei",
+                    "email": "kontakt@beberlei.de"
+                },
+                {
+                    "name": "Johannes Schmitt",
+                    "email": "schmittjoh@gmail.com",
+                    "homepage": "https://github.com/schmittjoh",
+                    "role": "Developer of wrapped JMSSerializerBundle"
+                }
+            ],
+            "description": "Docblock Annotations Parser",
+            "homepage": "http://www.doctrine-project.org",
+            "keywords": [
+                "annotations",
+                "parser",
+                "docblock"
+            ]
+        },
+        {
+            "name": "doctrine/cache",
+            "version": "v1.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/doctrine/cache.git",
+                "reference": "v1.0"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/doctrine/cache/archive/v1.0.zip",
+                "reference": "v1.0",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.2"
+            },
+            "time": "2013-01-10 22:43:46",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Doctrine\\Common\\Cache\\": "lib/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Jonathan Wage",
+                    "email": "jonwage@gmail.com",
+                    "homepage": "http://www.jwage.com/"
+                },
+                {
+                    "name": "Guilherme Blanco",
+                    "email": "guilhermeblanco@gmail.com",
+                    "homepage": "http://www.instaclick.com"
+                },
+                {
+                    "name": "Roman Borschel",
+                    "email": "roman@code-factory.org"
+                },
+                {
+                    "name": "Benjamin Eberlei",
+                    "email": "kontakt@beberlei.de"
+                },
+                {
+                    "name": "Johannes Schmitt",
+                    "email": "schmittjoh@gmail.com",
+                    "homepage": "https://github.com/schmittjoh",
+                    "role": "Developer of wrapped JMSSerializerBundle"
+                }
+            ],
+            "description": "Caching library offering an object-oriented API for many cache backends",
+            "homepage": "http://www.doctrine-project.org",
+            "keywords": [
+                "cache",
+                "caching"
+            ]
+        },
+        {
+            "name": "doctrine/collections",
+            "version": "v1.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/doctrine/collections.git",
+                "reference": "v1.0"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/doctrine/collections/archive/v1.0.zip",
+                "reference": "v1.0",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.2"
+            },
+            "time": "2013-01-12 16:36:50",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Doctrine\\Common\\Collections\\": "lib/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Jonathan Wage",
+                    "email": "jonwage@gmail.com",
+                    "homepage": "http://www.jwage.com/"
+                },
+                {
+                    "name": "Guilherme Blanco",
+                    "email": "guilhermeblanco@gmail.com",
+                    "homepage": "http://www.instaclick.com"
+                },
+                {
+                    "name": "Roman Borschel",
+                    "email": "roman@code-factory.org"
+                },
+                {
+                    "name": "Benjamin Eberlei",
+                    "email": "kontakt@beberlei.de"
+                },
+                {
+                    "name": "Johannes Schmitt",
+                    "email": "schmittjoh@gmail.com",
+                    "homepage": "https://github.com/schmittjoh",
+                    "role": "Developer of wrapped JMSSerializerBundle"
+                }
+            ],
+            "description": "Collections Abstraction library",
+            "homepage": "http://www.doctrine-project.org",
+            "keywords": [
+                "collections",
+                "iterator",
+                "array"
+            ]
+        },
+        {
+            "name": "doctrine/common",
+            "version": "dev-master",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/doctrine/common",
+                "reference": "185e6d76765fe37ddb1a94aad8f51d97c92b0649"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/doctrine/common/archive/185e6d76765fe37ddb1a94aad8f51d97c92b0649.zip",
+                "reference": "185e6d76765fe37ddb1a94aad8f51d97c92b0649",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.2",
+                "doctrine/inflector": "1.*",
+                "doctrine/cache": "1.*",
+                "doctrine/collections": "1.*",
+                "doctrine/lexer": "1.*",
+                "doctrine/annotations": "1.*"
+            },
+            "time": "2013-01-12 19:27:40",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.4.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Doctrine\\Common\\": "lib/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Jonathan Wage",
+                    "email": "jonwage@gmail.com",
+                    "homepage": "http://www.jwage.com/"
+                },
+                {
+                    "name": "Guilherme Blanco",
+                    "email": "guilhermeblanco@gmail.com",
+                    "homepage": "http://www.instaclick.com"
+                },
+                {
+                    "name": "Roman Borschel",
+                    "email": "roman@code-factory.org"
+                },
+                {
+                    "name": "Benjamin Eberlei",
+                    "email": "kontakt@beberlei.de"
+                },
+                {
+                    "name": "Johannes Schmitt",
+                    "email": "schmittjoh@gmail.com",
+                    "homepage": "https://github.com/schmittjoh",
+                    "role": "Developer of wrapped JMSSerializerBundle"
+                }
+            ],
+            "description": "Common Library for Doctrine projects",
+            "homepage": "http://www.doctrine-project.org",
+            "keywords": [
+                "collections",
+                "spl",
+                "eventmanager",
+                "annotations",
+                "persistence"
+            ]
+        },
+        {
+            "name": "doctrine/dbal",
+            "version": "dev-master",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/doctrine/dbal",
+                "reference": "f8604e1444263e8a3020c6b622a14ff63b50b42f"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/doctrine/dbal/archive/f8604e1444263e8a3020c6b622a14ff63b50b42f.zip",
+                "reference": "f8604e1444263e8a3020c6b622a14ff63b50b42f",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.2",
+                "doctrine/common": "2.4.x-dev"
+            },
+            "require-dev": {
+                "symfony/console": "2.*"
+            },
+            "suggest": {
+                "symfony/console": "For helpful console commands such as SQL execution and import of files."
+            },
+            "time": "2013-01-17 18:06:44",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.4.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Doctrine\\DBAL\\": "lib/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Jonathan Wage",
+                    "email": "jonwage@gmail.com",
+                    "homepage": "http://www.jwage.com/"
+                },
+                {
+                    "name": "Guilherme Blanco",
+                    "email": "guilhermeblanco@gmail.com",
+                    "homepage": "http://www.instaclick.com"
+                },
+                {
+                    "name": "Roman Borschel",
+                    "email": "roman@code-factory.org"
+                },
+                {
+                    "name": "Benjamin Eberlei",
+                    "email": "kontakt@beberlei.de"
+                }
+            ],
+            "description": "Database Abstraction Layer",
+            "homepage": "http://www.doctrine-project.org",
+            "keywords": [
+                "database",
+                "persistence",
+                "dbal",
+                "queryobject"
+            ]
+        },
+        {
+            "name": "doctrine/inflector",
+            "version": "v1.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/doctrine/inflector.git",
+                "reference": "v1.0"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/doctrine/inflector/archive/v1.0.zip",
+                "reference": "v1.0",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.2"
+            },
+            "time": "2013-01-10 21:49:15",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Doctrine\\Common\\Inflector\\": "lib/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Jonathan Wage",
+                    "email": "jonwage@gmail.com",
+                    "homepage": "http://www.jwage.com/"
+                },
+                {
+                    "name": "Guilherme Blanco",
+                    "email": "guilhermeblanco@gmail.com",
+                    "homepage": "http://www.instaclick.com"
+                },
+                {
+                    "name": "Roman Borschel",
+                    "email": "roman@code-factory.org"
+                },
+                {
+                    "name": "Benjamin Eberlei",
+                    "email": "kontakt@beberlei.de"
+                },
+                {
+                    "name": "Johannes Schmitt",
+                    "email": "schmittjoh@gmail.com",
+                    "homepage": "https://github.com/schmittjoh",
+                    "role": "Developer of wrapped JMSSerializerBundle"
+                }
+            ],
+            "description": "Common String Manipulations with regard to casing and singular/plural rules.",
+            "homepage": "http://www.doctrine-project.org",
+            "keywords": [
+                "string",
+                "inflection",
+                "singuarlize",
+                "pluarlize"
+            ]
+        },
+        {
+            "name": "doctrine/lexer",
+            "version": "v1.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/doctrine/lexer.git",
+                "reference": "v1.0"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/doctrine/lexer/archive/v1.0.zip",
+                "reference": "v1.0",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.2"
+            },
+            "time": "2013-01-12 18:59:04",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Doctrine\\Common\\Lexer\\": "lib/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Guilherme Blanco",
+                    "email": "guilhermeblanco@gmail.com",
+                    "homepage": "http://www.instaclick.com"
+                },
+                {
+                    "name": "Roman Borschel",
+                    "email": "roman@code-factory.org"
+                },
+                {
+                    "name": "Johannes Schmitt",
+                    "email": "schmittjoh@gmail.com",
+                    "homepage": "https://github.com/schmittjoh",
+                    "role": "Developer of wrapped JMSSerializerBundle"
+                }
+            ],
+            "description": "Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.",
+            "homepage": "http://www.doctrine-project.org",
+            "keywords": [
+                "parser",
+                "lexer"
+            ]
+        },
+        {
+            "name": "doctrine/migrations",
+            "version": "dev-master",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/doctrine/migrations",
+                "reference": "e1f6efcd94993b493de5c6a413cbc327ea9c0caa"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/doctrine/migrations/archive/e1f6efcd94993b493de5c6a413cbc327ea9c0caa.zip",
+                "reference": "e1f6efcd94993b493de5c6a413cbc327ea9c0caa",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.2",
+                "doctrine/dbal": ">=2.0,<2.5.x-dev"
+            },
+            "require-dev": {
+                "symfony/console": "2.*",
+                "symfony/yaml": "2.*"
+            },
+            "suggest": {
+                "symfony/console": "to run the migration from the console"
+            },
+            "time": "2012-12-27 16:39:29",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Doctrine\\DBAL\\Migrations": "lib"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "LGPL"
+            ],
+            "authors": [
+                {
+                    "name": "Jonathan Wage",
+                    "email": "jonwage@gmail.com",
+                    "homepage": "http://www.jwage.com/"
+                },
+                {
+                    "name": "Benjamin Eberlei",
+                    "email": "kontakt@beberlei.de"
+                }
+            ],
+            "description": "Database Schema migrations using Doctrine DBAL",
+            "homepage": "http://www.doctrine-project.org",
+            "keywords": [
+                "database",
+                "migrations"
+            ]
+        },
+        {
+            "name": "doctrine/orm",
+            "version": "dev-master",
+            "source": {
+                "type": "git",
+                "url": "git://github.com/doctrine/doctrine2.git",
+                "reference": "b30b06852bc4eacf8bbbed472e1d6ec21310ec0a"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/doctrine/doctrine2/archive/b30b06852bc4eacf8bbbed472e1d6ec21310ec0a.zip",
+                "reference": "b30b06852bc4eacf8bbbed472e1d6ec21310ec0a",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.2",
+                "ext-pdo": "*",
+                "symfony/console": "2.*",
+                "doctrine/dbal": ">=2.4-dev,<2.5-dev"
+            },
+            "suggest": {
+                "symfony/yaml": "If you want to use YAML Metadata Mapping Driver"
+            },
+            "time": "2013-01-14 01:16:50",
+            "bin": [
+                "bin/doctrine",
+                "bin/doctrine.php"
+            ],
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.4.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Doctrine\\ORM\\": "lib/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Jonathan Wage",
+                    "email": "jonwage@gmail.com",
+                    "homepage": "http://www.jwage.com/"
+                },
+                {
+                    "name": "Guilherme Blanco",
+                    "email": "guilhermeblanco@gmail.com",
+                    "homepage": "http://www.instaclick.com"
+                },
+                {
+                    "name": "Roman Borschel",
+                    "email": "roman@code-factory.org"
+                },
+                {
+                    "name": "Benjamin Eberlei",
+                    "email": "kontakt@beberlei.de"
+                }
+            ],
+            "description": "Object-Relational-Mapper for PHP",
+            "homepage": "http://www.doctrine-project.org",
+            "keywords": [
+                "database",
+                "orm"
+            ]
+        },
+        {
+            "name": "gedmo/doctrine-extensions",
+            "version": "dev-master",
+            "source": {
+                "type": "git",
+                "url": "git://github.com/l3pp4rd/DoctrineExtensions.git",
+                "reference": "8b76f310b038647c85ae17143971b0c2abbd0a57"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/l3pp4rd/DoctrineExtensions/archive/8b76f310b038647c85ae17143971b0c2abbd0a57.zip",
+                "reference": "8b76f310b038647c85ae17143971b0c2abbd0a57",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.2",
+                "doctrine/common": ">=2.2,<2.5-dev"
+            },
+            "require-dev": {
+                "doctrine/mongodb": ">=1.0.0-BETA1",
+                "doctrine/mongodb-odm": ">=1.0.0-BETA6",
+                "doctrine/orm": ">=2.2",
+                "doctrine/dbal": ">=2.2",
+                "symfony/yaml": "2.*"
+            },
+            "suggest": {
+                "doctrine/orm": ">=2.2",
+                "doctrine/dbal": ">=2.2",
+                "doctrine/mongodb": ">=1.0.0",
+                "doctrine/mongodb-odm": ">=1.0.0-BETA7"
+            },
+            "time": "2013-01-16 05:01:32",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.3.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Gedmo": "lib/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Gediminas Morkevicius",
+                    "email": "gediminas.morkevicius@gmail.com"
+                }
+            ],
+            "description": "Doctrine2 behavioral extensions",
+            "homepage": "http://gediminasm.org/",
+            "keywords": [
+                "tree",
+                "behaviors",
+                "doctrine2",
+                "extensions",
+                "gedmo",
+                "sluggable",
+                "loggable",
+                "translatable",
+                "nestedset",
+                "sortable",
+                "timestampable"
+            ]
+        },
+        {
+            "name": "knplabs/knp-menu",
+            "version": "dev-master",
+            "source": {
+                "type": "git",
+                "url": "http://github.com/KnpLabs/KnpMenu.git",
+                "reference": "730bc37232f5f813822acf80edfbd89381ea5971"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/KnpLabs/KnpMenu/archive/730bc37232f5f813822acf80edfbd89381ea5971.zip",
+                "reference": "730bc37232f5f813822acf80edfbd89381ea5971",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.0"
+            },
+            "require-dev": {
+                "silex/silex": "1.0.*",
+                "twig/twig": ">=1.2,<2.0-dev",
+                "pimple/pimple": "1.0.*"
+            },
+            "suggest": {
+                "pimple/pimple": "for the built-in implementations of the menu provider and renderer provider",
+                "silex/silex": "for the integration with your silex application",
+                "twig/twig": "for the TwigRenderer and the integration with your templates"
+            },
+            "time": "2012-12-27 13:04:16",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.0.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Knp\\Menu\\": "src/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Christophe Coevoet",
+                    "email": "stof@notk.org"
+                },
+                {
+                    "name": "KnpLabs",
+                    "homepage": "http://knplabs.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "https://github.com/KnpLabs/KnpMenu/contributors"
+                }
+            ],
+            "description": "An object oriented menu library",
+            "homepage": "http://knplabs.com",
+            "keywords": [
+                "menu",
+                "tree"
+            ]
+        },
+        {
+            "name": "monolog/monolog",
+            "version": "dev-master",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/Seldaek/monolog",
+                "reference": "1.3.1"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/Seldaek/monolog/archive/1.3.1.zip",
+                "reference": "1.3.1",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.0",
+                "psr/log": ">=1.0,<2.0"
+            },
+            "require-dev": {
+                "mlehner/gelf-php": "1.0.*",
+                "doctrine/couchdb": "dev-master",
+                "raven/raven": "0.3.*"
+            },
+            "suggest": {
+                "mlehner/gelf-php": "Allow sending log messages to a GrayLog2 server",
+                "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)",
+                "ext-mongo": "Allow sending log messages to a MongoDB server",
+                "doctrine/couchdb": "Allow sending log messages to a CouchDB server",
+                "raven/raven": "Allow sending log messages to a Sentry server"
+            },
+            "time": "2013-01-11 10:23:20",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.3.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Monolog": "src/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Jordi Boggiano",
+                    "email": "j.boggiano@seld.be",
+                    "homepage": "http://seld.be",
+                    "role": "Developer"
+                }
+            ],
+            "description": "Sends your logs to files, sockets, inboxes, databases and various web services",
+            "homepage": "http://github.com/Seldaek/monolog",
+            "keywords": [
+                "log",
+                "logging",
+                "psr-3"
+            ]
+        },
+        {
+            "name": "pagerfanta/pagerfanta",
+            "version": "dev-master",
+            "source": {
+                "type": "git",
+                "url": "git://github.com/whiteoctober/Pagerfanta.git",
+                "reference": "12f71d99457b018fb80746f84514dd5b495c5789"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/whiteoctober/Pagerfanta/archive/12f71d99457b018fb80746f84514dd5b495c5789.zip",
+                "reference": "12f71d99457b018fb80746f84514dd5b495c5789",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.0"
+            },
+            "suggest": {
+                "doctrine/orm": "2.*",
+                "doctrine/mongodb-odm": "2.*",
+                "solarium/solarium": "2.*"
+            },
+            "time": "2012-08-22 21:56:31",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Pagerfanta\\": "src/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Pablo Díez",
+                    "email": "pablodip@gmail.com",
+                    "homepage": "http://github.com/pablodip"
+                }
+            ],
+            "description": "Pagination for PHP 5.3",
+            "keywords": [
+                "page",
+                "paging"
+            ]
+        },
+        {
+            "name": "pimple/pimple",
+            "version": "dev-master",
+            "source": {
+                "type": "git",
+                "url": "git://github.com/fabpot/Pimple.git",
+                "reference": "d58cec632dfdd3305d6b4f2563a5cf2a75b4d978"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/fabpot/Pimple/archive/d58cec632dfdd3305d6b4f2563a5cf2a75b4d978.zip",
+                "reference": "d58cec632dfdd3305d6b4f2563a5cf2a75b4d978",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.0"
+            },
+            "time": "2013-01-07 10:39:26",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.0.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Pimple": "lib/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                }
+            ],
+            "description": "Pimple is a simple Dependency Injection Container for PHP 5.3",
+            "homepage": "http://pimple.sensiolabs.org",
+            "keywords": [
+                "dependency injection",
+                "container"
+            ]
+        },
+        {
+            "name": "psr/log",
+            "version": "1.0.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/php-fig/log",
+                "reference": "1.0.0"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/php-fig/log/archive/1.0.0.zip",
+                "reference": "1.0.0",
+                "shasum": ""
+            },
+            "time": "2012-12-21 11:40:51",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Psr\\Log\\": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "PHP-FIG",
+                    "homepage": "http://www.php-fig.org/"
+                }
+            ],
+            "description": "Common interface for logging libraries",
+            "keywords": [
+                "log",
+                "psr",
+                "psr-3"
+            ]
+        },
+        {
+            "name": "silex/silex",
+            "version": "dev-master",
+            "source": {
+                "type": "git",
+                "url": "git://github.com/fabpot/Silex.git",
+                "reference": "ec01b080852ee85bbb4ae5abd7fa205df9824079"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/fabpot/Silex/archive/ec01b080852ee85bbb4ae5abd7fa205df9824079.zip",
+                "reference": "ec01b080852ee85bbb4ae5abd7fa205df9824079",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3",
+                "pimple/pimple": "1.*",
+                "symfony/event-dispatcher": ">=2.1,<2.3-dev",
+                "symfony/http-foundation": ">=2.1,<2.3-dev",
+                "symfony/http-kernel": ">=2.1,<2.3-dev",
+                "symfony/routing": ">=2.1,<2.3-dev"
+            },
+            "require-dev": {
+                "monolog/monolog": ">=1.0.0,<1.2-dev",
+                "twig/twig": ">=1.8.0,<2.0-dev",
+                "swiftmailer/swiftmailer": "4.2.*",
+                "doctrine/dbal": ">=2.2.0,<2.4.0-dev",
+                "symfony/security": ">=2.1,<2.3-dev",
+                "symfony/config": ">=2.1,<2.3-dev",
+                "symfony/locale": ">=2.1,<2.3-dev",
+                "symfony/form": ">=2.1,<2.3-dev",
+                "symfony/browser-kit": ">=2.1,<2.3-dev",
+                "symfony/css-selector": ">=2.1,<2.3-dev",
+                "symfony/finder": ">=2.1,<2.3-dev",
+                "symfony/monolog-bridge": ">=2.1,<2.3-dev",
+                "symfony/process": ">=2.1,<2.3-dev",
+                "symfony/translation": ">=2.1,<2.3-dev",
+                "symfony/twig-bridge": ">=2.1,<2.3-dev",
+                "symfony/validator": ">=2.1,<2.3-dev",
+                "symfony/serializer": ">=2.1,<2.3-dev"
+            },
+            "suggest": {
+                "symfony/browser-kit": ">=2.1,<2.3-dev",
+                "symfony/css-selector": ">=2.1,<2.3-dev",
+                "symfony/dom-crawler": ">=2.1,<2.3-dev"
+            },
+            "time": "2013-01-17 12:25:17",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.0.x-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Silex": "src/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Igor Wiedler",
+                    "email": "igor@wiedler.ch",
+                    "homepage": "http://wiedler.ch/igor/"
+                }
+            ],
+            "description": "The PHP micro-framework based on the Symfony2 Components",
+            "homepage": "http://silex.sensiolabs.org",
+            "keywords": [
+                "microframework"
+            ]
+        },
+        {
+            "name": "swiftmailer/swiftmailer",
+            "version": "v4.1.8",
+            "source": {
+                "type": "git",
+                "url": "git://github.com/swiftmailer/swiftmailer.git",
+                "reference": "v4.1.8"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/swiftmailer/swiftmailer/zipball/v4.1.8",
+                "reference": "v4.1.8",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.2.4"
+            },
+            "time": "2012-06-17 13:55:34",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "4.1-dev"
+                }
+            },
+            "autoload": {
+                "files": [
+                    "lib/swift_required.php"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "LGPL"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Chris Corbyn"
+                }
+            ],
+            "description": "Swiftmailer, free feature-rich PHP mailer",
+            "homepage": "http://swiftmailer.org",
+            "keywords": [
+                "mail",
+                "mailer"
+            ]
+        },
+        {
+            "name": "symfony/config",
+            "version": "dev-master",
+            "target-dir": "Symfony/Component/Config",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/Config",
+                "reference": "072211a77a4bd89b26bb840fdd7d83253bc20f25"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/Config/archive/072211a77a4bd89b26bb840fdd7d83253bc20f25.zip",
+                "reference": "072211a77a4bd89b26bb840fdd7d83253bc20f25",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "time": "2013-01-17 15:25:59",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.2-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\Config\\": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony Config Component",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "symfony/console",
+            "version": "dev-master",
+            "target-dir": "Symfony/Component/Console",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/Console",
+                "reference": "b76fc0d327cb8d90ef0d685f3d696dab714b8327"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/Console/archive/b76fc0d327cb8d90ef0d685f3d696dab714b8327.zip",
+                "reference": "b76fc0d327cb8d90ef0d685f3d696dab714b8327",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "time": "2013-01-17 15:25:59",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.2-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\Console\\": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony Console Component",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "symfony/dependency-injection",
+            "version": "dev-master",
+            "target-dir": "Symfony/Component/DependencyInjection",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/DependencyInjection",
+                "reference": "e8bf1159bfbc4a889b3b0d251f75fd6ae1931656"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/DependencyInjection/archive/e8bf1159bfbc4a889b3b0d251f75fd6ae1931656.zip",
+                "reference": "e8bf1159bfbc4a889b3b0d251f75fd6ae1931656",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "require-dev": {
+                "symfony/yaml": "2.2.*",
+                "symfony/config": "2.2.*"
+            },
+            "suggest": {
+                "symfony/yaml": "2.2.*",
+                "symfony/config": "2.2.*"
+            },
+            "time": "2013-01-17 21:22:20",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.2-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\DependencyInjection\\": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony DependencyInjection Component",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "symfony/event-dispatcher",
+            "version": "2.1.x-dev",
+            "target-dir": "Symfony/Component/EventDispatcher",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/EventDispatcher",
+                "reference": "v2.1.7"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/EventDispatcher/archive/v2.1.7.zip",
+                "reference": "v2.1.7",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "require-dev": {
+                "symfony/dependency-injection": "2.1.*"
+            },
+            "suggest": {
+                "symfony/dependency-injection": "2.1.*",
+                "symfony/http-kernel": "2.1.*"
+            },
+            "time": "2013-01-11 00:31:43",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\EventDispatcher": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony EventDispatcher Component",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "symfony/form",
+            "version": "2.1.x-dev",
+            "target-dir": "Symfony/Component/Form",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/Form",
+                "reference": "v2.1.7"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/Form/archive/v2.1.7.zip",
+                "reference": "v2.1.7",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3",
+                "symfony/event-dispatcher": "2.1.*",
+                "symfony/locale": "2.1.*",
+                "symfony/options-resolver": "2.1.*"
+            },
+            "require-dev": {
+                "symfony/validator": "2.1.*",
+                "symfony/http-foundation": "2.1.*"
+            },
+            "suggest": {
+                "symfony/validator": "2.1.*",
+                "symfony/http-foundation": "2.1.*"
+            },
+            "time": "2013-01-11 13:37:17",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\Form": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony Form Component",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "symfony/http-foundation",
+            "version": "2.1.x-dev",
+            "target-dir": "Symfony/Component/HttpFoundation",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/HttpFoundation",
+                "reference": "v2.1.7"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/HttpFoundation/archive/v2.1.7.zip",
+                "reference": "v2.1.7",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "time": "2013-01-11 00:31:43",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\HttpFoundation": "",
+                    "SessionHandlerInterface": "Symfony/Component/HttpFoundation/Resources/stubs"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony HttpFoundation Component",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "symfony/http-kernel",
+            "version": "2.1.x-dev",
+            "target-dir": "Symfony/Component/HttpKernel",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/HttpKernel",
+                "reference": "e57b260d74b04671d26cc37c2049b90924bb636d"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/HttpKernel/archive/e57b260d74b04671d26cc37c2049b90924bb636d.zip",
+                "reference": "e57b260d74b04671d26cc37c2049b90924bb636d",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3",
+                "symfony/event-dispatcher": "2.1.*",
+                "symfony/http-foundation": "2.1.*"
+            },
+            "require-dev": {
+                "symfony/browser-kit": "2.1.*",
+                "symfony/class-loader": "2.1.*",
+                "symfony/config": "2.1.*",
+                "symfony/console": "2.1.*",
+                "symfony/dependency-injection": "2.1.*",
+                "symfony/finder": "2.1.*",
+                "symfony/process": "2.1.*",
+                "symfony/routing": "2.1.*"
+            },
+            "suggest": {
+                "symfony/browser-kit": "2.1.*",
+                "symfony/class-loader": "2.1.*",
+                "symfony/config": "2.1.*",
+                "symfony/console": "2.1.*",
+                "symfony/dependency-injection": "2.1.*",
+                "symfony/finder": "2.1.*"
+            },
+            "time": "2013-01-17 23:11:33",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\HttpKernel": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony HttpKernel Component",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "symfony/locale",
+            "version": "2.1.x-dev",
+            "target-dir": "Symfony/Component/Locale",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/Locale",
+                "reference": "v2.1.7"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/Locale/archive/v2.1.7.zip",
+                "reference": "v2.1.7",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "suggest": {
+                "ext-intl": ">=5.3.3"
+            },
+            "time": "2013-01-10 04:41:59",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\Locale": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony Locale Component",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "symfony/options-resolver",
+            "version": "2.1.x-dev",
+            "target-dir": "Symfony/Component/OptionsResolver",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/OptionsResolver",
+                "reference": "v2.1.7"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/OptionsResolver/archive/v2.1.7.zip",
+                "reference": "v2.1.7",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "time": "2013-01-09 08:51:07",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\OptionsResolver": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony OptionsResolver Component",
+            "homepage": "http://symfony.com",
+            "keywords": [
+                "configuration",
+                "config",
+                "options"
+            ]
+        },
+        {
+            "name": "symfony/routing",
+            "version": "dev-master",
+            "target-dir": "Symfony/Component/Routing",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/Routing",
+                "reference": "9ce05861fd9aa6cbb14759a78ab30d07afcf489f"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/Routing/archive/9ce05861fd9aa6cbb14759a78ab30d07afcf489f.zip",
+                "reference": "9ce05861fd9aa6cbb14759a78ab30d07afcf489f",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "require-dev": {
+                "doctrine/common": ">=2.2,<2.4-dev",
+                "symfony/config": "2.2.*",
+                "symfony/yaml": "2.2.*",
+                "symfony/http-kernel": "2.2.*",
+                "psr/log": ">=1.0,<2.0"
+            },
+            "suggest": {
+                "doctrine/common": ">=2.2,<2.4-dev",
+                "symfony/config": "2.2.*",
+                "symfony/yaml": "2.2.*"
+            },
+            "time": "2013-01-17 15:25:59",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.2-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\Routing\\": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony Routing Component",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "symfony/security",
+            "version": "2.1.x-dev",
+            "target-dir": "Symfony/Component/Security",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/Security",
+                "reference": "v2.1.7"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/Security/archive/v2.1.7.zip",
+                "reference": "v2.1.7",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3",
+                "symfony/event-dispatcher": "2.1.*",
+                "symfony/http-foundation": "2.1.*",
+                "symfony/http-kernel": "2.1.*"
+            },
+            "require-dev": {
+                "symfony/form": "2.1.*",
+                "symfony/routing": "2.1.*",
+                "symfony/validator": "2.1.*",
+                "doctrine/common": ">=2.2,<2.4-dev",
+                "doctrine/dbal": ">=2.2,<2.4-dev"
+            },
+            "suggest": {
+                "doctrine/dbal": "to use the built-in ACL implementation",
+                "symfony/class-loader": "2.1.*",
+                "symfony/finder": "2.1.*",
+                "symfony/form": "2.1.*",
+                "symfony/validator": "2.1.*",
+                "symfony/routing": "2.1.*"
+            },
+            "time": "2013-01-09 08:51:07",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\Security": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony Security Component",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "symfony/translation",
+            "version": "2.1.x-dev",
+            "target-dir": "Symfony/Component/Translation",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/Translation",
+                "reference": "v2.1.7"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/Translation/archive/v2.1.7.zip",
+                "reference": "v2.1.7",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "require-dev": {
+                "symfony/config": "2.1.*",
+                "symfony/yaml": "2.1.*"
+            },
+            "suggest": {
+                "symfony/config": "2.1.*",
+                "symfony/yaml": "2.1.*"
+            },
+            "time": "2013-01-09 08:51:07",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\Translation": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony Translation Component",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "symfony/twig-bridge",
+            "version": "dev-master",
+            "target-dir": "Symfony/Bridge/Twig",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/TwigBridge",
+                "reference": "b332bd4a0ffd0d5775d22e80cd14d0433c286027"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/TwigBridge/archive/b332bd4a0ffd0d5775d22e80cd14d0433c286027.zip",
+                "reference": "b332bd4a0ffd0d5775d22e80cd14d0433c286027",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3",
+                "twig/twig": ">=1.9.1,<2.0-dev"
+            },
+            "require-dev": {
+                "symfony/form": "2.2.*",
+                "symfony/routing": "2.2.*",
+                "symfony/templating": "2.2.*",
+                "symfony/translation": "2.2.*",
+                "symfony/yaml": "2.2.*",
+                "symfony/security": "2.2.*",
+                "symfony/http-kernel": "2.2.*"
+            },
+            "suggest": {
+                "symfony/form": "2.2.*",
+                "symfony/routing": "2.2.*",
+                "symfony/templating": "2.2.*",
+                "symfony/translation": "2.2.*",
+                "symfony/yaml": "2.2.*",
+                "symfony/security": "2.2.*",
+                "symfony/http-kernel": "2.2.*"
+            },
+            "time": "2013-01-17 15:25:59",
+            "type": "symfony-bridge",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.2-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Bridge\\Twig\\": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony Twig Bridge",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "symfony/validator",
+            "version": "2.1.x-dev",
+            "target-dir": "Symfony/Component/Validator",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/Validator",
+                "reference": "v2.1.7"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/Validator/archive/v2.1.7.zip",
+                "reference": "v2.1.7",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "require-dev": {
+                "symfony/http-foundation": "2.1.*",
+                "symfony/locale": "2.1.*",
+                "symfony/yaml": "2.1.*"
+            },
+            "suggest": {
+                "doctrine/common": ">=2.1,<2.4-dev",
+                "symfony/http-foundation": "2.1.*",
+                "symfony/yaml": "2.1.*"
+            },
+            "time": "2013-01-11 00:31:43",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\Validator": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony Validator Component",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "symfony/yaml",
+            "version": "2.1.x-dev",
+            "target-dir": "Symfony/Component/Yaml",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/symfony/Yaml",
+                "reference": "v2.1.7"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/symfony/Yaml/archive/v2.1.7.zip",
+                "reference": "v2.1.7",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.3.3"
+            },
+            "time": "2013-01-17 21:21:51",
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "Symfony\\Component\\Yaml": ""
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Symfony Community",
+                    "homepage": "http://symfony.com/contributors"
+                }
+            ],
+            "description": "Symfony Yaml Component",
+            "homepage": "http://symfony.com"
+        },
+        {
+            "name": "twig/twig",
+            "version": "dev-master",
+            "source": {
+                "type": "git",
+                "url": "git://github.com/fabpot/Twig.git",
+                "reference": "93c6a8dedc46c73ccdd61342de3d5e761e4412f6"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://github.com/fabpot/Twig/archive/93c6a8dedc46c73ccdd61342de3d5e761e4412f6.zip",
+                "reference": "93c6a8dedc46c73ccdd61342de3d5e761e4412f6",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.2.4"
+            },
+            "time": "2013-01-18 09:58:04",
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "1.12-dev"
+                }
+            },
+            "autoload": {
+                "psr-0": {
+                    "Twig_": "lib/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3"
+            ],
+            "authors": [
+                {
+                    "name": "Fabien Potencier",
+                    "email": "fabien@symfony.com"
+                },
+                {
+                    "name": "Armin Ronacher",
+                    "email": "armin.ronacher@active-4.com"
+                }
+            ],
+            "description": "Twig, the flexible, fast, and secure template language for PHP",
+            "homepage": "http://twig.sensiolabs.org",
+            "keywords": [
+                "templating"
+            ]
+        }
+    ],
+    "packages-dev": null,
+    "aliases": [
+
+    ],
+    "minimum-stability": "dev",
+    "stability-flags": {
+        "silex/silex": 20,
+        "symfony/config": 20,
+        "symfony/console": 20,
+        "symfony/twig-bridge": 20,
+        "symfony/dependency-injection": 20,
+        "dflydev/doctrine-orm-service-provider": 20,
+        "doctrine/migrations": 20,
+        "pagerfanta/pagerfanta": 20,
+        "knplabs/knp-menu": 20,
+        "gedmo/doctrine-extensions": 20
+    }
+}

+ 17 - 2
documentation/changelog.html

@@ -44,6 +44,23 @@
 <p><i>Note: most #wxyz references are issue numbers you can find in <a href="http://support.chamilo.org/projects/chamilo-18/issues" target="_blank">our public bug tracking system</a>. Some references marked BT#xyz are developments made externally for BeezNest customers and integrated into Chamilo. The details of these tasks cannot be seen for confidentiality reasons, but the code change is public and can be reviewed by anyone.</i></p>
 <p>&nbsp;</p>
 
+
+<h1>Chamilo 1.10.0 - ???, 31st of ???, 2012</h1>
+<h3>Release notes - summary</h3>
+<p>Chamilo 1.10.0 is a major stable version with loads of added features.</p>
+
+<h3>Release name</h3>
+<p><a href="http://fr.wikipedia.org/wiki/Vog%C3%BC%C3%A9">Vogüé</a> is a small town in the French region of Rhône-Alpes, and one of the most beautiful villages of France. It features a 12th century, a generally very pretty landscape and is one of the few remote towns in current growth. One of our new development team members chose this familiar town because it inspires stability and diversity.</p>
+
+<h3>New Features</h3>
+<h3>Improvements</h3>
+<h3>Debugging</h3>
+<h3>Important changes</h3>
+<ul>
+  <li>Users and sessions extra fields of "double select" type have a modified syntax. If you used this field type in a previous version of Chamilo, you will probably need to update it manually from the database.</li>
+  <li></li>
+</ul>
+
 <h1>Chamilo 1.9.4 - Puebla, 18th of January, 2013</h1>
 <h3>Release notes - summary</h3>
 <p>Chamilo 1.9.4 is a minor stable version with a series of improvements on top of 1.9.2.</p>
@@ -312,7 +329,6 @@
   <li>Added session-box-text and session-item elements to improve styling</li>
   <li>Modified #main_content to #top_main_content to avoid double #main_content id on the same page</li>
 </ul>
-  
 
 
 <h1>Chamilo 1.9.2 - Hanga Roa, 27th of September, 2012</h1>
@@ -410,7 +426,6 @@
   <li>Social network: An user could not modify its own official code, even if configured to be possible (#5538)</li>
 </ul>
 
-
 <h1>Chamilo 1.9.0 - Vogüé, 31st of July, 2012</h1>
 
 <h3>Release notes - summary</h3>

+ 2 - 4
htaccess

@@ -13,8 +13,6 @@ RewriteCond %{QUERY_STRING} ^id=(.*)$
 RewriteRule ^certificates/$ certificates/index.php?id=%1 [L]
 RewriteRule ^([^/.]+)/?$ user.php?$1 [L]
 
-
-
 # This will transform
-# http://my.chamilo.net/certificates/?id=123     to  http://my.chamilo.net/certificates/index.php?id=123 
-# http://my.chamilo.net/juliomontoya		to		 http://my.chamilo.net/user.php?juliomontoya 
+# http://my.chamilo.net/certificates/index.php?id=123 to http://my.chamilo.net/certificates/123
+# http://my.chamilo.net/user.php?jmontoya  to http://my.chamilo.net/jmontoya

+ 210 - 133
index.php

@@ -3,176 +3,253 @@
 
 /**
  * @package chamilo.main
- */
-
-
-use \ChamiloSession as Session;
+*/
 
 define('CHAMILO_HOMEPAGE', true);
 
 $language_file = array('courses', 'index');
 
-/* Flag forcing the 'current course' reset, as we're not inside a course anymore. */
+// Flag forcing the 'current course' reset, as we're not inside a course anymore.
 // Maybe we should change this into an api function? an example: CourseManager::unset();
 $cidReset = true;
 
 require_once 'main/inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'userportal.lib.php';
 require_once 'main/chat/chat_functions.lib.php';
 
 // The section (for the tabs).
 $this_section = SECTION_CAMPUS;
 
-$header_title = null;
-if (!api_is_anonymous()) {
-	$header_title = " ";
-}
-
 $htmlHeadXtra[] = api_get_jquery_libraries_js(array('bxslider'));
 $htmlHeadXtra[] ='
-<script type="text/javascript">
+<script>
 	$(document).ready(function(){
 		$("#slider").bxSlider({
 			infiniteLoop	: true,
 			auto			: true,
 			pager			: true,
 			autoHover		: true,
-			pause			: 10000
+		pause			: 10000
 		});
 	});
 </script>';
 
 //set cookie for check if client browser are cookies enabled
-setcookie('TestCookie', 'cookies_yes', time()+3600*24*31*12);
-
-$controller = new IndexManager($header_title);
-
-//Actions
-$loginFailed = isset($_GET['loginFailed']) ? true : isset($loginFailed);
-
-if (!empty($_GET['logout'])) {
-	$controller->logout();
-}
-
-/* Table definitions */
-
-/* Constants and CONFIGURATION parameters */
-/** @todo these configuration settings should move to the Chamilo config settings. */
+//setcookie('TestCookie', 'cookies_yes', time()+3600*24*31*12);
+//use Symfony\Component\HttpFoundation\Cookie;
+//$cookie = new Cookie('TestCookie', 'cookies_yes', time()+3600*24*31*12);
+//$response->headers->setCookie($cookie);
+
+use Silex\Application;
+use Symfony\Component\HttpFoundation\Response;
+
+class IndexController
+{
+    public function indexAction(Application $app) {
+        $request = $app['request'];
+
+        //Actions
+        $logout = $request->get('logout');
+
+        if (!empty($logout)) {
+            $this->logout();
+        }
+
+        //$article = $app['orm.em']->getRepository('Entity\EntityCourse');
+        //$courses_query = $app['orm.em']->createQuery('SELECT a FROM Entity\EntityCourse a');
+
+        //$a = new EntityCourse();
+//require_once '/var/www/chamilo11/main/inc/Entity/EntityCourse.php';
+        //$article = $app['orm.em']->getRepository('EntityCourse');
+        //var_dump($article);
+
+        //$courses_query = $app['orm.em']->createQuery('SELECT a FROM Entity\EntityCourse a');
+/*
+        $paginator = new Doctrine\ORM\Tools\Pagination\Paginator($courses_query, $fetchJoinCollection = true);
+        $c = count($paginator);
+        foreach ($paginator as $course) {
+            echo $course->getCode() . "\n";
+        }
+        exit;*/
+
+        //$app['orm.em']->find('EntityCourse', 1);
+        //var_dump($app['orm.ems']['mysql']);
+
+
+        // Defines wether or not anonymous visitors can see a list of the courses on the Chamilo homepage that are open to the world.
+        //$_setting['display_courses_to_anonymous_users'] = 'true';
+
+        // Delete session neccesary for legal terms
+        if (api_get_setting('allow_terms_conditions') == 'true') {
+            unset($_SESSION['term_and_condition']);
+        }
+
+        //If we are not logged in and customapages activated
+        if (!api_get_user_id() && CustomPages::enabled()) {
+            $logged_out = $request->get('loggedout');
+            if ($logged_out) {
+                CustomPages::display(CustomPages::LOGGED_OUT);
+            } else {
+                CustomPages::display(CustomPages::INDEX_UNLOGGED);
+            }
+        }
+
+        //$this->check_last_login();
+
+        if (api_get_setting('display_categories_on_homepage') == 'true') {
+            $app['template']->assign('course_category_block', PageController::return_courses_in_categories());
+        }
+
+        // Facebook connexion, if activated
+        if (api_is_facebook_auth_activated() && !api_get_user_id()) {
+            facebook_connect();
+        }
+
+        $this->set_login_form($app);
+
+        if (!api_is_anonymous()) {
+            PageController::return_profile_block();
+
+            PageController::return_user_image_block();
+
+            if (api_is_platform_admin()) {
+                PageController::return_course_block();
+            } else {
+                PageController::return_teacher_link();
+            }
+        }
+
+        //Hot courses & announcements
+        $hot_courses = null;
+        $announcements_block = null;
+
+        // When loading a chamilo page do not include the hot courses and news
+        if (!isset($_REQUEST['include'])) {
+            if (api_get_setting('show_hot_courses') == 'true') {
+                $hot_courses = PageController::return_hot_courses();
+            }
+            $announcements_block = PageController::return_announcements();
+        }
+
+        $app['template']->assign('hot_courses',              $hot_courses);
+        $app['template']->assign('announcements_block', 	 $announcements_block);
+
+        //Homepage
+        $app['template']->assign('home_page_block', 		 PageController::return_home_page());
+
+        //Navigation links
+        $nav_links = $app['template']->return_navigation_links();
 
-/** Defines wether or not anonymous visitors can see a list of the courses on the Chamilo homepage that are open to the world. */
-$_setting['display_courses_to_anonymous_users'] = 'true';
+        $app['template']->assign('navigation_course_links',  $nav_links);
+        $app['template']->assign('main_navigation_block',	 $nav_links);
 
-/* LOGIN */
+        PageController::return_notice();
+        PageController::return_help();
+
+        if (api_is_platform_admin() || api_is_drh()) {
+            PageController::return_skills_links();
+        }
+        $response = $app['template']->render_layout('layout_2_col.tpl');
 
-/**
- * @todo This piece of code should probably move to local.inc.php where the actual login / logout procedure is handled.
- * @todo Consider removing this piece of code because does nothing.
- */
-if (isset($_GET['submitAuth']) && $_GET['submitAuth'] == 1) {
-	// nice lie!!!
-	echo 'Attempted breakin - sysadmins notified.';
-	session_destroy();
-	die();
-}
+        //return new Response($response, 200, array('Cache-Control' => 's-maxage=3600, public'));
+        return new Response($response, 200, array());
+    }
 
-// Delete session neccesary for legal terms
-if (api_get_setting('allow_terms_conditions') == 'true') {
-	unset($_SESSION['term_and_condition']);
-}
-//If we are not logged in and customapages activated
-if (!api_get_user_id() && CustomPages::enabled()) {
-    if (Request::get('loggedout')) {
-        CustomPages::display(CustomPages::LOGGED_OUT);
-    } else {
-        CustomPages::display(CustomPages::INDEX_UNLOGGED);
+    /**
+     *
+    * @todo This piece of code should probably move to local.inc.php where the actual login procedure is handled.
+    * @todo Check if this code is used. I think this code is never executed because after clicking the submit button
+    *       the code does the stuff in local.inc.php and then redirects to index.php or user_portal.php depending
+    *       on api_get_setting('page_after_login').
+     * @deprecated seems not to be used
+    */
+    function check_last_login() {
+        if (!empty($_POST['submitAuth'])) {
+            // The user has been already authenticated, we are now to find the last login of the user.
+            if (!empty($this->user_id)) {
+                $track_login_table      = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+                $sql_last_login = "SELECT login_date
+                                    FROM $track_login_table
+                                    WHERE login_user_id = '".$this->user_id."'
+                                    ORDER BY login_date DESC LIMIT 1";
+                $result_last_login = Database::query($sql_last_login);
+                if (!$result_last_login) {
+                    if (Database::num_rows($result_last_login) > 0) {
+                        $user_last_login_datetime = Database::fetch_array($result_last_login);
+                        $user_last_login_datetime = $user_last_login_datetime[0];
+                        Session::write('user_last_login_datetime', $user_last_login_datetime);
+                    }
+                }
+                Database::free_result($result_last_login);
+
+                if (api_is_platform_admin()) {
+                    // decode all open event informations and fill the track_c_* tables
+                    include api_get_path(LIBRARY_PATH).'stats.lib.inc.php';
+                    decodeOpenInfos();
+                }
+            }
+            // End login -- if ($_POST['submitAuth'])
+        } else {
+            // Only if login form was not sent because if the form is sent the user was already on the page.
+            event_open();
+        }
     }
-}
 
-/**
- * @todo This piece of code should probably move to local.inc.php where the actual login procedure is handled.
- * @todo Check if this code is used. I think this code is never executed because after clicking the submit button
- *       the code does the stuff in local.inc.php and then redirects to index.php or user_portal.php depending
- *       on api_get_setting('page_after_login').
- */
-
-if (!empty($_POST['submitAuth'])) {
-	// The user has been already authenticated, we are now to find the last login of the user.
-	if (isset ($_user['user_id'])) {
-		$track_login_table      = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-		$sql_last_login = "SELECT UNIX_TIMESTAMP(login_date)
-                                FROM $track_login_table
-                                WHERE login_user_id = '".$_user['user_id']."'
-                                ORDER BY login_date DESC LIMIT 1";
-		$result_last_login = Database::query($sql_last_login);
-		if (!$result_last_login) {
-			if (Database::num_rows($result_last_login) > 0) {
-				$user_last_login_datetime = Database::fetch_array($result_last_login);
-				$user_last_login_datetime = $user_last_login_datetime[0];
-				Session::write('user_last_login_datetime',$user_last_login_datetime);
+    function set_login_form(Application $app) {
+        $user_id = api_get_user_id();
+        $login_form = null;
+        if (!$user_id || api_is_anonymous($user_id)) {
+
+			// Only display if the user isn't logged in.
+			$app['template']->assign('login_language_form', api_display_language_form(true));
+            //self::display_login_form($app);
+
+			$app['template']->assign('login_form',  self::display_login_form($app));
+
+			if (api_get_setting('allow_lostpassword') == 'true' || api_get_setting('allow_registration') == 'true') {
+				$login_form .= '<ul class="nav nav-list">';
+				if (api_get_setting('allow_registration') != 'false') {
+					$login_form .= '<li><a href="main/auth/inscription.php">'.get_lang('Reg').'</a></li>';
+				}
+				if (api_get_setting('allow_lostpassword') == 'true') {
+					$login_form .= '<li><a href="main/auth/lostPassword.php">'.get_lang('LostPassword').'</a></li>';
+				}
+				$login_form .= '</ul>';
 			}
-		}
-		Database::free_result($result_last_login);
+			$app['template']->assign('login_options',  $login_form);
+        }
+    }
 
-		//event_login();
-		if (api_is_platform_admin()) {
-			// decode all open event informations and fill the track_c_* tables
-			include api_get_path(LIBRARY_PATH).'stats.lib.inc.php';
-			decodeOpenInfos();
-		}
+    function logout() {
+        $user_id = api_get_user_id();
+        online_logout($user_id, true);
 	}
-	// End login -- if ($_POST['submitAuth'])
-} else {
-	// Only if login form was not sent because if the form is sent the user was already on the page.
-	event_open();
-}
-
-if (api_get_setting('display_categories_on_homepage') == 'true') {
-	$controller->tpl->assign('course_category_block', $controller->return_courses_in_categories());
-}
-
-// Facebook connexion, if activated
-if (api_is_facebook_auth_activated() && !api_get_user_id()) {
-    facebook_connect();
-}
 
-$controller->set_login_form();
-
-//@todo move this inside the IndexManager
-if (!api_is_anonymous()) {
-	$controller->tpl->assign('profile_block', $controller->return_profile_block());
-    $controller->tpl->assign('user_image_block', $controller->return_user_image_block());    
-
-	if (api_is_platform_admin()) {
-		$controller->tpl->assign('course_block',			$controller->return_course_block());
-	} else {
-		$controller->tpl->assign('teacher_block', 			$controller->return_teacher_link());
+    function display_login_form(Application $app) {
+         /*{{ form_widget(form) }}
+         $form = $app['form.factory']->createBuilder('form')
+        ->add('name')
+        ->add('email')
+        ->add('gender', 'choice', array(
+            'choices' => array(1 => 'male', 2 => 'female'),
+            'expanded' => true,
+        ))
+        ->getForm();
+        return $app['template']->assign('form', $form->createView());
+*/
+
+		$form = new FormValidator('formLogin', 'POST', null,  null, array('class'=>'form-vertical'));
+        $form->addElement('text', 'login', get_lang('UserName'), array('class' => 'span2 autocapitalize_off', 'autofocus' => 'autofocus'));
+		$form->addElement('password', 'password', get_lang('Pass'), array('class' => 'span2'));
+		$form->addElement('style_submit_button','submitAuth', get_lang('LoginEnter'), array('class' => 'btn'));
+		$html = $form->return_form();
+		if (api_get_setting('openid_authentication') == 'true') {
+			include_once 'main/auth/openid/login.php';
+			$html .= '<div>'.openid_form().'</div>';
+		}
+		return $html;
 	}
 }
 
-$hot_courses = null;
-$announcements_block = null;
-
-// When loading a chamilo page do not include the hot courses and news
-
-if (!isset($_REQUEST['include'])) {
-    if (api_get_setting('show_hot_courses') == 'true') {
-        $hot_courses = $controller->return_hot_courses();
-    }
-    $announcements_block = $controller->return_announcements();
-}
-
-$controller->tpl->assign('hot_courses',             $hot_courses);
-$controller->tpl->assign('announcements_block', 	$announcements_block);
-$controller->tpl->assign('home_page_block', 		$controller->return_home_page());
-
-$controller->tpl->assign('navigation_course_links', 	$controller->return_navigation_links());
-
-$controller->tpl->assign('notice_block',			$controller->return_notice());
-$controller->tpl->assign('main_navigation_block',	$controller->return_navigation_links());
-$controller->tpl->assign('help_block',              $controller->return_help());
-
-if (api_is_platform_admin() || api_is_drh()) {
-    $controller->tpl->assign('skills_block',            $controller->return_skills_links());
-}
-
-$controller->tpl->display_two_col_template();
+$app->match('/', 'IndexController::indexAction', 'POST|GET');
+$app->run();
+//$app['http_cache']->run();

+ 1 - 1
main/admin/access_url_add_courses_to_url.php

@@ -14,8 +14,8 @@ $cidReset = true;
 require_once '../inc/global.inc.php';
 $this_section=SECTION_PLATFORM_ADMIN;
 
-require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
 api_protect_global_admin_script();
+
 if (!api_get_multiple_access_url()) {
 	header('Location: index.php');
 	exit;

+ 1 - 2
main/admin/access_url_add_users_to_url.php

@@ -12,9 +12,8 @@
 $language_file = 'admin';
 $cidReset = true;
 require_once '../inc/global.inc.php';
-$this_section=SECTION_PLATFORM_ADMIN;
+$this_section = SECTION_PLATFORM_ADMIN;
 
-require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
 api_protect_global_admin_script();
 if (!api_get_multiple_access_url()) {
 	header('Location: index.php');

+ 0 - 2
main/admin/access_url_check_user_session.php

@@ -11,8 +11,6 @@ $language_file = 'admin';
 $cidReset = true;
 require_once '../inc/global.inc.php';
 
-require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
-
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;
 

+ 115 - 103
main/admin/access_url_edit.php

@@ -1,10 +1,14 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
-*	@package chamilo.admin
-*	@author Julio Montoya <gugli100@gmail.com>
-*/
-
+ * Create or edit access urls and branches
+ * @package chamilo.admin
+ * @author Julio Montoya <gugli100@gmail.com>
+ * @author Yannick Warnier <yannick.warnier@beeznest.com>
+ */
+/**
+ * Initialization
+ */
 $language_file = 'admin';
 $cidReset = true;
 require_once '../inc/global.inc.php';
@@ -14,104 +18,108 @@ $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_global_admin_script();
 
 if (!api_get_multiple_access_url()) {
-	header('Location: index.php');
-	exit;
+    header('Location: index.php');
+    exit;
 }
 
-require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
-
 // Create the form
 $form = new FormValidator('add_url');
 
 if( $form->validate()) {
-	$check = Security::check_token('post');
-	if($check) {
-		$url_array = $form->getSubmitValues();
-		$url = Security::remove_XSS($url_array['url']);
-		$description = Security::remove_XSS($url_array['description']);
-		$active = intval($url_array['active']);
-		$url_id = $url_array['id'];
-		$url_to_go='access_urls.php';
-		if ($url_id!='') {
-			//we can't change the status of the url with id=1
-			if ($url_id==1)
-				$active=1;
-			//checking url
-			if (substr($url,strlen($url)-1, strlen($url))=='/') {
-				UrlManager::udpate($url_id, $url, $description, $active);
-			} else {
-				UrlManager::udpate($url_id, $url.'/', $description, $active);
-			}
-			// URL Images
-			$url_images_dir = api_get_path(SYS_PATH).'custompages/url-images/';
-			$image_fields = array("url_image_1", "url_image_2", "url_image_3");
-			foreach ($image_fields as $image_field) {
-				if ($_FILES[$image_field]['error'] == 0) {
-					// Hardcoded: only PNG files allowed
-					if (end(explode('.', $_FILES[$image_field]['name'])) == 'png') {
-						move_uploaded_file($_FILES[$image_field]['tmp_name'], $url_images_dir.$url_id.'_'.$image_field.'.png');
-					}
-					// else fail silently
-				}
-				// else fail silently
-			}
-			$url_to_go='access_urls.php';
-			$message=get_lang('URLEdited');
-		} else {
-			$num = UrlManager::url_exist($url);
-			if ($num == 0) {
-				//checking url
-				if (substr($url,strlen($url)-1, strlen($url))=='/') {
-					UrlManager::add($url, $description, $active);
-				} else {
-					//create
-					UrlManager::add($url.'/', $description, $active);
-				}
-				$message = get_lang('URLAdded');
-				$url_to_go='access_urls.php';
-			} else {
-				$url_to_go='access_url_edit.php';
-				$message = get_lang('URLAlreadyAdded');
-			}
-			// URL Images
-			$url .= (substr($url,strlen($url)-1, strlen($url))=='/') ? '' : '/';
-			$url_id = UrlManager::get_url_id($url);
-			$url_images_dir = api_get_path(SYS_PATH).'custompages/url-images/';
-			$image_fields = array("url_image_1", "url_image_2", "url_image_3");
-			foreach ($image_fields as $image_field) {
-				if ($_FILES[$image_field]['error'] == 0) {
-					// Hardcoded: only PNG files allowed
-					if (end(explode('.', $_FILES[$image_field]['name'])) == 'png') {
-						move_uploaded_file($_FILES[$image_field]['tmp_name'], $url_images_dir.$url_id.'_'.$image_field.'.png');
-					}
-					// else fail silently
-				}
-				// else fail silently
-			}
-		}
-		Security::clear_token();
-		$tok = Security::get_token();
-		header('Location: '.$url_to_go.'?action=show_message&message='.urlencode($message).'&sec_token='.$tok);
-		exit();
-	}
+    $check = Security::check_token('post');
+    if($check) {
+        $url_array = $form->getSubmitValues();
+        $url = Security::remove_XSS($url_array['url']);
+        $description = Security::remove_XSS($url_array['description']);
+        $active = intval($url_array['active']);
+        $url_id = $url_array['id'];
+        $url_to_go='access_urls.php';
+        if ($url_id!='') {
+            //we can't change the status of the url with id=1
+            if ($url_id==1)
+                $active=1;
+            //checking url
+            if (substr($url,-1)!=='/') {
+                $url_id .= '/';
+            }
+            UrlManager::udpate($url_id, $url, $description, $active, $url_array['url_type'], $url_array);
+            // URL Images
+            $url_images_dir = api_get_path(SYS_PATH).'custompages/url-images/';
+            $image_fields = array("url_image_1", "url_image_2", "url_image_3");
+            foreach ($image_fields as $image_field) {
+                if ($_FILES[$image_field]['error'] == 0) {
+                    // Hardcoded: only PNG files allowed
+                    if (end(explode('.', $_FILES[$image_field]['name'])) == 'png') {
+                        move_uploaded_file($_FILES[$image_field]['tmp_name'], $url_images_dir.$url_id.'_'.$image_field.'.png');
+                    }
+                    // else fail silently
+                }
+                // else fail silently
+            }
+            $url_to_go='access_urls.php';
+            $message=get_lang('URLEdited');
+        } else {
+            $num = UrlManager::url_exist($url);
+            if ($num == 0) {
+                //checking url
+                if (substr($url,-1)!='/' && $url_array['url_type'] == 1) {
+                    $url.='/';
+                }
+                $url_array['ip'] = $url_array['url'];
+                UrlManager::add($url, $description, $active, $url_array['url_type'], $url_array);
+                $message = get_lang('URLAdded');
+                $url_to_go='access_urls.php';
+            } else {
+                $url_to_go='access_url_edit.php';
+                $message = get_lang('URLAlreadyAdded');
+            }
+            // URL Images
+            $url .= (substr($url,strlen($url)-1, strlen($url))=='/') ? '' : '/';
+            $url_id = UrlManager::get_url_id($url);
+            $url_images_dir = api_get_path(SYS_PATH).'custompages/url-images/';
+            $image_fields = array("url_image_1", "url_image_2", "url_image_3");
+            foreach ($image_fields as $image_field) {
+                if ($_FILES[$image_field]['error'] == 0) {
+                    // Hardcoded: only PNG files allowed
+                    if (end(explode('.', $_FILES[$image_field]['name'])) == 'png') {
+                        move_uploaded_file($_FILES[$image_field]['tmp_name'], $url_images_dir.$url_id.'_'.$image_field.'.png');
+                    }
+                    // else fail silently
+                }
+                // else fail silently
+            }
+        }
+        Security::clear_token();
+        $tok = Security::get_token();
+        header('Location: '.$url_to_go.'?action=show_message&message='.urlencode($message).'&sec_token='.$tok);
+        exit();
+    }
 } else {
-	if(isset($_POST['submit'])) {
-		Security::clear_token();
-	}
-	$token = Security::get_token();
-	$form->addElement('hidden','sec_token');
-	$form->setConstants(array('sec_token' => $token));
+    if(isset($_POST['submit'])) {
+        Security::clear_token();
+    }
+    $token = Security::get_token();
+    $form->addElement('hidden','sec_token');
+    $form->setConstants(array('sec_token' => $token));
 }
 
 
-$form->addElement('text','url', 'URL', array('class'=>'span6'));
+$form->addElement('text','url', get_lang('URLIP'), array('class'=>'span6'));
 $form->addRule('url', get_lang('ThisFieldIsRequired'), 'required');
 $form->addRule('url', '', 'maxlength',254);
+
+$types = array(
+  1=>get_lang('AccessURL'), 
+  2=>get_lang('SincroServer'), 
+  3=>get_lang('SincroClient'),
+);
+$form->addElement('select', 'url_type', get_lang('Type'), $types);
+
 $form->addElement('textarea','description',get_lang('Description'));
 
 //the first url with id = 1 will be always active
 if ($_GET['url_id'] != 1) {
-	$form->addElement('checkbox','active',get_lang('Active'));
+    $form->addElement('checkbox','active',get_lang('Active'));
 }
 
 //$form->addRule('checkbox', get_lang('ThisFieldIsRequired'), 'required');
@@ -121,32 +129,36 @@ $form->setDefaults($defaults);
 
 $submit_name = get_lang('AddUrl');
 if (isset($_GET['url_id'])) {
-	$url_id = Database::escape_string($_GET['url_id']);
-	$num_url_id = UrlManager::url_id_exist($url_id);
-	if($num_url_id != 1) {
-		header('Location: access_urls.php');
-		exit();
-	}
-	$url_data = UrlManager::get_url_data_from_id($url_id);
-	$form->addElement('hidden','id',$url_data['id']);
-	$form->setDefaults($url_data);
-	$submit_name = get_lang('AddUrl');
+    $url_id = Database::escape_string($_GET['url_id']);
+    $num_url_id = UrlManager::url_id_exist($url_id);
+    if($num_url_id != 1) {
+        header('Location: access_urls.php');
+        exit();
+    }
+    $url_data = UrlManager::get_url_data_from_id($url_id);
+    $form->addElement('hidden','id',$url_data['id']);
+    $form->setDefaults($url_data);
+    $submit_name = get_lang('AddUrl');
 }
 
-if (!$_configuration['multiple_access_urls'])
-	header('Location: index.php');
+if (!$_configuration['multiple_access_urls']) {
+    header('Location: index.php');
+}
 
 $tool_name = get_lang('AddUrl');
 $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array ("url" => 'access_urls.php', "name" => get_lang('MultipleAccessURLs'));
+/**
+ * View
+ */
 Display :: display_header($tool_name);
 
 if (isset ($_GET['action'])) {
-	switch ($_GET['action']) {
-		case 'show_message' :
-			Display :: display_normal_message(stripslashes($_GET['message']));
-			break;
-	}
+    switch ($_GET['action']) {
+        case 'show_message' :
+            Display :: display_normal_message(stripslashes($_GET['message']));
+            break;
+    }
 }
 
 // URL Images

+ 0 - 2
main/admin/access_url_edit_courses_to_url.php

@@ -13,8 +13,6 @@ $language_file = 'admin';
 $cidReset = true;
 
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
-require_once api_get_path(LIBRARY_PATH).'access_url_edit_courses_to_url_functions.lib.php';
 
 $xajax = new xajax();
 $xajax -> registerFunction (array('search_courses', 'Accessurleditcoursestourl', 'search_courses'));

+ 154 - 156
main/admin/access_url_edit_users_to_url.php

@@ -1,56 +1,56 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- * 	@package chamilo.admin
- * 	@author Julio Montoya <gugli100@gmail.com>
- */
+*	@package chamilo.admin
+*	@author Julio Montoya <gugli100@gmail.com>
+*/
+
+
 // name of the language file that needs to be included
-$language_file = 'admin';
+$language_file='admin';
 
 // resetting the course id
 $cidReset = true;
 
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH) . 'urlmanager.lib.php';
-require_once api_get_path(LIBRARY_PATH) . 'access_url_edit_users_to_url_functions.lib.php';
 require_once '../inc/lib/xajax/xajax.inc.php';
 $xajax = new xajax();
-//$xajax->debugOn();
-$xajax->registerFunction(array('search_users', 'Accessurledituserstourl', 'search_users'));
 
+$xajax -> registerFunction (array('search_users', 'Accessurledituserstourl', 'search_users'));
 
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;
 
 // Access restrictions
 api_protect_global_admin_script();
+
 if (!api_get_multiple_access_url()) {
-    header('Location: index.php');
-    exit;
+	header('Location: index.php');
+	exit;
 }
 
 
 // Database Table Definitions
-$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
+$tbl_user				 = Database::get_main_table(TABLE_MAIN_USER);
 $tbl_access_url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-$tbl_access_url = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+$tbl_access_url 		 = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
 
 // setting breadcrumbs
 $tool_name = get_lang('EditUsersToURL');
-$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
 
 $add_type = 'multiple';
-if (isset($_REQUEST['add_type']) && $_REQUEST['add_type'] != '') {
-    $add_type = Security::remove_XSS($_REQUEST['add_type']);
+if(isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
+	$add_type = Security::remove_XSS($_REQUEST['add_type']);
 }
 
-$access_url_id = 1;
-if (isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id'] != '') {
-    $access_url_id = Security::remove_XSS($_REQUEST['access_url_id']);
+$access_url_id=1;
+if(isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id']!=''){
+	$access_url_id = Security::remove_XSS($_REQUEST['access_url_id']);
 }
 
-$xajax->processRequests();
+$xajax -> processRequests();
 $htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
 $htmlHeadXtra[] = '
 <script type="text/javascript">
@@ -70,7 +70,7 @@ function send() {
 
 	if (document.formulaire.access_url_id.value!=0) {
 		document.formulaire.form_sent.value=0;
-		document.formulaire.add_type.value=\'' . $add_type . '\';
+		document.formulaire.add_type.value=\''.$add_type.'\';
 		document.formulaire.submit();
 	}
 }
@@ -86,53 +86,53 @@ function remove_item(origin)
 }
 </script>';
 
-$form_sent = 0;
-$errorMsg = '';
-$UserList = array();
+$form_sent=0;
+$errorMsg='';
+$UserList=array();
 
 $message = '';
 
 if ($_POST['form_sent']) {
-    $form_sent = $_POST['form_sent'];
-    $UserList = $_POST['sessionUsersList'];
-
-    if (!is_array($UserList)) {
-        $UserList = array();
-    }
-    if ($form_sent == 1) {
-        if ($access_url_id == 0) {
-            header('Location: access_url_edit_users_to_url.php?action=show_message&message=' . get_lang('SelectURL'));
-        } elseif (is_array($UserList)) {
-            $result = UrlManager::update_urls_rel_user($UserList, $access_url_id);
-            $url_info = UrlManager::get_url_data_from_id($access_url_id);
+	$form_sent  = $_POST['form_sent'];
+	$UserList   = $_POST['sessionUsersList'];
+    
+	if (!is_array($UserList)) {
+		$UserList=array();
+	}
+	if ($form_sent == 1) {
+		if ($access_url_id==0) {
+			header('Location: access_url_edit_users_to_url.php?action=show_message&message='.get_lang('SelectURL'));
+		} elseif (is_array($UserList)) {
+			$result     = UrlManager::update_urls_rel_user($UserList, $access_url_id);
+            $url_info   = UrlManager::get_url_data_from_id($access_url_id);            
             if (!empty($result)) {
-                $message .= 'URL: ' . $url_info['url'] . '<br />';
+                $message .= 'URL: '.$url_info['url'].'<br />';
             }
-
+                        
             if (!empty($result['users_added'])) {
-                $message .= '<h4>' . get_lang('UsersAdded') . ':</h4>';
+                $message .=  '<h4>'.get_lang('UsersAdded').':</h4>';
                 $i = 1;
                 $user_added_list = array();
-                foreach ($result['users_added'] as $user) {
+                foreach($result['users_added'] as $user) {
                     $user_info = api_get_user_info($user);
                     if (!empty($user_info)) {
-                        $user_added_list[] = $i . '. ' . api_get_person_name($user_info['firstname'], $user_info['lastname']);
+                        $user_added_list[] = $i.'. '.api_get_person_name($user_info['firstname'], $user_info['lastname']);
                         $i++;
                     }
                 }
                 if (!empty($user_added_list)) {
                     $message .= implode(', ', $user_added_list);
-                }
+                }                
             }
-
+            
             if (!empty($result['users_deleted'])) {
-                $message .= '<br /><h4>' . get_lang('UsersDeleted') . ': </h4>';
+                $message .= '<br /><h4>'.get_lang('UsersDeleted').': </h4>';
                 $user_deleted_list = array();
                 $i = 1;
-                foreach ($result['users_deleted'] as $user) {
+                foreach($result['users_deleted'] as $user) {
                     $user_info = api_get_user_info($user);
                     if (!empty($user_info)) {
-                        $user_deleted_list [] = $i . '. ' . api_get_person_name($user_info['firstname'], $user_info['lastname']);
+                        $user_deleted_list [] = $i.'. '.api_get_person_name($user_info['firstname'], $user_info['lastname']);
                         $i++;
                     }
                 }
@@ -140,8 +140,8 @@ if ($_POST['form_sent']) {
                     $message .= implode(', ', $user_deleted_list);
                 }
             }
-        }
-    }
+		}
+	}
 }
 
 Display::display_header($tool_name);
@@ -151,92 +151,90 @@ if (!empty($message)) {
 }
 
 echo '<div class="actions">';
-echo Display::url(Display::return_icon('view_more_stats.gif', get_lang('AddUserToURL'), ''), api_get_path(WEB_CODE_PATH) . 'admin/access_url_add_users_to_url.php');
+echo Display::url(Display::return_icon('view_more_stats.gif',get_lang('AddUserToURL'),''), api_get_path(WEB_CODE_PATH).'admin/access_url_add_users_to_url.php');
 echo '</div>';
 
 api_display_tool_title($tool_name);
 
 if ($_GET['action'] == 'show_message')
-    Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
+	Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
 
 $nosessionUsersList = $sessionUsersList = array();
 $ajax_search = $add_type == 'unique' ? true : false;
 
-if ($ajax_search) {
-    $Users = UrlManager::get_url_rel_user_data($access_url_id);
-    foreach ($Users as $user) {
-        $sessionUsersList[$user['user_id']] = $user;
-    }
+if($ajax_search) {
+	$Users=UrlManager::get_url_rel_user_data($access_url_id);
+	foreach($Users as $user) {
+		$sessionUsersList[$user['user_id']] = $user ;
+	}
 } else {
-    $Users = UrlManager::get_url_rel_user_data();
-    foreach ($Users as $user) {
-        if ($user['access_url_id'] == $access_url_id) {
-            $sessionUsersList[$user['user_id']] = $user;
-        }
-    }
-    $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-    $sql = "SELECT u.user_id, lastname, firstname, username
-	  	  	FROM $tbl_user u WHERE status <> " . ANONYMOUS . " " .
-            $order_clause;
-    $result = Database::query($sql);
-    $Users = Database::store_result($result);
-    $user_list_leys = array_keys($sessionUsersList);
-    foreach ($Users as $user) {
-        if (!in_array($user['user_id'], $user_list_leys)) {
-            $nosessionUsersList[$user['user_id']] = $user;
-        }
-    }
+	$Users=UrlManager::get_url_rel_user_data();
+	foreach($Users as $user) {
+		if($user['access_url_id'] == $access_url_id) {
+			$sessionUsersList[$user['user_id']] = $user ;
+		}
+	}
+	$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
+	$sql="SELECT u.user_id, lastname, firstname, username
+	  	  	FROM $tbl_user u WHERE status <> ".ANONYMOUS." ".
+			$order_clause;
+	$result=Database::query($sql);
+	$Users=Database::store_result($result);
+	$user_list_leys = array_keys($sessionUsersList);
+	foreach($Users as $user) {
+		if (!in_array($user['user_id'],$user_list_leys))
+			$nosessionUsersList[$user['user_id']] = $user ;
+	}
 }
 
 
-if ($add_type == 'multiple') {
-    $link_add_type_unique = '<a href="' . api_get_self() . '?add_type=unique&access_url_id=' . $access_url_id . '">' . get_lang('SessionAddTypeUnique') . '</a>';
-    $link_add_type_multiple = get_lang('SessionAddTypeMultiple');
+if($add_type == 'multiple') {
+	$link_add_type_unique = '<a href="'.api_get_self().'?add_type=unique&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeUnique').'</a>';
+	$link_add_type_multiple = get_lang('SessionAddTypeMultiple');
 } else {
-    $link_add_type_unique = get_lang('SessionAddTypeUnique');
-    $link_add_type_multiple = '<a href="' . api_get_self() . '?add_type=multiple&access_url_id=' . $access_url_id . '">' . get_lang('SessionAddTypeMultiple') . '</a>';
+	$link_add_type_unique = get_lang('SessionAddTypeUnique');
+	$link_add_type_multiple = '<a href="'.api_get_self().'?add_type=multiple&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeMultiple').'</a>';
 }
 
 $url_list = UrlManager::get_url_data();
+
 ?>
 
 <div style="text-align: left;">
-<?php echo $link_add_type_unique ?>&nbsp;|&nbsp;<?php echo $link_add_type_multiple ?>
+	<?php echo $link_add_type_unique ?>&nbsp;|&nbsp;<?php echo $link_add_type_multiple ?>
 </div>
 <br /><br />
-<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;" <?php if ($ajax_search) {
-    echo ' onsubmit="valide();"';
-} ?> >
-    <?php echo get_lang('SelectUrl') . ' : '; ?>
+<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;" <?php if($ajax_search){echo ' onsubmit="valide();"';}?> >
+<?php echo get_lang('SelectUrl').' : '; ?>
 <select name="access_url_id" onchange="javascript:send();">
-<option value="0"> <?php echo get_lang('SelectUrl') ?></option>
-        <?php
-        $url_selected = '';
-        foreach ($url_list as $url_obj) {
-            $checked = '';
-            if (!empty($access_url_id)) {
-                if ($url_obj['id'] == $access_url_id) {
-                    $checked = 'selected=true';
-                    $url_selected = $url_obj[1];
-                }
-            }
-            if ($url_obj['active'] == 1) {
-                ?>
-        		<option <?php echo $checked; ?> value="<?php echo $url_obj[0]; ?>"> <?php echo $url_obj[1]; ?></option>
-                <?php
-            }
-        }
-        ?>
+<option value="0"> <?php echo get_lang('SelectUrl')?></option>
+	<?php
+	$url_selected='';
+	foreach ($url_list as $url_obj) {
+		$checked = '';
+		if (!empty($access_url_id)) {
+			if ($url_obj['id']==$access_url_id) {
+			$checked = 'selected=true';
+			$url_selected=	$url_obj[1];
+			}
+		}
+		if ($url_obj['active']==1) {
+	?>
+		<option <?php echo $checked;?> value="<?php echo $url_obj[0]; ?>"> <?php echo $url_obj[1]; ?></option>
+	<?php
+		}
+	}
+	?>
 </select>
 <br /><br />
 <input type="hidden" name="form_sent" value="1" />
 <input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
 
-    <?php
-    if (!empty($errorMsg)) {
-        Display::display_normal_message($errorMsg); //main API
-    }
-    ?>
+<?php
+if(!empty($errorMsg)) {
+	Display::display_normal_message($errorMsg); //main API
+}
+?>
 
 <table border="0" cellpadding="5" cellspacing="0" width="100%">
 <tr>
@@ -253,64 +251,64 @@ $url_list = UrlManager::get_url_data();
   <td align="center"><b><?php echo get_lang('UserListInPlatform') ?> : <?php echo count($nosessionUsersList); ?></b>
   </td>
   <td></td>
-  <td align="center"><b><?php echo get_lang('UserListIn') . ' ' . $url_selected; ?> : <?php echo count($sessionUsersList); ?></b></td>
+  <td align="center"><b><?php echo get_lang('UserListIn').' '.$url_selected; ?> :</b></td>
 </tr>
 
 <tr>
   <td align="center">
   <div id="content_source">
-                    <?php
-                    if ($ajax_search) {
-                        ?>
-    		<input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)" />
-    		<div id="ajax_list_users"></div>
-                        <?php
-                    } else {
-                        ?>
-    	  <select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:380px;">
-                            <?php
-                            foreach ($nosessionUsersList as $enreg) {
-                                ?>
-        			<option value="<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']) . ' (' . $enreg['username'] . ')'; ?></option>
-                                <?php
-                            }
-                            unset($nosessionUsersList);
-                            ?>
-
-    	  </select>
-                        <?php
-                    }
-                    ?>
+  	  <?php
+  	  if($ajax_search) {
+  	  	?>
+		<input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)" />
+		<div id="ajax_list_users"></div>
+		<?php
+  	  } else {
+  	  ?>
+	  <select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:380px;">
+		<?php
+		foreach($nosessionUsersList as $enreg) {
+		?>
+			<option value="<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
+			<?php
+		}
+		unset($nosessionUsersList);
+		?>
+
+	  </select>
+	<?php
+  	  }
+  	 ?>
   </div>
   </td>
   <td width="10%" valign="middle" align="center">
-                <?php
-                if ($ajax_search) {
-                    ?>
-    	<button class="arrowl" type="button" onclick="remove_item(document.getElementById('destination_users'))"> </button>
-                    <?php
-                } else {
-                    ?>
-    	<button class="arrowr" type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" ></button>
-    	<br /><br />
-    	<button class="arrowl" type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" ></button>
-                    <?php
-                }
-                ?>
+  <?php
+  if($ajax_search) {
+	?>
+	<button class="arrowl" type="button" onclick="remove_item(document.getElementById('destination_users'))"> </button>
+  	<?php
+  } else {
+  	?>
+	<button class="arrowr" type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" ></button>
+	<br /><br />
+	<button class="arrowl" type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" ></button>
+	<?php
+  }
+  ?>
 	<br /><br /><br /><br /><br /><br />
   </td>
   <td align="center">
   <select id="destination_users" name="sessionUsersList[]" multiple="multiple" size="15" style="width:380px;">
 
-                    <?php
-                    foreach ($sessionUsersList as $enreg) {
-                        ?>
-    	<option value="<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']) . ' (' . $enreg['username'] . ')'; ?></option>
+<?php
+foreach($sessionUsersList as $enreg) {
+?>
+	<option value="<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
 
-                        <?php
-                    }
-                    unset($sessionUsersList);
-                    ?>
+<?php
+}
+unset($sessionUsersList);
+?>
 
   </select></td>
 </tr>
@@ -318,12 +316,12 @@ $url_list = UrlManager::get_url_data();
 <tr>
 	<td colspan="3" align="center">
 		<br />
-                <?php
-                if (isset($_GET['add']))
-                    echo '<button class="save" type="button" onclick="valide()" >' . get_lang('AddUsersToURL') . '</button>';
-                else
-                    echo '<button class="save" type="button" onclick="valide()" >' . get_lang('EditUsersToURL') . '</button>';
-                ?>
+		<?php
+		if(isset($_GET['add']))
+			echo '<button class="save" type="button" onclick="valide()" >'.get_lang('AddUsersToURL').'</button>';
+		else
+			echo '<button class="save" type="button" onclick="valide()" >'.get_lang('EditUsersToURL').'</button>';
+		?>
 	</td>
 </tr>
 

+ 91 - 72
main/admin/access_urls.php

@@ -1,10 +1,14 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
-*	@package chamilo.admin
-*	@author Julio Montoya <gugli100@gmail.com>
-*/
-
+ * Frontend script for multiple access urls
+ * @package chamilo.admin
+ * @author Julio Montoya <gugli100@gmail.com>
+ * @author Yannick Warnier <yannick.warnier@beeznest.com>
+ */
+/**
+ * Initialization
+ */
 // name of the language file that needs to be included
 $language_file = 'admin';
 $cidReset = true;
@@ -15,90 +19,86 @@ $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_global_admin_script();
 
 if (!api_get_multiple_access_url()) {
-	header('Location: index.php');
-	exit;
+    header('Location: index.php');
+    exit;
 }
 
 $interbreadcrumb[] = array ("url" => 'index.php', 'name' => get_lang('PlatformAdmin'));
 $tool_name = get_lang('MultipleAccessURLs');
 Display :: display_header($tool_name);
 
-require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
-
 $my_user_url_list = api_get_access_url_from_user(api_get_user_id());
 $current_access_url_id = api_get_current_access_url_id();
 $url_list = UrlManager::get_url_data();
-
-// Actions
+/**
+ * Controller
+ */
 if (isset ($_GET['action'])) {
-	if ($_GET['action'] == 'show_message')
-		Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
-
-	$check = Security::check_token('get');
-	if ($check) {
-		$url_id=Database::escape_string($_GET['url_id']);
-
-		switch ($_GET['action']) {
-			case 'delete_url' :
-				$result = UrlManager::delete($url_id);
-				if ($result) {
-					Display :: display_normal_message(get_lang('URLDeleted'));
-				} else {
-					Display :: display_error_message(get_lang('CannotDeleteURL'));
-				}
-				break;
-			case 'lock' :
-				UrlManager::set_url_status('lock',$url_id);
-				Display :: display_normal_message(get_lang('URLInactive'));
-				break;
-			case 'unlock';
-				UrlManager::set_url_status('unlock',$url_id);
-				Display :: display_normal_message(get_lang('URLActive'));
-				break;
-			case 'register';
-				// we are going to register the admin
-				if(api_is_platform_admin()) {
-					if($current_access_url_id!=-1) {
-						$url_str = '';
-						foreach($url_list as $my_url) {
-							if (!in_array($my_url['id'],$my_user_url_list)){
-								UrlManager::add_user_to_url(api_get_user_id(),$my_url['id']);
-									$url_str.=$my_url['url'].' <br />';
-							}
-						}
-						Display :: display_normal_message(get_lang('AdminUserRegisteredToThisURL').': '.$url_str.'<br />',false);
-					}
-				}
-				break;
-			}
-
-		}
-		Security::clear_token();
+    if ($_GET['action'] == 'show_message') {
+        Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
+    }
+    $check = Security::check_token('get');
+    if ($check) {
+        $url_id=Database::escape_string($_GET['url_id']);
+
+        switch ($_GET['action']) {
+            case 'delete_url' :
+                $result = UrlManager::delete($url_id);
+                if ($result) {
+                    Display :: display_normal_message(get_lang('URLDeleted'));
+                } else {
+                    Display :: display_error_message(get_lang('CannotDeleteURL'));
+                }
+                break;
+            case 'lock' :
+                UrlManager::set_url_status('lock',$url_id);
+                Display :: display_normal_message(get_lang('URLInactive'));
+                break;
+            case 'unlock';
+                UrlManager::set_url_status('unlock',$url_id);
+                Display :: display_normal_message(get_lang('URLActive'));
+                break;
+            case 'register';
+                // we are going to register the admin
+                if(api_is_platform_admin()) {
+                    if($current_access_url_id!=-1) {
+                        $url_str = '';
+                        foreach($url_list as $my_url) {
+                            if (!in_array($my_url['id'],$my_user_url_list)){
+                                UrlManager::add_user_to_url(api_get_user_id(),$my_url['id']);
+                                $url_str.=$my_url['url'].' <br />';
+                            }
+                        }
+                        Display :: display_normal_message(get_lang('AdminUserRegisteredToThisURL').': '.$url_str.'<br />',false);
+                    }
+                }
+                break;
+        }
+    }
+    Security::clear_token();
 }
-
 $parameters['sec_token'] = Security::get_token();
 
 // checking if the admin is registered in all sites
-
 $url_string='';
 $my_user_url_list = api_get_access_url_from_user(api_get_user_id());
 foreach($url_list as $my_url) {
-	if (!in_array($my_url['id'],$my_user_url_list)){
-		$url_string.=$my_url['url'].' <br />';
-	}
+    if (!in_array($my_url['id'],$my_user_url_list)){
+        $url_string.=$my_url['url'].' <br />';
+    }
 }
 if(!empty($url_string)) {
-	Display :: display_warning_message(get_lang('AdminShouldBeRegisterInSite').'<br />'.$url_string,false);
+    Display :: display_warning_message(get_lang('AdminShouldBeRegisterInSite').'<br />'.$url_string,false);
 }
 
 // checking the current installation
 if ($current_access_url_id==-1) {
-	Display :: display_warning_message(get_lang('URLNotConfiguredPleaseChangedTo').': '.api_get_path(WEB_PATH));
+    Display :: display_warning_message(get_lang('URLNotConfiguredPleaseChangedTo').': '.api_get_path(WEB_PATH));
 } elseif(api_is_platform_admin()) {
-	$quant= UrlManager::relation_url_user_exist(api_get_user_id(),$current_access_url_id);
-	if ($quant==0) {
-		Display :: display_warning_message('<a href="'.api_get_self().'?action=register&sec_token='.$parameters['sec_token'].'">'.get_lang('ClickToRegisterAdmin').'</a>',false);
-	}
+    $quant= UrlManager::relation_url_user_exist(api_get_user_id(),$current_access_url_id);
+    if ($quant==0) {
+        Display :: display_warning_message('<a href="'.api_get_self().'?action=register&sec_token='.$parameters['sec_token'].'">'.get_lang('ClickToRegisterAdmin').'</a>',false);
+    }
 }
 
 // action menu
@@ -112,11 +112,27 @@ echo '</div>';
 //$table = new SortableTable('urls', 'url_count_mask', 'get_url_data_mask',2);
 $sortable_data = UrlManager::get_url_data();
 $urls = array();
+$types = array(1=>'AccessURL',2=>'SincroServer',3=>'SincroClient'); 
 foreach($sortable_data as $row)  {
     //title
     $url = Display::url($row['url'], $row['url'], array('target'=>'_blank'));    
-    $description = $row['description'];
-    
+    $name = $row['description'];
+    if (!empty($row['branch_name'])) {
+        $name = $row['branch_name'];
+    }
+    $type = get_lang($types[$row['url_type']]);
+    $contact = '';
+    if (!empty($row['admin_mail']) || !empty($row['admin_name']) || !empty($row['admin_phone'])) {
+        $contact = (!empty($row['admin_name'])?$row['admin_name']:'').
+                   ' &lt;'.(!empty($row['admin_mail'])?$row['admin_mail']:'').
+                   '&gt;, '.(!empty($row['admin_phone'])?$row['admin_phone']:'');
+    }
+    $tech = '';
+    if (!empty($row['dwn_speed']) || !empty($row['up_speed']) || !empty($row['delay'])) {
+        $tech .= (empty($row['dwn_speed'])?'-':$row['dwn_speed']).'/';
+        $tech .= (empty($row['up_speed'])?'-':$row['up_speed']).'/';
+        $tech .= (empty($row['delay'])?'-':$row['delay']);
+    }
     //Status
     $active = $row['active'];
     if ($active=='1') {
@@ -139,7 +155,7 @@ foreach($sortable_data as $row)  {
     if ($url_id != '1') {
         $actions .= '<a href="access_urls.php?action=delete_url&amp;url_id='.$url_id.'&amp;sec_token='.$_SESSION['sec_token'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
     }    
-    $urls[] = array($url, $description, $status, $actions);
+    $urls[] = array($url, $name, $type, $tech, $contact, $status, $actions);
 }
 
 $table = new SortableTableFromArrayConfig($urls, 2, 50, 'urls');
@@ -147,10 +163,13 @@ $table->set_additional_parameters($parameters);
 
 //$table->set_header(0, '');
 $table->set_header(0, 'URL');
-$table->set_header(1, get_lang('Description'));
-$table->set_header(2, get_lang('Active'));
-$table->set_header(3, get_lang('Modify'), false);
+$table->set_header(1, get_lang('Name'));
+$table->set_header(2, get_lang('URLType'));
+$table->set_header(3, 'Dl/Ul/Delay in Kbit/s');
+$table->set_header(4, get_lang('Contact'));
+$table->set_header(5, get_lang('Active'));
+$table->set_header(6, get_lang('Modify'), false);
 $table->display();
 
-/*		FOOTER	*/
-Display :: display_footer();
+/*        FOOTER    */
+Display :: display_footer();

+ 0 - 2
main/admin/add_courses_to_usergroup.php

@@ -12,8 +12,6 @@ $cidReset = true;
 
 // including some necessary files
 require_once '../inc/global.inc.php';
-require_once '../inc/lib/xajax/xajax.inc.php';
-require_once api_get_path(LIBRARY_PATH).'usergroup.lib.php';
 
 $xajax = new xajax();
 

+ 0 - 2
main/admin/add_many_session_to_category.php

@@ -11,8 +11,6 @@ $language_file='admin';
 $cidReset = true;
 
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'add_many_session_to_category_functions.lib.php';
-require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
 
 $xajax = new xajax();
 $xajax -> registerFunction ('search_courses');

+ 0 - 4
main/admin/add_sessions_to_promotion.php

@@ -12,10 +12,6 @@ $cidReset=true;
 
 // including some necessary files
 require_once '../inc/global.inc.php';
-require_once '../inc/lib/xajax/xajax.inc.php';
-require_once api_get_path(LIBRARY_PATH).'promotion.lib.php';
-require_once api_get_path(LIBRARY_PATH).'career.lib.php';
-require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
 
 $xajax = new xajax();
 

+ 0 - 2
main/admin/add_sessions_to_usergroup.php

@@ -12,8 +12,6 @@ $cidReset=true;
 
 // including some necessary files
 require_once '../inc/global.inc.php';
-require_once '../inc/lib/xajax/xajax.inc.php';
-require_once api_get_path(LIBRARY_PATH).'usergroup.lib.php';
 
 $xajax = new xajax();
 

+ 0 - 1
main/admin/add_users_to_group.php

@@ -12,7 +12,6 @@ $cidReset=true;
 
 // including some necessary files
 require_once '../inc/global.inc.php';
-require_once '../inc/lib/xajax/xajax.inc.php';
 
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;

+ 116 - 87
main/admin/add_users_to_session.php

@@ -12,7 +12,6 @@ $cidReset = true;
 
 // including some necessary files
 require_once '../inc/global.inc.php';
-require_once '../inc/lib/xajax/xajax.inc.php';
 $xajax = new xajax();
 
 $xajax -> registerFunction ('search_users');
@@ -48,7 +47,7 @@ $page = isset($_GET['page']) ? Security::remove_XSS($_GET['page']) : null;
 
 //checking for extra field with filter on
 
-$extra_field_list= UserManager::get_extra_fields();
+$extra_field_list = UserManager::get_extra_fields();
 $new_field_list = array();
 if (is_array($extra_field_list)) {
 	foreach ($extra_field_list as $extra_field) {
@@ -119,6 +118,7 @@ function search_users($needle, $type) {
                         $order_clause;
                 break;
 		}
+
 		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();
@@ -165,7 +165,6 @@ function search_users($needle, $type) {
 	            	$return .= '...<br />';
 	            }
 			}
-
 			$xajax_response -> addAssign('ajax_list_users_single','innerHTML',api_utf8_encode($return));
 		} else {
 			global $nosessionUsersList;
@@ -185,7 +184,7 @@ $xajax -> processRequests();
 
 $htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
 $htmlHeadXtra[] = '
-<script type="text/javascript">
+<script>
 function add_user_to_session (code, content) {
 	document.getElementById("user_to_add").value = "";
 	document.getElementById("ajax_list_users_single").innerHTML = "";
@@ -212,9 +211,9 @@ function remove_item(origin) {
 }
 
 function validate_filter() {
-		document.formulaire.add_type.value = \''.$add_type.'\';
-		document.formulaire.form_sent.value=0;
-		document.formulaire.submit();
+    document.formulaire.add_type.value = \''.$add_type.'\';
+    document.formulaire.form_sent.value=0;
+    document.formulaire.submit();
 }
 
 function checked_in_no_session(checked) {
@@ -235,8 +234,8 @@ function change_select(val) {
 $form_sent=0;
 $errorMsg=$firstLetterUser=$firstLetterSession='';
 $UserList=$SessionList=array();
-$sessions=array();
-$noPHP_SELF=true;
+$sessions = array();
+$noPHP_SELF = true;
 
 if (isset($_POST['form_sent']) && $_POST['form_sent']) {
     $form_sent             = $_POST['form_sent'];
@@ -270,7 +269,11 @@ if ($ajax_search) {
             INNER JOIN $tbl_session_rel_user
                 ON $tbl_session_rel_user.id_user = u.user_id AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
                 AND $tbl_session_rel_user.id_session = ".intval($id_session)."
-                WHERE u.status<>".DRH." AND u.status<>6 $order_clause";
+                WHERE u.status<>".DRH." AND 
+                    u.status<>6 AND
+                    $tbl_session_rel_user.moved_to = 0 AND
+                    $tbl_session_rel_user.moved_status <> ".SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION."                        
+                $order_clause";
 
     if (api_is_multiple_url_enabled()) {
         $tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
@@ -282,7 +285,11 @@ if ($ajax_search) {
                 ON $tbl_session_rel_user.id_user = u.user_id AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
                 AND $tbl_session_rel_user.id_session = ".intval($id_session)."
                 INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id)
-                WHERE access_url_id = $access_url_id AND u.status<>".DRH." AND u.status<>6
+                WHERE   access_url_id = $access_url_id AND 
+                        u.status<>".DRH." AND 
+                        u.status<>6 AND 
+                        $tbl_session_rel_user.moved_to = 0 AND
+                        $tbl_session_rel_user.moved_status <> ".SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION."
                 $order_clause";
         }
     }
@@ -297,7 +304,7 @@ if ($ajax_search) {
     $use_extra_fields = false;
     if (is_array($extra_field_list)) {
         if (is_array($new_field_list) && count($new_field_list)>0 ) {
-            $result_list=array();
+            $result_list = array();
             foreach ($new_field_list as $new_field) {
                 $varname = 'field_'.$new_field['variable'];
                 if (UserManager::is_extra_field_available($new_field['variable'])) {
@@ -344,16 +351,23 @@ if ($ajax_search) {
         $sql = "SELECT  user_id, lastname, firstname, username, id_session
                FROM $tbl_user u
                     LEFT JOIN $tbl_session_rel_user
-                    ON $tbl_session_rel_user.id_user = u.user_id AND $tbl_session_rel_user.id_session = '$id_session' AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
-                    $where_filter AND u.status<>".DRH." AND u.status<>6
+                    ON  $tbl_session_rel_user.id_user = u.user_id AND 
+                        $tbl_session_rel_user.id_session = '$id_session' AND 
+                        $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
+                    $where_filter AND 
+                    u.status<>".DRH." AND 
+                    u.status<>6                    
                     $order_clause";
 
     } else {
         $sql = "SELECT  user_id, lastname, firstname, username, id_session
                 FROM $tbl_user u
                 LEFT JOIN $tbl_session_rel_user
-                ON $tbl_session_rel_user.id_user = u.user_id AND $tbl_session_rel_user.id_session = '$id_session' AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
-                WHERE u.status<>".DRH." AND u.status<>6
+                ON  $tbl_session_rel_user.id_user = u.user_id AND 
+                    $tbl_session_rel_user.id_session = '$id_session' AND 
+                    $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
+                WHERE   u.status<>".DRH." AND 
+                        u.status<>6                         
                 $order_clause";
     }
     if (api_is_multiple_url_enabled()) {
@@ -363,30 +377,40 @@ if ($ajax_search) {
             $sql = "SELECT  u.user_id, lastname, firstname, username, id_session
                     FROM $tbl_user u
                     LEFT JOIN $tbl_session_rel_user
-                        ON $tbl_session_rel_user.id_user = u.user_id AND $tbl_session_rel_user.id_session = '$id_session' AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
-                    INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id)
-                    WHERE access_url_id = $access_url_id  $where_filter AND u.status<>".DRH." AND u.status<>6
+                        ON  $tbl_session_rel_user.id_user = u.user_id AND 
+                            $tbl_session_rel_user.id_session = '$id_session' AND 
+                            $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
+                        INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id)
+                    WHERE   access_url_id = $access_url_id  $where_filter AND 
+                            u.status<>".DRH." AND 
+                            u.status<>6                            
                     $order_clause";
         }
     }
 
     $result   = Database::query($sql);
     $users    = Database::store_result($result,'ASSOC');
-
+    
     foreach ($users as $uid => $user) {
         if ($user['id_session'] != $id_session) {
             $nosessionUsersList[$user['user_id']] = array('fn'=>$user['firstname'],'ln'=>$user['lastname'],'un'=>$user['username']) ;
             unset($users[$uid]);
-	}
+        }
     }
     unset($users); //clean to free memory
 
-    //filling the correct users in list
-    $sql="SELECT  user_id, lastname, firstname, username, id_session
+    //Filling the correct users in list
+    $sql = "SELECT  user_id, lastname, firstname, username, id_session
           FROM $tbl_user u
           LEFT JOIN $tbl_session_rel_user
-          ON $tbl_session_rel_user.id_user = u.user_id AND $tbl_session_rel_user.id_session = '$id_session' AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
-          WHERE u.status<>".DRH." AND u.status<>6 $order_clause";
+          ON    $tbl_session_rel_user.id_user = u.user_id AND 
+                $tbl_session_rel_user.id_session = '$id_session' AND 
+                $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
+          WHERE u.status <> ".DRH." AND 
+                u.status <> 6 AND 
+                $tbl_session_rel_user.moved_to = 0 AND
+                $tbl_session_rel_user.moved_status <> ".SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION." 
+          $order_clause";
 
     if (api_is_multiple_url_enabled()) {
         $tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
@@ -397,12 +421,18 @@ if ($ajax_search) {
                 LEFT JOIN $tbl_session_rel_user
                     ON $tbl_session_rel_user.id_user = u.user_id AND $tbl_session_rel_user.id_session = '$id_session' AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
                 INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id)
-                WHERE access_url_id = $access_url_id AND u.status<>".DRH." AND u.status<>6
+                WHERE   access_url_id = $access_url_id AND 
+                        u.status<>".DRH." AND 
+                        u.status<>6 AND 
+                        $tbl_session_rel_user.moved_to = 0 AND
+                        $tbl_session_rel_user.moved_status <> ".SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION." 
+                                                
                 $order_clause";
         }
     }
-    $result=Database::query($sql);
-    $users=Database::store_result($result,'ASSOC');
+    
+    $result = Database::query($sql);
+    $users = Database::store_result($result,'ASSOC');
     foreach ($users as $uid => $user) {
         if ($user['id_session'] == $id_session) {
             $sessionUsersList[$user['user_id']] = $user;
@@ -415,6 +445,7 @@ if ($ajax_search) {
     unset($users); //clean to free memory
 }
 
+
 if ($add_type == 'multiple') {
 	$link_add_type_unique = '<a href="'.api_get_self().'?id_session='.$id_session.'&add='.Security::remove_XSS($_GET['add']).'&add_type=unique">'.Display::return_icon('single.gif').get_lang('SessionAddTypeUnique').'</a>';
 	$link_add_type_multiple = Display::return_icon('multiple.gif').get_lang('SessionAddTypeMultiple');
@@ -462,80 +493,83 @@ if ($add_type=='multiple') {
 <input type="hidden" name="add_type"  />
 
 <?php
-if (!empty($errorMsg)) {
+if(!empty($errorMsg)) {
 	Display::display_normal_message($errorMsg); //main API
 }
 ?>
+
 <div class="row">
     <div class="span5">
         <div class="multiple_select_header">
             <b><?php echo get_lang('UserListInPlatform') ?> :</b>
 
-        <?php if ($add_type=='multiple') { ?>
-            <?php echo get_lang('FirstLetterUser'); ?> :
-                <select id="first_letter_user" name="firstLetterUser" onchange = "change_select(this.value);" >
-                <option value = "%">--</option>
-                <?php
-                    echo Display :: get_alphabet_options();
-                ?>
-                </select>
-        <?php } ?>
+<?php if ($add_type=='multiple') { ?>
+
+    <?php echo get_lang('FirstLetterUser'); ?> :
+        <select id="first_letter_user" name="firstLetterUser" onchange = "change_select(this.value);" >
+        <option value = "%">--</option>
+        <?php
+            echo Display :: get_alphabet_options();
+        ?>
+        </select>
+<?php } ?>
         </div>
-            <div id="content_source">
-            <?php
-            if (!($add_type=='multiple')) {
-              ?>
-              <input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,'single')" />
-              <div id="ajax_list_users_single"></div>
-              <?php
-            } else {
-            ?>
-            <div id="ajax_list_users_multiple">
+  <div id="content_source">
+  	  <?php
+  	  if (!($add_type=='multiple')) {
+  	  	?>
+		<input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,'single')" />
+		<div id="ajax_list_users_single"></div>
+		<?php
+  	  } else {
+  	  ?>
+  	  <div id="ajax_list_users_multiple">
             <select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" class="span5">
-              <?php
-              foreach ($nosessionUsersList as $uid => $enreg) {
-              ?>
-                  <option value="<?php echo $uid; ?>" <?php if(in_array($uid,$UserList)) echo 'selected="selected"'; ?>><?php echo api_get_person_name($enreg['fn'], $enreg['ln']).' ('.$enreg['un'].')'; ?></option>
-              <?php
-              }
-              ?>
-            </select>
-            </div>
-                <input type="checkbox" onchange="checked_in_no_session(this.checked);" name="user_with_any_session" id="user_with_any_session_id">
-                <label for="user_with_any_session_id"><?php echo get_lang('UsersRegisteredInNoSession'); ?></label>
-            <?php
-            }
-            unset($nosessionUsersList);
-           ?>
-        </div>
+		<?php
+		foreach ($nosessionUsersList as $uid => $enreg) {
+		?>
+			<option value="<?php echo $uid; ?>" <?php if(in_array($uid,$UserList)) echo 'selected="selected"'; ?>><?php echo api_get_person_name($enreg['fn'], $enreg['ln']).' ('.$enreg['un'].')'; ?></option>
+		<?php
+		}
+		?>
+	  </select>
+	  </div>
+          <input type="checkbox" onchange="checked_in_no_session(this.checked);" name="user_with_any_session" id="user_with_any_session_id">
+          <label for="user_with_any_session_id"><?php echo get_lang('UsersRegisteredInNoSession'); ?></label>
+	  <?php
+  	  }
+  	  unset($nosessionUsersList);
+  	 ?>
+
+  </div>
     </div>
 
     <div class="span2">
         <div style="padding-top:54px;width:auto;text-align: center;">
-        <?php
-            if ($ajax_search) {
-            ?>
-              <button class="arrowl" type="button" onclick="remove_item(document.getElementById('destination_users'))" ></button>
-            <?php
-        } else {
-            ?>
-                <button class="arrowr" type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))"></button>
-                <br /><br />
-                <button class="arrowl" type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))"></button>
+  <?php
+  if ($ajax_search) {
+  ?>
+  	<button class="arrowl" type="button" onclick="remove_item(document.getElementById('destination_users'))" ></button>
+  <?php
+  } else {
+  ?>
+  	<button class="arrowr" type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))"></button>
+	<br /><br />
+	<button class="arrowl" type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))"></button>
+
+<?php
+}
+?>
 
-              <?php
-            }
-        ?>
         </div>
         <br />
-        <br />
+		<br />
 		<?php
 		if(isset($_GET['add'])) {
 			echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('FinishSessionCreation').'</button>';
         } else {
             //@todo see that the call to "valide()" doesn't duplicate the onsubmit of the form (necessary to avoid delete on "enter" key pressed)
 			echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('SubscribeUsersToSession').'</button>';
-
         }
 		?>
     </div>
@@ -557,11 +591,11 @@ if (!empty($errorMsg)) {
     </div>
 </div>
 </form>
+
 <script>
 <!--
 function moveItem(origin , destination){
-
-	for(var i = 0 ; i<origin.options.length ; i++) {
+	for (var i = 0 ; i<origin.options.length ; i++) {
 		if(origin.options[i].selected) {
 			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
 			origin.options[i]=null;
@@ -574,7 +608,6 @@ function moveItem(origin , destination){
 }
 
 function sortOptions(options) {
-
 	newOptions = new Array();
 	for (i = 0 ; i<options.length ; i++)
 		newOptions[i] = options[i];
@@ -605,9 +638,7 @@ function valide(){
 
 
 function loadUsersInSelect(select){
-
 	var xhr_object = null;
-
 	if(window.XMLHttpRequest) // Firefox
 		xhr_object = new XMLHttpRequest();
 	else if(window.ActiveXObject) // Internet Explorer
@@ -620,7 +651,6 @@ function loadUsersInSelect(select){
 
 	xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 
-
 	nosessionUsers = makepost(document.getElementById('origin_users'));
 	sessionUsers = makepost(document.getElementById('destination_users'));
 	nosessionClasses = makepost(document.getElementById('origin_classes'));
@@ -635,8 +665,7 @@ function loadUsersInSelect(select){
 	}
 }
 
-function makepost(select){
-
+function makepost(select) {
 	var options = select.options;
 	var ret = "";
 	for (i = 0 ; i<options.length ; i++)

+ 0 - 1
main/admin/add_users_to_usergroup.php

@@ -12,7 +12,6 @@ $cidReset = true;
 
 // including some necessary files
 require_once '../inc/global.inc.php';
-require_once '../inc/lib/xajax/xajax.inc.php';
 
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;

+ 0 - 2
main/admin/career_dashboard.php

@@ -13,8 +13,6 @@ $language_file = array('courses', 'index', 'admin');
 $cidReset = true;
 require_once '../inc/global.inc.php';
 $libpath = api_get_path(LIBRARY_PATH);
-require_once $libpath.'career.lib.php';
-require_once $libpath.'promotion.lib.php';
 
 require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
 require_once api_get_path(SYS_CODE_PATH).'exercice/exercise.lib.php';

+ 0 - 3
main/admin/careers.php

@@ -10,13 +10,11 @@ $language_file = array('admin');
 
 $cidReset = true;
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'career.lib.php';
 
 $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 
-
 //Add the JS needed to use the jqgrid
 $htmlHeadXtra[] = api_get_jqgrid_js();
 
@@ -39,7 +37,6 @@ if ($action == 'add') {
     $interbreadcrumb[]=array('url' => '#','name' => get_lang('Careers'));
 }
 
-// The header.
 Display::display_header($tool_name);
 
 //jqgrid will use this URL to do the selects

+ 88 - 0
main/admin/change_user_session.php

@@ -0,0 +1,88 @@
+<?php
+
+/* For licensing terms, see /license.txt */
+$language_file = 'admin';
+$cidReset = true;
+require_once '../inc/global.inc.php';
+
+$user_id = intval($_REQUEST['user_id']);
+$session_id = intval($_REQUEST['id_session']);
+
+if (empty($user_id) && empty($session_id)) {
+    api_not_allowed(true);
+}
+
+SessionManager::protect_session_edit($session_id);
+
+if (api_is_platform_admin()) {
+    $sessions = SessionManager::get_sessions_admin(array('order' => 'name'));
+} else {
+    $sessions = SessionManager::get_sessions_by_general_coach(api_get_session_id());
+}
+
+$message = null;
+$session_to_select = array();
+foreach ($sessions as $session) {
+    if ($session_id != $session['id']) {
+        $session_to_select[$session['id']] = $session['name'];
+    }
+}
+
+$session_name = api_get_session_name($session_id);
+$user_info = api_get_user_info($user_id);
+
+//Check if user was already moved
+$user_status = SessionManager::get_user_status_in_session($session_id, $user_id);
+if (isset($user_status['moved_to']) && $user_status['moved_to'] != 0 || $user_status['moved_status'] == SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION) {
+    api_not_allowed(true);
+}
+
+$form = new FormValidator('change_user_session', 'post', api_get_self());
+$form->addElement('hidden', 'user_id', $user_id);
+$form->addElement('hidden', 'id_session', $session_id);
+$form->addElement('header', get_lang('ChangeUserSession'));
+$form->addElement('label', get_lang('User'), '<b>'.$user_info['complete_name'].'</b>');
+$form->addElement('label', get_lang('CurrentSession'), $session_name);
+
+$form->addElement('select', 'reason_id', get_lang('Action'), SessionManager::get_session_change_user_reasons(), array('id' => 'reason_id'));
+$form->addElement('select', 'new_session_id', get_lang('SessionDestination'), $session_to_select, array('id' => 'new_session_id'));
+
+$form->addElement('button', 'submit', get_lang('Change'));
+
+$content = $form->return_form();
+
+if ($form->validate()) {
+    $values = $form->getSubmitValues();
+    $result = SessionManager::change_user_session($values['user_id'], $values['id_session'], $values['new_session_id'], $values['reason_id']);
+    if ($result) {
+        $message = Display::return_message(get_lang('UserSessionWasChanged'));
+    }
+    header('Location: resume_session.php?id_session='.$values['id_session']);
+    exit;
+}
+
+$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array('url' => 'session_list.php','name' => get_lang('SessionList'));
+$interbreadcrumb[] = array('url' => 'resume_session.php?id_session='.$session_id,'name' => get_lang('SessionOverview'));
+$interbreadcrumb[] = array('url' => '#','name' => get_lang('ChangeUserSession'));
+
+$htmlHeadXtra[] = '<script>
+
+$(document).ready(function() {
+    $("#reason_id").change(function() {
+        value = $(this).val();
+        if (value == "'.SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION.'") {
+            $("#new_session_id").parent().parent().hide();
+        } else {
+            $("#new_session_id").parent().parent().show();
+        }
+    });
+});
+
+</script>';
+
+$tpl = new Template();
+
+$tpl->assign('message', $message);
+$tpl->assign('content', $content);
+$tpl->display_one_col_template();

+ 0 - 1
main/admin/class_user_import.php

@@ -139,7 +139,6 @@ require_once '../inc/global.inc.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script(true);
 
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(LIBRARY_PATH).'import.lib.php';
 require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
 

+ 2 - 2
main/admin/configure_homepage.php

@@ -150,7 +150,7 @@ if (!empty($_GET['link'])) {
 
 // Start analysing requested actions
 if (!empty($action)) {
-	if ($_POST['formSent']) {
+	if (isset($_POST['formSent']) && $_POST['formSent']) {
 		// Variables used are $homep for home path, $menuf for menu file, $newsf
 		// for news file, $topf for top file, $noticef for noticefile,
 		// $ext for '.html'
@@ -821,7 +821,7 @@ switch ($action) {
 			</tr>
 			<tr>
 			<?php
-            
+
 			$access_url_id = 1;
 			// we only show the category options for the main chamilo installation
 			if (api_is_multiple_url_enabled()) {

+ 1 - 2
main/admin/configure_inscription.php

@@ -13,7 +13,6 @@ require_once '../inc/global.inc.php';
 api_protect_admin_script();
 
 require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
-require_once api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php';
 
 // Load terms & conditions from the current lang
 if (get_setting('allow_terms_conditions') == 'true') {
@@ -278,7 +277,7 @@ if ($display_all_form) {
         }
     }
     $extra_data = UserManager::get_extra_user_data(api_get_user_id(), true);
-    UserManager::set_extra_fields_in_form($form, $extra_data, 'registration');
+    ExtraField::set_extra_fields_in_form($form, $extra_data, 'registration', false, null, 'user');
 }
 
 // Terms and conditions

+ 4 - 4
main/admin/configure_plugin.php

@@ -33,7 +33,7 @@ global $_configuration;
 $content = null;
 
 if (isset($plugin_info['settings_form'])) {
-    $form = $plugin_info['settings_form'];    
+    $form = $plugin_info['settings_form'];
     if (isset($form)) {
         //We override the form attributes
         $attributes = array('action'=>api_get_self().'?name='.$plugin_name, 'method'=>'POST');
@@ -48,7 +48,7 @@ if (isset($plugin_info['settings_form'])) {
 if (isset($form)) {
     if ($form->validate()) {
         $values = $form->exportValues();
-        
+
         //api_delete_category_settings_by_subkey($plugin_name);
         $access_url_id = api_get_current_access_url_id();
         api_delete_settings_params(array('category = ? AND access_url = ? AND subkey = ? AND type = ? and variable <> ?' =>
@@ -56,12 +56,12 @@ if (isset($form)) {
         foreach ($values as $key => $value) {
             $key = Database::escape_string($plugin_name.'_'.$key);
             api_add_setting($value, $key, $plugin_name, 'setting', 'Plugins', $plugin_name, null, null, null, $_configuration['access_url'], 1);
-            
+
         }
         $message = Display::return_message(get_lang('Updated'), 'success');
     }
 }
-$tpl = new Template($tool_name, true, true, false, true, false);
+$tpl = new Template($tool_name);
 $tpl->assign('actions', $actions);
 $tpl->assign('message', $message);
 $tpl->assign('content', $content);

+ 0 - 2
main/admin/course_add.php

@@ -16,8 +16,6 @@ $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-
 $tool_name = get_lang('AddCourse');
 $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array('url' => 'course_list.php', 'name' => get_lang('CourseList'));

+ 5 - 5
main/admin/course_category.php

@@ -83,9 +83,9 @@ if (!empty($category)) {
 }
 
 if (empty($action)) {
-    $myquery = "SELECT t1.name,t1.code,t1.parent_id,t1.tree_pos,t1.children_count,COUNT(DISTINCT t3.code) AS nbr_courses 
-			 	FROM $tbl_category t1 LEFT JOIN $tbl_category t2 ON t1.code=t2.parent_id LEFT JOIN $tbl_course t3 ON t3.category_code=t1.code 
-				WHERE t1.parent_id " . (empty($category) ? "IS NULL" : "='$category'") . " 
+    $myquery = "SELECT t1.name,t1.code,t1.parent_id,t1.tree_pos,t1.children_count,COUNT(DISTINCT t3.code) AS nbr_courses
+			 	FROM $tbl_category t1 LEFT JOIN $tbl_category t2 ON t1.code=t2.parent_id LEFT JOIN $tbl_course t3 ON t3.category_code=t1.code
+				WHERE t1.parent_id " . (empty($category) ? "IS NULL" : "='$category'") . "
 				GROUP BY t1.name,t1.code,t1.parent_id,t1.tree_pos,t1.children_count ORDER BY t1.tree_pos";
     $result = Database::query($myquery);
     $Categories = Database::store_result($result);
@@ -265,7 +265,7 @@ function addNode($code, $name, $canHaveCourses, $parent_id) {
 
     $tree_pos = $row['maxTreePos'] + 1;
 
-    $code = generate_course_code($code);
+    $code = CourseManager::generate_course_code($code);
     Database::query("INSERT INTO $tbl_category(name,code,parent_id,tree_pos,children_count,auth_course_child) VALUES('$name','$code'," . (empty($parent_id) ? "NULL" : "'$parent_id'") . ",'$tree_pos','0','$canHaveCourses')");
 
     updateFils($parent_id);
@@ -287,7 +287,7 @@ function editNode($code, $name, $canHaveCourses, $old_code) {
             return false;
         }
     }
-    $code = generate_course_code($code);
+    $code = CourseManager::generate_course_code($code);
     Database::query("UPDATE $tbl_category SET name='$name', code='$code',auth_course_child='$canHaveCourses' WHERE code='$old_code'");
     $sql = "UPDATE $tbl_course SET category_code = '$code' WHERE category_code = '$old_code' ";
     Database::query($sql);

+ 19 - 119
main/admin/course_edit.php

@@ -12,10 +12,8 @@ $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-
 $course_table       = Database::get_main_table(TABLE_MAIN_COURSE);
-$course_user_table  = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+
 
 $course_code = isset($_GET['course_code']) ? $_GET['course_code'] : $_POST['code'];
 $noPHP_SELF = true;
@@ -174,19 +172,19 @@ $form->addElement('text','disk_quota',array(get_lang('CourseQuota'), null, get_l
 $form->addRule('disk_quota', get_lang('ThisFieldIsRequired'),'required');
 $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(get_lang('SpecialCourse'), get_lang('AllUsersAreAutomaticallyRegistered')) , get_lang($extra_field['field_default_value']), $checked);
-			$form->addElement('checkbox', 'extra_'.$extra_field['field_variable'], array(null, get_lang('AllUsersAreAutomaticallyRegistered')) , get_lang('SpecialCourse'), $checked);
-			break;		
-	}
-}
+//Extra fields
+$extra_field = new ExtraField('course');
+$extra = $extra_field->add_elements($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
@@ -201,10 +199,9 @@ $form->setDefaults($course);
 // Validate form
 if ($form->validate()) {
 	$course = $form->getSubmitValues();
-	$dbName = $_POST['dbName'];
-	$course_code = $course['code'];
-	$visual_code = $course['visual_code'];	
-	$visual_code = generate_course_code($visual_code);   
+    $visual_code = CourseManager::generate_course_code($course['visual_code']);
+    
+    CourseManager::update($course);
 
     // Check if the visual code is already used by *another* course
     $visual_code_is_used = false;
@@ -219,110 +216,13 @@ if ($form->validate()) {
             }
         }
         $warn = substr($warn,0,-1);
-    }
-    // an extra field
-    $extras = array();
-    foreach ($course as $key => $value) {
-	    if (substr($key,0,6)=='extra_') {
-			$extras[substr($key,6)] = $value;
-		}
-		if (substr($key,0,7)=='_extra_') {
-			if(!array_key_exists(substr($key,7), $extras)) $extras[substr($key,7)] = $value;
-		}
-    }
-
-	$tutor_id = $course['tutor_name'];
-	$tutor_name=$platform_teachers[$tutor_id];
-
-	$teachers = $course['group']['course_teachers'];
-
-	$title = $course['title'];
-	$category_code = $course['category_code'];
-	$department_name = $course['department_name'];
-	$department_url = $course['department_url'];
-	$course_language = $course['course_language'];
-    
-    $course['disk_quota'] = $course['disk_quota']*1024*1024;
-     
-	$disk_quota = $course['disk_quota'];
-	$visibility = $course['visibility'];
-	$subscribe = $course['subscribe'];
-	$unsubscribe = $course['unsubscribe'];
-	if (!stristr($department_url, 'http://')) {
-		$department_url = 'http://'.$department_url;
-	}
-	$sql = "UPDATE $course_table SET course_language='".Database::escape_string($course_language)."',
-								title='".Database::escape_string($title)."',
-								category_code='".Database::escape_string($category_code)."',
-								tutor_name='".Database::escape_string($tutor_name)."',
-								visual_code='".Database::escape_string($visual_code)."',
-								department_name='".Database::escape_string($department_name)."',
-								department_url='".Database::escape_string($department_url)."',
-								disk_quota='".Database::escape_string($disk_quota)."',
-								visibility = '".Database::escape_string($visibility)."',
-								subscribe = '".Database::escape_string($subscribe)."',
-								unsubscribe='".Database::escape_string($unsubscribe)."'
-							WHERE code='".Database::escape_string($course_code)."'";
-	Database::query($sql);
-
-	//update the extra fields
-	if (count($extras) > 0) {
-		foreach ($extras as $key => $value) {
-			CourseManager::update_course_extra_field_value($course_code, $key, $value);
-		}
-	}
-
-	//Delete only teacher relations that doesn't match the selected teachers
-	$cond='';
-	if (count($teachers)>0) {
-		foreach($teachers as $key) $cond.=" AND user_id<>'".$key."'";
-	}
-	$sql='DELETE FROM '.$course_user_table.' WHERE course_code="'.Database::escape_string($course_code).'" AND status="1"'.$cond;
-	Database::query($sql);
-
-	if (count($teachers)>0) {
-		foreach ($teachers as $key) {
-
-			//We check if the teacher is already subscribed in this course
-			$sql_select_teacher = 'SELECT 1 FROM '.$course_user_table.' WHERE user_id = "'.$key.'" AND course_code = "'.$course_code.'" ';
-			$result = Database::query($sql_select_teacher);
-
-			if (Database::num_rows($result) == 1) {
-				$sql = 'UPDATE '.$course_user_table.' SET status = "1" WHERE course_code = "'.$course_code.'" AND user_id = "'.$key.'"  ';
-			} else {
-				$sql = "INSERT INTO ".$course_user_table . " SET
-					course_code = '".Database::escape_string($course_code). "',
-					user_id = '".$key . "',
-					status = '1',
-					role = '',
-					tutor_id='0',
-					sort='0',
-					user_course_cat='0'";
-			}
-			Database::query($sql);
-		}
-	}
-
-	$sql = "INSERT IGNORE INTO ".$course_user_table . " SET
-				course_code = '".Database::escape_string($course_code). "',
-				user_id = '".$tutor_id . "',
-				status = '1',
-				role = '',
-				tutor_id='0',
-				sort='0',
-				user_course_cat='0'";
-	Database::query($sql);
-	
-	$course_info = api_get_course_info($course_code);
-	$course_id = $course_info['real_id'];
-	$forum_config_table = Database::get_course_table(TOOL_FORUM_CONFIG_TABLE);
-	$sql = "UPDATE ".$forum_config_table." SET default_lang='".Database::escape_string($course_language)."' WHERE c_id = $course_id ";
+    }    
 	if ($visual_code_is_used) {
 	    header('Location: course_list.php?action=show_msg&warn='.urlencode($warn));
 	} else {
         header('Location: course_list.php');
 	}
-	exit ();
+	
 }
 Display::display_header($tool_name);
 

+ 1 - 2
main/admin/course_import.php

@@ -153,12 +153,11 @@ $language_file = array('admin', 'registration','create_course', 'document');
 
 $cidReset = true;
 
-require '../inc/global.inc.php';
+require_once '../inc/global.inc.php';
 
 $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
 
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(LIBRARY_PATH).'import.lib.php';
 $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
 

+ 47 - 51
main/admin/course_information.php

@@ -56,24 +56,21 @@ if (!isset ($_GET['code'])) {
 }
 $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array ("url" => 'course_list.php', "name" => get_lang('Courses'));
-$table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
-$code = Database::escape_string($_GET['code']);
-$sql = "SELECT * FROM $table_course WHERE code = '".$code."'";
-$res = Database::query($sql);
-$course = Database::fetch_object($res);
-$tool_name = $course->title.' ('.$course->visual_code.')';
+
+$course_info = api_get_course_info($_GET['code']);
+$tool_name = $course_info['title'].' ('.$course_info['visual_code'].')';
 Display::display_header($tool_name);
-/* <a href="course_create_content.php?course_code=<?php echo $course->code ?>"><?php echo get_lang('AddDummyContentToCourse') ?></a> */
-?>
-<div class="actions">
-<a href="<?php echo api_get_path(WEB_COURSE_PATH).$course->directory; ?>"><?php Display::display_icon('home.png', get_lang('CourseHomepage'), array(), ICON_SIZE_MEDIUM); ?></a>
-</div>
-<?php 
 
-echo Display::page_header(get_lang('CourseUsage'));
+echo '<div class="actions">';
+echo '<a href="'.api_get_path(WEB_COURSE_PATH).$course_info['directory'].'">'.Display::display_icon('home.png', get_lang('CourseHomepage'), array(), ICON_SIZE_MEDIUM).'</a>';
+echo '</div>';
+
+echo Display::page_header($tool_name);
+
+echo Display::page_subheader(get_lang('CourseUsage'));
 
 $id_session = intval($_GET['id_session']);
-$table = new SortableTableFromArray(get_course_usage($course->code,$id_session),0,20,'usage_table');
+$table = new SortableTableFromArray(get_course_usage($course_info['code'],$id_session),0,20,'usage_table');
 $table->set_additional_parameters(array ('code' => Security::remove_XSS($_GET['code'])));
 $table->set_other_tables(array('user_table','class_table'));
 $table->set_header(0,get_lang('Tool'), true);
@@ -83,10 +80,10 @@ $table->display();
 /**
  * Show all users subscribed in this course
  */
-echo Display::page_header(get_lang('Users'));
+echo Display::page_subheader(get_lang('Users'));
 $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 $table_user = Database :: get_main_table(TABLE_MAIN_USER);
-$sql = "SELECT *,cu.status as course_status FROM $table_course_user cu, $table_user u WHERE cu.user_id = u.user_id AND cu.course_code = '".$code."' AND cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH." ";
+$sql = "SELECT *, cu.status as course_status FROM $table_course_user cu, $table_user u WHERE cu.user_id = u.user_id AND cu.course_code = '".$course_info['code']."' AND cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH." ";
 $res = Database::query($sql);
 $is_western_name_order = api_is_western_name_order();
 if (Database::num_rows($res) > 0) {
@@ -107,7 +104,7 @@ if (Database::num_rows($res) > 0) {
 		$users[] = $user;
 	}
 	$table = new SortableTableFromArray($users,0,20,'user_table');
-	$table->set_additional_parameters(array ('code' => $code));
+	$table->set_additional_parameters(array ('code' => $course_info['code']));
 	$table->set_other_tables(array('usage_table','class_table'));
 	$table->set_header(0,get_lang('OfficialCode'), true);
 	if ($is_western_name_order) {
@@ -122,10 +119,10 @@ if (Database::num_rows($res) > 0) {
 	$table->set_header(5,'', false);
 	$table->display();
 } else {
-	echo get_lang('NoUsersInCourse');
+	echo Display::display_warning_message(get_lang('NoUsersInCourse'));
 }
 
-$session_list = SessionManager::get_session_by_course($course->code);
+$session_list = SessionManager::get_session_by_course($course_info['code']);
 
 $url = api_get_path(WEB_CODE_PATH);
 if (!empty($session_list)) {
@@ -133,41 +130,40 @@ if (!empty($session_list)) {
         $session[0] = Display::url($session[0], $url.'admin/resume_session.php?id_session='.$session['id'] );
         unset($session[1]);
     }
-    echo Display::page_header(get_lang('Sessions')); 
+    echo Display::page_subheader(get_lang('Sessions'));
     $table = new SortableTableFromArray($session_list, 0, 20,'user_table');
     $table->display();
 }
 
-/*$group = new UserGroup();
-$usegroups = $group->get_usergroup_by_course($course->id);*/
+$extra_field = new ExtraField('course');
+$extra_fields = $extra_field->get_all();
+
+if (!empty($extra_fields)) {
+    echo Display::page_subheader(get_lang('ExtraFields'));
+    echo '<table class="data_table">';    
+    foreach ($extra_fields as $field) {
+        if ($field['field_visible'] != '1') {
+            continue;
+        }
+        $obj = new ExtraFieldValue($extra_field->type);
+        $result = $obj->get_values_by_handler_and_field_id($course_info['code'], $field['id'], true);
+        
+        $value = null;        
+        if ($result) {
+            $value = $result['field_value'];
+            
+            if (is_bool($value)) {
+                $value = $value ? get_lang('Yes') : get_lang('No');
+            }            
+        } else {
+            $value = '-';
+        }
+        echo "<tr>";
+        echo "<td> {$field['field_display_text']} </td>";
+        echo "<td> $value </td>";
+        echo "</tr>";    
+    }
+    echo "</table>";
+}
 
-/*@todo This should be dissapear classes are a deprecated feature*/ 
-/*
-//Show all classes subscribed in this course
- 
-$table_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
-$table_class 		= Database :: get_main_table(TABLE_MAIN_CLASS);
-$sql = "SELECT * FROM $table_course_class cc, $table_class c WHERE cc.class_id = c.id AND cc.course_code = '".$code."'";
-$res = Database::query($sql);
-if (Database::num_rows($res) > 0) {
-	$data = array ();
-	while ($class = Database::fetch_object($res)) {
-		$row = array ();
-		$row[] = $class->name;
-		$row[] = '<a href="class_information.php?id='.$class->id.'">'.Display::return_icon('synthese_view.gif', get_lang('Edit')).'</a>';
-		$data[] = $row;
-	}
-	echo '<p><b>'.get_lang('AdminClasses').'</b></p>';
-	echo '<blockquote>';
-	$table = new SortableTableFromArray($data,0,20,'class_table');
-	$table->set_additional_parameters(array ('code' => $_GET['code']));
-	$table->set_other_tables(array('usage_table','user_table'));
-	$table->set_header(0,get_lang('Title'));
-	$table->set_header(1,'');
-	$table->display();
-	echo '</blockquote>';
-} else {
-	echo '<p>'.get_lang('NoClassesForThisCourse').'</p>';
-}*/
-/*	FOOTER	*/
 Display::display_footer();

+ 1 - 11
main/admin/course_request_accepted.php

@@ -18,22 +18,12 @@ $language_file = array('admin', 'create_course');
 
 $cidReset = true;
 
-require '../inc/global.inc.php';
+require_once '../inc/global.inc.php';
 
 $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 
-require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
-require_once api_get_path(CONFIGURATION_PATH).'course_info.conf.php';
-require_once api_get_path(LIBRARY_PATH).'course_request.lib.php';
-
-// Including a configuration file.
-require api_get_path(CONFIGURATION_PATH).'add_course.conf.php';
-
-// Include additional libraries
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-
 // A check whether the course validation feature is enabled.
 $course_validation_feature = api_get_setting('course_validation') == 'true';
 

+ 0 - 11
main/admin/course_request_edit.php

@@ -19,17 +19,6 @@ $tool_name = get_lang('CourseRequestEdit');
 
 api_protect_admin_script();
 
-require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
-require_once api_get_path(CONFIGURATION_PATH).'course_info.conf.php';
-require_once api_get_path(LIBRARY_PATH).'course_request.lib.php';
-require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
-
-// Including a configuration file.
-require_once api_get_path(CONFIGURATION_PATH).'add_course.conf.php';
-
-// Including additional libraries.
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-
 // A check whether the course validation feature is enabled.
 $course_validation_feature = api_get_setting('course_validation') == 'true';
 

+ 3 - 14
main/admin/course_request_rejected.php

@@ -24,17 +24,6 @@ $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 
-require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
-require_once api_get_path(CONFIGURATION_PATH).'course_info.conf.php';
-require_once api_get_path(LIBRARY_PATH).'course_request.lib.php';
-require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
-
-// Including a configuration file.
-require api_get_path(CONFIGURATION_PATH).'add_course.conf.php';
-
-// Including additional libraries.
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-
 // A check whether the course validation feature is enabled.
 $course_validation_feature = api_get_setting('course_validation') == 'true';
 
@@ -48,9 +37,9 @@ $keyword = Database::escape_string(trim($_GET['keyword']));
 
 if ($course_validation_feature) {
 
-/**
- * Acceptance and creation of the requested course.
- */
+    /**
+     * Acceptance and creation of the requested course.
+     */
     if (!empty($accept_course_request)) {
         $course_request_code = CourseRequestManager::get_course_request_code($accept_course_request);
         $course_id = CourseRequestManager::accept_course_request($accept_course_request);

+ 1 - 12
main/admin/course_request_review.php

@@ -16,22 +16,11 @@
 $language_file = array('admin', 'create_course');
 
 $cidReset = true;
-require '../inc/global.inc.php';
+require_once '../inc/global.inc.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 
-require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
-require_once api_get_path(CONFIGURATION_PATH).'course_info.conf.php';
-require_once api_get_path(LIBRARY_PATH).'course_request.lib.php';
-require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
-
-// Including a configuration file.
-require_once api_get_path(CONFIGURATION_PATH).'add_course.conf.php';
-
-// Including additional libraries.
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-
 // The delete action should be deactivated in this page.
 // Better reject the target request, after that you can delete it.
 define(DELETE_ACTION_ENABLED, false);

+ 0 - 5
main/admin/course_user_import.php

@@ -155,12 +155,7 @@ $this_section = SECTION_PLATFORM_ADMIN;
 // Protecting the admin section.
 api_protect_admin_script();
 
-// Including additional libraries.
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'import.lib.php';
-
 $tool_name = get_lang('AddUsersToACourse').' CSV';
-
 $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 
 set_time_limit(0);

+ 0 - 3
main/admin/dashboard_add_courses_to_user.php

@@ -13,11 +13,8 @@ $cidReset=true;
 
 // including some necessary dokeos files
 require_once '../inc/global.inc.php';
-require_once '../inc/lib/xajax/xajax.inc.php';
 
 global $_configuration;
-
-
 // create an ajax object
 $xajax = new xajax();
 $xajax -> registerFunction ('search_courses');

+ 0 - 1
main/admin/dashboard_add_sessions_to_user.php

@@ -13,7 +13,6 @@ $cidReset=true;
 
 // including some necessary dokeos files
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'xajax/xajax.inc.php';
 global $_configuration;
 
 // create an ajax object

+ 0 - 1
main/admin/dashboard_add_users_to_user.php

@@ -13,7 +13,6 @@ $cidReset=true;
 
 // including some necessary dokeos files
 require_once '../inc/global.inc.php';
-require_once '../inc/lib/xajax/xajax.inc.php';
 
 global $_configuration;
 

+ 2 - 2
main/admin/example_session.csv

@@ -1,3 +1,3 @@
 SessionName;Coach;DateStart;DateEnd;Users;Courses
-Session1;jmontoya;2008/08/08;2012/12/12;username1|username2;course1[coach1][username1,username2]|course2[coach1][username1,username2]
-Session2;jmontoya;2008/08/08;2012/12/12;username1|username2;course1[coach1][username1,username2]|course2[coach1][username1,username2]
+Session1;jmontoya;2012-06-30 11:00:00;2016-06-30 11:00:00;username1|username2;course1[coach1][username1,username2]|course2[coach1][username1,username2]
+Session2;jmontoya;2012-06-30 11:00:00;2016-06-30 11:00:00;username1|username2;course1[coach1][username1,username2]|course2[coach1][username1,username2]

+ 2 - 2
main/admin/example_session.xml

@@ -24,8 +24,8 @@
     <Session>
         <SessionName>The Universe</SessionName>
         <Coach>Coach</Coach>
-        <DateStart>2008/08/01</DateStart>
-        <DateEnd>2020/12/12</DateEnd>
+        <DateStart>2012-06-30 11:00:00</DateStart>
+        <DateEnd>2016-06-30 11:00:00</DateEnd>
         <User>jmontoya</User>
         <User>jmontoya2</User>
     	<Course>

+ 164 - 0
main/admin/extra_field_options.php

@@ -0,0 +1,164 @@
+<?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;
+$field_id = isset($_GET['field_id']) ? $_GET['field_id'] : null;
+$type = 'session';
+
+if (empty($field_id)) {
+    api_not_allowed();
+}
+
+$extra_field = new ExtraField($type);
+$extra_field_info = $extra_field->get($field_id);
+
+
+$check = Security::check_token('request');
+$token = Security::get_token();    
+
+if ($action == 'add') {
+    $interbreadcrumb[]=array('url' => 'session_fields.php','name' => get_lang('ExtraFields'));
+    $interbreadcrumb[]=array('url' => 'session_fields.php?action=edit&id='.$extra_field_info['id'],'name' => $extra_field_info['field_display_text']);
+    $interbreadcrumb[]=array('url' => 'extra_field_options.php?type='.$type.'&field_id='.$extra_field_info['id'], 'name' => get_lang('EditExtraFieldOptions'));
+    $interbreadcrumb[]=array('url' => '#','name' => get_lang('Add'));
+} elseif ($action == 'edit') {
+    $interbreadcrumb[]=array('url' => 'session_fields.php','name' => get_lang('ExtraFields'));
+    $interbreadcrumb[]=array('url' => 'session_fields.php?action=edit&id='.$extra_field_info['id'],'name' => $extra_field_info['field_display_text']);
+    $interbreadcrumb[]=array('url' => 'extra_field_options.php?type='.$type.'&field_id='.$extra_field_info['id'], 'name' => get_lang('EditExtraFieldOptions'));
+    
+    $interbreadcrumb[]=array('url' => '#','name' => get_lang('Edit'));
+} else {
+    $interbreadcrumb[]=array('url' => 'session_fields.php','name' => get_lang('ExtraFields'));
+    $interbreadcrumb[]=array('url' => 'session_fields.php?action=edit&id='.$extra_field_info['id'],'name' => $extra_field_info['field_display_text']);
+    $interbreadcrumb[]=array('url' => '#','name' => get_lang('EditExtraFieldOptions'));
+}
+
+//jqgrid will use this URL to do the selects
+$params = 'field_id='.$field_id.'&type='.$type;
+$url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_extra_field_options&'.$params;
+
+//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('Value'),  get_lang('Order'), get_lang('Actions'));
+  
+//Column config
+$column_model   = array(
+                        array('name'=>'option_display_text', 'index'=>'option_display_text',      'width'=>'180',   'align'=>'left'),
+                        array('name'=>'option_value',       'index'=>'option_value',          'width'=>'',  'align'=>'left','sortable'=>'false'),
+                        array('name'=>'option_order',         'index'=>'option_order',              'width'=>'',  'align'=>'left','sortable'=>'false'),
+                        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'; 
+
+//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&'.$params.'&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&'.$params.'&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('extra_field_options',  $url, $columns, $column_model, $extra_params, array(), $action_links, true).'
+    
+});
+</script>';
+
+// The header.
+Display::display_header($tool_name);
+
+echo Display::page_header($extra_field_info['field_display_text']);
+
+$obj = new ExtraFieldOption($type);
+$obj->field_id = $field_id;
+
+// 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']).'&'.$params;
+        $form = $obj->return_form($url, 'add');
+
+        // The validation or display
+        if ($form->validate()) {
+            if ($check) {
+                $values = $form->exportValues();
+                $res    = $obj->save_one_item($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']).'&'.$params;
+        $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['name']), 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();

+ 6 - 1
main/admin/filler.php

@@ -39,6 +39,10 @@ if (!empty($_GET['fill'])) {
             require api_get_path(SYS_TEST_PATH).'datafiller/fill_courses.php';
             $output = fill_courses();
             break;
+        case 'exe':
+            require api_get_path(SYS_TEST_PATH).'datafiller/fill_exe.php';
+            $output = fill_exe();
+            break;
         default:
             break;
     }
@@ -68,8 +72,9 @@ if (count($output)>0) {
   <ul>
     <li><a href="filler.php?fill=users"><?php echo get_lang('FillUsers');?></a></li>
     <li><a href="filler.php?fill=courses"><?php echo get_lang('FillCourses');?></a></li>
+    <li><a href="filler.php?fill=exe"><?php echo get_lang('FillExercises');?></a></li>
   </ul>
 </div>
 <?php
 /* FOOTER */
-Display::display_footer();
+Display::display_footer();

+ 0 - 1
main/admin/grade_models.php

@@ -10,7 +10,6 @@ $language_file = array('admin', 'gradebook');
 
 $cidReset = true;
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'grade_model.lib.php';
 
 $this_section = SECTION_PLATFORM_ADMIN;
 

+ 1 - 2
main/admin/group_add.php

@@ -12,7 +12,6 @@ $cidReset = true;
 // Including necessary libraries.
 require '../inc/global.inc.php';
 $libpath = api_get_path(LIBRARY_PATH);
-require_once $libpath.'fileManage.lib.php';
 require_once $libpath.'fileUpload.lib.php';
 
 // Section for the tabs
@@ -133,7 +132,7 @@ if( $form->validate()) {
 			else {
 				$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName') ." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $_configuration['root_web'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
 			}
-			@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
+			api_mail_html($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
 		}*/
 
 		Security::clear_token();

+ 0 - 3
main/admin/group_edit.php

@@ -12,10 +12,7 @@ $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
 
 $libpath = api_get_path(LIBRARY_PATH);
-require_once $libpath.'fileManage.lib.php';
 require_once $libpath.'fileUpload.lib.php';
-require_once $libpath.'group_portal_manager.lib.php';
-require_once $libpath.'mail.lib.inc.php';
 
 $group_id = isset($_GET['id']) ? intval($_GET['id']) : intval($_POST['id']);
 $tool_name = get_lang('GroupEdit');

+ 0 - 2
main/admin/group_list.php

@@ -10,8 +10,6 @@
 $language_file = array('registration', 'admin', 'userInfo');
 $cidReset = true;
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'xajax/xajax.inc.php';
-require_once api_get_path(LIBRARY_PATH).'group_portal_manager.lib.php';
 
 $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script(true);

+ 0 - 4
main/admin/inactive_user_list.php

@@ -13,10 +13,6 @@
 $language_file = array ('registration','admin');
 $cidReset = true;
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'sortable_table.class.php';
-require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
-require_once api_get_path(LIBRARY_PATH).'security.lib.php';
-require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
 
 $tbl_stats_access 		= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ACCESS);
 $this_section = SECTION_PLATFORM_ADMIN;

+ 12 - 15
main/admin/index.php

@@ -15,7 +15,6 @@ $cidReset = true;
 
 // Including some necessary chamilo files.
 require_once '../inc/global.inc.php';
-require_once api_get_path(SYS_CODE_PATH).'admin/statistics/statistics.lib.php';
 
 // Setting the section (for the tabs).
 $this_section = SECTION_PLATFORM_ADMIN;
@@ -28,6 +27,7 @@ $nameTools = get_lang('PlatformAdmin');
 // Displaying the header
 $message = '';
 
+
 if (api_is_platform_admin()) {
     if (is_dir(api_get_path(SYS_CODE_PATH).'install/') && is_readable(api_get_path(SYS_CODE_PATH).'install/index.php')) {
         $message = Display::return_message(get_lang('InstallDirAccessibleSecurityThreat'),'warning');
@@ -148,7 +148,7 @@ if (api_is_platform_admin()) {
     $items[] = array('url'=>'settings.php?category=Plugins','label' => get_lang('Plugins'));
     $items[] = array('url'=>'settings.php?category=Regions','label' => get_lang('Regions'));
     $items[] = array('url'=>'system_announcements.php', 	'label' => get_lang('SystemAnnouncements'));
-    $items[] = array('url'=> api_get_path(WEB_CODE_PATH).'calendar/agenda_js.php?type=admin', 'label' => get_lang('GlobalAgenda'));
+    $items[] = array('url'=>api_get_path(WEB_CODE_PATH).'calendar/agenda_js.php?type=admin', 'label' => get_lang('GlobalAgenda'));
     $items[] = array('url'=>'configure_homepage.php', 		'label' => get_lang('ConfigureHomePage'));
     $items[] = array('url'=>'configure_inscription.php', 	'label' => get_lang('ConfigureInscription'));
     $items[] = array('url'=>'statistics/index.php', 		'label' => get_lang('Statistics'));
@@ -161,9 +161,9 @@ if (api_is_platform_admin()) {
     }
 
     if (!empty($_configuration['multiple_access_urls'])) {
-		if (api_is_global_platform_admin()) {
+	if (api_is_global_platform_admin()) {
             	$items[] = array('url'=>'access_urls.php', 	'label' => get_lang('ConfigureMultipleAccessURLs'));
-            }
+        }
     }
 
     if (api_get_setting('allow_reservation') == 'true') {
@@ -204,6 +204,7 @@ if (api_is_platform_admin()) {
 }
 
 $items[] = array('url'=>'usergroups.php', 	'label' => get_lang('Classes'));
+$items[] = array('url'=>'session_fields.php', 	'label' => get_lang('ManageSessionFields'));
 
 $blocks['sessions']['items'] = $items;
 $blocks['sessions']['extra'] = null;
@@ -224,10 +225,8 @@ if (api_is_platform_admin()) {
 	if (is_dir(api_get_path(SYS_TEST_PATH).'datafiller/')) {
 		$items[] = array('url'=>'filler.php', 	'label' => get_lang('DataFiller'));
 	}
-	$items[] = array('url'=>'archive_cleanup.php', 	'label' => get_lang('ArchiveDirCleanup'));
-        if (api_get_setting('server_type') === 'test') {
-            $items[] = array('url'=>'system_management.php', 'label' => get_lang('SystemManagement'));
-        }
+    $items[] = array('url'=>'archive_cleanup.php', 	'label' => get_lang('ArchiveDirCleanup'));
+	$items[] = array('url'=>'system_management.php', 'label' => get_lang('SystemManagement'));
 
 	$blocks['settings']['items'] = $items;
     $blocks['settings']['extra'] = null;
@@ -300,13 +299,11 @@ if (api_is_platform_admin()) {
     $blocks['version_check']['items'] = null;
 }
 
+
 $tpl = new Template();
+
 $tpl->assign('blocks', $blocks);
-$admin_template = $tpl->get_template('admin/settings_index.tpl');
-$content = $tpl->fetch($admin_template);
-$tpl->assign('content', $content);
-$tpl->assign('message', $message);
-$tpl->display_one_col_template();
+$tpl->display('default/admin/settings_index.tpl');
 
 /**
  * Displays either the text for the registration or the message that the installation is (not) up to date
@@ -332,7 +329,7 @@ function version_check() {
         $return .= '</form>';
         check_system_version();
     } else {
-        // site not registered. Call anyway
+        // Site registered. Call anyway
         $return .= check_system_version();
     }
     return $return;
@@ -375,7 +372,7 @@ function check_system_version() {
 
     if (ini_get('allow_url_fopen') == 1) {
         // The number of courses
-        $number_of_courses = statistics::count_courses();
+        $number_of_courses = Statistics::count_courses();
 
         // The number of users
         $number_of_users = statistics::count_users();

+ 4 - 12
main/admin/ldap_import_students_to_session.php

@@ -76,18 +76,10 @@ elseif(!empty($annee) && empty($id_session))
 	echo Display::return_icon('course.gif', get_lang('SelectSessionToImportUsersTo')).' '.get_lang('SelectSessionToImportUsersTo').'<br />';
 	echo '<form method="post" action="'.api_get_self().'?annee='.Security::remove_XSS($annee).'"><br />';
 	echo '<select name="id_session">';
-
-	$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
-	$sql = "SELECT id,name,nbr_courses,date_start,date_end " .
-		" FROM $tbl_session ".
-		" ORDER BY name";
-	$result = Database::query($sql);
-
-	$sessions=Database::store_result($result);
-	$nbr_results=count($sessions);
-	foreach($sessions as $row)
-	{
-		echo '<option value="'.$row['id'].'">'.api_htmlentities($row['name'], ENT_COMPAT, api_get_system_encoding()).' ('.$row['date_start'].' - '.$row['date_end'].')</option>';
+    
+    $sessions = SessionManager::get_sessions_list();	
+	foreach ($sessions as $row) {
+		echo '<option value="'.$row['id'].'">'.api_htmlentities($row['name'], ENT_COMPAT, api_get_system_encoding()).' ('.api_get_local_time($row['access_start_date']).' - '.api_get_local_time($row['access_end_date']).')</option>';
 	}
 	echo '</select>';
 	echo '<input type="submit" value="'.get_lang('Submit').'">';

+ 220 - 204
main/admin/resume_session.php

@@ -23,42 +23,19 @@ $tool_name = get_lang('SessionOverview');
 $interbreadcrumb[] = array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array('url' => 'session_list.php','name' => get_lang('SessionList'));
 
-// Database Table Definitions
-$tbl_session						= Database::get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_rel_class				= Database::get_main_table(TABLE_MAIN_SESSION_CLASS);
-$tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_course							= Database::get_main_table(TABLE_MAIN_COURSE);
-$tbl_user							= Database::get_main_table(TABLE_MAIN_USER);
-$tbl_session_rel_user				= Database::get_main_table(TABLE_MAIN_SESSION_USER);
-$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-$tbl_session_category				= Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
-
-$table_access_url_user              = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-
-$sql = 'SELECT name, nbr_courses, nbr_users, nbr_classes, DATE_FORMAT(date_start,"%d-%m-%Y") as date_start, DATE_FORMAT(date_end,"%d-%m-%Y") as date_end, lastname, firstname, username, session_admin_id, nb_days_access_before_beginning, nb_days_access_after_end, session_category_id, visibility
-		FROM '.$tbl_session.' LEFT JOIN '.$tbl_user.' ON id_coach = user_id
-		WHERE '.$tbl_session.'.id='.$id_session;
-
-$rs      = Database::query($sql);
-$session = Database::store_result($rs);
-$session = $session[0];
-
-$sql = 'SELECT name FROM  '.$tbl_session_category.' WHERE id = "'.intval($session['session_category_id']).'"';
-$rs = Database::query($sql);
-$session_category = '';
-
-if (Database::num_rows($rs)>0) {
-	$rows_session_category = Database::store_result($rs);
-	$rows_session_category = $rows_session_category[0];
-	$session_category = $rows_session_category['name'];
+$session = api_get_session_info($id_session);
+$session_cat_info = SessionManager::get_session_category($session['session_category_id']);
+$session_category = null;
+if (!empty($session_cat_info)) {
+    $session_category = $session_cat_info['name'];
 }
 
 $action = isset($_GET['action']) ? $_GET['action'] : null;
 
-$url_id = api_get_current_access_url_id();
+$url_id = api_get_current_access_url_id();     
 
-switch($action) {
-    case 'add_user_to_url':
+switch ($action) {
+    case 'add_user_to_url':        
         $user_id = $_REQUEST['user_id'];
         $result = UrlManager::add_user_to_url($user_id, $url_id);
         $user_info = api_get_user_info($user_id);
@@ -67,42 +44,15 @@ switch($action) {
         }
         break;
     case 'delete':
-        $idChecked = $_GET['idChecked'];
-        if(is_array($idChecked)) {
-            $my_temp = array();
-            foreach ($idChecked as $id){
-                $my_temp[]= Database::escape_string($id);// forcing the escape_string
-            }
-            $idChecked = $my_temp;
-
-            $idChecked="'".implode("','",$idChecked)."'";
-
-            Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND course_code IN($idChecked)");
-            $nbr_affected_rows=Database::affected_rows();
-
-            Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code IN($idChecked)");
-            Database::query("UPDATE $tbl_session SET nbr_courses=nbr_courses-$nbr_affected_rows WHERE id='$id_session'");
-        }
-
-        if(!empty($_GET['class'])){
-            Database::query("DELETE FROM $tbl_session_rel_class WHERE session_id='$id_session' AND class_id=".Database::escape_string($_GET['class']));
-            $nbr_affected_rows=Database::affected_rows();
-            Database::query("UPDATE $tbl_session SET nbr_classes=nbr_classes-$nbr_affected_rows WHERE id='$id_session'");
+        if (isset($_GET['course_code_to_delete'])) {
+            SessionManager::delete_course_in_session($id_session, $_GET['course_code_to_delete']);
         }
-
         if (!empty($_GET['user'])) {
-            Database::query("DELETE FROM $tbl_session_rel_user WHERE relation_type<>".SESSION_RELATION_TYPE_RRHH." AND id_session='$id_session' AND id_user=".intval($_GET['user']));
-            $nbr_affected_rows=Database::affected_rows();
-
-            Database::query("UPDATE $tbl_session SET nbr_users=nbr_users-$nbr_affected_rows WHERE id='$id_session'");
-
-            Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND id_user=".intval($_GET['user']));
-            $nbr_affected_rows=Database::affected_rows();
-
-            Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE id_session='$id_session'");
+            SessionManager::unsubscribe_user_from_session($id_session, $_GET['user']);            
         }
         break;
 }
+
 Display::display_header($tool_name);
 
 if (!empty($_GET['warn'])) {
@@ -112,18 +62,20 @@ if (!empty($_GET['warn'])) {
 if (!empty($message)) {
     echo $message;
 }
+$dates = SessionManager::parse_session_dates($session);
+echo Display::page_header(Display::return_icon('session.png', get_lang('Session')).' '.$session['name']." <small>$dates</small>");
 
-echo Display::page_header(Display::return_icon('session.png', get_lang('Session')).' '.$session['name']);
-
-$url = Display::url(Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL), "session_edit.php?page=resume_session.php&id=$id_session");
+$url = Display::url(Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL), "session_add.php?page=resume_session.php&id=$id_session");
 echo Display::page_subheader(get_lang('GeneralProperties').$url);
 
+$coach_info = api_get_user_info($session['id_coach']);
+
 ?>
 <!-- General properties -->
 <table class="data_table">
 <tr>
 	<td><?php echo get_lang('GeneralCoach'); ?> :</td>
-	<td><?php echo api_get_person_name($session['firstname'], $session['lastname']).' ('.$session['username'].')' ?></td>
+	<td><?php echo $coach_info['complete_name'].' ('.$coach_info['username'].')' ?></td>
 </tr>
 <?php if(!empty($session_category)) { ?>
 <tr>
@@ -132,67 +84,83 @@ echo Display::page_subheader(get_lang('GeneralProperties').$url);
 </tr>
 <?php } ?>
 <tr>
-	<td><?php echo get_lang('Date'); ?> :</td>
-	<td>
-	<?php
-		if ($session['date_start'] == '00-00-0000' && $session['date_end']== '00-00-0000' )
-			echo get_lang('NoTimeLimits');
-		else {
-            if ($session['date_start'] != '00-00-0000') {
-            	//$session['date_start'] = Display::tag('i', get_lang('NoTimeLimits'));
-                $session['date_start'] =  get_lang('From').' '.$session['date_start'];
-            } else {
-            	$session['date_start'] = '';
-            }
-            if ($session['date_end'] == '00-00-0000') {
-                $session['date_end'] ='';
-            } else {
-            	$session['date_end'] = get_lang('Until').' '.$session['date_end'];
-            }
-			echo $session['date_start'].' '.$session['date_end'];
-        }
-        ?>
-	</td>
+	<td><?php echo get_lang('SessionDisplayStartDate'); ?> :</td>
+	<td><?php echo api_get_local_time($session['display_start_date'], null, null, true); ?></td>    
 </tr>
-<!-- show nb_days_before and nb_days_after only if they are different from 0 -->
 <tr>
-	<td>
-		<?php echo api_ucfirst(get_lang('DaysBefore')) ?> :
-	</td>
-	<td>
-		<?php echo intval($session['nb_days_access_before_beginning']) ?>
-	</td>
+    <td><?php echo get_lang('SessionDisplayEndDate'); ?> :</td>
+	<td><?php echo api_get_local_time($session['display_end_date'], null, null, true); ?></td>
 </tr>
-<tr>
-	<td>
-		<?php echo api_ucfirst(get_lang('DaysAfter')) ?> :
-	</td>
-	<td>
-		<?php echo intval($session['nb_days_access_after_end']) ?>
-	</td>
+<tr>    
+    <td><?php echo get_lang('SessionStartDate'); ?> :</td>
+	<td><?php echo api_get_local_time($session['access_start_date'], null, null, true); ?></td>
+</tr>
+<tr>    
+    <td><?php echo get_lang('SessionEndDate'); ?> :</td>
+	<td><?php echo api_get_local_time($session['access_end_date'], null, null, true); ?></td>
+</tr>
+<tr>    
+    <td><?php echo get_lang('SessionCoachStartDate'); ?> :</td>
+	<td><?php echo api_get_local_time($session['coach_access_start_date'], null, null, true); ?></td>
+</tr>
+<tr>    
+    <td><?php echo get_lang('SessionCoachEndDate'); ?> :</td>
+	<td><?php echo api_get_local_time($session['coach_access_end_date'], null, null, true); ?></td>
 </tr>
 <tr>
 	<td>
 		<?php echo api_ucfirst(get_lang('SessionVisibility')) ?> :
 	</td>
 	<td>
-		<?php if ($session['visibility']==1) echo get_lang('ReadOnly'); elseif($session['visibility']==2) echo get_lang('Visible');elseif($session['visibility']==3) echo api_ucfirst(get_lang('Invisible'))  ?>
+		<?php        
+        if (isset($session['access_end_date']) && $session['access_end_date'] != '0000-00-00 00:00:00') {            
+            if ($session['visibility'] == 1) 
+                echo get_lang('ReadOnly'); 
+             elseif($session['visibility'] == 2) 
+                 echo get_lang('Visible');
+             elseif($session['visibility'] == 3) 
+                echo api_ucfirst(get_lang('Invisible'));
+        } else {
+            //By default course sessions can be access normally see function api_get_session_visibility() when no date_end is proposed            
+            echo get_lang('Visible'); 
+        }
+        ?>
 	</td>
 </tr>
 
 <?php
 
-$multiple_url_is_on = api_get_multiple_access_url();
+$session_field = new SessionField();
+$session_fields = $session_field->get_all();
+foreach ($session_fields as $session_field) {
+    if ($session_field['field_visible'] != '1') {
+        continue;        
+    }
+    $obj = new SessionFieldValue();
+    $result = $obj->get_values_by_handler_and_field_id($id_session, $session_field['id'], true);
+    
+    $session_value = null;
+    if ($result) {
+        $session_value = $result['field_value'];
+    }    
+    echo "<tr>";
+    echo "<td> {$session_field['field_display_text']} </td>";
+    echo "<td> $session_value </td>";
+    echo "</tr>";    
+}
+
+
+$multiple_url_is_on = api_is_multiple_url_enabled();
 
 if ($multiple_url_is_on) {
-    echo '<tr><td>';
-    echo 'URL';
+    echo '<tr><td>';   
+    echo 'URL';    
     echo '</td>';
     echo '<td>';
     $url_list = UrlManager::get_access_url_from_session($id_session);
-    foreach($url_list as $url_data) {
+    foreach ($url_list as $url_data) {
         echo $url_data['url'].'<br />';
-    }
+    }        
     echo '</td></tr>';
 }
 ?>
@@ -219,60 +187,26 @@ if ($session['nbr_courses'] == 0){
 	echo '<tr>
 			<td colspan="4">'.get_lang('NoCoursesForThisSession').'</td>
 		</tr>';
-} else {
-	// select the courses
-	$sql = "SELECT code,title,visual_code, nbr_users
-			FROM $tbl_course,$tbl_session_rel_course
-			WHERE course_code = code
-			AND	id_session='$id_session'
-			ORDER BY title";
-	$result=Database::query($sql);
-	$courses=Database::store_result($result);
+} else {    
+    $courses = SessionManager::get_course_list_by_session_id($id_session);	
 	foreach ($courses as $course) {
-		//select the number of users
-
-		$sql = " SELECT count(*) FROM $tbl_session_rel_user sru, $tbl_session_rel_course_rel_user srcru
-				WHERE srcru.id_user = sru.id_user AND srcru.id_session = sru.id_session AND srcru.course_code = '".Database::escape_string($course['code'])."'
-				AND sru.relation_type<>".SESSION_RELATION_TYPE_RRHH." AND srcru.id_session = '".intval($id_session)."'";
-
-		$rs = Database::query($sql);
-		$course['nbr_users'] = Database::result($rs,0,0);
-
-		// Get coachs of the courses in session
-
-		$sql = "SELECT user.lastname,user.firstname,user.username FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
-				WHERE session_rcru.id_user = user.user_id AND session_rcru.id_session = '".intval($id_session)."' AND session_rcru.course_code ='".Database::escape_string($course['code'])."' AND session_rcru.status=2";
-		$rs = Database::query($sql);
-
-		$coachs = array();
-		if (Database::num_rows($rs) > 0) {
-			while($info_coach = Database::fetch_array($rs)) {
-				$coachs[] = api_get_person_name($info_coach['firstname'], $info_coach['lastname']).' ('.$info_coach['username'].')';
-			}
-		} else {
-			$coach = get_lang('None');
-		}
-
-		if (count($coachs) > 0) {
-			$coach = implode('<br />',$coachs);
-		} else {
-			$coach = get_lang('None');
-		}
+        $count_users = SessionManager::get_count_users_in_course_session($course['code'], $id_session);
+        $coaches = SessionManager::get_session_course_coaches_to_string($course['code'], $id_session);
 
 		$orig_param = '&origin=resume_session';
 		//hide_course_breadcrumb the parameter has been added to hide the name of the course, that appeared in the default $interbreadcrumb
 		echo '
 		<tr>
 			<td>'.Display::url($course['title'].' ('.$course['visual_code'].')', api_get_path(WEB_COURSE_PATH).$course['code'].'/?id_session='.$id_session),'</td>
-			<td>'.$coach.'</td>
-			<td>'.$course['nbr_users'].'</td>
+			<td>'.$coaches.'</td>
+			<td>'.$count_users.'</td>
 			<td>
-                <a href="'.api_get_path(WEB_COURSE_PATH).$course['code'].'/?id_session='.$id_session.'">'.Display::return_icon('course_home.gif', get_lang('Course')).'</a>
+                <a href="'.api_get_path(WEB_COURSE_PATH).$course['code'].'/?id_session='.$id_session.'">'.Display::return_icon('course_home.gif', get_lang('Course')).'</a>   
                 <a href="session_course_user_list.php?id_session='.$id_session.'&course_code='.$course['code'].'">'.Display::return_icon('user.png', get_lang('Edit'), '', ICON_SIZE_SMALL).'</a>
-                <a href="'.api_get_path(WEB_CODE_PATH).'/user/user_import.php?action=import&cidReq='.$course['code'].'&id_session='.$id_session.'">'.Display::return_icon('import_csv.png', get_lang('ImportUsersToACourse'), null, ICON_SIZE_SMALL).'</a>
-				<a href="../tracking/courseLog.php?id_session='.$id_session.'&cidReq='.$course['code'].$orig_param.'&hide_course_breadcrumb=1">'.Display::return_icon('statistics.gif', get_lang('Tracking')).'</a>&nbsp;
+                <a href="'.api_get_path(WEB_CODE_PATH).'/user/user_import.php?action=import&cidReq='.$course['code'].'&id_session='.$id_session.'">'.Display::return_icon('import_csv.png', get_lang('ImportUsersToACourse'), null, ICON_SIZE_SMALL).'</a>   
+				<a href="../tracking/courseLog.php?id_session='.$id_session.'&cidReq='.$course['code'].$orig_param.'&hide_course_breadcrumb=1">'.Display::return_icon('statistics.gif', get_lang('Tracking')).'</a>&nbsp;                
 				<a href="session_course_edit.php?id_session='.$id_session.'&page=resume_session.php&course_code='.$course['code'].''.$orig_param.'">'.Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL).'</a>
-				<a href="'.api_get_self().'?id_session='.$id_session.'&action=delete&idChecked[]='.$course['code'].'" onclick="javascript:if(!confirm(\''.get_lang('ConfirmYourChoice').'\')) return false;">'.Display::return_icon('delete.png', get_lang('Delete')).'</a>
+				<a href="'.api_get_self().'?id_session='.$id_session.'&action=delete&course_code_to_delete='.$course['code'].'" onclick="javascript:if(!confirm(\''.get_lang('ConfirmYourChoice').'\')) return false;">'.Display::return_icon('delete.png', get_lang('Delete')).'</a>
 			</td>
 		</tr>';
 	}
@@ -285,7 +219,7 @@ if ($session['nbr_courses'] == 0){
 
 $url = Display::url(Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL), "add_users_to_session.php?page=resume_session.php&id_session=$id_session");
 $url .= Display::url(Display::return_icon('import_csv.png', get_lang('ImportUsers'), array(), ICON_SIZE_SMALL), "session_user_import.php?id_session=$id_session");
-echo Display::page_subheader(get_lang('UserList').$url);
+echo Display::page_subheader(get_lang('StudentList').$url);
 
 ?>
 
@@ -296,68 +230,150 @@ echo Display::page_subheader(get_lang('UserList').$url);
         <th>
             <?php echo get_lang('User'); ?>
         </th>
+        <th>
+            <?php echo get_lang('Status'); ?>
+        </th>
+        <th>
+            <?php echo get_lang('Information'); ?>
+        </th>
+        <th>
+            <?php echo get_lang('Destination'); ?>
+        </th>
+        <th>
+            <?php echo get_lang('MovedAt'); ?>
+        </th>
         <th>
             <?php echo get_lang('Actions'); ?>
         </th>
     </tr>
 <?php
-
-if ($session['nbr_users']==0) {
-	echo '<tr>
-			<td colspan="2">'.get_lang('NoUsersForThisSession').'</td>
-		</tr>';
-} else {
-	$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
-
-    if ($multiple_url_is_on) {
-        $sql = "SELECT u.user_id, lastname, firstname, username, access_url_id
-                FROM $tbl_user u
-                INNER JOIN $tbl_session_rel_user su
-                ON u.user_id = su.id_user AND su.relation_type<>".SESSION_RELATION_TYPE_RRHH."
-                LEFT OUTER JOIN $table_access_url_user uu ON (uu.user_id = u.user_id)
-                WHERE su.id_session = $id_session AND (access_url_id = $url_id OR access_url_id is null )
-                $order_clause";
-    } else {
-        $sql = "SELECT u.user_id, lastname, firstname, username
-                FROM $tbl_user u
-                INNER JOIN $tbl_session_rel_user su
-                ON u.user_id = su.id_user AND su.relation_type<>".SESSION_RELATION_TYPE_RRHH."
-                AND su.id_session = ".$id_session.$order_clause;
-    }
-
-	$result = Database::query($sql);
-	$users  = Database::store_result($result);
+/*
+if ($session['nbr_users'] == 0) {
+	
+} else {    
+*/
 	$orig_param = '&origin=resume_session&id_session='.$id_session; // change breadcrumb in destination page
-	foreach ($users as $user){
-        $user_link = '';
-        if (!empty($user['user_id'])) {
-            $user_link = '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_information.php?user_id='.intval($user['user_id']).'">'.api_htmlentities(api_get_person_name($user['firstname'], $user['lastname']),ENT_QUOTES,$charset).' ('.$user['username'].')</a>';
-        }
+    
+    $users = SessionManager::get_users_by_session($id_session, 0);        
+    //$reasons = SessionManager::get_session_change_user_reasons();
+    
+    if (!empty($users)) {
+        foreach ($users as $user) {
+            $user_info = api_get_user_info($user['user_id']);
+            //$link_class = 'class="item_disabled"';
+            $link_class = null;
+            $user_status_in_platform = Display::return_icon('error.png', get_lang('Inactive'));
+            $information = '';
+            $moved_date = '-';
+            
+            if ($user_info['active'] == 1 ) {
+                $user_status_in_platform = Display::return_icon('accept.png', get_lang('Active'));                
+                //$link_class = null;
+            } else {
+                $status_info = get_latest_event_by_user_and_type($user['user_id'], LOG_USER_DEACTIVATED);
+                //var_dump($status_info);
+                if (!empty($status_info)) {
+                    $information .= sprintf(get_lang('UserInactivedSinceX'), api_convert_and_format_date($status_info['default_date'], DATE_TIME_FORMAT_LONG));
+                    $moved_date = api_get_local_time($status_info['default_date']);
+                }
+                $user_info['complete_name_with_username'] = Display::tag('del', $user_info['complete_name_with_username']);
+            }
+            
+            $user_link = '';            
+            if (!empty($user['user_id'])) {
+                $user_link = '<a '.$link_class.' href="'.api_get_path(WEB_CODE_PATH).'admin/user_information.php?user_id='.intval($user['user_id']).'">'.$user_info['complete_name_with_username'].'</a>';
+            }
+            $origin = null;
+            $destination = null;
+            $row_style = null;
+
+            $course_link = '<a href="session_course_user.php?id_user='.$user['user_id'].'&id_session='.$id_session.'">'.Display::return_icon('course.gif', get_lang('BlockCoursesForThisUser')).'&nbsp;</a>';
+            $moved_link =  '<a href="change_user_session.php?user_id='.$user['user_id'].'&id_session='.$id_session.'">'.Display::return_icon('move.png', get_lang('ChangeUserSession')).'</a>&nbsp;';
+
+            //User in this session is subscribed but was moved to another session
+            if (isset($user['moved_to']) && !empty($user['moved_to']) || $user['moved_status'] == SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION) {
+                
+                $variation = SessionManager::get_session_change_user_reasons_variations_by_id($user['moved_status'], 'to');
+                //$information = $reasons[$user['moved_status']].$variation;
+                $information .= $variation;
+
+                $moved_date = isset($user['moved_at']) && $user['moved_at'] != '0000-00-00 00:00:00' ? api_get_local_time($user['moved_at']) : '-';                        
+                $session_info = SessionManager::fetch($user['moved_to']);
+
+                if ($user['moved_status'] != SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION) {
+                    $url = api_get_path(WEB_CODE_PATH).'admin/resume_session.php?id_session='.$id_session;                
+                    //$origin = Display::url($session['name'], $url);                
+
+                    if ($session_info) {
+                        $url = api_get_path(WEB_CODE_PATH).'admin/resume_session.php?id_session='.$session_info['id'];
+                        $destination = Display::url($session_info['name'], $url);
+                        //$destination = $destination;
+                    }            
+                }
+                $row_style = 'style = " background-color: #ddd;"';
+                $course_link=  Display::return_icon('course_na.gif', get_lang('BlockCoursesForThisUser')).'&nbsp;';
+                $moved_link =  Display::return_icon('move_na.png', get_lang('ChangeUserSession')).'&nbsp;';
+                $delete_link = Display::return_icon('delete_na.png', get_lang('Delete')).'&nbsp;';
+            } else {          
+                $session_origin_info = SessionManager::get_session_rel_user_by_moved_to($id_session, $user['user_id']);
+
+                if (!empty($session_origin_info)) {
+                   $moved_date = api_get_local_time($session_origin_info['moved_at']);
+                }            
+                $session_info = SessionManager::fetch($session_origin_info['id_session']);
+                
+                $variation = SessionManager::get_session_change_user_reasons_variations_by_id($session_origin_info['moved_status'], 'from');
+                
+                //$information = $reasons[$session_origin_info['moved_status']].$variation;
+                $information .= $variation;
+
+                if ($session_info) {
+                    $url = api_get_path(WEB_CODE_PATH).'admin/resume_session.php?id_session='.$session_info['id'];
+                    $origin = Display::url($session_info['name'], $url);
+
+                    $url = api_get_path(WEB_CODE_PATH).'admin/resume_session.php?id_session='.$id_session;                
+                    //$destination = Display::url($session['name'], $url);
+                    //$destination = ' / '.$destination;
+                }
+
+                $delete_link = '<a href="'.api_get_self().'?id_session='.$id_session.'&action=delete&user='.$user['user_id'].'" onclick="javascript:if(!confirm(\''.get_lang('ConfirmYourChoice').'\')) return false;">'.Display::return_icon('delete.png', get_lang('Delete')).'</a>';
 
-        $link_to_add_user_in_url = '';
+            }
 
-        if ($multiple_url_is_on) {
-            if ($user['access_url_id'] != $url_id) {
-                $user_link .= ' '.Display::return_icon('warning.png', get_lang('UserNotAddedInURL'), array(), ICON_SIZE_SMALL);
-                $add = Display::return_icon('add.png', get_lang('AddUsersToURL'), array(), ICON_SIZE_SMALL);
-                $link_to_add_user_in_url = '<a href="resume_session.php?action=add_user_to_url&id_session='.$id_session.'&user_id='.$user['user_id'].'">'.$add.'</a>';
+            $link_to_add_user_in_url = '';
+
+            if ($multiple_url_is_on) {
+                if ($user['access_url_id'] != $url_id) {            
+                    $user_link .= ' '.Display::return_icon('warning.png', get_lang('UserNotAddedInURL'), array(), ICON_SIZE_SMALL);
+                    $add = Display::return_icon('add.png', get_lang('AddUsersToURL'), array(), ICON_SIZE_SMALL);
+                    $link_to_add_user_in_url = '<a href="resume_session.php?action=add_user_to_url&id_session='.$id_session.'&user_id='.$user['user_id'].'">'.$add.'</a>';
+                }                
             }
+
+            echo '<tr '.$row_style.'>
+                    <td width="30%">
+                        '.$user_link.'
+                    </td>
+                    <td>'.$user_status_in_platform.'</td>
+                    <td>'.$information.'</td>
+                    <td>'.$origin.' '.$destination.'</td>
+                    <td>'.$moved_date.'</td>
+                    <td>
+                        <a href="../mySpace/myStudents.php?student='.$user['user_id'].''.$orig_param.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>&nbsp;
+                        '.$course_link.'
+                        '.$moved_link.'
+                        '.$delete_link.'
+                        '.$link_to_add_user_in_url.'
+                    </td>
+                    </tr>';
         }
-		echo '<tr>
-                <td width="90%">
-                    '.$user_link.'
-                </td>
-                <td>
-                    <a href="../mySpace/myStudents.php?student='.$user['user_id'].''.$orig_param.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>&nbsp;
-                    <a href="session_course_user.php?id_user='.$user['user_id'].'&id_session='.$id_session.'">'.Display::return_icon('course.gif', get_lang('BlockCoursesForThisUser')).'</a>&nbsp;
-                    <a href="'.api_get_self().'?id_session='.$id_session.'&action=delete&user='.$user['user_id'].'" onclick="javascript:if(!confirm(\''.get_lang('ConfirmYourChoice').'\')) return false;">'.Display::return_icon('delete.png', get_lang('Delete')).'</a>
-                    '.$link_to_add_user_in_url.'
-                </td>
-                </tr>';
-	}
-}
+    } else {
+        echo '<tr>
+			<td colspan="2">'.get_lang('NoUsersForThisSession').'</td>
+		</tr>';
+    }
+
 ?>
 </table>
 <?php
-// footer
-Display :: display_footer();
+Display :: display_footer();

+ 261 - 403
main/admin/session_add.php

@@ -7,441 +7,299 @@
 */
 
 // name of the language file that needs to be included
-$language_file='admin';
+$language_file = 'admin';
 
-$cidReset=true;
+$cidReset = true;
 
 // including the global Chamilo file
 require_once '../inc/global.inc.php';
 
-// including additional libraries
-require_once '../inc/lib/xajax/xajax.inc.php';
-
-$xajax = new xajax();
-//$xajax->debugOn();
-$xajax -> registerFunction ('search_coachs');
-
 // setting the section (for the tabs)
-$this_section=SECTION_PLATFORM_ADMIN;
+$this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script(true);
 
-$formSent=0;
-$errorMsg='';
-
-$interbreadcrumb[]=array('url' => 'index.php',       'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[]=array('url' => 'session_list.php','name' => get_lang('SessionList'));
-
-// Database Table Definitions
-$tbl_user		= Database::get_main_table(TABLE_MAIN_USER);
-
-function search_coachs($needle) {
-	global $tbl_user;
-
-	$xajax_response = new XajaxResponse();
-	$return = '';
-
-	if(!empty($needle)) {
-		// xajax send utf8 datas... datas in db can be non-utf8 datas
-		$charset = api_get_system_encoding();
-		$needle = api_convert_encoding($needle, $charset, 'utf-8');
-
-		$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-
-		// search users where username or firstname or lastname begins likes $needle
-		$sql = 'SELECT username, lastname, firstname FROM '.$tbl_user.' user
-				WHERE (username LIKE "'.$needle.'%"
-				OR firstname LIKE "'.$needle.'%"
-				OR lastname LIKE "'.$needle.'%")
-				AND status=1'.
-				$order_clause.
-				' LIMIT 10';
-
-		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 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 (username LIKE "'.$needle.'%"
-				OR firstname LIKE "'.$needle.'%"
-				OR lastname LIKE "'.$needle.'%")
-				AND status=1'.
-				$order_clause.
-				' LIMIT 10';
-
-			}
-		}
-
-		$rs = Database::query($sql);
-		while ($user = Database :: fetch_array($rs)) {
-			$return .= '<a href="javascript: void(0);" onclick="javascript: fill_coach_field(\''.$user['username'].'\')">'.api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')</a><br />';
-		}
-	}
-	$xajax_response -> addAssign('ajax_list_coachs','innerHTML', api_utf8_encode($return));
-	return $xajax_response;
-}
-$xajax -> processRequests();
+$interbreadcrumb[] = array('url' => 'index.php',       'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array('url' => 'session_list.php','name' => get_lang('SessionList'));
+
+$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/jquery.fcbkcomplete.js" type="text/javascript" language="javascript"></script>';
+$htmlHeadXtra[] = '<link href="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/style.css" rel="stylesheet" type="text/css" />';
+$htmlHeadXtra[] = api_get_jquery_libraries_js(array('jquery-ui-i18n'));
 
-$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
+$htmlHeadXtra = api_get_datetime_picker_js($htmlHeadXtra);
 
-$htmlHeadXtra[] = '
-<script type="text/javascript">
-function fill_coach_field (username) {
-	document.getElementById("coach_username").value = username;
-	document.getElementById("ajax_list_coachs").innerHTML = "";
+$id = null;
+$url_action = api_get_self();
+if (isset($_GET['id'])) {
+   $id = intval($_GET['id']);
+   $url_action = '?id='.$id;
 }
-</script>';
 
+$add_coach = null;
 
-if ($_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'];
-	//$nolimit               = $_POST['nolimit'];
-	$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'];
-
-    if (empty($end_limit) && empty($start_limit)) {
-        $nolimit = 1;
-    } else {
-    	$nolimit = null;
+if ($id) {
+    $tool_name = get_lang('EditSession');
+    SessionManager::protect_session_edit($id);
+    $session_info = api_get_session_info($id);
+    if (!empty($session_info['id_coach'])) {
+        $user_info = api_get_user_info($session_info['id_coach']);
+        $add_coach = '$("#coach_id").trigger("addItem", [{"title": "'.$user_info['complete_name'].'", "value": "'.$session_info['id_coach'].'"}]);';
     }
-	$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);
+    $button = get_lang('Update');
+} else {
+    $tool_name = get_lang('AddSession');
+    $button = get_lang('Add');
+}
 
-	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();
-	}
+$url = api_get_path(WEB_AJAX_PATH).'admin.ajax.php?1=1';
+
+$htmlHeadXtra[] ='
+<script>
+function check() {
+    $("#coach_id option:selected").each(function() {
+        var id = $(this).val();
+        var name = $(this).text();
+        if (id != "" ) {
+            $.ajax({
+                async: false,
+                url: "'.$url.'&a=user_exists",
+                data: "id="+id,
+                success: function(return_value) {
+                    if (return_value == 0 ) {
+                        alert("'.get_lang('UserDoesNotExist').'");
+                        //Deleting select option tag
+                        $("#coach_id").find("option").remove();
+
+                        $(".holder li").each(function () {
+                            if ($(this).attr("rel") == id) {
+                                $(this).remove();
+                            }
+                        });
+                    }
+                },
+            });
+        }
+    });
 }
 
-$nb_days_acess_before = 0;
-$nb_days_acess_after = 0;
+$(function() {
+
+    $("#coach_id").fcbkcomplete({
+        json_url: "'.$url.'&a=find_coaches",
+        maxitems: 1,
+        addontab: false,
+        input_min_size: 1,
+        cache: false,
+        complete_text:"'.get_lang('StartToType').'",
+        firstselected: false,
+        onselect: check,
+        filter_selected: true,
+        newel: true
+    });
+
+    '.$add_coach.'
+
+    $("#display_end_date").datetimepicker({
+        dateFormat: "yy-mm-dd",
+        hour: 9,
+        onSelect: function(selectedDateTime) {
+            var start = $(this).datetimepicker("getDate");
+
+            if (!$("#access_end_date").val()) {
+                $("#access_end_date").val(selectedDateTime);
+            }
 
-$thisYear=date('Y');
-$thisMonth=date('m');
-$thisDay=date('d');
+            if (!$("#coach_access_end_date").val()) {
+                $("#coach_access_end_date").val(selectedDateTime);
+            }
+        }
+    });
 
-$tool_name = get_lang('AddSession');
+    $("#display_start_date").datetimepicker({
+        dateFormat: "yy-mm-dd",
+        hour: 9,
+        onSelect: function(selectedDateTime) {
+            var start = $(this).datetimepicker("getDate");
 
-Display::display_header($tool_name);
+            if (!$("#access_start_date").val()) {
+                $("#access_start_date").val(selectedDateTime);
+            }
 
-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>';
+            if (!$("#coach_access_start_date").val()) {
+                $("#coach_access_start_date").val(selectedDateTime);
+            }
+        }
+    });
+
+    $("#access_start_date").datetimepicker({
+        dateFormat: "yy-mm-dd",
+        hour: 9,
+        onSelect: function(selectedDateTime) {
+            var start = $(this).datetimepicker("getDate");
+            //$("#access_end_date").val(selectedDateTime);
+        }
+    });
+
+    access_start_date_content = $("#access_end_date").val();
+
+    if (access_start_date_content.length > 0) {
+        $("#visibility_container").show();
+    } else {
+        $("#visibility_container").hide();
+    }
 
-?>
-<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">
+    $("#access_end_date").datetimepicker({
+        dateFormat: "yy-mm-dd",
+        onSelect: function(selectedDateTime) {
+            $("#visibility_container").show();
+        }
+    });
+
+    $("#access_end_date").on("change", function() {
+        content = $(this).val();
+        if (content.length > 0) {
+            $("#visibility_container").show();
+        } else {
+            $("#visibility_container").hide();
+        }
+
+    });
+
+    $("#coach_access_start_date").datetimepicker({
+        dateFormat: "yy-mm-dd",
+        hour: 9,
+        onSelect: function(selectedDateTime) {
+            var start = $(this).datetimepicker("getDate");
+            //$("#coach_access_end_date").val(selectedDateTime);
+        }
+    });
+
+    $("#coach_access_end_date").datetimepicker({
+        dateFormat: "yy-mm-dd"
+    });
+
+    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;
+            }
+        });
+    });
 
-<?php
+});
+</script>';
 
-$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'));
+$form = new FormValidator('add_session', 'post', $url_action);
+$form->addElement('header', $tool_name);
+
+//Name
+$form->addElement('text', 'name', get_lang('SessionName'), array('class' => 'span6'));
+$form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
+
+if (empty($id)) {
+    $form->addRule('name', get_lang('SessionNameAlreadyExists'), 'callback', 'check_session_name');
 } 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
+    $form->addElement('hidden', 'id', $id);
 }
-$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 }
-            }
-            ?>
-        </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">
+//Coaches
+//$coaches = SessionManager::get_user_list();
+$form->addElement('select', 'id_coach', get_lang('CoachName'), array(),array('id' => 'coach_id'));
+$form->addRule('id_coach', get_lang('ThisFieldIsRequired'), 'required');
 
-<?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
+$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">');
+
+//Dates
+$form->addElement('text', 'display_start_date', array(get_lang('SessionDisplayStartDate'), get_lang('SessionDisplayStartDateComment')), array('id' => 'display_start_date'));
+$form->addElement('text', 'display_end_date', array(get_lang('SessionDisplayEndDate'), get_lang('SessionDisplayEndDateComment')), array('id' => 'display_end_date'));
+$form->addRule(array('display_start_date', 'display_end_date'), get_lang('StartDateMustBeBeforeTheEndDate'), 'compare_datetime_text', '< allow_empty');
+
+$form->addElement('text', 'access_start_date', array(get_lang('SessionStartDate'), get_lang('SessionStartDateComment')), array('id' => 'access_start_date'));
+$form->addElement('text', 'access_end_date', array(get_lang('SessionEndDate'), get_lang('SessionEndDateComment')), array('id' => 'access_end_date'));
+$form->addRule(array('access_start_date', 'access_end_date'), get_lang('StartDateMustBeBeforeTheEndDate'), 'compare_datetime_text', '< allow_empty');
+
+//Visibility
+$visibility_list = array(SESSION_VISIBLE_READ_ONLY=>get_lang('SessionReadOnly'), SESSION_VISIBLE=>get_lang('SessionAccessible'), SESSION_INVISIBLE=>api_ucfirst(get_lang('SessionNotAccessible')));
+
+$form->addElement('html','<div id="visibility_container">');
+$form->addElement('select', 'visibility', get_lang('SessionVisibility'), $visibility_list, array('id' => 'visibility'));
+$form->addElement('html','</div>');
+
+$form->addElement('text', 'coach_access_start_date', array(get_lang('SessionCoachStartDate'), get_lang('SessionCoachStartDateComment')), array('id' => 'coach_access_start_date'));
+$form->addElement('text', 'coach_access_end_date', array(get_lang('SessionCoachEndDate'), get_lang('SessionCoachEndDateComment')), array('id' => 'coach_access_end_date'));
+$form->addRule(array('coach_access_start_date', 'coach_access_end_date'), get_lang('StartDateMustBeBeforeTheEndDate'), 'compare_datetime_text', '< allow_empty');
+
+//Session categories
+
+$categories = SessionManager::get_all_session_category();
+
+$select_categories = array();
+if (!empty($categories)) {
+    $select_categories = array('0' => get_lang('None'));
+    foreach ($categories as $row) {
+        $select_categories[$row['id']] = $row['name'];
+    }
 }
-?>
-    </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 if($item == $visibility_id) echo 'selected="selected"'; ?>><?php echo $item; ?></option>
-        <?php endforeach; ?>
-    </select>
-     </div>
-
-        </div>
-    </div>
-
-
- <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;
-	document.form.month_start.disabled = (select.checked) ? true : false;
-	document.form.year_start.disabled = (select.checked) ? true : false;
-
-	document.form.day_end.disabled = (select.checked) ? true : false;
-	document.form.month_end.disabled = (select.checked) ? true : false;
-	document.form.year_end.disabled = (select.checked) ? true : false;
-
-	document.form.session_visibility.disabled = (select.checked) ? true : false;
-	document.form.session_visibility.selectedIndex = 0;
-
-    document.form.start_limit.disabled = (select.checked) ? true : false;
-    document.form.start_limit.checked = false;
-    document.form.end_limit.disabled = (select.checked) ? true : false;
-    document.form.end_limit.checked = false;
-
-    var end_div = document.getElementById('end_date');
-    end_div.style.display = 'none';
-
-    var start_div = document.getElementById('start_date');
-    start_div.style.display = 'none';
+$form->addElement('select', 'session_category_id', get_lang('SessionCategory'), $select_categories, array('id' => 'session_category_id_name', 'class' => null));
+
+//Extra fields
+$extra_field = new ExtraField('session');
+$extra = $extra_field->add_elements($form, $id);
+
+
+$htmlHeadXtra[] ='
+<script>
+
+$(function() {
+    '.$extra['jquery_ready_content'].'
+});
+</script>';
+
+$form->addElement('html','</div>');
+
+$form->addElement('button', 'submit', $button);
+
+if (!empty($session_info)) {
+    $session_info['display_start_date'] = api_get_local_time($session_info['display_start_date'], null, null, true);
+    $session_info['display_end_date'] = api_get_local_time($session_info['display_end_date'], null, null, true);
+    $session_info['access_start_date'] = api_get_local_time($session_info['access_start_date'], null, null, true);
+    $session_info['access_end_date'] = api_get_local_time($session_info['access_end_date'], null, null, true);
+    $session_info['coach_access_start_date'] = api_get_local_time($session_info['coach_access_start_date'], null, null, true);
+    $session_info['coach_access_end_date'] = api_get_local_time($session_info['coach_access_end_date'], null, null, true);
+    $form->setDefaults($session_info);
 }
 
-function disable_endtime(select) {
-    var end_div = document.getElementById('end_date');
-    if (end_div.style.display == 'none')
-        end_div.style.display = 'block';
-     else
-        end_div.style.display = 'none';
+if ($form->validate()) {
+    $params = $form->getSubmitValues();
+    if (isset($params['id'])) {
+        SessionManager::update($params);
+        header('Location: resume_session.php?id_session='.$params['id']);
+		exit;
+    } else {
+        $session_id = SessionManager::add($params);
+        if ($session_id) {
+            // integer => no error on session creation
+            header('Location: add_courses_to_session.php?id_session='.$session_id.'&add=true&msg=');
+            exit;
+        }
+    }
 }
 
-function disable_starttime(select) {
-    var start_div = document.getElementById('start_date');
-    if (start_div.style.display == 'none')
-        start_div.style.display = 'block';
-     else
-        start_div.style.display = 'none';
+function check_session_name($name) {
+    $session = SessionManager::get_session_by_name($name);
+    return empty($session) ? true : false;
 }
-</script>
-<?php
+
+Display::display_header($tool_name);
+
+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();

+ 0 - 2
main/admin/session_category_add.php

@@ -13,8 +13,6 @@ $cidReset=true;
 // including the global Dokeos file
 require_once '../inc/global.inc.php';
 
-// including additional libraries
-require_once '../inc/lib/xajax/xajax.inc.php';
 $xajax = new xajax();
 $xajax -> registerFunction ('search_coachs');
 

+ 12 - 12
main/admin/session_course_edit.php

@@ -13,10 +13,10 @@ require_once '../inc/global.inc.php';
 $id_session = intval($_GET['id_session']);
 SessionManager::protect_session_edit($id_session);
 
-$course_code=trim(stripslashes($_GET['course_code']));
+$course_code = Database::escape_string($_GET['course_code']);
 
-$formSent=0;
-$errorMsg='';
+$formSent = 0;
+$errorMsg = '';
 
 // Database Table Definitions
 $tbl_user			= Database::get_main_table(TABLE_MAIN_USER);
@@ -26,14 +26,15 @@ $tbl_session_course	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
 $tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 
 $course_info=api_get_course_info($_REQUEST['course_code']);
-$tool_name=$course_info['name'];
+$tool_name = $course_info['name'];
 
 $interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
 $interbreadcrumb[]=array('url' => "session_list.php","name" => get_lang("SessionList"));
 $interbreadcrumb[]=array('url' => "resume_session.php?id_session=".$id_session,"name" => get_lang('SessionOverview'));
 $interbreadcrumb[]=array('url' => "session_course_list.php?id_session=$id_session","name" =>api_htmlentities($session_name,ENT_QUOTES,$charset));
 
-$result = Database::query("SELECT s.name, c.title FROM $tbl_session_course sc,$tbl_session s,$tbl_course c WHERE sc.id_session=s.id AND sc.course_code=c.code AND sc.id_session='$id_session' AND sc.course_code='".addslashes($course_code)."'");
+$result = Database::query("SELECT s.name, c.title FROM $tbl_session_course sc,$tbl_session s,$tbl_course c 
+                           WHERE sc.id_session=s.id AND sc.course_code=c.code AND sc.id_session='$id_session' AND sc.course_code='".$course_code."'");
 
 if (!list($session_name,$course_title)=Database::fetch_row($result)) {
 	header('Location: session_course_list.php?id_session='.$id_session);
@@ -68,7 +69,7 @@ if ($_POST['formSent']) {
 		$array_intersect = array_diff($coachs_course_session,$id_coachs);
 
 		foreach ($array_intersect as $nocoach_user_id) {
-			$rs2 = SessionManager::set_coach_to_course_session($nocoach_user_id, $id_session, $course_code,true);
+			$rs2 = SessionManager::set_coach_to_course_session($nocoach_user_id, $id_session, $course_code, true);
 		}
 
 		header('Location: '.Security::remove_XSS($_GET['page']).'?id_session='.$id_session);
@@ -96,19 +97,18 @@ if ($_configuration['multiple_access_urls']) {
     $sql="SELECT user_id,lastname,firstname,username FROM $tbl_user WHERE status='1'".$order_clause;
 }
 
-$result=Database::query($sql);
+$result = Database::query($sql);
 
-$coaches=Database::store_result($result);
+$coaches = Database::store_result($result);
 
 Display::display_header($tool_name);
 
-$tool_name=get_lang('ModifySessionCourse');
-api_display_tool_title($tool_name);
+$tool_name = get_lang('ModifySessionCourse');
+echo Display::page_header($tool_name);
 ?>
 <form method="post" action="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&page=<?php echo Security::remove_XSS($_GET['page']) ?>" style="margin:0px;">
 <input type="hidden" name="formSent" value="1">
-
-<table border="0" cellpadding="5" cellspacing="0" width="600px">
+<table>
 
 <?php
 if(!empty($errorMsg)) {

+ 3 - 1
main/admin/session_course_user.php

@@ -93,7 +93,8 @@ if ($_POST['formSent']) {
 			}
 		}
 	}
-	foreach($existingCourses as $existingCourse) {
+    
+	foreach ($existingCourses as $existingCourse) {
 		//$sql_insert_rel_course= "INSERT INTO $tbl_session_rel_course(id_session,course_code, id_coach) VALUES('$id_session','$enreg_course','$id_coach')";
 		if(!in_array($existingCourse['code'], $CourseList)){
 			$existingCourse = Database::escape_string($existingCourse['code']);
@@ -121,6 +122,7 @@ if (!empty($_GET['msg'])) {
 // the form header
 $session_info = SessionManager::fetch($id_session);
 $user_info = api_get_user_info($id_user);
+
 echo '<legend>'.$tool_name.': '.$session_info['name'].' - '.$user_info['complete_name'].'</legend>';
 
 $nosessionCourses = $sessionCourses = array();

+ 61 - 73
main/admin/session_course_user_list.php

@@ -11,24 +11,24 @@ $cidReset = true;
 
 require_once '../inc/global.inc.php';
 
-$tbl_user                           = Database::get_main_table(TABLE_MAIN_USER);
-$tbl_course                         = Database::get_main_table(TABLE_MAIN_COURSE);
-$tbl_session                        = Database::get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_rel_course             = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_session_rel_user               = Database::get_main_table(TABLE_MAIN_SESSION_USER);
-$tbl_session_rel_course_rel_user    = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
 $id_session = intval($_GET['id_session']);
+
 SessionManager::protect_session_edit($id_session);
 
-if (empty($id_session )) {
-    api_not_allowed();
+if (empty($id_session)) {
+    api_not_allowed(true);
+}
+
+$course_info = api_get_course_info($_GET['course_code']);
+
+if (empty($course_info)) {
+    api_not_allowed(true);
 }
 
-$course_code    = Database::escape_string(trim($_GET['course_code']));
+$course_code    = $course_info['code'];
 $page           = intval($_GET['page']);
 $action         = $_REQUEST['action'];
-$default_sort = api_sort_by_first_name() ? 'firstname':'lastname';
+$default_sort   = api_sort_by_first_name() ? 'firstname':'lastname';
 $sort           = in_array($_GET['sort'], array('lastname','firstname','username')) ? $_GET['sort'] : $default_sort;
 $idChecked      = (is_array($_GET['idChecked']) ? $_GET['idChecked'] : (is_array($_POST['idChecked']) ? $_POST['idChecked'] : null));
 
@@ -42,32 +42,19 @@ if (is_array($idChecked)) {
 	$idChecked = $my_temp;
 }
 
-$sql = "SELECT s.name, c.title  FROM $tbl_session_rel_course src
-		INNER JOIN $tbl_session s ON s.id = src.id_session
-		INNER JOIN $tbl_course c ON c.code = src.course_code
-		WHERE src.id_session='$id_session' AND src.course_code='".Database::escape_string($course_code)."' ";
-
-$result = Database::query($sql);
+$session_info = SessionManager::fetch($id_session);
+$courses = SessionManager::get_course_list_by_session_id($id_session);
 
-if (!list($session_name,$course_title)=Database::fetch_row($result)) {
+if (!isset($courses[$course_info['real_id']])) {
 	header('Location: session_course_list.php?id_session='.$id_session);
 	exit();
 }
 
-
-switch($action) {
+switch ($action) {
     case 'delete':
-        if (is_array($idChecked) && count($idChecked)>0 ) {
-            array_map('intval', $idChecked);
-            $idChecked = implode(',',$idChecked);
-        }
-        if (!empty($idChecked)) {
-            Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='".$course_code."' AND id_user IN($idChecked)");
-            $nbr_affected_rows = Database::affected_rows();
-            Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE id_session='$id_session' AND course_code='".$course_code."'");
-        }
+        SessionManager::unsubscribe_user_from_course_session($id_session, $idChecked, $course_code);        
         header('Location: '.api_get_self().'?id_session='.$id_session.'&course_code='.urlencode($course_code).'&sort='.$sort);
-        exit();
+        exit;
         break;
     case 'add':
         SessionManager::subscribe_users_to_session_course($idChecked, $id_session, $course_code);
@@ -81,29 +68,30 @@ $limit  = 20;
 $from   = $page * $limit;
 $is_western_name_order = api_is_western_name_order();
 
-//scru.status<>2  scru.course_code='".$course_code."'
+$Users = SessionManager::get_users_in_course_session($course_code, $id_session, $sort, $direction, $from, $limit);
+        
+/*
+
 $sql = "SELECT DISTINCT u.user_id,".($is_western_name_order ? 'u.firstname, u.lastname' : 'u.lastname, u.firstname').", u.username, scru.id_user as is_subscribed
-             FROM $tbl_session_rel_user s INNER JOIN $tbl_user u ON (u.user_id=s.id_user) LEFT JOIN $tbl_session_rel_course_rel_user scru ON (u.user_id=scru.id_user AND  scru.course_code = '".$course_code."' )
-             WHERE s.id_session='$id_session'
+             FROM $tbl_session_rel_user s INNER JOIN $tbl_user u ON (u.user_id=s.id_user) 
+                    LEFT JOIN $tbl_session_rel_course_rel_user scru ON (u.user_id=scru.id_user AND  scru.course_code = '".$course_code."' )
+             WHERE s.id_session='$id_session' 
              ORDER BY $sort $direction LIMIT $from,".($limit+1);
-
+*/
 if ($direction == 'desc') {
     $direction = 'asc';
 } else {
     $direction = 'desc';
 }
 
-$result = Database::query($sql);
-$Users  = Database::store_result($result);
-
 $nbr_results = sizeof($Users);
 
-$tool_name = get_lang('Session').': '.$session_name.' - '.get_lang('Course').': '.$course_title;
+$tool_name = get_lang('Session').': '.$session_info['name'].' - '.get_lang('Course').': '.$course_info['title'];
 
 $interbreadcrumb[] = array("url" => "index.php","name" => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array("url" => "session_list.php","name" => get_lang('SessionList'));
 $interbreadcrumb[] = array('url' => "resume_session.php?id_session=".$id_session,"name" => get_lang('SessionOverview'));
-//$interbreadcrumb[]=array("url" => "session_course_list.php?id_session=$id_session","name" => get_lang('ListOfCoursesOfSession')." &quot;".api_htmlentities($session_name,ENT_QUOTES,$charset)."&quot;");
+
 
 Display::display_header($tool_name);
 
@@ -122,7 +110,7 @@ if($page) {
 ?>
 |
 <?php
-if($nbr_results > $limit) {
+if ($nbr_results > $limit) {
 ?>
 <a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>"><?php echo get_lang('Next');?></a>
 <?php
@@ -149,38 +137,38 @@ if($nbr_results > $limit) {
 
 <?php
 $i=0;
-
-foreach ($Users as $key=>$enreg) {
-	if ($key == $limit) {
-		break;
-	}
-    ?>
-
-    <tr class="<?php echo $i?'row_odd':'row_even'; ?>">
-        <td><input type="checkbox" name="idChecked[]" value="<?php echo $enreg['user_id']; ?>"></td>
-        <?php if ($is_western_name_order) { ?>
-        <td><?php echo api_htmlentities($enreg['firstname'],ENT_QUOTES,$charset); ?></td>
-        <td><?php echo api_htmlentities($enreg['lastname'],ENT_QUOTES,$charset); ?></td>
-        <?php } else { ?>
-        <td><?php echo api_htmlentities($enreg['lastname'],ENT_QUOTES,$charset); ?></td>
-        <td><?php echo api_htmlentities($enreg['firstname'],ENT_QUOTES,$charset); ?></td>
-        <?php } ?>
-        <td><?php echo api_htmlentities($enreg['username'],ENT_QUOTES,$charset); ?></td>
-        <td>
-        <?php if ($enreg['is_subscribed']) { ?>
-            <a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=<?php echo $sort; ?>&action=delete&idChecked[]=<?php echo $enreg['user_id']; ?>" onclick="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;">
-                <?php Display::display_icon('delete.png', get_lang('Delete')); ?>
-            </a>
-        <?php } else  { ?>
-            <a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=<?php echo $sort; ?>&action=add&idChecked[]=<?php echo $enreg['user_id']; ?>" onclick="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;">
-                <?php Display::display_icon('add.png', get_lang('Add'), array(), ICON_SIZE_SMALL); ?>
-            </a>
-        <?php }  ?>
-
-        </td>
-    </tr>
-    <?php
-        $i=$i ? 0 : 1;
+if (!empty($Users)) {
+    foreach ($Users as $key=>$enreg) {
+        if ($key == $limit) {
+            break;
+        }
+        ?>
+        <tr class="<?php echo $i?'row_odd':'row_even'; ?>">
+            <td><input type="checkbox" name="idChecked[]" value="<?php echo $enreg['user_id']; ?>"></td>
+            <?php if ($is_western_name_order) { ?>
+            <td><?php echo api_htmlentities($enreg['firstname'],ENT_QUOTES,$charset); ?></td>
+            <td><?php echo api_htmlentities($enreg['lastname'],ENT_QUOTES,$charset); ?></td>
+            <?php } else { ?>
+            <td><?php echo api_htmlentities($enreg['lastname'],ENT_QUOTES,$charset); ?></td>
+            <td><?php echo api_htmlentities($enreg['firstname'],ENT_QUOTES,$charset); ?></td>
+            <?php } ?>
+            <td><?php echo api_htmlentities($enreg['username'],ENT_QUOTES,$charset); ?></td>
+            <td>
+            <?php if ($enreg['is_subscribed']) { ?>
+                <a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=<?php echo $sort; ?>&action=delete&idChecked[]=<?php echo $enreg['user_id']; ?>" onclick="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;">
+                    <?php Display::display_icon('delete.png', get_lang('Delete')); ?>
+                </a>
+            <?php } else  { ?>
+                <a href="<?php echo api_get_self(); ?>?id_session=<?php echo $id_session; ?>&course_code=<?php echo urlencode($course_code); ?>&sort=<?php echo $sort; ?>&action=add&idChecked[]=<?php echo $enreg['user_id']; ?>" onclick="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;">
+                    <?php Display::display_icon('add.png', get_lang('Add'), array(), ICON_SIZE_SMALL); ?>
+                </a>
+            <?php }  ?>
+
+            </td>
+        </tr>
+        <?php
+            $i=$i ? 0 : 1;
+    }
 }
 unset($Users);
 ?>
@@ -216,4 +204,4 @@ unset($Users);
 <button class="save" type="submit"> <?php echo get_lang('Ok'); ?></button>
 </form>
 <?php
-Display::display_footer();
+Display::display_footer();

+ 0 - 404
main/admin/session_edit.php

@@ -1,404 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-/**
- * Sessions edition script
- * @package chamilo.admin
- */
-/**
- * Code
- */
-
-// name of the language file that needs to be included
-$language_file ='admin';
-$cidReset = true;
-require_once '../inc/global.inc.php';
-
-// setting the section (for the tabs)
-$this_section = SECTION_PLATFORM_ADMIN;
-
-
-
-$formSent = 0;
-
-// Database Table Definitions
-$tbl_user		= Database::get_main_table(TABLE_MAIN_USER);
-$tbl_session	= Database::get_main_table(TABLE_MAIN_SESSION);
-
-$id = intval($_GET['id']);
-
-SessionManager::protect_session_edit($id);
-
-$sql = "SELECT name,date_start,date_end,id_coach, session_admin_id, nb_days_access_before_beginning, nb_days_access_after_end, session_category_id, visibility
-        FROM $tbl_session WHERE id = $id";
-$result = Database::query($sql);
-
-if (!$infos = Database::fetch_array($result)) {
-    header('Location: session_list.php');
-    exit();
-}
-
-$id_coach   = $infos['id_coach'];
-
-
-
-$tool_name = get_lang('EditSession');
-
-$interbreadcrumb[] = array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array('url' => "session_list.php","name" => get_lang('SessionList'));
-$interbreadcrumb[] = array('url' => "resume_session.php?id_session=".$id,"name" => get_lang('SessionOverview'));
-
-list($year_start,$month_start,$day_start)   = explode('-',$infos['date_start']);
-list($year_end,$month_end,$day_end)         = explode('-',$infos['date_end']);
-
-$end_year_disabled = $end_month_disabled = $end_day_disabled = '';
-
-if ($_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_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'];
-
-    $end_limit              = $_POST['end_limit'];
-    $start_limit            = $_POST['start_limit'];
-
-    if (empty($end_limit) && empty($start_limit)) {
-        $nolimit = 1;
-    } else {
-        $nolimit = null;
-    }
-
-	$return = SessionManager::edit_session($id,$name,$year_start,$month_start,$day_start,$year_end,$month_end,$day_end,$nb_days_acess_before,$nb_days_acess_after,$nolimit, $id_coach, $id_session_category,$id_visibility,$start_limit,$end_limit);
-	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 ($_configuration['multiple_access_urls']) {
-	$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);
-
-// display the tool title
-// api_display_tool_title($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>
-
-    <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>
-
-<script type="text/javascript">
-
-<?php if($year_start=="0000") echo "setDisable(document.form.nolimit);\r\n"; ?>
-
-function setDisable(select){
-
-	document.form.day_start.disabled = (select.checked) ? true : false;
-	document.form.month_start.disabled = (select.checked) ? true : false;
-	document.form.year_start.disabled = (select.checked) ? true : false;
-
-	document.form.day_end.disabled = (select.checked) ? true : false;
-	document.form.month_end.disabled = (select.checked) ? true : false;
-	document.form.year_end.disabled = (select.checked) ? true : false;
-
-	document.form.session_visibility.disabled = (select.checked) ? true : false;
-	document.form.session_visibility.selectedIndex = 0;
-
-    document.form.start_limit.disabled = (select.checked) ? true : false;
-    document.form.start_limit.checked = false;
-    document.form.end_limit.disabled = (select.checked) ? true : false;
-    document.form.end_limit.checked = false;
-
-    var end_div = document.getElementById('end_date');
-    end_div.style.display = 'none';
-
-    var start_div = document.getElementById('start_date');
-    start_div.style.display = 'none';
-
-
-}
-
-function disable_endtime(select) {
-    var end_div = document.getElementById('end_date');
-    if (end_div.style.display == 'none')
-        end_div.style.display = 'block';
-     else
-        end_div.style.display = 'none';
-}
-
-function disable_starttime(select) {
-    var start_div = document.getElementById('start_date');
-    if (start_div.style.display == 'none')
-        start_div.style.display = 'block';
-     else
-        start_div.style.display = 'none';
-}
-
-</script>
-<?php
-Display::display_footer();

+ 185 - 206
main/admin/session_export.php

@@ -1,249 +1,228 @@
 <?php
+
 /**
-*	@package chamilo.admin
-*/
+ * 	@package chamilo.admin
+ */
 // name of the language file that needs to be included
 $language_file = 'admin';
 
 $cidReset = true;
 
-include '../inc/global.inc.php';
+require_once '../inc/global.inc.php';
 
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script(true);
-include api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 
 $session_id = intval($_GET['session_id']);
 $formSent = 0;
 $errorMsg = '';
 
 // Database Table Definitions
-$tbl_user					= Database::get_main_table(TABLE_MAIN_USER);
-$tbl_course      			= Database::get_main_table(TABLE_MAIN_COURSE);
-$tbl_course_user 			= Database::get_main_table(TABLE_MAIN_COURSE_USER);
-$tbl_session      			= Database::get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_user      		= Database::get_main_table(TABLE_MAIN_SESSION_USER);
-$tbl_session_course      	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_session_course_user 	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
+$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
+$tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
+$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
+$tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 
 $archivePath = api_get_path(SYS_ARCHIVE_PATH);
-$archiveURL  = api_get_path(WEB_CODE_PATH).'course_info/download.php?archive=';
+$archiveURL = api_get_path(WEB_CODE_PATH) . 'course_info/download.php?archive=';
 
-$tool_name   = get_lang('ExportSessionListXMLCSV');
+$tool_name = get_lang('ExportSessionListXMLCSV');
 
 global $_configuration;
 
-
-$interbreadcrumb[] = array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array('url' => 'index.php', "name" => get_lang('PlatformAdmin'));
 
 set_time_limit(0);
 
 if ($_POST['formSent']) {
-	$formSent = $_POST['formSent'];
-	$file_type = ($_POST['file_type'] == 'csv')?'csv':'xml';
-	$session_id = $_POST['session_id'];
-	if (empty($session_id)) {
-		$sql = "SELECT id,name,id_coach,username,date_start,date_end,visibility,session_category_id FROM $tbl_session INNER JOIN $tbl_user
-					ON $tbl_user.user_id = $tbl_session.id_coach ORDER BY id";
-
-		
-		if ($_configuration['multiple_access_urls']) {
-			$tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1){
-			$sql = "SELECT id, name,id_coach,username,date_start,date_end,visibility,session_category_id FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url
+    $formSent = $_POST['formSent'];
+    $file_type = ($_POST['file_type'] == 'csv') ? 'csv' : 'xml';
+    $session_id = $_POST['session_id'];
+    if (empty($session_id)) {
+        $sql = "SELECT id,name,id_coach,username,access_start_date,access_end_date,visibility,session_category_id 
+                FROM $tbl_session INNER JOIN $tbl_user
+				ON $tbl_user.user_id = $tbl_session.id_coach ORDER BY id";
+        if ($_configuration['multiple_access_urls']) {
+            $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+            $access_url_id = api_get_current_access_url_id();
+            if ($access_url_id != -1) {
+                $sql = "SELECT id, name,id_coach,username,access_start_date,access_end_date,visibility,session_category_id 
+                FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url
 				ON (s.id= session_rel_url.session_id) INNER JOIN $tbl_user u ON (u.user_id = s.id_coach)
 				WHERE access_url_id = $access_url_id
 				ORDER BY id";
-
-			}
-		}
-		$result=Database::query($sql);
-	}
-	else
-	{
-		$sql = "SELECT id,name,username,date_start,date_end,visibility,session_category_id
+            }
+        }
+        $result = Database::query($sql);
+    } else {
+        $sql = "SELECT id,name,username,access_start_date,access_end_date,visibility,session_category_id
 				FROM $tbl_session
 				INNER JOIN $tbl_user
 					ON $tbl_user.user_id = $tbl_session.id_coach
 				WHERE id='$session_id'";
 
-		$result = Database::query($sql);
-
-	}
-
-	if(Database::num_rows($result))
-	{
-		if(!file_exists($archivePath))
-		{
-			mkdir($archivePath, api_get_permissions_for_new_directories(), true);
-		}
-
-		if(!file_exists($archivePath.'index.html'))
-		{
-			$fp=fopen($archivePath.'index.html','w');
-
-			fputs($fp,'<html><head></head><body></body></html>');
-
-			fclose($fp);
-		}
-
-		$archiveFile='export_sessions_'.$session_id.'_'.date('Y-m-d_H-i-s').'.'.$file_type;
-
-		while( file_exists($archivePath.$archiveFile))
-		{
-			$archiveFile='export_users_'.$session_id.'_'.date('Y-m-d_H-i-s').'_'.uniqid('').'.'.$file_type;
-		}
-		$fp=fopen($archivePath.$archiveFile,'w');
-
-		if($file_type == 'csv')
-		{
-			$cvs = true;
-			fputs($fp,"SessionName;Coach;DateStart;DateEnd;Visibility;SessionCategory;Users;Courses;\n");
-		}
-		else
-		{
-			$cvs = false;
-			fputs($fp, "<?xml version=\"1.0\" encoding=\"".api_get_system_encoding()."\"?>\n<Sessions>\n");
-		}
-
-		while($row=Database::fetch_array($result))
-		{
-			$add = '';
-			$row['name'] = str_replace(';',',',$row['name']);
-			$row['username'] = str_replace(';',',',$row['username']);
-			$row['date_start'] = str_replace(';',',',$row['date_start']);
-			$row['date_end'] = str_replace(';',',',$row['date_end']);
-			$row['visibility'] = str_replace(';',',',$row['visibility']);
-			$row['session_category'] = str_replace(';',',',$row['session_category_id']);
-			if($cvs){
-				$add.= $row['name'].';'.$row['username'].';'.$row['date_start'].';'.$row['date_end'].';'.$row['visibility'].';'.$row['session_category'].';';
-			}
-			else {
-				$add = "\t<Session>\n"
-						 ."\t\t<SessionName>$row[name]</SessionName>\n"
-						 ."\t\t<Coach>$row[username]</Coach>\n"
-						 ."\t\t<DateStart>$row[date_start]</DateStart>\n"
-						 ."\t\t<DateEnd>$row[date_end]</DateEnd>\n"
-						 ."\t\t<Visibility>$row[visibility]</Visibility>\n"
-						 ."\t\t<SessionCategory>$row[session_category]</SessionCategory>\n";
-			}
-
-			//users
-			$sql = "SELECT DISTINCT $tbl_user.username FROM $tbl_user
+        $result = Database::query($sql);
+    }
+
+    if (Database::num_rows($result)) {
+        if (!file_exists($archivePath)) {
+            mkdir($archivePath, api_get_permissions_for_new_directories(), true);
+        }
+
+        if (!file_exists($archivePath . 'index.html')) {
+            $fp = fopen($archivePath . 'index.html', 'w');
+
+            fputs($fp, '<html><head></head><body></body></html>');
+
+            fclose($fp);
+        }
+
+        $archiveFile = 'export_sessions_' . $session_id . '_' . date('Y-m-d_H-i-s') . '.' . $file_type;
+
+        while (file_exists($archivePath . $archiveFile)) {
+            $archiveFile = 'export_users_' . $session_id . '_' . date('Y-m-d_H-i-s') . '_' . uniqid('') . '.' . $file_type;
+        }
+        $fp = fopen($archivePath . $archiveFile, 'w');
+
+        if ($file_type == 'csv') {
+            $cvs = true;
+            fputs($fp, "SessionName;Coach;DateStart;DateEnd;Visibility;SessionCategory;Users;Courses;\n");
+        } else {
+            $cvs = false;
+            fputs($fp, "<?xml version=\"1.0\" encoding=\"" . api_get_system_encoding() . "\"?>\n<Sessions>\n");
+        }
+
+        while ($row = Database::fetch_array($result)) {
+            $add = '';
+            $row['name'] = str_replace(';', ',', $row['name']);
+            $row['username'] = str_replace(';', ',', $row['username']);
+            $row['access_start_date'] = str_replace(';', ',', api_get_local_time($row['access_start_date'], null, null, true));
+            $row['access_end_date'] = str_replace(';', ',', api_get_local_time($row['access_end_date'], null, null, true));
+            $row['visibility'] = str_replace(';', ',', $row['visibility']);
+            $row['session_category'] = str_replace(';', ',', $row['session_category_id']);
+            if ($cvs) {
+                $add.= $row['name'] . ';' . $row['username'] . ';' . $row['access_start_date'] . ';' . $row['access_end_date'] . ';' . $row['visibility'] . ';' . $row['session_category'] . ';';
+            } else {
+                $add = "\t<Session>\n"
+                        . "\t\t<SessionName>$row[name]</SessionName>\n"
+                        . "\t\t<Coach>$row[username]</Coach>\n"
+                        . "\t\t<DateStart>$row[access_start_date]</DateStart>\n"
+                        . "\t\t<DateEnd>$row[access_end_date]</DateEnd>\n"
+                        . "\t\t<Visibility>$row[visibility]</Visibility>\n"
+                        . "\t\t<SessionCategory>$row[session_category]</SessionCategory>\n";
+            }
+
+            //users
+            $sql = "SELECT DISTINCT $tbl_user.username FROM $tbl_user
 					INNER JOIN $tbl_session_user
-						ON $tbl_user.user_id = $tbl_session_user.id_user AND $tbl_session_user.relation_type<>".SESSION_RELATION_TYPE_RRHH."
-						AND $tbl_session_user.id_session = '".$row['id']."'";
-
-			$rsUsers = Database::query($sql);
-			$users = '';
-			while($rowUsers = Database::fetch_array($rsUsers)){
-				if($cvs){
-					$users .= str_replace(';',',',$rowUsers['username']).'|';
-				}
-				else {
-					$users .= "\t\t<User>$rowUsers[username]</User>\n";
-				}
-			}
-			if(!empty($users) && $cvs)
-				$users = api_substr($users , 0, api_strlen($users)-1);
-
-			if($cvs)
-				$users .= ';';
-
-			$add .= $users;
-
-			//courses
-			$sql = "SELECT DISTINCT $tbl_course.code
+						ON $tbl_user.user_id = $tbl_session_user.id_user AND $tbl_session_user.relation_type<>" . SESSION_RELATION_TYPE_RRHH . "
+						AND $tbl_session_user.id_session = '" . $row['id'] . "'";
+
+            $rsUsers = Database::query($sql);
+            $users = '';
+            while ($rowUsers = Database::fetch_array($rsUsers)) {
+                if ($cvs) {
+                    $users .= str_replace(';', ',', $rowUsers['username']) . '|';
+                } else {
+                    $users .= "\t\t<User>$rowUsers[username]</User>\n";
+                }
+            }
+            if (!empty($users) && $cvs)
+                $users = api_substr($users, 0, api_strlen($users) - 1);
+
+            if ($cvs)
+                $users .= ';';
+
+            $add .= $users;
+
+            //courses
+            $sql = "SELECT DISTINCT $tbl_course.code
 					FROM $tbl_course
 					INNER JOIN $tbl_session_course_user
 						ON $tbl_course.code = $tbl_session_course_user.course_code
-						AND $tbl_session_course_user.id_session = '".$row['id']."'";
+						AND $tbl_session_course_user.id_session = '" . $row['id'] . "'";
 
-			$rsCourses = Database::query($sql);
+            $rsCourses = Database::query($sql);
 
-			$courses = '';
-			while($rowCourses = Database::fetch_array($rsCourses)){
+            $courses = '';
+            while ($rowCourses = Database::fetch_array($rsCourses)) {
 
-				// get coachs from a course
-				$sql = "SELECT u.username
+                // get coachs from a course
+                $sql = "SELECT u.username
 					FROM $tbl_session_course_user scu
 					INNER JOIN $tbl_user u ON u.user_id = scu.id_user
 					WHERE scu.course_code = '{$rowCourses['code']}'
-						AND scu.id_session = '".$row['id']."' AND scu.status = 2 ";
-
-				$rs_coachs = Database::query($sql);
-				$coachs = array();
-				while ($row_coachs = Database::fetch_array($rs_coachs)) {
-					$coachs[] = $row_coachs['username'];
-				}
-
-				$coachs = implode(",",$coachs);
-
-				if($cvs){
-					$courses .= str_replace(';',',',$rowCourses['code']);
-					$courses .= '['.str_replace(';',',',$coachs).'][';
-				}
-				else {
-					$courses .= "\t\t<Course>\n";
-					$courses .= "\t\t\t<CourseCode>$rowCourses[code]</CourseCode>\n";
-					$courses .= "\t\t\t<Coach>$coachs</Coach>\n";
-				}
-
-				// rel user courses
-				$sql = "SELECT DISTINCT u.username
+						AND scu.id_session = '" . $row['id'] . "' AND scu.status = 2 ";
+
+                $rs_coachs = Database::query($sql);
+                $coachs = array();
+                while ($row_coachs = Database::fetch_array($rs_coachs)) {
+                    $coachs[] = $row_coachs['username'];
+                }
+
+                $coachs = implode(",", $coachs);
+                if ($cvs) {
+                    $courses .= str_replace(';', ',', $rowCourses['code']);
+                    $courses .= '[' . str_replace(';', ',', $coachs) . '][';
+                } else {
+                    $courses .= "\t\t<Course>\n";
+                    $courses .= "\t\t\t<CourseCode>$rowCourses[code]</CourseCode>\n";
+                    $courses .= "\t\t\t<Coach>$coachs</Coach>\n";
+                }
+
+                // rel user courses
+                $sql = "SELECT DISTINCT u.username
 						FROM $tbl_session_course_user scu
-						INNER JOIN $tbl_session_user su ON scu.id_user = su.id_user AND scu.id_session = su.id_session AND su.relation_type<>".SESSION_RELATION_TYPE_RRHH."
+						INNER JOIN $tbl_session_user su ON scu.id_user = su.id_user AND scu.id_session = su.id_session AND su.relation_type<>" . SESSION_RELATION_TYPE_RRHH . "
 						INNER JOIN $tbl_user u
 						ON scu.id_user = u.user_id
-						AND scu.course_code='".$rowCourses['code']."'
-						AND scu.id_session='".$row['id']."'";
-
-				$rsUsersCourse = Database::query($sql);
-				$userscourse = '';
-				while($rowUsersCourse = Database::fetch_array($rsUsersCourse)){
-
-					if($cvs){
-						$userscourse .= str_replace(';',',',$rowUsersCourse['username']).',';
-					}
-					else {
-						$courses .= "\t\t\t<User>$rowUsersCourse[username]</User>\n";
-					}
-				}
-				if($cvs){
-					if(!empty($userscourse))
-						$userscourse = api_substr($userscourse , 0, api_strlen($userscourse)-1);
-
-					$courses .= $userscourse.']|';
-				}
-				else {
-					$courses .= "\t\t</Course>\n";
-				}
-			}
-
-			if(!empty($courses) && $cvs)
-				$courses = api_substr($courses , 0, api_strlen($courses)-1);
-			$add .= $courses;
-
-			if($cvs) {
-				$breakline = api_is_windows_os()?"\r\n":"\n";
-				$add .= ";$breakline";
-			} else {
-				$add .= "\t</Session>\n";
-			}
-
-			fputs($fp, $add);
-		}
-
-		if(!$cvs)
-			fputs($fp,"</Sessions>\n");
-		fclose($fp);
-
-		$errorMsg=get_lang('UserListHasBeenExported').'<br/><a class="btn" href="'.$archiveURL.$archiveFile.'">'.get_lang('ClickHereToDownloadTheFile').'</a>';
-	}
+						AND scu.course_code='" . $rowCourses['code'] . "'
+						AND scu.id_session='" . $row['id'] . "'";
+
+                $rsUsersCourse = Database::query($sql);
+                $userscourse = '';
+                while ($rowUsersCourse = Database::fetch_array($rsUsersCourse)) {
+
+                    if ($cvs) {
+                        $userscourse .= str_replace(';', ',', $rowUsersCourse['username']) . ',';
+                    } else {
+                        $courses .= "\t\t\t<User>$rowUsersCourse[username]</User>\n";
+                    }
+                }
+                if ($cvs) {
+                    if (!empty($userscourse))
+                        $userscourse = api_substr($userscourse, 0, api_strlen($userscourse) - 1);
+
+                    $courses .= $userscourse . ']|';
+                }
+                else {
+                    $courses .= "\t\t</Course>\n";
+                }
+            }
+
+            if (!empty($courses) && $cvs)
+                $courses = api_substr($courses, 0, api_strlen($courses) - 1);
+            $add .= $courses;
+
+            if ($cvs) {
+                $breakline = api_is_windows_os() ? "\r\n" : "\n";
+                $add .= ";$breakline";
+            } else {
+                $add .= "\t</Session>\n";
+            }
+
+            fputs($fp, $add);
+        }
+
+        if (!$cvs)
+            fputs($fp, "</Sessions>\n");
+        fclose($fp);
+
+        $errorMsg = get_lang('UserListHasBeenExported') . '<br/><a class="btn" href="' . $archiveURL . $archiveFile . '">' . get_lang('ClickHereToDownloadTheFile') . '</a>';
+    }
 }
 
 // display the header
@@ -253,29 +232,29 @@ Display::display_header($tool_name);
 $sql = "SELECT id, name FROM $tbl_session ORDER BY name";
 
 if ($_configuration['multiple_access_urls']) {
-	$tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-	$access_url_id = api_get_current_access_url_id();
-	if ($access_url_id != -1){
-	$sql = "SELECT id, name FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url
+    $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+    $access_url_id = api_get_current_access_url_id();
+    if ($access_url_id != -1) {
+        $sql = "SELECT id, name FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url
 		ON (s.id= session_rel_url.session_id)
 		WHERE access_url_id = $access_url_id
 		ORDER BY name";
-	}
+    }
 }
 $result = Database::query($sql);
 $Sessions = Database::store_result($result);
 
 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="../admin/index.php">' . Display::return_icon('back.png', get_lang('BackTo') . ' ' . get_lang('PlatformAdmin'), '', ICON_SIZE_MEDIUM) . '</a>';
 echo '</div>';
 
 if (!empty($errorMsg)) {
-	Display::display_normal_message($errorMsg, false); //main API
+    Display::display_normal_message($errorMsg, false); //main API
 }
 
 $form = new FormValidator('session_export', 'post', api_get_self());
 $form->addElement('hidden', 'formSent', 1);
-$form->addElement('radio', 'file_type', get_lang('OutputFileType'), 'CSV' , 'csv', null, array('id' => 'file_type_csv'));
+$form->addElement('radio', 'file_type', get_lang('OutputFileType'), 'CSV', 'csv', null, array('id' => 'file_type_csv'));
 $form->addElement('radio', 'file_type', null, 'XML', 'xml', null, array('id' => 'file_type_xml'));
 
 $options = array();
@@ -284,7 +263,7 @@ foreach ($Sessions as $enreg) {
     $options[$enreg['id']] = $enreg['name'];
 }
 
-$form->addElement('select', 'session_id', get_lang('WhichSessionToExport'),  $options);
+$form->addElement('select', 'session_id', get_lang('WhichSessionToExport'), $options);
 $form->addElement('button', 'submit', get_lang('ExportSession'));
 
 $defaults = array();

+ 200 - 0
main/admin/session_fields.php

@@ -0,0 +1,200 @@
+<?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['name']), 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();

+ 71 - 105
main/admin/session_import.php

@@ -8,24 +8,18 @@
 $language_file = array('admin', 'registration');
 $cidReset = true;
 
-require '../inc/global.inc.php';
+require_once '../inc/global.inc.php';
 
 $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script(true);
 
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
-
 $form_sent = 0;
-$error_message = ''; // Avoid conflict with the global variable $error_msg (array type) in add_course.conf.php.
+$error_message = '';
 if (isset($_GET['action']) && $_GET['action'] == 'show_message') {
     $error_message = Security::remove_XSS($_GET['message']);
 }
 
-
 $tbl_user                   = Database::get_main_table(TABLE_MAIN_USER);
-$tbl_course                 = Database::get_main_table(TABLE_MAIN_COURSE);
-$tbl_course_user            = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 $tbl_session                = Database::get_main_table(TABLE_MAIN_SESSION);
 $tbl_session_user           = Database::get_main_table(TABLE_MAIN_SESSION_USER);
 $tbl_session_course         = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
@@ -56,9 +50,7 @@ if ($_POST['formSent']) {
         $session_counter = 0;
 
         if ($file_type == 'xml') {
-
             // XML
-
             // SimpleXML for PHP5 deals with various encodings, but how many they are, what are version issues, do we need to waste time with configuration options?
             // For avoiding complications we go some sort of "PHP4 way" - we convert the input xml-file into UTF-8 before passing it to the parser.
             // Instead of:
@@ -161,7 +153,7 @@ if ($_POST['formSent']) {
                         $params['user_id']          = api_get_user_id();
                         
                         // Looking up for the teacher.
-                        $username       = trim(api_utf8_decode($courseNode->CourseTeacher));
+                        $username = trim(api_utf8_decode($courseNode->CourseTeacher));
                         $sql = "SELECT user_id, lastname, firstname FROM $tbl_user WHERE username='$username'";
                         $rs = Database::query($sql);
                         list($user_id, $lastname, $firstname) = Database::fetch_array($rs);
@@ -193,30 +185,7 @@ if ($_POST['formSent']) {
                         }
 
                         $date_start = trim(api_utf8_decode($node_session->DateStart)); // Just in case - encoding conversion.
-
-                        if (!empty($date_start)) {
-                            list($year_start, $month_start, $day_start) = explode('/', $date_start);
-                            if(empty($year_start) || empty($month_start) || empty($day_start)) {
-                                $error_message .= get_lang('WrongDate').' : '.$date_start.'<br />';
-                                break;
-                            } else {
-                                $time_start = mktime(0, 0, 0, $month_start, $day_start, $year_start);
-                            }
-
-                            $date_end = trim(api_utf8_decode($node_session->DateEnd));
-                            if (!empty($date_start)) {
-                                list($year_end, $month_end, $day_end) = explode('/', $date_end);
-                                if (empty($year_end) || empty($month_end) || empty($day_end)) {
-                                    $error_message .= get_lang('Error').' : '.$date_end.'<br />';
-                                    break;
-                                } else {
-                                    $time_end = mktime(0, 0, 0, $month_end, $day_end, $year_end);
-                                }
-                            }
-                            if ($time_end - $time_start < 0) {
-                                $error_message .= get_lang('StartDateShouldBeBeforeEndDate').' : '.$date_end.'<br />';
-                            }
-                        }
+                        $date_end = trim(api_utf8_decode($node_session->DateEnd));                                                
 
                         $visibility = trim(api_utf8_decode($node_session->Visibility));
                         $session_category_id = trim(api_utf8_decode($node_session->SessionCategory));
@@ -239,45 +208,48 @@ if ($_POST['formSent']) {
                                     $session_name .= $suffix;
                                 }
                             }
-                            // Creating the session.
-                            $sql_session = "INSERT IGNORE INTO $tbl_session SET
-                                    name = '".Database::escape_string($session_name)."',
-                                    id_coach = '$coach_id',
-                                    date_start = '$date_start',
-                                    date_end = '$date_end',
-                                    visibility = '$visibility',
-                                    session_category_id = '$session_category_id',
-                                    session_admin_id=".intval($_user['user_id']);
-                            $rs_session = Database::query($sql_session);
-                            $session_id = Database::insert_id();
+                            
+                            $params = array (
+                                'id_coach' => $coach_id,
+                                'visibility' => $visibility,
+                                'name' => $session_name,
+                                'access_start_date' => $date_start,
+                                'access_end_date' => $date_end,
+                                'session_category_id' => $session_category_id,
+                                'session_admin_id' => api_get_user_id(),
+                            );
+                            $session_id = SessionManager::add($params);                            
                             $session_counter++;
 
                         } else {
                             // Update the session if it is needed.
                             $my_session_result = SessionManager::get_session_by_name($session_name);
+                            
                             if ($my_session_result === false) {
-                                // Creating the session.
-                                $sql_session = "INSERT IGNORE INTO $tbl_session SET
-                                        name = '".Database::escape_string($session_name)."',
-                                        id_coach = '$coach_id',
-                                        date_start = '$date_start',
-                                        date_end = '$date_end',
-                                        visibility = '$visibility',
-                                        session_category_id = '$session_category_id',
-                                        session_admin_id=".intval($_user['user_id']);
-                                $rs_session = Database::query($sql_session);
-                                $session_id = Database::insert_id();
+                                $params = array (
+                                    'id_coach' => $coach_id,
+                                    'visibility' => $visibility,
+                                    'name' => $session_name,
+                                    'access_start_date' => $date_start,
+                                    'access_end_date' => $date_end,
+                                    'session_category_id' => $session_category_id,
+                                    'session_admin_id' => api_get_user_id(),
+                                );
+                                $session_id = SessionManager::add($params);                                      
                                 $session_counter++;
                             } else {
-                                // if the session already exists - update it.
-                                $sql_session = "UPDATE $tbl_session SET
-                                        id_coach = '$coach_id',
-                                        date_start = '$date_start',
-                                        date_end = '$date_end',
-                                        visibility = '$visibility',
-                                        session_category_id = '$session_category_id'
-                                    WHERE name = '$session_name'";
-                                $rs_session = Database::query($sql_session);
+                                
+                                $params = array (
+                                    'id' => $my_session_result['id'],
+                                    'id_coach' => $coach_id,
+                                    'visibility' => $visibility,
+                                    'name' => $session_name,
+                                    'access_start_date' => $date_start,
+                                    'access_end_date' => $date_end,
+                                    'session_category_id' => $session_category_id,
+                                    'session_admin_id' => api_get_user_id(),
+                                );
+                                SessionManager::update($params);                                
                                 $session_id = Database::query("SELECT id FROM $tbl_session WHERE name='$session_name'");
                                 list($session_id) = Database::fetch_array($session_id);
                                 Database::query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'");
@@ -296,7 +268,6 @@ if ($_POST['formSent']) {
                             UrlManager::add_session_to_url($session_id, 1);
                         }
 
-
                         // Adding users to the new session.
                         foreach ($node_session->User as $node_user) {
                             $username = UserManager::purify_username(api_utf8_decode($node_user), $purification_option_for_usernames);
@@ -522,49 +493,44 @@ if ($_POST['formSent']) {
                                 $session_name .= $suffix;
                             }
                         }
-
-                        // Creating the session.
-                        $sql_session = "INSERT IGNORE INTO $tbl_session SET
-                                name = '".Database::escape_string($session_name)."',
-                                id_coach = '$coach_id',
-                                date_start = '$date_start',
-                                date_end = '$date_end',
-                                visibility = '$visibility',
-                                session_category_id = '$session_category_id',
-                                session_admin_id=".intval($_user['user_id']);
-                        $rs_session = Database::query($sql_session);
-                        $session_id = Database::insert_id();
+                        
+                        $params = array (
+                            'id_coach' => $coach_id,
+                            'visibility' => $visibility,
+                            'name' => $session_name,
+                            'access_start_date' => $date_start,
+                            'access_end_date' => $date_end,
+                            'session_category_id' => $session_category_id,
+                            'session_admin_id' => api_get_user_id(),
+                        );
+                        $session_id = SessionManager::add($params); 
                         $session_counter++;
                     } else {
                         $my_session_result = SessionManager::get_session_by_name($session_name);
                         if ($my_session_result === false) {
-
-                            // Creating a session.
-                            $sql_session = "INSERT IGNORE INTO $tbl_session SET
-                                    name = '$session_name',
-                                    id_coach = '$coach_id',
-                                    date_start = '$date_start',
-                                    date_end = '$date_end',
-                                    visibility = '$visibility',
-                                    session_category_id = '$session_category_id'";
-
-                            $rs_session = Database::query($sql_session);
-                            // We get the last insert id.
-                            $my_session_result = SessionManager::get_session_by_name($session_name);
-                            $session_id = $my_session_result['id'];
-                            //echo '<br>';
+                            $params = array (
+                                'id_coach' => $coach_id,
+                                'visibility' => $visibility,
+                                'name' => $session_name,
+                                'access_start_date' => $date_start,
+                                'access_end_date' => $date_end,
+                                'session_category_id' => $session_category_id,
+                                'session_admin_id' => api_get_user_id(),
+                            );
+                            $session_id = SessionManager::add($params); 
                         } else {
-                            // The session already exists, update it then.
-                            $sql_session = "UPDATE $tbl_session SET
-                                    id_coach = '$coach_id',
-                                    date_start = '$date_start',
-                                    date_end = '$date_end',
-                                    visibility = '$visibility',
-                                    session_category_id = '$session_category_id'
-                                WHERE name = '$session_name'";
-                            $rs_session = Database::query($sql_session);
-                            $session_id = Database::query("SELECT id FROM $tbl_session WHERE name='$session_name'");
-                            list($session_id) = Database::fetch_array($session_id);
+                            $session_id = $my_session_result['id'];
+                            $params = array (
+                                'id' => $session_id,
+                                'id_coach' => $coach_id,
+                                'visibility' => $visibility,
+                                'name' => $session_name,
+                                'access_start_date' => $date_start,
+                                'access_end_date' => $date_end,
+                                'session_category_id' => $session_category_id,
+                                'session_admin_id' => api_get_user_id(),
+                            );
+                            SessionManager::update($params);
                             Database::query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'");
                             Database::query("DELETE FROM $tbl_session_course WHERE id_session='$session_id'");
                             Database::query("DELETE FROM $tbl_session_course_user WHERE id_session='$session_id'");

+ 226 - 89
main/admin/session_list.php

@@ -18,25 +18,31 @@ api_protect_admin_script(true);
 //Add the JS needed to use the jqgrid
 $htmlHeadXtra[] = api_get_jqgrid_js();
 
-$action = $_REQUEST['action'];
-$idChecked = $_REQUEST['idChecked'];
+$htmlHeadXtra[] = api_get_js('json-js/json2.js');
+$htmlHeadXtra[] = api_get_js('date/date.js');
+
+$htmlHeadXtra = api_get_datetime_picker_js($htmlHeadXtra);
+
+$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null;
+$idChecked = isset($_REQUEST['idChecked']) ? $_REQUEST['idChecked'] : null;
+$list_type = isset($_REQUEST['list_type']) ? $_REQUEST['list_type'] : 'simple';
 
 if ($action == 'delete') {
 	SessionManager::delete_session($idChecked);
 	header('Location: session_list.php');
 	exit();
 } elseif ($action == 'copy') {
-	SessionManager::copy_session($idChecked);
+	SessionManager::copy_session($idChecked, true, false);
     header('Location: session_list.php');
     exit();
 }
 
-$interbreadcrumb[]=array("url" => "index.php","name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array("url" => "index.php","name" => get_lang('PlatformAdmin'));
 
 $tool_name = get_lang('SessionList');
 Display::display_header($tool_name);
 
-$error_message = ''; // Avoid conflict with the global variable $error_msg (array type) in add_course.conf.php.
+$error_message = '';
 if (isset($_GET['action']) && $_GET['action'] == 'show_message') {
     $error_message = Security::remove_XSS($_GET['message']);
 }
@@ -46,125 +52,256 @@ if (!empty($error_message)) {
 }
 
 //jqgrid will use this URL to do the selects
-$url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions';
+$url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions&list_type='.$list_type;
+
 if (isset($_REQUEST['keyword'])) {
     //Begin with see the searchOper param
-    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions&_search=true&rows=20&page=1&sidx=&sord=asc&filters=&searchField=name&searchString='.Security::remove_XSS($_REQUEST['keyword']).'&searchOper=bw';    
+    $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions&_search=true&rows=20&page=1&sidx=&sord=asc&filters=&searchField=name&searchString='.Security::remove_XSS($_REQUEST['keyword']).'&searchOper=bw';
 }
 
-//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('NumberOfCourses'), get_lang('NumberOfUsers'), get_lang('SessionCategoryName'), 
-                        get_lang('StartDate'), get_lang('EndDate'), get_lang('Coach'),  get_lang('Status'), get_lang('Visibility'), get_lang('Actions'));
-
-//$activeurl = '?sidx=session_active';
-//Column config
-$column_model   = array(
-                        array('name'=>'name',           'index'=>'name',          'width'=>'120',  'align'=>'left', 'search' => 'true'),                        
-                        array('name'=>'nbr_courses',    'index'=>'nbr_courses',   'width'=>'30',   'align'=>'left', 'search' => 'true'),
-                        array('name'=>'nbr_users',      'index'=>'nbr_users',     'width'=>'30',   'align'=>'left', 'search' => 'true'),
-                        array('name'=>'category_name',  'index'=>'category_name', 'width'=>'70',   'align'=>'left', 'search' => 'true'),
-                        array('name'=>'date_start',     'index'=>'date_start',    'width'=>'40',   'align'=>'left', 'search' => 'true'),
-                        array('name'=>'date_end',       'index'=>'date_end',      'width'=>'40',   'align'=>'left', 'search' => 'true'),
-                        array('name'=>'coach_name',     'index'=>'coach_name',    'width'=>'80',   'align'=>'left', 'search' => 'false'),                        
-                        array('name'=>'status',         'index'=>'session_active','width'=>'40',   'align'=>'left', 'search' => 'true', 'stype'=>'select',
-                                 
-                              //for the bottom bar
-                              'searchoptions' => array(                                                
-                                                'defaultValue'  => '1', 
-                                                'value'         => '1:'.get_lang('Active').';0:'.get_lang('Inactive')),
-                             
-                              //for the top bar                              
-                              'editoptions' => array('value' => ':'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive'))),
-                                          
-                                   
-                        array('name'=>'visibility',     'index'=>'visibility',      'width'=>'40',   'align'=>'left', 'search' => 'false'),                        
-                        array('name'=>'actions',        'index'=>'actions',         'width'=>'100',  'align'=>'left','formatter'=>'action_formatter','sortable'=>'false', 'search' => 'false')
-                       );            
-//Autowidth             
+//Autowidth
 $extra_params['autowidth'] = 'true';
+//Height auto
+$extra_params['height'] = '100%';
+
+$extra_params['rowList'] = array(20, 50, 100, 250, 500);
 
-//height auto 
-$extra_params['height'] = 'auto';
-//$extra_params['excel'] = 'excel';
-//$extra_params['rowList'] = array(10, 20 ,30);
+$result = SessionManager::get_session_columns($list_type);
+$columns = $result['columns'];
+$column_model = $result['column_model'];
+
+$extra_params['postData'] =array (
+                    'filters' => array(
+                                        "groupOp" => "AND",
+                                        "rules" => $result['rules'],
+                                        /*array(
+                                            array( "field" => "display_start_date", "op" => "gt", "data" => ""),
+                                            array( "field" => "display_end_date", "op" => "gt", "data" => "")
+                                        ),*/
+                                        //'groups' => $groups
+                                )
+);
 
 //With this function we can add actions to the jgrid (edit, delete, etc)
 $action_links = 'function action_formatter(cellvalue, options, rowObject) {
-                         return \'<a href="session_edit.php?page=resume_session.php&id=\'+options.rowId+\'">'.Display::return_icon('edit.png',get_lang('Edit'),'',ICON_SIZE_SMALL).'</a>'.
+                         return \'<a href="session_add.php?page=resume_session.php&id=\'+options.rowId+\'">'.Display::return_icon('edit.png',get_lang('Edit'),'',ICON_SIZE_SMALL).'</a>'.
                          '&nbsp;<a href="add_users_to_session.php?page=session_list.php&id_session=\'+options.rowId+\'">'.Display::return_icon('user_subscribe_session.png',get_lang('SubscribeUsersToSession'),'',ICON_SIZE_SMALL).'</a>'.
                          '&nbsp;<a href="add_courses_to_session.php?page=session_list.php&id_session=\'+options.rowId+\'">'.Display::return_icon('courses_to_session.png',get_lang('SubscribeCoursesToSession'),'',ICON_SIZE_SMALL).'</a>'.
                          '&nbsp;<a onclick="javascript:if(!confirm('."\'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES))."\'".')) return false;"  href="session_list.php?action=copy&idChecked=\'+options.rowId+\'">'.Display::return_icon('copy.png',get_lang('Copy'),'',ICON_SIZE_SMALL).'</a>'.
                          '&nbsp;<a onclick="javascript:if(!confirm('."\'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES))."\'".')) return false;"  href="session_list.php?action=delete&idChecked=\'+options.rowId+\'">'.Display::return_icon('delete.png',get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>'.
-                         '\'; 
+                         '\';
                  }';
+$url_select = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php?1=1';
 ?>
 <script>
 
+function setSearchSelect(columnName) {
+    $("#sessions").jqGrid('setColProp', columnName, {
 
-function setSearchSelect(columnName) {    
-    $("#sessions").jqGrid('setColProp', columnName,
-    {                   
-       searchoptions:{
-            dataInit:function(el){                            
+       /*searchoptions:{
+            dataInit:function(el){
                 $("option[value='1']",el).attr("selected", "selected");
                 setTimeout(function(){
                     $(el).trigger('change');
-                },1000);
+                }, 1000);
             }
-        }
+        }*/
     });
 }
+var added_cols = [];
+var original_cols = [];
 
+function clean_cols(grid, added_cols) {
+    //Cleaning
+    for (key in added_cols) {
+        //console.log('hide: ' + key);
+        grid.hideCol(key);
+    };
+    grid.showCol('name');
+    grid.showCol('display_start_date');
+    grid.showCol('display_end_date');
+    grid.showCol('course_title');
+}
+
+function show_cols(grid, added_cols) {
+    grid.showCol('name').trigger('reloadGrid');
+    for (key in added_cols) {
+        //console.log('show: ' + key);
+        grid.showCol(key);
+    };
+}
+
+var second_filters = [];
 
 $(function() {
-    <?php 
-        echo Display::grid_js('sessions', $url,$columns,$column_model,$extra_params, array(), $action_links,true);      
+
+
+    date_pick_today = function(elem) {
+        $(elem).datetimepicker({dateFormat: "yy-mm-dd"});
+        $(elem).datetimepicker('setDate', (new Date()));
+    }
+    date_pick_one_month = function(elem) {
+        $(elem).datetimepicker({dateFormat: "yy-mm-dd"});
+        next_month = Date.today().next().month();
+        $(elem).datetimepicker('setDate', next_month);
+    }
+
+    //Great hack
+    register_second_select = function(elem) {
+        second_filters[$(elem).val()] = $(elem);
+    }
+
+    fill_second_select = function(elem) {
+        $(elem).on("change", function() {
+            composed_id = $(this).val();
+            field_id = composed_id.split("#")[0];
+            id = composed_id.split("#")[1];
+
+            $.ajax({
+                url: "<?php echo $url_select ?>&a=get_second_select_options",
+                dataType: "json",
+                data: "type=session&field_id="+field_id+"&option_value_id="+id,
+                success: function(data) {
+                    my_select = second_filters[field_id];
+                    my_select.empty();
+                    $.each(data, function(index, value) {
+                        my_select.append($("<option/>", {
+                            value: index,
+                            text: value
+                        }));
+                    });
+                }
+            });
+        });
+    }
+
+    <?php
+        echo Display::grid_js('sessions', $url, $columns, $column_model, $extra_params, array(), $action_links, true);
     ?>
-    
-    setSearchSelect("status");    
-    
-    $("#sessions").jqGrid('navGrid','#sessions_pager', {edit:false,add:false,del:false},
-        {height:280,reloadAfterSubmit:false}, // edit options 
-        {height:280,reloadAfterSubmit:false}, // add options 
-        {reloadAfterSubmit:false}, // del options 
-        {width:500} // search options
+
+    setSearchSelect("status");
+
+    var grid = $("#sessions"),
+    prmSearch = {
+        multipleSearch : true,
+        overlay : false,
+        width: 'auto',
+        caption: '<?php echo addslashes(get_lang('Search')); ?>',
+        formclass:'data_table',
+        onSearch : function() {
+            var postdata = grid.jqGrid('getGridParam', 'postData');
+
+            if (postdata && postdata.filters) {
+                filters = jQuery.parseJSON(postdata.filters);
+                clean_cols(grid, added_cols);
+                added_cols = [];
+                //console.log(postdata);
+                $.each(filters, function(key, value){
+                    console.log('key: ' + key );
+
+                    if (key == 'rules') {
+                        $.each(value, function(subkey, subvalue) {
+
+                            if (subvalue.data == undefined) {
+                            }
+
+                            //if (added_cols[value.field] == undefined) {
+                                added_cols[subvalue.field] = subvalue.field;
+                            //}
+                            //grid.showCol(value.field);
+                        });
+                    }
+                });
+                show_cols(grid, added_cols);
+            }
+       },
+       onReset: function() {
+            clean_cols(grid, added_cols);
+       }
+    };
+
+    original_cols = grid.jqGrid('getGridParam', 'colModel');
+
+    grid.jqGrid('navGrid','#sessions_pager',
+        {edit:false,add:false,del:false},
+        {height:280,reloadAfterSubmit:false}, // edit options
+        {height:280,reloadAfterSubmit:false}, // add options
+        {reloadAfterSubmit:false},// del options
+        prmSearch
     );
-    /*
-    // add custom button to export the data to excel
-    jQuery("#sessions").jqGrid('navButtonAdd','#sessions_pager',{
-           caption:"", 
-           onClickButton : function () { 
-               jQuery("#sessions").excelExport();
-           } 
+
+    // create the searching dialog
+    grid.searchGrid(prmSearch);
+
+    //Fixes search table
+    var searchDialogAll = $("#fbox_"+grid[0].id);
+    searchDialogAll.addClass("table");
+
+    var searchDialog = $("#searchmodfbox_"+grid[0].id);
+    searchDialog.addClass("ui-jqgrid ui-widget ui-widget-content ui-corner-all");
+    searchDialog.css({position:"relative", "z-index":"auto", "float":"left"})
+    var gbox = $("#gbox_"+grid[0].id);
+    gbox.before(searchDialog);
+    gbox.css({clear:"left"});
+
+    //Select first elements by default
+    $('.input-elm').each(function(){
+        $(this).find('option:first').attr('selected', 'selected');
     });
-    
-    jQuery('#sessions').jqGrid('navButtonAdd','#sessions_pager',{id:'pager_csv',caption:'',title:'Export To CSV',onClickButton : function(e)
-    {
-        try {
-            jQuery("#sessions").jqGrid('excelExport',{tag:'csv', url:'grid.php'});
-        } catch (e) {
-            window.location= 'grid.php?oper=csv';
-        }
-    },buttonicon:'ui-icon-document'})
-    */
-   
-    
-    //Adding search options
-    var options = {
-        'stringResult': true,
-        'autosearch' : true,
-        'searchOnEnter':false      
-    }
-    jQuery("#sessions").jqGrid('filterToolbar',options);    
-    var sgrid = $("#sessions")[0];
-    sgrid.triggerToolbar();
+
+    $('.delete-rule').each(function(){
+        $(this).click(function(){
+             $('.input-elm').each(function(){
+                $(this).find('option:first').attr('selected', 'selected');
+            });
+        });
+    });
+
+    /*
+    $('.delete-rule').on('click', function(){
+        console.log('deleted');
+        $('.input-elm').each(function(){
+            $(this).find('option:first').attr('selected', 'selected');
+        });
+    });*/
+
+
 });
 </script>
-<div class="actions">
-<?php 
+<?php
+echo '<div class="actions">';
 echo '<a href="'.api_get_path(WEB_CODE_PATH).'admin/session_add.php">'.Display::return_icon('new_session.png',get_lang('AddSession'),'',ICON_SIZE_MEDIUM).'</a>';
 echo '<a href="'.api_get_path(WEB_CODE_PATH).'admin/add_many_session_to_category.php">'.Display::return_icon('session_to_category.png',get_lang('AddSessionsInCategories'),'',ICON_SIZE_MEDIUM).'</a>';
 echo '<a href="'.api_get_path(WEB_CODE_PATH).'admin/session_category_list.php">'.Display::return_icon('folder.png',get_lang('ListSessionCategory'),'',ICON_SIZE_MEDIUM).'</a>';
+if ($list_type == 'complete') {
+    echo '<a href="'.api_get_self().'?list_type=simple">'.Display::return_icon('view_remove.png',get_lang('Simple'),'',ICON_SIZE_MEDIUM).'</a>';
+} else {
+    echo '<a href="'.api_get_self().'?list_type=complete">'.Display::return_icon('view_text.png',get_lang('Complete'),'',ICON_SIZE_MEDIUM).'</a>';
+}
 echo '</div>';
+
+$form = new FormValidator('search');
+
+$form->addElement('header', get_lang('Filter'));
+
+$form->addElement('text', 'start_date_start', get_lang('Between'), array('id' =>'start_date_start'));
+$form->addElement('text', 'start_date_end', get_lang('And'), array('id' =>'start_date_end'));
+$renderer = $form->defaultRenderer();
+
+$renderer->setElementTemplate(get_lang('StartDate').' {label} {element}', 'start_date_start');
+$renderer->setElementTemplate('{label} {element}', 'start_date_end');
+
+$form->addElement('html', '<div class="clear"></div>');
+
+$form->addElement('text', 'end_date_start', get_lang('Between'), array('id' =>'end_date_start'));
+$form->addElement('text', 'end_date_end', get_lang('And'), array('id' =>'end_date_end'));
+
+$renderer->setElementTemplate(get_lang('EndDate').' {label} {element}', 'end_date_start');
+$renderer->setElementTemplate('{label} {element}', 'end_date_end');
+
+$options = CourseManager::get_course_list_of_user_as_course_admin(api_get_user_id());
+$form->addElement('select', 'course', get_lang('Course'), $options);
+$form->addElement('button', 'submit', get_lang('Search'), array('id' => 'search_button'));
+
 echo Display::grid_html('sessions');
 Display::display_footer();

+ 1 - 4
main/admin/session_user_import.php

@@ -13,11 +13,8 @@ require '../inc/global.inc.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script(true);
 
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
-
 $form_sent = 0;
-$error_message = ''; // Avoid conflict with the global variable $error_msg (array type) in add_course.conf.php.
+$error_message = '';
 if (isset($_GET['action']) && $_GET['action'] == 'show_message') {
     $error_message = Security::remove_XSS($_GET['message']);
 }

+ 24 - 19
main/admin/settings.lib.php

@@ -176,6 +176,7 @@ function handle_plugins() {
     echo '<button class="save" type="submit" name="submit_plugins">'.get_lang('EnablePlugins').'</button>';
     echo '</div>';
     echo '</form>';
+
 }
 
 /**
@@ -185,7 +186,6 @@ function handle_plugins() {
 */
 function handle_stylesheets() {
     global $_configuration;
-
     // Current style.
     $currentstyle = api_get_setting('stylesheets');
 
@@ -197,14 +197,14 @@ function handle_stylesheets() {
         if ($style_info[0]['access_url_changeable'] == 1 && $url_info['active'] == 1) {
             $is_style_changeable = true;
             /*echo '<div class="actions" id="stylesheetuploadlink">';
-            	Display::display_icon('upload_stylesheets.png',get_lang('UploadNewStylesheet'),'', ICON_SIZE_MEDIUM);
+            	Display::display_icon('upload_stylesheets.png',get_lang('UploadNewStylesheet'),'',ICON_SIZE_MEDIUM);
             	echo '<a href="" onclick="javascript: document.getElementById(\'newstylesheetform\').style.display = \'block\'; document.getElementById(\'stylesheetuploadlink\').style.display = \'none\'; return false; ">'.get_lang('UploadNewStylesheet').'</a>';
             echo '</div>';*/
         }
     } else {
         $is_style_changeable = true;
         /*echo '<div class="actions" id="stylesheetuploadlink">';
-			Display::display_icon('upload_stylesheets.png',get_lang('UploadNewStylesheet'),'', ICON_SIZE_MEDIUM);
+			Display::display_icon('upload_stylesheets.png',get_lang('UploadNewStylesheet'),'',ICON_SIZE_MEDIUM);
         	echo '<a href="" onclick="javascript: document.getElementById(\'newstylesheetform\').style.display = \'block\'; document.getElementById(\'stylesheetuploadlink\').style.display = \'none\'; return false; ">'.get_lang('UploadNewStylesheet').'</a>';
         echo '</div>';*/
     }
@@ -239,19 +239,19 @@ function handle_stylesheets() {
 
     if (isset($_POST['stylesheet_upload'])) {
         if ($form->validate()) {
-            $values = $form->exportValues();
-            $picture_element = $form->getElement('new_stylesheet');
-            $picture = $picture_element->getValue();
-            $result  = upload_stylesheet($values, $picture);
+        $values = $form->exportValues();
+        $picture_element = $form->getElement('new_stylesheet');
+        $picture = $picture_element->getValue();
+        $result  = upload_stylesheet($values, $picture);
 
-            // Add event to the system log.
-            $user_id = api_get_user_id();
-            $category = $_GET['category'];
-            event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
+        // Add event to the system log.
+        $user_id = api_get_user_id();
+        $category = $_GET['category'];
+        event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
 
-            if ($result) {
-                Display::display_confirmation_message(get_lang('StylesheetAdded'));
-            }
+        if ($result) {
+            Display::display_confirmation_message(get_lang('StylesheetAdded'));
+        }
         }
     }
 
@@ -286,7 +286,7 @@ function handle_stylesheets() {
                     $show_name = ucwords(str_replace('_', ' ', $style_dir));
 
                     if ($is_style_changeable) {
-                        $list_of_styles[$style_dir] = "<option value=\"".$style_dir."\" ".$selected." /> $show_name </option>";
+                        $list_of_styles[$style_dir] = "<option  value=\"".$style_dir."\" ".$selected." /> $show_name </option>";
                         $list_of_names[$style_dir]  = $show_name;
                         //echo "<input type=\"radio\" name=\"style\" value=\"".$style_dir."\" ".$selected." onClick=\"parent.preview.location='style_preview.php?style=".$style_dir."';\"/>";
                         //echo '<a href="style_preview.php?style='.$style_dir.'" target="preview">'.$show_name.'</a>';
@@ -303,7 +303,7 @@ function handle_stylesheets() {
     //Sort styles in alphabetical order
     asort($list_of_names);
     $select_list = array();
-    foreach ($list_of_names as $style_dir=>$item) {
+    foreach($list_of_names as $style_dir=>$item) {
         $select_list[$style_dir] = strip_tags($list_of_styles[$style_dir]);
     }
 
@@ -328,8 +328,7 @@ function handle_stylesheets() {
             Display::display_normal_message($str,false);
         }
     }
-
-    if ($is_style_changeable) {
+    if ($is_style_changeable){
         $group[] = $form_change->createElement('button', 'save', get_lang('SaveSettings'), array('class' => 'btn btn-primary'));
         $group[] = $form_change->createElement('button', 'preview', get_lang('Preview'), array('class' => 'btn'));
         $group[] = $form_change->createElement('button', 'download', get_lang('Download'), array('class' => 'btn'));
@@ -480,6 +479,7 @@ function store_regions() {
             }
         }
     }
+    api_set_setting_last_update();
 }
 
 /**
@@ -487,9 +487,11 @@ function store_regions() {
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 */
 function store_plugins() {
+
     $plugin_obj = new AppPlugin();
 
     // Get a list of all current 'Plugins' settings
+
     $plugin_list = $plugin_obj->read_plugins_from_path();
 
     $installed_plugins = array();
@@ -509,6 +511,7 @@ function store_plugins() {
     foreach ($remove_plugins as $plugin) {
         $plugin_obj->uninstall($plugin);
     }
+    api_set_setting_last_update();
 }
 
 /**
@@ -517,12 +520,15 @@ function store_plugins() {
 */
 function store_stylesheets() {
     global $_configuration;
+
     // Insert the stylesheet.
     $style = Database::escape_string($_POST['style']);
 
     if (is_style($style)) {
         api_set_setting('stylesheets', $style, null, 'stylesheets', $_configuration['access_url']);
+        api_set_setting_last_update();
     }
+
     return true;
 }
 
@@ -636,7 +642,6 @@ function handle_search() {
     echo '</div>';
 
     if ($search_enabled == 'true') {
-        require_once api_get_path(LIBRARY_PATH).'sortable_table.class.php';
         $xapian_path = api_get_path(SYS_PATH).'searchdb';
 
         /*

+ 4 - 3
main/admin/settings.php

@@ -27,7 +27,6 @@ $cidReset = true;
 
 // Including some necessary library files.
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 require_once 'settings.lib.php';
 
@@ -138,7 +137,7 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
         $mark_all = false;
         $un_mark_all = false;
 
-        if (api_is_multiple_url_enabled()) {
+        if ($_configuration['multiple_access_urls']) {
             if (isset($values['buttons_in_action_right']) && isset($values['buttons_in_action_right']['mark_all'])) {
                 $mark_all = true;
             }
@@ -196,7 +195,7 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
 			}
 		}
 
-        if (isset($values['allow_social_tool']) && $values['allow_social_tool'] == 'true') {
+        if ($values['allow_social_tool'] == 'true') {
             $values['allow_message_tool'] = 'true';
         }
 
@@ -307,6 +306,8 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
         $category = $_GET['category'];
         event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
 
+        api_set_setting_last_update();
+
         // Add event configuration settings variable to the system log.
         if (is_array($keys) && count($keys) > 0) {
             foreach ($keys as $variable) {

+ 2 - 1
main/admin/skills.php

@@ -33,7 +33,8 @@ $skill_visualizer = new SkillVisualizer($tree, $type);
 $html = $skill_visualizer->return_html();
 $url  = api_get_path(WEB_AJAX_PATH).'skill.ajax.php?1=1';
 
-$tpl = new Template(null, false, false);
+//$tpl = new Template(null, false, false);
+$tpl = new Template(null);
 
 $tpl->assign('url', $url);
 $tpl->assign('html', $html);

+ 0 - 3
main/admin/skills_import.php

@@ -12,9 +12,6 @@ $language_file = array ('admin', 'registration');
 
 $cidReset = true;
 require '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'import.lib.php';
 
 function validate_data($skills) {
     $errors = array();

+ 2 - 1
main/admin/skills_wheel.php

@@ -27,7 +27,8 @@ $htmlHeadXtra[] = api_get_js('d3/jquery.xcolor.js');
 $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/jquery.fcbkcomplete.js" type="text/javascript" language="javascript"></script>';
 $htmlHeadXtra[] = '<link  href="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/style.css" rel="stylesheet" type="text/css" />';
 
-$tpl = new Template(null, false, false);
+//$tpl = new Template(null, false, false);
+$tpl = new Template();
 
 $load_user = 0;
 if (isset($_GET['load_user'])) {

+ 0 - 2
main/admin/statistics.php

@@ -14,8 +14,6 @@ $this_section=SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-
 $interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
 $tool_name = get_lang('Statistics');
 Display::display_header($tool_name);

+ 3 - 7
main/admin/statistics/index.php

@@ -81,8 +81,7 @@ switch ($_REQUEST['report']) {
         break;
     case 'courselastvisit':
         Statistics::print_course_last_visit();
-        break;
-    //---
+        break;    
     case 'users':
         // total amount of users
         Statistics::print_stats(
@@ -116,12 +115,10 @@ switch ($_REQUEST['report']) {
         break;
     case 'zombies':
         ZombieReport::create(array('report' => 'zombies'))->display();
-        break;
-    //---
+        break;    
     case 'activities':
         Statistics::print_activities_stats();
-        break;
-    //---
+        break;    
     case 'messagesent':
         $messages_sent = Statistics::get_messages('sent');
         Statistics::print_stats(get_lang('MessagesSent'), $messages_sent);
@@ -136,5 +133,4 @@ switch ($_REQUEST['report']) {
         Statistics::print_stats(get_lang('CountFriends'), $friends);
         break;
 }
-
 Display::display_footer();

+ 0 - 722
main/admin/statistics/statistics.lib.php

@@ -1,722 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
-* This class provides some functions for statistics
-* @package chamilo.statistics
-*/
-class Statistics {
-
-    /**
-     * Converts a number of bytes in a formatted string
-     * @param int $size
-     * @return string Formatted file size
-     */
-    static function make_size_string($size) {
-        if ($size < pow(2,10)) return $size." bytes";
-        if ($size >= pow(2,10) && $size < pow(2,20)) return round($size / pow(2,10), 0)." KB";
-        if ($size >= pow(2,20) && $size < pow(2,30)) return round($size / pow(2,20), 1)." MB";
-        if ($size > pow(2,30)) return round($size / pow(2,30), 2)." GB";
-    }
-
-    /**
-     * Count courses
-     * @param string $category_code  Code of a course category. Default: count
-     * all courses.
-     * @return int Number of courses counted
-     */
-    static function count_courses($category_code = NULL) {
-        global $_configuration;
-        $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
-        $access_url_rel_course_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-        $current_url_id = api_get_current_access_url_id();
-        if (api_is_multiple_url_enabled()) {
-            $sql = "SELECT COUNT(*) AS number FROM ".$course_table." as c, ".$access_url_rel_course_table." as u WHERE u.course_code=c.code AND access_url_id='".$current_url_id."'";
-            if (isset ($category_code)) {
-                $sql .= " AND category_code = '".Database::escape_string($category_code)."'";
-            }
-        } else {
-            $sql = "SELECT COUNT(*) AS number FROM ".$course_table." ";
-            if (isset ($category_code)) {
-                $sql .= " WHERE category_code = '".Database::escape_string($category_code)."'";
-            }
-        }
-        $res = Database::query($sql);
-        $obj = Database::fetch_object($res);
-        return $obj->number;
-    }
-
-    /**
-     * Count courses by visibility
-     * @param int Visibility (0 = closed, 1 = private, 2 = open, 3 = public)
-     * all courses.
-     * @return int Number of courses counted
-     */
-    static function count_courses_by_visibility($vis = null) {
-        if (!isset($vis)) { return 0; }
-        $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
-        $access_url_rel_course_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-        $current_url_id = api_get_current_access_url_id();
-        if (api_is_multiple_url_enabled()) {
-            $sql = "SELECT COUNT(*) AS number FROM ".$course_table." as c, ".$access_url_rel_course_table." as u WHERE u.course_code=c.code AND access_url_id='".$current_url_id."'";
-            if (isset ($vis)) {
-                $sql .= " AND visibility = ".intval($vis);
-            }
-        } else {
-            $sql = "SELECT COUNT(*) AS number FROM ".$course_table." ";
-            if (isset ($vis)) {
-                $sql .= " WHERE visibility = ".intval($vis);
-            }
-        }
-        $res = Database::query($sql);
-        $obj = Database::fetch_object($res);
-        return $obj->number;
-    }
-
-    /**
-     * Count users
-     * @param int      optional, user status (COURSEMANAGER or STUDENT), if it's not setted it'll count all users.
-     * @param string optional, code of a course category. Default: count only users without filtering category
-     * @param bool count invisible courses (todo)
-     * @param bool count only active users (false to only return currently active users)
-     * @return int Number of users counted
-     */
-    static function count_users($status = null, $category_code = null, $count_invisible_courses = true, $only_active = false) {
-        // Database table definitions
-        $course_user_table     = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-        $course_table         = Database :: get_main_table(TABLE_MAIN_COURSE);
-        $user_table         = Database :: get_main_table(TABLE_MAIN_USER);
-        $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-        $current_url_id = api_get_current_access_url_id();
-        $active_filter = $only_active?' AND active=1':'';
-        $status_filter = isset($status)?' AND status = '.intval($status):'';
-
-        if (api_is_multiple_url_enabled()) {
-            $sql = "SELECT COUNT(DISTINCT(u.user_id)) AS number FROM $user_table as u, $access_url_rel_user_table as url WHERE u.user_id=url.user_id AND access_url_id='".$current_url_id."' $status_filter $active_filter";
-            if (isset ($category_code)) {
-                $sql = "SELECT COUNT(DISTINCT(cu.user_id)) AS number FROM $course_user_table cu, $course_table c, $access_url_rel_user_table as url WHERE c.code = cu.course_code AND c.category_code = '".Database::escape_string($category_code)."' AND cu.user_id=url.user_id AND access_url_id='".$current_url_id."' $status_filter $active_filter";
-            }
-        } else {
-            $sql = "SELECT COUNT(DISTINCT(user_id)) AS number FROM $user_table WHERE 1=1 $status_filter $active_filter";
-            if (isset ($category_code)) {
-                $status_filter = isset($status)?' AND status = '.intval($status):'';
-                $sql = "SELECT COUNT(DISTINCT(cu.user_id)) AS number FROM $course_user_table cu, $course_table c WHERE c.code = cu.course_code AND c.category_code = '".Database::escape_string($category_code)."' $status_filter $active_filter";
-            }
-        }
-
-        $res = Database::query($sql);
-        $obj = Database::fetch_object($res);
-        return $obj->number;
-    }
-
-    /**
-     * Count activities from track_e_default_table
-     * @return int Number of activities counted
-     */
-    static function get_number_of_activities() {
-        // Database table definitions
-        global $_configuration;
-        $track_e_default  = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
-        $table_user = Database::get_main_table(TABLE_MAIN_USER);
-        $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-        $current_url_id = api_get_current_access_url_id();
-        if ($_configuration['multiple_access_urls']) {
-            $sql = "SELECT count(default_id) AS total_number_of_items FROM $track_e_default, $table_user user, $access_url_rel_user_table url WHERE default_user_id = user.user_id AND user.user_id=url.user_id AND access_url_id='".$current_url_id."'";
-        } else {
-            $sql = "SELECT count(default_id) AS total_number_of_items FROM $track_e_default, $table_user user WHERE default_user_id = user.user_id ";
-        }
-
-        if (isset($_GET['keyword'])) {
-            $keyword = Database::escape_string(trim($_GET['keyword']));
-            $sql .= " AND (user.username LIKE '%".$keyword."%' OR default_event_type LIKE '%".$keyword."%' OR default_value_type LIKE '%".$keyword."%' OR default_value LIKE '%".$keyword."%') ";
-        }
-
-        $res = Database::query($sql);
-        $obj = Database::fetch_object($res);
-        return $obj->total_number_of_items;
-    }
-
-    /**
-     * Get activities data to display
-     */
-    static function get_activities_data($from, $number_of_items, $column, $direction) {
-        global $dateTimeFormatLong, $_configuration;
-        $track_e_default    		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
-        $table_user 				= Database::get_main_table(TABLE_MAIN_USER);
-        $access_url_rel_user_table	= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-        $current_url_id 			= api_get_current_access_url_id();
-
-        $column          = intval($column);
-        $from            = intval($from);
-        $number_of_items = intval($number_of_items);
-
-        if (!in_array($direction, array('ASC','DESC'))) {
-			$direction = 'DESC';
-        }
-        if ($_configuration['multiple_access_urls']) {
-            $sql = "SELECT ".
-                "default_event_type  as col0, ".
-                "default_value_type    as col1, ".
-                "default_value        as col2, ".
-                "user.username         as col3, ".
-                "user.user_id         as col4, ".
-                "default_date         as col5 ".
-                "FROM $track_e_default as track_default, $table_user as user, $access_url_rel_user_table as url ".
-                "WHERE track_default.default_user_id = user.user_id AND url.user_id=user.user_id AND access_url_id='".$current_url_id."'";
-        } else {
-            $sql = "SELECT ".
-                   "default_event_type  as col0, ".
-                   "default_value_type    as col1, ".
-                   "default_value        as col2, ".
-                   "user.username         as col3, ".
-                   "user.user_id         as col4, ".
-                   "default_date         as col5 ".
-                   "FROM $track_e_default track_default, $table_user user ".
-                   "WHERE track_default.default_user_id = user.user_id ";
-        }
-
-        if (isset($_GET['keyword'])) {
-            $keyword = Database::escape_string(trim($_GET['keyword']));
-            $sql .= " AND (user.username LIKE '%".$keyword."%' OR default_event_type LIKE '%".$keyword."%' OR default_value_type LIKE '%".$keyword."%' OR default_value LIKE '%".$keyword."%') ";
-        }
-
-        if (!empty($column) && !empty($direction)) {
-            $sql .= " ORDER BY col$column $direction";
-        } else {
-            $sql .= " ORDER BY col5 DESC ";
-        }
-        $sql .=    " LIMIT $from,$number_of_items ";
-
-        $res = Database::query($sql);
-        $activities = array ();
-        while ($row = Database::fetch_row($res)) {
-            if (strpos($row[1], '_object') === false) {
-                $row[2] = $row[2];
-            } else {
-                if (!empty($row[2])) {
-                    $row[2] = unserialize($row[2]);
-                    if (is_array($row[2]) && !empty($row[2])) {
-                        $row[2] = implode_with_key(', ', $row[2]);
-                    }
-                }
-            }
-        	if (!empty($row['default_date']) && $row['default_date'] != '0000-00-00 00:00:00') {
-            	$row['default_date'] = api_get_local_time($row['default_date']);
-        	} else {
-        		$row['default_date'] = '-';
-        	}
-            if (!empty($row[4])) { //user ID
-                $row[3] = Display::url($row[3],api_get_path(WEB_CODE_PATH).'admin/user_information?user_id='.$row[5], array('title' => get_lang('UserInfo')));
-
-                $row[4] = TrackingUserLog::get_ip_from_user_event($row[4],$row[5],true);
-                if (empty($row[4])) {
-                    $row[4] = get_lang('Unknown');
-                }
-            }
-            $activities[] = $row;
-        }
-        return $activities;
-    }
-
-    /**
-     * Get all course categories
-     * @return array All course categories (code => name)
-     */
-    static function get_course_categories() {
-        $category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
-        $sql = "SELECT code, name FROM $category_table ORDER BY tree_pos";
-        $res = Database::query($sql);
-        $categories = array ();
-        while ($category = Database::fetch_object($res)) {
-            $categories[$category->code] = $category->name;
-        }
-        return $categories;
-    }
-
-    /**
-     * Rescale data
-     * @param array $data The data that should be rescaled
-     * @param int $max The maximum value in the rescaled data (default = 500);
-     * @return array The rescaled data, same key as $data
-     */
-    static function rescale($data, $max = 500) {
-        $data_max = 1;
-        foreach ($data as $index => $value) {
-            $data_max = ($data_max < $value ? $value : $data_max);
-        }
-        reset($data);
-        $result = array ();
-        $delta = $max / $data_max;
-        foreach ($data as $index => $value) {
-            $result[$index] = (int) round($value * $delta);
-        }
-        return $result;
-    }
-
-    /**
-     * Show statistics
-     * @param string $title The title
-     * @param array $stats
-     * @param bool $show_total
-     * @param bool $is_file_size
-     */
-    static function print_stats($title, $stats, $show_total = true, $is_file_size = false) {
-        $total = 0;
-        $data = Statistics::rescale($stats);
-
-        echo '<table class="data_table" cellspacing="0" cellpadding="3">
-                <tr><th colspan="'.($show_total ? '4' : '3').'">'.$title.'</th></tr>';
-        $i = 0;
-        foreach ($stats as $subtitle => $number) {
-            $total += $number;
-        }
-
-        foreach ($stats as $subtitle => $number) {
-            if (!$is_file_size) {
-                $number_label = number_format($number, 0, ',', '.');
-            } else {
-                $number_label = Statistics::make_size_string($number);
-            }
-            $percentage = ($total>0?number_format(100*$number/$total, 1, ',', '.'):'0');
-
-            echo '<tr class="row_'.($i%2 == 0 ? 'odd' : 'even').'">
-                    <td width="150">'.$subtitle.'</td>
-                    <td width="550">'.Display::bar_progress($percentage, false).'</td>
-                    <td align="right">'.$number_label.'</td>';
-            if ($show_total) {
-                echo '<td align="right"> '.$percentage.'%</td>';
-            }
-            echo '</tr>';
-            $i ++;
-        }
-        if ($show_total) {
-            if (!$is_file_size) {
-                $total_label = number_format($total, 0, ',', '.');
-            } else {
-                $total_label = Statistics::make_size_string($total);
-            }
-            echo '<tr><th  colspan="4" align="right">'.get_lang('Total').': '.$total_label.'</td></tr>';
-        }
-        echo '</table>';
-    }
-
-    /**
-     * Show some stats about the number of logins
-     * @param string $type month, hour or day
-     */
-    static function print_login_stats($type) {
-        global $_configuration;
-        $table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-        $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-        $current_url_id = api_get_current_access_url_id();
-        if ($_configuration['multiple_access_urls']) {
-            $table_url = ", $access_url_rel_user_table";
-            $where_url = " WHERE login_user_id=user_id AND access_url_id='".$current_url_id."'";
-            $where_url_last = ' AND login_date > DATE_SUB(NOW(),INTERVAL 1 %s)';
-        } else {
-            $table_url = '';
-            $where_url = '';
-            $where_url_last = ' WHERE login_date > DATE_SUB(NOW(),INTERVAL 1 %s)';
-        }
-        switch ($type) {
-            case 'month':
-                $months = api_get_months_long();
-                $period = get_lang('PeriodMonth');
-                $sql = "SELECT DATE_FORMAT( login_date, '%Y-%m' ) AS stat_date , count( login_id ) AS number_of_logins FROM ".$table.$table_url.$where_url." GROUP BY stat_date ORDER BY login_date ";
-                $sql_last_x = "SELECT DATE_FORMAT( login_date, '%Y-%m' ) AS stat_date , count( login_id ) AS number_of_logins FROM ".$table.$table_url.$where_url.sprintf($where_url_last,'YEAR')." GROUP BY stat_date ORDER BY login_date ";
-                break;
-            case 'hour':
-                $period = get_lang('PeriodHour');
-                $sql = "SELECT DATE_FORMAT( login_date, '%H' ) AS stat_date , count( login_id ) AS number_of_logins FROM ".$table.$table_url.$where_url." GROUP BY stat_date ORDER BY stat_date ";
-                $sql_last_x = "SELECT DATE_FORMAT( login_date, '%H' ) AS stat_date , count( login_id ) AS number_of_logins FROM ".$table.$table_url.$where_url.sprintf($where_url_last,'DAY')." GROUP BY stat_date ORDER BY stat_date ";
-                break;
-            case 'day':
-                $week_days = api_get_week_days_long();
-                $period = get_lang('PeriodDay');
-                $sql = "SELECT DATE_FORMAT( login_date, '%w' ) AS stat_date , count( login_id ) AS number_of_logins FROM ".$table.$table_url.$where_url." GROUP BY stat_date ORDER BY DATE_FORMAT( login_date, '%w' ) ";
-                $sql_last_x = "SELECT DATE_FORMAT( login_date, '%w' ) AS stat_date , count( login_id ) AS number_of_logins FROM ".$table.$table_url.$where_url.sprintf($where_url_last,'WEEK')." GROUP BY stat_date ORDER BY DATE_FORMAT( login_date, '%w' ) ";
-                break;
-        }
-        $res_last_x = Database::query($sql_last_x);
-        $result_last_x = array();
-        while ($obj = Database::fetch_object($res_last_x)) {
-            $stat_date = $obj->stat_date;
-            switch ($type) {
-                case 'month':
-                    $stat_date = explode('-', $stat_date);
-                    $stat_date[1] = $months[$stat_date[1] - 1];
-                    $stat_date = implode(' ', $stat_date);
-                    break;
-                case 'day':
-                    $stat_date = $week_days[$stat_date];
-                    break;
-            }
-            $result_last_x[$stat_date] = $obj->number_of_logins;
-        }
-        Statistics::print_stats(get_lang('LastLogins').' ('.$period.')', $result_last_x, true);
-        flush(); //flush web request at this point to see something already while the full data set is loading
-        echo '<br />';
-        $res = Database::query($sql);
-        $result = array();
-        while ($obj = Database::fetch_object($res)) {
-            $stat_date = $obj->stat_date;
-            switch ($type) {
-                case 'month':
-                    $stat_date = explode('-', $stat_date);
-                    $stat_date[1] = $months[$stat_date[1] - 1];
-                    $stat_date = implode(' ', $stat_date);
-                    break;
-                case 'day':
-                    $stat_date = $week_days[$stat_date];
-                    break;
-            }
-            $result[$stat_date] = $obj->number_of_logins;
-        }
-        Statistics::print_stats(get_lang('AllLogins').' ('.$period.')', $result, true);
-    }
-
-    /**
-     * Print the number of recent logins
-     */
-    static function print_recent_login_stats() {
-        global $_configuration;
-        $total_logins = array();
-        $table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-        $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-        $current_url_id = api_get_current_access_url_id();
-        if ($_configuration['multiple_access_urls']) {
-            $table_url = ", $access_url_rel_user_table";
-            $where_url = " AND login_user_id=user_id AND access_url_id='".$current_url_id."'";
-        } else {
-            $table_url = '';
-            $where_url='';
-        }
-        $sql[get_lang('Thisday')]      = "SELECT count(login_user_id) AS number FROM $table $table_url WHERE DATE_ADD(login_date, INTERVAL 1 DAY) >= NOW() $where_url";
-        $sql[get_lang('Last7days')]  = "SELECT count(login_user_id) AS number  FROM $table $table_url WHERE DATE_ADD(login_date, INTERVAL 7 DAY) >= NOW() $where_url";
-        $sql[get_lang('Last31days')] = "SELECT count(login_user_id) AS number  FROM $table $table_url WHERE DATE_ADD(login_date, INTERVAL 31 DAY) >= NOW() $where_url";
-        $sql[get_lang('Total')]      = "SELECT count(login_user_id) AS number  FROM $table $table_url WHERE 1=1 $where_url";
-        foreach ($sql as $index => $query) {
-            $res = Database::query($query);
-            $obj = Database::fetch_object($res);
-            $total_logins[$index] = $obj->number;
-        }
-        Statistics::print_stats(get_lang('Logins'),$total_logins,false);
-    }
-    /**
-     * Show some stats about the accesses to the different course tools
-     */
-    static function print_tool_stats() {
-        global $_configuration;
-        $table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ACCESS);
-        $access_url_rel_course_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-        $current_url_id = api_get_current_access_url_id();
-
-        $tools = array('announcement','assignment','calendar_event',
-            'chat','conference','course_description','document',
-            'dropbox','group','learnpath','link','quiz',
-            'student_publication','user','forum');
-        $tool_names = array();
-        foreach ($tools as $tool) {
-            $tool_names[$tool] = get_lang(ucfirst($tool), '');
-        }
-        if ($_configuration['multiple_access_urls']) {
-            $sql = "SELECT access_tool, count( access_id ) ".
-                   "AS number_of_logins FROM $table, $access_url_rel_course_table ".
-                   "WHERE access_tool IN ('".implode("','",$tools)."') AND  course_code = access_cours_code AND access_url_id='".$current_url_id."' ".
-                   "GROUP BY access_tool ";
-        } else {
-            $sql = "SELECT access_tool, count( access_id ) ".
-                "AS number_of_logins FROM $table ".
-                "WHERE access_tool IN ('".implode("','",$tools)."') ".
-                "GROUP BY access_tool ";
-        }
-        $res = Database::query($sql);
-        $result = array();
-        while ($obj = Database::fetch_object($res)) {
-            $result[$tool_names[$obj->access_tool]] = $obj->number_of_logins;
-        }
-        Statistics::print_stats(get_lang('PlatformToolAccess'),$result,true);
-    }
-
-    /**
-     * Show some stats about the number of courses per language
-     */
-    static function print_course_by_language_stats() {
-        global $_configuration;
-        $table = Database :: get_main_table(TABLE_MAIN_COURSE);
-        $access_url_rel_course_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-        $current_url_id = api_get_current_access_url_id();
-        if ($_configuration['multiple_access_urls']) {
-            $sql = "SELECT course_language, count( c.code ) AS number_of_courses ".
-                   "FROM $table as c, $access_url_rel_course_table as u
-            		WHERE u.course_code=c.code AND access_url_id='".$current_url_id."'
-            		GROUP BY course_language ORDER BY number_of_courses DESC";
-        } else {
-            $sql = "SELECT course_language, count( code ) AS number_of_courses ".
-                   "FROM $table GROUP BY course_language ORDER BY number_of_courses DESC";
-        }
-        $res = Database::query($sql);
-        $result = array();
-        while ($obj = Database::fetch_object($res)) {
-            $result[$obj->course_language] = $obj->number_of_courses;
-        }
-        Statistics::print_stats(get_lang('CountCourseByLanguage'),$result,true);
-    }
-
-    /**
-     * Shows the number of users having their picture uploaded in Dokeos.
-     */
-    static function print_user_pictures_stats() {
-        global $_configuration;
-        $user_table = Database :: get_main_table(TABLE_MAIN_USER);
-        $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-        $current_url_id = api_get_current_access_url_id();
-        if ($_configuration['multiple_access_urls']) {
-            $url_condition =  ", $access_url_rel_user_table as url WHERE url.user_id=u.user_id AND access_url_id='".$current_url_id."'";
-            $url_condition2 = " AND url.user_id=u.user_id AND access_url_id='".$current_url_id."'";
-            $table = ", $access_url_rel_user_table as url ";
-        }
-        $sql = "SELECT COUNT(*) AS n FROM $user_table as u ".$url_condition;
-        $res = Database::query($sql);
-        $count1 = Database::fetch_object($res);
-        $sql = "SELECT COUNT(*) AS n FROM $user_table as u $table ".
-               "WHERE LENGTH(picture_uri) > 0 $url_condition2";
-        $res = Database::query($sql);
-        $count2 = Database::fetch_object($res);
-        // #users without picture
-        $result[get_lang('No')] = $count1->n - $count2->n;
-        $result[get_lang('Yes')] = $count2->n; // #users with picture
-        Statistics::print_stats(get_lang('CountUsers').' ('.get_lang('UserPicture').')',$result,true);
-    }
-
-    static function print_activities_stats() {
-
-        echo '<h4>'.get_lang('ImportantActivities').'</h4>';
-
-        // Create a search-box
-        $form = new FormValidator('search_simple','get',api_get_path(WEB_CODE_PATH).'admin/statistics/index.php','','width=200px',false);
-        $renderer =& $form->defaultRenderer();
-        $renderer->setElementTemplate('<span>{element}</span> ');
-        $form->addElement('hidden','report','activities');
-        $form->addElement('hidden','activities_direction','DESC');
-        $form->addElement('hidden','activities_column','4');
-        $form->addElement('text','keyword',get_lang('keyword'));
-        $form->addElement('style_submit_button', 'submit', get_lang('Search'),'class="search"');
-        echo '<div class="actions">';
-            $form->display();
-        echo '</div>';
-
-        $table = new SortableTable('activities', array('Statistics','get_number_of_activities'), array('Statistics','get_activities_data'),5,50,'DESC');
-        $parameters = array();
-
-        $parameters['report'] = 'activities';
-        if (isset($_GET['keyword'])) {
-            $parameters['keyword'] = Security::remove_XSS($_GET['keyword']);
-        }
-
-        $table->set_additional_parameters($parameters);
-        $table->set_header(0, get_lang('EventType'));
-        $table->set_header(1, get_lang('DataType'));
-        $table->set_header(2, get_lang('Value'));
-        $table->set_header(3, get_lang('UserName'));
-        $table->set_header(4, get_lang('IPAddress'));
-        $table->set_header(5, get_lang('Date'));
-        $table->display();
-    }
-
-    /**
-     * Shows statistics about the time of last visit to each course.
-     */
-    static function print_course_last_visit() {
-        global $_configuration;
-        $access_url_rel_course_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-        $current_url_id = api_get_current_access_url_id();
-
-        $columns[0] = 'access_cours_code';
-        $columns[1] = 'access_date';
-        $sql_order[SORT_ASC] = 'ASC';
-        $sql_order[SORT_DESC] = 'DESC';
-        $per_page = isset($_GET['per_page'])?intval($_GET['per_page']) : 10;
-        $page_nr = isset($_GET['page_nr'])?intval($_GET['page_nr']) : 1;
-        $column = isset($_GET['column'])?intval($_GET['column']) : 0;
-        $date_diff = isset($_GET['date_diff'])?intval($_GET['date_diff']) : 60;
-            if (!in_array($_GET['direction'],array(SORT_ASC,SORT_DESC))) {
-                $direction = SORT_ASC;
-            } else {
-                $direction = isset($_GET['direction']) ? $_GET['direction'] : SORT_ASC;
-            }
-        $form = new FormValidator('courselastvisit', 'get');
-        $form->addElement('hidden','report','courselastvisit');
-        $form->add_textfield('date_diff',get_lang('Days'),true);
-        $form->addRule('date_diff','InvalidNumber','numeric');
-        $form->addElement('style_submit_button', 'submit', get_lang('Search'),'class="search"');
-        if (!isset($_GET['date_diff'])) {
-            $defaults['date_diff'] = 60;
-        } else {
-            $defaults['date_diff'] = Security::remove_XSS($_GET['date_diff']);
-        }
-        $form->setDefaults($defaults);
-        $form->display();
-        $values = $form->exportValues();
-        $date_diff = $values['date_diff'];
-        $table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
-        if ($_configuration['multiple_access_urls']) {
-            $sql = "SELECT * FROM $table, $access_url_rel_course_table WHERE course_code = access_cours_code AND access_url_id='".$current_url_id."' ".
-                   "GROUP BY access_cours_code ".
-                   "HAVING access_cours_code <> '' ".
-                   "AND DATEDIFF( '".date('Y-m-d h:i:s')."' , access_date ) <= ". $date_diff;
-        } else {
-            $sql = "SELECT * FROM $table ".
-                   "GROUP BY access_cours_code ".
-                   "HAVING access_cours_code <> '' ".
-                   "AND DATEDIFF( '".date('Y-m-d h:i:s')."' , access_date ) <= ". $date_diff;
-        }
-        $res = Database::query($sql);
-        $number_of_courses = Database::num_rows($res);
-        $sql .= ' ORDER BY '.$columns[$column].' '.$sql_order[$direction];
-        $from = ($page_nr -1) * $per_page;
-        $sql .= ' LIMIT '.$from.','.$per_page;
-        echo '<p>'.get_lang('LastAccess').' &gt;= '.$date_diff.' '.get_lang('Days').'</p>';
-        $res = Database::query($sql);
-        if (Database::num_rows($res) > 0) {
-            $courses = array ();
-            while ($obj = Database::fetch_object($res)) {
-                $course = array ();
-                $course[]= '<a href="'.api_get_path(WEB_PATH).'courses/'.$obj->access_cours_code.'">'.$obj->access_cours_code.' <a>';
-                                //Allow sort by date hiding the numerical date
-                $course[] = '<span style="display:none;">'.$obj->access_date.'</span>'.api_convert_and_format_date($obj->access_date);
-                $courses[] = $course;
-            }
-            $parameters['date_diff'] = $date_diff;
-            $parameters['report'] = 'courselastvisit';
-            $table_header[] = array (get_lang("CourseCode"), true);
-            $table_header[] = array (get_lang("LastAccess"), true);
-            Display :: display_sortable_table($table_header, $courses, array ('column'=>$column,'direction'=>$direction), array (), $parameters);
-        } else {
-            echo get_lang('NoSearchResults');
-        }
-    }
-
-    /**
-     * Displays the statistics of the messages sent and received by each user in the social network
-     * @param string    Type of message: 'sent' or 'received'
-     * @return array    Message list
-     */
-    static function get_messages($message_type) {
-        global $_configuration;
-        $message_table 				= Database::get_main_table(TABLE_MAIN_MESSAGE);
-        $user_table 				= Database::get_main_table(TABLE_MAIN_USER);
-        $access_url_rel_user_table	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-
-        $current_url_id 			= api_get_current_access_url_id();
-
-        switch ($message_type) {
-            case 'sent':
-                $field = 'user_sender_id';
-                break;
-            case 'received':
-                $field = 'user_receiver_id';
-                break;
-        }
-        if ($_configuration['multiple_access_urls']) {
-
-            $sql = "SELECT lastname, firstname, username, COUNT($field) AS count_message ".
-                "FROM ".$access_url_rel_user_table." as url, ".$message_table." m ".
-                "LEFT JOIN ".$user_table." u ON m.$field = u.user_id ".
-                "WHERE  url.user_id = m.$field AND  access_url_id='".$current_url_id."' ".
-                "GROUP BY m.$field ORDER BY count_message DESC ";
-        } else {
-            $sql = "SELECT lastname, firstname, username, COUNT($field) AS count_message ".
-                "FROM ".$message_table." m ".
-                "LEFT JOIN ".$user_table." u ON m.$field = u.user_id ".
-                "GROUP BY m.$field ORDER BY count_message DESC ";
-        }
-        $res = Database::query($sql);
-        $messages_sent = array();
-        while ($messages = Database::fetch_array($res)) {
-            if (empty($messages['username'])) {
-                $messages['username'] = get_lang('Unknown');
-            }
-            $users = api_get_person_name($messages['firstname'], $messages['lastname']).'<br />('.$messages['username'].')';
-            $messages_sent[$users] = $messages['count_message'];
-        }
-        return $messages_sent;
-    }
-
-    /**
-     * Count the number of friends for social network users
-     */
-    static function get_friends() {
-        global $_configuration;
-        $user_friend_table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
-        $user_table = Database::get_main_table(TABLE_MAIN_USER);
-        $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-        $current_url_id = api_get_current_access_url_id();
-
-        if ($_configuration['multiple_access_urls']) {
-            $sql = "SELECT lastname, firstname, username, COUNT(friend_user_id) AS count_friend ".
-                "FROM ".$access_url_rel_user_table." as url, ".$user_friend_table." uf ".
-                "LEFT JOIN ".$user_table." u ON uf.user_id = u.user_id ".
-                "WHERE uf.relation_type <> '".USER_RELATION_TYPE_RRHH."' AND uf.user_id = url.user_id AND  access_url_id='".$current_url_id."' ".
-                "GROUP BY uf.user_id ORDER BY count_friend DESC ";
-        } else {
-            $sql = "SELECT lastname, firstname, username, COUNT(friend_user_id) AS count_friend ".
-                "FROM ".$user_friend_table." uf ".
-                "LEFT JOIN ".$user_table." u ON uf.user_id = u.user_id ".
-                "WHERE uf.relation_type <> '".USER_RELATION_TYPE_RRHH."' ".
-                "GROUP BY uf.user_id ORDER BY count_friend DESC ";
-        }
-        $res = Database::query($sql);
-        $list_friends = array();
-        while ($friends = Database::fetch_array($res)) {
-            $users = api_get_person_name($friends['firstname'], $friends['lastname']).'<br />('.$friends['username'].')';
-            $list_friends[$users] = $friends['count_friend'];
-        }
-        return $list_friends;
-    }
-
-    /**
-     * Print the number of users that didn't login for a certain period of time
-     */
-    static function print_users_not_logged_in_stats() {
-        global $_configuration;
-        $total_logins = array();
-        $table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-        $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-        $current_url_id = api_get_current_access_url_id();
-        $total = self::count_users();
-        if ($_configuration['multiple_access_urls']) {
-            $table_url = ", $access_url_rel_user_table";
-            $where_url = " AND login_user_id=user_id AND access_url_id='".$current_url_id."'";
-        } else {
-            $table_url = '';
-            $where_url='';
-        }
-        $sql[get_lang('Thisday')]    =
-            "SELECT count(distinct(login_user_id)) AS number ".
-            " FROM $table $table_url ".
-            " WHERE DATE_ADD(login_date, INTERVAL 1 DAY) >= NOW() $where_url";
-        $sql[get_lang('Last7days')]  =
-            "SELECT count(distinct(login_user_id)) AS number ".
-            " FROM $table $table_url ".
-            " WHERE DATE_ADD(login_date, INTERVAL 7 DAY) >= NOW() $where_url";
-        $sql[get_lang('Last31days')] =
-            "SELECT count(distinct(login_user_id)) AS number ".
-            " FROM $table $table_url ".
-            " WHERE DATE_ADD(login_date, INTERVAL 31 DAY) >= NOW() $where_url";
-        $sql[sprintf(get_lang('LastXMonths'),6)] =
-            "SELECT count(distinct(login_user_id)) AS number ".
-            " FROM $table $table_url ".
-            " WHERE DATE_ADD(login_date, INTERVAL 6 MONTH) >= NOW() $where_url";
-        $sql[get_lang('NeverConnected')]      =
-            "SELECT count(distinct(login_user_id)) AS number ".
-            " FROM $table $table_url WHERE 1=1 $where_url";
-        foreach ($sql as $index => $query) {
-            $res = Database::query($query);
-            $obj = Database::fetch_object($res);
-            $r = $total - $obj->number;
-            $total_logins[$index] = $r < 0 ? 0 : $r;
-        }
-        Statistics::print_stats(get_lang('StatsUsersDidNotLoginInLastPeriods'),$total_logins,false);
-    }
-}

+ 0 - 181
main/admin/style_preview.php

@@ -1,181 +0,0 @@
-<?php
-/* For licensing terms, see /chamilo_license.txt */
-/**
- * Deprecated - used to show a preview of a given stylesheet. Now replaced.
- * @package chamilo.admin
- */
-/**
- * Code
- */
-// @deprecated This page is not used
-
-exit;
-$language_file = array('create_course', 'courses', 'admin');
-
-require_once '../inc/global.inc.php';
-
-// Setting the section (for the tabs).
-$this_section = SECTION_PLATFORM_ADMIN;
-
-// Access restriction.
-api_protect_admin_script();
-
-// Manipulation of the platform-wide css setting.
-if (isset($_GET['style']) && $_GET['style'] != '') {
-	$_setting['stylesheets'] = Security::remove_XSS($_GET['style']);
-}
-
-// Hiding the link "Teacher/Student view", it is not needed to be shown here.
-$_setting['student_view_enabled'] = 'false';
-
-require_once api_get_path(INCLUDE_PATH).'header.inc.php';
-
-$week_days_short = api_get_week_days_short();
-$months_long = api_get_months_long();
-
-?>
-  <div class="maincontent" id="content">
-    <h3><?php echo get_lang('Title'); ?></h3>
-    <div id="courseintro">
-      <p><?php echo get_lang('IntroductionText'); ?></p>
-    </div>
-    <div id="courseintro_icons">
-    <a href="#"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a><a href="#"><?php Display::display_icon('delete.gif', get_lang('Delete')); ?></a></div>
-    <div class="normal-message">Normal Message</div>
-    <div class="confirmation-message">Confirmation Message</div>
-    <div class="warning-message">Warning Message</div>
-    <div class="error-message">Error Message</div>
-    <table width="750">
-      <tr>
-        <td>
-        <table>
-            <tr>
-              <td width="220">
-              <table id="smallcalendar" class="data_table">
-                  <tr id="title">
-                    <td width="10%"><a href="#"><?php Display::display_icon('action_prev.png'); ?></a></td>
-                    <td width="80%" colspan="5" align="center"><?php echo $months_long[6]; ?> 2010</td>
-                    <td width="10%"><a href="#"><?php Display::display_icon('action_next.png'); ?></a></td>
-                  </tr>
-                  <tr>
-                    <td class="weekdays"><?php echo $week_days_short[1]; ?></td>
-                    <td class="weekdays"><?php echo $week_days_short[2]; ?></td>
-                    <td class="weekdays"><?php echo $week_days_short[3]; ?></td>
-                    <td class="weekdays"><?php echo $week_days_short[4]; ?></td>
-                    <td class="weekdays"><?php echo $week_days_short[5]; ?></td>
-                    <td class="weekdays"><?php echo $week_days_short[6]; ?></td>
-                    <td class="weekdays"><?php echo $week_days_short[0]; ?></td>
-                  </tr>
-                  <tr>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td class="days_weekend">1</td>
-                  </tr>
-                  <tr>
-                    <td class="days_week">2</td>
-                    <td class="days_week">3</td>
-                    <td class="days_week">4</td>
-                    <td class="days_week">5</td>
-                    <td class="days_week">6</td>
-                    <td class="days_weekend">7</td>
-                    <td class="days_weekend">8</td>
-                  </tr>
-                  <tr>
-                    <td class="days_week">9</td>
-                    <td class="days_week">10</td>
-                    <td class="days_week">11</td>
-                    <td class="days_week">12</td>
-                    <td class="days_week">13</td>
-                    <td class="days_weekend">14</td>
-                    <td class="days_weekend">15</td>
-                  </tr>
-                  <tr>
-                    <td class="days_week">16</td>
-                    <td class="days_week">17</td>
-                    <td class="days_week">18</td>
-                    <td class="days_week">19</td>
-                    <td class="days_week">20</td>
-                    <td class="days_weekend">21</td>
-                    <td class="days_weekend">22</td>
-                  </tr>
-                  <tr>
-                    <td class="days_week">23</td>
-                    <td class="days_today">24</td>
-                    <td class="days_week">25</td>
-                    <td class="days_week">26</td>
-                    <td class="days_week">27</td>
-                    <td class="days_weekend">28</td>
-                    <td class="days_weekend">29</td>
-                  </tr>
-                  <tr>
-                    <td class="days_week">30</td>
-                    <td class="days_week">31</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                    <td>&nbsp;</td>
-                  </tr>
-                </table>
-              </td>
-            </tr>
-          </table>
-        </td>
-        <td width="500">
-          <table width="100%">
-            <tr>
-              <td></td>
-              <td align="right"></td>
-            </tr>
-          </table>
-          <table class="data_table" style="width: 250px;">
-            <tr>
-              <th style="width: 50%;"><a href="#"><?php echo get_lang('FirstName'); ?></a>&nbsp;&#8595; </th>
-              <th><a href="#"><?php echo get_lang('LastName'); ?></a></th>
-            </tr>
-            <tr class="row_odd">
-              <td>Julio</td>
-              <td>Montoya</td>
-            </tr>
-            <tr class="row_even">
-              <td>Yannick</td>
-              <td>Warnier</td>
-            </tr>
-          </table>
-          <table width="100%">
-            <tr>
-              <td></td>
-              <td align="right"></td>
-            </tr>
-          </table>
-        </td>
-      </tr>
-    </table>
-  </div>
-  <div class="menu" id="menu">
-    <form action="#" method="post" id="formLogin" name="formLogin"><br />
-      <label><?php echo get_lang('UserName'); ?></label><br />
-      <input type="text" name="login" id="login" size="15" value="" /><br />
-      <label><?php echo get_lang('Password'); ?></label><br />
-      <input type="password" name="password" id="password" size="15" /><br />
-  	  <button class="login" type="submit" name="submitAuth"disabled="disabled" ><?php echo get_lang('LoginEnter'); ?></button>
-  	  <div class="clear">
-        &nbsp;
-  	  </div>
-    </form>
-    <div class="menusection"><span class="menusectioncaption"><?php echo get_lang('User'); ?></span>
-      <ul class="menulist">
-        <li><a href="#"><?php echo get_lang('CourseManagement'); ?></a></li>
-        <li><a href="#"><?php echo get_lang('CourseCreate'); ?></a></li>
-      </ul>
-    </div>
-    <div class="note"><b>Example notice</b><br />
-      To modify this notice, go to the administration area of the portal.</div>
-  </div>
-<?php
-Display::display_footer();
-?>

+ 1 - 3
main/admin/user_add.php

@@ -10,9 +10,7 @@ $cidReset = true;
 // Including necessary libraries.
 require_once '../inc/global.inc.php';
 $libpath = api_get_path(LIBRARY_PATH);
-require_once $libpath.'fileManage.lib.php';
 require_once $libpath.'fileUpload.lib.php';
-require_once $libpath.'mail.lib.inc.php';
 
 // Section for the tabs
 $this_section = SECTION_PLATFORM_ADMIN;
@@ -212,7 +210,7 @@ $form->addElement('radio', 'active', '', get_lang('Inactive'), 0);
 
 $extra_data = UserManager::get_extra_user_data(0, true);
 
-$return_params = UserManager::set_extra_fields_in_form($form, $extra_data, 'user_add');
+$return_params = ExtraField::set_extra_fields_in_form($form, $extra_data, 'user_add', false, null, 'user');
 $jquery_ready_content = $return_params['jquery_ready_content'];
 
 // the $jquery_ready_content variable collects all functions that will be load in the $(document).ready javascript function

+ 1 - 3
main/admin/user_edit.php

@@ -68,9 +68,7 @@ function show_image(image,width,height) {
 </script>';
 
 $libpath = api_get_path(LIBRARY_PATH);
-require_once $libpath.'fileManage.lib.php';
 require_once $libpath.'fileUpload.lib.php';
-require_once $libpath.'mail.lib.inc.php';
 
 $noPHP_SELF = true;
 $tool_name = get_lang('ModifyUserInfo');
@@ -268,7 +266,7 @@ if (!$user_data['platform_admin']) {
 
 
 // EXTRA FIELDS
-$return_params = UserManager::set_extra_fields_in_form($form, $extra_data, 'user_edit', true, $user_id);
+$return_params = ExtraField::set_extra_fields_in_form($form, $extra_data, 'user_edit', true, $user_id, 'user');
 $jquery_ready_content = $return_params['jquery_ready_content'];
 
 // the $jquery_ready_content variable collects all functions that will be load in the $(document).ready javascript function

+ 266 - 280
main/admin/user_fields.php

@@ -1,8 +1,9 @@
 <?php
+
 /* For licensing terms, see /license.txt */
 /**
-*	@package chamilo.admin
-*/
+ * 	@package chamilo.admin
+ */
 // name of the language file that needs to be included
 $language_file = array('admin', 'registration');
 $cidReset = true;
@@ -11,170 +12,167 @@ $cidReset = true;
 require '../inc/global.inc.php';
 
 // section for the tabs
-$this_section=SECTION_PLATFORM_ADMIN;
+$this_section = SECTION_PLATFORM_ADMIN;
 
 // user permissions
 api_protect_admin_script();
 
 // Database table definitions
-$table_admin	= Database :: get_main_table(TABLE_MAIN_ADMIN);
-$table_user 	= Database :: get_main_table(TABLE_MAIN_USER);
-$table_uf	 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD);
-$table_uf_opt 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-$table_uf_val 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
+$table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
+$table_user = Database :: get_main_table(TABLE_MAIN_USER);
+$table_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
+$table_uf_opt = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
+$table_uf_val = Database :: get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
 
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 
 // Display form
-if(1)
-{
-	$tool_name = get_lang('UserFields');
-	Display :: display_header($tool_name, "");
-	//api_display_tool_title($tool_name);
-	if (isset ($_GET['action']))
-	{
-		$check = Security::check_token('get');
-		if($check) {
-			switch ($_GET['action']) {
-				case 'show_message' :
-					Display :: display_normal_message($_GET['message']);
-					break;
-				case 'show_field' :
-					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_visible'=>'1'))) {
-						Display :: display_confirmation_message(get_lang('FieldShown'));
-					} else {
-						Display :: display_error_message(get_lang('CannotShowField'));
-					}
-					break;
-				case 'hide_field' :
-					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_visible'=>'0'))) {
-						Display :: display_confirmation_message(get_lang('FieldHidden'));
-					} else {
-						Display :: display_error_message(get_lang('CannotHideField'));
-					}
-					break;
-				case 'thaw_field' :
-					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_changeable'=>'1'))) {
-						Display :: display_confirmation_message(get_lang('FieldMadeChangeable'));
-					} else {
-						Display :: display_error_message(get_lang('CannotMakeFieldChangeable'));
-					}
-					break;
-				case 'freeze_field' :
-					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_changeable'=>'0'))) {
-						Display :: display_confirmation_message(get_lang('FieldMadeUnchangeable'));
-					} else {
-						Display :: display_error_message(get_lang('CannotMakeFieldUnchangeable'));
-					}
-					break;
-				case 'moveup' :
-					if (api_is_platform_admin() && !empty($_GET['field_id'])) {
-						if (move_user_field('moveup', $_GET['field_id'])) {
-							Display :: display_confirmation_message(get_lang('FieldMovedUp'));
-						} else {
-							Display :: display_error_message(get_lang('CannotMoveField'));
-						}
-					}
-					break;
-				case 'movedown' :
-					if (api_is_platform_admin() && !empty($_GET['field_id'])) {
-						if (move_user_field('movedown', $_GET['field_id'])) {
-							Display :: display_confirmation_message(get_lang('FieldMovedDown'));
-						} else {
-							Display :: display_error_message(get_lang('CannotMoveField'));
-						}
-					}
-					break;
-				case 'filter_on' :
-					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_filter'=>'1'))) {
-						Display :: display_confirmation_message(get_lang('FieldFilterSetOn'));
-					} else {
-						Display :: display_error_message(get_lang('CannotShowField'));
-					}
-					break;
-				case 'filter_off' :
-					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_filter'=>'0'))) {
-						Display :: display_confirmation_message(get_lang('FieldFilterSetOff'));
-					} else {
-						Display :: display_error_message(get_lang('CannotShowField'));
-					}
-					break;
-
-				case 'delete':
-					if (api_is_platform_admin() && !empty($_GET['field_id'])) {
-						if (delete_user_fields($_GET['field_id'])) {
-							Display :: display_confirmation_message(get_lang('FieldDeleted'));
-						} else {
-							Display :: display_error_message(get_lang('CannotDeleteField'));
-						}
-					}
-					break;
-			}
-			Security::clear_token();
-		}
-	}
-	if (isset ($_POST['action'])) {
-		$check = Security::check_token('get');
-		if($check) {
-			switch ($_POST['action']) {
-				default:
-					break;
-			}
-			Security::clear_token();
-		}
-	}
-
-	// Create an add-field box
-	$form = new FormValidator('add_field','post','','',null,false);
-	$renderer =& $form->defaultRenderer();
-	$renderer->setElementTemplate('<span>{element}</span> ');
-	//$form->addElement('text','label',get_lang('FieldLabel'));
-	//$form->addElement('text','type',get_lang('FieldType'));
-	//$form->addElement('text','title',get_lang('FieldTitle'));
-	//$form->addElement('text','default',get_lang('FieldDefaultValue'));
-	//$form->addElement('submit','submit',get_lang('Search'));
-	$form->addElement('static','search_advanced_link',null,'<a href="user_fields_add.php?action=fill">'.Display::return_icon('add_user_fields.png', get_lang('AddUserField'),'',ICON_SIZE_MEDIUM).'</a>');
-	echo '<div class="actions">';
-	$form->display();
-	echo '</div>';
-
-	// Create a sortable table with user-data
-	$parameters['sec_token'] = Security::get_token();
-	//$column_show  = array(1,1,1,1,1,1,1,1,1,0,0);
-	//$column_order = array(1,2,3,4,5,6,7,8,9,10,11);
-	$extra_fields = UserManager::get_extra_fields();
-	$number_of_extra_fields = count($extra_fields);
-
-    $table = new SortableTable('user_field', array('UserManager','get_number_of_extra_fields'), array('UserManager','get_extra_fields'),5);
-	$table->set_additional_parameters($parameters);
-	$table->set_header(0, '', false);
-	$table->set_header(1, get_lang('FieldLabel'), false);
-	$table->set_header(2, get_lang('FieldType'), false);
-	$table->set_header(3, get_lang('FieldTitle'),false);
-	$table->set_header(4, get_lang('FieldDefaultValue'),false);
-	$table->set_header(5, get_lang('FieldOrder'), false);
-	$table->set_header(6, get_lang('FieldVisibility'), false);
-	$table->set_header(7, get_lang('FieldChangeability'), false);
-	$table->set_header(8, get_lang('FieldFilter'), false);
-	$table->set_header(9, get_lang('Modify'), false);
-	$table->set_column_filter(5, 'order_filter');
-	$table->set_column_filter(6, 'modify_visibility');
-	$table->set_column_filter(7, 'modify_changeability');
-	$table->set_column_filter(8, 'modify_field_filter');
-	$table->set_column_filter(9, 'edit_filter');
-	$table->set_column_filter(2, 'type_filter');
-	$table->display();
+$tool_name = get_lang('UserFields');
+Display :: display_header($tool_name);
+
+if (isset($_GET['action'])) {
+    $check = Security::check_token('get');
+    if ($check) {
+        switch ($_GET['action']) {
+            case 'show_message' :
+                Display :: display_normal_message($_GET['message']);
+                break;
+            case 'show_field' :
+                if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'], array('field_visible' => '1'))) {
+                    Display :: display_confirmation_message(get_lang('FieldShown'));
+                } else {
+                    Display :: display_error_message(get_lang('CannotShowField'));
+                }
+                break;
+            case 'hide_field' :
+                if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'], array('field_visible' => '0'))) {
+                    Display :: display_confirmation_message(get_lang('FieldHidden'));
+                } else {
+                    Display :: display_error_message(get_lang('CannotHideField'));
+                }
+                break;
+            case 'thaw_field' :
+                if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'], array('field_changeable' => '1'))) {
+                    Display :: display_confirmation_message(get_lang('FieldMadeChangeable'));
+                } else {
+                    Display :: display_error_message(get_lang('CannotMakeFieldChangeable'));
+                }
+                break;
+            case 'freeze_field' :
+                if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'], array('field_changeable' => '0'))) {
+                    Display :: display_confirmation_message(get_lang('FieldMadeUnchangeable'));
+                } else {
+                    Display :: display_error_message(get_lang('CannotMakeFieldUnchangeable'));
+                }
+                break;
+            case 'moveup' :
+                if (api_is_platform_admin() && !empty($_GET['field_id'])) {
+                    if (move_user_field('moveup', $_GET['field_id'])) {
+                        Display :: display_confirmation_message(get_lang('FieldMovedUp'));
+                    } else {
+                        Display :: display_error_message(get_lang('CannotMoveField'));
+                    }
+                }
+                break;
+            case 'movedown' :
+                if (api_is_platform_admin() && !empty($_GET['field_id'])) {
+                    if (move_user_field('movedown', $_GET['field_id'])) {
+                        Display :: display_confirmation_message(get_lang('FieldMovedDown'));
+                    } else {
+                        Display :: display_error_message(get_lang('CannotMoveField'));
+                    }
+                }
+                break;
+            case 'filter_on' :
+                if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'], array('field_filter' => '1'))) {
+                    Display :: display_confirmation_message(get_lang('FieldFilterSetOn'));
+                } else {
+                    Display :: display_error_message(get_lang('CannotShowField'));
+                }
+                break;
+            case 'filter_off' :
+                if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'], array('field_filter' => '0'))) {
+                    Display :: display_confirmation_message(get_lang('FieldFilterSetOff'));
+                } else {
+                    Display :: display_error_message(get_lang('CannotShowField'));
+                }
+                break;
+
+            case 'delete':
+                if (api_is_platform_admin() && !empty($_GET['field_id'])) {
+                    if (delete_user_fields($_GET['field_id'])) {
+                        Display :: display_confirmation_message(get_lang('FieldDeleted'));
+                    } else {
+                        Display :: display_error_message(get_lang('CannotDeleteField'));
+                    }
+                }
+                break;
+        }
+        Security::clear_token();
+    }
+}
+if (isset($_POST['action'])) {
+    $check = Security::check_token('get');
+    if ($check) {
+        switch ($_POST['action']) {
+            default:
+                break;
+        }
+        Security::clear_token();
+    }
 }
 
+// Create an add-field box
+$form = new FormValidator('add_field', 'post', '', '', null, false);
+$renderer = & $form->defaultRenderer();
+$renderer->setElementTemplate('<span>{element}</span> ');
+//$form->addElement('text','label',get_lang('FieldLabel'));
+//$form->addElement('text','type',get_lang('FieldType'));
+//$form->addElement('text','title',get_lang('FieldTitle'));
+//$form->addElement('text','default',get_lang('FieldDefaultValue'));
+//$form->addElement('submit','submit',get_lang('Search'));
+$form->addElement('static', 'search_advanced_link', null, '<a href="user_fields_add.php?action=fill">' . Display::return_icon('add_user_fields.png', get_lang('AddUserField'), '', ICON_SIZE_MEDIUM) . '</a>');
+echo '<div class="actions">';
+$form->display();
+echo '</div>';
+
+// Create a sortable table with user-data
+$parameters['sec_token'] = Security::get_token();
+//$column_show  = array(1,1,1,1,1,1,1,1,1,0,0);
+//$column_order = array(1,2,3,4,5,6,7,8,9,10,11);
+$extra_fields = UserManager::get_extra_fields();
+$number_of_extra_fields = count($extra_fields);
+
+$table = new SortableTable('user_field', array('UserManager', 'get_number_of_extra_fields'), array('UserManager', 'get_extra_fields'), 5);
+$table->set_additional_parameters($parameters);
+$table->set_header(0, '', false);
+$table->set_header(1, get_lang('FieldLabel'), false);
+$table->set_header(2, get_lang('FieldType'), false);
+$table->set_header(3, get_lang('FieldTitle'), false);
+$table->set_header(4, get_lang('FieldDefaultValue'), false);
+$table->set_header(5, get_lang('FieldOrder'), false);
+$table->set_header(6, get_lang('FieldVisibility'), false);
+$table->set_header(7, get_lang('FieldChangeability'), false);
+$table->set_header(8, get_lang('FieldFilter'), false);
+$table->set_header(9, get_lang('Modify'), false);
+$table->set_column_filter(5, 'order_filter');
+$table->set_column_filter(6, 'modify_visibility');
+$table->set_column_filter(7, 'modify_changeability');
+$table->set_column_filter(8, 'modify_field_filter');
+$table->set_column_filter(9, 'edit_filter');
+$table->set_column_filter(2, 'type_filter');
+$table->display();
+
+
 Display::display_footer();
+
 //gateway functions to the UserManager methods (provided for SorteableTable callback mechanism)
-function get_number_of_extra_fields()
-{
-	return UserManager::get_number_of_extra_fields();
+function get_number_of_extra_fields() {
+    return UserManager::get_number_of_extra_fields();
 }
-function get_extra_fields($f,$n,$o,$d)
-{
-	return UserManager::get_extra_fields($f,$n,$o,$d);
+
+function get_extra_fields($f, $n, $o, $d) {
+    return UserManager::get_extra_fields($f, $n, $o, $d);
 }
 
 /**
@@ -189,7 +187,7 @@ function get_extra_fields($f,$n,$o,$d)
  */
 function type_filter($type) {
     $types = UserManager::get_user_field_types();
-	return $types[$type];
+    return $types[$type];
 }
 
 /**
@@ -204,23 +202,23 @@ function type_filter($type) {
  * @version July 2008
  * @since Dokeos 1.8.6
  */
-function order_filter($field_order,$url_params,$row)
-{
-	global $number_of_extra_fields;
-	$return = '';
-	// the up icon only has to appear when the row can be moved up (all but the first row)
-	if ($row[5]<>1) {
-		$return .= '<a href="'.api_get_self().'?action=moveup&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('up.gif', get_lang('Up')).'</a>';
-	} else {
-		$return .= Display::return_icon('blank.gif','',array('width'=>'21px'));
-	}
-
-	// the down icon only has to appear when the row can be moved down (all but the last row)
-	if ($row[5]<>$number_of_extra_fields) {
-		$return .= '<a href="'.api_get_self().'?action=movedown&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('down.gif', get_lang('Down')).'</a>';
-	}
-	return $return;
+function order_filter($field_order, $url_params, $row) {
+    global $number_of_extra_fields;
+    $return = '';
+    // the up icon only has to appear when the row can be moved up (all but the first row)
+    if ($row[5] <> 1) {
+        $return .= '<a href="' . api_get_self() . '?action=moveup&field_id=' . $row[0] . '&sec_token=' . $_SESSION['sec_token'] . '">' . Display::return_icon('up.gif', get_lang('Up')) . '</a>';
+    } else {
+        $return .= Display::return_icon('blank.gif', '', array('width' => '21px'));
+    }
+
+    // the down icon only has to appear when the row can be moved down (all but the last row)
+    if ($row[5] <> $number_of_extra_fields) {
+        $return .= '<a href="' . api_get_self() . '?action=movedown&field_id=' . $row[0] . '&sec_token=' . $_SESSION['sec_token'] . '">' . Display::return_icon('down.gif', get_lang('Down')) . '</a>';
+    }
+    return $return;
 }
+
 /**
  * Modify the visible field to show links and icons
  * @param	int 	The current visibility
@@ -228,10 +226,10 @@ function order_filter($field_order,$url_params,$row)
  * @param	array	The results row
  * @return	string	The link
  */
-function modify_visibility($visibility,$url_params,$row)
-{
-	return ($visibility?'<a href="'.api_get_self().'?action=hide_field&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('visible.gif', get_lang('Hide')).'</a>':'<a href="'.api_get_self().'?action=show_field&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('invisible.gif', get_lang('Show')).'</a>');
+function modify_visibility($visibility, $url_params, $row) {
+    return ($visibility ? '<a href="' . api_get_self() . '?action=hide_field&field_id=' . $row[0] . '&sec_token=' . $_SESSION['sec_token'] . '">' . Display::return_icon('visible.gif', get_lang('Hide')) . '</a>' : '<a href="' . api_get_self() . '?action=show_field&field_id=' . $row[0] . '&sec_token=' . $_SESSION['sec_token'] . '">' . Display::return_icon('invisible.gif', get_lang('Show')) . '</a>');
 }
+
 /**
  * Modify the changeability field to show links and icons
  * @param	int 	The current changeability
@@ -239,23 +237,21 @@ function modify_visibility($visibility,$url_params,$row)
  * @param	array	The results row
  * @return	string	The link
  */
-function modify_changeability($changeability,$url_params,$row)
-{
-	return ($changeability?'<a href="'.api_get_self().'?action=freeze_field&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('right.gif', get_lang('MakeUnchangeable')).'</a>':'<a href="'.api_get_self().'?action=thaw_field&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('wrong.gif', get_lang('MakeChangeable')).'</a>');
+function modify_changeability($changeability, $url_params, $row) {
+    return ($changeability ? '<a href="' . api_get_self() . '?action=freeze_field&field_id=' . $row[0] . '&sec_token=' . $_SESSION['sec_token'] . '">' . Display::return_icon('right.gif', get_lang('MakeUnchangeable')) . '</a>' : '<a href="' . api_get_self() . '?action=thaw_field&field_id=' . $row[0] . '&sec_token=' . $_SESSION['sec_token'] . '">' . Display::return_icon('wrong.gif', get_lang('MakeChangeable')) . '</a>');
 }
 
-function modify_field_filter ($changeability,$url_params,$row)
-{
-	return ($changeability?'<a href="'.api_get_self().'?action=filter_off&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('right.gif', get_lang('FilterOff')).'</a>':'' .
-						   '<a href="'.api_get_self().'?action=filter_on&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('wrong.gif', get_lang('FilterOn')).'</a>');
+function modify_field_filter($changeability, $url_params, $row) {
+    return ($changeability ? '<a href="' . api_get_self() . '?action=filter_off&field_id=' . $row[0] . '&sec_token=' . $_SESSION['sec_token'] . '">' . Display::return_icon('right.gif', get_lang('FilterOff')) . '</a>' : '' .
+                    '<a href="' . api_get_self() . '?action=filter_on&field_id=' . $row[0] . '&sec_token=' . $_SESSION['sec_token'] . '">' . Display::return_icon('wrong.gif', get_lang('FilterOn')) . '</a>');
 }
 
 function edit_filter($id, $url_params, $row) {
-	global $charset;
-	$return = '<a href="user_fields_add.php?action=edit&field_id='.$row[0].'&field_type='.$row[2].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('edit.png',get_lang('Edit')).'</a>';
-	$return .= ' <a href="'.api_get_self().'?action=delete&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.
-            Display::return_icon('delete.png',get_lang('Delete')).'</a>';
-	return $return;
+    global $charset;
+    $return = '<a href="user_fields_add.php?action=edit&field_id=' . $row[0] . '&field_type=' . $row[2] . '&sec_token=' . $_SESSION['sec_token'] . '">' . Display::return_icon('edit.png', get_lang('Edit')) . '</a>';
+    $return .= ' <a href="' . api_get_self() . '?action=delete&field_id=' . $row[0] . '&sec_token=' . $_SESSION['sec_token'] . '" onclick="javascript:if(!confirm(' . "'" . addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES, $charset)) . "'" . ')) return false;">' .
+            Display::return_icon('delete.png', get_lang('Delete')) . '</a>';
+    return $return;
 }
 
 /**
@@ -268,71 +264,64 @@ function edit_filter($id, $url_params, $row) {
  * @version July 2008
  * @since Dokeos 1.8.6
  */
-function move_user_field($direction,$field_id) {
-	// Databse table definitions
-	$table_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
-
-	// check the parameters
-	if (!in_array($direction,array('moveup','movedown')) OR !is_numeric($field_id))
-	{
-		return false;
-	}
-
-	// determine the SQL sort direction
-	if ($direction == 'moveup')
-	{
-		$sortdirection = 'DESC';
-	}
-	else
-	{
-		$sortdirection = 'ASC';
-	}
+function move_user_field($direction, $field_id) {
+    // Databse table definitions
+    $table_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+
+    // check the parameters
+    if (!in_array($direction, array('moveup', 'movedown')) OR !is_numeric($field_id)) {
+        return false;
+    }
+
+    // determine the SQL sort direction
+    if ($direction == 'moveup') {
+        $sortdirection = 'DESC';
+    } else {
+        $sortdirection = 'ASC';
+    }
 
     // first reorder user_fields
     reorder_user_fields();
 
-	$found = false;
-	$sql = "SELECT id, field_order FROM $table_user_field ORDER BY field_order $sortdirection";
-	$result = Database::query($sql);
-	while($row = Database::fetch_array($result))
-	{
-		if ($found)
-		{
-			$next_id = $row['id'];
-			$next_order = $row['field_order'];
-			break;
-		}
-
-		if ($field_id == $row['id'])
-		{
-			$this_id = $row['id'];
-			$this_order = $row['field_order'];
-			$found = true;
-		}
-	}
-
-	$sql1 = "UPDATE ".$table_user_field." SET field_order = '".intval($next_order)."' WHERE id =  '".intval($this_id)."'";
-	$sql2 = "UPDATE ".$table_user_field." SET field_order = '".intval($this_order)."' WHERE id =  '".intval($next_id)."'";
-	Database::query($sql1);
-	Database::query($sql2);
-
-	return true;
+    $found = false;
+    $sql = "SELECT id, field_order FROM $table_user_field ORDER BY field_order $sortdirection";
+    $result = Database::query($sql);
+    while ($row = Database::fetch_array($result)) {
+        if ($found) {
+            $next_id = $row['id'];
+            $next_order = $row['field_order'];
+            break;
+        }
+
+        if ($field_id == $row['id']) {
+            $this_id = $row['id'];
+            $this_order = $row['field_order'];
+            $found = true;
+        }
+    }
+
+    $sql1 = "UPDATE " . $table_user_field . " SET field_order = '" . intval($next_order) . "' WHERE id =  '" . intval($this_id) . "'";
+    $sql2 = "UPDATE " . $table_user_field . " SET field_order = '" . intval($this_order) . "' WHERE id =  '" . intval($next_id) . "'";
+    Database::query($sql1);
+    Database::query($sql2);
+
+    return true;
 }
 
 /**
-* Re-order user fields
-*/
+ * Re-order user fields
+ */
 function reorder_user_fields() {
-      // Database table definition
-      $t_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
-      $sql = "SELECT * FROM $t_user_field ORDER by field_order ASC";
-      $res = Database::query($sql);
-      $i = 1;
-      while ($row = Database::fetch_array($res)) {
-              $sql_reorder = "UPDATE $t_user_field SET field_order = $i WHERE id = '".$row['id']."'";
-              Database::query($sql_reorder);
-              $i++;
-      }
+    // Database table definition
+    $t_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+    $sql = "SELECT * FROM $t_user_field ORDER by field_order ASC";
+    $res = Database::query($sql);
+    $i = 1;
+    while ($row = Database::fetch_array($res)) {
+        $sql_reorder = "UPDATE $t_user_field SET field_order = $i WHERE id = '" . $row['id'] . "'";
+        Database::query($sql_reorder);
+        $i++;
+    }
 }
 
 /**
@@ -345,42 +334,39 @@ function reorder_user_fields() {
  * @version July 2008
  * @since Dokeos 1.8.6
  */
-function delete_user_fields($field_id)
-{
-	// Database table definitions
-	$table_user_field 			= Database::get_main_table(TABLE_MAIN_USER_FIELD);
-	$table_user_field_options	= Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-	$table_user_field_values 	= Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
-
-	// delete the fields
-	$sql = "DELETE FROM $table_user_field WHERE id = '".Database::escape_string($field_id)."'";
-	$result = Database::query($sql);
-	if (Database::affected_rows() == 1)
-	{
-		// delete the field options
-		$sql = "DELETE FROM $table_user_field_options WHERE field_id = '".Database::escape_string($field_id)."'";
-		$result = Database::query($sql);
-
-		// delete the field values
-		$sql = "DELETE FROM $table_user_field_values WHERE field_id = '".Database::escape_string($field_id)."'";
-		$result = Database::query($sql);
-
-		// recalculate the field_order because the value is used to show/hide the up/down icon
-		// and the field_order value cannot be bigger than the number of fields
-		$sql = "SELECT * FROM $table_user_field ORDER BY field_order ASC";
-		$result = Database::query($sql);
-		$i = 1;
-		while($row = Database::fetch_array($result))
-		{
-			$sql_reorder = "UPDATE $table_user_field SET field_order = '".Database::escape_string($i)."' WHERE id = '".Database::escape_string($row['id'])."'";
-			$result_reorder = Database::query($sql_reorder);
-			$i++;
-		}
-
-		// field was deleted so we return true
-		return true;
-	} else {
-		// the field was not deleted so we return false
-		return false;
-	}
+function delete_user_fields($field_id) {
+    // Database table definitions
+    $table_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+    $table_user_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
+    $table_user_field_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
+
+    // delete the fields
+    $sql = "DELETE FROM $table_user_field WHERE id = '" . Database::escape_string($field_id) . "'";
+    $result = Database::query($sql);
+    if (Database::affected_rows() == 1) {
+        // delete the field options
+        $sql = "DELETE FROM $table_user_field_options WHERE field_id = '" . Database::escape_string($field_id) . "'";
+        $result = Database::query($sql);
+
+        // delete the field values
+        $sql = "DELETE FROM $table_user_field_values WHERE field_id = '" . Database::escape_string($field_id) . "'";
+        $result = Database::query($sql);
+
+        // recalculate the field_order because the value is used to show/hide the up/down icon
+        // and the field_order value cannot be bigger than the number of fields
+        $sql = "SELECT * FROM $table_user_field ORDER BY field_order ASC";
+        $result = Database::query($sql);
+        $i = 1;
+        while ($row = Database::fetch_array($result)) {
+            $sql_reorder = "UPDATE $table_user_field SET field_order = '" . Database::escape_string($i) . "' WHERE id = '" . Database::escape_string($row['id']) . "'";
+            $result_reorder = Database::query($sql_reorder);
+            $i++;
+        }
+
+        // field was deleted so we return true
+        return true;
+    } else {
+        // the field was not deleted so we return false
+        return false;
+    }
 }

+ 108 - 144
main/admin/user_fields_options.php

@@ -1,8 +1,9 @@
 <?php
+
 /* For licensing terms, see /license.txt */
 /**
-*	@package chamilo.admin
-*/
+ * 	@package chamilo.admin
+ */
 // name of the language file that needs to be included
 $language_file = array('admin', 'registration');
 
@@ -13,22 +14,15 @@ $cidReset = true;
 require '../inc/global.inc.php';
 
 // section for the tabs
-$this_section=SECTION_PLATFORM_ADMIN;
+$this_section = SECTION_PLATFORM_ADMIN;
 
 // user permissions
 api_protect_admin_script();
 
-// Database table definitions
-$table_admin				= Database :: get_main_table(TABLE_MAIN_ADMIN);
-$table_user 				= Database :: get_main_table(TABLE_MAIN_USER);
-$table_userfields	 		= Database :: get_main_table(TABLE_MAIN_USER_FIELD);
-$table_userfields_options 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-$table_userfields_values 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
-
 // breadcrumbs
-$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ('url' => 'user_fields.php', 'name' => get_lang('UserFields'));
-$interbreadcrumb[] = array ('url' => 'user_fields_add.php?action=edit&field_id='.Security::remove_XSS($_GET['field_id']).'&amp;sec_token='.$_SESSION['sec_token'], 'name' => get_lang('EditUserFields'));
+$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array('url' => 'user_fields.php', 'name' => get_lang('UserFields'));
+$interbreadcrumb[] = array('url' => 'user_fields_add.php?action=edit&field_id=' . Security::remove_XSS($_GET['field_id']) . '&amp;sec_token=' . $_SESSION['sec_token'], 'name' => get_lang('EditUserFields'));
 
 // name of the tools
 $tool_name = get_lang('UserFieldsSortOptions');
@@ -36,46 +30,35 @@ $tool_name = get_lang('UserFieldsSortOptions');
 // display header
 Display::display_header($tool_name);
 
-if (isset ($_GET['action']))
-{
-	$check = Security::check_token('get');
-	if($check)
-	{
-		switch ($_GET['action'])
-		{
-			case 'moveup' :
-				if (api_is_platform_admin() && !empty($_GET['option_id']))
-				{
-					if (move_user_field_option('moveup', $_GET['option_id']))
-					{
-						Display :: display_confirmation_message(get_lang('FieldOptionMovedUp'));
-					}
-					else
-					{
-						Display :: display_error_message(get_lang('CannotMoveFieldOption'));
-					}
-				}
-				break;
-			case 'movedown' :
-				if (api_is_platform_admin() && !empty($_GET['option_id']))
-				{
-					if (move_user_field_option('movedown', $_GET['option_id']))
-					{
-						Display :: display_confirmation_message(get_lang('FieldOptionMovedDown'));
-					}
-					else
-					{
-						Display :: display_error_message(get_lang('CannotMoveFieldOption'));
-					}
-				}
-				break;
-		}
-	}
+if (isset($_GET['action'])) {
+    $check = Security::check_token('get');
+    if ($check) {
+        switch ($_GET['action']) {
+            case 'moveup' :
+                if (api_is_platform_admin() && !empty($_GET['option_id'])) {
+                    if (move_user_field_option('moveup', $_GET['option_id'])) {
+                        Display :: display_confirmation_message(get_lang('FieldOptionMovedUp'));
+                    } else {
+                        Display :: display_error_message(get_lang('CannotMoveFieldOption'));
+                    }
+                }
+                break;
+            case 'movedown' :
+                if (api_is_platform_admin() && !empty($_GET['option_id'])) {
+                    if (move_user_field_option('movedown', $_GET['option_id'])) {
+                        Display :: display_confirmation_message(get_lang('FieldOptionMovedDown'));
+                    } else {
+                        Display :: display_error_message(get_lang('CannotMoveFieldOption'));
+                    }
+                }
+                break;
+        }
+    }
 }
 
 // getting all the information of the field
 $field_info = UserManager::get_extra_field_information($_GET['field_id']);
-echo '<strong>'.$field_info['3'].'</strong><br />';
+echo Display::page_header($field_info['3']);
 
 // the total number of options (used in the actions_filter function but declared here for performance reasons)
 $number_of_options = get_number_of_options();
@@ -83,7 +66,7 @@ $number_of_options = get_number_of_options();
 // displaying the sortable table
 $parameters['sec_token'] = Security::get_token();
 $parameters['field_id'] = Security::remove_XSS($_GET['field_id']);
-$table = new SortableTable('options', 'get_number_of_options', 'get_options_data',2);
+$table = new SortableTable('options', 'get_number_of_options', 'get_options_data', 2);
 $table->set_additional_parameters($parameters);
 $table->set_header(0, get_lang('DisplayOrder'), false);
 $table->set_header(1, get_lang('OptionText'), false);
@@ -94,59 +77,50 @@ $table->display();
 // display footer
 Display::display_footer();
 
+function get_options_data($from, $number_of_items, $column, $direction) {
+    // Database table definition
+    $table_userfields_options = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
 
-function get_options_data($from, $number_of_items, $column, $direction)
-{
-	// Database table definition
-	$table_userfields_options 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-
-	// The sql statement
-	$sql = "SELECT
+    // The sql statement
+    $sql = "SELECT
 				option_order 		AS col0,
 				option_display_text	AS col1,
 				id 					AS col2
-			FROM $table_userfields_options WHERE field_id='".Database::escape_string($_GET['field_id'])."' ORDER BY option_order ASC";
-	$sql .= " LIMIT $from,$number_of_items";
-	$res = Database::query($sql);
-	$return = array ();
-	while ($option = Database::fetch_row($res))
-	{
-		$return[] = $option;
-	}
-	return $return;
+			FROM $table_userfields_options WHERE field_id='" . Database::escape_string($_GET['field_id']) . "' ORDER BY option_order ASC";
+    $sql .= " LIMIT $from,$number_of_items";
+    $res = Database::query($sql);
+    $return = array();
+    while ($option = Database::fetch_row($res)) {
+        $return[] = $option;
+    }
+    return $return;
 }
 
-function get_number_of_options($from=null, $number_of_items=null, $column=null, $direction=null)
-{
-	// Database table definition
-	$table_userfields_options 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
+function get_number_of_options($from = null, $number_of_items = null, $column = null, $direction = null) {
+    // Database table definition
+    $table_userfields_options = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
 
-	// The sql statement
-	$sql = "SELECT count(id) as total FROM $table_userfields_options WHERE field_id='".Database::escape_string($_GET['field_id'])."' ";
-	$res = Database::query($sql);
-	$row = Database::fetch_row($res);
-	return $row[0];
+    // The sql statement
+    $sql = "SELECT count(id) as total FROM $table_userfields_options WHERE field_id='" . Database::escape_string($_GET['field_id']) . "' ";
+    $res = Database::query($sql);
+    $row = Database::fetch_row($res);
+    return $row[0];
 }
 
-function actions_filter($option_id,$url_params,$row)
-{
-	global $number_of_options;
-
-	if ($row[0]<>1)
-	{
-		$return .= '<a href="'.api_get_self().'?action=moveup&amp;option_id='.$option_id.'&amp;field_id='.Security::remove_XSS($_GET['field_id']).'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('up.gif', get_lang('Up')).'</a>';
-	}
-	else
-	{
-		$return .= Display::return_icon('blank.gif','',array('width'=>'21px'));
-	}
-
-	// the down icon only has to appear when the row can be moved down (all but the last row)
-	if ($row[0]<>$number_of_options)
-	{
-		$return .= '<a href="'.api_get_self().'?action=movedown&amp;option_id='.$option_id.'&amp;field_id='.Security::remove_XSS($_GET['field_id']).'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('down.gif', get_lang('Down')).'</a>';
-	}
-	return $return;
+function actions_filter($option_id, $url_params, $row) {
+    global $number_of_options;
+
+    if ($row[0] <> 1) {
+        $return .= '<a href="' . api_get_self() . '?action=moveup&amp;option_id=' . $option_id . '&amp;field_id=' . Security::remove_XSS($_GET['field_id']) . '&amp;sec_token=' . $_SESSION['sec_token'] . '">' . Display::return_icon('up.gif', get_lang('Up')) . '</a>';
+    } else {
+        $return .= Display::return_icon('blank.gif', '', array('width' => '21px'));
+    }
+
+    // the down icon only has to appear when the row can be moved down (all but the last row)
+    if ($row[0] <> $number_of_options) {
+        $return .= '<a href="' . api_get_self() . '?action=movedown&amp;option_id=' . $option_id . '&amp;field_id=' . Security::remove_XSS($_GET['field_id']) . '&amp;sec_token=' . $_SESSION['sec_token'] . '">' . Display::return_icon('down.gif', get_lang('Down')) . '</a>';
+    }
+    return $return;
 }
 
 /**
@@ -159,53 +133,43 @@ function actions_filter($option_id,$url_params,$row)
  * @version July 2008
  * @since Dokeos 1.8.6
  */
-function move_user_field_option($direction,$option_id)
-{
-	// Database table definition
-	$table_userfields_options 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-
-	// check the parameters
-	if (!in_array($direction,array('moveup','movedown')) OR !is_numeric($option_id))
-	{
-		return false;
-	}
-
-	// determine the SQL sort direction
-	if ($direction == 'moveup')
-	{
-		$sortdirection = 'DESC';
-	}
-	else
-	{
-		$sortdirection = 'ASC';
-	}
-
-	$found = false;
-
-	$sql = "SELECT id, option_order FROM $table_userfields_options  WHERE field_id='".Database::escape_string($_GET['field_id'])."' ORDER BY option_order $sortdirection";
-	$result = Database::query($sql);
-	while($row = Database::fetch_array($result))
-	{
-		if ($found)
-		{
-			$next_id = $row['id'];
-			$next_order = $row['option_order'];
-			break;
-		}
-
-		if ($option_id == $row['id'])
-		{
-			$this_id = $row['id'];
-			$this_order = $row['option_order'];
-			$found = true;
-		}
-	}
-
-	$sql1 = "UPDATE ".$table_userfields_options." SET option_order = '".Database::escape_string($next_order)."' WHERE id =  '".Database::escape_string($this_id)."'";
-	$sql2 = "UPDATE ".$table_userfields_options." SET option_order = '".Database::escape_string($this_order)."' WHERE id =  '".Database::escape_string($next_id)."'";
-	Database::query($sql1);
-	Database::query($sql2);
-
-	return true;
-}
-?>
+function move_user_field_option($direction, $option_id) {
+    // Database table definition
+    $table_userfields_options = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
+
+    // check the parameters
+    if (!in_array($direction, array('moveup', 'movedown')) OR !is_numeric($option_id)) {
+        return false;
+    }
+
+    // determine the SQL sort direction
+    if ($direction == 'moveup') {
+        $sortdirection = 'DESC';
+    } else {
+        $sortdirection = 'ASC';
+    }
+
+    $found = false;
+
+    $sql = "SELECT id, option_order FROM $table_userfields_options  WHERE field_id='" . Database::escape_string($_GET['field_id']) . "' ORDER BY option_order $sortdirection";
+    $result = Database::query($sql);
+    while ($row = Database::fetch_array($result)) {
+        if ($found) {
+            $next_id = $row['id'];
+            $next_order = $row['option_order'];
+            break;
+        }
+
+        if ($option_id == $row['id']) {
+            $this_id = $row['id'];
+            $this_order = $row['option_order'];
+            $found = true;
+        }
+    }
+
+    $sql1 = "UPDATE " . $table_userfields_options . " SET option_order = '" . Database::escape_string($next_order) . "' WHERE id =  '" . Database::escape_string($this_id) . "'";
+    $sql2 = "UPDATE " . $table_userfields_options . " SET option_order = '" . Database::escape_string($this_order) . "' WHERE id =  '" . Database::escape_string($next_id) . "'";
+    Database::query($sql1);
+    Database::query($sql2);
+    return true;
+}

+ 2 - 6
main/admin/user_import.php

@@ -10,14 +10,10 @@
  * Validate the imported data.
  */
 
-$language_file = array ('admin', 'registration');
+$language_file = array('admin', 'registration');
 
 $cidReset = true;
-require '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
-require_once api_get_path(LIBRARY_PATH).'import.lib.php';
+require_once '../inc/global.inc.php';
 
 // Set this option to true to enforce strict purification for usenames.
 $purification_option_for_usernames = false;

+ 20 - 13
main/admin/user_information.php

@@ -87,18 +87,22 @@ if (count($sessions) > 0) {
     $header[] = array ('', false);
 
     foreach ($sessions as $session_item) {
-
+        
         $data = array ();
         $personal_course_list = array();
         $id_session = $session_item['session_id'];
-
+                
         foreach ($session_item['courses'] as $my_course) {
             $course_info = api_get_course_info($my_course['code']);
             $row = array ();
             $row[] = $my_course['code'];
             $row[] = $course_info['title'];
-            $row[] = $my_course['status'] == STUDENT ? get_lang('Student') : get_lang('Teacher');
-
+            //$row[] = $my_course['status'] == STUDENT ? get_lang('Student') : get_lang('Teacher');
+            
+            $roles = api_detect_user_roles($user['user_id'], $my_course['code'], $id_session);
+            $row[] = api_get_roles_to_string($roles);
+        
+            
             $tools = '<a href="course_information.php?code='.$course_info['code'].'&id_session='.$id_session.'">'.Display::return_icon('synthese_view.gif', get_lang('Overview')).'</a>'.
                     '<a href="'.api_get_path(WEB_COURSE_PATH).$course_info['path'].'?id_session='.$id_session.'">'.Display::return_icon('course_home.gif', get_lang('CourseHomepage')).'</a>';
 
@@ -112,7 +116,7 @@ if (count($sessions) > 0) {
         Display :: display_sortable_table($header, $data, array (), array(), array ('user_id' => intval($_GET['user_id'])));
     }
 } else {
-    echo '<p>'.get_lang('NoSessionsForThisUser').'</p>';
+    Display::display_warning_message(get_lang('NoSessionsForThisUser'));
 }
 
 
@@ -129,12 +133,15 @@ if (Database::num_rows($res) > 0) {
     $header[] = array (get_lang('Title'), true);
     $header[] = array (get_lang('Status'), true);
     $header[] = array ('', false);
-    $data = array ();
+    $data = array();
     while ($course = Database::fetch_object($res)) {
         $row = array ();
         $row[] = $course->code;
         $row[] = $course->title;
-        $row[] = $course->status == STUDENT ? get_lang('Student') : get_lang('Teacher');
+        
+        //$row[] = $course->status == STUDENT ? get_lang('Student') : get_lang('Teacher');
+        $roles = api_detect_user_roles($user['user_id'], $course->code);
+        $row[] = api_get_roles_to_string($roles);
         $tools = '<a href="course_information.php?code='.$course->code.'">'.Display::return_icon('synthese_view.gif', get_lang('Overview')).'</a>'.
                 '<a href="'.api_get_path(WEB_COURSE_PATH).$course->directory.'">'.Display::return_icon('course_home.gif', get_lang('CourseHomepage')).'</a>' .
                 '<a href="course_edit.php?course_code='.$course->code.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
@@ -146,9 +153,9 @@ if (Database::num_rows($res) > 0) {
         $data[] = $row;
     }
     echo Display::page_subheader(get_lang('Courses'));
-    Display :: display_sortable_table($header, $data, array (), array (), array ('user_id' => intval($_GET['user_id'])));
+    Display :: display_sortable_table($header, $data, array (), array (), array ('user_id' => intval($_GET['user_id'])));    
 } else {
-    echo '<p>'.get_lang('NoCoursesForThisUser').'</p>';
+    Display::display_warning_message(get_lang('NoCoursesForThisUser'));
 }
 
 /**
@@ -175,7 +182,7 @@ if (Database::num_rows($res) > 0) {
     echo '<blockquote>';
     Display :: display_sortable_table($header, $data, array (), array (), array ('user_id' => intval($_GET['user_id'])));
     echo '</blockquote>';
-} else {
+} else {    
     echo '<p>'.get_lang('NoClassesForThisUser').'</p>';
 }*/
 
@@ -183,7 +190,7 @@ if (Database::num_rows($res) > 0) {
  * Show the URL in which this user is subscribed
  */
 global $_configuration;
-if ($_configuration['multiple_access_urls']) {
+if ($_configuration['multiple_access_urls']) {    
     $url_list= UrlManager::get_access_url_from_user($user['user_id']);
     if (count($url_list) > 0) {
         $header = array();
@@ -194,8 +201,8 @@ if ($_configuration['multiple_access_urls']) {
             $row[] = Display::url($url['url'], $url['url']);
             $data[] = $row;
         }
-        echo '<p><b>'.get_lang('URLList').'</b></p>';
-        Display :: display_sortable_table($header, $data, array (), array (), array ('user_id' => intval($_GET['user_id'])));
+        echo '<p><b>'.get_lang('URLList').'</b></p>';        
+        Display :: display_sortable_table($header, $data, array (), array (), array ('user_id' => intval($_GET['user_id'])));        
     } else {
         echo '<p>'.get_lang('NoUrlForThisUser').'</p>';
     }

+ 104 - 144
main/admin/user_list.php

@@ -21,8 +21,8 @@ if (isset($_configuration['deny_delete_users']) &&  $_configuration['deny_delete
 	$delete_user_available = false;
 }
 $url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=get_user_courses';
-        
-$htmlHeadXtra[] = '<script type="text/javascript">
+
+$htmlHeadXtra[] = '<script>
 function load_course_list (div_course,my_user_id) {
 	 $.ajax({
 		contentType: "application/x-www-form-urlencoded",
@@ -62,7 +62,7 @@ function active_user(element_div) {
 				if (data == 1) {
 					$(ident).attr("src","'.api_get_path(WEB_IMG_PATH).'icons/16/accept.png'.'");
 					$(ident).attr("title","'.get_lang('Lock').'");
-				} 
+				}
                 if (data == 0) {
 					$(ident).attr("src","'.api_get_path(WEB_IMG_PATH).'icons/16/error.png'.'");
 					$(ident).attr("title","'.get_lang('Unlock').'");
@@ -95,24 +95,24 @@ $(document).ready(function() {
 
     var select_val = $("#input_select_extra_data").val();
     if ( document.getElementById(\'extra_data_text\')) {
-    
+
         if (select_val != 0) {
             document.getElementById(\'extra_data_text\').style.display="block";
-            if (document.getElementById(\'input_extra_text\')) 
+            if (document.getElementById(\'input_extra_text\'))
                 document.getElementById(\'input_extra_text\').value = "";
         } else {
             document.getElementById(\'extra_data_text\').style.display="none";
         }
     }
-    
-    
+
+
     $(".agenda_opener").live("click", function() {
         var url = this.href;
         var dialog = $("#dialog");
-                
+
         if ($("#dialog").length == 0) {
             dialog = $(\'<div id="dialog" style="display:hidden"></div> \').appendTo(\'body\');
-        }     
+        }
         // load remote content
         dialog.load(
                 url,
@@ -123,14 +123,14 @@ $(document).ready(function() {
             );
         //prevent the browser to follow the link
         return false;
-    });    
+    });
 });
 
 //Load user calendar
-function load_calendar(user_id, month, year) {  
+function load_calendar(user_id, month, year) {
  	var url = "'.api_get_path(WEB_AJAX_PATH).'agenda.ajax.php?a=get_user_agenda&user_id=" +user_id + "&month="+month+"&year="+year;
-	$("#dialog").load( url    	 	
-	);    	
+	$("#dialog").load( url
+	);
 }
 </script>';
 
@@ -147,20 +147,20 @@ api_protect_admin_script(true);
 *	@author Evie Embrechts
 *   @author Yannick Warnier <yannick.warnier@dokeos.com>
 */
-function login_user($user_id) {    
+function login_user($user_id) {
     $user_id = intval($user_id);
-    
+
     if (empty($user_id)) {
         return false;
     }
     if ($user_id != strval(intval($user_id))) {
     	return false;
     }
-    
+
     //Only superadmins can login to admin accounts
     if (!api_global_admin_can_edit_admin($user_id)) {
         return false;
-    }    
+    }
 
     //Load $_user to be sure we clean it before logging in
 	global $uidReset, $loginFailed, $_configuration, $_user;
@@ -201,11 +201,10 @@ function login_user($user_id) {
 			LEFT JOIN $track_e_login_table login
 			ON user.user_id = login.login_user_id
 			WHERE user.user_id = '".$user_id."'
-			ORDER BY login.login_date DESC LIMIT 1";		
+			ORDER BY login.login_date DESC LIMIT 1";
 
 		$sql_result = Database::query($sql_query);
 
-
 		if (Database::num_rows($sql_result) > 0) {
 			// Extracting the user data
 
@@ -253,82 +252,14 @@ function login_user($user_id) {
 		}
 	}
 }
+
 /**
  * Get the total number of users on the platform
  * @see SortableTable#get_total_number_of_items()
  */
 function get_number_of_users() {
-	$user_table = Database :: get_main_table(TABLE_MAIN_USER);
-	$sql = "SELECT COUNT(u.user_id) AS total_number_of_items FROM $user_table u";
-
-	// adding the filter to see the user's only of the current access_url
-    if ((api_is_platform_admin() || api_is_session_admin()) && api_get_multiple_access_url()) {
-    	$access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-    	$sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
-    }
-
-    if (isset($_GET['keyword_extra_data'])) {
-        $keyword_extra_data = Database::escape_string($_GET['keyword_extra_data']);
-        if (!empty($keyword_extra_data)) {
-            $extra_info = UserManager::get_extra_field_information_by_name($keyword_extra_data);
-            $field_id = $extra_info['id'];
-            $sql.= " INNER JOIN user_field_values ufv ON u.user_id=ufv.user_id AND ufv.field_id=$field_id ";
-        }
-    }
-
-	if ( isset ($_GET['keyword'])) {
-		$keyword = Database::escape_string(trim($_GET['keyword']));
-		$sql .= " WHERE (u.firstname LIKE '%".$keyword."%' OR u.lastname LIKE '%".$keyword."%'  OR concat(u.firstname,' ',u.lastname) LIKE '%".$keyword."%'  OR concat(u.lastname,' ',u.firstname) LIKE '%".$keyword."%' OR u.username LIKE '%".$keyword."%' OR u.email LIKE '%".$keyword."%'  OR u.official_code LIKE '%".$keyword."%') ";
-	} elseif (isset ($_GET['keyword_firstname'])) {
-		$admin_table = Database :: get_main_table(TABLE_MAIN_ADMIN);
-		$keyword_firstname = Database::escape_string($_GET['keyword_firstname']);
-		$keyword_lastname = Database::escape_string($_GET['keyword_lastname']);
-		$keyword_email = Database::escape_string($_GET['keyword_email']);
-		$keyword_officialcode = Database::escape_string($_GET['keyword_officialcode']);
-		$keyword_username = Database::escape_string($_GET['keyword_username']);
-		$keyword_status = Database::escape_string($_GET['keyword_status']);
-		$query_admin_table = '';
-		$keyword_admin = '';
-		if ($keyword_status == SESSIONADMIN) {
-			$keyword_status = '%';
-			$query_admin_table = " , $admin_table a ";
-			$keyword_admin = ' AND a.user_id = u.user_id ';
-		}
-
-        $keyword_extra_value = '';
-        if (isset($_GET['keyword_extra_data'])) {
-            if (!empty($_GET['keyword_extra_data']) && !empty($_GET['keyword_extra_data_text'])) {
-                $keyword_extra_data_text = Database::escape_string($_GET['keyword_extra_data_text']);
-                $keyword_extra_value = " AND ufv.field_value LIKE '%".trim($keyword_extra_data_text)."%' ";
-            }
-        }
-
-		$keyword_active = isset($_GET['keyword_active']);
-		$keyword_inactive = isset($_GET['keyword_inactive']);
-		$sql .= $query_admin_table .
-				" WHERE (u.firstname LIKE '%".$keyword_firstname."%' " .
-				"AND u.lastname LIKE '%".$keyword_lastname."%' " .
-				"AND u.username LIKE '%".$keyword_username."%'  " .
-				"AND u.email LIKE '%".$keyword_email."%'   " .
-				"AND u.official_code LIKE '%".$keyword_officialcode."%'" .
-				"AND u.status LIKE '".$keyword_status."'" .
-				$keyword_admin.$keyword_extra_value;
-		if($keyword_active && !$keyword_inactive) {
-			$sql .= " AND u.active='1'";
-		} elseif($keyword_inactive && !$keyword_active) {
-			$sql .= " AND u.active='0'";
-		}
-		$sql .= " ) ";
-	}
-
-    // adding the filter to see the user's only of the current access_url
-	if ((api_is_platform_admin() || api_is_session_admin()) && api_get_multiple_access_url()) {
-    		$sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
-    }
-
-	$res = Database::query($sql);
-	$obj = Database::fetch_object($res);
-	return $obj->total_number_of_items;
+	$total_rows = get_user_data(null, null, null, null, true);
+    return $total_rows;
 }
 
 /**
@@ -339,12 +270,13 @@ function get_number_of_users() {
  * @param   string  Order (ASC,DESC)
  * @see SortableTable#get_table_data($from)
  */
-function get_user_data($from, $number_of_items, $column, $direction) {
+function get_user_data($from, $number_of_items, $column, $direction, $get_count = false) {
 	global $origin;
 
 	$user_table = Database :: get_main_table(TABLE_MAIN_USER);
 	$admin_table = Database :: get_main_table(TABLE_MAIN_ADMIN);
-	$sql = "SELECT
+
+	$select = "SELECT
                  u.user_id				AS col0,
                  u.official_code		AS col2,
 				 ".(api_is_western_name_order()
@@ -358,8 +290,13 @@ function get_user_data($from, $number_of_items, $column, $direction) {
                  u.active				AS col8,
                  u.user_id				AS col9,
                  u.registration_date    AS col10 ".
-                 ", u.expiration_date   AS exp ".
-            " FROM $user_table u ";
+                 ", u.expiration_date   AS exp            ";
+
+    if ($get_count) {
+        $select = "SELECT count(u.user_id) as total_rows";
+    }
+
+     $sql = "$select FROM $user_table u ";
 
     // adding the filter to see the user's only of the current access_url
     if ((api_is_platform_admin() || api_is_session_admin()) && api_get_multiple_access_url()) {
@@ -388,38 +325,53 @@ function get_user_data($from, $number_of_items, $column, $direction) {
 		$keyword_status = Database::escape_string($_GET['keyword_status']);
 
 		$query_admin_table = '';
-		$keyword_admin = '';
+
+        $and_conditions = array();
 
 		if ($keyword_status == SESSIONADMIN) {
 			$keyword_status = '%';
 			$query_admin_table = " , $admin_table a ";
-			$keyword_admin = ' AND a.user_id = u.user_id ';
+			$and_conditions[] = ' a.user_id = u.user_id ';
 		}
 
-		$keyword_extra_value = '';
-		
         if (isset($_GET['keyword_extra_data'])) {
         	if (!empty($_GET['keyword_extra_data']) && !empty($_GET['keyword_extra_data_text'])) {
             	$keyword_extra_data_text = Database::escape_string($_GET['keyword_extra_data_text']);
-                $keyword_extra_value = " AND ufv.field_value LIKE '%".trim($keyword_extra_data_text)."%' ";
+                $and_conditions[] = " ufv.field_value LIKE '%".trim($keyword_extra_data_text)."%' ";
 			}
 		}
 
 		$keyword_active = isset($_GET['keyword_active']);
 		$keyword_inactive = isset($_GET['keyword_inactive']);
-		$sql .= $query_admin_table." WHERE (u.firstname LIKE '%".$keyword_firstname."%' " .
-				"AND u.lastname LIKE '%".$keyword_lastname."%' " .
-				"AND u.username LIKE '%".$keyword_username."%'  " .
-				"AND u.email LIKE '%".$keyword_email."%'   " .
-				"AND u.official_code LIKE '%".$keyword_officialcode."%'    " .
-				"AND u.status LIKE '".$keyword_status."'" .
-				$keyword_admin.$keyword_extra_value;
+		$sql .= $query_admin_table." WHERE ( ";
+
+        if (!empty($keyword_firstname)) {
+            $and_conditions[] = "u.firstname LIKE '%".$keyword_firstname."%' ";
+        }
+        if (!empty($keyword_lastname)) {
+            $and_conditions[] = "u.lastname LIKE '%".$keyword_lastname."%' ";
+        }
+        if (!empty($keyword_username)) {
+            $and_conditions[] = "u.username LIKE '%".$keyword_username."%'  ";
+        }
+        if (!empty($keyword_email)) {
+            $and_conditions[] = "u.email LIKE '%".$keyword_email."%' ";
+        }
+        if (!empty($keyword_officialcode)) {
+             $and_conditions[] = "u.official_code LIKE '%".$keyword_officialcode."%' ";
+        }
+        if (!empty($keyword_status)) {
+             $and_conditions[] = "u.status LIKE '".$keyword_status."' ";
+        }
 
 		if ($keyword_active && !$keyword_inactive) {
-			$sql .= " AND u.active='1'";
+			$and_conditions[] =  "  u.active='1' ";
 		} elseif($keyword_inactive && !$keyword_active) {
-			$sql .= " AND u.active='0'";
+			$and_conditions[] = "  u.active='0' ";
 		}
+        if (!empty($and_conditions)) {
+            $sql .= implode(' AND ', $and_conditions);
+        }
 		$sql .= " ) ";
 	}
 
@@ -431,18 +383,25 @@ function get_user_data($from, $number_of_items, $column, $direction) {
     if (!in_array($direction, array('ASC','DESC'))) {
     	$direction = 'ASC';
     }
+
     $column = intval($column);
     $from 	= intval($from);
     $number_of_items = intval($number_of_items);
 
-	$sql .= " ORDER BY col$column $direction ";
-	$sql .= " LIMIT $from,$number_of_items";
+    //Returns counts and exits function
+    if ($get_count) {
+        $res = Database::query($sql);
+        $user = Database::fetch_array($res);
+        return $user['total_rows'];
+    }
 
-	$res = Database::query($sql);
+    $sql .= " ORDER BY col$column $direction ";
+	$sql .= " LIMIT $from,$number_of_items";
+    $res = Database::query($sql);
 
 	$users = array ();
     $t = time();
-	while ($user = Database::fetch_row($res)) {        
+	while ($user = Database::fetch_row($res)) {
 		$image_path 	= UserManager::get_user_picture_path_by_id($user[0], 'web', false, true);
 		$user_profile 	= UserManager::get_picture_user($user[0], $image_path['file'], 22, USER_IMAGE_SIZE_SMALL, ' width="22" height="22" ');
 		if (!api_is_anonymous()) {
@@ -491,12 +450,12 @@ function user_filter($name, $params, $row) {
  * @return string Some HTML-code with modify-buttons
  */
 function modify_filter($user_id, $url_params, $row) {
-	global $charset, $_admins_list, $delete_user_available;    
+	global $charset, $_admins_list, $delete_user_available;
 	$is_admin   = in_array($user_id,$_admins_list);
 	$statusname = api_get_status_langvars();
 	$user_is_anonymous = false;
     $current_user_status_label = $row['7'];
-        
+
 	if ($current_user_status_label == $statusname[ANONYMOUS]) {
 		$user_is_anonymous =true;
 	}
@@ -524,7 +483,7 @@ function modify_filter($user_id, $url_params, $row) {
             if (api_global_admin_can_edit_admin($user_id)) {
                 $result .= '<a href="user_list.php?action=login_as&amp;user_id='.$user_id.'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>&nbsp;&nbsp;';
             } else {
-                $result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';                
+                $result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';
             }
             //$result .= '<a href="user_list.php?action=login_as&amp;user_id='.$user_id.'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>&nbsp;&nbsp;';
     	} else {
@@ -533,29 +492,29 @@ function modify_filter($user_id, $url_params, $row) {
     } else {
     	$result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';
     }
-    
+
 	if ($current_user_status_label != $statusname[STUDENT]) {
 		$result .= Display::return_icon('statistics_na.gif', get_lang('Reporting')).'&nbsp;&nbsp;';
 	} else {
 		$result .= '<a href="../mySpace/myStudents.php?student='.$user_id.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>&nbsp;&nbsp;';
 	}
 
-	if (api_is_platform_admin(true)) {        
-        
+	if (api_is_platform_admin(true)) {
+
 		if (!$user_is_anonymous && api_global_admin_can_edit_admin($user_id, null, true)) {
             $result .= '<a href="user_edit.php?user_id='.$user_id.'">'.Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>&nbsp;';
 		} else {
             $result .= Display::return_icon('edit_na.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>&nbsp;';
 		}
 	}
-    
-    
+
+
 	if ($is_admin) {
 		$result .= Display::return_icon('admin_star.png', get_lang('IsAdministrator'),array('width'=> ICON_SIZE_SMALL, 'heigth'=> ICON_SIZE_SMALL));
 	} else {
 		$result .= Display::return_icon('admin_star_na.png', get_lang('IsNotAdministrator'));
 	}
-	
+
 
 	// actions for assigning sessions, courses or users
 	if (api_is_session_admin()) {
@@ -571,17 +530,17 @@ function modify_filter($user_id, $url_params, $row) {
 			$result .= '<a href="dashboard_add_sessions_to_user.php?user='.$user_id.'">'.Display::return_icon('view_more_stats.gif', get_lang('AssignSessions')).'</a>&nbsp;&nbsp;';
 		}
 	}
-	
-    if (api_is_platform_admin()) {        
+
+    if (api_is_platform_admin()) {
         $result .= ' <a href="'.api_get_path(WEB_AJAX_PATH).'agenda.ajax.php?a=get_user_agenda&amp;user_id='.$user_id.'" class="agenda_opener">'.Display::return_icon('month.png', get_lang('FreeBusyCalendar'), array(), ICON_SIZE_SMALL).'</a>';
         if ($delete_user_available) {
-            if ($user_id != api_get_user_id() && !$user_is_anonymous && api_global_admin_can_edit_admin($user_id)) {                  
+            if ($user_id != api_get_user_id() && !$user_is_anonymous && api_global_admin_can_edit_admin($user_id)) {
                 // you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.
                 $result .= ' <a href="user_list.php?action=delete_user&amp;user_id='.$user_id.'&amp;'.$url_params.'&amp;sec_token='.$_SESSION['sec_token'].'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
             } else {
                 $result .= Display::return_icon('delete_na.png', get_lang('Delete'), array(), ICON_SIZE_SMALL);
             }
-        }       
+        }
     }
 	return $result;
 }
@@ -614,7 +573,7 @@ function active_filter($active, $url_params, $row) {
     if ($action=='edit') {
         $result = Display::return_icon($image.'.png', get_lang('AccountExpired'), array(), 16);
     } elseif ($row['0']<>$_user['user_id']) {
-    	// you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.		
+    	// you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.
 		$result = Display::return_icon($image.'.png', get_lang(ucfirst($action)), array('onclick'=>'active_user(this);', 'id'=>'img_'.$row['0']), 16).'</a>';
 	}
 	return $result;
@@ -648,7 +607,7 @@ if (isset($_GET['keyword']) || isset($_GET['keyword_firstname'])) {
 $message = '';
 
 if (!empty($action)) {
-	$check = Security::check_token('get');    
+	$check = Security::check_token('get');
 	if ($check) {
 		switch ($action) {
             case 'add_user_to_my_url':
@@ -658,7 +617,7 @@ if (!empty($action)) {
                     $user_info = api_get_user_info($user_id);
                     $message = get_lang('UserAdded').' '.$user_info['firstname'].' '.$user_info['lastname'].' ('.$user_info['username'].')';
                     $message  = Display::return_message($message, 'confirmation');
-                }                
+                }
                 break;
             case 'login_as':
                 $login_as_user_id = $_GET["user_id"];
@@ -682,7 +641,7 @@ if (!empty($action)) {
 				if (api_is_platform_admin()) {
                     $user_to_delete = $_GET['user_id'];
                     $current_user_id = api_get_user_id();
-                    
+
 					if ($delete_user_available && api_global_admin_can_edit_admin($_GET['user_id'])) {
 						if ($user_to_delete != $current_user_id && UserManager :: delete_user($_GET['user_id'])) {
 							$message = Display :: return_message(get_lang('UserDeleted'), 'confirmation');
@@ -707,10 +666,10 @@ if (!empty($action)) {
 							}
 						}
 					}
-					if ($number_of_selected_users == $number_of_deleted_users) {						
+					if ($number_of_selected_users == $number_of_deleted_users) {
                         $message = Display :: return_message(get_lang('SelectedUsersDeleted'), 'confirmation');
 					} else {
-                        $message = Display :: return_message(get_lang('SomeUsersNotDeleted'), 'error');						
+                        $message = Display :: return_message(get_lang('SomeUsersNotDeleted'), 'error');
 					}
 				}
 				break;
@@ -733,7 +692,7 @@ if (api_is_platform_admin()) {
 		 '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_add.php">'.Display::return_icon('new_user.png',get_lang('AddUsers'),'',ICON_SIZE_MEDIUM).'</a>'.
 		 '</span>';
 }
-$actions .=$form->return_form();
+$actions .= $form->return_form();
 
 if (isset ($_GET['keyword'])) {
 	$parameters = array ('keyword' => Security::remove_XSS($_GET['keyword']));
@@ -747,6 +706,7 @@ if (isset ($_GET['keyword'])) {
 	$parameters['keyword_active'] 		= Security::remove_XSS($_GET['keyword_active']);
 	$parameters['keyword_inactive'] 	= Security::remove_XSS($_GET['keyword_inactive']);
 }
+
 // Create a sortable table with user-data
 $parameters['sec_token'] = Security::get_token();
 
@@ -873,27 +833,27 @@ $extra_search_options = '';
 
 //Try to search the user everywhere
 if ($table->get_total_number_of_items() == 0) {
-    
-    if (api_get_multiple_access_url() && isset($_REQUEST['keyword'])) {     
+
+    if (api_get_multiple_access_url() && isset($_REQUEST['keyword'])) {
         $keyword = Database::escape_string($_REQUEST['keyword']);
         //$conditions = array('firstname' => $keyword, 'lastname' => $keyword, 'username' => $keyword);
         $conditions = array('username' => $keyword);
-        $user_list = UserManager::get_user_list($conditions, array(), false, ' OR ');        
+        $user_list = UserManager::get_user_list($conditions, array(), false, ' OR ');
         if (!empty($user_list)) {
-            
+
             $extra_search_options = Display::page_subheader(get_lang('UsersFoundInOtherPortals'));
-            
+
             $table = new HTML_Table(array('class' => 'data_table'));
             $column = 0;
-            $row = 0;            
+            $row = 0;
             $headers = array(get_lang('User'), 'URL', get_lang('Actions'));
             foreach ($headers as $header) {
                 $table->setHeaderContents($row, $column, $header);
                 $column++;
             }
             $row++;
-            
-            foreach ($user_list as $user) {      
+
+            foreach ($user_list as $user) {
                 $column = 0;
                 $access_info = UrlManager::get_access_url_from_user($user['user_id']);
                 $access_info_to_string = '';
@@ -901,18 +861,18 @@ if ($table->get_total_number_of_items() == 0) {
                 if (!empty($access_info)) {
                     foreach ($access_info as $url_info) {
                         if ($current_access_url_id == $url_info['access_url_id']) {
-                            $add_user = false;                            
+                            $add_user = false;
                         }
                         $access_info_to_string .= $url_info['url'].'<br />';
                     }
                 }
-                if ($add_user) {   
+                if ($add_user) {
                     $row_table = array();
                     $row_table[] =  api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].') ';
                     $row_table[] =  $access_info_to_string;
                     $url = api_get_self().'?action=add_user_to_my_url&user_id='.$user['user_id'].'&sec_token='.$_SESSION['sec_token'];
                     $row_table[] =  Display::url(get_lang('AddUserToMyURL'), $url, array('class' => 'btn'));
-                    	
+
                     foreach ($row_table as $cell) {
                         $table->setCellContents($row, $column, $cell);
                         $table->updateCellAttributes($row, $column, 'align="center"');
@@ -925,7 +885,7 @@ if ($table->get_total_number_of_items() == 0) {
             $extra_search_options .= $table->toHtml();
             $table_result = '';
         }
-    }    
+    }
 }
 
 $tpl = new Template($tool_name);

+ 1 - 1
main/admin/user_move_stats.php

@@ -113,7 +113,7 @@ if (isset($_REQUEST['load_ajax'])) {
                 if (empty($result) || !in_array($user_id, array_keys($result))) {
                     if ($debug) echo 'User added to the session'; 
                     //Registering user to the new session
-                    SessionManager::suscribe_users_to_session($new_session_id,array($user_id),false);                    
+                    SessionManager::suscribe_users_to_session($new_session_id, array($user_id), false);                    
                 }            
                            
                 //Begin with the import process

+ 0 - 1
main/admin/usergroup_export.php

@@ -15,7 +15,6 @@ require_once '../inc/global.inc.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
 
 $tool_name = get_lang('Export');

+ 20 - 20
main/admin/usergroup_import.php

@@ -1,20 +1,20 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- * 	@package chamilo.admin
- */
+*	@package chamilo.admin
+*/
 /**
  * Code
- *   This     tool allows platform admins to add classes by uploading a CSV file
- * @todo Add some langvars to DLTT
- */
+*   This     tool allows platform admins to add classes by uploading a CSV file
+* @todo Add some langvars to DLTT
+*/
 
 /**
  * Validates imported data.
  */
 function validate_data($classes) {
     $errors = array();
-    $usergroup = new UserGroup();
+     $usergroup = new UserGroup();
     foreach ($classes as $index => $class) {
         // 1. Check wheter ClassName is available.
         if (!isset($class['name']) || strlen(trim($class['name'])) == 0) {
@@ -23,10 +23,10 @@ function validate_data($classes) {
             $errors[] = $class;
         }
         // 2. Check whether class doesn't exist yet.
-        else {
+        else {            
             if ($usergroup->usergroup_exists($class['name'])) {
                 $class['line'] = $index + 2;
-                $class['error'] = get_lang('ClassNameExists') . ' <strong>' . $class['ClassName'] . '</strong>';
+                $class['error'] = get_lang('ClassNameExists').' <strong>'.$class['ClassName'].'</strong>';
                 $errors[] = $class;
             }
         }
@@ -39,7 +39,7 @@ function validate_data($classes) {
  */
 function save_data($classes) {
     $number_of_added_classes = 0;
-    $usergroup = new UserGroup();
+    $usergroup = new UserGroup();    
     foreach ($classes as $index => $class) {
         $id = $usergroup->save($class);
         if ($id) {
@@ -50,15 +50,13 @@ function save_data($classes) {
 }
 
 // Language files that should be included.
-$language_file = array('admin', 'registration');
+$language_file = array ('admin', 'registration');
 
 // Resetting the course id.
 $cidReset = true;
 
-// Including some necessary dokeos files.
-include '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH) . 'fileManage.lib.php';
-require_once api_get_path(LIBRARY_PATH) . 'import.lib.php';
+// Including some necessary dokeos files
+require_once '../inc/global.inc.php';
 
 // Setting the section (for the tabs).
 $this_section = SECTION_PLATFORM_ADMIN;
@@ -67,10 +65,11 @@ $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
 
 // setting breadcrumbs
-$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array('url' => 'usergroups.php', 'name' => get_lang('Classes'));
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'usergroups.php', 'name' => get_lang('Classes'));
 
 // Database Table Definitions
+
 // Setting the name of the tool.
 $tool_name = get_lang('ImportClassListCSV');
 
@@ -82,7 +81,7 @@ set_time_limit(0);
 $form = new FormValidator('import_classes');
 $form->addElement('file', 'import_file', get_lang('ImportCSVFileLocation'));
 $group = array();
-$group[] = $form->createElement('radio', 'file_type', '', 'CSV (<a href="example_class.csv" target="_blank">' . get_lang('ExampleCSVFile') . '</a>)', 'csv');
+$group[] = $form->createElement('radio', 'file_type', '', 'CSV (<a href="example_class.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)', 'csv');
 $form->addGroup($group, '', get_lang('FileType'), '<br/>');
 $form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
 
@@ -91,12 +90,12 @@ if ($form->validate()) {
     $errors = validate_data($classes);
     if (count($errors) == 0) {
         $number_of_added_classes = save_data($classes);
-        Display::display_normal_message($number_of_added_classes . ' ' . get_lang('Added'));
+        Display::display_normal_message($number_of_added_classes.' '.get_lang('Added'));
     } else {
         $error_message = get_lang('ErrorsWhenImportingFile');
         $error_message .= '<ul>';
         foreach ($errors as $index => $error_class) {
-            $error_message .= '<li>' . $error_class['error'] . ' (' . get_lang('Line') . ' ' . $error_class['line'] . ')';
+            $error_message .= '<li>'.$error_class['error'].' ('.get_lang('Line').' '.$error_class['line'].')';
             $error_message .= '</li>';
         }
         $error_message .= '</ul>';
@@ -107,12 +106,13 @@ if ($form->validate()) {
 
 $form->display();
 ?>
-<p><?php echo get_lang('CSVMustLookLike') . ' (' . get_lang('MandatoryFields') . ')'; ?> :</p>
+<p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
 
 <pre>
 <b>name;description</b>
 "User group 1";"Description"
 </pre>
 <?php
+
 // Displaying the footer.
 Display :: display_footer();

+ 0 - 1132
main/announcements/announcements.inc.php

@@ -1,1132 +0,0 @@
-<?php
-
-/* For licensing terms, see /license.txt */
-/**
- * Include file with functions for the announcements module.
- * @package chamilo.announcements
- * @todo use OOP
- */
-
-/**
- * @author jmontoya
- *
- */
-class AnnouncementManager {
-
-    public function __construct() {
-
-    }
-
-    public static function get_tags() {
-        return array('((user_name))', '((teacher_name))', '((teacher_email))', '((course_title))', '((course_link))');
-    }
-
-    public static function parse_content($content, $course_code) {
-        $reader_info = api_get_user_info(api_get_user_id());
-        $course_info = api_get_course_info($course_code);
-        $teacher_list = CourseManager::get_teacher_list_from_course_code($course_info['code']);
-
-        $teacher_name = '';
-        if (!empty($teacher_list)) {
-            foreach ($teacher_list as $teacher_data) {
-                $teacher_name = api_get_person_name($teacher_data['firstname'], $teacher_data['lastname']);
-                $teacher_email = $teacher_data['email'];
-                break;
-            }
-        }
-        $course_link = api_get_course_url();
-
-        $data['username'] = $reader_info['username'];
-        $data['teacher_name'] = $teacher_name;
-        $data['teacher_email'] = $teacher_email;
-        $data['course_title'] = $course_info['name'];
-        $data['course_link'] = Display::url($course_link, $course_link);
-
-        $content = str_replace(self::get_tags(), $data, $content);
-        return $content;
-    }
-
-    /**
-     * Gets all announcements from a course
-     * @param	string course db
-     * @param	int session id
-     * @return	array html with the content and count of announcements or false otherwise
-     */
-    public static function get_all_annoucement_by_course($course_info, $session_id = 0) {
-        $session_id = intval($session_id);
-        $course_id = $course_info['real_id'];
-
-        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
-        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
-
-        $sql = "SELECT DISTINCT announcement.id, announcement.title, announcement.content
-				FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties
-				WHERE   announcement.id = toolitemproperties.ref AND
-				        toolitemproperties.tool='announcement' AND
-				        announcement.session_id  = '$session_id' AND
-				        announcement.c_id = $course_id AND
-				        toolitemproperties.c_id = $course_id
-				ORDER BY display_order DESC";
-        $rs = Database::query($sql);
-        $num_rows = Database::num_rows($rs);
-        $result = array();
-        if ($num_rows > 0) {
-            $list = array();
-            while ($row = Database::fetch_array($rs)) {
-                $list[] = $row;
-            }
-            return $list;
-        }
-        return false;
-    }
-
-    /**
-     * This functions swithes the visibility a course resource
-     * using the visibility field in 'item_property'
-     * @param    array	the course array
-     * @param    int     ID of the element of the corresponding type
-     * @return   bool    False on failure, True on success
-     */
-    public static function change_visibility_announcement($_course, $id) {
-        $session_id = api_get_session_id();
-        $item_visibility = api_get_item_visibility($_course, TOOL_ANNOUNCEMENT, $id, $session_id);
-        if ($item_visibility == '1') {
-            api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, 'invisible', api_get_user_id());
-        } else {
-            api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, 'visible', api_get_user_id());
-        }
-        return true;
-    }
-
-    /**
-     * Deletes an announcement
-     * @param array the course array
-     * @param int 	the announcement id
-     */
-    public static function delete_announcement($_course, $id) {
-        api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, 'delete', api_get_user_id());
-    }
-
-    /**
-     * Deletes all announcements by course
-     * @param array the course array
-     */
-    public static function delete_all_announcements($_course) {
-        $announcements = self::get_all_annoucement_by_course($_course, api_get_session_id());
-
-
-        foreach ($announcements as $annon) {
-            api_item_property_update($_course, TOOL_ANNOUNCEMENT, $annon['id'], 'delete', api_get_user_id());
-        }
-    }
-
-    /**
-     * Displays one specific announcement
-     * @param $announcement_id, the id of the announcement you want to display
-     */
-    public static function display_announcement($announcement_id) {
-        if ($announcement_id != strval(intval($announcement_id))) {
-            return false;
-        } // potencial sql injection
-        global $charset;
-        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
-        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
-        $course_id = api_get_course_int_id();
-
-        if (api_is_allowed_to_edit(false, true) || (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
-            $sql_query = "  SELECT announcement.*, toolitemproperties.*
-                            FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties
-                            WHERE announcement.id = toolitemproperties.ref
-                            AND announcement.id = '$announcement_id'
-                            AND toolitemproperties.tool='announcement' AND
-                            announcement.c_id = $course_id AND
-							toolitemproperties.c_id = $course_id
-                            ORDER BY display_order DESC";
-        } else {
-
-            $group_list = GroupManager::get_group_ids($course_id, api_get_user_id());
-            if (empty($group_list)) {
-                $group_list[] = 0;
-            }
-            if (api_get_user_id() != 0) {
-                $sql_query = "	SELECT announcement.*, toolitemproperties.*
-    							FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties
-    							WHERE announcement.id = toolitemproperties.ref
-    							AND announcement.id = '$announcement_id'
-    							AND toolitemproperties.tool='announcement'
-    							AND (toolitemproperties.to_user_id='" . api_get_user_id() . "' OR toolitemproperties.to_group_id IN ('0', '" . implode("', '", $group_list) . "'))
-    							AND toolitemproperties.visibility='1' AND
-    							announcement.c_id = $course_id AND
-								toolitemproperties.c_id = $course_id
-    							ORDER BY display_order DESC";
-            } else {
-                $sql_query = "	SELECT announcement.*, toolitemproperties.*
-    							FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties
-    							WHERE announcement.id = toolitemproperties.ref
-    							AND announcement.id = '$announcement_id'
-    							AND toolitemproperties.tool='announcement'
-    							AND toolitemproperties.to_group_id='0'
-    							AND toolitemproperties.visibility='1' AND
-    							announcement.c_id = $course_id AND
-								toolitemproperties.c_id = $course_id
-    							";
-            }
-        }
-
-        $sql_result = Database::query($sql_query);
-        if (Database::num_rows($sql_result) > 0) {
-            $result = Database::fetch_array($sql_result, 'ASSOC');
-            $title = $result['title'];
-            $content = $result['content'];
-            echo "<table height=\"100\" width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" class=\"data_table\">";
-            echo "<tr><td><h2>" . $title . "</h2></td></tr>";
-
-            if (api_is_allowed_to_edit(false, true) || (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
-                $modify_icons = "<a href=\"" . api_get_self() . "?" . api_get_cidreq() . "&action=modify&id=" . $announcement_id . "\">" . Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL) . "</a>";
-                if ($result['visibility'] == 1) {
-                    $image_visibility = "visible";
-                    $alt_visibility = get_lang('Hide');
-                } else {
-                    $image_visibility = "invisible";
-                    $alt_visibility = get_lang('Visible');
-                }
-                global $stok;
-
-                $modify_icons .= "<a href=\"" . api_get_self() . "?" . api_get_cidreq() . "&origin=" . (!empty($_GET['origin']) ? Security::remove_XSS($_GET['origin']) : '') . "&action=showhide&id=" . $announcement_id . "&sec_token=" . $stok . "\">" .
-                        Display::return_icon($image_visibility . '.png', $alt_visibility, '', ICON_SIZE_SMALL) . "</a>";
-
-                if (api_is_allowed_to_edit(false, true)) {
-                    $modify_icons .= "<a href=\"" . api_get_self() . "?" . api_get_cidreq() . "&action=delete&id=" . $announcement_id . "&sec_token=" . $stok . "\" onclick=\"javascript:if(!confirm('" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset)) . "')) return false;\">" .
-                            Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) .
-                            "</a>";
-                }
-                echo "<tr><th style='text-align:right'>$modify_icons</th></tr>";
-            }
-
-            $content = self::parse_content($content, api_get_course_id());
-
-            echo "<tr><td>$content</td></tr>";
-
-            echo "<tr><td class=\"announcements_datum\">" . get_lang('LastUpdateDate') . " : " . api_convert_and_format_date($result['insert_date'], DATE_TIME_FORMAT_LONG) . "</td></tr>";
-
-            // User or group icon
-            $sent_to_icon = '';
-            if ($result['to_group_id'] !== '0' and $result['to_group_id'] !== 'NULL') {
-                $sent_to_icon = Display::return_icon('group.gif', get_lang('AnnounceSentToUserSelection'));
-            }
-            $sent_to = self::sent_to('announcement', $announcement_id);
-
-            $sent_to_form = self::sent_to_form($sent_to);
-
-            echo Display::tag('td', get_lang('SentTo') . ' : ' . $sent_to_form, array('class' => 'announcements_datum'));
-
-            $attachment_list = self::get_attachment($announcement_id);
-
-            if (count($attachment_list) > 0) {
-                echo "<tr><td>";
-                $realname = $attachment_list['path'];
-                $user_filename = $attachment_list['filename'];
-                $full_file_name = 'download.php?file=' . $realname;
-                echo '<br/>';
-                echo Display::return_icon('attachment.gif', get_lang('Attachment'));
-                echo '<a href="' . $full_file_name . ' "> ' . $user_filename . ' </a>';
-                echo ' - <span class="forum_attach_comment" >' . $attachment_list['comment'] . '</span>';
-                if (api_is_allowed_to_edit(false, true)) {
-                    echo Display::url(Display::return_icon('delete.png', get_lang('Delete'), '', 16), api_get_self() . "?" . api_get_cidreq() . "&action=delete_attachment&id_attach=" . $attachment_list['id'] . "&sec_token=" . $stok);
-                }
-                echo '</td></tr>';
-            }
-            echo "</table>";
-        } else {
-            return false;
-        }
-    }
-
-    public static function get_last_announcement_order() {
-        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
-        $course_id = api_get_course_int_id();
-        $sql_max = "SELECT MAX(display_order) FROM $tbl_announcement WHERE c_id = $course_id ";
-        $res_max = Database::query($sql_max);
-
-        $order = 0;
-        if (Database::num_rows($res_max)) {
-            $row_max = Database::fetch_array($res_max);
-            $order   = intval($row_max[0])+1;
-        }
-        return $order;
-    }
-
-    /**
-     * Store an announcement in the database (including its attached file if any)
-     * @param string    Announcement title (pure text)
-     * @param string    Content of the announcement (can be HTML)
-     * @param int       Display order in the list of announcements
-     * @param array     Array of users and groups to send the announcement to
-     * @param array	    uploaded file $_FILES
-     * @param string    Comment describing the attachment
-     * @return int      false on failure, ID of the announcement on success
-     */
-    public static function add_announcement($emailTitle, $newContent, $sent_to, $file = array(), $file_comment = null, $end_date = null) {
-        global $_course;
-        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
-
-        // filter data
-        $emailTitle = Database::escape_string($emailTitle);
-        $newContent = Database::escape_string($newContent);
-
-        if (empty($end_date)) {
-            $end_date = api_get_utc_datetime();
-        } else {
-            $end_date = Database::escape_string($end_date);
-        }
-
-        $course_id = api_get_course_int_id();
-
-        $order = self::get_last_announcement_order();
-
-        // store in the table announcement
-        $sql = "INSERT INTO $tbl_announcement SET
-				c_id 			= '$course_id',
-				content 		= '$newContent',
-				title 			= '$emailTitle',
-                end_date        = '$end_date',
-				display_order 	= '$order',
-				session_id		= " . api_get_session_id();
-        $result = Database::query($sql);
-        if ($result === false) {
-            return false;
-        } else {
-            //Store the attach file
-            $last_id = Database::insert_id();
-            if (!empty($file)) {
-                self::add_announcement_attachment_file($last_id, $file_comment, $_FILES['user_upload']);
-            }
-
-            // store in item_property (first the groups, then the users
-            if (!is_null($sent_to)) {
-                // !is_null($sent_to): when no user is selected we send it to everyone
-                $send_to = self::separate_users_groups($sent_to);
-                // storing the selected groups
-                if (is_array($send_to['groups'])) {
-                    foreach ($send_to['groups'] as $group) {
-                        api_item_property_update($_course, TOOL_ANNOUNCEMENT, $last_id, "AnnouncementAdded", api_get_user_id(), $group);
-                    }
-                }
-
-                // storing the selected users
-                if (is_array($send_to['users'])) {
-                    foreach ($send_to['users'] as $user) {
-                        api_item_property_update($_course, TOOL_ANNOUNCEMENT, $last_id, "AnnouncementAdded", api_get_user_id(), '', $user);
-                    }
-                }
-            } else {
-                // the message is sent to everyone, so we set the group to 0
-                api_item_property_update($_course, TOOL_ANNOUNCEMENT, $last_id, "AnnouncementAdded", api_get_user_id(), '0');
-            }
-            return $last_id;
-        }
-    }
-
-    /*
-      STORE ANNOUNCEMENT  GROUP ITEM
-     */
-
-    public static function add_group_announcement($emailTitle, $newContent, $to, $to_users, $file = array(), $file_comment = '') {
-        global $_course;
-
-        // database definitions
-        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
-
-        $emailTitle = Database::escape_string($emailTitle);
-        $newContent = Database::escape_string($newContent);
-        $order = self::get_last_announcement_order();
-
-        $now = api_get_utc_datetime();
-        $course_id = api_get_course_int_id();
-
-        // store in the table announcement
-        $sql = "INSERT INTO $tbl_announcement SET
-                c_id 			= '$course_id',
-                content 		= '$newContent',
-                title 			= '$emailTitle',
-                end_date 		= '$now',
-                display_order 	= '$order',
-                session_id		= " . api_get_session_id();
-        $result = Database::query($sql);
-        if ($result === false) {
-            return false;
-        }
-
-        //store the attach file
-        $last_id = Database::insert_id();
-        if (!empty($file)) {
-            $save_attachment = self::add_announcement_attachment_file($last_id, $file_comment, $file);
-        }
-
-        // store in item_property (first the groups, then the users
-
-        if (!isset($to_users)) { // !isset($to): when no user is selected we send it to everyone
-            $send_to = self::separate_users_groups($to);
-            // storing the selected groups
-            if (is_array($send_to['groups'])) {
-                foreach ($send_to['groups'] as $group) {
-                    api_item_property_update($_course, TOOL_ANNOUNCEMENT, $last_id, "AnnouncementAdded", api_get_user_id(), $group);
-                }
-            }
-        } else {
-            // the message is sent to everyone, so we set the group to 0
-            // storing the selected users
-            if (is_array($to_users)) {
-                foreach ($to_users as $user) {
-                    api_item_property_update($_course, TOOL_ANNOUNCEMENT, $last_id, "AnnouncementAdded", api_get_user_id(), '', $user);
-                }
-            }
-        }
-        return $last_id;
-    }
-
-    /*
-      EDIT ANNOUNCEMENT
-     */
-
-    /**
-     * This function stores the announcement item in the announcement table
-     * and updates the item_property table
-     *
-     * @param int 	id of the announcement
-     * @param string email
-     * @param string content
-     * @param array 	users that will receive the announcement
-     * @param mixed 	attachment
-     * @param string file comment
-     *
-     */
-    public static function edit_announcement($id, $emailTitle, $newContent, $to, $file = array(), $file_comment = '') {
-        global $_course;
-
-        $course_id = api_get_course_int_id();
-        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
-        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
-
-        $emailTitle = Database::escape_string($emailTitle);
-        $newContent = Database::escape_string($newContent);
-        $id = intval($id);
-
-        // store the modifications in the table announcement
-        $sql = "UPDATE $tbl_announcement SET content = '$newContent', title = '$emailTitle' WHERE c_id = $course_id AND id='$id'";
-        $result = Database::query($sql);
-
-        // save attachment file
-        $row_attach = self::get_attachment($id);
-        $id_attach = intval($row_attach['id']);
-
-        if (!empty($file)) {
-            if (empty($id_attach)) {
-                self::add_announcement_attachment_file($id, $file_comment, $file);
-            } else {
-                self::edit_announcement_attachment_file($id_attach, $file, $file_comment);
-            }
-        }
-
-        // we remove everything from item_property for this
-        $sql_delete = "DELETE FROM $tbl_item_property WHERE c_id = $course_id AND ref='$id' AND tool='announcement'";
-        $result = Database::query($sql_delete);
-
-        // store in item_property (first the groups, then the users
-
-        if (!is_null($to)) {
-            // !is_null($to): when no user is selected we send it to everyone
-
-            $send_to = self::separate_users_groups($to);
-
-            // storing the selected groups
-            if (is_array($send_to['groups'])) {
-                foreach ($send_to['groups'] as $group) {
-                    api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, "AnnouncementUpdated", api_get_user_id(), $group);
-                }
-            }
-            // storing the selected users
-            if (is_array($send_to['users'])) {
-                foreach ($send_to['users'] as $user) {
-                    api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, "AnnouncementUpdated", api_get_user_id(), 0, $user);
-                }
-            }
-        } else {
-            // the message is sent to everyone, so we set the group to 0
-            api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, "AnnouncementUpdated", api_get_user_id(), '0');
-        }
-    }
-
-    /*
-      MAIL FUNCTIONS
-     */
-
-    public static function update_mail_sent($insert_id) {
-        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
-        if ($insert_id != strval(intval($insert_id))) {
-            return false;
-        }
-        $insert_id = Database::escape_string($insert_id);
-        $course_id = api_get_course_int_id();
-        // store the modifications in the table tbl_annoucement
-        $sql = "UPDATE $tbl_announcement SET email_sent='1' WHERE c_id = $course_id AND id='$insert_id'";
-        Database::query($sql);
-    }
-
-    /**
-     * Gets all announcements from a user by course
-     * @param	string course db
-     * @param	int user id
-     * @return	array html with the content and count of announcements or false otherwise
-     */
-    public static function get_all_annoucement_by_user_course($course_code, $user_id) {
-
-        $course_info = api_get_course_info($course_code);
-        $course_id = $course_info['real_id'];
-
-        if (empty($user_id)) {
-            return false;
-        }
-        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
-        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
-        if (!empty($user_id) && is_numeric($user_id)) {
-            $user_id = intval($user_id);
-            $sql = "SELECT DISTINCT announcement.title, announcement.content
-					FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties
-					WHERE
-						announcement.c_id = $course_id AND
-						toolitemproperties.c_id = $course_id AND
-						announcement.id = toolitemproperties.ref AND
-						toolitemproperties.tool='announcement' AND
-						(toolitemproperties.insert_user_id='$user_id' AND (toolitemproperties.to_group_id='0' OR toolitemproperties.to_group_id is null))
-						AND toolitemproperties.visibility='1'
-						AND announcement.session_id  = 0
-					ORDER BY display_order DESC";
-            $rs = Database::query($sql);
-            $num_rows = Database::num_rows($rs);
-            $content = '';
-            $i = 0;
-            $result = array();
-            if ($num_rows > 0) {
-                while ($myrow = Database::fetch_array($rs)) {
-                    $content.= '<strong>' . $myrow['title'] . '</strong><br /><br />';
-                    $content.= $myrow['content'];
-                    $i++;
-                }
-                $result['content'] = $content;
-                $result['count'] = $i;
-                return $result;
-            }
-            return false;
-        }
-        return false;
-    }
-
-    /*
-      SHOW_TO_FORM
-     */
-
-    /**
-     * this function shows the form for sending a message to a specific group or user.
-     */
-    public static function show_to_form($to_already_selected) {
-
-        $user_list = self::get_course_users();
-        $group_list = self::get_course_groups();
-
-        if ($to_already_selected == '' || $to_already_selected == 'everyone') {
-            $to_already_selected = array();
-        }
-
-        echo "<table id=\"recipient_list\" style=\"display: none;\">";
-        echo '<tr>';
-
-        // the form containing all the groups and all the users of the course
-        echo '<td>';
-        echo "<strong>" . get_lang('Users') . "</strong><br />";
-        self::construct_not_selected_select_form($group_list, $user_list, $to_already_selected);
-        echo "</td>";
-
-        // the buttons for adding or removing groups/users
-        echo '<td valign="middle">';
-        echo '<button class="arrowr" type="button" onClick="javascript: move(this.form.elements[0], this.form.elements[3])" onClick="javascript: move(this.form.elements[0], this.form.elements[3])"></button>';
-        echo '<br /> <br />';
-        echo '<button class="arrowl" type="button" onClick="javascript: move(this.form.elements[3], this.form.elements[0])" onClick="javascript: move(this.form.elements[3], this.form.elements[0])"></button>';
-        echo "</td>";
-
-        echo "<td>";
-
-        // the form containing the selected groups and users
-        echo "<strong>" . get_lang('DestinationUsers') . "</strong><br />";
-        self::construct_selected_select_form($group_list, $user_list, $to_already_selected);
-        echo "</td>";
-        echo "</tr>";
-        echo "</table>";
-    }
-
-    /**
-     * this function shows the form for sending a message to a specific group or user.
-     */
-    public static function show_to_form_group($group_id) {
-        echo "<table id=\"recipient_list\" style=\"display: none;\">";
-        echo "<tr>";
-        echo "<td>";
-        echo "<select name=\"not_selected_form[]\" size=5 style=\"width:200px\" multiple>";
-        $group_users = GroupManager::get_subscribed_users($group_id);
-        foreach ($group_users as $user) {
-            echo '<option value="' . $user['user_id'] . '" title="' . sprintf(get_lang('LoginX'), $user['username']) . '" >' . api_get_person_name($user['firstname'], $user['lastname']) . '</option>';
-        }
-        echo '</select>';
-        echo "</td>";
-
-        // the buttons for adding or removing groups/users
-        echo "<td valign=\"middle\">";
-        echo '<button class="arrowr" type="button" onClick="javascript: move(this.form.elements[1], this.form.elements[4])" onClick="javascript: move(this.form.elements[1], this.form.elements[4])"></button>';
-        echo '<br /> <br />';
-        echo '<button class="arrowl" type="button" onClick="javascript: move(this.form.elements[4], this.form.elements[1])" onClick="javascript: move(this.form.elements[4], this.form.elements[1])"></button>';
-        echo "</td>";
-        echo "<td>";
-
-        echo "<select id=\"selectedform\" name=\"selectedform[]\" size=5 style=\"width:200px\" multiple>";
-        echo '</select>';
-
-        echo "</td>";
-        echo "</tr>";
-        echo "</table>";
-    }
-
-    /*
-      CONSTRUCT_NOT_SELECT_SELECT_FORM
-     */
-
-    /**
-     * this function shows the form for sending a message to a specific group or user.
-     */
-    public static function construct_not_selected_select_form($group_list = null, $user_list = null, $to_already_selected) {
-
-        echo '<select name="not_selected_form[]" size="7" class="span4" multiple>';
-        // adding the groups to the select form
-        if ($group_list) {
-            foreach ($group_list as $this_group) {
-                if (is_array($to_already_selected)) {
-                    if (!in_array("GROUP:" . $this_group['id'], $to_already_selected)) { // $to_already_selected is the array containing the groups (and users) that are already selected
-                        $user_label = ($this_group['userNb'] > 0) ? get_lang('Users') : get_lang('LowerCaseUser') ;
-                        $user_disabled = ($this_group['userNb'] > 0) ? "" : "disabled=disabled" ;
-                        echo "<option $user_disabled value=\"GROUP:" . $this_group['id'] . "\">",
-                        "G: ", $this_group['name'], " - " . $this_group['userNb'] . " " . $user_label .
-                        "</option>";
-                    }
-                }
-            }
-            // a divider
-            echo "<option value=\"\">---------------------------------------------------------</option>";
-        }
-        // adding the individual users to the select form
-        if ($user_list) {
-            foreach ($user_list as $this_user) {
-                if (is_array($to_already_selected)) {
-                    if (!in_array("USER:" . $this_user['user_id'], $to_already_selected)) { // $to_already_selected is the array containing the users (and groups) that are already selected
-                        echo "<option value=\"USER:" . $this_user['user_id'] . "\" title='" . sprintf(get_lang('LoginX'), $this_user['username']) . "'>",
-                        "", api_get_person_name($this_user['firstname'], $this_user['lastname']),
-                        "</option>";
-                    }
-                }
-            }
-        }
-        echo "</select>";
-    }
-
-    /*
-      CONSTRUCT_SELECTED_SELECT_FORM
-     */
-
-    /**
-     * this function shows the form for sending a message to a specific group or user.
-     */
-    public static function construct_selected_select_form($group_list = null, $user_list = null, $to_already_selected) {
-        // we separate the $to_already_selected array (containing groups AND users into
-        // two separate arrays
-        $groupuser = array();
-        if (is_array($to_already_selected)) {
-            $groupuser = self::separate_users_groups($to_already_selected);
-        }
-        $groups_to_already_selected = $groupuser['groups'];
-        $users_to_already_selected = $groupuser['users'];
-
-        // we load all the groups and all the users into a reference array that we use to search the name of the group / user
-        $ref_array_groups = self::get_course_groups();
-        $ref_array_users = self::get_course_users();
-
-        // we construct the form of the already selected groups / users
-        echo '<select id="selectedform" name="selectedform[]" size="7" multiple class="span4">';
-        if (is_array($to_already_selected)) {
-            foreach ($to_already_selected as $groupuser) {
-                list($type, $id) = explode(":", $groupuser);
-                if ($type == "GROUP") {
-                    echo "<option value=\"" . $groupuser . "\">G: " . $ref_array_groups[$id]['name'] . "</option>";
-                } else {
-                    foreach ($ref_array_users as $key => $value) {
-                        if ($value['user_id'] == $id) {
-                            echo "<option value=\"" . $groupuser . "\" title='" . sprintf(get_lang('LoginX'), $value['username']) . "'>" . api_get_person_name($value['firstname'], $value['lastname']) . "</option>";
-                            break;
-                        }
-                    }
-                }
-            }
-        } else {
-            if ($to_already_selected == 'everyone') {
-                // adding the groups to the select form
-                if (is_array($ref_array_groups)) {
-                    foreach ($ref_array_groups as $this_group) {
-                        //api_display_normal_message("group " . $thisGroup[id] . $thisGroup[name]);
-                        if (!is_array($to_already_selected) || !in_array("GROUP:" . $this_group['id'], $to_already_selected)) { // $to_already_selected is the array containing the groups (and users) that are already selected
-                            echo "<option value=\"GROUP:" . $this_group['id'] . "\">",
-                            "G: ", $this_group['name'], " &ndash; " . $this_group['userNb'] . " " . get_lang('Users') .
-                            "</option>";
-                        }
-                    }
-                }
-                // adding the individual users to the select form
-                foreach ($ref_array_users as $this_user) {
-                    if (!is_array($to_already_selected) || !in_array("USER:" . $this_user['user_id'], $to_already_selected)) { // $to_already_selected is the array containing the users (and groups) that are already selected
-                        echo "<option value=\"USER:", $this_user['user_id'], "\"  title='" . sprintf(get_lang('LoginX'), $user['username']) . "'>",
-                        "", api_get_person_name($this_user['firstname'], $this_user['lastname']),
-                        "</option>";
-                    }
-                }
-            }
-        }
-        echo "</select>";
-    }
-
-    /*
-      DATA FUNCTIONS
-     */
-
-    /**
-     * Returns announcement info from its id
-     *
-     * @param type $course_id
-     * @param type $annoucement_id
-     * @return array
-     */
-    public static function get_by_id($course_id, $annoucement_id) {
-        $annoucement_id = intval($annoucement_id);
-        $course_id = $course_id ? intval($course_id) : api_get_course_int_id();
-
-        $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
-        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
-
-        $sql = "SELECT DISTINCT announcement.id, announcement.title, announcement.content
-                           FROM $tbl_announcement announcement INNER JOIN $tbl_item_property toolitemproperties
-                           ON   announcement.id = toolitemproperties.ref AND
-                                announcement.c_id = $course_id AND
-                                toolitemproperties.c_id = $course_id
-                           WHERE toolitemproperties.tool='announcement' AND
-                                 announcement.id = $annoucement_id";
-        $result = Database::query($sql);
-        if (Database::num_rows($result)) {
-            return Database::fetch_array($result);
-        }
-        return array();
-    }
-
-    /**
-     * this function gets all the users of the course,
-     * including users from linked courses
-     * @todo deprecate this function, use CourseManager class
-     */
-    public static function get_course_users() {
-        //this would return only the users from real courses:
-        $session_id = api_get_session_id();
-        if ($session_id != 0) {
-            $user_list = CourseManager::get_real_and_linked_user_list(api_get_course_id(), true, $session_id);
-        } else {
-            $user_list = CourseManager::get_real_and_linked_user_list(api_get_course_id(), false, 0);
-        }
-
-        return $user_list;
-    }
-
-    /**
-     * this function gets all the groups of the course,
-     * not including linked courses
-     */
-    public static function get_course_groups() {
-        $session_id = api_get_session_id();
-        if ($session_id != 0) {
-            $new_group_list = CourseManager::get_group_list_of_course(api_get_course_id(), $session_id, 1);
-        } else {
-            $new_group_list = CourseManager::get_group_list_of_course(api_get_course_id(), 0, 1);
-        }
-        return $new_group_list;
-    }
-
-    /*
-     *
-      LOAD_EDIT_USERS
-     */
-
-    /**
-     * This tools loads all the users and all the groups who have received
-     * a specific item (in this case an announcement item)
-     */
-    public static function load_edit_users($tool, $id) {
-        $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
-        $tool = Database::escape_string($tool);
-        $id = Database::escape_string($id);
-        $course_id = api_get_course_int_id();
-
-        $sql = "SELECT * FROM $tbl_item_property WHERE c_id = $course_id AND tool='$tool' AND ref='$id'";
-        $result = Database::query($sql);
-        while ($row = Database::fetch_array($result)) {
-            $to_group = $row['to_group_id'];
-            switch ($to_group) {
-                // it was send to one specific user
-                case null:
-                    $to[] = "USER:" . $row['to_user_id'];
-                    break;
-                // it was sent to everyone
-                case 0:
-                    return "everyone";
-                    exit;
-                    break;
-                default:
-                    $to[] = "GROUP:" . $row['to_group_id'];
-            }
-        }
-        return $to;
-    }
-
-    /*
-      USER_GROUP_FILTER_JAVASCRIPT
-     */
-
-    /**
-     * returns the javascript for setting a filter
-     * this goes into the $htmlHeadXtra[] array
-     */
-    public static function user_group_filter_javascript() {
-        return "<script language=\"JavaScript\" type=\"text/JavaScript\">
-		<!--
-		function jumpMenu(targ,selObj,restore)
-		{
-		  eval(targ+\".location='\"+selObj.options[selObj.selectedIndex].value+\"'\");
-		  if (restore) selObj.selectedIndex=0;
-		}
-		//-->
-		</script>";
-    }
-
-    /*
-      TO_JAVASCRIPT
-     */
-
-    /**
-     * returns all the javascript that is required for easily
-     * setting the target people/groups
-     * this goes into the $htmlHeadXtra[] array
-     */
-    public static function to_javascript() {
-        $www = api_get_path(WEB_PATH);
-        /*
-         * Do not allow this kind of behaviour. js minifieds should be manage by the template class or assetic or whatever see #4757 for more info
-        if (api_get_setting('server_type') == 'test') {
-            $src = $www . 'main/announcements/resources/js/main.js';
-        } else {
-            $src = $www . 'main/announcements/resources/js/main.min.js';
-        }*/
-        $src = $www . 'main/announcements/resources/js/main.js';
-        $result = Javascript::tag($src);
-        $root = Chamilo::url();
-        $code = "var www = '$root';\n";
-        $code .= Javascript::get_lang('FieldRequired', 'Send2All', 'AddAnAttachment', 'Everybody');
-        $result .= Javascript::tag_code($code);
-        return $result;
-    }
-
-    /*
-      SENT_TO_FORM
-     */
-
-    /**
-     * constructs the form to display all the groups and users the message has been sent to
-     * input: 	$sent_to_array is a 2 dimensional array containing the groups and the users
-     * 			the first level is a distinction between groups and users:
-     * 			$sent_to_array['groups'] * and $sent_to_array['users']
-     * 			$sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array
-     * 			containing all the id's of the groups (resp. users) who have received this message.
-     * @author Patrick Cool <patrick.cool@>
-     */
-    public static function sent_to_form($sent_to_array) {
-        // we find all the names of the groups
-        $group_names = self::get_course_groups();
-
-        // we count the number of users and the number of groups
-        if (isset($sent_to_array['users'])) {
-            $number_users = count($sent_to_array['users']);
-        } else {
-            $number_users = 0;
-        }
-        if (isset($sent_to_array['groups'])) {
-            $number_groups = count($sent_to_array['groups']);
-        } else {
-            $number_groups = 0;
-        }
-        $total_numbers = $number_users + $number_groups;
-
-        // starting the form if there is more than one user/group
-        $output = array();
-        if ($total_numbers > 1) {
-            //$output.="<option>".get_lang("SentTo")."</option>";
-            // outputting the name of the groups
-            if (is_array($sent_to_array['groups'])) {
-                foreach ($sent_to_array['groups'] as $group_id) {
-                    $output[] = $group_names[$group_id]['name'];
-                }
-            }
-
-            if (isset($sent_to_array['users'])) {
-                if (is_array($sent_to_array['users'])) {
-                    foreach ($sent_to_array['users'] as $user_id) {
-                        $user_info = api_get_user_info($user_id);
-                        $output[] = $user_info['complete_name_with_username'];
-                    }
-                }
-            }
-        } else {
-            // there is only one user/group
-            if (isset($sent_to_array['users']) and is_array($sent_to_array['users'])) {
-                $user_info = api_get_user_info($sent_to_array['users'][0]);
-                $output[] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
-            }
-            if (isset($sent_to_array['groups']) and is_array($sent_to_array['groups']) and isset($sent_to_array['groups'][0]) and $sent_to_array['groups'][0] !== 0) {
-                $group_id = $sent_to_array['groups'][0];
-                $output[] = "&nbsp;" . $group_names[$group_id]['name'];
-            }
-            if (empty($sent_to_array['groups']) and empty($sent_to_array['users'])) {
-                $output[] = "&nbsp;" . get_lang('Everybody');
-            }
-        }
-
-        if (!empty($output)) {
-            $output = array_filter($output);
-            if (count($output) > 0) {
-                $output = implode(', ', $output);
-            }
-            return $output;
-        }
-    }
-
-    /*
-      SEPARATE_USERS_GROUPS
-     */
-
-    /**
-     * This function separates the users from the groups
-     * users have a value USER:XXX (with XXX the dokeos id
-     * groups have a value GROUP:YYY (with YYY the group id)
-     * @param    array   Array of strings that define the type and id of each destination
-     * @return   array   Array of groups and users (each an array of IDs)
-     */
-    public static function separate_users_groups($to) {
-        foreach ($to as $to_item) {
-            list($type, $id) = explode(':', $to_item);
-            switch ($type) {
-                case 'GROUP':
-                    $grouplist[] = intval($id);
-                    break;
-                case 'USER':
-                    $userlist[] = intval($id);
-                    break;
-            }
-        }
-
-        $send_to['groups'] = $grouplist;
-        $send_to['users'] = $userlist;
-        return $send_to;
-    }
-
-    /*
-      SENT_TO()
-     */
-
-    /**
-     * Returns all the users and all the groups a specific announcement item
-     * has been sent to
-     * @param    string  The tool (announcement, agenda, ...)
-     * @param    int     ID of the element of the corresponding type
-     * @return   array   Array of users and groups to whom the element has been sent
-     */
-    public static function sent_to($tool, $id) {
-        global $_course;
-        global $tbl_item_property;
-
-        $tool = Database::escape_string($tool);
-        $id = intval($id);
-
-        $sent_to_group = array();
-        $sent_to = array();
-        $course_id = api_get_course_int_id();
-
-        $sql = "SELECT to_group_id, to_user_id FROM $tbl_item_property WHERE c_id = $course_id AND tool = '$tool' AND ref=" . $id;
-        $result = Database::query($sql);
-
-        while ($row = Database::fetch_array($result)) {
-            // if to_group_id is null then it is sent to a specific user
-            // if to_group_id = 0 then it is sent to everybody
-            if ($row['to_group_id'] != 0) {
-                $sent_to_group[] = $row['to_group_id'];
-            }
-            // if to_user_id <> 0 then it is sent to a specific user
-            if ($row['to_user_id'] <> 0) {
-                $sent_to_user[] = $row['to_user_id'];
-            }
-        }
-        if (isset($sent_to_group)) {
-            $sent_to['groups'] = $sent_to_group;
-        }
-        if (isset($sent_to_user)) {
-            $sent_to['users'] = $sent_to_user;
-        }
-        return $sent_to;
-    }
-
-    /* 		ATTACHMENT FUNCTIONS	 */
-
-    /**
-     * Show a list with all the attachments according to the post's id
-     * @param int announcement id
-     * @return array with the post info
-     * @author Arthur Portugal
-     * @version November 2009, dokeos 1.8.6.2
-     */
-    public static function get_attachment($announcement_id) {
-        $tbl_announcement_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
-        $announcement_id = intval($announcement_id);
-        $course_id = api_get_course_int_id();
-        $row = array();
-        $sql = 'SELECT id, path, filename, comment FROM ' . $tbl_announcement_attachment . '
-				WHERE c_id = ' . $course_id . ' AND announcement_id = ' . $announcement_id . '';
-        $result = Database::query($sql);
-        if (Database::num_rows($result) != 0) {
-            $row = Database::fetch_array($result, 'ASSOC');
-        }
-        return $row;
-    }
-
-    /**
-     * This function add a attachment file into announcement
-     * @param int  announcement id
-     * @param string file comment
-     * @param array  uploaded file $_FILES
-     * @return int  -1 if failed, 0 if unknown (should not happen), 1 if success
-     */
-    public static function add_announcement_attachment_file($announcement_id, $file_comment, $file) {
-        global $_course;
-        $tbl_announcement_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
-        $return = 0;
-        $announcement_id = intval($announcement_id);
-        $course_id = api_get_course_int_id();
-
-        if (is_array($file) && $file['error'] == 0) {
-            $courseDir = $_course['path'] . '/upload/announcements'; // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
-            $sys_course_path = api_get_path(SYS_COURSE_PATH);
-            $updir = $sys_course_path . $courseDir;
-
-            // Try to add an extension to the file if it hasn't one
-            $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
-            // user's file name
-            $file_name = $file['name'];
-
-            if (!filter_extension($new_file_name)) {
-                $return = -1;
-                Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
-            } else {
-                $new_file_name = uniqid('');
-                $new_path = $updir . '/' . $new_file_name;
-                $result = @move_uploaded_file($file['tmp_name'], $new_path);
-                $safe_file_comment = Database::escape_string($file_comment);
-                $safe_file_name = Database::escape_string($file_name);
-                $safe_new_file_name = Database::escape_string($new_file_name);
-                // Storing the attachments if any
-                $sql = 'INSERT INTO ' . $tbl_announcement_attachment . ' (c_id, filename, comment, path, announcement_id, size) ' .
-                        "VALUES ($course_id, '$safe_file_name', '$file_comment', '$safe_new_file_name' , '$announcement_id', '" . intval($file['size']) . "' )";
-                $result = Database::query($sql);
-                $return = 1;
-            }
-        }
-        return $return;
-    }
-
-    /**
-     * This function edit a attachment file into announcement
-     * @param int attach id
-     * @param array uploaded file $_FILES
-     * @param string file comment
-     * @return int
-     */
-    public static function edit_announcement_attachment_file($id_attach, $file, $file_comment) {
-        global $_course;
-        $tbl_announcement_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
-        $return = 0;
-        $course_id = api_get_course_int_id();
-
-        if (is_array($file) && $file['error'] == 0) {
-            $courseDir = $_course['path'] . '/upload/announcements'; // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
-            $sys_course_path = api_get_path(SYS_COURSE_PATH);
-            $updir = $sys_course_path . $courseDir;
-
-            // Try to add an extension to the file if it hasn't one
-            $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
-            // user's file name
-            $file_name = $file ['name'];
-
-            if (!filter_extension($new_file_name)) {
-                $return - 1;
-                Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
-            } else {
-                $new_file_name = uniqid('');
-                $new_path = $updir . '/' . $new_file_name;
-                $result = @move_uploaded_file($file['tmp_name'], $new_path);
-                $safe_file_comment = Database::escape_string($file_comment);
-                $safe_file_name = Database::escape_string($file_name);
-                $safe_new_file_name = Database::escape_string($new_file_name);
-                $id_attach = intval($id_attach);
-                $sql = "UPDATE $tbl_announcement_attachment SET filename = '$safe_file_name', comment = '$safe_file_comment', path = '$safe_new_file_name', size ='" . intval($file['size']) . "'
-					 	WHERE c_id = $course_id AND id = '$id_attach'";
-                $result = Database::query($sql);
-                if ($result === false) {
-                    $return = -1;
-                    Display :: display_error_message(get_lang('UplUnableToSaveFile'));
-                } else {
-                    $return = 1;
-                }
-            }
-        }
-        return $return;
-    }
-
-    /**
-     * This function delete a attachment file by id
-     * @param integer attachment file Id
-     *
-     */
-    public static function delete_announcement_attachment_file($id) {
-        $tbl_announcement_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
-        $id = intval($id);
-        $course_id = api_get_course_int_id();
-        $sql = "DELETE FROM $tbl_announcement_attachment WHERE c_id = $course_id AND id = $id";
-        $result = Database::query($sql);
-        // update item_property
-        //api_item_property_update($_course, 'announcement_attachment',  $id,'AnnouncementAttachmentDeleted', api_get_user_id());
-    }
-
-    public static function send_email($annoucement_id) {
-        $email = AnnouncementEmail::create(null, $annoucement_id);
-        $email->send();
-    }
-
-}
-
-//end class

File diff suppressed because it is too large
+ 390 - 410
main/announcements/announcements.php


+ 34 - 25
main/attendance/attendance_controller.php

@@ -19,6 +19,7 @@
 
  class AttendanceController
  {
+
  	/**
 	 * Constructor
 	 */
@@ -33,12 +34,9 @@
 	 * @param boolean   true for listing history (optional)
 	 * @param array 	message for showing by action['edit','add','delete'] (optional)
 	 */
-	public function attendance_list($history=false,$messages=array()) {
-		$attendance = new Attendance();
-		$data = array();
-
+	public function attendance_list($history = false, $messages = array()) {
 		// render to the view
-		$this->view->set_data($data);
+		$this->view->set_data(array());
 		$this->view->set_layout('layout');
 		$this->view->set_template('attendance_list');
 		$this->view->render();
@@ -163,7 +161,6 @@
 	 */
 	public function attendance_delete($attendance_id) {
 		$attendance = new Attendance();
-		//$attendance_id = intval($attendance_id);
 		if (!empty($attendance_id)) {
 			$affected_rows = $attendance->attendance_delete($attendance_id);
 		}
@@ -179,7 +176,6 @@
 	 */
 	public function attendance_restore($attendance_id) {
 		$attendance = new Attendance();
-		//$attendance_id = intval($attendance_id);
 		if (!empty($attendance_id)) {
 			$affected_rows = $attendance->attendance_restore($attendance_id);
 		}
@@ -222,14 +218,22 @@
 	 * @param string action
 	 * @param int	 attendance id
 	 */
-	public function attendance_sheet($action, $attendance_id, $student_id = 0, $edit = true) {
+	public function attendance_sheet($action, $attendance_id, $user_id = 0, $edit = true) {
 		$attendance = new Attendance();
 		$data = array();
-		$data['attendance_id'] = $attendance_id;
+		$data['attendance_id']   = $attendance_id;
+        $data['attendance_obj'] = $attendance;
+        $data['attendance_states']   = $attendance->get_attendance_states();
 		$data['users_in_course'] = $attendance->get_users_rel_course($attendance_id);
 
 		$filter_type = 'today';
 
+        if (!empty($user_id)) {
+            $user_id = intval($user_id);
+        } else {
+            $user_id = api_get_user_id();
+        }
+
 		if (!empty($_REQUEST['filter'])) {
 			$filter_type = $_REQUEST['filter'];
 		}
@@ -237,22 +241,13 @@
         if ($edit == true) {
             if (api_is_allowed_to_edit(null, true)) {
                 $data['users_presence'] = $attendance->get_users_attendance_sheet($attendance_id);
-            } else {
-
             }
         } else {
-            if (!empty($student_id)) {
-                $user_id = intval($student_id);
-            } else {
-                $user_id = api_get_user_id();
-            }
-
             if (api_is_allowed_to_edit(null, true) || api_is_coach(api_get_session_id(), api_get_course_id())) {
                 $data['users_presence']  = $attendance->get_users_attendance_sheet($attendance_id);
             } else {
                 $data['users_presence']  = $attendance->get_users_attendance_sheet($attendance_id, $user_id);
             }
-
             $data['faults']  = $attendance->get_faults_of_user($user_id, $attendance_id);
             $data['user_id'] = $user_id;
         }
@@ -263,16 +258,30 @@
 		if (strtoupper($_SERVER['REQUEST_METHOD']) == "POST") {
 
 			if (isset($_POST['hidden_input'])) {
-				foreach ($_POST['hidden_input'] as $cal_id) {
-					$users_present = array();
+                $columns_to_update = $_POST['hidden_input'];
+                $columns_to_update = array_unique(array_filter($columns_to_update));
+				foreach ($columns_to_update as $cal_id) {
+					$users_result = array();
 					if (isset($_POST['check_presence'][$cal_id])) {
-						$users_present = $_POST['check_presence'][$cal_id];
+						$users_result = $_POST['check_presence'][$cal_id];
 					}
-					$affected_rows = $attendance->attendance_sheet_add($cal_id,$users_present,$attendance_id);
+                    $user_final_results = array();
+                    if (!empty($users_result)) {
+                        foreach ($users_result as $result) {
+                            //Example: state_1_link_2_12_3  ==> state_[stateid]_YY_[userid]_calid
+                            $user_status = explode('_', $result);
+                            if (isset($user_status[0]) && $user_status[0] == 'state' && isset($user_status[4]) && isset($user_status[1])) {
+                               $user_final_results[$user_status[4]] = $user_status[1];
+                            }
+                        }
+                    }
+
+                    if (!empty($user_final_results)) {
+                        $attendance->attendance_sheet_add($cal_id, $user_final_results, $attendance_id, false, true);
+                    }
 				}
 			}
-
-			$data['users_in_course'] 			 = $attendance->get_users_rel_course($attendance_id);
+			$data['users_in_course'] = $attendance->get_users_rel_course($attendance_id);
 			$my_calendar_id = null;
 			if (is_numeric($filter_type)) {
 			    $my_calendar_id = $filter_type;
@@ -487,7 +496,7 @@
         }
         $max_cols_per_page = 12; //10 dates + 2 name and number
         $max_dates_per_page = $max_dates_per_page_original = $max_cols_per_page - 2;//10
-        //var_dump($cols);exit;
+
         $rows = count($data_table);
 
         if ($cols > $max_cols_per_page) {

+ 46 - 2
main/attendance/attendance_list.php

@@ -7,6 +7,7 @@
 * @package chamilo.attendance
 */
 
+
 // protect a course script
 api_protect_course_script(true);
 
@@ -19,7 +20,9 @@ if (api_is_allowed_to_edit(null, true)) {
 	echo '<a href="index.php?'.api_get_cidreq().$param_gradebook.'&action=attendance_add">'.Display::return_icon('new_attendance_list.png',get_lang('CreateANewAttendance'),'',ICON_SIZE_MEDIUM).'</a>';	
 	echo '</div>';
 }
-   
+
+/*
+
 $table = new SortableTable('attendance_list', array('Attendance', 'get_number_of_attendances'), array('Attendance', 'get_attendance_data'), $default_column);
 $table->set_additional_parameters($parameters);
 $table->set_header(0, '', false, array('style'=>'width:20px;'));
@@ -34,4 +37,45 @@ if (api_is_allowed_to_edit(null, true)) {
 
 if ($table->get_total_number_of_items() > 0) {
 	$table->display();
-}
+}*/
+
+
+
+//jqgrid will use this URL to do the selects
+//$url            = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_careers';
+
+//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('Description'), get_lang('CountDoneAttendance'));
+
+//Column config
+$column_model   = array(
+                        array('name'=>'name',           'index'=>'name',        'width'=>'300',   'align'=>'left'),
+                        array('name'=>'description',    'index'=>'description', 'width'=>'200',  'align'=>'left','sortable'=>'false'),
+                        array('name'=>'attendance_qualify_max',    'index'=>'attendance_qualify_max', 'width'=>'80',  'align'=>'left','sortable'=>'false')                        
+                       );
+
+if (api_is_allowed_to_edit(null, true)) {
+    $columns[] = get_lang('Actions');
+    $column_model[] = array('name'=>'actions',        'index'=>'actions',     'width'=>'100',  'align'=>'left','sortable'=>'false');
+}
+
+$extra_params = array();
+//Autowidth             
+$extra_params['autowidth'] = 'true';
+//height auto 
+$extra_params['height'] = 'auto'; 
+
+$data = Attendance::get_attendance_data();
+
+?>
+<script>
+$(function() {
+<?php 
+    // grid definition see the $career->display() function
+    echo Display::grid_js('attendance',  'false', $columns, $column_model, $extra_params, $data, null, true);       
+?> 
+});
+</script>
+<?php
+
+echo Display::grid_html('attendance');  

+ 237 - 164
main/attendance/attendance_sheet.php

@@ -2,7 +2,7 @@
 /* For licensing terms, see /license.txt */
 
 /**
-* View (MVC patter) for attendance sheet (list, edit, add) 
+* View (MVC patter) for attendance sheet (list, edit, add)
 * @author Christian Fasanando <christian1827@gmail.com>
 * @author Julio Montoya reworked 2010
 * @package chamilo.attendance
@@ -12,64 +12,64 @@
 api_protect_course_script(true);
 
 if (api_is_allowed_to_edit(null, true) || api_is_coach(api_get_session_id(), api_get_course_id())) {
-    
+
     $param_gradebook = '';
     if (isset($_SESSION['gradebook'])) {
         $param_gradebook = '&gradebook='.$_SESSION['gradebook'];
-    }   
-    
-    $form = new FormValidator('filter', 'post', 'index.php?action=attendance_sheet_list&'.api_get_cidreq().$param_gradebook.'&attendance_id='.$attendance_id, null, array('class' => 'form-search pull-left'));    
+    }
+
+    $form = new FormValidator('filter', 'post', 'index.php?action=attendance_sheet_list&'.api_get_cidreq().$param_gradebook.'&attendance_id='.$attendance_id, null, array('class' => 'form-search pull-left'));
     $values = array(
-        'all'           => get_lang('All'), 
+        'all'           => get_lang('All'),
         'today'         => get_lang('Today'),
-        'all_done'      => get_lang('AllDone'), 
+        'all_done'      => get_lang('AllDone'),
         'all_not_done'  => get_lang('AllNotDone')
-    );                    
+    );
     $today = api_convert_and_format_date(null, DATE_FORMAT_SHORT);
     $exists_attendance_today = false;
-    
+
     if (!empty($attendant_calendar_all)) {
         $values[''] = '---------------';
         foreach($attendant_calendar_all as $attendance_date) {
             if ($today == $attendance_date['date']) {
-                $exists_attendance_today = true; 
-            }                        
+                $exists_attendance_today = true;
+            }
             $values[$attendance_date['id']] = $attendance_date['date_time'];
         }
     }
-    
+
     if (!$exists_attendance_today) {
         Display::display_warning_message(get_lang('ThereIsNoClassScheduledTodayTryPickingAnotherDay'));
     }
-    
-    $form->addElement('select', 'filter', get_lang('Filter'), $values, array('id' => 'filter_id'));   
+
+    $form->addElement('select', 'filter', get_lang('Filter'), $values, array('id' => 'filter_id'));
     $form->addElement('style_submit_button', null, get_lang('Filter'), 'class="filter"');
-    
-    if (isset($_REQUEST['filter'])) {        
+
+    if (isset($_REQUEST['filter'])) {
         if (in_array($_REQUEST['filter'], array_keys($values))) {
             $default_filter = $_REQUEST['filter'];
-        }       
+        }
     } else {
-        $default_filter = 'today';      
-    }  
-    
+        $default_filter = 'today';
+    }
+
     $renderer = $form->defaultRenderer();
     $renderer->setElementTemplate('{label} {element} ');
-    
+
     $form->setDefaults(array('filter'=>$default_filter));
-    
+
     if (!$is_locked_attendance || api_is_platform_admin()) {
         echo '<div class="actions">';
         echo '<a style="float:left;" href="index.php?'.api_get_cidreq().'&action=calendar_list&attendance_id='.$attendance_id.$param_gradebook.'">'.
                 Display::return_icon('attendance_calendar.png',get_lang('AttendanceCalendar'),'',ICON_SIZE_MEDIUM).'</a>';
         if (count($users_in_course) > 0) {
-            $form->display(); 
+            $form->display();
         }
         echo '<a id="pdf_export" style="float:left;"  href="index.php?'.api_get_cidreq().'&action=attendance_sheet_export_to_pdf&attendance_id='.$attendance_id.$param_gradebook.'&filter='.$default_filter.'">'.
                 Display::return_icon('pdf.png',get_lang('ExportToPDF'),'',ICON_SIZE_MEDIUM).'</a>';
         echo '</div>';
     }
-    
+
     $message_information = get_lang('AttendanceSheetDescription');
     if (!empty($message_information)) {
         $message = '<strong>'.get_lang('Information').'</strong><br />';
@@ -80,115 +80,172 @@ if (api_is_allowed_to_edit(null, true) || api_is_coach(api_get_session_id(), api
     if ($is_locked_attendance) {
         Display::display_warning_message(get_lang('TheAttendanceSheetIsLocked'), false);
     }
-    
+
     $param_filter = '&filter='.Security::remove_XSS($default_filter);
-    
+
     if (count($users_in_course) > 0) {
-        
-    ?>
-    <script>
-    var original_url = '';    
-    $("#filter_id").on('change', function() {
-       filter = $(this).val();
-       if (original_url == '') {
-          original_url = $("#pdf_export").attr('href');
-       }
-       new_url =  original_url + "&filter=" +filter
-       $("#pdf_export").attr('href', new_url);       
-    });
-    
-    function UpdateTableHeaders() {
-        $("div.divTableWithFloatingHeader").each(function() {
-            var originalHeaderRow = $(".tableFloatingHeaderOriginal", this);
-            var floatingHeaderRow = $(".tableFloatingHeader", this);
-            var offset = $(this).offset();
-            var scrollTop = $(window).scrollTop();
-            if ((scrollTop > offset.top) && (scrollTop < offset.top + $(this).height())) {
-                floatingHeaderRow.css("visibility", "hidden");
-                var topbar = 0;
-                if ($("#topbar").length != 0) {
-                    topbar = $("#topbar").height();
-                } else {                
-                    if ($(".subnav").length != 0) {
-                        topbar = $(".subnav").height();
-                    }
-                }
-                
-                var top_value = Math.min(scrollTop - offset.top, $(this).height() - floatingHeaderRow.height()) + topbar;
-                
-                floatingHeaderRow.css("top",  top_value + "px");
-
-                // Copy cell widths from original header
-                $("th", floatingHeaderRow).each(function(index) {
-                    var cellWidth = $("th", originalHeaderRow).eq(index).css('width');
-                    $(this).css('width', cellWidth);
-                });
-
-                // Copy row width from whole table
-                floatingHeaderRow.css("width", $(this).css("width")); 
-                floatingHeaderRow.css("visibility", "visible");
-                floatingHeaderRow.css("z-index", "1000");
-                originalHeaderRow.css("height", "80px");                  
+        foreach ($attendance_states as $id => $state) {
+            echo $attendance_obj->get_attendance_state_button($id, true).'&nbsp;';
+        }
+
+?>
+<script>
+var original_url = '';
+$("#filter_id").on('change', function() {
+   filter = $(this).val();
+   if (original_url == '') {
+      original_url = $("#pdf_export").attr('href');
+   }
+   new_url =  original_url + "&filter=" +filter
+   $("#pdf_export").attr('href', new_url);
+});
+
+function UpdateTableHeaders() {
+    $("div.divTableWithFloatingHeader").each(function() {
+        var originalHeaderRow = $(".tableFloatingHeaderOriginal", this);
+        var floatingHeaderRow = $(".tableFloatingHeader", this);
+        var offset = $(this).offset();
+        var scrollTop = $(window).scrollTop();
+        if ((scrollTop > offset.top) && (scrollTop < offset.top + $(this).height())) {
+            floatingHeaderRow.css("visibility", "hidden");
+            var topbar = 0;
+            if ($("#topbar").length != 0) {
+                topbar = $("#topbar").height();
             } else {
-                floatingHeaderRow.css("visibility", "hidden");
-                floatingHeaderRow.css("top", "0px");
+                if ($(".subnav").length != 0) {
+                    topbar = $(".subnav").height();
+                }
             }
-        });
-    }
 
-    $(document).ready(function() {
-		$("table.tableWithFloatingHeader").each(function() {
-            $(this).wrap("<div class=\"divTableWithFloatingHeader\" style=\"position:relative\"></div>");
-    
-            var originalHeaderRow = $("tr:first", this)
-            originalHeaderRow.before(originalHeaderRow.clone());
-            var clonedHeaderRow = $("tr:first", this)
-    
-            clonedHeaderRow.addClass("tableFloatingHeader");
-            clonedHeaderRow.css("position", "absolute");
-            clonedHeaderRow.css("top", "0px");
-            clonedHeaderRow.css("left", $(this).css("margin-left"));
-            clonedHeaderRow.css("visibility", "hidden");
-    
-            originalHeaderRow.addClass("tableFloatingHeaderOriginal");
-        });
-    
-        UpdateTableHeaders();
-        $(window).scroll(UpdateTableHeaders);
-        $(window).resize(UpdateTableHeaders);
+            var top_value = Math.min(scrollTop - offset.top, $(this).height() - floatingHeaderRow.height()) + topbar;
+
+            floatingHeaderRow.css("top",  top_value + "px");
+
+            // Copy cell widths from original header
+            $("th", floatingHeaderRow).each(function(index) {
+                var cellWidth = $("th", originalHeaderRow).eq(index).css('width');
+                $(this).css('width', cellWidth);
+            });
+
+            // Copy row width from whole table
+            floatingHeaderRow.css("width", $(this).css("width"));
+            floatingHeaderRow.css("visibility", "visible");
+            floatingHeaderRow.css("z-index", "1000");
+            originalHeaderRow.css("height", "40px");
+        } else {
+            floatingHeaderRow.css("visibility", "hidden");
+            floatingHeaderRow.css("top", "0px");
+        }
+    });
+}
+
+function save_checkboxes() {
+    $('#form_attendance_sheet').submit();
+}
+
+$(document).ready(function() {
+    $('.switch').click(function() {
+        var state = 0;
+        var my_class = 'btn';
+        var current_class = '';
+        var my_button = $(this);
+
+        if (my_button.is('.disabled')) {
+            return false;
+        }
+
+        if (my_button.is('.btn')) {
+            current_class = 'btn';
+            state = 1;
+            my_class = 'btn-success';
+        }
+
+        if (my_button.is('.btn-success')) {
+            current_class = 'btn-success';
+            state = 0;
+            my_class = 'btn-danger';
+        }
+
+         if (my_button.is('.btn-danger')) {
+            current_class = 'btn-danger';
+            state = 3;
+            my_class = 'btn-info';
+        }
+
+         if (my_button.is('.btn-info')) {
+            current_class = 'btn-info';
+            state = 2;
+            my_class = 'btn-warning';
+        }
+
+        if (my_button.is('.btn-warning')) {
+            current_class = 'btn-warning';
+            state = 4;
+            my_class = 'btn';
+        }
+
+        var id = my_button.attr('id');
+        $('#hidden_'+id).attr('value', 'state_'+state+'_'+id);
+
+        my_button.attr('data-state', state);
+        my_button.removeClass(current_class);
+
+        my_button.addClass('btn b1');
+        my_button.addClass(my_class);
     });
-	</script>
 
-    <form method="post" action="index.php?action=attendance_sheet_add&<?php echo api_get_cidreq().$param_gradebook.$param_filter ?>&attendance_id=<?php echo $attendance_id?>" >
-    
+    $("table.tableWithFloatingHeader").each(function() {
+        $(this).wrap("<div class=\"divTableWithFloatingHeader\" style=\"position:relative\"></div>");
+
+        var originalHeaderRow = $("tr:first", this)
+        originalHeaderRow.before(originalHeaderRow.clone());
+        var clonedHeaderRow = $("tr:first", this)
+
+        clonedHeaderRow.addClass("tableFloatingHeader");
+        clonedHeaderRow.css("position", "absolute");
+        clonedHeaderRow.css("top", "0px");
+        clonedHeaderRow.css("left", $(this).css("margin-left"));
+        clonedHeaderRow.css("visibility", "hidden");
+
+        originalHeaderRow.addClass("tableFloatingHeaderOriginal");
+    });
+
+    UpdateTableHeaders();
+    $(window).scroll(UpdateTableHeaders);
+    $(window).resize(UpdateTableHeaders);
+});
+</script>
+
+    <form id="form_attendance_sheet" method="post" action="index.php?action=attendance_sheet_add&<?php echo api_get_cidreq().$param_gradebook.$param_filter ?>&attendance_id=<?php echo $attendance_id?>" >
+
     <div class="attendance-sheet-content" style="width:100%;background-color:#E1E1E1;margin-top:20px;">
         <div class="divTableWithFloatingHeader attendance-users-table" style="width:45%;float:left;margin:0px;padding:0px;">
             <table class="tableWithFloatingHeader data_table" width="100%">
                 <thead>
-                <tr class="tableFloatingHeader" style="position: absolute; top: 0px; left: 0px; visibility: hidden; margin:0px;padding:0px" >   
+                <tr class="tableFloatingHeader" style="position: absolute; top: 0px; left: 0px; visibility: hidden; margin:0px;padding:0px" >
                     <th width="10px"><?php echo '#'; ?></th>
                     <th width="10px"><?php echo get_lang('Photo')?></th>
                     <th width="100px"><?php echo get_lang('LastName')?></th>
                     <th width="100px"><?php echo get_lang('FirstName')?></th>
                     <th width="100px"><?php echo get_lang('AttendancesFaults')?></th>
                 </tr>
-                <tr class="tableFloatingHeaderOriginal" >   
+                <tr class="tableFloatingHeaderOriginal" >
                     <th height="65px" width="10px"><?php echo '#';?></th>
                     <th width="10px"><?php echo get_lang('Photo')?></th>
                     <th width="150px"><?php echo get_lang('LastName')?></th>
                     <th width="140px"><?php echo get_lang('FirstName')?></th>
-                    <th width="100px"><?php echo get_lang('AttendancesFaults')?></th>
+                    <th width="92px"><?php echo get_lang('AttendancesFaults')?></th>
                 </tr>
                 </thead>
-                                
+
                 <tbody>
-                <?php 
+                <?php
                 $i = 1;
-                $class = '';                
+                $class = '';
                 foreach ($users_in_course as $data) {
                     $faults = 0;
                     if ($i%2 == 0) {
-                        $class='row_odd';                        
+                        $class='row_odd';
                     } else {
                         $class='row_even';
                     }
@@ -200,9 +257,9 @@ if (api_is_allowed_to_edit(null, true) || api_is_coach(api_get_session_id(), api
                         <td><span title="<?php echo $username ?>"><?php echo $data['lastname'] ?></span></td>
                         <td><?php echo $data['firstname'] ?></td>
                         <td>
-                            <div class="attendance-faults-bar" style="background-color:<?php echo (!empty($data['result_color_bar'])?$data['result_color_bar']:'none') ?>">
-                                <?php echo $data['attendance_result'] ?>
-                            </div>                        
+                            <div class="attendance-faults-bar">
+                                <?php echo Display::label($data['attendance_result'], $data['result_color_bar']); ?>
+                            </div>
                         </td>
                     </tr>
                 <?php
@@ -212,33 +269,38 @@ if (api_is_allowed_to_edit(null, true) || api_is_coach(api_get_session_id(), api
                 </tbody>
             </table>
         </div>
-        
-        <?php     
-        
+
+        <?php
+
         echo '<div class="divTableWithFloatingHeader attendance-calendar-table" style="margin:0px;padding:0px;float:left;width:55%;overflow:auto;overflow-y:hidden;">';
         echo '<table class="tableWithFloatingHeader data_table" width="100%">';
         echo '<thead>';
+        $result = null;
         if (count($attendant_calendar) > 0 ) {
             foreach ($attendant_calendar as $calendar) {
                 $date = $calendar['date'];
                 $time = $calendar['time'];
+
                 $datetime = $date.'<br />'.$time;
+                $datetime = api_format_date($calendar['date_time'], DATE_FORMAT_NUMBER_NO_YEAR);
 
                 $img_lock = Display::return_icon('lock.gif',get_lang('DateUnLock'),array('class'=>'img_lock','id'=>'datetime_column_'.$calendar['id']));
 
                 if (!empty($calendar['done_attendance'])){
-                    $datetime = '<font color="blue">'.$date.'<br />'.$time.'</font>';
+                    $datetime = '<font color="blue">'.$datetime.'</font>';
                 }
                 $disabled_check = 'disabled = "true"';
-                $input_hidden = '<input type="hidden" id="hidden_input_'.$calendar['id'].'" name="hidden_input[]" value="" disabled />';                        
+
                 if ($next_attendance_calendar_id == $calendar['id']) {
                     $input_hidden = '<input type="hidden" id="hidden_input_'.$calendar['id'].'" name="hidden_input[]" value="'.$calendar['id'].'" />';
                     $disabled_check = '';
                     $img_lock = Display::return_icon('unlock.gif',get_lang('DateLock'),array('class'=>'img_unlock','id'=>'datetime_column_'.$calendar['id']));
-                }                                   
+                } else {
+                    $input_hidden = '<input type="hidden" id="hidden_input_'.$calendar['id'].'" name="hidden_input[]" value="" />';
+                }
 
-                $result .= '<th width="800px">';
-                $result .= '<center><div style="font-size:10px;width:125px;">'.$datetime.'&nbsp;';
+                $result .= '<th width="800px" style="text-align:center">';
+                $result .= '<center><div style="width:40px;">'.$datetime.'<br />';
 
                 if (api_is_allowed_to_edit(null, true)) {
                     $result .= '<span id="attendance_lock" style="cursor:pointer">'.(!$is_locked_attendance || api_is_platform_admin()?$img_lock:'').'</span>';
@@ -246,72 +308,81 @@ if (api_is_allowed_to_edit(null, true) || api_is_coach(api_get_session_id(), api
 
                 if ($is_locked_attendance == false) {
                     if (api_is_allowed_to_edit(null, true)) {
-                        $result .= '<br /><input type="checkbox" class="checkbox_head_'.$calendar['id'].'" id="checkbox_head_'.$calendar['id'].'" '.$disabled_check.' checked="checked" />'.$input_hidden.'</div></center></th>';
+                        $result .= $input_hidden.'</div><center></th>';
                     }
                 }
-             }                  
+             }
         } else {
             $result  = '<th width="2000px"><span><a href="index.php?'.api_get_cidreq().'&action=calendar_list&attendance_id='.$attendance_id.$param_gradebook.'">';
             $result .= Display::return_icon('attendance_calendar.png',get_lang('AttendanceCalendar'),'',ICON_SIZE_MEDIUM).' '.get_lang('GoToAttendanceCalendar').'</a></span></th>';
         }
 
         echo '<tr class="tableFloatingHeader row_odd" style="position: absolute; top: 0px; left: 0px; visibility: hidden; margin:0px;padding:0px">';
-        echo $result; 
-        echo '</tr>';                
+        echo $result;
+        echo '</tr>';
         echo '<tr class="tableWithFloatingHeader row_odd">';
         echo $result;
         echo '</tr>';
         echo '</thead>';
-        
+
         echo '<tbody>';
         $i = 0;
+
+        $default_presence_value = $attendance_obj->get_default_attendance_state();
+
         foreach ($users_in_course as $user) {
             $class = '';
-            if ($i%2 == 0) {
-                $class = 'row_even';                        
+            if ($i % 2 == 0) {
+                $class = 'row_even';
             } else {
                 $class = 'row_odd';
             }
             echo '<tr class="'.$class.'">';
 
-            if (count($attendant_calendar) > 0 ) {                            
+            if (count($attendant_calendar) > 0 ) {
                 foreach ($attendant_calendar as $calendar) {
-                    $checked = 'checked';
-                    $presence = -1;
+                    $presence = $default_presence_value;
 
                     if (isset($users_presence[$user['user_id']][$calendar['id']]['presence'])) {
-                        $presence = $users_presence[$user['user_id']][$calendar['id']]['presence'];                                    
-                        if (intval($presence) == 1) {
-                            $checked = 'checked';
-                        } else {
-                            $checked = '';
-                        }
+                        $presence = isset($users_presence[$user['user_id']][$calendar['id']]['presence']) ? $users_presence[$user['user_id']][$calendar['id']]['presence'] : $default_presence_value;
                     } else {
                         //if the user wasn't registered at that time, consider unchecked
                         if ($next_attendance_calendar_datetime == 0 || $calendar['date_time'] < $next_attendance_calendar_datetime) {
-                            $checked = '';
+                            $presence = $default_presence_value;
                         }
                     }
                     $disabled = 'disabled';
                     $style_td = '';
 
                     if ($next_attendance_calendar_id == $calendar['id']) {
-                        if ($i%2==0)
+                        if ($i % 2 == 0)
                             $style_td = 'background-color:#eee;';
-                        else 
+                        else
                             $style_td = 'background-color:#dcdcdc;';
                         $disabled = '';
                     }
 
                     echo '<td style="'.$style_td.'" class="checkboxes_col_'.$calendar['id'].'">';
-                    echo '<div style="height:20px">';
-                    echo '<center>';
+                    echo '<div style="text-align:center; height:20px">';
+
                     if (api_is_allowed_to_edit(null, true)) {
                         if (!$is_locked_attendance || api_is_platform_admin()) {
-                            echo '<input type="checkbox" name="check_presence['.$calendar['id'].'][]" value="'.$user['user_id'].'" '.$disabled.' '.$checked.' />';
+                            //echo '<input type="checkbox" name="check_presence['.$calendar['id'].'][]" value="'.$user['user_id'].'" '.$disabled.' '.$checked.' />';
+                            foreach ($attendance_states as $key => $state) {
+                                $input_checked = null;
+                                if ($key == $presence) {
+                                    $input_checked = " checked=checked";
+                                }
+                                //echo Display::tag('label', '<input type="checkbox" name="check_presence['.$calendar['id'].'][]" value = "state_'.$key.'_'.$user['user_id'].'" '.$disabled.' '.$input_checked.' />&nbsp;'.$state, array('class'=> 'checkbox'));
+                            }
+                            $link_id = 'link_'.$key.'_'.$user['user_id'].'_'.$calendar['id'];
+                            $attributes = array('id' => $link_id, 'class' => 'switch '.$disabled);
+                            echo $attendance_obj->get_attendance_state_button($presence, false, $attributes);
+                            echo '<input id = "hidden_'.$link_id.'" type="hidden" name="check_presence['.$calendar['id'].'][]" '.$input_checked.' value="'.$presence.'" />';
+
                             echo '<span class="anchor_'.$calendar['id'].'"></span>';
-                        } else { 
-                            echo $presence ? Display::return_icon('checkbox_on.gif',get_lang('Presence')) : Display::return_icon('checkbox_off.gif',get_lang('Presence'));                            
+                        } else {
+                            echo $presence ? Display::return_icon('checkbox_on.gif',get_lang('Presence')) : Display::return_icon('checkbox_off.gif',get_lang('Presence'));
                         }
                     } else {
                         switch($presence) {
@@ -321,16 +392,16 @@ if (api_is_allowed_to_edit(null, true) || api_is_coach(api_get_session_id(), api
                             case 0:
                                 echo Display::return_icon('exclamation.png',get_lang('NotAttended'));
                                 break;
-                            case -1:                                
+                            case -1:
                                 //echo Display::return_icon('warning.png',get_lang('NotAttended'));
                                 break;
-                        }                        
+                        }
                     }
-                    echo '</center>';
+
                     echo '</div>';
                     echo '</td>';
                 }
-            } else { 
+            } else {
                 echo '<td class="checkboxes_col_'.$calendar['id'].'">';
                 echo '<div style="height:20px">';
                 echo '<center>&nbsp;</center>
@@ -338,30 +409,30 @@ if (api_is_allowed_to_edit(null, true) || api_is_coach(api_get_session_id(), api
                         </td>';
             }
             echo '</tr>';
-            $i++ ;            
+            $i++ ;
         }
         echo '</tbody></table>';
         echo '</div></div>';
     ?>
     <div class="clear"></div>
     <div style="margin-top:20px;">
-        <?php if (!$is_locked_attendance || api_is_platform_admin()) { 
+        <?php if (!$is_locked_attendance || api_is_platform_admin()) {
                 if (api_is_allowed_to_edit(null, true)) {
             ?>
-            <button type="submit" class="save"><?php echo get_lang('Save') ?></button>
+            <button onclick="save_checkboxes();" type="button" class="save"><?php echo get_lang('Save') ?></button>
         <?php }
             }
         ?>
     </div>
-    </form> 
-    <?php 
-    } else {  
-        echo Display::display_warning_message('<a href="'.api_get_path(WEB_CODE_PATH).'user/user.php?'.api_get_cidreq().'">'.get_lang('ThereAreNoRegisteredLearnersInsidetheCourse').'</a>', false);  
+    </form>
+    <?php
+    } else {
+        echo Display::display_warning_message('<a href="'.api_get_path(WEB_CODE_PATH).'user/user.php?'.api_get_cidreq().'">'.get_lang('ThereAreNoRegisteredLearnersInsidetheCourse').'</a>', false);
     }
 } else {
     echo Display::page_header(get_lang('AttendanceSheetReport'));
     // View for students
-?>      
+?>
     <?php if(!empty($users_presence)) { ?>
         <div>
             <table width="250px;">
@@ -379,29 +450,31 @@ if (api_is_allowed_to_edit(null, true) || api_is_coach(api_get_session_id(), api
             <th><?php echo get_lang('Attendance')?></th>
         </tr>
         <?php
-        
+
         if (!empty($users_presence)) {
             $i = 0;
-            foreach ($users_presence[$user_id] as $presence) { 
+            foreach ($users_presence[$user_id] as $presence) {
                 $class = '';
                 if ($i%2==0) {
                     $class = 'row_even';
                 } else {
                     $class = 'row_odd';
-                }  
+                }
             ?>
-            <tr class="<?php echo $class ?>">                    
-                <td>                        
-                    <?php echo $presence['presence']?Display::return_icon('checkbox_on.gif',get_lang('Presence')):Display::return_icon('checkbox_off.gif',get_lang('Presence')) ?>
-                    <?php echo "&nbsp; ".$presence['date_time'] ?>                                                                       
+            <tr class="<?php echo $class ?>">
+                <td>
+                    <?php
+                        echo $attendance_obj->get_attendance_state_button($presence['presence']);
+                        //echo $presence['presence']?Display::return_icon('checkbox_on.gif',get_lang('Presence')):Display::return_icon('checkbox_off.gif',get_lang('Presence'))
+                        echo "&nbsp; ".$presence['date_time'] ?>
                 </td>
-            </tr>                  
-        <?php } 
+            </tr>
+        <?php }
         } else { ?>
             <tr><td>
                 <center><?php echo get_lang('YouDoNotHaveDoneAttendances')?></center></td>
-            </tr> 
-        <?php }            
+            </tr>
+        <?php }
         ?>
     </table>
-<?php } ?>
+<?php } ?>

+ 85 - 70
main/attendance/index.php

@@ -1,16 +1,16 @@
 <?php
-
 /* For licensing terms, see /license.txt */
 
 /**
- * Template (front controller in MVC pattern) used for distpaching to the controllers depend on the current action
- * @author Christian Fasanando <christian1827@gmail.com>
- * @author Julio Montoya <gugli100@gmail.com> Bug fixing, sql improvements
- *
- * @package chamilo.attendance
- */
+* Template (front controller in MVC pattern) used for distpaching to the controllers depend on the current action
+* @author Christian Fasanando <christian1827@gmail.com>
+* @author Julio Montoya <gugli100@gmail.com> Bug fixing, sql improvements
+*
+* @package chamilo.attendance
+*/
+
 // name of the language file that needs to be included
-$language_file = array('course_description', 'course_info', 'userInfo', 'admin', 'agenda', 'tracking', 'gradebook');
+$language_file = array ('course_description', 'course_info', 'userInfo', 'admin', 'agenda','tracking', 'gradebook');
 
 // including files
 require_once '../inc/global.inc.php';
@@ -22,7 +22,7 @@ require_once 'attendance_controller.php';
 require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/fe/exportgradebook.php';
 require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
 
-$current_course_tool = TOOL_ATTENDANCE;
+$current_course_tool  = TOOL_ATTENDANCE;
 
 // current section
 $this_section = SECTION_COURSES;
@@ -41,34 +41,36 @@ $actions = array(
     'attendance_delete_select',
     'attendance_restore',
     'attendance_sheet_export_to_pdf',
-    'attendance_sheet_list_no_edit'
+    'attendance_sheet_list_no_edit',
+    'lock_attendance',
+    'unlock_attendance'
 );
 
 $actions_calendar = array('calendar_list', 'calendar_add', 'calendar_edit', 'calendar_delete', 'calendar_all_delete');
-$action = 'attendance_list';
+$action  = 'attendance_list';
 
 $course_id = '';
-if (isset($_GET['cidReq'])) {
+if (isset($_GET['cidReq'])){
     $course_id = $_GET['cidReq'];
 }
 
-if (isset($_GET['action']) && (in_array($_GET['action'], $actions) || in_array($_GET['action'], $actions_calendar))) {
-    $action = $_GET['action'];
+if (isset($_GET['action']) && (in_array($_GET['action'],$actions) || in_array($_GET['action'],$actions_calendar))) {
+	$action = $_GET['action'];
 }
 if (isset($_GET['isStudentView']) && $_GET['isStudentView'] == 'true') {
-    $action = 'attendance_list';
+	$action = 'attendance_list';
 }
 
 // get attendance id
 $attendance_id = 0;
 if (isset($_GET['attendance_id'])) {
-    $attendance_id = intval($_GET['attendance_id']);
+	$attendance_id = intval($_GET['attendance_id']);
 }
 
 // get calendar id
 $calendar_id = '';
 if (isset($_GET['calendar_id'])) {
-    $calendar_id = intval($_GET['calendar_id']);
+	$calendar_id = intval($_GET['calendar_id']);
 }
 
 // instance attendance object for using like library here
@@ -79,10 +81,12 @@ $attendance_controller = new AttendanceController();
 
 // get attendance data
 if (!empty($attendance_id)) {
-    // attendance data by id
-    $attendance_data = $attendance->get_attendance_by_id($attendance_id);
+	// attendance data by id
+	$attendance_data = $attendance->get_attendance_by_id($attendance_id);
 }
 
+$htmlHeadXtra[] = api_get_jqgrid_js();
+
 $htmlHeadXtra[] = '<script>
 
 $(function() {
@@ -105,6 +109,10 @@ $(function() {
 			$(this).attr("class","img_lock");
 			$("#hidden_input_"+calendar_id).attr("value","");
 			$("#hidden_input_"+calendar_id).attr("disabled",true);
+
+            $(".checkboxes_col_"+calendar_id).find(".switch").each(function(index) {
+                $(this).addClass("disabled");
+            });
 			return false;
 
 		} else {
@@ -112,6 +120,7 @@ $(function() {
 			$(".checkbox_head_"+calendar_id).attr("disabled", false);
 			$(".checkbox_head_"+calendar_id).removeAttr("disabled");
 
+
 			$(".row_odd  td.checkboxes_col_"+calendar_id).css({"opacity":"1","background-color":"#dcdcdc", "border-left":"1px #bbb solid", "border-right":"1px #bbb solid", "z-index":"1" });
 			$(".row_even td.checkboxes_col_"+calendar_id).css({"opacity":"1","background-color":"#eee", "border-left":"1px #bbb solid", "border-right":"1px #bbb solid", "z-index":"1" });
 
@@ -126,12 +135,17 @@ $(function() {
                 //	$("row_odd  td.checkboxes_col_"+calendar_id).css({"opacity":"1","background-color":"#FFF", 	  "border-left":"1px #EEEE00 solid", "border-right":"1px #EEEE00 solid" , "border-bottom":"1px #ccc solid" });
 			});
 
-			$(".checkboxes_col_"+calendar_id+" input:checkbox").attr("disabled",false);
+			$(".checkboxes_col_"+calendar_id).find(".switch").each(function(index) {
+                $(this).removeClass("disabled");
+            });
+
+
 			$(this).attr("src","'.api_get_path(WEB_CODE_PATH).'img/unlock.gif");
 			$(this).attr("title","'.get_lang('DateLock').'");
 			$(this).attr("alt","'.get_lang('DateLock').'");
 			$(this).attr("class","img_unlock");
 			$("#hidden_input_"+calendar_id).attr("disabled",false);
+
 			$("#hidden_input_"+calendar_id).attr("value",calendar_id);
 			return false;
 		}
@@ -161,10 +175,10 @@ $(function() {
 	$(".advanced_parameters").click(function() {
 		if ($("#id_qualify").css("display") == "none") {
 			$("#id_qualify").css("display","block");
-			$("#img_plus_and_minus").html(\'&nbsp;'.Display::return_icon('div_hide.gif', get_lang('Hide'), array('style' => 'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\');
+			$("#img_plus_and_minus").html(\'&nbsp;'.Display::return_icon('div_hide.gif',get_lang('Hide'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\');
 		} else {
 			$("#id_qualify").css("display","none");
-			$("#img_plus_and_minus").html(\'&nbsp;'.Display::return_icon('div_show.gif', get_lang('Show'), array('style' => 'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\');
+			$("#img_plus_and_minus").html(\'&nbsp;'.Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\');
 		}
 	});
 });
@@ -172,119 +186,120 @@ $(function() {
 </script>';
 
 // interbreadcrumbs
-if (!empty($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
-    $_SESSION['gradebook'] = Security::remove_XSS($_GET['gradebook']);
-    $gradebook = $_SESSION['gradebook'];
+if (!empty($_GET['gradebook']) && $_GET['gradebook']=='view' ) {
+	$_SESSION['gradebook']=Security::remove_XSS($_GET['gradebook']);
+	$gradebook=	$_SESSION['gradebook'];
 } elseif (empty($_GET['gradebook'])) {
-    unset($_SESSION['gradebook']);
-    $gradebook = '';
+	unset($_SESSION['gradebook']);
+	$gradebook=	'';
 }
 $param_gradebook = '';
 if (isset($_SESSION['gradebook'])) {
-    $param_gradebook = '&gradebook='.$gradebook;
+	$param_gradebook = '&gradebook='.$gradebook;
 }
 $student_param = '';
 $student_id = null;
 if (api_is_drh() && isset($_GET['student_id'])) {
-    $student_id = intval($_GET['student_id']);
-    $student_param = '&student_id='.$student_id;
-    $student_info = api_get_user_info($student_id);
-    $student_name = api_get_person_name($student_info['firstname'], $student_info['lastname']);
-    $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.$student_id, 'name' => $student_name);
+	$student_id = intval($_GET['student_id']);
+	$student_param = '&student_id='.$student_id;
+	$student_info  = api_get_user_info($student_id);
+	$student_name  =  api_get_person_name($student_info['firstname'],$student_info['lastname']);
+	$interbreadcrumb[] = array ('url' => api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.$student_id, 'name' => $student_name);
 }
 if (!empty($gradebook)) {
-    $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'gradebook/index.php', 'name' => get_lang('ToolGradebook'));
+	$interbreadcrumb[] = array ('url' => api_get_path(WEB_CODE_PATH).'gradebook/index.php', 'name' => get_lang('ToolGradebook'));
 }
-$interbreadcrumb[] = array('url' => 'index.php?'.api_get_cidreq().'&action=attendance_list'.$param_gradebook.$student_param, 'name' => get_lang('ToolAttendance'));
+$interbreadcrumb[] = array ('url' => 'index.php?'.api_get_cidreq().'&action=attendance_list'.$param_gradebook.$student_param, 'name' => get_lang('ToolAttendance'));
 if ($action == 'attendance_add') {
-    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('CreateANewAttendance'));
+	$interbreadcrumb[] = array ('url' => '#', 'name' => get_lang('CreateANewAttendance'));
 }
 if ($action == 'attendance_edit') {
-    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('Edit'));
+	$interbreadcrumb[] = array ('url' => '#', 'name' => get_lang('Edit'));
 }
 if ($action == 'attendance_sheet_list' || $action == 'attendance_sheet_add') {
-    $interbreadcrumb[] = array('url' => '#', 'name' => $attendance_data['name']);
+	$interbreadcrumb[] = array ('url' => '#', 'name' => $attendance_data['name']);
 }
 if ($action == 'calendar_list' || $action == 'calendar_edit' || $action == 'calendar_delete' || $action == 'calendar_all_delete') {
-    $interbreadcrumb[] = array('url' => 'index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance_id.$param_gradebook, 'name' => $attendance_data['name']);
-    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('AttendanceCalendar'));
+	$interbreadcrumb[] = array ('url' => 'index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance_id.$param_gradebook, 'name' => $attendance_data['name']);
+	$interbreadcrumb[] = array ('url' => '#', 'name' => get_lang('AttendanceCalendar'));
 }
 if ($action == 'calendar_add') {
-    $interbreadcrumb[] = array('url' => 'index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance_id.$param_gradebook, 'name' => $attendance_data['name']);
-    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('AddDateAndTime'));
+	$interbreadcrumb[] = array ('url' => 'index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance_id.$param_gradebook, 'name' => $attendance_data['name']);
+	$interbreadcrumb[] = array ('url' => '#', 'name' => get_lang('AddDateAndTime'));
 }
 
 // delete selected attendance
 if (isset($_POST['action']) && $_POST['action'] == 'attendance_delete_select') {
-    $attendance_controller->attendance_delete($_POST['id']);
+	$attendance_controller->attendance_delete($_POST['id']);
 }
 // distpacher actions to controller
 switch ($action) {
-    case 'attendance_list':
+	case 'attendance_list':
         $attendance_controller->attendance_list();
-        break;
-    case 'attendance_add':
+		break;
+	case 'attendance_add':
         if (api_is_allowed_to_edit(null, true)) {
             $attendance_controller->attendance_add();
         } else {
-            api_not_allowed();
+        	api_not_allowed();
         }
         break;
-    case 'attendance_edit' :
+	case 'attendance_edit'		:
         if (api_is_allowed_to_edit(null, true)) {
             $attendance_controller->attendance_edit($attendance_id);
         } else {
             api_not_allowed();
         }
-        break;
-    case 'attendance_delete' :
-        if (api_is_allowed_to_edit(null, true)) {
+		break;
+	case 'attendance_delete'	:
+    	if (api_is_allowed_to_edit(null, true)) {
             $attendance_controller->attendance_delete($attendance_id);
         } else {
             api_not_allowed();
         }
-        break;
-    case 'attendance_restore':
-        if (api_is_allowed_to_edit(null, true)) {
+		 break;
+	case 'attendance_restore':
+    	if (api_is_allowed_to_edit(null, true)) {
             $attendance_controller->attendance_restore($attendance_id);
         } else {
             api_not_allowed();
         }
-        break;
-    case 'attendance_sheet_list':
-        $attendance_controller->attendance_sheet($action, $attendance_id, $student_id, true);
-        break;
+		 break;
+	case 'attendance_sheet_list':
+        $edit_content = api_is_allowed_to_edit(null, true);
+        $attendance_controller->attendance_sheet($action, $attendance_id, $student_id, $edit_content);
+		break;
     case 'attendance_sheet_list_no_edit':
         $attendance_controller->attendance_sheet($action, $attendance_id, $student_id, false);
         break;
     case 'attendance_sheet_export_to_pdf':
         $attendance_controller->attendance_sheet_export_to_pdf($action, $attendance_id, $student_id, $course_id);
         break;
-    case 'attendance_sheet_add' :
+	case 'attendance_sheet_add' 	:
         if (api_is_allowed_to_edit(null, true)) {
             $attendance_controller->attendance_sheet($action, $attendance_id);
         } else {
             api_not_allowed();
         }
-        break;
-    case 'lock_attendance' :
-    case 'unlock_attendance' :
+		break;
+    case 'lock_attendance'          :
+    case 'unlock_attendance'        :
         if (api_is_allowed_to_edit(null, true)) {
             $attendance_controller->lock_attendance($action, $attendance_id);
         } else {
             api_not_allowed();
         }
         break;
-    case 'calendar_add' :
-    case 'calendar_edit' :
-    case 'calendar_all_delete' :
-    case 'calendar_delete' :
+	case 'calendar_add'  		:
+	case 'calendar_edit' 		:
+	case 'calendar_all_delete' 	:
+	case 'calendar_delete' 		:
         if (!api_is_allowed_to_edit(null, true)) {
             api_not_allowed();
         }
-    case 'calendar_list' :
+    case 'calendar_list'        :
         $attendance_controller->attendance_calendar($action, $attendance_id, $calendar_id);
-        break;
-    default :
+		break;
+	default		  		:
         $attendance_controller->attendance_list();
-}
+}

+ 1 - 1
main/auth/inscription.php

@@ -155,7 +155,7 @@ if ($user_already_registered_show_terms == false) {
     }
     // EXTRA FIELDS
     $extra_data = UserManager::get_extra_user_data(api_get_user_id(), true);
-    UserManager::set_extra_fields_in_form($form, $extra_data, 'registration');
+    ExtraField::set_extra_fields_in_form($form, $extra_data, 'registration', false, null, 'user');
 }
 
 if (isset($_SESSION['user_language_choice']) && $_SESSION['user_language_choice'] != '') {

+ 341 - 339
main/auth/profile.php

@@ -41,23 +41,23 @@ function confirmation(name) {
     }
 }
 function show_image(image,width,height) {
-    width = parseInt(width) + 20;
-    height = parseInt(height) + 20;
-    window_x = window.open(image,\'windowX\',\'width=\'+ width + \', height=\'+ height + \'\');
+	width = parseInt(width) + 20;
+	height = parseInt(height) + 20;
+	window_x = window.open(image,\'windowX\',\'width=\'+ width + \', height=\'+ height + \'\');
 
 }
 function generate_open_id_form() {
-    $.ajax({
-        contentType: "application/x-www-form-urlencoded",
-        beforeSend: function(objeto) {
-        /*$("#div_api_key").html("Loading...");*/ },
-        type: "POST",
-        url: "'.api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=generate_api_key",
-        data: "num_key_id="+"",
-        success: function(datos) {
-         $("#div_api_key").html(datos);
-        }
-    });
+	$.ajax({
+		contentType: "application/x-www-form-urlencoded",
+		beforeSend: function(objeto) {
+		/*$("#div_api_key").html("Loading...");*/ },
+		type: "POST",
+		url: "'.api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=generate_api_key",
+		data: "num_key_id="+"",
+		success: function(datos) {
+		 $("#div_api_key").html(datos);
+		}
+	});
 }
 
 function hide_icon_edit(element_html)  {
@@ -72,27 +72,27 @@ function show_icon_edit(element_html) {
 
 //$interbreadcrumb[] = array('url' => '../auth/profile.php', 'name' => get_lang('ModifyProfile'));
 if (!empty ($_GET['coursePath'])) {
-    $course_url = api_get_path(WEB_COURSE_PATH).htmlentities(strip_tags($_GET['coursePath'])).'/index.php';
-    $interbreadcrumb[] = array('url' => $course_url, 'name' => Security::remove_XSS($_GET['courseCode']));
+	$course_url = api_get_path(WEB_COURSE_PATH).htmlentities(strip_tags($_GET['coursePath'])).'/index.php';
+	$interbreadcrumb[] = array('url' => $course_url, 'name' => Security::remove_XSS($_GET['courseCode']));
 }
 
 $warning_msg = '';
 if (!empty($_GET['fe'])) {
-    $warning_msg .= get_lang('UplUnableToSaveFileFilteredExtension');
-    $_GET['fe'] = null;
+	$warning_msg .= get_lang('UplUnableToSaveFileFilteredExtension');
+	$_GET['fe'] = null;
 }
 
 $jquery_ready_content = '';
 if (api_get_setting('allow_message_tool') == 'true') {
-    $jquery_ready_content = <<<EOF
-            $(".message-content .message-delete").click(function(){
-                $(this).parents(".message-content").animate({ opacity: "hide" }, "slow");
-                $(".message-view").animate({ opacity: "show" }, "slow");
-            });
+	$jquery_ready_content = <<<EOF
+			$(".message-content .message-delete").click(function(){
+				$(this).parents(".message-content").animate({ opacity: "hide" }, "slow");
+				$(".message-view").animate({ opacity: "show" }, "slow");
+			});
 EOF;
 }
 
-//    Configuration file
+//	Configuration file
 require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
 
 // Libraries
@@ -102,7 +102,7 @@ require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 $tool_name = is_profile_editable() ? get_lang('ModifProfile') : get_lang('ViewProfile');
 $table_user = Database :: get_main_table(TABLE_MAIN_USER);
 
-/*    Form    */
+/*	Form	*/
 
 /*
  * Get initial values for all fields.
@@ -114,9 +114,9 @@ $value_array = $array_list_key[$id_temp_key];
 $user_data['api_key_generate'] = $value_array;
 
 if ($user_data !== false) {
-    if (is_null($user_data['language'])) {
-        $user_data['language'] = api_get_setting('platformLanguage');
-    }
+	if (is_null($user_data['language'])) {
+		$user_data['language'] = api_get_setting('platformLanguage');
+	}
 }
 
 /*
@@ -125,26 +125,26 @@ if ($user_data !== false) {
 $form = new FormValidator('profile', 'post', api_get_self()."?".str_replace('&fe=1', '', $_SERVER['QUERY_STRING']), null, array('style' => 'width: 70%; float: '.($text_dir == 'rtl' ? 'right;' : 'left;')));
 
 if (api_is_western_name_order()) {
-    //    FIRST NAME and LAST NAME
-    $form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
-    $form->addElement('text', 'lastname',  get_lang('LastName'),  array('size' => 40));
+	//	FIRST NAME and LAST NAME
+	$form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
+	$form->addElement('text', 'lastname',  get_lang('LastName'),  array('size' => 40));
 } else {
-    //    LAST NAME and FIRST NAME
-    $form->addElement('text', 'lastname',  get_lang('LastName'),  array('size' => 40));
-    $form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
+	//	LAST NAME and FIRST NAME
+	$form->addElement('text', 'lastname',  get_lang('LastName'),  array('size' => 40));
+	$form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
 }
 if (api_get_setting('profile', 'name') !== 'true') {
-    $form->freeze(array('lastname', 'firstname'));
+	$form->freeze(array('lastname', 'firstname'));
 }
 $form->applyFilter(array('lastname', 'firstname'), 'stripslashes');
 $form->applyFilter(array('lastname', 'firstname'), 'trim');
 $form->addRule('lastname' , get_lang('ThisFieldIsRequired'), 'required');
 $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
 
-//    USERNAME
+//	USERNAME
 $form->addElement('text', 'username', get_lang('UserName'), array('maxlength' => USERNAME_MAX_LENGTH, 'size' => USERNAME_MAX_LENGTH));
 if (api_get_setting('profile', 'login') !== 'true') {
-    $form->freeze('username');
+	$form->freeze('username');
 }
 $form->applyFilter('username', 'stripslashes');
 $form->applyFilter('username', 'trim');
@@ -152,23 +152,23 @@ $form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
 $form->addRule('username', get_lang('UsernameWrong'), 'username');
 $form->addRule('username', get_lang('UserTaken'), 'username_available', $user_data['username']);
 
-//    OFFICIAL CODE
+//	OFFICIAL CODE
 if (CONFVAL_ASK_FOR_OFFICIAL_CODE) {
-    $form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => 40));
-    if (api_get_setting('profile', 'officialcode') !== 'true') {
-        $form->freeze('official_code');
-    }
-    $form->applyFilter('official_code', 'stripslashes');
-    $form->applyFilter('official_code', 'trim');
-    if (api_get_setting('registration', 'officialcode') == 'true' && api_get_setting('profile', 'officialcode') == 'true') {
-        $form->addRule('official_code', get_lang('ThisFieldIsRequired'), 'required');
-    }
-}
-
-//    EMAIL
+	$form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => 40));
+	if (api_get_setting('profile', 'officialcode') !== 'true') {
+		$form->freeze('official_code');
+	}
+	$form->applyFilter('official_code', 'stripslashes');
+	$form->applyFilter('official_code', 'trim');
+	if (api_get_setting('registration', 'officialcode') == 'true' && api_get_setting('profile', 'officialcode') == 'true') {
+		$form->addRule('official_code', get_lang('ThisFieldIsRequired'), 'required');
+	}
+}
+
+//	EMAIL
 $form->addElement('email', 'email', get_lang('Email'), array('size' => 40));
 if (api_get_setting('profile', 'email') !== 'true') {
-    $form->freeze('email');
+	$form->freeze('email');
 }
 
 if (api_get_setting('registration', 'email') == 'true' &&  api_get_setting('profile', 'email') == 'true') {
@@ -180,43 +180,43 @@ if (api_get_setting('registration', 'email') == 'true' &&  api_get_setting('prof
 
 // OPENID URL
 if (is_profile_editable() && api_get_setting('openid_authentication') == 'true') {
-    $form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => 40));
-    if (api_get_setting('profile', 'openid') !== 'true') {
-        $form->freeze('openid');
-    }
-    $form->applyFilter('openid', 'trim');
-    //if (api_get_setting('registration', 'openid') == 'true') {
-    //    $form->addRule('openid', get_lang('ThisFieldIsRequired'), 'required');
-    //}
+	$form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => 40));
+	if (api_get_setting('profile', 'openid') !== 'true') {
+		$form->freeze('openid');
+	}
+	$form->applyFilter('openid', 'trim');
+	//if (api_get_setting('registration', 'openid') == 'true') {
+	//	$form->addRule('openid', get_lang('ThisFieldIsRequired'), 'required');
+	//}
 }
 
-//    PHONE
+//	PHONE
 $form->addElement('text', 'phone', get_lang('phone'), array('size' => 20));
 if (api_get_setting('profile', 'phone') !== 'true') {
-    $form->freeze('phone');
+	$form->freeze('phone');
 }
 $form->applyFilter('phone', 'stripslashes');
 $form->applyFilter('phone', 'trim');
 /*if (api_get_setting('registration', 'phone') == 'true') {
-    $form->addRule('phone', get_lang('ThisFieldIsRequired'), 'required');
+	$form->addRule('phone', get_lang('ThisFieldIsRequired'), 'required');
 }
 $form->addRule('phone', get_lang('EmailWrong'), 'email');*/
 
-//    PICTURE
+//	PICTURE
 if (is_profile_editable() && api_get_setting('profile', 'picture') == 'true') {
-    $form->addElement('file', 'picture', ($user_data['picture_uri'] != '' ? get_lang('UpdateImage') : get_lang('AddImage')));
-    $form->add_progress_bar();
-    if (!empty($user_data['picture_uri'])) {
-        $form->addElement('checkbox', 'remove_picture', null, get_lang('DelImage'));
-    }
-    $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
-    $form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
+	$form->addElement('file', 'picture', ($user_data['picture_uri'] != '' ? get_lang('UpdateImage') : get_lang('AddImage')));
+	$form->add_progress_bar();
+	if (!empty($user_data['picture_uri'])) {
+		$form->addElement('checkbox', 'remove_picture', null, get_lang('DelImage'));
+	}
+	$allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
+	$form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
 }
 
-//    LANGUAGE
+//	LANGUAGE
 $form->addElement('select_language', 'language', get_lang('Language'));
 if (api_get_setting('profile', 'language') !== 'true') {
-    $form->freeze('language');
+	$form->freeze('language');
 }
 
 //THEME
@@ -227,74 +227,72 @@ if (is_profile_editable() && api_get_setting('user_selected_theme') == 'true') {
     }
     $form->applyFilter('theme', 'trim');
 }
-
-
-//    EXTENDED PROFILE  this make the page very slow!
+//	EXTENDED PROFILE  this make the page very slow!
 if (api_get_setting('extended_profile') == 'true') {
-    if (!isset($_GET['type']) || (isset($_GET['type']) && $_GET['type'] == 'extended')) {
-        $width_extended_profile = 500;
-        //$form->addElement('html', '<a href="javascript: void(0);" onclick="javascript: show_extend();"> show_extend_profile</a>');
-        //$form->addElement('static', null, '<em>'.get_lang('OptionalTextFields').'</em>');
-        //    MY COMPETENCES
-        $form->add_html_editor('competences', get_lang('MyCompetences'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130'));
-        //    MY DIPLOMAS
-        $form->add_html_editor('diplomas', get_lang('MyDiplomas'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130'));
-        //    WHAT I AM ABLE TO TEACH
-        $form->add_html_editor('teach', get_lang('MyTeach'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130'));
-
-        //    MY PRODUCTIONS
-        $form->addElement('file', 'production', get_lang('MyProductions'));
-        if ($production_list = UserManager::build_production_list(api_get_user_id(), '', true)) {
-            $form->addElement('static', 'productions_list', null, $production_list);
-        }
-        //    MY PERSONAL OPEN AREA
-        $form->add_html_editor('openarea', get_lang('MyPersonalOpenArea'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '350'));
-        $form->applyFilter(array('competences', 'diplomas', 'teach', 'openarea'), 'stripslashes');
-        $form->applyFilter(array('competences', 'diplomas', 'teach'), 'trim'); // openarea is untrimmed for maximum openness
-    }
-}
-
-//    PASSWORD, if auth_source is platform
+	if (!isset($_GET['type']) || (isset($_GET['type']) && $_GET['type'] == 'extended')) {
+		$width_extended_profile = 500;
+		//$form->addElement('html', '<a href="javascript: void(0);" onclick="javascript: show_extend();"> show_extend_profile</a>');
+		//$form->addElement('static', null, '<em>'.get_lang('OptionalTextFields').'</em>');
+		//	MY COMPETENCES
+		$form->add_html_editor('competences', get_lang('MyCompetences'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130'));
+		//	MY DIPLOMAS
+		$form->add_html_editor('diplomas', get_lang('MyDiplomas'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130'));
+		//	WHAT I AM ABLE TO TEACH
+		$form->add_html_editor('teach', get_lang('MyTeach'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130'));
+
+		//	MY PRODUCTIONS
+		$form->addElement('file', 'production', get_lang('MyProductions'));
+		if ($production_list = UserManager::build_production_list(api_get_user_id(), '', true)) {
+			$form->addElement('static', 'productions_list', null, $production_list);
+		}
+		//	MY PERSONAL OPEN AREA
+		$form->add_html_editor('openarea', get_lang('MyPersonalOpenArea'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '350'));
+		$form->applyFilter(array('competences', 'diplomas', 'teach', 'openarea'), 'stripslashes');
+		$form->applyFilter(array('competences', 'diplomas', 'teach'), 'trim'); // openarea is untrimmed for maximum openness
+	}
+}
+
+//	PASSWORD, if auth_source is platform
 if (is_platform_authentication() && is_profile_editable() && api_get_setting('profile', 'password') == 'true') {
-    $form->addElement('password', 'password0', array(get_lang('Pass'), get_lang('Enter2passToChange')), array('size' => 40));
-    $form->addElement('password', 'password1', get_lang('NewPass'), array('size' => 40));
-    $form->addElement('password', 'password2', get_lang('Confirmation'), array('size' => 40));
-    //    user must enter identical password twice so we can prevent some user errors
-    $form->addRule(array('password1', 'password2'), get_lang('PassTwo'), 'compare');
-    if (CHECK_PASS_EASY_TO_FIND) {
-        $form->addRule('password1', get_lang('CurrentPasswordEmptyOrIncorrect'), 'callback', 'api_check_password');
-    }
+	$form->addElement('password', 'password0', array(get_lang('Pass'), get_lang('Enter2passToChange')), array('size' => 40));
+	$form->addElement('password', 'password1', get_lang('NewPass'), array('size' => 40));
+	$form->addElement('password', 'password2', get_lang('Confirmation'), array('size' => 40));
+	//	user must enter identical password twice so we can prevent some user errors
+	$form->addRule(array('password1', 'password2'), get_lang('PassTwo'), 'compare');
+	if (CHECK_PASS_EASY_TO_FIND) {
+		$form->addRule('password1', get_lang('CurrentPasswordEmptyOrIncorrect'), 'callback', 'api_check_password');
+	}
 }
 
 // EXTRA FIELDS
 $extra_data = UserManager::get_extra_user_data(api_get_user_id(), true);
-$return_params = UserManager::set_extra_fields_in_form($form, $extra_data, 'profile', false, api_get_user_id());
+$return_params = ExtraField::set_extra_fields_in_form($form, $extra_data, 'profile', false, api_get_user_id(), 'user');
 $jquery_ready_content = $return_params['jquery_ready_content'];
 
 // the $jquery_ready_content variable collects all functions that will be load in the $(document).ready javascript function
 $htmlHeadXtra[] ='<script>
 $(document).ready(function(){
-    '.$jquery_ready_content.'
+	'.$jquery_ready_content.'
 });
 </script>';
 
 if (api_get_setting('profile', 'apikeys') == 'true') {
-    $form->addElement('html', '<div id="div_api_key">');
-    $form->addElement('text', 'api_key_generate', get_lang('MyApiKey'), array('size' => 40, 'id' => 'id_api_key_generate'));
-    $form->addElement('html', '</div>');
-    $form->addElement('button', 'generate_api_key', get_lang('GenerateApiKey'), array('id' => 'id_generate_api_key', 'onclick' => 'generate_open_id_form()')); //generate_open_id_form()
+	$form->addElement('html', '<div id="div_api_key">');
+	$form->addElement('text', 'api_key_generate', get_lang('MyApiKey'), array('size' => 40, 'id' => 'id_api_key_generate'));
+	$form->addElement('html', '</div>');
+	$form->addElement('button', 'generate_api_key', get_lang('GenerateApiKey'), array('id' => 'id_generate_api_key', 'onclick' => 'generate_open_id_form()')); //generate_open_id_form()
 }
-//    SUBMIT
+//	SUBMIT
 if (is_profile_editable()) {
-    $form->addElement('style_submit_button', 'apply_change', get_lang('SaveSettings'), 'class="save"');
+	$form->addElement('style_submit_button', 'apply_change', get_lang('SaveSettings'), 'class="save"');
 } else {
-    $form->freeze();
+	$form->freeze();
 }
 
 $user_data = array_merge($user_data, $extra_data);
 $form->setDefaults($user_data);
 
-/*        FUNCTIONS   */
+/*		FUNCTIONS   */
 
 
 /**
@@ -310,74 +308,74 @@ function is_platform_authentication() {
 /**
  * Can a user edit his/her profile?
  *
- * @return    boolean    Editability of the profile
+ * @return	boolean	Editability of the profile
  */
 function is_profile_editable() {
-    return $GLOBALS['profileIsEditable'];
+	return $GLOBALS['profileIsEditable'];
 }
 
 /*
-    PRODUCTIONS FUNCTIONS
+	PRODUCTIONS FUNCTIONS
 */
 
 /**
  * Upload a submitted user production.
  *
- * @param    $user_id    User id
- * @return    The filename of the new production or FALSE if the upload has failed
+ * @param	$user_id	User id
+ * @return	The filename of the new production or FALSE if the upload has failed
  */
 function upload_user_production($user_id) {
-    $image_path = UserManager::get_user_picture_path_by_id($user_id, 'system', true);
+	$image_path = UserManager::get_user_picture_path_by_id($user_id, 'system', true);
 
-    $production_repository = $image_path['dir'].$user_id.'/';
+	$production_repository = $image_path['dir'].$user_id.'/';
 
-    if (!file_exists($production_repository)) {
-        @mkdir($production_repository, api_get_permissions_for_new_directories(), true);
-    }
-    $filename = replace_dangerous_char($_FILES['production']['name']);
-    $filename = disable_dangerous_file($filename);
+	if (!file_exists($production_repository)) {
+		@mkdir($production_repository, api_get_permissions_for_new_directories(), true);
+	}
+	$filename = replace_dangerous_char($_FILES['production']['name']);
+	$filename = disable_dangerous_file($filename);
 
-    if (filter_extension($filename)) {
-        if (@move_uploaded_file($_FILES['production']['tmp_name'], $production_repository.$filename)) {
-            return $filename;
-        }
-    }
-    return false; // this should be returned if anything went wrong with the upload
+	if (filter_extension($filename)) {
+		if (@move_uploaded_file($_FILES['production']['tmp_name'], $production_repository.$filename)) {
+			return $filename;
+		}
+	}
+	return false; // this should be returned if anything went wrong with the upload
 }
 
 /**
  * Check current user's current password
- * @param    char    password
- * @return    bool true o false
+ * @param	char	password
+ * @return	bool true o false
  * @uses Gets user ID from global variable
  */
 function check_user_password($password){
-    global $_user;
-    $user_id = api_get_user_id();
-    if ($user_id != strval(intval($user_id)) || empty($password)) { return false; }
-    $table_user = Database :: get_main_table(TABLE_MAIN_USER);
-    $password = api_get_encrypted_password($password);
-    $sql_password = "SELECT * FROM $table_user WHERE user_id='".$user_id."' AND password='".$password."'";
-    $result = Database::query($sql_password);
-    return Database::num_rows($result) != 0;
+	global $_user;
+	$user_id = api_get_user_id();
+	if ($user_id != strval(intval($user_id)) || empty($password)) { return false; }
+	$table_user = Database :: get_main_table(TABLE_MAIN_USER);
+	$password = api_get_encrypted_password($password);
+	$sql_password = "SELECT * FROM $table_user WHERE user_id='".$user_id."' AND password='".$password."'";
+	$result = Database::query($sql_password);
+	return Database::num_rows($result) != 0;
 }
 /**
  * Check current user's current password
- * @param    char    email
- * @return    bool true o false
+ * @param	char	email
+ * @return	bool true o false
  * @uses Gets user ID from global variable
  */
 function check_user_email($email) {
-    $user_id = api_get_user_id();
-    if ($user_id != strval(intval($user_id)) || empty($email)) { return false; }
-    $table_user = Database :: get_main_table(TABLE_MAIN_USER);
+	$user_id = api_get_user_id();
+	if ($user_id != strval(intval($user_id)) || empty($email)) { return false; }
+	$table_user = Database :: get_main_table(TABLE_MAIN_USER);
     $email = Database::escape_string($email);
-    $sql_password = "SELECT * FROM $table_user WHERE user_id='".$user_id."' AND email='".$email."'";
-    $result = Database::query($sql_password);
-    return Database::num_rows($result) != 0;
+	$sql_password = "SELECT * FROM $table_user WHERE user_id='".$user_id."' AND email='".$email."'";
+	$result = Database::query($sql_password);
+	return Database::num_rows($result) != 0;
 }
 
-/*        MAIN CODE */
+/*		MAIN CODE */
 $filtered_extension         = false;
 $update_success             = false;
 $upload_picture_success     = false;
@@ -387,61 +385,58 @@ $msg_is_not_password        = false;
 
 if (is_platform_authentication()) {
     if (!empty($_SESSION['change_email'])) {
-        $msg_fail_changue_email= ($_SESSION['change_email'] == 'success');
-        unset($_SESSION['change_email']);
+    	$msg_fail_changue_email= ($_SESSION['change_email'] == 'success');
+    	unset($_SESSION['change_email']);
     } elseif (!empty($_SESSION['is_not_password'])) {
-        $msg_is_not_password = ($_SESSION['is_not_password'] == 'success');
-        unset($_SESSION['is_not_password']);
+    	$msg_is_not_password = ($_SESSION['is_not_password'] == 'success');
+    	unset($_SESSION['is_not_password']);
     } elseif (!empty($_SESSION['profile_update'])) {
-        $update_success = ($_SESSION['profile_update'] == 'success');
-        unset($_SESSION['profile_update']);
+    	$update_success = ($_SESSION['profile_update'] == 'success');
+    	unset($_SESSION['profile_update']);
     } elseif (!empty($_SESSION['image_uploaded'])) {
-        $upload_picture_success = ($_SESSION['image_uploaded'] == 'success');
-        unset($_SESSION['image_uploaded']);
+    	$upload_picture_success = ($_SESSION['image_uploaded'] == 'success');
+    	unset($_SESSION['image_uploaded']);
     } elseif (!empty($_SESSION['production_uploaded'])) {
-        $upload_production_success = ($_SESSION['production_uploaded'] == 'success');
-        unset($_SESSION['production_uploaded']);
+    	$upload_production_success = ($_SESSION['production_uploaded'] == 'success');
+    	unset($_SESSION['production_uploaded']);
     }
 }
 
 if ($form->validate()) {
 
-    $wrong_current_password = false;
-//    $user_data = $form->exportValues();
-    $user_data = $form->getSubmitValues();
-
-    // set password if a new one was provided
-    if (!empty($user_data['password0'])) {
-        if (check_user_password($user_data['password0'])) {
-            if (!empty($user_data['password1'])) {
-                $password = $user_data['password1'];
-            }
-        } else {
-            $wrong_current_password = true;
-            $_SESSION['is_not_password'] = 'success';
-        }
-    }
-    if (empty($user_data['password0']) && !empty($user_data['password1'])) {
-        $wrong_current_password = true;
-        $_SESSION['is_not_password'] = 'success';
-    }
+	$wrong_current_password = false;
+//	$user_data = $form->exportValues();
+	$user_data = $form->getSubmitValues();
+
+	// set password if a new one was provided
+	if (!empty($user_data['password0'])) {
+		if (check_user_password($user_data['password0'])) {
+			if (!empty($user_data['password1'])) {
+				$password = $user_data['password1'];
+			}
+		} else {
+			$wrong_current_password = true;
+			$_SESSION['is_not_password'] = 'success';
+		}
+	}
+	if (empty($user_data['password0']) && !empty($user_data['password1'])) {
+		$wrong_current_password = true;
+		$_SESSION['is_not_password'] = 'success';
+	}
 
     $allow_users_to_change_email_with_no_password = true;
     if (is_platform_authentication() && api_get_setting('allow_users_to_change_email_with_no_password') == 'false') {
         $allow_users_to_change_email_with_no_password = false;
     }
 
-
-
-
     //If user sending the email to be changed (input available and not frozen )
     if (api_get_setting('profile', 'email') == 'true') {
+
         if ($allow_users_to_change_email_with_no_password) {
             if (!check_user_email($user_data['email'])) {
                 $changeemail = $user_data['email'];
                 //$_SESSION['change_email'] = 'success';
             }
-
         } else {
             //Normal behaviour
             if (!check_user_email($user_data['email']) && !empty($user_data['password0']) && !$wrong_current_password) {
@@ -455,67 +450,67 @@ if ($form->validate()) {
     }
 
 
-    // Upload picture if a new one is provided
-    if ($_FILES['picture']['size']) {
-        if ($new_picture = UserManager::update_user_picture(api_get_user_id(), $_FILES['picture']['name'], $_FILES['picture']['tmp_name'])) {
-            $user_data['picture_uri'] = $new_picture;
-            $_SESSION['image_uploaded'] = 'success';
-        }
-    } elseif (!empty($user_data['remove_picture'])) {
-        // remove existing picture if asked
-        UserManager::delete_user_picture(api_get_user_id());
-        $user_data['picture_uri'] = '';
-    }
-
-    //Remove production
-    if (is_array($user_data['remove_production'])) {
-        foreach (array_keys($user_data['remove_production']) as $production) {
-            UserManager::remove_user_production(api_get_user_id(), urldecode($production));
-        }
-        if ($production_list = UserManager::build_production_list(api_get_user_id(), true, true)) {
-            $form->insertElementBefore($form->createElement('static', null, null, $production_list), 'productions_list');
-        }
-        $form->removeElement('productions_list');
-        $file_deleted = true;
-    }
-
-    // upload production if a new one is provided
-    if ($_FILES['production']['size']) {
-        $res = upload_user_production(api_get_user_id());
-        if (!$res) {
-            //it's a bit excessive to assume the extension is the reason why upload_user_production() returned false, but it's true in most cases
-            $filtered_extension = true;
-        } else {
-            $_SESSION['production_uploaded'] = 'success';
-        }
-    }
-
-    // remove values that shouldn't go in the database
-    unset($user_data['password0'],$user_data['password1'], $user_data['password2'], $user_data['MAX_FILE_SIZE'],
-    $user_data['remove_picture'], $user_data['apply_change'],$user_data['email'] );
-
-    // Following RFC2396 (http://www.faqs.org/rfcs/rfc2396.html), a URI uses ':' as a reserved character
-    // we can thus ensure the URL doesn't contain any scheme name by searching for ':' in the string
-    $my_user_openid = isset($user_data['openid']) ? $user_data['openid'] : '';
-    if (!preg_match('/^[^:]*:\/\/.*$/', $my_user_openid)) {
-        //ensure there is at least a http:// scheme in the URI provided
-        $user_data['openid'] = 'http://'.$my_user_openid;
-    }
-    $extras = array();
-
-    //Checking the user language
-    $languages = api_get_languages();
+	// Upload picture if a new one is provided
+	if ($_FILES['picture']['size']) {
+		if ($new_picture = UserManager::update_user_picture(api_get_user_id(), $_FILES['picture']['name'], $_FILES['picture']['tmp_name'])) {
+			$user_data['picture_uri'] = $new_picture;
+			$_SESSION['image_uploaded'] = 'success';
+		}
+	} elseif (!empty($user_data['remove_picture'])) {
+	    // remove existing picture if asked
+		UserManager::delete_user_picture(api_get_user_id());
+		$user_data['picture_uri'] = '';
+	}
+
+	//Remove production
+	if (is_array($user_data['remove_production'])) {
+		foreach (array_keys($user_data['remove_production']) as $production) {
+			UserManager::remove_user_production(api_get_user_id(), urldecode($production));
+		}
+		if ($production_list = UserManager::build_production_list(api_get_user_id(), true, true)) {
+			$form->insertElementBefore($form->createElement('static', null, null, $production_list), 'productions_list');
+		}
+		$form->removeElement('productions_list');
+		$file_deleted = true;
+	}
+
+	// upload production if a new one is provided
+	if ($_FILES['production']['size']) {
+		$res = upload_user_production(api_get_user_id());
+		if (!$res) {
+			//it's a bit excessive to assume the extension is the reason why upload_user_production() returned false, but it's true in most cases
+			$filtered_extension = true;
+		} else {
+			$_SESSION['production_uploaded'] = 'success';
+		}
+	}
+
+	// remove values that shouldn't go in the database
+	unset($user_data['password0'],$user_data['password1'], $user_data['password2'], $user_data['MAX_FILE_SIZE'],
+	$user_data['remove_picture'], $user_data['apply_change'],$user_data['email'] );
+
+	// Following RFC2396 (http://www.faqs.org/rfcs/rfc2396.html), a URI uses ':' as a reserved character
+	// we can thus ensure the URL doesn't contain any scheme name by searching for ':' in the string
+	$my_user_openid = isset($user_data['openid']) ? $user_data['openid'] : '';
+	if (!preg_match('/^[^:]*:\/\/.*$/', $my_user_openid)) {
+		//ensure there is at least a http:// scheme in the URI provided
+		$user_data['openid'] = 'http://'.$my_user_openid;
+	}
+	$extras = array();
+
+	//Checking the user language
+	$languages = api_get_languages();
     if (!in_array($user_data['language'], $languages['folder'])) {
         $user_data['language'] = api_get_setting('platformLanguage');
     }
 
-    //Only update values that are request by the "profile" setting
-    $profile_list = api_get_setting('profile');
-    //Adding missing variables
+	//Only update values that are request by the "profile" setting
+	$profile_list = api_get_setting('profile');
+	//Adding missing variables
 
-    $available_values_to_modify = array();
-    foreach($profile_list as $key => $status) {
-        if ($status == 'true') {
+	$available_values_to_modify = array();
+	foreach($profile_list as $key => $status) {
+	    if ($status == 'true') {
             switch($key) {
                 case 'login':
                     $available_values_to_modify[] = 'username';
@@ -531,41 +526,41 @@ if ($form->validate()) {
                     $available_values_to_modify[] = $key;
                     break;
             }
-        }
-    }
+	    }
+	}
 
-    //Fixing missing variables
+	//Fixing missing variables
     $available_values_to_modify = array_merge($available_values_to_modify, array('competences', 'diplomas', 'openarea', 'teach', 'openid'));
 
-    // build SQL query
-    $sql = "UPDATE $table_user SET";
-    unset($user_data['api_key_generate']);
-    foreach ($user_data as $key => $value) {
-        if (substr($key, 0, 6) == 'extra_') { //an extra field
-            $new_key = substr($key, 6);
-            // format array date to 'Y-m-d' or date time  to 'Y-m-d H:i:s'
-            if (is_array($value) && isset($value['Y']) && isset($value['F']) && isset($value['d'])) {
-                if (isset($value['H']) && isset($value['i'])) {
-                    // extra field date time
-                    $time = mktime($value['H'],$value['i'],0,$value['F'],$value['d'],$value['Y']);
-                    $extras[$new_key] = date('Y-m-d H:i:s',$time);
-                } else {
-                    // extra field date
-                    $time = mktime(0,0,0,$value['F'],$value['d'],$value['Y']);
-                    $extras[$new_key] = date('Y-m-d',$time);
-                }
-            } else {
-                $extras[$new_key] = $value;
-            }
-        } else {
-            if (in_array($key, $available_values_to_modify)) {
+	// build SQL query
+	$sql = "UPDATE $table_user SET";
+	unset($user_data['api_key_generate']);
+	foreach ($user_data as $key => $value) {
+		if (substr($key, 0, 6) == 'extra_') { //an extra field
+			$new_key = substr($key, 6);
+			// format array date to 'Y-m-d' or date time  to 'Y-m-d H:i:s'
+			if (is_array($value) && isset($value['Y']) && isset($value['F']) && isset($value['d'])) {
+				if (isset($value['H']) && isset($value['i'])) {
+					// extra field date time
+					$time = mktime($value['H'],$value['i'],0,$value['F'],$value['d'],$value['Y']);
+					$extras[$new_key] = date('Y-m-d H:i:s',$time);
+				} else {
+					// extra field date
+					$time = mktime(0,0,0,$value['F'],$value['d'],$value['Y']);
+					$extras[$new_key] = date('Y-m-d',$time);
+				}
+			} else {
+				$extras[$new_key] = $value;
+			}
+		} else {
+		    if (in_array($key, $available_values_to_modify)) {
                 $sql .= " $key = '".Database::escape_string($value)."',";
-            }
-        }
-    }
+		    }
+		}
+	}
 
-    //change email
-    if ($allow_users_to_change_email_with_no_password) {
+	//change email
+	if ($allow_users_to_change_email_with_no_password) {
         if (isset($changeemail) && in_array('email', $available_values_to_modify)) {
             $sql .= " email = '".Database::escape_string($changeemail)."',";
         }
@@ -598,29 +593,28 @@ if ($form->validate()) {
     if (api_get_setting('profile', 'officialcode') == 'true' && isset($user_data['official_code'])) {
         $sql .= ", official_code = '".Database::escape_string($user_data['official_code'])."'";
     }
+	$sql .= " WHERE user_id  = '".api_get_user_id()."'";
+	Database::query($sql);
 
-    $sql .= " WHERE user_id  = '".api_get_user_id()."'";
-    Database::query($sql);
 
+	// User tag process
+	//1. Deleting all user tags
+	$list_extra_field_type_tag = UserManager::get_all_extra_field_by_type(ExtraField::FIELD_TYPE_TAG);
 
-    // User tag process
-    //1. Deleting all user tags
-    $list_extra_field_type_tag = UserManager::get_all_extra_field_by_type(UserManager::USER_FIELD_TYPE_TAG);
+	if (is_array($list_extra_field_type_tag) && count($list_extra_field_type_tag)>0) {
+		foreach ($list_extra_field_type_tag as $id) {
+			UserManager::delete_user_tags(api_get_user_id(), $id);
+		}
+	}
 
-    if (is_array($list_extra_field_type_tag) && count($list_extra_field_type_tag)>0) {
-        foreach ($list_extra_field_type_tag as $id) {
-            UserManager::delete_user_tags(api_get_user_id(), $id);
-        }
-    }
-
-    //2. Update the extra fields and user tags if available
+	//2. Update the extra fields and user tags if available
 
-    if (is_array($extras) && count($extras)> 0) {
-        foreach ($extras as $key => $value) {
-            //3. Tags are process in the UserManager::update_extra_field_value by the UserManager::process_tags function
-            UserManager::update_extra_field_value(api_get_user_id(), $key, $value);
-        }
-    }
+	if (is_array($extras) && count($extras)> 0) {
+		foreach ($extras as $key => $value) {
+			//3. Tags are process in the UserManager::update_extra_field_value by the UserManager::process_tags function
+			UserManager::update_extra_field_value(api_get_user_id(), $key, $value);
+		}
+	}
 
     // re-init the system to take new settings into account
     $_SESSION['_user']['uidReset'] = true;
@@ -632,70 +626,77 @@ if ($form->validate()) {
 }
 
 
-/*          MAIN DISPLAY SECTION  */
+/*  		MAIN DISPLAY SECTION  */
 // the header
 Display::display_header(get_lang('ModifyProfile'));
 
 if (api_get_setting('allow_social_tool') != 'true') {
 
-    if (api_get_setting('extended_profile') == 'true') {
-        echo '<div class="actions">';
+	if (api_get_setting('extended_profile') == 'true') {
+		echo '<div class="actions">';
 
-        if (api_get_setting('allow_social_tool') == 'true' && api_get_setting('allow_message_tool') == 'true') {
-            echo '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php">'.Display::return_icon('shared_profile.png', get_lang('ViewSharedProfile')).'</a>';
-        }
-        if (api_get_setting('allow_message_tool') == 'true') {
-            echo '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.Display::return_icon('inbox.png', get_lang('Messages')).'</a>';
-        }
-        $show = isset($_GET['show']) ? '&amp;show='.Security::remove_XSS($_GET['show']) : '';
+		if (api_get_setting('allow_social_tool') == 'true' && api_get_setting('allow_message_tool') == 'true') {
+			echo '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php">'.Display::return_icon('shared_profile.png', get_lang('ViewSharedProfile')).'</a>';
+		}
+		if (api_get_setting('allow_message_tool') == 'true') {
+			echo '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.Display::return_icon('inbox.png', get_lang('Messages')).'</a>';
+		}
+		$show = isset($_GET['show']) ? '&amp;show='.Security::remove_XSS($_GET['show']) : '';
 
-        if (isset($_GET['type']) && $_GET['type'] == 'extended') {
-            echo '<a href="profile.php?type=reduced'.$show.'">'.Display::return_icon('edit.png', get_lang('EditNormalProfile'),'',16).'</a>';
-        } else {
-            echo '<a href="profile.php?type=extended'.$show.'">'.Display::return_icon('edit.png', get_lang('EditExtendProfile'),'',16).'</a>';
-        }
-        echo '</div>';
-    }
+		if (isset($_GET['type']) && $_GET['type'] == 'extended') {
+			echo '<a href="profile.php?type=reduced'.$show.'">'.Display::return_icon('edit.png', get_lang('EditNormalProfile'),'',16).'</a>';
+		} else {
+			echo '<a href="profile.php?type=extended'.$show.'">'.Display::return_icon('edit.png', get_lang('EditExtendProfile'),'',16).'</a>';
+		}
+		echo '</div>';
+	}
 }
 
 if (!empty($file_deleted)) {
-    Display :: display_confirmation_message(get_lang('FileDeleted'), false);
+	Display :: display_confirmation_message(get_lang('FileDeleted'), false);
 } elseif (!empty($update_success)) {
-    $message = get_lang('ProfileReg');
+	$message = get_lang('ProfileReg');
 
-    if ($upload_picture_success) {
-        $message .= '<br /> '.get_lang('PictureUploaded');
-    }
+	if ($upload_picture_success) {
+		$message .= '<br /> '.get_lang('PictureUploaded');
+	}
 
-    if ($upload_production_success) {
-        $message.='<br />'.get_lang('ProductionUploaded');
-    }
-    Display :: display_confirmation_message($message, false);
+	if ($upload_production_success) {
+		$message.='<br />'.get_lang('ProductionUploaded');
+	}
+	Display :: display_confirmation_message($message, false);
 }
 
 
 if (!empty($msg_fail_changue_email)){
-    $errormail=get_lang('ToChangeYourEmailMustTypeYourPassword');
-    Display :: display_error_message($errormail, false);
+	$errormail=get_lang('ToChangeYourEmailMustTypeYourPassword');
+	Display :: display_error_message($errormail, false);
 }
 
 if (!empty($msg_is_not_password)){
-    $warning_msg = get_lang('CurrentPasswordEmptyOrIncorrect');
-    Display :: display_warning_message($warning_msg, false);
+	$warning_msg = get_lang('CurrentPasswordEmptyOrIncorrect');
+	Display :: display_warning_message($warning_msg, false);
 }
 
 //User picture size is calculated from SYSTEM path
 $image_syspath = UserManager::get_user_picture_path_by_id(api_get_user_id(), 'system', false, true);
 $image_syspath['dir'].$image_syspath['file'];
 
+//$image_size = api_getimagesize($image_syspath['dir'].$image_syspath['file']);
+
 //Web path
 $image_path = UserManager::get_user_picture_path_by_id(api_get_user_id(), 'web', false, true);
 $image_dir = $image_path['dir'];
 $image = $image_path['file'];
 $image_file = $image_dir.$image;
 $img_attributes = 'src="'.$image_file.'?rand='.time().'" '
-    .'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
-    .'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; margin-top:0px;padding:5px;" ';
+	.'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
+	.'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; margin-top:0px;padding:5px;" ';
+/*
+if ($image_size['width'] > 300) {
+	//limit display width to 300px
+	$img_attributes .= 'width="300" ';
+}*/
 
 // get the path,width and height from original picture
 $big_image = $image_dir.'big_'.$image;
@@ -708,23 +709,24 @@ $url_big_image      = $big_image.'?rnd='.time();
 $show_delete_account_button = api_get_setting('platform_unsubscribe_allowed') == 'true' ? true : false;
 
 if (api_get_setting('allow_social_tool') == 'true') {
-    echo '<div class="row-fluid">';
-        echo '<div class="span3">';
-        echo SocialManager::show_social_menu('home', null, api_get_user_id(), false, $show_delete_account_button);
-        echo '</div>';
-        echo '<div class="span9">';
+	echo '<div class="row-fluid">';
+		echo '<div class="span3">';
+		echo SocialManager::show_social_menu('home', null, api_get_user_id(), false, $show_delete_account_button);
+		echo '</div>';
+		echo '<div class="span9">';
         $form->display();
-    echo '</div>';
+	echo '</div>';
 } else {
-    // Style position:absolute has been removed for Opera-compatibility.
-    echo '<div id="image-message-container" style="float:right;display:inline;padding:3px;width:230px;" >';
-
-    if ($image == 'unknown.jpg') {
-        echo '<img '.$img_attributes.' />';
-    } else {
-        echo '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
-    }
-    echo '</div>';
-    $form->display();
+	// Style position:absolute has been removed for Opera-compatibility.
+	//echo '<div id="image-message-container" style="float:right;display:inline;position:absolute;padding:3px;width:250px;" >';
+	echo '<div id="image-message-container" style="float:right;display:inline;padding:3px;width:230px;" >';
+
+	if ($image == 'unknown.jpg') {
+		echo '<img '.$img_attributes.' />';
+	} else {
+		echo '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
+	}
+	echo '</div>';
+	$form->display();
 }
 Display :: display_footer();

+ 7 - 9
main/auth/shibboleth/app/controller/shibboleth_controller.class.php

@@ -4,10 +4,9 @@ namespace Shibboleth;
 
 use \Redirect;
 use \Display;
-use IndexManager;
 
 /**
- * Controller for the Shibboleth authentication system. 
+ * Controller for the Shibboleth authentication system.
  *
  * @license see /license.txt
  * @author Laurent Opprecht <laurent@opprecht.info>, Nicolas Rod for the University of Geneva
@@ -17,7 +16,7 @@ class ShibbolethController
 
     /**
      *
-     * @return ShibbolethController 
+     * @return ShibbolethController
      */
     public static function instance()
     {
@@ -30,7 +29,7 @@ class ShibbolethController
     }
 
     /**
-     * Log user in with Shibboleth authentication 
+     * Log user in with Shibboleth authentication
      */
     function login()
     {
@@ -92,13 +91,12 @@ class ShibbolethController
             $message = get_lang('already_logged_in');
             Shibboleth::display()->message_page($message, $title);
         }
-        $index_manager = new IndexManager('');
-        $html = $index_manager->display_login_form();
+        $html = PageController::display_login_form();
         Shibboleth::display()->page($html, $title);
     }
 
     /**
-     * Display the request new status page to administrator for new users. 
+     * Display the request new status page to administrator for new users.
      */
     public function request_status()
     {
@@ -115,7 +113,7 @@ class ShibbolethController
             //Maximum user right is reached.
             Shibboleth::redirect();
         }
-        
+
         $form = ShibbolethStatusRequestForm::instance();
 
         if ($form->cancelled())
@@ -131,7 +129,7 @@ class ShibbolethController
 
             $message = <<<EOT
 New status: $status
-            
+
 Reason:
 $reason
 EOT;

+ 54 - 46
main/auth/sso/sso.class.php

@@ -39,7 +39,6 @@ class sso {
         $this->master_url = $this->protocol.$this->domain.$this->auth_uri;
         $this->target     = api_get_path(WEB_PATH);
     }
-    
     /**
      * Unlogs the user from the remote server 
      */
@@ -47,7 +46,7 @@ class sso {
         header('Location: '.$this->deauth_url);
         exit;
     }
-    
+
     /**
      * Sends the user to the master URL for a check of active connection
      */
@@ -62,6 +61,16 @@ class sso {
         exit;
     }
     
+    function redirect_to($sso, $user_id, $logged_in) {           
+        if (isset($sso['target']) && !empty($sso['target'])) {
+            header('Location: '. $sso['target']);    
+        } else {
+            //Use this handy function to deal with platform settings
+            Redirect::session_request_uri($logged_in, $user_id);                                            
+        }                                            
+        exit;
+    }
+    
     /**
      * Validates the received active connection data with the database
      * @return	bool	Return the loginFailed variable value to local.inc.php
@@ -105,7 +114,6 @@ class sso {
                     if ($uData['active']=='1') {
                         // check if the expiration date has not been reached
                         if ($uData['expiration_date'] > date('Y-m-d H:i:s') OR $uData['expiration_date']=='0000-00-00 00:00:00') {                            
-                            
                             //If Multiple URL is enabled
                             if (api_get_multiple_access_url()) {
                                 //Check the access_url configuration setting if the user is registered in the access_url_rel_user table
@@ -120,63 +128,64 @@ class sso {
                             }
                             
                             $my_user_is_admin = UserManager::is_admin($uData['user_id']);
-                            
-                            if ($my_user_is_admin === false) {
-                                if (is_array($my_url_list) && count($my_url_list) > 0 ) {
-                                    if (in_array($current_access_url_id, $my_url_list)) {
-                                        // the user has permission to enter at this site
-                                        $_user['user_id'] = $uData['user_id'];
+                                if ($my_user_is_admin === false) {
+                                    if (is_array($my_url_list) && count($my_url_list)>0 ) {
+                                        if (in_array($current_access_url_id, $my_url_list)) {
+                                            // the user has permission to enter at this site
+                                            $_user['user_id'] = $uData['user_id'];                                            
                                         $_user = api_get_user_info($_user['user_id']);
-                                        Session::write('_user', $_user);
-                                        event_login();
-                                        // Redirect to homepage
-                                        $sso_target = isset($sso['target']) ? $sso['target'] : api_get_path(WEB_PATH) .'.index.php';
-                                        header('Location: '. $sso_target);
-                                        exit;
+                                            Session::write('_user',$_user);
+                                            event_login();                                            
+                                            // Redirect to homepage
+                                            $sso_target = isset($sso['target']) ? $sso['target'] : api_get_path(WEB_PATH) .'.index.php';
+                                            header('Location: '. $sso_target);
+                                            exit;
+                                        } else {
+                                            // user does not have permission for this site
+                                            $loginFailed = true;
+                                            Session::erase('_uid');
+                                            header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
+                                            exit;
+                                        }
                                     } else {
-                                        // user does not have permission for this site
+                                        // there is no URL in the multiple 
+                                        // urls list for this user
                                         $loginFailed = true;
                                         Session::erase('_uid');
                                         header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
                                         exit;
                                     }
-                                } else {
-                                    // there is no URL in the multiple 
-                                    // urls list for this user
-                                    $loginFailed = true;
-                                    Session::erase('_uid');
-                                    header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
-                                    exit;
-                                }
-                            } else {
-                                //Only admins of the "main" (first) Chamilo
-                                // portal can login wherever they want
-                                if (in_array(1, $my_url_list)) { 
-                                    //Check if this admin is admin on the  
-                                    // principal portal
-                                    $_user['user_id'] = $uData['user_id'];
+                                } else { 
+                                    //Only admins of the "main" (first) Chamilo
+                                    // portal can login wherever they want
+                                    if (in_array(1, $my_url_list)) { 
+                                        //Check if this admin is admin on the  
+                                        // principal portal
+                                        $_user['user_id'] = $uData['user_id'];
                                     $_user = api_get_user_info($_user['user_id']);
                                     $is_platformAdmin = $uData['status'] == COURSEMANAGER;
                                     Session::write('is_platformAdmin', $is_platformAdmin);
-                                    Session::write('_user', $_user);
-                                    event_login();
-                                } else {
-                                    //Secondary URL admin wants to login 
-                                    // so we check as a normal user
-                                    if (in_array($current_access_url_id, $my_url_list)) {
-                                        $_user['user_id'] = $uData['user_id'];
-                                        $_user = api_get_user_info($_user['user_id']);
                                         Session::write('_user',$_user);
                                         event_login();
+                                        self::redirect_to($sso, $_user['user_id'], true);
                                     } else {
-                                        $loginFailed = true;
-                                        Session::erase('_uid');
-                                        header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
-                                        exit;
+                                        //Secondary URL admin wants to login 
+                                        // so we check as a normal user
+                                        if (in_array($current_access_url_id, $my_url_list)) {
+                                            $_user['user_id'] = $uData['user_id'];
+                                        $_user = api_get_user_info($_user['user_id']);
+                                            Session::write('_user',$_user);
+                                            event_login();
+                                            self::redirect_to($sso, $_user['user_id'], true);
+                                        } else {
+                                            $loginFailed = true;
+                                            Session::erase('_uid');
+                                            header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=access_url_inactive');
+                                            exit;
+                                        }
                                     }
                                 }
-                            }                       
-                        } else {
+                            } else {
                             // user account expired
                             $loginFailed = true;
                             Session::erase('_uid');
@@ -213,7 +222,6 @@ class sso {
         }
         return $loginFailed;
     }
-    
     /**
      * Decode the cookie (this function may vary depending on the
      * Single Sign On implementation

File diff suppressed because it is too large
+ 416 - 420
main/calendar/agenda.lib.php


+ 42 - 48
main/calendar/agenda_js.php

@@ -6,6 +6,7 @@
 /**
  * INIT SECTION
  */
+
 // name of the language file that needs to be included
 $language_file = array('agenda', 'group', 'announcements');
 
@@ -13,7 +14,7 @@ $language_file = array('agenda', 'group', 'announcements');
 $use_anonymous = true;
 
 //Calendar type
-$type = isset($_REQUEST['type']) && in_array($_REQUEST['type'], array('personal', 'course', 'admin')) ? $_REQUEST['type'] : 'personal';
+$type  	= isset($_REQUEST['type']) && in_array($_REQUEST['type'], array('personal', 'course', 'admin')) ?  $_REQUEST['type'] : 'personal';
 
 if ($type == 'personal') {
     $cidReset = true; // fixes #5162
@@ -23,11 +24,11 @@ require_once '../inc/global.inc.php';
 require_once 'agenda.lib.php';
 require_once 'agenda.inc.php';
 
-$current_course_tool = TOOL_CALENDAR_EVENT;
+$current_course_tool  = TOOL_CALENDAR_EVENT;
 
 $this_section = SECTION_MYAGENDA;
 
-$htmlHeadXtra[] = api_get_jquery_libraries_js(array('jquery-ui', 'jquery-ui-i18n'));
+$htmlHeadXtra[] = api_get_jquery_libraries_js(array('jquery-ui','jquery-ui-i18n'));
 $htmlHeadXtra[] = api_get_js('qtip2/jquery.qtip.min.js');
 $htmlHeadXtra[] = api_get_js('fullcalendar/fullcalendar.min.js');
 $htmlHeadXtra[] = api_get_js('fullcalendar/gcal.js');
@@ -35,12 +36,12 @@ $htmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/fullcal
 $htmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/qtip2/jquery.qtip.min.css');
 
 if (api_is_platform_admin() && $type == 'admin') {
-    $type = 'admin';
+	$type = 'admin';
 }
 
 //if (api_get_course_id() != -1 && $type == 'course') {
 if (isset($_REQUEST['cidReq']) && !empty($_REQUEST['cidReq'])) {
-    $type = 'course';
+	$type = 'course';
 }
 
 
@@ -51,9 +52,9 @@ $group_id = api_get_group_id();
 
 if (!empty($group_id)) {
     $is_group_tutor = GroupManager::is_tutor_of_group(api_get_user_id(), $group_id);
-    $group_properties = GroupManager :: get_group_properties($group_id);
-    $interbreadcrumb[] = array("url" => "../group/group.php", "name" => get_lang('Groups'));
-    $interbreadcrumb[] = array("url" => "../group/group_space.php?gidReq=".$group_id, "name" => get_lang('GroupSpace').' '.$group_properties['name']);
+    $group_properties  = GroupManager :: get_group_properties($group_id);
+    $interbreadcrumb[] = array ("url" => "../group/group.php", "name" => get_lang('Groups'));
+    $interbreadcrumb[] = array ("url"=>"../group/group_space.php?gidReq=".$group_id, "name"=> get_lang('GroupSpace').' '.$group_properties['name']);
 }
 
 $tpl = new Template(get_lang('Agenda'));
@@ -62,17 +63,17 @@ $tpl->assign('use_google_calendar', 0);
 
 $can_add_events = 0;
 
-switch ($type) {
-    case 'admin':
+switch($type) {
+	case 'admin':
         api_protect_admin_script();
-        $this_section = SECTION_PLATFORM_ADMIN;
+		$this_section = SECTION_PLATFORM_ADMIN;
         if (api_is_platform_admin()) {
             $can_add_events = 1;
         }
-        break;
-    case 'course':
+		break;
+	case 'course':
         api_protect_course_script();
-        $this_section = SECTION_COURSES;
+		$this_section = SECTION_COURSES;
         if (api_is_allowed_to_edit()) {
             $can_add_events = 1;
         }
@@ -81,8 +82,8 @@ switch ($type) {
                 $can_add_events = 1;
             }
         }
-        break;
-    case 'personal':
+		break;
+	case 'personal':
         if (api_is_anonymous()) {
             api_not_allowed(true);
         }
@@ -91,57 +92,56 @@ switch ($type) {
             $tpl->assign('use_google_calendar', 1);
             $tpl->assign('google_calendar_url', $extra_field_data['google_calendar_url']);
         }
-        $this_section = SECTION_MYAGENDA;
+		$this_section = SECTION_MYAGENDA;
         if (!api_is_anonymous()) {
             $can_add_events = 1;
         }
-        break;
+		break;
 }
 
 
 //Setting translations
-$day_short = api_get_week_days_short();
-$days = api_get_week_days_long();
-$months = api_get_months_long();
-$months_short = api_get_months_short();
+$day_short 		= api_get_week_days_short();
+$days 			= api_get_week_days_long();
+$months 		= api_get_months_long();
+$months_short 	= api_get_months_short();
 
 //Setting calendar translations
-$tpl->assign('month_names', json_encode($months));
-$tpl->assign('month_names_short', json_encode($months_short));
-$tpl->assign('day_names', json_encode($days));
-$tpl->assign('day_names_short', json_encode($day_short));
-$tpl->assign('button_text', json_encode(array('today' => get_lang('Today'),
-        'month' => get_lang('Month'),
-        'week' => get_lang('Week'),
-        'day' => get_lang('Day'))));
+$tpl->assign('month_names', 		json_encode($months));
+$tpl->assign('month_names_short', 	json_encode($months_short));
+$tpl->assign('day_names', 			json_encode($days));
+$tpl->assign('day_names_short', 	json_encode($day_short));
+$tpl->assign('button_text', 		json_encode(array(	'today'	=> get_lang('Today'),
+														'month'	=> get_lang('Month'),
+														'week'	=> get_lang('Week'),
+														'day'	=> get_lang('Day'))));
 
 //see http://docs.jquery.com/UI/Datepicker/$.datepicker.formatDate
 
-$tpl->assign('js_format_date', 'D d M yy');
+$tpl->assign('js_format_date', 	'D d M yy');
 $region_value = api_get_language_isocode();
 
 if ($region_value == 'en') {
     $region_value = 'en-GB';
 }
-$tpl->assign('region_value', $region_value);
 
+$tpl->assign('region_value', 	$region_value);
 
 $export_icon = '../img/export.png';
 $export_icon_low = '../img/export_low_fade.png';
 $export_icon_high = '../img/export_high_fade.png';
 
-$tpl->assign('export_ical_confidential_icon', Display::return_icon($export_icon_high, get_lang('ExportiCalConfidential')));
+$tpl->assign('export_ical_confidential_icon', 	Display::return_icon($export_icon_high, get_lang('ExportiCalConfidential')));
 
 $actions = null;
-
-if (api_is_allowed_to_edit(false, true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()) && api_is_allowed_to_session_edit(false, true) OR $is_group_tutor) {
+if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()) && api_is_allowed_to_session_edit(false,true) OR $is_group_tutor) {
     if ($type == 'course') {
         if (isset($_GET['user_id'])) {
             $filter = $_GET['user_id'];
         }
         $actions = display_courseadmin_links($filter);
     }
-    $tpl->assign('actions', $actions);
+	$tpl->assign('actions', $actions);
 }
 
 //Calendar Type : course, admin, personal
@@ -173,7 +173,8 @@ if (isset($_GET['user_id'])) {
     $agenda_ajax_url = api_get_path(WEB_AJAX_PATH).'agenda.ajax.php?type='.$type;
 }
 $tpl->assign('web_agenda_ajax_url', $agenda_ajax_url);
-$course_code = api_get_course_id();
+
+$course_code  = api_get_course_id();
 
 if ((api_is_allowed_to_edit() || $is_group_tutor) && $course_code != '-1' && $type == 'course') {
     $order = 'lastname';
@@ -181,10 +182,10 @@ if ((api_is_allowed_to_edit() || $is_group_tutor) && $course_code != '-1' && $ty
         $order = 'firstname';
     }
     if (!empty($group_id)) {
-        $group_list = array($group_id => $group_properties);
-        $user_list = GroupManager::get_subscribed_users($group_id);
+        $group_list  = array($group_id => $group_properties);
+        $user_list  = GroupManager::get_subscribed_users($group_id);
     } else {
-        $user_list = CourseManager::get_user_list_from_course_code(api_get_course_id(), api_get_session_id(), null, $order);
+        $user_list  = CourseManager::get_user_list_from_course_code(api_get_course_id(), api_get_session_id(), null, $order);
         $group_list = CourseManager::get_group_list_of_course(api_get_course_id(), api_get_session_id());
     }
 
@@ -193,11 +194,4 @@ if ((api_is_allowed_to_edit() || $is_group_tutor) && $course_code != '-1' && $ty
     $select = $agenda->construct_not_selected_select_form($group_list, $user_list);
     $tpl->assign('visible_to', $select);
 }
-
-//Loading Agenda template
-$content = $tpl->fetch('default/agenda/month.tpl');
-
-$tpl->assign('content', $content);
-
-//Loading main Chamilo 1 col template
-$tpl->display_one_col_template();
+$tpl->display('default/agenda/month.tpl');

+ 0 - 2
main/course_home/activity.php

@@ -105,8 +105,6 @@ if (api_is_allowed_to_edit(null, true) && !api_is_coach()) {
 				$my_list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
 				$content .= CourseHome::show_tools_category($my_list);
     $content .= '</div>';
-    //	TOOLS AUTHORING
-
 } else {
 	$my_list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
 	if (count($my_list) > 0) {

+ 1 - 3
main/course_home/course_home.php

@@ -30,7 +30,6 @@
 
 /* 		INIT SECTION		*/
 
-
 use \ChamiloSession as Session;
 
 // Name of the language file that needs to be included.
@@ -243,8 +242,6 @@ $content = Display::return_introduction_section(TOOL_COURSE_HOMEPAGE, array(
 	the setting homepage_view is adjustable through
 	the platform administration section */
 
-require_once api_get_path(LIBRARY_PATH).'course_home.lib.php';
-
 if ($show_autolunch_lp_warning) {
     $show_message .= Display::return_message(get_lang('TheLPAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificLP'),'warning');
 }
@@ -259,6 +256,7 @@ if (api_get_setting('homepage_view') == 'activity' || api_get_setting('homepage_
 }
 $content = '<div id="course_tools">'.$content.'</div>';
 $tpl = new Template(null);
+
 $tpl->assign('message', $show_message);
 $tpl->assign('content', $content);
 $tpl->display_one_col_template();

+ 0 - 1
main/course_info/infocours.php

@@ -25,7 +25,6 @@ $this_section = SECTION_COURSES;
 $nameTools = get_lang('ModifInfo');
 
 /*	Libraries */
-require_once api_get_path(INCLUDE_PATH).'conf/course_info.conf.php';
 require_once api_get_path(LIBRARY_PATH).'pdf.lib.php';
 require_once api_get_path(LIBRARY_PATH).'fileDisplay.lib.php';
 

+ 1 - 1
main/course_info/legal.php

@@ -67,7 +67,7 @@ if (empty($session_id)) {
         header('Location: '.$url);
     }
     
-    $user_session_status = SessionManager::get_user_status_in_session($user_id, $course_code, $session_id);
+    $user_session_status = SessionManager::get_user_status_in_course_session($user_id, $course_code, $session_id);
     
     if (isset($user_session_status) || api_check_user_access_to_legal($course_info['visibility'])) {        
         $user_accepted_legal = CourseManager::is_user_accepted_legal($user_id, $course_code, $session_id);        

+ 21 - 16
main/course_info/maintenance.php

@@ -19,31 +19,36 @@ api_protect_course_script(true);
 api_block_anonymous_users();
 
 Display :: display_header($nameTools);
-echo Display::page_header($nameTools);
 
+echo Display::page_subheader(Display::return_icon('save_import.gif', get_lang('backup')).'&nbsp;&nbsp;'.get_lang('backup'));
 ?>
-
-<div class="sectiontitle"><?php Display::display_icon('save_import.gif', get_lang('backup')); ?>&nbsp;&nbsp;<a href="../coursecopy/backup.php?<?php echo api_get_cidreq(); ?>"><?php echo get_lang('backup'); ?></a></div>
 <div class="sectioncomment">
 		<ul>
-		    <li><a href="../coursecopy/create_backup.php?<?php echo api_get_cidreq(); ?>"><?php echo get_lang('CreateBackup'); ?></a><br/>
-		    <?php echo get_lang('CreateBackupInfo'); ?>
+		    <li>
+                <a href="../coursecopy/create_backup.php?<?php echo api_get_cidreq(); ?>"><?php echo get_lang('CreateBackup'); ?></a><br/>
+                <?php echo get_lang('CreateBackupInfo'); ?>
 		    </li>
-		    <li><a href="../coursecopy/import_backup.php?<?php echo api_get_cidreq(); ?>"><?php echo get_lang('ImportBackup'); ?></a><br/>
-		    <?php echo get_lang('ImportBackupInfo'); ?>
+		    <li>
+                <a href="../coursecopy/import_backup.php?<?php echo api_get_cidreq(); ?>"><?php echo get_lang('ImportBackup'); ?></a><br/>
+                <?php echo get_lang('ImportBackupInfo'); ?>
 		    </li>
-	    </ul>
-</div>
 
-<div class="sectiontitle"><?php Display::display_icon('copy.gif', get_lang('CopyCourse')); ?>&nbsp;&nbsp;<a href="../coursecopy/copy_course.php?<?php echo api_get_cidreq(); ?>"><?php echo get_lang('CopyCourse'); ?></a></div>
-<div class="sectioncomment"><?php echo get_lang('DescriptionCopyCourse'); ?></div>
+            <li>
+            <a href="../coursecopy/copy_course.php?<?php echo api_get_cidreq(); ?>"><?php echo get_lang('CopyCourse'); ?></a><br/>
+            <?php echo get_lang('DescriptionCopyCourse'); ?>
+            </li>
 
-<div class="sectiontitle"><?php Display::display_icon('tool_delete.gif', get_lang('recycle_course')); ?>&nbsp;&nbsp;<a href="../coursecopy/recycle_course.php?<?php echo api_get_cidreq(); ?>"><?php echo get_lang('recycle_course'); ?></a></div>
-<div class="sectioncomment"><?php echo get_lang('DescriptionRecycleCourse'); ?></div>
-
-<div class="sectiontitle"><?php Display::display_icon('delete.gif', get_lang('DelCourse')); ?>&nbsp;&nbsp;<a href="../course_info/delete_course.php?<?php echo api_get_cidreq(); ?>"><?php echo get_lang('DelCourse'); ?></a></div>
-<div class="sectioncomment"><?php echo get_lang('DescriptionDeleteCourse');	?></div>
+            <li>
+            <a href="../coursecopy/recycle_course.php?<?php echo api_get_cidreq(); ?>"><?php echo get_lang('recycle_course'); ?></a><br/>
+            <?php echo get_lang('DescriptionRecycleCourse'); ?>
+            </li>
 
+            <li>
+            <a href="../course_info/delete_course.php?<?php echo api_get_cidreq(); ?>"><?php echo get_lang('DelCourse'); ?></a><br/>
+            <?php echo get_lang('DescriptionDeleteCourse');	?>
+            </li>
+	    </ul>
+</div>
 <?php
 // Footer
 Display::display_footer();

+ 1 - 3
main/course_progress/index.php

@@ -14,13 +14,11 @@ $language_file = array ('course_description', 'userInfo', 'admin');
 
 // including files
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'attendance.lib.php';
 require_once api_get_path(LIBRARY_PATH).'thematic.lib.php';
 require_once api_get_path(LIBRARY_PATH).'app_view.php';
 require_once 'thematic_controller.php';
 
 require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
-require_once api_get_path(LIBRARY_PATH).'import.lib.php';
 
 // current section
 $this_section = SECTION_COURSES;
@@ -333,4 +331,4 @@ switch ($action) {
     case 'thematic_advance_list'    : 
         $thematic_controller->thematic_advance($action);
         break;
-}
+}

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