Browse Source

Merge branch '1.10.x' into bootstrap

aragonc 9 years ago
parent
commit
135753fca4
73 changed files with 3588 additions and 4312 deletions
  1. 4 2
      app/Migrations/Schema/V110/Version110.php
  2. 0 9
      app/Resources/public/css/base.css
  3. 117 0
      documentation/changelog.html
  4. 7 2
      main/admin/user_add.php
  5. 11 6
      main/inc/ajax/user_manager.ajax.php
  6. 1 1
      main/inc/lib/agenda.lib.php
  7. 5 5
      main/inc/lib/api.lib.php
  8. 10 6
      main/inc/lib/auth.lib.php
  9. 19 0
      main/inc/lib/sessionmanager.lib.php
  10. 43 6
      main/inc/lib/social.lib.php
  11. 1 1
      main/inc/local.inc.php
  12. 1 1
      main/lang/spanish/trad4all.inc.php
  13. 4 7
      main/session/session_category_list.php
  14. 17 2
      main/social/search.php
  15. 1 4
      main/template/default/agenda/month.tpl
  16. 4 48
      main/template/default/social/form_modals.tpl
  17. 52 3
      plugin/buycourses/CHANGELOG.md
  18. 11 9
      plugin/buycourses/README.md
  19. 0 12
      plugin/buycourses/config.php
  20. 398 383
      plugin/buycourses/database.php
  21. 16 210
      plugin/buycourses/js/buycourses.js
  22. 68 67
      plugin/buycourses/lang/english.php
  23. 66 65
      plugin/buycourses/lang/french.php
  24. 70 69
      plugin/buycourses/lang/spanish.php
  25. 11 5
      plugin/buycourses/readme.txt
  26. BIN
      plugin/buycourses/resources/acces_tool.gif
  27. 0 105
      plugin/buycourses/resources/content.css
  28. 2 116
      plugin/buycourses/resources/css/style.css
  29. BIN
      plugin/buycourses/resources/delete.png
  30. BIN
      plugin/buycourses/resources/edit_message.gif
  31. BIN
      plugin/buycourses/resources/img/128/accept.png
  32. BIN
      plugin/buycourses/resources/img/32/accept.png
  33. BIN
      plugin/buycourses/resources/img/32/delete.png
  34. BIN
      plugin/buycourses/resources/img/32/new.png
  35. BIN
      plugin/buycourses/resources/img/32/save.png
  36. BIN
      plugin/buycourses/resources/message_confirmation.png
  37. BIN
      plugin/buycourses/resources/message_warning.png
  38. BIN
      plugin/buycourses/resources/more.png
  39. BIN
      plugin/buycourses/resources/new_message.gif
  40. 0 79
      plugin/buycourses/resources/plugin.css
  41. BIN
      plugin/buycourses/resources/save.png
  42. BIN
      plugin/buycourses/resources/save2.png
  43. BIN
      plugin/buycourses/resources/toggle.png
  44. 0 31
      plugin/buycourses/src/ajax.php
  45. 0 676
      plugin/buycourses/src/buy_course.lib.php
  46. 1069 15
      plugin/buycourses/src/buy_course_plugin.class.php
  47. 28 45
      plugin/buycourses/src/configuration.php
  48. 71 0
      plugin/buycourses/src/course_catalog.php
  49. 3 17
      plugin/buycourses/src/error.php
  50. 63 499
      plugin/buycourses/src/function.php
  51. 12 16
      plugin/buycourses/src/index.buycourses.php
  52. 0 333
      plugin/buycourses/src/inscription.php
  53. 0 68
      plugin/buycourses/src/list.php
  54. 162 40
      plugin/buycourses/src/paymentsetup.php
  55. 9 0
      plugin/buycourses/src/paypalfunctions.php
  56. 0 40
      plugin/buycourses/src/pending_orders.php
  57. 73 84
      plugin/buycourses/src/process.php
  58. 144 145
      plugin/buycourses/src/process_confirm.php
  59. 116 0
      plugin/buycourses/src/sales_report.php
  60. 76 0
      plugin/buycourses/src/session_catalog.php
  61. 182 313
      plugin/buycourses/src/success.php
  62. 112 0
      plugin/buycourses/view/catalog.tpl
  63. 138 98
      plugin/buycourses/view/configuration.tpl
  64. 57 48
      plugin/buycourses/view/index.tpl
  65. 0 190
      plugin/buycourses/view/list.tpl
  66. 36 0
      plugin/buycourses/view/message_transfer.tpl
  67. 66 100
      plugin/buycourses/view/paymentsetup.tpl
  68. 0 39
      plugin/buycourses/view/pending_orders.tpl
  69. 41 111
      plugin/buycourses/view/process.tpl
  70. 76 77
      plugin/buycourses/view/process_confirm.tpl
  71. 53 0
      plugin/buycourses/view/sales_report.tpl
  72. 53 95
      plugin/buycourses/view/success.tpl
  73. 9 9
      plugin/tour/lang/french.php

+ 4 - 2
app/Migrations/Schema/V110/Version110.php

@@ -81,7 +81,10 @@ class Version110 extends AbstractMigrationChamilo
 
         $this->addSql("ALTER TABLE user MODIFY COLUMN user_id int unsigned DEFAULT null");
         $this->addSql("ALTER TABLE user DROP PRIMARY KEY");
-        $this->addSql("ALTER TABLE user ADD COLUMN id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT AFTER user_id");
+        $this->addSql("ALTER TABLE user ADD COLUMN id int unsigned DEFAULT null");
+        $this->addSql("UPDATE user SET id = user_id");
+        $this->addSql("ALTER TABLE user MODIFY COLUMN id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT AFTER user_id");
+
         $this->addSql("ALTER TABLE user MODIFY COLUMN chatcall_date datetime default NULL");
         $this->addSql("ALTER TABLE user MODIFY COLUMN chatcall_text varchar(50) default NULL");
         $this->addSql("ALTER TABLE user MODIFY COLUMN chatcall_user_id int unsigned default 0");
@@ -419,7 +422,6 @@ class Version110 extends AbstractMigrationChamilo
         $this->addSql("ALTER TABLE c_survey MODIFY COLUMN anonymous char(10) NOT NULL default '0'");
         $this->addSql("ALTER TABLE c_course_setting MODIFY COLUMN value varchar(255) default ''");
 
-        $this->addSql("UPDATE user SET id = user_id");
         $this->addSql("UPDATE course_field SET field_type = 1 WHERE field_variable = 'special_course'");
         $this->addSql("UPDATE user SET registration_date = NULL WHERE registration_date = '0000-00-00 00:00:00'");
         $this->addSql("UPDATE user SET expiration_date = NULL WHERE expiration_date = '0000-00-00 00:00:00'");

+ 0 - 9
app/Resources/public/css/base.css

@@ -3627,7 +3627,6 @@ a:active{
 }
 
 #my_timeline {
-    background: url("dot.gif") repeat-x scroll left 45px;
     margin: 0px auto;
 }
 
@@ -3644,7 +3643,6 @@ a:active{
 }
 
 #dates li {
-    background: url("biggerdot.png") no-repeat scroll center bottom transparent;
     float: left;
     font-size: 14px;
     height: 50px;
@@ -4287,10 +4285,6 @@ i.size-32.icon-new-note{
     background-position: right center;
 }
 
-#course_category_well {
-    padding: 9px 0;
-}
-
 .nav-list img {
     margin-right: 6px;
 }
@@ -4355,7 +4349,6 @@ i.size-32.icon-new-work{
     margin-left: 110px;
 }
 .btn-msg {
-  background: url("send_msg.png") no-repeat left center;
   background-position: 3px;
   padding: 2px 4px;
   padding-left: 22px;
@@ -4365,7 +4358,6 @@ i.size-32.icon-new-work{
   background-color: #e6e6e6;
 }
 .btn-inv {
-  background: url("send_inv.png") no-repeat left center;
   background-position: 3px;
   padding: 2px 4px;
   padding-left: 22px;
@@ -4375,7 +4367,6 @@ i.size-32.icon-new-work{
   background-color: #e6e6e6;
 }
 .btn-inv-off {
-  background: url("send_inv_off.png") no-repeat left center;
   background-position: 3px;
   padding: 2px 4px;
   padding-left: 22px;

+ 117 - 0
documentation/changelog.html

@@ -169,6 +169,18 @@
     <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/fcc9030fafb047c4a62eb671a6213671797edabd">fcc9030f</a> - <a href="https://task.beeznest.com/issues/9881">BT#9881</a>) Add fields to associate forum to lp</li>
     <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/389f0c2d3a0591c289d068fab6c8d24f8fb64504">389f0c2d</a> - <a href="https://task.beeznest.com/issues/9901">BT#9901</a>) Fix issue with sublanguage terms saving (update jQuery call for the value of textarea)</li>
     <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/265fd2eac15ef7ce2f6f3fef7183d47bbf5d25b4">265fd2ea</a>) Update introduction to sub-languages to explain a bit better what's supposed to happen</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/d1992debd3c9777cfbbf63d0712f351f85471330">d1992deb</a> - <a href="https://support.chamilo.org/issues/7150">#7150</a>) Add tracking page link to learning paths list</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/4d2f0513909bf7777499ce6093a1269fd78987a9">4d2f0513</a> - <a href="https://support.chamilo.org/issues/7808">#7808</a>) Save asset time in learning paths</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/95e9710dd5f94c70c41d8393082a0e34a6d3b0b5">95e9710d</a> - <a href="https://support.chamilo.org/issues/5208">#5208</a>) Add CKEditor to textarea in agenda event creation form</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/863b7c49bdf3c367565e3c850778b99ebe4541d0">863b7c49</a> - <a href="https://task.beeznest.com/issues/10219">BT#10219</a>) Show Sign-Up button on sesion details page for not-logged user</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/3ff85070c8b452f2606bacee19cfd4b744f8938e">3ff85070</a>) PrestaShop plugin fixes.</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/f0f62976b23ef76f776cc84f45396a56b97ecb68">f0f62976</a> - <a href="https://task.beeznest.com/issues/10175">BT#10175</a>) Allow subscription to open session</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/56d0756a2e32258b45923f4def0c4a4ba6899ffa">56d0756a</a> - <a href="https://task.beeznest.com/issues/10175">BT#10175</a>) Add setting option to hide the course catalogue</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/cd77a3ef861e2997df983b1233acfd6564ac9010">cd77a3ef</a> - <a href="https://support.chamilo.org/issues/7448">#7448</a>) Prevent coach to edit feedback on exercise result</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/4190658cc1056e03d2f678c3b9732bc1e986ea14">4190658c</a> - <a href="https://task.beeznest.com/issues/9896">BT#9896</a>) Send email when user has been subscribed to session</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/92ffaf62c2a2587fe4af423fe3a53c12da685a9e">92ffaf62</a> - <a href="https://support.chamilo.org/issues/7619">#7619</a>) Add session view (option my_courses_view_by_session) in my courses list</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/9096794b57005e39e3216efdb348f157d309eff6">9096794b</a> - <a href="https://support.chamilo.org/issues/7618">#7618</a>) Add new options in fill blanks question type</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/5f231873215312eaf430caa980f1aaeb2d6a58bb">5f231873</a> - <a href="https://task.beeznest.com/issues/9896">BT#9896</a>) Add option to send an email when a user is being subscribed to a sessino</li>
   </ul>
   <h4>For developers and sysadmins</h4>
   <ul>
@@ -336,6 +348,59 @@
     <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/3cd5b4bc0621a40b73af4ece196df854790eece2">3cd5b4bc</a> - <a href="https://support.chamilo.org/issues/7510">#7510</a>) Add DB compression flag configuration</li>
     <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/646a600e3ebe11c649e33323f3bd607a2e32bd1c">646a600e</a> - <a href="https://task.beeznest.com/issues/9325">BT#9325</a>) Save extra data in admin panel</li>
     <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/370fd8c85193e081ebf499ca334076a27866f312">370fd8c8</a> - <a href="https://support.chamilo.org/issues/7501">#7501</a>) Adds composer as autoloader instead of custom autoloader</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/431576b2b9bda713b5f29b85b553a6a6265d195f">431576b2</a> - <a href="https://support.chamilo.org/issues/6579">#6579</a>) Load favicon from CSS theme directory if it exists</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/f2a03393774e8dd02f1d33acc69022f3cd6fb133">f2a03393</a> - <a href="https://support.chamilo.org/issues/7558">#7558</a>) Add method to get a HTML code for a icon by Font Awesome</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/e94602ec57b374c05e4acc78142889fbea36fdb3">e94602ec</a> - <a href="https://support.chamilo.org/issues/7837">#7837</a>) Replace old code with api_get_user_info</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/22dc909a3893264ab5d15953a5554bada84d2ee1">22dc909a</a> - <a href="https://task.beeznest.com/issues/10259">BT#10259</a>) Add expiration_date validation</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/57f99efbdc9224512a242096482998bef0df4cf7">57f99efb</a> - <a href="https://task.beeznest.com/issues/10253">BT#10253</a>) Add dropbox_hide_general_coach setting</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/8371a3754f643658cd9e71e811bbd804bb560373">8371a375</a> - <a href="https://task.beeznest.com/issues/10217">BT#10217</a>) XFrameOptions work around</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/7a11b484f5f21401d051353de69c400ec346e75c">7a11b484</a> - <a href="https://task.beeznest.com/issues/10248">BT#10248</a>) Show session_admin on Resume Session page</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/7cc56e6946ed1e27f837d86877ef1bbfb39e4e7c">7cc56e69</a> - <a href="https://support.chamilo.org/issues/7220">#7220</a>) Fix missing variable in function orig_item_type (learning paths)</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/ca6f82131805bdd78b4a469da98930592b8e3431">ca6f8213</a>) Remove use of dbName or db_name</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/98f4510ab80a17a27637c0e9f4467270bf27af86">98f4510a</a>) Remove virtual course code.</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/5a9ae8837d9142c114a3c55998d78b83e92ca9a0">5a9ae883</a> - <a href="https://support.chamilo.org/issues/7823">#7823</a>) Set default value auth_cat_child</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/a2d3f1c99ccb4ab25c180fbf1bdb896395009288">a2d3f1c9</a> - <a href="https://support.chamilo.org/issues/7819">#7819</a>) Add database port to installation procedure and configuration file</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/5451fd535fc5e9c7c14bddca4d081f4707e50f83">5451fd53</a>) Delete group category and group  when deleting a course.</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/2ce8bedf327eb7d75264fba4427b261f7f2b47d7">2ce8bedf</a> - <a href="https://task.beeznest.com/issues/10219">BT#10219</a>) Add method to search session by name on course catalog</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/c169d7fcac7911dd4eeee71b26083cc804456c60">c169d7fc</a> - <a href="https://task.beeznest.com/issues/10045">BT#10045</a>) Attempt at Nginx and Apache config examples in installation guide (Spanish only for now). Still presenting issues with file uploads under Nginx</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/a1429e93dcd4bc45dced3374efab27650bba885f">a1429e93</a>) Add section about testing with Docker in CONTRIBUTING.md</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/28a2a5e9a8ec37e27afeb2e176e23f68c86ea8f8">28a2a5e9</a> - <a href="https://task.beeznest.com/issues/10145">BT#10145</a>) Add param to prevent limitless redirections in SSO for Drupal</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/e1be9c9864bcf280aac058aa1127a95acd6e5d62">e1be9c98</a>) Update fxp version requirement in README</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/9b5dc83734c455f59f5c62d764b888a81e9c99c7">9b5dc837</a> - <a href="https://task.beeznest.com/issues/10174">BT#10174</a>) Force session user data reload when login through sso</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/da5c70c191ade10c67a4a941ad71adeb30a0dae6">da5c70c1</a> - <a href="https://task.beeznest.com/issues/10181">BT#10181</a>) Add option to enable/disable individual skills</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/d2f674b4633f44b8d6f42195cccea97644d75eed">d2f674b4</a> - <a href="https://task.beeznest.com/issues/10181">BT#10181</a>) Add status and update_at on skill table</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/5542e7b6619e86bc3a47a2f62f6907128c29514c">5542e7b6</a> - <a href="https://task.beeznest.com/issues/10175">BT#10175</a>) Show number of user in session for Advanced Subscription</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/d5467da510ae696d298c3691e6355edbb9f84ea5">d5467da5</a> - <a href="https://task.beeznest.com/issues/10175">BT#10175</a>) Add student status on admin_view for Advanced Subsciption</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/a7f2c5f67730537a65b25c3e7f621069955a7be2">a7f2c5f6</a> - <a href="https://task.beeznest.com/issues/10175">BT#10175</a>) Add RewriteRule to get files in course directories</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/c897c8e180c7bc081ae279a01c07471e066d19d6">c897c8e1</a>) Add option to boost encoding detection for learning paths - see https://github.com/chamilo/chamilo-lms/pull/771</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/443b7823f7791b7a03dcbe8acbb562d587ee2c83">443b7823</a> - <a href="https://task.beeznest.com/issues/10174">BT#10174</a>) Add referrer_uri variable to enable the right redirect to happen when user is authenticated after a Single Sign On operation </li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/1481dd4573c0e559936b24b6007ee8c944994fad">1481dd45</a> - <a href="https://task.beeznest.com/issues/10175">BT#10175</a>) Fix links to example files in session imports</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/98d0cf7828f5c608f9df4dba30ea1c87d2996538">98d0cf78</a> - <a href="https://support.chamilo.org/issues/7794">#7794</a>) Move my_courses_view_by_session setting to database</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/a740f7ff0324a8cf4b53bf8f88758fde527e8edf">a740f7ff</a> - <a href="https://support.chamilo.org/issues/7794">#7794</a>) Move user_reset_password and user_reset_password_token_limit settings to database</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/ea94df0669cda8ab7ed95863845a3a6d02ff14bd">ea94df06</a> - <a href="https://support.chamilo.org/issues/7794">#7794</a>) Move course_catalog_published setting to database</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/189ea94d9a92830f58f2fc9c11fbcfa22ee25ad5">189ea94d</a>) Fix query error when saving an lp_item imported from a ppt file -refs bt10091</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/9ed26091d29e05bb9f9b7fe116efd4b4685f72cf">9ed26091</a> - <a href="https://support.chamilo.org/issues/7794">#7794</a>) Move gradebook_detailed_admin_view setting to database</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/628e0ccd81e4ff0e3d8639ecaeb294e238ead3e3">628e0ccd</a> - <a href="https://support.chamilo.org/issues/7794">#7794</a>) Move prevent_multiple_simultaneous_login setting to database</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/5331084f626ab0e3150a5b8574a4a4223c748fab">5331084f</a> - <a href="https://support.chamilo.org/issues/7792">#7792</a>) Add mathajax lib</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/620e79631f26a86c1a9743e606eb73498ae59d34">620e7963</a> - <a href="https://support.chamilo.org/issues/7794">#7794</a>) Remove db_admin_path setting, now replaced by db_manager_enabled</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/9a04803fb157e7b959737cedaf8d9c6c39622396">9a04803f</a> - <a href="https://support.chamilo.org/issues/7448">#7448</a>) Add setting to allow feedback from coaches on exercise results</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/00c59b690fdaa923331ad2ceec1004ccc6519ca9">00c59b69</a> - <a href="https://support.chamilo.org/issues/1483">#1483</a>) Add install profiles mechanism (beta)</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/a9d953db390e0d67497a3f1e91004e869867c505">a9d953db</a>) If error in the query then hide the sql error (in production mode)</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/003ee63187bcac677de01909aef65c8d3c0c5534">003ee631</a>) Replace Spreadsheet_Excel_Writer/Writer with PHPExcel</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/b1786914ed9746442a635ec6708c3436df02ed8d">b1786914</a> - <a href="https://task.beeznest.com/issues/10139">BT#10139</a>) Create new extra fields types 'letters' and 'alphanumeric with spaces' -  refs BT#10139 #TMI</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/69422fa712e400a5b656d5d21875e21d2236927a">69422fa7</a> - <a href="https://task.beeznest.com/issues/10139">BT#10139</a>) Add pattern to validate only letters and numbers on course code</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/dc17948791649dc4ac2cfbf2847bcccc7066b9a4">dc179487</a>) Add script to delete old unused courses</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/dbe3b890c6f26b5066e8d5ebbb17981ffb082169">dbe3b890</a> - <a href="https://task.beeznest.com/issues/10139">BT#10139</a>) Change date params when agenda event is created</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/e296bc849040c1aee97d4e29d10d7c254cdb5bba">e296bc84</a> - <a href="https://task.beeznest.com/issues/10139">BT#10139</a>) Add 'only_letters' and 'alphanumeric' types of extra fields</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/8d4d575690ccf30865718e123f103c5729c4b30e">8d4d5756</a> - <a href="https://task.beeznest.com/issues/10139">BT#10139</a>) Add validation pattern for course code in create course form</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/a37f8d44bf4df0940b3275ba21dd15ec46af3c23">a37f8d44</a> - <a href="https://task.beeznest.com/issues/10139">BT#10139</a>) Update jquery jqplot lib</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/5af5c2834c9c152cdffef6b0e056571ca586dc0a">5af5c283</a> - <a href="https://task.beeznest.com/issues/9897">BT#9897</a>) Delete token and time from user password reset after first use</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/b458a6f0ec07302c1642515b9f950f9e5f2e9f46">b458a6f0</a>) Add iid in c_group_info</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/541fdf612f95c671b3ccb30a2fd26a754f51f7c9">541fdf61</a> - <a href="https://task.beeznest.com/issues/9898">BT#9898</a>) Add management for Cron Job</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/41608e948ccb7956a3644d0a399cf14fdd4212d8">41608e94</a>) Add basis for Claroline to Chamilo migration scripts</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/4c0780aa76778c390ace24f6cf85a100fc6459ba">4c0780aa</a> - <a href="https://task.beeznest.com/issues/9897">BT#9897</a>) Add new reset password option</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/67b0693c31b338c18ee0a8aa5868c411c81a5c66">67b0693c</a> - <a href="https://task.beeznest.com/issues/10092">BT#10092</a>) Create TrackECourseAccessRepository entity</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/fcc9030fafb047c4a62eb671a6213671797edabd">fcc9030f</a> - <a href="https://task.beeznest.com/issues/9881">BT#9881</a>) Add fields to associate forum to lp</li>
   </ul>
 
   <h3>Improvements (minor features) and debug</h3>
@@ -823,6 +888,57 @@
     <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/2fa39544aaaade7fcc87b6f47f74a068be3f3238">2fa39544</a> - <a href="https://support.chamilo.org/issues/7370">#7370</a>) Fix a few buy courses plugin issues</li>
     <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/f37f0bd3c6e0ae4707227f5a5c6583ab288644cc">f37f0bd3</a> - <a href="https://task.beeznest.com/issues/9068">BT#9068</a>) Fix session_id and visible_result creation issue</li>
     <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/2fd2c2b7a4284204138662bd432a7301c625579d">2fd2c2b7</a> - <a href="https://task.beeznest.com/issues/9022">BT#9022</a>) Add certificate path to the web service. Add 'add_gradebook_certificates_cron_task_enabled' configuration parameter</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/56504c645d2003fd1e28fc965298760dddd8aabc">56504c64</a> - <a href="https://task.beeznest.com/issues/10254">BT#10254</a>) Fix download zip when using windows</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/9a4c0f5fa725a5247217340e0b7b454f4a5ebc64">9a4c0f5f</a>) Fix announcement, thematic and wiki imports</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/29fb361f8fc4441d64e496b03dfb54b7726946de">29fb361f</a>) Move class UTCDateTimeType  inside app folder (permissions issue)</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/7913f289f7fabcce38a95f91494056cc91f22776">7913f289</a> - <a href="https://support.chamilo.org/issues/7808">#7808</a>) Show link only if message tool is on, in e-mails sent to users</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/76d25d799a39ca3d2dd37201a829a99e58426e67">76d25d79</a> - <a href="https://task.beeznest.com/issues/10102">BT#10102</a>) Increase year range for date pickers</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/c65dbc37821ea5893e5cdbdd7ac2e56e62968afd">c65dbc37</a> - <a href="https://support.chamilo.org/issues/7807">#7807</a>) Move js code into 2 separate files</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/666cb686fb6be62123dc6ff9361c2fbbf1804fb4">666cb686</a>) Display: add functions toolbar actions for pages</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/108a252aaa644d8c33b7eb019667f43849f2d299">108a252a</a> - <a href="https://support.chamilo.org/issues/5405">#5405</a>) Remove remaining now() call in course.lib.php</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/0a8495e3b54f34510188404e6cf1bb21cd0bbf19">0a8495e3</a>) Remove gid unset, use api_get_group_id, api_get_course_id</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/21318bb1287644d6481d064063b7d276016454e9">21318bb1</a>) Fix "Multiple answer true/false/don't know" question CRUD</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/546e927ed0791b04c568fbfe5d71f8a94bec3b83">546e927e</a>) Change main/inc/conf references to app/config/</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/c9acd1f54a19008165205af87aadd2b1def9cc0d">c9acd1f5</a> - <a href="https://support.chamilo.org/issues/7768">#7768</a>) Add class method for get user from course by status</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/9ba243744578424a6317041e398134c840218b23">9ba24374</a>) Fix jsplumb error in admin question list</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/dd8733e65b743317902ab76a3a9c74603b7ffda0">dd8733e6</a> - <a href="https://task.beeznest.com/issues/10175">BT#10175</a>) Fix generate PDF when output mode is F</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/5d15b58832785044bb766634ccb289800597cd1f">5d15b588</a>) Updating status for open sessions -refs BT10175 #FGE</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/87af6dcf9cb620f8eaacedcac7f64e098515a7ea">87af6dcf</a> - <a href="https://task.beeznest.com/issues/10175">BT#10175</a>) Show always the skill name like a tooltip on skill wheel</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/fcb12ae9431ac83b031cd3e346d2bf40f55ed86f">fcb12ae9</a> - <a href="https://task.beeznest.com/issues/10175">BT#10175</a>) Allow show full skill name on skill wheel</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/6a67ed2a52a0c95066c1eb8c4b45c84956b7bab8">6a67ed2a</a> - <a href="https://task.beeznest.com/issues/10175">BT#10175</a>) Fix showing description in exercise execution</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/30629475b583a47a849001097124a2dd8ddda727">30629475</a>) Get rid of username column in the certificates' result page -refs BT10175 #FGE</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/3887d26ed8c66f657a6985e823ce5458989d3724">3887d26e</a>) Update install documentation link to localized version for French, Spanish and Italian</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/53cd9c7e96e8273a5bb1f7bb492e67650abfc66a">53cd9c7e</a> - <a href="https://task.beeznest.com/issues/10175">BT#10175</a>) Fix URL link when searching skills</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/abae544df32afd8d58df17b5b4e387bfcca2181d">abae544d</a> - <a href="https://task.beeznest.com/issues/10175">BT#10175</a>) Improve admin_view on Advanced Subscription</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/cd4d275823e1e9ae55f7c3a34d678dfe7e1f1f3e">cd4d2758</a> - <a href="https://task.beeznest.com/issues/10139">BT#10139</a>) Add new export types</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/7832686cc41393b7feeb564683fc3a0a8d6b9966">7832686c</a> - <a href="https://task.beeznest.com/issues/10139">BT#10139</a>) Add export to xls</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/fccfb6b77df1a98fca296f8d9232ad043418ed87">fccfb6b7</a> - <a href="https://task.beeznest.com/issues/7683">BT#7683</a>) Add frame.css in CkEditor BT#7683</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/76e9608ef4bf0b1fb83c49a3b47f6bb799fda228">76e9608e</a>) Add CSS SCORM iFrame style</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/0672f0386cc87e6a815664c5627eed9fe802c0c0">0672f038</a>) Fix course cateogory order.</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/e7323004863d21841401ce76dcdc7765355663bf">e7323004</a>) deleted base_chamilo.css obsolete</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/1bc2b02f45b651a5f1f069b089a15293912b3537">1bc2b02f</a> - <a href="https://task.beeznest.com/issues/7683">BT#7683</a>) Add icons for chat online status BT#7683</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/a9aec19920c1537915d34ec118ac654b9363b60f">a9aec199</a>) Fix iid/id issues when using exporting/importing courses.</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/8b3b37451dfeff9752c3c3dc549b84ce5d752506">8b3b3745</a>) Remove unused build_datetime_from_array, fix dates.</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/4a3d526cd58d961eca6a1754cefee277d8bf8c03">4a3d526c</a>) Avoid double header.</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/f3724f53714b8f5898718dcf266a6cefb8c95637">f3724f53</a> - <a href="https://task.beeznest.com/issues/10139">BT#10139</a>) Rename FormValidator functions</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/bcdaab02b3f95a51695bfc91a5e44c948e024ca2">bcdaab02</a> - <a href="https://task.beeznest.com/issues/10139">BT#10139</a>) Show input dates with format</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/d44ab51077cc0adf4e81e1a84d24128bc5770e87">d44ab510</a>) Add message if no courses in the session.</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/dcaad88a2e69f8facc8db6a44a7cf5cacb417d81">dcaad88a</a> - <a href="https://support.chamilo.org/issues/7788">#7788</a>) Fix issue with missing image in auto-created forum</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/7d2eec85d9e6812e6847f31d8884372dd9779a0a">7d2eec85</a> - <a href="https://support.chamilo.org/issues/7788">#7788</a>) Fix issue with missing thread_qualify</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/3ea9c064321a60031ff3c831fe66aa7e2ecb1fa4">3ea9c064</a> - <a href="https://task.beeznest.com/issues/10139">BT#10139</a>) If course plugin image does not exists then use default image.</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/dde0a54a44357946c9cd41158785823393b3446b">dde0a54a</a> - <a href="https://task.beeznest.com/issues/9898">BT#9898</a>) Create template for mail sent by the Course Finished cron</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/0934761879af2ea245818bede37c24398909695f">09347618</a> - <a href="https://task.beeznest.com/issues/9898">BT#9898</a>) Create template for mail sent by the Remind Course Expiration cron</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/d11fe19094c58516c3f0c05ebd5ca63fb72ed51f">d11fe190</a>) Replace &amp; with &</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/731f0fb2a6f89b53ddf67f14ce364b475fbd34c8">731f0fb2</a> - <a href="https://task.beeznest.com/issues/7683">BT#7683</a>) Change hot courses image size - BT#7683</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/38d5bb28643fb640f1d2e237dc83694c9f5ad4af">38d5bb28</a> - <a href="https://task.beeznest.com/issues/9895">BT#9895</a>) update session subscription tpls and enable use of tpl for registration mail confirmation</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/98e741c8002c8513e6e19f8ce7378519e31cae41">98e741c8</a>) Add stats for distinct users in number of logins report on admin statistics page</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/2b8f8a384be5a7f0e04e233d368dedd8e3929300">2b8f8a38</a>) Fix missing values on call to chamilo_void_save_asset() in exercises included in learning paths #TMI</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/141be5d9d1851ef2b3cb081cdfc46855984298c2">141be5d9</a> - <a href="https://task.beeznest.com/issues/9889">BT#9889</a>) Add session subscription confirmation request</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/433999d04ca1248e2d1e67568083bbf2e9dae707">433999d0</a> - <a href="https://task.beeznest.com/issues/9889">BT#9889</a>) Show subscribe to session button when user is logged on session description page</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/e6c81faef7fc59d834e16a5634ddd341245469f9">e6c81fae</a> - <a href="https://task.beeznest.com/issues/10092">BT#10092</a>) Fix calculate points and stars by lps in courses</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/3ae531093d48ea9ce5e1cec71151f17db34829e8">3ae53109</a> - <a href="https://task.beeznest.com/issues/9886">BT#9886</a>) Show lp_view progress bar when gamification is active</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/95d977931a4f0fe8af863a8fdff09a615c1f249e">95d97793</a> - <a href="https://task.beeznest.com/issues/9886">BT#9886</a>) Calculate stars and points when gamification is active</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/389f0c2d3a0591c289d068fab6c8d24f8fb64504">389f0c2d</a> - <a href="https://task.beeznest.com/issues/9901">BT#9901</a>) Fix issue with sublanguage terms saving (update jQuery call for the value of textarea)</li>
   </ul>
 <h3>Stylesheets and theming</h3>
   <ul>
@@ -831,6 +947,7 @@
     <li>Removed all previous stylesheets and rewritten main ones from scratch</li>
     <li>Most of the CSS classes to most elements have been changed, making it practically impossible to maintain previous CSS styles with this new version (we're very sorry about that, but it was either this or sticking to non-mobile-friendly design)</li>
     <li>Many pages have been moved to TPL, making it easier to redesign them</li>
+    <li>(<a href="https://github.com/chamilo/chamilo-lms/commit/10e8ff1ed2f2dd20b32e6b8d45f68537c7801ed6">10e8ff1e</a> - <a href="https://support.chamilo.org/issues/7539">#7539</a>) Add Beach CSS theme - CT#7539</li>
   </ul>
 <h3>Web services</h3>
   <ul>

+ 7 - 2
main/admin/user_add.php

@@ -197,10 +197,15 @@ $group[] = $form->createElement(
 );
 
 $form->addGroup($group, 'password', get_lang('Password'), '');
-$form->addGroupRule('password', 'password', 'required', null, 2);
+$form->addGroupRule('password', get_lang('EnterPassword'), 'required', null, 2);
 
 if ($checkPass) {
-    $form->addElement('label', null, '<div id="password_progress" style="display:none"></div>');
+    $passwordStrengthLabels = '
+        <div id="password-verdict"></div>
+        <div id="password-errors"></div>
+        <div id="password_progress" style="display:none"></div>
+    ';
+    $form->addElement('label', null, $passwordStrengthLabels);
 }
 
 // Status

+ 11 - 6
main/inc/ajax/user_manager.ajax.php

@@ -11,14 +11,13 @@ switch ($action) {
         $user_info = api_get_user_info($_REQUEST['user_id']);
         $ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';
 
-        echo '<div class="well">';
         echo '<div class="row">';
-        echo '<div class="span2">';
+        echo '<div class="col-sm-5">';
         echo '<div class="thumbnail">';
         echo '<img src="'.$user_info['avatar'].'" /> ';
         echo '</div>';
         echo '</div>';
-        echo '<div class="span3">';
+        echo '<div class="col-sm-7">';
         if (api_get_setting('show_email_addresses') == 'false') {
             $user_info['mail'] = ' ';
         } else {
@@ -55,9 +54,15 @@ switch ($action) {
                 'block'
             );
 
-            echo '<a class="btn btn-primary" id="send_message_link">'.
-                get_lang('Send').
-                '</a>';
+            echo '
+                <div class="row">
+                    <div class="col-sm-10 col-sm-offset-2">
+                        <a class="btn btn-primary" id="send_message_link">
+                            <i class="fa fa-envelope"></i> ' . get_lang('Send') . '
+                        </a>
+                    </div>
+                </div>
+            ';
         }
         break;
     case 'user_id_exists':

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

@@ -145,7 +145,7 @@ class Agenda
         $end = api_get_utc_datetime($end);
         $allDay = isset($allDay) && $allDay == 'true' ? 1 : 0;
         $id = null;
-        $content = nl2br($content);
+        $content = Security::remove_XSS($content);
         $eventComment = nl2br($eventComment);
 
         switch ($this->type) {

+ 5 - 5
main/inc/lib/api.lib.php

@@ -7234,8 +7234,8 @@ function api_get_password_checker_js($usernameInputId, $passwordInputid)
 
     var verdicts = ['".implode("','", $verdicts)."'];
     var errorMessages = {
-        password_to_short : '".get_lang('PasswordIsTooShort')."',
-        same_as_username : '".get_lang('YourPasswordCannotBeTheSameAsYourUsername')."'
+        password_to_short : \"" . get_lang('PasswordIsTooShort')."\",
+        same_as_username : \"".get_lang('YourPasswordCannotBeTheSameAsYourUsername')."\"
     };
 
     $(document).ready(function() {
@@ -7249,9 +7249,9 @@ function api_get_password_checker_js($usernameInputId, $passwordInputid)
             },
             errorMessages : errorMessages,
             viewports: {
-                progress: '#password_progress'
-                //verdict: undefined,
-                //errors: undefined
+                progress: '#password_progress',
+                verdict: '#password-verdict',
+                errors: '#password-errors'
             },
             usernameField: '$usernameInputId'
         };

+ 10 - 6
main/inc/lib/auth.lib.php

@@ -654,12 +654,16 @@ class Auth
         $qb = $em->createQueryBuilder();
 
         $_sessions = $qb->select('s')
-            ->from('ChamiloCoreBundle:Session', 's')
-            ->setFirstResult($limit['start'])
-            ->setMaxResults($limit['length'])
-            ->where(
-                $qb->expr()->gt('s.nbrCourses', 0)
-            );
+            ->from('ChamiloCoreBundle:Session', 's');
+        
+        if (!empty($limit)) {
+            $_sessions->setFirstResult($limit['start'])
+                ->setMaxResults($limit['length']);
+        }
+
+        $_sessions->where(
+            $qb->expr()->gt('s.nbrCourses', 0)
+        );
 
         if (!is_null($date)) {
             $_sessions

+ 19 - 0
main/inc/lib/sessionmanager.lib.php

@@ -390,6 +390,7 @@ class SessionManager
     public static function get_sessions_admin($options = array(), $get_count = false)
     {
         $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
+        $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 
         $where = 'WHERE 1 = 1 ';
         $user_id = api_get_user_id();
@@ -418,6 +419,8 @@ class SessionManager
         $order = $conditions['order'];
         $limit = $conditions['limit'];
 
+        $isMakingOrder = false;
+
         if ($get_count == true) {
             $select = " SELECT count(*) as total_rows";
         } else {
@@ -432,6 +435,22 @@ class SessionManager
                 " s.session_category_id, ".
                 " $inject_extra_fields ".
                 " s.id ";
+
+            $isMakingOrder = strpos($options['order'], 'category_name') === 0;
+        }
+
+        $isFilteringSessionCategory = strpos($where, 'category_name') !== false;
+
+        if ($isMakingOrder || $isFilteringSessionCategory) {
+            $inject_joins .= " LEFT JOIN $sessionCategoryTable sc ON s.session_category_id = sc.id ";
+
+            if ($isFilteringSessionCategory) {
+                $where = str_replace('category_name', 'sc.name', $where);
+            }
+
+            if ($isMakingOrder) {
+                $order = str_replace('category_name', 'sc.name', $order);
+            }
         }
 
         $query = "$select FROM $tbl_session s $inject_joins $where $inject_where";

+ 43 - 6
main/inc/lib/social.lib.php

@@ -372,9 +372,13 @@ class SocialManager extends UserManager
             $send_message = MessageManager::send_message($userfriend_id, $subject_message, $content_message);
 
             if ($send_message) {
-                echo Display::display_confirmation_message($succes, true);
+                Display::addFlash(
+                    Display::display_confirmation_message($succes, true, true)
+                );
             } else {
-                echo Display::display_error_message(get_lang('ErrorSendingMessage'), true);
+                Display::addFlash(
+                    Display::display_error_message(get_lang('ErrorSendingMessage'), true, true)
+                );
             }
             return false;
         } elseif (isset($userfriend_id) && !isset($subject_message)) {
@@ -384,9 +388,21 @@ class SocialManager extends UserManager
                 $count_is_true = self::send_invitation_friend(api_get_user_id(), $userfriend_id, $message_title, $content_message);
 
                 if ($count_is_true) {
-                    echo Display::display_confirmation_message(api_htmlentities(get_lang('InvitationHasBeenSent'), ENT_QUOTES, $charset), false);
+                    Display::addFlash(
+                        Display::display_confirmation_message(
+                            api_htmlentities(get_lang('InvitationHasBeenSent'), ENT_QUOTES, $charset),
+                            false,
+                            true
+                        )
+                    );
                 } else {
-                    echo Display::display_warning_message(api_htmlentities(get_lang('YouAlreadySentAnInvitation'), ENT_QUOTES, $charset), false);
+                    Display::addFlash(
+                        Display::display_warning_message(
+                            api_htmlentities(get_lang('YouAlreadySentAnInvitation'), ENT_QUOTES, $charset),
+                            false,
+                            true
+                        )
+                    );
                 }
             }
         }
@@ -756,8 +772,29 @@ class SocialManager extends UserManager
 
             // My friend profile.
             if ($user_id != api_get_user_id()) {
-                $html .= '<li><a href="#" class="btn-to-send-message" data-send-to="' . $user_id . '" title="'.get_lang('SendMessage').'">';
-                $html .= Display::return_icon('compose_message.png', get_lang('SendMessage')).'&nbsp;&nbsp;'.get_lang('SendMessage').'</a></li>';
+                $sendMessageText = get_lang('SendMessage');
+                $sendMessageIcon = Display::return_icon(
+                    'compose_message.png',
+                    $sendMessageText
+                );
+                $sendMesssageUrl = api_get_path(WEB_AJAX_PATH)
+                    . 'user_manager.ajax.php?'
+                    . http_build_query([
+                        'a' => 'get_user_popup',
+                        'user_id' => $user_id
+                    ]);
+
+                $html .= '<li>';
+                $html .= Display::url(
+                    "$sendMessageIcon $sendMessageText",
+                    $sendMesssageUrl,
+                    [
+                        'class' => 'ajax',
+                        'title' => $sendMessageText,
+                        'data-title' => $sendMessageText
+                    ]
+                );
+                $html .= '</li>';
             }
 
             // Check if I already sent an invitation message

+ 1 - 1
main/inc/local.inc.php

@@ -270,7 +270,7 @@ if (!empty($_SESSION['_user']['user_id']) && !($login || $logout)) {
                     // Check captcha
                     $captchaText = $_POST['captcha'];
                     /** @var Text_CAPTCHA $obj */
-                    $obj = isset($_SESSION['userportal.lib']) ? $_SESSION['userportal.lib'] : null;
+                    $obj = isset($_SESSION['template.lib']) ? $_SESSION['template.lib'] : null;
                     if ($obj) {
                         $obj->getPhrase();
                         if ($obj->getPhrase() != $captchaText) {

+ 1 - 1
main/lang/spanish/trad4all.inc.php

@@ -3945,7 +3945,7 @@ $RegYou = "lo ha inscrito en este curso";
 $OneResp = "Uno de los administradores del curso";
 $UserPicture = "Foto";
 $ProfileReg = "Su nuevo perfil de usuario ha sido guardado";
-$EmailWrong = "La dirección de correo electrónico que ha escrito está incompleta ocontiene caracteres no válidos";
+$EmailWrong = "La dirección de correo electrónico que ha escrito está incompleta o contiene caracteres no válidos";
 $UserTaken = "El nombre de usuario que ha elegido ya existe";
 $Fields = "No ha rellenado todos los campos";
 $Again = "¡ Comience de nuevo !";

+ 4 - 7
main/session/session_category_list.php

@@ -18,14 +18,11 @@ api_protect_limit_for_session_admin();
 $this_section = SECTION_PLATFORM_ADMIN;
 $htmlHeadXtra[] = '<script>
 function selectAll(idCheck,numRows,action) {
-    for(i=0;i<numRows;i++) {
-        idcheck = document.getElementById(idCheck+"_"+i);
-        if (action == "true"){
-            idcheck.checked = true;
-        } else {
-            idcheck.checked = false;
-        }
+    for(i = 0; i < numRows; i++) {
+        idcheck = document.getElementById(idCheck + "_" + i);
+        idcheck.checked = action == "true";
     }
+}
 </script>';
 
 $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);

+ 17 - 2
main/social/search.php

@@ -87,8 +87,23 @@ if ($query != '' || ($query_vars['search_type']=='1' && count($query_vars)>2) )
                 $send_inv = '<a href="#" class="'.$buttonClass.' btn-to-send-invitation" data-send-to="' . $user['user_id'] . '">
                              <i class="fa fa-user"></i> '.get_lang('SendInvitation').'</a>';
             }
-            $send_msg = '<a href="#" class="btn-to-send-message '.$buttonClass.'" data-send-to="' . $user['user_id'] . '">
-                        <i class="fa fa-envelope"></i> '.get_lang('SendMessage').'</a>';
+
+            $sendMesssageUrl = api_get_path(WEB_AJAX_PATH)
+                . 'user_manager.ajax.php?'
+                . http_build_query([
+                    'a' => 'get_user_popup',
+                    'user_id' => $user['user_id']
+                ]);
+            $send_msg = Display::toolbarButton(
+                get_lang('SendMessage'),
+                $sendMesssageUrl,
+                'envelope',
+                'default',
+                [
+                    'class' => 'ajax btn-sm',
+                    'data-title' => get_lang('SendMessage')
+                ]
+            );
 
             $img = '<img src="'.$user_info['avatar'].'" width="100" height="100">';
 

+ 1 - 4
main/template/default/agenda/month.tpl

@@ -154,7 +154,7 @@ $(document).ready(function() {
 							var bValid = true;
 							bValid = bValid && checkLength(title, "title", 1, 255);
                                                         
-                            //This For make the CKEDITOR SERIALIZABLE
+                            //Update the CKEditor Instance to the remplaced textarea, ready to be serializable
                             for ( instance in CKEDITOR.instances ) {
                                 CKEDITOR.instances[instance].updateElement();
                             }
@@ -212,9 +212,6 @@ $(document).ready(function() {
 					}
 				});
 
-	            // Don't follow the link.
-	            return false;
-
 				calendar.fullCalendar('unselect');
                 //Reload events
                 calendar.fullCalendar("refetchEvents");

+ 4 - 48
main/template/default/social/form_modals.tpl

@@ -1,25 +1,3 @@
-<div class="modal fade" id="send-message-modal" tabindex="-1" role="dialog" aria-labelledby="send-message-modal-title" aria-hidden="true">
-    <div class="modal-dialog">
-        <div class="modal-content">
-            <div class="modal-header">
-                <button type="button" class="close" data-dismiss="modal" aria-label="{{ 'Close' | get_lang }}">
-                    <span aria-hidden="true">&times;</span>
-                </button>
-                <h4 class="modal-title" id="send-message-modal-title">{{ 'SendMessage' | get_lang }}</h4>
-            </div>
-            <div class="modal-body">
-                <div id="send-message-alert"></div>
-                {{ messageForm }}
-            </div>
-            <div class="modal-footer">
-                <button type="button" id="btn-send-message" class="btn btn-primary">
-                    <i class="fa fa-send"></i> {{ 'Send' | get_lang }}
-                </button>
-            </div>
-        </div>
-    </div>
-</div>
-
 <div class="modal fade" id="send-invitation-modal" tabindex="-1" role="dialog" aria-labelledby="send-invitation-modal-title" aria-hidden="true">
     <div class="modal-dialog">
         <div class="modal-content">
@@ -44,32 +22,10 @@
 
 <script>
     $(document).on('ready', function() {
-        var $sendMessageModal = $('#send-message-modal'),
-            $sendInvitationModal = $('#send-invitation-modal');
+        var $sendInvitationModal = $('#send-invitation-modal');
 
         var sendToUser = 0;
 
-        $('.btn-to-send-message').on('click', function(e) {
-            e.preventDefault();
-
-            sendToUser = $(this).data('send-to');
-
-            $sendMessageModal.modal('show');
-        });
-
-        $('#btn-send-message').on('click', function(e) {
-            e.preventDefault();
-
-            var $frmSendMessage = $sendMessageModal.find('.modal-body form'),
-                url = '{{ _p.web_ajax }}message.ajax.php?a=send_message&user_id=' + sendToUser;
-
-            $.get(url, $frmSendMessage.serialize(), function(response) {
-                $('#send-message-alert').html(response);
-
-                $frmSendMessage[0].reset();
-            });
-        });
-
         $('.btn-to-send-invitation').on('click', function(e) {
             e.preventDefault();
 
@@ -84,10 +40,10 @@
             var $frmSendInvitation = $sendInvitationModal.find('.modal-body form'),
                 url = '{{ _p.web_ajax }}message.ajax.php?a=send_invitation&user_id=' + sendToUser;
 
-            $.get(url, $frmSendInvitation.serialize(), function(response) {
-                $('#send-invitation-alert').html(response);
-
+            $.get(url, $frmSendInvitation.serialize(), function() {
                 $frmSendInvitation[0].reset();
+
+                window.location.reload();
             });
         });
     });

+ 52 - 3
plugin/buycourses/CHANGELOG.md

@@ -1,9 +1,57 @@
+v3.0
+====
+
+This version has been fixed and improved for Chamilo LMS 1.10.x.
+
+- A new user interface for platform admins and users.
+- Avoid data redundancy by adding courses/sessions to catalog
+- The catalog of sessions can be configured to offer some courses or sessions
+in a currency other than the others courses or sessions
+- The sales have a status: Pending, Completed, Canceled
+- The Peding Orders pages has been replaced by a Sales Report.
+Allowing filter the sales by its status
+- The plugin Registration page was removed. Instead the Chamilo LMS
+registrarion page is used.
+
+##Changes in database structure
+
+The database structure has been changed totally. The previous database
+structure was formed for the tables:
+
+- `plugin_buy_course` The registered courses in the platform
+- `plugin_buy_course_country` The list of countries with their currencies
+- `plugin_buy_course_paypal` The PayPal account info
+- `plugin_buy_course_sale` The sales of courses that were made
+- `plugin_buy_course_temporal` The pending orders of courses that were made
+- `plugin_buy_course_transfer` The bank accounts for transfers
+- `plugin_buy_session` The registered courses in the platform
+- `plugin_buy_session_course` The courses in sessions
+- `plugin_buy_session_sale` The sales of session that were made
+- `plugin_buy_session_temporary` The pending orders of session that were made
+
+To avoid the data redundancy, the `plugin_buy_course`, `plugin_buy_session`
+and `plugin_buy_session_course` tables were replaced for the
+`plugin_buycourses_item` table. And the `plugin_buy_course_sale`,
+`plugin_buy_course_temporal`, `plugin_buy_session_sale` and
+`plugin_buy_session_temporary` tables were replaced for the
+ `plugin_buycourses_item` table.
+
+The __new database__ structure is formed for the tables:
+
+- `plugin_buycourses_currency` The list of countries with their currencies
+- `plugin_buycourses_item` The registered courses and sessions in the platform
+- `plugin_buycourses_paypal_account` The PayPal account info
+- `plugin_buycourses_sale` The sales of courses and sessions that were made
+- `plugin_buycourses_transfer` The bank accounts for transfers
+
+---
+
 v2.0 - 2014-10-14
 =================
 This version adds support for sales of sessions access.
 A session can be purchased as soon as it is given a price, granted the current
-date is either previous to the session start date, between the start and end, or
-no date has been defined for the session.
+date is either previous to the session start date, between the start and end,
+or no date has been defined for the session.
 Students are subscribed automatically once they have paid. There is no 
 intermediary step.
 This version does not work (yet) with the session period defined by user
@@ -16,4 +64,5 @@ look at the installer to *fix* your plugin tables (add a few fields).
 
 v1.0 - 2014-06-30 (or something)
 =================
-This is the first release of the plugin, with only the PayPal payment method in working state and only for courses.
+This is the first release of the plugin, with only the PayPal payment method
+in working state and only for courses.

+ 11 - 9
plugin/buycourses/README.md

@@ -1,11 +1,13 @@
-Courses purchase plugin for Chamilo LMS
+Buy Courses plugin for Chamilo LMS
 =======================================
-Users can access the purchases catalog to buy courses (or sessions, since v2 of
-this plugin) enabled for purchase.
-If the user is not registered or logged in, he/she will be requested to 
-register/login before he/she can resume buying items.
-Once the course is chosen, Chamilo shows available payment types (currently only
-PayPal works) and lets the user proceed with the purchase.
-Finally, the user receives an e-mail confirming the purchase and his account is
-automatically modified to give him/her access to the course/session.
+Users can access the purchases catalog to buy courses or sessions (since v2 of this plugin)
+enabled for sale.
 
+If the user is not registered or logged in, he/she will be requested to register/login
+before he/she can resume buying items.
+
+Once the course or session is chosen, shows available payment types (currently only PayPal works)
+and lets the user proceed with the purchase.
+
+Finally, the user receives an e-mail confirming the purchase and him/her is can access to the
+course/session.

+ 0 - 12
plugin/buycourses/config.php

@@ -1,16 +1,4 @@
 <?php
 /* For licensing terms, see /license.txt */
 
-define('TABLE_BUY_SESSION', 'plugin_buy_session');
-define('TABLE_BUY_SESSION_COURSE', 'plugin_buy_session_course');
-define('TABLE_BUY_SESSION_TEMPORARY', 'plugin_buy_session_temporary');
-define('TABLE_BUY_SESSION_SALE', 'plugin_buy_session_sale');
-define('TABLE_BUY_COURSE', 'plugin_buy_course');
-define('TABLE_BUY_COURSE_COUNTRY', 'plugin_buy_course_country');
-define('TABLE_BUY_COURSE_PAYPAL', 'plugin_buy_course_paypal');
-define('TABLE_BUY_COURSE_TRANSFER', 'plugin_buy_course_transfer');
-define('TABLE_BUY_COURSE_TEMPORAL', 'plugin_buy_course_temporal');
-define('TABLE_BUY_COURSE_SALE', 'plugin_buy_course_sale');
-
 require_once __DIR__ . '/../../main/inc/global.inc.php';
-require_once  api_get_path(PLUGIN_PATH) . 'buycourses/src/buy_course_plugin.class.php';

+ 398 - 383
plugin/buycourses/database.php

@@ -11,398 +11,413 @@
 if (!function_exists('api_get_path')) {
     die('This script must be loaded through the Chamilo plugin installer sequence');
 }
-/**
- * Create the script context, then execute database queries to enable
- */
-
-$table = Database::get_main_table(TABLE_BUY_SESSION);
-$sql = "CREATE TABLE IF NOT EXISTS $table (
-    id INT unsigned NOT NULL auto_increment PRIMARY KEY,
-    session_id INT unsigned NOT NULL DEFAULT '0',
-    name VARCHAR(250),
-    date_start VARCHAR(40),
-    date_end VARCHAR(40),
-    visible int,
-    price FLOAT(11,2) NOT NULL DEFAULT '0',
-    sync int)";
-Database::query($sql);
 
-$tableSession = Database::get_main_table(TABLE_MAIN_SESSION);
-$sql = "SELECT id, name, access_start_date, access_end_date FROM $tableSession";
-$res = Database::query($sql);
-while ($row = Database::fetch_assoc($res)) {
-    $presql = "INSERT INTO $table (id, name, date_start, date_end, visible)
-    VALUES ('" . $row['id'] . "','" . $row['name'] . "','" . $row['access_start_date'] . "','" . $row['access_end_date'] . "','NO')";
-    Database::query($presql);
-}
+$entityManager = Database::getManager();
+$pluginSchema = new \Doctrine\DBAL\Schema\Schema();
+$connection = $entityManager->getConnection();
+$platform = $connection->getDatabasePlatform();
 
-$table = Database::get_main_table(TABLE_BUY_COURSE);
-$sql = "CREATE TABLE IF NOT EXISTS $table (
-    id INT unsigned NOT NULL auto_increment PRIMARY KEY,
-    session_id INT unsigned NOT NULL DEFAULT 0,
-    course_id INT unsigned NOT NULL DEFAULT '0',
-    code VARCHAR(40),
-    title VARCHAR(250),
-    visible int,
-    price FLOAT(11,2) NOT NULL DEFAULT '0',
-    sync int)";
-Database::query($sql);
+//Create tables
+$paypalTable = $pluginSchema->createTable(BuyCoursesPlugin::TABLE_PAYPAL);
+$paypalTable->addColumn(
+    'id',
+    \Doctrine\DBAL\Types\Type::INTEGER,
+    ['autoincrement' => true, 'unsigned' => true]
+);
+$paypalTable->addColumn('username', \Doctrine\DBAL\Types\Type::STRING);
+$paypalTable->addColumn('password', \Doctrine\DBAL\Types\Type::STRING);
+$paypalTable->addColumn('signature', \Doctrine\DBAL\Types\Type::STRING);
+$paypalTable->addColumn('sandbox', \Doctrine\DBAL\Types\Type::BOOLEAN);
+$paypalTable->setPrimaryKey(['id']);
 
-$tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
-$sql = "SELECT id, code, title FROM $tableCourse";
-$res = Database::query($sql);
-while ($row = Database::fetch_assoc($res)) {
-    $presql = "INSERT INTO $table (course_id, code, title, visible) VALUES ('" . $row['id'] . "','" . $row['code'] . "','" . $row['title'] . "','NO')";
-    Database::query($presql);
-}
+$transferTable = $pluginSchema->createTable(BuyCoursesPlugin::TABLE_TRANSFER);
+$transferTable->addColumn(
+    'id',
+    \Doctrine\DBAL\Types\Type::INTEGER,
+    ['autoincrement' => true, 'unsigned' => true]
+);
+$transferTable->addColumn('name', \Doctrine\DBAL\Types\Type::STRING);
+$transferTable->addColumn('account', \Doctrine\DBAL\Types\Type::STRING);
+$transferTable->addColumn('swift', \Doctrine\DBAL\Types\Type::STRING);
+$transferTable->setPrimaryKey(['id']);
 
-$table = Database::get_main_table(TABLE_BUY_SESSION_COURSE);
-$sql = "CREATE TABLE IF NOT EXISTS $table (
-	id INT unsigned NOT NULL auto_increment PRIMARY KEY,
-    session_id SMALLINT(5) unsigned DEFAULT '0',
-    course_code VARCHAR(40),
-    nbr_users SMALLINT(5) unsigned DEFAULT '0',
-    sync int)";
-Database::query($sql);
+$currencyTable = $pluginSchema->createTable(BuyCoursesPlugin::TABLE_CURRENCY);
+$currencyTable->addColumn(
+    'id',
+    \Doctrine\DBAL\Types\Type::INTEGER,
+    ['autoincrement' => true, 'unsigned' => true]
+);
+$currencyTable->addColumn(
+    'country_code',
+    \Doctrine\DBAL\Types\Type::STRING,
+    ['length' => 2]
+);
+$currencyTable->addColumn(
+    'country_name',
+    \Doctrine\DBAL\Types\Type::STRING,
+    ['length' => 255]
+);
+$currencyTable->addColumn(
+    'iso_code',
+    \Doctrine\DBAL\Types\Type::STRING,
+    ['length' => 3]
+);
+$currencyTable->addColumn('status', \Doctrine\DBAL\Types\Type::BOOLEAN);
+$currencyTable->addUniqueIndex(['country_code']);
+$currencyTable->addIndex(['iso_code']);
+$currencyTable->setPrimaryKey(['id']);
 
-$table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-$sql = "SELECT * FROM $table";
-$res = Database::query($sql);
-while ($row = Database::fetch_assoc($res)) {
-    $presql = "INSERT INTO $table (session_id, c_id, nbr_users)
-    VALUES ('" . $row['session_id'] . "','" . $row['c_id'] . "','" . $row['nbr_users'] . "')";
-    Database::query($presql);
-}
+$itemTable = $pluginSchema->createTable(BuyCoursesPlugin::TABLE_ITEM);
+$itemTable->addColumn(
+    'id',
+    \Doctrine\DBAL\Types\Type::INTEGER,
+    ['autoincrement' => true, 'unsigned' => true]
+);
+$itemTable->addColumn('product_type', \Doctrine\DBAL\Types\Type::INTEGER);
+$itemTable->addColumn(
+    'product_id',
+    \Doctrine\DBAL\Types\Type::INTEGER,
+    ['unsigned' => true]
+);
+$itemTable->addColumn(
+    'price',
+    \Doctrine\DBAL\Types\Type::DECIMAL,
+    ['scale' => 2]
+);
+$itemTable->addColumn(
+    'currency_id',
+    \Doctrine\DBAL\Types\Type::INTEGER,
+    ['unsigned' => true]
+);
+$itemTable->setPrimaryKey(['id']);
+$itemTable->addForeignKeyConstraint(
+    $currencyTable,
+    ['currency_id'],
+    ['id'],
+    ['onDelete' => 'CASCADE']
+);
 
-$table = Database::get_main_table(TABLE_BUY_COURSE_COUNTRY);
-$sql = "CREATE TABLE IF NOT EXISTS $table (
-    country_id int NOT NULL AUTO_INCREMENT,
-    country_code char(2) NOT NULL DEFAULT '',
-    country_name varchar(45) NOT NULL DEFAULT '',
-    currency_code char(3) DEFAULT NULL,
-    iso_alpha3 char(3) DEFAULT NULL,
-    status int DEFAULT '0',
-    PRIMARY KEY (country_id)
-    ) DEFAULT CHARSET=utf8 AUTO_INCREMENT=0;";
-Database::query($sql);
+$saleTable = $pluginSchema->createTable(BuyCoursesPlugin::TABLE_SALE);
+$saleTable->addColumn(
+    'id',
+    \Doctrine\DBAL\Types\Type::INTEGER,
+    ['autoincrement' => true, 'unsigned' => true]
+);
+$saleTable->addColumn('reference', \Doctrine\DBAL\Types\Type::STRING);
+$saleTable->addColumn('date', \Doctrine\DBAL\Types\Type::DATE);
+$saleTable->addColumn(
+    'user_id',
+    \Doctrine\DBAL\Types\Type::INTEGER,
+    ['unsigned' => true]
+);
+$saleTable->addColumn('product_type', \Doctrine\DBAL\Types\Type::INTEGER);
+$saleTable->addColumn('product_name', \Doctrine\DBAL\Types\Type::STRING);
+$saleTable->addColumn(
+    'product_id',
+    \Doctrine\DBAL\Types\Type::INTEGER,
+    ['unsigned' => true]
+);
+$saleTable->addColumn(
+    'price',
+    \Doctrine\DBAL\Types\Type::DECIMAL,
+    ['scale' => 2]
+);
+$saleTable->addColumn(
+    'currency_id',
+    \Doctrine\DBAL\Types\Type::INTEGER,
+    ['unsigned' => true]
+);
+$saleTable->addColumn('status', \Doctrine\DBAL\Types\Type::INTEGER);
+$saleTable->addColumn('payment_type', \Doctrine\DBAL\Types\Type::INTEGER);
+$saleTable->setPrimaryKey(['id']);
+$saleTable->addForeignKeyConstraint(
+    $currencyTable,
+    ['currency_id'],
+    ['id'],
+    ['onDelete' => 'CASCADE']
+);
 
-$sql = "CREATE UNIQUE INDEX index_country ON $table (country_code)";
-Database::query($sql);
+$queries = $pluginSchema->toSql($platform);
 
-$sql = "INSERT INTO $table (country_code, country_name, currency_code, iso_alpha3) VALUES
-	('AD', 'Andorra', 'EUR', 'AND'),
-	('AE', 'United Arab Emirates', 'AED', 'ARE'),
-	('AF', 'Afghanistan', 'AFN', 'AFG'),
-	('AG', 'Antigua and Barbuda', 'XCD', 'ATG'),
-	('AI', 'Anguilla', 'XCD', 'AIA'),
-	('AL', 'Albania', 'ALL', 'ALB'),
-	('AM', 'Armenia', 'AMD', 'ARM'),
-	('AO', 'Angola', 'AOA', 'AGO'),
-	('AR', 'Argentina', 'ARS', 'ARG'),
-	('AS', 'American Samoa', 'USD', 'ASM'),
-	('AT', 'Austria', 'EUR', 'AUT'),
-	('AU', 'Australia', 'AUD', 'AUS'),
-	('AW', 'Aruba', 'AWG', 'ABW'),
-	('AX', '&Aring;land', 'EUR', 'ALA'),
-	('AZ', 'Azerbaijan', 'AZN', 'AZE'),
-	('BA', 'Bosnia and Herzegovina', 'BAM', 'BIH'),
-	('BB', 'Barbados', 'BBD', 'BRB'),
-	('BD', 'Bangladesh', 'BDT', 'BGD'),
-	('BE', 'Belgium', 'EUR', 'BEL'),
-	('BF', 'Burkina Faso', 'XOF', 'BFA'),
-	('BG', 'Bulgaria', 'BGN', 'BGR'),
-	('BH', 'Bahrain', 'BHD', 'BHR'),
-	('BI', 'Burundi', 'BIF', 'BDI'),
-	('BJ', 'Benin', 'XOF', 'BEN'),
-	('BL', 'Saint Barth&eacute;lemy', 'EUR', 'BLM'),
-	('BM', 'Bermuda', 'BMD', 'BMU'),
-	('BN', 'Brunei', 'BND', 'BRN'),
-	('BO', 'Bolivia', 'BOB', 'BOL'),
-	('BQ', 'Bonaire', 'USD', 'BES'),
-	('BR', 'Brazil', 'BRL', 'BRA'),
-	('BS', 'Bahamas', 'BSD', 'BHS'),
-	('BT', 'Bhutan', 'BTN', 'BTN'),
-	('BV', 'Bouvet Island', 'NOK', 'BVT'),
-	('BW', 'Botswana', 'BWP', 'BWA'),
-	('BY', 'Belarus', 'BYR', 'BLR'),
-	('BZ', 'Belize', 'BZD', 'BLZ'),
-	('CA', 'Canada', 'CAD', 'CAN'),
-	('CC', 'Cocos [Keeling] Islands', 'AUD', 'CCK'),
-	('CD', 'Congo', 'CDF', 'COD'),
-	('CF', 'Central African Republic', 'XAF', 'CAF'),
-	('CG', 'Republic of the Congo', 'XAF', 'COG'),
-	('CH', 'Switzerland', 'CHF', 'CHE'),
-	('CI', 'Ivory Coast', 'XOF', 'CIV'),
-	('CK', 'Cook Islands', 'NZD', 'COK'),
-	('CL', 'Chile', 'CLP', 'CHL'),
-	('CM', 'Cameroon', 'XAF', 'CMR'),
-	('CN', 'China', 'CNY', 'CHN'),
-	('CO', 'Colombia', 'COP', 'COL'),
-	('CR', 'Costa Rica', 'CRC', 'CRI'),
-	('CU', 'Cuba', 'CUP', 'CUB'),
-	('CV', 'Cape Verde', 'CVE', 'CPV'),
-	('CW', 'Curacao', 'ANG', 'CUW'),
-	('CX', 'Christmas Island', 'AUD', 'CXR'),
-	('CY', 'Cyprus', 'EUR', 'CYP'),
-	('CZ', 'Czechia', 'CZK', 'CZE'),
-	('DE', 'Germany', 'EUR', 'DEU'),
-	('DJ', 'Djibouti', 'DJF', 'DJI'),
-	('DK', 'Denmark', 'DKK', 'DNK'),
-	('DM', 'Dominica', 'XCD', 'DMA'),
-	('DO', 'Dominican Republic', 'DOP', 'DOM'),
-	('DZ', 'Algeria', 'DZD', 'DZA'),
-	('EC', 'Ecuador', 'USD', 'ECU'),
-	('EE', 'Estonia', 'EUR', 'EST'),
-	('EG', 'Egypt', 'EGP', 'EGY'),
-	('EH', 'Western Sahara', 'MAD', 'ESH'),
-	('ER', 'Eritrea', 'ERN', 'ERI'),
-	('ES', 'Spain', 'EUR', 'ESP'),
-	('ET', 'Ethiopia', 'ETB', 'ETH'),
-	('FI', 'Finland', 'EUR', 'FIN'),
-	('FJ', 'Fiji', 'FJD', 'FJI'),
-	('FK', 'Falkland Islands', 'FKP', 'FLK'),
-	('FM', 'Micronesia', 'USD', 'FSM'),
-	('FO', 'Faroe Islands', 'DKK', 'FRO'),
-	('FR', 'France', 'EUR', 'FRA'),
-	('GA', 'Gabon', 'XAF', 'GAB'),
-	('GB', 'United Kingdom', 'GBP', 'GBR'),
-	('GD', 'Grenada', 'XCD', 'GRD'),
-	('GE', 'Georgia', 'GEL', 'GEO'),
-	('GF', 'French Guiana', 'EUR', 'GUF'),
-	('GG', 'Guernsey', 'GBP', 'GGY'),
-	('GH', 'Ghana', 'GHS', 'GHA'),
-	('GI', 'Gibraltar', 'GIP', 'GIB'),
-	('GL', 'Greenland', 'DKK', 'GRL'),
-	('GM', 'Gambia', 'GMD', 'GMB'),
-	('GN', 'Guinea', 'GNF', 'GIN'),
-	('GP', 'Guadeloupe', 'EUR', 'GLP'),
-	('GQ', 'Equatorial Guinea', 'XAF', 'GNQ'),
-	('GR', 'Greece', 'EUR', 'GRC'),
-	('GS', 'South Georgia and the South Sandwich Islands', 'GBP', 'SGS'),
-	('GT', 'Guatemala', 'GTQ', 'GTM'),
-	('GU', 'Guam', 'USD', 'GUM'),
-	('GW', 'Guinea-Bissau', 'XOF', 'GNB'),
-	('GY', 'Guyana', 'GYD', 'GUY'),
-	('HK', 'Hong Kong', 'HKD', 'HKG'),
-	('HM', 'Heard Island and McDonald Islands', 'AUD', 'HMD'),
-	('HN', 'Honduras', 'HNL', 'HND'),
-	('HR', 'Croatia', 'HRK', 'HRV'),
-	('HT', 'Haiti', 'HTG', 'HTI'),
-	('HU', 'Hungary', 'HUF', 'HUN'),
-	('ID', 'Indonesia', 'IDR', 'IDN'),
-	('IE', 'Ireland', 'EUR', 'IRL'),
-	('IL', 'Israel', 'ILS', 'ISR'),
-	('IM', 'Isle of Man', 'GBP', 'IMN'),
-	('IN', 'India', 'INR', 'IND'),
-	('IO', 'British Indian Ocean Territory', 'USD', 'IOT'),
-	('IQ', 'Iraq', 'IQD', 'IRQ'),
-	('IR', 'Iran', 'IRR', 'IRN'),
-	('IS', 'Iceland', 'ISK', 'ISL'),
-	('IT', 'Italy', 'EUR', 'ITA'),
-	('JE', 'Jersey', 'GBP', 'JEY'),
-	('JM', 'Jamaica', 'JMD', 'JAM'),
-	('JO', 'Jordan', 'JOD', 'JOR'),
-	('JP', 'Japan', 'JPY', 'JPN'),
-	('KE', 'Kenya', 'KES', 'KEN'),
-	('KG', 'Kyrgyzstan', 'KGS', 'KGZ'),
-	('KH', 'Cambodia', 'KHR', 'KHM'),
-	('KI', 'Kiribati', 'AUD', 'KIR'),
-	('KM', 'Comoros', 'KMF', 'COM'),
-	('KN', 'Saint Kitts and Nevis', 'XCD', 'KNA'),
-	('KP', 'North Korea', 'KPW', 'PRK'),
-	('KR', 'South Korea', 'KRW', 'KOR'),
-	('KW', 'Kuwait', 'KWD', 'KWT'),
-	('KY', 'Cayman Islands', 'KYD', 'CYM'),
-	('KZ', 'Kazakhstan', 'KZT', 'KAZ'),
-	('LA', 'Laos', 'LAK', 'LAO'),
-	('LB', 'Lebanon', 'LBP', 'LBN'),
-	('LC', 'Saint Lucia', 'XCD', 'LCA'),
-	('LI', 'Liechtenstein', 'CHF', 'LIE'),
-	('LK', 'Sri Lanka', 'LKR', 'LKA'),
-	('LR', 'Liberia', 'LRD', 'LBR'),
-	('LS', 'Lesotho', 'LSL', 'LSO'),
-	('LT', 'Lithuania', 'LTL', 'LTU'),
-	('LU', 'Luxembourg', 'EUR', 'LUX'),
-	('LV', 'Latvia', 'LVL', 'LVA'),
-	('LY', 'Libya', 'LYD', 'LBY'),
-	('MA', 'Morocco', 'MAD', 'MAR'),
-	('MC', 'Monaco', 'EUR', 'MCO'),
-	('MD', 'Moldova', 'MDL', 'MDA'),
-	('ME', 'Montenegro', 'EUR', 'MNE'),
-	('MF', 'Saint Martin', 'EUR', 'MAF'),
-	('MG', 'Madagascar', 'MGA', 'MDG'),
-	('MH', 'Marshall Islands', 'USD', 'MHL'),
-	('MK', 'Macedonia', 'MKD', 'MKD'),
-	('ML', 'Mali', 'XOF', 'MLI'),
-	('MM', 'Myanmar [Burma]', 'MMK', 'MMR'),
-	('MN', 'Mongolia', 'MNT', 'MNG'),
-	('MO', 'Macao', 'MOP', 'MAC'),
-	('MP', 'Northern Mariana Islands', 'USD', 'MNP'),
-	('MQ', 'Martinique', 'EUR', 'MTQ'),
-	('MR', 'Mauritania', 'MRO', 'MRT'),
-	('MS', 'Montserrat', 'XCD', 'MSR'),
-	('MT', 'Malta', 'EUR', 'MLT'),
-	('MU', 'Mauritius', 'MUR', 'MUS'),
-	('MV', 'Maldives', 'MVR', 'MDV'),
-	('MW', 'Malawi', 'MWK', 'MWI'),
-	('MX', 'Mexico', 'MXN', 'MEX'),
-	('MY', 'Malaysia', 'MYR', 'MYS'),
-	('MZ', 'Mozambique', 'MZN', 'MOZ'),
-	('NA', 'Namibia', 'NAD', 'NAM'),
-	('NC', 'New Caledonia', 'XPF', 'NCL'),
-	('NE', 'Niger', 'XOF', 'NER'),
-	('NF', 'Norfolk Island', 'AUD', 'NFK'),
-	('NG', 'Nigeria', 'NGN', 'NGA'),
-	('NI', 'Nicaragua', 'NIO', 'NIC'),
-	('NL', 'Netherlands', 'EUR', 'NLD'),
-	('NO', 'Norway', 'NOK', 'NOR'),
-	('NP', 'Nepal', 'NPR', 'NPL'),
-	('NR', 'Nauru', 'AUD', 'NRU'),
-	('NU', 'Niue', 'NZD', 'NIU'),
-	('NZ', 'New Zealand', 'NZD', 'NZL'),
-	('OM', 'Oman', 'OMR', 'OMN'),
-	('PA', 'Panama', 'PAB', 'PAN'),
-	('PE', 'Peru', 'PEN', 'PER'),
-	('PF', 'French Polynesia', 'XPF', 'PYF'),
-	('PG', 'Papua New Guinea', 'PGK', 'PNG'),
-	('PH', 'Philippines', 'PHP', 'PHL'),
-	('PK', 'Pakistan', 'PKR', 'PAK'),
-	('PL', 'Poland', 'PLN', 'POL'),
-	('PM', 'Saint Pierre and Miquelon', 'EUR', 'SPM'),
-	('PN', 'Pitcairn Islands', 'NZD', 'PCN'),
-	('PR', 'Puerto Rico', 'USD', 'PRI'),
-	('PS', 'Palestine', 'ILS', 'PSE'),
-	('PT', 'Portugal', 'EUR', 'PRT'),
-	('PW', 'Palau', 'USD', 'PLW'),
-	('PY', 'Paraguay', 'PYG', 'PRY'),
-	('QA', 'Qatar', 'QAR', 'QAT'),
-	('RE', 'R&eacute;union', 'EUR', 'REU'),
-	('RO', 'Romania', 'RON', 'ROU'),
-	('RS', 'Serbia', 'RSD', 'SRB'),
-	('RU', 'Russia', 'RUB', 'RUS'),
-	('RW', 'Rwanda', 'RWF', 'RWA'),
-	('SA', 'Saudi Arabia', 'SAR', 'SAU'),
-	('SB', 'Solomon Islands', 'SBD', 'SLB'),
-	('SC', 'Seychelles', 'SCR', 'SYC'),
-	('SD', 'Sudan', 'SDG', 'SDN'),
-	('SE', 'Sweden', 'SEK', 'SWE'),
-	('SG', 'Singapore', 'SGD', 'SGP'),
-	('SH', 'Saint Helena', 'SHP', 'SHN'),
-	('SI', 'Slovenia', 'EUR', 'SVN'),
-	('SJ', 'Svalbard and Jan Mayen', 'NOK', 'SJM'),
-	('SK', 'Slovakia', 'EUR', 'SVK'),
-	('SL', 'Sierra Leone', 'SLL', 'SLE'),
-	('SM', 'San Marino', 'EUR', 'SMR'),
-	('SN', 'Senegal', 'XOF', 'SEN'),
-	('SO', 'Somalia', 'SOS', 'SOM'),
-	('SR', 'Suriname', 'SRD', 'SUR'),
-	('SS', 'South Sudan', 'SSP', 'SSD'),
-	('ST', 'S&atilde;o Tom&eacute; and Pr&iacute;ncipe', 'STD', 'STP'),
-	('SV', 'El Salvador', 'USD', 'SLV'),
-	('SX', 'Sint Maarten', 'ANG', 'SXM'),
-	('SY', 'Syria', 'SYP', 'SYR'),
-	('SZ', 'Swaziland', 'SZL', 'SWZ'),
-	('TC', 'Turks and Caicos Islands', 'USD', 'TCA'),
-	('TD', 'Chad', 'XAF', 'TCD'),
-	('TF', 'French Southern Territories', 'EUR', 'ATF'),
-	('TG', 'Togo', 'XOF', 'TGO'),
-	('TH', 'Thailand', 'THB', 'THA'),
-	('TJ', 'Tajikistan', 'TJS', 'TJK'),
-	('TK', 'Tokelau', 'NZD', 'TKL'),
-	('TL', 'East Timor', 'USD', 'TLS'),
-	('TM', 'Turkmenistan', 'TMT', 'TKM'),
-	('TN', 'Tunisia', 'TND', 'TUN'),
-	('TO', 'Tonga', 'TOP', 'TON'),
-	('TR', 'Turkey', 'TRY', 'TUR'),
-	('TT', 'Trinidad and Tobago', 'TTD', 'TTO'),
-	('TV', 'Tuvalu', 'AUD', 'TUV'),
-	('TW', 'Taiwan', 'TWD', 'TWN'),
-	('TZ', 'Tanzania', 'TZS', 'TZA'),
-	('UA', 'Ukraine', 'UAH', 'UKR'),
-	('UG', 'Uganda', 'UGX', 'UGA'),
-	('UM', 'U.S. Minor Outlying Islands', 'USD', 'UMI'),
-	('US', 'United States', 'USD', 'USA'),
-	('UY', 'Uruguay', 'UYU', 'URY'),
-	('UZ', 'Uzbekistan', 'UZS', 'UZB'),
-	('VA', 'Vatican City', 'EUR', 'VAT'),
-	('VC', 'Saint Vincent and the Grenadines', 'XCD', 'VCT'),
-	('VE', 'Venezuela', 'VEF', 'VEN'),
-	('VG', 'British Virgin Islands', 'USD', 'VGB'),
-	('VI', 'U.S. Virgin Islands', 'USD', 'VIR'),
-	('VN', 'Vietnam', 'VND', 'VNM'),
-	('VU', 'Vanuatu', 'VUV', 'VUT'),
-	('WF', 'Wallis and Futuna', 'XPF', 'WLF'),
-	('WS', 'Samoa', 'WST', 'WSM'),
-	('XK', 'Kosovo', 'EUR', 'XKX'),
-	('YE', 'Yemen', 'YER', 'YEM'),
-	('YT', 'Mayotte', 'EUR', 'MYT'),
-	('ZA', 'South Africa', 'ZAR', 'ZAF'),
-	('ZM', 'Zambia', 'ZMK', 'ZMB'),
-	('ZW', 'Zimbabwe', 'ZWL', 'ZWE')";
-Database::query($sql);
-
-$table = Database::get_main_table(TABLE_BUY_COURSE_PAYPAL);
-$sql = "CREATE TABLE IF NOT EXISTS $table (
-    id INT unsigned NOT NULL auto_increment PRIMARY KEY,
-    sandbox VARCHAR(5) NOT NULL DEFAULT 'YES',
-    username VARCHAR(100) NOT NULL DEFAULT '',
-    password VARCHAR(100) NOT NULL DEFAULT '',
-    signature VARCHAR(100) NOT NULL DEFAULT '')";
-Database::query($sql);
-
-$sql = "INSERT INTO $table (id,username,password,signature) VALUES ('1', 'API_UserName', 'API_Password', 'API_Signature')";
-Database::query($sql);
-
-$table = Database::get_main_table(TABLE_BUY_COURSE_TRANSFER);
-$sql = "CREATE TABLE IF NOT EXISTS $table (
-    id INT unsigned NOT NULL auto_increment PRIMARY KEY,
-    name VARCHAR(100) NOT NULL DEFAULT '',
-    account VARCHAR(100) NOT NULL DEFAULT '',
-    swift VARCHAR(100) NOT NULL DEFAULT '')";
-Database::query($sql);
+foreach ($queries as $query) {
+    Database::query($query);
+}
 
-$table = Database::get_main_table(TABLE_BUY_SESSION_TEMPORARY);
-$sql = "CREATE TABLE IF NOT EXISTS $table (
-    cod INT unsigned NOT NULL auto_increment PRIMARY KEY,
-    user_id INT unsigned NOT NULL,
-    name VARCHAR(255) NOT NULL DEFAULT '',
-    session_id INT unsigned NOT NULL DEFAULT '0',
-    title VARCHAR(200) NOT NULL DEFAULT '',
-    reference VARCHAR(20) NOT NULL DEFAULT '',
-    price FLOAT(11,2) NOT NULL DEFAULT '0',
-    date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)";
-Database::query($sql);
+//Insert data
+$paypalTable = Database::get_main_table(BuyCoursesPlugin::TABLE_PAYPAL);
+$currencyTable = Database::get_main_table(BuyCoursesPlugin::TABLE_CURRENCY);
+$itemTable = Database::get_main_table(BuyCoursesPlugin::TABLE_ITEM);
+$saleTable = Database::get_main_table(BuyCoursesPlugin::TABLE_SALE);
 
-$table = Database::get_main_table(TABLE_BUY_COURSE_TEMPORAL);
-$sql = "CREATE TABLE IF NOT EXISTS $table (
-    cod INT unsigned NOT NULL auto_increment PRIMARY KEY,
-    user_id INT unsigned NOT NULL,
-    name VARCHAR(255) NOT NULL DEFAULT '',
-    course_code VARCHAR(200) NOT NULL DEFAULT '',
-    title VARCHAR(200) NOT NULL DEFAULT '',
-    reference VARCHAR(20) NOT NULL DEFAULT '',
-    price FLOAT(11,2) NOT NULL DEFAULT '0',
-    date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)";
-Database::query($sql);
+Database::insert(
+    $paypalTable,
+    [
+        'username' => '',
+        'password' => '',
+        'signature' => '',
+        'sandbox' => true
+    ]
+);
 
-$table = Database::get_main_table(TABLE_BUY_SESSION_SALE);
-$sql = "CREATE TABLE IF NOT EXISTS $table (
-    cod INT unsigned NOT NULL auto_increment PRIMARY KEY,
-    user_id INT unsigned NOT NULL,
-    session_id INT unsigned NOT NULL DEFAULT '0',
-    price FLOAT(11,2) NOT NULL DEFAULT '0',
-    payment_type VARCHAR(100) NOT NULL DEFAULT '',
-    status VARCHAR(20) NOT NULL DEFAULT '',
-    date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)";
-Database::query($sql);
+$currencies = [
+    ['AD', 'Andorra', 'EUR', 'AND'],
+    ['AE', 'United Arab Emirates', 'AED', 'ARE'],
+    ['AF', 'Afghanistan', 'AFN', 'AFG'],
+    ['AG', 'Antigua and Barbuda', 'XCD', 'ATG'],
+    ['AI', 'Anguilla', 'XCD', 'AIA'],
+    ['AL', 'Albania', 'ALL', 'ALB'],
+    ['AM', 'Armenia', 'AMD', 'ARM'],
+    ['AO', 'Angola', 'AOA', 'AGO'],
+    ['AR', 'Argentina', 'ARS', 'ARG'],
+    ['AS', 'American Samoa', 'USD', 'ASM'],
+    ['AT', 'Austria', 'EUR', 'AUT'],
+    ['AU', 'Australia', 'AUD', 'AUS'],
+    ['AW', 'Aruba', 'AWG', 'ABW'],
+    ['AX', '&Aring;land', 'EUR', 'ALA'],
+    ['AZ', 'Azerbaijan', 'AZN', 'AZE'],
+    ['BA', 'Bosnia and Herzegovina', 'BAM', 'BIH'],
+    ['BB', 'Barbados', 'BBD', 'BRB'],
+    ['BD', 'Bangladesh', 'BDT', 'BGD'],
+    ['BE', 'Belgium', 'EUR', 'BEL'],
+    ['BF', 'Burkina Faso', 'XOF', 'BFA'],
+    ['BG', 'Bulgaria', 'BGN', 'BGR'],
+    ['BH', 'Bahrain', 'BHD', 'BHR'],
+    ['BI', 'Burundi', 'BIF', 'BDI'],
+    ['BJ', 'Benin', 'XOF', 'BEN'],
+    ['BL', 'Saint Barth&eacute;lemy', 'EUR', 'BLM'],
+    ['BM', 'Bermuda', 'BMD', 'BMU'],
+    ['BN', 'Brunei', 'BND', 'BRN'],
+    ['BO', 'Bolivia', 'BOB', 'BOL'],
+    ['BQ', 'Bonaire', 'USD', 'BES'],
+    ['BR', 'Brazil', 'BRL', 'BRA'],
+    ['BS', 'Bahamas', 'BSD', 'BHS'],
+    ['BT', 'Bhutan', 'BTN', 'BTN'],
+    ['BV', 'Bouvet Island', 'NOK', 'BVT'],
+    ['BW', 'Botswana', 'BWP', 'BWA'],
+    ['BY', 'Belarus', 'BYR', 'BLR'],
+    ['BZ', 'Belize', 'BZD', 'BLZ'],
+    ['CA', 'Canada', 'CAD', 'CAN'],
+    ['CC', 'Cocos [Keeling] Islands', 'AUD', 'CCK'],
+    ['CD', 'Congo', 'CDF', 'COD'],
+    ['CF', 'Central African Republic', 'XAF', 'CAF'],
+    ['CG', 'Republic of the Congo', 'XAF', 'COG'],
+    ['CH', 'Switzerland', 'CHF', 'CHE'],
+    ['CI', 'Ivory Coast', 'XOF', 'CIV'],
+    ['CK', 'Cook Islands', 'NZD', 'COK'],
+    ['CL', 'Chile', 'CLP', 'CHL'],
+    ['CM', 'Cameroon', 'XAF', 'CMR'],
+    ['CN', 'China', 'CNY', 'CHN'],
+    ['CO', 'Colombia', 'COP', 'COL'],
+    ['CR', 'Costa Rica', 'CRC', 'CRI'],
+    ['CU', 'Cuba', 'CUP', 'CUB'],
+    ['CV', 'Cape Verde', 'CVE', 'CPV'],
+    ['CW', 'Curacao', 'ANG', 'CUW'],
+    ['CX', 'Christmas Island', 'AUD', 'CXR'],
+    ['CY', 'Cyprus', 'EUR', 'CYP'],
+    ['CZ', 'Czechia', 'CZK', 'CZE'],
+    ['DE', 'Germany', 'EUR', 'DEU'],
+    ['DJ', 'Djibouti', 'DJF', 'DJI'],
+    ['DK', 'Denmark', 'DKK', 'DNK'],
+    ['DM', 'Dominica', 'XCD', 'DMA'],
+    ['DO', 'Dominican Republic', 'DOP', 'DOM'],
+    ['DZ', 'Algeria', 'DZD', 'DZA'],
+    ['EC', 'Ecuador', 'USD', 'ECU'],
+    ['EE', 'Estonia', 'EUR', 'EST'],
+    ['EG', 'Egypt', 'EGP', 'EGY'],
+    ['EH', 'Western Sahara', 'MAD', 'ESH'],
+    ['ER', 'Eritrea', 'ERN', 'ERI'],
+    ['ES', 'Spain', 'EUR', 'ESP'],
+    ['ET', 'Ethiopia', 'ETB', 'ETH'],
+    ['FI', 'Finland', 'EUR', 'FIN'],
+    ['FJ', 'Fiji', 'FJD', 'FJI'],
+    ['FK', 'Falkland Islands', 'FKP', 'FLK'],
+    ['FM', 'Micronesia', 'USD', 'FSM'],
+    ['FO', 'Faroe Islands', 'DKK', 'FRO'],
+    ['FR', 'France', 'EUR', 'FRA'],
+    ['GA', 'Gabon', 'XAF', 'GAB'],
+    ['GB', 'United Kingdom', 'GBP', 'GBR'],
+    ['GD', 'Grenada', 'XCD', 'GRD'],
+    ['GE', 'Georgia', 'GEL', 'GEO'],
+    ['GF', 'French Guiana', 'EUR', 'GUF'],
+    ['GG', 'Guernsey', 'GBP', 'GGY'],
+    ['GH', 'Ghana', 'GHS', 'GHA'],
+    ['GI', 'Gibraltar', 'GIP', 'GIB'],
+    ['GL', 'Greenland', 'DKK', 'GRL'],
+    ['GM', 'Gambia', 'GMD', 'GMB'],
+    ['GN', 'Guinea', 'GNF', 'GIN'],
+    ['GP', 'Guadeloupe', 'EUR', 'GLP'],
+    ['GQ', 'Equatorial Guinea', 'XAF', 'GNQ'],
+    ['GR', 'Greece', 'EUR', 'GRC'],
+    ['GS', 'South Georgia and the South Sandwich Islands', 'GBP', 'SGS'],
+    ['GT', 'Guatemala', 'GTQ', 'GTM'],
+    ['GU', 'Guam', 'USD', 'GUM'],
+    ['GW', 'Guinea-Bissau', 'XOF', 'GNB'],
+    ['GY', 'Guyana', 'GYD', 'GUY'],
+    ['HK', 'Hong Kong', 'HKD', 'HKG'],
+    ['HM', 'Heard Island and McDonald Islands', 'AUD', 'HMD'],
+    ['HN', 'Honduras', 'HNL', 'HND'],
+    ['HR', 'Croatia', 'HRK', 'HRV'],
+    ['HT', 'Haiti', 'HTG', 'HTI'],
+    ['HU', 'Hungary', 'HUF', 'HUN'],
+    ['ID', 'Indonesia', 'IDR', 'IDN'],
+    ['IE', 'Ireland', 'EUR', 'IRL'],
+    ['IL', 'Israel', 'ILS', 'ISR'],
+    ['IM', 'Isle of Man', 'GBP', 'IMN'],
+    ['IN', 'India', 'INR', 'IND'],
+    ['IO', 'British Indian Ocean Territory', 'USD', 'IOT'],
+    ['IQ', 'Iraq', 'IQD', 'IRQ'],
+    ['IR', 'Iran', 'IRR', 'IRN'],
+    ['IS', 'Iceland', 'ISK', 'ISL'],
+    ['IT', 'Italy', 'EUR', 'ITA'],
+    ['JE', 'Jersey', 'GBP', 'JEY'],
+    ['JM', 'Jamaica', 'JMD', 'JAM'],
+    ['JO', 'Jordan', 'JOD', 'JOR'],
+    ['JP', 'Japan', 'JPY', 'JPN'],
+    ['KE', 'Kenya', 'KES', 'KEN'],
+    ['KG', 'Kyrgyzstan', 'KGS', 'KGZ'],
+    ['KH', 'Cambodia', 'KHR', 'KHM'],
+    ['KI', 'Kiribati', 'AUD', 'KIR'],
+    ['KM', 'Comoros', 'KMF', 'COM'],
+    ['KN', 'Saint Kitts and Nevis', 'XCD', 'KNA'],
+    ['KP', 'North Korea', 'KPW', 'PRK'],
+    ['KR', 'South Korea', 'KRW', 'KOR'],
+    ['KW', 'Kuwait', 'KWD', 'KWT'],
+    ['KY', 'Cayman Islands', 'KYD', 'CYM'],
+    ['KZ', 'Kazakhstan', 'KZT', 'KAZ'],
+    ['LA', 'Laos', 'LAK', 'LAO'],
+    ['LB', 'Lebanon', 'LBP', 'LBN'],
+    ['LC', 'Saint Lucia', 'XCD', 'LCA'],
+    ['LI', 'Liechtenstein', 'CHF', 'LIE'],
+    ['LK', 'Sri Lanka', 'LKR', 'LKA'],
+    ['LR', 'Liberia', 'LRD', 'LBR'],
+    ['LS', 'Lesotho', 'LSL', 'LSO'],
+    ['LT', 'Lithuania', 'LTL', 'LTU'],
+    ['LU', 'Luxembourg', 'EUR', 'LUX'],
+    ['LV', 'Latvia', 'LVL', 'LVA'],
+    ['LY', 'Libya', 'LYD', 'LBY'],
+    ['MA', 'Morocco', 'MAD', 'MAR'],
+    ['MC', 'Monaco', 'EUR', 'MCO'],
+    ['MD', 'Moldova', 'MDL', 'MDA'],
+    ['ME', 'Montenegro', 'EUR', 'MNE'],
+    ['MF', 'Saint Martin', 'EUR', 'MAF'],
+    ['MG', 'Madagascar', 'MGA', 'MDG'],
+    ['MH', 'Marshall Islands', 'USD', 'MHL'],
+    ['MK', 'Macedonia', 'MKD', 'MKD'],
+    ['ML', 'Mali', 'XOF', 'MLI'],
+    ['MM', 'Myanmar [Burma]', 'MMK', 'MMR'],
+    ['MN', 'Mongolia', 'MNT', 'MNG'],
+    ['MO', 'Macao', 'MOP', 'MAC'],
+    ['MP', 'Northern Mariana Islands', 'USD', 'MNP'],
+    ['MQ', 'Martinique', 'EUR', 'MTQ'],
+    ['MR', 'Mauritania', 'MRO', 'MRT'],
+    ['MS', 'Montserrat', 'XCD', 'MSR'],
+    ['MT', 'Malta', 'EUR', 'MLT'],
+    ['MU', 'Mauritius', 'MUR', 'MUS'],
+    ['MV', 'Maldives', 'MVR', 'MDV'],
+    ['MW', 'Malawi', 'MWK', 'MWI'],
+    ['MX', 'Mexico', 'MXN', 'MEX'],
+    ['MY', 'Malaysia', 'MYR', 'MYS'],
+    ['MZ', 'Mozambique', 'MZN', 'MOZ'],
+    ['NA', 'Namibia', 'NAD', 'NAM'],
+    ['NC', 'New Caledonia', 'XPF', 'NCL'],
+    ['NE', 'Niger', 'XOF', 'NER'],
+    ['NF', 'Norfolk Island', 'AUD', 'NFK'],
+    ['NG', 'Nigeria', 'NGN', 'NGA'],
+    ['NI', 'Nicaragua', 'NIO', 'NIC'],
+    ['NL', 'Netherlands', 'EUR', 'NLD'],
+    ['NO', 'Norway', 'NOK', 'NOR'],
+    ['NP', 'Nepal', 'NPR', 'NPL'],
+    ['NR', 'Nauru', 'AUD', 'NRU'],
+    ['NU', 'Niue', 'NZD', 'NIU'],
+    ['NZ', 'New Zealand', 'NZD', 'NZL'],
+    ['OM', 'Oman', 'OMR', 'OMN'],
+    ['PA', 'Panama', 'PAB', 'PAN'],
+    ['PE', 'Peru', 'PEN', 'PER'],
+    ['PF', 'French Polynesia', 'XPF', 'PYF'],
+    ['PG', 'Papua New Guinea', 'PGK', 'PNG'],
+    ['PH', 'Philippines', 'PHP', 'PHL'],
+    ['PK', 'Pakistan', 'PKR', 'PAK'],
+    ['PL', 'Poland', 'PLN', 'POL'],
+    ['PM', 'Saint Pierre and Miquelon', 'EUR', 'SPM'],
+    ['PN', 'Pitcairn Islands', 'NZD', 'PCN'],
+    ['PR', 'Puerto Rico', 'USD', 'PRI'],
+    ['PS', 'Palestine', 'ILS', 'PSE'],
+    ['PT', 'Portugal', 'EUR', 'PRT'],
+    ['PW', 'Palau', 'USD', 'PLW'],
+    ['PY', 'Paraguay', 'PYG', 'PRY'],
+    ['QA', 'Qatar', 'QAR', 'QAT'],
+    ['RE', 'R&eacute;union', 'EUR', 'REU'],
+    ['RO', 'Romania', 'RON', 'ROU'],
+    ['RS', 'Serbia', 'RSD', 'SRB'],
+    ['RU', 'Russia', 'RUB', 'RUS'],
+    ['RW', 'Rwanda', 'RWF', 'RWA'],
+    ['SA', 'Saudi Arabia', 'SAR', 'SAU'],
+    ['SB', 'Solomon Islands', 'SBD', 'SLB'],
+    ['SC', 'Seychelles', 'SCR', 'SYC'],
+    ['SD', 'Sudan', 'SDG', 'SDN'],
+    ['SE', 'Sweden', 'SEK', 'SWE'],
+    ['SG', 'Singapore', 'SGD', 'SGP'],
+    ['SH', 'Saint Helena', 'SHP', 'SHN'],
+    ['SI', 'Slovenia', 'EUR', 'SVN'],
+    ['SJ', 'Svalbard and Jan Mayen', 'NOK', 'SJM'],
+    ['SK', 'Slovakia', 'EUR', 'SVK'],
+    ['SL', 'Sierra Leone', 'SLL', 'SLE'],
+    ['SM', 'San Marino', 'EUR', 'SMR'],
+    ['SN', 'Senegal', 'XOF', 'SEN'],
+    ['SO', 'Somalia', 'SOS', 'SOM'],
+    ['SR', 'Suriname', 'SRD', 'SUR'],
+    ['SS', 'South Sudan', 'SSP', 'SSD'],
+    ['ST', 'S&atilde;o Tom&eacute; and Pr&iacute;ncipe', 'STD', 'STP'],
+    ['SV', 'El Salvador', 'USD', 'SLV'],
+    ['SX', 'Sint Maarten', 'ANG', 'SXM'],
+    ['SY', 'Syria', 'SYP', 'SYR'],
+    ['SZ', 'Swaziland', 'SZL', 'SWZ'],
+    ['TC', 'Turks and Caicos Islands', 'USD', 'TCA'],
+    ['TD', 'Chad', 'XAF', 'TCD'],
+    ['TF', 'French Southern Territories', 'EUR', 'ATF'],
+    ['TG', 'Togo', 'XOF', 'TGO'],
+    ['TH', 'Thailand', 'THB', 'THA'],
+    ['TJ', 'Tajikistan', 'TJS', 'TJK'],
+    ['TK', 'Tokelau', 'NZD', 'TKL'],
+    ['TL', 'East Timor', 'USD', 'TLS'],
+    ['TM', 'Turkmenistan', 'TMT', 'TKM'],
+    ['TN', 'Tunisia', 'TND', 'TUN'],
+    ['TO', 'Tonga', 'TOP', 'TON'],
+    ['TR', 'Turkey', 'TRY', 'TUR'],
+    ['TT', 'Trinidad and Tobago', 'TTD', 'TTO'],
+    ['TV', 'Tuvalu', 'AUD', 'TUV'],
+    ['TW', 'Taiwan', 'TWD', 'TWN'],
+    ['TZ', 'Tanzania', 'TZS', 'TZA'],
+    ['UA', 'Ukraine', 'UAH', 'UKR'],
+    ['UG', 'Uganda', 'UGX', 'UGA'],
+    ['UM', 'U.S. Minor Outlying Islands', 'USD', 'UMI'],
+    ['US', 'United States', 'USD', 'USA'],
+    ['UY', 'Uruguay', 'UYU', 'URY'],
+    ['UZ', 'Uzbekistan', 'UZS', 'UZB'],
+    ['VA', 'Vatican City', 'EUR', 'VAT'],
+    ['VC', 'Saint Vincent and the Grenadines', 'XCD', 'VCT'],
+    ['VE', 'Venezuela', 'VEF', 'VEN'],
+    ['VG', 'British Virgin Islands', 'USD', 'VGB'],
+    ['VI', 'U.S. Virgin Islands', 'USD', 'VIR'],
+    ['VN', 'Vietnam', 'VND', 'VNM'],
+    ['VU', 'Vanuatu', 'VUV', 'VUT'],
+    ['WF', 'Wallis and Futuna', 'XPF', 'WLF'],
+    ['WS', 'Samoa', 'WST', 'WSM'],
+    ['XK', 'Kosovo', 'EUR', 'XKX'],
+    ['YE', 'Yemen', 'YER', 'YEM'],
+    ['YT', 'Mayotte', 'EUR', 'MYT'],
+    ['ZA', 'South Africa', 'ZAR', 'ZAF'],
+    ['ZM', 'Zambia', 'ZMK', 'ZMB'],
+    ['ZW', 'Zimbabwe', 'ZWL', 'ZWE']
+];
 
-$table = Database::get_main_table(TABLE_BUY_COURSE_SALE);
-$sql = "CREATE TABLE IF NOT EXISTS $table (
-    cod INT unsigned NOT NULL auto_increment PRIMARY KEY,
-    user_id INT unsigned NOT NULL,
-    course_code VARCHAR(200) NOT NULL DEFAULT '',
-    price FLOAT(11,2) NOT NULL DEFAULT '0',
-    payment_type VARCHAR(100) NOT NULL DEFAULT '',
-    status VARCHAR(20) NOT NULL DEFAULT '',
-    date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)";
-Database::query($sql);
+foreach ($currencies as $currency) {
+    Database::insert(
+        $currencyTable,
+        [
+            'country_code' => $currency[0],
+            'country_name' => $currency[1],
+            'iso_code' => $currency[2]
+        ]
+    );
+}

+ 16 - 210
plugin/buycourses/js/buycourses.js

@@ -4,227 +4,33 @@
  * @package chamilo.plugin.buycourses
  */
 $(document).ready(function () {
-    $("input[name='price']").change(function () {
-        $(this).parent().next().children().attr("style", "display:none");
-        $(this).parent().next().children().next().attr("style", "display:''");
-        $(this).parent().parent().addClass("fmod");
-        $(this).parent().parent().children().each(function () {
-            $(this).addClass("btop");
-        });
-    });
-
-    $("input[name='price']").keyup(function () {
-        $(this).parent().next().children().attr("style", "display:none");
-        $(this).parent().next().children().next().attr("style", "display:''");
-        $(this).parent().parent().addClass("fmod");
-        $(this).parent().parent().children().each(function () {
-            $(this).addClass("btop");
-        });
-    });
-
-    $("input[name='visible']").change(function () {
-        $(this).parent().next().next().children().attr("style", "display:none");
-        $(this).parent().next().next().children().next().attr("style", "display:''");
-        $(this).parent().parent().addClass("fmod");
-        $(this).parent().parent().children().each(function () {
-            $(this).addClass("btop");
-        });
-    });
-
-    $(".save").click(function () {
+    $(".bc-button-save").click(function () {
         var currentRow = $(this).closest("tr");
-        var courseOrSessionObject ={
+        var courseOrSessionObject = {
             tab: "save_mod",
             visible: currentRow.find("[name='visible']").is(':checked') ? 1 : 0,
             price: currentRow.find("[name='price']").val()
         };
 
-        var course_id = $(this).attr('id');
-        var courseOrSession = ($(this).closest("td").attr('id')).indexOf("session") > -1 ? "session_id" : "course_id";
-
-        courseOrSessionObject[courseOrSession] = course_id;
-
-        $.post("function.php", courseOrSessionObject,
-            function (data) {
-                if (data.status == "false") {
-                    alert("Database Error");
-                } else {
-                    courseOrSession = courseOrSession.replace("_id", "");
-                    $("#" + courseOrSession + data.course_id).children().attr("style", "display:''");
-                    $("#" + courseOrSession + data.course_id).children().next().attr("style", "display:none");
-                    $("#" + courseOrSession + data.course_id).parent().removeClass("fmod")
-                    $("#" + courseOrSession + data.course_id).parent().children().each(function () {
-                        $(this).removeClass("btop");
-                    });
-                }
-            }, "json");
-    });
+        var itemField = currentRow.data('type') + '_id';
 
-    $('#sync').click(function (e) {
-        $.post("function.php", {tab: "sync"},
-            function (data) {
-                if (data.status == "false") {
-                    alert(data.contenido);
-                } else {
-                    alert(data.contenido);
-                    location.reload();
-                }
-            }, "json");
-        e.preventDefault();
-        e.stopPropagation();
-    });
+        courseOrSessionObject[itemField] = currentRow.data('item') || 0;
 
-    $(".filter").click(function (e) {
-        var target = "#"+($(this).closest(".row").children().last()).attr("id");
-        var filterFields = $(this).siblings("input");
-        var filterFieldsData = { tab: $(this).attr("id") };
-        $.each(filterFields, function() {
-            // Get only the first class
-            var className = $(this).attr("class").split(" ")[0];
-            filterFieldsData[className] = $(this).val();
-        });
-        $.post("function.php", filterFieldsData,
+        $.post(
+            "function.php",
+            courseOrSessionObject,
             function (data) {
-                if (data.status == "false") {
-                    alert(data.content);
-                    $(target).html('');
-                } else {
-                    $(target).html(data.content);
+                if (!data.status) {
+                    return;
                 }
-                $(document).ready(acciones_ajax);
-            }, "json");
-        e.preventDefault();
-        e.stopPropagation();
-    });
-
-    $("#save_currency").click(function (e) {
-        var currency_type = $("#currency_type").attr("value");
-        $.post("function.php", {tab: "save_currency", currency: currency_type},
-            function (data) {
-                alert(data.content);
-            }, "json");
 
-        e.preventDefault();
-        e.stopPropagation();
-    });
-
-    $("#save_paypal").click(function (e) {
-        var name = $("#username").attr("value");
-        var clave = $("#password").attr("value");
-        var firma = $("#signature").attr("value");
-        if ($("#sandbox").attr("checked") == "checked") {
-            var vsandbox = "YES";
-        } else {
-            var vsandbox = "NO";
-        }
-        $.post("function.php", {tab: "save_paypal", username: name, password: clave, signature: firma, sandbox: vsandbox},
-            function (data) {
-                alert(data.content);
-            }, "json");
-
-        e.preventDefault();
-        e.stopPropagation();
-    });
+                currentRow.addClass('success');
 
-    $("#add_account").click(function (e) {
-        var tname = $("#tname").attr("value");
-        var taccount = $("#taccount").attr("value");
-        var tswift = $("#tswift").attr("value");
-        if (tname == '' || taccount == '') {
-            alert("Complete los campos antes de insertar");
-        } else {
-            $.post("function.php", {tab: "add_account", name: tname, account: taccount, swift: tswift},
-                function (data) {
-                    location.reload();
-                }, "json");
-        }
-        e.preventDefault();
-        e.stopPropagation();
-    });
-
-    $(".delete_account").click(function (e) {
-        var fieldName = $(this).parent().attr("id");
-        var id = $("#id_" + fieldName).val();
-        $.post("function.php", {tab: "delete_account", id: id},
-            function (data) {
-                location.reload();
-            }, "json");
-
-        e.preventDefault();
-        e.stopPropagation();
-    });
-
-    $("#cancel_order").click(function (e) {
-        $.post("function.php", {tab: "unset_variables"});
-        window.location.replace("list.php");
-    });
-
-    $(".clear_order").click(function (e) {
-        var vid = $(this).parent().attr("id");
-        $.post("function.php", {tab: "clear_order", id: vid},
-            function (data) {
-                location.reload();
-            }, "json");
-
-        e.preventDefault();
-        e.stopPropagation();
-    });
-
-    $(".confirm_order").click(function (e) {
-        var vid = $(this).parent().attr("id");
-        $.post("function.php", {tab: "confirm_order", id: vid},
-            function (data) {
-                location.reload();
-            }, "json");
-
-        e.preventDefault();
-        e.stopPropagation();
-    });
-
-    $(".slt_tpv").change(function () {
-        var vcod = $(this).attr("value");
-        $.post("function.php", {tab: "activar_tpv", cod: vcod});
+                window.setTimeout(function () {
+                    currentRow.removeClass('success');
+                }, 3000);
+            },
+            "json"
+        );
     });
 });
-
-function acciones_ajax() {
-    $('.ajax').on('click', function () {
-        var url = this.href;
-        var dialog = $("#dialog");
-        if ($("#dialog").length == 0) {
-            dialog = $('<div id="dialog" style="display:none"></div>').appendTo('body');
-        }
-        width_value = 580;
-        height_value = 450;
-        resizable_value = true;
-        new_param = get_url_params(url, 'width');
-        if (new_param) {
-            width_value = new_param;
-        }
-        new_param = get_url_params(url, 'height')
-        if (new_param) {
-            height_value = new_param;
-        }
-        new_param = get_url_params(url, 'resizable');
-        if (new_param) {
-            resizable_value = new_param;
-        }
-        // load remote content
-        dialog.load(
-            url,
-            {},
-            function (responseText, textStatus, XMLHttpRequest) {
-                dialog.dialog({
-                    modal: true,
-                    width: width_value,
-                    height: height_value,
-                    resizable: resizable_value
-                });
-            });
-        //prevent the browser to follow the link
-        return false;
-    });
-
-
-}
-

+ 68 - 67
plugin/buycourses/lang/english.php

@@ -3,83 +3,84 @@ $strings['plugin_title'] = "Sell courses";
 $strings['plugin_comment'] = "Sell courses directly through your Chamilo portal, using a PayPal account to receive funds. This plugin is in beta version. Neither the Chamilo association nor the developers involved could be considered responsible of any issue you might suffer using this plugin.";
 $strings['show_main_menu_tab'] = "Show tab in main menu";
 $strings['show_main_menu_tab_help'] = "In case of not wanting to show the tab, you can create this link in your Chamilo homepage : %s";
-$strings['Visible'] = "Show list";
-$strings['Options'] = "Options";
-$strings['Price'] = "Price";
-$strings['SyncCourseDatabase'] = "Synchronize courses from database";
-$strings['Private'] = "Private - access authorized only for course members";
-$strings['CourseVisibilityClosed'] = "Closed - no access to this course";
-$strings['OpenToThePlatform'] = "Open - access authorized only for users registered on the platform";
-$strings['OpenToTheWorld'] = "Public - access open to anybody";
-$strings['CourseVisibilityHidden'] = "Hidden - Completely hidden to all users except the administrators";
-$strings['Description'] = "Description";
-$strings['Buy'] = "Buy";
-$strings['Mostrar_disponibles'] = "Show available courses";
 $strings['include_sessions'] = "Include sessions";
 $strings['paypal_enable'] = "Enable PayPal";
 $strings['transfer_enable'] = "Enable bank transfer";
 $strings['unregistered_users_enable'] = "Allow anonymous users";
-$strings['Cancelacionpedido'] = "The payment has been cancelled.";
-$strings['AlreadyBuy'] = "You are already subscribed to this course.";
-$strings['bc_subject'] = "Confirmation of course order";
-$strings['paypal'] = 'PayPal';
-$strings['confirmar_compra'] = 'Course purchase confirmation';
-$strings['TheUserIsAlreadyRegistered'] = 'The user is already registered';
-$strings['ProblemToSaveTheCurrencyType'] = 'Problem loading the currency type';
-$strings['ProblemToSaveThePaypalParameters'] = 'Problem saving PayPal parameters';
-$strings['ProblemToInsertANewAccount'] = 'Problem inserting the new account';
-$strings['ProblemToDeleteTheAccount'] = 'Problem removing account';
-$strings['ProblemToSaveTheMessage'] = 'Problem saving message';
-$strings['ProblemToSubscribeTheUser'] = 'Problem subscribing the user';
-$strings['TheSubscriptionAndActivationWereDoneSuccessfully'] = 'The subscription and activation were successful';
-$strings['TheUserIsAlreadyRegisteredInTheCourse'] = 'You are already registered in the course.';
-$strings['CourseListOnSale'] = 'List of courses on sale';
-$strings['BuySessions'] = "Buy sessions";
-$strings['BuyCourses'] = 'Buy courses';
-$strings['ConfigurationOfCoursesAndPrices'] = 'Courses and prices configuration';
-$strings['ConfigurationOfPayments'] = 'Payments configuration';
-$strings['OrdersPendingOfPayment'] = 'Orders awaiting payment';
-$strings['AvailableCoursesConfiguration'] = 'Available courses configuration';
-$strings['PaymentsConfiguration'] = 'Payments configuration';
-$strings['bc_message'] = "Dear {{name}}. <br />We are currently waiting for the payment confirmation. Once received, we will enable your user in course <strong>{{curso}}</strong>.<br><br><strong>Please do not forget to mention your order reference number in your transfer: <div style='display:inline;text-align:center; font-weight:bold; font-size:20px; color:#333'>{{reference}}</div></strong>";
-$strings['Categories'] = "Categories";
-$strings['BankTransfer'] = 'Bank transfer';
-$strings['EnrollToCourseXSuccessful'] = "Your subscription to the course is complete";
+
+$strings['BankTransfer'] = "Bank transfer";
+$strings['SaleStatusPending'] = "Sale pending";
+$strings['SaleStatusCanceled'] = "Sale canceled";
+$strings['SaleStatusCompleted'] = "Sale completed";
+$strings['CourseListOnSale'] = "List of courses on sale";
+$strings['AvailableCourses'] = "Available Courses";
+$strings['Price'] = "Price";
 $strings['SearchFilter'] = "Search filter";
 $strings['MinimumPrice'] = "Minimum price";
 $strings['MaximumPrice'] = "Maximum price";
-$strings['AvailableCourses'] = "Courses available";
-$strings['PaymentConfiguration'] = "Payment configuration";
+$strings['AvailableCoursesConfiguration'] = "Available courses configuration";
+$strings['PaymentsConfiguration'] = "Payments configuration";
+$strings['TheUserIsAlreadyRegisteredInTheCourse'] = "You are already registered in the course.";
+$strings['SeeDescription'] = "Description";
+$strings['Buy'] = "Buy";
 $strings['WaitingToReceiveThePayment'] = "Currently pending payment";
-$strings['CurrencyType'] = "Currency type";
-$strings['SelectACurrency'] = "Choose a currency";
-$strings['Sandbox'] = "Test environment";
+$strings['TheUserIsAlreadyRegisteredInTheSession'] = "You are already registered in the session";
+$strings['ItemNotSaved'] = "Item not saved";
+$strings['TitlePlugin'] = "Everything you need to teach and sell courses online";
+$strings['PluginPresentation'] = "The BuyCourses Plugin gives you the means to sell your courses or sessions and teach online, through only a few simple steps and settings. What are you waiting for? Start selling courses through Chamilo LMS!";
+$strings['Instructions'] = "Instructions";
+$strings['InstructionsStepOne'] = "Create a course or session on the platform.";
+$strings['InstructionsStepTwo'] = "In the <strong>payment settings</strong>, set the currency with which you would like to sell your courses or sessions.";
+$strings['InstructionsStepThree'] = "Configure courses to sell in the <strong>Courses and prices</strong > settings.";
+$strings['BuyCourses'] = "Buy courses";
+$strings['ConfigurationOfCoursesAndPrices'] = "Courses and prices configuration";
+$strings['SalesReport'] = "Sales report";
+$strings['UserInformation'] = "Buyer's details";
+$strings['PaymentMethods'] = "Payment methods";
+$strings['ConfirmOrder'] = "Confirm order";
+$strings['PurchaseData'] = "Purchase data";
+$strings['bc_subject'] = "Confirmation of course order";
+$strings['PurchaseStatusX'] = "Purchase status: %s";
+$strings['PendingReasonByTransfer'] = "<b>Pending</b>. Awaiting for transfer confirmation";
+$strings['CancelOrder'] = "Cancel order";
+$strings['BankAccountInformation'] = "Bank account details";
 $strings['BankAccount'] = "Bank account";
+$strings['OnceItIsConfirmedYouWillReceiveAnEmailWithTheBankInformationAndAnOrderReference'] = "Once confirmed, you will receive an e-mail with the bank details and an order reference.";
+$strings['SubscriptionToCourseXSuccessful'] = "Your subscription to \"%s\" was completed successfully.";
+$strings['OrderCanceled'] = "Order canceled";
+$strings['OrderStatus'] = "Order status";
+$strings['SearchByStatus'] = "Search by status";
+$strings['OrderReference'] = "Order reference";
+$strings['OrderDate'] = "Order date";
+$strings['ProductType'] = "Product type";
 $strings['SubscribeUser'] = "Subscribe user";
-$strings['DeleteTheOrder'] = "Delete order";
-$strings['ReferenceOrder'] = 'Order reference';
-$strings['UserInformation'] = "Buyer's details";
-$strings['OnceItIsConfirmed,YouWillReceiveAnEmailWithTheBankInformationAndAnOrderReference'] = "Once confirmed, you will receive an e-mail with the bank details and an order reference.";
-$strings['BankAccountInformation'] = 'Bank account details';
-$strings['ConfirmOrder'] = 'Confirm order';
-$strings['PaymentMethods'] = 'Payment methods';
-$strings['CancelOrder'] = 'Cancel order';
+$strings['DeleteOrder'] = "Delete order";
 $strings['ErrorContactPlatformAdmin'] = "Unknown error. Please contact the platform administrator.";
+$strings['PendingReasonByAddress'] = "<b>Pending</b>. You did not enter a confirmed shipping address.";
+$strings['PendingReasonByAuthorization'] = "<b>Pending</b>. We have not yet captured funds.";
+$strings['PendingReasonByEcheck'] = "<b>Pending</b>. The payment was made by an eCheck that has not yet cleared";
+$strings['PendingReasonByIntl'] = "<b>Pending</b>. We have no a withdrawal mechanism for funds.";
+$strings['PendingReasonByMulticurrency'] = "<b>Pending</b>. We have not balance in the currency sent.";
+$strings['PendingReasonByOrder'] = "<b>Pending</b>. Order made. We have not yet captured funds.";
+$strings['PendingReasonByPaymentReview'] = "<b>Pending</b>. The payment is being reviewed by PayPal for risk.";
+$strings['PendingReasonByRegulatoryReview'] = "<b>Pending</b>. The payment is being reviewed for compliance with government regulations.";
+$strings['PendingReasonByUnilateral'] = "<b>Pending</b>. The email address is not yet registered o confirmed.";
+$strings['PendingReasonByUpgrade'] = "<b>Pending</b>. The payment was made via credit card.";
+$strings['PendingReasonByVerify'] = "<b>Pending</b>. Sorry. We are not yet verified in PayPal.";
+$strings['PendingReasonByOther'] = "<b>Pending</b>. Please contact with the platform admin.";
+$strings['PayPalPaymentOKPleaseConfirm'] = "PayPal reports the transaction is ready to be executed. To acknowledge that you are OK to proceed, please click the confirmation button below. Once clicked, you will be registered to the course and the funds will be transferred from your PayPal account to our shop. You can always access your courses through the 'My courses' tab. Thank you for your custom!";
+$strings['Sandbox'] = "Test environment";
 $strings['PayPalConfig'] = "PayPal configuration:";
 $strings['TransfersConfig'] = "Bank transfers configuration:";
-$strings['PayPalPaymentOKPleaseConfirm'] = "PayPal reports the transaction is ready to be executed. To acknowledge that you are OK to proceed, please click the confirmation button below. Once clicked, you will be registered to the course and the funds will be transferred from your PayPal account to our shop. You can always access your courses through the 'My courses' tab. Thank you for your custom!";
-$strings['EnrollToSessionXSuccessful'] = "Your subscription to the session is complete";
-$strings['TheUserIsAlreadyRegisteredInTheSession'] = 'You are already registered in the session';
-$strings['Instructions'] = 'Instructions';
-$strings['InstructionsStepOne'] = 'Create a course or session on the platform.';
-$strings['InstructionsStepTwo'] = 'In the <strong>payment settings</strong>, set the currency with which you would like to sell your courses or sessions.';
-$strings['InstructionsStepThree'] = 'Configure courses to sell in the <strong>Courses and prices</strong > settings.';
-$strings['PluginPresentation'] = 'The BuyCourses Plugin gives you the means to sell your courses or sessions and teach online, through only a few simple steps and settings. What are you waiting for? Start selling courses through Chamilo LMS!';
-$strings['TitlePlugin'] = 'Everything you need to teach and sell courses online';
-$strings['PluginInstruction'] = 'You can enable or disable the option to pay via PayPal or bank transfer settings in the configuration section of the plugin.';
-$strings['ClickHere'] = 'Click here for more details';
-$strings['InfoCurrency'] = 'Sets the currency for the payment of your courses.';
-$strings['InfoApiCredentials'] = 'To generate your API credentials to integrate Chamilo with your PayPal account, you must follow the following steps';
-$strings['InfoApiStepOne'] = 'Go to your PayPal account, <strong>Summary</strong>, then <front>Seller preferences</front> in the <front>Selling Tools</front> menu (if you do not have this menu entry, you might need to get the authorization to sell stuff through PayPal first).';
-$strings['InfoApiStepTwo'] = 'In paragraph <strong>API access</strong>, click <strong>Update</strong>';
-$strings['InfoApiStepThree'] = 'In Option 2 (Request API credentials to create your own API username and password), click the <strong>View API Signature</strong> link, and copy the credentials shown right into the BuyCourses plugin form';
+$strings['PluginInstruction'] = "You can enable or disable the option to pay via PayPal or bank transfer settings in the configuration section of the plugin.";
+$strings['ClickHere'] = "<i>Click here</i> for more details";
+$strings['CurrencyType'] = "Currency type";
+$strings['InfoCurrency'] = "Sets the currency for the payment of your courses.";
+$strings['ApiUsername'] = "API Username";
+$strings['ApiPassword'] = "API Password";
+$strings['ApiSignature'] = "API Signature";
+$strings['InfoApiCredentials'] = "To generate your API credentials to integrate Chamilo with your PayPal account, you must follow the following steps";
+$strings['InfoApiStepOne'] = "Go to your PayPal account, <strong>Summary</strong>, then <front>Seller preferences</front> in the <front>Selling Tools</front> menu (if you do not have this menu entry, you might need to get the authorization to sell stuff through PayPal first).";
+$strings['InfoApiStepTwo'] = "In paragraph <strong>API access</strong>, click <strong>Update</strong>";
+$strings['InfoApiStepThree'] = "In Option 2 (Request API credentials to create your own API username and password), click the <strong>View API Signature</strong> link, and copy the credentials shown right into the BuyCourses plugin form";
+$strings['ErrorOccurred'] = "<strong>An error ocurred</strong>. Code: %s. Message: %s. Please contact to platform admin";

+ 66 - 65
plugin/buycourses/lang/french.php

@@ -3,83 +3,84 @@ $strings['plugin_title'] = "Vente de cours";
 $strings['plugin_comment'] = "Vendez vos cours directement depuis votre portail Chamilo, au travers d'un compte PayPal. Plugin en version beta, à utiliser avec précaution. Ni l'association Chamilo ni les développeurs impliqués dans le développement de ce plugin ne sauraient être tenus responsables d'un quelconque inconvénient causé par celui-ci.";
 $strings['show_main_menu_tab'] = "Montrer l'onglet dans le menu principal";
 $strings['show_main_menu_tab_help'] = "Dans le cas où vous ne souhaitez pas montrer l'onglet, il est possible de rajouter le lien suivant à votre portail Chamilo: %s";
-$strings['Visible'] = "Montrer dans la liste";
-$strings['Options'] = "Options";
-$strings['Price'] = "Prix";
-$strings['SyncCourseDatabase'] = "Synchroniser les cours depuis la base de données";
-$strings['Private'] = "Privé - Accès autorisé seulement aux inscrits au cours";
-$strings['CourseVisibilityClosed'] = "Fermé - Pas d'accès au cours";
-$strings['OpenToThePlatform'] = "Ouvert - Accès autorisé seulement pour les utilisateurs inscrits à la plateforme";
-$strings['OpenToTheWorld'] = "Public - Accès autorisé à tous";
-$strings['CourseVisibilityHidden'] = "Invisible - Complètement invisible et inaccessible pour tous les utilisateurs excepté les administrateurs";
-$strings['Description'] = "Description";
-$strings['Buy'] = "Acheter";
-$strings['Mostrar_disponibles'] = "Montrer les cours disponibles";
 $strings['include_sessions'] = "Inclure les sessions";
 $strings['paypal_enable'] = "Activer PayPal";
 $strings['transfer_enable'] = "Activer les transferts bancaires";
 $strings['unregistered_users_enable'] = "Permettre l'accès aux utilisateurs non enregistrés sur la plateforme";
-$strings['Cancelacionpedido'] = "La commande a été annulée.";
-$strings['AlreadyBuy'] = "Vous êtes déjà inscrit au cours";
-$strings['bc_subject'] = "Confirmation de commande de cours";
-$strings['paypal'] = "PayPal";
-$strings['confirmar_compra'] = "Confirmer achat de cours";
-$strings['TheUserIsAlreadyRegistered'] = "L'utilisateur est déjà inscrit";
-$strings['ProblemToSaveTheCurrencyType'] = "Problème de sauvegarde du type de devise";
-$strings['ProblemToSaveThePaypalParameters'] = "Problème de sauvegarde des paramètres de Paypal";
-$strings['ProblemToInsertANewAccount'] = "Problème à l'insertion du nouveau compte";
-$strings['ProblemToDeleteTheAccount'] = "Problème de suppression du compte";
-$strings['ProblemToSaveTheMessage'] = "Problème d'enregistrement du message";
-$strings['ProblemToSubscribeTheUser'] = "Problème d'inscription de l'utilisateur";
-$strings['TheSubscriptionAndActivationWereDoneSuccessfully'] = "L'inscription et l'activation se sont déroulés sans problème.";
-$strings['TheUserIsAlreadyRegisteredInTheCourse'] = "L'utilisateur est déjà inscrit au cours";
+
+$strings['BankTransfer'] = "Transfert bancaire";
+$strings['SaleStatusPending'] = "Vente non confirmée";
+$strings['SaleStatusCanceled'] = "Vente annulée";
+$strings['SaleStatusCompleted'] = "Vente finalisée";
 $strings['CourseListOnSale'] = "Liste de cours en vente";
-$strings['BuySessions'] = "Acheter des sessions";
-$strings['BuyCourses'] = "Acheter des cours";
-$strings['ConfigurationOfCoursesAndPrices'] = "Configuration des cours et prix";
-$strings['ConfigurationOfPayments'] = "Configuration des paiements";
-$strings['OrdersPendingOfPayment'] = "Commandes en attente de paiement";
-$strings['AvailableCoursesConfiguration'] = "Configuration des cours disponibles";
-$strings['PaymentsConfiguration'] = "Configuration des paiements";
-$strings['bc_message'] = "Cher/Chère {{name}}. <br />À la réception de la confirmation de paiement, nous terminerons le processus d'inscrtipion au cours <strong>{{curso}}</strong>.<br><br><strong>N'oubliez pas d'indiquer le numéro de référence de la commande lors de votre transfert: <div style='display:inline;text-align:center; font-weight:bold; font-size:20px; color:#333'>{{reference}}</div></strong>";
-$strings['Categories'] = "Catégories";
-$strings['BankTransfer'] = 'Transfert bancaire';
-$strings['EnrollToCourseXSuccessful'] = "Votre inscription au cours %s est terminée.";
+$strings['AvailableCourses'] = "Cours disponibles";
+$strings['Price'] = "Prix";
 $strings['SearchFilter'] = "Filtre de recherche";
 $strings['MinimumPrice'] = "Prix minimum";
 $strings['MaximumPrice'] = "Prix maximum";
-$strings['AvailableCourses'] = "Cours disponibles";
-$strings['PaymentConfiguration'] = "Configuration des paiements";
+$strings['AvailableCourses'] = "Configuration des cours disponibles";
+$strings['PaymentsConfiguration'] = "Configuration des paiements";
+$strings['TheUserIsAlreadyRegisteredInTheCourse'] = "L'utilisateur est déjà inscrit au cours";
+$strings['SeeDescription'] = "Voir description";
+$strings['Buy'] = "Acheter";
 $strings['WaitingToReceiveThePayment'] = "En attente de réception du paiement";
-$strings['CurrencyType'] = "Tipe de device";
-$strings['SelectACurrency'] = "Sélectionnez une devise";
-$strings['Sandbox'] = "Environnement de test";
-$strings['BankAccount'] = "Compte bancaire";
-$strings['SubscribeUser'] = "Inscrire utilisateur";
-$strings['DeleteTheOrder'] = "Éliminer la commande";
-$strings['ReferenceOrder'] = "Référence de la commande";
+$strings['TheUserIsAlreadyRegisteredInTheSession'] = "Vous êtes déjà inscrit à cette session";
+$strings['ItemNotSaved'] = "Article non sauvé";
+$strings['TitlePlugin'] = "Tout le nécessaire pour enseigner et vendre des cours en ligne";
+$strings['PluginPresentation'] = "Le plugin BuyCourses vous donne les moyens nécessaires pour vendre vos cours ou vos sessions existants et d\'enseigner en ligne, en quelques étapes très simples. Qu\'attendez-vous? Commencez à vendre des cours grâce à Chamilo dès maintenant!";
+$strings['Instructions'] = "Instructions d'utilisation";
+$strings['InstructionsStepOne'] = "Créer un cours ou une session de formation sur la plateforme.";
+$strings['InstructionsStepTwo'] = "Dans la section <strong>configuration de paiements</strong>, configurer le type de devise dans lequel vous souhaitez vendre vos cours et sessions";
+$strings['InstructionsStepThree'] = "Configurer les cours à vendre dans la section <strong>Configuration de cours et prix</strong>";
+$strings['BuyCourses'] = "Acheter des cours";
+$strings['ConfigurationOfCoursesAndPrices'] = "Configuration des cours et prix";
+$strings['SalesReport'] = "Rapport des ventes";
 $strings['UserInformation'] = "Fiche acheteur";
-$strings['OnceItIsConfirmed,YouWillReceiveAnEmailWithTheBankInformationAndAnOrderReference'] = "Une fois confirmée, vous recevrez un e-mail avec les données bancaires et la référence de la commande";
-$strings['BankAccountInformation'] = "Détails du compte bancaire";
-$strings['ConfirmOrder'] = "Confirmer commande";
 $strings['PaymentMethods'] = "Méthodes de paiement";
+$strings['ConfirmOrder'] = "Confirmer commande";
+$strings['PurchaseData'] = "Détails d'achat";
+$strings['bc_subject'] = "Confirmation de commande de cours";
+$strings['PurchaseStatusX'] = "État de la vente: %s";
+$strings['PendingReasonByTransfer'] = "<b>En attente</b>. Transfert pas encore confirmé";
 $strings['CancelOrder'] = "Annuler la commande";
+$strings['BankAccountInformation'] = "Détails du compte bancaire";
+$strings['BankAccount'] = "Compte bancaire";
+$strings['OnceItIsConfirmedYouWillReceiveAnEmailWithTheBankInformationAndAnOrderReference'] = "Une fois confirmée, vous recevrez un e-mail avec les données bancaires et la référence de la commande";
+$strings['SubscriptionToCourseXSuccessful'] = "Votre inscription au \"%s\" est terminée.";
+$strings['OrderCanceled'] = "Commande annulée";
+$strings['OrderStatus'] = "Statut de commande";
+$strings['SearchByStatus'] = "Recherche par statut";
+$strings['OrderReference'] = "Référence de la commande";
+$strings['OrderDate'] = "Date de commande";
+$strings['ProductType'] = "Type de produit";
+$strings['SubscribeUser'] = "Inscrire utilisateur";
+$strings['DeleteOrder'] = "Éliminer la commande";
 $strings['ErrorContactPlatformAdmin'] = "Une erreur inconnue s'est produite. Veuillez contacter l'administrateur de la plateforme.";
+$strings['PendingReasonByAddress'] = "<b>En attente</b>. Il manque une adresse de livraison.";
+$strings['PendingReasonByAuthorization'] = "<b>En attente</b>. Nous n'avons pas confirmé la réception des fonds.";
+$strings['PendingReasonByEcheck'] = "<b>En attente</b>. Le paiement a été fait via un chèque qui n'a pas encore été libéré";
+$strings['PendingReasonByIntl'] = "<b>En attente</b>. Aucun moyen de toucher les fonds.";
+$strings['PendingReasonByMulticurrency'] = "<b>En attente</b>. Nous n'avons pas de compte dans la devise indiquée.";
+$strings['PendingReasonByOrder'] = "<b>En attente</b>. Commande enregistrée. Les fonds n'ont pas encore été libérés.";
+$strings['PendingReasonByPaymentReview'] = "<b>En attente</b>. Le paiement est en révision anti-fraude chez PayPal.";
+$strings['PendingReasonByRegulatoryReview'] = "<b>En attente</b>. Le paiement est actuellement revu pour correspondre aux règles mises en vigueur par le gouvernement.";
+$strings['PendingReasonByUnilateral'] = "<b>En attente</b>. L'adresse e-mail n'est pas encore confirmée ou enregistrée.";
+$strings['PendingReasonByUpgrade'] = "<b>En attente</b>. Le paiement a été fait par carte de crédit.";
+$strings['PendingReasonByVerify'] = "<b>En attente</b>. Désolé, nous n'avons pas encore vérifié sur PayPal.";
+$strings['PendingReasonByOther'] = "<b>En attente</b>. Veuillez contacter l'administrateur.";
+$strings['PayPalPaymentOKPleaseConfirm'] = "PayPal nous indique que la transaction est prête à être exécutée. Par mesure de sécurité, nous vous demandons de bien vouloir confirmer une dernière fois la transaction en cliquant sur le bouton de confirmation ci-dessous. Une fois cliqué, vous serez immédiatement enregistré au cours, et les fonds correspondants seront soustraits de votre compte PayPal. Vous pouvez accéder à vos cours à tout moment à partir de l'onglet 'Mes cours'. Merci de votre fidélité!";
+$strings['Sandbox'] = "Environnement de test";
 $strings['PayPalConfig'] = "Configuration PayPal:";
 $strings['TransfersConfig'] = "Configuration des transfers bancaires:";
-$strings['PayPalPaymentOKPleaseConfirm'] = "PayPal nous indique que la transaction est prête à être exécutée. Par mesure de sécurité, nous vous demandons de bien vouloir confirmer une dernière fois la transaction en cliquant sur le bouton de confirmation ci-dessous. Une fois cliqué, vous serez immédiatement enregistré au cours, et les fonds correspondants seront soustraits de votre compte PayPal. Vous pouvez accéder à vos cours à tout moment à partir de l'onglet 'Mes cours'. Merci de votre fidélité!";
-$strings['EnrollToSessionXSuccessful'] = "Votre inscription à la session %s est terminée.";
-$strings['TheUserIsAlreadyRegisteredInTheSession'] = "Vous êtes déjà inscrit à cette session";
-$strings['Instructions'] = 'Instructions d\'utilisation';
-$strings['InstructionsStepOne'] = 'Créer un cours ou une session de formation sur la plateforme.';
-$strings['InstructionsStepTwo'] = 'Dans la section <strong>configuration de paiements</strong>, configurer le type de devise dans lequel vous souhaitez vendre vos cours et sessions';
-$strings['InstructionsStepThree'] = 'Configurer les cours à vendre dans la section <strong>Configuration de cours et prix</strong>';
-$strings['PluginPresentation'] = 'Le plugin BuyCourses vous donne les moyens nécessaires pour vendre vos cours ou vos sessions existants et d\'enseigner en ligne, en quelques étapes très simples. Qu\'attendez-vous? Commencez à vendre des cours grâce à Chamilo dès maintenant!';
-$strings['TitlePlugin'] = 'Tout le nécessaire pour enseigner et vendre des cours en ligne';
-$strings['PluginInstruction'] = 'Vous pouvez activer ou désactiver l\'option de paiements via PayPal ou de transferts bancaires dans la section de configuration des plugins.';
-$strings['ClickHere'] = 'Cliquez ici pour plus d\'infos';
-$strings['InfoCurrency'] = 'Permet configurer le type de devise pour l\'achat des cours.';
-$strings['InfoApiCredentials'] = 'Pour générer vos données API pour intégrer votre compte PayPal à Chamilo, il vous faudra suivre les étapes suivantes';
-$strings['InfoApiStepOne'] = 'Aller dans l\'option <strong>profil</strong> de PayPal, et ensuite dans <strong>Outils de vente</strong>';
-$strings['InfoApiStepTwo'] = 'Dans la section <strong>API d\'accès</strong>, cloquer sur l\'option <strong>Mettre à jour</strong>';
-$strings['InfoApiStepThree'] = 'Dans l\'option 2 de Configuration des données et permissions API, cliquer sur <strong>Voir signature API</strong>. Copier ces donées dans le formulaire de configuration de ce plugin';
+$strings['PluginInstruction'] = "Vous pouvez activer ou désactiver l'option de paiements via PayPal ou de transferts bancaires dans la section de configuration des plugins.";
+$strings['ClickHere'] = "Cliquez ici pour plus d'infos";
+$strings['CurrencyType'] = "Type de devise";
+$strings['InfoCurrency'] = "Permet de configurer la devise pour l'achat des cours.";
+$strings['ApiUsername'] = "Nom d'utilisateur de l'API";
+$strings['ApiPassword'] = "Mot de passe de l'API";
+$strings['ApiSignature'] = "Signature de l'API";
+$strings['InfoApiCredentials'] = "Pour générer vos données API pour intégrer votre compte PayPal à Chamilo, il vous faudra suivre les étapes suivantes";
+$strings['InfoApiStepOne'] = "Aller dans l\'option <strong>profil</strong> de PayPal, et ensuite dans <strong>Outils de vente</strong>";
+$strings['InfoApiStepTwo'] = "Dans la section <strong>API d\'accès</strong>, cloquer sur l\'option <strong>Mettre à jour</strong>";
+$strings['InfoApiStepThree'] = "Dans l\'option 2 de Configuration des données et permissions API, cliquer sur <strong>Voir signature API</strong>. Copier ces donées dans le formulaire de configuration de ce plugin";
+$strings['ErrorOccurred'] = "<strong>Une erreur est survenue</strong>. Code: %s. Message: %s. Veuillez contacter l'administrateur de la plateforme";

+ 70 - 69
plugin/buycourses/lang/spanish.php

@@ -3,83 +3,84 @@ $strings['plugin_title'] = "Venta de cursos";
 $strings['plugin_comment'] = "Vender cursos a través de PayPal directamente desde su portal Chamilo. Plugin en versión Beta, a usar con mucha precaución. La asociación Chamilo y los desarrolladores involucrados no pueden ser considerados responsables de cualquier inconveniente que se presente.";
 $strings['show_main_menu_tab'] = "Mostrar pestaña en el menu principal";
 $strings['show_main_menu_tab_help'] = "En caso de no querer mostrar la pestaña, puede agregar el siguiente enlace a su portal Chamilo: %s";
-$strings['Visible'] = "Mostrar en el listado";
-$strings['Options'] = "Opciones";
-$strings['Price'] = "Precio";
-$strings['SyncCourseDatabase'] = "Sincronizar cursos de la base de datos";
-$strings['Private'] = "Privado - acceso autorizado s&oacute;lo para los miembros del curso";
-$strings['CourseVisibilityClosed'] = "Cerrado - no hay acceso a este curso";
-$strings['OpenToThePlatform'] = "Abierto - acceso autorizado s&oacute;lo para los usuarios registrados en la plataforma";
-$strings['OpenToTheWorld'] = "P&uacute;blico - acceso autorizado a cualquier persona";
-$strings['CourseVisibilityHidden'] = "Invisible - Totalmente invisible para todos los usuarios a parte de los administradores";
-$strings['Description'] = "Descripci&oacute;n";
-$strings['Buy'] = "Comprar";
-$strings['Mostrar_disponibles'] = "Mostrar cursos disponibles";
 $strings['include_sessions'] = "Incluir sesiones";
 $strings['paypal_enable'] = "Habilitar PayPal";
 $strings['transfer_enable'] = "Habilitar transferencia";
 $strings['unregistered_users_enable'] = "Permitir usuarios sin registro en la plataforma";
-$strings['Cancelacionpedido'] = "El pedido se ha cancelado.";
-$strings['AlreadyBuy'] = "Ya está matriculado en el curso";
-$strings['bc_subject'] = "Confirmación pedido de cursos";
-$strings['paypal'] = 'PayPal';
-$strings['confirmar_compra'] = 'Confirmar compra de curso';
-$strings['TheUserIsAlreadyRegistered'] = 'El usuario ya está registrado';
-$strings['ProblemToSaveTheCurrencyType'] = 'Problema al guardar el tipo de moneda';
-$strings['ProblemToSaveThePaypalParameters'] = 'Problema para guardar los parametros de Paypal';
-$strings['ProblemToInsertANewAccount'] = 'Problemas para insertar una nueva cuenta';
-$strings['ProblemToDeleteTheAccount'] = 'Problema para eliminar la cuenta';
-$strings['ProblemToSaveTheMessage'] = 'Problema para guardar el mensaje';
-$strings['ProblemToSubscribeTheUser'] = 'Problema para suscribir el usuario';
-$strings['TheSubscriptionAndActivationWereDoneSuccessfully'] = 'La suscripción y la activación se realizaron con éxito.';
-$strings['TheUserIsAlreadyRegisteredInTheCourse'] = 'El usuario ya está registrado en el curso.';
-$strings['CourseListOnSale'] = 'Lista de cursos a la venta';
-$strings['BuySessions'] = "Comprar sesiones";
-$strings['BuyCourses'] = 'Comprar cursos';
-$strings['ConfigurationOfCoursesAndPrices'] = 'Configuración de cursos y precios';
-$strings['ConfigurationOfPayments'] = 'Configuración de pagos';
-$strings['OrdersPendingOfPayment'] = 'Pedidos pendientes de pago';
-$strings['AvailableCoursesConfiguration'] = 'Configuración de cursos disponibles';
-$strings['PaymentsConfiguration'] = 'Configuración de Pagos';
-$strings['bc_message'] = "Estimado {{name}}. <br />En cuanto recibamos confirmaci&oacute;n de pago procederemos a dar de alta su usuario en el curso <strong>{{curso}}</strong>.<br><br><strong>No olvide indicar en el concepto de la transferencia el n&uacute;mero de referencia del pedido: <div style='display:inline;text-align:center; font-weight:bold; font-size:20px; color:#333'>{{reference}}</div></strong>";
-$strings['Categories'] = "Categorias";
-$strings['BankTransfer'] = 'Transferencia Bancaria';
-$strings['EnrollToCourseXSuccessful'] = "Su inscripción en el curso %s se ha completado.";
+
+$strings['BankTransfer'] = "Transferencia Bancaria";
+$strings['SaleStatusPending'] = "Venta pendiente";
+$strings['SaleStatusCanceled'] = "Venta cancelada";
+$strings['SaleStatusCompleted'] = "Venta completada";
+$strings['CourseListOnSale'] = "Lista de cursos a la venta";
+$strings['AvailableCourses'] = "Cursos disponibles";
+$strings['Price'] = "Precio";
 $strings['SearchFilter'] = "Filtro de búsqueda";
 $strings['MinimumPrice'] = "Precio mínimo";
 $strings['MaximumPrice'] = "Precio máximo";
-$strings['AvailableCourses'] = "Cursos disponibles";
-$strings['PaymentConfiguration'] = "Configuración de Pagos";
+$strings['AvailableCoursesConfiguration'] = "Configuración de cursos disponibles";
+$strings['PaymentsConfiguration'] = "Configuración de Pagos";
+$strings['TheUserIsAlreadyRegisteredInTheCourse'] = "Usted ya está registrado en el curso.";
+$strings['SeeDescription'] = "Ver descripción";
+$strings['Buy'] = "Comprar";
 $strings['WaitingToReceiveThePayment'] = "Se encuentra a la espera de recibir el pago";
-$strings['CurrencyType'] = "Tipo de moneda";
-$strings['SelectACurrency'] = "Seleccione una moneda";
-$strings['Sandbox'] = "Entorno de Pruebas";
+$strings['TheUserIsAlreadyRegisteredInTheSession'] = "Usted ya está registrado en la sesión";
+$strings['ItemNotSaved'] = "Elemento no guardado";
+$strings['TitlePlugin'] = "Todo lo que necesita para enseñar y vender cursos en línea";
+$strings['PluginPresentation'] = "El Plugin BuyCourses le da los recursos para vender sus cursos o sus sesiones ya creados y enseñar en línea, todo en unos simples pasos y configuraciones. ¿Qué espera? Empiece a vender cursos a través de Chamilo ahora!";
+$strings['Instructions'] = "Instrucciones de uso";
+$strings['InstructionsStepOne'] = "Crea un curso o una sesión de formación en la plataforma.";
+$strings['InstructionsStepTwo'] = "En la sección <strong>configuración de pagos</strong>, configure el tipo de moneda con el que venderá sus cursos o sesiones.";
+$strings['InstructionsStepThree'] = "Configure los cursos a vender en la sección <strong>Configuración de cursos y precios</strong>";
+$strings['BuyCourses'] = "Comprar cursos";
+$strings['ConfigurationOfCoursesAndPrices'] = "Configuración de cursos y precios";
+$strings['SalesReport'] = "Reporte de ventas";
+$strings['UserInformation'] = "Ficha del comprador";
+$strings['PaymentMethods'] = "Métodos de pago";
+$strings['ConfirmOrder'] = "Confirmar Orden";
+$strings['PurchaseData'] = "Datos de la compra";
+$strings['bc_subject'] = "Confirmación pedido de cursos";
+$strings['PurchaseStatusX'] = "Estado de la compra: %s";
+$strings['PendingReasonByTransfer'] = "<b>Pendiente</b>. Esperando la confirmación de la transferencia";
+$strings['CancelOrder'] = "Cancelar Orden";
+$strings['BankAccountInformation'] = "Información de la Cuenta Bancaria";
 $strings['BankAccount'] = "Cuenta Bancaria";
-$strings['SubscribeUser'] = "Suscribir Usuario";
-$strings['DeleteTheOrder'] = "Eliminar el Pedido";
-$strings['ReferenceOrder'] = 'Referencia del pedido';
-$strings['UserInformation'] = 'Ficha del comprador';
-$strings['OnceItIsConfirmed,YouWillReceiveAnEmailWithTheBankInformationAndAnOrderReference'] = "Una vez confirmado, recibira un e-mail con los datos bancarios y una referencia del pedido.";
-$strings['BankAccountInformation'] = 'Información de la Cuenta Bancaria';
-$strings['ConfirmOrder'] = 'Confirmar Orden';
-$strings['PaymentMethods'] = 'Métodos de pago';
-$strings['CancelOrder'] = 'Cancelar Orden';
+$strings['OnceItIsConfirmedYouWillReceiveAnEmailWithTheBankInformationAndAnOrderReference'] = "Una vez confirmado, recibira un e-mail con los datos bancarios y una referencia del pedido.";
+$strings['SubscriptionToCourseXSuccessful'] = "Tu subscripción a \"%s\" se realizó correctamente.";
+$strings['OrderCanceled'] = "Pedido cancelado";
+$strings['OrderStatus'] = "Estado del pedido";
+$strings['SearchByStatus'] = "Buscar por estado";
+$strings['OrderReference'] = "Referencia del pedido";
+$strings['OrderDate'] = "Fecha del pedido";
+$strings['ProductType'] = "Tipo de producto";
+$strings['SubscribeUser'] = "Inscribir usuario";
+$strings['DeleteOrder'] = "Eliminar pedido";
 $strings['ErrorContactPlatformAdmin'] = "Se ha producido un error desconocido. Por favor, póngase en contacto con el administrador de la plataforma.";
-$strings['PayPalConfig'] = "Configuraci&oacute;n PayPal:";
-$strings['TransfersConfig'] = "Configuraci&oacute;n de transferencias:";
+$strings['PendingReasonByAddress'] = "<b>Pendiente</b>. No has ingresado una dirección de correo confirmada.";
+$strings['PendingReasonByAuthorization'] = "<b>Pendiente</b>. No hemos recibido los fondos.";
+$strings['PendingReasonByEcheck'] = "<b>Pendiente</b>. El pago fue hecho a través de un eCheck que aún no está declarado";
+$strings['PendingReasonByIntl'] = "<b>Pendiente</b>. No tenemos un mecanismo de retiro de fondos.";
+$strings['PendingReasonByMulticurrency'] = "<b>Pending</b>. No podemos realizar el cambio de moneda.";
+$strings['PendingReasonByOrder'] = "<b>Pendiente</b>. Pedido realizado. No hemos recibido los fondos.";
+$strings['PendingReasonByPaymentReview'] = "<b>Pendiente</b>. El pago está siendo revisado por PayPal por riesgo.";
+$strings['PendingReasonByRegulatoryReview'] = "<b>Pendiente</b>. El pago está siendo revisado por cumplimiento con regulaciones gubernamentales.";
+$strings['PendingReasonByUnilateral'] = "<b>Pendiente</b>. La dirección de correo electrónico aún no está registrada o confirmada.";
+$strings['PendingReasonByUpgrade'] = "<b>Pendiente</b>. El pago fue realizado a través de una tarjeta de crédito.";
+$strings['PendingReasonByVerify'] = "<b>Pendiente</b>. Lo sentimos. Todavía no estamos verificados en PayPal.";
+$strings['PendingReasonByOther'] = "<b>Pendiente</b>. Por favor contacta al administrador de la plataforma.";
 $strings['PayPalPaymentOKPleaseConfirm'] = "PayPal nos indicó que todo estaba listo para ejecutar el pago. Por seguridad, le pedimos confirme una última vez su pedido dando clic en el botón de confirmación a bajo. Una vez le haya dado clic, será registrado al curso y el monto correspondiente será retirado de su cuenta PayPal. Siempre puede acceder a sus cursos a partir de la pestaña 'Mis cursos'. Gracias por su compra!";
-$strings['EnrollToSessionXSuccessful'] = "Su inscripción en la sesión %s se ha completado.";
-$strings['TheUserIsAlreadyRegisteredInTheSession'] = 'El usuario ya está registrado en la sesión.';
-$strings['Instructions'] = 'Instrucciones de uso';
-$strings['InstructionsStepOne'] = 'Crea un curso o una sesión de formación en la plataforma.';
-$strings['InstructionsStepTwo'] = 'En la sección <strong>configuración de pagos</strong>, configure el tipo de moneda con el que venderá sus cursos o sesiones.';
-$strings['InstructionsStepThree'] = 'Configure los cursos a vender en la sección <strong>Configuración de cursos y precios</strong>';
-$strings['PluginPresentation'] = 'El Plugin BuyCourses le da los recursos para vender sus cursos o sus sesiones ya creados y enseñar en línea, todo en unos simples pasos y configuraciones. ¿Qué espera? Empiece a vender cursos a través de Chamilo ahora!';
-$strings['TitlePlugin'] = 'Todo lo que necesita para enseñar y vender cursos en línea';
-$strings['PluginInstruction'] = 'Puede activar o desactivar la opción de pagos vía PayPal o configuración de transferencias bancarias, en la sección del configuración del plugin.';
-$strings['ClickHere'] = 'Clic Aquí';
-$strings['InfoCurrency'] = 'Permite configurar el tipo de moneda (de pago) para sus cursos.';
-$strings['InfoApiCredentials'] = 'Para generar tu credenciales API para integrar su cuenta PayPal con Chamilo LMS, deberá seguir los siguientes pasos';
-$strings['InfoApiStepOne'] = 'Ir a la opción de <strong>Perfil de PayPal</strong>, luego en <strong>Mis herramientas de venta</strong>';
-$strings['InfoApiStepTwo'] = 'En el apartado <strong>Acceso API</strong>, dar clic en la opción <strong>Actualizar</strong>';
-$strings['InfoApiStepThree'] = 'En la opción 2, de Configuración de credenciales y permisos de API, dar clic en <strong>Ver firma de API</strong>. Copiar los datos de las credenciales en el formulario de configuración de este plugin';
+$strings['Sandbox'] = "Entorno de Pruebas";
+$strings['PayPalConfig'] = "Configuración PayPal:";
+$strings['TransfersConfig'] = "Configuraci&oacute;n de transferencias:";
+$strings['PluginInstruction'] = "Puede activar o desactivar la opción de pagos vía PayPal o configuración de transferencias bancarias, en la sección del configuración del plugin.";
+$strings['ClickHere'] = "<i>Clic aquí</i> para más detalles";
+$strings['CurrencyType'] = "Tipo de moneda";
+$strings['InfoCurrency'] = "Permite configurar el tipo de moneda (de pago) para sus cursos.";
+$strings['ApiUsername'] = "Nombre de usuario de API";
+$strings['ApiPassword'] = "Contraseña de API";
+$strings['ApiSignature'] = "Firma";
+$strings['InfoApiCredentials'] = "Para generar tu credenciales API para integrar su cuenta PayPal con Chamilo LMS, deberá seguir los siguientes pasos";
+$strings['InfoApiStepOne'] = "Ir a la opción de <strong>Perfil de PayPal</strong>, luego en <strong>Mis herramientas de venta</strong>";
+$strings['InfoApiStepTwo'] = "En el apartado <strong>Acceso API</strong>, dar clic en la opción <strong>Actualizar</strong>";
+$strings['InfoApiStepThree'] = "En la opción 2, de Configuración de credenciales y permisos de API, dar clic en <strong>Ver firma de API</strong>. Copiar los datos de las credenciales en el formulario de configuración de este plugin";
+$strings['ErrorOccurred'] = "<strong>Ocurrio un error</strong>. Codigo: %s. Mensaje: %s. Por favor, contacta al administrador de la plataforma.";

+ 11 - 5
plugin/buycourses/readme.txt

@@ -1,5 +1,11 @@
-Courses purchase plugin<br/><br/>
-Users can access the courses purchase catalog to buy available courses.<br/>
-If the user is unregistered he/she will be requested to register.<br/>
-Once the course is chosen, Chamilo shows the different payment types available (currently only PayPal works). <br/>
-Finally, the user receives user and password by e-mail, to access the chosen course. <br/>
+<p>Users can access the purchases catalog to buy courses or sessions (since v2 of this plugin)
+enabled for sale.</p>
+
+<p>If the user is not registered or logged in, he/she will be requested to register/login
+before he/she can resume buying items.</p>
+
+<p>Once the course or session is chosen, shows available payment types (currently only PayPal works)
+and lets the user proceed with the purchase.</p>
+
+<p>Finally, the user receives an e-mail confirming the purchase and him/her is can access to the
+course/session.</p>

BIN
plugin/buycourses/resources/acces_tool.gif


+ 0 - 105
plugin/buycourses/resources/content.css

@@ -1,105 +0,0 @@
-body {
-    background-color: #FFFFFF;
-    font-family: Verdana, Arial, Helvetica, sans-serif;
-    font-size: 10px;
-    scrollbar-3dlight-color: #F0F0EE;
-    scrollbar-arrow-color: #676662;
-    scrollbar-base-color: #F0F0EE;
-    scrollbar-darkshadow-color: #DDDDDD;
-    scrollbar-face-color: #E0E0DD;
-    scrollbar-highlight-color: #F0F0EE;
-    scrollbar-shadow-color: #F0F0EE;
-    scrollbar-track-color: #F5F5F5;
-}
-
-td {
-    font-family: Verdana, Arial, Helvetica, sans-serif;
-    font-size: 10px;
-}
-
-pre {
-    font-family: Verdana, Arial, Helvetica, sans-serif;
-    font-size: 10px;
-}
-
-.example1 {
-    font-weight: bold;
-    font-size: 14px
-}
-
-.example2 {
-    font-weight: bold;
-    font-size: 12px;
-    color: #FF0000
-}
-
-.tablerow1 {
-    background-color: #BBBBBB;
-}
-
-thead {
-    background-color: #FFBBBB;
-}
-
-tfoot {
-    background-color: #BBBBFF;
-}
-
-th {
-    font-family: Verdana, Arial, Helvetica, sans-serif;
-    font-size: 13px;
-}
-
-/* Basic formats */
-
-.bold {
-    font-weight: bold;
-}
-
-.italic {
-    font-style: italic;
-}
-
-.underline {
-    text-decoration: underline;
-}
-
-/* Global align classes */
-
-.left {
-    text-align: inherit;
-}
-
-.center {
-    text-align: center;
-}
-
-.right {
-    text-align: right;
-}
-
-.full {
-    text-align: justify
-}
-
-/* Image and table specific aligns */
-
-img.left, table.left {
-    float: left;
-    text-align: inherit;
-}
-
-img.center, table.center {
-    margin-left: auto;
-    margin-right: auto;
-    text-align: inherit;
-}
-
-img.center {
-    display: block;
-}
-
-img.right, table.right {
-    float: right;
-    text-align: inherit;
-}

+ 2 - 116
plugin/buycourses/resources/css/style.css

@@ -1,117 +1,3 @@
-.thumbnail .caption{
-	text-align: center;
+.buy-courses-tabs {
+    margin-bottom: 15px;
 }
-.cleared {
-    content: ".";
-    display: block;
-    height: 0;
-    clear: both;
-    visibility: hidden;
-    line-height: 0;
-}
-table .bg-color{
-	background-color: #E5EDF9;
-	color: #333;
-}
-table td.ta-center, table th.ta-center {
-    text-align: center;
-}
-
-#courses_table td, #transfer_table td, #order_table td {
-    vertical-align: middle;
-}
-
-#courses_table td input.price, #transfer_table td input, #currency_type {
-    margin: 0;
-}
-
-#courses_table td.btop {
-    border-top: 1px solid #C5DEEB;
-    border-bottom: 1px solid #C5DEEB;
-}
-
-#courses_table tr.fmod {
-    border: 1px solid #C5DEEB;
-    background: #C5DEEB;
-}
-
-.sprice {
-    color: #4D984E;
-    font-size: 18px;
-    font-weight: bold;
-    margin: 15px 0;
-}
-
-.dinline {
-    display: inline;
-}
-
-.fright {
-    float: right;
-}
-
-.cursor {
-    cursor: pointer;
-}
-
-.ta-center {
-    text-align: center;
-}
-
-textarea#message {
-    width: 50%;
-}
-
-.send_result {
-    font-weight: bold;
-}
-
-select#lsessions, select#lcourses, select#lexercises, select#status {
-    margin-bottom: 0px;
-}
-
-.column_field_filter {
-    padding: 6px 10px 1px 1px;
-    text-align: right;
-}
-
-.height5 {
-    height: 5px;
-}
-
-.margin-left-fifty{
-    margin-left: 50px !important;
-}
-.category_well h4{
-	padding-left: 0;
-}
-.category_well .form-content{
-	padding-left: 1em;
-	padding-right: 1em;
-}
-.category_well .btn{
-	width: 100%;
-	line-height: 30px;
-	font-size: 16px;
-}
-.icon-course .thumbnail{
-	border: none;
-	box-shadow: none;
-}
-.well-course{
-	padding-top: 1em;
-	padding-bottom: 1em;
-	border-bottom: 1px solid #D3E6F0;
-}
-.ui-widget-content .well-course a, .ui-widget-content .well-course a:hover{
-	color: #fff;
-}
-.label-info, .badge-info {
-  background-color: #53a0c6;
-  font-weight: normal;
-}
-.categories-course-description h3 {
-  color: #666;
-  font-weight: bold;
-  font-family: Arial;
-}

BIN
plugin/buycourses/resources/delete.png


BIN
plugin/buycourses/resources/edit_message.gif


BIN
plugin/buycourses/resources/img/128/accept.png


BIN
plugin/buycourses/resources/img/32/accept.png


BIN
plugin/buycourses/resources/img/32/delete.png


BIN
plugin/buycourses/resources/img/32/new.png


BIN
plugin/buycourses/resources/img/32/save.png


BIN
plugin/buycourses/resources/message_confirmation.png


BIN
plugin/buycourses/resources/message_warning.png


BIN
plugin/buycourses/resources/more.png


BIN
plugin/buycourses/resources/new_message.gif


+ 0 - 79
plugin/buycourses/resources/plugin.css

@@ -1,79 +0,0 @@
-.cleared {
-    content: ".";
-    display: block;
-    height: 0;
-    clear: both;
-    visibility: hidden;
-    line-height: 0;
-}
-
-table td.ta-center, table th.ta-center {
-    text-align: center;
-}
-
-#courses_table td, #transfer_table td, #order_table td {
-    vertical-align: middle;
-}
-
-#courses_table td input.price, #transfer_table td input, #currency_type {
-    margin: 0;
-}
-
-#courses_table td.btop {
-    border-top: 1px solid red;
-    border-bottom: 1px solid red;
-}
-
-#courses_table tr.fmod {
-    border: 1px solid red;
-    background: #FFE0E0;
-}
-
-.sprice {
-    color: #FF5555;
-    font-size: 26px;
-    font-weight: 500;
-    margin: 15px 0;
-    text-shadow: 2px 1px 0 #222222;
-}
-
-.dinline {
-    display: inline;
-}
-
-.fright {
-    float: right;
-}
-
-.cursor {
-    cursor: pointer;
-}
-
-.ta-center {
-    text-align: center;
-}
-
-textarea#message {
-    width: 50%;
-}
-
-.send_result {
-    font-weight: bold;
-}
-
-select#lsessions, select#lcourses, select#lexercises, select#status {
-    margin-bottom: 0px;
-}
-
-.column_field_filter {
-    padding: 6px 10px 1px 1px;
-    text-align: right;
-}
-
-.height5 {
-    height: 5px;
-}
-
-.margin-left-fifty{
-    margin-left: 50px !important;
-}

BIN
plugin/buycourses/resources/save.png


BIN
plugin/buycourses/resources/save2.png


BIN
plugin/buycourses/resources/toggle.png


+ 0 - 31
plugin/buycourses/src/ajax.php

@@ -1,31 +0,0 @@
-<?php
-/* For license terms, see /license.txt */
-/**
- * AJAX script to get courses descriptions
- * @package chamilo.plugin.buycourses
- */
-
-require_once '../config.php';
-
-// Get the name of the database course.
-$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
-
-$code = Database::escape_string($_GET['code']);
-$course_info = api_get_course_info($code);
-echo Display::tag('h2', $course_info['name']);
-echo '<br />';
-
-$sql = "SELECT * FROM $tbl_course_description
-    WHERE c_id = " . intval($course_info['real_id']) . "
-    AND session_id = 0 ORDER BY id";
-
-$result = Database::query($sql);
-if (Database::num_rows($result) > 0) {
-    while ($description = Database::fetch_object($result)) {
-        $descriptions[$description->id] = $description;
-    }
-    // Function that displays the details of the course description in html.
-    echo CourseManager::get_details_course_description_html($descriptions, api_get_system_encoding(), false);
-} else {
-    echo get_lang('NoDescription');
-}

+ 0 - 676
plugin/buycourses/src/buy_course.lib.php

@@ -1,676 +0,0 @@
-<?php
-/* For license terms, see /license.txt */
-/**
- * Functions
- * @package chamilo.plugin.buycourses
- */
-/**
- * Init
- */
-require_once '../../../main/inc/global.inc.php';
-require_once '../config.php';
-require_once api_get_path(LIBRARY_PATH) . 'plugin.class.php';
-
-/**
- *
- */
-function sync()
-{
-    $tableBuySessionRelCourse = Database::get_main_table(TABLE_BUY_SESSION_COURSE);
-    $tableSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-
-    $sql = "UPDATE $tableBuySessionRelCourse SET sync = 0";
-    Database::query($sql);
-
-    $sql = "SELECT session_id, c_id, nbr_users FROM $tableSessionRelCourse";
-    $res = Database::query($sql);
-    while ($row = Database::fetch_assoc($res)) {
-        $sql = "SELECT 1 FROM $tableBuySessionRelCourse WHERE session_id=" . $row['session_id'];
-        $result = Database::query($sql);
-        if (Database::affected_rows($result) > 0) {
-            $sql = "UPDATE $tableBuySessionRelCourse SET sync = 1 WHERE session_id=" . $row['session_id'];
-            Database::query($sql);
-        } else {
-            $courseCode = api_get_course_info_by_id($row['c_id'])['code'];
-            $sql = "INSERT INTO $tableBuySessionRelCourse (session_id, course_code, nbr_users, sync)
-            VALUES (" . $row['session_id'] . ", '" . $courseCode . "', " . $row['nbr_users'] . ", 1);";
-            Database::query($sql);
-        }
-    }
-    $sql = "DELETE FROM $tableBuySessionRelCourse WHERE sync = 0;";
-    Database::query($sql);
-
-    $tableBuyCourse = Database::get_main_table(TABLE_BUY_COURSE);
-    $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
-
-    $sql = "UPDATE $tableBuyCourse SET sync = 0";
-    Database::query($sql);
-
-    $sql = "SELECT id, code, title FROM $tableCourse";
-    $res = Database::query($sql);
-    while ($row = Database::fetch_assoc($res)) {
-        $sql = "SELECT session_id FROM $tableBuySessionRelCourse
-        WHERE course_code = '" . $row['code'] . "' LIMIT 1";
-        $courseIdSession = Database::fetch_assoc(Database::query($sql))['session_id'];
-        if (!is_numeric($courseIdSession)) {
-            $courseIdSession = 0;
-        }
-
-        $sql = "SELECT 1 FROM $tableBuyCourse WHERE course_id='" . $row['id'] . "';";
-        $result = Database::query($sql);
-        if (Database::affected_rows($result) > 0) {
-            $sql = "UPDATE $tableBuyCourse SET sync = 1, session_id = $courseIdSession WHERE course_id='" . $row['id'] . "';";
-            Database::query($sql);
-        } else {
-            $sql = "INSERT INTO $tableBuyCourse (session_id, course_id, code, title, visible, sync)
-            VALUES ('" . $courseIdSession . "', '" . $row['id'] . "', '" .
-            $row['code'] . "', '" . $row['title'] . "', 0, 1);";
-            Database::query($sql);
-        }
-    }
-    $sql = "DELETE FROM $tableBuyCourse WHERE sync = 0;";
-    Database::query($sql);
-
-    $tableBuySession = Database::get_main_table(TABLE_BUY_SESSION);
-    $tableSession = Database::get_main_table(TABLE_MAIN_SESSION);
-
-    $sql = "UPDATE $tableBuySession SET sync = 0";
-    Database::query($sql);
-
-    $sql = "SELECT id, name, access_start_date, access_end_date FROM $tableSession";
-    $res = Database::query($sql);
-    while ($row = Database::fetch_assoc($res)) {
-        $sql = "SELECT 1 FROM $tableBuySession WHERE session_id='" . $row['id'] . "';";
-        $result = Database::query($sql);
-        if (Database::affected_rows($result) > 0) {
-            $sql = "UPDATE $tableBuySession SET sync = 1 WHERE session_id='" . $row['id'] . "';";
-            Database::query($sql);
-        } else {
-            $sql = "INSERT INTO $tableBuySession (session_id, name, date_start, date_end, visible, sync)
-            VALUES ('" . $row['id'] . "', '" . $row['name'] . "', '" .
-                $row['access_start_date'] .  "', '" . $row['access_end_date'] . "', 0, 1);";
-            Database::query($sql);
-        }
-    }
-    $sql = "DELETE FROM $tableBuySession WHERE sync = 0;";
-    Database::query($sql);
-}
-
-/**
- * List sessions details from the buy-session table and the session table
- * @return array Results (list of session details)
- */
-function listSessions()
-{
-    $tableBuySession = Database::get_main_table(TABLE_BUY_SESSION);
-    $tableSession = Database::get_main_table(TABLE_MAIN_SESSION);
-    $sql = "SELECT a.session_id, a.visible, a.price, b.*
-        FROM $tableBuySession a, $tableSession b
-        WHERE a.session_id = b.id;";
-
-    $res = Database::query($sql);
-    $aux = array();
-    while ($row = Database::fetch_assoc($res)) {
-        $aux[] = $row;
-    }
-
-    return $aux;
-}
-
-/**
- * List courses details from the buy-course table and the course table
- * @return array Results (list of courses details)
- */
-function listCourses()
-{
-    $tableBuyCourse = Database::get_main_table(TABLE_BUY_COURSE);
-    $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
-    $sql = "SELECT a.course_id, a.visible, a.price, b.*
-        FROM $tableBuyCourse a, $tableCourse b
-        WHERE a.course_id = b.id AND a.session_id = 0;";
-    $res = Database::query($sql);
-    $aux = array();
-    while ($row = Database::fetch_assoc($res)) {
-        $aux[] = $row;
-    }
-    return $aux;
-}
-
-/**
- * Lists current user session details, including each session course details
- * @return array Sessions details list
- */
-function userSessionList()
-{
-    $tableBuySession = Database::get_main_table(TABLE_BUY_SESSION);
-    $tableSession = Database::get_main_table(TABLE_MAIN_SESSION);
-    $tableBuySessionRelCourse = Database::get_main_table(TABLE_BUY_SESSION_COURSE);
-    $tableSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-    $tableBuyCourse = Database::get_main_table(TABLE_BUY_COURSE);
-    $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
-    $tableSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
-    $tableBuySessionTemporal = Database::get_main_table(TABLE_BUY_SESSION_TEMPORARY);
-    $currentUserId = api_get_user_id();
-
-    // get existing sessions
-    $sql = "SELECT a.session_id, a.visible, a.price, b.*
-        FROM $tableBuySession a, $tableSession b
-        WHERE a.session_id = b.id AND a.visible = 1;";
-    $resSessions = Database::query($sql);
-    $auxSessions = array();
-    // loop through all sessions
-    while ($rowSession = Database::fetch_assoc($resSessions)) {
-        // get courses of current session
-        $sqlSessionCourse = "SELECT DISTINCT a.session_id, a.course_code, a.nbr_users
-        FROM $tableBuySessionRelCourse a, $tableSessionRelCourse b
-        WHERE a.session_id = b.session_id AND a.session_id = " . $rowSession['session_id'] . ";";
-        $resSessionCourse = Database::query($sqlSessionCourse);
-        $aux = array();
-        // loop through courses of current session
-        while ($rowSessionCourse = Database::fetch_assoc($resSessionCourse)) {
-            // get course of current session
-            $sql = "SELECT a.course_id, a.session_id, a.visible, a.price, b.*
-            FROM $tableBuyCourse a, $tableCourse b
-            WHERE a.code = b.code AND a.code = '" . $rowSessionCourse['course_code'] . "';";
-            $res = Database::query($sql);
-            // loop inside a course of current session
-            while ($row = Database::fetch_assoc($res)) {
-                //check teacher
-                $sql = "SELECT lastname, firstname
-                FROM course_rel_user a, user b
-                WHERE a.c_id='" . $row['id'] . "'
-                AND a.status <> 6
-                AND a.user_id=b.id;";
-                $tmp = Database::query($sql);
-                $rowTmp = Database::fetch_assoc($tmp);
-                $row['teacher'] = $rowTmp['firstname'] . ' ' . $rowTmp['lastname'];
-                //check images
-                if (file_exists(api_get_path(SYS_COURSE_PATH) . $row['directory'] . "/course-pic85x85.png")) {
-                    $row['course_img'] = "courses/" . $row['directory'] . "/course-pic85x85.png";
-                } else {
-                    $row['course_img'] = "main/img/without_picture.png";
-                }
-                $row['price'] = number_format($row['price'], 2, '.', ' ');
-                $aux[] = $row;
-            }
-        }
-        //check if the user is enrolled in the current session
-        if ($currentUserId > 0) {
-            $sql = "SELECT 1 FROM $tableSessionRelUser
-                WHERE session_id ='".$rowSession['session_id']."' AND
-                user_id = $currentUserId";
-            $result = Database::query($sql);
-            if (Database::affected_rows($result) > 0) {
-                $rowSession['enrolled'] = "YES";
-            } else {
-                $sql = "SELECT 1 FROM $tableBuySessionTemporal
-                    WHERE session_id ='".$rowSession['session_id']."' AND
-                    user_id='" . $currentUserId . "';";
-                $result = Database::query($sql);
-                if (Database::affected_rows($result) > 0) {
-                    $rowSession['enrolled'] = "TMP";
-                } else {
-                    $rowSession['enrolled'] = "NO";
-                }
-            }
-        } else {
-            $sql = "SELECT 1 FROM $tableBuySessionTemporal
-                WHERE session_id ='".$rowSession['session_id']."' AND
-                user_id='" . $currentUserId . "';";
-            $result = Database::query($sql);
-            if (Database::affected_rows($result) > 0) {
-                $rowSession['enrolled'] = "TMP";
-            } else {
-                $rowSession['enrolled'] = "NO";
-            }
-        }
-        // add courses to current session
-        $rowSession['courses'] = $aux;
-        // add the current whole session
-        $auxSessions[] = $rowSession;
-    }
-    return $auxSessions;
-}
-
-/**
- * Lists current user course details
- * @return array Course details list
- */
-function userCourseList()
-{
-    $tableBuyCourse = Database::get_main_table(TABLE_BUY_COURSE);
-    $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
-    $tableCourseRelUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
-    $tableBuyCourseTemporal = Database::get_main_table(TABLE_BUY_COURSE_TEMPORAL);
-    $currentUserId = api_get_user_id();
-
-    $sql = "SELECT a.course_id, a.visible, a.price, b.*
-            FROM $tableBuyCourse a, $tableCourse b
-            WHERE a.course_id = b.id AND a.session_id = 0 AND a.visible = 1;";
-    $res = Database::query($sql);
-    $aux = array();
-    while ($row = Database::fetch_assoc($res)) {
-        //check teacher
-        $sql = "SELECT lastname, firstname
-            FROM $tableCourseRelUser a, user b
-            WHERE
-                a.c_id='" . $row['id'] . "' AND
-                a.status <> 6 AND
-                a.user_id=b.user_id;";
-        $tmp = Database::query($sql);
-        $rowTmp = Database::fetch_assoc($tmp);
-        $row['teacher'] = $rowTmp['firstname'] . ' ' . $rowTmp['lastname'];
-        //check if the user is enrolled
-        if ($currentUserId > 0) {
-            $sql = "SELECT 1 FROM $tableCourseRelUser
-                WHERE c_id='" . $row['id'] . "'
-                AND user_id='" . $currentUserId . "';";
-            $result = Database::query($sql);
-            if (Database::affected_rows($result) > 0) {
-                $row['enrolled'] = "YES";
-            } else {
-                $sql = "SELECT 1 FROM $tableBuyCourseTemporal
-                    WHERE course_code='" . $row['code'] . "'
-                    AND user_id='" . $currentUserId . "';";
-                $result = Database::query($sql);
-                if (Database::affected_rows($result) > 0) {
-                    $row['enrolled'] = "TMP";
-                } else {
-                    $row['enrolled'] = "NO";
-                }
-            }
-        } else {
-            $sql = "SELECT 1 FROM $tableBuyCourseTemporal
-                WHERE course_code='" . $row['code'] . "'
-                AND user_id='" . $currentUserId . "';";
-            $result = Database::query($sql);
-            if (Database::affected_rows($result) > 0) {
-                $row['enrolled'] = "TMP";
-            } else {
-                $row['enrolled'] = "NO";
-            }
-        }
-        //check images
-        if (file_exists("../../courses/" . $row['code'] . "/course-pic85x85.png")) {
-            $row['course_img'] = "courses/" . $row['code'] . "/course-pic85x85.png";
-        } else {
-            $row['course_img'] = "main/img/without_picture.png";
-        }
-        $row['price'] = number_format($row['price'], 2, '.', ' ');
-        $aux[] = $row;
-    }
-    return $aux;
-}
-
-/**
- * Checks if a session or a course is already bought
- * @param string Session id or course code
- * @param int User id
- * @param string What has to be checked
- * @todo fix this function because TABLE_MAIN_COURSE_USER needs a c_id not a course_code
- * @return boolean True if it is already bought, and false otherwise
- */
-function checkUserBuy($parameter, $user, $type = 'COURSE')
-{
-    $sql = "SELECT 1 FROM %s WHERE %s ='" . Database::escape_string($parameter) . "' AND %s ='" . intval($user) . "';";
-    $sql = $type === 'SESSION' ?
-        sprintf($sql, Database::get_main_table(TABLE_MAIN_SESSION_USER), 'session_id', 'user_id') :
-        sprintf($sql, Database::get_main_table(TABLE_MAIN_COURSE_USER), 'c_id', 'user_id');
-    $result = Database::query($sql);
-    if (Database::affected_rows($result) > 0) {
-        return true;
-    } else {
-        return false;
-    }
-}
-
-/**
- * Checks if a session or a course has already a transfer
- * @param string Session id or course code
- * @param int User id
- * @param string What has to be checked
- * @return boolean True if it has already a transfer, and false otherwise
- */
-function checkUserBuyTransfer($parameter, $user, $type = 'COURSE')
-{
-    $sql = "SELECT 1 FROM %s WHERE %s ='" . Database::escape_string($parameter) . "' AND user_id ='" . intval($user) . "';";
-    $sql = $type === 'SESSION' ?
-        sprintf($sql, Database::get_main_table(TABLE_BUY_SESSION_TEMPORARY), 'session_id') :
-        sprintf($sql, Database::get_main_table(TABLE_BUY_COURSE_TEMPORAL), 'course_code');
-    $result = Database::query($sql);
-    if (Database::affected_rows($result) > 0) {
-        return true;
-    } else {
-        return false;
-    }
-}
-
-/**
- * Returns an array with all the categories
- * @return array All the categories
- */
-function buyCourseListCategories()
-{
-    $tblCourseCategory = Database::get_main_table(TABLE_MAIN_CATEGORY);
-    $sql = "SELECT code, name FROM $tblCourseCategory";
-    $res = Database::query($sql);
-    $aux = array();
-    while ($row = Database::fetch_assoc($res)) {
-        $aux[] = $row;
-    }
-
-    return $aux;
-}
-
-/**
- * Return an icon representing the visibility of the course
- * @param int $option The course visibility
- * @return string HTML string of the visibility icon
- */
-function getCourseVisibilityIcon($option)
-{
-    $style = 'margin-bottom:-5px;margin-right:5px;';
-    switch ($option) {
-        case 0:
-            return Display::return_icon('bullet_red.gif', get_plugin_lang('CourseVisibilityClosed', 'BuyCoursesPlugin'), array('style' => $style));
-            break;
-        case 1:
-            return Display::return_icon('bullet_orange.gif', get_plugin_lang('Private', 'BuyCoursesPlugin'), array('style' => $style));
-            break;
-        case 2:
-            return Display::return_icon('bullet_green.gif', get_plugin_lang('OpenToThePlatform', 'BuyCoursesPlugin'), array('style' => $style));
-            break;
-        case 3:
-            return Display::return_icon('bullet_blue.gif', get_plugin_lang('OpenToTheWorld', 'BuyCoursesPlugin'), array('style' => $style));
-            break;
-        default:
-            return Display::return_icon('bullet_grey.gif', get_plugin_lang('CourseVisibilityHidden', 'BuyCoursesPlugin'), array('style' => $style));
-    }
-}
-/**
- * List the available currencies
- * @result array The list of currencies
- */
-function listCurrency()
-{
-    $tableBuyCourseCountry = Database::get_main_table(TABLE_BUY_COURSE_COUNTRY);
-    $sql = "SELECT * FROM $tableBuyCourseCountry
-        ORDER BY country_name ASC";
-    $res = Database::query($sql);
-    $aux = array();
-    while ($row = Database::fetch_assoc($res)) {
-        $aux[] = $row;
-    }
-
-    return $aux;
-}
-/**
- * Gets the list of accounts from the buy_course_transfer table
- * @return array The list of accounts
- */
-function listAccounts()
-{
-    $tableBuyCourseTransfer = Database::get_main_table(TABLE_BUY_COURSE_TRANSFER);
-    $sql = "SELECT * FROM $tableBuyCourseTransfer";
-    $res = Database::query($sql);
-    $aux = array();
-    while ($row = Database::fetch_assoc($res)) {
-        $aux[] = $row;
-    }
-
-    return $aux;
-}
-/**
- * Gets the stored PayPal params
- * @return array The stored PayPal params
- */
-function paypalParameters()
-{
-    $tableBuyCoursePaypal = Database::get_main_table(TABLE_BUY_COURSE_PAYPAL);
-    $sql = "SELECT * FROM $tableBuyCoursePaypal";
-    $res = Database::query($sql);
-    $row = Database::fetch_assoc($res);
-
-    return $row;
-}
-/**
- * Gets the parameters for the bank transfers payment method
- * @result array Bank transfer payment parameters stored
- */
-function transferParameters()
-{
-    $tableBuyCourseTransfer = Database::get_main_table(TABLE_BUY_COURSE_TRANSFER);
-    $sql = "SELECT * FROM $tableBuyCourseTransfer";
-    $res = Database::query($sql);
-    $aux = array();
-    while ($row = Database::fetch_assoc($res)) {
-        $aux[] = $row;
-    }
-
-    return $aux;
-}
-/**
- * Find the first enabled currency (there should be only one)
- * @result string The code of the active currency
- */
-function findCurrency()
-{
-    $tableBuyCourseCountry = Database::get_main_table(TABLE_BUY_COURSE_COUNTRY);
-    $sql = "SELECT * FROM $tableBuyCourseCountry WHERE status='1';";
-    $res = Database::query($sql);
-    $row = Database::fetch_assoc($res);
-
-    return $row['currency_code'];
-}
-/**
- * Extended information about the session (from the session table as well as
- * the buy_session table)
- * @param string $code The session code
- * @return array Info about the session
- */
-function sessionInfo($code)
-{
-    $tableBuySession = Database::get_main_table(TABLE_BUY_SESSION);
-    $tableSession = Database::get_main_table(TABLE_MAIN_SESSION);
-    $tableBuySessionRelCourse = Database::get_main_table(TABLE_BUY_SESSION_COURSE);
-    $tableSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-    $tableBuyCourse = Database::get_main_table(TABLE_BUY_COURSE);
-    $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
-    $tableSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
-    $tableBuySessionTemporal = Database::get_main_table(TABLE_BUY_SESSION_TEMPORARY);
-    $currentUserId = api_get_user_id();
-
-    $code = Database::escape_string($code);
-    $sql = "SELECT a.session_id, a.visible, a.price, b.*
-        FROM $tableBuySession a, $tableSession b
-        WHERE a.session_id=b.id
-        AND a.visible = 1
-        AND b.id = '".$code."';";
-    $res = Database::query($sql);
-    $rowSession = Database::fetch_assoc($res);
-    $sqlSessionCourse = "SELECT DISTINCT a.session_id, a.course_code, a.nbr_users
-    FROM $tableBuySessionRelCourse a, $tableSessionRelCourse b
-    WHERE a.session_id = b.session_id AND a.session_id = " . $rowSession['session_id'] . ";";
-    $resSessionCourse = Database::query($sqlSessionCourse);
-    $aux = array();
-    // loop through courses of current session
-    while ($rowSessionCourse = Database::fetch_assoc($resSessionCourse)) {
-        // get course of current session
-        $sql = "SELECT a.course_id, a.session_id, a.visible, a.price, b.*
-        FROM $tableBuyCourse a, $tableCourse b
-        WHERE a.code = b.code AND a.code = '".$rowSessionCourse['course_code']."' AND a.visible = 1;";
-        $res = Database::query($sql);
-        // loop inside a course of current session
-        while ($row = Database::fetch_assoc($res)) {
-            //check teacher
-            $sql = "SELECT lastname, firstname
-            FROM course_rel_user a, user b
-            WHERE a.c_id='".$row['id']."'
-            AND a.status <> 6
-            AND a.user_id=b.id;";
-            $tmp = Database::query($sql);
-            $rowTmp = Database::fetch_assoc($tmp);
-            $row['teacher'] = $rowTmp['firstname'].' '.$rowTmp['lastname'];
-            //check images
-            if (file_exists(api_get_path(SYS_COURSE_PATH).$row['directory']."/course-pic85x85.png")) {
-                $row['course_img'] = "courses/".$row['directory']."/course-pic85x85.png";
-            } else {
-                $row['course_img'] = "main/img/without_picture.png";
-            }
-            $row['price'] = number_format($row['price'], 2, '.', ' ');
-            $aux[] = $row;
-        }
-    }
-    //check if the user is enrolled in the current session
-    if ($currentUserId > 0) {
-        $sql = "SELECT 1 FROM $tableSessionRelUser
-                WHERE user_id = $currentUserId";
-        $result = Database::query($sql);
-        if (Database::affected_rows($result) > 0) {
-            $rowSession['enrolled'] = "YES";
-        } else {
-            $sql = "SELECT 1 FROM $tableBuySessionTemporal
-                    WHERE user_id='".$currentUserId."';";
-            $result = Database::query($sql);
-            if (Database::affected_rows($result) > 0) {
-                $rowSession['enrolled'] = "TMP";
-            } else {
-                $rowSession['enrolled'] = "NO";
-            }
-        }
-    } else {
-        $sql = "SELECT 1 FROM $tableBuySessionTemporal
-            WHERE user_id='".$currentUserId."';";
-        $result = Database::query($sql);
-        if (Database::affected_rows($result) > 0) {
-            $rowSession['enrolled'] = "TMP";
-        } else {
-            $rowSession['enrolled'] = "NO";
-        }
-    }
-    // add courses to current session
-    $rowSession['courses'] = $aux;
-    return $rowSession;
-}
-/**
- * Extended information about the course (from the course table as well as
- * the buy_course table)
- * @param string $code The course code
- * @return array Info about the course
- */
-function courseInfo($code)
-{
-    $tableBuyCourse = Database::get_main_table(TABLE_BUY_COURSE);
-    $tableCourseRelUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
-    $tableUser = Database::get_main_table(TABLE_MAIN_USER);
-    $currentUserId = api_get_user_id();
-    $code = Database::escape_string($code);
-    $sql = "SELECT a.course_id, a.visible, a.price, b.*
-            FROM $tableBuyCourse a, course b
-            WHERE
-                a.course_id=b.id AND
-                a.visible = 1 AND
-                b.id = '" . $code . "'";
-    $res = Database::query($sql);
-    $row = Database::fetch_assoc($res);
-    // Check teacher
-    $sql = "SELECT lastname, firstname
-        FROM $tableCourseRelUser a, $tableUser b
-        WHERE
-            a.c_id = '" . $row['id'] . "' AND
-            a.status <> 6 AND
-            a.user_id = b.user_id;";
-    $tmp = Database::query($sql);
-    $rowTmp = Database::fetch_assoc($tmp);
-    $row['teacher'] = $rowTmp['firstname'] . ' ' . $rowTmp['lastname'];
-    //Check if student is enrolled
-    if ($currentUserId > 0) {
-        $sql = "SELECT 1 FROM $tableCourseRelUser
-                WHERE
-                    c_id ='" . $row['id'] . "' AND
-                    user_id='" . $currentUserId . "';";
-        $result = Database::query($sql);
-        if (Database::affected_rows($result) > 0) {
-            $row['enrolled'] = "YES";
-        } else {
-            $row['enrolled'] = "NO";
-        }
-    } else {
-        $row['enrolled'] = "NO";
-    }
-    //check img
-    if (file_exists("../../courses/" . $row['code'] . "/course-pic85x85.png")) {
-        $row['course_img'] = "courses/" . $row['code'] . "/course-pic85x85.png";
-    } else {
-        $row['course_img'] = "main/img/without_picture.png";
-    }
-    $row['price'] = number_format($row['price'], 2, '.', ' ');
-
-    return $row;
-}
-/**
- * Generates a random text (used for order references)
- * @param int $long
- * @param bool $minWords
- * @param bool $maxWords
- * @param bool $number
- * @return string A random text
- */
-function randomText($long = 6, $minWords = true, $maxWords = true, $number = true)
-{
-    $salt = $minWords ? 'abchefghknpqrstuvwxyz' : '';
-    $salt .= $maxWords ? 'ACDEFHKNPRSTUVWXYZ' : '';
-    $salt .= $number ? (strlen($salt) ? '2345679' : '0123456789') : '';
-
-    if (strlen($salt) == 0) {
-        return '';
-    }
-
-    $i = 0;
-    $str = '';
-
-    srand((double)microtime() * 1000000);
-
-    while ($i < $long) {
-        $number = rand(0, strlen($salt) - 1);
-        $str .= substr($salt, $number, 1);
-        $i++;
-    }
-
-    return $str;
-}
-/**
- * Generates an order reference
- * @result string A reference number
- */
-function calculateReference($bcCodetext)
-{
-    $tableBuyTemporal = $bcCodetext === 'THIS_IS_A_SESSION' ?
-        Database::get_main_table(TABLE_BUY_SESSION_TEMPORARY) :
-        Database::get_main_table(TABLE_BUY_COURSE_TEMPORAL);
-    $sql = "SELECT MAX(cod) as cod FROM $tableBuyTemporal";
-    $res = Database::query($sql);
-    $row = Database::fetch_assoc($res);
-    $reference = ($row['cod'] != '') ? $row['cod'] : '1';
-    $randomText = randomText();
-    $reference .= $randomText;
-    return $reference;
-}
-/**
- * Gets a list of pending orders
- * @result array List of orders
- * @todo Enable pagination
- */
-function pendingList($bcCodetext)
-{
-    $tableBuyTemporal = $bcCodetext === 'THIS_IS_A_SESSION' ?
-        Database::get_main_table(TABLE_BUY_SESSION_TEMPORARY) :
-        Database::get_main_table(TABLE_BUY_COURSE_TEMPORAL);
-    $sql = "SELECT * FROM $tableBuyTemporal;";
-    $res = Database::query($sql);
-    $aux = array();
-    while ($row = Database::fetch_assoc($res)) {
-        $aux[] = $row;
-    }
-    return $aux;
-}

+ 1069 - 15
plugin/buycourses/src/buy_course_plugin.class.php

@@ -6,12 +6,26 @@
  * @author Jose Angel Ruiz    <jaruiz@nosolored.com>
  * @author Imanol Losada      <imanol.losada@beeznest.com>
  * @author Alex Aragón      <alex.aragon@beeznest.com>
+ * @author Angel Fernando Quiroz Campos <angel.quiroz@beeznest.com>
  */
 /**
  * Plugin class for the BuyCourses plugin
  */
 class BuyCoursesPlugin extends Plugin
 {
+    const TABLE_PAYPAL = 'plugin_buycourses_paypal_account';
+    const TABLE_CURRENCY = 'plugin_buycourses_currency';
+    const TABLE_ITEM = 'plugin_buycourses_item';
+    const TABLE_SALE = 'plugin_buycourses_sale';
+    const TABLE_TRANSFER = 'plugin_buycourses_transfer';
+    const PRODUCT_TYPE_COURSE = 1;
+    const PRODUCT_TYPE_SESSION = 2;
+    const PAYMENT_TYPE_PAYPAL = 1;
+    const PAYMENT_TYPE_TRANSFER = 2;
+    const SALE_STATUS_CANCELED = -1;
+    const SALE_STATUS_PENDING = 0;
+    const SALE_STATUS_COMPLETED = 1;
+
     /**
      *
      * @return StaticPlugin
@@ -26,10 +40,13 @@ class BuyCoursesPlugin extends Plugin
     {
         parent::__construct(
             '1.0',
-            'Jose Angel Ruiz - NoSoloRed (original author),
-            Francis Gonzales and Yannick Warnier - BeezNest (integration),
-            Alex Aragón - BeezNest (Design icons and css styles),
-            Imanol Losada - BeezNest (introduction of sessions purchase)',
+            "
+                Jose Angel Ruiz - NoSoloRed (original author),
+                Francis Gonzales and Yannick Warnier - BeezNest (integration),
+                Alex Aragón - BeezNest (Design icons and css styles),
+                Imanol Losada - BeezNest (introduction of sessions purchase)
+                Angel Fernando Quiroz Campos - BeezNest
+            ",
             array(
                 'show_main_menu_tab' => 'boolean',
                 'include_sessions' => 'boolean',
@@ -53,19 +70,14 @@ class BuyCoursesPlugin extends Plugin
      */
     function uninstall()
     {
-        require_once __DIR__.'/../config.php';
         $tablesToBeDeleted = array(
-            TABLE_BUY_SESSION,
-            TABLE_BUY_SESSION_COURSE,
-            TABLE_BUY_SESSION_TEMPORARY,
-            TABLE_BUY_SESSION_SALE,
-            TABLE_BUY_COURSE,
-            TABLE_BUY_COURSE_COUNTRY,
-            TABLE_BUY_COURSE_PAYPAL,
-            TABLE_BUY_COURSE_TRANSFER,
-            TABLE_BUY_COURSE_TEMPORAL,
-            TABLE_BUY_COURSE_SALE
+            self::TABLE_PAYPAL,
+            self::TABLE_TRANSFER,
+            self::TABLE_ITEM,
+            self::TABLE_SALE,
+            self::TABLE_CURRENCY
         );
+
         foreach ($tablesToBeDeleted as $tableToBeDeleted) {
             $table = Database::get_main_table($tableToBeDeleted);
             $sql = "DROP TABLE IF EXISTS $table";
@@ -73,4 +85,1046 @@ class BuyCoursesPlugin extends Plugin
         }
         $this->manageTab(false);
     }
+
+    /**
+     * Get the currency for sales
+     * @return array The selected currency. Otherwise return false
+     */
+    public function getSelectedCurrency()
+    {
+        return Database::select(
+            '*',
+            Database::get_main_table(BuyCoursesPlugin::TABLE_CURRENCY),
+            [
+                'where' => ['status = ?' => true]
+            ],
+            'first'
+        );
+    }
+
+    /**
+     * Get a list of currencies
+     * @return array The currencies. Otherwise return false
+     */
+    public function getCurrencies()
+    {
+        return Database::select(
+            '*',
+            Database::get_main_table(BuyCoursesPlugin::TABLE_CURRENCY)
+        );
+    }
+
+    /**
+     * Save the selected currency
+     * @param int $selectedId The currency Id
+     */
+    public function selectCurrency($selectedId)
+    {
+        $currencyTable = Database::get_main_table(
+            BuyCoursesPlugin::TABLE_CURRENCY
+        );
+
+        Database::update(
+            $currencyTable,
+            ['status' => 0]
+        );
+        Database::update(
+            $currencyTable,
+            ['status' => 1],
+            ['id = ?' => intval($selectedId)]
+        );
+    }
+
+    /**
+     * Save the PayPal configuration params
+     * @param array $params
+     * @return int Rows affected. Otherwise return false
+     */
+    public function savePaypalParams($params)
+    {
+        return Database::update(
+            Database::get_main_table(BuyCoursesPlugin::TABLE_PAYPAL),
+            [
+                'username' => $params['username'],
+                'password' => $params['password'],
+                'signature' => $params['signature'],
+                'sandbox' => isset($params['sandbox'])
+            ],
+            ['id = ?' => 1]
+        );
+    }
+
+    /**
+     * Gets the stored PayPal params
+     * @return array
+     */
+    public function getPaypalParams()
+    {
+        return Database::select(
+            '*',
+            Database::get_main_table(BuyCoursesPlugin::TABLE_PAYPAL),
+            ['id = ?' => 1],
+            'first'
+        );
+    }
+
+    /**
+     * Save a transfer account information
+     * @param array $params The transfer account
+     * @return int Rows affected. Otherwise return false
+     */
+    public function saveTransferAccount($params)
+    {
+        return Database::insert(
+            Database::get_main_table(self::TABLE_TRANSFER),
+            [
+                'name' => $params['tname'],
+                'account' => $params['taccount'],
+                'swift' => $params['tswift']
+            ]
+        );
+    }
+
+    /**
+     * Get a list of transfer accounts
+     * @return array
+     */
+    public function getTransferAccounts()
+    {
+        return Database::select(
+            '*',
+            Database::get_main_table(self::TABLE_TRANSFER)
+        );
+    }
+
+    /**
+     * Remove a transfer account
+     * @param int $id The transfer account ID
+     * @return int Rows affected. Otherwise return false
+     */
+    public function deleteTransferAccount($id)
+    {
+        return Database::delete(
+            Database::get_main_table(self::TABLE_TRANSFER),
+            ['id = ?' => intval($id)]
+        );
+    }
+
+    /**
+     * Filter the registered courses for show in plugin catalog
+     * @return array
+     */
+    private function getCourses()
+    {
+        $entityManager = Database::getManager();
+        $query = $entityManager->createQueryBuilder();
+        
+        $courses = $query
+            ->select('c')
+            ->from('ChamiloCoreBundle:Course', 'c')
+            ->leftJoin(
+                'ChamiloCoreBundle:SessionRelCourse',
+                'sc',
+                \Doctrine\ORM\Query\Expr\Join::WITH,
+                'c = sc.course'
+            )
+            ->where(
+                $query->expr()->isNull('sc.course')
+            )
+            ->getQuery()
+            ->getResult();
+
+        return $courses;
+    }
+
+    /**
+     * Get the item data
+     * @param int $productId The item ID
+     * @param int $itemType The item type
+     * @return array
+     */
+    public function getItemByProduct($productId, $itemType)
+    {
+        $buyItemTable = Database::get_main_table(BuyCoursesPlugin::TABLE_ITEM);
+        $buyCurrencyTable = Database::get_main_table(BuyCoursesPlugin::TABLE_CURRENCY);
+
+        $fakeItemFrom = "
+            $buyItemTable i
+            INNER JOIN $buyCurrencyTable c
+                ON i.currency_id = c.id
+        ";
+
+        return Database::select(
+            ['i.*', 'c.iso_code'],
+            $fakeItemFrom,
+            [
+                'where' => [
+                    'i.product_id = ? AND i.product_type = ?' => [
+                        intval($productId),
+                        intval($itemType)
+                    ]
+                ]
+            ],
+            'first'
+        );
+    }
+
+    /**
+     * List courses details from the configuration page
+     * @return array
+     */
+    public function getCoursesForConfiguration()
+    {
+        $courses = $this->getCourses();
+
+        if (empty($courses)) {
+            return[];
+        }
+
+        $configurationCourses = [];
+        $currency = $this->getSelectedCurrency();
+
+        foreach ($courses as $course) {
+            $courseItem = [
+                'course_id' => $course->getId(),
+                'course_visual_code' => $course->getVisualCode(),
+                'course_code' => $course->getCode(),
+                'course_title' => $course->getTitle(),
+                'course_visibility' => $course->getVisibility(),
+                'visible' => false,
+                'currency' =>  empty($currency) ? null : $currency['iso_code'],
+                'price' => 0.00
+            ];
+
+            $item = $this->getItemByProduct($course->getId(), self::PRODUCT_TYPE_COURSE);
+
+            if ($item !== false) {
+                $courseItem['visible'] = true;
+                $courseItem['currency'] = $item['iso_code'];
+                $courseItem['price'] = $item['price'];
+            }
+
+            $configurationCourses[] = $courseItem;
+        }
+
+        return $configurationCourses;
+    }
+
+    /**
+     * List sessions details from the buy-session table and the session table
+     * @return array The sessions. Otherwise return false
+     */
+    public function getSessionsForConfiguration()
+    {
+        $buyItemTable = Database::get_main_table(BuyCoursesPlugin::TABLE_ITEM);
+        $buyCurrencyTable = Database::get_main_table(BuyCoursesPlugin::TABLE_CURRENCY);
+
+        $auth = new Auth();
+        $sessions = $auth->browseSessions();
+
+        $currency = $this->getSelectedCurrency();
+
+        $items = [];
+
+        $fakeItemFrom = "
+            $buyItemTable i
+            INNER JOIN $buyCurrencyTable c
+                ON i.currency_id = c.id
+        ";
+
+        foreach ($sessions as $session) {
+            $sessionItem = [
+                'session_id' => $session->getId(),
+                'session_name' => $session->getName(),
+                'session_visibility' => $session->getVisibility(),
+                'session_display_start_date' => null,
+                'session_display_end_date' => null,
+                'visible' => false,
+                'currency' =>  empty($currency) ? null : $currency['iso_code'],
+                'price' => 0.00
+            ];
+
+            if (!empty($session->getDisplayStartDate())) {
+                $sessionItem['session_display_start_date'] = api_format_date(
+                    $session->getDisplayStartDate()->format('Y-m-d h:i:s')
+                );
+            }
+
+            if (!empty($session->getDisplayEndDate())) {
+                $sessionItem['session_display_end_date'] = api_format_date(
+                    $session->getDisplayEndDate()->format('Y-m-d h:i:s')
+                );
+            }
+
+            $item = Database::select(
+                ['i.*', 'c.iso_code'],
+                $fakeItemFrom,
+                [
+                    'where' => [
+                        'i.product_id = ? AND ' => $session->getId(),
+                        'i.product_type = ?' => self::PRODUCT_TYPE_SESSION
+                    ]
+                ],
+                'first'
+            );
+
+            if ($item !== false) {
+                $sessionItem['visible'] = true;
+                $sessionItem['currency'] = $item['iso_code'];
+                $sessionItem['price'] = $item['price'];
+            }
+
+            $items[] = $sessionItem;
+        }
+
+        return $items;
+    }
+
+    /**
+     * Get the user status for the session
+     * @param int $userId The user ID
+     * @param \Chamilo\CoreBundle\Entity\Session $session The session
+     * @return string
+     */
+    private function getUserStatusForSession($userId, \Chamilo\CoreBundle\Entity\Session $session)
+    {
+        if (empty($userId)) {
+            return 'NO';
+        }
+
+        $entityManager = Database::getManager();
+        $scuRepo = $entityManager->getRepository('ChamiloCoreBundle:SessionRelCourseRelUser');
+
+        $buySaleTable = Database::get_main_table(self::TABLE_SALE);
+
+        // Check if user bought the course
+        $sale = Database::select(
+            'COUNT(1) as qty',
+            $buySaleTable,
+            [
+                'where' => [
+                    'user_id = ? AND product_type = ? AND product_id = ? AND status = ?' => [
+                        $userId,
+                        self::PRODUCT_TYPE_SESSION,
+                        $session->getId(),
+                        self::SALE_STATUS_PENDING
+                    ]
+                ]
+            ],
+            'first'
+        );
+
+        if ($sale['qty'] > 0) {
+            return "TMP";
+        }
+
+        // Check if user is already subscribe to session
+        $userSubscription = $scuRepo->findBy([
+            'session' => $session,
+            'user' => $userId
+        ]);
+
+        if (!empty($userSubscription)) {
+            return 'YES';
+        }
+
+        return 'NO';
+    }
+
+    /**
+     * Lists current user session details, including each session course details
+     * @param string $name Optional. The name filter
+     * @param int $min Optional. The minimum price filter
+     * @param int $max Optional. The maximum price filter
+     * @return array
+     */
+    public function getCatalogSessionList($name = null, $min = 0, $max = 0)
+    {
+        $sessions = $this->filterSessionList($name, $min, $max);
+
+        $sessionCatalog = array();
+        // loop through all sessions
+        foreach ($sessions as $session) {
+            $sessionCourses = $session->getCourses();
+
+            if (empty($sessionCourses)) {
+                continue;
+            }
+
+            $item = $this->getItemByProduct($session->getId(), self::PRODUCT_TYPE_SESSION);
+
+            if (empty($item)) {
+                continue;
+            }
+
+            $sessionData = $this->getSessionInfo($session->getId());
+            $sessionData['coach'] = $session->getGeneralCoach()->getCompleteName();
+            $sessionData['enrolled'] = $this->getUserStatusForSession(api_get_user_id(), $session);
+            $sessionData['courses'] = array();
+
+            foreach ($sessionCourses as $sessionCourse) {
+                $course = $sessionCourse->getCourse();
+
+                $sessionCourseData = [
+                    'title' => $course->getTitle(),
+                    'coaches' => []
+                ];
+                
+                $userCourseSubscriptions = $session->getUserCourseSubscriptionsByStatus(
+                    $course,
+                    Chamilo\CoreBundle\Entity\Session::COACH
+                );
+
+                foreach ($userCourseSubscriptions as $userCourseSubscription) {
+                    $user = $userCourseSubscription->getUser();
+                    $sessionCourseData['coaches'][] = $user->getCompleteName();
+                }
+
+                $sessionData['courses'][] = $sessionCourseData;
+            }
+
+            $sessionCatalog[] = $sessionData;
+        }
+
+        return $sessionCatalog;
+    }
+
+    /**
+     * Get the user status for the course
+     * @param int $userId The user Id
+     * @param \Chamilo\CoreBundle\Entity\Course $course The course
+     * @return string
+     */
+    private function getUserStatusForCourse($userId, \Chamilo\CoreBundle\Entity\Course $course)
+    {
+        if (empty($userId)) {
+            return 'NO';
+        }
+
+        $entityManager = Database::getManager();
+        $cuRepo = $entityManager->getRepository('ChamiloCoreBundle:CourseRelUser');
+
+        $buySaleTable = Database::get_main_table(self::TABLE_SALE);
+
+        // Check if user bought the course
+        $sale = Database::select(
+            'COUNT(1) as qty',
+            $buySaleTable,
+            [
+                'where' => [
+                    'user_id = ? AND product_type = ? AND product_id = ? AND status = ?' => [
+                        $userId,
+                        self::PRODUCT_TYPE_COURSE,
+                        $course->getId(),
+                        self::SALE_STATUS_PENDING
+                    ]
+                ]
+            ],
+            'first'
+        );
+
+        if ($sale['qty'] > 0) {
+            return "TMP";
+        }
+
+        // Check if user is already subscribe to course
+        $userSubscription = $cuRepo->findBy([
+            'course' => $course,
+            'user' => $userId
+        ]);
+
+        if (!empty($userSubscription)) {
+            return 'YES';
+        }
+
+        return 'NO';
+    }
+
+    /**
+     * Lists current user course details
+     * @return array
+     */
+    /**
+     * Lists current user course details
+     * @param string $name Optional. The name filter
+     * @param int $min Optional. The minimum price filter
+     * @param int $max Optional. The maximum price filter
+     * @return array
+     */
+    public function getCatalogCourseList($name = null, $min = 0, $max = 0)
+    {
+        $courses = $this->filterCourseList($name, $min, $max);
+
+        if (empty($courses)) {
+            return [];
+        }
+
+        $courseCatalog = [];
+
+        foreach ($courses as $course) {
+            $item = $this->getItemByProduct($course->getId(), self::PRODUCT_TYPE_COURSE);
+
+            if (empty($item)) {
+                continue;
+            }
+
+            $courseItem = [
+                'id' => $course->getId(),
+                'title' => $course->getTitle(),
+                'code' => $course->getCode(),
+                'course_img' => null,
+                'price' => $item['price'],
+                'currency' => $item['iso_code'],
+                'teachers' => [],
+                'enrolled' => $this->getUserStatusForCourse(api_get_user_id(), $course)
+            ];
+
+            foreach ($course->getTeachers() as $courseUser) {
+                $teacher = $courseUser->getUser();
+                $courseItem['teachers'][] = $teacher->getCompleteName();
+            }
+
+            //check images
+            $possiblePath = api_get_path(SYS_COURSE_PATH);
+            $possiblePath .= $course->getDirectory();
+            $possiblePath .= '/course-pic.png';
+
+            if (file_exists($possiblePath)) {
+                $courseItem['course_img'] = api_get_path(WEB_COURSE_PATH)
+                    . $course->getDirectory()
+                    . '/course-pic.png';
+            }
+
+            $courseCatalog[] = $courseItem;
+        }
+
+        return $courseCatalog;
+    }
+
+    /**
+     * Get course info
+     * @param int $courseId The course ID
+     * @return array
+     */
+    public function getCourseInfo($courseId)
+    {
+        $entityManager = Database::getManager();
+        $course = $entityManager->find('ChamiloCoreBundle:Course', $courseId);
+
+        if (empty($course)) {
+            return [];
+        }
+
+        $item = $this->getItemByProduct($course->getId(), self::PRODUCT_TYPE_COURSE);
+
+        if (empty($item)) {
+            return [];
+        }
+
+        $courseInfo = [
+            'id' => $course->getId(),
+            'title' => $course->getTitle(),
+            'code' => $course->getCode(),
+            'visual_code' => $course->getVisualCode(),
+            'teachers' => [],
+            'price' => $item['price'],
+            'currency' => $item['iso_code'],
+            'course_img' => null
+        ];
+
+        $courseTeachers = $course->getTeachers();
+
+        foreach ($courseTeachers as $teacher) {
+            $courseInfo['teachers'][] = $teacher->getUser()->getCompleteName();
+        }
+
+        $possiblePath = api_get_path(SYS_COURSE_PATH);
+        $possiblePath .= $course->getDirectory();
+        $possiblePath .= '/course-pic.png';
+
+        if (file_exists($possiblePath)) {
+            $courseInfo['course_img'] = api_get_path(WEB_COURSE_PATH)
+                . $course->getDirectory()
+                . '/course-pic.png';
+        }
+
+        return $courseInfo;
+    }
+
+    /**
+     * Get session info
+     * @param array $sessionId The session ID
+     * @return array
+     */
+    public function getSessionInfo($sessionId) 
+    {
+        $entityManager = Database::getManager();
+        $session = $entityManager->find('ChamiloCoreBundle:Session', $sessionId);
+
+        if (empty($session)) {
+            return [];
+        }
+
+        $item = $this->getItemByProduct($session->getId(), self::PRODUCT_TYPE_SESSION);
+
+        if (empty($item)) {
+            return [];
+        }
+
+        $sessionDates = SessionManager::parseSessionDates([
+            'display_start_date' => $session->getDisplayStartDate(),
+            'display_end_date' => $session->getDisplayEndDate(),
+            'access_start_date' => $session->getAccessStartDate(),
+            'access_end_date' => $session->getAccessEndDate(),
+            'coach_access_start_date' => $session->getCoachAccessStartDate(),
+            'coach_access_end_date' => $session->getCoachAccessEndDate()
+        ]);
+
+        $sessionInfo = [
+            'id' => $session->getId(),
+            'name' => $session->getName(),
+            'dates' => $sessionDates,
+            'courses' => [],
+            'price' => $item['price'],
+            'currency' => $item['iso_code'],
+            'image' => null
+        ];
+
+        $fieldValue = new ExtraFieldValue('session');
+        $sessionImage = $fieldValue->get_values_by_handler_and_field_variable(
+            $session->getId(),
+            'image'
+        );
+
+        if (!empty($sessionImage)) {
+            $sessionInfo['image'] = api_get_path(WEB_UPLOAD_PATH) . $sessionImage['value'];
+        }
+
+        $sessionCourses = $session->getCourses();
+
+        foreach ($sessionCourses as $sessionCourse) {
+            $course = $sessionCourse->getCourse();
+
+            $sessionCourseData = [
+                'title' => $course->getTitle(),
+                'coaches' => []
+            ];
+
+            $userCourseSubscriptions = $session->getUserCourseSubscriptionsByStatus(
+                $course,
+                Chamilo\CoreBundle\Entity\Session::COACH
+            );
+
+            foreach ($userCourseSubscriptions as $userCourseSubscription) {
+                $user = $userCourseSubscription->getUser();
+                $sessionCourseData['coaches'][] = $user->getCompleteName();
+            }
+
+            $sessionInfo['courses'][] = $sessionCourseData;
+        }
+
+        return $sessionInfo;
+    }
+
+    /**
+     * Get registered item data
+     * @param int $itemId The item ID
+     * @return array
+     */
+    public function getItem($itemId)
+    {
+        return Database::select(
+            '*',
+            Database::get_main_table(self::TABLE_ITEM),
+            [
+                'where' => ['id = ?' => intval($itemId)]
+            ],
+            'first'
+        );
+    }
+
+    /**
+     * Register a sale
+     * @param int $itemId The product ID
+     * @param int $paymentType The payment type
+     * @return boolean
+     */
+    public function registerSale($itemId, $paymentType)
+    {
+        if (!in_array($paymentType, [self::PAYMENT_TYPE_PAYPAL, self::PAYMENT_TYPE_TRANSFER])) {
+            return false;
+        }
+
+        $entityManager = Database::getManager();
+
+        $item = $this->getItem($itemId);
+
+        if (empty($item)) {
+            return false;
+        }
+
+        if ($item['product_type'] == self::PRODUCT_TYPE_COURSE) {
+            $course = $entityManager->find('ChamiloCoreBundle:Course', $item['product_id']);
+
+            if (empty($course)) {
+                return false;
+            }
+
+            $productName = $course->getTitle();
+        } elseif ($item['product_type'] == self::PRODUCT_TYPE_SESSION) {
+            $session = $entityManager->find('ChamiloCoreBundle:Session', $item['product_id']);
+
+            if (empty($session)) {
+                return false;
+            }
+
+            $productName = $session->getName();
+        }
+
+        $values = [
+            'reference' => $this->generateReference(
+                api_get_user_id(),
+                $item['product_type'],
+                $item['product_id']
+            ),
+            'currency_id' => $item['currency_id'],
+            'date' => api_get_utc_datetime(),
+            'user_id' => api_get_user_id(),
+            'product_type' => $item['product_type'],
+            'product_name' => $productName,
+            'product_id' => $item['product_id'],
+            'price' => $item['price'],
+            'status' => self::SALE_STATUS_PENDING,
+            'payment_type' => intval($paymentType)
+        ];
+
+        return Database::insert(self::TABLE_SALE, $values);
+    }
+
+    /**
+     * Get sale data by ID
+     * @param int $saleId The sale ID
+     * @return array
+     */
+    public function getSale($saleId)
+    {
+        return Database::select(
+            '*',
+            Database::get_main_table(self::TABLE_SALE),
+            [
+                'where' => ['id = ?' => intval($saleId)]
+            ],
+            'first'
+        );
+    }
+
+    /**
+     * Get currency data by ID
+     * @param int $currencyId The currency ID
+     * @return array
+     */
+    public function getCurrency($currencyId)
+    {
+        return Database::select(
+            '*',
+            Database::get_main_table(BuyCoursesPlugin::TABLE_CURRENCY),
+            [
+                'where' => ['id = ?' => intval($currencyId)]
+            ],
+            'first'
+        );
+    }
+
+    /**
+     * Update the sale status
+     * @param int $saleId The sale ID
+     * @param int $newStatus The new status
+     * @return boolean
+     */
+    private function updateSaleStatus($saleId, $newStatus = self::SALE_STATUS_PENDING)
+    {
+        $saleTable = Database::get_main_table(self::TABLE_SALE);
+
+        return Database::update(
+            $saleTable,
+            ['status' => intval($newStatus)],
+            ['id = ?' => intval($saleId)]
+        );
+    }
+
+    /**
+     * Complete sale process. Update sale status to completed
+     * @param int $saleId The sale ID
+     * @return boolean
+     */
+    public function completeSale($saleId)
+    {
+        $sale = $this->getSale($saleId);
+
+        if ($sale['status'] == self::SALE_STATUS_COMPLETED) {
+            return true;
+        }
+
+        $saleIsCompleted = false;
+
+        switch ($sale['product_type']) {
+            case self::PRODUCT_TYPE_COURSE:
+                $course = api_get_course_info_by_id($sale['product_id']);
+
+                $saleIsCompleted = CourseManager::subscribe_user($sale['user_id'], $course['code']);
+                break;
+            case self::PRODUCT_TYPE_SESSION:
+                SessionManager::suscribe_users_to_session(
+                    $sale['product_id'],
+                    [$sale['user_id']],
+                    api_get_session_visibility($sale['product_id']),
+                    false
+                );
+
+                $saleIsCompleted = true;
+                break;
+        }
+
+        if ($saleIsCompleted) {
+            $this->updateSaleStatus($sale['id'], self::SALE_STATUS_COMPLETED);
+        }
+
+        return $saleIsCompleted;
+    }
+
+    /**
+     * Update sale status to canceled
+     * @param int $saleId The sale ID
+     */
+    public function cancelSale($saleId)
+    {
+        $this->updateSaleStatus($saleId, self::SALE_STATUS_CANCELED);
+    }
+
+    /**
+     * Get payment types
+     * @return array
+     */
+    public function getPaymentTypes()
+    {
+        return [
+            self::PAYMENT_TYPE_PAYPAL => 'PayPal',
+            self::PAYMENT_TYPE_TRANSFER => $this->get_lang('BankTransfer')
+        ];
+    }
+
+    /**
+     * Get a list of sales by the status
+     * @param type $status
+     * @return type
+     */
+    public function getSaleListByStatus($status = self::SALE_STATUS_PENDING)
+    {
+        $saleTable = Database::get_main_table(BuyCoursesPlugin::TABLE_SALE);
+        $currencyTable = Database::get_main_table(BuyCoursesPlugin::TABLE_CURRENCY);
+        $userTable = Database::get_main_table(TABLE_MAIN_USER);
+
+        $innerJoins = "
+            INNER JOIN $currencyTable c
+                ON s.currency_id = c.id
+            INNER JOIN $userTable u
+                ON s.user_id = u.id
+        ";
+
+        return Database::select(
+            ['c.iso_code', 'u.firstname', 'u.lastname', 's.*'],
+            "$saleTable s $innerJoins",
+            [
+                'where' => ['s.status = ?' => intval($status)],
+                'order' => 'id DESC'
+            ]
+        );
+    }
+
+    /**
+     * Get the statuses for sales
+     * @return array
+     */
+    public function getSaleStatuses()
+    {
+        return [
+            self::SALE_STATUS_CANCELED => $this->get_lang('SaleStatusCanceled'),
+            self::SALE_STATUS_PENDING => $this->get_lang('SaleStatusPending'),
+            self::SALE_STATUS_COMPLETED => $this->get_lang('SaleStatusCompleted')
+        ];
+    }
+
+    /**
+     * Get the list of product types
+     * @return array
+     */
+    public function getProductTypes()
+    {
+        return [
+            self::PRODUCT_TYPE_COURSE => get_lang('Course'),
+            self::PRODUCT_TYPE_SESSION => get_lang('Session')
+        ];
+    }
+
+    /**
+     * Search filtered sessions by name, and range of price
+     * @param string $name Optional. The name filter
+     * @param int $min Optional. The minimun price filter
+     * @param int $max Optional. The maximum price filter
+     * @return array
+     */
+    private function filterSessionList($name = null, $min = 0, $max = 0)
+    {
+        if (empty($name) && empty($min) && empty($max)) {
+            $auth = new Auth();
+            return $auth->browseSessions();
+        }
+
+        $itemTable = Database::get_main_table(self::TABLE_ITEM);
+        $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
+
+        $min = floatval($min);
+        $max = floatval($max);
+
+        $innerJoin = "$itemTable i ON s.id = i.product_id";
+        $whereConditions = [
+            'i.product_type = ? ' => self::PRODUCT_TYPE_SESSION
+        ];
+
+        if (!empty($name)) {
+            $whereConditions['AND s.name LIKE %?%'] = $name;
+        }
+
+        if (!empty($min)) {
+            $whereConditions['AND i.price >= ?'] = $min;
+        }
+
+        if (!empty($max)) {
+            $whereConditions['AND i.price <= ?'] = $max;
+        }
+
+        $sessionIds = Database::select(
+            's.id',
+            "$sessionTable s INNER JOIN $innerJoin",
+            ['where' => $whereConditions]
+        );
+
+        if (!$sessionIds) {
+            return [];
+        }
+
+        $sessions = [];
+
+        foreach ($sessionIds as $sessionId) {
+            $sessions[] = Database::getManager()->find('ChamiloCoreBundle:Session', $sessionId);
+        }
+
+        return $sessions;
+    }
+
+    /**
+     * Search filtered courses by name, and range of price
+     * @param string $name Optional. The name filter
+     * @param int $min Optional. The minimun price filter
+     * @param int $max Optional. The maximum price filter
+     * @return array
+     */
+    private function filterCourseList($name = null, $min = 0, $max = 0)
+    {
+        if (empty($name) && empty($min) && empty($max)) {
+            return $this->getCourses();
+        }
+
+        $itemTable = Database::get_main_table(self::TABLE_ITEM);
+        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
+
+        $min = floatval($min);
+        $max = floatval($max);
+
+        $innerJoin = "$itemTable i ON c.id = i.product_id";
+        $whereConditions = [
+            'i.product_type = ? ' => self::PRODUCT_TYPE_COURSE
+        ];
+
+        if (!empty($name)) {
+            $whereConditions['AND c.title LIKE %?%'] = $name;
+        }
+
+        if (!empty($min)) {
+            $whereConditions['AND i.price >= ?'] = $min;
+        }
+
+        if (!empty($max)) {
+            $whereConditions['AND i.price <= ?'] = $max;
+        }
+
+        $courseIds = Database::select(
+            'c.id',
+            "$courseTable c INNER JOIN $innerJoin",
+            ['where' => $whereConditions]
+        );
+
+        if (!$courseIds) {
+            return [];
+        }
+
+        $courses = [];
+
+        foreach ($courseIds as $courseId) {
+            $courses[] = Database::getManager()->find('ChamiloCoreBundle:Course', $courseId);
+        }
+
+        return $courses;
+    }
+
+    /**
+     * Generates a random text (used for order references)
+     * @param int $length Optional. Length of characters
+     * @param boolean $lowercase Optional. Include lowercase characters
+     * @param boolean $uppercase Optional. Include uppercase characters
+     * @param boolean $numbers Optional. Include numbers
+     * @return string
+     */
+    public static function randomText(
+        $length = 6,
+        $lowercase = true,
+        $uppercase = true,
+        $numbers = true
+    )
+    {
+        $salt = $lowercase ? 'abchefghknpqrstuvwxyz' : '';
+        $salt .= $uppercase ? 'ACDEFHKNPRSTUVWXYZ' : '';
+        $salt .= $numbers ? (strlen($salt) ? '2345679' : '0123456789') : '';
+
+        if (strlen($salt) == 0) {
+            return '';
+        }
+
+        $str = '';
+
+        srand((double)microtime() * 1000000);
+
+        for ($i = 0; $i < $length; $i++) {
+            $numbers = rand(0, strlen($salt) - 1);
+            $str .= substr($salt, $numbers, 1);
+        }
+
+        return $str;
+    }
+
+    /**
+     * Generates an order reference
+     * @param int $userId The user ID
+     * @param int $productType The course/session type
+     * @param int $productId The course/session ID
+     * @return string
+     */
+    public function generateReference($userId, $productType, $productId)
+    {
+        return vsprintf(
+            "%d-%d-%d-%s",
+            [$userId, $productType, $productId, self::randomText()]
+        );
+    }
+
 }

+ 28 - 45
plugin/buycourses/src/configuration.php

@@ -7,57 +7,40 @@
 /**
  * Initialization
  */
-require_once dirname(__FILE__) . '/buy_course.lib.php';
+$cidReset = true;
+
 require_once '../../../main/inc/global.inc.php';
-require_once 'buy_course_plugin.class.php';
 
 $plugin = BuyCoursesPlugin::create();
+$includeSession = $plugin->get('include_sessions') === 'true';
 
-$_cid = 0;
-$templateName = $plugin->get_lang('AvailableCourses');
-$interbreadcrumb[] = array("url" => "list.php", "name" => $plugin->get_lang('CourseListOnSale'));
-$interbreadcrumb[] = array("url" => "paymentsetup.php", "name" => get_lang('Configuration'));
+api_protect_admin_script(true);
+
+$courses = $plugin->getCoursesForConfiguration();
+
+//view
+$interbreadcrumb[] = [
+    'url' => 'course_catalog.php',
+    'name' => $plugin->get_lang('CourseListOnSale')
+];
+$interbreadcrumb[] = [
+    'url' => 'paymentsetup.php',
+    'name' => get_lang('Configuration')
+];
 
+$templateName = $plugin->get_lang('AvailableCourses');
 $tpl = new Template($templateName);
+$tpl->assign('courses', $courses);
+$tpl->assign('sessions_are_included', $includeSession);
 
-$teacher = api_is_platform_admin();
-api_protect_admin_script(true);
+if ($includeSession) {
+    $sessions = $plugin->getSessionsForConfiguration();
 
-if ($teacher) {
-    // sync course table with the plugin
-    sync();
-    $visibility = array();
-    $visibility[] = getCourseVisibilityIcon('0');
-    $visibility[] = getCourseVisibilityIcon('1');
-    $visibility[] = getCourseVisibilityIcon('2');
-    $visibility[] = getCourseVisibilityIcon('3');
-    $visibility[] = getCourseVisibilityIcon('4');
-
-    $coursesList = listCourses();
-    $confirmationImgPath = api_get_path(WEB_PLUGIN_PATH) . 'buycourses/resources/img/32/accept.png';
-    $saveImgPath = api_get_path(WEB_PLUGIN_PATH) . 'buycourses/resources/img/32/save.png';
-    $currencyType = findCurrency();
-
-    $tpl->assign('server', $_configuration['root_web']);
-    $tpl->assign('courses', $coursesList);
-    $tpl->assign('visibility', $visibility);
-    $tpl->assign('confirmation_img', $confirmationImgPath);
-    $tpl->assign('save_img', $saveImgPath);
-    $tpl->assign('currency', $currencyType);
-
-    $selectedValue = Database::select(
-        'selected_value',
-        Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT),
-        array('where'=> array('variable = ?' => array('buycourses_include_sessions')))
-    );
-    $result = array_shift($selectedValue);
-    if ($result['selected_value'] === 'true') {
-        $tpl->assign('sessionsAreIncluded', 'YES');
-        $tpl->assign('sessions', listSessions());
-    }
-
-    $listing_tpl = 'buycourses/view/configuration.tpl';
-    $content = $tpl->fetch($listing_tpl);
-    $tpl->assign('content', $content);
-    $tpl->display_one_col_template();
+    $tpl->assign('sessions', $sessions);
 }
+
+$content = $tpl->fetch('buycourses/view/configuration.tpl');
+
+$tpl->assign('header', $templateName);
+$tpl->assign('content', $content);
+$tpl->display_one_col_template();

+ 71 - 0
plugin/buycourses/src/course_catalog.php

@@ -0,0 +1,71 @@
+<?php
+/**
+ * List of courses
+ * @package chamilo.plugin.buycourses
+ */
+/**
+ * Initialization
+ */
+$cidReset = true;
+
+require_once '../../../main/inc/global.inc.php';
+
+$plugin = BuyCoursesPlugin::create();
+$includeSessions = $plugin->get('include_sessions') === 'true';
+
+$nameFilter = null;
+$minFilter = 0;
+$maxFilter = 0;
+
+$form = new FormValidator('search_filter_form', 'get', null, null, [], FormValidator::LAYOUT_INLINE);
+
+if ($form->validate()) {
+    $formValues = $form->getSubmitValues();
+    $nameFilter = isset($formValues['name']) ? $formValues['name'] : null;
+    $minFilter = isset($formValues['min']) ? $formValues['min'] : 0;
+    $maxFilter = isset($formValues['max']) ? $formValues['max'] : 0;
+}
+
+$form->addHeader($plugin->get_lang('SearchFilter'));
+$form->addText('name', get_lang('SessionName'), false);
+$form->addElement(
+    'number',
+    'min',
+    $plugin->get_lang('MinimumPrice'),
+    ['step' => '0.01', 'min' => '0']
+);
+$form->addElement(
+    'number',
+    'max',
+    $plugin->get_lang('MaximumPrice'),
+    ['step' => '0.01', 'min' => '0']
+);
+$form->addHtml('<hr>');
+$form->addButtonFilter(get_lang('Search'));
+
+$courseList = $plugin->getCatalogCourseList($nameFilter, $minFilter, $maxFilter);
+
+//View
+if (api_is_platform_admin()) {
+    $interbreadcrumb[] = [
+        'url' => 'configuration.php',
+        'name' => $plugin->get_lang('AvailableCoursesConfiguration')
+    ];
+    $interbreadcrumb[] = [
+        'url' => 'paymentsetup.php',
+        'name' => $plugin->get_lang('PaymentsConfiguration')
+    ];
+}
+
+$templateName = $plugin->get_lang('CourseListOnSale');
+$tpl = new Template($templateName);
+$tpl->assign('search_filter_form', $form->returnForm());
+$tpl->assign('showing_courses', true);
+$tpl->assign('courses', $courseList);
+$tpl->assign('sessions_are_included', $includeSessions);
+
+$content = $tpl->fetch('buycourses/view/catalog.tpl');
+
+$tpl->assign('header', $templateName);
+$tpl->assign('content', $content);
+$tpl->display_one_col_template();

+ 3 - 17
plugin/buycourses/src/error.php

@@ -1,26 +1,12 @@
 <?php
 /* For license terms, see /license.txt */
 /**
- * Errors management for the Buy Courses plugin - Redirects to list.php
+ * Errors management for the Buy Courses plugin - Redirects to course_catalog.php
  * @package chamilo.plugin.buycourses
  */
 /**
  * Config
  */
-$course_plugin = 'buycourses';
-require_once 'buy_course.lib.php';
-require_once 'buy_course_plugin.class.php';
+unset($_SESSION['bc_sale_id']);
 
-unset($_SESSION['bc_user_id']);
-unset($_SESSION['bc_registered']);
-unset($_SESSION['bc_code']);
-unset($_SESSION['bc_title']);
-unset($_SESSION['Payment_Amount']);
-unset($_SESSION['currencyCodeType']);
-unset($_SESSION['PaymentType']);
-unset($_SESSION['nvpReqArray']);
-unset($_SESSION['TOKEN']);
-$_SESSION['bc_success'] = false;
-$_SESSION['bc_message'] = 'CancelOrder';
-
-header('Location:list.php');
+header('Location: course_catalog.php');

+ 63 - 499
plugin/buycourses/src/function.php

@@ -8,514 +8,78 @@
  * Init
  */
 require_once '../config.php';
-require_once 'buy_course.lib.php';
 
-$tableBuySession = Database::get_main_table(TABLE_BUY_SESSION);
-$tableBuySessionTemporal = Database::get_main_table(TABLE_BUY_SESSION_TEMPORARY);
-$tableBuySessionRelCourse = Database::get_main_table(TABLE_BUY_SESSION_COURSE);
-$tableSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tableBuyCourse = Database::get_main_table(TABLE_BUY_COURSE);
-$tableBuyCourseCountry = Database::get_main_table(TABLE_BUY_COURSE_COUNTRY);
-$tableBuyCoursePaypal = Database::get_main_table(TABLE_BUY_COURSE_PAYPAL);
-$tableBuyCourseTransfer = Database::get_main_table(TABLE_BUY_COURSE_TRANSFER);
-$tableBuyCourseTemporal = Database::get_main_table(TABLE_BUY_COURSE_TEMPORAL);
-$tableSession = Database::get_main_table(TABLE_MAIN_SESSION);
-$tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
-$tableSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
-$tableCourseRelUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
-$tableUser = Database::get_main_table(TABLE_MAIN_USER);
+$itemTable = Database::get_main_table(BuyCoursesPlugin::TABLE_ITEM);
 
 $plugin = BuyCoursesPlugin::create();
-$buy_name = $plugin->get_lang('Buy');
-
-if ($_REQUEST['tab'] == 'sync') {
-    $sql = "SELECT code, title FROM $tableCourse;";
-    $res = Database::query($sql);
-    while ($row = Database::fetch_assoc($res)) {
-        $aux_code .= $row['code'];
-        $aux_title .= $row['title'];
-    }
-    $sql = "SELECT name, access_start_date, access_end_date FROM $tableSession;";
-    $res = Database::query($sql);
-    while ($row = Database::fetch_assoc($res)) {
-        $aux_name .= $row['name'];
-        $aux_date_start .= $row['access_start_date'];
-        $aux_date_end .= $row['access_end_date'];
-    }
-    echo json_encode(array("status" => "true", "content" => $content));
-}
-
-if ($_REQUEST['tab'] == 'sessions_filter') {
-    $session = isset($_REQUEST['name']) ? Database::escape_string($_REQUEST['name']) : '';
-    $priceMin = isset($_REQUEST['pricemin']) ? floatval($_REQUEST['pricemin']) : 0;
-    $priceMax = isset($_REQUEST['pricemax']) ? floatval($_REQUEST['pricemax']) : 0;
-    //$category = isset($_REQUEST['category']) ? Database::escape_string($_REQUEST['category']) : '';
-    $server = api_get_path(WEB_PATH);
-
-    $sql = "SELECT a.session_id, a.visible, a.price, b.*
-            FROM $tableBuySession a, $tableSession b
-            WHERE a.session_id = b.id AND a.visible = 1;";
-
-    $filter = "";
-    if (!empty($session)) {
-        $filter .= " AND b.name LIKE '%".$session."%'";
-    }
-
-    if ($priceMin > 0) {
-        $filter .= " AND a.price >= ".$priceMin;
-    }
-
-    if ($priceMax > 0) {
-        $filter .= " AND a.price <= ".$priceMax;
-    }
-
-    /*if (!empty($category)) {
-        $filter .= " AND b.category_code = '".$category."'";
-    }*/
-
-    if (!empty($filter)) {
-        $sql = substr_replace($sql, $filter.";", -1);
-    }
-
-    $resSessions = Database::query($sql);
-    $auxSessions = array();
-
-    // loop through all sessions
-    while ($rowSession = Database::fetch_assoc($resSessions)) {
-        // get courses of current session
-        $sqlSessionCourse = "SELECT DISTINCT a.session_id, a.course_code, a.nbr_users
-        FROM $tableBuySessionRelCourse a, $tableSessionRelCourse b
-        WHERE a.session_id = b.session_id AND a.session_id = " . $rowSession['session_id'] . ";";
-        $resSessionCourse = Database::query($sqlSessionCourse);
-        $aux = array();
-        // loop through courses of current session
-        while ($rowSessionCourse = Database::fetch_assoc($resSessionCourse)) {
-            // get course of current session
-            $sql = "SELECT a.course_id, a.session_id, a.visible, a.price, b.*
-            FROM $tableBuyCourse a, $tableCourse b
-            WHERE a.code = b.code AND a.code = '" . $rowSessionCourse['course_code'] . "';";
-            $res = Database::query($sql);
-            // loop inside a course of current session
-            while ($row = Database::fetch_assoc($res)) {
-                //check teacher
-                $sql = "SELECT lastname, firstname
-                FROM course_rel_user a, user b
-                WHERE a.c_id=" . $row['id'] . "
-                AND a.status <> 6
-                AND a.user_id=b.id;";
-                $tmp = Database::query($sql);
-                $rowTmp = Database::fetch_assoc($tmp);
-                $row['teacher'] = $rowTmp['firstname'] . ' ' . $rowTmp['lastname'];
-                //check images
-                if (file_exists(api_get_path(SYS_COURSE_PATH) . $row['code'] . "/course-pic85x85.png")) {
-                    $row['course_img'] = "courses/" . $row['code'] . "/course-pic85x85.png";
-                } else {
-                    $row['course_img'] = "main/img/without_picture.png";
-                }
-                $row['price'] = number_format($row['price'], 2, '.', ' ');
-                $aux[] = $row;
-            }
-        }
-        //check if the user is enrolled in the current session
-        if (isset($_SESSION['_user']) || $_SESSION['_user']['user_id'] != '') {
-            $sql = "SELECT 1 FROM $tableSessionRelUser
-                WHERE session_id ='".$rowSession['session_id']."' AND
-                user_id ='" . api_get_user_id() . "'";
-            $result = Database::query($sql);
-            if (Database::affected_rows($result) > 0) {
-                $rowSession['enrolled'] = "YES";
-            } else {
-                $sql = "SELECT 1 FROM $tableBuySessionTemporal
-                    WHERE session_id ='".$rowSession['session_id']."' AND
-                    user_id='" . api_get_user_id() . "'";
-                $result = Database::query($sql);
-                if (Database::affected_rows($result) > 0) {
-                    $rowSession['enrolled'] = "TMP";
-                } else {
-                    $rowSession['enrolled'] = "NO";
-                }
-            }
-        } else {
-            $sql = "SELECT 1 FROM $tableBuySessionTemporal
-                WHERE session_id ='".$rowSession['session_id']."' AND
-                user_id='" . api_get_user_id() . "'";
-            $result = Database::query($sql);
-            if (Database::affected_rows($result) > 0) {
-                $rowSession['enrolled'] = "TMP";
-            } else {
-                $rowSession['enrolled'] = "NO";
-            }
-        }
-        // add courses to current session
-        $rowSession['courses'] = $aux;
-        // add the current whole session
-        $auxSessions[] = $rowSession;
-    }
-
-    $currencyType = findCurrency();
-    $content = '';
-    foreach ($auxSessions as $session) {
-        $content .= '<div class="span8 well-course">
-            <div class="row">
-                <div class="span4 ">
-                    <div class="categories-course-description">
-                        <h3>'.$session['name'].'</h3>
-                        <h5>'.get_lang('From').' '.$session['access_start_date'].
-                        ' '.get_lang('Until').' '.$session['access_end_date'].'</h5>';
-        if ($session['enrolled'] == "YES") {
-            $content .= '<span class="label label-info">'.$plugin->get_lang('TheUserIsAlreadyRegisteredInTheSession').'</span>';
-        }
-        if ($session['enrolled'] == "TMP") {
-            $content .= '<span class="label label-warning">'.$plugin->get_lang('WaitingToReceiveThePayment').'</span>';
-        }
-        $content .= '</div>
-                </div>
-            <div class="span right">
-                <div class="sprice right">'.
-                    $session['price'].' '.$currencyType.'
-                </div>
-                <div class="cleared">
-                </div>
-                <div class="btn-group right">';
-        if ($session['enrolled'] == "NO") {
-            $content .= '<a class="btn btn-success" title="" href="'.$server.
-                        'plugin/buycourses/src/process.php?scode='.$session['session_id'].'">'.
-                            $buy_name.
-                        '</a>';
-        }
-        $content .= '</div>
-            </div>
-        </div>';
-        $courses = $session['courses'];
-        foreach ($courses as $course) {
-            $content .= '<div class="row">
-                <div class="span">
-                    <div class="thumbnail">
-                        <a class="ajax" rel="gb_page_center[778]" title=""
-                        href="'.$server.'plugin/buycourses/src/ajax.php?
-                        a=show_course_information&code='.$course['code'].'">
-                            <img alt="" src="' . $server . $course['course_img'] . '">
-                        </a>
-                    </div>
-                </div>
-                <div class="span4">
-                    <div class="categories-course-description">
-                        <h3>'.$course['title'].'</h3>
-                        <h5>'.get_lang('Teacher').': '.$course['teacher'].'</h5>
-                    </div>
-                </div>
-                <div class="span right">
-                    <div class="cleared">
-                    </div>
-                    <div class="btn-group right">
-                        <a class="ajax btn btn-primary" title=""
-                        href="'.$server.'plugin/buycourses/src/ajax.php?
-                        a=show_course_information&code='.$course['code'].'">'.get_lang('Description').'</a>
-                    </div>
-                </div>
-            </div>';
-        }
-        $content .= '</div>';
-    }
-
-    echo json_encode(array("status" => "true", "content" => $content));
-}
-
-if ($_REQUEST['tab'] == 'courses_filter') {
-    $course = isset($_REQUEST['name']) ? Database::escape_string($_REQUEST['name']) : '';
-    $priceMin = isset($_REQUEST['pricemin']) ? floatval($_REQUEST['pricemin']) : 0;
-    $priceMax = isset($_REQUEST['pricemax']) ? floatval($_REQUEST['pricemax']) : 0;
-    /**
-     * Deprecated since 2014-10-14
-     */
-    //$show = Database::escape_string($_REQUEST['show']);
-    //$category = Database::escape_string($_REQUEST['category']);
-    $server = api_get_path(WEB_PATH);
-
-    $sql = "SELECT a.course_id, a.visible, a.price, b.*
-            FROM $tableBuyCourse a, $tableCourse b
-            WHERE a.course_id = b.id AND a.session_id = 0
-            AND a.visible = 1;";
-
-    $filter = "";
-    if (!empty($course)) {
-        $filter .= " AND b.title LIKE '%".$course."%'";
-    }
-
-    if ($priceMin > 0) {
-        $filter .= " AND a.price >= ".$priceMin;
-    }
-
-    if ($priceMax > 0) {
-        $filter .= " AND a.price <= ".$priceMax;
-    }
-
-    /*if (!empty($category)) {
-        $filter .= " AND b.category_code = '".$category."'";
-    }*/
-
-    if (!empty($filter)) {
-        $sql = substr_replace($sql, $filter.";", -1);
-    }
-
-    $res = Database::query($sql);
-    $aux = array();
-    while ($row = Database::fetch_assoc($res)) {
-        //Check teacher
-        $sql = "SELECT lastname, firstname
-            FROM $tableCourseRelUser a, $tableUser b
-            WHERE a.c_id = " . $row['id'] . "
-            AND a.status <> 6
-            AND a.user_id = b.id;";
-
-        $tmp = Database::query($sql);
-        $rowTmp = Database::fetch_assoc($tmp);
-        $row['teacher'] = $rowTmp['firstname'] . ' ' . $rowTmp['lastname'];
-        //Check if the student is enrolled
-        if (isset($_SESSION['_user']) || $_SESSION['_user']['user_id'] != '') {
-            $sql = "SELECT 1 FROM $tableCourseRelUser
-                WHERE c_id = " . $row['id'] . "
-                AND user_id = " . intval($_SESSION['_user']['user_id']) . ";";
-
-            $tmp = Database::query($sql);
-            if (Database::affected_rows($tmp) > 0) {
-                $row['enrolled'] = "YES";
-            } else {
-                $row['enrolled'] = "NO";
-            }
-        } else {
-            $row['enrolled'] = "NO";
-        }
-        // Check img
-        if (file_exists(api_get_path(SYS_COURSE_PATH) . $row['directory'] . "/course-pic85x85.png")) {
-            $row['course_img'] = "courses/" . $row['directory'] . "/course-pic85x85.png";
-        } else {
-            $row['course_img'] = "main/img/without_picture.png";
-        }
-
-        $aux[] = $row;
-        /**
-         * Deprecated since 2014-10-14
-         */
-        /*if ($show == "YES" && $row['enrolled'] == "YES") {
-            ;
-        } else {
-          $aux[] = $row;
-        }*/
-
-    }
-    $currencyType = findCurrency();
-    $content = '';
-    foreach ($aux as $course) {
-        $content .= '
-            <div class="span8">
-                <div class="row well-course">
-                    <div class="span1 icon-course">
-                        <div class="thumbnail">
-                            <a class="ajax" rel="gb_page_center[778]" title=""
-                            href="'.$server.'plugin/buycourses/src/ajax.php?
-                            a=show_course_information&code='.$course['code'].'">
-                                <img alt="" src="'.$server.$course['course_img'].'">
-                            </a>
-                        </div>
-                    </div>
-                    <div class="span3">
-                        <div class="categories-course-description">
-                            <h3>'.$course['title'].'</h3>
-                            <h5>'.get_lang('Teacher').': '.$course['teacher'].'</h5>
-                        </div>';
-        if ($course['enrolled'] == "YES") {
-            $content .= '<span class="label label-info">'.$plugin->get_lang('TheUserIsAlreadyRegisteredInTheCourse').'</span>';
-        }
-        if ($course['enrolled'] == "TMP") {
-            $content .= '<span class="label label-warning">'.$plugin->get_lang('WaitingToReceiveThePayment').'</span>';
-        }
-        $content .= '</div>
-                    <div class="span3 right">
-                        <div class="sprice right">'.
-                            $course['price'].' '.$currencyType.'
-                        </div>
-                        <div class="cleared">
-                        </div>
-                        <div class="btn-group right">
-                            <a class="ajax btn btn-primary" title=""
-                            href="'.$server.'plugin/buycourses/src/ajax.php?
-                            a=show_course_information&code='.$course['code'].'">'.
-                                get_lang('Description').
-                            '</a>';
-        if ($course['enrolled'] != "YES") {
-            $content .= '<a class="btn btn-success" title=""
-                            href="'.$server.'plugin/buycourses/src/process.php?code='.$course['id'].'">'.
-                                $buy_name.
-                            '</a>';
-        }
-        $content .= '</div>
-                    </div>
-                </div>
-            </div>';
-    }
-    echo json_encode(array("status" => "true", "content" => $content));
-}
-
-if ($_REQUEST['tab'] == 'save_currency') {
-    $id = Database::escape_string($_REQUEST['currency']);
-    $sql = "UPDATE $tableBuyCourseCountry SET status='0';";
-    $res = Database::query($sql);
-    $sql = "UPDATE $tableBuyCourseCountry SET status='1' WHERE country_id='" . $id . "';";
-    $res = Database::query($sql);
-    if (!$res) {
-        $content = $plugin->get_lang('ProblemToSaveTheCurrencyType');
-        echo json_encode(array("status" => "false", "content" => $content));
-    } else {
-        $content = get_lang('Saved');
-        echo json_encode(array("status" => "true", "content" => $content));
-    }
-}
-
-if ($_REQUEST['tab'] == 'save_paypal') {
-    $username = Database::escape_string($_REQUEST['username']);
-    $password = Database::escape_string($_REQUEST['password']);
-    $signature = Database::escape_string($_REQUEST['signature']);
-    $sandbox = Database::escape_string($_REQUEST['sandbox']);
-    $sql = "UPDATE $tableBuyCoursePaypal
-        SET sandbox = '" . $sandbox . "',
-        username = '" . $username . "',
-        password = '" . $password . "',
-        signature = '" . $signature . "'
-        WHERE id = '1';";
-
-    $res = Database::query($sql);
-    if (!$res) {
-        $content = $plugin->get_lang('ProblemToSaveThePaypalParameters');
-        echo json_encode(array("status" => "false", "content" => $content));
-    } else {
-        $content = get_lang('Saved');
-        echo json_encode(array("status" => "true", "content" => $content));
-    }
-}
-
-if ($_REQUEST['tab'] == 'add_account') {
-    $name = Database::escape_string($_REQUEST['name']);
-    $account = Database::escape_string($_REQUEST['account']);
-    $swift = Database::escape_string($_REQUEST['swift']);
-    $sql = "INSERT INTO $tableBuyCourseTransfer (name, account, swift)
-        VALUES ('" . $name . "','" . $account . "', '" . $swift . "');";
-
-    $res = Database::query($sql);
-    if (!$res) {
-        $content = $plugin->get_lang('ProblemToInsertANewAccount');
-        echo json_encode(array("status" => "false", "content" => $content));
-    } else {
-        $content = get_lang('Saved');
-        echo json_encode(array("status" => "true", "content" => $content));
-    }
-}
-
-if ($_REQUEST['tab'] == 'delete_account') {
-    $id = intval($_REQUEST['id']);
-
-    $sql = "DELETE FROM $tableBuyCourseTransfer WHERE id='" . $id . "';";
-    $res = Database::query($sql);
-    if (!$res) {
-        $content = $plugin->get_lang('ProblemToDeleteTheAccount');
-        echo json_encode(array("status" => "false", "content" => $content));
-    } else {
-        $content = get_lang('Saved');
-        echo json_encode(array("status" => "true", "content" => $content));
-    }
-}
+$currency = $plugin->getSelectedCurrency();
 
 if ($_REQUEST['tab'] == 'save_mod') {
-
-    $id;
-    $tableBuy;
-    $tableField;
-
     if (isset($_REQUEST['course_id'])) {
-        $id = intval($_REQUEST['course_id']);
-        $tableBuy = $tableBuyCourse;
-        $tableField = 'course_id';
-    } else {
-        $id = intval($_REQUEST['session_id']);
-        $tableBuy = $tableBuySession;
-        $tableField = 'session_id';
-    }
-
-    $visible = intval($_REQUEST['visible']);
-    $price = Database::escape_string($_REQUEST['price']);
-
-    $sql = "UPDATE $tableBuy
-        SET visible = " . $visible . ",
-        price = '" . $price . "'
-        WHERE " . $tableField . " = '" . $id . "';";
-
-    $res = Database::query($sql);
-    if (!$res) {
-        $content = $plugin->get_lang('ProblemToSaveTheMessage');
-        echo json_encode(array("status" => "false", "content" => $content));
+        $productId = $_REQUEST['course_id'];
+        $productType = BuyCoursesPlugin::PRODUCT_TYPE_COURSE;
     } else {
-        echo json_encode(array("status" => "true", "course_id" => $id));
-    }
-}
-
-if ($_REQUEST['tab'] == 'unset_variables') {
-    unset($_SESSION['bc_user_id']);
-    unset($_SESSION['bc_registered']);
-    unset($_SESSION['bc_code']);
-    unset($_SESSION['bc_title']);
-    unset($_SESSION["Payment_Amount"]);
-    unset($_SESSION["currencyCodeType"]);
-    unset($_SESSION["PaymentType"]);
-    unset($_SESSION["nvpReqArray"]);
-    unset($_SESSION['TOKEN']);
-    $_SESSION['bc_success'] = false;
-    $_SESSION['bc_message'] = 'CancelOrder';
-    unset($_SESSION['bc_url']);
-}
-
-if ($_REQUEST['tab'] == 'clear_order') {
-    $id = substr(intval($_REQUEST['id']), 6);
-    $sql = "DELETE FROM $tableBuyCourseTemporal WHERE cod='" . $id . "';";
-
-    $res = Database::query($sql);
-    if (!$res) {
-        $content = $plugin->get_lang('ProblemToDeleteTheAccount');
-        echo json_encode(array("status" => "false", "content" => $content));
+        $productId = $_REQUEST['session_id'];
+        $productType = BuyCoursesPlugin::PRODUCT_TYPE_SESSION;
+    }
+
+    $affectedRows = false;
+
+    if ($_POST['visible'] == 1) {
+        $item = Database::select(
+            'COUNT(1) AS qty',
+            $itemTable,
+            [
+                'where' => [
+                    'product_id = ? AND ' => intval($productId),
+                    'product_type = ?' => $productType
+                ]
+            ],
+            'first'
+        );
+
+        if ($item['qty'] > 0) {
+            $affectedRows = Database::update(
+                $itemTable,
+                ['price' => floatval($_POST['price'])],
+                [
+                    'product_id = ? AND ' => intval($productId),
+                    'product_type' => $productType
+                ]
+            );
+        } else {
+            $affectedRows = Database::insert(
+                $itemTable,
+                [
+                    'currency_id' => $currency['id'],
+                    'product_type' => $productType,
+                    'product_id' => intval($productId),
+                    'price' => floatval($_POST['price'])
+                ]
+            );
+        }
     } else {
-        $content = get_lang('Saved');
-        echo json_encode(array("status" => "true", "content" => $content));
-    }
-}
-
-if ($_REQUEST['tab'] == 'confirm_order') {
-    $id = substr(intval($_REQUEST['id']), 6);
-    $sql = "SELECT * FROM $tableBuyCourseTemporal WHERE cod='" . $id . "';";
-    $res = Database::query($sql);
-    $row = Database::fetch_assoc($res);
-
-    $isAllowed = false;
-    $user_id = $row['user_id'];
-    $course_code = $row['course_code'];
-    $all_course_information = CourseManager::get_course_information($course_code);
-
-    if (CourseManager::subscribe_user($user_id, $course_code)) {
-        $isAllowed = true;
+        $affectedRows = Database::delete(
+            $itemTable,
+            [
+                'product_id = ? AND ' => intval($productId),
+                'product_type = ?' => $productType
+            ]
+        );
+    }
+
+    if ($affectedRows > 0) {
+        $jsonResult = [
+            "status" => true,
+            "itemId" => $productId
+        ];
     } else {
-        $isAllowed = false;
+        $jsonResult = [
+            "status" => false,
+            "content" => $plugin->get_lang('ItemNotSaved')
+        ];
     }
-    //Activate user account
-    if ($isAllowed) {
-        // 1. set account inactive
-        $sql = "UPDATE $tableUser SET active = '1' WHERE user_id = " . intval($_SESSION['bc_user_id']) . "";
-        Database::query($sql);
 
-        $sql = "DELETE FROM $tableBuyCourseTemporal WHERE cod='" . $id . "';";
-        $res = Database::query($sql);
-
-        $content = $plugin->get_lang('TheSubscriptionAndActivationWereDoneSuccessfully');
-        echo json_encode(array("status" => "true", "content" => $content));
-    } else {
-        $content = $plugin->get_lang('ProblemToSubscribeTheUser');
-        echo json_encode(array("status" => "false", "content" => $content));
-    }
+    echo json_encode($jsonResult);
+    exit;
 }

+ 12 - 16
plugin/buycourses/src/index.buycourses.php

@@ -11,22 +11,18 @@ $plugin = BuyCoursesPlugin::create();
 $guess_enable = $plugin->get('unregistered_users_enable');
 
 if ($guess_enable == "true" || isset($_SESSION['_user'])) {
-    $isAdmin = api_is_platform_admin();
-    $title = $plugin->get_lang('CourseListOnSale');
-    $templateName = $plugin->get_lang('BuyCourses');
+    // If the user is NOT an administrator, redirect it to course/session buy list
+    if (!api_is_platform_admin()) {
+        header('Location: src/course_catalog.php');
+        exit;
+    }
+
+    $tpl = new Template();
+
+    $content = $tpl->fetch('buycourses/view/index.tpl');
 
-    $tpl = new Template($templateName);
-    $tpl->assign('isAdmin', $isAdmin);
-    $tpl->assign('title', $title);
-    $tpl->assign('BuySessions', $plugin->get_lang('BuySessions'));
-    $tpl->assign('BuyCourses', $templateName);
-    $tpl->assign('ConfigurationOfSessionsAndPrices', $plugin->get_lang('ConfigurationOfSessionsAndPrices'));
-    $tpl->assign('ConfigurationOfCoursesAndPrices', $plugin->get_lang('ConfigurationOfCoursesAndPrices'));
-    $tpl->assign('ConfigurationOfPayments', $plugin->get_lang('ConfigurationOfPayments'));
-    $tpl->assign('OrdersPendingOfPayment', $plugin->get_lang('OrdersPendingOfPayment'));
-    $listing_tpl = 'buycourses/view/index.tpl';
-    $content = $tpl->fetch($listing_tpl);
+    $tpl->assign('header', $plugin->get_lang('plugin_title'));
     $tpl->assign('content', $content);
-    // If the user is NOT an administrator, redirect it to course/session buy list
-    $isAdmin ? $tpl->display_one_col_template() : header('Location: src/list.php');
+
+    $tpl->display_one_col_template();
 }

+ 0 - 333
plugin/buycourses/src/inscription.php

@@ -1,333 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-/**
- * This script displays a form for registering new users to a course directly
- * @package  chamilo.plugin.buycourses
- */
-/**
- * Init
- */
-use ChamiloSession as Session;
-
-if (!empty($_POST['language'])) { //quick hack to adapt the registration form result to the selected registration language
-    $_GET['language'] = $_POST['language'];
-}
-require_once '../config.php';
-
-if (!empty($_SESSION['user_language_choice'])) {
-    $user_selected_language = $_SESSION['user_language_choice'];
-} elseif (!empty($_SESSION['_user']['language'])) {
-    $user_selected_language = $_SESSION['_user']['language'];
-} else {
-    $user_selected_language = api_get_setting('platformLanguage');
-}
-
-$form = new FormValidator('registration');
-
-if (api_get_setting('allow_terms_conditions') == 'true') {
-    $user_already_registered_show_terms = isset($_SESSION['term_and_condition']['user_id']);
-} else {
-    $user_already_registered_show_terms = false;
-}
-
-//Direct Link Subscription feature #5299
-$course_code_redirect = isset($_REQUEST['c']) && !empty($_REQUEST['c']) ? $_REQUEST['c'] : null;
-$exercise_redirect = isset($_REQUEST['e']) && !empty($_REQUEST['e']) ? $_REQUEST['e'] : null;
-
-if (!empty($course_code_redirect)) {
-    Session::write('course_redirect', $course_code_redirect);
-    Session::write('exercise_redirect', $exercise_redirect);
-}
-
-if ($user_already_registered_show_terms == false) {
-
-    if (api_is_western_name_order()) {
-        //	FIRST NAME and LAST NAME
-        $form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
-        $form->addElement('text', 'lastname', get_lang('LastName'), array('size' => 40));
-    } else {
-        //	LAST NAME and FIRST NAME
-        $form->addElement('text', 'lastname', get_lang('LastName'), array('size' => 40));
-        $form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
-    }
-    $form->applyFilter(array('lastname', 'firstname'), 'trim');
-    $form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
-    $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
-
-    //	EMAIL
-    $form->addElement('text', 'email', get_lang('Email'), array('size' => 40));
-    if (api_get_setting('registration', 'email') == 'true') {
-        $form->addRule('email', get_lang('ThisFieldIsRequired'), 'required');
-    }
-
-    if (api_get_setting('login_is_email') == 'true') {
-        $form->applyFilter('email', 'trim');
-        if (api_get_setting('registration', 'email') != 'true') {
-            $form->addRule('email', get_lang('ThisFieldIsRequired'), 'required');
-        }
-        $form->addRule('email', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
-        $form->addRule('email', get_lang('UserTaken'), 'username_available');
-    }
-
-    $form->addRule('email', get_lang('EmailWrong'), 'email');
-    if (api_get_setting('openid_authentication') == 'true') {
-        $form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => 40));
-    }
-
-    //	USERNAME
-    if (api_get_setting('login_is_email') != 'true') {
-        $form->addElement('text', 'username', get_lang('UserName'), array('size' => USERNAME_MAX_LENGTH));
-        $form->applyFilter('username', 'trim');
-        $form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
-        $form->addRule('username', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
-        $form->addRule('username', get_lang('UsernameWrong'), 'username');
-        $form->addRule('username', get_lang('UserTaken'), 'username_available');
-    }
-
-    //	PASSWORD
-    $form->addElement('password', 'pass1', get_lang('Pass'), array('size' => 20, 'autocomplete' => 'off'));
-    $form->addElement('password', 'pass2', get_lang('Confirmation'), array('size' => 20, 'autocomplete' => 'off'));
-    $form->addRule('pass1', get_lang('ThisFieldIsRequired'), 'required');
-    $form->addRule('pass2', get_lang('ThisFieldIsRequired'), 'required');
-    $form->addRule(array('pass1', 'pass2'), get_lang('PassTwo'), 'compare');
-
-    if (CHECK_PASS_EASY_TO_FIND) {
-        $form->addRule('password1', get_lang('PassTooEasy') . ': ' . api_generate_password(), 'callback', 'api_check_password');
-    }
-
-    //	PHONE
-    $form->addElement('text', 'phone', get_lang('Phone'), array('size' => 20));
-    if (api_get_setting('registration', 'phone') == 'true') {
-        $form->addRule('phone', get_lang('ThisFieldIsRequired'), 'required');
-    }
-
-    //	LANGUAGE
-    if (api_get_setting('registration', 'language') == 'true') {
-        $form->addElement('select_language', 'language', get_lang('Language'));
-    }
-
-}
-
-if (isset($_SESSION['user_language_choice']) && $_SESSION['user_language_choice'] != '') {
-    $defaults['language'] = $_SESSION['user_language_choice'];
-} else {
-    $defaults['language'] = api_get_setting('platformLanguage');
-}
-if (!empty($_GET['username'])) {
-    $defaults['username'] = Security::remove_XSS($_GET['username']);
-}
-if (!empty($_GET['email'])) {
-    $defaults['email'] = Security::remove_XSS($_GET['email']);
-}
-
-if (!empty($_GET['phone'])) {
-    $defaults['phone'] = Security::remove_XSS($_GET['phone']);
-}
-
-if (api_get_setting('openid_authentication') == 'true' && !empty($_GET['openid'])) {
-    $defaults['openid'] = Security::remove_XSS($_GET['openid']);
-}
-$defaults['status'] = STUDENT;
-
-if (is_array($extra_data)) {
-    $defaults = array_merge($defaults, $extra_data);
-}
-
-$form->setDefaults($defaults);
-
-$content = null;
-
-if (api_get_setting('allow_terms_conditions') == 'true') {
-    $get = array_keys($_GET);
-    if (isset($get)) {
-        if ($get[0] == 'legal') {
-            $language = api_get_interface_language();
-            $language = api_get_language_id($language);
-            $term_preview = LegalManager::get_last_condition($language);
-            if (!$term_preview) {
-                //look for the default language
-                $language = api_get_setting('platformLanguage');
-                $language = api_get_language_id($language);
-                $term_preview = LegalManager::get_last_condition($language);
-            }
-            $tool_name = get_lang('TermsAndConditions');
-            Display :: display_header($tool_name);
-
-            if (!empty($term_preview['content'])) {
-                echo $term_preview['content'];
-            } else {
-                echo get_lang('ComingSoon');
-            }
-            Display :: display_footer();
-            exit;
-        }
-    }
-}
-
-$tool_name = get_lang('Registration', null, (!empty($_POST['language']) ? $_POST['language'] : $_user['language']));
-
-if (api_get_setting('allow_terms_conditions') == 'true' && $user_already_registered_show_terms) {
-    $tool_name = get_lang('TermsAndConditions');
-}
-
-$home = api_get_path(SYS_PATH) . 'home/';
-if (api_is_multiple_url_enabled()) {
-    $access_url_id = api_get_current_access_url_id();
-    if ($access_url_id != -1) {
-        $url_info = api_get_access_url($access_url_id);
-        $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $url_info['url']));
-        $clean_url = api_replace_dangerous_char($url);
-        $clean_url = str_replace('/', '-', $clean_url);
-        $clean_url .= '/';
-        $home_old = api_get_path(SYS_PATH) . 'home/';
-        $home = api_get_path(SYS_PATH) . 'home/' . $clean_url;
-    }
-}
-
-if (file_exists($home . 'register_top_' . $user_selected_language . '.html')) {
-    $home_top_temp = @(string)file_get_contents($home . 'register_top_' . $user_selected_language . '.html');
-    $open = str_replace('{rel_path}', api_get_path(REL_PATH), $home_top_temp);
-    $open = api_to_system_encoding($open, api_detect_encoding(strip_tags($open)));
-    if (!empty($open)) {
-        $content = '<div class="well_border">' . $open . '</div>';
-    }
-}
-
-$content .= Display::return_message(get_lang('YourAccountHasToBeApproved'));
-
-// Terms and conditions
-if (api_get_setting('allow_terms_conditions') == 'true') {
-    $language = api_get_interface_language();
-    $language = api_get_language_id($language);
-    $term_preview = LegalManager::get_last_condition($language);
-
-    if (!$term_preview) {
-        //we load from the platform
-        $language = api_get_setting('platformLanguage');
-        $language = api_get_language_id($language);
-        $term_preview = LegalManager::get_last_condition($language);
-
-        //if is false we load from english
-        if (!$term_preview) {
-            $language = api_get_language_id('english'); //this must work
-            $term_preview = LegalManager::get_last_condition($language);
-        }
-    }
-
-    // Version and language
-    $form->addElement('hidden', 'legal_accept_type', $term_preview['version'] . ':' . $term_preview['language_id']);
-    $form->addElement('hidden', 'legal_info', $term_preview['legal_id'] . ':' . $term_preview['language_id']);
-
-    if ($term_preview['type'] == 1) {
-        $form->addElement('checkbox', 'legal_accept', null, get_lang('IHaveReadAndAgree') . '&nbsp;<a href="inscription.php?legal" target="_blank">' . get_lang('TermsAndConditions') . '</a>');
-        $form->addRule('legal_accept', get_lang('ThisFieldIsRequired'), 'required');
-    } else {
-        $preview = LegalManager::show_last_condition($term_preview);
-        $form->addElement('label', null, $preview);
-    }
-}
-
-$form->addElement('button', 'submit', get_lang('RegisterUser'), array('class' => 'btn btn-primary btn-large'));
-
-if ($form->validate()) {
-    $values = $form->exportValues();
-    $values['username'] = api_substr($values['username'], 0, USERNAME_MAX_LENGTH); //make *sure* the login isn't too long
-    $values['status'] = STUDENT;
-    $values['official_code'] = api_strtoupper($values['username']);
-
-    if (api_get_setting('login_is_email') == 'true') {
-        $values['username'] = $values['email'];
-    }
-
-    // Creates a new user
-    $user_id = UserManager::create_user($values['firstname'], $values['lastname'], $values['status'], $values['email'], $values['username'], $values['pass1'], $values['official_code'], $values['language'], $values['phone'], $picture_uri, PLATFORM_AUTH_SOURCE, null, 1, 0, null, null, true);
-
-    // Register extra fields
-    $extras = array();
-    foreach ($values as $key => $value) {
-        if (substr($key, 0, 6) == 'extra_') { //an extra field
-            $extras[substr($key, 6)] = $value;
-        }
-    }
-
-    //update the extra fields
-    $count_extra_field = count($extras);
-    if ($count_extra_field > 0) {
-        foreach ($extras as $key => $value) {
-            UserManager::update_extra_field_value($user_id, $key, $value);
-        }
-    }
-
-    if ($user_id) {
-        // storing the extended profile
-        $store_extended = false;
-        $sql = "UPDATE " . Database::get_main_table(TABLE_MAIN_USER) . " SET ";
-        if (api_get_setting('extended_profile') == 'true' && api_get_setting('extendedprofile_registration', 'mycomptetences') == 'true') {
-            $sql_set[] = "competences = '" . Database::escape_string($values['competences']) . "'";
-            $store_extended = true;
-        }
-        if (api_get_setting('extended_profile') == 'true' && api_get_setting('extendedprofile_registration', 'mydiplomas') == 'true') {
-            $sql_set[] = "diplomas = '" . Database::escape_string($values['diplomas']) . "'";
-            $store_extended = true;
-        }
-        if (api_get_setting('extended_profile') == 'true' && api_get_setting('extendedprofile_registration', 'myteach') == 'true') {
-            $sql_set[] = "teach = '" . Database::escape_string($values['teach']) . "'";
-            $store_extended = true;
-        }
-        if (api_get_setting('extended_profile') == 'true' && api_get_setting('extendedprofile_registration', 'mypersonalopenarea') == 'true') {
-            $sql_set[] = "openarea = '" . Database::escape_string($values['openarea']) . "'";
-            $store_extended = true;
-        }
-        if ($store_extended) {
-            $sql .= implode(',', $sql_set);
-            $sql .= " WHERE user_id = '" . intval($user_id) . "'";
-            Database::query($sql);
-        }
-
-        // if there is a default duration of a valid account then we have to change the expiration_date accordingly
-        if (api_get_setting('account_valid_duration') != '') {
-            $sql = "UPDATE " . Database::get_main_table(TABLE_MAIN_USER) . " SET expiration_date='registration_date+1' WHERE user_id='" . $user_id . "'";
-            Database::query($sql);
-        }
-
-        // if the account has to be approved then we set the account to inactive, sent a mail to the platform admin and exit the page.
-
-        $TABLE_USER = Database::get_main_table(TABLE_MAIN_USER);
-        // 1. set account inactive
-        $sql = "UPDATE " . $TABLE_USER . "	SET active='0' WHERE user_id='" . $user_id . "'";
-        Database::query($sql);
-    }
-
-
-    // Terms & Conditions
-    if (api_get_setting('allow_terms_conditions') == 'true') {
-        // update the terms & conditions
-
-        if (isset($values['legal_accept_type'])) {
-            $cond_array = explode(':', $values['legal_accept_type']);
-            if (!empty($cond_array[0]) && !empty($cond_array[1])) {
-                $time = time();
-                $condition_to_save = intval($cond_array[0]) . ':' . intval($cond_array[1]) . ':' . $time;
-                UserManager::update_extra_field_value($user_id, 'legal_accept', $condition_to_save);
-            }
-        }
-        $values = api_get_user_info($user_id);
-    }
-
-    /* SESSION REGISTERING */
-    /* @todo move this in a function */
-    $_user['firstName'] = stripslashes($values['firstname']);
-    $_user['lastName'] = stripslashes($values['lastname']);
-    $_user['mail'] = $values['email'];
-    $_user['language'] = $values['language'];
-    $_user['user_id'] = $user_id;
-    $_user['username'] = $values['username'];
-    Session::write('bc_user', $_user);
-    header('Location:process.php');
-} else {
-    Display :: display_header($tool_name);
-    echo Display::page_header($tool_name);
-    echo $content;
-    $form->display();
-    Display :: display_footer();
-}

+ 0 - 68
plugin/buycourses/src/list.php

@@ -1,68 +0,0 @@
-<?php
-/**
- * List of courses
- * @package chamilo.plugin.buycourses
- */
-/**
- * Initialization
- */
-
-require_once '../../../main/inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH) . 'plugin.class.php';
-require_once 'buy_course_plugin.class.php';
-require_once 'buy_course.lib.php';
-
-$course_plugin = 'buycourses';
-$plugin = BuyCoursesPlugin::create();
-$_cid = 0;
-
-if (api_is_platform_admin()) {
-    $interbreadcrumb[] = array("url" => "configuration.php", "name" => $plugin->get_lang('AvailableCoursesConfiguration'));
-    $interbreadcrumb[] = array("url" => "paymentsetup.php", "name" => $plugin->get_lang('PaymentsConfiguration'));
-}
-
-$templateName = $plugin->get_lang('CourseListOnSale');
-$tpl = new Template($templateName);
-if (isset($_SESSION['bc_success'])) {
-    $tpl->assign('rmessage', 'YES');
-    if ($_SESSION['bc_success'] == true) {
-        $message = sprintf($plugin->get_lang($_SESSION['bc_message']), $_SESSION['bc_url']);
-        unset($_SESSION['bc_url']);
-        $tpl->assign('class', 'confirmation-message');
-    } else {
-        $message = $plugin->get_lang($_SESSION['bc_message']);
-        $tpl->assign('class', 'warning-message');
-    }
-    $tpl->assign('responseMessage', $message);
-    unset($_SESSION['bc_success']);
-    unset($_SESSION['bc_message']);
-
-} else {
-    $tpl->assign('rmessage', 'NO');
-}
-
-$courseList = userCourseList();
-$categoryList = buyCourseListCategories();
-$currencyType = findCurrency();
-
-$tpl->assign('server', $_configuration['root_web']);
-$tpl->assign('courses', $courseList);
-$tpl->assign('category', $categoryList);
-$tpl->assign('currency', $currencyType);
-
-$selectedValue = Database::select(
-    'selected_value',
-    Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT),
-    array('where'=> array('variable = ?' => array('buycourses_include_sessions')))
-);
-$result = array_shift($selectedValue);
-
-if ($result['selected_value'] === 'true') {
-    $tpl->assign('sessionsAreIncluded', 'YES');
-    $tpl->assign('sessions', userSessionList());
-}
-
-$listing_tpl = 'buycourses/view/list.tpl';
-$content = $tpl->fetch($listing_tpl);
-$tpl->assign('content', $content);
-$tpl->display_one_col_template();

+ 162 - 40
plugin/buycourses/src/paymentsetup.php

@@ -7,48 +7,170 @@
 /**
  * Initialization
  */
-require_once dirname(__FILE__) . '/buy_course.lib.php';
+$cidReset = true;
+
 require_once '../../../main/inc/global.inc.php';
-require_once 'buy_course_plugin.class.php';
-$plugin = BuyCoursesPlugin::create();
-$_cid = 0;
-$templateName = $plugin->get_lang('PaymentConfiguration');
-$interbreadcrumb[] = array("url" => "list.php", "name" => $plugin->get_lang('CourseListOnSale'));
-$interbreadcrumb[] = array("url" => "configuration.php", "name" => $plugin->get_lang('AvailableCoursesConfiguration'));
 
-$tpl = new Template($templateName);
-$teacher = api_is_platform_admin();
 api_protect_admin_script(true);
 
-if ($teacher) {
-    // Sync course table with the plugin
-    $listCurrency = listCurrency();
-    $paypalParams = paypalParameters();
-    $transferParams = transferParameters();
-
-    $confirmationImg = api_get_path(WEB_PLUGIN_PATH) . 'buycourses/resources/message_confirmation.png';
-    $saveImg = api_get_path(WEB_PLUGIN_PATH) . 'buycourses/resources/save.png';
-    $moreImg = api_get_path(WEB_PLUGIN_PATH) . 'buycourses/resources/img/32/new.png';
-    $deleteImg = api_get_path(WEB_PLUGIN_PATH) . 'buycourses/resources/img/32/delete.png';
-    $showImg = api_get_path(WEB_PLUGIN_PATH) . 'buycourses/resources/acces_tool.gif';
-
-    $paypalEnable = $plugin->get('paypal_enable');
-    $transferEnable = $plugin->get('transfer_enable');
-
-    $tpl->assign('server', $_configuration['root_web']);
-    $tpl->assign('currencies', $listCurrency);
-    $tpl->assign('paypal', $paypalParams);
-    $tpl->assign('transfer', $transferParams);
-    $tpl->assign('confirmation_img', $confirmationImg);
-    $tpl->assign('save_img', $saveImg);
-    $tpl->assign('more_img', $moreImg);
-    $tpl->assign('delete_img', $deleteImg);
-    $tpl->assign('show_img', $showImg);
-    $tpl->assign('paypal_enable', $paypalEnable);
-    $tpl->assign('transfer_enable', $transferEnable);
-
-    $listing_tpl = 'buycourses/view/paymentsetup.tpl';
-    $content = $tpl->fetch($listing_tpl);
-    $tpl->assign('content', $content);
-    $tpl->display_one_col_template();
+$plugin = BuyCoursesPlugin::create();
+
+$paypalEnable = $plugin->get('paypal_enable');
+$transferEnable = $plugin->get('transfer_enable');
+
+if (isset($_GET['action'], $_GET['id'])) {
+    if ($_GET['action'] == 'delete_taccount') {
+        $plugin->deleteTransferAccount($_GET['id']);
+
+        Display::addFlash(
+            Display::return_message(get_lang('ItemRemoved'), 'success')
+        );
+
+        header('Location: ' . api_get_self());
+        exit;
+    }
 }
+
+$currencyForm = new FormValidator('currency');
+
+if ($currencyForm->validate()) {
+    $currencyFormValues = $currencyForm->getSubmitValues();
+
+    $plugin->selectCurrency($currencyFormValues['currency']);
+
+    Display::addFlash(
+        Display::return_message(get_lang('Saved'), 'success')
+    );
+
+    header('Location:' . api_get_self());
+    exit;
+}
+
+$currencies = $plugin->getCurrencies();
+
+$currencySelect = $currencyForm->addSelect(
+    'currency',
+    [
+        $plugin->get_lang('CurrencyType'),
+        $plugin->get_lang('InfoCurrency')
+    ],
+    [get_lang('Select')]
+);
+
+foreach ($currencies as $currency) {
+    $currencyText = implode(
+        ' => ',
+        [
+            $currency['country_name'],
+            $currency['iso_code']
+        ]
+    );
+    $currencyValue = $currency['id'];
+
+    $currencySelect->addOption($currencyText, $currencyValue);
+
+    if ($currency['status']) {
+        $currencySelect->setSelected($currencyValue);
+    }
+}
+
+$currencyForm->addButtonSave(get_lang('Save'));
+
+$paypalForm = new FormValidator('paypal');
+
+if ($paypalForm->validate()) {
+    $paypalFormValues = $paypalForm->getSubmitValues();
+
+    $plugin->savePaypalParams($paypalFormValues);
+
+    Display::addFlash(
+        Display::return_message(get_lang('Saved'), 'success')
+    );
+
+    header('Location:' . api_get_self());
+    exit;
+}
+
+$paypalForm->addText(
+    'username',
+    $plugin->get_lang('ApiUsername'),
+    false,
+    ['cols-size' => [3, 8, 1]]
+);
+$paypalForm->addText(
+    'password',
+    $plugin->get_lang('ApiPassword'),
+    false,
+    ['cols-size' => [3, 8, 1]]
+);
+$paypalForm->addText(
+    'signature',
+    $plugin->get_lang('ApiSignature'),
+    false,
+    ['cols-size' => [3, 8, 1]]
+);
+$paypalForm->addCheckBox('sandbox', null, $plugin->get_lang('Sandbox'));
+$paypalForm->addButtonSave(get_lang('Save'));
+$paypalForm->setDefaults($plugin->getPaypalParams());
+
+$transferForm = new FormValidator('transfer_account');
+
+if ($transferForm->validate()) {
+    $transferFormValues = $transferForm->getSubmitValues();
+
+    $plugin->saveTransferAccount($transferFormValues);
+
+    Display::addFlash(
+        Display::return_message(get_lang('Saved'), 'success')
+    );
+
+    header('Location:' . api_get_self());
+    exit;
+}
+
+$transferForm->addText(
+    'tname',
+    get_lang('Name'),
+    false,
+    ['cols-size' => [3, 8, 1]]
+);
+$transferForm->addText(
+    'taccount',
+    $plugin->get_lang('BankAccount'),
+    false,
+    ['cols-size' => [3, 8, 1]]
+);
+$transferForm->addText(
+    'tswift',
+    get_lang('SWIFT'),
+    false,
+    ['cols-size' => [3, 8, 1]]
+);
+$transferForm->addButtonCreate(get_lang('Add'));
+
+$transferAccounts = $plugin->getTransferAccounts();
+
+//view
+$interbreadcrumb[] = [
+    'url' => 'course_catalog.php',
+    'name' => $plugin->get_lang('CourseListOnSale')
+];
+$interbreadcrumb[] = [
+    'url' => 'configuration.php',
+    'name' => $plugin->get_lang('AvailableCoursesConfiguration')
+];
+
+$templateName = $plugin->get_lang('PaymentsConfiguration');
+$tpl = new Template($templateName);
+$tpl->assign('header', $templateName);
+$tpl->assign('curency_form', $currencyForm->returnForm());
+$tpl->assign('paypal_form', $paypalForm->returnForm());
+$tpl->assign('transfer_form', $transferForm->returnForm());
+$tpl->assign('transfer_accounts', $transferAccounts);
+$tpl->assign('paypal_enable', $paypalEnable);
+$tpl->assign('transfer_enable', $transferEnable);
+
+$content = $tpl->fetch('buycourses/view/paymentsetup.tpl');
+
+$tpl->assign('content', $content);
+$tpl->display_one_col_template();

+ 9 - 0
plugin/buycourses/src/paypalfunctions.php

@@ -215,6 +215,15 @@ function ConfirmPayment($FinalPaymentAmt)
 
     $nvpstr = '&TOKEN=' . $token . '&PAYERID=' . $payerID . '&PAYMENTREQUEST_0_PAYMENTACTION=' . $paymentType . '&PAYMENTREQUEST_0_AMT=' . $FinalPaymentAmt;
     $nvpstr .= '&PAYMENTREQUEST_0_CURRENCYCODE=' . $currencyCodeType . '&IPADDRESS=' . $serverName;
+    $nvpstr = '&' . http_build_query([
+        'TOKEN' => $token,
+        'PAYERID' => $payerID,
+        'PAYMENTACTION' => $paymentType,
+        'PAYMENTREQUEST_0_AMT' => $FinalPaymentAmt,
+        'PAYMENTREQUEST_0_CURRENCYCODE' => $currencyCodeType,
+        'IPADDRESS' => $serverName,
+        'paymentactionspecified' => 'true'
+    ]);
 
     /**
      * Make the call to PayPal to finalize payment

+ 0 - 40
plugin/buycourses/src/pending_orders.php

@@ -1,40 +0,0 @@
-<?php
-/* For license terms, see /license.txt */
-/**
- * List of pending payments of the Buy Courses plugin
- * @package chamilo.plugin.buycourses
- */
-/**
- * Initialization
- */
-require_once '../config.php';
-require_once dirname(__FILE__) . '/buy_course.lib.php';
-
-$plugin = BuyCoursesPlugin::create();
-$_cid = 0;
-$tableName = $plugin->get_lang('AvailableCoursesConfiguration');
-$interbreadcrumb[] = array("url" => "list.php", "name" => $plugin->get_lang('CourseListOnSale'));
-$interbreadcrumb[] = array("url" => "paymentsetup.php", "name" => $plugin->get_lang('PaymentsConfiguration'));
-
-$tpl = new Template($tableName);
-
-$teacher = api_is_platform_admin();
-api_protect_admin_script(true);
-
-if ($teacher) {
-    $pendingList = pendingList($_SESSION['bc_codetext']);
-    $confirmationImg = api_get_path(WEB_PLUGIN_PATH) . 'buycourses/resources/message_confirmation.png';
-    $deleteImg = api_get_path(WEB_PLUGIN_PATH) . 'buycourses/resources/delete.png';
-    $currencyType = findCurrency();
-
-    $tpl->assign('server', $_configuration['root_web']);
-    $tpl->assign('pending', $pendingList);
-    $tpl->assign('confirmation_img', $confirmationImg);
-    $tpl->assign('delete_img', $deleteImg);
-    $tpl->assign('currency', $currencyType);
-
-    $listing_tpl = 'buycourses/view/pending_orders.tpl';
-    $content = $tpl->fetch($listing_tpl);
-    $tpl->assign('content', $content);
-    $tpl->display_one_col_template();
-}

+ 73 - 84
plugin/buycourses/src/process.php

@@ -8,106 +8,95 @@
  * Initialization
  */
 require_once '../config.php';
-require_once dirname(__FILE__) . '/buy_course.lib.php';
 
-$plugin = BuyCoursesPlugin::create();
-$_cid = 0;
-$templateName = $plugin->get_lang('PaymentMethods');
-$interbreadcrumb[] = array("url" => "list.php", "name" => $plugin->get_lang('CourseListOnSale'));
+$currentUserId = api_get_user_id();
 
-$tpl = new Template($templateName);
+if (empty($currentUserId)) {
+    header('Location: ' . api_get_path(WEB_CODE_PATH) . 'auth/inscription.php');
+    exit;
+}
+
+$plugin = BuyCoursesPlugin::create();
+$includeSession = $plugin->get('include_sessions') === 'true';
+$paypalEnabled = $plugin->get('paypal_enable') === 'true';
+$transferEnabled = $plugin->get('transfer_enable') === 'true';
 
-if (!empty($_GET['code'])) {
-    $codeType = "COURSE";
-    $code = (int)$_GET['code'];
-} else if (!empty($_GET['scode'])) {
-    $codeType = "SESSION";
-    $code = (int)$_GET['scode'];
-} else {
-    $code = $_SESSION['bc_code'];
+if (!isset($_REQUEST['t'], $_REQUEST['i'])) {
+    die;
 }
 
-$selectedValue = Database::select(
-    'selected_value',
-    Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT),
-    array('where'=> array('variable = ?' => array('buycourses_include_sessions')))
-);
-$result = array_shift($selectedValue);
-
-if ($codeType === 'SESSION' && $result['selected_value'] === 'true') {
-    $tableSession = Database::get_main_table(TABLE_MAIN_SESSION);
-    $tableBuySession = Database::get_main_table(TABLE_BUY_SESSION);
-    $sql = "SELECT a.session_id, a.name, a.date_start, a.date_end, a.price
-    FROM $tableBuySession a, $tableSession b
-    WHERE a.session_id = ".$code."
-    AND a.session_id = b.id;";
-    $res = Database::query($sql);
-    $row = Database::fetch_assoc($res);
-    $_SESSION['bc_title'] = $row['name'];
-    $_SESSION['bc_codetext'] = 'THIS_IS_A_SESSION';
-    $tpl->assign('session', sessionInfo($code));
-    $tpl->assign('isSession', 'YES');
-} else {
-    $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
-    $tableBuyCourse = Database::get_main_table(TABLE_BUY_COURSE);
-    $sql = "SELECT a.price, a.title, b.code
-    FROM $tableBuyCourse a, $tableCourse b
-    WHERE a.course_id = " . $code . "
-    AND a.course_id = b.id;";
-    $res = Database::query($sql);
-    $row = Database::fetch_assoc($res);
-    $_SESSION['bc_title'] = $row['title'];
-    $_SESSION['bc_codetext'] = $row['code'];
-    $tpl->assign('course', courseInfo($code));
+$buyingCourse = intval($_REQUEST['t']) === BuyCoursesPlugin::PRODUCT_TYPE_COURSE;
+$buyingSession = intval($_REQUEST['t']) === BuyCoursesPlugin::PRODUCT_TYPE_SESSION;
+
+if ($buyingCourse) {
+    $courseInfo = $plugin->getCourseInfo($_REQUEST['i']);
+    $item = $plugin->getItemByProduct($_REQUEST['i'], BuyCoursesPlugin::PRODUCT_TYPE_COURSE);
+} elseif ($buyingSession) {
+    $sessionInfo = $plugin->getSessionInfo($_REQUEST['i']);
+    $item = $plugin->getItemByProduct($_REQUEST['i'], BuyCoursesPlugin::PRODUCT_TYPE_SESSION);
 }
-$_SESSION['Payment_Amount'] = number_format($row['price'], 2, '.', '');
-$_SESSION['bc_code'] = $code;
-
-if (!isset($_SESSION['_user'])) {
-    //Needs to be Registered
-    if (!isset($_SESSION['bc_user'])) {
-        header('Location:inscription.php');
-        exit;
-    } else {
-        $_SESSION['bc_user_id'] = $_SESSION['bc_user']['user_id'];
-        $tpl->assign('name', $_SESSION['bc_user']['firstName'] . ' ' . $_SESSION['bc_user']['lastName']);
-        $tpl->assign('email', $_SESSION['bc_user']['mail']);
-        $tpl->assign('user', $_SESSION['bc_user']['username']);
+
+$userInfo = api_get_user_info();
+
+$form = new FormValidator('confirm_sale');
+
+if ($form->validate()) {
+    $formValues = $form->getSubmitValues();
+
+    $saleId = $plugin->registerSale($item['id'], $formValues['payment_type']);
+
+    if ($saleId !== false) {
+        $_SESSION['bc_sale_id'] = $saleId;
+        header('Location: ' . api_get_path(WEB_PLUGIN_PATH) . 'buycourses/src/process_confirm.php');  
     }
-} else {
-    $_SESSION['bc_user_id'] = $_SESSION['_user']['user_id'];
-    $_SESSION['bc_user'] = $_SESSION['_user'];
-    $tpl->assign('name', $_SESSION['bc_user']['firstname'] . ' ' . $_SESSION['bc_user']['lastname']);
-    $tpl->assign('email', $_SESSION['bc_user']['email']);
-    $tpl->assign('user', $_SESSION['bc_user']['username']);
+
+    exit;
 }
 
-$currencyType = findCurrency();
+$form->addHeader($plugin->get_lang('UserInformation'));
+$form->addText('name', get_lang('Name'), false, ['cols-size' => [5, 7, 0]]);
+$form->addText('username', get_lang('Username'), false, ['cols-size' => [5, 7, 0]]);
+$form->addText('email', get_lang('EmailAddress'), false, ['cols-size' => [5, 7, 0]]);
+$form->addHeader($plugin->get_lang('PaymentMethods'));
 
-$paypalEnable = $plugin->get('paypal_enable');
-$transferEnable = $plugin->get('transfer_enable');
+$paymentTypesOptions = $plugin->getPaymentTypes();
 
+if (!$paypalEnabled) {
+    unset($paymentTypesOptions[BuyCoursesPlugin::PAYMENT_TYPE_PAYPAL]);
+}
 
-if (checkUserBuy($_SESSION['bc_codetext'], $_SESSION['bc_user_id'], $codeType)) {
-    $_SESSION['bc_success'] = false;
-    $_SESSION['bc_message'] = 'AlreadyBuy';
-    header('Location: list.php');
+if (!$transferEnabled) {
+    unset($paymentTypesOptions[BuyCoursesPlugin::PAYMENT_TYPE_TRANSFER]);
 }
 
-if (checkUserBuyTransfer($_SESSION['bc_codetext'], $_SESSION['bc_user_id'], $codeType)) {
-    $_SESSION['bc_success'] = false;
-    $_SESSION['bc_message'] = 'bc_tmp_registered';
-    header('Location: list.php');
+$form->addRadio('payment_type', null, $paymentTypesOptions);
+$form->addHidden('t', intval($_GET['t']));
+$form->addHidden('i', intval($_GET['i']));
+$form->freeze(['name', 'username', 'email']);
+$form->setDefaults([
+    'name' => $userInfo['complete_name'],
+    'username' => $userInfo['username'],
+    'email' => $userInfo['email']
+]);
+$form->addButton('submit', $plugin->get_lang('ConfirmOrder'), 'check', 'success');
+
+// View
+$templateName = $plugin->get_lang('PaymentMethods');
+$interbreadcrumb[] = array("url" => "course_catalog.php", "name" => $plugin->get_lang('CourseListOnSale'));
+
+$tpl = new Template($templateName);
+$tpl->assign('buying_course', $buyingCourse);
+$tpl->assign('buying_session', $buyingSession);
+$tpl->assign('user', api_get_user_info());
+$tpl->assign('form', $form->returnForm());
+
+if ($buyingCourse) {
+    $tpl->assign('course', $courseInfo);
+} elseif ($buyingSession) {
+    $tpl->assign('session', $sessionInfo);
 }
 
-$tpl->assign('server', $_configuration['root_web']);
-$tpl->assign('paypal_enable', $paypalEnable);
-$tpl->assign('transfer_enable', $transferEnable);
-$tpl->assign('title', $_SESSION['bc_title']);
-$tpl->assign('price', $_SESSION['Payment_Amount']);
-$tpl->assign('currency', $currencyType);
+$content = $tpl->fetch('buycourses/view/process.tpl');
 
-$listing_tpl = 'buycourses/view/process.tpl';
-$content = $tpl->fetch($listing_tpl);
 $tpl->assign('content', $content);
 $tpl->display_one_col_template();

+ 144 - 145
plugin/buycourses/src/process_confirm.php

@@ -8,156 +8,155 @@
  * Init
  */
 require_once '../config.php';
-require_once dirname(__FILE__) . '/buy_course.lib.php';
 
-if ($_POST['payment_type'] == '') {
-    header('Location:process.php');
-}
+$plugin = BuyCoursesPlugin::create();
 
-$tableBuyCourseTemporal = Database::get_main_table(TABLE_BUY_COURSE_TEMPORAL);
-$tableBuyCoursePaypal = Database::get_main_table(TABLE_BUY_COURSE_PAYPAL);
-
-if (isset($_POST['Confirm'])) {
-    // Save the user, course and reference in a tmp table
-    $user_id = $_SESSION['bc_user_id'];
-    $reference = calculateReference($_SESSION['bc_codetext']);
-
-    reset($_POST);
-    while (list ($param, $val) = each($_POST)) {
-        $asignacion = "\$" . $param . "=mysql_real_escape_string(\$_POST['" . $param . "']);";
-        eval($asignacion);
-    }
-
-    $sql = $_SESSION['bc_codetext'] === 'THIS_IS_A_SESSION' ?
-        "INSERT INTO $tableBuySessionTemporal (user_id, name, session_id, title, reference, price)
-        VALUES ('" . $user_id . "', '" . $name . "','" . $_SESSION['bc_code'] . "','" . $title . "','" . $reference . "','" . $price . "');" :
-        "INSERT INTO $tableBuyCourseTemporal (user_id, name, course_code, title, reference, price)
-        VALUES ('" . $user_id . "', '" . $name . "','" . $_SESSION['bc_codetext'] . "','" . $title . "','" . $reference . "','" . $price . "');";
-    $res = Database::query($sql);
-
-    // Notify the user and send the bank info
-
-    $accountsList = listAccounts();
-    $text = '<div align="center"><table style="width:70%"><tr><th style="text-align:center"><h3>Datos Bancarios</h3></th></tr>';
-    foreach ($accountsList as $account) {
-        $text .= '<tr>';
-        $text .= '<td>';
-        $text .= '<font color="#0000FF"><strong>' . htmlspecialchars($account['name']) . '</strong></font><br />';
-        if ($account['swift'] != '') {
-            $text .= 'SWIFT: <strong>' . htmlspecialchars($account['swift']) . '</strong><br />';
-        }
-        $text .= 'Cuenta Bancaria: <strong>' . htmlspecialchars($account['account']) . '</strong><br />';
-        $text .= '</td></tr>';
-    }
-    $text .= '</table></div>';
-
-    $plugin = BuyCoursesPlugin::create();
-    $asunto = utf8_encode($plugin->get_lang('bc_subject'));
-
-
-    if (!isset($_SESSION['_user'])) {
-        $name = $_SESSION['bc_user']['firstName'] . ' ' . $_SESSION['bc_user']['lastName'];
-        $email = $_SESSION['bc_user']['mail'];
-    } else {
-        $name = $_SESSION['bc_user']['firstname'] . ' ' . $_SESSION['bc_user']['lastname'];
-        $email = $_SESSION['bc_user']['email'];
-    }
-
-    $message = $plugin->get_lang('bc_message');
-    $message = str_replace("{{name}}", $name, $message);
-    $_SESSION['bc_codetext'] === 'THIS_IS_A_SESSION' ?
-        $message = str_replace("{{session}}", sessionInfo($_SESSION['bc_code'])['name'], $message) :
-        $message = str_replace("{{course}}", courseInfo($_SESSION['bc_code'])['title'], $message);
-    $message = str_replace("{{".$parameterName."}}", $title, $message);
-    $message = str_replace("{{reference}}", $reference, $message);
-    $message .= $text;
-
-    api_mail_html($name, $email, $asunto, $message);
-    // Return to course list
-    header('Location:list.php');
+$saleId = $_SESSION['bc_sale_id'];
+
+if (empty($saleId)) {
+    api_not_allowed(true);
 }
 
+$sale = $plugin->getSale($saleId);
 
-$currencyType = $_POST['currency_type'];
-$_SESSION['bc_currency_type'] = $currencyType;
-$server = $_POST['server'];
-
-if ($_POST['payment_type'] == "PayPal") {
-    $sql = "SELECT * FROM $tableBuyCoursePaypal WHERE id='1';";
-    $res = Database::query($sql);
-    $row = Database::fetch_assoc($res);
-    $pruebas = ($row['sandbox'] == "YES") ? true: false;
-    $paypalUsername = $row['username'];
-    $paypalPassword = $row['password'];
-    $paypalSignature = $row['signature'];
-    require_once("paypalfunctions.php");
-    // PayPal Express Checkout Module
-    $paymentAmount = $_SESSION["Payment_Amount"];
-    $currencyCodeType = $currencyType;
-    $paymentType = "Sale";
-    $returnURL = $server . "plugin/buycourses/src/success.php";
-    $cancelURL = $server . "plugin/buycourses/src/error.php";
-
-
-    $title = $_SESSION['bc_codetext'] === 'THIS_IS_A_SESSION' ?
-        sessionInfo($_SESSION['bc_code'])['name'] :
-        courseInfo($_SESSION['bc_code'])['title'];
-
-    $i = 0;
-    $extra = "&L_PAYMENTREQUEST_0_NAME" . $i . "=" . $title;
-    $extra .= "&L_PAYMENTREQUEST_0_AMT" . $i . "=" . $paymentAmount;
-    $extra .= "&L_PAYMENTREQUEST_0_QTY" . $i . "=1";
-
-    $resArray = CallShortcutExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $extra);
-    $ack = strtoupper($resArray["ACK"]);
-
-    if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
-        RedirectToPayPal($resArray["TOKEN"]);
-    } else {
-        $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
-        $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
-        $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
-        $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
-
-        echo "<br />SetExpressCheckout API call failed. ";
-        echo "<br />Detailed Error Message: " . $ErrorLongMsg;
-        echo "<br />Short Error Message: " . $ErrorShortMsg;
-        echo "<br />Error Code: " . $ErrorCode;
-        echo "<br />Error Severity Code: " . $ErrorSeverityCode;
-    }
+if (empty($sale)) {
+    api_not_allowed(true);
 }
 
-if ($_POST['payment_type'] == "Transfer") {
-    $_cid = 0;
-    $templateName = $plugin->get_lang('PaymentMethods');
-    $interbreadcrumb[] = array("url" => "list.php", "name" => $plugin->get_lang('CourseListOnSale'));
-
-    $tpl = new Template($templateName);
-
-    $_SESSION['bc_codetext'] === 'THIS_IS_A_SESSION' ?
-        $tpl->assign('session', sessionInfo($_SESSION['bc_code'])) :
-        $tpl->assign('course', courseInfo($_SESSION['bc_code']));
-
-    $tpl->assign('server', $_configuration['root_web']);
-    $tpl->assign('title', $_SESSION['bc_title']);
-    $tpl->assign('price', $_SESSION['Payment_Amount']);
-    $tpl->assign('currency', $_SESSION['bc_currency_type']);
-    if (!isset($_SESSION['_user'])) {
-        $tpl->assign('name', $_SESSION['bc_user']['firstName'] . ' ' . $_SESSION['bc_user']['lastName']);
-        $tpl->assign('email', $_SESSION['bc_user']['mail']);
-        $tpl->assign('user', $_SESSION['bc_user']['username']);
-    } else {
-        $tpl->assign('name', $_SESSION['bc_user']['firstname'] . ' ' . $_SESSION['bc_user']['lastname']);
-        $tpl->assign('email', $_SESSION['bc_user']['email']);
-        $tpl->assign('user', $_SESSION['bc_user']['username']);
-    }
-
-    //Get bank list account
-    $accountsList = listAccounts();
-    $tpl->assign('accounts', $accountsList);
-
-    $listing_tpl = 'buycourses/view/process_confirm.tpl';
-    $content = $tpl->fetch($listing_tpl);
-    $tpl->assign('content', $content);
-    $tpl->display_one_col_template();
+$currency = $plugin->getCurrency($sale['currency_id']);
+
+switch ($sale['payment_type']) {
+    case BuyCoursesPlugin::PAYMENT_TYPE_PAYPAL:
+        $paypalParams = $plugin->getPaypalParams();
+
+        $pruebas = $paypalParams['sandbox'] == 1;
+        $paypalUsername = $paypalParams['username'];
+        $paypalPassword = $paypalParams['password'];
+        $paypalSignature = $paypalParams['signature'];
+
+        require_once("paypalfunctions.php");
+
+        $i = 0;
+        $extra = "&L_PAYMENTREQUEST_0_NAME0={$sale['product_name']}";
+        $extra .= "&L_PAYMENTREQUEST_0_AMT0={$sale['price']}";
+        $extra .= "&L_PAYMENTREQUEST_0_QTY0=1";
+
+        $expressCheckout = CallShortcutExpressCheckout(
+            $sale['price'],
+            $currency['iso_code'],
+            'paypal',
+            api_get_path(WEB_PLUGIN_PATH) . 'buycourses/src/success.php',
+            api_get_path(WEB_PLUGIN_PATH) . 'buycourses/src/error.php',
+            $extra
+        );
+
+        if ($expressCheckout["ACK"] !== 'Success') {
+            $erroMessage = vsprintf(
+                $plugin->get_lang('ErrorOccurred'),
+                [$expressCheckout['L_ERRORCODE0'], $expressCheckout['L_LONGMESSAGE0']]
+            );
+            Display::addFlash(
+                Display::return_message($erroMessage, 'error', false)
+            );
+            header('Location: ../index.php');
+            exit;
+        }
+
+        RedirectToPayPal($expressCheckout["TOKEN"]);
+        break;
+    case BuyCoursesPlugin::PAYMENT_TYPE_TRANSFER:
+        $buyingCourse = false;
+        $buyingSession = false;
+
+        switch ($sale['product_type']) {
+            case BuyCoursesPlugin::PRODUCT_TYPE_COURSE:
+                $buyingCourse = true;
+                $course = $plugin->getCourseInfo($sale['product_id']);
+                break;
+            case BuyCoursesPlugin::PRODUCT_TYPE_SESSION:
+                $buyingSession = true;
+                $session = $plugin->getSessionInfo($sale['product_id']);
+                break;
+        }
+
+        $transferAccounts = $plugin->getTransferAccounts();
+        $userInfo = api_get_user_info($sale['user_id']);
+
+        $form = new FormValidator('success', 'POST', api_get_self(), null, null, FormValidator::LAYOUT_INLINE);
+
+        if ($form->validate()) {
+            $formValues = $form->getSubmitValues();
+
+            if (isset($formValues['cancel'])) {
+                $plugin->cancelSale($sale['id']);
+
+                unset($_SESSION['bc_sale_id']);
+
+                header('Location: ' . api_get_path(WEB_PLUGIN_PATH) . 'buycourses/index.php');
+                exit;
+            }
+
+            $messageTemplate = new Template();
+            $messageTemplate->assign('user', $userInfo);
+            $messageTemplate->assign(
+                'sale',
+                [
+                    'date' => api_format_date($sale['date'], DATE_FORMAT_LONG_NO_DAY),
+                    'product' => $sale['product_name'],
+                    'currency' => $currency['iso_code'],
+                    'price' => $sale['price'],
+                    'reference' => $sale['reference']
+                ]
+            );
+            $messageTemplate->assign('transfer_accounts', $transferAccounts);
+
+            api_mail_html(
+                $userInfo['complete_name'],
+                $userInfo['email'],
+                $plugin->get_lang('bc_subject'),
+                $messageTemplate->fetch('buycourses/view/message_transfer.tpl')
+            );
+
+            Display::addFlash(
+                Display::return_message(
+                    sprintf(
+                        $plugin->get_lang('PurchaseStatusX'),
+                        $plugin->get_lang('PendingReasonByTransfer')
+                    ),
+                    'success',
+                    false
+                )
+            );
+
+            unset($_SESSION['bc_sale_id']);
+            header('Location: ' . api_get_path(WEB_PLUGIN_PATH) . 'buycourses/src/course_catalog.php');
+            exit;
+        }
+
+        $form->addButton('confirm', $plugin->get_lang('ConfirmOrder'), 'check', 'success');
+        $form->addButtonCancel($plugin->get_lang('CancelOrder'), 'cancel');
+
+        $template = new Template();
+
+        if ($buyingCourse) {
+            $template->assign('course', $course);
+        } elseif ($buyingSession) {
+            $template->assign('session', $session);
+        }
+
+        $template->assign('buying_course', $buyingCourse);
+        $template->assign('buying_session', $buyingSession);
+
+        $template->assign('title', $sale['product_name']);
+        $template->assign('price', $sale['price']);
+        $template->assign('currency', $sale['currency_id']);
+        $template->assign('user', $userInfo);
+        $template->assign('transfer_accounts', $transferAccounts);
+        $template->assign('form', $form->returnForm());
+
+        $content = $template->fetch('buycourses/view/process_confirm.tpl');
+
+        $template->assign('content', $content);
+        $template->display_one_col_template();
+        break;
 }

+ 116 - 0
plugin/buycourses/src/sales_report.php

@@ -0,0 +1,116 @@
+<?php
+/* For license terms, see /license.txt */
+/**
+ * List of pending payments of the Buy Courses plugin
+ * @package chamilo.plugin.buycourses
+ */
+//Initialization
+$cidReset = true;
+
+require_once '../config.php';
+
+api_protect_admin_script();
+
+$plugin = BuyCoursesPlugin::create();
+
+if (isset($_GET['order'])) {
+    $sale = $plugin->getSale($_GET['order']);
+
+    if (empty($sale)) {
+        api_not_allowed(true);
+    }
+
+    $urlToRedirect = api_get_self() . '?';
+
+    switch ($_GET['action']) {
+        case 'confirm':
+            $plugin->completeSale($sale['id']);
+
+            Display::addFlash(
+                Display::return_message(
+                    sprintf($plugin->get_lang('SubscriptionToCourseXSuccessful'), $sale['product_name']),
+                    'success'
+                )
+            );
+
+            $urlToRedirect .= http_build_query([
+                'status' => BuyCoursesPlugin::SALE_STATUS_COMPLETED,
+                'sale' =>  $sale['id']
+            ]);
+            break;
+        case 'cancel':
+            $plugin->cancelSale($sale['id']);
+
+            Display::addFlash(
+                Display::return_message(
+                    $plugin->get_lang('OrderCanceled'),
+                    'warning'
+                )
+            );
+
+            $urlToRedirect .= http_build_query([
+                'status' => BuyCoursesPlugin::SALE_STATUS_CANCELED,
+                'sale' =>  $sale['id']
+            ]);
+            break;
+    }
+
+    header("Location: $urlToRedirect");
+    exit;
+}
+
+$productTypes = $plugin->getProductTypes();
+$saleStatuses = $plugin->getSaleStatuses();
+$selectedStatus = isset($_GET['status']) ? $_GET['status'] : BuyCoursesPlugin::SALE_STATUS_PENDING;
+$selectedSale = isset($_GET['sale']) ? intval($_GET['sale']) : 0;
+
+$form = new FormValidator('search', 'get');
+
+if ($form->validate()) {
+    $selectedStatus = $form->getSubmitValue('status');
+
+    if ($selectedStatus === false) {
+        $selectedStatus = BuyCoursesPlugin::SALE_STATUS_PENDING;
+    }
+}
+
+$form->addSelect('status', $plugin->get_lang('OrderStatus'), $saleStatuses);
+$form->addButtonFilter($plugin->get_lang('SearchByStatus'));
+$form->setDefaults(['status' => $selectedStatus]);
+
+$sales = $plugin->getSaleListByStatus($selectedStatus);
+$saleList = [];
+
+foreach ($sales as $sale) {
+    $saleList[] = [
+        'id' => $sale['id'],
+        'reference' => $sale['reference'],
+        'status' => $sale['status'],
+        'date' => api_format_date($sale['date'], DATE_FORMAT_LONG_NO_DAY),
+        'currency' => $sale['iso_code'],
+        'price' => $sale['price'],
+        'product_name' => $sale['product_name'],
+        'product_type' => $productTypes[$sale['product_type']],
+        'complete_user_name' => api_get_person_name($sale['firstname'], $sale['lastname'])
+    ];
+}
+
+//View
+$interbreadcrumb[] = ['url' => '../index.php', 'name' => $plugin->get_lang('plugin_title')];
+
+$templateName = $plugin->get_lang('SalesReport');
+
+$template = new Template($templateName);
+$template->assign('form', $form->returnForm());
+$template->assign('selected_sale', $selectedSale);
+$template->assign('selected_status', $selectedStatus);
+$template->assign('sale_list', $saleList);
+$template->assign('sale_status_canceled', BuyCoursesPlugin::SALE_STATUS_CANCELED);
+$template->assign('sale_status_pending', BuyCoursesPlugin::SALE_STATUS_PENDING);
+$template->assign('sale_status_completed', BuyCoursesPlugin::SALE_STATUS_COMPLETED);
+
+$content = $template->fetch('buycourses/view/sales_report.tpl');
+
+$template->assign('header', $templateName);
+$template->assign('content', $content);
+$template->display_one_col_template();

+ 76 - 0
plugin/buycourses/src/session_catalog.php

@@ -0,0 +1,76 @@
+<?php
+/**
+ * List of courses
+ * @package chamilo.plugin.buycourses
+ */
+/**
+ * Initialization
+ */
+$cidReset = true;
+
+require_once '../../../main/inc/global.inc.php';
+
+$plugin = BuyCoursesPlugin::create();
+$includeSessions = $plugin->get('include_sessions') === 'true';
+
+if (!$includeSessions) {
+    api_not_allowed(true);
+}
+
+$nameFilter = null;
+$minFilter = 0;
+$maxFilter = 0;
+
+$form = new FormValidator('search_filter_form', 'get', null, null, [], FormValidator::LAYOUT_INLINE);
+
+if ($form->validate()) {
+    $formValues = $form->getSubmitValues();
+    $nameFilter = isset($formValues['name']) ? $formValues['name'] : null;
+    $minFilter = isset($formValues['min']) ? $formValues['min'] : 0;
+    $maxFilter = isset($formValues['max']) ? $formValues['max'] : 0;
+}
+
+$form->addHeader($plugin->get_lang('SearchFilter'));
+$form->addText('name', get_lang('SessionName'), false);
+$form->addElement(
+    'number',
+    'min',
+    $plugin->get_lang('MinimumPrice'),
+    ['step' => '0.01', 'min' => '0']
+);
+$form->addElement(
+    'number',
+    'max',
+    $plugin->get_lang('MaximumPrice'),
+    ['step' => '0.01', 'min' => '0']
+);
+$form->addHtml('<hr>');
+$form->addButtonFilter(get_lang('Search'));
+
+$sessionList = $plugin->getCatalogSessionList($nameFilter, $minFilter, $maxFilter);
+
+//View
+if (api_is_platform_admin()) {
+    $interbreadcrumb[] = [
+        'url' => 'configuration.php',
+        'name' => $plugin->get_lang('AvailableCoursesConfiguration')
+    ];
+    $interbreadcrumb[] = [
+        'url' => 'paymentsetup.php',
+        'name' => $plugin->get_lang('PaymentsConfiguration')
+    ];
+}
+
+$templateName = $plugin->get_lang('CourseListOnSale');
+
+$template = new Template($templateName);
+$template->assign('search_filter_form', $form->returnForm());
+$template->assign('sessions_are_included', $includeSessions);
+$template->assign('showing_sessions', true);
+$template->assign('sessions', $sessionList);
+
+$content = $template->fetch('buycourses/view/catalog.tpl');
+
+$template->assign('header', $templateName);
+$template->assign('content', $content);
+$template->display_one_col_template();

+ 182 - 313
plugin/buycourses/src/success.php

@@ -7,337 +7,206 @@
 /**
  * Init
  */
-use ChamiloSession as Session;
-
 require_once '../config.php';
-require_once dirname(__FILE__) . '/buy_course.lib.php';
-
-$tableBuyCoursePaypal = Database::get_main_table(TABLE_BUY_COURSE_PAYPAL);
 
 $plugin = BuyCoursesPlugin::create();
+$paypalEnabled = $plugin->get('paypal_enable') === 'true';
 
-/**
- * Paypal data
- */
-$sql = "SELECT * FROM $tableBuyCoursePaypal WHERE id='1';";
-$res = Database::query($sql);
-$row = Database::fetch_assoc($res);
-$pruebas = ($row['sandbox'] == "YES") ? true: false;
-$paypalUsername = $row['username'];
-$paypalPassword = $row['password'];
-$paypalSignature = $row['signature'];
-require_once("paypalfunctions.php");
+if (!$paypalEnabled) {
+    api_not_allowed(true);
+}
 
-/**
- * PayPal Express Checkout Call
- */
+$sale = $plugin->getSale($_SESSION['bc_sale_id']);
 
-// Check to see if the Request object contains a variable named 'token'
-$token = "";
-if (isset($_REQUEST['token'])) {
-    $token = $_REQUEST['token'];
+if (empty($sale)) {
+    api_not_allowed(true);
 }
 
-// If the Request object contains the variable 'token' then it means that the user is coming from PayPal site.
-if ($token != "") {
-    $sql = "SELECT * FROM $tableBuyCoursePaypal WHERE id='1';";
-    $res = Database::query($sql);
-    $row = Database::fetch_assoc($res);
-    $paypalUsername = $row['username'];
-    $paypalPassword = $row['password'];
-    $paypalSignature = $row['signature'];
-    require_once 'paypalfunctions.php';
-
-    /**
-     * Calls the GetExpressCheckoutDetails API call
-     * The GetShippingDetails function is defined in PayPalFunctions.jsp
-     *included at the top of this file.
-     */
-    $resArray = GetShippingDetails($token);
-    $ack = strtoupper($resArray["ACK"]);
-    if ($ack == "SUCCESS" || $ack == "SUCESSWITHWARNING") {
-        /**
-         * The information that is returned by the GetExpressCheckoutDetails
-         * call should be integrated by the partner into his Order Review page
-         */
-        $email = $resArray["EMAIL"]; // ' Email address of payer.
-        $payerId = $resArray["PAYERID"]; // ' Unique PayPal customer account identification number.
-        $payerStatus = $resArray["PAYERSTATUS"]; // ' Status of payer. Character length and limitations: 10 single-byte alphabetic characters.
-        $salutation = isset($resArray["SALUTATION"]) ? $resArray["SALUTATION"] : null; // ' Payer's salutation.
-        $firstName = $resArray["FIRSTNAME"]; // ' Payer's first name.
-        $middleName = isset($resArray["MIDDLENAME"]) ? $resArray["MIDDLENAME"] : null; // ' Payer's middle name.
-        $lastName = $resArray["LASTNAME"]; // ' Payer's last name.
-        $suffix = isset($resArray["SUFFIX"]) ? $resArray["SUFFIX"] : null; // ' Payer's suffix.
-        $cntryCode = isset($resArray["COUNTRY_CODE"]) ? $resArray["COUNTRY_CODE"] : null; // ' Payer's country of residence in the form of ISO standard 3166 two-character country codes.
-        $business = isset($resArray["BUSINESS"]) ? $resArray["BUSINESS"] : null; // ' Payer's business name.
-        $shipToName = $resArray["PAYMENTREQUEST_0_SHIPTONAME"]; // ' Person's name associated with this address.
-        $shipToStreet = $resArray["PAYMENTREQUEST_0_SHIPTOSTREET"]; // ' First street address.
-        $shipToStreet2 = isset($resArray["PAYMENTREQUEST_0_SHIPTOSTREET2"]) ? $resArray["PAYMENTREQUEST_0_SHIPTOSTREET2"] : null; // ' Second street address.
-        $shipToCity = $resArray["PAYMENTREQUEST_0_SHIPTOCITY"]; // ' Name of city.
-        $shipToState = $resArray["PAYMENTREQUEST_0_SHIPTOSTATE"]; // ' State or province
-        $shipToCntryCode = $resArray["PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE"]; // ' Country code.
-        $shipToZip = $resArray["PAYMENTREQUEST_0_SHIPTOZIP"]; // ' U.S. Zip code or other country-specific postal code.
-        $addressStatus = $resArray["ADDRESSSTATUS"]; // ' Status of street address on file with PayPal
-        $invoiceNumber = isset($resArray["INVNUM"]) ? $resArray["INVNUM"] : null; // ' Your own invoice or tracking number, as set by you in the element of the same name in SetExpressCheckout request .
-        $phonNumber = isset($resArray["PHONENUM"]) ? $resArray["PHONENUM"] : null; // ' Payer's contact telephone number. Note:  PayPal returns a contact telephone number only if your Merchant account profile settings require that the buyer enter one.
-    } else {
-        //Display a user friendly Error on the page using any of the following error information returned by PayPal
-        $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
-        $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
-        $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
-        $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
-
-        echo "<br />GetExpressCheckoutDetails API call failed. ";
-        echo "<br />Detailed Error Message: " . $ErrorLongMsg;
-        echo "<br />Short Error Message: " . $ErrorShortMsg;
-        echo "<br />Error Code: " . $ErrorCode;
-        echo "<br />Error Severity Code: " . $ErrorSeverityCode;
-    }
+$buyingCourse = false;
+$buyingSession = false;
+
+switch ($sale['product_type']) {
+    case BuyCoursesPlugin::PRODUCT_TYPE_COURSE:
+        $buyingCourse = true;
+        $course = $plugin->getCourseInfo($sale['product_id']);
+        break;
+    case BuyCoursesPlugin::PRODUCT_TYPE_SESSION:
+        $buyingSession = true;
+        $session = $plugin->getSessionInfo($sale['product_id']);
+        break;
 }
 
+$paypalParams = $plugin->getPaypalParams();
+
+$pruebas = $paypalParams['sandbox'] == 1;
+$paypalUsername = $paypalParams['username'];
+$paypalPassword = $paypalParams['password'];
+$paypalSignature = $paypalParams['signature'];
+
+require_once("paypalfunctions.php");
 
-if (!isset($_POST['paymentOption'])) {
-    // Confirm the order
-    $_cid = 0;
-    $templateName = $plugin->get_lang('PaymentMethods');
-    $interbreadcrumb[] = array("url" => "list.php", "name" => $plugin->get_lang('CourseListOnSale'));
+$form = new FormValidator('success', 'POST', api_get_self(), null, null, FormValidator::LAYOUT_INLINE);
+$form->addButton('confirm', $plugin->get_lang('ConfirmOrder'), 'check', 'success');
+$form->addButtonCancel($plugin->get_lang('CancelOrder'), 'cancel');
 
-    $tpl = new Template($templateName);
+if ($form->validate()) {
+    $formValues = $form->getSubmitValues();
 
-    if ($_SESSION['bc_codetext'] === 'THIS_IS_A_SESSION') {
-        $tpl->assign('isSession', 'YES');
-        $tpl->assign('session', sessionInfo($_SESSION['bc_code']));
-    } else {
-        $tpl->assign('course', courseInfo($_SESSION['bc_code']));
+    if (isset($formValues['cancel'])) {
+        $plugin->cancelSale($sale['id']);
+
+        unset($_SESSION['bc_sale_id']);
+
+        header('Location: ' . api_get_path(WEB_PLUGIN_PATH) . 'buycourses/index.php');
+        exit;
     }
 
-    $tpl->assign('server', $_configuration['root_web']);
-    $tpl->assign('title', $_SESSION['bc_title']);
-    $tpl->assign('price', $_SESSION['Payment_Amount']);
-    $tpl->assign('currency', $_SESSION['bc_currency_type']);
-    if (!isset($_SESSION['_user'])) {
-        $tpl->assign('name', $_SESSION['bc_user']['firstName'] . ' ' . $_SESSION['bc_user']['lastName']);
-        $tpl->assign('email', $_SESSION['bc_user']['mail']);
-        $tpl->assign('user', $_SESSION['bc_user']['username']);
-    } else {
-        $tpl->assign('name', $_SESSION['bc_user']['firstname'] . ' ' . $_SESSION['bc_user']['lastname']);
-        $tpl->assign('email', $_SESSION['bc_user']['email']);
-        $tpl->assign('user', $_SESSION['bc_user']['username']);
+    $confirmPayments = ConfirmPayment($sale['price']);
+
+    if ($confirmPayments['ACK'] !== 'Success') {
+        $erroMessage = vsprintf(
+            $plugin->get_lang('ErrorOccurred'),
+            [$expressCheckout['L_ERRORCODE0'], $confirmPayments['L_LONGMESSAGE0']]
+        );
+        Display::addFlash(
+            Display::return_message($erroMessage, 'error', false)
+        );
+        header('Location: ../index.php');
+        exit;
     }
 
+    $transactionId = $confirmPayments["PAYMENTINFO_0_TRANSACTIONID"];
+    $transactionType = $confirmPayments["PAYMENTINFO_0_TRANSACTIONTYPE"];
+
+    switch ($confirmPayments["PAYMENTINFO_0_PAYMENTSTATUS"]) {
+        case 'Completed':
+            $saleIsCompleted = $plugin->completeSale($sale['id']);
+
+            if ($saleIsCompleted && $buyingSession) {
+                Display::addFlash(
+                    Display::return_message(
+                        sprintf($plugin->get_lang('SubscriptionToCourseXSuccessful'), $session['name']),
+                        'success'
+                    )
+                );
+                break;
+            }
 
-    $listing_tpl = 'buycourses/view/success.tpl';
-    $content = $tpl->fetch($listing_tpl);
-    $tpl->assign('content', $content);
-    $tpl->display_one_col_template();
-
-} else {
-    /**
-     * PayPal Express Checkout Call
-     */
-    $PaymentOption = $_POST['paymentOption'];
-    $sql = "SELECT * FROM $tableBuyCoursePaypal WHERE id='1';";
-    $res = Database::query($sql);
-    $row = Database::fetch_assoc($res);
-    $paypalUsername = $row['username'];
-    $paypalPassword = $row['password'];
-    $paypalSignature = $row['signature'];
-    require_once("paypalfunctions.php");
-    if ($PaymentOption == "PayPal") {
-
-        /**
-         * The paymentAmount is the total value of
-         * the shopping cart, that was set
-         * earlier in a session variable
-         * by the shopping cart page
-         */
-        $finalPaymentAmount = $_SESSION["Payment_Amount"];
-
-        /**
-         * Calls the DoExpressCheckoutPayment API call
-         * The ConfirmPayment function is defined in the file PayPalFunctions.jsp,
-         * that is included at the top of this file.
-         */
-        $resArray = ConfirmPayment($finalPaymentAmount);
-        $ack = strtoupper($resArray["ACK"]);
-        if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
-
-            /**
-             * THE PARTNER SHOULD SAVE THE KEY TRANSACTION RELATED INFORMATION LIKE transactionId & orderTime
-             * IN THEIR OWN  DATABASE
-             * AND THE REST OF THE INFORMATION CAN BE USED TO UNDERSTAND THE STATUS OF THE PAYMENT
-             */
-
-            $transactionId = $resArray["PAYMENTINFO_0_TRANSACTIONID"]; // ' Unique transaction ID of the payment. Note:  If the PaymentAction of the request was Authorization or Order, this value is your AuthorizationID for use with the Authorization & Capture APIs.
-            $transactionType = $resArray["PAYMENTINFO_0_TRANSACTIONTYPE"]; //' The type of transaction Possible values: l  cart l  express-checkout
-            $paymentType = $resArray["PAYMENTINFO_0_PAYMENTTYPE"]; //' Indicates whether the payment is instant or delayed. Possible values: l  none l  echeck l  instant
-            $orderTime = $resArray["PAYMENTINFO_0_ORDERTIME"]; //' Time/date stamp of payment
-            $amt = $resArray["PAYMENTINFO_0_AMT"]; //' The final amount charged, including any shipping and taxes from your Merchant Profile.
-            $currencyCode = $resArray["PAYMENTINFO_0_CURRENCYCODE"]; //' A three-character currency code for one of the currencies listed in PayPay-Supported Transactional Currencies. Default: USD.
-            $feeAmt = $resArray["PAYMENTINFO_0_FEEAMT"]; //' PayPal fee amount charged for the transaction
-            $settleAmt = $resArray["PAYMENTINFO_0_SETTLEAMT"]; //' Amount deposited in your PayPal account after a currency conversion.
-            $taxAmt = $resArray["PAYMENTINFO_0_TAXAMT"]; //' Tax charged on the transaction.
-            $exchangeRate = $resArray["PAYMENTINFO_0_EXCHANGERATE"]; //' Exchange rate if a currency conversion occurred. Relevant only if your are billing in their non-primary currency. If the customer chooses to pay with a currency other than the non-primary currency, the conversion occurs in the customer's account.
-
-            /**
-             * Status of the payment:
-             * Completed: The payment has been completed, and the funds have been added successfully to your account balance.
-             * Pending: The payment is pending. See the PendingReason element for more information.
-             */
-
-            $paymentStatus = $resArray["PAYMENTINFO_0_PAYMENTSTATUS"];
-
-            /**
-             * The reason the payment is pending:
-             * none: No pending reason
-             * address: The payment is pending because your customer did not include a confirmed
-             * shipping address and your Payment Receiving Preferences is set such that you want to
-             * manually accept or deny each of these payments. To change your preference, go to the Preferences section of your Profile.
-             * echeck: The payment is pending because it was made by an eCheck that has not yet cleared.
-             * intl: The payment is pending because you hold a non-U.S. account and do not have a withdrawal mechanism.
-             * You must manually accept or deny this payment from your Account Overview.
-             * multi-currency: You do not have a balance in the currency sent, and you do not have your
-             * Payment Receiving Preferences set to automatically convert and accept this payment. You must manually accept or deny this payment.
-             * verify: The payment is pending because you are not yet verified. You must verify your account before you can accept this payment.
-             * other: The payment is pending for a reason other than those listed above. For more information, contact PayPal customer service.
-             */
-            $pendingReason = $resArray["PAYMENTINFO_0_PENDINGREASON"];
-
-            /**
-             * The reason for a reversal if TransactionType is reversal:
-             *  none: No reason code
-             *  chargeback: A reversal has occurred on this transaction due to a chargeback by your customer.
-             *  guarantee: A reversal has occurred on this transaction due to your customer triggering a money-back guarantee.
-             *  buyer-complaint: A reversal has occurred on this transaction due to a complaint about the transaction from your customer.
-             *  refund: A reversal has occurred on this transaction because you have given the customer a refund.
-             *  other: A reversal has occurred on this transaction due to a reason not listed above.
-             */
-
-            $reasonCode = $resArray["PAYMENTINFO_0_REASONCODE"];
-
-            // Insert the user information to activate the user
-            if ($paymentStatus == "Completed") {
-                $userId = $_SESSION['bc_user_id'];
-                if ($_SESSION['bc_codetext'] === 'THIS_IS_A_SESSION') {
-                    $sessionId = $_SESSION['bc_code'];
-                    $all_session_information = SessionManager::fetch($sessionId);
-                    SessionManager::suscribe_users_to_session(
-                        $sessionId,
-                        array($userId),
-                        api_get_session_visibility($sessionId),
-                        false
-                    );
-                    $url = Display::url(
-                        $all_session_information['name'],
-                        api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$sessionId
-                    );
-                    $_SESSION['bc_message'] = 'EnrollToSessionXSuccessful';
-                    $_SESSION['bc_url'] = $url;
-                    $_SESSION['bc_success'] = true;
-                } else {
-                    $course_code = $_SESSION['bc_codetext'];
-                    $all_course_information = CourseManager::get_course_information($course_code);
-                    if (CourseManager::subscribe_user($user_id, $course_code)) {
-                        $send = api_get_course_setting('email_alert_to_teacher_on_new_user_in_course', $course_code);
-                        if ($send == 1) {
-                            CourseManager::email_to_tutor($user_id, $course_code, $send_to_tutor_also = false);
-                        } else if ($send == 2) {
-                            CourseManager::email_to_tutor($user_id, $course_code, $send_to_tutor_also = true);
-                        }
-                        $url = Display::url($all_course_information['title'], api_get_course_url($course_code));
-                        $_SESSION['bc_message'] = 'EnrollToCourseXSuccessful';
-                        $_SESSION['bc_url'] = $url;
-                        $_SESSION['bc_success'] = true;
-                    } else {
-                        $_SESSION['bc_message'] = 'ErrorContactPlatformAdmin';
-                        $_SESSION['bc_success'] = false;
-                    }
-                }
-
-                // Activate the use
-                $TABLE_USER = Database::get_main_table(TABLE_MAIN_USER);
-                $sql = "UPDATE " . $TABLE_USER . "	SET active='1' WHERE user_id='" . $_SESSION['bc_user_id'] . "'";
-                Database::query($sql);
-
-                $user_table = Database::get_main_table(TABLE_MAIN_USER);
-                $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
-                $track_e_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-
-                $sql = "SELECT user.*, a.user_id is_admin, login.login_date
-					FROM $user_table
-					LEFT JOIN $admin_table a
-					ON user.user_id = a.user_id
-					LEFT JOIN $track_e_login login
-					ON user.user_id  = login.login_user_id
-					WHERE user.user_id = '" . $_SESSION['bc_user_id'] . "'
-					ORDER BY login.login_date DESC LIMIT 1";
-
-                $result = Database::query($sql);
-
-                if (Database::num_rows($result) > 0) {
-                    // Extracting the user data
-                    $uData = Database::fetch_array($result);
-
-                    $_user = _api_format_user($uData, false);
-                    $_user['lastLogin'] = api_strtotime($uData['login_date'], 'UTC');
-
-                    $is_platformAdmin = (bool)(!is_null($uData['is_admin']));
-
-                    $is_allowedCreateCourse = (bool)(($uData ['status'] == COURSEMANAGER) or (api_get_setting('drhCourseManagerRights') and $uData['status'] == DRH));
-
-                    ConditionalLogin::check_conditions($uData);
-
-                    Session::write('_user', $_user);
-
-                    UserManager::update_extra_field_value($_user['user_id'], 'already_logged_in', 'true');
-                    Session::write('is_platformAdmin', $is_platformAdmin);
-
-                    Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
-
-                } else {
-                    header('location:' . api_get_path(WEB_PATH));
-                }
-
-                // Delete variables
-                unset($_SESSION['bc_user_id']);
-                unset($_SESSION['bc_code']);
-                unset($_SESSION['bc_codetext']);
-                unset($_SESSION['bc_title']);
-                unset($_SESSION['bc_user']);
-                unset($_SESSION["Payment_Amount"]);
-                unset($_SESSION["sec_token"]);
-                unset($_SESSION["currencyCodeType"]);
-                unset($_SESSION["PaymentType"]);
-                unset($_SESSION["nvpReqArray"]);
-                unset($_SESSION['TOKEN']);
-                header('Location:list.php');
-            } else {
-                $_SESSION['bc_message'] = 'CancelOrder';
-                unset($_SESSION['bc_code']);
-                unset($_SESSION['bc_title']);
-                unset($_SESSION["Payment_Amount"]);
-                unset($_SESSION["currencyCodeType"]);
-                unset($_SESSION["PaymentType"]);
-                unset($_SESSION["nvpReqArray"]);
-                unset($_SESSION['TOKEN']);
-                header('Location:list.php');
+            if ($saleIsCompleted && $buyingCourse) {
+                Display::addFlash(
+                    Display::return_message(
+                        sprintf($plugin->get_lang('SubscriptionToCourseXSuccessful'), $course['title']),
+                        'success'
+                    )
+                );
+                break;
             }
-        } else {
-            //Display a user friendly Error on the page using any of the following error information returned by PayPal
-            $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
-            $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
-            $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
-            $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
-            $_SESSION['bc_message'] = 'ErrorContactPlatformAdmin';
-            unset($_SESSION['bc_code']);
-            unset($_SESSION['bc_codetext']);
-            unset($_SESSION['bc_title']);
-            unset($_SESSION["Payment_Amount"]);
-            unset($_SESSION["currencyCodeType"]);
-            unset($_SESSION["PaymentType"]);
-            unset($_SESSION["nvpReqArray"]);
-            unset($_SESSION['TOKEN']);
-            header('Location:list.php');
-        }
+
+            Display::addFlash(
+                Display::return_message($plugin->get_lang('ErrorContactPlatformAdmin'), 'error')
+            );
+            break;
+        case 'Pending':
+            switch ($confirmPayments["PAYMENTINFO_0_PENDINGREASON"]) {
+                case 'address':
+                    $purchaseStatus = $plugin->get_lang('PendingReasonByAddress');
+                    break;
+                case 'authorization':
+                    $purchaseStatus = $plugin->get_lang('PendingReasonByAuthorization');
+                    break;
+                case 'echeck':
+                    $purchaseStatus = $plugin->get_lang('PendingReasonByEcheck');
+                    break;
+                case 'intl':
+                    $purchaseStatus = $plugin->get_lang('PendingReasonByIntl');
+                    break;
+                case 'multicurrency':
+                    $purchaseStatus = $plugin->get_lang('PendingReasonByMulticurrency');
+                    break;
+                case 'order':
+                    $purchaseStatus = $plugin->get_lang('PendingReasonByOrder');
+                    break;
+                case 'paymentreview':
+                    $purchaseStatus = $plugin->get_lang('PendingReasonByPaymentReview');
+                    break;
+                case 'regulatoryreview':
+                    $purchaseStatus = $plugin->get_lang('PendingReasonByRegulatoryReview');
+                    break;
+                case 'unilateral':
+                    $purchaseStatus = $plugin->get_lang('PendingReasonByUnilateral');
+                    break;
+                case 'upgrade':
+                    $purchaseStatus = $plugin->get_lang('PendingReasonByUpgrade');
+                    break;
+                case 'verify':
+                    $purchaseStatus = $plugin->get_lang('PendingReasonByVerify');
+                    break;
+                case 'other':
+                    //no break
+                default:
+                    $purchaseStatus = $plugin->get_lang('PendingReasonByOther');
+                    break;
+            }
+
+            Display::addFlash(
+                Display::return_message(
+                    sprintf($plugin->get_lang('PurchaseStatusX'), $purchaseStatus),
+                    'warning',
+                    false
+                )
+            );
+            break;
+        default:
+            Display::addFlash(
+                Display::return_message($plugin->get_lang('ErrorContactPlatformAdmin'), 'error')
+            );
+            break;
     }
+
+    unset($_SESSION['bc_sale_id']);
+    header('Location: ' . api_get_path(WEB_PLUGIN_PATH) . 'buycourses/src/course_catalog.php');
+    exit;
+}
+
+$token = isset($_GET['token']) ? $_GET['token'] : null;
+
+if (empty($token)) {
+    api_not_allowed(true);
 }
+
+$shippingDetails = GetShippingDetails($token);
+
+if ($shippingDetails['ACK'] !== 'Success') {
+    $erroMessage = vsprintf(
+        $plugin->get_lang('ErrorOccurred'),
+        [$expressCheckout['L_ERRORCODE0'], $shippingDetails['L_LONGMESSAGE0']]
+    );
+    Display::addFlash(
+        Display::return_message($erroMessage, 'error', false)
+    );
+    header('Location: ../index.php');
+    exit;
+}
+
+$interbreadcrumb[] = array("url" => "course_catalog.php", "name" => $plugin->get_lang('CourseListOnSale'));
+
+$templateName = $plugin->get_lang('PaymentMethods');
+$tpl = new Template($templateName);
+
+if ($buyingCourse) {
+    $tpl->assign('course', $course);
+} elseif ($buyingSession) {
+    $tpl->assign('session', $session);
+}
+
+$tpl->assign('buying_course', $buyingCourse);
+$tpl->assign('buying_session', $buyingSession);
+$tpl->assign('title', $sale['product_name']);
+$tpl->assign('price', $sale['price']);
+$tpl->assign('currency', $sale['currency_id']);
+$tpl->assign('user', api_get_user_info($sale['user_id']));
+$tpl->assign('form', $form->returnForm());
+
+$content = $tpl->fetch('buycourses/view/success.tpl');
+$tpl->assign('content', $content);
+$tpl->display_one_col_template();

+ 112 - 0
plugin/buycourses/view/catalog.tpl

@@ -0,0 +1,112 @@
+<link rel="stylesheet" type="text/css" href="../resources/css/style.css"/>
+
+<div id="buy-courses-tabs">
+    {% if sessions_are_included %}
+        <ul class="nav nav-tabs buy-courses-tabs" role="tablist">
+            <li id="buy-courses-tab" class="{{ showing_courses ? 'active' : '' }}" role="presentation">
+                <a href="course_catalog.php" aria-controls="buy-courses" role="tab">{{ 'Courses'|get_lang }}</a>
+            </li>
+            <li id="buy-sessions-tab" class="{{ showing_sessions ? 'active' : '' }}" role="presentation">
+                <a href="session_catalog.php" aria-controls="buy-sessions" role="tab">{{ 'Sessions'|get_lang }}</a>
+            </li>
+        </ul>
+    {% endif %}
+
+    <div class="tab-content">
+        <div class="tab-pane active" aria-labelledby="buy-sessions-tab" role="tabpanel">
+            <div class="row">
+                <div class="col-md-3">
+                    {{ search_filter_form }}
+                </div>
+                <div class="col-md-9">
+                    <div class="row">
+                        {% if showing_courses %}
+                            {% for course in courses %}
+                                <div class="col-md-4 col-sm-6">
+                                    <div class="thumbnail">
+                                        <img alt="{{ course.title }}" class="img-responsive" src="{{ course.course_img ? course.course_img : 'session_default.png'|icon() }}">
+                                        <div class="caption">
+                                            {% set course_description_url = _p.web_ajax ~ 'course_home.ajax.php?' ~ {'code': course.code, 'a': 'show_course_information'}|url_encode() %}
+                                            <h3>
+                                                <a class="ajax" href="{{ course_description_url }}" data-title="{{ course.title }}">{{ course.title }}</a>
+                                            </h3>
+                                            <ul class="list-unstyled">
+                                                {% for teacher in course.teachers %}
+                                                    <li><i class="fa fa-user"></i> {{ teacher }}</li>
+                                                    {% endfor %}
+                                            </ul>
+                                            <p class="lead text-right">{{ course.currency }} {{ course.price }}</p>
+                                            {% if course.enrolled == "YES" %}
+                                                <div class="alert alert-success">
+                                                    <i class="fa fa-check-square-o fa-fw"></i> {{ 'TheUserIsAlreadyRegisteredInTheCourse'|get_plugin_lang('BuyCoursesPlugin') }}
+                                                </div>
+                                            {% elseif course.enrolled == "NO" %}
+                                                <div class="text-center">
+                                                    <a class="ajax btn btn-primary" title="" href="{{ course_description_url }}" data-title="{{ course.title }}">
+                                                        <i class="fa fa-file-text"></i> {{ 'SeeDescription'|get_plugin_lang('BuyCoursesPlugin') }}
+                                                    </a>
+                                                    <a class="btn btn-success" title="" href="{{ _p.web_plugin ~ 'buycourses/src/process.php?' ~ {'i': course.id, 't': 1}|url_encode() }}">
+                                                        <i class="fa fa-shopping-cart"></i> {{ 'Buy'|get_plugin_lang('BuyCoursesPlugin') }}
+                                                    </a>
+                                                </div>
+                                            {% elseif course.enrolled == "TMP" %}
+                                                <div class="alert alert-info">{{ 'WaitingToReceiveThePayment'|get_plugin_lang('BuyCoursesPlugin') }}</div>
+                                            {% endif %}
+                                        </div>
+                                    </div>
+                                </div>
+                            {% endfor %}
+                        {% endif %}
+
+                        {% if showing_sessions %}
+                            {% for session in sessions %}
+                                <div class="col-md-4 col-sm-6">
+                                    <div class="thumbnail">
+                                        <img alt="{{ session.name }}" class="img-responsive" src="{{ session.image ? session.image : 'session_default.png'|icon() }}">
+                                        <div class="caption">
+                                            <h3>
+                                                <a href="{{ _p.web ~ 'session/' ~ session.id ~ '/about/' }}">{{ session.name }}</a>
+                                            </h3>
+                                            {% if 'show_session_coach'|get_setting == 'true' %}
+                                                <p><i class="fa fa-user fa-fw"></i> {{ session.coach }}</p>
+                                            {% endif %}
+                                            <p><i class="fa fa-calendar fa-fw"></i> {{ session.dates.display }}</p>
+                                            <p class="lead text-right">{{ session.currency }} {{ session.price }}</p>
+                                            <ul class="list-unstyled">
+                                                {% for course in session.courses %}
+                                                    <li>
+                                                        <i class="fa fa-book fa-fw"></i> {{ course.title }}
+                                                        {% if course.coaches|length %}
+                                                            <ul>
+                                                                {% for coach in course.coaches %}
+                                                                    <li>{{ coach }}</li>
+                                                                    {% endfor %}
+                                                            </ul>
+                                                        {% endif %}
+                                                    </li>
+                                                {% endfor %}
+                                            </ul>
+                                            {% if session.enrolled == "YES" %}
+                                                <div class="alert alert-success">
+                                                    <i class="fa fa-check-square-o fa-fw"></i> {{ 'TheUserIsAlreadyRegisteredInTheSession'|get_plugin_lang('BuyCoursesPlugin') }}
+                                                </div>
+                                            {% elseif session.enrolled == "NO" %}
+                                                <div class="text-center">
+                                                    <a class="btn btn-success" href="{{ _p.web_plugin ~ 'buycourses/src/process.php?' ~ {'i': session.id, 't': 2}|url_encode() }}">
+                                                        <i class="fa fa-shopping-cart"></i> {{ 'Buy'|get_plugin_lang('BuyCoursesPlugin') }}
+                                                    </a>
+                                                </div>
+                                            {% elseif session.enrolled == "TMP" %}
+                                                <div class="alert alert-info">{{ 'WaitingToReceiveThePayment'|get_plugin_lang('BuyCoursesPlugin') }}</div>
+                                            {% endif %}
+                                        </div>
+                                    </div>
+                                </div>
+                            {% endfor %}
+                        {% endif %}
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div>
+</div>

+ 138 - 98
plugin/buycourses/view/configuration.tpl

@@ -2,107 +2,147 @@
 
 <link rel="stylesheet" type="text/css" href="../resources/css/style.css"/>
 
-<script>
-$(function() {
-/* Binds a tab id in the url */
-    $("#tabs").bind('tabsselect', function(event, ui) {
-        window.location.href=ui.tab;
-    });
-    // Generate tabs with jquery-ui
-    $('#tabs').tabs();
-    $( "#sub_tab" ).tabs();
-});
-</script>
-
-{% if sessionsAreIncluded == "YES" %}
-    <div class="ui-tabs ui-widget ui-widget-content ui-corner-all" id="tabs"> <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"> <li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"> <a href="#tabs-1">{{ 'Courses'|get_lang }}</a></li><li class="ui-state-default ui-corner-top"> <a href="#tabs-2">{{ 'Sessions'|get_lang }}</a></li></ul>
+{% if sessions_are_included %}
+    <ul class="nav nav-tabs buy-courses-tabs" role="tablist">
+        <li role="presentation" class="active">
+            <a href="#courses" aria-controls="courses" role="tab" data-toggle="tab">{{ 'Courses'|get_lang }}</a>
+        </li>
+        <li role="presentation">
+            <a href="#sessions" aria-controls="sessions" role="tab" data-toggle="tab">{{ 'Sessions'|get_lang }}</a>
+        </li>
+    </ul>
 {% endif %}
 
-<div id="tabs-1" class="row">
-    <div class="span12">
-        <table id="courses_table" class="data_table">
-            <tr class="row_odd">
-                <th class="bg-color">{{ 'Title'|get_lang }}</th>
-                <th class="bg-color">{{ 'OfficialCode'|get_lang }}</th>
-                <th class="ta-center bg-color">{{ 'Visible'|get_lang }}</th>
-                <th class="span2 bg-color">{{ 'Price'|get_plugin_lang('BuyCoursesPlugin') }}</th>
-                <th class="span1 ta-center bg-color">{{ 'Option'|get_lang }}</th>
-            </tr>
-            {% set i = 0 %}
+<div class="tab-content">
+    <div role="tabpanel" class="tab-pane fade in active" id="courses">
+        <div class="table-responsive">
+            <table id="courses_table" class="table table-striped table-hover">
+                <thead>
+                    <tr>
+                        <th>{{ 'Title'|get_lang }}</th>
+                        <th class="text-center">{{ 'OfficialCode'|get_lang }}</th>
+                        <th class="text-center">{{ 'Visible'|get_lang }}</th>
+                        <th class="text-right" width="200">{{ 'Price'|get_plugin_lang('BuyCoursesPlugin') }}</th>
+                        <th class="text-right">{{ 'Option'|get_lang }}</th>
+                    </tr>
+                </thead>
 
-            {% for course in courses %}
-                {{ i%2 == 0 ? '<tr class="row_even">' : '<tr class="row_odd">' }}
-                    {% set i = i + 1 %}
-                    <td>
-                        {{ visibility[course.visibility] }}
-                        <a href="{{ server }}courses/{{course.code}}/index.php">{{course.title}}</a>
-                        <span class="label label-info">{{ course.visual_code }}</span>
-                    </td>
-                    <td>
-                        {{course.code}}
-                    </td>
-                    <td class="ta-center">
-                        {% if course.visible == 1 %}
-                            <input type="checkbox" name="visible" value="1" checked="checked" size="6" />
-                        {% else %}
-                            <input type="checkbox" name="visible" value="1" size="6" />
-                        {% endif %}
-                    </td>
-                    <td><input type="text" name="price" value="{{course.price}}" class="span1 price" /> {{ currency }}</td>
-                    <td class=" ta-center" id="course{{ course.id }}">
-                        <div class="confirmed"><img src="{{ confirmation_img }}" alt="ok"/></div>
-                        <div class="modified" style="display:none"><img id="{{course.course_id}}" src="{{ save_img }}" alt="save" class="cursor save"/></div>
-                    </td>
-                </tr>
-            {% endfor %}
-        </table>
-    </div>
-<div class="cleared"></div>
-</div>
-{% if sessionsAreIncluded == "YES" %}
-<div id="tabs-2" class="row">
-    <div class="span12">
-        <table id="courses_table" class="data_table">
-            <tr class="row_odd">
-                <th class="bg-color">{{ 'Title'|get_lang }}</th>
-                <th class="bg-color">{{ 'StartDate'|get_lang }}</th>
-                <th class="bg-color">{{ 'EndDate'|get_lang }}</th>
-                <th class="bg-color ta-center">{{ 'Visible'|get_lang }}</th>
-                <th class="bg-color span2">{{ 'Price'|get_plugin_lang('BuyCoursesPlugin') }}</th>
-                <th class="bg-color span1 ta-center">{{ 'Option'|get_lang }}</th>
-            </tr>
-            {% set i = 0 %}
+                <tbody>
+                    {% for item in courses %}
+                        <tr data-item="{{ item.course_id }}" data-type="course">
+                            <td>
+                                {% if item.course_visibility == 0 %}
+                                    <img src="{{ 'bullet_red.gif'|icon() }}" alt="{{ 'CourseVisibilityClosed'|get_lang }}" title="{{ 'CourseVisibilityClosed'|get_lang }}">
+                                {% elseif item.course_visibility == 1 %}
+                                    <img src="{{ 'bullet_orange.gif'|icon() }}" alt="{{ 'Private'|get_lang }}" title="{{ 'Private'|get_lang }}">
+                                {% elseif item.course_visibility == 2 %}
+                                    <img src="{{ 'bullet_green.gif'|icon() }}" alt="{{ 'OpenToThePlatform'|get_lang }}" title="{{ 'OpenToThePlatform'|get_lang }}">
+                                {% elseif item.course_visibility == 3 %}
+                                    <img src="{{ 'bullet_blue.gif'|icon() }}" alt="{{ 'OpenToTheWorld'|get_lang }}" title="{{ 'OpenToTheWorld'|get_lang }}">
+                                {% elseif item.course_visibility == 4 %}
+                                    <img src="{{ 'bullet_gray.gif'|icon() }}" alt="{{ 'CourseVisibilityHidden'|get_lang }}" title="{{ 'CourseVisibilityHidden'|get_lang }}">
+                                {% endif %}
 
-            {% for session in sessions %}
-                {{ i%2 == 0 ? '<tr class="row_even">' : '<tr class="row_odd">' }}
-                    {% set i = i + 1 %}
-                    <td>
-                        {{ visibility[session.visibility] }}
-                        <a href="{{ server }}main/session/index.php?session_id={{ session.id }}">{{session.name}}</a>
-                    </td>
-                    <td>
-                        {{ session.access_start_date }}
-                    </td>
-                    <td>
-                        {{ session.access_end_date }}
-                    </td>
-                    <td class="ta-center">
-                        {% if session.visible == 1 %}
-                            <input type="checkbox" name="visible" value="1" checked="checked" size="6" />
-                        {% else %}
-                            <input type="checkbox" name="visible" value="1" size="6" />
-                        {% endif %}
-                    </td>
-                    <td><input type="text" name="price" value="{{session.price}}" class="span1 price" /> {{ currency }}</td>
-                    <td class=" ta-center" id="session{{ session.id }}">
-                        <div class="confirmed"><img src="{{ confirmation_img }}" alt="ok"/></div>
-                        <div class="modified" style="display:none"><img id="{{session.id}}" src="{{ save_img }}" alt="save" class="cursor save"/></div>
-                    </td>
-                </tr>
-            {% endfor %}
-        </table>
+                                <a href="{{ _p.web_course ~ item.course_code ~ '/index.php' }}">{{ item.course_title }}</a>
+                                <span class="label label-info">{{ item.course_visual_code }}</span>
+                            </td>
+                            <td class="text-center">
+                                {{ item.course_code }}
+                            </td>
+                            <td class="text-center">
+                                {% if item.visible == 1 %}
+                                    <input type="checkbox" name="visible" value="1" checked="checked" size="6">
+                                {% else %}
+                                    <input type="checkbox" name="visible" value="1" size="6">
+                                {% endif %}
+                            </td>
+                            <td width="200">
+                                {% if item.currency %}
+                                    <div class="input-group">
+                                        <span class="input-group-addon" id="price-{{ item.course_id }}">{{ item.currency }}</span>
+                                        <input type="number" name="price" value="{{ item.price }}" step="0.01" min="0" class="text-right form-control" aria-describedby="price-{{ item.course_id }}">
+                                    </div>
+                                {% else %}
+                                    <input type="number" name="price" value="{{ item.price }}" step="0.01" min="0" class="text-right form-control">
+                                {% endif %}
+                            </td>
+                            <td class="text-right">
+                                <button class="btn btn-success btn-sm bc-button-save" type="button">
+                                    <i class="fa fa-save"></i> {{ 'Save'|get_lang }}
+                                </button>
+                            </td>
+                        </tr>
+                    {% endfor %}
+                </tbody>
+            </table>
+        </div>
     </div>
-<div class="cleared"></div>
-</div>
+
+    {% if sessions_are_included %}
+        <div role="tabpanel" class="tab-pane" id="sessions">
+            <div class="table-responsive">
+                <table id="courses_table" class="table">
+                    <thead>
+                        <tr>
+                            <th>{{ 'Title'|get_lang }}</th>
+                            <th class="text-center">{{ 'StartDate'|get_lang }}</th>
+                            <th class="text-center">{{ 'EndDate'|get_lang }}</th>
+                            <th class="text-center">{{ 'Visible'|get_lang }}</th>
+                            <th class="text-right">{{ 'Price'|get_plugin_lang('BuyCoursesPlugin') }}</th>
+                            <th class="text-right">{{ 'Option'|get_lang }}</th>
+                        </tr>
+                    </thead>
+                    <tbody>
+                        {% for item in sessions %}
+                            <tr data-item="{{ item.session_id }}" data-type="session">
+                                <td>
+                                    {% if item.session_visibility == 0 %}
+                                        <img src="{{ 'bullet_red.gif'|icon() }}" alt="{{ 'CourseVisibilityClosed'|get_lang }}" title="{{ 'CourseVisibilityClosed'|get_lang }}">
+                                    {% elseif item.session_visibility == 1 %}
+                                        <img src="{{ 'bullet_orange.gif'|icon() }}" alt="{{ 'Private'|get_lang }}" title="{{ 'Private'|get_lang }}">
+                                    {% elseif item.session_visibility == 2 %}
+                                        <img src="{{ 'bullet_green.gif'|icon() }}" alt="{{ 'OpenToThePlatform'|get_lang }}" title="{{ 'OpenToThePlatform'|get_lang }}">
+                                    {% elseif item.session_visibility == 3 %}
+                                        <img src="{{ 'bullet_blue.gif'|icon() }}" alt="{{ 'OpenToTheWorld'|get_lang }}" title="{{ 'OpenToTheWorld'|get_lang }}">
+                                    {% elseif item.session_visibility == 4 %}
+                                        <img src="{{ 'bullet_gray.gif'|icon() }}" alt="{{ 'CourseVisibilityHidden'|get_lang }}" title="{{ 'CourseVisibilityHidden'|get_lang }}">
+                                    {% endif %}
+
+                                    <a href="{{ _p.web_main ~ 'session/index.php?' ~ {'session_id': item.session_id}|url_encode() }}">{{ item.session_name }}</a>
+                                </td>
+                                <td class="text-center">
+                                    {{ item.session_display_start_date }}
+                                </td>
+                                <td class="text-center">
+                                    {{ item.session_display_end_date }}
+                                </td>
+                                <td class="text-center">
+                                    {% if item.visible %}
+                                        <input type="checkbox" name="visible" value="1" checked="checked" size="6" />
+                                    {% else %}
+                                        <input type="checkbox" name="visible" value="1" size="6" />
+                                    {% endif %}
+                                </td>
+                                <td class="text-right" width="200">
+                                    {% if item.currency %}
+                                        <div class="input-group">
+                                            <span class="input-group-addon" id="price-{{ item.session_id }}">{{ item.currency }}</span>
+                                            <input type="number" name="price" value="{{ item.price }}" step="0.01" min="0" class="text-right form-control" aria-describedby="price-{{ item.session_id }}">
+                                        </div>
+                                    {% else %}
+                                        <input type="number" name="price" value="{{ item.price }}" step="0.01" min="0" class="text-right form-control">
+                                    {% endif %}
+                                </td>
+                                <td class=" text-center" id="session{{ item.session_id }}">
+                                    <button class="btn btn-success btn-sm bc-button-save" type="button">
+                                        <i class="fa fa-save"></i> {{ 'Save'|get_lang }}
+                                    </button>
+                                </td>
+                            </tr>
+                        {% endfor %}
+                    </tbody>
+                </table>
+            </div>
+        </div>
+    {% endif %}
 </div>
-{% endif %}

+ 57 - 48
plugin/buycourses/view/index.tpl

@@ -1,70 +1,79 @@
 <link rel="stylesheet" type="text/css" href="resources/css/style.css"/>
 <div class="row">
-    <div class="span12">
-        <div class="row">
-        {% if isAdmin == 'true' %}
-            <div class="span12">
-                <div>
-                    <h2>{{ 'TitlePlugin'|get_plugin_lang('BuyCoursesPlugin') }}</h2>
-                    <p>{{ 'PluginPresentation'|get_plugin_lang('BuyCoursesPlugin') }}</p>
-                </div>
-                <div class="normal-message">
-                    <h3>{{ 'Instructions'|get_plugin_lang('BuyCoursesPlugin') }}</h3>
-                    <ul>
-                        <li>{{ 'InstructionsStepOne'|get_plugin_lang('BuyCoursesPlugin') }}</li>
-                        <li>{{ 'InstructionsStepTwo'|get_plugin_lang('BuyCoursesPlugin') }}</li>
-                        <li>{{ 'InstructionsStepThree'|get_plugin_lang('BuyCoursesPlugin') }}</li>
-                    </ul>
+    <div class="col-md-12">
+        {% if _u.is_admin %}
+            <div class="help-bycourse">
+                <div class="row">
+                    <div class="col-md-7">
+                        <div class="panel panel-default">
+                            <div class="panel-body">
+                                <h3>{{ 'TitlePlugin'|get_plugin_lang('BuyCoursesPlugin') }}</h3>
+                                <p>{{ 'PluginPresentation'|get_plugin_lang('BuyCoursesPlugin') }}</p>
+                                <p>&nbsp;</p>
+                            </div>
+                        </div>
+                    </div>
+                    <div class="col-md-5">
+                        <div class="panel panel-default">
+                            <div class="panel-heading">
+                                {{ 'Instructions'|get_plugin_lang('BuyCoursesPlugin') }}
+                            </div>
+                            <div class="panel-body">
+                                <ul>
+                                    <li>{{ 'InstructionsStepOne'|get_plugin_lang('BuyCoursesPlugin') }}</li>
+                                    <li>{{ 'InstructionsStepTwo'|get_plugin_lang('BuyCoursesPlugin') }}</li>
+                                    <li>{{ 'InstructionsStepThree'|get_plugin_lang('BuyCoursesPlugin') }}</li>
+                                </ul>
+                            </div>
+                        </div>
+                    </div>
                 </div>
             </div>
         {% endif %}
-            <div class="span12">
 
-            </div>
-        </div>
         <div class="row">
-
-            <div class="span3">
+            <div class="col-md-3">
                 <div class="thumbnail">
-                    <a href="src/list.php">
+                    <a href="src/course_catalog.php">
                         <img src="resources/img/128/buycourses.png">
                     </a>
-                    <div class="caption">
-                        <a class="btn btn-default" href="src/list.php">{{ BuyCourses }}</a>
+                    <div class="caption"  align="center">
+                        <a class="btn btn-default btn-sm" href="src/course_catalog.php">{{ 'BuyCourses'|get_plugin_lang('BuyCoursesPlugin') }}</a>
                     </div>
                 </div>
             </div>
-            {% if isAdmin == 'true' %}
-            <div class="span3">
-                <div class="thumbnail">
-                    <a href="src/configuration.php">
-                        <img src="resources/img/128/settings.png">
-                    </a>
-                    <div class="caption">
-                        <a class="btn btn-default" href="src/configuration.php">{{ ConfigurationOfCoursesAndPrices }}</a>
+
+            {% if _u.is_admin %}
+                <div class="col-md-3">
+                    <div class="thumbnail">
+                        <a href="src/configuration.php">
+                            <img src="resources/img/128/settings.png">
+                        </a>
+                        <div class="caption"  align="center">
+                            <a class="btn btn-default btn-sm" href="src/configuration.php">{{ 'ConfigurationOfCoursesAndPrices'|get_plugin_lang('BuyCoursesPlugin') }}</a>
+                        </div>
                     </div>
                 </div>
-            </div>
-            <div class="span3">
-                <div class="thumbnail">
-                    <a href="src/paymentsetup.php">
-                        <img src="resources/img/128/paymentsettings.png">
-                    </a>
-                    <div class="caption">
-                        <a class="btn btn-default" href="src/paymentsetup.php">{{ ConfigurationOfPayments }} </a>
+                <div class="col-md-3">
+                    <div class="thumbnail">
+                        <a href="src/paymentsetup.php">
+                            <img src="resources/img/128/paymentsettings.png">
+                        </a>
+                        <div class="caption" align="center">
+                            <a class="btn btn-default btn-sm" href="src/paymentsetup.php">{{ 'PaymentsConfiguration'|get_plugin_lang('BuyCoursesPlugin') }} </a>
+                        </div>
                     </div>
                 </div>
-            </div>
-            <div class="span3">
-                <div class="thumbnail">
-                    <a href="src/pending_orders.php">
-                        <img src="resources/img/128/backlogs.png">
-                    </a>
-                    <div class="caption">
-                        <a class="btn btn-default" href="src/pending_orders.php"> {{ OrdersPendingOfPayment }} </a>
+                <div class="col-md-3">
+                    <div class="thumbnail">
+                        <a href="src/sales_report.php">
+                            <img src="resources/img/128/backlogs.png">
+                        </a>
+                        <div class="caption"  align="center">
+                            <a class="btn btn-default btn-sm" href="src/sales_report.php"> {{ 'SalesReport'|get_plugin_lang('BuyCoursesPlugin') }} </a>
+                        </div>
                     </div>
                 </div>
-            </div>
             {% endif %}
         </div>
     </div>

+ 0 - 190
plugin/buycourses/view/list.tpl

@@ -1,190 +0,0 @@
-<script type='text/javascript' src="../js/buycourses.js"></script>
-
-<link rel="stylesheet" type="text/css" href="../resources/css/style.css"/>
-
-<script>
-$(function() {
-/* Binds a tab id in the url */
-    $("#tabs").bind('tabsselect', function(event, ui) {
-        window.location.href=ui.tab;
-    });
-    // Generate tabs with jquery-ui
-    $('#tabs').tabs();
-    $( "#sub_tab" ).tabs();
-});
-</script>
-
-{% if sessionsAreIncluded == "YES" %}
-    <div class="ui-tabs ui-widget ui-widget-content ui-corner-all" id="tabs"> <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"> <li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"> <a href="#tabs-1">{{ 'Courses'|get_lang }}</a></li><li class="ui-state-default ui-corner-top"> <a href="#tabs-2">{{ 'Sessions'|get_lang }}</a></li></ul>
-{% endif %}
-
-<div id="tabs-1">
-<div class="row">
-    <div class="span3">
-        <div class="category_well well">
-            <div class="form-content">
-                <h4>{{ 'SearchFilter'|get_plugin_lang('BuyCoursesPlugin') }}:</h4>
-                <label class="control-label">{{ 'CourseName'|get_lang }}:</label>
-                <input type="text" class="name" />
-                <label class="control-label">{{ 'MinimumPrice'|get_plugin_lang('BuyCoursesPlugin') }}:</label>
-                <input type="text" class="pricemin span1"/>
-                <label class="control-label">{{ 'MaximumPrice'|get_plugin_lang('BuyCoursesPlugin') }}:</label>
-                <input type="text" class="pricemax span1"/>
-                    {% for category in categories %}
-                        <label class="control-label">{{ 'Categories'|get_lang }}:</label>
-                        <select id="courses_category">
-                            <option value="" selected="selected"></option>
-                                <option value="{{ category.code }}">{{ category.name }}</option>
-                        </select>
-                    {% endfor %}
-                <br>
-                 <input type="button" class="filter btn btn-primary" value="{{ 'Search'|get_lang }}" id="courses_filter" />
-            </div>
-        </div>
-    </div>
-    <div class="span8" id="course_results">
-        {% if rmessage == "YES" %}
-            <div class="{{ class }}">
-                {{ responseMessage }}
-            </div>
-        {% endif %}
-        {% for course in courses %}
-            <div class="span8">
-                <div class="row well-course">
-                    <div class="span1 icon-course">
-                        <div class="thumbnail">
-                            <a class="ajax" rel="gb_page_center[778]" title="" href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">
-                                <img alt="" src="{{ server }}{{ course.course_img }}">
-                            </a>
-                        </div>
-                    </div>
-                    <div class="span3">
-                        <div class="categories-course-description">
-                            <h3>{{ course.title }}</h3>
-                            <h5>{{ 'Teacher'|get_lang }}: {{ course.teacher }}</h5>
-                        </div>
-                        {% if course.enrolled == "YES" %}
-                            <span class="label label-info">{{ 'TheUserIsAlreadyRegisteredInTheCourse'|get_plugin_lang('BuyCoursesPlugin') }}</span>
-                        {% endif %}
-                        {% if course.enrolled == "TMP" %}
-                            <span class="label label-warning">{{ 'WaitingToReceiveThePayment'|get_plugin_lang('BuyCoursesPlugin') }}</span>
-                        {% endif %}
-                    </div>
-                    <div class="span3 right">
-                        <div class="sprice right">
-                            {{ course.price }} {{ currency }}
-                        </div>
-                        <div class="cleared"></div>
-                        <div class="btn-group right">
-                            <a class="ajax btn btn-primary" title="" href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">
-                                {{ 'Description'|get_lang }}
-                            </a>
-                            {% if course.enrolled == "NO" %}
-                                <a class="btn btn-success" title="" href="{{ server }}plugin/buycourses/src/process.php?code={{ course.id }}">
-                                    {{ 'Buy'|get_plugin_lang('BuyCoursesPlugin') }}
-                                </a>
-                            {% endif %}
-                        </div>
-                    </div>
-                </div>
-            </div>
-        {% endfor %}
-    </div>
-</div>
-</div>
-{% if sessionsAreIncluded == "YES" %}
-<div id="tabs-2" class="row">
-    <div class="span3">
-        <div class="category_well well">
-            <div class="form-content">
-                <h4>{{ 'SearchFilter'|get_plugin_lang('BuyCoursesPlugin') }}:</h4>
-                <label class="control-label">{{ 'SessionName'|get_lang }}:</label>
-                <input type="text" class="name" />
-                <label class="control-label">{{ 'MinimumPrice'|get_plugin_lang('BuyCoursesPlugin') }}:</label>
-                <input type="text" class="pricemin span1"/>
-                <label class="control-label">{{ 'MaximumPrice'|get_plugin_lang('BuyCoursesPlugin') }}:</label>
-                <input type="text" class="pricemax span1"/>
-                    {% for category in categories %}
-                        <label class="control-label">{{ 'Categories'|get_lang }}:</label>
-                        <select id="sessions_category">
-                            <option value="" selected="selected"></option>
-                                <option value="{{ category.code }}">{{ category.name }}</option>
-                        </select>
-                    {% endfor %}
-                <br>
-                 <input type="button" class="filter btn btn-primary" value="{{ 'Search'|get_lang }}" id="sessions_filter" />
-            </div>
-        </div>
-    </div>
-    <div class="span8" id="session_results">
-        {% if rmessage == "YES" %}
-            <div class="{{ class }}">
-                {{ responseMessage }}
-            </div>
-        {% endif %}
-        {% for session in sessions %}
-            <div class="span8 well-course">
-                <div class="row">
-                    <div class="span4 ">
-                        <div class="categories-course-description">
-                            <h3>{{ session.name }}</h3>
-                            <h5>{{ 'From'|get_lang }} {{ session.access_start_date }} {{ 'Until'|get_lang }} {{ session.access_end_date }}</h5>
-                            {% if session.enrolled == "YES" %}
-                                <span class="label label-info">{{ 'TheUserIsAlreadyRegisteredInTheSession'|get_plugin_lang('BuyCoursesPlugin') }}</span>
-                            {% endif %}
-                            {% if session.enrolled == "TMP" %}
-                                <span class="label label-warning">{{ 'WaitingToReceiveThePayment'|get_plugin_lang('BuyCoursesPlugin') }}</span>
-                            {% endif %}
-                        </div>
-                    </div>
-                    <div class="span right">
-                        <div class="sprice right">
-                            {{ session.price }} {{ currency }}
-                        </div>
-                        <div class="cleared"></div>
-                        <div class="btn-group right">
-                            {% if session.enrolled == "NO" %}
-                                <a class="btn btn-success" title="" href="{{ server }}plugin/buycourses/src/process.php?scode={{ session.session_id }}">
-                                    {{ 'Buy'|get_plugin_lang('BuyCoursesPlugin') }}
-                                </a>
-                            {% endif %}
-                        </div>
-                    </div>
-                </div>
-                {% for course in session.courses %}
-                    <div class="row">
-                        <div class="span">
-                            <div class="thumbnail">
-                                <a class="ajax" rel="gb_page_center[778]" title="" href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">
-                                    <img alt="" src="{{ server }}{{ course.course_img }}">
-                                </a>
-                            </div>
-                        </div>
-                        <div class="span4">
-                            <div class="categories-course-description">
-                                <h3>{{ course.title }}</h3>
-                                <h5>{{ 'Teacher'|get_lang }}: {{ course.teacher }}</h5>
-                            </div>
-                            {% if course.enrolled == "YES" %}
-                                <span class="label label-info">{{ 'TheUserIsAlreadyRegisteredInTheCourse'|get_plugin_lang('BuyCoursesPlugin') }}</span>
-                            {% endif %}
-                            {% if course.enrolled == "TMP" %}
-                                <span class="label label-warning">{{ 'WaitingToReceiveThePayment'|get_plugin_lang('BuyCoursesPlugin') }}</span>
-                            {% endif %}
-                        </div>
-                        <div class="span right">
-                            <div class="cleared"></div>
-                            <div class="btn-group right">
-                                <a class="ajax btn btn-primary" title="" href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">
-                                    {{ 'Description'|get_lang }}
-                                </a>
-                            </div>
-                        </div>
-                    </div>
-                {% endfor %}
-            </div>
-        {% endfor %}
-    </div>
-</div>
-</div>
-{% endif %}

+ 36 - 0
plugin/buycourses/view/message_transfer.tpl

@@ -0,0 +1,36 @@
+<div>
+    <p>{{ 'DearUser'|get_lang }}</p>
+    <p>{{ 'PurchaseDetailsIntro'|get_plugin_lang('BuyCoursesPlugin') }}</p>
+    <dl>
+        <dt>{{ 'OrderDate'|get_plugin_lang('BuyCoursesPlugin') }}</dt>
+        <dd>{{ sale.date }}</dd>
+        <dt>{{ 'OrderReference'|get_plugin_lang('BuyCoursesPlugin') }}</dt>
+        <dd>sale.reference</dd>
+        <dt>{{ 'UserName'|get_lang }}</dt>
+        <dd>{{ user.complete_name }}</dd>
+        <dt>{{ 'Course'|get_lang }}</dt>
+        <dd>{{ sale.product }}</dd>
+        <dt>{{ 'ProductName'|get_plugin_lang('BuyCoursesPlugin') }}</dt>
+        <dd>{{ sale.currency ~ ' ' ~ sale.price }}</dd>
+    </dl>
+    <p>{{ 'BankAccountIntro'|get_plugin_lang('BuyCoursesPlugin')|format(sale.product) }}</p>
+    <table>
+        <thead>
+            <tr>
+                <th>{{ 'Name'|get_lang }}</th>
+                <th>{{ 'BankAccount'|get_plugin_lang('BuyCoursesPlugin') }}</th>
+                <th>{{ 'SWIFT'|get_lang }}</th>
+            </tr>
+        </thead>
+        <tbody>
+            {% for account in transfer_accounts %}
+                <tr>
+                    <td>{{ account.name }}</td>
+                    <td>{{ account.account }}</td>
+                    <td>{{ account.swift }}</td>
+                </tr>
+            {% endfor %}
+        </tbody>
+    </table>
+    <p>{{ 'PurchaseDetailsEnd'|get_plugin_lang('BuyCoursesPlugin') }}</p>
+</div>

+ 66 - 100
plugin/buycourses/view/paymentsetup.tpl

@@ -1,110 +1,76 @@
 <script type='text/javascript' src="../js/buycourses.js"></script>
 
 <link rel="stylesheet" type="text/css" href="../resources/css/style.css"/>
-<div class="row">
-    <div class="span12">
-        <p class="normal-message">{{ 'PluginInstruction'|get_plugin_lang('BuyCoursesPlugin') }}<a href="{{ server }}main/admin/configure_plugin.php?name=buycourses">{{ 'ClickHere'|get_plugin_lang('BuyCoursesPlugin') }}</a></p>
-    </div>
-</div>
-<div class="row">
-    <div class="span6">
-        <div class="info">
-            
 
-            <h3>{{ 'CurrencyType'|get_plugin_lang('BuyCoursesPlugin') }}</h3>
-            <p>{{ 'InfoCurrency'|get_plugin_lang('BuyCoursesPlugin') }}</p>
+{{ curency_form }}
+
+<p class="alert alert-info">
+    {{ 'PluginInstruction'|get_plugin_lang('BuyCoursesPlugin') }}
+    <a href="{{ _p.web_main }}admin/configure_plugin.php?name=buycourses">{{ 'ClickHere'|get_plugin_lang('BuyCoursesPlugin') }}</a>
+</p>
 
+{% if paypal_enable == "true" %}
+    <div class="panel panel-default">
+        <div class="panel-heading">
+            <h3 class="panel-title">{{ 'PayPalConfig'|get_plugin_lang('BuyCoursesPlugin') }}</h3>
         </div>
-        <div class="input-content">
-            <select id="currency_type">
-            <option value="" selected="selected">{{ 'SelectACurrency'|get_plugin_lang('BuyCoursesPlugin') }}</option>
-            {% for currency in currencies %}
-                {% if currency.status == 1 %}
-                    <option value="{{ currency.country_id }}" selected="selected">{{ currency.country_name }} => {{ currency.currency_code }}
-                    </option>
-                {% else %}
-                    <option value="{{ currency.country_id }}">{{ currency.country_name }} => {{ currency.currency_code }}</option>
-                {% endif %}
-            {% endfor %}
-        </select>
-        <input type="button" id="save_currency" class="btn btn-primary" value="{{ 'Save'|get_lang }}" />
+        <div class="panel-body">
+            <div class="row">
+                <div class="col-md-5">
+                    <p>{{ 'InfoApiCredentials'|get_plugin_lang('BuyCoursesPlugin') }}</p>
+                    <ul>
+                        <li>{{ 'InfoApiStepOne'|get_plugin_lang('BuyCoursesPlugin') }}</li>
+                        <li>{{ 'InfoApiStepTwo'|get_plugin_lang('BuyCoursesPlugin') }}</li>
+                        <li>{{ 'InfoApiStepThree'|get_plugin_lang('BuyCoursesPlugin') }}</li>
+                    </ul>
+                </div>
+                <div class="col-md-7">
+                    {{ paypal_form }}
+                </div>
+            </div>
         </div>
     </div>
-    {% if paypal_enable == "true" %}
-    <div class="span6">
-        <div class="info">
-            <h3>{{ 'PayPalConfig'|get_plugin_lang('BuyCoursesPlugin') }}</h3>
+{% endif %}
+
+{% if transfer_enable == "true" %}
+    <div class="panel panel-default">
+        <div class="panel-heading">
+            <h3 class="panel-title">{{ 'TransfersConfig'|get_plugin_lang('BuyCoursesPlugin') }}</h3>
+        </div>
+        <div class="panel-body">
+            <div class="row">
+                <div class="col-md-5">
+                    {{ transfer_form }}
+                </div>
+                <div class="col-md-7">
+                    <div class="table-responsive">
+                        <table class="table table-striped table-hover">
+                            <thead>
+                                <tr>
+                                    <th>{{ 'Name'|get_lang }}</th>
+                                    <th>{{ 'BankAccount'|get_plugin_lang('BuyCoursesPlugin') }}</th>
+                                    <th>{{ 'SWIFT'|get_lang }}</th>
+                                    <th>{{ 'Actions'|get_lang }}</th>
+                                </tr>
+                            </thead>
+                            <tbody>
+                                {% for account in transfer_accounts %}
+                                    <tr>
+                                        <td>{{ account.name }}</td>
+                                        <td>{{ account.account }}</td>
+                                        <td>{{ account.swift }}</td>
+                                        <td>
+                                            <a href="{{ _p.web_self ~ '?' ~ {'action':'delete_taccount', 'id': account.id}|url_encode() }}" class="btn btn-danger btn-sm">
+                                                <i class="fa fa-remove"></i> {{ 'Delete'|get_lang }}
+                                            </a>
+                                        </td>
+                                    </tr>
+                                {% endfor %}
+                            </tbody>
+                        </table>
+                    </div>
+                </div>
+            </div>
         </div>
-         <div class="input-content">
-            
-            <p>{{ 'InfoApiCredentials'|get_plugin_lang('BuyCoursesPlugin') }}</p>
-            <ul>
-                <li>{{ 'InfoApiStepOne'|get_plugin_lang('BuyCoursesPlugin') }}</li>
-                <li>{{ 'InfoApiStepTwo'|get_plugin_lang('BuyCoursesPlugin') }}</li>
-                <li>{{ 'InfoApiStepThree'|get_plugin_lang('BuyCoursesPlugin') }}</li>
-            </ul>
-            <label class="control-label">API_UserName: </label><input type="text" id="username" value="{{ paypal.username | e}}" />
-            <label class="control-label">API_Password: </label><input type="text" id="password" value="{{ paypal.password | e }}"/>
-            <label class="control-label">API_Signature: </label> <input type="text" id="signature" value="{{ paypal.signature | e }}"/>
-           
-            {% if paypal.sandbox == "YES" %}
-                    <label class="checkbox">
-                        <input type="checkbox" id="sandbox" value="YES" checked="checked"> {{ 'Sandbox'|get_plugin_lang('BuyCoursesPlugin') }}
-                    </label>
-                {% else %}
-                    <label class="checkbox">
-                        <input type="checkbox" id="sandbox" value="YES" />{{ 'Sandbox'|get_plugin_lang('BuyCoursesPlugin') }}
-                    </label>
-                     
-            {% endif %}
-            
-            <input type="button" id="save_paypal" class="btn btn-primary" value="{{ 'Save'|get_lang }}"/>
-         </div>
     </div>
-    {% endif %}
-</div>
-
-<div class="row">
-    <div class="span12">
-        
-        {% if transfer_enable == "true" %}
-            <hr />
-            <h3>{{ 'TransfersConfig'|get_plugin_lang('BuyCoursesPlugin') }}</h3>
-            <table id="transfer_table" class="data_table">
-                <tr class="row_odd">
-                <th class="bg-color">{{ 'Name'|get_lang }}</th>
-                <th class="bg-color">{{ 'BankAccount'|get_plugin_lang('BuyCoursesPlugin') }}</th>
-                <th class="bg-color">{{ 'SWIFT'|get_lang }}</th>
-                <th class="span1 ta-center bg-color">{{ 'Option'|get_lang }}</th>
-                </tr>
-                {% set i = 0 %}
-
-                {% for transf in transfer %}
-                {{ i%2==0 ? '
-                <tr class="row_even">' : '
-                <tr class="row_odd">' }}
-                    {% set i = i + 1 %}
-                    <td>{{ transf.name | e }}</td>
-                    <td>{{ transf.account | e }}</td>
-                    <td>{{ transf.swift | e }}</td>
-                    <td class="ta-center" id="account{{ transf.id }}">
-                        <img src="{{ delete_img }}" class="cursor delete_account" alt="ok"/>
-                        <input type="hidden" id="id_account{{ transf.id }}" name="id_account{{ transf.id }}" value="{{ transf.id }}" />
-                    </td>
-                </tr>
-                {% endfor %}
-                {{ i%2==0 ? '
-                <tr class="row_even">' : '
-                <tr class="row_odd">' }}
-                    <td><input class="span4" type="text" id="tname"/></td>
-                    <td><input type="text" id="taccount"/></td>
-                    <td><input class="span2" type="text" id="tswift"</td>
-                    <td class="ta-center">
-                        <img class="cursor" id="add_account" src="{{ more_img }}" alt="add account"/>
-                    </td>
-                </tr>
-            </table>
-        {% endif %}
-</div>
-<div class="cleared"></div>
-</div>
+{% endif %}

+ 0 - 39
plugin/buycourses/view/pending_orders.tpl

@@ -1,39 +0,0 @@
-<script type='text/javascript' src="../js/buycourses.js"></script>
-
-<link rel="stylesheet" type="text/css" href="../resources/plugin.css"/>
-
-<div class="row">
-    <div class="span12">
-        <table id="orders_table" class="data_table">
-            <tr class="row_odd">
-                <th class="ta-center">{{ 'ReferenceOrder'|get_plugin_lang('BuyCoursesPlugin') }}</th>
-                <th>{{ 'Name'|get_lang }}</th>
-                <th>{{ 'Title'|get_lang }}</th>
-                <th class="span2">{{ 'Price'|get_lang }}</th>
-                <th class="ta-center">{{ 'Date'|get_lang }}</th>
-                <th class="span2 ta-center">{{ 'Options'|get_lang }}</th>
-            </tr>
-            {% set i = 0 %}
-
-            {% for order in pending %}
-                {{ i%2==0 ? '<tr class="row_even">' : '<tr class="row_odd">' }}
-                {% set i = i + 1 %}
-                <td class="ta-center">{{ order.reference }}</td>
-                <td>{{ order.name }}</td>
-                <td>{{ order.title }}</td>
-                <td>{{ order.price }} {{ currency }}</td>
-                <td class="ta-center">{{ order.date }}</td>
-                <td class="ta-center" id="order{{ order.cod }}">
-                    <img src="{{ confirmation_img }}" alt="ok" class="cursor confirm_order"
-                         title="{{ 'SubscribeUser'|get_plugin_lang('BuyCoursesPlugin') }}"/>
-                    &nbsp;&nbsp;
-                    <img src="{{ delete_img }}" alt="delete" class="cursor clear_order"
-                         title="{{ 'DeleteTheOrder'|get_plugin_lang('BuyCoursesPlugin') }}"/>
-                </td>
-            </tr>
-{% endfor %}
-
-</table>
-</div>
-<div class="cleared"></div>
-</div>

+ 41 - 111
plugin/buycourses/view/process.tpl

@@ -1,122 +1,52 @@
 <script type='text/javascript' src="../js/buycourses.js"></script>
 
-<link rel="stylesheet" type="text/css" href="../resources/plugin.css"/>
-
 <div class="row">
-    <div class="span12">
-        <div id="course_category_well" class="well span3">
-            <ul class="nav nav-list">
-                <li class="nav-header"><h4>{{ 'UserInformation'|get_plugin_lang('BuyCoursesPlugin') }}:</h4></li>
-                <li class="nav-header">{{ 'Name'|get_lang }}:</li>
-                <li><h5>{{ name }}</h5></li>
-                <li class="nav-header">{{ 'User'|get_lang }}:</li>
-                <li><h5>{{ user }}</h5></li>
-                <li class="nav-header">{{ 'Email'|get_lang }}:</li>
-                <li><h5>{{ email }}</h5></li>
-                <br/>
-            </ul>
-        </div>
-
-        <br/><br/>
-        <div class="well_border span8">
-        {% if isSession == "YES" %}
-            <div class="row">
-                <div class="span4">
-                    <div class="categories-course-description">
-                        <h3>{{ title }}</h3>
-                        <h5>{{ 'From'|get_lang }} {{ session.access_start_date }} {{ 'To'|get_lang }} {{ session.access_end_date }}</h5>
-                    </div>
-                </div>
-                <div class="span right">
-                    <div class="sprice right">
-                        {{ session.price }} {{ currency }}
-                    </div>
-                    <div class="cleared"></div>
+    <div class="col-md-7">
+        <h3 class="page-header">{{ 'PurchaseData'|get_plugin_lang('BuyCoursesPlugin') }}</h3>
+        <div class="row">
+            {% if buying_course %}
+                <div class="col-sm-6 col-md-5">
+                    <p>
+                        <img alt="{{ course.title }}" class="img-responsive" src="{{ course.course_img ? course.course_img : 'session_default.png'|icon() }}">
+                    </p>
+                    <p class="lead text-right">{{ course.currency }} {{ course.price }}</p>
                 </div>
-            </div>
-            {% for course in session.courses %}
-                <div class="row">
-                    <div class="span">
-                        <div class="thumbnail">
-                            <a class="ajax" rel="gb_page_center[778]" title="" href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">
-                                <img alt="" src="{{ server }}{{ course.course_img }}">
-                            </a>
-                        </div>
-                    </div>
-                    <div class="span4">
-                        <div class="categories-course-description">
-                            <h3>{{ course.title }}</h3>
-                            <h5>{{ 'Teacher'|get_lang }}: {{ course.teacher }}</h5>
-                        </div>
-                        {% if course.enrolled == "YES" %}
-                            <span class="label label-info">{{ 'TheUserIsAlreadyRegisteredInTheCourse'|get_plugin_lang('BuyCoursesPlugin') }}</span>
-                        {% endif %}
-                        {% if course.enrolled == "TMP" %}
-                            <span class="label label-warning">{{ 'WaitingToReceiveThePayment'|get_plugin_lang('BuyCoursesPlugin') }}</span>
-                        {% endif %}
-                    </div>
-                    <div class="span right">
-                        <div class="cleared"></div>
-                        <div class="btn-toolbar right">
-                            <a class="ajax btn btn-primary" title="" href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">
-                                {{ 'Description'|get_lang }}
-                            </a>
-                        </div>
-                    </div>
-                </div>
-            {% endfor %}
-        {% else %}
-            <div class="row">
-                <div class="span">
-                    <div class="thumbnail">
-                        <a class="ajax" rel="gb_page_center[778]" title=""
-                           href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">
-                            <img alt="" src="{{ server }}{{ course.course_img }}">
+                <div class="col-sm-6 col-md-7">
+                    <h3 class="page-header">{{ course.title }}</h3>
+                    <ul class="items-teacher list-unstyled">
+                        {% for teacher in course.teachers %}
+                            <li><i class="fa fa-user"></i> {{ teacher }}</li>
+                        {% endfor %}
+                    </ul>
+                    <p>
+                        <a class="ajax btn btn-primary btn-sm" data-title="{{ course.title }}" href="{{ _p.web_ajax ~ 'course_home.ajax.php?' ~ {'a': 'show_course_information', 'code': course.code}|url_encode() }}">
+                            {{'Description'|get_lang }}
                         </a>
-                    </div>
+                    </p>
                 </div>
-                <div class="span4">
-                    <div class="categories-course-description">
-                        <h3>{{ course.title }}</h3>
-                        <h5>{{ 'Teacher'|get_lang }}: {{ course.teacher }}</h5>
-                    </div>
+            {% elseif buying_session %}
+                <div class="col-sm-6 col-md-5">
+                    <p>
+                        <img alt="{{ session.name }}" class="img-responsive" src="{{ session.image ? session.image : 'session_default.png'|icon() }}">
+                    </p>
+                    <p class="lead text-right">{{ session.currency }} {{ session.price }}</p>
                 </div>
-                <div class="span right">
-                    <div class="sprice right">{{ course.price }} {{ currency }}</div>
-                    <div class="cleared"></div>
-                    <div class="btn-toolbar right">
-                        <a class="ajax btn btn-primary" title=""
-                           href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">{{'Description'|get_lang }}
-                        </a>
-                    </div>
+                <div class="col-sm-6 col-md-7">
+                    <h3 class="page-header">{{ session.name }}</h3>
+                    <p>{{ session.dates.display }}</p>
+                    <dl>
+                        {% for course in session.courses %}
+                            <dt>{{ course.title }}</dt>
+                            {% for coach in course.coaches %}
+                                <dd><i class="fa fa-user fa-fw"></i> {{ coach }}</dd>
+                            {% endfor %}
+                        {% endfor %}
+                    </dl>
                 </div>
-            </div>
-        {% endif %}
+            {% endif %}
         </div>
     </div>
-    <div class="cleared"></div>
-    <form class="form-horizontal span3 offset4" action="../src/process_confirm.php" method="post">
-        <fieldset>
-            <legend align="center">{{ 'PaymentMethods'|get_plugin_lang('BuyCoursesPlugin') }}</legend>
-            <div align="center" class="control-group">
-                <div class="controls margin-left-fifty">
-                    {% if paypal_enable == "true" %}
-                        <label class="radio">
-                            <input type="radio" id="payment_type-p" name="payment_type" value="PayPal" > Paypal
-                        </label>
-                    {% endif %}
-                    {% if transfer_enable == "true" %}
-                        <label class="radio">
-                            <input type="radio" id="payment_type-tra" name="payment_type" value="Transfer" > {{ 'BankTransfer'|get_plugin_lang('BuyCoursesPlugin') }}
-                        </label>
-                    {% endif %}
-                </div>
-                </br>
-                <input type="hidden" name="currency_type" value="{{ currency }}" />
-                <input type="hidden" name="server" value="{{ server }}"/>
-                <input align="center" type="submit" class="btn btn-success" value="{{ 'ConfirmOrder'|get_plugin_lang('BuyCoursesPlugin') }}"/>
-            </div>
-        </fieldset>
-    </form>
-    <div class="cleared"></div>
+    <div class="col-md-5">
+        {{ form }}
+    </div>
 </div>

+ 76 - 77
plugin/buycourses/view/process_confirm.tpl

@@ -1,88 +1,87 @@
-<script type='text/javascript' src="../js/buycourses.js"></script>
-
-<link rel="stylesheet" type="text/css" href="../resources/plugin.css"/>
-
 <div class="row">
-    <div class="span12">
-        <div id="course_category_well" class="well span3">
-            <ul class="nav nav-list">
-                <li class="nav-header"><h4>{{ 'UserInformation'|get_plugin_lang('BuyCoursesPlugin') }}:</h4></li>
-                <li class="nav-header">{{ 'Name'|get_lang }}:</li>
-                <li><h5>{{ name | e }}</h5></li>
-                <li class="nav-header">{{ 'User'|get_lang }}:</li>
-                <li><h5>{{ user | e }}</h5></li>
-                <li class="nav-header">{{ 'Email'|get_lang }}:</li>
-                <li><h5>{{ email | e}}</h5></li>
-                <br/>
-            </ul>
-        </div>
-
-        <br/><br/>
-
-        <div class="well_border span8">
+    <div class="col-sm-6 col-md-5">
+        <h3 class="page-header">{{ 'UserInformation'|get_plugin_lang('BuyCoursesPlugin') }}</h3>
+        <dl class="dl-horizontal">
+            <dt>{{ 'Name'|get_lang }}<dt>
+            <dd>{{ user.complete_name }}</dd>
+            <dt>{{ 'Username'|get_lang }}<dt>
+            <dd>{{ user.username }}</dd>
+            <dt>{{ 'EmailAddress'|get_lang }}<dt>
+            <dd>{{ user.email }}</dd>
+        </dl>
+    </div>
+    <div class="col-sm-6 col-md-7">
+        {% if buying_course %}
             <div class="row">
-                <div class="span">
-                    <div class="thumbnail">
-                        <a class="ajax" rel="gb_page_center[778]" title=""
-                           href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">
-                            <img src="{{ server }}{{ course.course_img }}">
+                <div class="col-sm-6 col-md-5">
+                    <p>
+                        <img alt="{{ course.title }}" class="img-responsive" src="{{ course.course_img ? course.course_img : 'session_default.png'|icon() }}">
+                    </p>
+                    <p class="lead text-right">{{ course.currency }} {{ course.price }}</p>
+                </div>
+                <div class="col-sm-6 col-md-7">
+                    <h3 class="page-header">{{ course.title }}</h3>
+                    <ul class="items-teacher list-unstyled">
+                        {% for teacher in course.teachers %}
+                            <li><i class="fa fa-user"></i> {{ teacher }}</li>
+                        {% endfor %}
+                    </ul>
+                    <p>
+                        <a class="ajax btn btn-primary btn-sm" data-title="{{ course.title }}" href="{{ _p.web_ajax ~ 'course_home.ajax.php?' ~ {'a': 'show_course_information', 'code': course.code}|url_encode() }}">
+                            {{'Description'|get_lang }}
                         </a>
-                    </div>
+                    </p>
                 </div>
-                <div class="span4">
-                    <div class="categories-course-description">
-                        <h3>{{ course.title }}</h3>
-                        <h5>{{ 'Teacher'|get_lang }}: {{ course.teacher }}</h5>
-                    </div>
+            </div>
+        {% elseif buying_session %}
+            <h3 class="page-header">{{ session.name }}</h3>
+            <div class="row">
+                <div class="col-sm-12 col-md-5">
+                    <p>
+                        <img alt="{{ session.name }}" class="img-responsive" src="{{ session.image ? session.image : 'session_default.png'|icon() }}">
+                    </p>
+                    <p class="lead text-right">{{ session.currency }} {{ session.price }}</p>
                 </div>
-                <div class="span right">
-                    <div class="sprice right">{{ course.price }} {{ currency }}</div>
-                    <div class="cleared"></div>
-                    <div class="btn-toolbar right">
-                        <a class="ajax btn btn-primary" title=""
-                           href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">{{'Description'|get_lang }}
-                        </a>
-                    </div>
+                <div class="col-sm-12 col-md-7">
+                    <p>{{ session.dates.display }}</p>
+                    <dl>
+                        {% for course in session.courses %}
+                            <dt>{{ course.title }}</dt>
+                            {% for coach in course.coaches %}
+                                <dd><i class="fa fa-user fa-fw"></i> {{ coach }}</dd>
+                            {% endfor %}
+                        {% endfor %}
+                    </dl>
                 </div>
             </div>
-        </div>
+        {% endif %}
     </div>
-    <div class="cleared"></div>
-    <hr/>
-    <div align="center">
-        <table class="data_table" style="width:70%">
-            <tr>
-                <th class="ta-center">{{ 'BankAccountInformation'|get_plugin_lang('BuyCoursesPlugin') }}</th>
-            </tr>
-            {% set i = 0 %}
-            {% for account in accounts %}
-            {{ i%2==0 ? '<tr class="row_even">' : '<tr class="row_odd">' }}
-                {% set i = i + 1 %}
-                <td class="ta-center">
-                <font color="#0000FF">{{ account.name | e }}</font><br/>
-                {% if account.swift != '' %}
-                SWIFT: <strong>{{ account.swift | e }}</strong><br/>
-                {% endif %}
-                {{ 'BankAccount'|get_plugin_lang('BuyCoursesPlugin') }}: <strong>{{ account.account | e }}</strong><br/>
-                </td></tr>
-            {% endfor %}
+</div>
+<div class="row">
+    <div class="col-xs-12">
+        <h3 class="page-header">{{ 'BankAccountInformation'|get_plugin_lang('BuyCoursesPlugin') }}</h3>
+        <div class="table-responsive">
+            <table class="table table-striped table-hover">
+                <thead>
+                    <tr>
+                        <th>{{ 'Name'|get_lang }}</th>
+                        <th class="text-center">{{ 'BankAccount'|get_plugin_lang('BuyCoursesPlugin') }}</th>
+                        <th class="text-center">{{ 'SWIFT'|get_lang }}</th>
+                    </tr>
+                </thead>
+                <tbody>
+                    {% for account in transfer_accounts %}
+                        <tr>
+                            <td>{{ account.name }}</td>
+                            <td class="text-center">{{ account.account }}</td>
+                            <td class="text-center">{{ account.swift }}</td>
+                        </tr>
+                    {% endfor %}
+                </tbody>
             </table>
-            <br />
-            <div class="normal-message">{{ 'OnceItIsConfirmed,YouWillReceiveAnEmailWithTheBankInformationAndAnOrderReference'|get_plugin_lang('BuyCoursesPlugin') | e}}
-    </div>
-    <br/>
-
-    <form method="post" name="frmConfirm" action="../src/process_confirm.php">
-        <input type="hidden" name="payment_type" value="Transfer"/>
-        <input type="hidden" name="name" value="{{ name | e }}"/>
-        <input type="hidden" name="price" value="{{ course.price }}"/>
-        <input type="hidden" name="title" value="{{ course.title | e }}"/>
-
-        <div class="btn_next">
-            <input class="btn btn-success" type="submit" name="Confirm" value="{{ 'ConfirmOrder'|get_plugin_lang('BuyCoursesPlugin') }}"/>
-            <input class="btn btn-danger" type="button" name="Cancel" value="{{ 'CancelOrder'|get_plugin_lang('BuyCoursesPlugin') }}" id="CancelOrder"/>
         </div>
-    </form>
-</div>
-<div class="cleared"></div>
+        <p>{{ 'OnceItIsConfirmedYouWillReceiveAnEmailWithTheBankInformationAndAnOrderReference'|get_plugin_lang('BuyCoursesPlugin') }}</p>
+    </div>
 </div>
+
+{{ form }}

+ 53 - 0
plugin/buycourses/view/sales_report.tpl

@@ -0,0 +1,53 @@
+{{ form }}
+
+<div class="table-responsive">
+    <table class="table table-striped table-hover">
+        <thead>
+            <tr>
+                <th class="text-center">{{ 'OrderReference'|get_plugin_lang('BuyCoursesPlugin') }}</th>
+                <th class="text-center">{{ 'OrderStatus'|get_plugin_lang('BuyCoursesPlugin') }}</th>
+                <th class="text-center">{{ 'OrderDate'|get_plugin_lang('BuyCoursesPlugin') }}</th>
+                <th class="text-center">{{ 'Price'|get_plugin_lang('BuyCoursesPlugin') }}</th>
+                <th class="text-center">{{ 'ProductType'|get_plugin_lang('BuyCoursesPlugin') }}</th>
+                <th>{{ 'Name'|get_lang }}</th>
+                <th>{{ 'UserName'|get_lang }}</th>
+                {% if selected_status == sale_status_pending %}
+                    <th class="text-center">{{ 'Options'|get_lang }}</th>
+                {% endif %}
+            </tr>
+        </thead>
+        <tbody>
+            {% for sale in sale_list %}
+                <tr {{ sale.id == selected_sale ? 'class="warning"' : '' }}>
+                    <td class="text-center">{{ sale.reference }}</td>
+                    <td class="text-center">
+                        {% if sale.status == sale_status_canceled %}
+                            {{ 'SaleStatusCanceled'|get_plugin_lang('BuyCoursesPlugin') }}
+                        {% elseif sale.status == sale_status_pending %}
+                            {{ 'SaleStatusPending'|get_plugin_lang('BuyCoursesPlugin') }}
+                        {% elseif sale.status == sale_status_completed %}
+                            {{ 'SaleStatusCompleted'|get_plugin_lang('BuyCoursesPlugin') }}
+                        {% endif %}
+                    </td>
+                    <td class="text-center">{{ sale.date }}</td>
+                    <td class="text-right">{{ sale.currency ~ ' ' ~ sale.price }}</td>
+                    <td class="text-center">{{ sale.product_type }}</td>
+                    <td>{{ sale.product_name }}</td>
+                    <td>{{ sale.complete_user_name }}</td>
+                    {% if selected_status == sale_status_pending %}
+                        <td class="text-center">
+                            {% if sale.status == sale_status_pending %}
+                                <a href="{{ _p.web_self ~ '?' ~ {'order': sale.id, 'action': 'confirm'}|url_encode() }}" class="btn btn-success btn-sm">
+                                    <i class="fa fa-user-plus fa-fw"></i> {{ 'SubscribeUser'|get_plugin_lang('BuyCoursesPlugin') }}
+                                </a>
+                                <a href="{{ _p.web_self ~ '?' ~ {'order': sale.id, 'action': 'cancel'}|url_encode() }}" class="btn btn-danger btn-sm">
+                                    <i class="fa fa-times fa-fw"></i> {{ 'DeleteOrder'|get_plugin_lang('BuyCoursesPlugin') }}
+                                </a>
+                            {% endif %}
+                        </td>
+                    {% endif %}
+                </tr>
+            {% endfor %}
+        </tbody>
+    </table>
+</div>

+ 53 - 95
plugin/buycourses/view/success.tpl

@@ -1,106 +1,64 @@
-<script type='text/javascript' src="../js/buycourses.js"></script>
-
-<link rel="stylesheet" type="text/css" href="../resources/plugin.css"/>
-
+<div class="alert alert-info">
+    {{ 'PayPalPaymentOKPleaseConfirm'|get_plugin_lang('BuyCoursesPlugin') }}
+</div>
 <div class="row">
-    <div class="span12">
-        <div id="course_category_well" class="well span3">
-            <ul class="nav nav-list">
-                <li class="nav-header"><h4>{{ 'UserInformation'|get_plugin_lang('BuyCoursesPlugin') }}:</h4></li>
-                <li class="nav-header">{{ 'Name'|get_lang }}:</li>
-                <li><h5>{{ name }}</h5></li>
-                <li class="nav-header">{{ 'User'|get_lang }}:</li>
-                <li><h5>{{ user }}</h5></li>
-                <li class="nav-header">{{ 'Email'|get_lang }}:</li>
-                <li><h5>{{ email }}</h5></li>
-                <br/>
-            </ul>
-        </div>
-
-        <br/><br/>
-
-        <div class="well_border span8">
-            {% if isSession == "YES" %}
+    <div class="col-sm-6 col-md-5">
+        <h3 class="page-header">{{ 'UserInformation'|get_plugin_lang('BuyCoursesPlugin') }}</h3>
+        <dl class="dl-horizontal">
+            <dt>{{ 'Name'|get_lang }}<dt>
+            <dd>{{ user.complete_name }}</dd>
+            <dt>{{ 'Username'|get_lang }}<dt>
+            <dd>{{ user.username }}</dd>
+            <dt>{{ 'EmailAddress'|get_lang }}<dt>
+            <dd>{{ user.email }}</dd>
+        </dl>
+    </div>
+    <div class="col-sm-6 col-md-7">
+        {% if buying_course %}
             <div class="row">
-                <div class="span4">
-                    <div class="categories-course-description">
-                        <h3>{{ session.name }}</h3>
-                        <h5>{{ 'From'|get_lang }} {{ session.access_start_date }} {{ 'To'|get_lang }} {{ session.access_end_date }}</h5>
-                    </div>
+                <div class="col-sm-6 col-md-5">
+                    <p>
+                        <img alt="{{ course.title }}" class="img-responsive" src="{{ course.course_img ? course.course_img : 'session_default.png'|icon() }}">
+                    </p>
+                    <p class="lead text-right">{{ course.currency }} {{ course.price }}</p>
                 </div>
-                <div class="span right">
-                    <div class="sprice right">
-                        {{ session.price }} {{ currency }}
-                    </div>
-                    <div class="cleared"></div>
+                <div class="col-sm-6 col-md-7">
+                    <h3 class="page-header">{{ course.title }}</h3>
+                    <ul class="items-teacher list-unstyled">
+                        {% for teacher in course.teachers %}
+                            <li><i class="fa fa-user"></i> {{ teacher }}</li>
+                        {% endfor %}
+                    </ul>
+                    <p>
+                        <a class="ajax btn btn-primary btn-sm" data-title="{{ course.title }}" href="{{ _p.web_ajax ~ 'course_home.ajax.php?' ~ {'a': 'show_course_information', 'code': course.code}|url_encode() }}">
+                            {{'Description'|get_lang }}
+                        </a>
+                    </p>
                 </div>
             </div>
-            {% for course in session.courses %}
-                <div class="row">
-                    <div class="span">
-                        <div class="thumbnail">
-                            <a class="ajax" rel="gb_page_center[778]" title="" href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">
-                                <img alt="" src="{{ server }}{{ course.course_img }}">
-                            </a>
-                        </div>
-                    </div>
-                    <div class="span4">
-                        <div class="categories-course-description">
-                            <h3>{{ course.title }}</h3>
-                            <h5>{{ 'Teacher'|get_lang }}: {{ course.teacher }}</h5>
-                        </div>
-                    </div>
-                    <div class="span right">
-                        <div class="cleared"></div>
-                        <div class="btn-toolbar right">
-                            <a class="ajax btn btn-primary" title="" href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">
-                                {{ 'Description'|get_lang }}
-                            </a>
-                        </div>
-                    </div>
-                </div>
-            {% endfor %}
-            {% else %}
+        {% elseif buying_session %}
+            <h3 class="page-header">{{ session.name }}</h3>
             <div class="row">
-                <div class="span">
-                    <div class="thumbnail">
-                        <a class="ajax" rel="gb_page_center[778]" title=""
-                           href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">
-                            <img alt="" src="{{ server }}{{ course.course_img }}">
-                        </a>
-                    </div>
-                </div>
-                <div class="span4">
-                    <div class="categories-course-description">
-                        <h3>{{ course.title }}</h3>
-                        <h5>{{ 'Teacher'|get_lang }}: {{ course.teacher }}</h5>
-                    </div>
+                <div class="col-sm-12 col-md-5">
+                    <p>
+                        <img alt="{{ session.name }}" class="img-responsive" src="{{ session.image ? session.image : 'session_default.png'|icon() }}">
+                    </p>
+                    <p class="lead text-right">{{ session.currency }} {{ session.price }}</p>
                 </div>
-                <div class="span right">
-                    <div class="sprice right">{{ course.price }} {{ currency }}</div>
-                    <div class="cleared"></div>
-                    <div class="btn-toolbar right">
-                        <a class="ajax btn btn-primary" title=""
-                           href="{{ server }}plugin/buycourses/src/ajax.php?code={{ course.code }}">{{'Description'|get_lang }}</a>
-
-                    </div>
+                <div class="col-sm-12 col-md-7">
+                    <p>{{ session.dates.display }}</p>
+                    <dl>
+                        {% for course in session.courses %}
+                            <dt>{{ course.title }}</dt>
+                            {% for coach in course.coaches %}
+                                <dd><i class="fa fa-user fa-fw"></i> {{ coach }}</dd>
+                            {% endfor %}
+                        {% endfor %}
+                    </dl>
                 </div>
             </div>
-            {% endif %}
-        </div>
-    </div>
-    <div class="cleared"></div>
-    <hr/>
-    <div align="center">
-        <div class="confirmation-message">{{ 'PayPalPaymentOKPleaseConfirm'|get_plugin_lang('BuyCoursesPlugin') }}</div>
-        <br />
-        <form method="post" name="frmConfirm" action="../src/success.php">
-            <input type="hidden" name="paymentOption" value="PayPal"/>
-            <div class="btn_next">
-                <input class="btn btn-success" type="submit" name="Confirm" value="{{ 'ConfirmOrder'|get_plugin_lang('BuyCoursesPlugin') }}"/>
-                <input class="btn btn-danger" type="button" name="Cancel" value="{{ 'CancelOrder'|get_plugin_lang('BuyCoursesPlugin') }}" id="cancel_order"/>
-            </div>
-        </form>
+        {% endif %}
     </div>
-    <div class="cleared"></div>
 </div>
+    
+{{ form }}

+ 9 - 9
plugin/tour/lang/french.php

@@ -39,19 +39,19 @@ $strings['TheHomePageStep'] = 'Ceci est la page d\'accueil du portail. On y retr
 $strings['YourCoursesList'] = 'Cette zone affiche les différents cours (ou sessions) auxquels vous avez accès. Si aucun cours ne s\'affiche, rendez-vous sur le catalogue de cours (voir menu) ou parlez-en à votre administrateur de portail';
 
 // if body class = section-myagenda
-$strings['AgendaAllowsYouToSeeWhatsHappening'] = 'The agenda tool allows you to see what events are scheduled for the upcoming days, weeks or months.';
-$strings['AgendaTheActionBar'] = 'You can decide to show the events as a list, rather than in a calendar view, using the action icons provided';
-$strings['AgendaTodayButton'] = 'Click the "today" button to see only today\'s schedule';
-$strings['AgendaTheMonthIsAlwaysInEvidence'] = 'The current month is always shown in evidence in the calendar view';
-$strings['AgendaButtonsAllowYouToChangePeriod'] = 'You can switch the view to daily, weekly or monthly by clicking one of these buttons';
+$strings['AgendaAllowsYouToSeeWhatsHappening'] = 'L\'outil d\'agenda vous permet de voir les événements qui sont programmés pour les prochains jours, semaines ou mois.';
+$strings['AgendaTheActionBar'] = 'Vous pouvez décider de montrer les événements sous forme de liste, plutôt qu\'en vue calendrier, en utilisant les icônes d\'action fournis';
+$strings['AgendaTodayButton'] = 'Cliquez sur le bouton "Aujourd\'hui pour voir seulement le programme d\'aujourd\'hui';
+$strings['AgendaTheMonthIsAlwaysInEvidence'] = 'Le mois actuel est toujours mis en évidence dans la vue calendrier';
+$strings['AgendaButtonsAllowYouToChangePeriod'] = 'Vous pouvez changer la vue à quotidien, semanal ou mensuel en cliquant sur l\'un de ces boutons';
 
 // if body class = section-session_my_space
-$strings['MySpaceAllowsYouToKeepTrackOfProgress'] = 'This area allows you to check your progress if you\'re a student, or the progress of your students if you are a teacher';
-$strings['MySpaceSectionsGiveYouImportantInsight'] = 'The reports provided on this screen are extensible and can provide you very valuable insight on your learning or teaching';
+$strings['MySpaceAllowsYouToKeepTrackOfProgress'] = 'Cette zone vous permet de vérifier votre progrès si vous êtes étudiant, ou le progrès de vos étudiants si vous êtes enseignant';
+$strings['MySpaceSectionsGiveYouImportantInsight'] = 'Les rapports fournis sur cet écran sont extensibles et peuvent vous fournir un détail intéressant sur votre apprentissage ou la façon dont vous enseignez.';
 
 // if body class = section-social-network
-$strings['SocialAllowsYouToGetInTouchWithOtherUsersOfThePlatform'] = 'The social area allows you to get in touch with other users on the platform';
-$strings['SocialMenuGivesAccessToDifferentToolsToGetInTouchOrPublishStuff'] = 'The menu gives you access to a series of screens allowing you to participate in private messaging, chat, interest groups, etc';
+$strings['SocialAllowsYouToGetInTouchWithOtherUsersOfThePlatform'] = 'La zone sociale vous permet de vous maintenir au courant de ce que font les autres utilisateurs de la plateforme';
+$strings['SocialMenuGivesAccessToDifferentToolsToGetInTouchOrPublishStuff'] = 'Le menu vous donne accès à une série d\'écrans vous permettant de participer à de la messagerie privée, du chat, des groupes d\'intérêt, etc';
 
 // if body class = section-dashboard
 $strings['DashboardAllowsYouToGetVerySpecificInformationInAnIllustratedCondensedFormat'] = 'The dashboard allows you to get very specific information in an illustrated and condensed format. Only administrators have access to this feature at this time';