<commit_before><?php
/**
 * @title          Main Controller
 *
 * @author         <NAME> <<EMAIL>>
 * @copyright      (c) 2012-2017, <NAME>. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Payment / Controller
 * @version        1.4
 */

namespace PH7;

use Braintree_Transaction;
use PH7\Framework\Cache\Cache;
use PH7\Framework\File\File;
use PH7\Framework\Mail\Mail;
use PH7\Framework\Mvc\Model\DbConfig;
use PH7\Framework\Payment\Gateway\Api\Api as ApiInterface;

class MainController extends Controller
{
    const PAYPAL_GATEWAY_NAME = 'paypal';
    const STRIPE_GATEWAY_NAME = 'stripe';
    const BRAINTREE_GATEWAY_NAME = 'braintree';
    const TWO_CHECKOUT_GATEWAY_NAME = '2co';
    const CCBILL_GATEWAY_NAME = 'ccbill';


    /** @var AffiliateCoreModel */
    protected $oUserModel;

    /** @var PaymentModel */
    protected $oPayModel;

    /** @var string */
    protected $sTitle;

    /** @var int */
    protected $iProfileId;

    /** @var bool Payment status. Default is failure (FALSE) */
    private $_bStatus = false;


    public function __construct()
    {
        parent::__construct();

        $this->oUserModel = new AffiliateCoreModel;
        $this->oPayModel = new PaymentModel;
        $this->iProfileId = $this->session->get('member_id');
    }

    public function index()
    {
        $this->view->page_title = $this->view->h1_title = t('Payment Zone');
        $this->output();
    }

    public function membership()
    {
        $oMembershipData = $this->oPayModel->getMemberships();

        if (empty($oMembershipData)) {
            $this->displayPageNotFound(t('No membership found!'));
        } else {
            $this->view->page_title = $this->view->h2_title = t('Memberships List');
            $this->view->memberships = $oMembershipData;
            $this->output();
        }
    }

    /**
     * @param null|int $iMembershipId
     *
     * @return void
     */
    public function pay($iMembershipId = null)
    {
        $iMembershipId = (int) $iMembershipId;

        $oMembershipData = $this->oPayModel->getMemberships($iMembershipId);

        if (empty($iMembershipId) || empty($oMembershipData)) {
            $this->displayPageNotFound(t('No membership found!'));
        } else {
            // Adding the stylesheet for Gatway Logo
            $this->design->addCss(PH7_LAYOUT . PH7_SYS . PH7_MOD . $this->registry->module . PH7_SH . PH7_TPL . PH7_TPL_MOD_NAME . PH7_SH . PH7_CSS, 'common.css');

            // Regenerate the session ID to prevent the session fixation attack
            $this->session->regenerateId();

            $this->view->page_title = $this->view->h1_title = t('Payment Option');
            $this->view->membership = $oMembershipData;
            $this->output();
        }
    }

    /**
     * @param string $sProvider
     *
     * @return void
     */
    public function process($sProvider = '')
    {
        switch ($sProvider) {
            case static::PAYPAL_GATEWAY_NAME: {
                $oPayPal = new PayPal($this->config->values['module.setting']['sandbox.enabled']);
                if ($oPayPal->valid() && $this->httpRequest->postExists('custom')) {
                    $aData = explode('|', base64_decode($this->httpRequest->post('custom')));
                    $iItemNumber = (int) $aData[0];
                    if ($this->oUserModel->updateMembership(
                        $iItemNumber,
                        $this->iProfileId,
                        $this->dateTime->get()->dateTime('Y-m-d H:i:s'))
                    ) {
                        $this->_bStatus = true; // Status is OK
                        $this->updateUserGroupId($iItemNumber);
                        // PayPal will call automatically the "notification()" method thanks its IPN feature and "notify_url" form attribute.
                    }
                }
                unset($oPayPal);
            } break;

            case static::STRIPE_GATEWAY_NAME: {
                if ($this->httpRequest->postExists('stripeToken')) {
                    \Stripe\Stripe::setApiKey($this->config->values['module.setting']['stripe.secret_key']);
                    $sAmount = $this->httpRequest->post('amount');

                    try {
                        $oCharge = \Stripe\Charge::create(
                            [
                                'amount' => Stripe::getAmount($sAmount),
                                'currency' => $this->config->values['module.setting']['currency'],
                                'source' => $this->httpRequest->post('stripeToken'),
                                'description'    => 'Membership charged for ' . $this->httpRequest->post('stripeEmail')
                            ]
                        );

                        $iItemNumber = $this->httpRequest->post('item_number');
                        if ($this->oUserModel->updateMembership(
                            $iItemNumber,
                            $this->iProfileId,
                            $this->dateTime->get()->dateTime('Y-m-d H:i:s'))
                        ) {
                            $this->_bStatus = true; // Status is OK
                            $this->updateUserGroupId($iItemNumber);
                            $this->notification('Stripe', $iItemNumber); // Add info into the log file
                        }
                    }
                    catch (\Stripe\Error\Card $oE) {
                        // The card has been declined
                        // Do nothing here as "$this->_bStatus" is by default FALSE and so it will display "Error occurred" msg later
                    }
                    catch (\Stripe\Error\Base $oE) {
                        $this->design->setMessage( $this->str->escape($oE->getMessage(), true) );
                    }
                }
            } break;

            case static::BRAINTREE_GATEWAY_NAME: {
                if ($bNonce = $this->httpRequest->post('payment_method_nonce')) {
                    Braintree::init($this->config);

                    $oResult = Braintree_Transaction::sale([
                        'amount' => $this->httpRequest->post('amount'),
                        'paymentMethodNonce' => $bNonce,
                        'options' => [ 'submitForSettlement' => true ]
                    ]);

                    if ($oResult->success) {
                        $iItemNumber = $this->httpRequest->post('item_number');
                        if ($this->oUserModel->updateMembership(
                            $iItemNumber,
                            $this->iProfileId,
                            $this->dateTime->get()->dateTime('Y-m-d H:i:s'))
                        ) {
                            $this->_bStatus = true; // Status is OK
                            $this->updateUserGroupId($iItemNumber);
                            $this->notification('Braintree', $iItemNumber); // Add info into the log file
                        }
                    } else if ($oResult->transaction) {
                        print_r("Error processing transaction:");
                        print_r("\n  code: " . $oResult->transaction->processorResponseCode);
                        print_r("\n  text: " . $oResult->transaction->processorResponseText);
                    } else {
                        print_r("Validation errors: \n");
                        print_r($oResult->errors->deepAll());
                    }
                }
            } break;

            case static::TWO_CHECKOUT_GATEWAY_NAME: {
                $o2CO = new TwoCO($this->config->values['module.setting']['sandbox.enabled']);
                $sVendorId = $this->config->values['module.setting']['2co.vendor_id'];
                $sSecretWord = $this->config->values['module.setting']['2co.secret_word'];

                $iItemNumber = $this->httpRequest->post('cart_order_id');
                if ($o2CO->valid($sVendorId, $sSecretWord) && $this->httpRequest->postExists('sale_id')) {
                    if (
                        $this->oUserModel->updateMembership(
                            $iItemNumber,
                            $this->iProfileId,
                            $this->dateTime->get()->dateTime('Y-m-d H:i:s')
                        )
                    ) {
                        $this->_bStatus = true; // Status is OK
                        $this->updateUserGroupId($iItemNumber);
                        $this->notification('TwoCO', $iItemNumber); // Add info into the log file
                    }
                }
                unset($o2CO);
            } break;<commit_msg>Show message dialog when on failure<commit_after><?php
/**
 * @title          Main Controller
 *
 * @author         <NAME> <<EMAIL>>
 * @copyright      (c) 2012-2017, <NAME>. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Payment / Controller
 * @version        1.4
 */

namespace PH7;

use Braintree_Transaction;
use PH7\Framework\Cache\Cache;
use PH7\Framework\File\File;
use PH7\Framework\Mail\Mail;
use PH7\Framework\Mvc\Model\DbConfig;
use PH7\Framework\Payment\Gateway\Api\Api as ApiInterface;

class MainController extends Controller
{
    const PAYPAL_GATEWAY_NAME = 'paypal';
    const STRIPE_GATEWAY_NAME = 'stripe';
    const BRAINTREE_GATEWAY_NAME = 'braintree';
    const TWO_CHECKOUT_GATEWAY_NAME = '2co';
    const CCBILL_GATEWAY_NAME = 'ccbill';


    /** @var AffiliateCoreModel */
    protected $oUserModel;

    /** @var PaymentModel */
    protected $oPayModel;

    /** @var string */
    protected $sTitle;

    /** @var int */
    protected $iProfileId;

    /** @var bool Payment status. Default is failure (FALSE) */
    private $_bStatus = false;


    public function __construct()
    {
        parent::__construct();

        $this->oUserModel = new AffiliateCoreModel;
        $this->oPayModel = new PaymentModel;
        $this->iProfileId = $this->session->get('member_id');
    }

    public function index()
    {
        $this->view->page_title = $this->view->h1_title = t('Payment Zone');
        $this->output();
    }

    public function membership()
    {
        $oMembershipData = $this->oPayModel->getMemberships();

        if (empty($oMembershipData)) {
            $this->displayPageNotFound(t('No membership found!'));
        } else {
            $this->view->page_title = $this->view->h2_title = t('Memberships List');
            $this->view->memberships = $oMembershipData;
            $this->output();
        }
    }

    /**
     * @param null|int $iMembershipId
     *
     * @return void
     */
    public function pay($iMembershipId = null)
    {
        $iMembershipId = (int) $iMembershipId;

        $oMembershipData = $this->oPayModel->getMemberships($iMembershipId);

        if (empty($iMembershipId) || empty($oMembershipData)) {
            $this->displayPageNotFound(t('No membership found!'));
        } else {
            // Adding the stylesheet for Gatway Logo
            $this->design->addCss(PH7_LAYOUT . PH7_SYS . PH7_MOD . $this->registry->module . PH7_SH . PH7_TPL . PH7_TPL_MOD_NAME . PH7_SH . PH7_CSS, 'common.css');

            // Regenerate the session ID to prevent the session fixation attack
            $this->session->regenerateId();

            $this->view->page_title = $this->view->h1_title = t('Payment Option');
            $this->view->membership = $oMembershipData;
            $this->output();
        }
    }

    /**
     * @param string $sProvider
     *
     * @return void
     */
    public function process($sProvider = '')
    {
        switch ($sProvider) {
            case static::PAYPAL_GATEWAY_NAME: {
                $oPayPal = new PayPal($this->config->values['module.setting']['sandbox.enabled']);
                if ($oPayPal->valid() && $this->httpRequest->postExists('custom')) {
                    $aData = explode('|', base64_decode($this->httpRequest->post('custom')));
                    $iItemNumber = (int) $aData[0];
                    if ($this->oUserModel->updateMembership(
                        $iItemNumber,
                        $this->iProfileId,
                        $this->dateTime->get()->dateTime('Y-m-d H:i:s'))
                    ) {
                        $this->_bStatus = true; // Status is OK
                        $this->updateUserGroupId($iItemNumber);
                        // PayPal will call automatically the "notification()" method thanks its IPN feature and "notify_url" form attribute.
                    }
                }
                unset($oPayPal);
            } break;

            case static::STRIPE_GATEWAY_NAME: {
                if ($this->httpRequest->postExists('stripeToken')) {
                    \Stripe\Stripe::setApiKey($this->config->values['module.setting']['stripe.secret_key']);
                    $sAmount = $this->httpRequest->post('amount');

                    try {
                        $oCharge = \Stripe\Charge::create(
                            [
                                'amount' => Stripe::getAmount($sAmount),
                                'currency' => $this->config->values['module.setting']['currency'],
                                'source' => $this->httpRequest->post('stripeToken'),
                                'description'    => 'Membership charged for ' . $this->httpRequest->post('stripeEmail')
                            ]
                        );

                        $iItemNumber = $this->httpRequest->post('item_number');
                        if ($this->oUserModel->updateMembership(
                            $iItemNumber,
                            $this->iProfileId,
                            $this->dateTime->get()->dateTime('Y-m-d H:i:s'))
                        ) {
                            $this->_bStatus = true; // Status is OK
                            $this->updateUserGroupId($iItemNumber);
                            $this->notification('Stripe', $iItemNumber); // Add info into the log file
                        }
                    }
                    catch (\Stripe\Error\Card $oE) {
                        // The card has been declined
                        // Do nothing here as "$this->_bStatus" is by default FALSE and so it will display "Error occurred" msg later
                    }
                    catch (\Stripe\Error\Base $oE) {
                        $this->design->setMessage( $this->str->escape($oE->getMessage(), true) );
                    }
                }
            } break;

            case static::BRAINTREE_GATEWAY_NAME: {
                if ($bNonce = $this->httpRequest->post('payment_method_nonce')) {
                    Braintree::init($this->config);

                    $oResult = Braintree_Transaction::sale([
                        'amount' => $this->httpRequest->post('amount'),
                        'paymentMethodNonce' => $bNonce,
                        'options' => [ 'submitForSettlement' => true ]
                    ]);

                    if ($oResult->success) {
                        $iItemNumber = $this->httpRequest->post('item_number');
                        if ($this->oUserModel->updateMembership(
                            $iItemNumber,
                            $this->iProfileId,
                            $this->dateTime->get()->dateTime('Y-m-d H:i:s'))
                        ) {
                            $this->_bStatus = true; // Status is OK
                            $this->updateUserGroupId($iItemNumber);
                            $this->notification('Braintree', $iItemNumber); // Add info into the log file
                        }
                    } elseif ($oResult->transaction) {
                        $sErrMsg = t('Error processing transaction: %0%', $oResult->transaction->processorResponseText);
                        $this->design->setMessage( $this->str->escape($sErrMsg, true) );
                    }
                }
            } break;

            case static::TWO_CHECKOUT_GATEWAY_NAME: {
                $o2CO = new TwoCO($this->config->values['module.setting']['sandbox.enabled']);
                $sVendorId = $this->config->values['module.setting']['2co.vendor_id'];
                $sSecretWord = $this->config->values['module.setting']['2co.secret_word'];

                $iItemNumber = $this->httpRequest->post('cart_order_id');
                if ($o2CO->valid($sVendorId, $sSecretWord) && $this->httpRequest->postExists('sale_id')) {
                    if (
                        $this->oUserModel->updateMembership(
                            $iItemNumber,
                            $this->iProfileId,
                            $this->dateTime->get()->dateTime('Y-m-d H:i:s')
                        )
                    ) {
                        $this->_bStatus = true; // Status is OK
                        $this->updateUserGroupId($iItemNumber);
                        $this->notification('TwoCO', $iItemNumber); // Add info into the log file
                    }
                }
                unset($o2CO);
            } break;
{'fraction_non_alphanumeric': 0.13248158379373848, 'fraction_numerical': 0.004546500920810313, 'mean_word_length': 1.5028085841855106, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 275, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1219344', 'n_tokens_mistral': 4778, 'n_tokens_neox': 4555, 'n_words': 826}