Browse Source

Merge branch 'master' of github.com:chamilo/chamilo-lms

Yannick Warnier 11 years ago
parent
commit
d15b21f889
100 changed files with 2308 additions and 6964 deletions
  1. 7 1
      .gitignore
  2. 20 15
      composer.json
  3. 306 175
      composer.lock
  4. 0 0
      config/auth.conf.dist.php
  5. 154 0
      config/configuration.dist.php
  6. 45 0
      config/configuration.dist.yml.php
  7. 66 0
      config/events.conf.dist.php
  8. 16 0
      config/mail.conf.dist.php
  9. 0 0
      config/portfolio.conf.dist.php
  10. 0 0
      config/profile.conf.dist.php
  11. 0 2
      main/admin/calendar.lib.php
  12. 5 5
      main/admin/configure_extensions.php
  13. 16 25
      main/admin/course_create_content.php
  14. 13 6
      main/admin/course_list.php
  15. 3 3
      main/admin/extra_field_workflow.php
  16. 7 7
      main/admin/extra_fields.php
  17. 3 3
      main/admin/session_course_list.php
  18. 1 0
      main/admin/settings.php
  19. 7 6
      main/admin/special_exports.php
  20. 2 2
      main/admin/user_fields.php
  21. 2 2
      main/admin/user_list.php
  22. 5 5
      main/admin/user_move_stats.php
  23. 2 2
      main/auth/shibboleth/init.php
  24. 3 3
      main/calendar/agenda.inc.php
  25. 1 1
      main/calendar/agenda.lib.php
  26. 7 7
      main/calendar/myagenda.inc.php
  27. 17 17
      main/calendar/myagenda.php
  28. 62 62
      main/course_description/course_description.class.php
  29. 3 2
      main/course_progress/index.php
  30. 19 10
      main/course_progress/thematic_controller.php
  31. 6 3
      main/coursecopy/classes/CourseBuilder.class.php
  32. 1 1
      main/coursecopy/classes/CourseRestorer.class.php
  33. 1 1
      main/coursecopy/classes/DummyCourseCreator.class.php
  34. 2 2
      main/dropbox/dropbox_functions.inc.php
  35. 1 1
      main/dropbox/dropbox_init.inc.php
  36. 11 12
      main/exercice/admin.php
  37. 5 1
      main/exercice/exercice.php
  38. 46 12
      main/exercice/exercise.class.php
  39. 2 2
      main/exercice/exercise_history.php
  40. 32 41
      main/exercice/exercise_report.php
  41. 7 7
      main/exercice/exercise_result.class.php
  42. 1 1
      main/exercice/exercise_result.php
  43. 2 2
      main/exercice/exercise_show.php
  44. 1 1
      main/exercice/exercise_submit.php
  45. 3 3
      main/exercice/hotpotatoes_exercise_report.php
  46. 4 4
      main/exercice/hotpotatoes_exercise_result.class.php
  47. 1 1
      main/exercice/hotspot_answers.as.php
  48. 1 1
      main/exercice/hotspot_savescore.inc.php
  49. 1 1
      main/exercice/hotspot_updatescore.inc.php
  50. 1 1
      main/exercice/mark_free_answer.php
  51. 4 2
      main/exercice/question.class.php
  52. 5 3
      main/exercice/question_list_admin.inc.php
  53. 2 2
      main/exercice/question_list_pagination_admin.inc.php
  54. 2 2
      main/exercice/savescores.php
  55. 18 16
      main/exercice/testcategory.class.php
  56. 1 1
      main/forum/forumfunction.inc.php
  57. 1 1
      main/gradebook/exercise_jump.php
  58. 3 3
      main/gradebook/gradebook_result.class.php
  59. 1 1
      main/gradebook/index.php
  60. 2 2
      main/gradebook/lib/be/exerciselink.class.php
  61. 2 2
      main/gradebook/lib/fe/displaygradebook.php
  62. 2 2
      main/gradebook/lib/fe/gradebooktable.class.php
  63. 2 2
      main/inc/ajax/exercise.ajax.php
  64. 2 2
      main/inc/ajax/message.ajax.php
  65. 9 5
      main/inc/ajax/thematic.ajax.php
  66. 0 66
      main/inc/conf/events.conf.dist.php
  67. 0 6
      main/inc/conf/index.html
  68. 0 18
      main/inc/conf/mail.conf.dist.php
  69. 184 211
      main/inc/global.inc.php
  70. 1 8
      main/inc/lib/announcements.inc.php
  71. 26 26
      main/inc/lib/attendance.lib.php
  72. 21 22
      main/inc/lib/auth.lib.php
  73. 3 3
      main/inc/lib/classmanager.lib.php
  74. 147 82
      main/inc/lib/course.lib.php
  75. 54 54
      main/inc/lib/course_description.lib.php
  76. 1 1
      main/inc/lib/course_request.lib.php
  77. 2 4
      main/inc/lib/dashboard.lib.php
  78. 149 644
      main/inc/lib/database.lib.php
  79. 0 1245
      main/inc/lib/database.mysqli.lib.php
  80. 477 138
      main/inc/lib/diagnoser.lib.php
  81. 4 3
      main/inc/lib/display.lib.php
  82. 54 54
      main/inc/lib/events.lib.inc.php
  83. 16 16
      main/inc/lib/exercise.lib.php
  84. 4 4
      main/inc/lib/extra_field.lib.php
  85. 4 4
      main/inc/lib/extra_field_value.lib.php
  86. 3 3
      main/inc/lib/fckeditor/fckeditor.php
  87. 1 1
      main/inc/lib/glossary.lib.php
  88. 4 4
      main/inc/lib/groupmanager.lib.php
  89. 20 12
      main/inc/lib/internationalization.lib.php
  90. 5 10
      main/inc/lib/login.lib.php
  91. 107 158
      main/inc/lib/main_api.lib.php
  92. 4 3
      main/inc/lib/nanogong.lib.php
  93. 4 4
      main/inc/lib/notebook.lib.php
  94. 35 23
      main/inc/lib/online.inc.php
  95. 1 2
      main/inc/lib/page.lib.php
  96. 0 504
      main/inc/lib/phpmailer/LICENSE
  97. 0 218
      main/inc/lib/phpmailer/README
  98. 0 169
      main/inc/lib/phpmailer/aboutus.html
  99. 0 408
      main/inc/lib/phpmailer/changelog.txt
  100. 0 2331
      main/inc/lib/phpmailer/class.phpmailer.php

+ 7 - 1
.gitignore

@@ -1,7 +1,13 @@
 # Chamilo
 
 main/inc/conf
-config/*
+config/auth.conf.php
+config/configuration.php
+config/events.conf.php
+config/mail.conf.php
+config/portfolio.conf.php
+config/profile.conf.php
+
 temp/*
 data/*
 !data/upload/users

+ 20 - 15
composer.json

@@ -1,7 +1,8 @@
 {
-    "name" : "chamilo/chamilo-lms",
-    "homepage" : "www.chamilo.org",
-    "license" : "GPL-3.0",
+    "name": "chamilo/chamilo-lms",
+    "type": "project",
+    "homepage": "www.chamilo.org",
+    "license": "GPL-3.0",
     "support": {
         "forum": "http://www.chamilo.org/forum",
         "irc": "irc://irc.freenode.org/chamilo"
@@ -34,22 +35,24 @@
         {
             "type": "vcs",
             "url": "https://github.com/jmontoyaa/silex-pagerfanta-provider"
+        },
+        {
+            "type": "vcs",
+            "url": "https://github.com/ThePixelDeveloper/ConsoleServiceProvider"
         }
     ],
     "require": {
         "php": ">=5.3.2",
         "silex/silex": "~1.0",
-        "symfony/config": "2.2.*@dev",
-        "symfony/yaml": "2.1.*@dev",
-        "symfony/console"  : "2.3.*@dev",
-        "symfony/twig-bridge": "2.2.*@dev",
+        "symfony/console"  : "~2.3",
+        "symfony/twig-bridge": "~2.3",
         "symfony/doctrine-bridge": "2.3.*@dev",
-        "symfony/security": "2.3.*@dev",
-        "symfony/form": "2.2.*@dev",
+        "symfony/security": "~2.3",
+        "symfony/form": "~2.3",
         "symfony/property-access": "2.3.*@dev",
-        "symfony/validator": "2.3.*@dev",
-        "symfony/translation": "2.3.*@dev",
-        "symfony/dependency-injection": "2.3.*@dev",
+        "symfony/validator": "~2.3",
+        "symfony/translation": "~2.3",
+        "symfony/dependency-injection": "~2.3",
         "monolog/monolog" : ">=1.0.0",
         "twig/twig": ">=1.8,<2.0-dev",
         "dflydev/doctrine-orm-service-provider": "1.0.*@dev",
@@ -59,16 +62,17 @@
         "swiftmailer/swiftmailer": ">=4.1.2,<4.2-dev",
         "pagerfanta/pagerfanta": "dev-master",
         "franmomu/silex-pagerfanta-provider": "2.3.*@dev",
-        "knplabs/knp-menu": "2.0.*@dev",
         "igorw/config-service-provider": "1.0.*@dev",
         "mpdf/mpdf": "v5.6.1",
         "ezyang/htmlpurifier": "v4.5.0",
         "realityking/pchart": "dev-master",
         "imagine/imagine": "dev-develop",
         "grom/silex-service-provider": "dev-master",
+        "knplabs/knp-menu": "2.0.*@dev",
         "knplabs/knp-snappy": "dev-master",
-        "jmontoyaa/phpqrcode": "dev-master",
+        "knplabs/console-service-provider": "dev-master",
         "knplabs/gaufrette": "0.2.*@dev",
+        "jmontoyaa/phpqrcode": "dev-master",
         "bt51/gaufrette-serviceprovider": "dev-master",
         "neutron/silex-filesystem-provider": "dev-master",
         "jbroadway/urlify": "dev-master"
@@ -79,7 +83,8 @@
         "silex/web-profiler": "1.0.x-dev",
         "natxet/CssMin": "dev-master",
         "leafo/lessphp": "dev-master",
-        "mheap/silex-assetic": "dev-master"
+        "mheap/silex-assetic": "1.0.*@dev",
+        "filp/whoops": "dev-master"
     },
     "scripts": {
         "post-install-cmd": "ChamiloLMS\\Composer\\Tasks::postInstall",

File diff suppressed because it is too large
+ 306 - 175
composer.lock


+ 0 - 0
main/inc/conf/auth.conf.dist.php → config/auth.conf.dist.php


+ 154 - 0
config/configuration.dist.php

@@ -0,0 +1,154 @@
+<?php
+// Chamilo version {NEW_VERSION}
+// File generated by /install/index.php script - {DATE_GENERATED}
+/* For licensing terms, see /license.txt */
+/**
+ *		Chamilo configuration
+ *
+ * This file contains a list of variables that can be modified by the campus
+ * site's server administrator. Pay attention when changing these variables,
+ * some changes may cause Chamilo to stop working.
+ * If you changed some settings and want to restore them, please have a look at
+ * configuration.dist.php. That file is an exact copy of the config file at
+ * install time.
+ */
+
+/**
+ * $_configuration define only the bare essential variables
+ * for configuring the platform (paths, database connections, ...).
+ * Changing a $_configuration variable CAN generally break the installation.
+ * Besides the $_configuration, a $_settings array also exists, that
+ * contains variables that can be changed and will not break the platform.
+ * These optional settings are defined in the database, now (table settings_current).
+ */
+
+/**
+ * Database settings
+ */
+// Host
+$_configuration['db_host']     = '{DATABASE_HOST}';
+// Username
+$_configuration['db_user']     = '{DATABASE_USER}';
+// Password
+$_configuration['db_password'] = '{DATABASE_PASSWORD}';
+// Driver
+$_configuration['db_driver']   = '{DATABASE_DRIVER}';
+// Database name
+$_configuration['main_database'] = '{DATABASE_MAIN}';
+
+/** Directory settings */
+// URL to the root of your Chamilo installation, e.g.: http://www.mychamilo.com/
+$_configuration['root_web']    = '{ROOT_WEB}';
+
+/** Chamilo will automatically manage all this paths */
+
+// Path to the webroot of system, example: /var/www/chamilo
+//$_configuration['root_sys'] = '{ROOT_SYS}';
+
+// Path to the data folder, example /var/www/chamilo/data
+//$_configuration['sys_data_path'] = null;
+
+// Path to the config folder, example /var/www/chamilo/config
+//$_configuration['sys_config_path'] = null;
+
+// Path to the temp folder, example /var/www/chamilo/temp
+//$_configuration['sys_temp_path'] = null;
+
+// Path to the logs folder, example /var/www/chamilo/logs
+//$_configuration['sys_log_path'] = null;
+
+// URL to your phpMyAdmin installation.
+// If not empty, a link will be available in the Platform Administration
+$_configuration['db_admin_path']  = '';
+
+/** Login modules settings */
+// CAS IMPLEMENTATION
+// -> Go to your portal Chamilo > Administration > CAS to activate CAS
+// You can leave these lines uncommented even if you don't use CAS authentification
+//$extAuthSource["cas"]["login"] = $_configuration['root_sys'].$_configuration['code_append']."auth/cas/login.php";
+//$extAuthSource["cas"]["newUser"] = $_configuration['root_sys'].$_configuration['code_append']."auth/cas/newUser.php";
+//
+// NEW LDAP IMPLEMENTATION BASED ON external_login info
+// -> Uncomment the two lines bellow to activate LDAP AND edit main/auth/external_login/ldap.conf.php for configuration
+// $extAuthSource["extldap"]["login"] = $_configuration['root_sys'].$_configuration['code_append']."auth/external_login/login.ldap.php";
+// $extAuthSource["extldap"]["newUser"] = $_configuration['root_sys'].$_configuration['code_append']."auth/external_login/newUser.ldap.php";
+//
+// FACEBOOK IMPLEMENTATION BASED ON external_login info
+// -> Uncomment the line bellow to activate Facebook Auth AND edit main/auth/external_login/ldap.conf.php for configuration
+// $_configuration['facebook_auth'] = 1;
+//
+// OTHER EXTERNAL LOGIN INFORMATION
+// To fetch external login information, uncomment those 2 lines and modify  files auth/external_login/newUser.php and auth/external_login/updateUser.php files
+// $extAuthSource["external_login"]["newUser"] = $_configuration['root_sys'].$_configuration['code_append']."auth/external_login/newUser.php";
+// $extAuthSource["external_login"]["updateUser"] = $_configuration['root_sys'].$_configuration['code_append']."auth/external_login/updateUser.php";
+
+/**
+ *
+ * Hosting settings - Allows you to set limits to the Chamilo portal when
+ * hosting it for a third party. These settings can be overwritten by an
+ * optionally-loaded extension file with only the settings (no comments).
+ * The settings use an index at the first level to represent the ID of the
+ * URL in case you use multi-url (otherwise it will always use 1, which is
+ * the ID of the only URL inside the access_url table).
+ */
+// Set a maximum number of users. Default (0) = no limit
+$_configuration[1]['hosting_limit_users'] = 0;
+// Set a maximum number of teachers. Default (0) = no limit
+$_configuration[1]['hosting_limit_teachers'] = 0;
+// Set a maximum number of courses. Default (0) = no limit
+$_configuration[1]['hosting_limit_courses'] = 0;
+// Set a maximum number of sessions. Default (0) = no limit
+$_configuration[1]['hosting_limit_sessions'] = 0;
+// Set a maximum disk space used, in MB (set to 1024 for 1GB, 5120 for 5GB).
+// Default (0) = no limit
+$_configuration[1]['hosting_limit_disk_space'] = 0;
+
+/**
+ * Content Delivery Network (CDN) settings. Only use if you need a separate
+ * server to serve your static data. If you don't know what a CDN is, you
+ * don't need it. These settings are for simple Origin Pull CDNs and are
+ * experimental. Enable only if you really know what you're doing.
+ * This might conflict with multiple-access urls.
+ */
+// Set the following setting to true to start using the CDN
+$_configuration['cdn_enable'] = false;
+// The following setting will be ignored if the previous one is set to false
+$_configuration['cdn'] = array(
+  //You can define several CDNs and split them by extensions
+  //Replace the following by your full CDN URL, which should point to
+  // your Chamilo's root directory. DO NOT INCLUDE a final slash! (won't work)
+  'http://cdn.chamilo.org' => array('.css','.js','.jpg','.jpeg','.png','.gif','.avi','.flv'),
+  // copy the line above and modify following your needs
+);
+
+/**
+ * Session settings
+ */
+// You may have to restart your web server if you change this
+$_configuration['session_stored_in_db'] = false;
+// Session lifetime
+$_configuration['session_lifetime'] = SESSION_LIFETIME;
+
+/** Security */
+// Security word for password recovery
+$_configuration['security_key'] = '{SECURITY_KEY}';
+// Hash function method
+$_configuration['password_encryption'] = '{ENCRYPT_PASSWORD}';
+//Deny the elimination of users
+$_configuration['deny_delete_users'] = false;
+//Prevent all admins from using the "login_as" feature
+$_configuration['login_as_forbidden_globally'] = false;
+
+/** Multiple URL */
+// Activation for multi-url access
+//$_configuration['multiple_access_urls'] = true;
+
+/** Chamilo version settings */
+$_configuration['system_version']    = '{NEW_VERSION}';
+$_configuration['system_stable']     = NEW_VERSION_STABLE;
+$_configuration['software_name']     = 'Chamilo';
+$_configuration['software_url']	     = 'http://www.chamilo.org/';
+
+/** Chamilo dev settings */
+$_configuration['debug']             = false;
+$_configuration['show_profiler']     = false;

+ 45 - 0
config/configuration.dist.yml.php

@@ -0,0 +1,45 @@
+<?php
+/** This script is only use when using the console.php chamilo:install command */
+/**
+ * Database settings
+ */
+// Your MySQL server
+$_configuration['db_host']     = 'localhost';
+// Your MySQL username
+$_configuration['db_user']     = 'root';
+// Your MySQL password
+$_configuration['db_password'] = 'root';
+
+// Prefix for course tables (IF NOT EMPTY, can be replaced by another prefix, else leave empty)
+/*$_configuration['table_prefix']          = '';
+// prefix all created bases (for courses) with this string
+$_configuration['db_prefix']             = '';*/
+// main Chamilo database
+$_configuration['main_database']         = 'chamilo';
+
+/**
+ * Directory settings
+ */
+// URL to the root of your Chamilo installation, e.g.: http://www.mychamilo.com/
+$_configuration['root_web']       = 'http://localhost/chamilo';
+$_configuration['root_sys']       = '/var/www/chamilo';
+
+/**
+ * Misc. settings
+ */
+// Security word for password recovery
+$_configuration['security_key']      = md5(uniqid(rand().time()));
+// Hash function method
+$_configuration['password_encryption']      = 'sha1';
+// You may have to restart your web server if you change this
+$_configuration['session_stored_in_db']     = false;
+// Session lifetime
+$_configuration['session_lifetime']         = 3600;
+// Activation for multi-url access
+//$_configuration['multiple_access_urls']   = true;
+//Deny the elimination of users
+$_configuration['deny_delete_users']        = false;
+//Prevent all admins from using the "login_as" feature
+$_configuration['login_as_forbidden_globally'] = false;
+// Version settings
+$_configuration['system_version']           = '1.10.0';

+ 66 - 0
config/events.conf.dist.php

@@ -0,0 +1,66 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+/**
+ * Events' configuration
+ * Used to configure each event and to link them to functions the event'll fire.
+ * The flow is like the following :
+ * 1. somewhere in the application an event is fired
+ * 2. that event is intercepted by the switch EventsDispatcher
+ * 3. that switch will go all over the "actions" in the event_config initialized beneath us according to the event
+ * 4. that switch will see if the function actually exists (if not, we get dont do anything)
+ * 5. then it will see if a filter for that function exists (if it does, the filter is executed)
+ * 6. if the filter says it's ok, the function linked to the event is executed
+ * 7. and that function will actually call the truly interesting function with the good require_once
+ */
+global $event_config;
+
+$event_config = array(
+    'portal_homepage_edited' => array( // key for "user registration" event
+        'actions' => array( // we link this event to a bunch of functions that will be triggered when the event is fired
+            'event_send_mail' // don't forget to actually write this function in the events.lib.php file
+        ),
+        'self_sent' => false, // this key states that we can't add user to this event through the admin panel
+        'name_lang_var' => 'PortalHomepageEdited',
+        'desc_lang_var' => 'PortalHomepageEdited',
+        'available_keyvars' => array (// keys used for the mail template
+            'url'           => 'portal',
+            'sitename'      => 'sitename',
+            'firstname'     => 'firstname',
+            'lastname'      => 'lastname',
+            'username'      => 'username',
+            'usermail'      => 'usermail',
+            'password'      => 'password',
+            'user_lang'     => 'language',
+            'admin_name'    => 'administrator_name',
+            'admin_surname' => 'administrator_surname',
+            'admin_phone'   => 'administrator_phone',
+            'admin_email'   => 'administrator_email',
+        )
+    ),
+    'user_registration' => array( // key for "user registration" event
+        'actions' => array( // we link this event to a bunch of functions that will be triggered when the event is fired
+            'event_send_mail' // don't forget to actually write this function in the events.lib.php file
+        ),
+        'self_sent' => true, // this key states that we can't add user to this event through the admin panel
+        'name_lang_var' => 'UserRegistrationTitle',
+        'desc_lang_var' => 'UserRegistrationComment',
+        'available_keyvars' => array (// keys used for the mail template
+            'url'           => 'portal',
+            'sitename'      => 'sitename',
+            'firstname'     => 'firstname',
+            'lastname'      => 'lastname',
+            'username'      => 'username',
+            'usermail'      => 'usermail',
+            'password'      => 'password',
+            'user_lang'     => 'language',
+            'admin_name'    => 'administrator_name',
+            'admin_surname' => 'administrator_surname',
+            'admin_phone'   => 'administrator_phone',
+            'admin_email'   => 'administrator_email',
+        )
+    ),
+);
+
+
+//@include 'events.conf.local.php';

+ 16 - 0
config/mail.conf.dist.php

@@ -0,0 +1,16 @@
+<?php
+
+/**
+ *	This file holds the email configuration settings
+ *	@package chamilo.configuration
+ */
+
+$platform_email['SMTP_FROM_EMAIL']   = (isset($administrator['email'])?$administrator['email']:'admin@example.com');
+$platform_email['SMTP_FROM_NAME']    = (isset($administrator['name'])?$administrator['name']:'Admin');
+$platform_email['SMTP_HOST']         = 'localhost';
+$platform_email['SMTP_PORT']         = 25;
+$platform_email['SMTP_MAILER']       = 'mail'; // mail, sendmail or smtp
+$platform_email['SMTP_AUTH']         = 0;
+$platform_email['SMTP_USER']         = '';
+$platform_email['SMTP_PASS']         = '';
+$platform_email['SMTP_CHARSET']      = 'UTF-8';

+ 0 - 0
main/inc/conf/portfolio.conf.dist.php → config/portfolio.conf.dist.php


+ 0 - 0
main/inc/conf/profile.conf.dist.php → config/profile.conf.dist.php


+ 0 - 2
main/admin/calendar.lib.php

@@ -1637,9 +1637,7 @@ function get_agendaitems($month, $year)
 
     //databases of the courses
     $TABLEAGENDA = Database :: get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-    //$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
 
-    //$group_memberships = GroupManager :: get_group_ids(Database::get_current_course_database(), $_user['user_id']);
     // if the user is administrator of that course we show all the agenda items
     //if (api_is_allowed_to_edit())
     //{

+ 5 - 5
main/admin/configure_extensions.php

@@ -26,7 +26,7 @@ if (isset($_POST['activeExtension'])) {
 					WHERE variable="service_visio"
 					AND subkey="active"';
 			$rs = Database::query($sql);
-			if(Database::affected_rows()>0) {
+			if (Database::affected_rows($rs)>0) {
 				// select all the courses and insert the tool inside
 				$sql = 'SELECT id FROM '.Database::get_main_table(TABLE_MAIN_COURSE);
 				$rs = Database::query($sql);
@@ -105,7 +105,7 @@ if (isset($_POST['activeExtension'])) {
 
 			$rs = Database::query($sql);
 
-			if(Database::affected_rows()>0){
+			if (Database::affected_rows($rs)>0){
 				$message = get_lang('ServiceActivated');
 			}
 
@@ -299,7 +299,7 @@ Display::display_header($nameTool);
 	</div>
 
  */ ?>
-    
+
 	<!-- PPT2LP -->
 	<div id="main_ppt2lp">
 		<div id="extension_header_ppt2lp" class="accordion_header">
@@ -441,8 +441,8 @@ Display::display_header($nameTool);
 	</div>
 	*/
     /*
-	
-    
+
+
 	<!-- SEARCH -->
 	<div id="main_search">
 		<div id="extension_header_search" class="accordion_header">

+ 16 - 25
main/admin/course_create_content.php

@@ -7,39 +7,30 @@
  * @package chamilo.admin
  */
 /**
- *		INIT SECTION
+ *        INIT SECTION
  */
 
 // name of the language file that needs to be included
 $language_file = 'admin';
-include ('../inc/global.inc.php');
-$this_section=SECTION_PLATFORM_ADMIN;
+include('../inc/global.inc.php');
+$this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 $tool_name = get_lang('DummyCourseCreator');
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 Display::display_header($tool_name);
 //api_display_tool_title($tool_name);
-if(api_get_setting('server_type') != 'test')
-{
-	echo get_lang('DummyCourseOnlyOnTestServer');
+if (api_get_setting('server_type') != 'test') {
+    echo get_lang('DummyCourseOnlyOnTestServer');
+} elseif (isset($_POST['action'])) {
+    require_once('../coursecopy/classes/DummyCourseCreator.class.php');
+    $dcc = new DummyCourseCreator();
+    $dcc->create_dummy_course($_POST['course_code']);
+    echo get_lang('Done');
+} else {
+    echo get_lang('DummyCourseDescription');
+    echo '<form method="post"><input type="hidden" name="course_code" value="'.Security::remove_XSS(
+            $_GET['course_code']
+        ).'"/><input type="submit" name="action" value="'.get_lang('Ok').'"/></form>';
 }
-elseif( isset($_POST['action']))
-{
-	require_once('../coursecopy/classes/DummyCourseCreator.class.php');
-	$dcc = new DummyCourseCreator();
-	$dcc->create_dummy_course($_POST['course_code']);
-	echo get_lang('Done');
-}
-else
-{
-	echo get_lang('DummyCourseDescription');
-	echo '<form method="post"><input type="hidden" name="course_code" value="'.Security::remove_XSS($_GET['course_code']).'"/><input type="submit" name="action" value="'.get_lang('Ok').'"/></form>';
-}
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
 Display::display_footer();
-?>

+ 13 - 6
main/admin/course_list.php

@@ -24,11 +24,11 @@ require_once '../gradebook/lib/be/category.class.php';
  */
 function get_number_of_courses() {
     $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
-    $sql = "SELECT COUNT(code) AS total_number_of_items FROM $course_table";
+    $sql = "SELECT COUNT(code) AS total_number_of_items FROM $course_table course";
 
     if ((api_is_platform_admin() || api_is_session_admin()) && api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1) {
         $access_url_rel_course_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-        $sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (id = url_rel_course.c_id)";
+        $sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (course.id = url_rel_course.c_id)";
     }
 
     if (isset ($_GET['keyword'])) {
@@ -42,7 +42,13 @@ function get_number_of_courses() {
         $keyword_visibility = Database::escape_string($_GET['keyword_visibility']);
         $keyword_subscribe = Database::escape_string($_GET['keyword_subscribe']);
         $keyword_unsubscribe = Database::escape_string($_GET['keyword_unsubscribe']);
-        $sql .= " WHERE (code LIKE '%".$keyword_code."%' OR visual_code LIKE '%".$keyword_code."%') AND title LIKE '%".$keyword_title."%' AND category_code LIKE '%".$keyword_category."%'  AND course_language LIKE '%".$keyword_language."%'   AND visibility LIKE '%".$keyword_visibility."%'    AND subscribe LIKE '".$keyword_subscribe."'AND unsubscribe LIKE '".$keyword_unsubscribe."'";
+        $sql .= " WHERE (code LIKE '%".$keyword_code."%' OR visual_code LIKE '%".$keyword_code."%') AND
+                        title LIKE '%".$keyword_title."%' AND
+                        category_code LIKE '%".$keyword_category."%' AND
+                        course_language LIKE '%".$keyword_language."%'  AND
+                        visibility LIKE '%".$keyword_visibility."%'    AND
+                        subscribe LIKE '".$keyword_subscribe."'AND
+                        unsubscribe LIKE '".$keyword_unsubscribe."'";
     }
 
      // adding the filter to see the user's only of the current access_url
@@ -72,11 +78,11 @@ function get_course_data($from, $number_of_items, $column, $direction) {
                     visibility AS col8,
                     directory as col9,
                     visual_code
-    		FROM $course_table";
+    		FROM $course_table course";
 
     if ((api_is_platform_admin() || api_is_session_admin()) && api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1) {
         $access_url_rel_course_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-        $sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (id = url_rel_course.c_id)";
+        $sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (course.id = url_rel_course.c_id)";
     }
 
     if (isset ($_GET['keyword'])) {
@@ -104,6 +110,7 @@ function get_course_data($from, $number_of_items, $column, $direction) {
     $res = Database::query($sql);
     $courses = array ();
     while ($course = Database::fetch_array($res)) {
+
         // Place colour icons in front of courses.
         $show_visual_code = $course['visual_code'] != $course[2] ? Display::label($course['visual_code'], 'info') : null;
         $course[1] = get_course_visibility_icon($course[8]).'<a href="'.api_get_path(WEB_COURSE_PATH).$course[9].'/index.php">'.$course[1].'</a> '.$show_visual_code;
@@ -224,7 +231,7 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
                 break;
         }
     }
-    if (isset ($_GET['delete_course'])) {
+    if (isset($_GET['delete_course'])) {
         CourseManager::delete_course($_GET['delete_course']);
         $obj_cat = new Category();
         $obj_cat->update_category_delete($_GET['delete_course']);

+ 3 - 3
main/admin/extra_field_workflow.php

@@ -198,18 +198,18 @@ if ($form->validate()) {
                         $extraFieldOptionRelFieldOption->setFieldOptionId($subItemId);
                         $extraFieldOptionRelFieldOption->setRelatedFieldOptionId($id);
                         $extraFieldOptionRelFieldOption->setRoleId($roleId);
-                        $app['orm.em']->persist($extraFieldOptionRelFieldOption);
+                        $app['orm.ems']['db_write']->persist($extraFieldOptionRelFieldOption);
                     }
                 } else {
 
                     if ($extraFieldOptionRelFieldOption) {
-                        $app['orm.em']->remove($extraFieldOptionRelFieldOption);
+                        $app['orm.ems']['db_write']->remove($extraFieldOptionRelFieldOption);
                     }
                 }
 
             }
         }
-        $app['orm.em']->flush();
+        $app['orm.ems']['db_write']->flush();
         header('Location:'.api_get_self().'?'.$params);
         exit;
     }

+ 7 - 7
main/admin/extra_fields.php

@@ -134,13 +134,13 @@ switch ($action) {
 
         // The validation or display
         if ($form->validate()) {
-            if ($check) {
+            //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">';
@@ -158,11 +158,11 @@ switch ($action) {
 
         // The validation or display
         if ($form->validate()) {
-            if ($check) {
+            //if ($check) {
                 $values = $form->exportValues();
                 $res    = $obj->update($values);
-                Display::display_confirmation_message(sprintf(get_lang('ItemUpdated'), $values['name']), false);
-            }
+                Display::display_confirmation_message(sprintf(get_lang('ItemUpdated'), $values['field_variable']), false);
+            //}
             $obj->display();
         } else {
             echo '<div class="actions">';
@@ -175,12 +175,12 @@ switch ($action) {
         break;
     case 'delete':
         // Action handling: delete
-        if ($check) {
+        //if ($check) {
             $res = $obj->delete($_GET['id']);
             if ($res) {
                 Display::display_confirmation_message(get_lang('ItemDeleted'));
             }
-        }
+        //}
         $obj->display();
         break;
     default:

+ 3 - 3
main/admin/session_course_list.php

@@ -47,8 +47,8 @@ if ($action == 'delete') {
 		}
 		$idChecked = $my_temp;
 		$idChecked="'".implode("','", $idChecked)."'";
-		Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND c_id IN($idChecked)");
-		$nbr_affected_rows=Database::affected_rows();
+		$result = Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND c_id IN($idChecked)");
+		$nbr_affected_rows = Database::affected_rows($result);
 		Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND c_id IN($idChecked)");
 		Database::query("UPDATE $tbl_session SET nbr_courses=nbr_courses-$nbr_affected_rows WHERE id='$id_session'");
 	}
@@ -99,4 +99,4 @@ echo '<select name="action">
 	</select>
 	<button class="save" type="submit">'.get_lang('Ok').'</button>
 	</form>';
-Display::display_footer();
+Display::display_footer();

+ 1 - 0
main/admin/settings.php

@@ -41,6 +41,7 @@ api_protect_admin_script();
 // Settings to avoid
 $settings_to_avoid = array(
     'stylesheets' => '', // handled by the handle_stylesheet() function
+    'server_type',
     'use_session_mode' => 'true',
     'gradebook_enable' => 'false',
     'example_material_course_creation' => 'true' // ON by default - now we have this option when we create a course

+ 7 - 6
main/admin/special_exports.php

@@ -68,7 +68,7 @@ if ((isset ($_POST['action']) && $_POST['action'] == 'course_select_form') || (i
 			$Resource = $_POST['resource'];
 
 			foreach ($Resource as $Code_course => $Sessions) {
-				$_course 		= Database::get_course_info($Code_course);
+				$_course 		= api_get_course_info($Code_course);
 				$tbl_document 	= Database::get_course_table(TABLE_DOCUMENT);
 				$tbl_property 	= Database::get_course_table(TABLE_ITEM_PROPERTY);
 				$course_id 		= $_course['real_id'];
@@ -103,10 +103,11 @@ if ((isset ($_POST['action']) && $_POST['action'] == 'course_select_form') || (i
 							AND props.to_group_id= $to_group_id AND docs.c_id = $course_id AND props.c_id = $course_id";
 					$query_session_doc = Database::query($sql_session_doc);
 					while ($rows_course_session_file = Database::fetch_assoc($query_session_doc)) {
-						$zip_folder->add($FileZip['PATH_COURSE'].$_course['directory'].'/document'.$rows_course_session_file['path'],
-										 PCLZIP_OPT_ADD_PATH, $_course['directory']."/".$ListSession[$session_id],
-										 PCLZIP_OPT_REMOVE_PATH, $FileZip['PATH_COURSE'].$_course['directory'].'/document'.$FileZip['PATH_REMOVE']
-										);
+						$zip_folder->add(
+                            $FileZip['PATH_COURSE'].$_course['directory'].'/document'.$rows_course_session_file['path'],
+                            PCLZIP_OPT_ADD_PATH, $_course['directory']."/".$ListSession[$session_id],
+                            PCLZIP_OPT_REMOVE_PATH, $FileZip['PATH_COURSE'].$_course['directory'].'/document'.$FileZip['PATH_REMOVE']
+                        );
 					}
 				}
 			}
@@ -209,7 +210,7 @@ function fullexportspecial(){
     $code_course = '';
     $list_course = array();
     $zip_folder = new PclZip($FileZip['TEMP_FILE_ZIP']);
-    $list_course = Database::get_course_list();
+    $list_course = CourseManager::get_course_list();
 
     $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
     $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);

+ 2 - 2
main/admin/user_fields.php

@@ -343,7 +343,7 @@ function delete_user_fields($field_id) {
     // 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) {
+    if (Database::affected_rows($result) == 1) {
         // delete the field options
         $sql = "DELETE FROM $table_user_field_options WHERE field_id = '" . Database::escape_string($field_id) . "'";
         $result = Database::query($sql);
@@ -369,4 +369,4 @@ function delete_user_fields($field_id) {
         // the field was not deleted so we return false
         return false;
     }
-}
+}

+ 2 - 2
main/admin/user_list.php

@@ -167,7 +167,7 @@ function login_user($user_id) {
 
 	$main_user_table      = Database::get_main_table(TABLE_MAIN_USER);
 	$main_admin_table     = Database::get_main_table(TABLE_MAIN_ADMIN);
-	$track_e_login_table  = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+	$track_e_login_table  = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
 
 	unset($_user['user_id']); // uid not in session ? prevent any hacking
 
@@ -906,4 +906,4 @@ $tpl = $app['template'];
 $tpl->assign('actions', $actions);
 $tpl->assign('message', $message);
 $tpl->assign('content', $form.$table_result.$extra_search_options);
-$tpl->display_one_col_template();
+$tpl->display_one_col_template();

+ 5 - 5
main/admin/user_move_stats.php

@@ -118,10 +118,10 @@ if (isset($_REQUEST['load_ajax'])) {
 
                 //Begin with the import process
 
-                $TABLETRACK_EXERCICES       = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-                $TBL_TRACK_ATTEMPT          = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-                $TBL_TRACK_E_COURSE_ACCESS  = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
-                $TBL_TRACK_E_LAST_ACCESS    = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
+                $TABLETRACK_EXERCICES       = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+                $TBL_TRACK_ATTEMPT          = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+                $TBL_TRACK_E_COURSE_ACCESS  = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
+                $TBL_TRACK_E_LAST_ACCESS    = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
 
                 $TBL_LP_VIEW                = Database::get_course_table(TABLE_LP_VIEW);
                 $TBL_NOTEBOOK               = Database::get_course_table(TABLE_NOTEBOOK);
@@ -588,7 +588,7 @@ $htmlHeadXtra[] = '<script type="text/javascript">
  </script>';
 
 function get_courses_list_by_user_id_based_in_exercises($user_id) {
-    $TABLETRACK_EXERCICES       = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $TABLETRACK_EXERCICES       = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
     $user_id = intval($user_id);
     $sql = "SELECT DISTINCT exe_user_id, c_id, session_id as id_session
     FROM $TABLETRACK_EXERCICES WHERE exe_user_id = $user_id

+ 2 - 2
main/auth/shibboleth/init.php

@@ -16,10 +16,10 @@ include_once($__dir . '/../../inc/global.inc.php');
 
 require_once $__dir . 'config.php';
 
-if (api_get_setting('server_type') == 'test')
+if ($app['debug'])
 {
     include_once $__dir . '/test/shibboleth_test_helper.class.php';
     include_once $__dir . '/test/shibboleth_test.class.php';
 }
 
-$language_files[] = 'shibboleth';
+$language_files[] = 'shibboleth';

+ 3 - 3
main/calendar/agenda.inc.php

@@ -34,7 +34,7 @@ $(function() {
         } else {
             url = String(window.location)+temp;
             window.location.replace(url);
-        }    
+        }
     });
 });
 </script>';
@@ -289,7 +289,7 @@ function get_calendar_items($select_month, $select_year, $select_day = false)
 
     //Check my personal calendar items
     if (api_get_setting('allow_personal_agenda') == 'true' && empty($_SESSION['user']) && empty($_SESSION['group'])) {
-        $tbl_personal_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
+        $tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
         // 1. creating the SQL statement for getting the personal agenda items in MONTH view
         $sql = "SELECT id, title, text as content , date as start_date, enddate as end_date, parent_event_id FROM ".$tbl_personal_agenda."
                 WHERE user='".api_get_user_id()."' ".$show_all_current_personal;
@@ -1120,7 +1120,7 @@ function construct_to_select_form($group_list = null, $user_list = null, $filter
         }
         $result .= "</optgroup>";
     }
-    
+
     // adding the individual users to the select form
     if (!empty($user_list)) {
         $result .= '<optgroup label="'.get_lang('FilterByUser').'">';

+ 1 - 1
main/calendar/agenda.lib.php

@@ -14,7 +14,7 @@ class Agenda
     {
         //Table definitions
         $this->tbl_global_agenda   = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-        $this->tbl_personal_agenda = Database::get_user_personal_table(TABLE_PERSONAL_AGENDA);
+        $this->tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
         $this->tbl_course_agenda   = Database::get_course_table(TABLE_AGENDA);
 
         //Setting the course object if we are in a course

+ 7 - 7
main/calendar/myagenda.inc.php

@@ -327,7 +327,7 @@ function display_myminimonthcalendar($agendaitems, $month, $year, $monthName) {
 function show_new_personal_item_form($id = "") {
 	global $year, $MonthsLong;
 
-	$tbl_personal_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
+	$tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
 
 	// we construct the default time and date data (used if we are not editing a personal agenda item)
 	//$today = getdate();
@@ -517,7 +517,7 @@ function show_new_personal_item_form($id = "") {
  */
 function store_personal_item($day, $month, $year, $hour, $minute, $title, $content, $id = "") {
 
-	$tbl_personal_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
+	$tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
 
 	//constructing the date
 	$date = $year."-".$month."-".$day." ".$hour.":".$minute.":00";
@@ -598,7 +598,7 @@ function get_courses_of_user() {
  * This function retrieves all the personal agenda items and add them to the agenda items found by the other functions.
  */
 function get_personal_agenda_items($user_id, $agendaitems, $day = "", $month = "", $year = "", $week = "", $type) {
-	$tbl_personal_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
+	$tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
 	$user_id = intval($user_id);
 
 	// 1. creating the SQL statement for getting the personal agenda items in MONTH view
@@ -700,7 +700,7 @@ function get_personal_agenda_items($user_id, $agendaitems, $day = "", $month = "
  * @return 	array	The results of the database query, or null if not found
  */
 function get_personal_agenda_item($id) {
-	$tbl_personal_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
+	$tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
 	$id = Database::escape_string($id);
 	// make sure events of the personal agenda can only be seen by the user himself
 	$user = api_get_user_id();
@@ -720,7 +720,7 @@ function get_personal_agenda_item($id) {
 function show_personal_agenda() {
 	global $MonthsLong, $charset;
 
-	$tbl_personal_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
+	$tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
 
 	// The SQL statement that retrieves all the personal agenda items of this user
 	$sql = "SELECT * FROM ".$tbl_personal_agenda." WHERE user='".api_get_user_id()."' ORDER BY date DESC";
@@ -824,7 +824,7 @@ function show_personal_agenda() {
 function show_simple_personal_agenda($user_id) {
 	global $MonthsLong, $charset;
 
-	$tbl_personal_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
+	$tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
 
 	// The SQL statement that retrieves all the personal agenda items of this user
 	$sql = "SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' ORDER BY date DESC";
@@ -885,7 +885,7 @@ function show_simple_personal_agenda($user_id) {
  * does not belong to him/her
  */
 function delete_personal_agenda($id) {
-	$tbl_personal_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
+	$tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
 
 	if ($id != strval(intval($id))) {
 		return false; //potential SQL injection

+ 17 - 17
main/calendar/myagenda.php

@@ -31,11 +31,11 @@ if (!empty ($course_path)) {
 $htmlHeadXtra[] = to_javascript();
 $htmlHeadXtra[] = "<script src=\"tbl_change.js\" type=\"text/javascript\" language=\"javascript\"></script>";
 $htmlHeadXtra[] = "<script>
-$(function() {  
-    $(\".dialog\").dialog(\"destroy\");        
+$(function() {
+    $(\".dialog\").dialog(\"destroy\");
     $(\".dialog\").dialog({
             autoOpen: false,
-            show: \"blind\",                
+            show: \"blind\",
             resizable: false,
             height:300,
             width:550,
@@ -62,7 +62,7 @@ $TABLECOURS 		= Database :: get_main_table(TABLE_MAIN_COURSE);
 $TABLECOURSUSER 	= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 $TABLEAGENDA 		= Database :: get_course_table(TABLE_AGENDA);
 $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-$tbl_personal_agenda= Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
+$tbl_personal_agenda= Database :: get_main_table(TABLE_PERSONAL_AGENDA);
 
 // the variables for the days and the months
 // Defining the shorts for the days
@@ -141,7 +141,7 @@ if (isset($_user['user_id'])) {
 	// getting all the courses that this user is subscribed to
 	//$courses_dbs = get_all_courses_of_user();
 	$my_course_list = CourseManager::get_courses_list_by_user_id(api_get_user_id(), true);
-	
+
 	if (!is_array($my_course_list)) {
 		// this is for the special case if the user has no courses (otherwise you get an error)
 		$my_course_list = array();
@@ -178,13 +178,13 @@ if (isset($_user['user_id'])) {
 	}
 	echo "</div>";
 
-	$agendaitems = get_myagendaitems(api_get_user_id(), $my_course_list, $month, $year);	
+	$agendaitems = get_myagendaitems(api_get_user_id(), $my_course_list, $month, $year);
 	$agendaitems = get_global_agenda_items($agendaitems, $day, $month, $year, $week, "month_view");
-	
+
 	if (api_get_setting('allow_personal_agenda') == 'true') {
 		$agendaitems = get_personal_agenda_items(api_get_user_id(), $agendaitems, $day, $month, $year, $week, "month_view");
 	}
-	
+
 	if ($process != 'month_view') {
 	    echo "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
     	echo "<tr>";
@@ -196,26 +196,26 @@ if (isset($_user['user_id'])) {
     	// OlivierB : the image has a white background, which causes trouble if the portal has another background color. Image should be transparent. ----> echo "<td width=\"20\" background=\"../img/verticalruler.gif\">&nbsp;</td>";
     	echo "<td width=\"8\">&nbsp;</td>";
     	// the main area: day, week, month view
-    	echo "<td valign=\"top\">";   
+    	echo "<td valign=\"top\">";
 	}
-	
+
 	switch ($process) {
-		case 'month_view' :			
+		case 'month_view' :
 			display_mymonthcalendar(api_get_user_id(), $agendaitems, $month, $year, array(), $monthName);
 			break;
 		case 'week_view' :
-			$agendaitems = get_week_agendaitems($my_course_list, $month, $year, $week);						
-			$agendaitems = get_global_agenda_items($agendaitems, $day, $month, $year, $week, "week_view");			
+			$agendaitems = get_week_agendaitems($my_course_list, $month, $year, $week);
+			$agendaitems = get_global_agenda_items($agendaitems, $day, $month, $year, $week, "week_view");
 			if (api_get_setting("allow_personal_agenda") == "true") {
 				$agendaitems = get_personal_agenda_items(api_get_user_id(), $agendaitems, $day, $month, $year, $week, "week_view");
 			}
 			display_weekcalendar($agendaitems, $month, $year, array(), $monthName);
 			break;
 		case 'day_view' :
-			$agendaitems = get_day_agendaitems($my_course_list, $month, $year, $day);								
-			$agendaitems = get_global_agenda_items($agendaitems, $day, $month, $year, $week, "day_view");			
+			$agendaitems = get_day_agendaitems($my_course_list, $month, $year, $day);
+			$agendaitems = get_global_agenda_items($agendaitems, $day, $month, $year, $week, "day_view");
 			if (api_get_setting('allow_personal_agenda') == 'true') {
-				$agendaitems = get_personal_agenda_items(api_get_user_id(), $agendaitems, $day, $month, $year, $week, "day_view");				
+				$agendaitems = get_personal_agenda_items(api_get_user_id(), $agendaitems, $day, $month, $year, $week, "day_view");
 			}
 			display_daycalendar($agendaitems, $day, $month, $year, array(), $monthName);
 			break;
@@ -250,4 +250,4 @@ if (isset($_user['user_id'])) {
 if ($process != 'month_view') {
     echo '</td></tr></table>';
 }
-Display :: display_footer();
+Display :: display_footer();

+ 62 - 62
main/course_description/course_description.class.php

@@ -3,42 +3,42 @@
 namespace CourseDescription;
 
 /**
- * Object Model for the "Course Description" database table. Allows to 
- * 
+ * Object Model for the "Course Description" database table. Allows to
+ *
  *      - query database
  *      - create/insert new course descriptions
  *      - update/edit course descriptions
  *      - delete course descriptions
- * 
- * Course descriptions used to provide descriptions for course/sessions. 
+ *
+ * Course descriptions used to provide descriptions for course/sessions.
  * A course/session can have several descriptions associated to it from various types.
  * Course descriptions are primarily made primarily of
- * 
+ *
  *      - a title
  *      - some content
  *      - a type (for ex: info, objectives, etc)
- * 
+ *
  * Usage:
- *      
+ *
  *      Create
- * 
+ *
  *      $des = new CourseDescription();
  *      $des->set_title('...');
  *      $des->set_content('...');
  *      $des->set_description_type(...);
  *      $des->insert();
- * 
+ *
  *      Update
- * 
+ *
  *      $des = CourseDescription::get_by_id(..., ...);
  *      $des->set_title('...');
  *      $des->update();
- * 
+ *
  *      Delete
- * 
+ *
  *      $des = CourseDescription::get_by_id(..., ...);
  *      $des->delete();
- * 
+ *
  * @package chamilo.course_description
  * @author Christian Fasanando <christian1827@gmail.com>
  * @author Laurent Opprecht <laurent@opprecht.info> for the University of Geneva
@@ -49,8 +49,8 @@ class CourseDescription
 
     /**
      * Return the repository.
-     * 
-     * @return \CourseDescription\CourseDescriptionRepository 
+     *
+     * @return \CourseDescription\CourseDescriptionRepository
      */
     public static function repository()
     {
@@ -59,7 +59,7 @@ class CourseDescription
 
     /**
      * Returns the list of all available types
-     * 
+     *
      * @return array
      */
     public static function get_types()
@@ -69,7 +69,7 @@ class CourseDescription
 
 //    /**
 //     * Deprecated (still used by web services)
-//     * 
+//     *
 //     * @param int Course id
 //     * @deprecated use get_descriptions_by_course
 //     * @return array Array of CourseDescriptions
@@ -153,7 +153,7 @@ class CourseDescription
 
 //    /**
 //     * Insert the course description object into the course_description table.
-//     * 
+//     *
 //     * @return bool True on success, false on failure
 //     */
 //    public function insert()
@@ -168,11 +168,11 @@ class CourseDescription
 //
 //        $table = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
 //        $sql = "INSERT IGNORE INTO $table SET
-//				c_id 				= $course_id, 
-//				description_type	= $description_type, 
-//				title 				= '$title', 
-//				content 			= '$content', 
-//				progress 			= $progress, 
+//				c_id 				= $course_id,
+//				description_type	= $description_type,
+//				title 				= '$title',
+//				content 			= '$content',
+//				progress 			= $progress,
 //				session_id          = $session_id";
 //
 //        Database::query($sql);
@@ -184,7 +184,7 @@ class CourseDescription
 //        $this->id = $id;
 //
 //        /**
-//         * @todo: course info should come from c_id 
+//         * @todo: course info should come from c_id
 //         */
 //        api_item_property_update(api_get_course_info(), TOOL_COURSE_DESCRIPTION, $id, 'CourseDescriptionAdded', api_get_user_id());
 //
@@ -192,13 +192,13 @@ class CourseDescription
 //    }
 //    /**
 //     * Insert a row like history inside track_e_item_property table
-//     * 
+//     *
 //     * @param 	int 	description type
 //     * @return  int		affected rows
 //     */
 //    public function insert_stats($description_type)
 //    {
-//        $tbl_stats_item_property = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
+//        $tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
 //        $description_id = $this->get_id_by_description_type($description_type);
 //        $course_id = api_get_real_course_id();
 //        $course_code = api_get_course_id();
@@ -219,7 +219,7 @@ class CourseDescription
 //    }
 //    /**
 //     * Update a course description object to the database.
-//     * 
+//     *
 //     * @return bool True on success, false on failure.
 //     */
 //    public function update()
@@ -234,11 +234,11 @@ class CourseDescription
 //        $session_id = $this->get_session_id();
 //
 //        $table = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
-//        $sql = "UPDATE $table SET  
-//						title       = '$title', 
-//						content     = '$content', 
-//						progress    = $progress 
-//				WHERE 	id          = $id AND 
+//        $sql = "UPDATE $table SET
+//						title       = '$title',
+//						content     = '$content',
+//						progress    = $progress
+//				WHERE 	id          = $id AND
 //						c_id = $course_id ";
 //
 //        Database::query($sql);
@@ -247,7 +247,7 @@ class CourseDescription
 //        if ($result) {
 //            //insert into item_property
 //            /**
-//             * @todo: course info should come from c_id 
+//             * @todo: course info should come from c_id
 //             */
 //            api_item_property_update(api_get_course_info(), TOOL_COURSE_DESCRIPTION, $this->id, 'CourseDescriptionUpdated', api_get_user_id());
 //        }
@@ -255,7 +255,7 @@ class CourseDescription
 //    }
 //    /**
 //     * Delete a course description object from the database.
-//     * 
+//     *
 //     * @return bool True on success false on failure
 //     */
 //    public function delete()
@@ -269,7 +269,7 @@ class CourseDescription
 //        $result = (bool) Database::affected_rows();
 //        if ($result) {
 //            /**
-//             * @todo: should get course info from $this->c_id 
+//             * @todo: should get course info from $this->c_id
 //             */
 //            api_item_property_update(api_get_course_info(), TOOL_COURSE_DESCRIPTION, $this->id, 'CourseDescriptionDeleted', api_get_user_id());
 //        }
@@ -341,8 +341,8 @@ class CourseDescription
 //    }
 
     /**
-     * The course id. 
-     * 
+     * The course id.
+     *
      * @see get_course() property to get access to the course object
      * @return int
      */
@@ -361,7 +361,7 @@ class CourseDescription
 
     /**
      * The id of the object.
-     * 
+     *
      * @return int
      */
     public function get_id()
@@ -370,7 +370,7 @@ class CourseDescription
     }
 
     /**
-     * 
+     *
      * @return void
      */
     public function set_id($value)
@@ -380,7 +380,7 @@ class CourseDescription
 
     /**
      * The title of the course description.
-     * 
+     *
      * @return string
      */
     public function get_title()
@@ -389,7 +389,7 @@ class CourseDescription
     }
 
     /**
-     * 
+     *
      * @return void
      */
     public function set_title($title)
@@ -407,7 +407,7 @@ class CourseDescription
     }
 
     /**
-     * 
+     *
      * @return void
      */
     public function set_content($content)
@@ -417,7 +417,7 @@ class CourseDescription
 
     /**
      * The session id the object is associated with.
-     * 
+     *
      * @return int
      */
     public function get_session_id()
@@ -426,7 +426,7 @@ class CourseDescription
     }
 
     /**
-     * 
+     *
      * @return void
      */
     public function set_session_id($value)
@@ -437,7 +437,7 @@ class CourseDescription
     /**
      * The type of the course description. Should match one of the id returns
      * by CourseDescription::get_types().
-     * 
+     *
      * @return int
      */
     public function get_description_type()
@@ -446,7 +446,7 @@ class CourseDescription
     }
 
     /**
-     * 
+     *
      * @return void
      */
     public function set_description_type($value)
@@ -464,7 +464,7 @@ class CourseDescription
     }
 
     /**
-     * 
+     *
      * @return void
      */
     public function set_progress($value)
@@ -474,8 +474,8 @@ class CourseDescription
 
     /**
      * Return one type from its id
-     * 
-     * @return \CourseDescription\CourseDescriptionType 
+     *
+     * @return \CourseDescription\CourseDescriptionType
      */
     public function get_type()
     {
@@ -504,7 +504,7 @@ class CourseDescription
 
     /**
      * The item property this object is associated with.
-     * 
+     *
      * @return \Model\ItemProperty
      */
     public function get_item_property()
@@ -521,12 +521,12 @@ class CourseDescription
 
 //
 ///**
-// * The common routes (urls) for course description objects: 
-// * 
+// * The common routes (urls) for course description objects:
+// *
 // *      - create new course description
 // *      - edit course description
-// *      - delete course description 
-// * 
+// *      - delete course description
+// *
 // * @author Laurent Opprecht <laurent@opprecht.info> for the University of Geneva
 // * @licence /license.txt
 // */
@@ -535,7 +535,7 @@ class CourseDescription
 //
 //    /**
 //     *
-//     * @return CourseDescriptionRoutes 
+//     * @return CourseDescriptionRoutes
 //     */
 //    public static function instance()
 //    {
@@ -553,7 +553,7 @@ class CourseDescription
 //
 //    /**
 //     * Returns the url used to create a new course description from a specific type.
-//     * 
+//     *
 //     * @param CourseDescriptionType $type
 //     * @param bool $html True to html escape the url, false otherwise.
 //     * @return string
@@ -573,10 +573,10 @@ class CourseDescription
 //
 //    /**
 //     * The url to edit a course description object
-//     * 
+//     *
 //     * @param CourseDescription $description
 //     * @param bool $html True to html escape the url, false otherwise.
-//     * @return string  
+//     * @return string
 //     */
 //    function edit($description, $html = true)
 //    {
@@ -592,9 +592,9 @@ class CourseDescription
 //
 //    /**
 //     * The index route to list all course descriptions for the current course/session
-//     * 
+//     *
 //     * @param bool $html True to html escape the url, false otherwise.
-//     * @return type 
+//     * @return type
 //     */
 //    function index($html = true)
 //    {
@@ -605,10 +605,10 @@ class CourseDescription
 //
 //    /**
 //     * Url to delete a course description object.
-//     * 
+//     *
 //     * @param CourseDescription $description
 //     * @param bool $html True to html escape the url, false otherwise.
-//     * @return string  
+//     * @return string
 //     */
 //    function delete($description, $html = true)
 //    {

+ 3 - 2
main/course_progress/index.php

@@ -60,9 +60,10 @@ if (isset($_GET['thematic_id'])) {
 if (isset($_GET['description_type'])) {
 	$description_type = intval($_GET['description_type']);
 }
+$courseInfo = api_get_course_info();
 
 // instance thematic object for using like library here
-$thematic = new Thematic();
+$thematic = new Thematic($courseInfo);
 
 // thematic controller object
 $thematic_controller = new ThematicController();
@@ -328,4 +329,4 @@ switch ($action) {
     case 'thematic_advance_list'    :
         $thematic_controller->thematic_advance($action);
         break;
-}
+}

+ 19 - 10
main/course_progress/thematic_controller.php

@@ -15,14 +15,17 @@
 /**
  * Thematic Controller script. Prepares the common background variables to give to the scripts corresponding to
  * the requested action
+ * @todo use a proper controller in src/ChamiloLMS
  * @package chamilo.course_progress
  */
-class ThematicController {
+class ThematicController
+{
 
     /**
      * Constructor
      */
-    public function __construct() {
+    public function __construct()
+    {
         $this->toolname = 'course_progress';
         $this->view = new View($this->toolname);
     }
@@ -32,8 +35,10 @@ class ThematicController {
      * @param 	string	Action
      * render to thematic.php
      */
-    public function thematic($action) {
-        $thematic = new Thematic();
+    public function thematic($action)
+    {
+        $courseInfo = api_get_course_info();
+        $thematic = new Thematic($courseInfo);
         $data = array();
         $error = false;
 
@@ -222,7 +227,7 @@ class ThematicController {
                 }
                 $data['total_average_of_advances'] = $thematic->get_average_of_advances_by_thematic($thematic_id);
             } else {
-                $thematic_data = $thematic->get_thematic_list(null, api_get_course_id(), api_get_session_id());
+                $thematic_data = $thematic->get_thematic_list(null, null, api_get_session_id());
                 $data['max_thematic_item'] = $thematic->get_max_thematic_item();
                 $data['last_done_thematic_advance'] = $thematic->get_last_done_thematic_advance();
                 $data['total_average_of_advances'] = $thematic->get_total_average_of_thematic_advances();
@@ -258,8 +263,10 @@ class ThematicController {
      * @param 	string	Action
      * render to thematic_plan.php
      */
-    public function thematic_plan($action) {
-        $thematic = new Thematic();
+    public function thematic_plan($action)
+    {
+        $courseInfo = api_get_course_info();
+        $thematic = new Thematic($courseInfo);
 
         $data = array();
         $error = false;
@@ -361,8 +368,10 @@ class ThematicController {
      * @param 	string	Action
      * render to thematic_advance.php
      */
-    public function thematic_advance($action) {
-        $thematic = new Thematic();
+    public function thematic_advance($action)
+    {
+        $courseInfo = api_get_course_info();
+        $thematic = new Thematic($courseInfo);
         $attendance = new Attendance();
         $data = array();
 
@@ -475,4 +484,4 @@ class ThematicController {
         $this->view->render();
     }
 
-}
+}

+ 6 - 3
main/coursecopy/classes/CourseBuilder.class.php

@@ -925,7 +925,7 @@ class CourseBuilder
 	function build_session_course(){
 		$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
 		$tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-		$list_course = Database::get_course_list();
+		$list_course = CourseManager::get_course_list();
 		$list = array();
 		foreach($list_course as $_course) {
 			$this->course = new Course();
@@ -977,7 +977,8 @@ class CourseBuilder
 	/**
 	* Build the Surveys
 	*/
-	function build_thematic($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array()) {
+	function build_thematic($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array())
+    {
 		$table_thematic			= Database :: get_course_table(TABLE_THEMATIC);
 		$table_thematic_advance = Database :: get_course_table(TABLE_THEMATIC_ADVANCE);
 		$table_thematic_plan    = Database :: get_course_table(TABLE_THEMATIC_PLAN);
@@ -991,10 +992,12 @@ class CourseBuilder
 
 		$course_id = api_get_course_int_id();
 
+        $courseInfo = api_get_course_info();
+
 		$sql = "SELECT * FROM $table_thematic WHERE c_id = $course_id $session_condition ";
 		$db_result = Database::query($sql);
 		while ($row = Database::fetch_array($db_result,'ASSOC')) {
-			$thematic = new Thematic($row);
+			$thematic = new Thematic($courseInfo);
 			$sql = 'SELECT * FROM '.$table_thematic_advance.' WHERE c_id = '.$course_id.' AND thematic_id = '.$row['id'];
 
 			$result = Database::query($sql);

+ 1 - 1
main/coursecopy/classes/CourseRestorer.class.php

@@ -2447,7 +2447,7 @@ class CourseRestorer
                     $glossary->description
                 )."', display_order='".self::DBUTF8escapestring($glossary->display_order)."' $condition_session ";
                 Database::query($sql);
-                $my_id = Database::get_last_insert_id();
+                $my_id = Database::insert_id();
                 api_item_property_update(
                     $this->destination_course_info,
                     TOOL_GLOSSARY,

+ 1 - 1
main/coursecopy/classes/DummyCourseCreator.class.php

@@ -48,7 +48,7 @@ class DummyCourseCreator
 		$this->default_property['start_visible'] = '0000-00-00 00:00:00';
 		$this->default_property['end_visible'] =  '0000-00-00 00:00:00';
 
-		$course = Database::get_course_info($course_code);
+		$course = api_get_course_info($course_code);
 		$this->course = new Course();
 		$tmp_path = api_get_path(SYS_COURSE_PATH).$course['directory'].'/document/tmp_'.uniqid('');
 		@mkdir($tmp_path, api_get_permissions_for_new_directories(), true);

+ 2 - 2
main/dropbox/dropbox_functions.inc.php

@@ -1363,7 +1363,7 @@ function get_last_tool_access($tool, $courseId = '', $user_id = '')
     }
 
     // the table where the last tool access is stored (=track_e_lastaccess)
-    $table_last_access = Database::get_statistic_table('track_e_lastaccess');
+    $table_last_access = Database::get_main_table('track_e_lastaccess');
 
     $sql = "SELECT access_date FROM $table_last_access WHERE access_user_id='".Database::escape_string($user_id)."'
 				AND c_id ='".Database::escape_string($courseId)."'
@@ -1374,4 +1374,4 @@ function get_last_tool_access($tool, $courseId = '', $user_id = '')
     $row = Database::fetch_array($result);
 
     return $row['access_date'];
-}
+}

+ 1 - 1
main/dropbox/dropbox_init.inc.php

@@ -64,7 +64,7 @@ require_once api_get_path(SYS_CODE_PATH).'document/document.inc.php';  // we use
 $user_id = api_get_user_id();
 $course_code = api_get_course_id();
 $courseId = api_get_course_int_id();
-$course_info = Database::get_course_info($course_code);
+$course_info = api_get_course_info($course_code);
 
 $session_id = api_get_session_id();
 if (empty($session_id)) {

+ 11 - 12
main/exercice/admin.php

@@ -84,9 +84,7 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
     }
 }
 
-
-
-// get vars from GET
+// Get vars from GET
 if (empty($exerciseId)) {
     $exerciseId = isset($_GET['exerciseId'])?intval($_GET['exerciseId']):'0';
 }
@@ -105,14 +103,15 @@ if (empty($modifyQuestion)) {
 if (empty($deleteQuestion)) {
     $deleteQuestion = isset($_GET['deleteQuestion'])?$_GET['deleteQuestion']:0;
 }
-if (empty($clone_question)) {
-    $clone_question = isset($_GET['clone_question'])?$_GET['clone_question']:0;
-}
+
+$clone_question = isset($_REQUEST['clone_question']) ? $_REQUEST['clone_question']:0;
+
 if (empty($questionId)) {
     $questionId = isset($_SESSION['questionId'])?$_SESSION['questionId']:0;
 }
 
-// Cleaning all incomplete attempts of the admin/teacher to avoid weird problems when changing the exercise settings, number of questions, etc
+/* Cleaning all incomplete attempts of the admin/teacher to avoid weird problems
+    when changing the exercise settings, number of questions, etc */
 
 delete_all_incomplete_attempts(api_get_user_id(), $exerciseId, api_get_course_int_id(), api_get_session_id());
 
@@ -121,7 +120,7 @@ $objExercise = isset($_SESSION['objExercise']) ? $_SESSION['objExercise'] : 0;
 /** @var Question $objQuestion */
 $objQuestion = isset($_SESSION['objQuestion']) ? $_SESSION['objQuestion'] : 0;
 /** @var Answer $objAnswer */
-$objAnswer = isset($_SESSION['objAnswer'])?$_SESSION['objAnswer']:0;
+$objAnswer = isset($_SESSION['objAnswer']) ? $_SESSION['objAnswer'] : 0;
 
 // document path
 $documentPath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
@@ -172,10 +171,9 @@ if (!empty($_GET['action']) && $_GET['action'] == 'exportqti2' && !empty($_GET['
 if (!is_object($objExercise)) {
     // construction of the Exercise object
     $objExercise = new Exercise();
-
     // creation of a new exercise if wrong or not specified exercise ID
     if ($exerciseId) {
-        $objExercise->read($exerciseId, false);
+        $objExercise->read($exerciseId, true);
     }
     // saves the object into the session
     Session::write('objExercise', $objExercise);
@@ -236,14 +234,15 @@ if (!empty($cancelQuestion)) {
     }
 }
 
+
 if (!empty($clone_question) && !empty($objExercise->id)) {
-    $old_question_obj = Question::read($clone_question, api_get_course_int_id());
 
+    $old_question_obj = Question::read($clone_question, api_get_course_int_id());
     $old_question_obj->question = $old_question_obj->question.' - '.get_lang('Copy');
 
     $new_id = $old_question_obj->duplicate();
     $new_question_obj = Question::read($new_id, api_get_course_int_id());
-    $new_question_obj->addToList($exerciseId);
+    $new_question_obj->addToList($objExercise->id);
 
     // This should be moved to the duplicate function
     $new_answer_obj = new Answer($clone_question, null, $objExercise);

+ 5 - 1
main/exercice/exercice.php

@@ -48,7 +48,7 @@ $TBL_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
 $TBL_ITEM_PROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
 $TBL_EXERCICE_QUESTION = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
 $TBL_EXERCICES = Database :: get_course_table(TABLE_QUIZ_TEST);
-$TBL_TRACK_EXERCICES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+$TBL_TRACK_EXERCICES = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
 
 // document path
 $documentPath = api_get_path(SYS_COURSE_PATH).$_course['path']."/document";
@@ -1022,3 +1022,7 @@ if (empty($exercise_list) && $hotpotatoes_exist == false) {
 if ($origin != 'learnpath') { //so we are not in learnpath tool
     Display :: display_footer();
 }
+
+Session::erase('objExercise', $objExercise);
+Session::erase('objQuestion', $objQuestion);
+Session::erase('objAnswer', $objAnswer);

+ 46 - 12
main/exercice/exercise.class.php

@@ -2183,8 +2183,8 @@ class Exercise
      */
     public function clean_results()
     {
-        $table_track_e_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-        $table_track_e_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+        $table_track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $table_track_e_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 
         $sql = "SELECT exe_id FROM $table_track_e_exercises
 					   WHERE 	c_id = '".api_get_course_int_id()."' AND
@@ -2464,7 +2464,7 @@ class Exercise
         $lp_item_view_id = 0,
         $status = 'incomplete'
     ) {
-        $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
         if (empty($lp_id)) {
             $lp_id = 0;
         }
@@ -2511,7 +2511,7 @@ class Exercise
         $questionList = array(),
         $weight = 0
     ) {
-        $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
         $safe_lp_id = intval($safe_lp_id);
         $safe_lp_item_id = intval($safe_lp_item_id);
         $safe_lp_item_view_id = intval($safe_lp_item_view_id);
@@ -2890,7 +2890,7 @@ class Exercise
 
         $questionId = intval($questionId);
         $exeId = intval($exeId);
-        $TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+        $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
         $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
 
         // Creates a temporary Question object
@@ -3502,7 +3502,7 @@ class Exercise
                 case HOT_SPOT :
                     if ($from_database) {
                         if ($show_result) {
-                            $TBL_TRACK_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
+                            $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
                             $query = "SELECT hotspot_correct
                                      FROM ".$TBL_TRACK_HOTSPOT."
                                      WHERE  hotspot_exe_id = '".$exeId."' and
@@ -3544,7 +3544,7 @@ class Exercise
                 case HOT_SPOT_DELINEATION :
                     if ($from_database) {
                         // getting the user answer
-                        $TBL_TRACK_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
+                        $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
                         $query = "SELECT hotspot_correct, hotspot_coordinate
                                   FROM ".$TBL_TRACK_HOTSPOT."
                                   WHERE hotspot_exe_id = '".$exeId."' AND
@@ -4406,7 +4406,7 @@ class Exercise
         }
 
         if ($saved_results) {
-            $stat_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+            $stat_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
             $sql_update = 'UPDATE '.$stat_table.' SET exe_result = exe_result + '.floatval($questionScore).' WHERE exe_id = '.$exeId;
             if ($debug) {
                 error_log($sql_update);
@@ -4975,6 +4975,8 @@ class Exercise
 
     /**
      * Returns an array with this form
+     * @example
+     * <code>
      * array (size=3)
           999 =>
             array (size=3)
@@ -4988,6 +4990,7 @@ class Exercise
           101 =>
             array (size=1)
               0 => int 3482
+     * </code>
      * The array inside the key 999 means the question list that belongs to the media id = 999,
      * this case is special because 999 means "no media".
      * @return array
@@ -4998,7 +5001,7 @@ class Exercise
     }
 
     /**
-      *Is media question activated
+     * Is media question activated
      * @return bool
      */
     public function mediaIsActivated()
@@ -5023,25 +5026,56 @@ class Exercise
     /**
      * Gets question list from the exercise
      * (true show all questions, false show media question id instead of the question ids)
+     * @return array
      */
     public function getQuestionList()
     {
         return $this->questionList;
     }
 
+    /**
+     * Question list with medias compressed like this
+     * @example
+     * <code>
+     * array(
+     *      question_id,
+     *      question_id,
+     *      media_id, <- this media id contains question ids
+     *      question_id,
+     * )
+     * </code>
+     * @return array
+     */
     public function getQuestionListWithMediasCompressed()
     {
         return $this->questionList;
     }
 
+    /**
+     * Question list with medias uncompressed like this
+     * @example
+     * <code>
+     * array(
+     *      question_id,
+     *      question_id,
+     *      question_id, <- belongs to a media id
+     *      question_id, <- belongs to a media id
+     *      question_id,
+     * )
+     * </code>
+     * @return array
+     */
     public function getQuestionListWithMediasUncompressed()
     {
         return $this->questionListUncompressed;
     }
 
+    /**
+     * Sets the question list when the exercise->read() is executed created depending of a parameter
+     */
     public function setQuestionList()
     {
-        //Getting question list
+        // Getting question list.
         $questionList = $this->selectQuestionList(true);
         $this->setMediaList($questionList);
 
@@ -5104,7 +5138,7 @@ class Exercise
      */
     public function getStatTrackExerciseInfoByExeId($exe_id)
     {
-        $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
         $exe_id = intval($exe_id);
         $sql_track = "SELECT * FROM $track_exercises WHERE exe_id = $exe_id ";
         $result = Database::query($sql_track);
@@ -5144,7 +5178,7 @@ class Exercise
         $exercise_info = self::getStatTrackExerciseInfoByExeId($exe_id);
         $question_id = intval($question_id);
         $exe_id = intval($exe_id);
-        $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
         if ($exercise_info) {
 
             if (empty($exercise_info['questions_to_check'])) {

+ 2 - 2
main/exercice/exercise_history.php

@@ -41,8 +41,8 @@ $interbreadcrumb[]= array ('url' => 'exercise_history.php'.'?exe_id='.intval($_G
 $TBL_USER          	    = Database::get_main_table(TABLE_MAIN_USER);
 $TBL_EXERCICES			= Database::get_course_table(TABLE_QUIZ_TEST);
 $TBL_EXERCICES_QUESTION	= Database::get_course_table(TABLE_QUIZ_QUESTION);
-$TBL_TRACK_EXERCICES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-$TBL_TRACK_ATTEMPT_RECORDING= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
+$TBL_TRACK_EXERCICES	= Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+$TBL_TRACK_ATTEMPT_RECORDING= Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
 Display::display_header($nameTools,get_lang('Exercise'));
 
 if (isset($_GET['message'])) {

+ 32 - 41
main/exercice/exercise_report.php

@@ -44,14 +44,15 @@ $is_allowedToEdit = api_is_allowed_to_edit(null, true) || api_is_drh();
 $is_tutor = api_is_allowed_to_edit(true);
 
 $TBL_QUESTIONS = Database :: get_course_table(TABLE_QUIZ_QUESTION);
-$TBL_TRACK_EXERCICES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-$TBL_TRACK_ATTEMPT = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-$TBL_TRACK_ATTEMPT_RECORDING = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
+$TBL_TRACK_EXERCICES = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+$TBL_TRACK_ATTEMPT = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+$TBL_TRACK_ATTEMPT_RECORDING = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
 $TBL_LP_ITEM_VIEW = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
 
 $course_id = api_get_course_int_id();
 $exercise_id = isset($_REQUEST['exerciseId']) ? intval($_REQUEST['exerciseId']) : null;
 $filter_user = isset($_REQUEST['filter_by_user']) ? intval($_REQUEST['filter_by_user']) : null;
+$gradebook = isset($_REQUEST['gradebook']) ? Security::remove_XSS($_REQUEST['gradebook']) : null;
 
 $locked = api_resource_is_locked_by_gradebook($exercise_id, LINK_EXERCISE);
 
@@ -63,6 +64,7 @@ if (!$is_allowedToEdit) {
     api_not_allowed(true);
 }
 
+// @todo check if the $parameters is used
 if (!empty($exercise_id)) {
     $parameters['exerciseId'] = $exercise_id;
 }
@@ -77,10 +79,9 @@ if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') {
         if (isset($_REQUEST['extra_data']) && $_REQUEST['extra_data'] == 1) {
             $load_extra_data = true;
         }
-
         require_once 'exercise_result.class.php';
         switch ($_GET['export_format']) {
-            case 'xls' :
+            case 'xls':
                 $export = new ExerciseResult();
                 $export->exportCompleteReportXLS(
                     $documentPath,
@@ -92,8 +93,8 @@ if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') {
                 );
                 exit;
                 break;
-            case 'csv' :
-            default :
+            case 'csv':
+            default:
                 $export = new ExerciseResult();
                 $export->exportCompleteReportCSV(
                     $documentPath,
@@ -112,10 +113,7 @@ if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') {
 }
 
 //Send student email @todo move this code in a class, library
-if (isset($_REQUEST['comments']) && $_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_GET['exeid'] == strval(
-    intval($_GET['exeid'])
-)
-) {
+if (isset($_REQUEST['comments']) && $_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_GET['exeid'] == strval(intval($_GET['exeid']))) {
     $id = intval($_GET['exeid']); //filtered by post-condition
     $track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($id);
     if (empty($track_exercise_info)) {
@@ -164,26 +162,34 @@ if (isset($_REQUEST['comments']) && $_REQUEST['comments'] == 'update' && ($is_al
     }
 
     for ($i = 0; $i < $loop_in_track; $i++) {
-        $my_marks = Database::escape_string($_POST['marks_'.$array_content_id_exe[$i]]);
-        $contain_comments = Database::escape_string($_POST['comments_'.$array_content_id_exe[$i]]);
+        $my_marks = null;
+        if (isset($_POST['marks_'.$array_content_id_exe[$i]])) {
+            $my_marks = Database::escape_string($_POST['marks_'.$array_content_id_exe[$i]]);
+        }
+
+        $contain_comments = null;
+        if (isset($_POST['comments_'.$array_content_id_exe[$i]])) {
+            $contain_comments = Database::escape_string($_POST['comments_'.$array_content_id_exe[$i]]);
+        }
+
         if (isset($contain_comments)) {
             $my_comments = Database::escape_string($_POST['comments_'.$array_content_id_exe[$i]]);
         } else {
             $my_comments = '';
         }
         $my_questionid = intval($array_content_id_exe[$i]);
-        $sql = "SELECT question from $TBL_QUESTIONS WHERE c_id = $course_id AND id = '$my_questionid'";
+        $sql = "SELECT question from $TBL_QUESTIONS WHERE c_id = $course_id AND iid = '$my_questionid'";
 
         $result = Database::query($sql);
         Database::result($result, 0, "question");
 
-        $query = "UPDATE $TBL_TRACK_ATTEMPT SET marks = '$my_marks', teacher_comment = '$my_comments' WHERE question_id = ".$my_questionid." AND exe_id=".$id;
+        $query = "UPDATE $TBL_TRACK_ATTEMPT SET marks = '$my_marks', teacher_comment = '$my_comments'
+                  WHERE question_id = ".$my_questionid." AND exe_id=".$id;
         Database::query($query);
 
         //Saving results in the track recording table
         $recording_changes = 'INSERT INTO '.$TBL_TRACK_ATTEMPT_RECORDING.' (exe_id, question_id, marks, insert_date, author, teacher_comment)
-                              VALUES ('."'$id','".$my_questionid."','$my_marks','".api_get_utc_datetime(
-        )."','".api_get_user_id()."'".',"'.$my_comments.'")';
+                              VALUES ('."'$id','".$my_questionid."','$my_marks','".api_get_utc_datetime()."','".api_get_user_id()."'".',"'.$my_comments.'")';
         Database::query($recording_changes);
     }
 
@@ -249,35 +255,20 @@ if (isset($origin) && $origin == 'learnpath') {
     if ($is_allowedToEdit) {
         // the form
         if (api_is_platform_admin() || api_is_course_admin() || api_is_course_tutor() || api_is_course_coach()) {
-            $actions .= '<a href="admin.php?exerciseId='.intval($_GET['exerciseId']).'">'.Display :: return_icon(
-                'back.png',
-                get_lang('GoBackToQuestionList'),
-                '',
-                ICON_SIZE_MEDIUM
-            ).'</a>';
-            $actions .= '<a href="live_stats.php?'.api_get_cidreq().'&exerciseId='.$exercise_id.'">'.Display :: return_icon(
-                'activity_monitor.png',
-                get_lang('LiveResults'),
-                '',
-                ICON_SIZE_MEDIUM
-            ).'</a>';
-            $actions .= '<a href="stats.php?'.api_get_cidreq().'&exerciseId='.$exercise_id.'">'.Display :: return_icon(
-                'statistics.png',
-                get_lang('ReportByQuestion'),
-                '',
-                ICON_SIZE_MEDIUM
-            ).'</a>';
-            $actions .= '<a id="export_opener" href="'.api_get_self(
-            ).'?export_report=1&hotpotato_name='.Security::remove_XSS($_GET['path']).'&exerciseId='.intval(
-                $_GET['exerciseId']
-            ).'" >'.
+            // @todo check if $path is used
+            $path = isset($_GET['path']) ? Security::remove_XSS($_GET['path']) : null;
+
+            $actions .= '<a href="admin.php?exerciseId='.intval($_GET['exerciseId']).'">'.Display :: return_icon('back.png',get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).'</a>';
+            $actions .= '<a href="live_stats.php?'.api_get_cidreq().'&exerciseId='.$exercise_id.'">'.Display :: return_icon('activity_monitor.png',get_lang('LiveResults'), '', ICON_SIZE_MEDIUM ).'</a>';
+            $actions .= '<a href="stats.php?'.api_get_cidreq().'&exerciseId='.$exercise_id.'">'.Display :: return_icon('statistics.png',get_lang('ReportByQuestion'), '', ICON_SIZE_MEDIUM).'</a>';
+            $actions .= '<a id="export_opener" href="'.api_get_self().'?export_report=1&hotpotato_name='.$path.'&exerciseId='.intval($_GET['exerciseId']).'" >'.
                 Display::return_icon('save.png', get_lang('Export'), '', ICON_SIZE_MEDIUM).'</a>';
         }
     }
 }
 
 //Deleting an attempt
-if (($is_allowedToEdit || $is_tutor || api_is_coach()) && $_GET['delete'] == 'delete' && !empty ($_GET['did']) && $locked == false
+if (($is_allowedToEdit || $is_tutor || api_is_coach()) && isset($_GET['delete']) && $_GET['delete'] == 'delete' && !empty ($_GET['did']) && $locked == false
 ) {
     $exe_id = intval($_GET['did']);
     if (!empty($exe_id)) {
@@ -592,4 +583,4 @@ jQuery("#results").jqGrid('navButtonAdd','#results_pager',{
 <?php
 
 echo Display::grid_html('results');
-Display :: display_footer();
+Display :: display_footer();

+ 7 - 7
main/exercice/exercise_result.class.php

@@ -87,9 +87,9 @@ class ExerciseResult
 
     	$TBL_EXERCISES          = Database::get_course_table(TABLE_QUIZ_TEST);
 		$TBL_USER          	    = Database::get_main_table(TABLE_MAIN_USER);
-		$TBL_TRACK_EXERCISES    	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-		$TBL_TRACK_HOTPOTATOES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
-        $TBL_TRACK_ATTEMPT_RECORDING = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
+		$TBL_TRACK_EXERCISES    	= Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+		$TBL_TRACK_HOTPOTATOES	= Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
+        $TBL_TRACK_ATTEMPT_RECORDING = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
 
     	$cid             = api_get_course_id();
         $course_id       = api_get_course_int_id();
@@ -115,7 +115,7 @@ class ExerciseResult
                         steps_counter as exstep,
                         exe_user_id as excruid,
                         te.exe_duration as duration
-                FROM $TBL_EXERCISES  AS ce INNER JOIN $TBL_TRACK_EXERCISES AS te ON (te.exe_exo_id = ce.id) INNER JOIN
+                FROM $TBL_EXERCISES  AS ce INNER JOIN $TBL_TRACK_EXERCISES AS te ON (te.exe_exo_id = ce.iid) INNER JOIN
                      $TBL_USER  AS user ON (user.user_id = exe_user_id)
                 WHERE   ce.c_id = $course_id AND
                         te.status != 'incomplete' AND
@@ -150,7 +150,7 @@ class ExerciseResult
                     exe_user_id as excruid,
                     te.exe_duration as duration,
                     ce.results_disabled as exdisabled
-                        FROM $TBL_EXERCISES  AS ce INNER JOIN $TBL_TRACK_EXERCISES AS te ON (te.exe_exo_id = ce.id)
+                        FROM $TBL_EXERCISES  AS ce INNER JOIN $TBL_TRACK_EXERCISES AS te ON (te.exe_exo_id = ce.iid)
                         INNER JOIN $TBL_USER  AS user ON (user.user_id = exe_user_id)
                         WHERE   ce.c_id = $course_id AND
                                 te.status != 'incomplete' AND
@@ -438,7 +438,7 @@ class ExerciseResult
 		foreach ($this->results as $row) {
 			$column = 0;
 
-            if ($with_column_user) {               
+            if ($with_column_user) {
 
                 if (api_is_western_name_order()) {
                     $worksheet->write($line,$column,api_html_entity_decode(strip_tags($row['first_name']), ENT_QUOTES, $charset));
@@ -486,4 +486,4 @@ class ExerciseResult
 		$workbook->close();
 		return true;
 	}
-}
+}

+ 1 - 1
main/exercice/exercise_result.php

@@ -144,7 +144,7 @@ $objExercise->displayQuestionListByAttempt($exe_id, true);
 // If is not valid.
 $session_control_key = ExerciseLib::get_session_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id);
 if (isset($session_control_key) && !ExerciseLib::exercise_time_control_is_valid($objExercise->id, $learnpath_id, $learnpath_item_id)) {
-    $TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $sql_fraud = "UPDATE $TBL_TRACK_ATTEMPT SET answer = 0, marks = 0, position = 0 WHERE exe_id = $exe_id ";
     Database::query($sql_fraud);
 }

+ 2 - 2
main/exercice/exercise_show.php

@@ -39,8 +39,8 @@ if ($origin == 'learnpath') {
 // Database table definitions
 $TBL_EXERCICE_QUESTION 	= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
 $TBL_QUESTIONS         	= Database::get_course_table(TABLE_QUIZ_QUESTION);
-$TBL_TRACK_EXERCICES    = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-$TBL_TRACK_ATTEMPT		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+$TBL_TRACK_EXERCICES    = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+$TBL_TRACK_ATTEMPT		= Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 
 // General parameters passed via POST/GET
 if ($debug) { error_log('Entered exercise_show.php: '.print_r($_POST,1)); }

+ 1 - 1
main/exercice/exercise_submit.php

@@ -333,7 +333,7 @@ if (api_is_allowed_to_edit(null,true) && isset($_GET['preview']) && $_GET['previ
 }
 
 // 1. Loading the $objExercise variable
-if (!isset($_SESSION['objExercise']) || $_SESSION['objExercise']->id != $_REQUEST['exerciseId']) {
+if (!isset($_SESSION['objExercise']) || isset($_SESSION['objExercise']) && ($_SESSION['objExercise']->id != $_REQUEST['exerciseId'])) {
     // Construction of Exercise
     /** @var Exercise $objExercise */
     $objExercise = new Exercise();

+ 3 - 3
main/exercice/hotpotatoes_exercise_report.php

@@ -42,8 +42,8 @@ $is_allowedToEdit = api_is_allowed_to_edit(null, true) || api_is_drh();
 $is_tutor = api_is_allowed_to_edit(true);
 
 $TBL_QUESTIONS = Database :: get_course_table(TABLE_QUIZ_QUESTION);
-$TBL_TRACK_EXERCICES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-$TBL_TRACK_HOTPOTATOES_EXERCICES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
+$TBL_TRACK_EXERCICES = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+$TBL_TRACK_HOTPOTATOES_EXERCICES = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
 $TBL_LP_ITEM_VIEW = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
 
 $course_id = api_get_course_int_id();
@@ -488,4 +488,4 @@ $extra_params['height'] = 'auto';
 <?php
 
 echo Display::grid_html('results');
-Display :: display_footer();
+Display :: display_footer();

+ 4 - 4
main/exercice/hotpotatoes_exercise_result.class.php

@@ -66,9 +66,9 @@ class HotpotatoesExerciseResult
 
     $TBL_EXERCISES          = Database::get_course_table(TABLE_QUIZ_TEST);
     $TBL_USER          	    = Database::get_main_table(TABLE_MAIN_USER);
-    $TBL_TRACK_EXERCISES    	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-    $TBL_TRACK_HOTPOTATOES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
-    $TBL_TRACK_ATTEMPT_RECORDING = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
+    $TBL_TRACK_EXERCISES    	= Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $TBL_TRACK_HOTPOTATOES	= Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
+    $TBL_TRACK_ATTEMPT_RECORDING = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
 
     $cid             = api_get_course_id();
     $course_id       = api_get_course_int_id();
@@ -376,4 +376,4 @@ class HotpotatoesExerciseResult
 		$workbook->close();
 		return true;
 	}
-}
+}

+ 1 - 1
main/exercice/hotspot_answers.as.php

@@ -95,7 +95,7 @@ if(isset($_SESSION['exerciseResultCoordinates']) && $from_db==0) {
 	}
 } else {
 	// get it from db
-	$tbl_track_e_hotspot = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
+	$tbl_track_e_hotspot = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
 	$sql = "SELECT hotspot_coordinate
             FROM $tbl_track_e_hotspot
             WHERE   hotspot_question_id = $questionId AND

+ 1 - 1
main/exercice/hotspot_savescore.inc.php

@@ -42,7 +42,7 @@ foreach ($coords as $coord) {
 }
 $coordinates = substr($coordinates,0,-1);
 
-$TBL_TRACK_E_HOTSPOT = Database::get_statistic_table(STATISTIC_TRACK_E_HOTSPOTS);
+$TBL_TRACK_E_HOTSPOT = Database::get_main_table(STATISTIC_TRACK_E_HOTSPOTS);
 // Save into db
 $sql = "INSERT INTO $TBL_TRACK_E_HOTSPOT (user_id , course_id , quiz_id , question_id , answer_id , correct , coordinate ) VALUES (
 			'".Database::escape_string($_user['user_id'])."',

+ 1 - 1
main/exercice/hotspot_updatescore.inc.php

@@ -52,7 +52,7 @@ foreach ($coords as $coord) {
 }
 $coordinates = substr($coordinates,0,-1);
 
-$TBL_TRACK_E_HOTSPOT   = Database::get_statistic_table(STATISTIC_TRACK_E_HOTSPOTS);
+$TBL_TRACK_E_HOTSPOT   = Database::get_main_table(STATISTIC_TRACK_E_HOTSPOTS);
 
 // update db
 $update_id = $_SESSION['exerciseResult'][$questionId]['ids'][$answerId];

+ 1 - 1
main/exercice/mark_free_answer.php

@@ -87,7 +87,7 @@ if ($action == 'mark') {
 	if (!empty($_POST['score']) AND $_POST['score'] < $obj_question->selectWeighting() AND $_POST['score'] >= 0) {
 		//mark the user mark into the database using something similar to the following function:
 
-		$exercise_table = Database::get_statistic_table('track_e_exercices');
+		$exercise_table = Database::get_main_table('track_e_exercices');
 		#global $origin, $tbl_learnpath_user, $learnpath_id, $learnpath_item_id;
 		$sql = "SELECT * FROM $exercise_table
 			    WHERE   exe_user_id = '".Database::escape_string($my_usr)."' AND

+ 4 - 2
main/exercice/question.class.php

@@ -1046,12 +1046,14 @@ abstract class Question
         $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
         $id                    = $this->id;
         // checks if the exercise ID is not in the list
+
         if (!in_array($exerciseId, $this->exerciseList)) {
             $this->exerciseList[] = $exerciseId;
-            $new_exercise         = new Exercise();
+            $new_exercise = new Exercise();
             $new_exercise->read($exerciseId);
             $count = $new_exercise->selectNbrQuestions();
             $count++;
+
             $sql = "INSERT INTO $TBL_EXERCICE_QUESTION (c_id, question_id, exercice_id, question_order) VALUES
 				 ({$this->course['real_id']}, '".Database::escape_string($id)."','".Database::escape_string($exerciseId)."', '$count' )";
             Database::query($sql);
@@ -1840,7 +1842,7 @@ abstract class Question
                 VALUES ($course_id, '".Database::escape_string($question_name)."', '$max_score', $max_position, $type, $level)";
         Database::query($sql);
         // Get the question ID
-        $question_id = Database::get_last_insert_id();
+        $question_id = Database::insert_id();
 
         // Get the max question_order
         $sql = "SELECT max(question_order) as max_order FROM $tbl_quiz_rel_question

+ 5 - 3
main/exercice/question_list_admin.inc.php

@@ -109,6 +109,7 @@ echo Question::getMediaLabels();
 
 // If we are in a test.
 $inATest = isset($exerciseId) && $exerciseId > 0;
+
 if (!$inATest) {
 	echo "<p class='warning-message'>".get_lang("ChoiceQuestionType")."</p>";
 } else {
@@ -123,11 +124,12 @@ if (!$inATest) {
     echo "<div style='clear:both'>&nbsp;</div>";
 
     echo '<div id="question_list">';
+
     if ($nbrQuestions) {
         // Always getting list from DB.
 
         $objExercise->setCategoriesGrouping(false);
-        $questionList = $objExercise->selectQuestionList(true);
+        $questionList = $objExercise->getQuestionList();
 
         // Style for columns.
         $styleQuestion = "width:50%; float:left;";
@@ -139,8 +141,8 @@ if (!$inATest) {
         $category_list = Testcategory::getListOfCategoriesNameForTest($objExercise->id, false);
 
         if (is_array($questionList)) {
-			foreach ($questionList as $id) {
-				// To avoid warning messages
+            foreach ($questionList as $id) {
+				// To avoid warning messages.
 				if (!is_numeric($id)) {
 					continue;
 				}

+ 2 - 2
main/exercice/question_list_pagination_admin.inc.php

@@ -88,12 +88,12 @@ $courseCode = api_get_course_id();
 
 $delete_link = null;
 if ($objExercise->edit_exercise_in_lp == true) {
-    $delete_link = '&nbsp;<a onclick="javascript:if(!confirm('."\'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES))."\'".')) return false;"  href="?cidReq='.$courseCode.'&sec_token='.$token.'&deleteQuestion=\'+options.rowId+\'">'.Display::return_icon( 'delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
+    $delete_link = '&nbsp;<a onclick="javascript:if(!confirm('."\'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES))."\'".')) return false;" href="?exerciseId='.$exerciseId.'&cidReq='.$courseCode.'&sec_token='.$token.'&deleteQuestion=\'+options.rowId+\'">'.Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
 }
 //With this function we can add actions to the jgrid (edit, delete, etc)
 $action_links = 'function action_formatter(cellvalue, options, rowObject) {
     return \'<a href="?exerciseId='.$exerciseId.'&myid=1&cidReq='.$courseCode.'&editQuestion=\'+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="?cidReq='.$courseCode.'&sec_token='.$token.'&clone_question=\'+options.rowId+\'">'.Display::return_icon('cd.gif',get_lang('Copy'), '',ICON_SIZE_SMALL).'</a>'.
+    '&nbsp;<a onclick="javascript:if(!confirm('."\'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES))."\'".')) return false;" href="?cidReq='.$courseCode.'&sec_token='.$token.'&clone_question=\'+options.rowId+\'">'.Display::return_icon('cd.gif', get_lang('Copy'), '',ICON_SIZE_SMALL).'</a>'.
     $delete_link.'\';
 }';
 ?>

+ 2 - 2
main/exercice/savescores.php

@@ -35,7 +35,7 @@ $full_file_path = $documentPath.$test;
 
 FileManager::my_delete($full_file_path.$_user['user_id'].".t.html");
 
-$TABLETRACK_HOTPOTATOES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
+$TABLETRACK_HOTPOTATOES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
 $tbl_learnpath_user = Database::get_course_table(TABLE_LEARNPATH_USER);
 $TABLE_LP_ITEM_VIEW = Database::get_course_table(TABLE_LP_ITEM_VIEW);
 
@@ -102,4 +102,4 @@ if ($origin != 'learnpath') {
     Display::display_reduced_header();
     Display::display_confirmation_message(get_lang('HotPotatoesFinished'));
     Display::display_footer();
-}
+}

+ 18 - 16
main/exercice/testcategory.class.php

@@ -126,14 +126,14 @@ class Testcategory
             $category->setDescription($this->description);
 
             if (!empty($parent_id)) {
-                $parent = $app['orm.em']->find('\Entity\CQuizCategory', $parent_id);
+                $parent = $app['orm.ems']['db_write']->find('\Entity\CQuizCategory', $parent_id);
                 if ($parent) {
                     $category->setParent($parent);
                 }
             }
             $category->setCId($course_id);
-            $app['orm.em']->persist($category);
-            $app['orm.em']->flush();
+            $app['orm.ems']['db_write']->persist($category);
+            $app['orm.ems']['db_write']->flush();
 
             if ($category->getIid()) {
                 return $category->getIid();
@@ -152,7 +152,7 @@ class Testcategory
     {
         // @todo inject the app in the class
         global $app;
-        $category = $app['orm.em']->find('\Entity\CQuizCategory', $this->id);
+        $category = $app['orm.ems']['db_write']->find('\Entity\CQuizCategory', $this->id);
         if (!$category) {
             return false;
         }
@@ -171,7 +171,7 @@ class Testcategory
                 if ($this->id == $parentId) {
                     continue;
                 }
-                $parent = $app['orm.em']->find('\Entity\CQuizCategory', $parentId);
+                $parent = $app['orm.ems']['db_write']->find('\Entity\CQuizCategory', $parentId);
                 if ($parent) {
                     $category->setParent($parent);
                 }
@@ -181,8 +181,8 @@ class Testcategory
             $category->setParent(null);
         }
 
-        $app['orm.em']->persist($category);
-        $app['orm.em']->flush();
+        $app['orm.ems']['db_write']->persist($category);
+        $app['orm.ems']['db_write']->flush();
 
         if ($category->getIid()) {
             return $category->getIid();
@@ -200,7 +200,7 @@ class Testcategory
     public function removeCategory()
     {
         global $app;
-        $category = $app['orm.em']->find('\Entity\CQuizCategory', $this->id);
+        $category = $app['orm.ems']['db_write']->find('\Entity\CQuizCategory', $this->id);
         if (!$category) {
             return false;
         }
@@ -212,9 +212,10 @@ class Testcategory
             return false;
         }
 
-        $repo = $app['orm.em']->getRepository('Entity\CQuizCategory');
+        $repo = $app['orm.ems']['db_write']->getRepository('Entity\CQuizCategory');
         $repo->removeFromTree($category);
-        $app['orm.em']->clear(); // clear cached nodes
+        // clear cached nodes
+        $app['orm.ems']['db_write']->clear();
         return true;
     }
 
@@ -502,11 +503,11 @@ class Testcategory
         return $categories_in_exercise;*/
     }
 
-    public static function getListOfCategoriesIDForTestObject($exercise_obj)
+    public static function getListOfCategoriesIDForTestObject(Exercise $exercise_obj)
     {
         // parcourir les questions d'un test, recup les categories uniques dans un tableau
         $categories_in_exercise = array();
-        $question_list = $exercise_obj->selectQuestionList();
+        $question_list = $exercise_obj->getQuestionList();
 
         // the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ???
         foreach ($question_list as $question_id) {
@@ -554,7 +555,7 @@ class Testcategory
      * @param Exercise $exercise_obj
      * @return array
      */
-    public static function getListOfCategoriesForTest($exercise_obj) {
+    public static function getListOfCategoriesForTest(Exercise $exercise_obj) {
         $result = array();
         $categories = self::getListOfCategoriesIDForTestObject($exercise_obj);
         foreach ($categories as $cat_id) {
@@ -583,11 +584,12 @@ class Testcategory
 	 * return : integer
 	 * hubert.borderiou 07-04-2011
 	 */
-	public static function getNumberOfQuestionsInCategoryForTest($exercise_id, $category_id) {
+	public static function getNumberOfQuestionsInCategoryForTest($exercise_id, $category_id)
+    {
 		$number_questions_in_category = 0;
 		$exercise = new Exercise();
 		$exercise->read($exercise_id);
-		$question_list = $exercise->selectQuestionList();
+		$question_list = $exercise->getQuestionList();
 		// the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ? ? ?
         foreach ($question_list as $question_id) {
             $category_in_question = Testcategory::getCategoryForQuestion($question_id);
@@ -762,7 +764,7 @@ class Testcategory
 		* If no question for this category, return ""
 	*/
 	public static function getCatScoreForExeidForUserid($in_cat_id, $in_exe_id, $in_user_id) {
-		$tbl_track_attempt		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+		$tbl_track_attempt		= Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 		$tbl_question_rel_category = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
         $in_cat_id = intval($in_cat_id);
         $in_exe_id = intval($in_exe_id);

+ 1 - 1
main/forum/forumfunction.inc.php

@@ -3274,7 +3274,7 @@ function get_whats_new()
     $_course = api_get_course_info();
 
     $table_posts = Database :: get_course_table(TABLE_FORUM_POST);
-    $tracking_last_tool_access = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
+    $tracking_last_tool_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
 
     // Note: This has to be replaced by the tool constant later. But temporarily bb_forum is used since this is the only thing that is in the tracking currently.
     //$tool = TOOL_FORUM;

+ 1 - 1
main/gradebook/exercise_jump.php

@@ -18,7 +18,7 @@ api_block_anonymous_users();
 $this_section=SECTION_COURSES;
 
 $course_code = api_get_course_id();
-$course_info = Database::get_course_info($course_code);
+$course_info = api_get_course_info($course_code);
 $course_title = $course_info['title'];
 $course_code = $return_result['code'];
 $gradebook = Security::remove_XSS($_GET['gradebook']);

+ 3 - 3
main/gradebook/gradebook_result.class.php

@@ -92,8 +92,8 @@ class GradeBookResult
 		$return = array();
     	$TBL_EXERCISES          = Database::get_course_table(TABLE_QUIZ_TEST);
     	$TBL_USER          	    = Database::get_main_table(TABLE_MAIN_USER);
-		$TBL_TRACK_EXERCISES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-		$TBL_TRACK_HOTPOTATOES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
+		$TBL_TRACK_EXERCISES	= Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+		$TBL_TRACK_HOTPOTATOES	= Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
 
     	$cid = api_get_course_id();
     	$course_id = api_get_course_int_id();
@@ -328,4 +328,4 @@ class GradeBookResult
         echo $data;
         return true;
     }
-}
+}

+ 1 - 1
main/gradebook/index.php

@@ -731,7 +731,7 @@ $no_qualification = false;
 if ($category != '0') {
 	$cat = new Category();
 	$category_id   = intval($_GET['selectcat']);
-	$course_id     = Database::get_course_by_category($category_id);
+	$course_id     = CourseManager::get_course_by_category($category_id);
 	$show_message  = $cat->show_message_resource_delete($course_id);
 
 	if ($show_message == '') {

+ 2 - 2
main/gradebook/lib/be/exerciselink.class.php

@@ -85,7 +85,7 @@ class ExerciseLink extends AbstractLink
      * Has anyone done this exercise yet ?
      */
     public function has_results() {
-    	$tbl_stats = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    	$tbl_stats = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
         $session_id = api_get_session_id();
 		$sql = 'SELECT count(exe_id) AS number FROM '.$tbl_stats."
                 WHERE   session_id = $session_id AND
@@ -105,7 +105,7 @@ class ExerciseLink extends AbstractLink
 	 */
     public function calc_score($stud_id = null)
     {
-    	$tbl_stats = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    	$tbl_stats = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
         // The following query should be similar (in conditions)
         // to the one used in exercice/exercice.php, look for note-query-exe-results marker
         $session_id = api_get_session_id();

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

@@ -189,7 +189,7 @@ class DisplayGradebook
 		// Student
 		$status = CourseManager::get_user_in_course_status(api_get_user_id(), api_get_course_id());
 		$objcat = new Category();
-		$course_id = Database::get_course_by_category($selectcat);
+		$course_id = CourseManager::get_course_by_category($selectcat);
 		$message_resource=$objcat->show_message_resource_delete($course_id);
 
 		if (!$is_course_admin && $status<>1 && $selectcat<>0) {
@@ -361,7 +361,7 @@ class DisplayGradebook
 		//student
 		$status = CourseManager::get_user_in_course_status(api_get_user_id(), api_get_course_id());
 		$objcat = new Category();
-		$course_id = Database::get_course_by_category($selectcat);
+		$course_id = CourseManager::get_course_by_category($selectcat);
 		$message_resource = $objcat->show_message_resource_delete($course_id);
 
         $grade_model_id = $catobj->get_grade_model_id();

+ 2 - 2
main/gradebook/lib/fe/gradebooktable.class.php

@@ -520,7 +520,7 @@ class GradebookTable extends SortableTable {
 			// evaluation
 			case 'E' :
 				$cat = new Category();
-				$course_id = Database::get_course_by_category($_GET['selectcat']);
+				$course_id = CourseManager::get_course_by_category($_GET['selectcat']);
 
 				$show_message = $cat->show_message_resource_delete($course_id);
 
@@ -557,7 +557,7 @@ class GradebookTable extends SortableTable {
 			// link
 			case 'L' :
 				$cat 			= new Category();
-				$course_id	 	= Database::get_course_by_category($_GET['selectcat']);
+				$course_id	 	= CourseManager::get_course_by_category($_GET['selectcat']);
 				$show_message	= $cat->show_message_resource_delete($course_id);
 
 				$url = $item->get_link();

+ 2 - 2
main/inc/ajax/exercise.ajax.php

@@ -149,9 +149,9 @@ switch ($action) {
             $sidx = 1;
         }
 
-        $track_exercise        = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $track_exercise        = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
         $user_table            = Database::get_main_table(TABLE_MAIN_USER);
-        $track_attempt         = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+        $track_attempt         = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 
         $minutes        = intval($_REQUEST['minutes']);
         $now            = time() - 60*$minutes; //1 hour

+ 2 - 2
main/inc/ajax/message.ajax.php

@@ -27,7 +27,7 @@ switch ($action) {
 			echo '';
 			break;
 		}
-		$track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+		$track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
 		$tbl_my_user		= Database::get_main_table(TABLE_MAIN_USER);
 		$tbl_my_user_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
 		$tbl_user 			= Database::get_main_table(TABLE_MAIN_USER);
@@ -77,4 +77,4 @@ switch ($action) {
 	default:
 		echo '';
 }
-exit;
+exit;

+ 9 - 5
main/inc/ajax/thematic.ajax.php

@@ -9,7 +9,9 @@ require_once '../global.inc.php';
 api_protect_course_script(true);
 
 $action = $_GET['a'];
-$thematic = new Thematic();
+$courseInfo = api_get_course_info();
+
+$thematic = new Thematic($courseInfo);
 
 switch ($action) {
 	case 'save_thematic_plan':
@@ -84,12 +86,13 @@ switch ($action) {
 	case 'get_datetime_by_attendance':
 		$attendance_id       = intval($_REQUEST['attendance_id']);
 		$thematic_advance_id = intval($_REQUEST['thematic_advance_id']);
+        $courseInfo = api_get_course_info();
 
 		$label = '';
 		$input_select = '';
 		if (!empty($attendance_id)) {
 			$attendance = new Attendance();
-			$thematic   = new Thematic();
+			$thematic   = new Thematic($courseInfo);
             $thematic_list = $thematic->get_thematic_list();
 
             $my_list = $thematic_list_temp = array();
@@ -143,12 +146,13 @@ switch ($action) {
 	    break;
 	case 'update_done_thematic_advance':
 		$thematic_advance_id = intval($_GET['thematic_advance_id']);
+        $courseInfo = api_get_course_info();
 		$total_average = 0;
 		if (!empty($thematic_advance_id)) {
-			$thematic = new Thematic();
+			$thematic = new Thematic($courseInfo);
 			$affected_rows  = $thematic->update_done_thematic_advances($thematic_advance_id);
 			//if ($affected_rows) {
-			$total_average  = $thematic->get_total_average_of_thematic_advances(api_get_course_id(), api_get_session_id());
+			$total_average  = $thematic->get_total_average_of_thematic_advances(null, api_get_session_id());
 			//}
 		}
 		echo $total_average;
@@ -156,4 +160,4 @@ switch ($action) {
 	default:
 		echo '';
 }
-exit;
+exit;

+ 0 - 66
main/inc/conf/events.conf.dist.php

@@ -1,66 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Events' configuration
- * Used to configure each event and to link them to functions the event'll fire.
- * The flow is like the following :
- * 1. somewhere in the application an event is fired
- * 2. that event is intercepted by the switch EventsDispatcher
- * 3. that switch will go all over the "actions" in the event_config initialized beneath us according to the event
- * 4. that switch will see if the function actually exists (if not, we get dont do anything)
- * 5. then it will see if a filter for that function exists (if it does, the filter is executed)
- * 6. if the filter says it's ok, the function linked to the event is executed
- * 7. and that function will actually call the truly interesting function with the good require_once
- */
-global $event_config;
-
-$event_config = array(
-    'portal_homepage_edited' => array( // key for "user registration" event
-        'actions' => array( // we link this event to a bunch of functions that will be triggered when the event is fired
-            'event_send_mail' // don't forget to actually write this function in the events.lib.php file
-        ),
-        'self_sent' => false, // this key states that we can't add user to this event through the admin panel
-        'name_lang_var' => 'PortalHomepageEdited',
-        'desc_lang_var' => 'PortalHomepageEdited',
-        'available_keyvars' => array (// keys used for the mail template
-            'url'           => 'portal',
-            'sitename'      => 'sitename',
-            'firstname'     => 'firstname',
-            'lastname'      => 'lastname',
-            'username'      => 'username',
-            'usermail'      => 'usermail',
-            'password'      => 'password',
-            'user_lang'     => 'language',
-            'admin_name'    => 'administrator_name',
-            'admin_surname' => 'administrator_surname',
-            'admin_phone'   => 'administrator_phone',
-            'admin_email'   => 'administrator_email',
-        )
-    ),
-    'user_registration' => array( // key for "user registration" event
-        'actions' => array( // we link this event to a bunch of functions that will be triggered when the event is fired
-            'event_send_mail' // don't forget to actually write this function in the events.lib.php file
-        ),
-        'self_sent' => true, // this key states that we can't add user to this event through the admin panel
-        'name_lang_var' => 'UserRegistrationTitle',
-        'desc_lang_var' => 'UserRegistrationComment',
-        'available_keyvars' => array (// keys used for the mail template
-            'url'           => 'portal',
-            'sitename'      => 'sitename',
-            'firstname'     => 'firstname',
-            'lastname'      => 'lastname',
-            'username'      => 'username',
-            'usermail'      => 'usermail',
-            'password'      => 'password',
-            'user_lang'     => 'language',
-            'admin_name'    => 'administrator_name',
-            'admin_surname' => 'administrator_surname',
-            'admin_phone'   => 'administrator_phone',
-            'admin_email'   => 'administrator_email',
-        )
-    ),
-);
-
-
-@include 'events.conf.local.php';

+ 0 - 6
main/inc/conf/index.html

@@ -1,6 +0,0 @@
-<html>
-<head>
-</head>
-<body>
-</body>
-</html>

+ 0 - 18
main/inc/conf/mail.conf.dist.php

@@ -1,18 +0,0 @@
-<?php
-
-/**
- *	This file holds the configuration settings
- *	for phpmailer Class.
- *
- *	@package chamilo.configuration
- */
-
-$platform_email['SMTP_FROM_EMAIL']   = (isset($administrator['email'])?$administrator['email']:'admin@example.com');
-$platform_email['SMTP_FROM_NAME']    = (isset($administrator['name'])?$administrator['name']:'Admin');
-$platform_email['SMTP_HOST']         = 'localhost';
-$platform_email['SMTP_PORT']         = 25;
-$platform_email['SMTP_MAILER']       = IS_WINDOWS_OS ? 'smtp' : 'mail'; // mail, sendmail or smtp
-$platform_email['SMTP_AUTH']         = 0;
-$platform_email['SMTP_USER']         = '';
-$platform_email['SMTP_PASS']         = '';
-$platform_email['SMTP_CHARSET']      = 'UTF-8';

+ 184 - 211
main/inc/global.inc.php

@@ -47,7 +47,7 @@ $app = new Application();
     $app->register(new Igorw\Silex\ConfigServiceProvider($settingsFile));
 */
 
-/** Loading configuration file */
+/** Reading configuration files */
 // Reading configuration file from main/inc/conf/configuration.php or app/config/configuration.yml
 $configurationFilePath = $includePath.'/conf/configuration.php';
 $configurationYMLFile = $includePath.'/../../config/configuration.yml';
@@ -81,9 +81,7 @@ if (file_exists($configurationYMLFile)) {
     }
 }
 
-/**  End loading configuration file */
-
-/**  Setting Chamilo paths */
+/** Setting Chamilo paths */
 
 $app['root_sys'] = isset($_configuration['root_sys']) ? $_configuration['root_sys'] : dirname(dirname(__DIR__)).'/';
 $app['sys_data_path'] = isset($_configuration['sys_data_path']) ? $_configuration['sys_data_path'] : $app['root_sys'].'data/';
@@ -91,33 +89,10 @@ $app['sys_config_path'] = isset($_configuration['sys_config_path']) ? $_configur
 $app['sys_temp_path'] = isset($_configuration['sys_temp_path']) ? $_configuration['sys_temp_path'] : $app['root_sys'].'temp/';
 $app['sys_log_path'] = isset($_configuration['sys_log_path']) ? $_configuration['sys_log_path'] : $app['root_sys'].'logs/';
 
-/** Including legacy libs */
-
-// Include the main Chamilo platform library file.
-require_once $includePath.'/lib/main_api.lib.php';
-
-// Setting url_append
-$urlInfo = isset($_configuration['root_web']) ? parse_url($_configuration['root_web']) : null;
-$_configuration['url_append'] = null;
-if (isset($urlInfo['path'])) {
-    $_configuration['url_append'] = '/'.basename($urlInfo['path']);
-}
-
-// Do not over-use this variable. It is only for this scripts local use.
-$libPath = $includePath.'/lib/';
-
-// Database constants
-require_once $libPath.'database.constants.inc.php';
-
-// @todo Rewrite the events.lib.inc.php in a class
-require_once $libPath.'events.lib.inc.php';
-
-// Load allowed tag definitions for kses and/or HTMLPurifier.
-require_once $libPath.'formvalidator/Rule/allowed_tags.inc.php';
-
-/** Loading config files */
+/** Loading config files (mail, auth, profile) */
 
 if ($alreadyInstalled) {
+
     $configPath = $app['sys_config_path'];
 
     $confFiles = array(
@@ -136,7 +111,7 @@ if ($alreadyInstalled) {
 
     // Fixing $_configuration array
 
-    //Fixes bug in Chamilo 1.8.7.1 array was not set
+    // Fixes bug in Chamilo 1.8.7.1 array was not set
     $administrator['email'] = isset($administrator['email']) ? $administrator['email'] : 'admin@example.com';
     $administrator['name'] = isset($administrator['name']) ? $administrator['name'] : 'Admin';
 
@@ -153,6 +128,29 @@ if ($alreadyInstalled) {
     $userPasswordCrypted = (!empty($_configuration['password_encryption']) ? $_configuration['password_encryption'] : 'sha1');
 }
 
+/** End loading config files */
+
+/** Including legacy libs */
+require_once $includePath.'/lib/main_api.lib.php';
+
+// Setting $_configuration['url_append']
+$urlInfo = isset($_configuration['root_web']) ? parse_url($_configuration['root_web']) : null;
+$_configuration['url_append'] = null;
+if (isset($urlInfo['path'])) {
+    $_configuration['url_append'] = '/'.basename($urlInfo['path']);
+}
+
+$libPath = $includePath.'/lib/';
+$langPath = api_get_path(SYS_LANG_PATH);
+
+// Database constants
+require_once $libPath.'database.constants.inc.php';
+
+// @todo Rewrite the events.lib.inc.php in a class
+require_once $libPath.'events.lib.inc.php';
+
+// Load allowed tag definitions for kses and/or HTMLPurifier.
+require_once $libPath.'formvalidator/Rule/allowed_tags.inc.php';
 
 // Ensure that _configuration is in the global scope before loading
 // main_api.lib.php. This is particularly helpful for unit tests
@@ -168,10 +166,19 @@ $app['configuration_file'] = $configurationFilePath;
 $app['configuration_yml_file'] = $configurationYMLFile;
 $app['languages_file'] = array();
 $app['installed'] = $alreadyInstalled;
+$app['app.theme'] = 'chamilo';
 
-// Loading $app settings
-//require_once __DIR__.'/../../src/ChamiloLMS/Resources/config/prod.php';
-require_once __DIR__.'/../../src/ChamiloLMS/Resources/config/dev.php';
+// Developer options relies in the configuration.php file
+
+$app['debug'] = isset($_configuration['debug']) ? $_configuration['debug'] : false;
+$app['show_profiler'] = isset($_configuration['show_profiler']) ? $_configuration['show_profiler'] : false;
+
+// Loading $app settings depending of the debug option
+if ($app['debug']) {
+    require_once __DIR__.'/../../src/ChamiloLMS/Resources/config/dev.php';
+} else {
+    require_once __DIR__.'/../../src/ChamiloLMS/Resources/config/prod.php';
+}
 
 // Classic way of render pages or the Controller approach
 $app['classic_layout'] = false;
@@ -186,64 +193,47 @@ $app['allowed'] = true;
 // @todo use silex session provider instead of a custom class
 Chamilo::session()->start($alreadyInstalled);
 
-// Connect to the server database and select the main chamilo database.
-if (!($conn_return = @Database::connect(
-    array(
-        'server' => $_configuration['db_host'],
-        'username' => $_configuration['db_user'],
-        'password' => $_configuration['db_password'],
-        'persistent' => isset($_configuration['db_persistent_connection']) ? $_configuration['db_persistent_connection'] : null
-        // When $app['configuration']['db_persistent_connection'] is set, it is expected to be a boolean type.
-    )
-))
-) {
-    //$app->abort(500, "Database is unavailable"); //error 3
-}
+// Loading chamilo settings
+/* @todo create a service provider to load plugins.
+   Check how bolt add extensions (including twig templates, config with yml)*/
 
-/*
-if (!$app['configuration']['db_host']) {
-    //$app->abort(500, "Database is unavailable"); //error 3
-}*/
+// Template settings loaded in template.lib.php
+$app['template.show_header'] = true;
+$app['template.show_footer'] = true;
+$app['template.show_learnpath'] = false;
+$app['template.hide_global_chat'] = true;
+$app['template.load_plugins'] = true;
 
-$checkConnection = false;
+$app['configuration'] = $_configuration;
 
-if (isset($_configuration['main_database'])) {
-    // The system has not been designed to use special SQL modes that were introduced since MySQL 5.
-    Database::query("set session sql_mode='';");
-    $checkConnection = @Database::select_db($_configuration['main_database'], $conn_return);
+/** Including service providers */
+require_once 'services.php';
 
-    if ($checkConnection) {
+$_plugins = array();
+if ($alreadyInstalled) {
 
-        // Initialization of the database encoding to be used.
-        Database::query("SET SESSION character_set_server = 'utf8';");
-        Database::query("SET SESSION collation_server = 'utf8_general_ci';");
-        Database::query("SET NAMES 'utf8';");
-    }
-}
+    // Setting the static database class
+    $database = $app['database'];
 
-/* Retrieving all the chamilo config settings for multiple URLs feature*/
-if (isset($_configuration['multiple_access_urls']) && !empty($_configuration['multiple_access_urls'])) {
+    // Retrieving all the chamilo config settings for multiple URLs feature
     $_configuration['access_url'] = 1;
-    $access_urls = api_get_access_urls();
-
-    $protocol = ((!empty($_SERVER['HTTPS']) && strtoupper($_SERVER['HTTPS']) != 'OFF') ? 'https' : 'http').'://';
-    $request_url1 = $protocol.$_SERVER['SERVER_NAME'].'/';
-    $request_url2 = $protocol.$_SERVER['HTTP_HOST'].'/';
-
-    foreach ($access_urls as & $details) {
-        if ($request_url1 == $details['url'] or $request_url2 == $details['url']) {
-            $_configuration['access_url'] = $details['id'];
+    if (api_get_multiple_access_url()) {
+        $access_urls = api_get_access_urls();
+        $protocol = ((!empty($_SERVER['HTTPS']) && strtoupper($_SERVER['HTTPS']) != 'OFF') ? 'https' : 'http').'://';
+        $request_url1 = $protocol.$_SERVER['SERVER_NAME'].'/';
+        $request_url2 = $protocol.$_SERVER['HTTP_HOST'].'/';
+
+        foreach ($access_urls as & $details) {
+            if ($request_url1 == $details['url'] or $request_url2 == $details['url']) {
+                $_configuration['access_url'] = $details['id'];
+            }
         }
+        Session::write('url_id', $_configuration['access_url']);
+        Session::write('url_info', api_get_current_access_url_info($_configuration['access_url']));
+    } else {
+        Session::write('url_id', -1);
     }
-} else {
-    $_configuration['access_url'] = 1;
-}
 
-// Loading chamilo settings
-/* @todo create a service provider to load plugins.
-   Check how bolt add extensions (including twig templates, config with yml)*/
-$_plugins = array();
-if ($alreadyInstalled && $checkConnection) {
     $settings_refresh_info = api_get_settings_params_simple(array('variable = ?' => 'settings_latest_update'));
     $settings_latest_update = $settings_refresh_info ? $settings_refresh_info['selected_value'] : null;
 
@@ -259,32 +249,20 @@ if ($alreadyInstalled && $checkConnection) {
             $_plugins = isset($_SESSION['_plugins']) ? $_SESSION['_plugins'] : null;
         }
     }
-}
-$app['plugins'] = $_plugins;
 
-// Template settings loaded in template.lib.php
-$app['template.show_header'] = true;
-$app['template.show_footer'] = true;
-$app['template.show_learnpath'] = false;
-$app['template.hide_global_chat'] = true;
-$app['template.load_plugins'] = true;
-
-// Default template style
-$templateStyle = api_get_setting('template');
-$templateStyle = isset($templateStyle) && !empty($templateStyle) ? $templateStyle : 'default';
-$app['template_style'] = $templateStyle;
-
-// Default layout
-$app['default_layout'] = $app['template_style'].'/layout/layout_1_col.tpl';
+    // Default template style
+    $templateStyle = api_get_setting('template');
+    $templateStyle = isset($templateStyle) && !empty($templateStyle) ? $templateStyle : 'default';
+    $app['template_style'] = $templateStyle;
 
-$app['configuration'] = $_configuration;
+    // Default layout
+    $app['default_layout'] = $app['template_style'].'/layout/layout_1_col.tpl';
 
-/** Including service providers */
-require_once 'services.php';
+    $app['plugins'] = $_plugins;
+}
 
 $charset = 'UTF-8';
 
-
 // Manage Chamilo error messages
 $app->error(
     function (\Exception $e, $code) use ($app) {
@@ -321,7 +299,6 @@ $app->error(
 // Preserving the value of the global variable $charset.
 $charset_initial_value = $charset;
 
-
 // Section (tabs in the main chamilo menu)
 $app['this_section'] = SECTION_GLOBAL;
 
@@ -330,115 +307,111 @@ require_once $libPath.'internationalization.lib.php';
 // Functions for internal use behind this API
 require_once $libPath.'internationalization_internal.lib.php';
 
-// Setting languages
-$app['api_get_languages'] = api_get_languages();
-
 // Checking if we have a valid language. If not we set it to the platform language.
 if ($alreadyInstalled) {
+    // Setting languages
+    $app['api_get_languages'] = api_get_languages();
     $app['language_interface'] = $language_interface = api_get_language_interface();
-} else {
-    $app['language_interface'] = $language_interface = 'english';
-}
-
-// Initialization of the internationalization library.
-api_initialize_internationalization();
-
-// Initialization of the default encoding that will be used by the multibyte string routines in the internationalization library.
-api_set_internationalization_default_encoding($charset);
-
-// include the local (contextual) parameters of this course or section
-require $includePath.'/local.inc.php';
 
-// reconfigure templat now we know the user
-$app['template.hide_global_chat'] = !api_is_global_chat_enabled();
+    // Initialization of the internationalization library.
+    api_initialize_internationalization();
 
-/**	Loading languages and sublanguages **/
-// @todo improve the language loading
+    // Initialization of the default encoding that will be used by the multibyte string routines in the internationalization library.
+    api_set_internationalization_default_encoding($charset);
 
-// if we use the javascript version (without go button) we receive a get
-// if we use the non-javascript version (with the go button) we receive a post
+    // include the local (contextual) parameters of this course or section
+    require $includePath.'/local.inc.php';
 
-// Include all files (first english and then current interface language)
-$app['this_script'] = isset($this_script) ? $this_script : null;
+    // reconfigure template now we know the user
+    $app['template.hide_global_chat'] = !api_is_global_chat_enabled();
 
-// Sometimes the variable $language_interface is changed
-// temporarily for achieving translation in different language.
-// We need to save the genuine value of this variable and
-// to use it within the function get_lang(...).
-$language_interface_initial_value = $language_interface;
+    /**	Loading languages and sublanguages **/
+    // @todo improve the language loading
 
-$langPath = api_get_path(SYS_LANG_PATH);
-
-$this_script = $app['this_script'];
-$language_interface = $app['language_interface'];
-
-/* This will only work if we are in the page to edit a sub_language */
-if (isset($this_script) && $this_script == 'sub_language') {
-    require_once api_get_path(SYS_CODE_PATH).'admin/sub_language.class.php';
-    // getting the arrays of files i.e notification, trad4all, etc
-    $language_files_to_load = SubLanguageManager:: get_lang_folder_files_list(
-        api_get_path(SYS_LANG_PATH).'english',
-        true
-    );
-    //getting parent info
-    $languageId = isset($_REQUEST['id']) ? $_REQUEST['id'] : null;
-    $parent_language = SubLanguageManager::get_all_information_of_language($languageId);
+    // if we use the javascript version (without go button) we receive a get
+    // if we use the non-javascript version (with the go button) we receive a post
 
-    $subLanguageId = isset($_REQUEST['sub_language_id']) ? $_REQUEST['sub_language_id'] : null;
+    // Include all files (first english and then current interface language)
+    $app['this_script'] = isset($this_script) ? $this_script : null;
 
-    //getting sub language info
-    $sub_language = SubLanguageManager::get_all_information_of_language($subLanguageId);
+    // Sometimes the variable $language_interface is changed
+    // temporarily for achieving translation in different language.
+    // We need to save the genuine value of this variable and
+    // to use it within the function get_lang(...).
+    $language_interface_initial_value = $language_interface;
 
-    $english_language_array = $parent_language_array = $sub_language_array = array();
+    $this_script = $app['this_script'];
 
-    if (!empty($language_files_to_load)) {
-        foreach ($language_files_to_load as $language_file_item) {
-            $lang_list_pre = array_keys($GLOBALS);
-            //loading english
-            $path = $langPath.'english/'.$language_file_item.'.inc.php';
-            if (file_exists($path)) {
-                include $path;
-            }
+    /* This will only work if we are in the page to edit a sub_language */
+    if (isset($this_script) && $this_script == 'sub_language') {
+        require_once api_get_path(SYS_CODE_PATH).'admin/sub_language.class.php';
+        // getting the arrays of files i.e notification, trad4all, etc
+        $language_files_to_load = SubLanguageManager:: get_lang_folder_files_list(
+            api_get_path(SYS_LANG_PATH).'english',
+            true
+        );
+        //getting parent info
+        $languageId = isset($_REQUEST['id']) ? $_REQUEST['id'] : null;
+        $parent_language = SubLanguageManager::get_all_information_of_language($languageId);
+
+        $subLanguageId = isset($_REQUEST['sub_language_id']) ? $_REQUEST['sub_language_id'] : null;
+
+        //getting sub language info
+        $sub_language = SubLanguageManager::get_all_information_of_language($subLanguageId);
+
+        $english_language_array = $parent_language_array = $sub_language_array = array();
+
+        if (!empty($language_files_to_load)) {
+            foreach ($language_files_to_load as $language_file_item) {
+                $lang_list_pre = array_keys($GLOBALS);
+                //loading english
+                $path = $langPath.'english/'.$language_file_item.'.inc.php';
+                if (file_exists($path)) {
+                    include $path;
+                }
 
-            $lang_list_post = array_keys($GLOBALS);
-            $lang_list_result = array_diff($lang_list_post, $lang_list_pre);
-            unset($lang_list_pre);
+                $lang_list_post = array_keys($GLOBALS);
+                $lang_list_result = array_diff($lang_list_post, $lang_list_pre);
+                unset($lang_list_pre);
 
-            //  english language array
-            $english_language_array[$language_file_item] = compact($lang_list_result);
+                //  english language array
+                $english_language_array[$language_file_item] = compact($lang_list_result);
 
-            //cleaning the variables
-            foreach ($lang_list_result as $item) {
-                unset(${$item});
-            }
-            $parent_file = $langPath.$parent_language['dokeos_folder'].'/'.$language_file_item.'.inc.php';
+                //cleaning the variables
+                foreach ($lang_list_result as $item) {
+                    unset(${$item});
+                }
+                $parent_file = $langPath.$parent_language['dokeos_folder'].'/'.$language_file_item.'.inc.php';
 
-            if (file_exists($parent_file) && is_file($parent_file)) {
-                include_once $parent_file;
-            }
-            //  parent language array
-            $parent_language_array[$language_file_item] = compact($lang_list_result);
+                if (file_exists($parent_file) && is_file($parent_file)) {
+                    include_once $parent_file;
+                }
+                //  parent language array
+                $parent_language_array[$language_file_item] = compact($lang_list_result);
 
-            //cleaning the variables
-            foreach ($lang_list_result as $item) {
-                unset(${$item});
-            }
-            if (!empty($sub_language)) {
-                $sub_file = $langPath.$sub_language['dokeos_folder'].'/'.$language_file_item.'.inc.php';
-                if (file_exists($sub_file) && is_file($sub_file)) {
-                    include $sub_file;
+                //cleaning the variables
+                foreach ($lang_list_result as $item) {
+                    unset(${$item});
+                }
+                if (!empty($sub_language)) {
+                    $sub_file = $langPath.$sub_language['dokeos_folder'].'/'.$language_file_item.'.inc.php';
+                    if (file_exists($sub_file) && is_file($sub_file)) {
+                        include $sub_file;
+                    }
                 }
-            }
 
-            //  sub language array
-            $sub_language_array[$language_file_item] = compact($lang_list_result);
+                //  sub language array
+                $sub_language_array[$language_file_item] = compact($lang_list_result);
 
-            //cleaning the variables
-            foreach ($lang_list_result as $item) {
-                unset(${$item});
+                //cleaning the variables
+                foreach ($lang_list_result as $item) {
+                    unset(${$item});
+                }
             }
         }
     }
+} else {
+    $app['language_interface'] = $language_interface = $language_interface_initial_value = 'english';
 }
 
 /**
@@ -527,11 +500,10 @@ if (api_get_setting('login_is_email') == 'true') {
 /** A "before" middleware allows you to tweak the Request before the controller is executed */
 
 $app->before(
-    function () use ($app, $checkConnection) {
-
+    function () use ($app) {
         if (!file_exists($app['configuration_file']) && !file_exists($app['configuration_yml_file'])) {
             return new RedirectResponse(api_get_path(WEB_CODE_PATH).'install');
-            $app->abort(500, "Incorrect PHP version");
+            $app->abort(500, "Configuration file was not found");
         }
 
         //Check the PHP version
@@ -539,23 +511,14 @@ $app->before(
             $app->abort(500, "Incorrect PHP version");
         }
 
-        if ($checkConnection == false) {
-            $app->abort(500, "Database not available");
-        }
-
         if (!is_writable(api_get_path(SYS_ARCHIVE_PATH))) {
             $app->abort(500, "temp folder must be writable");
         }
 
         // Check and modify the date of user in the track.e.online table
-
-        //if ($checkConnection && !$x = strpos($_SERVER['PHP_SELF'], 'whoisonline.php')) {
         Online::loginCheck(api_get_user_id());
-        //}
-
         //$app['request']->getSession()->start();
         //var_dump($app['cidReset']);
-
     }
 );
 
@@ -586,10 +549,11 @@ $text_dir = api_get_text_direction();
 // Update of the logout_date field in the table track_e_login (needed for the calculation of the total connection time)
 
 /** "Login as user" custom script */
+// @todo move this code in a controller
 if (!isset($_SESSION['login_as']) && isset($_user)) {
     // if $_SESSION['login_as'] is set, then the user is an admin logged as the user
 
-    $tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+    $tbl_track_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
     $sql_last_connection = "SELECT login_id, login_date FROM $tbl_track_login WHERE login_user_id='".$_user["user_id"]."' ORDER BY login_date DESC LIMIT 0,1";
 
     $q_last_connection = Database::query($sql_last_connection);
@@ -606,8 +570,8 @@ if (!isset($_SESSION['login_as']) && isset($_user)) {
             $q_last_connection = Database::query($sql_last_connection);
             $i_id_last_connection = Database::result($q_last_connection, 0, 'login_id');
         }
-
-        $s_sql_update_logout_date = "UPDATE $tbl_track_login SET logout_date=NOW() WHERE login_id='$i_id_last_connection'";
+        $now = api_get_utc_datetime();
+        $s_sql_update_logout_date = "UPDATE $tbl_track_login SET logout_date = '$now' WHERE login_id = $i_id_last_connection";
         Database::query($s_sql_update_logout_date);
     } else {
         // it isn't, we should create a fresh entry
@@ -645,8 +609,7 @@ $app['is_admin'] = false;
 /** Including routes */
 require_once 'routes.php';
 
-
-// Setting gedmo extensions
+// Setting doctrine2 extensions
 
 if (isset($app['configuration']['main_database']) && isset($app['db.event_manager'])) {
 
@@ -664,17 +627,26 @@ if (isset($app['configuration']['main_database']) && isset($app['db.event_manage
 
     // Setting Doctrine2 extensions
     $timestampableListener = new \Gedmo\Timestampable\TimestampableListener();
-    $app['db.event_manager']->addEventSubscriber($timestampableListener);
+    // $app['db.event_manager']->addEventSubscriber($timestampableListener);
+    $app['dbs.event_manager']['db_read']->addEventSubscriber($timestampableListener);
+    $app['dbs.event_manager']['db_write']->addEventSubscriber($timestampableListener);
 
     $sluggableListener = new \Gedmo\Sluggable\SluggableListener();
-    $app['db.event_manager']->addEventSubscriber($sluggableListener);
+    // $app['db.event_manager']->addEventSubscriber($sluggableListener);
+    $app['dbs.event_manager']['db_read']->addEventSubscriber($sluggableListener);
+    $app['dbs.event_manager']['db_write']->addEventSubscriber($sluggableListener);
+
 
     $sortableListener = new Gedmo\Sortable\SortableListener();
-    $app['db.event_manager']->addEventSubscriber($sortableListener);
+    // $app['db.event_manager']->addEventSubscriber($sortableListener);
+    $app['dbs.event_manager']['db_read']->addEventSubscriber($sortableListener);
+    $app['dbs.event_manager']['db_write']->addEventSubscriber($sortableListener);
 
     $treeListener = new \Gedmo\Tree\TreeListener();
     //$treeListener->setAnnotationReader($cachedAnnotationReader);
-    $app['db.event_manager']->addEventSubscriber($treeListener);
+    // $app['db.event_manager']->addEventSubscriber($treeListener);
+    $app['dbs.event_manager']['db_read']->addEventSubscriber($treeListener);
+    $app['dbs.event_manager']['db_write']->addEventSubscriber($treeListener);
 
     $loggableListener = new \Gedmo\Loggable\LoggableListener();
     $userInfo = api_get_user_info();
@@ -682,11 +654,12 @@ if (isset($app['configuration']['main_database']) && isset($app['db.event_manage
     if (isset($userInfo) && !empty($userInfo['username'])) {
         $loggableListener->setUsername($userInfo['username']);
     }
-
-    $app['db.event_manager']->addEventSubscriber($loggableListener);
+    //$app['db.event_manager']->addEventSubscriber($loggableListener);
+    $app['dbs.event_manager']['db_read']->addEventSubscriber($loggableListener);
+    $app['dbs.event_manager']['db_write']->addEventSubscriber($loggableListener);
 }
 
-//Fixes uses of $_course in the scripts
+// Fixes uses of $_course in the scripts.
 $_course = api_get_course_info();
 $_cid = api_get_course_id();
 

+ 1 - 8
main/inc/lib/announcements.inc.php

@@ -1005,13 +1005,6 @@ class AnnouncementManager
     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();
@@ -1343,4 +1336,4 @@ class AnnouncementManager
 
     }
 }
-//end class
+//end class

+ 26 - 26
main/inc/lib/attendance.lib.php

@@ -277,8 +277,8 @@ class Attendance
 					attendance_qualify_title = '$title_gradebook',
 					attendance_weight = '$weight_calification',
 					session_id = '$session_id'";
-		Database::query($sql);
-		$affected_rows = Database::affected_rows();
+		$result = Database::query($sql);
+		$affected_rows = Database::affected_rows($result);
 		$last_id = 0;
 		if (!empty($affected_rows)) {
 			// save inside item property table
@@ -361,8 +361,8 @@ class Attendance
 			foreach ($attendance_id as $id) {
 				$id	= intval($id);
 				$sql = "UPDATE $tbl_attendance SET active = 1 WHERE c_id = $course_id AND id = '$id'";
-				Database::query($sql);
-				$affected_rows = Database::affected_rows();
+				$result = Database::query($sql);
+				$affected_rows = Database::affected_rows($result);
 				if (!empty($affected_rows)) {
 					// update row item property table
 					api_item_property_update($course_info, TOOL_ATTENDANCE, $id,"restore", $user_id);
@@ -371,8 +371,8 @@ class Attendance
 		} else  {
 			$attendance_id	= intval($attendance_id);
 			$sql = "UPDATE $tbl_attendance SET active = 1 WHERE c_id = $course_id AND id = '$attendance_id'";
-			Database::query($sql);
-			$affected_rows = Database::affected_rows();
+			$result = Database::query($sql);
+			$affected_rows = Database::affected_rows($result);
 			if (!empty($affected_rows)) {
 				// update row item property table
 				api_item_property_update($course_info, TOOL_ATTENDANCE, $attendance_id,"restore", $user_id);
@@ -397,8 +397,8 @@ class Attendance
 			foreach ($attendance_id as $id) {
 				$id	= intval($id);
 				$sql = "UPDATE $tbl_attendance SET active = 0 WHERE c_id = $course_id AND id = '$id'";
-				Database::query($sql);
-				$affected_rows = Database::affected_rows();
+				$result = Database::query($sql);
+				$affected_rows = Database::affected_rows($result);
 				if (!empty($affected_rows)) {
 					// update row item property table
 					api_item_property_update($course_info, TOOL_ATTENDANCE, $id,"delete", $user_id);
@@ -407,8 +407,8 @@ class Attendance
 		} else  {
 			$attendance_id	= intval($attendance_id);
 			$sql = "UPDATE $tbl_attendance SET active = 0 WHERE c_id = $course_id AND id = '$attendance_id'";
-			Database::query($sql);
-			$affected_rows = Database::affected_rows();
+			$result = Database::query($sql);
+			$affected_rows = Database::affected_rows($result);
 			if (!empty($affected_rows)) {
 				// update row item property table
 				api_item_property_update($course_info, TOOL_ATTENDANCE, $attendance_id,"delete", $user_id);
@@ -428,8 +428,8 @@ class Attendance
         $attendance_id = intval($attendance_id);
         $locked = ($lock)?1:0;
         $upd = "UPDATE $tbl_attendance SET locked = $locked WHERE c_id = $course_id AND id = $attendance_id";
-        Database::query($upd);
-        $affected_rows = Database::affected_rows();
+        $result = Database::query($upd);
+        $affected_rows = Database::affected_rows($result);
         if ($affected_rows && $lock) {
             //save attendance sheet log
             $lastedit_type = self::LOCKED_ATTENDANCE_LOG_TYPE;
@@ -575,13 +575,13 @@ class Attendance
                             user_id 				= '$uid',
                             attendance_calendar_id 	= '$calendar_id',
                             presence 				= $presence";
-                    Database::query($sql);
-                    $affected_rows += Database::affected_rows();
+                    $result = Database::query($sql);
+                    $affected_rows += Database::affected_rows($result);
                 } else {
                     $sql = "UPDATE $tbl_attendance_sheet SET presence = $presence
                             WHERE c_id = $course_id AND user_id ='$uid' AND attendance_calendar_id = '$calendar_id'";
-                    Database::query($sql);
-                    $affected_rows += Database::affected_rows();
+                    $result = Database::query($sql);
+                    $affected_rows += Database::affected_rows($result);
                 }
             }
         }
@@ -765,8 +765,8 @@ class Attendance
         // save data
         $ins = "INSERT INTO $tbl_attendance_sheet_log(c_id, attendance_id, lastedit_date, lastedit_type, lastedit_user_id, calendar_date_value)
                 VALUES ($course_id, $attendance_id, '$lastedit_date', '$lastedit_type', $lastedit_user_id, '$calendar_date_value')";
-        Database::query($ins);
-        return Database::affected_rows();
+        $result = Database::query($ins);
+        return Database::affected_rows($result);
    }
 
 	/**
@@ -1222,9 +1222,9 @@ class Attendance
 					c_id			= $course_id,
 					date_time		= '".Database::escape_string($this->date_time)."',
 					attendance_id 	= '$attendance_id'";
-			Database::query($sql);
-            $cal_id = Database::get_last_insert_id();
-			$affected_rows = Database::affected_rows();
+			$result = Database::query($sql);
+            $cal_id = Database::insert_id();
+			$affected_rows = Database::affected_rows($result);
 		}
 
         // update locked attendance
@@ -1336,8 +1336,8 @@ class Attendance
 		$rs = Database::query($sql);
 		if (Database::num_rows($rs) == 0) {
 			$sql = "UPDATE $tbl_attendance_calendar SET date_time='".Database::escape_string($this->date_time)."' WHERE c_id = $course_id AND id = '".intval($calendar_id)."'";
-			Database::query($sql);
-			$affected_rows = Database::affected_rows();
+			$result = Database::query($sql);
+			$affected_rows = Database::affected_rows($result);
 		}
 
         // update locked attendance
@@ -1379,7 +1379,7 @@ class Attendance
 					Database::query($sql);
 					// delete data from attendance calendar
 					$sql = "DELETE FROM $tbl_attendance_calendar WHERE c_id = $course_id AND id = '".intval($cal['id'])."'";
-					Database::query($sql);
+					$result = Database::query($sql);
 				}
 			}
 		} else {
@@ -1388,10 +1388,10 @@ class Attendance
 			Database::query($sql);
 			// delete data from attendance calendar
 			$sql = "DELETE FROM $tbl_attendance_calendar WHERE c_id = $course_id AND id = '".intval($calendar_id)."'";
-			Database::query($sql);
+			$result = Database::query($sql);
 		}
 
-		$affected_rows = Database::affected_rows();
+		$affected_rows = Database::affected_rows($result);
 		// update users' results
 		$this->update_users_results($user_ids, $attendance_id);
 

+ 21 - 22
main/inc/lib/auth.lib.php

@@ -96,7 +96,7 @@ class AuthLib {
      */
     public function get_user_course_categories() {
         $user_id = api_get_user_id();
-        $table_category = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
+        $table_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
         $sql = "SELECT * FROM " . $table_category . " WHERE user_id=$user_id ORDER BY sort ASC";
         $result = Database::query($sql);
         $output = array();
@@ -118,7 +118,7 @@ class AuthLib {
         // table definitions
         $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
         $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
-        $TABLE_USER_COURSE_CATEGORY = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
+        $TABLE_USER_COURSE_CATEGORY = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
         $TABLE_COURSE_FIELD = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
         $TABLE_COURSE_FIELD_VALUE = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
 
@@ -177,10 +177,10 @@ class AuthLib {
         $current_user = api_get_user_id();
 
         $max_sort_value = api_max_sort_value($newcategory, $current_user); // max_sort_value($newcategory);
-        Database::query("UPDATE $TABLECOURSUSER SET user_course_cat='" . $newcategory . "', sort='" . ($max_sort_value + 1) . "'
+        $result = Database::query("UPDATE $TABLECOURSUSER SET user_course_cat='" . $newcategory . "', sort='" . ($max_sort_value + 1) . "'
                         WHERE c_id ='" . $courseId . "' AND user_id='" . $current_user . "' AND relation_type<>" . COURSE_RELATION_TYPE_RRHH . "");
-        $result = false;
-        if (Database::affected_rows()) {
+
+        if (Database::affected_rows($result)) {
             $result = true;
         }
         return $result;
@@ -231,8 +231,8 @@ class AuthLib {
             $sql_update2 = "UPDATE $TABLECOURSUSER SET sort='" . $source_course['sort'] . "'
                             WHERE c_id = '" . $target_course['real_id'] . "' AND user_id='" . $current_user_id . "' AND relation_type<>" . COURSE_RELATION_TYPE_RRHH . " ";
             Database::query($sql_update2);
-            Database::query($sql_update1);
-            if (Database::affected_rows()) {
+            $result = Database::query($sql_update1);
+            if (Database::affected_rows($result)) {
                 $result = true;
             }
         }
@@ -248,7 +248,7 @@ class AuthLib {
     public function move_category($direction, $category2move) {
 
         // the database definition of the table that stores the user defined course categories
-        $table_user_defined_category = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
+        $table_user_defined_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
 
         $current_user_id = api_get_user_id();
         $user_coursecategories = $this->get_user_course_categories();
@@ -273,8 +273,8 @@ class AuthLib {
             $sql_update1 = "UPDATE $table_user_defined_category SET sort='" . Database::escape_string($target_category['sort']) . "' WHERE id='" . intval($source_category['id']) . "' AND user_id='" . $current_user_id . "'";
             $sql_update2 = "UPDATE $table_user_defined_category SET sort='" . Database::escape_string($source_category['sort']) . "' WHERE id='" . intval($target_category['id']) . "' AND user_id='" . $current_user_id . "'";
             Database::query($sql_update2);
-            Database::query($sql_update1);
-            if (Database::affected_rows()) {
+            $result = Database::query($sql_update1);
+            if (Database::affected_rows($result)) {
                 $result = true;
             }
         }
@@ -287,7 +287,7 @@ class AuthLib {
      */
     public function get_user_course_categories_info() {
         $current_user_id = api_get_user_id();
-        $table_category = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
+        $table_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
         $sql = "SELECT * FROM " . $table_category . " WHERE user_id='" . $current_user_id . "' ORDER BY sort ASC";
         $result = Database::query($sql);
         while ($row = Database::fetch_array($result)) {
@@ -307,10 +307,10 @@ class AuthLib {
         $title = Database::escape_string($title);
         $category_id = intval($category_id);
         $result = false;
-        $tucc = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
+        $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
         $sql_update = "UPDATE $tucc SET title='" . api_htmlentities($title, ENT_QUOTES, api_get_system_encoding()) . "' WHERE id='" . $category_id . "'";
-        Database::query($sql_update);
-        if (Database::affected_rows()) {
+        $result = Database::query($sql_update);
+        if (Database::affected_rows($result)) {
             $result = true;
         }
         return $result;
@@ -323,13 +323,12 @@ class AuthLib {
      */
     public function delete_course_category($category_id) {
         $current_user_id = api_get_user_id();
-        $tucc = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
+        $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
         $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
         $category_id = intval($category_id);
-        $result = false;
         $sql_delete = "DELETE FROM $tucc WHERE id='" . $category_id . "' and user_id='" . $current_user_id . "'";
-        Database::query($sql_delete);
-        if (Database::affected_rows()) {
+        $result = Database::query($sql_delete);
+        if (Database::affected_rows($result)) {
             $result = true;
         }
         $sql_update = "UPDATE $TABLECOURSUSER SET user_course_cat='0'
@@ -373,7 +372,7 @@ class AuthLib {
      */
     public function store_course_category($category_title) {
 
-        $tucc = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
+        $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
 
         // protect data
         $current_user_id = api_get_user_id();
@@ -391,8 +390,8 @@ class AuthLib {
         $rs = Database::query($sql);
         if (Database::num_rows($rs) == 0) {
             $sql_insert = "INSERT INTO $tucc (user_id, title,sort) VALUES ('" . $current_user_id . "', '" . api_htmlentities($category_title, ENT_QUOTES, api_get_system_encoding()) . "', '" . $nextsort . "')";
-            Database::query($sql_insert);
-            if (Database::affected_rows()) {
+            $result = Database::query($sql_insert);
+            if (Database::affected_rows($result)) {
                 $result = true;
             }
         } else {
@@ -691,4 +690,4 @@ class AuthLib {
             return array('message' => $message, 'content' => $content);
         }
     }
-}
+}

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

@@ -39,8 +39,8 @@ class ClassManager
 	function create_class($name) {
 		$table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
 		$sql = "INSERT INTO $table_class SET name='".Database::escape_string($name)."'";
-		Database::query($sql);
-		return Database::affected_rows() == 1;
+		$result = Database::query($sql);
+		return Database::affected_rows($result) == 1;
 	}
 	/**
 	 * Check if a classname is allready in use
@@ -224,4 +224,4 @@ class ClassManager
 		}
 		return $classes;
 	}
-}
+}

+ 147 - 82
main/inc/lib/course.lib.php

@@ -30,9 +30,11 @@ class CourseManager
      * @param   array   with the columns in the main.course table
      * @param   mixed   false if the course was not created, array with the course info
      * @return mixed False on error, or an array with course attributes on success
+     * @todo remove globals
      * @assert () === false
      */
-    static function create_course($params) {
+    public static function create_course($params)
+    {
         global $_configuration;
 
         // Check portal limits
@@ -127,8 +129,11 @@ class CourseManager
      * @return array Array of course attributes
      * @assert () === false
      */
-    static function update($params) {
-        if (!is_array($params) or count($params)<1) { return false; }
+    public static function update($params)
+    {
+        if (!is_array($params) or count($params)<1) {
+            return false;
+        }
         $course_user_table  = Database::get_main_table(TABLE_MAIN_COURSE_USER);
         $course_table       = Database::get_main_table(TABLE_MAIN_COURSE);
 
@@ -179,7 +184,9 @@ class CourseManager
         //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."'";
+            foreach($teachers as $key) {
+                $cond.=" AND user_id<>'".$key."'";
+            }
         }
         $sql = 'DELETE FROM '.$course_user_table.' WHERE c_id = "'.Database::escape_string($courseInfo['real_id']).'" AND status="1"'.$cond;
         Database::query($sql);
@@ -217,6 +224,7 @@ class CourseManager
         Database::query($sql);
 
         $course_info = api_get_course_info($course_code);
+
         return $course_info;
     }
 
@@ -227,7 +235,8 @@ class CourseManager
      * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
      * @assert (array(1,2,3)) === false
      */
-    public static function get_course_information($course_code) {
+    public static function get_course_information($course_code)
+    {
         return Database::fetch_array(Database::query(
             "SELECT *, id as real_id FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
             WHERE code='".Database::escape_string($course_code)."'"),'ASSOC'
@@ -241,7 +250,8 @@ class CourseManager
      * @return an array with all the fields of the course table
      * @assert (-1) === false
      */
-    public static function get_course_information_by_id($course_id) {
+    public static function get_course_information_by_id($course_id)
+    {
         return Database::select('*, id as real_id', Database::get_main_table(TABLE_MAIN_COURSE), array('where'=>array('id = ?' =>intval($course_id))),'first');
     }
 
@@ -256,7 +266,8 @@ class CourseManager
      * @return mixed Array of courses details, or false on error
      * @assert (array(1,2,3)) === false
      */
-    public static function get_courses_list($from = 0, $howmany = 0, $orderby = 1, $orderdirection = 'ASC', $visibility = -1, $startwith = '') {
+    public static function get_courses_list($from = 0, $howmany = 0, $orderby = 1, $orderdirection = 'ASC', $visibility = -1, $startwith = '')
+    {
 
         $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." ";
         if (!empty($startwith)) {
@@ -308,7 +319,8 @@ class CourseManager
      * @return an array with int fields "visibility", "subscribe", "unsubscribe"
      * @assert () === false
      */
-    public static function get_access_settings($course_code) {
+    public static function get_access_settings($course_code)
+    {
         return Database::fetch_array(Database::query(
             "SELECT visibility, subscribe, unsubscribe from ".Database::get_main_table(TABLE_MAIN_COURSE)."
             WHERE code = '".Database::escape_string($course_code)."'")
@@ -323,7 +335,8 @@ class CourseManager
      * @return int the status of the user in that course
      * @assert () === false
      */
-    public static function get_user_in_course_status($user_id, $courseId) {
+    public static function get_user_in_course_status($user_id, $courseId)
+    {
         $result = Database::fetch_array(Database::query(
             "SELECT status FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
             WHERE c_id = '".Database::escape_string($courseId)."' AND user_id = ".Database::escape_string($user_id))
@@ -337,7 +350,8 @@ class CourseManager
      * @return mixed The tutor ID
      * @assert () === false
      */
-    public static function get_tutor_in_course_status($user_id, $courseId) {
+    public static function get_tutor_in_course_status($user_id, $courseId)
+    {
         $result = Database::fetch_array(Database::query(
                 "SELECT tutor_id FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
                 WHERE c_id = '".Database::escape_string($courseId)."' AND user_id = ".Database::escape_string($user_id))
@@ -480,7 +494,8 @@ class CourseManager
      * @return  bool    True on success, false on failure
      * @see add_user_to_course
      */
-    public static function subscribe_user($user_id, $course_code, $status = STUDENT, $session_id = 0) {
+    public static function subscribe_user($user_id, $course_code, $status = STUDENT, $session_id = 0)
+    {
 
         if ($user_id != strval(intval($user_id))) {
             return false; //detected possible SQL injection
@@ -1347,12 +1362,22 @@ class CourseManager
      * @param bool $add_link_to_profile
      * @return string
      */
-    public static function get_teacher_list_from_course_code_to_string($courseId, $separator = self::USER_SEPARATOR, $add_link_to_profile = false) {
+    public static function get_teacher_list_from_course_code_to_string($courseId, $separator = null, $add_link_to_profile = false)
+    {
         $teacher_list = self::get_teacher_list_from_course_code($courseId);
+
+        return self::formatUserListToString($teacher_list, $separator, $add_link_to_profile);
+    }
+
+    public static function formatUserListToString($userList, $separator = null, $add_link_to_profile = false)
+    {
+        if (empty($separator)) {
+            $separator = self::USER_SEPARATOR;
+        }
         $teacher_string = '';
         $list = array();
-        if (!empty($teacher_list)) {
-            foreach($teacher_list as $teacher) {
+        if (!empty($userList)) {
+            foreach($userList as $teacher) {
                 $teacher_name = api_get_person_name($teacher['firstname'], $teacher['lastname']);
                 if ($add_link_to_profile) {
                     $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&resizable=0&height=300&user_id='.$teacher['user_id'];
@@ -1474,7 +1499,7 @@ class CourseManager
      * @return  array   List of groups info
      */
     public static function get_group_list_of_course($course_code, $session_id = 0, $in_get_empty_group = 0) {
-        $course_info = Database::get_course_info($course_code);
+        $course_info = api_get_course_info($course_code);
         $course_id = $course_info['real_id'];
         $group_list = array();
         $session_id != 0 ? $session_condition = ' WHERE g.session_id IN(1,'.intval($session_id).')' : $session_condition = ' WHERE g.session_id = 0';
@@ -1521,7 +1546,6 @@ class CourseManager
      */
     public static function delete_course($code)
     {
-
         $table_course                       = Database::get_main_table(TABLE_MAIN_COURSE);
         $table_course_user                  = Database::get_main_table(TABLE_MAIN_COURSE_USER);
         $table_course_class                 = Database::get_main_table(TABLE_MAIN_COURSE_CLASS);
@@ -1532,17 +1556,17 @@ class CourseManager
         $table_course_survey_question       = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
         $table_course_survey_question_option= Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
 
-        $table_stats_hotpots        = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
-        $table_stats_attempt        = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-        $table_stats_exercises      = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-        $table_stats_access         = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ACCESS);
-        $table_stats_lastaccess     = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
-        $table_stats_course_access  = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
-        $table_stats_online         = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
-        $table_stats_default        = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
-        $table_stats_downloads      = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
-        $table_stats_links          = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LINKS);
-        $table_stats_uploads        = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_UPLOADS);
+        $table_stats_hotpots        = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
+        $table_stats_attempt        = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+        $table_stats_exercises      = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $table_stats_access         = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
+        $table_stats_lastaccess     = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
+        $table_stats_course_access  = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
+        $table_stats_online         = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+        $table_stats_default        = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
+        $table_stats_downloads      = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
+        $table_stats_links          = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
+        $table_stats_uploads        = Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS);
 
         $courseInfo = api_get_course_info($code);
 
@@ -1703,7 +1727,7 @@ class CourseManager
                     foreach ($row as $key => $value) {
                         $row_to_save[$key] = $key."='".Database::escape_string($row[$key])."'";
                     }
-                    $sql_dump .= "\nINSERT INTO $table SET ".implode(', ', $row_to_save).';';
+                    $sql_dump .= "INSERT INTO $table SET ".implode(', ', $row_to_save).';';
                 }
             }
         }
@@ -1764,10 +1788,10 @@ class CourseManager
                     $course_sort = $courses['sort'];
 
                     if ($counter == 0) {
-                        $sql = 'UPDATE '.$TABLECOURSUSER.' SET sort = sort+1 WHERE user_id= "'.$user_id.'" AND relation_type<>'.COURSE_RELATION_TYPE_RRHH.' AND user_course_cat="0" AND sort > "'.$course_sort.'"';
+                        $sql = 'UPDATE '.$TABLECOURSUSER.' SET sort = sort+1 WHERE user_id = "'.$user_id.'" AND relation_type<>'.COURSE_RELATION_TYPE_RRHH.' AND user_course_cat="0" AND sort > "'.$course_sort.'"';
                         $course_sort++;
                     } else {
-                        $sql = 'UPDATE '.$TABLECOURSUSER.' SET sort = sort+1 WHERE user_id= "'.$user_id.'" AND relation_type<>'.COURSE_RELATION_TYPE_RRHH.' AND user_course_cat="0" AND sort >= "'.$course_sort.'"';
+                        $sql = 'UPDATE '.$TABLECOURSUSER.' SET sort = sort+1 WHERE user_id = "'.$user_id.'" AND relation_type<>'.COURSE_RELATION_TYPE_RRHH.' AND user_course_cat="0" AND sort >= "'.$course_sort.'"';
                     }
 
                     Database::query($sql);
@@ -1937,7 +1961,7 @@ class CourseManager
         $codes = array();
         $tbl_course                 = Database::get_main_table(TABLE_MAIN_COURSE);
         $tbl_course_user            = Database::get_main_table(TABLE_MAIN_COURSE_USER);
-        $tbl_user_course_category   = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
+        $tbl_user_course_category   = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
 
         $special_course_list = self::get_special_course_list();
 
@@ -2032,29 +2056,6 @@ class CourseManager
         return $result;
     }
 
-    /**
-     * Get emails of tutors to course
-     * @param string Visual code
-     * @return array List of emails of tutors to course
-     * @author Carlos Vargas <carlos.vargas@dokeos.com>, Dokeos Latino
-     * */
-    public static function get_emails_of_tutors_to_course($courseId)
-    {
-        $list = array();
-        $courseId = intval($courseId);
-        $res = Database::query("SELECT user_id FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
-                WHERE c_id = '".$courseId."' AND status=1");
-        while ($list_users = Database::fetch_array($res)) {
-            $result = Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
-                    WHERE user_id=".$list_users['user_id']);
-            while ($row_user = Database::fetch_array($result)){
-                $name_teacher = api_get_person_name($row_user['firstname'], $row_user['lastname']);
-                $list[] = array($row_user['email'] => $name_teacher);
-            }
-        }
-        return $list;
-    }
-
     /**
      * Get coachs' emails by session
      * @param int session id
@@ -2442,8 +2443,8 @@ class CourseManager
             foreach ($courses_list as $courseId) {
                 $courseId = Database::escape_string($courseId);
                 $insert_sql = "INSERT IGNORE INTO $tbl_course_rel_user(c_id, user_id, status, relation_type) VALUES('$courseId', $hr_manager_id, '".DRH."', '".COURSE_RELATION_TYPE_RRHH."')";
-                Database::query($insert_sql);
-                if (Database::affected_rows()) {
+                $result = Database::query($insert_sql);
+                if (Database::affected_rows($result)) {
                     $affected_rows++;
                 }
             }
@@ -2731,7 +2732,7 @@ class CourseManager
     }
 
     public static function displayPersonalCourseCategories($user_id, $filter, $load_dirs, $getCount, $start = null, $maxPerPage = null) {
-        $tableUserCourseCategory = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
+        $tableUserCourseCategory = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
 
         // Table definitions
         $TABLECOURS                     = Database :: get_main_table(TABLE_MAIN_COURSE);
@@ -2890,7 +2891,8 @@ class CourseManager
         return $html;
     }
 
-    static function displayCourses($user_id, $filter, $load_dirs, $getCount, $start = null, $maxPerPage = null) {
+    static function displayCourses($user_id, $filter, $load_dirs, $getCount, $start = null, $maxPerPage = null)
+    {
 
         // Table definitions
         $TABLECOURS                     = Database :: get_main_table(TABLE_MAIN_COURSE);
@@ -3024,7 +3026,7 @@ class CourseManager
                 $course_title .= ' ('.$course_info['visual_code'].') ';
             }
             if (api_get_setting('display_teacher_in_courselist') == 'true') {
-                $teachers = CourseManager::get_teacher_list_from_course_code_to_string($course['real_id'], self::USER_SEPARATOR, true);
+                $teachers = $course_info['teacher_list_formatted'];
             }
 
             $params['link'] = $course_title_url;
@@ -3061,7 +3063,7 @@ class CourseManager
         $html = null;
 
         // Step 1: We get all the categories of the user
-        $tucc = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
+        $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
         $sql = "SELECT id, title FROM $tucc WHERE user_id='".$user_id."' ORDER BY sort ASC";
         $result = Database::query($sql);
         while ($row = Database::fetch_array($result)) {
@@ -3085,7 +3087,8 @@ class CourseManager
      * @param bool      Whether to show the document quick-loader or not
      *  @return void
      */
-    public static function display_courses_in_category($user_category_id, $load_dirs = false) {
+    public static function display_courses_in_category($user_category_id, $load_dirs = false)
+    {
         $user_id = api_get_user_id();
         // Table definitions
         $TABLECOURS                     = Database :: get_main_table(TABLE_MAIN_COURSE);
@@ -3223,11 +3226,11 @@ class CourseManager
      * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
      * @return array containing all the titles of the user defined courses with the id as key of the array
      */
-    function get_user_course_categories() {
-        global $_user;
+    function get_user_course_categories()
+    {
         $output = array();
-        $table_category = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
-        $sql = "SELECT * FROM ".$table_category." WHERE user_id='".Database::escape_string($_user['user_id'])."'";
+        $table_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
+        $sql = "SELECT * FROM ".$table_category." WHERE user_id='".Database::escape_string(api_get_user_id())."'";
         $result = Database::query($sql);
         while ($row = Database::fetch_array($result)) {
             $output[$row['id']] = $row['title'];
@@ -3397,8 +3400,8 @@ class CourseManager
      * if the course code doest not exist in the DB the same course code will be returned
      * @return string    wanted unused code
      */
-    public static function generate_nice_next_course_code($wanted_code) {
-        require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
+    public static function generate_nice_next_course_code($wanted_code)
+    {
         $course_code_ok = !self::course_code_exists($wanted_code);
         if (!$course_code_ok) {
            $wanted_code = self::generate_course_code($wanted_code);
@@ -3429,7 +3432,8 @@ class CourseManager
      * @param int session id
      * @return boolean
      */
-    public static function is_user_accepted_legal($user_id, $courseInfo, $session_id = null) {
+    public static function is_user_accepted_legal($user_id, $courseInfo, $session_id = null)
+    {
         $user_id    = intval($user_id);
         $course_code = $courseInfo['code'];
         $course_id = $courseInfo['real_id'];
@@ -3469,7 +3473,8 @@ class CourseManager
      * @param   string course code
      * @param   int session id
      */
-    function save_user_legal($user_id, $courseInfo, $session_id = null) {
+    function save_user_legal($user_id, $courseInfo, $session_id = null)
+    {
 
         $user_id    = intval($user_id);
         $course_code  = $courseInfo['code'];
@@ -3561,7 +3566,8 @@ class CourseManager
      * @param id    url id
      *
      **/
-    public static function update_course_ranking($course_id = null, $session_id = null, $url_id = null, $points_to_add = null, $add_access = true, $add_user = true) {
+    public static function update_course_ranking($course_id = null, $session_id = null, $url_id = null, $points_to_add = null, $add_access = true, $add_user = true)
+    {
         //Course catalog stats modifications see #4191
         $table_course_ranking       = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
 
@@ -3626,7 +3632,8 @@ class CourseManager
      *
      */
 
-    public static function add_course_vote($user_id, $vote, $course_id, $session_id = null, $url_id = null) {
+    public static function add_course_vote($user_id, $vote, $course_id, $session_id = null, $url_id = null)
+    {
         $table_user_course_vote     = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
         $course_id  = empty($course_id) ? api_get_course_int_id() : intval($course_id);
 
@@ -3704,7 +3711,8 @@ class CourseManager
      * @param   int number of days
      * @param   int number of hottest courses
      */
-    public static function return_hot_courses($days = 30, $limit = 5) {
+    public static function return_hot_courses($days = 30, $limit = 5)
+    {
         $urlId = api_get_current_access_url_id();
         $limit  = intval($limit);
 
@@ -3796,7 +3804,6 @@ class CourseManager
     }
 
     /**
-     *
      *
      * @return ResultSet
      */
@@ -3829,7 +3836,8 @@ class CourseManager
      * @param int Access URL ID (optional)
      * @return int Number of courses
      */
-    public static function count_courses($access_url_id = null) {
+    public static function count_courses($access_url_id = null)
+    {
         $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
         $table_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
         $sql = "SELECT count(id) FROM $table_course c";
@@ -3849,7 +3857,8 @@ class CourseManager
      * @param array  List of courses to which the user is subscribed (if not provided, will be generated)
      * @return mixed 'enter' for a link to go to the course or 'register' for a link to subscribe, or false if no access
      */
-    static function get_access_link_by_user($uid, $course, $user_courses = array()) {
+    static function get_access_link_by_user($uid, $course, $user_courses = array())
+    {
         if (empty($uid) or empty($course)) { return false; }
         if (empty($user_courses)) {
             // get the array of courses to which the user is subscribed
@@ -3911,7 +3920,8 @@ class CourseManager
      * @return array    An array with the needed keys ['currentCourseCode'], ['currentCourseId'], ['currentCourseDbName'], ['currentCourseRepository']
      * @todo Eliminate the global variables.
      */
-    static function define_course_keys($wanted_code, $prefix_for_all = '', $prefix_for_base_name = '', $prefix_for_path = '', $add_unique_prefix = false, $use_code_indepedent_keys = true) {
+    static function define_course_keys($wanted_code, $prefix_for_all = '', $prefix_for_base_name = '', $prefix_for_path = '', $add_unique_prefix = false, $use_code_indepedent_keys = true)
+    {
         global $prefixAntiNumber, $_configuration;
         $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
         $wanted_code = self::generate_course_code($wanted_code);
@@ -4186,7 +4196,13 @@ class CourseManager
         return $files;
     }
 
-    static function sort_pictures($files, $type) {
+    /**
+     * @param $files
+     * @param $type
+     * @return array
+     */
+    static function sort_pictures($files, $type)
+    {
         $pictures = array();
         foreach ($files as $key => $value){
             if (isset($value[$type]) && !empty($value[$type])) {
@@ -4200,7 +4216,8 @@ class CourseManager
      * Fills the course database with some required content and example content.
      * @version 1.2
      */
-    static function fill_db_course($course_id, $course_repository, $language, $fill_with_exemplary_content = null) {
+    static function fill_db_course($course_id, $course_repository, $language, $fill_with_exemplary_content = null)
+    {
         if (is_null($fill_with_exemplary_content)) {
             $fill_with_exemplary_content = api_get_setting('example_material_course_creation') != 'false';
         }
@@ -4626,7 +4643,8 @@ class CourseManager
      * @return int      0
      * @todo use an array called $params instead of lots of params
      */
-    static function register_course($params) {
+    static function register_course($params)
+    {
         global $error_msg, $firstExpirationDelay;
 
         $title              = $params['title'];
@@ -4732,10 +4750,9 @@ class CourseManager
                 subscribe       = '".intval($subscribe) . "',
                 unsubscribe     = '".intval($unsubscribe) . "',
                 visual_code     = '".Database :: escape_string($visual_code) . "'";
-            Database::query($sql);
-            //error_log($sql);
 
-            $course_id  = Database::get_last_insert_id();
+            Database::query($sql);
+            $course_id  = Database::insert_id();
 
             if ($course_id) {
 
@@ -4854,5 +4871,53 @@ class CourseManager
         }
     }
 
+    /**
+     * @return a list (array) of all courses.
+     * This function was originally in the Database class
+     */
+    public static function get_course_list()
+    {
+        $table = Database::get_main_table(TABLE_MAIN_COURSE);
+
+        return Database::store_result(Database::query("SELECT *, id as real_id FROM $table"));
+    }
+
+
+    /**
+     * Returns course code from a given gradebook category's id
+     * @param int  Category ID
+     * @return string  Course code
+     */
+    public static function get_course_by_category($category_id)
+    {
+        $category_id = intval($category_id);
+        $info = Database::fetch_array(
+            Database::query(
+                'SELECT course_code FROM '.Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY).' WHERE id='.$category_id
+            ),
+            'ASSOC'
+        );
+
+        return $info ? $info['course_code'] : false;
+    }
+
+    /**
+     * @param $courseId
+     * @return array
+     */
+    public static function getCourseSettings($courseId)
+    {
+        $settingTable = Database::get_course_table(TABLE_COURSE_SETTING);
+        $courseId = intval($courseId);
+        $sql = "SELECT * FROM $settingTable WHERE c_id = $courseId";
+        $result = Database::query($sql);
+        $settings = array();
+        if (Database::num_rows($result)) {
+            while ($row = Database::fetch_array($result, 'ASSOC')) {
+                $settings[$row['variable']] = $row;
+            }
+        }
+        return $settings;
+    }
 
 } //end class CourseManager

+ 54 - 54
main/inc/lib/course_description.lib.php

@@ -1,8 +1,8 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- * This file contains a class used like library provides functions for 
- * course description tool. It's also used like model to 
+ * This file contains a class used like library provides functions for
+ * course description tool. It's also used like model to
  * course_description_controller (MVC pattern)
  * @author Christian Fasanando <christian1827@gmail.com>
  * @package chamilo.course_description
@@ -27,10 +27,10 @@ class CourseDescription
 	 * Constructor
 	 */
 	public function __construct() {}
-	
+
 	/**
 	 * Returns an array of objects of type CourseDescription corresponding to a specific course, without session ids (session id = 0)
-	 * 
+	 *
 	 * @param int Course id
 	 * @return array Array of CourseDescriptions
 	 */
@@ -41,7 +41,7 @@ class CourseDescription
             $course_id = $course_info['real_id'];
         } else {
             return array();
-        }		
+        }
 		$t_course_desc = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
 		$sql = "SELECT * FROM $t_course_desc WHERE c_id = $course_id AND session_id = '0';";
 		$sql_result = Database::query($sql);
@@ -58,7 +58,7 @@ class CourseDescription
 		}
 		return $results;
 	}
-		
+
 
     /**
      * Get all data of course description by session id,
@@ -72,7 +72,7 @@ class CourseDescription
 		$sql = "SELECT * FROM $tbl_course_description WHERE c_id = $course_id $condition_session ORDER BY id ";
 		$rs = Database::query($sql);
 		$data = array();
-		while ($description = Database::fetch_array($rs)) {			
+		while ($description = Database::fetch_array($rs)) {
 			$data['descriptions'][$description['id']] = Security::remove_XSS($description, STUDENT);
 			//reload titles to ensure we have the last version (after edition)
 			//$data['default_description_titles'][$description['id']] = Security::remove_XSS($description['title'], STUDENT);
@@ -86,18 +86,18 @@ class CourseDescription
      * @return array
      */
 	public function get_description_history($description_type) {
-		$tbl_stats_item_property = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
+		$tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
 		$tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
-		
+
 		$description_id = $this->get_id_by_description_type($description_type);
 		$item_property_id = api_get_item_property_id($course_id, TOOL_COURSE_DESCRIPTION, $description_id);
-		
+
 		$course_id = api_get_course_int_id();
 
-		$sql = "SELECT tip.id, tip.course_id, tip.item_property_id, tip.title, tip.content, tip.progress, tip.lastedit_date, tip.session_id 
-				FROM $tbl_stats_item_property tip INNER JOIN $tbl_item_property ip 
+		$sql = "SELECT tip.id, tip.course_id, tip.item_property_id, tip.title, tip.content, tip.progress, tip.lastedit_date, tip.session_id
+				FROM $tbl_stats_item_property tip INNER JOIN $tbl_item_property ip
 				ON ip.tool = '".TOOL_COURSE_DESCRIPTION."' AND ip.id = tip.item_property_id
-				WHERE ip.c_id = $course_id AND tip.course_id = '$course_id' AND tip.session_id = '".intval($this->session_id)."' 
+				WHERE ip.c_id = $course_id AND tip.course_id = '$course_id' AND tip.session_id = '".intval($this->session_id)."'
 				ORDER BY tip.lastedit_date DESC";
 
 		$rs = Database::query($sql);
@@ -119,13 +119,13 @@ class CourseDescription
 	public function get_data_by_description_type($description_type, $course_code = '', $session_id = null) {
 		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
 		$course_id = api_get_course_int_id();
-		
+
 		if (!isset($session_id)) {
 			$session_id = $this->session_id;
-		}		
-		$condition_session = api_get_session_condition($session_id);		
+		}
+		$condition_session = api_get_session_condition($session_id);
 		if (!empty($course_code)) {
-			$course_info = api_get_course_info($course_code);	
+			$course_info = api_get_course_info($course_code);
             $course_id = $course_info['real_id'];
 		}
         $description_type = intval($description_type);
@@ -139,18 +139,18 @@ class CourseDescription
 		}
 		return $data;
 	}
-    
-   
+
+
     public function get_data_by_id($id, $course_code = '', $session_id = null) {
 		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
 		$course_id = api_get_course_int_id();
-		
+
 		if (!isset($session_id)) {
 			$session_id = $this->session_id;
-		}		
-		$condition_session = api_get_session_condition($session_id);		
+		}
+		$condition_session = api_get_session_condition($session_id);
 		if (!empty($course_code)) {
-			$course_info = api_get_course_info($course_code);	
+			$course_info = api_get_course_info($course_code);
             $course_id = $course_info['real_id'];
 		}
         $id = intval($id);
@@ -165,7 +165,7 @@ class CourseDescription
 		}
 		return $data;
 	}
-    
+
 
 	/**
      * Get maximum description type by session id, first you must set session_id properties with the object CourseDescription
@@ -174,7 +174,7 @@ class CourseDescription
 	public function get_max_description_type() {
 		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
         $course_id = api_get_course_int_id();
-        
+
 		$sql = "SELECT MAX(description_type) as MAX FROM $tbl_course_description WHERE c_id = $course_id AND session_id='".$this->session_id."'";
 		$rs  = Database::query($sql);
 		$max = Database::fetch_array($rs);
@@ -190,19 +190,19 @@ class CourseDescription
      * first you must set description_type, title, content, progress and session_id properties with the object CourseDescription
      * @return  int  affected rows
      */
-	public function insert() {		
+	public function insert() {
 		$course_id = api_get_course_int_id();
-		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);		
+		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
 		$sql = "INSERT IGNORE INTO $tbl_course_description SET
-				c_id 				=  $course_id, 
-				description_type	= '".intval($this->description_type)."', 
-				title 				= '".Database::escape_string($this->title)."', 
-				content 			= '".Database::escape_string($this->content)."', 
-				progress 			= '".intval($this->progress)."', 
+				c_id 				=  $course_id,
+				description_type	= '".intval($this->description_type)."',
+				title 				= '".Database::escape_string($this->title)."',
+				content 			= '".Database::escape_string($this->content)."',
+				progress 			= '".intval($this->progress)."',
 				session_id = '".intval($this->session_id)."' ";
-		Database::query($sql);
+		$result = Database::query($sql);
 		$last_id = Database::insert_id();
-		$affected_rows = Database::affected_rows();
+		$affected_rows = Database::affected_rows($result);
 		if ($last_id > 0) {
 			//insert into item_property
 			api_item_property_update(api_get_course_info(), TOOL_COURSE_DESCRIPTION, $last_id, 'CourseDescriptionAdded', api_get_user_id());
@@ -218,7 +218,7 @@ class CourseDescription
      * @return  int		affected rows
      */
 	public function insert_stats($description_type) {
-		$tbl_stats_item_property = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
+		$tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
 		$description_id = $this->get_id_by_description_type($description_type);
 		$course_id = api_get_real_course_id();
 		$course_code = api_get_course_id();
@@ -233,8 +233,8 @@ class CourseDescription
 			 	lastedit_date 		= '".date('Y-m-d H:i:s')."',
 			 	lastedit_user_id 	= '".api_get_user_id()."',
 			 	session_id			= '".intval($this->session_id)."'";
-		Database::query($sql);
-		$affected_rows = Database::affected_rows();
+		$result = Database::query($sql);
+		$affected_rows = Database::affected_rows($result);
 		return $affected_rows;
 	}
 
@@ -243,19 +243,19 @@ class CourseDescription
      * and session_id properties with the object CourseDescription
      * @return int	affected rows
      */
-	public function update() {		
-		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);	
-		$sql = "UPDATE $tbl_course_description SET  
-						title       = '".Database::escape_string($this->title)."', 
-						content     = '".Database::escape_string($this->content)."', 
-						progress    = '".$this->progress."' 
-				WHERE 	id          = '".intval($this->id)."' AND 
+	public function update() {
+		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
+		$sql = "UPDATE $tbl_course_description SET
+						title       = '".Database::escape_string($this->title)."',
+						content     = '".Database::escape_string($this->content)."',
+						progress    = '".$this->progress."'
+				WHERE 	id          = '".intval($this->id)."' AND
 						session_id  = '".$this->session_id."' AND
 						c_id = ".api_get_course_int_id()."
 						";
-		Database::query($sql);
-		$affected_rows = Database::affected_rows();
-		
+		$result = Database::query($sql);
+		$affected_rows = Database::affected_rows($result);
+
 		if ($this->id > 0) {
 			//insert into item_property
 			api_item_property_update(api_get_course_info(), TOOL_COURSE_DESCRIPTION, $this->id, 'CourseDescriptionUpdated', api_get_user_id());
@@ -268,11 +268,11 @@ class CourseDescription
      * @return int	affected rows
      */
 	public function delete() {
-		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);		
+		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
 		$course_id = api_get_course_int_id();
 		$sql = "DELETE FROM $tbl_course_description WHERE c_id = $course_id AND id = '".intval($this->id)."' AND session_id = '".intval($this->session_id)."'";
-		Database::query($sql);
-		$affected_rows = Database::affected_rows();
+		$result = Database::query($sql);
+		$affected_rows = Database::affected_rows($result);
 		if ($this->id > 0) {
 			//insert into item_property
 			api_item_property_update(api_get_course_info(), TOOL_COURSE_DESCRIPTION, $this->id, 'CourseDescriptionDeleted', api_get_user_id());
@@ -288,7 +288,7 @@ class CourseDescription
 	public function get_id_by_description_type($description_type) {
 		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
         $course_id = api_get_course_int_id();
-        
+
 		$sql = "SELECT id FROM $tbl_course_description WHERE c_id = $course_id AND description_type = '".intval($description_type)."'";
 		$rs  = Database::query($sql);
 		$row = Database::fetch_array($rs);
@@ -307,7 +307,7 @@ class CourseDescription
 	 	$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
 	 	$session_id = intval($session_id);
         $course_id = api_get_course_int_id();
-        
+
 		$sql = "SELECT progress FROM $tbl_course_description WHERE c_id = $course_id AND description_type = '".intval($description_type)."' AND session_id = '".intval($this->session_id)."' ";
 		$rs  = Database::query($sql);
 		$progress = '';
@@ -339,7 +339,7 @@ class CourseDescription
 		$default_description_titles[5]= get_lang('CourseMaterial');
 		$default_description_titles[6]= get_lang('HumanAndTechnicalResources');
 		$default_description_titles[7]= get_lang('Assessment');
-		
+
 		$default_description_titles[8]= get_lang('Other');
 		return $default_description_titles;
 	}
@@ -508,4 +508,4 @@ class CourseDescription
 	public function get_progress() {
 		return $this->progress;
 	}
-}
+}

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

@@ -107,7 +107,7 @@ class CourseRequestManager {
         if (!$result_sql) {
             return false;
         }
-        $last_insert_id = Database::get_last_insert_id();
+        $last_insert_id = Database::insert_id();
 
         // E-mail notifications.
 

+ 2 - 4
main/inc/lib/dashboard.lib.php

@@ -232,12 +232,10 @@ class DashboardManager {
 					$ins = "INSERT INTO $tbl_block(name, description, path, controller) VALUES ('$plugin_name', '$plugin_description', '$plugin_path', '$plugin_controller')";
 					Database::query($ins);
 				}
-				$affected_rows = Database::affected_rows();
+				// $affected_rows = Database::affected_rows();
 			}
-
 		}
-
-		return $affected_rows;
+		return true;
 	}
 
 	/**

File diff suppressed because it is too large
+ 149 - 644
main/inc/lib/database.lib.php


+ 0 - 1245
main/inc/lib/database.mysqli.lib.php

@@ -1,1245 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-/**
- *	This is a special version of the main database library for Chamilo focused
- *  on using the MySQLi driver instead of the MySQL driver.
- * To use it, make a backup copy of your database.lib.php file and replace
- * database.lib.php by this file.
- *	Include/require it in your code to use its functionality.
- *   Because this library contains all the basic database calls, it could be
- *   replaced by another library for say, PostgreSQL, to actually use Chamilo
- *   with another database (this is not ready yet because a lot of code still
- *   uses the MySQL database functions extensively).
- *
- *	@package chamilo.library
-
- */
-
-/*	Loading constants */
-require_once 'database.constants.inc.php';
-
-
-/**
- * DATABASE CLASS
- *      The class and its methods
- *	@package chamilo.library
- */
-class DatabaseSQLI {
-
-    /* Variable use only in the installation process to log errors. See the Database::query function */
-    static $log_queries = false;
-
-    /*
-        Accessor methods
-        Usually, you won't need these directly but instead
-        rely on of the get_xxx_table methods.
-    */
-
-    /**
-     *	Returns the name of the main database.
-     */
-    public static function get_main_database() {
-        global $_configuration;
-        return $_configuration['main_database'];
-    }
-
-    /**
-     *	Returns the name of the statistics database.
-     */
-    public static function get_statistic_database() {
-        global $_configuration;
-        return $_configuration['statistics_database'];
-    }
-
-    /**
-     *	Returns the name of the current course database.
-     *  @return    mixed   Glued database name of false if undefined
-     */
-    public static function get_current_course_database() {
-        $course_info = api_get_course_info();
-        if (empty($course_info['dbName'])) {
-            return false;
-        }
-        return $course_info['dbName'];
-    }
-
-    /**
-     *	Returns the glued name of the current course database.
-     *  @return    mixed   Glued database name of false if undefined
-     */
-    public static function get_current_course_glued_database() {
-        $course_info = api_get_course_info();
-        if (empty($course_info['dbNameGlu'])) {
-            return false;
-        }
-        return $course_info['dbNameGlu'];
-    }
-
-    /**
-     *	The glue is the string needed between database and table.
-     *	The trick is: in multiple databases, this is a period (with backticks).
-     *	In single database, this can be e.g. an underscore so we just fake
-     *	there are multiple databases and the code can be written independent
-     *	of the single / multiple database setting.
-     */
-    public static function get_database_glue() {
-        global $_configuration;
-        return $_configuration['db_glue'];
-    }
-
-    /**
-     *	Returns the database prefix.
-     *	All created COURSE databases are prefixed with this string.
-     *
-     *	TIP: This can be convenient e.g. if you have multiple system installations
-     *	on the same physical server.
-     */
-    public static function get_database_name_prefix() {
-        global $_configuration;
-        return $_configuration['db_prefix'];
-    }
-
-    /**
-     *	Returns the course table prefix for single database.
-     *	Not certain exactly when this is used.
-     *	Do research.
-     *	It's used in local.inc.php.
-     */
-    public static function get_course_table_prefix() {
-        global $_configuration;
-        return $_configuration['table_prefix'];
-    }
-
-    /*
-        Table name methods
-        Use these methods to get table names for queries,
-        instead of constructing them yourself.
-
-        Backticks automatically surround the result,
-        e.g. `COURSE_NAME`.`link`
-        so the queries can look cleaner.
-
-        Example:
-        $table = Database::get_course_table(TABLE_DOCUMENT);
-        $sql_query = "SELECT * FROM $table WHERE $condition";
-        $sql_result = Database::query($sql_query);
-        $result = Database::fetch_array($sql_result);
-    */
-
-    /**
-     * A more generic method than the other get_main_xxx_table methods,
-     * This one returns the correct complete name of any table of the main database of which you pass
-     * the short name as a parameter.
-     * Please, define table names as constants in this library and use them
-     * instead of directly using magic words in your tool code.
-     *
-     * @param string $short_table_name, the name of the table
-     */
-    public static function get_main_table($short_table_name) {
-        return self::format_table_name(self::get_main_database(), $short_table_name);
-    }
-
-    /**
-     * A more generic method than the older get_course_xxx_table methods,
-     * This one can return the correct complete name of any course table of which you pass
-     * the short name as a parameter.
-     * Please, define table names as constants in this library and use them
-     * instead of directly using magic words in your tool code.
-     *
-     * @param string $short_table_name, the name of the table
-     * @param string $database_name, optional, name of the course database
-     * - if you don't specify this, you work on the current course.
-     */
-    public static function get_course_table($short_table_name, $database_name = '') {
-        return self::format_glued_course_table_name(self::fix_database_parameter($database_name), $short_table_name);
-    }
-
-    /**
-     * This generic method returns the correct and complete name of any statistic table
-     * of which you pass the short name as a parameter.
-     * Please, define table names as constants in this library and use them
-     * instead of directly using magic words in your tool code.
-     *
-     * @param string $short_table_name, the name of the table
-     */
-    public static function get_statistic_table($short_table_name) {
-        return self::get_main_table($short_table_name);
-    }
-
-    /**
-     * This generic method returns the correct and complete name of any scorm
-     * table of which you pass the short name as a parameter. Please, define
-     * table names as constants in this library and use them instead of directly
-     * using magic words in your tool code.
-     *
-     * @param string $short_table_name, the name of the table
-     */
-    public static function get_user_personal_table($short_table_name) {
-        return self::get_main_table($short_table_name);
-    }
-
-    public static function get_course_chat_connected_table($database_name = '') {
-        return self::format_glued_course_table_name(self::fix_database_parameter($database_name), TABLE_CHAT_CONNECTED);
-    }
-
-    /*
-        Query methods
-        These methods execute a query and return the result(s).
-    */
-
-    /**
-     *	@return a list (array) of all courses.
-     * 	@todo shouldn't this be in the course.lib.php script?
-     */
-    public static function get_course_list() {
-        $table = self::get_main_table(TABLE_MAIN_COURSE);
-        return self::store_result(self::query("SELECT * FROM $table"));
-    }
-
-    /**
-     *	Returns an array with all database fields for the specified course.
-     *
-     *	@param the real (system) code of the course (ID from inside the main course table)
-     * 	@todo shouldn't this be in the course.lib.php script?
-     */
-    public static function get_course_info($course_code) {
-        $course_code = self::escape_string($course_code);
-        $table = self::get_main_table(TABLE_MAIN_COURSE);
-        $result = self::generate_abstract_course_field_names(
-            self::fetch_array(self::query("SELECT * FROM $table WHERE `code` = '$course_code'")));
-        return $result === false ? array('db_name' => '') : $result;
-    }
-
-    /**
-     * Returns course code from a given gradebook category's id
-     * @param int  Category ID
-     * @return string  Course code
-     * @todo move this function in a gradebook-related library
-     */
-    public static function get_course_by_category($category_id) {
-        $category_id = intval($category_id);
-        $info = self::fetch_array(self::query('SELECT course_code FROM '.self::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY).' WHERE id='.$category_id), 'ASSOC');
-        return $info ? $info['course_code'] : false;
-    }
-
-    /**
-     *	This method creates an abstraction layer between database field names
-     *	and field names expected in code.
-     *
-     *	This approach helps when changing database names.
-     *	It's also useful now to get rid of the 'franglais'.
-     *
-     *	@todo	add more array entries to abstract course info from field names
-     *	@author	Roan Embrechts
-     *
-     * 	@todo What's the use of this method. I think this is better removed.
-     * 		  There should be consistency in the variable names and the use throughout the scripts
-     * 		  for the database name we should consistently use or db_name or database (db_name probably being the better one)
-     */
-    public static function generate_abstract_course_field_names($result_array) {
-        $visual_code = isset($result_array['visual_code']) ? $result_array['visual_code'] : null;
-        $code        = isset($result_array['code']) ? $result_array['code'] : null;
-        $title       = isset($result_array['title']) ? $result_array['title'] : null;
-        $db_name     = isset($result_array['db_name']) ? $result_array['db_name'] : null;
-        $category_code = isset($result_array['category_code']) ? $result_array['category_code'] : null;
-        $result_array['official_code'] = $visual_code;
-        $result_array['visual_code']   = $visual_code;
-        $result_array['real_code']     = $code;
-        $result_array['system_code']   = $code;
-        $result_array['title']         = $title;
-        $result_array['database']      = $db_name;
-        $result_array['faculty']       = $category_code;
-        //$result_array['directory'] = $result_array['directory'];
-        /*
-        still to do: (info taken from local.inc.php)
-
-        $_course['id'          ]         = $cData['cours_id'         ]; //auto-assigned integer
-        $_course['name'        ]         = $cData['title'            ];
-        $_course['official_code']        = $cData['visual_code'        ]; // use in echo
-        $_course['sysCode'     ]         = $cData['code'             ]; // use as key in db
-        $_course['path'        ]         = $cData['directory'        ]; // use as key in path
-        $_course['dbName'      ]         = $cData['db_name'           ]; // use as key in db list
-        $_course['dbNameGlu'   ]         = $_configuration['table_prefix'] . $cData['dbName'] . $_configuration['db_glue']; // use in all queries
-        $_course['titular'     ]         = $cData['tutor_name'       ];
-        $_course['language'    ]         = $cData['course_language'   ];
-        $_course['extLink'     ]['url' ] = $cData['department_url'    ];
-        $_course['extLink'     ]['name'] = $cData['department_name'];
-        $_course['categoryCode']         = $cData['faCode'           ];
-        $_course['categoryName']         = $cData['faName'           ];
-
-        $_course['visibility'  ]         = (bool) ($cData['visibility'] == 2 || $cData['visibility'] == 3);
-        $_course['registrationAllowed']  = (bool) ($cData['visibility'] == 1 || $cData['visibility'] == 2);
-        */
-        return $result_array;
-    }
-
-    /**
-     *	This method creates an abstraction layer between database field names
-     *	and field names expected in code.
-     *
-     *	This helps when changing database names.
-     *	It's also useful now to get rid of the 'franglais'.
-     *
-     *	@todo add more array entries to abstract user info from field names
-     *	@author Roan Embrechts
-     *	@author Patrick Cool
-     *
-     * 	@todo what's the use of this function. I think this is better removed.
-     * 		There should be consistency in the variable names and the use throughout the scripts
-     */
-    public static function generate_abstract_user_field_names($result_array) {
-        $result_array['firstName'] 		= $result_array['firstname'];
-        $result_array['lastName'] 		= $result_array['lastname'];
-        $result_array['mail'] 			= $result_array['email'];
-        #$result_array['picture_uri'] 	= $result_array['picture_uri'];
-        #$result_array ['user_id']		= $result_array['user_id'];
-        return $result_array;
-    }
-
-    /**
-     * Counts the number of rows in a table
-     * @param string $table The table of which the rows should be counted
-     * @return int The number of rows in the given table.
-     */
-    public static function count_rows($table) {
-        $obj = self::fetch_object(self::query("SELECT COUNT(*) AS n FROM $table"));
-        return $obj->n;
-    }
-
-    /*
-        An intermediate API-layer between the system and the dabase server.
-    */
-
-    /**
-     * Returns the number of affected rows in the last database operation.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return int								Returns the number of affected rows on success, and -1 if the last query failed.
-     */
-    public static function affected_rows($connection = null) {
-        global $database_connection;
-        return $database_connection->affected_rows;
-    }
-
-    /**
-     * Closes non-persistent database connection.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return bool								Returns TRUE on success or FALSE on failure.
-     */
-    public static function close($connection = null) {
-        return self::use_default_connection($connection) ? mysqli::close() : mysqli::close($connection);
-    }
-
-    /**
-     * Opens a connection to a database server.
-     * @param array $parameters (optional)		An array that contains the necessary parameters for accessing the server.
-     * @return resource/boolean					Returns a database connection on success or FALSE on failure.
-     * Note: Currently the array could contain MySQL-specific parameters:
-     * $parameters['server'], $parameters['username'], $parameters['password'],
-     * $parameters['new_link'], $parameters['client_flags'], $parameters['persistent'].
-     * For details see documentation about the functions mysql_connect() and mysql_pconnect().
-     * @link http://php.net/manual/en/function.mysql-connect.php
-     * @link http://php.net/manual/en/function.mysql-pconnect.php
-     */
-    public static function connect($parameters = array()) {
-        global $database_connection;
-        // A MySQL-specific implementation.
-        if (!isset($parameters['server'])) {
-            $parameters['server'] = @ini_get('mysqli.default_host');
-            if (empty($parameters['server'])) {
-                $parameters['server'] = 'localhost:3306';
-            }
-        }
-        if (!isset($parameters['username'])) {
-            $parameters['username'] = @ini_get('mysqli.default_user');
-        }
-        if (!isset($parameters['password'])) {
-            $parameters['password'] = @ini_get('mysqli.default_pw');
-        }
-        $database_connection = $parameters['persistent']
-            ? new mysqli('p:'.$parameters['server'], $parameters['username'], $parameters['password'])
-            : new mysqli($parameters['server'], $parameters['username'], $parameters['password']);
-        if ($database_connection->connect_errno) {
-            error_log($database_connection->connect_errno());
-            return false;
-        } else {
-            return true;
-        }
-    }
-
-    /**
-     * Returns the error number from the last operation done on the database server.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return int								Returns the error number from the last database (operation, or 0 (zero) if no error occurred.
-     */
-    public static function errno($connection = null) {
-        return self::use_default_connection($connection) ? mysqli::mysqli_errno() : mysqli::mysqli_errno($connection);
-    }
-
-    /**
-     * Returns the error text from the last operation done on the database server.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return string							Returns the error text from the last database operation, or '' (empty string) if no error occurred.
-     */
-    public static function error($connection = null) {
-        return self::use_default_connection($connection) ? mysqli::mysqli_error() : mysqli::mysqli_error($connection);
-    }
-
-    /**
-     * Escapes a string to insert into the database as text
-     * @param string							The string to escape
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return string							The escaped string
-     * @author Yannick Warnier <yannick.warnier@dokeos.com>
-     * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
-     */
-    public static function escape_string($string, $connection = null) {
-        global $database_connection;
-        return get_magic_quotes_gpc()
-            ? ( $database_connection->escape_string(stripslashes($string)))
-            : ( $database_connection->escape_string($string));
-    }
-
-    /**
-     * Gets the array from a SQL result (as returned by Database::query) - help achieving database independence
-     * @param resource		The result from a call to sql_query (e.g. Database::query)
-     * @param string		Optional: "ASSOC","NUM" or "BOTH", as the constant used in mysqli_fetch_array.
-     * @return array		Array of results as returned by php
-     * @author Yannick Warnier <yannick.warnier@beeznest.com>
-     */
-    public static function fetch_array($result, $option = 'BOTH') {
-        return ($option == 'ASSOC') ? $result->fetch_array(MYSQLI_ASSOC) : ($option == 'NUM' ? $result->fetch_array(MYSQLI_NUM) : $result->fetch_array());
-    }
-
-    /**
-     * Gets an associative array from a SQL result (as returned by Database::query).
-     * This method is equivalent to calling Database::fetch_array() with 'ASSOC' value for the optional second parameter.
-     * @param resource $result	The result from a call to sql_query (e.g. Database::query).
-     * @return array			Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
-     */
-    public static function fetch_assoc($result) {
-        return $result->fetch_assoc();
-    }
-
-    /**
-     * Gets the next row of the result of the SQL query (as returned by Database::query) in an object form
-     * @param	resource	The result from a call to sql_query (e.g. Database::query)
-     * @param	string		Optional class name to instanciate
-     * @param	array		Optional array of parameters
-     * @return	object		Object of class StdClass or the required class, containing the query result row
-     * @author	Yannick Warnier <yannick.warnier@dokeos.com>
-     */
-    public static function fetch_object($result, $class = null, $params = null) {
-        return !empty($class) ? (is_array($params) ? $result->fetch_object($class, $params) : $result->fetch_object($class)) : $result->fetch_object();
-    }
-
-    /**
-     * Gets the array from a SQL result (as returned by Database::query) - help achieving database independence
-     * @param resource		The result from a call to sql_query (see Database::query()).
-     * @return array		Array of results as returned by php (mysql_fetch_row)
-     */
-    public static function fetch_row($result) {
-        return $result->fetch_row();
-    }
-
-    /**
-     * Frees all the memory associated with the provided result identifier.
-     * @return bool		Returns TRUE on success or FALSE on failure.
-     * Notes: Use this method if you are concerned about how much memory is being used for queries that return large result sets.
-     * Anyway, all associated result memory is automatically freed at the end of the script's execution.
-     */
-    public static function free_result($result) {
-        return $result->free_result();
-    }
-
-    /**
-     * Returns the database client library version.
-     * @return strung		Returns a string that represents the client library version.
-     */
-    public function get_client_info() {
-        return mysqli_get_client_info();
-    }
-
-    /**
-     * Returns a list of databases created on the server. The list may contain all of the
-     * available database names or filtered database names by using a pattern.
-     * @param string $pattern (optional)		A pattern for filtering database names as if it was needed for the SQL's LIKE clause, for example 'chamilo_%'.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return array							Returns in an array the retrieved list of database names.
-     */
-    public static function get_databases($pattern = '', $connection = null) {
-        $result = array();
-        $query_result = Database::query(!empty($pattern) ? "SHOW DATABASES LIKE '".self::escape_string($pattern, $connection)."'" : "SHOW DATABASES", $connection);
-        while ($row = Database::fetch_row($query_result)) {
-            $result[] = $row[0];
-        }
-        return $result;
-    }
-
-    /**
-     * Returns a list of the fields that a given table contains. The list may contain all of the available field names or filtered field names by using a pattern.
-     * By using a special option, this method is able to return an indexed list of fields' properties, where field names are keys.
-     * @param string $table						This is the examined table.
-     * @param string $pattern (optional)		A pattern for filtering field names as if it was needed for the SQL's LIKE clause, for example 'column_%'.
-     * @param string $database (optional)		The name of the targeted database. If it is omited, the current database is assumed, see Database::select_db().
-     * @param bool $including_properties (optional)	When this option is true, the returned result has the followong format:
-     * 												array(field_name_1 => array(0 => property_1, 1 => property_2, ...), fieald_name_2 => array(0 => property_1, ...), ...)
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return array							Returns in an array the retrieved list of field names.
-     */
-    public static function get_fields($table, $pattern = '', $database = '', $including_properties = false, $connection = null) {
-        $result = array();
-        $query = "SHOW COLUMNS FROM `".self::escape_string($table, $connection)."`";
-        if (!empty($database)) {
-            $query .= " FROM `".self::escape_string($database, $connection)."`";
-        }
-        if (!empty($pattern)) {
-            $query .= " LIKE '".self::escape_string($pattern, $connection)."'";
-        }
-        $query_result = Database::query($query, $connection);
-        if ($including_properties) {
-            // Making an indexed list of the fields and their properties.
-            while ($row = Database::fetch_row($query_result)) {
-                $result[$row[0]] = $row;
-            }
-        } else {
-            // Making a plain, flat list.
-            while ($row = Database::fetch_row($query_result)) {
-                $result[] = $row[0];
-            }
-        }
-        return $result;
-    }
-
-    /**
-     * Returns information about the type of the current connection and the server host name.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return string/boolean					Returns string data on success or FALSE on failure.
-     */
-    public function get_host_info($connection = null) {
-        return self::use_default_connection($connection) ? mysqli::mysqli_get_host_info() : mysqli::mysqli_get_host_info($connection);
-    }
-
-    /**
-     * Retrieves database client/server protocol version.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return int/boolean						Returns the protocol version on success or FALSE on failure.
-     */
-    public function get_proto_info($connection = null) {
-        return self::use_default_connection($connection) ? mysqli::mysqli_get_proto_info() : mysqli::mysqli_get_proto_info($connection);
-    }
-
-    /**
-     * Retrieves the database server version.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return string/boolean					Returns the MySQL server version on success or FALSE on failure.
-     */
-    public function get_server_info($connection = null) {
-        return self::use_default_connection($connection) ? mysqli::mysqli_get_server_info() : mysqli::mysqli_get_server_info($connection);
-    }
-
-    /**
-     * Returns a list of tables within a database. The list may contain all of the
-     * available table names or filtered table names by using a pattern.
-     * @param string $database (optional)		The name of the examined database. If it is omited, the current database is assumed, see Database::select_db().
-     * @param string $pattern (optional)		A pattern for filtering table names as if it was needed for the SQL's LIKE clause, for example 'access_%'.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return array							Returns in an array the retrieved list of table names.
-     */
-    public static function get_tables($database = '', $pattern = '', $connection = null) {
-        $result = array();
-        $query = "SHOW TABLES";
-        if (!empty($database)) {
-            $query .= " FROM `".self::escape_string($database, $connection)."`";
-        }
-        if (!empty($pattern)) {
-            $query .= " LIKE '".self::escape_string($pattern, $connection)."'";
-        }
-        $query_result = Database::query($query, $connection);
-        while ($row = Database::fetch_row($query_result)) {
-            $result[] = $row[0];
-        }
-        return $result;
-    }
-
-    /**
-     * Gets the ID of the last item inserted into the database
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return int								The last ID as returned by the DB function
-     * @comment This should be updated to use ADODB at some point
-     */
-    public static function insert_id($connection = null) {
-        global $database_connection;
-        return $database_connection->insert_id;
-    }
-
-    /**
-     * Gets the number of rows from the last query result - help achieving database independence
-     * @param resource		The result
-     * @return integer		The number of rows contained in this result
-     * @author Yannick Warnier <yannick.warnier@dokeos.com>
-     **/
-    public static function num_rows($result) {
-        return is_a($result,'mysqli_result') ? $result->num_rows : false;
-    }
-
-    /**
-     * Acts as the relative *_result() function of most DB drivers and fetches a
-     * specific line and a field
-     * @param	resource	The database resource to get data from
-     * @param	integer		The row number
-     * @param	string		Optional field name or number
-     * @result	mixed		One cell of the result, or FALSE on error
-     */
-    public static function result(&$resource, $row, $field = '') {
-        if (self::num_rows($resource) > 0) {
-            if (!empty($field)) {
-                $r = mysqli_data_seek($resource, $row);
-                return $r[$field];
-            } else {
-                return mysqli_data_seek($resource, $row);
-            }
-        } else { return null; }
-    }
-
-    /**
-     * This method returns a resource
-     * Documentation has been added by Arthur Portugal
-     * Some adaptations have been implemented by Ivan Tcholakov, 2009, 2010
-     * @author Olivier Brouckaert
-     * @param string $query						The SQL query
-     * @param resource $connection (optional)	The database server (MySQL) connection.
-     * 											If it is not specified, the connection opened by mysql_connect() is assumed.
-     * 											If no connection is found, the server will try to create one as if mysql_connect() was called with no arguments.
-     * 											If no connection is found or established, an E_WARNING level error is generated.
-     * @param string $file (optional)			On error it shows the file in which the error has been trigerred (use the "magic" constant __FILE__ as input parameter)
-     * @param string $line (optional)			On error it shows the line in which the error has been trigerred (use the "magic" constant __LINE__ as input parameter)
-     * @return resource							The returned result from the query
-     * Note: The parameter $connection could be skipped. Here are examples of this method usage:
-     * Database::query($query);
-     * $result = Database::query($query);
-     * Database::query($query, $connection);
-     * $result = Database::query($query, $connection);
-     * The following ways for calling this method are obsolete:
-     * Database::query($query, __FILE__, __LINE__);
-     * $result = Database::query($query, __FILE__, __LINE__);
-     * Database::query($query, $connection, __FILE__, __LINE__);
-     * $result = Database::query($query, $connection, __FILE__, __LINE__);
-     */
-    public static function query($query, $connection = null, $file = null, $line = null) {
-        global $database_connection;
-
-        $result = @$database_connection->query($query);
-        if ($database_connection->errno) {
-            $backtrace = debug_backtrace(); // Retrieving information about the caller statement.
-            if (isset($backtrace[0])) {
-                $caller = & $backtrace[0];
-            } else {
-                $caller = array();
-            }
-            if (isset($backtrace[1])) {
-                $owner = & $backtrace[1];
-            } else {
-                $owner = array();
-            }
-            if (empty($file)) {
-                $file = $caller['file'];
-            }
-            if (empty($line) && $line !== false) {
-                $line = $caller['line'];
-            }
-            $type = $owner['type'];
-            $function = $owner['function'];
-            $class = $owner['class'];
-            $server_type = api_get_setting('server_type');
-            if (!empty($line) && !empty($server_type) && $server_type != 'production') {
-                $info = '<pre>' .
-                    '<strong>DATABASE ERROR #'.self::errno($connection).':</strong><br /> ' .
-                    self::remove_XSS(self::error($connection)) . '<br />' .
-                    '<strong>QUERY       :</strong><br /> ' .
-                    self::remove_XSS($query) . '<br />' .
-                    '<strong>FILE        :</strong><br /> ' .
-                    (empty($file) ? ' unknown ' : $file) . '<br />' .
-                    '<strong>LINE        :</strong><br /> ' .
-                    (empty($line) ? ' unknown ' : $line) . '<br />';
-                if (empty($type)) {
-                    if (!empty($function)) {
-                        $info .= '<strong>FUNCTION    :</strong><br /> ' . $function;
-                    }
-                } else {
-                    if (!empty($class) && !empty($function)) {
-                        $info .= '<strong>CLASS       :</strong><br /> ' . $class . '<br />';
-                        $info .= '<strong>METHOD      :</strong><br /> ' . $function;
-                    }
-                }
-                $info .= '</pre>';
-                echo $info;
-            }
-
-            if (isset(self::$log_queries) && self::$log_queries) {
-                error_log("----------------  SQL error ---------------- ");
-                error_log($query);
-
-                error_log('error #'.self::errno($connection));
-                error_log('error: '.self::error($connection));
-
-                $info = 'FILE: ' .(empty($file) ? ' unknown ' : $file);
-                error_log($info);
-                $info = 'LINE: '.(empty($line) ? ' unknown ' : $line);
-                error_log($info);
-
-                if (empty($type)) {
-                    if (!empty($function)) {
-                        $info = 'FUNCTION: ' . $function;
-                        error_log($info);
-                    }
-                } else {
-                    if (!empty($class) && !empty($function)) {
-                        $info .= 'CLASS: ' . $class;
-                        error_log($info);
-                        $info .= 'METHOD: ' . $function;
-                        error_log($info);
-                    }
-                }
-                error_log("---------------- end ----------------");
-            }
-
-        }
-        return $result;
-    }
-
-    /**
-     * Selects a database.
-     * @param string $database_name				The name of the database that is to be selected.
-     * @param resource $connection (optional)	The database server connection, for detailed description see the method query().
-     * @return bool								Returns TRUE on success or FALSE on failure.
-     */
-    public static function select_db($database_name, $connection = null) {
-        global $database_connection;
-        $database_connection->select_db($database_name);
-        return !$database_connection->errno;
-        //return self::use_default_connection($connection) ? mysqli_select_db($connection, $database_name) : mysqli_select_db($connection, $database_name);
-    }
-
-    /**
-     * Stores a query result into an array.
-     *
-     * @author Olivier Brouckaert
-     * @param  resource $result - the return value of the query
-     * @param  option BOTH, ASSOC, or NUM
-     * @return array - the value returned by the query
-     */
-    public static function store_result($result, $option = 'BOTH') {
-        $array = array();
-        if ($result !== false) { // For isolation from database engine's behaviour.
-            while ($row = self::fetch_array($result, $option)) {
-                $array[] = $row;
-            }
-        }
-        return $array;
-    }
-
-    /*
-        Encodings and collations supported by MySQL database server
-    */
-
-    /**
-     * Checks whether a given encoding is supported by the database server.
-     * @param string $encoding	The encoding (a system conventional id, for example 'UTF-8') to be checked.
-     * @return bool				Returns a boolean value as a check-result.
-     * @author Ivan Tcholakov
-     */
-    public static function is_encoding_supported($encoding) {
-        static $supported = array();
-        if (!isset($supported[$encoding])) {
-            $supported[$encoding] = false;
-            if (strlen($db_encoding = self::to_db_encoding($encoding)) > 0) {
-                if (self::num_rows(self::query("SHOW CHARACTER SET WHERE Charset =  '".self::escape_string($db_encoding)."';")) > 0) {
-                    $supported[$encoding] = true;
-                }
-            }
-        }
-        return $supported[$encoding];
-    }
-
-    /**
-     * Constructs a SQL clause about default character set and default collation for newly created databases and tables.
-     * Example: Database::make_charset_clause('UTF-8', 'bulgarian') returns
-     *  DEFAULT CHARACTER SET `utf8` DEFAULT COLLATE `utf8_general_ci`
-     * @param string $encoding (optional)	The default database/table encoding (a system conventional id) to be used.
-     * @param string $language (optional)	Language (a system conventional id) used for choosing language sensitive collation (if it is possible).
-     * @return string						Returns the constructed SQL clause or empty string if $encoding is not correct or is not supported.
-     * @author Ivan Tcholakov
-     */
-    public static function make_charset_clause($encoding = null, $language = null) {
-        if (empty($encoding)) {
-            $encoding = api_get_system_encoding();
-        }
-        if (empty($language)) {
-            $language = api_get_interface_language();
-        }
-        $charset_clause = '';
-        if (self::is_encoding_supported($encoding)) {
-            $db_encoding = Database::to_db_encoding($encoding);
-            $charset_clause .= " DEFAULT CHARACTER SET `".$db_encoding."`";
-            $db_collation = Database::to_db_collation($encoding, $language);
-            if (!empty($db_collation)) {
-                $charset_clause .= " DEFAULT COLLATE `".$db_collation."`";
-            }
-        }
-        return $charset_clause;
-    }
-
-    /**
-     * Converts an encoding identificator to MySQL-specific encoding identifictor,
-     * i.e. 'UTF-8' --> 'utf8'.
-     * @param string $encoding	The conventional encoding identificator.
-     * @return string			Returns the corresponding MySQL-specific encoding identificator if any, otherwise returns NULL.
-     * @author Ivan Tcholakov
-     */
-    public static function to_db_encoding($encoding) {
-        static $result = array();
-        if (!isset($result[$encoding])) {
-            $result[$encoding] = null;
-            $encoding_map = & self::get_db_encoding_map();
-            foreach ($encoding_map as $key => $value) {
-                if (api_equal_encodings($encoding, $key)) {
-                    $result[$encoding] = $value;
-                    break;
-                }
-            }
-        }
-        return $result[$encoding];
-    }
-
-    /**
-     * Converts a MySQL-specific encoding identifictor to conventional encoding identificator,
-     * i.e. 'utf8' --> 'UTF-8'.
-     * @param string $encoding	The MySQL-specific encoding identificator.
-     * @return string			Returns the corresponding conventional encoding identificator if any, otherwise returns NULL.
-     * @author Ivan Tcholakov
-     */
-    public static function from_db_encoding($db_encoding) {
-        static $result = array();
-        if (!isset($result[$db_encoding])) {
-            $result[$db_encoding] = null;
-            $encoding_map = & self::get_db_encoding_map();
-            foreach ($encoding_map as $key => $value) {
-                if (strtolower($db_encoding) == $value) {
-                    $result[$db_encoding] = $key;
-                    break;
-                }
-            }
-        }
-        return $result[$db_encoding];
-    }
-
-    /**
-     * Chooses the default MySQL-specific collation from given encoding and language.
-     * @param string $encoding				A conventional encoding id, i.e. 'UTF-8'
-     * @param string $language (optional)	A conventional for the system language id, i.e. 'bulgarian'. If it is empty, the chosen collation is the default server value corresponding to the given encoding.
-     * @return string						Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
-     * @author Ivan Tcholakov
-     */
-    public static function to_db_collation($encoding, $language = null) {
-        static $result = array();
-        if (!isset($result[$encoding][$language])) {
-            $result[$encoding][$language] = null;
-            if (self::is_encoding_supported($encoding)) {
-                $db_encoding = self::to_db_encoding($encoding);
-                if (!empty($language)) {
-                    $lang = api_purify_language_id($language);
-                    $res = self::check_db_collation($db_encoding, $lang);
-                    if (empty($res)) {
-                        $db_collation_map = & self::get_db_collation_map();
-                        if (isset($db_collation_map[$lang])) {
-                            $res = self::check_db_collation($db_encoding, $db_collation_map[$lang]);
-                        }
-                    }
-                    if (empty($res)) {
-                        $res = self::check_db_collation($db_encoding, null);
-                    }
-                    $result[$encoding][$language] = $res;
-                } else {
-                    $result[$encoding][$language] = self::check_db_collation($db_encoding, null);
-                }
-            }
-        }
-        return $result[$encoding][$language];
-    }
-
-    /*
-        Private methods
-        You should not access these from outside the class
-        No effort is made to keep the names / results the same.
-    */
-
-    /**
-     *	Glues a course database.
-     *	glue format from local.inc.php.
-     */
-    private static function glue_course_database_name($database_name) {
-        return self::get_course_table_prefix().$database_name.self::get_database_glue();
-    }
-
-    /**
-     *	@param string $database_name, can be empty to use current course db
-     *
-     *	@return the glued parameter if it is not empty,
-     *	or the current course database (glued) if the parameter is empty.
-     */
-    private static function fix_database_parameter($database_name) {
-        if (empty($database_name)) {
-            $course_info = api_get_course_info();
-            return $course_info['dbNameGlu'];
-        }
-        return self::glue_course_database_name($database_name);
-    }
-
-    /**
-     *	Structures a course database and table name to ready them
-     *	for querying. The course database parameter is considered glued:
-     *	e.g. COURSE001`.`
-     */
-    private static function format_glued_course_table_name($database_name_with_glue, $table) {
-        return '`'.$database_name_with_glue.$table.'`';
-    }
-
-    /**
-     *	Structures a database and table name to ready them
-     *	for querying. The database parameter is considered not glued,
-     *	just plain e.g. COURSE001
-     */
-    private static function format_table_name($database, $table) {
-        return '`'.$database.'`.`'.$table.'`';
-    }
-
-    /**
-     * This private method is to be used by the other methods in this class for
-     * checking whether the input parameter $connection actually has been provided.
-     * If the input parameter connection is not a resource or if it is not FALSE (in case of error)
-     * then the default opened connection should be used by the called method.
-     * @param resource/boolean $connection	The checked parameter $connection.
-     * @return boolean						TRUE means that calling method should use the default connection.
-     * 										FALSE means that (valid) parameter $connection has been provided and it should be used.
-     */
-    private static function use_default_connection($connection) {
-        return !is_resource($connection) && $connection !== false;
-    }
-
-    /**
-     * This private method tackles the XSS injections. It is similar to Security::remove_XSS() and works always,
-     * including the time of initialization when the class Security has not been loaded yet.
-     * @param string	The input variable to be filtered from XSS, in this class it is expected to be a string.
-     * @return string	Returns the filtered string as a result.
-     */
-    private static function remove_XSS(& $var) {
-        return class_exists('Security') ? Security::remove_XSS($var) : @htmlspecialchars($var, ENT_QUOTES, api_get_system_encoding());
-    }
-
-    /**
-     * This private method encapsulates a table with relations between
-     * conventional and MuSQL-specific encoding identificators.
-     * @author Ivan Tcholakov
-     */
-    private static function & get_db_encoding_map() {
-        static $encoding_map = array(
-            'ARMSCII-8'    => 'armscii8',
-            'BIG5'         => 'big5',
-            'BINARY'       => 'binary',
-            'CP866'        => 'cp866',
-            'EUC-JP'       => 'ujis',
-            'EUC-KR'       => 'euckr',
-            'GB2312'       => 'gb2312',
-            'GBK'          => 'gbk',
-            'ISO-8859-1'   => 'latin1',
-            'ISO-8859-2'   => 'latin2',
-            'ISO-8859-7'   => 'greek',
-            'ISO-8859-8'   => 'hebrew',
-            'ISO-8859-9'   => 'latin5',
-            'ISO-8859-13'  => 'latin7',
-            'ISO-8859-15'  => 'latin1',
-            'KOI8-R'       => 'koi8r',
-            'KOI8-U'       => 'koi8u',
-            'SHIFT-JIS'    => 'sjis',
-            'TIS-620'      => 'tis620',
-            'US-ASCII'     => 'ascii',
-            'UTF-8'        => 'utf8',
-            'WINDOWS-1250' => 'cp1250',
-            'WINDOWS-1251' => 'cp1251',
-            'WINDOWS-1252' => 'latin1',
-            'WINDOWS-1256' => 'cp1256',
-            'WINDOWS-1257' => 'cp1257'
-        );
-        return $encoding_map;
-    }
-
-    /**
-     * A helper language id translation table for choosing some collations.
-     * @author Ivan Tcholakov
-     */
-    private static function & get_db_collation_map() {
-        static $db_collation_map = array(
-            'german' => 'german2',
-            'simpl_chinese' => 'chinese',
-            'trad_chinese' => 'chinese',
-            'turkce' => 'turkish'
-        );
-        return $db_collation_map;
-    }
-
-    /**
-     * Constructs a MySQL-specific collation and checks whether it is supported by the database server.
-     * @param string $db_encoding	A MySQL-specific encoding id, i.e. 'utf8'
-     * @param string $language		A MySQL-compatible language id, i.e. 'bulgarian'
-     * @return string				Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
-     * @author Ivan Tcholakov
-     */
-    private static function check_db_collation($db_encoding, $language) {
-        if (empty($db_encoding)) {
-            return null;
-        }
-        if (empty($language)) {
-            $result = self::fetch_array(self::query("SHOW COLLATION WHERE Charset = '".self::escape_string($db_encoding)."' AND  `Default` = 'Yes';"), 'NUM');
-            return $result ? $result[0] : null;
-        }
-        $collation = $db_encoding.'_'.$language.'_ci';
-        $query_result = self::query("SHOW COLLATION WHERE Charset = '".self::escape_string($db_encoding)."';");
-        while ($result = self::fetch_array($query_result, 'NUM')) {
-            if ($result[0] == $collation) {
-                return $collation;
-            }
-        }
-        return null;
-    }
-
-    /*
-        New useful DB functions
-    */
-
-    /**
-     * Experimental useful database insert
-     * @todo lot of stuff to do here
-     */
-    public static function insert($table_name, $attributes) {
-        if (empty($attributes) || empty($table_name)) {
-            return false;
-        }
-        $filtred_attributes = array();
-        foreach($attributes as $key => $value) {
-            $filtred_attributes[$key] = "'".self::escape_string($value)."'";
-        }
-        $params = array_keys($filtred_attributes); //@todo check if the field exists in the table we should use a describe of that table
-        $values = array_values($filtred_attributes);
-        if (!empty($params) && !empty($values)) {
-            $sql    = 'INSERT INTO '.$table_name.' ('.implode(',',$params).') VALUES ('.implode(',',$values).')';
-            $result = self::query($sql);
-            return  self::get_last_insert_id();
-        }
-        return false;
-    }
-
-    /**
-     * Experimental useful database finder
-     * @todo lot of stuff to do here
-    */
-
-    public static function select($columns, $table_name,  $conditions = array(), $type_result = 'all', $option = 'ASSOC') {
-        $conditions = self::parse_conditions($conditions);
-
-        //@todo we could do a describe here to check the columns ...
-        $clean_columns = '';
-        if (is_array($columns)) {
-            $clean_columns = implode(',', $columns);
-        } else {
-            if ($columns == '*') {
-                $clean_columns = '*';
-            } else {
-                $clean_columns = (string)$columns;
-            }
-        }
-
-
-        $sql    = "SELECT $clean_columns FROM $table_name $conditions";
-
-        $result = self::query($sql);
-        $array = array();
-        //if (self::num_rows($result) > 0 ) {
-        if ($type_result == 'all') {
-            while ($row = self::fetch_array($result, $option)) {
-                if (isset($row['id'])) {
-                    $array[$row['id']] = $row;
-                } else {
-                    $array[] = $row;
-                }
-            }
-        } else {
-            $array = self::fetch_array($result, $option);
-        }
-        return $array;
-    }
-
-    /**
-     * Parses WHERE/ORDER conditions i.e array('where'=>array('id = ?' =>'4'), 'order'=>'id DESC'))
-     * @param   array
-     * @todo lot of stuff to do here
-    */
-    static function parse_conditions($conditions) {
-        if (empty($conditions)) {
-            return '';
-        }
-        $return_value = '';
-        foreach ($conditions as $type_condition => $condition_data) {
-            $type_condition = strtolower($type_condition);
-             switch ($type_condition) {
-                case 'where':
-                    foreach ($condition_data as $condition => $value_array) {
-                        if (is_array($value_array)) {
-                            $clean_values = array();
-                            foreach($value_array as $item) {
-                                $item = Database::escape_string($item);
-                                $clean_values[]= $item;
-                            }
-                        } else {
-                            $value_array = Database::escape_string($value_array);
-                            $clean_values = $value_array;
-                        }
-                        if (!empty($condition) && $clean_values != '') {
-                            $condition = str_replace('%',"'@percentage@'", $condition); //replace "%"
-                            $condition = str_replace("'?'","%s", $condition);
-                            $condition = str_replace("?","%s", $condition);
-
-                            $condition = str_replace("@%s@","@-@", $condition);
-                            $condition = str_replace("%s","'%s'", $condition);
-                            $condition = str_replace("@-@","@%s@", $condition);
-
-                            //Treat conditons as string
-                            $condition = vsprintf($condition, $clean_values);
-                            $condition = str_replace('@percentage@','%', $condition); //replace "%"
-                            $where_return .= $condition;
-                        }
-                    }
-                    if (!empty($where_return)) {
-                        $return_value = " WHERE $where_return" ;
-                    }
-                    break;
-                case 'order':
-                    $order_array = $condition_data;
-
-                    if (!empty($order_array)) {
-                        // 'order' => 'id desc, name desc'
-                        $order_array = self::escape_string($order_array);
-                        $new_order_array = explode(',', $order_array);
-                        $temp_value = array();
-
-                        foreach($new_order_array as $element) {
-                            $element = explode(' ', $element);
-                            $element = array_filter($element);
-                            $element = array_values($element);
-
-                            if (!empty($element[1])) {
-                                $element[1] = strtolower($element[1]);
-                                $order = 'DESC';
-                                if (in_array($element[1], array('desc', 'asc'))) {
-                                    $order = $element[1];
-                                }
-                                $temp_value[]= $element[0].' '.$order.' ';
-                            } else {
-                                //by default DESC
-                                $temp_value[]= $element[0].' DESC ';
-                            }
-                        }
-                        if (!empty($temp_value)) {
-                            $return_value .= ' ORDER BY '.implode(', ', $temp_value);
-                        } else {
-                            //$return_value .= '';
-                        }
-                    }
-                    break;
-
-                case 'limit':
-                    $limit_array = explode(',', $condition_data);
-                    if (!empty($limit_array)) {
-                        if (count($limit_array) > 1) {
-                            $return_value .= ' LIMIT '.intval($limit_array[0]).' , '.intval($limit_array[1]);
-                        }  else {
-                            $return_value .= ' LIMIT '.intval($limit_array[0]);
-                        }
-                    }
-                break;
-
-            }
-        }
-        return $return_value;
-    }
-
-    public static function parse_where_conditions($coditions){
-        return self::parse_conditions(array('where'=>$coditions));
-    }
-
-    /**
-     * Experimental useful database update
-     * @todo lot of stuff to do here
-     */
-    public static function delete($table_name, $where_conditions) {
-        $result = false;
-        $where_return = self::parse_where_conditions($where_conditions);
-        $sql    = "DELETE FROM $table_name $where_return ";
-        $result = self::query($sql);
-        $affected_rows = self::affected_rows();
-        //@todo should return affected_rows for
-        return $affected_rows;
-    }
-
-
-    /**
-     * Experimental useful database update
-     * @todo lot of stuff to do here
-     */
-    public static function update($table_name, $attributes, $where_conditions = array()) {
-
-        if (!empty($table_name) && !empty($attributes)) {
-            $update_sql = '';
-            //Cleaning attributes
-            $count = 1;
-            foreach ($attributes as $key=>$value) {
-                $value = self::escape_string($value);
-                $update_sql .= "$key = '$value' ";
-                if ($count < count($attributes)) {
-                    $update_sql.=', ';
-                }
-                $count++;
-            }
-            if (!empty($update_sql)) {
-                //Parsing and cleaning the where conditions
-                $where_return = self::parse_where_conditions($where_conditions);
-                $sql    = "UPDATE $table_name SET $update_sql $where_return ";
-                //echo $sql; exit;
-                $result = self::query($sql);
-                $affected_rows = self::affected_rows();
-                return $affected_rows;
-            }
-        }
-        return false;
-    }
-
-     /*
-        DEPRECATED METHODS
-    */
-
-    /**
-     * @deprecated Use api_get_language_isocode($language) instead.
-     */
-    public static function get_language_isocode($language) {
-        return api_get_language_isocode($language);
-    }
-
-    /**
-     * @deprecated Use Database::insert_id() instead.
-     */
-    public static function get_last_insert_id() {
-        global $database_connection;
-        return $database_connection->insert_id($database_connection);
-    }
-
-}
-//end class Database

+ 477 - 138
main/inc/lib/diagnoser.lib.php

@@ -20,15 +20,17 @@ class Diagnoser
     /**
      * The status's
      */
-    const STATUS_OK 			= 1;
-    const STATUS_WARNING 		= 2;
-    const STATUS_ERROR 			= 3;
-    const STATUS_INFORMATION 	= 4;
+    const STATUS_OK          = 1;
+    const STATUS_WARNING     = 2;
+    const STATUS_ERROR       = 3;
+    const STATUS_INFORMATION = 4;
 
-    function __construct() {
+    function __construct()
+    {
     }
 
-    function show_html() {
+    function show_html()
+    {
 
         $sections = array('chamilo', 'php', 'mysql', 'webserver');
 
@@ -48,21 +50,21 @@ class Diagnoser
                 $html .= '<li>';
             }
             $params['section'] = $section;
-            $html .='<a href="system_status.php?section='.$section.'">'.get_lang($section).'</a></li>';
+            $html .= '<a href="system_status.php?section='.$section.'">'.get_lang($section).'</a></li>';
         }
 
         $html .= '</ul><div class="tab-pane">';
 
-        $data = call_user_func(array($this, 'get_' . $current_section . '_data'));
+        $data = call_user_func(array($this, 'get_'.$current_section.'_data'));
         echo $html;
         $table = new SortableTableFromArray($data, 1, 100);
 
-        $table->set_header(0,'', false);
-        $table->set_header(1,get_lang('Section'), false);
-        $table->set_header(2,get_lang('Setting'), false);
-        $table->set_header(3,get_lang('Current'), false);
-        $table->set_header(4,get_lang('Expected'), false);
-        $table->set_header(5,get_lang('Comment'), false);
+        $table->set_header(0, '', false);
+        $table->set_header(1, get_lang('Section'), false);
+        $table->set_header(2, get_lang('Setting'), false);
+        $table->set_header(3, get_lang('Current'), false);
+        $table->set_header(4, get_lang('Expected'), false);
+        $table->set_header(5, get_lang('Comment'), false);
 
         $table->display();
         echo '</div></div>';
@@ -72,21 +74,55 @@ class Diagnoser
      * Functions to get the data for the chamilo diagnostics
      * @return array of data
      */
-    function get_chamilo_data() {
-        $array = array();
-        $writable_folders = array('archive', 'courses', 'home', 'main/upload/users/', 'main/default_course_document/images/');
+    function get_chamilo_data()
+    {
+        $array            = array();
+        $writable_folders = array(
+            'archive',
+            'courses',
+            'home',
+            'main/upload/users/',
+            'main/default_course_document/images/'
+        );
         foreach ($writable_folders as $index => $folder) {
-            $writable = is_writable(api_get_path(SYS_PATH) . $folder);
-            $status = $writable ? self :: STATUS_OK : self :: STATUS_ERROR;
-            $array[] = $this->build_setting($status, '[FILES]', get_lang('IsWritable') . ': ' . $folder, 'http://be2.php.net/manual/en/function.is-writable.php', $writable, 1, 'yes_no', get_lang('DirectoryMustBeWritable'));
+            $writable = is_writable(api_get_path(SYS_PATH).$folder);
+            $status   = $writable ? self :: STATUS_OK : self :: STATUS_ERROR;
+            $array[]  = $this->build_setting(
+                $status,
+                '[FILES]',
+                get_lang('IsWritable').': '.$folder,
+                'http://be2.php.net/manual/en/function.is-writable.php',
+                $writable,
+                1,
+                'yes_no',
+                get_lang('DirectoryMustBeWritable')
+            );
         }
 
-        $exists = file_exists(api_get_path(SYS_CODE_PATH).'install');
-        $status = $exists ? self :: STATUS_WARNING : self :: STATUS_OK;
-        $array[] = $this->build_setting($status, '[FILES]', get_lang('DirectoryExists') . ': /install', 'http://be2.php.net/file_exists', $exists, 0, 'yes_no', get_lang('DirectoryShouldBeRemoved'));
+        $exists  = file_exists(api_get_path(SYS_CODE_PATH).'install');
+        $status  = $exists ? self :: STATUS_WARNING : self :: STATUS_OK;
+        $array[] = $this->build_setting(
+            $status,
+            '[FILES]',
+            get_lang('DirectoryExists').': /install',
+            'http://be2.php.net/file_exists',
+            $exists,
+            0,
+            'yes_no',
+            get_lang('DirectoryShouldBeRemoved')
+        );
 
         $app_version = api_get_setting('chamilo_database_version');
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[DB]', 'chamilo_database_version', '#', $app_version, 0, null,  'Chamilo DB version');
+        $array[]     = $this->build_setting(
+            self :: STATUS_INFORMATION,
+            '[DB]',
+            'chamilo_database_version',
+            '#',
+            $app_version,
+            0,
+            null,
+            'Chamilo DB version'
+        );
 
         return $array;
     }
@@ -95,127 +131,340 @@ class Diagnoser
      * Functions to get the data for the php diagnostics
      * @return array of data
      */
-    function get_php_data() {
+    function get_php_data()
+    {
         $array = array();
 
         // General Functions
 
         $version = phpversion();
-        $status = $version > REQUIRED_PHP_VERSION ? self :: STATUS_OK : self :: STATUS_ERROR;
-        $array[] = $this->build_setting($status, '[PHP]', 'phpversion()', 'http://www.php.net/manual/en/function.phpversion.php', phpversion(), '>= '.REQUIRED_PHP_VERSION, null, get_lang('PHPVersionInfo'));
+        $status  = $version > REQUIRED_PHP_VERSION ? self :: STATUS_OK : self :: STATUS_ERROR;
+        $array[] = $this->build_setting(
+            $status,
+            '[PHP]',
+            'phpversion()',
+            'http://www.php.net/manual/en/function.phpversion.php',
+            phpversion(),
+            '>= '.REQUIRED_PHP_VERSION,
+            null,
+            get_lang('PHPVersionInfo')
+        );
 
-        $setting = ini_get('output_buffering');
+        $setting     = ini_get('output_buffering');
         $req_setting = 1;
-        $status = $setting >= $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
-        $array[] = $this->build_setting($status, '[INI]', 'output_buffering', 'http://www.php.net/manual/en/outcontrol.configuration.php#ini.output-buffering', $setting, $req_setting, 'on_off', get_lang('OutputBufferingInfo'));
+        $status      = $setting >= $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
+        $array[]     = $this->build_setting(
+            $status,
+            '[INI]',
+            'output_buffering',
+            'http://www.php.net/manual/en/outcontrol.configuration.php#ini.output-buffering',
+            $setting,
+            $req_setting,
+            'on_off',
+            get_lang('OutputBufferingInfo')
+        );
 
-        $setting = ini_get('file_uploads');
+        $setting     = ini_get('file_uploads');
         $req_setting = 1;
-        $status = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
-        $array[] = $this->build_setting($status, '[INI]', 'file_uploads', 'http://www.php.net/manual/en/ini.core.php#ini.file-uploads', $setting, $req_setting, 'on_off', get_lang('FileUploadsInfo'));
+        $status      = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
+        $array[]     = $this->build_setting(
+            $status,
+            '[INI]',
+            'file_uploads',
+            'http://www.php.net/manual/en/ini.core.php#ini.file-uploads',
+            $setting,
+            $req_setting,
+            'on_off',
+            get_lang('FileUploadsInfo')
+        );
 
-        $setting = ini_get('magic_quotes_runtime');
+        $setting     = ini_get('magic_quotes_runtime');
         $req_setting = 0;
-        $status = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
-        $array[] = $this->build_setting($status, '[INI]', 'magic_quotes_runtime', 'http://www.php.net/manual/en/ini.core.php#ini.magic-quotes-runtime', $setting, $req_setting, 'on_off', get_lang('MagicQuotesRuntimeInfo'));
+        $status      = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
+        $array[]     = $this->build_setting(
+            $status,
+            '[INI]',
+            'magic_quotes_runtime',
+            'http://www.php.net/manual/en/ini.core.php#ini.magic-quotes-runtime',
+            $setting,
+            $req_setting,
+            'on_off',
+            get_lang('MagicQuotesRuntimeInfo')
+        );
 
-        $setting = ini_get('safe_mode');
+        $setting     = ini_get('safe_mode');
         $req_setting = 0;
-        $status = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_WARNING;
-        $array[] = $this->build_setting($status, '[INI]', 'safe_mode', 'http://www.php.net/manual/en/ini.core.php#ini.safe-mode', $setting, $req_setting, 'on_off', get_lang('SafeModeInfo'));
+        $status      = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_WARNING;
+        $array[]     = $this->build_setting(
+            $status,
+            '[INI]',
+            'safe_mode',
+            'http://www.php.net/manual/en/ini.core.php#ini.safe-mode',
+            $setting,
+            $req_setting,
+            'on_off',
+            get_lang('SafeModeInfo')
+        );
 
-        $setting = ini_get('register_globals');
+        $setting     = ini_get('register_globals');
         $req_setting = 0;
-        $status = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
-        $array[] = $this->build_setting($status, '[INI]', 'register_globals', 'http://www.php.net/manual/en/ini.core.php#ini.register-globals', $setting, $req_setting, 'on_off', get_lang('RegisterGlobalsInfo'));
+        $status      = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
+        $array[]     = $this->build_setting(
+            $status,
+            '[INI]',
+            'register_globals',
+            'http://www.php.net/manual/en/ini.core.php#ini.register-globals',
+            $setting,
+            $req_setting,
+            'on_off',
+            get_lang('RegisterGlobalsInfo')
+        );
 
-        $setting = ini_get('short_open_tag');
+        $setting     = ini_get('short_open_tag');
         $req_setting = 0;
-        $status = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_WARNING;
-        $array[] = $this->build_setting($status, '[INI]', 'short_open_tag', 'http://www.php.net/manual/en/ini.core.php#ini.short-open-tag', $setting, $req_setting, 'on_off', get_lang('ShortOpenTagInfo'));
+        $status      = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_WARNING;
+        $array[]     = $this->build_setting(
+            $status,
+            '[INI]',
+            'short_open_tag',
+            'http://www.php.net/manual/en/ini.core.php#ini.short-open-tag',
+            $setting,
+            $req_setting,
+            'on_off',
+            get_lang('ShortOpenTagInfo')
+        );
 
-        $setting = ini_get('magic_quotes_gpc');
+        $setting     = ini_get('magic_quotes_gpc');
         $req_setting = 0;
-        $status = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
-        $array[] = $this->build_setting($status, '[INI]', 'magic_quotes_gpc', 'http://www.php.net/manual/en/ini.core.php#ini.magic_quotes_gpc', $setting, $req_setting, 'on_off', get_lang('MagicQuotesGpcInfo'));
+        $status      = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
+        $array[]     = $this->build_setting(
+            $status,
+            '[INI]',
+            'magic_quotes_gpc',
+            'http://www.php.net/manual/en/ini.core.php#ini.magic_quotes_gpc',
+            $setting,
+            $req_setting,
+            'on_off',
+            get_lang('MagicQuotesGpcInfo')
+        );
 
-        $setting = ini_get('display_errors');
+        $setting     = ini_get('display_errors');
         $req_setting = 0;
-        $status = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_WARNING;
-        $array[] = $this->build_setting($status, '[INI]', 'display_errors', 'http://www.php.net/manual/en/ini.core.php#ini.display_errors', $setting, $req_setting, 'on_off', get_lang('DisplayErrorsInfo'));
+        $status      = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_WARNING;
+        $array[]     = $this->build_setting(
+            $status,
+            '[INI]',
+            'display_errors',
+            'http://www.php.net/manual/en/ini.core.php#ini.display_errors',
+            $setting,
+            $req_setting,
+            'on_off',
+            get_lang('DisplayErrorsInfo')
+        );
 
         $setting = ini_get('default_charset');
-        if ($setting == '')
+        if ($setting == '') {
             $setting = null;
+        }
         $req_setting = null;
-        $status = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
-        $array[] = $this->build_setting($status, '[INI]', 'default_charset', 'http://www.php.net/manual/en/ini.core.php#ini.default-charset', $setting, $req_setting, null, get_lang('DefaultCharsetInfo'));
+        $status      = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
+        $array[]     = $this->build_setting(
+            $status,
+            '[INI]',
+            'default_charset',
+            'http://www.php.net/manual/en/ini.core.php#ini.default-charset',
+            $setting,
+            $req_setting,
+            null,
+            get_lang('DefaultCharsetInfo')
+        );
 
-        $setting = ini_get('max_execution_time');
-        $req_setting = '300 (' . get_lang('minimum') . ')';
-        $status = $setting >= 300 ? self :: STATUS_OK : self :: STATUS_WARNING;
-        $array[] = $this->build_setting($status, '[INI]', 'max_execution_time', 'http://www.php.net/manual/en/ini.core.php#ini.max-execution-time', $setting, $req_setting, null, get_lang('MaxExecutionTimeInfo'));
+        $setting     = ini_get('max_execution_time');
+        $req_setting = '300 ('.get_lang('minimum').')';
+        $status      = $setting >= 300 ? self :: STATUS_OK : self :: STATUS_WARNING;
+        $array[]     = $this->build_setting(
+            $status,
+            '[INI]',
+            'max_execution_time',
+            'http://www.php.net/manual/en/ini.core.php#ini.max-execution-time',
+            $setting,
+            $req_setting,
+            null,
+            get_lang('MaxExecutionTimeInfo')
+        );
 
-        $setting = ini_get('max_input_time');
-        $req_setting = '300 (' . get_lang('minimum') . ')';
-        $status = $setting >= 300 ? self :: STATUS_OK : self :: STATUS_WARNING;
-        $array[] = $this->build_setting($status, '[INI]', 'max_input_time', 'http://www.php.net/manual/en/ini.core.php#ini.max-input-time', $setting, $req_setting, null, get_lang('MaxInputTimeInfo'));
+        $setting     = ini_get('max_input_time');
+        $req_setting = '300 ('.get_lang('minimum').')';
+        $status      = $setting >= 300 ? self :: STATUS_OK : self :: STATUS_WARNING;
+        $array[]     = $this->build_setting(
+            $status,
+            '[INI]',
+            'max_input_time',
+            'http://www.php.net/manual/en/ini.core.php#ini.max-input-time',
+            $setting,
+            $req_setting,
+            null,
+            get_lang('MaxInputTimeInfo')
+        );
 
-        $setting = ini_get('memory_limit');
+        $setting     = ini_get('memory_limit');
         $req_setting = '>= '.REQUIRED_MIN_MEMORY_LIMIT.'M';
-        $status = self :: STATUS_ERROR;
-        if ((float)$setting >= REQUIRED_MIN_MEMORY_LIMIT)
+        $status      = self :: STATUS_ERROR;
+        if ((float)$setting >= REQUIRED_MIN_MEMORY_LIMIT) {
             $status = self :: STATUS_OK;
-        $array[] = $this->build_setting($status, '[INI]', 'memory_limit', 'http://www.php.net/manual/en/ini.core.php#ini.memory-limit', $setting, $req_setting, null, get_lang('MemoryLimitInfo'));
+        }
+        $array[] = $this->build_setting(
+            $status,
+            '[INI]',
+            'memory_limit',
+            'http://www.php.net/manual/en/ini.core.php#ini.memory-limit',
+            $setting,
+            $req_setting,
+            null,
+            get_lang('MemoryLimitInfo')
+        );
 
-        $setting = ini_get('post_max_size');
+        $setting     = ini_get('post_max_size');
         $req_setting = '>= '.REQUIRED_MIN_POST_MAX_SIZE.'M';
-        $status = self :: STATUS_ERROR;
-        if ((float)$setting >= REQUIRED_MIN_POST_MAX_SIZE)
+        $status      = self :: STATUS_ERROR;
+        if ((float)$setting >= REQUIRED_MIN_POST_MAX_SIZE) {
             $status = self :: STATUS_OK;
-        $array[] = $this->build_setting($status, '[INI]', 'post_max_size', 'http://www.php.net/manual/en/ini.core.php#ini.post-max-size', $setting, $req_setting, null, get_lang('PostMaxSizeInfo'));
+        }
+        $array[] = $this->build_setting(
+            $status,
+            '[INI]',
+            'post_max_size',
+            'http://www.php.net/manual/en/ini.core.php#ini.post-max-size',
+            $setting,
+            $req_setting,
+            null,
+            get_lang('PostMaxSizeInfo')
+        );
 
-        $setting = ini_get('upload_max_filesize');
+        $setting     = ini_get('upload_max_filesize');
         $req_setting = '>= '.REQUIRED_MIN_UPLOAD_MAX_FILESIZE.'M';
-        $status = self :: STATUS_ERROR;
-        if ((float)$setting >= REQUIRED_UPLOAD_MAX_FILESIZE)
+        $status      = self :: STATUS_ERROR;
+        if ((float)$setting >= REQUIRED_UPLOAD_MAX_FILESIZE) {
             $status = self :: STATUS_OK;
-        $array[] = $this->build_setting($status, '[INI]', 'upload_max_filesize', 'http://www.php.net/manual/en/ini.core.php#ini.upload_max_filesize', $setting, $req_setting, null, get_lang('UploadMaxFilesizeInfo'));
+        }
+        $array[] = $this->build_setting(
+            $status,
+            '[INI]',
+            'upload_max_filesize',
+            'http://www.php.net/manual/en/ini.core.php#ini.upload_max_filesize',
+            $setting,
+            $req_setting,
+            null,
+            get_lang('UploadMaxFilesizeInfo')
+        );
 
-        $setting = ini_get('variables_order');
+        $setting     = ini_get('variables_order');
         $req_setting = 'GPCS';
-        $status = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
-        $array[] = $this->build_setting($status, '[INI]', 'variables_order', 'http://www.php.net/manual/en/ini.core.php#ini.variables-order', $setting, $req_setting, null, get_lang('VariablesOrderInfo'));
+        $status      = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_ERROR;
+        $array[]     = $this->build_setting(
+            $status,
+            '[INI]',
+            'variables_order',
+            'http://www.php.net/manual/en/ini.core.php#ini.variables-order',
+            $setting,
+            $req_setting,
+            null,
+            get_lang('VariablesOrderInfo')
+        );
 
-        $setting = ini_get('session.gc_maxlifetime');
+        $setting     = ini_get('session.gc_maxlifetime');
         $req_setting = '4320';
-        $status = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_WARNING;
-        $array[] = $this->build_setting($status, '[SESSION]', 'session.gc_maxlifetime', 'http://www.php.net/manual/en/ini.core.php#session.gc-maxlifetime', $setting, $req_setting, null, get_lang('SessionGCMaxLifetimeInfo'));
+        $status      = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_WARNING;
+        $array[]     = $this->build_setting(
+            $status,
+            '[SESSION]',
+            'session.gc_maxlifetime',
+            'http://www.php.net/manual/en/ini.core.php#session.gc-maxlifetime',
+            $setting,
+            $req_setting,
+            null,
+            get_lang('SessionGCMaxLifetimeInfo')
+        );
 
-        if (api_check_browscap()){$setting = true;}else{$setting=false;}
+        if (api_check_browscap()) {
+            $setting = true;
+        } else {
+            $setting = false;
+        }
         $req_setting = true;
-        $status = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_WARNING;
-        $array[] = $this->build_setting($status, '[INI]', 'browscap', 'http://www.php.net/manual/en/misc.configuration.php#ini.browscap', $setting, $req_setting, 'on_off', get_lang('BrowscapInfo'));
+        $status      = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_WARNING;
+        $array[]     = $this->build_setting(
+            $status,
+            '[INI]',
+            'browscap',
+            'http://www.php.net/manual/en/misc.configuration.php#ini.browscap',
+            $setting,
+            $req_setting,
+            'on_off',
+            get_lang('BrowscapInfo')
+        );
 
         //Extensions
-        $extensions = array('gd' 		=> array('link'=>'http://www.php.net/gd', 		'expected' => 1, 'comment' => get_lang('ExtensionMustBeLoaded')),
-        					'mysql' 	=> array('link'=>'http://www.php.net/mysql', 	'expected' => 1, 'comment' => get_lang('ExtensionMustBeLoaded')),
-        					'pcre' 		=> array('link'=>'http://www.php.net/pcre', 	'expected' => 1, 'comment' => get_lang('ExtensionMustBeLoaded')),
-        					'session' 	=> array('link'=>'http://www.php.net/session', 	'expected' => 1, 'comment' => get_lang('ExtensionMustBeLoaded')),
-        					'standard' 	=> array('link'=>'http://www.php.net/spl', 		'expected' => 1, 'comment' => get_lang('ExtensionMustBeLoaded')),
-        					'zlib' 		=> array('link'=>'http://www.php.net/zlib', 	'expected' => 1, 'comment' => get_lang('ExtensionMustBeLoaded')),
-        					'xsl' 		=> array('link'=>'http://be2.php.net/xsl', 		'expected' => 2, 'comment' => get_lang('ExtensionShouldBeLoaded')),
-        					'curl' 		=> array('link'=>'http://www.php.net/curl', 	'expected' => 2, 'comment' => get_lang('ExtensionShouldBeLoaded')),
+        $extensions = array(
+            'gd'       => array(
+                'link'     => 'http://www.php.net/gd',
+                'expected' => 1,
+                'comment'  => get_lang('ExtensionMustBeLoaded')
+            ),
+            'mysql'    => array(
+                'link'     => 'http://www.php.net/mysql',
+                'expected' => 1,
+                'comment'  => get_lang('ExtensionMustBeLoaded')
+            ),
+            'pcre'     => array(
+                'link'     => 'http://www.php.net/pcre',
+                'expected' => 1,
+                'comment'  => get_lang('ExtensionMustBeLoaded')
+            ),
+            'session'  => array(
+                'link'     => 'http://www.php.net/session',
+                'expected' => 1,
+                'comment'  => get_lang('ExtensionMustBeLoaded')
+            ),
+            'standard' => array(
+                'link'     => 'http://www.php.net/spl',
+                'expected' => 1,
+                'comment'  => get_lang('ExtensionMustBeLoaded')
+            ),
+            'zlib'     => array(
+                'link'     => 'http://www.php.net/zlib',
+                'expected' => 1,
+                'comment'  => get_lang('ExtensionMustBeLoaded')
+            ),
+            'xsl'      => array(
+                'link'     => 'http://be2.php.net/xsl',
+                'expected' => 2,
+                'comment'  => get_lang('ExtensionShouldBeLoaded')
+            ),
+            'curl'     => array(
+                'link'     => 'http://www.php.net/curl',
+                'expected' => 2,
+                'comment'  => get_lang('ExtensionShouldBeLoaded')
+            ),
         );
 
         foreach ($extensions as $extension => $data) {
-        	$url  	  		= $data['link'];
-        	$expected_value = $data['expected'];
-        	$comment 		= $data['comment'];
-
-            $loaded = extension_loaded($extension);
-            $status = $loaded ? self :: STATUS_OK : self :: STATUS_ERROR;
-            $array[] = $this->build_setting($status, '[EXTENSION]', get_lang('LoadedExtension') . ': ' . $extension, $url, $loaded, $expected_value, 'yes_no_optional', $comment);
+            $url            = $data['link'];
+            $expected_value = $data['expected'];
+            $comment        = $data['comment'];
+
+            $loaded  = extension_loaded($extension);
+            $status  = $loaded ? self :: STATUS_OK : self :: STATUS_ERROR;
+            $array[] = $this->build_setting(
+                $status,
+                '[EXTENSION]',
+                get_lang('LoadedExtension').': '.$extension,
+                $url,
+                $loaded,
+                $expected_value,
+                'yes_no_optional',
+                $comment
+            );
         }
 
         return $array;
@@ -225,18 +474,19 @@ class Diagnoser
      * Functions to get the data for the mysql diagnostics
      * @return array of data
      */
-    function get_mysql_data() {
+    function get_mysql_data()
+    {
         $array = array();
 
         // A note: Maybe it would be better if all "MySQL"-like variable names and words on the page to be replaced with "Database"-like ones.
 
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'mysql_get_host_info()', 'http://www.php.net/manual/en/function.mysql-get-host-info.php', Database::get_host_info(), null, null, get_lang('MysqlHostInfo'));
+        //$array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'mysql_get_host_info()', 'http://www.php.net/manual/en/function.mysql-get-host-info.php', Database::get_host_info(), null, null, get_lang('MysqlHostInfo'));
 
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'mysql_get_server_info()', 'http://www.php.net/manual/en/function.mysql-get-server-info.php', Database::get_server_info(), null, null, get_lang('MysqlServerInfo'));
+        ///$array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'mysql_get_server_info()', 'http://www.php.net/manual/en/function.mysql-get-server-info.php', Database::get_server_info(), null, null, get_lang('MysqlServerInfo'));
 
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'mysql_get_proto_info()', 'http://www.php.net/manual/en/function.mysql-get-proto-info.php', Database::get_proto_info(), null, null, get_lang('MysqlProtoInfo'));
+        //$array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'mysql_get_proto_info()', 'http://www.php.net/manual/en/function.mysql-get-proto-info.php', Database::get_proto_info(), null, null, get_lang('MysqlProtoInfo'));
 
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'mysql_get_client_info()', 'http://www.php.net/manual/en/function.mysql-get-client-info.php', Database::get_client_info(), null, null, get_lang('MysqlClientInfo'));
+        //$array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'mysql_get_client_info()', 'http://www.php.net/manual/en/function.mysql-get-client-info.php', Database::get_client_info(), null, null, get_lang('MysqlClientInfo'));
 
         return $array;
     }
@@ -245,29 +495,102 @@ class Diagnoser
      * Functions to get the data for the webserver diagnostics
      * @return array of data
      */
-    function get_webserver_data() {
+    function get_webserver_data()
+    {
         $array = array();
 
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[SERVER]', '$_SERVER["SERVER_NAME"]', 'http://be.php.net/reserved.variables.server', $_SERVER["SERVER_NAME"], null, null, get_lang('ServerNameInfo'));
+        $array[] = $this->build_setting(
+            self :: STATUS_INFORMATION,
+            '[SERVER]',
+            '$_SERVER["SERVER_NAME"]',
+            'http://be.php.net/reserved.variables.server',
+            $_SERVER["SERVER_NAME"],
+            null,
+            null,
+            get_lang('ServerNameInfo')
+        );
 
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[SERVER]', '$_SERVER["SERVER_ADDR"]', 'http://be.php.net/reserved.variables.server', $_SERVER["SERVER_ADDR"], null, null, get_lang('ServerAddessInfo'));
+        $array[] = $this->build_setting(
+            self :: STATUS_INFORMATION,
+            '[SERVER]',
+            '$_SERVER["SERVER_ADDR"]',
+            'http://be.php.net/reserved.variables.server',
+            $_SERVER["SERVER_ADDR"],
+            null,
+            null,
+            get_lang('ServerAddessInfo')
+        );
 
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[SERVER]', '$_SERVER["SERVER_PORT"]', 'http://be.php.net/reserved.variables.server', $_SERVER["SERVER_PORT"], null, null, get_lang('ServerPortInfo'));
+        $array[] = $this->build_setting(
+            self :: STATUS_INFORMATION,
+            '[SERVER]',
+            '$_SERVER["SERVER_PORT"]',
+            'http://be.php.net/reserved.variables.server',
+            $_SERVER["SERVER_PORT"],
+            null,
+            null,
+            get_lang('ServerPortInfo')
+        );
 
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[SERVER]', '$_SERVER["SERVER_SOFTWARE"]', 'http://be.php.net/reserved.variables.server', $_SERVER["SERVER_SOFTWARE"], null, null, get_lang('ServerSoftwareInfo'));
+        $array[] = $this->build_setting(
+            self :: STATUS_INFORMATION,
+            '[SERVER]',
+            '$_SERVER["SERVER_SOFTWARE"]',
+            'http://be.php.net/reserved.variables.server',
+            $_SERVER["SERVER_SOFTWARE"],
+            null,
+            null,
+            get_lang('ServerSoftwareInfo')
+        );
 
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[SERVER]', '$_SERVER["REMOTE_ADDR"]', 'http://be.php.net/reserved.variables.server', $_SERVER["REMOTE_ADDR"], null, null, get_lang('ServerRemoteInfo'));
+        $array[] = $this->build_setting(
+            self :: STATUS_INFORMATION,
+            '[SERVER]',
+            '$_SERVER["REMOTE_ADDR"]',
+            'http://be.php.net/reserved.variables.server',
+            $_SERVER["REMOTE_ADDR"],
+            null,
+            null,
+            get_lang('ServerRemoteInfo')
+        );
 
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[SERVER]', '$_SERVER["HTTP_USER_AGENT"]', 'http://be.php.net/reserved.variables.server', $_SERVER["HTTP_USER_AGENT"], null, null, get_lang('ServerUserAgentInfo'));
+        $array[] = $this->build_setting(
+            self :: STATUS_INFORMATION,
+            '[SERVER]',
+            '$_SERVER["HTTP_USER_AGENT"]',
+            'http://be.php.net/reserved.variables.server',
+            $_SERVER["HTTP_USER_AGENT"],
+            null,
+            null,
+            get_lang('ServerUserAgentInfo')
+        );
 
         /*$path = $this->manager->get_url(array('section' => Request :: get('section')));
         $request = $_SERVER["REQUEST_URI"];
         $status = $request != $path ? self :: STATUS_ERROR : self :: STATUS_OK;
         $array[] = $this->build_setting($status, '[SERVER]', '$_SERVER["REQUEST_URI"]', 'http://be.php.net/reserved.variables.server', $request, $path, null, get_lang('RequestURIInfo'));
         */
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[SERVER]', '$_SERVER["SERVER_PROTOCOL"]', 'http://be.php.net/reserved.variables.server', $_SERVER["SERVER_PROTOCOL"], null, null, get_lang('ServerProtocolInfo'));
+        $array[] = $this->build_setting(
+            self :: STATUS_INFORMATION,
+            '[SERVER]',
+            '$_SERVER["SERVER_PROTOCOL"]',
+            'http://be.php.net/reserved.variables.server',
+            $_SERVER["SERVER_PROTOCOL"],
+            null,
+            null,
+            get_lang('ServerProtocolInfo')
+        );
 
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[SERVER]', 'php_uname()', 'http://be2.php.net/php_uname', php_uname(), null, null, get_lang('UnameInfo'));
+        $array[] = $this->build_setting(
+            self :: STATUS_INFORMATION,
+            '[SERVER]',
+            'php_uname()',
+            'http://be2.php.net/php_uname',
+            php_uname(),
+            null,
+            null,
+            get_lang('UnameInfo')
+        );
 
         return $array;
     }
@@ -276,7 +599,17 @@ class Diagnoser
      * Additional functions needed for fast integration
      */
 
-    function build_setting($status, $section, $title, $url, $current_value, $expected_value, $formatter, $comment, $img_path = null) {
+    function build_setting(
+        $status,
+        $section,
+        $title,
+        $url,
+        $current_value,
+        $expected_value,
+        $formatter,
+        $comment,
+        $img_path = null
+    ) {
         switch ($status) {
             case self :: STATUS_OK :
                 $img = 'bullet_green.gif';
@@ -292,20 +625,20 @@ class Diagnoser
                 break;
         }
 
-        if (! $img_path) {
+        if (!$img_path) {
             $img_path = api_get_path(WEB_IMG_PATH);
         }
 
-        $image = '<img src="' . $img_path . $img . '" alt="' . $status . '" />';
-        $url = $this->get_link($title, $url);
+        $image = '<img src="'.$img_path.$img.'" alt="'.$status.'" />';
+        $url   = $this->get_link($title, $url);
 
-        $formatted_current_value = $current_value;
+        $formatted_current_value  = $current_value;
         $formatted_expected_value = $expected_value;
 
         if ($formatter) {
-            if (method_exists($this, 'format_' . $formatter)) {
-                $formatted_current_value = call_user_func(array($this, 'format_' . $formatter), $current_value);
-                $formatted_expected_value = call_user_func(array($this, 'format_' . $formatter), $expected_value);
+            if (method_exists($this, 'format_'.$formatter)) {
+                $formatted_current_value  = call_user_func(array($this, 'format_'.$formatter), $current_value);
+                $formatted_expected_value = call_user_func(array($this, 'format_'.$formatter), $expected_value);
             }
         }
 
@@ -318,37 +651,43 @@ class Diagnoser
      * @param $url
      * @return string the url
      */
-    function get_link($title, $url) {
-        return '<a href="' . $url . '" target="about:bank">' . $title . '</a>';
+    function get_link($title, $url)
+    {
+        return '<a href="'.$url.'" target="about:bank">'.$title.'</a>';
     }
 
-    function format_yes_no_optional($value) {
-    	$return = '';
-    	switch($value) {
-     		case 0:
-     			$return = get_lang('No');
-     			break;
-     		case 1:
-     			$return = get_lang('Yes');
-     			break;
-			case 2:
-				$return = get_lang('Optional');
-				break;
-    	}
-    	return $return;
+    function format_yes_no_optional($value)
+    {
+        $return = '';
+        switch ($value) {
+            case 0:
+                $return = get_lang('No');
+                break;
+            case 1:
+                $return = get_lang('Yes');
+                break;
+            case 2:
+                $return = get_lang('Optional');
+                break;
+        }
+
+        return $return;
 
     }
 
-    function format_yes_no($value) {
+    function format_yes_no($value)
+    {
         return $value ? get_lang('Yes') : get_lang('No');
     }
 
-    function format_on_off($value) {
+    function format_on_off($value)
+    {
         $value = intval($value);
         if ($value > 1) {
             // Greater than 1 values are shown "as-is", they may be interpreted as "On" later.
             return $value;
         }
+
         // These are the values 'On' and 'Off' used in the php-ini file. Translation (get_lang()) is not needed here.
         return $value ? 'On' : 'Off';
     }

+ 4 - 3
main/inc/lib/display.lib.php

@@ -114,6 +114,7 @@ class Display
         global $charset;
         $is_allowed_to_edit = api_is_allowed_to_edit();
         $moduleId = $tool;
+        $courseInfo = api_get_course_info();
         $introduction_section = null;
 
         if (api_get_setting('enable_tool_introduction') == 'true' || $tool == TOOL_COURSE_HOMEPAGE) {
@@ -146,7 +147,7 @@ class Display
             $thematic_description_html = '';
 
             if ($tool == TOOL_COURSE_HOMEPAGE) {
-                $thematic = new Thematic();
+                $thematic = new Thematic($courseInfo);
                 $thematic->set_course_int_id(api_get_course_int_id());
                 if (api_get_course_setting('display_info_advance_inside_homecourse') == '1') {
                     $information_title = get_lang('InfoAboutLastDoneAdvance');
@@ -205,7 +206,7 @@ class Display
             $introduction_section .= '<div class="row"><div class="span12">';
             $introduction_section .=  $thematic_description_html;
 
-            if (!empty($intro_content))	{
+            if (!empty($intro_content)) {
                 $introduction_section .=  $intro_content;
             }
             $introduction_section .=  '</div>';
@@ -1310,7 +1311,7 @@ class Display
      */
     public static function show_notification($course_info)
     {
-        $t_track_e_access = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
+        $t_track_e_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
         $user_id          = api_get_user_id();
 
         $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);

+ 54 - 54
main/inc/lib/events.lib.inc.php

@@ -19,7 +19,7 @@
 function event_open()
 {
     global $_configuration;
-    $TABLETRACK_OPEN = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_OPEN);
+    $TABLETRACK_OPEN = Database::get_main_table(TABLE_STATISTIC_TRACK_E_OPEN);
 
     // @getHostByAddr($_SERVER['REMOTE_ADDR']) : will provide host and country information
     // $_SERVER['HTTP_USER_AGENT'] :  will provide browser and os information
@@ -58,7 +58,7 @@ function event_open()
  */
 function event_login()
 {
-    $TABLETRACK_LOGIN = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+    $TABLETRACK_LOGIN = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
     $_user = api_get_user_info();
 
     $reallyNow = api_get_utc_datetime();
@@ -92,8 +92,8 @@ function event_login()
  */
 function event_access_course()
 {
-    $TABLETRACK_ACCESS = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ACCESS);
-    $TABLETRACK_LASTACCESS = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS); //for "what's new" notification
+    $TABLETRACK_ACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
+    $TABLETRACK_LASTACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS); //for "what's new" notification
 
     $id_session = api_get_session_id();
     $now = api_get_utc_datetime();
@@ -112,9 +112,9 @@ function event_access_course()
     // added for "what's new" notification
     $sql = "UPDATE $TABLETRACK_LASTACCESS  SET access_date = '$now'
         	WHERE access_user_id = $user_id AND c_id = '$courseId' AND access_tool IS NULL AND access_session_id=".$id_session;
-    Database::query($sql);
+    $result = Database::query($sql);
 
-    if (Database::affected_rows() == 0) {
+    if (Database::affected_rows($result) == 0) {
         $sql = "INSERT INTO $TABLETRACK_LASTACCESS (access_user_id, c_id, access_date, access_session_id)
         		VALUES (".$user_id.", '".$courseId."', '$now', '".$id_session."')";
         Database::query($sql);
@@ -140,8 +140,8 @@ function event_access_course()
 function event_access_tool($tool, $id_session = 0)
 {
     global $_configuration;
-    $TABLETRACK_ACCESS = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ACCESS);
-    $TABLETRACK_LASTACCESS = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS); //for "what's new" notification
+    $TABLETRACK_ACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
+    $TABLETRACK_LASTACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS); //for "what's new" notification
 
     $_course = api_get_course_info();
     $courseId = api_get_course_int_id();
@@ -179,8 +179,8 @@ function event_access_tool($tool, $id_session = 0)
     $sql = "UPDATE $TABLETRACK_LASTACCESS
         	SET access_date = '$reallyNow'
         	WHERE access_user_id = ".$user_id." AND c_id = '".$courseId."' AND access_tool = '".$tool."' AND access_session_id=".$id_session;
-    Database::query($sql);
-    if (Database::affected_rows() == 0) {
+    $result = Database::query($sql);
+    if (Database::affected_rows($result) == 0) {
         $sql = "INSERT INTO $TABLETRACK_LASTACCESS (access_user_id, c_id, access_tool, access_date, access_session_id)
         		VALUES (".$user_id.", '".$courseId."' , '$tool', '$reallyNow', $id_session)";
         Database::query($sql);
@@ -203,7 +203,7 @@ function event_access_tool($tool, $id_session = 0)
  */
 function event_download($doc_url)
 {
-    $tbl_stats_downloads = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
+    $tbl_stats_downloads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
     $doc_url = Database::escape_string($doc_url);
 
     $reallyNow = api_get_utc_datetime();
@@ -237,7 +237,7 @@ function event_download($doc_url)
  */
 function event_upload($doc_id)
 {
-    $TABLETRACK_UPLOADS = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_UPLOADS);
+    $TABLETRACK_UPLOADS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS);
     $courseCode = api_get_course_id();
     $reallyNow = api_get_utc_datetime();
     $user_id = api_get_user_id();
@@ -268,7 +268,7 @@ function event_upload($doc_id)
  */
 function event_link($link_id)
 {
-    $TABLETRACK_LINKS = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LINKS);
+    $TABLETRACK_LINKS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
     $reallyNow = api_get_utc_datetime();
     $user_id = api_get_user_id();
     $sql = "INSERT INTO ".$TABLETRACK_LINKS."
@@ -306,7 +306,7 @@ function event_link($link_id)
  */
 function update_event_exercise($exeid, $exo_id, $score, $weight, $session_id, $learnpath_id = 0, $learnpath_item_id = 0, $learnpath_item_view_id = 0, $duration = 0, $status = '', $remind_list = array() , $end_date = null) {
     global $debug;
-    $TABLETRACK_EXERCICES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $TABLETRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
 
     if ($debug) {
         error_log('Called to update_event_exercise');
@@ -377,7 +377,7 @@ function createEventExercise($exo_id)
     if (empty($exo_id) or (intval($exo_id) != $exo_id)) {
         return false;
     }
-    $tbl_track_exe = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $tbl_track_exe = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
     $tbl_exe = Database::get_course_table(TABLE_QUIZ_TEST);
     $uid = api_get_user_id();
     $course_id = api_get_course_int_id();
@@ -443,7 +443,7 @@ function saveExerciseAttempt($score, $answer, $question_id, $exe_id, $position,
     $now = api_get_utc_datetime();
     $user_id = api_get_user_id();
 
-    $TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 
     if ($debug) {
         error_log("----- entering saveExerciseAttempt() function ------");
@@ -517,7 +517,7 @@ function saveExerciseAttempt($score, $answer, $question_id, $exe_id, $position,
 
         $res = Database::query($sql);
         if (defined('ENABLED_LIVE_EXERCISE_TRACKING')) {
-            $recording_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
+            $recording_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
             if ($debug) {
                 error_log("Saving e attempt recording ");
             }
@@ -549,7 +549,7 @@ function saveExerciseAttemptHotspot($exe_id, $question_id, $answer_id, $correct,
         $correct = 0;
     }
 
-    $tbl_track_e_hotspot = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
+    $tbl_track_e_hotspot = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
     $sql = "INSERT INTO $tbl_track_e_hotspot (hotspot_user_id, c_id, hotspot_exe_id, hotspot_question_id, hotspot_answer_id, hotspot_correct, hotspot_coordinate)".
         " VALUES ('".api_get_user_id()."',".
         " '".api_get_course_int_id()."', ".
@@ -574,7 +574,7 @@ function saveExerciseAttemptHotspot($exe_id, $question_id, $answer_id, $correct,
  */
 function event_system($event_type, $event_value_type, $event_value, $datetime = null, $user_id = null, $course_code = null)
 {
-    $TABLETRACK_DEFAULT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
+    $TABLETRACK_DEFAULT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
 
     if (empty($event_type)) {
         return false;
@@ -710,7 +710,7 @@ function get_event_users($event_name)
 
 function get_events_by_user_and_type($user_id, $event_type)
 {
-    $TABLETRACK_DEFAULT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
+    $TABLETRACK_DEFAULT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
     $user_id = intval($user_id);
     $event_type = Database::escape_string($event_type);
 
@@ -822,7 +822,7 @@ function eventType_mod($etId, $users, $message, $subject)
 function getLastAttemptDateOfExercise($exe_id)
 {
     $exe_id = intval($exe_id);
-    $track_attempts = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $track_attempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $sql_track_attempt = 'SELECT max(tms) as last_attempt_date FROM '.$track_attempts.' WHERE exe_id='.$exe_id;
     $rs_last_attempt = Database::query($sql_track_attempt);
     $row_last_attempt = Database::fetch_array($rs_last_attempt);
@@ -838,7 +838,7 @@ function getLastAttemptDateOfExercise($exe_id)
 function getLatestQuestionIdFromAttempt($exe_id)
 {
     $exe_id = intval($exe_id);
-    $track_attempts = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $track_attempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $sql = 'SELECT question_id FROM '.$track_attempts.' WHERE exe_id='.$exe_id.' ORDER BY tms DESC LIMIT 1';
     $result = Database::query($sql);
     if (Database::num_rows($result)) {
@@ -859,7 +859,7 @@ function getLatestQuestionIdFromAttempt($exe_id)
  */
 function get_attempt_count($user_id, $exerciseId, $lp_id, $lp_item_id, $lp_item_view_id)
 {
-    $stat_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $stat_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
     $user_id = intval($user_id);
     $exerciseId = intval($exerciseId);
     $lp_id = intval($lp_id);
@@ -887,7 +887,7 @@ function get_attempt_count($user_id, $exerciseId, $lp_id, $lp_item_id, $lp_item_
 
 function get_attempt_count_not_finished($user_id, $exerciseId, $lp_id, $lp_item_id)
 {
-    $stat_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $stat_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
     $user_id = intval($user_id);
     $exerciseId = intval($exerciseId);
     $lp_id = intval($lp_id);
@@ -928,9 +928,9 @@ function delete_student_lp_events($user_id, $lp_id, $course, $session_id)
         $course_id = api_get_course_int_id();
     }
 
-    $track_e_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-    $track_attempts = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-    $recording_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
+    $track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $track_attempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $recording_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
 
     $user_id = intval($user_id);
     $lp_id = intval($lp_id);
@@ -984,7 +984,7 @@ function delete_student_lp_events($user_id, $lp_id, $course, $session_id)
  */
 function delete_all_incomplete_attempts($user_id, $exercise_id, $course_id, $session_id = 0)
 {
-    $track_e_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
     $user_id = intval($user_id);
     $exercise_id = intval($exercise_id);
     $course_id = intval($course_id);
@@ -1010,8 +1010,8 @@ function delete_all_incomplete_attempts($user_id, $exercise_id, $course_id, $ses
  */
 function get_all_exercise_results($exercise_id, $courseId, $session_id = 0, $load_question_list = true, $user_id = null)
 {
-    $TABLETRACK_EXERCICES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-    $TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $TABLETRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $courseId = intval($courseId);
     $exercise_id = intval($exercise_id);
     $session_id = intval($session_id);
@@ -1054,8 +1054,8 @@ function get_all_exercise_results($exercise_id, $courseId, $session_id = 0, $loa
  */
 function get_all_exercise_results_by_course($courseId, $session_id = 0, $get_count = true)
 {
-    $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-    $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $courseId = intval($courseId);
     $session_id = intval($session_id);
 
@@ -1098,8 +1098,8 @@ function get_all_exercise_results_by_course($courseId, $session_id = 0, $get_cou
  */
 function get_all_exercise_results_by_user($user_id, $courseId, $session_id = 0)
 {
-    $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-    $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $courseId = intval($courseId);
     $session_id = intval($session_id);
     $user_id = intval($user_id);
@@ -1137,9 +1137,9 @@ function get_all_exercise_results_by_user($user_id, $courseId, $session_id = 0)
  */
 function get_exercise_results_by_attempt($exe_id)
 {
-    $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-    $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-    $table_track_attempt_recording = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
+    $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $table_track_attempt_recording = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
     $exe_id = intval($exe_id);
 
     $sql = "SELECT * FROM $table_track_exercises WHERE status = '' AND exe_id = $exe_id";
@@ -1180,9 +1180,9 @@ function get_exercise_results_by_attempt($exe_id)
  */
 function getExerciseResultsByUser($user_id, $exercise_id, $courseId, $session_id = 0, $lp_id = 0, $lp_item_id = 0, $order = null)
 {
-    $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-    $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-    $table_track_attempt_recording = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
+    $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $table_track_attempt_recording = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
     $courseId = intval($courseId);
     $exercise_id = intval($exercise_id);
     $session_id = intval($session_id);
@@ -1234,7 +1234,7 @@ function getExerciseResultsByUser($user_id, $exercise_id, $courseId, $session_id
  */
 function count_exercise_attempts_by_user($user_id, $exercise_id, $courseId, $session_id = 0)
 {
-    $TABLETRACK_EXERCICES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $TABLETRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
     $courseId = intval($courseId);
     $exercise_id = intval($exercise_id);
     $session_id = intval($session_id);
@@ -1269,8 +1269,8 @@ function count_exercise_attempts_by_user($user_id, $exercise_id, $courseId, $ses
  */
 function get_best_exercise_results_by_user($exercise_id, $courseId, $session_id = 0)
 {
-    $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-    $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $courseId = intval($courseId);
     $exercise_id = intval($exercise_id);
     $session_id = intval($session_id);
@@ -1318,7 +1318,7 @@ function get_best_exercise_results_by_user($exercise_id, $courseId, $session_id
  */
 function get_best_attempt_exercise_results_per_user($user_id, $exercise_id, $courseId, $session_id = 0)
 {
-    $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
     $courseId = intval($courseId);
     $exercise_id = intval($exercise_id);
     $session_id = intval($session_id);
@@ -1368,8 +1368,8 @@ function get_best_attempt_exercise_results_per_user($user_id, $exercise_id, $cou
  */
 function count_exercise_result_not_validated($exercise_id, $courseId, $session_id = 0)
 {
-    $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-    $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
+    $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
     $courseId = intval($courseId);
     $session_id = intval($session_id);
     $exercise_id = intval($exercise_id);
@@ -1399,7 +1399,7 @@ function count_exercise_result_not_validated($exercise_id, $courseId, $session_i
  */
 function get_count_exercises_attempted_by_course($courseId, $session_id = 0)
 {
-    $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
     $courseId = intval($courseId);
     $session_id = intval($session_id);
 
@@ -1428,8 +1428,8 @@ function get_count_exercises_attempted_by_course($courseId, $session_id = 0)
  */
 function get_all_exercise_event_from_lp($exercise_id, $courseId, $session_id = 0)
 {
-    $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-    $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $courseId = intval($courseId);
     $exercise_id = intval($exercise_id);
     $session_id = intval($session_id);
@@ -1480,7 +1480,7 @@ function get_all_exercises_from_lp($lp_id, $course_id)
  */
 function get_comments($exe_id, $question_id)
 {
-    $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $sql = "SELECT teacher_comment FROM ".$table_track_attempt."
             WHERE exe_id='".Database::escape_string($exe_id)."' AND question_id = '".Database::escape_string($question_id)."'
             ORDER by question_id";
@@ -1495,7 +1495,7 @@ function get_comments($exe_id, $question_id)
  */
 function getAllExerciseEventByExeId($exe_id)
 {
-    $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $exe_id = intval($exe_id);
     $list = array();
 
@@ -1519,7 +1519,7 @@ function getAllExerciseEventByExeId($exe_id)
  */
 function delete_attempt($exe_id, $user_id, $courseId, $session_id, $question_id)
 {
-    $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 
     $exe_id = intval($exe_id);
     $user_id = intval($user_id);
@@ -1544,7 +1544,7 @@ function delete_attempt($exe_id, $user_id, $courseId, $session_id, $question_id)
  */
 function delete_attempt_hotspot($exe_id, $user_id, $courseId, $question_id)
 {
-    $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
+    $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
 
     $exe_id = intval($exe_id);
     $user_id = intval($user_id);
@@ -1594,7 +1594,7 @@ function getAnsweredQuestionsFromAttempt($exe_id, $objExercise)
  */
 function event_course_login($courseId, $user_id, $session_id)
 {
-    $course_tracking_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
+    $course_tracking_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
     $time = api_get_datetime();
 
     $courseId = Database::escape_string($courseId);

+ 16 - 16
main/inc/lib/exercise.lib.php

@@ -879,7 +879,7 @@ class ExerciseLib
     public static function get_exercise_track_exercise_info($exe_id)
     {
         $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
-        $TBL_TRACK_EXERCICES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $TBL_TRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
         $TBL_COURSE = Database::get_main_table(TABLE_MAIN_COURSE);
         $exe_id = intval($exe_id);
         $result_array = array();
@@ -989,7 +989,7 @@ class ExerciseLib
             $in_column = 'firstname';
         }
 
-        $TBL_TRACK_HOTPOTATOES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
+        $TBL_TRACK_HOTPOTATOES = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
         $TBL_USER = Database :: get_main_table(TABLE_MAIN_USER);
 
         $sql = "SELECT * FROM $TBL_TRACK_HOTPOTATOES thp
@@ -1042,9 +1042,9 @@ class ExerciseLib
         $TBL_GROUP_REL_USER = Database :: get_course_table(TABLE_GROUP_USER);
         $TBL_GROUP = Database :: get_course_table(TABLE_GROUP);
 
-        $TBL_TRACK_EXERCICES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-        $TBL_TRACK_HOTPOTATOES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
-        $TBL_TRACK_ATTEMPT_RECORDING = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
+        $TBL_TRACK_EXERCICES = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $TBL_TRACK_HOTPOTATOES = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
+        $TBL_TRACK_ATTEMPT_RECORDING = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
 
         $session_id_and = ' AND te.session_id = '.api_get_session_id().' ';
 
@@ -1903,8 +1903,8 @@ class ExerciseLib
      * */
     public static function get_student_stats_by_question($question_id, $exercise_id, $courseId, $session_id)
     {
-        $track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-        $track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+        $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 
         $question_id = intval($question_id);
         $exercise_id = intval($exercise_id);
@@ -1935,8 +1935,8 @@ class ExerciseLib
      */
     public static function get_number_students_question_with_answer_count($question_id, $exercise_id, $courseId, $session_id)
     {
-        $track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-        $track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+        $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
         $course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 
         $question_id = intval($question_id);
@@ -1973,8 +1973,8 @@ class ExerciseLib
      */
     public static function get_number_students_answer_hotspot_count($answer_id, $question_id, $exercise_id, $courseId, $session_id)
     {
-        $track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-        $track_hotspot = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
+        $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $track_hotspot = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
         $course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 
         $question_id = intval($question_id);
@@ -2020,8 +2020,8 @@ class ExerciseLib
      */
     public static function get_number_students_answer_count($answer_id, $question_id, $exercise_id, $courseId, $session_id, $question_type = null, $correct_answer = null, $current_answer = null)
     {
-        $track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-        $track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+        $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
         $course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 
         $question_id = intval($question_id);
@@ -2200,8 +2200,8 @@ class ExerciseLib
      */
     public static function get_number_students_finish_exercise($exercise_id, $courseId, $session_id)
     {
-        $track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-        $track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+        $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 
         $exercise_id = intval($exercise_id);
         $courseId = intval($courseId);
@@ -2287,7 +2287,7 @@ class ExerciseLib
      */
     public static function update_attempt_date($exeId, $last_attempt_date)
     {
-        $exercice_attemp_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+        $exercice_attemp_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
         $exeId = intval($exeId);
         $last_attempt_date = Database::escape_string($last_attempt_date);
         $sql = "UPDATE $exercice_attemp_table SET tms = '".api_get_utc_datetime()."'

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

@@ -106,7 +106,10 @@ class ExtraField extends Model
                 break;
         }
         $this->pageUrl  = 'extra_fields.php?type='.$this->type;
-        $this->pageName = get_lang(ucwords($this->type).'Fields'); // Example QuestionFields
+        // Example QuestionFields
+        // @todo error while installing
+        // $this->pageName = get_lang(ucwords($this->type).'Fields');
+        $this->pageName = ucwords($this->type).'Fields';
     }
 
     static function getValidExtraFieldTypes()
@@ -695,8 +698,6 @@ class ExtraField extends Model
                                 $field_details['field_display_text'].' '.get_lang('Comment')
                             );
 
-                            /*$extraField = new Extrafield($field_details['field_type']);
-                            $link = Display::url();*/
                             $extraFieldValue = new ExtraFieldValue($this->type);
                             $repo = $app['orm.em']->getRepository($extraFieldValue->entityName);
                             $repoLog = $app['orm.em']->getRepository('Gedmo\Loggable\Entity\LogEntry');
@@ -1092,7 +1093,6 @@ EOF;
 
     }
 
-
     public function return_form($url, $action)
     {
         $form = new FormValidator($this->type.'_field', 'post', $url);

+ 4 - 4
main/inc/lib/extra_field_value.lib.php

@@ -216,8 +216,8 @@ class ExtraFieldValue extends Model
                             $extraFieldValue->setFieldValue($params['field_value']);
                             $extraFieldValue->setFieldId($params['field_id']);
                             $extraFieldValue->setTms(api_get_utc_datetime(null, false, true));
-                            $app['orm.em']->persist($extraFieldValue);
-                            $app['orm.em']->flush();
+                            $app['orm.ems']['db_write']->persist($extraFieldValue);
+                            $app['orm.ems']['db_write']->flush();
                         }
                     }
 
@@ -270,8 +270,8 @@ class ExtraFieldValue extends Model
                             $extraFieldValue->setFieldValue($params['field_value']);
                             $extraFieldValue->setFieldId($params['field_id']);
                             $extraFieldValue->setTms(api_get_utc_datetime(null, false, true));
-                            $app['orm.em']->persist($extraFieldValue);
-                            $app['orm.em']->flush();
+                            $app['orm.ems']['db_write']->persist($extraFieldValue);
+                            $app['orm.ems']['db_write']->flush();
                         }
                     }
                 } else {

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

@@ -182,10 +182,10 @@ class FCKeditor
         $HtmlValue = htmlspecialchars( $this->Value ) ;
         $Html = '' ;
         if ( FCKeditor::IsCompatible() ) {
-            if ( api_get_setting('server_type') == 'test' )
+            /*if ( api_get_setting('server_type') == 'test' )
                 $File = 'fckeditor.original.html' ;
-            else
-                $File = 'fckeditor.html' ;
+            else*/
+            $File = 'fckeditor.html' ;
 
             $Link = "{$this->BasePath}editor/{$File}?InstanceName={$this->InstanceName}" ;
 

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

@@ -306,7 +306,7 @@ class GlossaryManager
             $glossary_id
         )."'";
         $result = Database::query($sql);
-        if ($result === false or Database::affected_rows() < 1) {
+        if ($result === false or Database::affected_rows($result) < 1) {
             return false;
         }
         //update item_property (delete)

+ 4 - 4
main/inc/lib/groupmanager.lib.php

@@ -420,9 +420,9 @@ class GroupManager
             "' , '",
             $group_ids
         )."')";
-        Database::query($sql2);
+        $result = Database::query($sql2);
 
-        return Database::affected_rows();
+        return Database::affected_rows($result);
     }
 
     /**
@@ -1477,7 +1477,7 @@ class GroupManager
         $user_id = Database::escape_string($user_id);
 
         $sql = "SELECT tutor_id FROM ".$course_user_table."
-		        WHERE user_id='".$user_id."' AND c_id ='".api_get_course_int_id()."'"."AND tutor_id=1";
+		        WHERE user_id = '".$user_id."' AND c_id ='".api_get_course_int_id()."'"."AND tutor_id=1";
         $db_result = Database::query($sql);
         $result = (Database::num_rows($db_result) > 0);
 
@@ -1967,4 +1967,4 @@ class GroupManager
         }
         $table->display();
     }
-}
+}

+ 20 - 12
main/inc/lib/internationalization.lib.php

@@ -159,17 +159,18 @@ function get_lang($variable, $reserved = null, $language = null)
         global $langstats;
         $langstats->add_use($variable, '');
     }
-    if (!isset ($used_lang_vars)) {
+    if (!isset($used_lang_vars)) {
         $used_lang_vars = array();
     }
 
     // Caching results from some API functions, for speed.
     static $initialized, $encoding, $is_utf8_encoding, $langpath, $test_server_mode, $show_special_markup;
+
     if (!isset($initialized)) {
         $encoding = api_get_system_encoding();
         $is_utf8_encoding = api_is_utf8($encoding);
         $langpath = api_get_path(SYS_LANG_PATH);
-        $test_server_mode = api_get_setting('server_type') == 'test';
+        $test_server_mode = $app['debug'] == true;
         //$test_server_mode = false;
         $show_special_markup = api_get_setting('hide_dltt_markup') != 'true' || $test_server_mode;
         $initialized = true;
@@ -196,7 +197,6 @@ function get_lang($variable, $reserved = null, $language = null)
         return $ret;
     }
 
-
     $_api_is_translated = false;
 
     // There is no cached translation, we have to retrieve it:
@@ -287,7 +287,7 @@ function get_lang($variable, $reserved = null, $language = null)
         $_api_is_translated = false;
         $langvar = $show_special_markup ? SPECIAL_OPENING_TAG.$variable.SPECIAL_CLOSING_TAG : $variable;
     }
-    //return $cache[$language][$variable] = $is_utf8_encoding ? $langvar : api_utf8_decode($langvar, $encoding);
+
     $ret = $cache[$language][$variable] = $is_utf8_encoding ? $langvar : api_utf8_decode($langvar, $encoding);
     $used_lang_vars[$variable.$lang_postfix] = $ret;
     return $ret;
@@ -418,13 +418,18 @@ function api_get_language_isocode($language = null, $default_code = 'en')
     if (empty($language)) {
         $language = api_get_interface_language(false, true);
     }
+
+    // Try session
+    /*if (empty($iso_code)) {
+        $iso_code = Session::read('_setting.api_get_language_isocode');
+    }*/
+
     if (!isset($iso_code[$language])) {
         if (!class_exists('Database')) {
             return $default_code; // This might happen, in case of calling this function early during the global initialization.
         }
-        $sql_result = Database::query(
-            "SELECT isocode FROM ".Database::get_main_table(TABLE_MAIN_LANGUAGE)." WHERE dokeos_folder = '$language'"
-        );
+        $sql = "SELECT isocode FROM ".Database::get_main_table(TABLE_MAIN_LANGUAGE)." WHERE dokeos_folder = '$language'";
+        $sql_result = Database::query($sql);
         if (Database::num_rows($sql_result)) {
             $result = Database::fetch_array($sql_result);
             $iso_code[$language] = trim($result['isocode']);
@@ -435,7 +440,9 @@ function api_get_language_isocode($language = null, $default_code = 'en')
         if (empty($iso_code[$language])) {
             $iso_code[$language] = $default_code;
         }
+        //Session::write('_setting.api_get_language_isocode', $iso_code);
     }
+
     return $iso_code[$language];
 }
 
@@ -597,12 +604,13 @@ function _api_get_timezone()
     // If allowed by the administrator
     $use_users_timezone = api_get_setting('use_users_timezone', 'timezones');
 
-    if ($use_users_timezone == 'true' && !empty($userId)) {
+    if ($use_users_timezone == 'true' && !empty($userId) && !api_is_anonymous()) {
+        $userInfo = api_get_user_info();
+        $extraFields = $userInfo['extra_fields'];
         // Get the timezone based on user preference, if it exists
-        $timezone_user = UserManager::get_extra_user_data_by_field($userId, 'timezone');
-
-        if (isset($timezone_user['timezone']) && $timezone_user['timezone'] != null) {
-            $to_timezone = $timezone_user['timezone'];
+        // $timezone_user = UserManager::get_extra_user_data_by_field($userId, 'timezone');
+        if (isset($extraFields['extra_timezone']) && $extraFields['extra_timezone'] != null) {
+            $to_timezone = $extraFields['extra_timezone'];
         }
     }
 

+ 5 - 10
main/inc/lib/login.lib.php

@@ -28,16 +28,11 @@ class Login
      */
     public static function get_user_account_list($user, $reset = false, $by_username = false)
     {
-        global $_configuration;
-        //$portal_url = $_configuration['root_web'];
         $portal_url = api_get_path(WEB_PATH);
 
-        if ($_configuration['multiple_access_urls']) {
-            $access_url_id = api_get_current_access_url_id();
-            if ($access_url_id != -1) {
-                $url = api_get_access_url($access_url_id);
-                $portal_url = $url['url'];
-            }
+        if (api_is_multiple_url_enabled()) {
+            $url = api_get_current_access_url_info();
+            $portal_url = $url['url'];
         }
 
         if ($reset) {
@@ -228,7 +223,7 @@ class Login
                 // a uid is given (log in succeeded)
                 $user_table = Database::get_main_table(TABLE_MAIN_USER);
                 $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
-                $track_e_login = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+                $track_e_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
 
                 $sql = "SELECT user.*, a.user_id is_admin, UNIX_TIMESTAMP(login.login_date) login_date
                         FROM $user_table
@@ -458,7 +453,7 @@ class Login
                     }
 
                     if ($save_course_access) {
-                        $course_tracking_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
+                        $course_tracking_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
 
                         /*
                          * When $_configuration['session_lifetime'] is too big 100 hours (in order to let users take exercises with no problems)

+ 107 - 158
main/inc/lib/main_api.lib.php

@@ -4,7 +4,7 @@
 /**
  * This is a code library for Chamilo.
  * It is included by default in every Chamilo file (through including the global.inc.php)
- *
+ * @todo transform this in a class!
  * @package chamilo.library
  */
 
@@ -255,7 +255,9 @@ define('WEB_TEMPLATE_PATH', 'WEB_TEMPLATE_PATH');
 define('SYS_TEMPLATE_PATH', 'SYS_TEMPLATE_PATH');
 
 // 1.10 new paths
+
 define('WEB_PUBLIC_PATH', 'WEB_PUBLIC_PATH');
+define('SYS_WEB_PATH', 'SYS_WEB_PATH');
 define('SYS_PATH', 'SYS_PATH');
 define('SYS_DATA_PATH', 'SYS_DATA_PATH');
 define('SYS_LOG_PATH', 'SYS_LOG_PATH');
@@ -474,7 +476,8 @@ define ('SKILL_TYPE_BOTH',          'both');
  * api_get_path(SYS_LOG_PATH)                   /var/www/chamilo/logs/
  * api_get_path(SYS_DATA_PATH)                  /var/www/chamilo/data/
  * api_get_path(SYS_CONFIG_PATH)                /var/www/chamilo/config/
-
+ * api_get_path(SYS_WEB_PATH)                   /var/www/chamilo/web/
+ *
  * api_get_path(SYS_COURSE_PATH)                /var/www/chamilo/data/courses/
  * api_get_path(SYS_CODE_PATH)                  /var/www/chamilo/main/
  * api_get_path(SYS_CSS_PATH)                   /var/www/chamilo/main/css
@@ -522,6 +525,7 @@ function api_get_path($path_type, $path = null) {
         WEB_PATH                => '',
         SYS_PATH                => '',
         SYS_DATA_PATH           => 'data/',
+        SYS_WEB_PATH            => 'web/',
         SYS_CONFIG_PATH         => 'config/',
         SYS_LOG_PATH            => 'logs/',
         REL_PATH                => '',
@@ -586,8 +590,7 @@ function api_get_path($path_type, $path = null) {
     if ($path_type == WEB_PATH) {
         if (isset($_configuration['access_url']) &&  $_configuration['access_url'] != 1) {
             //we look into the DB the function api_get_access_url
-            $url_info = api_get_access_url($_configuration['access_url']);
-
+            $url_info = api_get_current_access_url_info();
             $root_web = $url_info['active'] == 1 ? $url_info['url'] : $_configuration['root_web'];
             $load_new_config = true;
         }
@@ -604,7 +607,7 @@ function api_get_path($path_type, $path = null) {
         // Developers might use the function api_get_path() directly or indirectly (this is difficult to be traced), at the moment when
         // configuration has not been created yet. This is why this function should be upgraded to return correct results in this case.
 
-        //if (defined('SYSTEM_INSTALLATION') && SYSTEM_INSTALLATION) 
+        //if (defined('SYSTEM_INSTALLATION') && SYSTEM_INSTALLATION)
 
         if (empty($root_web)) {
 
@@ -655,6 +658,7 @@ function api_get_path($path_type, $path = null) {
 
         //update data path to get it from config file if defined
         $paths[SYS_DATA_PATH]           = $root_sys.'data/';
+        $paths[SYS_WEB_PATH]            = $root_sys.'web/';
         $paths[SYS_LOG_PATH]            = $root_sys.'logs/';
         $paths[SYS_CONFIG_PATH]         = $root_sys.'config/';
 
@@ -1088,7 +1092,7 @@ function api_protect_admin_script($allow_sessions_admins = false) {
 function api_block_anonymous_users($print_headers = true)
 {
     $_user = Session::read('_user');
-    if (!(isset($_user['user_id']) && $_user['user_id']) || api_is_anonymous($_user['user_id'], true)) {
+    if (!(isset($_user['user_id']) && $_user['user_id']) || api_is_anonymous($_user['user_id'])) {
         api_not_allowed($print_headers);
         return false;
     }
@@ -1168,6 +1172,7 @@ function api_get_user_id() {
  * @param int       User ID
  * @param boolean   Whether to get session courses or not - NOT YET IMPLEMENTED
  * @return array    Array of courses in the form [0]=>('code'=>xxx,'db'=>xxx,'dir'=>xxx,'status'=>d)
+ * @deprecated use the UserManager or CourseManager class
  */
 function api_get_user_courses($userid, $fetch_session = true) {
     if ($userid != strval(intval($userid))) { return array(); } //get out if not integer
@@ -1250,6 +1255,9 @@ function _api_format_user($user, $add_password = false) {
     $result['status']           = $user['status'];
     $result['auth_source']      = $user['auth_source'];
     $result['active']           = $user['active'];
+    $result['expiration_date']  = $user['expiration_date'];
+    $result['registration_date']  = $user['registration_date'];
+    $result['creator_id']       = $user['creator_id'];
 
     if (isset($user['username'])) {
         $result['username']         = $user['username'];
@@ -1311,6 +1319,8 @@ function _api_format_user($user, $add_password = false) {
         $result['password'] = $user['password'];
     }
 
+    $result['extra_fields'] = isset($user['extra_fields']) ? $user['extra_fields'] : array();
+
     return $result;
 }
 
@@ -1326,7 +1336,7 @@ function api_get_user_info($user_id = '', $check_if_user_is_online = false, $sho
         $_user = Session::read('_user');
         return _api_format_user($_user);
     }
-    $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)." WHERE user_id='".Database::escape_string($user_id)."'";
+    $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)." WHERE user_id = '".Database::escape_string($user_id)."'";
     $result = Database::query($sql);
     if (Database::num_rows($result) > 0) {
         $result_array = Database::fetch_array($result);
@@ -1346,7 +1356,6 @@ function api_get_user_info($user_id = '', $check_if_user_is_online = false, $sho
 		}
         $user = _api_format_user($result_array, $show_password);
 
-
         if ($add_extra_values) {
             $extra_field_values = new ExtraField('user');
             $user['extra_fields'] = $extra_field_values->get_handler_extra_data($user_id);
@@ -1417,14 +1426,20 @@ function api_get_course_path($course_code = null) {
  */
 function api_get_course_setting($setting_name, $course_code = null) {
     $course_info = api_get_course_info($course_code);
-	$table 		 = Database::get_course_table(TABLE_COURSE_SETTING);
-    $setting_name = Database::escape_string($setting_name);
-    if (!empty($course_info['real_id']) && !empty($setting_name)) {
-        $sql = "SELECT value FROM $table WHERE c_id = {$course_info['real_id']} AND variable = '$setting_name'";
-        $res = Database::query($sql);
-        if (Database::num_rows($res) > 0) {
-            $row = Database::fetch_array($res);
-            return $row['value'];
+
+    if (isset($course_info['settings']) && isset($course_info['settings'][$setting_name])) {
+        return $course_info['settings'][$setting_name]['value'];
+    } else {
+        //var_dump($course_info);
+        $table 		 = Database::get_course_table(TABLE_COURSE_SETTING);
+        $setting_name = Database::escape_string($setting_name);
+        if (!empty($course_info['real_id']) && !empty($setting_name)) {
+            $sql = "SELECT value FROM $table WHERE c_id = {$course_info['real_id']} AND variable = '$setting_name'";
+            $res = Database::query($sql);
+            if (Database::num_rows($res) > 0) {
+                $row = Database::fetch_array($res);
+                return $row['value'];
+            }
         }
     }
     return -1;
@@ -1495,7 +1510,8 @@ function api_get_cidreq($add_session_id = true, $add_group_id = true) {
  * particular course, not specially the current one.
  * @todo    Same behaviour as api_get_user_info so that api_get_course_id becomes absolete too.
  */
-function api_get_course_info($course_code = null, $add_extra_values = false) {
+function api_get_course_info($course_code = null, $add_extra_values = false, $addCourseSettings = false)
+{
     if (!empty($course_code)) {
         $course_code        = Database::escape_string($course_code);
         $course_table       = Database::get_main_table(TABLE_MAIN_COURSE);
@@ -1505,6 +1521,7 @@ function api_get_course_info($course_code = null, $add_extra_values = false) {
                  LEFT JOIN $course_cat_table
                  ON course.category_code =  course_category.code
                  WHERE course.code = '$course_code'";
+
         $result = Database::query($sql);
         $_course = array();
         if (Database::num_rows($result) > 0) {
@@ -1514,6 +1531,14 @@ function api_get_course_info($course_code = null, $add_extra_values = false) {
                 $extra_field_values = new ExtraField('course');
                 $course_data['extra_fields'] = $extra_field_values->get_handler_extra_data($course_code);
             }
+
+            if ($addCourseSettings) {
+                $course_data['settings'] = CourseManager::getCourseSettings($course_data['id']);
+            }
+
+            $course_data['teacher_list'] = CourseManager::get_teacher_list_from_course_code($course_data['id']);
+            $course_data['teacher_list_formatted'] = CourseManager::formatUserListToString($course_data['teacher_list'], null, true);
+
             $_course = api_format_course_array($course_data);
         }
         return $_course;
@@ -1558,6 +1583,11 @@ function api_get_course_info_by_id($id = null, $add_extra_values = false) {
     return $_course;
 }
 
+/**
+ * Sets the course array
+ * @param array  $course_data course info
+ * @return array
+ */
 function api_format_course_array($course_data) {
 
     if (empty($course_data)) {
@@ -1607,7 +1637,7 @@ function api_format_course_array($course_data) {
     $_course['registration_code']     = !empty($course_data['registration_code']) ? sha1($course_data['registration_code']) : null;
     $_course['disk_quota']            = $course_data['disk_quota'];
     $_course['course_public_url']     = api_get_path(WEB_COURSE_PATH).$course_data['directory'].'/index.php';
-    $_course['course_web_public_url']     = api_get_path(WEB_PUBLIC_PATH).'courses/'.$course_data['directory'].'/';
+    $_course['course_web_public_url'] = api_get_path(WEB_PUBLIC_PATH).'courses/'.$course_data['directory'].'/';
     $_course['course_sys_data']       = api_get_path(SYS_DATA_PATH).'courses/'.$course_data['directory'].'/';
 
     $_course['user_status_in_course'] = CourseManager::get_user_in_course_status(api_get_user_id(), $_course['code']);
@@ -1618,9 +1648,12 @@ function api_format_course_array($course_data) {
         $url_image = api_get_path(WEB_IMG_PATH).'without_picture.png';
     }
     $_course['course_image'] = $url_image;
+    $_course['extra_fields'] = isset($course_data['extra_fields']) ? $course_data['extra_fields'] : array();
+    $_course['settings']     = isset($course_data['settings']) ? $course_data['settings'] : array();
+    $_course['teacher_list'] = isset($course_data['teacher_list']) ? $course_data['teacher_list'] : array();
+    $_course['teacher_list_formatted'] = isset($course_data['teacher_list_formatted']) ? $course_data['teacher_list_formatted'] : array();
 
     return $_course;
-
 }
 
 /* STRING MANAGEMENT */
@@ -2403,6 +2436,7 @@ function api_is_course_session_coach($user_id, $courseId, $session_id)
  * Checks whether the current user is a course or session coach
  * @param int - optional, session id
  * @param string - optional, course code
+ * @todo this function is called many times and hits in the DB
  * @return boolean True if current user is a course or session coach
  */
 function api_is_coach($session_id = 0, $courseId = null) {
@@ -2451,8 +2485,8 @@ function api_is_coach($session_id = 0, $courseId = null) {
 	if (!empty($session_id)) {
 	    $sql = "SELECT DISTINCT id
 	         	FROM $session_table
-	         	WHERE   session.id_coach =  '".$user_id."' AND
-                        id = '$session_id'";
+	         	WHERE session.id_coach =  '".$user_id."' AND
+                      id = '$session_id'";
 	    $result = Database::query($sql);
 	    if (!empty($sessionIsCoach)) {
 	    	$sessionIsCoach = array_merge($sessionIsCoach , Database::store_result($result));
@@ -2460,7 +2494,8 @@ function api_is_coach($session_id = 0, $courseId = null) {
 	    	$sessionIsCoach = Database::store_result($result);
 	    }
 	}
-    return (count($sessionIsCoach) > 0);
+    $result = count($sessionIsCoach) > 0;
+    return $result;
 }
 
 /**
@@ -2943,6 +2978,7 @@ function api_not_found($print_headers = false) {
  */
 function api_not_allowed($print_headers = false, $message = null) {
     global $app;
+
     if (api_get_setting('sso_authentication') === 'true') {
         global $osso;
         if ($osso) {
@@ -2988,6 +3024,7 @@ function api_not_allowed($print_headers = false, $message = null) {
     $app['template']->assign('content', $msg);
     $app['allowed'] = true;
 
+
     if (($user_id!=0 && !api_is_anonymous()) && (!isset($course) || $course == -1) && empty($_GET['cidReq'])) {
         // if the access is not authorized and there is some login information
         // but the cidReq is not found, assume we are missing course data and send the user
@@ -3291,9 +3328,9 @@ function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $us
                     WHERE $filter";
     }
 
-    Database::query($sql);
+    $result = Database::query($sql);
     // Insert if no entries are found (can only happen in case of $lastedit_type switch is 'default').
-    if (Database::affected_rows() == 0) {
+    if (Database::affected_rows($result) == 0) {
         $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool,ref,insert_date,insert_user_id,lastedit_date,lastedit_type,   lastedit_user_id, to_user_id, to_group_id, visibility, start_visible, end_visible, id_session)
                 VALUES ($course_id, '$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_user_id', '$to_group_id', '$visibility', '$start_visible', '$end_visible', '$session_id')";
 
@@ -3363,7 +3400,7 @@ function api_get_item_property_id($course_code, $tool, $ref) {
  */
 
 function api_track_item_property_update($tool, $ref, $title, $content, $progress) {
-    $tbl_stats_item_property = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
+    $tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
     $course_id = api_get_real_course_id(); //numeric
     $course_code = api_get_course_id(); //alphanumeric
     $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
@@ -3377,15 +3414,15 @@ function api_track_item_property_update($tool, $ref, $title, $content, $progress
                 lastedit_date       = '".api_get_utc_datetime()."',
                 lastedit_user_id    = '".api_get_user_id()."',
                 session_id          = '".api_get_session_id()."'";
-        Database::query($sql);
-        $affected_rows = Database::affected_rows();
+        $result = Database::query($sql);
+        $affected_rows = Database::affected_rows($result);
         return $affected_rows;
     }
     return false;
 }
 
 function api_get_track_item_property_history($tool, $ref) {
-    $tbl_stats_item_property = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
+    $tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
     $course_id = api_get_real_course_id(); //numeric
     $course_code = api_get_course_id(); //alphanumeric
     $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
@@ -3515,12 +3552,10 @@ function api_display_language_form($hide_if_no_choice = false) {
  *  array['folder'] = An array with the corresponding names of the language-folders in the filesystem
  */
 function api_get_languages() {
-    global $app;
-
-    if (isset($app['api_get_languages'])) {
-        return $app['api_get_languages'];
+    $language_list = Session::read('_setting.api_get_languages');
+    if (isset($language_list) && !empty($language_list)) {
+        return $language_list;
     }
-
     $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
     $sql = "SELECT * FROM $tbl_language WHERE available = '1' ORDER BY original_name ASC";
 
@@ -3530,7 +3565,7 @@ function api_get_languages() {
         $language_list['name'][] = $row['original_name'];
         $language_list['folder'][] = $row['dokeos_folder'];
     }
-    $app['api_get_languages'] = $language_list;
+    Session::write('_setting.api_get_languages', $language_list);
     return $language_list;
 }
 
@@ -4491,20 +4526,24 @@ function api_get_access_urls($from = 0, $to = 1000000, $order = 'url', $directio
  */
 function api_get_access_url($id)
 {
-    global $_configuration;
-    $id = Database::escape_string(intval($id));
-    // Calling the Database:: library dont work this is handmade.
-    //$table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
-    $table = 'access_url';
-    $database = $_configuration['main_database'];
-    $table_access_url =  "".$database.".".$table."";
-    $sql = "SELECT url, description, active, created_by, tms
-            FROM $table_access_url WHERE id = '$id' ";
+    $id = intval($id);
+    $table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
+    $sql = "SELECT url, description, active, created_by, tms FROM $table_access_url WHERE id = '$id' ";
     $res = Database::query($sql);
-    $result = @Database::fetch_array($res);
+    $result = Database::fetch_array($res);
     return $result;
 }
 
+/**
+ * Gets the current url info
+ */
+function api_get_current_access_url_info()
+{
+    $userInfo = Session::read('url_info');
+    return $userInfo;
+}
+
+
 /**
  * Adds an access URL into the database
  * @param string    URL
@@ -5027,11 +5066,29 @@ function api_create_include_path_setting() {
     return api_get_path(LIBRARY_PATH).'pear';
 }
 
-/** Gets the current access_url id of the Chamilo Platform
+/**
+ * Gets the current access_url id of the Chamilo Platform loaded in the session
  * @author Julio Montoya <gugli100@gmail.com>
  * @return int access_url_id of the current Chamilo Installation
  */
-function api_get_current_access_url_id() {
+function api_get_current_access_url_id()
+{
+    $urlId = Session::read('url_id');
+
+    if (empty($urlId)) {
+        return 1;
+    } else {
+        return $urlId;
+    }
+}
+
+/**
+ * Gets the current access_url id of the api_get_path(WEB_PATH) Chamilo Platform
+ * @author Julio Montoya <gugli100@gmail.com>
+ * @return int access_url_id of the current Chamilo Installation
+ */
+function api_get_access_url_id_from_web_path()
+{
     $access_url_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
     $path = Database::escape_string(api_get_path(WEB_PATH));
     $sql = "SELECT id FROM $access_url_table WHERE url = '".$path."'";
@@ -5040,10 +5097,6 @@ function api_get_current_access_url_id() {
         $access_url_id = Database::result($result, 0, 0);
         return $access_url_id;
     }
-    //if the url in WEB_PATH was not found, it can only mean that there is
-    // either a configuration problem or the first URL has not been defined yet
-    // (by default it is http://localhost/). Thus the more sensible thing we can
-    // do is return 1 (the main URL) as the user cannot hack this value anyway
     return 1;
 }
 
@@ -5381,110 +5434,6 @@ function is_allowed_to_edit() {
 }
 
 
-/**
- *
- * Send an email.
- *
- * Wrapper function for the standard php mail() function. Change this function
- * to your needs. The parameters must follow the same rules as the standard php
- * mail() function. Please look at the documentation on http://php.net/manual/en/function.mail.php
- * @param string $to
- * @param string $subject
- * @param string $message
- * @param string $additional_headers
- * @param string $additional_parameters
- * @author Ivan Tcholakov, 04-OCT-2009, a reworked version of this function.
- * @deprecated use api_mail_html
- * @link http://www.dokeos.com/forum/viewtopic.php?t=15557
- */
-function api_send_mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null) {
-
-    require_once api_get_path(LIBRARY_PATH).'phpmailer/class.phpmailer.php';
-
-    if (empty($platform_email['SMTP_FROM_NAME'])) {
-        $platform_email['SMTP_FROM_NAME'] = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
-    }
-
-    if (empty($platform_email['SMTP_FROM_EMAIL'])) {
-        $platform_email['SMTP_FROM_EMAIL'] = api_get_setting('emailAdministrator');
-    }
-
-    $matches = array();
-    if (preg_match('/([^<]*)<(.+)>/si', $to, $matches)) {
-        $recipient_name = trim($matches[1]);
-        $recipient_email = trim($matches[2]);
-    } else {
-        $recipient_name = '';
-        $recipient_email = trim($to);
-    }
-
-    $sender_name = '';
-    $sender_email = '';
-    $extra_headers = $additional_headers;
-
-    // Regular expression to test for valid email address.
-    // This should actually be revised to use the complete RFC3696 description.
-    // http://tools.ietf.org/html/rfc3696#section-3
-    //$regexp = "^[0-9a-z_\.+-]+@(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z][0-9a-z-]*[0-9a-z]\.)+[a-z]{2,3})$"; // Deprecated, 13-OCT-2010.
-
-    $mail = new PHPMailer();
-    $mail->CharSet = $platform_email['SMTP_CHARSET'];
-    $mail->Mailer = $platform_email['SMTP_MAILER'];
-    $mail->Host = $platform_email['SMTP_HOST'];
-    $mail->Port = $platform_email['SMTP_PORT'];
-
-    if ($platform_email['SMTP_AUTH']) {
-        $mail->SMTPAuth = 1;
-        $mail->Username = $platform_email['SMTP_USER'];
-        $mail->Password = $platform_email['SMTP_PASS'];
-    }
-
-    $mail->Priority = 3; // 5 = low, 1 = high
-    $mail->AddCustomHeader('Errors-To: '.$platform_email['SMTP_FROM_EMAIL']);
-    $mail->IsHTML(0);
-    $mail->SMTPKeepAlive = true;
-
-    // Attachments.
-    // $mail->AddAttachment($path);
-    // $mail->AddAttachment($path, $filename);
-
-    if ($sender_email != '') {
-        $mail->From = $sender_email;
-        $mail->Sender = $sender_email;
-        //$mail->ConfirmReadingTo = $sender_email; // Disposition-Notification
-    } else {
-        $mail->From = $platform_email['SMTP_FROM_EMAIL'];
-        $mail->Sender = $platform_email['SMTP_FROM_EMAIL'];
-        //$mail->ConfirmReadingTo = $platform_email['SMTP_FROM_EMAIL']; // Disposition-Notification
-    }
-
-    if ($sender_name != '') {
-        $mail->FromName = $sender_name;
-    } else {
-        $mail->FromName = $platform_email['SMTP_FROM_NAME'];
-    }
-    $mail->Subject = $subject;
-    $mail->Body = $message;
-    // Only valid address are to be accepted.
-    //if (eregi( $regexp, $recipient_email )) { // Deprecated, 13-OCT-2010.
-    if (api_valid_email($recipient_email)) {
-        $mail->AddAddress($recipient_email, $recipient_name);
-    }
-
-    if ($extra_headers != '') {
-        $mail->AddCustomHeader($extra_headers);
-    }
-
-    // Send mail.
-    if (!$mail->Send()) {
-        return 0;
-    }
-
-    // Clear all the addresses.
-    $mail->ClearAddresses();
-    return 1;
-}
-
 /**
  * Function used to protect a "global" admin script.
  * The function blocks access when the user has no global platform admin rights.
@@ -5947,9 +5896,9 @@ function api_get_unique_id() {
 
 function api_get_home_path() {
 	$home = 'home/';
-	if (api_get_multiple_access_url()) {
-		$access_url_id = api_get_current_access_url_id();
-		$url_info      = api_get_access_url($access_url_id);
+    $access_url_id = api_get_current_access_url_id();
+	if (api_get_multiple_access_url() && $access_url_id != -1) {
+		$url_info      = api_get_current_access_url_info();
 		$url           = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $url_info['url']));
 		$clean_url     = replace_dangerous_char($url);
 		$clean_url     = str_replace('/', '-', $clean_url);
@@ -6375,7 +6324,7 @@ function api_set_settings_and_plugins()
     $settings_by_access_list = array();
     $access_url_id = api_get_current_access_url_id();
     if ($access_url_id != 1) {
-        $url_info = api_get_access_url($_configuration['access_url']);
+        $url_info = api_get_current_access_url_info();
         if ($url_info['active'] == 1) {
             $settings_by_access = api_get_settings(null, 'list', $_configuration['access_url'], 1);
             foreach ($settings_by_access as $row) {

+ 4 - 3
main/inc/lib/nanogong.lib.php

@@ -233,8 +233,9 @@ class Nanogong
         if ($load_from_database) {
 
             //Load the real filename just if exists
-            if (isset($this->params['exe_id']) && isset($this->params['user_id']) && isset($this->params['question_id']) && isset($this->params['session_id']) && isset($this->params['course_id'])) {
-                $attempt_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+            if (isset($this->params['exe_id']) && isset($this->params['user_id']) &&
+                isset($this->params['question_id']) && isset($this->params['session_id']) && isset($this->params['course_id'])) {
+                $attempt_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
                 $sql = "SELECT filename FROM $attempt_table
                         WHERE 	exe_id 		= ".$this->params['exe_id']." AND
                                 user_id 	= ".$this->params['user_id']." AND
@@ -692,4 +693,4 @@ class Nanogong
 
         return $html;
     }
-}
+}

+ 4 - 4
main/inc/lib/notebook.lib.php

@@ -70,7 +70,7 @@ class NotebookManager {
             //insert into item_property
             api_item_property_update(api_get_course_info(), TOOL_NOTEBOOK, $id, 'NotebookAdded', api_get_user_id());
         }
-        $affected_rows = Database::affected_rows();
+        $affected_rows = Database::affected_rows($result);
         if (!empty($affected_rows)) {
             return $id;
         }
@@ -127,7 +127,7 @@ class NotebookManager {
 
         //update item_property (update)
         api_item_property_update(api_get_course_info(), TOOL_NOTEBOOK, $values['notebook_id'], 'NotebookUpdated', api_get_user_id());
-        $affected_rows = Database::affected_rows();
+        $affected_rows = Database::affected_rows($result);
         if (!empty($affected_rows)) {
             return true;
         }
@@ -144,7 +144,7 @@ class NotebookManager {
 
         $sql = "DELETE FROM $t_notebook WHERE c_id = $course_id AND notebook_id='" . intval($notebook_id) . "' AND user_id = '" . api_get_user_id() . "'";
         $result = Database::query($sql);
-        $affected_rows = Database::affected_rows();
+        $affected_rows = Database::affected_rows($result);
         if ($affected_rows != 1) {
             return false;
         }
@@ -226,4 +226,4 @@ class NotebookManager {
             echo '</div>';
         }
     }
-}
+}

+ 35 - 23
main/inc/lib/online.inc.php

@@ -19,20 +19,21 @@
 
 use \ChamiloSession as Session;
 
-class Online {
+class Online
+{
 
     /**
      * Checking user in DB
      * @param int $uid
      */
-    static function loginCheck($uid)
+    public static function loginCheck($uid)
     {
         $_course = api_get_course_info();
         $uid = (int) $uid;
-        $online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+        $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
         if (!empty($uid)) {
             $login_ip = '';
-            if(!empty($_SERVER['REMOTE_ADDR'])) {
+            if (!empty($_SERVER['REMOTE_ADDR'])) {
                 $login_ip = Database::escape_string($_SERVER['REMOTE_ADDR']);
             }
 
@@ -45,9 +46,11 @@ class Online {
             // if the $_course array exists this means we are in a course and we have to store this in the who's online table also
             // to have the x users in this course feature working
             if (is_array($_course) && count($_course)>0 && !empty($_course['id'])) {
-                $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,login_ip, course, session_id, access_url_id) VALUES ($uid,$uid,'$login_date','$login_ip', '".$_course['id']."' , '$session_id' , '$access_url_id' )";
+                $query = "REPLACE INTO ".$online_table ." (login_id, login_user_id, login_date, login_ip, course, session_id, access_url_id)
+                          VALUES ($uid, $uid, '$login_date', '$login_ip', '".$_course['id']."', '$session_id', '$access_url_id' )";
             } else {
-                $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,login_ip, session_id, access_url_id) VALUES ($uid,$uid,'$login_date','$login_ip', '$session_id', '$access_url_id')";
+                $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,login_ip, session_id, access_url_id)
+                          VALUES ($uid,$uid,'$login_date','$login_ip', '$session_id', '$access_url_id')";
             }
             Database::query($query);
         }
@@ -58,11 +61,12 @@ class Online {
      * @return void  Directly redirects the user or leaves him where he is, but doesn't return anything
      * @author Fernando P. García <fernando@develcuy.com>
      */
-    static function logout($user_id = null, $logout_redirect = false) {
+    public static function logout($user_id = null, $logout_redirect = false)
+    {
         global $extAuthSource;
 
         // Database table definition
-        $tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+        $tbl_track_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
 
         if (empty($user_id)) {
             $user_id = api_get_user_id();
@@ -75,7 +79,8 @@ class Online {
         }
 
         // selecting the last login of the user
-        $sql_last_connection="SELECT login_id, login_date FROM $tbl_track_login WHERE login_user_id='$user_id' ORDER BY login_date DESC LIMIT 0,1";
+        $sql_last_connection = "SELECT login_id, login_date FROM $tbl_track_login
+                              WHERE login_user_id='$user_id' ORDER BY login_date DESC LIMIT 0,1";
         $q_last_connection=Database::query($sql_last_connection);
         $i_id_last_connection = null;
         if (Database::num_rows($q_last_connection)>0) {
@@ -124,8 +129,9 @@ class Online {
      * @param int User ID
      * @return bool
      */
-    static function loginDelete($user_id) {
-        $online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+    public static function loginDelete($user_id)
+    {
+        $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
         $user_id = intval($user_id);
         if (empty($user_id)) {
             return false;
@@ -135,8 +141,9 @@ class Online {
         return true;
     }
 
-    static function user_is_online($user_id) {
-        $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+    public static function user_is_online($user_id)
+    {
+        $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
         $table_user			= Database::get_main_table(TABLE_MAIN_USER);
 
 
@@ -164,7 +171,8 @@ class Online {
      * Gives a list of people online now (and in the last $valid minutes)
      * @return  array       For each line, a list of user IDs and login dates, or FALSE on error or empty results
      */
-    static function who_is_online($from, $number_of_items, $column = null, $direction = null, $time_limit = null, $friends = false) {
+    public static function who_is_online($from, $number_of_items, $column = null, $direction = null, $time_limit = null, $friends = false)
+    {
 
         // Time limit in seconds?
         if (empty($time_limit)) {
@@ -193,7 +201,7 @@ class Online {
 
         $online_time 		= time() - $time_limit*60;
         $current_date		= api_get_utc_datetime($online_time);
-        $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+        $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
         $friend_user_table  = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
         $table_user			= Database::get_main_table(TABLE_MAIN_USER);
         $query              = '';
@@ -261,13 +269,14 @@ class Online {
         }
     }
 
-    static function who_is_online_count($time_limit = null, $friends = false) {
+    public static function who_is_online_count($time_limit = null, $friends = false)
+    {
         if (empty($time_limit)) {
             $time_limit = api_get_setting('time_limit_whosonline');
         } else {
             $time_limit = intval($time_limit);
         }
-        $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+        $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
         $friend_user_table  = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
         $table_user			= Database::get_main_table(TABLE_MAIN_USER);
         $query = '';
@@ -320,7 +329,6 @@ class Online {
         }
     }
 
-
     /**
     * Returns a list (array) of users who are online and in this course.
     * @param    int User ID
@@ -328,7 +336,8 @@ class Online {
     * @param    string  Course code (could be empty, but then the function returns false)
     * @return   array   Each line gives a user id and a login time
     */
-    static function who_is_online_in_this_course($from, $number_of_items, $uid, $time_limit, $course_code) {
+    public static function who_is_online_in_this_course($from, $number_of_items, $uid, $time_limit, $course_code)
+    {
         if (empty($course_code)) return false;
 
         if (empty($time_limit)) {
@@ -339,7 +348,7 @@ class Online {
 
         $online_time 		= time() - $time_limit*60;
         $current_date		= api_get_utc_datetime($online_time);
-        $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+        $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
         $course_code        = Database::escape_string($course_code);
 
         $from            = intval($from);
@@ -367,9 +376,12 @@ class Online {
         }
     }
 
-    static function who_is_online_in_this_course_count($uid, $time_limit, $coursecode=null) {
-        if(empty($coursecode)) return false;
-        $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+    public static function who_is_online_in_this_course_count($uid, $time_limit, $coursecode=null)
+    {
+        if (empty($coursecode)) {
+            return false;
+        }
+        $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
         $coursecode = Database::escape_string($coursecode);
         $time_limit = Database::escape_string($time_limit);
 

+ 1 - 2
main/inc/lib/page.lib.php

@@ -953,7 +953,7 @@ class PageController
     /**
      * The most important function here, prints the session and course list (user_portal.php)
      *
-     * @param int User ID
+     * @param int User id
      * @param string filter
      * @param int page
      * @return string HTML list of sessions and courses
@@ -971,7 +971,6 @@ class PageController
         $start    = ($page - 1) * $this->maxPerPage;
 
         $nbResults = CourseManager::displayCourses($user_id, $filter, $loadDirs, true);
-
         $html = CourseManager::displayCourses($user_id, $filter, $loadDirs, false, $start, $this->maxPerPage);
         if (!empty($html)) {
 

+ 0 - 504
main/inc/lib/phpmailer/LICENSE

@@ -1,504 +0,0 @@
-		  GNU LESSER GENERAL PUBLIC LICENSE
-		       Version 2.1, February 1999
-
- Copyright (C) 1991, 1999 Free Software Foundation, Inc.
-     59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-[This is the first released version of the Lesser GPL.  It also counts
- as the successor of the GNU Library Public License, version 2, hence
- the version number 2.1.]
-
-			    Preamble
-
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-Licenses are intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-
-  This license, the Lesser General Public License, applies to some
-specially designated software packages--typically libraries--of the
-Free Software Foundation and other authors who decide to use it.  You
-can use it too, but we suggest you first think carefully about whether
-this license or the ordinary General Public License is the better
-strategy to use in any particular case, based on the explanations below.
-
-  When we speak of free software, we are referring to freedom of use,
-not price.  Our General Public Licenses are designed to make sure that
-you have the freedom to distribute copies of free software (and charge
-for this service if you wish); that you receive source code or can get
-it if you want it; that you can change the software and use pieces of
-it in new free programs; and that you are informed that you can do
-these things.
-
-  To protect your rights, we need to make restrictions that forbid
-distributors to deny you these rights or to ask you to surrender these
-rights.  These restrictions translate to certain responsibilities for
-you if you distribute copies of the library or if you modify it.
-
-  For example, if you distribute copies of the library, whether gratis
-or for a fee, you must give the recipients all the rights that we gave
-you.  You must make sure that they, too, receive or can get the source
-code.  If you link other code with the library, you must provide
-complete object files to the recipients, so that they can relink them
-with the library after making changes to the library and recompiling
-it.  And you must show them these terms so they know their rights.
-
-  We protect your rights with a two-step method: (1) we copyright the
-library, and (2) we offer you this license, which gives you legal
-permission to copy, distribute and/or modify the library.
-
-  To protect each distributor, we want to make it very clear that
-there is no warranty for the free library.  Also, if the library is
-modified by someone else and passed on, the recipients should know
-that what they have is not the original version, so that the original
-author's reputation will not be affected by problems that might be
-introduced by others.
-
-  Finally, software patents pose a constant threat to the existence of
-any free program.  We wish to make sure that a company cannot
-effectively restrict the users of a free program by obtaining a
-restrictive license from a patent holder.  Therefore, we insist that
-any patent license obtained for a version of the library must be
-consistent with the full freedom of use specified in this license.
-
-  Most GNU software, including some libraries, is covered by the
-ordinary GNU General Public License.  This license, the GNU Lesser
-General Public License, applies to certain designated libraries, and
-is quite different from the ordinary General Public License.  We use
-this license for certain libraries in order to permit linking those
-libraries into non-free programs.
-
-  When a program is linked with a library, whether statically or using
-a shared library, the combination of the two is legally speaking a
-combined work, a derivative of the original library.  The ordinary
-General Public License therefore permits such linking only if the
-entire combination fits its criteria of freedom.  The Lesser General
-Public License permits more lax criteria for linking other code with
-the library.
-
-  We call this license the "Lesser" General Public License because it
-does Less to protect the user's freedom than the ordinary General
-Public License.  It also provides other free software developers Less
-of an advantage over competing non-free programs.  These disadvantages
-are the reason we use the ordinary General Public License for many
-libraries.  However, the Lesser license provides advantages in certain
-special circumstances.
-
-  For example, on rare occasions, there may be a special need to
-encourage the widest possible use of a certain library, so that it becomes
-a de-facto standard.  To achieve this, non-free programs must be
-allowed to use the library.  A more frequent case is that a free
-library does the same job as widely used non-free libraries.  In this
-case, there is little to gain by limiting the free library to free
-software only, so we use the Lesser General Public License.
-
-  In other cases, permission to use a particular library in non-free
-programs enables a greater number of people to use a large body of
-free software.  For example, permission to use the GNU C Library in
-non-free programs enables many more people to use the whole GNU
-operating system, as well as its variant, the GNU/Linux operating
-system.
-
-  Although the Lesser General Public License is Less protective of the
-users' freedom, it does ensure that the user of a program that is
-linked with the Library has the freedom and the wherewithal to run
-that program using a modified version of the Library.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.  Pay close attention to the difference between a
-"work based on the library" and a "work that uses the library".  The
-former contains code derived from the library, whereas the latter must
-be combined with the library in order to run.
-
-		  GNU LESSER GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
-  0. This License Agreement applies to any software library or other
-program which contains a notice placed by the copyright holder or
-other authorized party saying it may be distributed under the terms of
-this Lesser General Public License (also called "this License").
-Each licensee is addressed as "you".
-
-  A "library" means a collection of software functions and/or data
-prepared so as to be conveniently linked with application programs
-(which use some of those functions and data) to form executables.
-
-  The "Library", below, refers to any such software library or work
-which has been distributed under these terms.  A "work based on the
-Library" means either the Library or any derivative work under
-copyright law: that is to say, a work containing the Library or a
-portion of it, either verbatim or with modifications and/or translated
-straightforwardly into another language.  (Hereinafter, translation is
-included without limitation in the term "modification".)
-
-  "Source code" for a work means the preferred form of the work for
-making modifications to it.  For a library, complete source code means
-all the source code for all modules it contains, plus any associated
-interface definition files, plus the scripts used to control compilation
-and installation of the library.
-
-  Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running a program using the Library is not restricted, and output from
-such a program is covered only if its contents constitute a work based
-on the Library (independent of the use of the Library in a tool for
-writing it).  Whether that is true depends on what the Library does
-and what the program that uses the Library does.
-  
-  1. You may copy and distribute verbatim copies of the Library's
-complete source code as you receive it, in any medium, provided that
-you conspicuously and appropriately publish on each copy an
-appropriate copyright notice and disclaimer of warranty; keep intact
-all the notices that refer to this License and to the absence of any
-warranty; and distribute a copy of this License along with the
-Library.
-
-  You may charge a fee for the physical act of transferring a copy,
-and you may at your option offer warranty protection in exchange for a
-fee.
-
-  2. You may modify your copy or copies of the Library or any portion
-of it, thus forming a work based on the Library, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
-    a) The modified work must itself be a software library.
-
-    b) You must cause the files modified to carry prominent notices
-    stating that you changed the files and the date of any change.
-
-    c) You must cause the whole of the work to be licensed at no
-    charge to all third parties under the terms of this License.
-
-    d) If a facility in the modified Library refers to a function or a
-    table of data to be supplied by an application program that uses
-    the facility, other than as an argument passed when the facility
-    is invoked, then you must make a good faith effort to ensure that,
-    in the event an application does not supply such function or
-    table, the facility still operates, and performs whatever part of
-    its purpose remains meaningful.
-
-    (For example, a function in a library to compute square roots has
-    a purpose that is entirely well-defined independent of the
-    application.  Therefore, Subsection 2d requires that any
-    application-supplied function or table used by this function must
-    be optional: if the application does not supply it, the square
-    root function must still compute square roots.)
-
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Library,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Library, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote
-it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Library.
-
-In addition, mere aggregation of another work not based on the Library
-with the Library (or with a work based on the Library) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
-  3. You may opt to apply the terms of the ordinary GNU General Public
-License instead of this License to a given copy of the Library.  To do
-this, you must alter all the notices that refer to this License, so
-that they refer to the ordinary GNU General Public License, version 2,
-instead of to this License.  (If a newer version than version 2 of the
-ordinary GNU General Public License has appeared, then you can specify
-that version instead if you wish.)  Do not make any other change in
-these notices.
-
-  Once this change is made in a given copy, it is irreversible for
-that copy, so the ordinary GNU General Public License applies to all
-subsequent copies and derivative works made from that copy.
-
-  This option is useful when you wish to copy part of the code of
-the Library into a program that is not a library.
-
-  4. You may copy and distribute the Library (or a portion or
-derivative of it, under Section 2) in object code or executable form
-under the terms of Sections 1 and 2 above provided that you accompany
-it with the complete corresponding machine-readable source code, which
-must be distributed under the terms of Sections 1 and 2 above on a
-medium customarily used for software interchange.
-
-  If distribution of object code is made by offering access to copy
-from a designated place, then offering equivalent access to copy the
-source code from the same place satisfies the requirement to
-distribute the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
-  5. A program that contains no derivative of any portion of the
-Library, but is designed to work with the Library by being compiled or
-linked with it, is called a "work that uses the Library".  Such a
-work, in isolation, is not a derivative work of the Library, and
-therefore falls outside the scope of this License.
-
-  However, linking a "work that uses the Library" with the Library
-creates an executable that is a derivative of the Library (because it
-contains portions of the Library), rather than a "work that uses the
-library".  The executable is therefore covered by this License.
-Section 6 states terms for distribution of such executables.
-
-  When a "work that uses the Library" uses material from a header file
-that is part of the Library, the object code for the work may be a
-derivative work of the Library even though the source code is not.
-Whether this is true is especially significant if the work can be
-linked without the Library, or if the work is itself a library.  The
-threshold for this to be true is not precisely defined by law.
-
-  If such an object file uses only numerical parameters, data
-structure layouts and accessors, and small macros and small inline
-functions (ten lines or less in length), then the use of the object
-file is unrestricted, regardless of whether it is legally a derivative
-work.  (Executables containing this object code plus portions of the
-Library will still fall under Section 6.)
-
-  Otherwise, if the work is a derivative of the Library, you may
-distribute the object code for the work under the terms of Section 6.
-Any executables containing that work also fall under Section 6,
-whether or not they are linked directly with the Library itself.
-
-  6. As an exception to the Sections above, you may also combine or
-link a "work that uses the Library" with the Library to produce a
-work containing portions of the Library, and distribute that work
-under terms of your choice, provided that the terms permit
-modification of the work for the customer's own use and reverse
-engineering for debugging such modifications.
-
-  You must give prominent notice with each copy of the work that the
-Library is used in it and that the Library and its use are covered by
-this License.  You must supply a copy of this License.  If the work
-during execution displays copyright notices, you must include the
-copyright notice for the Library among them, as well as a reference
-directing the user to the copy of this License.  Also, you must do one
-of these things:
-
-    a) Accompany the work with the complete corresponding
-    machine-readable source code for the Library including whatever
-    changes were used in the work (which must be distributed under
-    Sections 1 and 2 above); and, if the work is an executable linked
-    with the Library, with the complete machine-readable "work that
-    uses the Library", as object code and/or source code, so that the
-    user can modify the Library and then relink to produce a modified
-    executable containing the modified Library.  (It is understood
-    that the user who changes the contents of definitions files in the
-    Library will not necessarily be able to recompile the application
-    to use the modified definitions.)
-
-    b) Use a suitable shared library mechanism for linking with the
-    Library.  A suitable mechanism is one that (1) uses at run time a
-    copy of the library already present on the user's computer system,
-    rather than copying library functions into the executable, and (2)
-    will operate properly with a modified version of the library, if
-    the user installs one, as long as the modified version is
-    interface-compatible with the version that the work was made with.
-
-    c) Accompany the work with a written offer, valid for at
-    least three years, to give the same user the materials
-    specified in Subsection 6a, above, for a charge no more
-    than the cost of performing this distribution.
-
-    d) If distribution of the work is made by offering access to copy
-    from a designated place, offer equivalent access to copy the above
-    specified materials from the same place.
-
-    e) Verify that the user has already received a copy of these
-    materials or that you have already sent this user a copy.
-
-  For an executable, the required form of the "work that uses the
-Library" must include any data and utility programs needed for
-reproducing the executable from it.  However, as a special exception,
-the materials to be distributed need not include anything that is
-normally distributed (in either source or binary form) with the major
-components (compiler, kernel, and so on) of the operating system on
-which the executable runs, unless that component itself accompanies
-the executable.
-
-  It may happen that this requirement contradicts the license
-restrictions of other proprietary libraries that do not normally
-accompany the operating system.  Such a contradiction means you cannot
-use both them and the Library together in an executable that you
-distribute.
-
-  7. You may place library facilities that are a work based on the
-Library side-by-side in a single library together with other library
-facilities not covered by this License, and distribute such a combined
-library, provided that the separate distribution of the work based on
-the Library and of the other library facilities is otherwise
-permitted, and provided that you do these two things:
-
-    a) Accompany the combined library with a copy of the same work
-    based on the Library, uncombined with any other library
-    facilities.  This must be distributed under the terms of the
-    Sections above.
-
-    b) Give prominent notice with the combined library of the fact
-    that part of it is a work based on the Library, and explaining
-    where to find the accompanying uncombined form of the same work.
-
-  8. You may not copy, modify, sublicense, link with, or distribute
-the Library except as expressly provided under this License.  Any
-attempt otherwise to copy, modify, sublicense, link with, or
-distribute the Library is void, and will automatically terminate your
-rights under this License.  However, parties who have received copies,
-or rights, from you under this License will not have their licenses
-terminated so long as such parties remain in full compliance.
-
-  9. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Library or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Library (or any work based on the
-Library), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Library or works based on it.
-
-  10. Each time you redistribute the Library (or any work based on the
-Library), the recipient automatically receives a license from the
-original licensor to copy, distribute, link with or modify the Library
-subject to these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties with
-this License.
-
-  11. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Library at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Library by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Library.
-
-If any portion of this section is held invalid or unenforceable under any
-particular circumstance, the balance of the section is intended to apply,
-and the section as a whole is intended to apply in other circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  12. If the distribution and/or use of the Library is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Library under this License may add
-an explicit geographical distribution limitation excluding those countries,
-so that distribution is permitted only in or among countries not thus
-excluded.  In such case, this License incorporates the limitation as if
-written in the body of this License.
-
-  13. The Free Software Foundation may publish revised and/or new
-versions of the Lesser General Public License from time to time.
-Such new versions will be similar in spirit to the present version,
-but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Library
-specifies a version number of this License which applies to it and
-"any later version", you have the option of following the terms and
-conditions either of that version or of any later version published by
-the Free Software Foundation.  If the Library does not specify a
-license version number, you may choose any version ever published by
-the Free Software Foundation.
-
-  14. If you wish to incorporate parts of the Library into other free
-programs whose distribution conditions are incompatible with these,
-write to the author to ask for permission.  For software which is
-copyrighted by the Free Software Foundation, write to the Free
-Software Foundation; we sometimes make exceptions for this.  Our
-decision will be guided by the two goals of preserving the free status
-of all derivatives of our free software and of promoting the sharing
-and reuse of software generally.
-
-			    NO WARRANTY
-
-  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
-WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
-EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
-OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
-KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
-LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
-THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
-  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
-WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
-FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
-CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
-LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
-RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
-FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
-SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGES.
-
-		     END OF TERMS AND CONDITIONS
-
-           How to Apply These Terms to Your New Libraries
-
-  If you develop a new library, and you want it to be of the greatest
-possible use to the public, we recommend making it free software that
-everyone can redistribute and change.  You can do so by permitting
-redistribution under these terms (or, alternatively, under the terms of the
-ordinary General Public License).
-
-  To apply these terms, attach the following notices to the library.  It is
-safest to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least the
-"copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the library's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
-
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-
-Also add information on how to contact you by electronic and paper mail.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the library, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the
-  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
-
-  <signature of Ty Coon>, 1 April 1990
-  Ty Coon, President of Vice
-
-That's all there is to it!
-
-

+ 0 - 218
main/inc/lib/phpmailer/README

@@ -1,218 +0,0 @@
-/*******************************************************************
-* The http://phpmailer.codeworxtech.com/ website now carries a few *
-* advertisements through the Google Adsense network. Please visit  *
-* the advertiser sites and help us offset some of our costs.       *
-* Thanks ....                                                      *
-********************************************************************/
-
-PHPMailer
-Full Featured Email Transfer Class for PHP
-==========================================
-
-Version 5.0.0 (April 02, 2009)
-
-With the release of this version, we are initiating a new version numbering
-system to differentiate from the PHP4 version of PHPMailer.
-
-Most notable in this release is fully object oriented code.
-
-We now have available the PHPDocumentor (phpdocs) documentation. This is
-separate from the regular download to keep file sizes down. Please see the
-download area of http://phpmailer.codeworxtech.com.
-
-We also have created a new test script (see /test_script) that you can use
-right out of the box. Copy the /test_script folder directly to your server (in
-the same structure ... with class.phpmailer.php and class.smtp.php in the
-folder above it. Then launch the test script with:
-http://www.yourdomain.com/phpmailer/test_script/index.php
-from this one script, you can test your server settings for mail(), sendmail (or
-qmail), and SMTP. This will email you a sample email (using contents.html for
-the email body) and two attachments. One of the attachments is used as an inline
-image to demonstrate how PHPMailer will automatically detect if attachments are
-the same source as inline graphics and only include one version. Once you click
-the Submit button, the results will be displayed including any SMTP debug
-information and send status. We will also display a version of the script that
-you can cut and paste to include in your projects. Enjoy!
-
-Version 2.3 (November 08, 2008)
-
-We have removed the /phpdoc from the downloads. All documentation is now on
-the http://phpmailer.codeworxtech.com website.
-
-The phpunit.php has been updated to support PHP5.
-
-For all other changes and notes, please see the changelog.
-
-Donations are accepted at PayPal with our id "paypal@worxteam.com".
-
-Version 2.2 (July 15 2008)
-
-- see the changelog.
-
-Version 2.1 (June 04 2008)
-
-With this release, we are announcing that the development of PHPMailer for PHP5
-will be our focus from this date on. We have implemented all the enhancements
-and fixes from the latest release of PHPMailer for PHP4.
-
-Far more important, though, is that this release of PHPMailer (v2.1) is
-fully tested with E_STRICT error checking enabled.
-
-** NOTE: WE HAVE A NEW LANGUAGE VARIABLE FOR DIGITALLY SIGNED S/MIME EMAILS.
-   IF YOU CAN HELP WITH LANGUAGES OTHER THAN ENGLISH AND SPANISH, IT WOULD BE
-   APPRECIATED.
-
-We have now added S/MIME functionality (ability to digitally sign emails).
-BIG THANKS TO "sergiocambra" for posting this patch back in November 2007.
-The "Signed Emails" functionality adds the Sign method to pass the private key
-filename and the password to read it, and then email will be sent with
-content-type multipart/signed and with the digital signature attached.
-
-A quick note on E_STRICT:
-
-- In about half the test environments the development version was subjected
-  to, an error was thrown for the date() functions (used at line 1565 and 1569).
-  This is NOT a PHPMailer error, it is the result of an incorrectly configured
-  PHP5 installation. The fix is to modify your 'php.ini' file and include the
-  date.timezone = America/New York
-  directive, (for your own server timezone)
-- If you do get this error, and are unable to access your php.ini file, there is
-  a workaround. In your PHP script, add
-  date_default_timezone_set('America/Toronto');
-
-  * do NOT try to use
-  $myVar = date_default_timezone_get();
-  as a test, it will throw an error.
-
-We have also included more example files to show the use of "sendmail", "mail()",
-"smtp", and "gmail".
-
-We are also looking for more programmers to join the volunteer development team.
-If you have an interest in this, please let us know.
-
-Enjoy!
-
-
-Version 2.1.0beta1 & beta2
-
-please note, this is BETA software
-** DO NOT USE THIS IN PRODUCTION OR LIVE PROJECTS
-INTENDED STRICTLY FOR TESTING
-
-** NOTE:
-
-As of November 2007, PHPMailer has a new project team headed by industry
-veteran Andy Prevost (codeworxtech). The first release in more than two
-years will focus on fixes, adding ease-of-use enhancements, provide
-basic compatibility with PHP4 and PHP5 using PHP5 backwards compatibility
-features. A new release is planned before year-end 2007 that will provide
-full compatiblity with PHP4 and PHP5, as well as more bug fixes.
-
-We are looking for project developers to assist in restoring PHPMailer to
-its leadership position. Our goals are to simplify use of PHPMailer, provide
-good documentation and examples, and retain backward compatibility to level
-1.7.3 standards.
-
-If you are interested in helping out, visit http://sourceforge.net/projects/phpmailer
-and indicate your interest.
-
-**
-
-http://phpmailer.sourceforge.net/
-
-This software is licenced under the LGPL.  Please read LICENSE for information on the
-software availability and distribution.
-
-Class Features:
-- Send emails with multiple TOs, CCs, BCCs and REPLY-TOs
-- Redundant SMTP servers
-- Multipart/alternative emails for mail clients that do not read HTML email
-- Support for 8bit, base64, binary, and quoted-printable encoding
-- Uses the same methods as the very popular AspEmail active server (COM) component
-- SMTP authentication
-- Native language support
-- Word wrap, and more!
-
-Why you might need it:
-
-Many PHP developers utilize email in their code.  The only PHP function
-that supports this is the mail() function.  However, it does not expose
-any of the popular features that many email clients use nowadays like
-HTML-based emails and attachments. There are two proprietary
-development tools out there that have all the functionality built into
-easy to use classes: AspEmail(tm) and AspMail.  Both of these
-programs are COM components only available on Windows.  They are also a
-little pricey for smaller projects.
-
-Since I do Linux development I�ve missed these tools for my PHP coding.
-So I built a version myself that implements the same methods (object
-calls) that the Windows-based components do. It is open source and the
-LGPL license allows you to place the class in your proprietary PHP
-projects.
-
-
-Installation:
-
-Copy class.phpmailer.php into your php.ini include_path. If you are
-using the SMTP mailer then place class.smtp.php in your path as well.
-In the language directory you will find several files like
-phpmailer.lang-en.php.  If you look right before the .php extension
-that there are two letters.  These represent the language type of the
-translation file.  For instance "en" is the English file and "br" is
-the Portuguese file.  Chose the file that best fits with your language
-and place it in the PHP include path.  If your language is English
-then you have nothing more to do.  If it is a different language then
-you must point PHPMailer to the correct translation.  To do this, call
-the PHPMailer SetLanguage method like so:
-
-// To load the Portuguese version
-$mail->SetLanguage("br", "/optional/path/to/language/directory/");
-
-That's it.  You should now be ready to use PHPMailer!
-
-
-A Simple Example:
-
-<?php
-require("class.phpmailer.php");
-
-$mail = new PHPMailer();
-
-$mail->IsSMTP();                                      // set mailer to use SMTP
-$mail->Host = "smtp1.example.com;smtp2.example.com";  // specify main and backup server
-$mail->SMTPAuth = true;     // turn on SMTP authentication
-$mail->Username = "jswan";  // SMTP username
-$mail->Password = "secret"; // SMTP password
-
-$mail->From = "from@example.com";
-$mail->FromName = "Mailer";
-$mail->AddAddress("josh@example.net", "Josh Adams");
-$mail->AddAddress("ellen@example.com");                  // name is optional
-$mail->AddReplyTo("info@example.com", "Information");
-
-$mail->WordWrap = 50;                                 // set word wrap to 50 characters
-$mail->AddAttachment("/var/tmp/file.tar.gz");         // add attachments
-$mail->AddAttachment("/tmp/image.jpg", "new.jpg");    // optional name
-$mail->IsHTML(true);                                  // set email format to HTML
-
-$mail->Subject = "Here is the subject";
-$mail->Body    = "This is the HTML message body <b>in bold!</b>";
-$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
-
-if(!$mail->Send())
-{
-   echo "Message could not be sent. <p>";
-   echo "Mailer Error: " . $mail->ErrorInfo;
-   exit;
-}
-
-echo "Message has been sent";
-?>
-
-CHANGELOG
-
-See ChangeLog.txt
-
-Download: http://sourceforge.net/project/showfiles.php?group_id=26031
-
-Andy Prevost

+ 0 - 169
main/inc/lib/phpmailer/aboutus.html

@@ -1,169 +0,0 @@
-<html>
-<head>
-<style>
-body, p, li, td {
-  font-family: Arial, Helvetica, sans-serif;
-  font-size: 12px;
-}
-ul {
-  margin:0 0px 0 15px;
-  padding:0;
-}
-div.width {
-  width: 760px;
-  text-align: left;
-}
-</style>
-<script>
-<!--
-var popsite="http://phpmailer.codeworxtech.com"
-var withfeatures="width=960,height=760,scrollbars=1,resizable=1,toolbar=1,location=1,menubar=1,status=1,directories=0"
-var once_per_session=0
-function get_cookie(Name) {
-  var search = Name + "="
-  var returnvalue = "";
-  if (document.cookie.length > 0) {
-    offset = document.cookie.indexOf(search)
-    if (offset != -1) { // if cookie exists
-      offset += search.length
-      // set index of beginning of value
-      end = document.cookie.indexOf(";", offset);
-      // set index of end of cookie value
-      if (end == -1)
-         end = document.cookie.length;
-      returnvalue=unescape(document.cookie.substring(offset, end))
-      }
-   }
-  return returnvalue;
-}
-function loadornot(){
-  if (get_cookie('popsite')=='') {
-    loadpopsite()
-    document.cookie="popsite=yes"
-  }
-}
-function loadpopsite(){
-  win2=window.open(popsite,"",withfeatures)
-  win2.blur()
-  window.focus()
-}
-if (once_per_session==0) {
-  loadpopsite()
-} else {
-  loadornot()
-}
--->
-</script>
-</head>
-<body>
-<center>
-<div class="width">
-<hr>
-The http://phpmailer.codeworxtech.com/ website now carries a few
-advertisements through the Google Adsense network to help offset
-some of our costs.<br />
-Thanks ....<br />
-<hr>
-<p>PHPMailer is the world's leading email transport class and downloaded an
-average of more than 32,000 each month. In March 2009, PHPMailer was downloaded
-more than 31,000 times -- that's an average of 1,000 downloads daily. Our thanks
-to our new users and loyal users. We understand you have many choices available
-to select from and we thank you for select our fast and stable tool for your
-website and projects.</p>
-<p>Credits:<br>
-PHPMailer's original founder is Brent Matzelle. The current team is:<br>
-Project Administrator: Andy Prevost (codeworxtech),
-<a href="mailto:codeworxtech@users.sourceforge.net">
-codeworxtech@users.sourceforge.net</a><br>
-Author: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net<br>
-Author: Marcus Bointon (coolbru) <a href="mailto:coolbru@users.sourceforge.net">
-coolbru@users.sourceforge.net</a></p>
-<p>PHPMailer is used in many projects ranging from Open Source to commercial
-packages. Our LGPL licensing terms are very flexible and allow for including
-PHPMailer to enhance projects of all types. If you discover PHPMailer being used
-in a project, please let us know about it.</p>
-<p><strong>WHY USE OUR TOOLS &amp; WHAT&#39;S IN IT FOR YOU?</strong></p>
-<p>A valid question. We're developers too. We've been writing software, primarily for the internet, for more than 15 years. Along the way, there are two major things that had tremendous impact of our company: PHP and Open Source. PHP is without doubt the most popular platform for the internet. There has been more progress in this area of technology because of Open Source software than in any other IT segment. We have used many open source tools, some as learning tools, some as components in projects we were working on. To us, it's not about popularity ... we're committed to robust, stable, and efficient tools you can use to get your projects in your user's hands quickly. So the shorter answer: what's in it for you? rapid development and rapid deployment without fuss and with straight forward open source licensing.</p>
-<p>Now, here's our team:</p>
-<table width="100%" cellpadding="5" style="border-collapse: collapse" border="1">
-  <tr>
-    <th><b>About Andy Prevost, AKA "codeworxtech".</b></th>
-    <th><b>About Marcus Bointon, AKA "coolbru".</b></th>
-  </tr>
-  <tr>
-    <td width="50%" valign="top">
-      <p><a href="http://www.codeworxtech.com">www.codeworxtech.com</a> for more information.<br>
-    Web design, web applications, forms: <a href="http://www.worxstudio.com">WorxStudio.com</a><br />
-      </p>
-      <p>Our company, <strong>Worx International Inc.</strong>, is the publisher of several Open Source applications and developer tools as well as several commercial PHP applications. The Open Source applications are ttCMS and DCP Portal. The Open Source developer tools include QuickComponents (QuickSkin and QuickCache) and now PHPMailer.
-      We have staff and offices in the United States, Caribbean, the Middle
-      East, and our primary development center in Canada. Our company is represented by
-      agents and resellers globally.</p>
-      <p><strong>Worx International Inc.</strong> is at the forefront of developing PHP applications. Our staff are all Zend Certified university educated and experts at object oriented programming. While <strong>Worx International Inc.</strong> can handle any project from trouble shooting programs written by others all the way to finished mission-critical applications, we specialize in taking projects from inception all the way through to implementation - on budget, and on time. If you need help with your projects, we&#39;re the team to get it done right at a reasonable price.</p>
-      <p>Over the years, there have been a number of tools that have been constant favorites in all of our projects. We have become the project administrators for most of these tools.</p>
-      <p>Our developer tools are all Open Source. Here&#39;s a brief description:</p>
-      <ul>
-        <li><span style="background-color: #FFFF00"><strong>PHPMailer</strong></span>. Originally authored by Brent Matzelle, PHPMailer is the leading "email transfer class" for PHP. PHPMailer is downloaded more than
-    26000 times each and every month by developers looking for a fast, stable, simple email solution. We used it ourselves for years as our favorite tool. It&#39;s always been small (the entire footprint is
-    less than 100 Kb), stable, and as complete a solution as you can find.
-    Other tools are nowhere near as simple. Our thanks to Brent Matzelle for this superb tool - our commitment is to keep it lean, keep it focused, and compliant with standards. Visit the PHPMailer website at
-        <a href="http://phpmailer.codeworxtech.com/">http://phpmailer.codeworxtech.com/</a>. <br />
-        Please note: <strong>all of our focus is now on the PHPMailer for PHP5.</strong><br />
-        <span style="background-color: #FFFF00">PS. While you are at it, please visit our sponsor&#39;s sites, click on their ads.
-        It helps offset some of our costs.</span><br />
-        Want to help? We're looking for progressive developers to join our team of volunteer professionals working on PHPMailer. Our entire focus is on PHPMailer
-    for PHP5. If you are interested, let us know.<br />
-        <br />
-        </li>
-        <li><strong><span style="background-color: #FFFF00">QuickCache</span></strong>. Originally authored by Jean Pierre Deckers as jpCache, QuickCache is an HTTP OpCode caching strategy that works on your entire site with only one line of code at the top of your script. The cached pages can be stored as files or as database objects. The benefits are absolutely astounding: bandwidth savings of up to 80% and screen display times increased by 8 - 10x. Visit the QuickCache website at
-        <a href="http://quickcache.codeworxtech.com/">http://quickcache.codeworxtech.com/</a>.<br />
-        <br />
-        </li>
-        <li><strong><span style="background-color: #FFFF00">QuickSkin</span></strong>. Originally authored by Philipp v. Criegern and named "SmartTemplate". The project was taken over by Manuel 'EndelWar' Dalla Lana and now by "codeworxtech". QuickSkin is one of the truly outstanding templating engines available, but has always been confused with Smarty Templating Engine. QuickSkin is even more relevant today than when it was launched. It&#39;s a small footprint with big impact on your projects. It features a built in caching technology, token based substitution, and works on the concept of one single HTML file as the template. The HTML template file can contain variable information making it one small powerful tool for your developer tool kit. Visit the QuickSkin website at
-        <a href="http://quickskin.codeworxtech.com/">http://quickskin.codeworxtech.com/</a>.<br />
-        <br />
-        </li>
-      </ul>
-      <p>We're committed to PHP and to the Open Source community.</p>
-      <p>Opportunities with <strong>Worx International Inc.</strong>:</p>
-      <ul>
-      <li><span style="background-color: #FFFF00">Resellers/Agents</span>: We're always interested in talking with companies that
-      want to represent
-      <strong>Worx International Inc.</strong> in their markets. We also have private label programs for our commercial products (in certain circumstances).</li>
-      <li>Programmers/Developers: We are usually fully staffed, however, if you would like to be considered for a career with
-      <strong>Worx International Inc.</strong>, we would be pleased to hear from you.<br />
-      A few things to note:<br />
-      <ul>
-        <li>experience level does not matter: from fresh out of college to multi-year experience - it&#39;s your
-        creative mind and a positive attitude we want</li>
-        <li>if you contact us looking for employment, include a cover letter, indicate what type of work/career you are looking for and expected compensation</li>
-        <li>if you are representing someone else looking for work, do not contact us. We have an exclusive relationship with a recruiting partner already and not interested in altering the arrangement. We will not hire your candidate under any circumstances unless they wish to approach us individually.</li>
-        <li>any contact that ignores any of these points will be discarded</li>
-      </ul></li>
-      <li>Affiliates/Partnerships: We are interested in partnering with other firms who are leaders in their field. We clearly understand that successful companies are built on successful relationships in all industries world-wide. We currently have innovative relationships throughout the world that are mutually beneficial. Drop us a line and let&#39;s talk.</li>
-      </ul>
-      Regards,<br />
-      Andy Prevost (aka, codeworxtech)<br />
-      <a href="mailto:codeworxtech@users.sourceforge.net">codeworxtech@users.sourceforge.net</a><br />
-      <br />
-      We now also offer website design. hosting, and remote forms processing. Visit <a href="http://www.worxstudio.com/" target="_blank">WorxStudio.com</a> for more information.<br />
-    </td>
-    <td width="50%" valign="top">
-    <p>Marcus is the technical director of <a href="http://www.synchromedia.co.uk/">Synchromedia Limited</a>, a UK-based company providing online business services. Synchromedia's main services are:</p>
-        <h2>Smartmessages.net</h2>
-      <p><a href="https://www.smartmessages.net/"><img src="http://www.synchromedia.co.uk/uploads/images/smlogo.gif" width="292" height="48" alt="Smartmessages.net logo" /><br />Smartmessages.net</a> is Synchromedia's large-scale mailing list management system, providing email delivery services for a wide range of businesses, from sole traders to corporates.
-      We pride ourselves on personal service, and realise that every one of your subscribers is a precious asset to be handled with care.
-      We provide fast, reliable, high-volume delivery (some of our customers have lists of more than 1,000,000 subscribers) with fine-grained tracking while ensuring you stay fully compliant with UK, EC and US data protection laws. Smartmessages of course uses PHPMailer at its heart!</p>
-    <h2>info@hand</h2>
-      <p><a href="http://www.synchromedia.co.uk/what-we-do/info-at-hand-crm/"><img src="http://www.synchromedia.co.uk/uploads/images/infoathand-large.png" width="250" height="40" alt="info@hand logo" /></a><br />Synchromedia is the official UK distributor of <a href="http://www.thelongreach.com/">info@hand</a>, a class-leading open-source web-based CRM system. We provide licenses, hosting, planning, support and training for this very fully-featured system at very competitive prices. info@hand also uses PHPMailer!</p>
-    <h2>How can we help you?</h2>
-      <p>In addition to our headline services, we also provide consulting, development, hosting and sysadmin services, so if you just need a simple web hosting package, we can do that too. Not surprisingly, we know rather a lot about email, so you can talk to us about that too.</p>
-      <p>Please <a href="http://www.synchromedia.co.uk/about-us/contact-us/">contact us</a> if you'd like to know more.</p>
-      <p>Marcus is a regular attendee at <a href="http://www.phplondon.org/">PHP London</a>, and occasionally speaks on email at technical conferences.</p>
-  </td>
-  </tr>
-</table>
-</div>
-</center>
-</body>
-</html>

+ 0 - 408
main/inc/lib/phpmailer/changelog.txt

@@ -1,408 +0,0 @@
-ChangeLog
-
-NOTE: THIS VERSION OF PHPMAILER IS DESIGNED FOR PHP5/PHP6.
-      IT WILL NOT WORK WITH PHP4.
-
-Version 5.1 (October 20, 2009)
-* fixed filename issue with AddStringAttachment (thanks to Tony)
-* fixed "SingleTo" property, now works with Senmail, Qmail, and SMTP in
-  addition to PHP mail()
-* added DKIM digital signing functionality
-  New properties:
-  - DKIM_domain (sets the domain name)
-  - DKIM_private (holds DKIM private key)
-  - DKIM_passphrase (holds your DKIM passphrase)
-  - DKIM_selector (holds the DKIM "selector")
-  - DKIM_identity (holds the identifying email address)
-* added callback function support
-  - callback function parameters include:
-    result, to, cc, bcc, subject and body
-  * see the test/test_callback.php file for usage.
-* added "auto" identity functionality
-  - can automatically add:
-    - Return-path (if Sender not set)
-    - Reply-To (if ReplyTo not set)
-  - can be disabled:
-    - $mail->SetFrom('yourname@yourdomain.com','First Last',false);
-    - or by adding the $mail->Sender and/or $mail->ReplyTo properties
-  Note: "auto" identity added to help with emails ending up in spam
-  or junk boxes because of missing headers
-
-Version 5.0.2 (May 24, 2009)
-* Fix for missing attachments when inline graphics are present
-* Fix for missing Cc in header when using SMTP (mail was sent,
-  but not displayed in header -- Cc receiver only saw email To: 
-  line and no Cc line, but did get the email (To receiver
-  saw same)
-
-Version 5.0.1 (April 05, 2009)
-* Temporary fix for missing attachments
-
-Version 5.0.0 (April 02, 2009)
-
-* With the release of this version, we are initiating a new version numbering
-  system to differentiate from the PHP4 version of PHPMailer.
-* Most notable in this release is fully object oriented code.
-class.smtp.php:
-* Refactored class.smtp.php to support new exception handling
-  code size reduced from 29.2 Kb to 25.6 Kb
-* Removed unnecessary functions from class.smtp.php:
-  public function Expand($name) {
-  public function Help($keyword="") {
-  public function Noop() {
-  public function Send($from) {
-  public function SendOrMail($from) {
-  public function Verify($name) {
-class.phpmailer.php:
-* Refactored class.phpmailer.php with new exception handling
-* Changed processing functionality of Sendmail and Qmail so they cannot be
-  inadvertently used
-* removed getFile() function, just became a simple wrapper for
-  file_get_contents()
-* added check for PHP version (will gracefully exit if not at least PHP 5.0)
-class.phpmailer.php enhancements
-* enhanced code to check if an attachment source is the same as an embedded or
-  inline graphic source to eliminate duplicate attachments
-New /test_script
-* We have written a test script you can use to test the script as part of your
-  installation. Once you press submit, the test script will send a multi-mime
-  email with either the message you type in or an HTML email with an inline
-  graphic. Two attachments are included in the email (one of the attachments
-  is also the inline graphic so you can see that only one copy of the graphic
-  is sent in the email). The test script will also display the functional
-  script that you can copy/paste to your editor to duplicate the functionality.
-New examples
-* All new examples in both basic and advanced modes. Advanced examples show
-  Exception handling.
-PHPDocumentator (phpdocs) documentation for PHPMailer version 5.0.0
-* all new documentation
-
-Please note: the website has been updated to reflect the changes in PHPMailer
-version 5.0.0. http://phpmailer.codeworxtech.com/
-
-Version 2.3 (November 06, 2008)
-
-* added Arabic language (many thanks to Bahjat Al Mostafa)
-* removed English language from language files and made it a default within
-  class.phpmailer.php - if no language is found, it will default to use
-  the english language translation
-* fixed public/private declarations
-* corrected line 1728, $basedir to $directory
-* added $sign_cert_file to avoid improper duplicate use of $sign_key_file
-* corrected $this->Hello on line 612 to $this->Helo
-* changed default of $LE to "\r\n" to comply with RFC 2822. Can be set by the user
-  if default is not acceptable
-* removed trim() from return results in EncodeQP
-* /test and three files it contained are removed from version 2.3
-* fixed phpunit.php for compliance with PHP5
-* changed $this->AltBody = $textMsg; to $this->AltBody = html_entity_decode($textMsg);
-* We have removed the /phpdoc from the downloads. All documentation is now on
-  the http://phpmailer.codeworxtech.com website.
-
-Version 2.2.1 () July 19 2008
-
-* fixed line 1092 in class.smtp.php (my apologies, error on my part)
-
-Version 2.2 () July 15 2008
-
-* Fixed redirect issue (display of UTF-8 in thank you redirect)
-* fixed error in getResponse function declaration (class.pop3.php)
-* PHPMailer now PHP6 compliant
-* fixed line 1092 in class.smtp.php (endless loop from missing = sign)
-
-Version 2.1 (Wed, June 04 2008)
-
-** NOTE: WE HAVE A NEW LANGUAGE VARIABLE FOR DIGITALLY SIGNED S/MIME EMAILS.
-   IF YOU CAN HELP WITH LANGUAGES OTHER THAN ENGLISH AND SPANISH, IT WOULD BE
-   APPRECIATED.
-
-* added S/MIME functionality (ability to digitally sign emails)
-  BIG THANKS TO "sergiocambra" for posting this patch back in November 2007.
-  The "Signed Emails" functionality adds the Sign method to pass the private key
-  filename and the password to read it, and then email will be sent with
-  content-type multipart/signed and with the digital signature attached.
-* fully compatible with E_STRICT error level
-  - Please note:
-    In about half the test environments this development version was subjected
-    to, an error was thrown for the date() functions used (line 1565 and 1569).
-    This is NOT a PHPMailer error, it is the result of an incorrectly configured
-    PHP5 installation. The fix is to modify your 'php.ini' file and include the
-    date.timezone = America/New York
-    directive, to your own server timezone
-  - If you do get this error, and are unable to access your php.ini file:
-    In your PHP script, add
-    date_default_timezone_set('America/Toronto');
-    - do not try to use
-    $myVar = date_default_timezone_get();
-    as a test, it will throw an error.
-* added ability to define path (mainly for embedded images)
-  function MsgHTML($message,$basedir='') ... where:
-  $basedir is the fully qualified path
-* fixed MsgHTML() function:
-  - Embedded Images where images are specified by <protocol>:// will not be altered or embedded
-* fixed the return value of SMTP exit code ( pclose )
-* addressed issue of multibyte characters in subject line and truncating
-* added ability to have user specified Message ID
-  (default is still that PHPMailer create a unique Message ID)
-* corrected unidentified message type to 'application/octet-stream'
-* fixed chunk_split() multibyte issue (thanks to Colin Brown, et al).
-* added check for added attachments
-* enhanced conversion of HTML to text in MsgHTML (thanks to "brunny")
-
-Version 2.1.0beta2 (Sun, Dec 02 2007)
-* implemented updated EncodeQP (thanks to coolbru, aka Marcus Bointon)
-* finished all testing, all known bugs corrected, enhancements tested
-- note: will NOT work with PHP4.
-
-please note, this is BETA software
-** DO NOT USE THIS IN PRODUCTION OR LIVE PROJECTS
-INTENDED STRICTLY FOR TESTING
-
-Version 2.1.0beta1
-please note, this is BETA software
-** DO NOT USE THIS IN PRODUCTION OR LIVE PROJECTS
-INTENDED STRICTLY FOR TESTING
-
-Version 2.0.0 rc2 (Fri, Nov 16 2007), interim release
-* implements new property to control VERP in class.smtp.php
-  example (requires instantiating class.smtp.php):
-  $mail->do_verp = true;
-* POP-before-SMTP functionality included, thanks to Richard Davey
-  (see class.pop3.php & pop3_before_smtp_test.php for examples)
-* included example showing how to use PHPMailer with GMAIL
-* fixed the missing Cc in SendMail() and Mail()
-
-******************
-A note on sending bulk emails:
-
-If the email you are sending is not personalized, consider using the
-"undisclosed-recipient:;" strategy. That is, put all of your recipients
-in the Bcc field and set the To field to "undisclosed-recipients:;".
-It's a lot faster (only one send) and saves quite a bit on resources.
-Contrary to some opinions, this will not get you listed in spam engines -
-it's a legitimate way for you to send emails.
-
-A partial example for use with PHPMailer:
-
-$mail->AddAddress("undisclosed-recipients:;");
-$mail->AddBCC("email1@anydomain.com,email2@anyotherdomain.com,email3@anyalternatedomain.com");
-
-Many email service providers restrict the number of emails that can be sent
-in any given time period. Often that is between 50 - 60 emails maximum
-per hour or per send session.
-
-If that's the case, then break up your Bcc lists into chunks that are one
-less than your limit, and put a pause in your script.
-*******************
-
-Version 2.0.0 rc1 (Thu, Nov 08 2007), interim release
-* dramatically simplified using inline graphics ... it's fully automated and requires no user input
-* added automatic document type detection for attachments and pictures
-* added MsgHTML() function to replace Body tag for HTML emails
-* fixed the SendMail security issues (input validation vulnerability)
-* enhanced the AddAddresses functionality so that the "Name" portion is used in the email address
-* removed the need to use the AltBody method (set from the HTML, or default text used)
-* set the PHP Mail() function as the default (still support SendMail, SMTP Mail)
-* removed the need to set the IsHTML property (set automatically)
-* added Estonian language file by Indrek P&auml;ri
-* added header injection patch
-* added "set" method to permit users to create their own pseudo-properties like 'X-Headers', etc.
-  example of use:
-  $mail->set('X-Priority', '3');
-  $mail->set('X-MSMail-Priority', 'Normal');
-* fixed warning message in SMTP get_lines method
-* added TLS/SSL SMTP support
-  example of use:
-  $mail = new PHPMailer();
-  $mail->Mailer = "smtp";
-  $mail->Host = "smtp.example.com";
-  $mail->SMTPSecure   = "tls"; // option
-  //$mail->SMTPSecure   = "ssl";  // option
-  ...
-  $mail->Send();
-* PHPMailer has been tested with PHP4 (4.4.7) and PHP5 (5.2.7)
-* Works with PHP installed as a module or as CGI-PHP
-- NOTE: will NOT work with PHP5 in E_STRICT error mode
-
-Version 1.73 (Sun, Jun 10 2005)
-* Fixed denial of service bug: http://www.cybsec.com/vuln/PHPMailer-DOS.pdf
-* Now has a total of 20 translations
-* Fixed alt attachments bug: http://tinyurl.com/98u9k
-
-Version 1.72 (Wed, May 25 2004)
-* Added Dutch, Swedish, Czech, Norwegian, and Turkish translations.
-* Received: Removed this method because spam filter programs like
-SpamAssassin reject this header.
-* Fixed error count bug.
-* SetLanguage default is now "language/".
-* Fixed magic_quotes_runtime bug.
-
-Version 1.71 (Tue, Jul 28 2003)
-* Made several speed enhancements
-* Added German and Italian translation files
-* Fixed HELO/AUTH bugs on keep-alive connects
-* Now provides an error message if language file does not load
-* Fixed attachment EOL bug
-* Updated some unclear documentation
-* Added additional tests and improved others
-
-Version 1.70 (Mon, Jun 20 2003)
-* Added SMTP keep-alive support
-* Added IsError method for error detection
-* Added error message translation support (SetLanguage)
-* Refactored many methods to increase library performance
-* Hello now sends the newer EHLO message before HELO as per RFC 2821
-* Removed the boundary class and replaced it with GetBoundary
-* Removed queue support methods
-* New $Hostname variable
-* New Message-ID header
-* Received header reformat
-* Helo variable default changed to $Hostname
-* Removed extra spaces in Content-Type definition (#667182)
-* Return-Path should be set to Sender when set
-* Adds Q or B encoding to headers when necessary
-* quoted-encoding should now encode NULs \000
-* Fixed encoding of body/AltBody (#553370)
-* Adds "To: undisclosed-recipients:;" when all recipients are hidden (BCC)
-* Multiple bug fixes
-
-Version 1.65 (Fri, Aug 09 2002)
-* Fixed non-visible attachment bug (#585097) for Outlook
-* SMTP connections are now closed after each transaction
-* Fixed SMTP::Expand return value
-* Converted SMTP class documentation to phpDocumentor format
-
-Version 1.62 (Wed, Jun 26 2002)
-* Fixed multi-attach bug
-* Set proper word wrapping
-* Reduced memory use with attachments
-* Added more debugging
-* Changed documentation to phpDocumentor format
-
-Version 1.60 (Sat, Mar 30 2002)
-* Sendmail pipe and address patch (Christian Holtje)
-* Added embedded image and read confirmation support (A. Ognio)
-* Added unit tests
-* Added SMTP timeout support (*nix only)
-* Added possibly temporary PluginDir variable for SMTP class
-* Added LE message line ending variable
-* Refactored boundary and attachment code
-* Eliminated SMTP class warnings
-* Added SendToQueue method for future queuing support
-
-Version 1.54 (Wed, Dec 19 2001)
-* Add some queuing support code
-* Fixed a pesky multi/alt bug
-* Messages are no longer forced to have "To" addresses
-
-Version 1.50 (Thu, Nov 08 2001)
-* Fix extra lines when not using SMTP mailer
-* Set WordWrap variable to int with a zero default
-
-Version 1.47 (Tue, Oct 16 2001)
-* Fixed Received header code format
-* Fixed AltBody order error
-* Fixed alternate port warning
-
-Version 1.45 (Tue, Sep 25 2001)
-* Added enhanced SMTP debug support
-* Added support for multiple ports on SMTP
-* Added Received header for tracing
-* Fixed AddStringAttachment encoding
-* Fixed possible header name quote bug
-* Fixed wordwrap() trim bug
-* Couple other small bug fixes
-
-Version 1.41 (Wed, Aug 22 2001)
-* Fixed AltBody bug w/o attachments
-* Fixed rfc_date() for certain mail servers
-
-Version 1.40 (Sun, Aug 12 2001)
-* Added multipart/alternative support (AltBody)
-* Documentation update
-* Fixed bug in Mercury MTA
-
-Version 1.29 (Fri, Aug 03 2001)
-* Added AddStringAttachment() method
-* Added SMTP authentication support
-
-Version 1.28 (Mon, Jul 30 2001)
-* Fixed a typo in SMTP class
-* Fixed header issue with Imail (win32) SMTP server
-* Made fopen() calls for attachments use "rb" to fix win32 error
-
-Version 1.25 (Mon, Jul 02 2001)
-* Added RFC 822 date fix (Patrice)
-* Added improved error handling by adding a $ErrorInfo variable
-* Removed MailerDebug variable (obsolete with new error handler)
-
-Version 1.20 (Mon, Jun 25 2001)
-* Added quoted-printable encoding (Patrice)
-* Set Version as public and removed PrintVersion()
-* Changed phpdoc to only display public variables and methods
-
-Version 1.19 (Thu, Jun 21 2001)
-* Fixed MS Mail header bug
-* Added fix for Bcc problem with mail(). *Does not work on Win32*
-  (See PHP bug report: http://www.php.net/bugs.php?id=11616)
-* mail() no longer passes a fifth parameter when not needed
-
-Version 1.15 (Fri, Jun 15 2001)
-[Note: these changes contributed by Patrice Fournier]
-* Changed all remaining \n to \r\n
-* Bcc: header no longer writen to message except
-when sent directly to sendmail
-* Added a small message to non-MIME compliant mail reader
-* Added Sender variable to change the Sender email
-used in -f for sendmail/mail and in 'MAIL FROM' for smtp mode
-* Changed boundary setting to a place it will be set only once
-* Removed transfer encoding for whole message when using multipart
-* Message body now uses Encoding in multipart messages
-* Can set encoding and type to attachments 7bit, 8bit
-and binary attachment are sent as is, base64 are encoded
-* Can set Encoding to base64 to send 8 bits body
-through 7 bits servers
-
-Version 1.10 (Tue, Jun 12 2001)
-* Fixed win32 mail header bug (printed out headers in message body)
-
-Version 1.09 (Fri, Jun 08 2001)
-* Changed date header to work with Netscape mail programs
-* Altered phpdoc documentation
-
-Version 1.08 (Tue, Jun 05 2001)
-* Added enhanced error-checking
-* Added phpdoc documentation to source
-
-Version 1.06 (Fri, Jun 01 2001)
-* Added optional name for file attachments
-
-Version 1.05 (Tue, May 29 2001)
-* Code cleanup
-* Eliminated sendmail header warning message
-* Fixed possible SMTP error
-
-Version 1.03 (Thu, May 24 2001)
-* Fixed problem where qmail sends out duplicate messages
-
-Version 1.02 (Wed, May 23 2001)
-* Added multiple recipient and attachment Clear* methods
-* Added Sendmail public variable
-* Fixed problem with loading SMTP library multiple times
-
-Version 0.98 (Tue, May 22 2001)
-* Fixed problem with redundant mail hosts sending out multiple messages
-* Added additional error handler code
-* Added AddCustomHeader() function
-* Added support for Microsoft mail client headers (affects priority)
-* Fixed small bug with Mailer variable
-* Added PrintVersion() function
-
-Version 0.92 (Tue, May 15 2001)
-* Changed file names to class.phpmailer.php and class.smtp.php to match
-  current PHP class trend.
-* Fixed problem where body not being printed when a message is attached
-* Several small bug fixes
-
-Version 0.90 (Tue, April 17 2001)
-* Intial public release

+ 0 - 2331
main/inc/lib/phpmailer/class.phpmailer.php

@@ -1,2331 +0,0 @@
-<?php
-/*~ class.phpmailer.php
-.---------------------------------------------------------------------------.
-|  Software: PHPMailer - PHP email class                                    |
-|   Version: 5.1                                                            |
-|   Contact: via sourceforge.net support pages (also www.worxware.com)      |
-|      Info: http://phpmailer.sourceforge.net                               |
-|   Support: http://sourceforge.net/projects/phpmailer/                     |
-| ------------------------------------------------------------------------- |
-|     Admin: Andy Prevost (project admininistrator)                         |
-|   Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
-|          : Marcus Bointon (coolbru) coolbru@users.sourceforge.net         |
-|   Founder: Brent R. Matzelle (original founder)                           |
-| Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved.               |
-| Copyright (c) 2001-2003, Brent R. Matzelle                                |
-| ------------------------------------------------------------------------- |
-|   License: Distributed under the Lesser General Public License (LGPL)     |
-|            http://www.gnu.org/copyleft/lesser.html                        |
-| This program is distributed in the hope that it will be useful - WITHOUT  |
-| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or     |
-| FITNESS FOR A PARTICULAR PURPOSE.                                         |
-| ------------------------------------------------------------------------- |
-| We offer a number of paid services (www.worxware.com):                    |
-| - Web Hosting on highly optimized fast and secure servers                 |
-| - Technology Consulting                                                   |
-| - Oursourcing (highly qualified programmers and graphic designers)        |
-'---------------------------------------------------------------------------'
-*/
-
-/**
- * PHPMailer - PHP email transport class
- * NOTE: Requires PHP version 5 or later
- * @package PHPMailer
- * @author Andy Prevost
- * @author Marcus Bointon
- * @copyright 2004 - 2009 Andy Prevost
- * @version $Id: class.phpmailer.php 447 2009-05-25 01:36:38Z codeworxtech $
- * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
- */
-
-if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
-
-class PHPMailer {
-
-  /////////////////////////////////////////////////
-  // PROPERTIES, PUBLIC
-  /////////////////////////////////////////////////
-
-  /**
-   * Email priority (1 = High, 3 = Normal, 5 = low).
-   * @var int
-   */
-  public $Priority          = 3;
-
-  /**
-   * Sets the CharSet of the message.
-   * @var string
-   */
-  public $CharSet           = 'iso-8859-1';
-
-  /**
-   * Sets the Content-type of the message.
-   * @var string
-   */
-  public $ContentType       = 'text/plain';
-
-  /**
-   * Sets the Encoding of the message. Options for this are
-   *  "8bit", "7bit", "binary", "base64", and "quoted-printable".
-   * @var string
-   */
-  public $Encoding          = '8bit';
-
-  /**
-   * Holds the most recent mailer error message.
-   * @var string
-   */
-  public $ErrorInfo         = '';
-
-  /**
-   * Sets the From email address for the message.
-   * @var string
-   */
-  public $From              = 'root@localhost';
-
-  /**
-   * Sets the From name of the message.
-   * @var string
-   */
-  public $FromName          = 'Root User';
-
-  /**
-   * Sets the Sender email (Return-Path) of the message.  If not empty,
-   * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
-   * @var string
-   */
-  public $Sender            = '';
-
-  /**
-   * Sets the Subject of the message.
-   * @var string
-   */
-  public $Subject           = '';
-
-  /**
-   * Sets the Body of the message.  This can be either an HTML or text body.
-   * If HTML then run IsHTML(true).
-   * @var string
-   */
-  public $Body              = '';
-
-  /**
-   * Sets the text-only body of the message.  This automatically sets the
-   * email to multipart/alternative.  This body can be read by mail
-   * clients that do not have HTML email capability such as mutt. Clients
-   * that can read HTML will view the normal Body.
-   * @var string
-   */
-  public $AltBody           = '';
-
-  /**
-   * Sets word wrapping on the body of the message to a given number of
-   * characters.
-   * @var int
-   */
-  public $WordWrap          = 0;
-
-  /**
-   * Method to send mail: ("mail", "sendmail", or "smtp").
-   * @var string
-   */
-  public $Mailer            = 'mail';
-
-  /**
-   * Sets the path of the sendmail program.
-   * @var string
-   */
-  public $Sendmail          = '/usr/sbin/sendmail';
-
-  /**
-   * Path to PHPMailer plugins.  Useful if the SMTP class
-   * is in a different directory than the PHP include path.
-   * @var string
-   */
-  public $PluginDir         = '';
-
-  /**
-   * Sets the email address that a reading confirmation will be sent.
-   * @var string
-   */
-  public $ConfirmReadingTo  = '';
-
-  /**
-   * Sets the hostname to use in Message-Id and Received headers
-   * and as default HELO string. If empty, the value returned
-   * by SERVER_NAME is used or 'localhost.localdomain'.
-   * @var string
-   */
-  public $Hostname          = '';
-
-  /**
-   * Sets the message ID to be used in the Message-Id header.
-   * If empty, a unique id will be generated.
-   * @var string
-   */
-  public $MessageID         = '';
-
-  /////////////////////////////////////////////////
-  // PROPERTIES FOR SMTP
-  /////////////////////////////////////////////////
-
-  /**
-   * Sets the SMTP hosts.  All hosts must be separated by a
-   * semicolon.  You can also specify a different port
-   * for each host by using this format: [hostname:port]
-   * (e.g. "smtp1.example.com:25;smtp2.example.com").
-   * Hosts will be tried in order.
-   * @var string
-   */
-  public $Host          = 'localhost';
-
-  /**
-   * Sets the default SMTP server port.
-   * @var int
-   */
-  public $Port          = 25;
-
-  /**
-   * Sets the SMTP HELO of the message (Default is $Hostname).
-   * @var string
-   */
-  public $Helo          = '';
-
-  /**
-   * Sets connection prefix.
-   * Options are "", "ssl" or "tls"
-   * @var string
-   */
-  public $SMTPSecure    = '';
-
-  /**
-   * Sets SMTP authentication. Utilizes the Username and Password variables.
-   * @var bool
-   */
-  public $SMTPAuth      = false;
-
-  /**
-   * Sets SMTP username.
-   * @var string
-   */
-  public $Username      = '';
-
-  /**
-   * Sets SMTP password.
-   * @var string
-   */
-  public $Password      = '';
-
-  /**
-   * Sets the SMTP server timeout in seconds.
-   * This function will not work with the win32 version.
-   * @var int
-   */
-  public $Timeout       = 10;
-
-  /**
-   * Sets SMTP class debugging on or off.
-   * @var bool
-   */
-  public $SMTPDebug     = false;
-
-  /**
-   * Prevents the SMTP connection from being closed after each mail
-   * sending.  If this is set to true then to close the connection
-   * requires an explicit call to SmtpClose().
-   * @var bool
-   */
-  public $SMTPKeepAlive = false;
-
-  /**
-   * Provides the ability to have the TO field process individual
-   * emails, instead of sending to entire TO addresses
-   * @var bool
-   */
-  public $SingleTo      = false;
-
-   /**
-   * If SingleTo is true, this provides the array to hold the email addresses
-   * @var bool
-   */
-  public $SingleToArray = array();
-
- /**
-   * Provides the ability to change the line ending
-   * @var string
-   */
-  public $LE              = "\n";
-
-  /**
-   * Used with DKIM DNS Resource Record
-   * @var string
-   */
-  public $DKIM_selector   = 'phpmailer';
-
-  /**
-   * Used with DKIM DNS Resource Record
-   * optional, in format of email address 'you@yourdomain.com'
-   * @var string
-   */
-  public $DKIM_identity   = '';
-
-  /**
-   * Used with DKIM DNS Resource Record
-   * optional, in format of email address 'you@yourdomain.com'
-   * @var string
-   */
-  public $DKIM_domain     = '';
-
-  /**
-   * Used with DKIM DNS Resource Record
-   * optional, in format of email address 'you@yourdomain.com'
-   * @var string
-   */
-  public $DKIM_private    = '';
-
-  /**
-   * Callback Action function name
-   * the function that handles the result of the send email action. Parameters:
-   *   bool    $result        result of the send action
-   *   string  $to            email address of the recipient
-   *   string  $cc            cc email addresses
-   *   string  $bcc           bcc email addresses
-   *   string  $subject       the subject
-   *   string  $body          the email body
-   * @var string
-   */
-  public $action_function = ''; //'callbackAction';
-
-  /**
-   * Sets the PHPMailer Version number
-   * @var string
-   */
-  public $Version         = '5.1';
-
-  /////////////////////////////////////////////////
-  // PROPERTIES, PRIVATE AND PROTECTED
-  /////////////////////////////////////////////////
-
-  private   $smtp           = NULL;
-  private   $to             = array();
-  private   $cc             = array();
-  private   $bcc            = array();
-  private   $ReplyTo        = array();
-  private   $all_recipients = array();
-  private   $attachment     = array();
-  private   $CustomHeader   = array();
-  private   $message_type   = '';
-  private   $boundary       = array();
-  protected $language       = array();
-  private   $error_count    = 0;
-  private   $sign_cert_file = "";
-  private   $sign_key_file  = "";
-  private   $sign_key_pass  = "";
-  private   $exceptions     = false;
-
-  /////////////////////////////////////////////////
-  // CONSTANTS
-  /////////////////////////////////////////////////
-
-  const STOP_MESSAGE  = 0; // message only, continue processing
-  const STOP_CONTINUE = 1; // message?, likely ok to continue processing
-  const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
-
-  /////////////////////////////////////////////////
-  // METHODS, VARIABLES
-  /////////////////////////////////////////////////
-
-  /**
-   * Constructor
-   * @param boolean $exceptions Should we throw external exceptions?
-   */
-  public function __construct($exceptions = false) {
-    $this->exceptions = ($exceptions == true);
-  }
-
-  /**
-   * Sets message type to HTML.
-   * @param bool $ishtml
-   * @return void
-   */
-  public function IsHTML($ishtml = true) {
-    if ($ishtml) {
-      $this->ContentType = 'text/html';
-    } else {
-      $this->ContentType = 'text/plain';
-    }
-  }
-
-  /**
-   * Sets Mailer to send message using SMTP.
-   * @return void
-   */
-  public function IsSMTP() {
-    $this->Mailer = 'smtp';
-  }
-
-  /**
-   * Sets Mailer to send message using PHP mail() function.
-   * @return void
-   */
-  public function IsMail() {
-    $this->Mailer = 'mail';
-  }
-
-  /**
-   * Sets Mailer to send message using the $Sendmail program.
-   * @return void
-   */
-  public function IsSendmail() {
-    if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
-      $this->Sendmail = '/var/qmail/bin/sendmail';
-    }
-    $this->Mailer = 'sendmail';
-  }
-
-  /**
-   * Sets Mailer to send message using the qmail MTA.
-   * @return void
-   */
-  public function IsQmail() {
-    if (stristr(ini_get('sendmail_path'), 'qmail')) {
-      $this->Sendmail = '/var/qmail/bin/sendmail';
-    }
-    $this->Mailer = 'sendmail';
-  }
-
-  /////////////////////////////////////////////////
-  // METHODS, RECIPIENTS
-  /////////////////////////////////////////////////
-
-  /**
-   * Adds a "To" address.
-   * @param string $address
-   * @param string $name
-   * @return boolean true on success, false if address already used
-   */
-  public function AddAddress($address, $name = '') {
-    return $this->AddAnAddress('to', $address, $name);
-  }
-
-  /**
-   * Adds a "Cc" address.
-   * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
-   * @param string $address
-   * @param string $name
-   * @return boolean true on success, false if address already used
-   */
-  public function AddCC($address, $name = '') {
-    return $this->AddAnAddress('cc', $address, $name);
-  }
-
-  /**
-   * Adds a "Bcc" address.
-   * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
-   * @param string $address
-   * @param string $name
-   * @return boolean true on success, false if address already used
-   */
-  public function AddBCC($address, $name = '') {
-    return $this->AddAnAddress('bcc', $address, $name);
-  }
-
-  /**
-   * Adds a "Reply-to" address.
-   * @param string $address
-   * @param string $name
-   * @return boolean
-   */
-  public function AddReplyTo($address, $name = '') {
-    return $this->AddAnAddress('ReplyTo', $address, $name);
-  }
-
-  /**
-   * Adds an address to one of the recipient arrays
-   * Addresses that have been added already return false, but do not throw exceptions
-   * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
-   * @param string $address The email address to send to
-   * @param string $name
-   * @return boolean true on success, false if address already used or invalid in some way
-   * @access private
-   */
-  private function AddAnAddress($kind, $address, $name = '') {
-    if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) {
-      error_log('Invalid recipient array: ' . $kind);
-      return false;
-    }
-    $address = trim($address);
-    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
-    if (!self::ValidateAddress($address)) {
-      $this->SetError($this->Lang('invalid_address').': '. $address);
-      if ($this->exceptions) {
-        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
-      }
-      error_log($this->Lang('invalid_address').': '.$address);
-      return false;
-    }
-    if ($kind != 'ReplyTo') {
-      if (!isset($this->all_recipients[strtolower($address)])) {
-        array_push($this->$kind, array($address, $name));
-        $this->all_recipients[strtolower($address)] = true;
-        return true;
-      }
-    } else {
-      if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
-        $this->ReplyTo[strtolower($address)] = array($address, $name);
-      return true;
-    }
-  }
-  return false;
-}
-
-/**
- * Set the From and FromName properties
- * @param string $address
- * @param string $name
- * @return boolean
- */
-  public function SetFrom($address, $name = '',$auto=1) {
-    $address = trim($address);
-    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
-    if (!self::ValidateAddress($address)) {
-      $this->SetError($this->Lang('invalid_address').': '. $address);
-      if ($this->exceptions) {
-        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
-      }
-      error_log($this->Lang('invalid_address').': '.$address);
-      return false;
-    }
-    $this->From = $address;
-    $this->FromName = $name;
-    if ($auto) {
-      if (empty($this->ReplyTo)) {
-        $this->AddAnAddress('ReplyTo', $address, $name);
-      }
-      if (empty($this->Sender)) {
-        $this->Sender = $address;
-      }
-    }
-    return true;
-  }
-
-  /**
-   * Check that a string looks roughly like an email address should
-   * Static so it can be used without instantiation
-   * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator
-   * Conforms approximately to RFC2822
-   * @link http://www.hexillion.com/samples/#Regex Original pattern found here
-   * @param string $address The email address to check
-   * @return boolean
-   * @static
-   * @access public
-   */
-  public static function ValidateAddress($address) {
-    if (function_exists('filter_var')) { //Introduced in PHP 5.2
-      if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) {
-        return false;
-      } else {
-        return true;
-      }
-    } else {
-      return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
-    }
-  }
-
-  /////////////////////////////////////////////////
-  // METHODS, MAIL SENDING
-  /////////////////////////////////////////////////
-
-  /**
-   * Creates message and assigns Mailer. If the message is
-   * not sent successfully then it returns false.  Use the ErrorInfo
-   * variable to view description of the error.
-   * @return bool
-   */
-  public function Send() {
-    try {
-      if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
-        throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
-      }
-
-      // Set whether the message is multipart/alternative
-      if(!empty($this->AltBody)) {
-        $this->ContentType = 'multipart/alternative';
-      }
-
-      $this->error_count = 0; // reset errors
-      $this->SetMessageType();
-      $header = $this->CreateHeader();
-      $body = $this->CreateBody();
-
-      if (empty($this->Body)) {
-        throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
-      }
-
-      // digitally sign with DKIM if enabled
-      if ($this->DKIM_domain && $this->DKIM_private) {
-        $header_dkim = $this->DKIM_Add($header,$this->Subject,$body);
-        $header = str_replace("\r\n","\n",$header_dkim) . $header;
-      }
-
-      // Choose the mailer and send through it
-      switch($this->Mailer) {
-        case 'sendmail':
-          return $this->SendmailSend($header, $body);
-        case 'smtp':
-          return $this->SmtpSend($header, $body);
-        default:
-          return $this->MailSend($header, $body);
-      }
-
-    } catch (phpmailerException $e) {
-      $this->SetError($e->getMessage());
-      if ($this->exceptions) {
-        throw $e;
-      }
-      return false;
-    }
-  }
-
-  /**
-   * Sends mail using the $Sendmail program.
-   * @param string $header The message headers
-   * @param string $body The message body
-   * @access protected
-   * @return bool
-   */
-  protected function SendmailSend($header, $body) {
-    if ($this->Sender != '') {
-      $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
-    } else {
-      $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
-    }
-    if ($this->SingleTo === true) {
-      foreach ($this->SingleToArray as $key => $val) {
-        if(!@$mail = popen($sendmail, 'w')) {
-          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
-        }
-        fputs($mail, "To: " . $val . "\n");
-        fputs($mail, $header);
-        fputs($mail, $body);
-        $result = pclose($mail);
-        // implement call back function if it exists
-        $isSent = ($result == 0) ? 1 : 0;
-        $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
-        if($result != 0) {
-          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
-        }
-      }
-    } else {
-      if(!@$mail = popen($sendmail, 'w')) {
-        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
-      }
-      fputs($mail, $header);
-      fputs($mail, $body);
-      $result = pclose($mail);
-      // implement call back function if it exists
-      $isSent = ($result == 0) ? 1 : 0;
-      $this->doCallback($isSent,$this->to,$this->cc,$this->bcc,$this->Subject,$body);
-      if($result != 0) {
-        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
-      }
-    }
-    return true;
-  }
-
-  /**
-   * Sends mail using the PHP mail() function.
-   * @param string $header The message headers
-   * @param string $body The message body
-   * @access protected
-   * @return bool
-   */
-  protected function MailSend($header, $body) {
-    $toArr = array();
-    foreach($this->to as $t) {
-      $toArr[] = $this->AddrFormat($t);
-    }
-    $to = implode(', ', $toArr);
-
-    $params = sprintf("-oi -f %s", $this->Sender);
-    if ($this->Sender != '' && strlen(ini_get('safe_mode'))< 1) {
-      $old_from = ini_get('sendmail_from');
-      ini_set('sendmail_from', $this->Sender);
-      if ($this->SingleTo === true && count($toArr) > 1) {
-        foreach ($toArr as $key => $val) {
-          $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
-          // implement call back function if it exists
-          $isSent = ($rt == 1) ? 1 : 0;
-          $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
-        }
-      } else {
-        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
-        // implement call back function if it exists
-        $isSent = ($rt == 1) ? 1 : 0;
-        $this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body);
-      }
-    } else {
-      if ($this->SingleTo === true && count($toArr) > 1) {
-        foreach ($toArr as $key => $val) {
-          $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
-          // implement call back function if it exists
-          $isSent = ($rt == 1) ? 1 : 0;
-          $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
-        }
-      } else {
-        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
-        // implement call back function if it exists
-        $isSent = ($rt == 1) ? 1 : 0;
-        $this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body);
-      }
-    }
-    if (isset($old_from)) {
-      ini_set('sendmail_from', $old_from);
-    }
-    if(!$rt) {
-      throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
-    }
-    return true;
-  }
-
-  /**
-   * Sends mail via SMTP using PhpSMTP
-   * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
-   * @param string $header The message headers
-   * @param string $body The message body
-   * @uses SMTP
-   * @access protected
-   * @return bool
-   */
-  protected function SmtpSend($header, $body) {
-    require_once $this->PluginDir . 'class.smtp.php';
-    $bad_rcpt = array();
-
-    if(!$this->SmtpConnect()) {
-      throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
-    }
-    $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
-    if(!$this->smtp->Mail($smtp_from)) {
-      throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);
-    }
-
-    // Attempt to send attach all recipients
-    foreach($this->to as $to) {
-      if (!$this->smtp->Recipient($to[0])) {
-        $bad_rcpt[] = $to[0];
-        // implement call back function if it exists
-        $isSent = 0;
-        $this->doCallback($isSent,$to[0],'','',$this->Subject,$body);
-      } else {
-        // implement call back function if it exists
-        $isSent = 1;
-        $this->doCallback($isSent,$to[0],'','',$this->Subject,$body);
-      }
-    }
-    foreach($this->cc as $cc) {
-      if (!$this->smtp->Recipient($cc[0])) {
-        $bad_rcpt[] = $cc[0];
-        // implement call back function if it exists
-        $isSent = 0;
-        $this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body);
-      } else {
-        // implement call back function if it exists
-        $isSent = 1;
-        $this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body);
-      }
-    }
-    foreach($this->bcc as $bcc) {
-      if (!$this->smtp->Recipient($bcc[0])) {
-        $bad_rcpt[] = $bcc[0];
-        // implement call back function if it exists
-        $isSent = 0;
-        $this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body);
-      } else {
-        // implement call back function if it exists
-        $isSent = 1;
-        $this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body);
-      }
-    }
-
-
-    if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
-      $badaddresses = implode(', ', $bad_rcpt);
-      throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
-    }
-    if(!$this->smtp->Data($header . $body)) {
-      throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
-    }
-    if($this->SMTPKeepAlive == true) {
-      $this->smtp->Reset();
-    }
-    return true;
-  }
-
-  /**
-   * Initiates a connection to an SMTP server.
-   * Returns false if the operation failed.
-   * @uses SMTP
-   * @access public
-   * @return bool
-   */
-  public function SmtpConnect() {
-    if(is_null($this->smtp)) {
-      $this->smtp = new SMTP();
-    }
-
-    $this->smtp->do_debug = $this->SMTPDebug;
-    $hosts = explode(';', $this->Host);
-    $index = 0;
-    $connection = $this->smtp->Connected();
-
-    // Retry while there is no connection
-    try {
-      while($index < count($hosts) && !$connection) {
-        $hostinfo = array();
-        if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
-          $host = $hostinfo[1];
-          $port = $hostinfo[2];
-        } else {
-          $host = $hosts[$index];
-          $port = $this->Port;
-        }
-
-        $tls = ($this->SMTPSecure == 'tls');
-        $ssl = ($this->SMTPSecure == 'ssl');
-
-        if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
-
-          $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
-          $this->smtp->Hello($hello);
-
-          if ($tls) {
-            if (!$this->smtp->StartTLS()) {
-              throw new phpmailerException($this->Lang('tls'));
-            }
-
-            //We must resend HELO after tls negotiation
-            $this->smtp->Hello($hello);
-          }
-
-          $connection = true;
-          if ($this->SMTPAuth) {
-            if (!$this->smtp->Authenticate($this->Username, $this->Password)) {
-              throw new phpmailerException($this->Lang('authenticate'));
-            }
-          }
-        }
-        $index++;
-        if (!$connection) {
-          throw new phpmailerException($this->Lang('connect_host'));
-        }
-      }
-    } catch (phpmailerException $e) {
-      $this->smtp->Reset();
-      throw $e;
-    }
-    return true;
-  }
-
-  /**
-   * Closes the active SMTP session if one exists.
-   * @return void
-   */
-  public function SmtpClose() {
-    if(!is_null($this->smtp)) {
-      if($this->smtp->Connected()) {
-        $this->smtp->Quit();
-        $this->smtp->Close();
-      }
-    }
-  }
-
-  /**
-  * Sets the language for all class error messages.
-  * Returns false if it cannot load the language file.  The default language is English.
-  * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
-  * @param string $lang_path Path to the language file directory
-  * @access public
-  */
-  function SetLanguage($langcode = 'en', $lang_path = 'language/') {
-    //Define full set of translatable strings
-    $PHPMAILER_LANG = array(
-      'provide_address' => 'You must provide at least one recipient email address.',
-      'mailer_not_supported' => ' mailer is not supported.',
-      'execute' => 'Could not execute: ',
-      'instantiate' => 'Could not instantiate mail function.',
-      'authenticate' => 'SMTP Error: Could not authenticate.',
-      'from_failed' => 'The following From address failed: ',
-      'recipients_failed' => 'SMTP Error: The following recipients failed: ',
-      'data_not_accepted' => 'SMTP Error: Data not accepted.',
-      'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
-      'file_access' => 'Could not access file: ',
-      'file_open' => 'File Error: Could not open file: ',
-      'encoding' => 'Unknown encoding: ',
-      'signing' => 'Signing Error: ',
-      'smtp_error' => 'SMTP server error: ',
-      'empty_message' => 'Message body empty',
-      'invalid_address' => 'Invalid address',
-      'variable_set' => 'Cannot set or reset variable: '
-    );
-    //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
-    $l = true;
-    if ($langcode != 'en') { //There is no English translation file
-      $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
-    }
-    $this->language = $PHPMAILER_LANG;
-    return ($l == true); //Returns false if language not found
-  }
-
-  /**
-  * Return the current array of language strings
-  * @return array
-  */
-  public function GetTranslations() {
-    return $this->language;
-  }
-
-  /////////////////////////////////////////////////
-  // METHODS, MESSAGE CREATION
-  /////////////////////////////////////////////////
-
-  /**
-   * Creates recipient headers.
-   * @access public
-   * @return string
-   */
-  public function AddrAppend($type, $addr) {
-    $addr_str = $type . ': ';
-    $addresses = array();
-    foreach ($addr as $a) {
-      $addresses[] = $this->AddrFormat($a);
-    }
-    $addr_str .= implode(', ', $addresses);
-    $addr_str .= $this->LE;
-
-    return $addr_str;
-  }
-
-  /**
-   * Formats an address correctly.
-   * @access public
-   * @return string
-   */
-  public function AddrFormat($addr) {
-    if (empty($addr[1])) {
-      return $this->SecureHeader($addr[0]);
-    } else {
-      return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
-    }
-  }
-
-  /**
-   * Wraps message for use with mailers that do not
-   * automatically perform wrapping and for quoted-printable.
-   * Original written by philippe.
-   * @param string $message The message to wrap
-   * @param integer $length The line length to wrap to
-   * @param boolean $qp_mode Whether to run in Quoted-Printable mode
-   * @access public
-   * @return string
-   */
-  public function WrapText($message, $length, $qp_mode = false) {
-    $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
-    // If utf-8 encoding is used, we will need to make sure we don't
-    // split multibyte characters when we wrap
-    $is_utf8 = (strtolower($this->CharSet) == "utf-8");
-
-    $message = $this->FixEOL($message);
-    if (substr($message, -1) == $this->LE) {
-      $message = substr($message, 0, -1);
-    }
-
-    $line = explode($this->LE, $message);
-    $message = '';
-    for ($i=0 ;$i < count($line); $i++) {
-      $line_part = explode(' ', $line[$i]);
-      $buf = '';
-      for ($e = 0; $e<count($line_part); $e++) {
-        $word = $line_part[$e];
-        if ($qp_mode and (strlen($word) > $length)) {
-          $space_left = $length - strlen($buf) - 1;
-          if ($e != 0) {
-            if ($space_left > 20) {
-              $len = $space_left;
-              if ($is_utf8) {
-                $len = $this->UTF8CharBoundary($word, $len);
-              } elseif (substr($word, $len - 1, 1) == "=") {
-                $len--;
-              } elseif (substr($word, $len - 2, 1) == "=") {
-                $len -= 2;
-              }
-              $part = substr($word, 0, $len);
-              $word = substr($word, $len);
-              $buf .= ' ' . $part;
-              $message .= $buf . sprintf("=%s", $this->LE);
-            } else {
-              $message .= $buf . $soft_break;
-            }
-            $buf = '';
-          }
-          while (strlen($word) > 0) {
-            $len = $length;
-            if ($is_utf8) {
-              $len = $this->UTF8CharBoundary($word, $len);
-            } elseif (substr($word, $len - 1, 1) == "=") {
-              $len--;
-            } elseif (substr($word, $len - 2, 1) == "=") {
-              $len -= 2;
-            }
-            $part = substr($word, 0, $len);
-            $word = substr($word, $len);
-
-            if (strlen($word) > 0) {
-              $message .= $part . sprintf("=%s", $this->LE);
-            } else {
-              $buf = $part;
-            }
-          }
-        } else {
-          $buf_o = $buf;
-          $buf .= ($e == 0) ? $word : (' ' . $word);
-
-          if (strlen($buf) > $length and $buf_o != '') {
-            $message .= $buf_o . $soft_break;
-            $buf = $word;
-          }
-        }
-      }
-      $message .= $buf . $this->LE;
-    }
-
-    return $message;
-  }
-
-  /**
-   * Finds last character boundary prior to maxLength in a utf-8
-   * quoted (printable) encoded string.
-   * Original written by Colin Brown.
-   * @access public
-   * @param string $encodedText utf-8 QP text
-   * @param int    $maxLength   find last character boundary prior to this length
-   * @return int
-   */
-  public function UTF8CharBoundary($encodedText, $maxLength) {
-    $foundSplitPos = false;
-    $lookBack = 3;
-    while (!$foundSplitPos) {
-      $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
-      $encodedCharPos = strpos($lastChunk, "=");
-      if ($encodedCharPos !== false) {
-        // Found start of encoded character byte within $lookBack block.
-        // Check the encoded byte value (the 2 chars after the '=')
-        $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
-        $dec = hexdec($hex);
-        if ($dec < 128) { // Single byte character.
-          // If the encoded char was found at pos 0, it will fit
-          // otherwise reduce maxLength to start of the encoded char
-          $maxLength = ($encodedCharPos == 0) ? $maxLength :
-          $maxLength - ($lookBack - $encodedCharPos);
-          $foundSplitPos = true;
-        } elseif ($dec >= 192) { // First byte of a multi byte character
-          // Reduce maxLength to split at start of character
-          $maxLength = $maxLength - ($lookBack - $encodedCharPos);
-          $foundSplitPos = true;
-        } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
-          $lookBack += 3;
-        }
-      } else {
-        // No encoded character found
-        $foundSplitPos = true;
-      }
-    }
-    return $maxLength;
-  }
-
-
-  /**
-   * Set the body wrapping.
-   * @access public
-   * @return void
-   */
-  public function SetWordWrap() {
-    if($this->WordWrap < 1) {
-      return;
-    }
-
-    switch($this->message_type) {
-      case 'alt':
-      case 'alt_attachments':
-        $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
-        break;
-      default:
-        $this->Body = $this->WrapText($this->Body, $this->WordWrap);
-        break;
-    }
-  }
-
-  /**
-   * Assembles message header.
-   * @access public
-   * @return string The assembled header
-   */
-  public function CreateHeader() {
-    $result = '';
-
-    // Set the boundaries
-    $uniq_id = md5(uniqid(time()));
-    $this->boundary[1] = 'b1_' . $uniq_id;
-    $this->boundary[2] = 'b2_' . $uniq_id;
-
-    $result .= $this->HeaderLine('Date', self::RFCDate());
-    if($this->Sender == '') {
-      $result .= $this->HeaderLine('Return-Path', trim($this->From));
-    } else {
-      $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
-    }
-
-    // To be created automatically by mail()
-    if($this->Mailer != 'mail') {
-      if ($this->SingleTo === true) {
-        foreach($this->to as $t) {
-          $this->SingleToArray[] = $this->AddrFormat($t);
-        }
-      } else {
-        if(count($this->to) > 0) {
-          $result .= $this->AddrAppend('To', $this->to);
-        } elseif (count($this->cc) == 0) {
-          $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
-        }
-      }
-    }
-
-    $from = array();
-    $from[0][0] = trim($this->From);
-    $from[0][1] = $this->FromName;
-    $result .= $this->AddrAppend('From', $from);
-
-    // sendmail and mail() extract Cc from the header before sending
-    if(count($this->cc) > 0) {
-      $result .= $this->AddrAppend('Cc', $this->cc);
-    }
-
-    // sendmail and mail() extract Bcc from the header before sending
-    if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
-      $result .= $this->AddrAppend('Bcc', $this->bcc);
-    }
-
-    if(count($this->ReplyTo) > 0) {
-      $result .= $this->AddrAppend('Reply-to', $this->ReplyTo);
-    }
-
-    // mail() sets the subject itself
-    if($this->Mailer != 'mail') {
-      $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
-    }
-
-    if($this->MessageID != '') {
-      $result .= $this->HeaderLine('Message-ID',$this->MessageID);
-    } else {
-      $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
-    }
-    $result .= $this->HeaderLine('X-Priority', $this->Priority);
-    $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (phpmailer.sourceforge.net)');
-
-    if($this->ConfirmReadingTo != '') {
-      $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
-    }
-
-    // Add custom headers
-    for($index = 0; $index < count($this->CustomHeader); $index++) {
-      $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
-    }
-    if (!$this->sign_key_file) {
-      $result .= $this->HeaderLine('MIME-Version', '1.0');
-      $result .= $this->GetMailMIME();
-    }
-
-    return $result;
-  }
-
-  /**
-   * Returns the message MIME.
-   * @access public
-   * @return string
-   */
-  public function GetMailMIME() {
-    $result = '';
-    switch($this->message_type) {
-      case 'plain':
-        $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
-        $result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType, $this->CharSet);
-        break;
-      case 'attachments':
-      case 'alt_attachments':
-        if($this->InlineImageExists()){
-          $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE, $this->LE, $this->boundary[1], $this->LE);
-        } else {
-          $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
-          $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
-        }
-        break;
-      case 'alt':
-        $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
-        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
-        break;
-    }
-
-    if($this->Mailer != 'mail') {
-      $result .= $this->LE.$this->LE;
-    }
-
-    return $result;
-  }
-
-  /**
-   * Assembles the message body.  Returns an empty string on failure.
-   * @access public
-   * @return string The assembled message body
-   */
-  public function CreateBody() {
-    $body = '';
-
-    if ($this->sign_key_file) {
-      $body .= $this->GetMailMIME();
-    }
-
-    $this->SetWordWrap();
-
-    switch($this->message_type) {
-      case 'alt':
-        $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
-        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
-        $body .= $this->LE.$this->LE;
-        $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
-        $body .= $this->EncodeString($this->Body, $this->Encoding);
-        $body .= $this->LE.$this->LE;
-        $body .= $this->EndBoundary($this->boundary[1]);
-        break;
-      case 'plain':
-        $body .= $this->EncodeString($this->Body, $this->Encoding);
-        break;
-      case 'attachments':
-        $body .= $this->GetBoundary($this->boundary[1], '', '', '');
-        $body .= $this->EncodeString($this->Body, $this->Encoding);
-        $body .= $this->LE;
-        $body .= $this->AttachAll();
-        break;
-      case 'alt_attachments':
-        $body .= sprintf("--%s%s", $this->boundary[1], $this->LE);
-        $body .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE);
-        $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body
-        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
-        $body .= $this->LE.$this->LE;
-        $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body
-        $body .= $this->EncodeString($this->Body, $this->Encoding);
-        $body .= $this->LE.$this->LE;
-        $body .= $this->EndBoundary($this->boundary[2]);
-        $body .= $this->AttachAll();
-        break;
-    }
-
-    if ($this->IsError()) {
-      $body = '';
-    } elseif ($this->sign_key_file) {
-      try {
-        $file = tempnam('', 'mail');
-        file_put_contents($file, $body); //TODO check this worked
-        $signed = tempnam("", "signed");
-        if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
-          @unlink($file);
-          @unlink($signed);
-          $body = file_get_contents($signed);
-        } else {
-          @unlink($file);
-          @unlink($signed);
-          throw new phpmailerException($this->Lang("signing").openssl_error_string());
-        }
-      } catch (phpmailerException $e) {
-        $body = '';
-        if ($this->exceptions) {
-          throw $e;
-        }
-      }
-    }
-
-    return $body;
-  }
-
-  /**
-   * Returns the start of a message boundary.
-   * @access private
-   */
-  private function GetBoundary($boundary, $charSet, $contentType, $encoding) {
-    $result = '';
-    if($charSet == '') {
-      $charSet = $this->CharSet;
-    }
-    if($contentType == '') {
-      $contentType = $this->ContentType;
-    }
-    if($encoding == '') {
-      $encoding = $this->Encoding;
-    }
-    $result .= $this->TextLine('--' . $boundary);
-    $result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet);
-    $result .= $this->LE;
-    $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
-    $result .= $this->LE;
-
-    return $result;
-  }
-
-  /**
-   * Returns the end of a message boundary.
-   * @access private
-   */
-  private function EndBoundary($boundary) {
-    return $this->LE . '--' . $boundary . '--' . $this->LE;
-  }
-
-  /**
-   * Sets the message type.
-   * @access private
-   * @return void
-   */
-  private function SetMessageType() {
-    if(count($this->attachment) < 1 && strlen($this->AltBody) < 1) {
-      $this->message_type = 'plain';
-    } else {
-      if(count($this->attachment) > 0) {
-        $this->message_type = 'attachments';
-      }
-      if(strlen($this->AltBody) > 0 && count($this->attachment) < 1) {
-        $this->message_type = 'alt';
-      }
-      if(strlen($this->AltBody) > 0 && count($this->attachment) > 0) {
-        $this->message_type = 'alt_attachments';
-      }
-    }
-  }
-
-  /**
-   *  Returns a formatted header line.
-   * @access public
-   * @return string
-   */
-  public function HeaderLine($name, $value) {
-    return $name . ': ' . $value . $this->LE;
-  }
-
-  /**
-   * Returns a formatted mail line.
-   * @access public
-   * @return string
-   */
-  public function TextLine($value) {
-    return $value . $this->LE;
-  }
-
-  /////////////////////////////////////////////////
-  // CLASS METHODS, ATTACHMENTS
-  /////////////////////////////////////////////////
-
-  /**
-   * Adds an attachment from a path on the filesystem.
-   * Returns false if the file could not be found
-   * or accessed.
-   * @param string $path Path to the attachment.
-   * @param string $name Overrides the attachment name.
-   * @param string $encoding File encoding (see $Encoding).
-   * @param string $type File extension (MIME) type.
-   * @return bool
-   */
-  public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
-    try {
-      if ( !@is_file($path) ) {
-        throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
-      }
-      $filename = basename($path);
-      if ( $name == '' ) {
-        $name = $filename;
-      }
-
-      $this->attachment[] = array(
-        0 => $path,
-        1 => $filename,
-        2 => $name,
-        3 => $encoding,
-        4 => $type,
-        5 => false,  // isStringAttachment
-        6 => 'attachment',
-        7 => 0
-      );
-
-    } catch (phpmailerException $e) {
-      $this->SetError($e->getMessage());
-      if ($this->exceptions) {
-        throw $e;
-      }
-      error_log($e->getMessage()."\n");
-      if ( $e->getCode() == self::STOP_CRITICAL ) {
-        return false;
-      }
-    }
-    return true;
-  }
-
-  /**
-  * Return the current array of attachments
-  * @return array
-  */
-  public function GetAttachments() {
-    return $this->attachment;
-  }
-
-  /**
-   * Attaches all fs, string, and binary attachments to the message.
-   * Returns an empty string on failure.
-   * @access private
-   * @return string
-   */
-  private function AttachAll() {
-    // Return text of body
-    $mime = array();
-    $cidUniq = array();
-    $incl = array();
-
-    // Add all attachments
-    foreach ($this->attachment as $attachment) {
-      // Check for string attachment
-      $bString = $attachment[5];
-      if ($bString) {
-        $string = $attachment[0];
-      } else {
-        $path = $attachment[0];
-      }
-
-      if (in_array($attachment[0], $incl)) { continue; }
-      $filename    = $attachment[1];
-      $name        = $attachment[2];
-      $encoding    = $attachment[3];
-      $type        = $attachment[4];
-      $disposition = $attachment[6];
-      $cid         = $attachment[7];
-      $incl[]      = $attachment[0];
-      if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
-      $cidUniq[$cid] = true;
-
-      $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
-      $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
-      $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
-
-      if($disposition == 'inline') {
-        $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
-      }
-
-      $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
-
-      // Encode as string attachment
-      if($bString) {
-        $mime[] = $this->EncodeString($string, $encoding);
-        if($this->IsError()) {
-          return '';
-        }
-        $mime[] = $this->LE.$this->LE;
-      } else {
-        $mime[] = $this->EncodeFile($path, $encoding);
-        if($this->IsError()) {
-          return '';
-        }
-        $mime[] = $this->LE.$this->LE;
-      }
-    }
-
-    $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
-
-    return join('', $mime);
-  }
-
-  /**
-   * Encodes attachment in requested format.
-   * Returns an empty string on failure.
-   * @param string $path The full path to the file
-   * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
-   * @see EncodeFile()
-   * @access private
-   * @return string
-   */
-  private function EncodeFile($path, $encoding = 'base64') {
-    try {
-      if (!is_readable($path)) {
-        throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
-      }
-      if (function_exists('get_magic_quotes')) {
-        function get_magic_quotes() {
-          return false;
-        }
-      }
-      if (PHP_VERSION < 6) {
-        $magic_quotes = get_magic_quotes_runtime();
-        set_magic_quotes_runtime(0);
-      }
-      $file_buffer  = file_get_contents($path);
-      $file_buffer  = $this->EncodeString($file_buffer, $encoding);
-      if (PHP_VERSION < 6) { set_magic_quotes_runtime($magic_quotes); }
-      return $file_buffer;
-    } catch (Exception $e) {
-      $this->SetError($e->getMessage());
-      return '';
-    }
-  }
-
-  /**
-   * Encodes string to requested format.
-   * Returns an empty string on failure.
-   * @param string $str The text to encode
-   * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
-   * @access public
-   * @return string
-   */
-  public function EncodeString ($str, $encoding = 'base64') {
-    $encoded = '';
-    switch(strtolower($encoding)) {
-      case 'base64':
-        $encoded = chunk_split(base64_encode($str), 76, $this->LE);
-        break;
-      case '7bit':
-      case '8bit':
-        $encoded = $this->FixEOL($str);
-        //Make sure it ends with a line break
-        if (substr($encoded, -(strlen($this->LE))) != $this->LE)
-          $encoded .= $this->LE;
-        break;
-      case 'binary':
-        $encoded = $str;
-        break;
-      case 'quoted-printable':
-        $encoded = $this->EncodeQP($str);
-        break;
-      default:
-        $this->SetError($this->Lang('encoding') . $encoding);
-        break;
-    }
-    return $encoded;
-  }
-
-  /**
-   * Encode a header string to best (shortest) of Q, B, quoted or none.
-   * @access public
-   * @return string
-   */
-  public function EncodeHeader($str, $position = 'text') {
-    $x = 0;
-
-    switch (strtolower($position)) {
-      case 'phrase':
-        if (!preg_match('/[\200-\377]/', $str)) {
-          // Can't use addslashes as we don't know what value has magic_quotes_sybase
-          $encoded = addcslashes($str, "\0..\37\177\\\"");
-          if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
-            return ($encoded);
-          } else {
-            return ("\"$encoded\"");
-          }
-        }
-        $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
-        break;
-      case 'comment':
-        $x = preg_match_all('/[()"]/', $str, $matches);
-        // Fall-through
-      case 'text':
-      default:
-        $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
-        break;
-    }
-
-    if ($x == 0) {
-      return ($str);
-    }
-
-    $maxlen = 75 - 7 - strlen($this->CharSet);
-    // Try to select the encoding which should produce the shortest output
-    if (strlen($str)/3 < $x) {
-      $encoding = 'B';
-      // Modified by Ivan Tcholakov, 24-JAN-2010.
-      //if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
-      if ($this->HasMultiBytes($str)) {
-      //
-        // Use a custom function which correctly encodes and wraps long
-        // multibyte strings without breaking lines within a character
-        $encoded = $this->Base64EncodeWrapMB($str);
-      } else {
-        $encoded = base64_encode($str);
-        $maxlen -= $maxlen % 4;
-        $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
-      }
-    } else {
-      $encoding = 'Q';
-      $encoded = $this->EncodeQ($str, $position);
-      $encoded = $this->WrapText($encoded, $maxlen, true);
-      $encoded = str_replace('='.$this->LE, "\n", trim($encoded));
-    }
-
-    $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
-    $encoded = trim(str_replace("\n", $this->LE, $encoded));
-
-    return $encoded;
-  }
-
-  /**
-   * Checks if a string contains multibyte characters.
-   * @access public
-   * @param string $str multi-byte text to wrap encode
-   * @return bool
-   */
-  public function HasMultiBytes($str) {
-  	// Modified by Ivan Tcholakov, 24-JAN-2010.
-    // (function_exists('mb_strlen')) {
-    //  return (strlen($str) > mb_strlen($str, $this->CharSet));
-    //} else { // Assume no multibytes (we can't handle without mbstring functions anyway)
-    //  return false;
-    //}
-    return (api_byte_count($str) > api_strlen($str, $this->CharSet));
-    //
-  }
-
-  /**
-   * Correctly encodes and wraps long multibyte strings for mail headers
-   * without breaking lines within a character.
-   * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
-   * @access public
-   * @param string $str multi-byte text to wrap encode
-   * @return string
-   */
-  public function Base64EncodeWrapMB($str) {
-    $start = "=?".$this->CharSet."?B?";
-    $end = "?=";
-    $encoded = "";
-
-    // Modified by Ivan Tcholakov, 24-JAN-2010.
-    //$mb_length = mb_strlen($str, $this->CharSet);
-    $mb_length = api_strlen($str, $this->CharSet);
-    //
-    // Each line must have length <= 75, including $start and $end
-    $length = 75 - strlen($start) - strlen($end);
-    // Average multi-byte ratio
-    $ratio = $mb_length / strlen($str);
-    // Base64 has a 4:3 ratio
-    $offset = $avgLength = floor($length * $ratio * .75);
-
-    for ($i = 0; $i < $mb_length; $i += $offset) {
-      $lookBack = 0;
-
-      do {
-        $offset = $avgLength - $lookBack;
-        // Modified by Ivan Tcholakov, 24-JAN-2010.
-        //$chunk = mb_substr($str, $i, $offset, $this->CharSet);
-        $chunk = api_substr($str, $i, $offset, $this->CharSet);
-        //
-        $chunk = base64_encode($chunk);
-        $lookBack++;
-      }
-      while (strlen($chunk) > $length);
-
-      $encoded .= $chunk . $this->LE;
-    }
-
-    // Chomp the last linefeed
-    $encoded = substr($encoded, 0, -strlen($this->LE));
-    return $encoded;
-  }
-
-  /**
-  * Encode string to quoted-printable.
-  * Only uses standard PHP, slow, but will always work
-  * @access public
-  * @param string $string the text to encode
-  * @param integer $line_max Number of chars allowed on a line before wrapping
-  * @return string
-  */
-  public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
-    $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
-    $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
-    $eol = "\r\n";
-    $escape = '=';
-    $output = '';
-    while( list(, $line) = each($lines) ) {
-      $linlen = strlen($line);
-      $newline = '';
-      for($i = 0; $i < $linlen; $i++) {
-        $c = substr( $line, $i, 1 );
-        $dec = ord( $c );
-        if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
-          $c = '=2E';
-        }
-        if ( $dec == 32 ) {
-          if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
-            $c = '=20';
-          } else if ( $space_conv ) {
-            $c = '=20';
-          }
-        } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
-          $h2 = floor($dec/16);
-          $h1 = floor($dec%16);
-          $c = $escape.$hex[$h2].$hex[$h1];
-        }
-        if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
-          $output .= $newline.$escape.$eol; //  soft line break; " =\r\n" is okay
-          $newline = '';
-          // check if newline first character will be point or not
-          if ( $dec == 46 ) {
-            $c = '=2E';
-          }
-        }
-        $newline .= $c;
-      } // end of for
-      $output .= $newline.$eol;
-    } // end of while
-    return $output;
-  }
-
-  /**
-  * Encode string to RFC2045 (6.7) quoted-printable format
-  * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version
-  * Also results in same content as you started with after decoding
-  * @see EncodeQPphp()
-  * @access public
-  * @param string $string the text to encode
-  * @param integer $line_max Number of chars allowed on a line before wrapping
-  * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function
-  * @return string
-  * @author Marcus Bointon
-  */
-  public function EncodeQP($string, $line_max = 76, $space_conv = false) {
-    if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
-      return quoted_printable_encode($string);
-    }
-    $filters = stream_get_filters();
-    if (!in_array('convert.*', $filters)) { //Got convert stream filter?
-      return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation
-    }
-    $fp = fopen('php://temp/', 'r+');
-    $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks
-    $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE);
-    $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
-    fputs($fp, $string);
-    rewind($fp);
-    $out = stream_get_contents($fp);
-    stream_filter_remove($s);
-    $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange
-    fclose($fp);
-    return $out;
-  }
-
-  /**
-   * Encode string to q encoding.
-   * @link http://tools.ietf.org/html/rfc2047
-   * @param string $str the text to encode
-   * @param string $position Where the text is going to be used, see the RFC for what that means
-   * @access public
-   * @return string
-   */
-  public function EncodeQ ($str, $position = 'text') {
-    // There should not be any EOL in the string
-    $encoded = preg_replace('/[\r\n]*/', '', $str);
-
-    switch (strtolower($position)) {
-      case 'phrase':
-        $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
-        break;
-      case 'comment':
-        $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
-      case 'text':
-      default:
-        // Replace every high ascii, control =, ? and _ characters
-        //TODO using /e (equivalent to eval()) is probably not a good idea
-        $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
-              "'='.sprintf('%02X', ord('\\1'))", $encoded);
-        break;
-    }
-
-    // Replace every spaces to _ (more readable than =20)
-    $encoded = str_replace(' ', '_', $encoded);
-
-    return $encoded;
-  }
-
-  /**
-   * Adds a string or binary attachment (non-filesystem) to the list.
-   * This method can be used to attach ascii or binary data,
-   * such as a BLOB record from a database.
-   * @param string $string String attachment data.
-   * @param string $filename Name of the attachment.
-   * @param string $encoding File encoding (see $Encoding).
-   * @param string $type File extension (MIME) type.
-   * @return void
-   */
-  public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
-    // Append to $attachment array
-    $this->attachment[] = array(
-      0 => $string,
-      1 => $filename,
-      2 => basename($filename),
-      3 => $encoding,
-      4 => $type,
-      5 => true,  // isStringAttachment
-      6 => 'attachment',
-      7 => 0
-    );
-  }
-
-  /**
-   * Adds an embedded attachment.  This can include images, sounds, and
-   * just about any other document.  Make sure to set the $type to an
-   * image type.  For JPEG images use "image/jpeg" and for GIF images
-   * use "image/gif".
-   * @param string $path Path to the attachment.
-   * @param string $cid Content ID of the attachment.  Use this to identify
-   *        the Id for accessing the image in an HTML form.
-   * @param string $name Overrides the attachment name.
-   * @param string $encoding File encoding (see $Encoding).
-   * @param string $type File extension (MIME) type.
-   * @return bool
-   */
-  public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
-
-    if ( !@is_file($path) ) {
-      $this->SetError($this->Lang('file_access') . $path);
-      return false;
-    }
-
-    $filename = basename($path);
-    if ( $name == '' ) {
-      $name = $filename;
-    }
-
-    // Append to $attachment array
-    $this->attachment[] = array(
-      0 => $path,
-      1 => $filename,
-      2 => $name,
-      3 => $encoding,
-      4 => $type,
-      5 => false,  // isStringAttachment
-      6 => 'inline',
-      7 => $cid
-    );
-
-    return true;
-  }
-
-  /**
-   * Returns true if an inline attachment is present.
-   * @access public
-   * @return bool
-   */
-  public function InlineImageExists() {
-    foreach($this->attachment as $attachment) {
-      if ($attachment[6] == 'inline') {
-        return true;
-      }
-    }
-    return false;
-  }
-
-  /////////////////////////////////////////////////
-  // CLASS METHODS, MESSAGE RESET
-  /////////////////////////////////////////////////
-
-  /**
-   * Clears all recipients assigned in the TO array.  Returns void.
-   * @return void
-   */
-  public function ClearAddresses() {
-    foreach($this->to as $to) {
-      unset($this->all_recipients[strtolower($to[0])]);
-    }
-    $this->to = array();
-  }
-
-  /**
-   * Clears all recipients assigned in the CC array.  Returns void.
-   * @return void
-   */
-  public function ClearCCs() {
-    foreach($this->cc as $cc) {
-      unset($this->all_recipients[strtolower($cc[0])]);
-    }
-    $this->cc = array();
-  }
-
-  /**
-   * Clears all recipients assigned in the BCC array.  Returns void.
-   * @return void
-   */
-  public function ClearBCCs() {
-    foreach($this->bcc as $bcc) {
-      unset($this->all_recipients[strtolower($bcc[0])]);
-    }
-    $this->bcc = array();
-  }
-
-  /**
-   * Clears all recipients assigned in the ReplyTo array.  Returns void.
-   * @return void
-   */
-  public function ClearReplyTos() {
-    $this->ReplyTo = array();
-  }
-
-  /**
-   * Clears all recipients assigned in the TO, CC and BCC
-   * array.  Returns void.
-   * @return void
-   */
-  public function ClearAllRecipients() {
-    $this->to = array();
-    $this->cc = array();
-    $this->bcc = array();
-    $this->all_recipients = array();
-  }
-
-  /**
-   * Clears all previously set filesystem, string, and binary
-   * attachments.  Returns void.
-   * @return void
-   */
-  public function ClearAttachments() {
-    $this->attachment = array();
-  }
-
-  /**
-   * Clears all custom headers.  Returns void.
-   * @return void
-   */
-  public function ClearCustomHeaders() {
-    $this->CustomHeader = array();
-  }
-
-  /////////////////////////////////////////////////
-  // CLASS METHODS, MISCELLANEOUS
-  /////////////////////////////////////////////////
-
-  /**
-   * Adds the error message to the error container.
-   * @access protected
-   * @return void
-   */
-  protected function SetError($msg) {
-    $this->error_count++;
-    if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
-      $lasterror = $this->smtp->getError();
-      if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
-        $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
-      }
-    }
-    $this->ErrorInfo = $msg;
-  }
-
-  /**
-   * Returns the proper RFC 822 formatted date.
-   * @access public
-   * @return string
-   * @static
-   */
-  public static function RFCDate() {
-    $tz = date('Z');
-    $tzs = ($tz < 0) ? '-' : '+';
-    $tz = abs($tz);
-    $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
-    $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
-
-    return $result;
-  }
-
-  /**
-   * Returns the server hostname or 'localhost.localdomain' if unknown.
-   * @access private
-   * @return string
-   */
-  private function ServerHostname() {
-    if (!empty($this->Hostname)) {
-      $result = $this->Hostname;
-    } elseif (isset($_SERVER['SERVER_NAME'])) {
-      $result = $_SERVER['SERVER_NAME'];
-    } else {
-      $result = 'localhost.localdomain';
-    }
-
-    return $result;
-  }
-
-  /**
-   * Returns a message in the appropriate language.
-   * @access private
-   * @return string
-   */
-  private function Lang($key) {
-    if(count($this->language) < 1) {
-      $this->SetLanguage('en'); // set the default language
-    }
-
-    if(isset($this->language[$key])) {
-      return $this->language[$key];
-    } else {
-      return 'Language string failed to load: ' . $key;
-    }
-  }
-
-  /**
-   * Returns true if an error occurred.
-   * @access public
-   * @return bool
-   */
-  public function IsError() {
-    return ($this->error_count > 0);
-  }
-
-  /**
-   * Changes every end of line from CR or LF to CRLF.
-   * @access private
-   * @return string
-   */
-  private function FixEOL($str) {
-    $str = str_replace("\r\n", "\n", $str);
-    $str = str_replace("\r", "\n", $str);
-    $str = str_replace("\n", $this->LE, $str);
-    return $str;
-  }
-
-  /**
-   * Adds a custom header.
-   * @access public
-   * @return void
-   */
-  public function AddCustomHeader($custom_header) {
-    $this->CustomHeader[] = explode(':', $custom_header, 2);
-  }
-
-  /**
-   * Evaluates the message and returns modifications for inline images and backgrounds
-   * @access public
-   * @return $message
-   */
-  public function MsgHTML($message, $basedir = '') {
-    preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images);
-    if(isset($images[2])) {
-      foreach($images[2] as $i => $url) {
-        // do not change urls for absolute images (thanks to corvuscorax)
-        if (!preg_match('#^[A-z]+://#',$url)) {
-          $filename = basename($url);
-          $directory = dirname($url);
-          ($directory == '.')?$directory='':'';
-          $cid = 'cid:' . md5($filename);
-          $ext = pathinfo($filename, PATHINFO_EXTENSION);
-          $mimeType  = self::_mime_types($ext);
-          if ( strlen($basedir) > 1 && substr($basedir,-1) != '/') { $basedir .= '/'; }
-          if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; }
-          if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64',$mimeType) ) {
-            $message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message);
-          }
-        }
-      }
-    }
-    $this->IsHTML(true);
-    $this->Body = $message;
-    $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
-    if (!empty($textMsg) && empty($this->AltBody)) {
-      $this->AltBody = html_entity_decode($textMsg);
-    }
-    if (empty($this->AltBody)) {
-      $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
-    }
-  }
-
-  /**
-   * Gets the MIME type of the embedded or inline image
-   * @param string File extension
-   * @access public
-   * @return string MIME type of ext
-   * @static
-   */
-  public static function _mime_types($ext = '') {
-    $mimes = array(
-      'hqx'   =>  'application/mac-binhex40',
-      'cpt'   =>  'application/mac-compactpro',
-      'doc'   =>  'application/msword',
-      'bin'   =>  'application/macbinary',
-      'dms'   =>  'application/octet-stream',
-      'lha'   =>  'application/octet-stream',
-      'lzh'   =>  'application/octet-stream',
-      'exe'   =>  'application/octet-stream',
-      'class' =>  'application/octet-stream',
-      'psd'   =>  'application/octet-stream',
-      'so'    =>  'application/octet-stream',
-      'sea'   =>  'application/octet-stream',
-      'dll'   =>  'application/octet-stream',
-      'oda'   =>  'application/oda',
-      'pdf'   =>  'application/pdf',
-      'ai'    =>  'application/postscript',
-      'eps'   =>  'application/postscript',
-      'ps'    =>  'application/postscript',
-      'smi'   =>  'application/smil',
-      'smil'  =>  'application/smil',
-      'mif'   =>  'application/vnd.mif',
-      'xls'   =>  'application/vnd.ms-excel',
-      'ppt'   =>  'application/vnd.ms-powerpoint',
-      'wbxml' =>  'application/vnd.wap.wbxml',
-      'wmlc'  =>  'application/vnd.wap.wmlc',
-      'dcr'   =>  'application/x-director',
-      'dir'   =>  'application/x-director',
-      'dxr'   =>  'application/x-director',
-      'dvi'   =>  'application/x-dvi',
-      'gtar'  =>  'application/x-gtar',
-      'php'   =>  'application/x-httpd-php',
-      'php4'  =>  'application/x-httpd-php',
-      'php3'  =>  'application/x-httpd-php',
-      'phtml' =>  'application/x-httpd-php',
-      'phps'  =>  'application/x-httpd-php-source',
-      'js'    =>  'application/x-javascript',
-      'swf'   =>  'application/x-shockwave-flash',
-      'sit'   =>  'application/x-stuffit',
-      'tar'   =>  'application/x-tar',
-      'tgz'   =>  'application/x-tar',
-      'xhtml' =>  'application/xhtml+xml',
-      'xht'   =>  'application/xhtml+xml',
-      'zip'   =>  'application/zip',
-      'mid'   =>  'audio/midi',
-      'midi'  =>  'audio/midi',
-      'mpga'  =>  'audio/mpeg',
-      'mp2'   =>  'audio/mpeg',
-      'mp3'   =>  'audio/mpeg',
-      'aif'   =>  'audio/x-aiff',
-      'aiff'  =>  'audio/x-aiff',
-      'aifc'  =>  'audio/x-aiff',
-      'ram'   =>  'audio/x-pn-realaudio',
-      'rm'    =>  'audio/x-pn-realaudio',
-      'rpm'   =>  'audio/x-pn-realaudio-plugin',
-      'ra'    =>  'audio/x-realaudio',
-      'rv'    =>  'video/vnd.rn-realvideo',
-      'wav'   =>  'audio/x-wav',
-      'bmp'   =>  'image/bmp',
-      'gif'   =>  'image/gif',
-      'jpeg'  =>  'image/jpeg',
-      'jpg'   =>  'image/jpeg',
-      'jpe'   =>  'image/jpeg',
-      'png'   =>  'image/png',
-      'tiff'  =>  'image/tiff',
-      'tif'   =>  'image/tiff',
-      'css'   =>  'text/css',
-      'html'  =>  'text/html',
-      'htm'   =>  'text/html',
-      'shtml' =>  'text/html',
-      'txt'   =>  'text/plain',
-      'text'  =>  'text/plain',
-      'log'   =>  'text/plain',
-      'rtx'   =>  'text/richtext',
-      'rtf'   =>  'text/rtf',
-      'xml'   =>  'text/xml',
-      'xsl'   =>  'text/xml',
-      'mpeg'  =>  'video/mpeg',
-      'mpg'   =>  'video/mpeg',
-      'mpe'   =>  'video/mpeg',
-      'qt'    =>  'video/quicktime',
-      'mov'   =>  'video/quicktime',
-      'avi'   =>  'video/x-msvideo',
-      'movie' =>  'video/x-sgi-movie',
-      'doc'   =>  'application/msword',
-      'word'  =>  'application/msword',
-      'xl'    =>  'application/excel',
-      'eml'   =>  'message/rfc822'
-    );
-    return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
-  }
-
-  /**
-  * Set (or reset) Class Objects (variables)
-  *
-  * Usage Example:
-  * $page->set('X-Priority', '3');
-  *
-  * @access public
-  * @param string $name Parameter Name
-  * @param mixed $value Parameter Value
-  * NOTE: will not work with arrays, there are no arrays to set/reset
-  * @todo Should this not be using __set() magic function?
-  */
-  public function set($name, $value = '') {
-    try {
-      if (isset($this->$name) ) {
-        $this->$name = $value;
-      } else {
-        throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
-      }
-    } catch (Exception $e) {
-      $this->SetError($e->getMessage());
-      if ($e->getCode() == self::STOP_CRITICAL) {
-        return false;
-      }
-    }
-    return true;
-  }
-
-  /**
-   * Strips newlines to prevent header injection.
-   * @access public
-   * @param string $str String
-   * @return string
-   */
-  public function SecureHeader($str) {
-    $str = str_replace("\r", '', $str);
-    $str = str_replace("\n", '', $str);
-    return trim($str);
-  }
-
-  /**
-   * Set the private key file and password to sign the message.
-   *
-   * @access public
-   * @param string $key_filename Parameter File Name
-   * @param string $key_pass Password for private key
-   */
-  public function Sign($cert_filename, $key_filename, $key_pass) {
-    $this->sign_cert_file = $cert_filename;
-    $this->sign_key_file = $key_filename;
-    $this->sign_key_pass = $key_pass;
-  }
-
-  /**
-   * Set the private key file and password to sign the message.
-   *
-   * @access public
-   * @param string $key_filename Parameter File Name
-   * @param string $key_pass Password for private key
-   */
-  public function DKIM_QP($txt) {
-    $tmp="";
-    $line="";
-    for ($i=0;$i<strlen($txt);$i++) {
-      $ord=ord($txt[$i]);
-      if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
-        $line.=$txt[$i];
-      } else {
-        $line.="=".sprintf("%02X",$ord);
-      }
-    }
-    return $line;
-  }
-
-  /**
-   * Generate DKIM signature
-   *
-   * @access public
-   * @param string $s Header
-   */
-  public function DKIM_Sign($s) {
-    $privKeyStr = file_get_contents($this->DKIM_private);
-    if ($this->DKIM_passphrase!='') {
-      $privKey = openssl_pkey_get_private($privKeyStr,$this->DKIM_passphrase);
-    } else {
-      $privKey = $privKeyStr;
-    }
-    if (openssl_sign($s, $signature, $privKey)) {
-      return base64_encode($signature);
-    }
-  }
-
-  /**
-   * Generate DKIM Canonicalization Header
-   *
-   * @access public
-   * @param string $s Header
-   */
-  public function DKIM_HeaderC($s) {
-    $s=preg_replace("/\r\n\s+/"," ",$s);
-    $lines=explode("\r\n",$s);
-    foreach ($lines as $key=>$line) {
-      list($heading,$value)=explode(":",$line,2);
-      $heading=strtolower($heading);
-      $value=preg_replace("/\s+/"," ",$value) ; // Compress useless spaces
-      $lines[$key]=$heading.":".trim($value) ; // Don't forget to remove WSP around the value
-    }
-    $s=implode("\r\n",$lines);
-    return $s;
-  }
-
-  /**
-   * Generate DKIM Canonicalization Body
-   *
-   * @access public
-   * @param string $body Message Body
-   */
-  public function DKIM_BodyC($body) {
-    if ($body == '') return "\r\n";
-    // stabilize line endings
-    $body=str_replace("\r\n","\n",$body);
-    $body=str_replace("\n","\r\n",$body);
-    // END stabilize line endings
-    while (substr($body,strlen($body)-4,4) == "\r\n\r\n") {
-      $body=substr($body,0,strlen($body)-2);
-    }
-    return $body;
-  }
-
-  /**
-   * Create the DKIM header, body, as new header
-   *
-   * @access public
-   * @param string $headers_line Header lines
-   * @param string $subject Subject
-   * @param string $body Body
-   */
-  public function DKIM_Add($headers_line,$subject,$body) {
-    $DKIMsignatureType    = 'rsa-sha1'; // Signature & hash algorithms
-    $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
-    $DKIMquery            = 'dns/txt'; // Query method
-    $DKIMtime             = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
-    $subject_header       = "Subject: $subject";
-    $headers              = explode("\r\n",$headers_line);
-    foreach($headers as $header) {
-      if (strpos($header,'From:') === 0) {
-        $from_header=$header;
-      } elseif (strpos($header,'To:') === 0) {
-        $to_header=$header;
-      }
-    }
-    $from     = str_replace('|','=7C',$this->DKIM_QP($from_header));
-    $to       = str_replace('|','=7C',$this->DKIM_QP($to_header));
-    $subject  = str_replace('|','=7C',$this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
-    $body     = $this->DKIM_BodyC($body);
-    $DKIMlen  = strlen($body) ; // Length of body
-    $DKIMb64  = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
-    $ident    = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
-    $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
-                "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
-                "\th=From:To:Subject;\r\n".
-                "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
-                "\tz=$from\r\n".
-                "\t|$to\r\n".
-                "\t|$subject;\r\n".
-                "\tbh=" . $DKIMb64 . ";\r\n".
-                "\tb=";
-    $toSign   = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
-    $signed   = $this->DKIM_Sign($toSign);
-    return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n";
-  }
-
-  protected function doCallback($isSent,$to,$cc,$bcc,$subject,$body) {
-    if (!empty($this->action_function) && function_exists($this->action_function)) {
-      $params = array($isSent,$to,$cc,$bcc,$subject,$body);
-      call_user_func_array($this->action_function,$params);
-    }
-  }
-}
-
-class phpmailerException extends Exception {
-  public function errorMessage() {
-    $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
-    return $errorMsg;
-  }
-}
-?>

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