Ver Fonte

Fix PayPal process - refs #7768

Angel Fernando Quiroz Campos há 9 anos atrás
pai
commit
e1f3bb96a7

+ 198 - 8
plugin/buycourses/src/buy_course_plugin.class.php

@@ -14,6 +14,11 @@ class BuyCoursesPlugin extends Plugin
 {
     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;
 
     /**
      *
@@ -230,11 +235,11 @@ class BuyCoursesPlugin extends Plugin
 
     /**
      * Get the item data
-     * @param int $itemId The item ID
+     * @param int $productId The item ID
      * @param int $itemType The item type
      * @return array
      */
-    private function getItem($itemId, $itemType)
+    public function getItemByProduct($productId, $itemType)
     {
         $buyItemTable = Database::get_main_table(BuyCoursesUtils::TABLE_ITEM);
         $buyCurrencyTable = Database::get_main_table(BuyCoursesUtils::TABLE_CURRENCY);
@@ -250,7 +255,10 @@ class BuyCoursesPlugin extends Plugin
             $fakeItemFrom,
             [
                 'where' => [
-                    'i.product_id = ? AND i.product_type = ?' => [$itemId, $itemType]
+                    'i.product_id = ? AND i.product_type = ?' => [
+                        intval($productId),
+                        intval($itemType)
+                    ]
                 ]
             ],
             'first'
@@ -284,7 +292,7 @@ class BuyCoursesPlugin extends Plugin
                 'price' => 0.00
             ];
 
-            $item = $this->getItem($course->getId(), self::PRODUCT_TYPE_COURSE);
+            $item = $this->getItemByProduct($course->getId(), self::PRODUCT_TYPE_COURSE);
 
             if ($item !== false) {
                 $courseItem['visible'] = true;
@@ -440,7 +448,7 @@ class BuyCoursesPlugin extends Plugin
                 continue;
             }
 
-            $item = $this->getItem($session->getId(), self::PRODUCT_TYPE_SESSION);
+            $item = $this->getItemByProduct($session->getId(), self::PRODUCT_TYPE_SESSION);
 
             if (empty($item)) {
                 continue;
@@ -555,7 +563,7 @@ class BuyCoursesPlugin extends Plugin
         $courseCatalog = [];
 
         foreach ($courses as $course) {
-            $item = $this->getItem($course->getId(), self::PRODUCT_TYPE_COURSE);
+            $item = $this->getItemByProduct($course->getId(), self::PRODUCT_TYPE_COURSE);
 
             if (empty($item)) {
                 continue;
@@ -608,7 +616,7 @@ class BuyCoursesPlugin extends Plugin
             return [];
         }
 
-        $item = $this->getItem($course->getId(), self::PRODUCT_TYPE_COURSE);
+        $item = $this->getItemByProduct($course->getId(), self::PRODUCT_TYPE_COURSE);
 
         if (empty($item)) {
             return [];
@@ -658,7 +666,7 @@ class BuyCoursesPlugin extends Plugin
             return [];
         }
 
-        $item = $this->getItem($session->getId(), self::PRODUCT_TYPE_SESSION);
+        $item = $this->getItemByProduct($session->getId(), self::PRODUCT_TYPE_SESSION);
 
         if (empty($item)) {
             return [];
@@ -719,4 +727,186 @@ class BuyCoursesPlugin extends Plugin
         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(BuyCoursesUtils::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 = [
+            '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(BuyCoursesUtils::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(BuyCoursesUtils::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(BuyCoursesUtils::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(BuyCoursesUtils::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')
+        ];
+    }
+
 }

+ 45 - 5
plugin/buycourses/src/process.php

@@ -15,19 +15,58 @@ $includeSession = $plugin->get('include_sessions') === 'true';
 $paypalEnabled = $plugin->get('paypal_enable') === 'true';
 $transferEnabled = $plugin->get('transfer_enable') === 'true';
 
-if (!isset($_GET['t'], $_GET['i'])) {
+if (!isset($_REQUEST['t'], $_REQUEST['i'])) {
     die;
 }
 
-$buyingCourse = intval($_GET['t']) === BuyCoursesPlugin::PRODUCT_TYPE_COURSE;
-$buyingSession = intval($_GET['t']) === BuyCoursesPlugin::PRODUCT_TYPE_SESSION;
+$buyingCourse = intval($_REQUEST['t']) === BuyCoursesPlugin::PRODUCT_TYPE_COURSE;
+$buyingSession = intval($_REQUEST['t']) === BuyCoursesPlugin::PRODUCT_TYPE_SESSION;
 
 if ($buyingCourse) {
-    $courseInfo = $plugin->getCourseInfo($_GET['i']);
+    $courseInfo = $plugin->getCourseInfo($_REQUEST['i']);
+    $item = $plugin->getItemByProduct($_REQUEST['i'], BuyCoursesPlugin::PRODUCT_TYPE_COURSE);
 } elseif ($buyingSession) {
-    $sessionInfo = $plugin->getSessionInfo($_GET['i']);
+    $sessionInfo = $plugin->getSessionInfo($_REQUEST['i']);
+    $item = $plugin->getItemByProduct($_REQUEST['i'], BuyCoursesPlugin::PRODUCT_TYPE_SESSION);
 }
 
+$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');  
+    }
+
+    exit;
+}
+
+$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'));
+$form->addRadio(
+    'payment_type',
+    null,
+    $plugin->getPaymentTypes()
+);
+$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" => "list.php", "name" => $plugin->get_lang('CourseListOnSale'));
@@ -38,6 +77,7 @@ $tpl->assign('buying_session', $buyingSession);
 $tpl->assign('user', api_get_user_info());
 $tpl->assign('paypal_enabled', $paypalEnabled);
 $tpl->assign('transfer_enabled', $transferEnabled);
+$tpl->assign('form', $form->returnForm());
 
 if ($buyingCourse) {
     $tpl->assign('course', $courseInfo);

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

@@ -10,158 +10,59 @@
 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);
-
-$buySessionTemporaryTable = Database::get_main_table(TABLE_BUY_SESSION_TEMPORARY);
-
-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 $buySessionTemporaryTable (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;
+$saleId = $_SESSION['bc_sale_id'];
 
-    api_mail_html($name, $email, $asunto, $message);
-    // Return to course list
-    header('Location:list.php');
+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);
+$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') {
+            var_dump([
+                'error_code' => $expressCheckout['L_ERRORCODE0'],
+                'short_message' => $expressCheckout['L_SHORTMESSAGE0'],
+                'long_message' => $expressCheckout['L_LONGMESSAGE0'],
+                'severity_code' => $expressCheckout['L_SEVERITYCODE0']
+            ]);
+            exit;
+        }
 
-    $listing_tpl = 'buycourses/view/process_confirm.tpl';
-    $content = $tpl->fetch($listing_tpl);
-    $tpl->assign('content', $content);
-    $tpl->display_one_col_template();
+        RedirectToPayPal($expressCheckout["TOKEN"]);
+        break;
+    case BuyCoursesPlugin::PAYMENT_TYPE_TRANSFER:
+        break;
 }

+ 162 - 302
plugin/buycourses/src/success.php

@@ -7,337 +7,197 @@
 /**
  * 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();
 
-/**
- * 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");
+$sale = $plugin->getSale($_SESSION['bc_sale_id']);
 
-/**
- * PayPal Express Checkout Call
- */
-
-// 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();
 
-if (!isset($_POST['paymentOption'])) {
-    // Confirm the order
-    $_cid = 0;
-    $templateName = $plugin->get_lang('PaymentMethods');
-    $interbreadcrumb[] = array("url" => "list.php", "name" => $plugin->get_lang('CourseListOnSale'));
-
-    $tpl = new Template($templateName);
-
-    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']));
-    }
-
-    $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']);
-    }
-
-
-    $listing_tpl = 'buycourses/view/success.tpl';
-    $content = $tpl->fetch($listing_tpl);
-    $tpl->assign('content', $content);
-    $tpl->display_one_col_template();
+$pruebas = $paypalParams['sandbox'] == 1;
+$paypalUsername = $paypalParams['username'];
+$paypalPassword = $paypalParams['password'];
+$paypalSignature = $paypalParams['signature'];
 
-} 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.
-             */
+require_once("paypalfunctions.php");
 
-            $paymentStatus = $resArray["PAYMENTINFO_0_PAYMENTSTATUS"];
+$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');
 
-            /**
-             * 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"];
+if ($form->validate()) {
+    $formValues = $form->getSubmitValues();
 
-            /**
-             * 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.
-             */
+    if (isset($formValues['cancel'])) {
+        $plugin->cancelSale($sale['id']);
 
-            $reasonCode = $resArray["PAYMENTINFO_0_REASONCODE"];
+        unset($_SESSION['bc_sale_id']);
 
-            // 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;
-                    }
-                }
+        header('Location: ' . api_get_path(WEB_PLUGIN_PATH) . 'buycourses/index.php');
+        exit;
+    }
 
-                // 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);
+    $confirmPayments = ConfirmPayment($sale['price']);
 
-                $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);
+    if ($confirmPayments['ACK'] !== 'Success') {
+        var_dump([
+            'error_code' => $confirmPayments['L_ERRORCODE0'],
+            'short_message' => $confirmPayments['L_SHORTMESSAGE0'],
+            'long_message' => $confirmPayments['L_LONGMESSAGE0'],
+            'severity_code' => $confirmPayments['L_SEVERITYCODE0']
+        ]);
+        exit;
+    }
 
-                $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";
+    $transactionId = $confirmPayments["PAYMENTINFO_0_TRANSACTIONID"];
+    $transactionType = $confirmPayments["PAYMENTINFO_0_TRANSACTIONTYPE"];
+
+    switch ($confirmPayments["PAYMENTINFO_0_PAYMENTSTATUS"]) {
+        case 'Completed':
+            $saleIsCompleted = $plugin->completeSale($sale['id']);
+
+            if ($saleIsCompleted && $buyingCourse) {
+                Display::addFlash(
+                    Display::return_message(
+                        sprintf($plugin->get_lang('EnrollToSessionXSuccessful'), $session['name']),
+                        'success'
+                    )
+                );
+                break;
+            }
 
-                $result = Database::query($sql);
+            if ($saleIsCompleted && $buyingSession) {
+                Display::addFlash(
+                    Display::return_message(
+                        sprintf($plugin->get_lang('EnrollToCourseXSuccessful'), $course['name']),
+                        'success'
+                    )
+                );
+                break;
+            }
 
-                if (Database::num_rows($result) > 0) {
-                    // Extracting the user data
-                    $uData = Database::fetch_array($result);
+            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;
+            }
 
-                    $_user = _api_format_user($uData, false);
-                    $_user['lastLogin'] = api_strtotime($uData['login_date'], 'UTC');
+            Display::addFlash(
+                Display::return_message(
+                    sprintf($plugin->get_lang('PurchaseStatusX'), $purchaseStatus),
+                    'warning'
+                )
+            );
+            break;
+        default:
+            Display::addFlash(
+                Display::return_message($plugin->get_lang('ErrorContactPlatformAdmin'), 'error')
+            );
+            break;
+    }
 
-                    $is_platformAdmin = (bool)(!is_null($uData['is_admin']));
+    unset($_SESSION['bc_sale_id']);
+    header('Location: ' . api_get_path(WEB_PLUGIN_PATH) . 'buycourses/src/list.php');
+    exit;
+}
 
-                    $is_allowedCreateCourse = (bool)(($uData ['status'] == COURSEMANAGER) or (api_get_setting('drhCourseManagerRights') and $uData['status'] == DRH));
+$token = isset($_GET['token']) ? $_GET['token'] : null;
 
-                    ConditionalLogin::check_conditions($uData);
+if (empty($token)) {
+    api_not_allowed(true);
+}
 
-                    Session::write('_user', $_user);
+$shippingDetails = GetShippingDetails($token);
 
-                    UserManager::update_extra_field_value($_user['user_id'], 'already_logged_in', 'true');
-                    Session::write('is_platformAdmin', $is_platformAdmin);
+if ($shippingDetails['ACK'] !== 'Success') {
+    var_dump([
+        'error_code' => $shippingDetails['L_ERRORCODE0'],
+        'short_message' => $shippingDetails['L_SHORTMESSAGE0'],
+        'long_message' => $shippingDetails['L_LONGMESSAGE0'],
+        'severity_code' => $shippingDetails['L_SEVERITYCODE0']
+    ]);
+    exit;
+}
 
-                    Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
+$interbreadcrumb[] = array("url" => "list.php", "name" => $plugin->get_lang('CourseListOnSale'));
 
-                } else {
-                    header('location:' . api_get_path(WEB_PATH));
-                }
+$templateName = $plugin->get_lang('PaymentMethods');
+$tpl = new Template($templateName);
 
-                // 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');
-            }
-        } 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');
-        }
-    }
+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();

+ 1 - 30
plugin/buycourses/view/process.tpl

@@ -49,35 +49,6 @@
         </div>
     </div>
     <div class="col-md-5">
-        <form action="../src/process_confirm.php" method="post">
-            <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>{{ 'User'|get_lang }}:</dt>
-                <dd>{{ user.username }}</dd>
-                <dt>{{ 'Email'|get_lang }}:</dt>
-                <dd>{{ user.email }}</dd>
-            </dl>
-            <legend align="center">{{ 'PaymentMethods'|get_plugin_lang('BuyCoursesPlugin') }}</legend>
-            <div class="form-group">
-                {% if paypal_enabled == "true" %}
-                    <label class="radio-inline">
-                        <input type="radio" name="payment_type" value="PayPal" > <i class="fa fa-fw fa-cc-paypal"></i> Paypal
-                    </label>
-                {% endif %}
-
-                {% if transfer_enabled == "true" %}
-                    <label class="radio-inline">
-                        <input type="radio" name="payment_type" value="Transfer" > <i class="fa fa-fw fa-money"></i> {{ 'BankTransfer'|get_plugin_lang('BuyCoursesPlugin') }}
-                    </label>
-                {% endif %}
-            </div>
-            <div class="form-group">
-                <button class="btn btn-success" type="submit">
-                    <i class="fa fa-check"></i> {{ 'ConfirmOrder'|get_plugin_lang('BuyCoursesPlugin') }}
-                </button>
-            </div>
-        </form>
+        {{ form }}
     </div>
 </div>

+ 58 - 106
plugin/buycourses/view/success.tpl

@@ -1,112 +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="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>
-                    <div class="span right">
-                        <div class="sprice right">
-                            {{ session.price }} {{ currency }}
-                        </div>
-                        <div class="cleared"></div>
-                    </div>
+    <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="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>
-                {% 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 %}
-                <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="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>
+                <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>
+        {% 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="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>
-            {% 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 }}