PHP: Generate Laravel Paginator Secure (HTTPS) Links - laravel

I'm developing an app using Laravel 4.2 over HTTPS with secure routes and redirects. I'm using Paginator to paginate results, but the links rendered in the view points to the http pages, how can we force Paginator to generate https links?

I had this issue today and found this global solution.
In your AppServiceProvider::boot method you can add the following to force https on pagination links
$this->app['request']->server->set('HTTPS','on');

If your current page is served over HTTPS, then the pagination URLs generated should use that schema.
However if you're using a proxy that does not pass the correct headers, the Request class responsible for determining if the connection is secure, might not report it as such. To determine if the request is detected as secure use Request::secure(). If that returns false, try using Laravel Trusted Proxies.
If that does not work you can force the pagination URLs with setBaseUrl as follows:
$results->paginate();
$results->setBaseUrl('https://' . Request::getHttpHost() . '/' . Request::path());

Add a custom presenter ZurbPresenter.php in app/helpers/ (you can place it inside other directory provided its path is included in to ClassLoader::addDirectories()):
<?php
class ZurbPresenter extends Illuminate\Pagination\Presenter {
/**
* Get HTML wrapper for a page link.
*
* #param string $url
* #param int $page
* #param string $rel
* #return string
*/
public function getPageLinkWrapper($url, $page, $rel = null)
{
$rel = is_null($rel) ? '' : ' rel="'.$rel.'"';
if (strpos($url, "http://") === 0) {
$url = "https://" . ltrim($url, "http://");
}
return '<li><a href="'.$url.'"'.$rel.'>'.$page.'</a></li>';
}
/**
* Get HTML wrapper for disabled text.
*
* #param string $text
* #return string
*/
public function getDisabledTextWrapper($text)
{
return '<li class="disabled"><span>'.$text.'</span></li>';
}
/**
* Get HTML wrapper for active text.
*
* #param string $text
* #return string
*/
public function getActivePageWrapper($text)
{
return '<li class="active"><span>'.$text.'</span></li>';
}
}
Notice the getPageLinkWrapper() has a logic to replace http by https.
Create a view file to use the presenter. Inside app/views create a file zurb_pagination.php with following content:
<?php
$presenter = new ZurbPresenter($paginator);
$trans = $environment->getTranslator();
?>
<?php if ($paginator->getLastPage() > 1): ?>
<ul class="pager">
<?php
echo $presenter->getPrevious($trans->trans('pagination.previous'));
echo $presenter->getNext($trans->trans('pagination.next'));
?>
</ul>
<?php endif; ?>
Finally change your app config to use the new presenter in app\config/view.php for pagination:
'pagination' => '_zurb_pagination_simple',
I use a similar approach for my website and you can verify it's working here.

Related

Add module to subpage in Joomla

I have a module which I add from admin panel to some subpage. After that some subpages show properly content with this module but some subpages after click on it open blank, white page with no content inside. I don't know what caused that problem. Why some subpages with this module work properly and some show blank page?
This is what I see on page:
Fatal error: Cannot redeclare class ModProductsMenuHelper in /opt2/data-dev/modules/mod_products_menu/helper.php on line 15
Thank you for help!
This is my code
<?php
/**
* Slajder class for Hello World! module
*
* #package Joomla.Tutorials
* #subpackage Modules
* #link http://docs.joomla.org/J3.x:Creating_a_simple_module/Developing_a_Basic_Module
* #license GNU/GPL, see LICENSE.php
* mod_helloworld is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
class ModProductsMenuHelper
{
/**
* Retrieves the hello message
*
* #param array $params An object containing the module parameters
*
* #access public
*/
public function getProducts($params)
{
$lang = JFactory::getLanguage();
$langTag = $lang->getTag();
$app = JFactory::getApplication();
$isSMB = $app->get('isSMB');
$parentMenuId = $langTag == 'pl-PL' ? 107 : 103;
$results = $this->getChildren($parentMenuId, $langTag);
return $results;
}
private function getChildren($parentId, $langTag){
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query
->select(array('id', 'title', 'path', 'alias'))
->from($db->quoteName('#__menu'))
->where("(language = '*' OR language= ".$db->quote($langTag).") AND published = 1 AND parent_id=".$parentId)
->order($db->quoteName('lft') . ' ASC, '.$db->quoteName('id') . ' ASC');
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
foreach ($results as $key=>$val){
$results[$key]->children = $this->getChildren($val->id, $langTag);
}
return $results;
}
}
From what I can gather you have created a module and assigned it to specific pages. You haven't mentioned what the contents of the module are (custom html etc).
Have you assigned the module to the correct pages in the 'module assignment' tab? Have a look at this question and answer as it explains how to do that.
If you are seeing a white page, i'd suggest enabling error reporting in Joomla. This should provide you with additional useful information about the error.
If you have a link to your website that would be helpful, and the version of Joomla you are using.

Symfony2.3 recaptcha doesn't work in my form

I'm developping a website using symfony framework. Now I'm trying to integrate recaptcha into my form so that I used this EWZRecaptchaBundle.
I hardly could install it using the 1.* version (not the version mentioned in the documentation). I followed the documentation and get the keys from hereand I put as domain :127.0.0.1 since I'm on localhost. Then I changed my formType.php file like this:
use EWZ\Bundle\RecaptchaBundle\Validator\Constraints as Recaptcha;
class ContactType extends AbstractType
{
/**
* #Recaptcha\True
*/
public $recaptcha;
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('email')
->add('subject')
->add('message')
->add('recaptcha', 'ewz_recaptcha')
;
}
and added the recaptcha on my twig file like this:
{% form_theme form 'EWZRecaptchaBundle:Form:ewz_recaptcha_widget.html.twig' %}
{{ form_widget(form.recaptcha, { 'attr': {
'options' : {
'theme': 'light',
'type': 'image'
},
} })
}}
But when I try to display the page I get : The parameter "fr" must be defined.
Looking in the details of the error I found:
at appProdDebugProjectContainer ->getParameter ('fr')
in C:\wamp\www\fstn\vendor\excelwebzone\recaptcha-bundle\EWZ\Bundle\RecaptchaBundle\Form\Type\RecaptchaType.php at line 62 -
$this->publicKey = $container->getParameter('ewz_recaptcha.public_key');
$this->secure = $container->getParameter('ewz_recaptcha.secure');
$this->enabled = $container->getParameter('ewz_recaptcha.enabled');
$this->language = $container->getParameter($container->getParameter('ewz_recaptcha.locale_key'));
}
/**
Is it related to the version of the Recaptcha Bundle that I have installed? how can I fix this?
Try to change this line:
$this->language = $container->getParameter($container->getParameter('ewz_recaptcha.locale_key'));
to this:
$this->language = $container->getParameter('ewz_recaptcha.locale_key');
This issue should be fixed in version 2.X

Codeigniter template class: check if pseudo variables have a value

Not sure if it's possible, but can you use if statements inside a template?
So if a phone number does not have a value I don't want to display that sentence at all...
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="utf-8"/>
<title>{form_title}</title>
</head>
<body>
<p>You received the following message from {name} through the Gossip Cakes' contact form.</p>
<p>Their email is {email}</p>
<p>Their phone number is {phone}</p>
<p>The message: {message}</p>
</body>
</html>
I guess I could use straight php, but is there a method of returning the html of a view?
CI templates do have support for IF statements if you are creative. I use them frequently. You can even use them to prevent the template elements from being parsed if there is no data.
Consider these three example arrays:
$phone_numbers = array(
array('phone_number'=>'555-1212'),
array('phone_number'=>'555-1313')
)
$phone_numbers = array()
$phone_numbers = array( array('phone_number'=>'555-1414') )
And consider this is the relevant section in your html:
{phone_numbers} <p>{phone_number}</p> {phone_numbers}
Using the three arrays, the respective output arrays one and three are as follows. (Using array two would print nothing as the control array is empty.)
<p>555-1212</p><p>555-1313</p>
<p>555-1414</p>
Assuming you're using CI's built in parser, you have to prep all the variables beforehand. There is no support for conditions, variable assignment, or anything beyond loops and basic token replacement at this time.
To do this in CI, you'd have to prep the whole message, something like this in your controller:
if ($phone) {
$data['phone_msg'] = "<p>Their phone number is $phone</p>";
} else {
$data['phone_msg'] = '';
}
Not a good solution. Personally I'd recommend Twig if you're looking for a nice template parser. Your idea of "I guess I could use straight PHP" is also a very good one.
is there a method of returning the html of a view?
Use the third param of view() like so:
$html = $this->load->view('myview', $mydata, TRUE);
echo 'Here is the HTML:';
echo $html;
// OR...
echo $this->parser->parse_string($html, NULL, TRUE);
class MY_Parser extends CI_Parser{
/**
* Parse a template
*
* Parses pseudo-variables contained in the specified template,
* replacing them with the data in the second param,
* and clean the variables that have not been set
*
* #access public
* #param string
* #param array
* #param bool
* #return string
*/
function _parse($template, $data, $return = FALSE)
{
if ($template == '')
{
return FALSE;
}
foreach ($data as $key => $val)
{
if (is_array($val))
{
$template = $this->_parse_pair($key, $val, $template);
}
else
{
$template = $this->_parse_single($key, (string)$val, $template);
}
}
#$template = preg_replace('/\{.*\}/','',$template);
$patron = '/\\'.$this->l_delim.'.*\\'.$this->r_delim.'/';
$template = preg_replace($patron,'',$template);
if ($return == FALSE)
{
$CI =& get_instance();
$CI->output->append_output($template);
}
return $template;
}
}
Enjoy :D

Magento Limit Number of Products in Home page

I have added this code {{block type="catalog/product_list" category_id="25" template="catalog/product/list.phtml"}} in cms home page
I want to limit no of products to display to nine to this category only.How can i do that?
I don't think there is a value you can pass into the block tag to limit it. I would suggest making a new list.phtml file that limits it there.
Let me look at the code real quick.
Ok. If you were to copy the file /app/design/frontend/default/default/template/catalog/product/list.phtml
to
/app/design/frontend/default/default/template/catalog/product/list-limit.phtml
and then edit it as follows:
LINE49: After the foreach
<?php if($_iterator >=9) { break; } ?>
LINE94: Where $_collectionSize is assigned change to:
<?php $_collectionSize = main(9, $_productCollection->count()) ?>
Line97: After the foreach
<?php if($i >= 9) { break; } ?>
It should achieve what you desire regardless of Grid or List view.
... shortly an alternative method ...
The other way would be to edit the List.php file that loads the product list that the phtml file presents. Block Type of 'catalog/product_list' means you need the file:
/app/code/core/Mage/Catalog/Block/Product/List.php
In there you will see the method getLoadedProductCollection, which calls _getProductCollection. That code could be edited to filter/limit the number of returned products. You would want to make a copy of that file though, and update the block link in your page. Don't add underscores to the name, as that will require the file be put in a subdirectory.
Hope this helped.
Following on from the previous answer, I seem to have acheived this by editing the List.php by adding the following after line 96.
return $this->_productCollection
->setPageSize($this->getProductsCount());
}
/**
* Set how much product should be displayed at once.
*
* #param $count
* #return Mage_Catalog_Block_Product_New
*/
public function setProductsCount($count)
{
$this->_productsCount = $count;
return $this;
}
/**
* Get how much products should be displayed at once.
*
* #return int
*/
public function getProductsCount()
{
if (null === $this->_productsCount) {
$this->_productsCount = self::DEFAULT_PRODUCTS_COUNT;
}
return $this->_productsCount;
}
and adding this after line 43
/**
* Default value for products count that will be shown
*/
const DEFAULT_PRODUCTS_COUNT = 100;
/**
* Products count
*
* #var null
*/
protected $_productsCount;
I got the codes from new.php

magento redirect checkout payment to a 3rd party gateway

I am trying to implement my new payment method its working fine. But My requirement is little bit different. I need to redirect user to the payment gateway page. This is how I am trying to implement.
When user clicks on Place Order my Namespace_Bank_Model_Payment >> authorize method gets called. My gateway Says send an initial request, Based on details given gateway send a URL & Payment id. On this Url user must be redirected Where customer actually makes the payment. I have two actions in Controller success & error to handle the final response.
As, this code is getting called in an ajax request, I can't redirect user to another website. Can anybody guide me how to accomplish it?
Here is my code. I Have implemented getOrderPlaceRedirectUrl() method.
Here is my class::
<?php
class Namespace_Hdfc_Model_Payment extends Mage_Payment_Model_Method_Abstract
{
protected $_isGateway = true;
protected $_canAuthorize = true;
protected $_canUseCheckout = true;
protected $_code = "hdfc";
/**
* Order instance
*/
protected $_order;
protected $_config;
protected $_payment;
protected $_redirectUrl;
/**
* #return Mage_Checkout_Model_Session
*/
protected function _getCheckout()
{
return Mage::getSingleton('checkout/session');
}
/**
* Return order instance loaded by increment id'
*
* #return Mage_Sales_Model_Order
*/
protected function _getOrder()
{
return $this->_order;
}
/**
* Return HDFC config instance
*
*/
public function getConfig()
{
if(empty($this->_config))
$this->_config = Mage::getModel('hdfc/config');
return $this->_config;
}
public function authorize(Varien_Object $payment, $amount)
{
if (empty($this->_order))
$this->_order = $payment->getOrder();
if (empty($this->_payment))
$this->_payment = $payment;
$orderId = $payment->getOrder()->getIncrementId();
$order = $this->_getOrder();
$billingAddress = $order->getBillingAddress();
$tm = Mage::getModel('hdfc/hdfc');
$qstr = $this->getQueryString();
// adding amount
$qstr .= '&amt='.$amount;
//echo 'obj details:';
//print_r(get_class_methods(get_class($billingAddress)));
// adding UDFs
$qstr .= '&udf1='.$order->getCustomerEmail();
$qstr .= '&udf2='.str_replace(".", '', $billingAddress->getName() );
$qstr .= '&udf3='.str_replace("\n", ' ', $billingAddress->getStreetFull());
$qstr .= '&udf4='.$billingAddress->getCity();
$qstr .= '&udf5='.$billingAddress->getCountry();
$qstr .= '&trackid='.$orderId;
// saving transaction into database;
$tm->setOrderId($orderId);
$tm->setAction(1);
$tm->setAmount($amount);
$tm->setTransactionAt( now() );
$tm->setCustomerEmail($order->getCustomerEmail());
$tm->setCustomerName($billingAddress->getName());
$tm->setCustomerAddress($billingAddress->getStreetFull());
$tm->setCustomerCity($billingAddress->getCity());
$tm->setCustomerCountry($billingAddress->getCountry());
$tm->setTempStatus('INITIAL REQUEST SENT');
$tm->save();
Mage::Log("\n\n queryString = $qstr");
// posting to server
try{
$response = $this->_initiateRequest($qstr);
// if response has error;
if($er = strpos($response,"!ERROR!") )
{
$tm->setErrorDesc( $response );
$tm->setTempStatus('TRANSACTION FAILED WHILE INITIAL REQUEST RESPONSE');
$tm->save();
$this->_getCheckout()->addError( $response );
return false;
}
$i = strpos($response,":");
$paymentId = substr($response, 0, $i);
$paymentPage = substr( $response, $i + 1);
$tm->setPaymentId($paymentId);
$tm->setPaymentPage($paymentPage);
$tm->setTempStatus('REDIRECTING TO PAYMENT GATEWAY');
$tm->save();
// prepare url for redirection & redirect it to gateway
$rurl = $paymentPage . '?PaymentID=' . $paymentId;
Mage::Log("url to redicts:: $rurl");
$this->_redirectUrl = $rurl; // saving redirect rl in object
// header("Location: $rurl"); // this is where I am trying to redirect as it is an ajax call so it won't work
//exit;
}
catch (Exception $e)
{
Mage::throwException($e->getMessage());
}
}
public function getOrderPlaceRedirectUrl()
{
Mage::Log('returning redirect url:: ' . $this->_redirectUrl ); // not in log
return $this->_redirectUrl;
}
}
Now getOrderPlaceRedirectUrl() its getting called. I can see the Mage::log message. but the url is not there. I mean the value of $this->_redirectUrl is not there at the time of function call.
And one more thing, I am not planning to show customer any page like "You are being redirected".
Magento supports this type of payment gateway as standard and directly supports redirecting the user to a third party site for payment.
In your payment model, the one that extends Mage_Payment_Model_Method_Abstract, you'll need to implement the method:
function getOrderPlaceRedirectUrl() {
return 'http://www.where.should.we.pay.com/pay';
Typically you redirect the user to a page on your site, /mymodule/payment/redirect for example, and then handle the redirection logic in the action of the controller. This keeps your payment model clean and stateless, while allowing you to some some kind of "You are now being transferred to the gateway for payment" message.
Save everything you need to decide where to redirect to in a session variable, again typically Mage::getSingleton('checkout/session').
Magento have a pretty solid, if messy, implementation of this for Paypal standard. You can checkout how they do it in app/code/core/Mage/Paypal/{Model/Standard.php,controllers/StandardController.php}.
Hello guys here is solution.
In authorize function (see my code in above answer) change
$this->_redirectUrl = $rurl;
by Mage::getSingleton('customer/session')->setRedirectUrl($rurl);
& in function getOrderPlaceRedirectUrl() change it to like
public function getOrderPlaceRedirectUrl()
{
Mage::Log('returning redirect url:: ' . Mage::getSingleton('customer/session')->getRedirectUrl() );
return Mage::getSingleton('customer/session')->getRedirectUrl(); ;
}
after that code must be running & u'll be getting redirected to the third party gateway

Resources