Remove items from cart after 30 minutes - Magento - magento

I would like to remove items from cart for both logged in and guest shoppers.
I have set the Cookie Session timeout to 1800 which solves the guest shoppers but under quote lifetime I can only select 1 day. Anyway to get this to 30 mins?
I changed:
$lifetimes = Mage::getConfig()->getStoresConfigByPath('checkout/cart/delete_quote_after');
foreach ($lifetimes as $storeId=>$lifetime) {
$lifetime *= 86400;
}
to
$lifetimes = Mage::getConfig()->getStoresConfigByPath('checkout/cart/delete_quote_after');
foreach ($lifetimes as $storeId=>$lifetime) {
$lifetime *= 1800;
}
then set 1 day under quote life time. Still no joy.

I would say create a module that adds an expiration time to the quote item and then checks each for that expiration time. Something along the lines of
class My_Module_Model_Observer
{
/* observes sales_quote_add_item */
public function addItemExpiration(Varien_Event_Observer $event)
{
$item = $event->getItem();
$itemExpiration = Mage::getModel('catalog/session')->getQuoteItemExpiration();
if (!$itemExpiration)$itemExpiration = array();
$itemExpiration[$item->getId()] = (time() + (30 * 60));
Mage::getModel('catalog/session')->setQuoteItemExpiration($itemExpiration);
}
/* observes sales_quote_load_after */
public function removeExpiredItems(Varien_Event_Observer $event)
{
$itemExpiration = Mage::getModel('catalog/session')->getQuoteItemExpiration();
foreach ($event->getQuote()->getAllItems() as $item) {
if ($itemExpiration[$item->getId()] < time()) {
$event->getQuote()->removeItem($item->getId());
}
}
}
}
Note that I have not tested this and simply coded it by memory and so it might not work without some modification

here is one more solution you can try
paste this code in sidebar.phtml
<?php if ($this->helper('customer')->isLoggedIn()) {
$session = Mage::getSingleton('checkout/cart');
if ($session['quote']) {
$cart = Mage::getModel('checkout/cart')->getQuote()->getData();
$qtyCart = (int) $cart['items_qty'];
if ($qtyCart > 0) {
$updateAt = $session['quote']->getUpdatedAt(); // cart update date
$currentDate = strtotime($updateAt);
$futureDate = $currentDate + (60 * 20); //target date
$date1 = date("Y-m-d H:i:s");
$date1 = strtotime($date1); // current date
//$futureDate = date();
$dateFormat = "d F Y -- g:i a";
$targetDate = $futureDate; //Change the 25 to however many minutes you want to countdown
$actualDate = $date1;
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff / 60 / 60 / 24);
$remainingHour = floor(($secondsDiff - ($remainingDay * 60 * 60 * 24)) / 60 / 60);
$remainingMinutes = floor(($secondsDiff - ($remainingDay * 60 * 60 * 24) - ($remainingHour * 60 * 60)) / 60);
$remainingSeconds = floor(($secondsDiff - ($remainingDay * 60 * 60 * 24) - ($remainingHour * 60 * 60)) - ($remainingMinutes * 60));
$actualDateDisplay = date($dateFormat, $actualDate);
$targetDateDisplay = date($dateFormat, $targetDate);
?>
<script type="text/javascript">
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
function setCountDown(statusfun)
{//alert(seconds);
var SD;
if(days >= 0 && minutes >= 0){
var dataReturn = jQuery.ajax({
type: "GET",
url: "<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB) . 'index.php/countdowncont/'; ?>",
async: true,
success: function(data){
var data = data.split("/");
day = data[0];
hours = data[1];
minutes = data[2];
seconds = data[3];
}
});
seconds--;
if (seconds < 0){
minutes--;
seconds = 59
}
if (minutes < 0){
hours--;
minutes = 59
}
if (hours < 0){
days--;
hours = 23
}
document.getElementById("remain").style.display = "block";
document.getElementById("remain").innerHTML = " Items reversed for <span> "+minutes+":"+seconds+"</span> minutes.";
SD=window.setTimeout( "setCountDown()", 1000 );
}else{
document.getElementById("remain").innerHTML = "";
seconds = "00"; window.clearTimeout(SD);
jQuery.ajax({
type: "GET",
url: "<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB) . 'index.php/countdown/'; ?>", // this the path of your controller
async: false,
success: function(html){
}
});
document.getElementById("remain").innerHTML = "";
//window.location = document.URL; // Add your redirect url*/
}
}
</script>
<?php if ($date1 < $futureDate && ($qtyCart > 0)) { ?>
<script type="text/javascript">
setCountDown();
</script>
<?php } else {
foreach(
Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection()
as $item ){
Mage::getSingleton('checkout/cart')->removeItem( $item->getId() )->save();}
?>
<style>
#remain{display:none;}
</style>
<?php
}
}
}
} ?>
Now create a controller and assign it to the ajax url and past the following code to that controller
public function indexAction() {
$cartHelperAjax = Mage::helper('checkout/cart');
$cart = Mage::getModel('checkout/cart')->getQuote()->getData();
$qtyCart = (int)$cart['items_qty'];
if($qtyCart > 0){
$updateAt = $cartHelperAjax->getQuote()->getUpdatedAt(); // cart update date
$currentDate = strtotime($updateAt);
$futureDate = $currentDate+(60*20);//target date
$date1 = date("Y-m-d H:i:s");
$date1 = strtotime($date1); // current date
//$futureDate = date();
$dateFormat = "d F Y -- g:i a";
$targetDate = $futureDate;//Change the 25 to however many minutes you want to countdown
$actualDate = $date1;
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);
echo $total_remainTime = $remainingDay ."/".$remainingHour."/".$remainingMinutes."/".$remainingSeconds;
}
}
by these line of code can create a countdown timer. and after particular time the all items from cart will removed.

set timeout from Admin > System > Configuration > Web > Session Cookie Management > Cookie Lifetime

Please try this code to remove last day cart items :
<?php
mb_internal_encoding('UTF-8');
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once '../app/Mage.php';
Mage::app('admin');
$STORE_ID = 0;
Mage::app()->setCurrentStore($STORE_ID);
$lifetime = 3600;
$quoteCollection = Mage::getModel('sales/quote')
->getCollection()
->addFieldToFilter('created_at', array('to' => date("Y-m-d H:i:s", time() - $lifetime)))
->addFieldToFilter('is_active', 1);
//print_r($quoteCollection);
//echo count($quoteCollection);
//die;
// $date = date('Y-m-d H:i:s');
//echo date("Y-m-d H:i:s", time() - $lifetime) . '<br><br>';
foreach ($quoteCollection as $item) {
$item->delete();
}
echo PHP_EOL . "All process completed now." . PHP_EOL;
?>

Related

DataBase Schema File (.sql file ) Download with laravel

Schenario :
1) suppose that i have a database called myDataBase
2) Assume that myDataBase have some tables like A,B,C,D
3) i have to download the schema of the table A,B from the database with name myDataBase
Hope you have done the migration of all the table of your project . If you are using a xampp server then goto http://localhost/phpmyadmin and select your database and then goto export tab on the top tab bar and simply export with go button
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlUserName = "root";
$mysqlPassword = "";
$mysqlHostName = "localhost";
$DbName = "ukkoteknik";
$backup_name = "mybackup.sql";
$tables = array("admin", "sample");
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables, $backup_name=false );
function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
//$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
$date = date("Y-m-d");
$backup_name = $backup_name ? $backup_name : $name.".$date.sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
//echo $content; exit;
}
?>

Restrict zip codes for custom shipping method is not working after hide the shipping method

we are really facing very strange problem here.
we are using 1.9.0.1 and custom shipping method.
We Hide Shipping Method Step in checkout using answer gave by #Marius here :
https://magento.stackexchange.com/questions/53355/remove-shipping-steps-in-onepage-checkout
But we have one problem here.
we allowed only some zip codes to place an order.
but here its allowing for all zip codes when user enter first time.
once user enter zip code and click on "Continue" button, it will go to next step [payment methods]
Payment method step
Than if user again come to Previous step and enter same zip code and if user click on "Continue"
button, than it will show error message in pop up - "Invalid shipping method"
This is fine, but it should not allow when user enter zip code for first time also.
Before everything was fine, once we hide shipping method , this problem happened. but for default shipping method it is working fine.
ex site : link & zip code 000000
we are using this code for restricting zip codes and finding shipping charges.
<?php
class extension_Mpperproductshipping_Model_Carrier_LocalDelivery extends Mage_Shipping_Model_Carrier_Abstract
{
/* Use group alias */
protected $_code = 'mpperproductshipping';
public function collectRates(Mage_Shipping_Model_Rate_Request $request){
$postCode = $request->getDestPostcode();
$restrictedCodes = array(
110001,
110002
); //restricted values. they can come from anywhere
if (!in_array($postCode, $restrictedCodes)) {
return false;
}
$result = Mage::getModel('shipping/rate_result');
/* Edited by vikas_mageworx */
$postcode=$request->getDestPostcode();
$countrycode=$request->getDestCountry();
$items=$request->getAllItems();
/* End Editing by vikas_mageworx */
$postcode=str_replace('-', '', $postcode);
$shippingdetail=array();
/* one start */
$shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode,'items'=>$items);
/* one end */
foreach($items as $item) {
$proid=$item->getProductId();
$options=$item->getProductOptions();
$mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
if(!$mpassignproductId) {
foreach($item->getOptions() as $option) {
$temp=unserialize($option['value']);
if($temp['mpassignproduct_id']) {
$mpassignproductId=$temp['mpassignproduct_id'];
}
}
}
if($mpassignproductId) {
$mpassignModel = Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId);
$partner = $mpassignModel->getSellerId();
} else {
$collection=Mage::getModel('marketplace/product')
->getCollection()->addFieldToFilter('mageproductid',array('eq'=>$proid));
foreach($collection as $temp) {
$partner=$temp->getUserid();
}
}
$product=Mage::getModel('catalog/product')->load($proid)->getWeight();
$weight=$product*$item->getQty();
if(count($shippingdetail)==0){
array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
}else{
$shipinfoflag=true;
$index=0;
foreach($shippingdetail as $itemship){
if($itemship['seller_id']==$partner){
$itemship['items_weight']=$itemship['items_weight']+$weight;
$itemship['product_name']=$itemship['product_name'].",".$item->getName();
$itemship['item_id']=$itemship['item_id'].",".$item->getId();
$itemship['qty']=$itemship['qty']+$item->getQty();
$shippingdetail[$index]=$itemship;
$shipinfoflag=false;
}
$index++;
}
if($shipinfoflag==true){
array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
}
}
}
$shippingpricedetail=$this->getShippingPricedetail($shippingdetail,$shippostaldetail);
if($shippingpricedetail['errormsg']!==""){
Mage::getSingleton('core/session')->setShippingCustomError($shippingpricedetail['errormsg']);
return $result;
}
/*store shipping in session*/
$shippingAll=Mage::getSingleton('core/session')->getData('shippinginfo');
$shippingAll[$this->_code]=$shippingpricedetail['shippinginfo'];
Mage::getSingleton('core/session')->setData('shippinginfo',$shippingAll);
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier($this->_code);
$method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title'));
/* Use method name */
$method->setMethod($this->_code);
$method->setMethodTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/name'));
$method->setCost($shippingpricedetail['handlingfee']);
$method->setPrice($shippingpricedetail['handlingfee']);
$result->append($method);
return $result;
}
public function getShippingPricedetail($shippingdetail,$shippostaldetail) {
$shippinginfo=array();
$handling=0;
$session = Mage::getSingleton('checkout/session');
$customerAddress = $session->getQuote()->getShippingAddress();
/* Edited by vikas_boy */
$customerPostCode = $shippostaldetail['postalcode'];
$items = $shippostaldetail['items'];
/* End Editing by vikas_boy */
/* one */
foreach($shippingdetail as $shipdetail) {
$seller = Mage::getModel("customer/customer")->load($shipdetail['seller_id']);
$sellerAddress = $seller->getPrimaryShippingAddress();
$distance = $this->getDistanse($sellerAddress->getPostcode(),$customerPostCode);
// echo "distance ".$distance;die;
$price = 0;
$itemsarray=explode(',',$shipdetail['item_id']);
foreach($items as $item) {
$proid=$item->getProductId();
$options=$item->getProductOptions();
$mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
if(!$mpassignproductId) {
foreach($item->getOptions() as $option) {
$temp=unserialize($option['value']);
if($temp['mpassignproduct_id']) {
$mpassignproductId=$temp['mpassignproduct_id'];
}
}
}
if (Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($proid))
{
continue;
}
$mpshippingcharge = 0;
$localDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/local_shipping_distance');
$regionalDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/regional_shipping_distance');
$stateDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/state_shipping_distance');
if(in_array($item->getId(),$itemsarray)) {
if($mpassignproductId) {
if($distance < $localDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getLocalShippingCharge();
} elseif($distance > $localDistance && $distance < $regionalDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getRegionalShippingCharge();
} elseif($distance > $regionalDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getStateShippingCharge();
}
} else {
// echo "imte ".$item->getProductId();
if($distance < $localDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpLocalShippingCharge();
// echo "imte ".$item->getProductId();
// echo "ship ".$mpshippingcharge;
} elseif($distance > $localDistance && $distance < $regionalDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpRegionalShippingCharge();
} elseif($distance > $regionalDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpStateShippingCharge();
}
}
/* tt */
// echo "test ".$mpshippingcharge;die;
if(!is_numeric($mpshippingcharge)){
$price=$price+floatval($this->getConfigData('defalt_ship_amount')* floatval($item->getQty()));
}else{
$price=$price+($mpshippingcharge * floatval($item->getQty()));
}
}
}
$handling = $handling+$price;
$submethod = array(array('method'=>Mage::getStoreConfig('carriers/'.$this->_code.'/title'),'cost'=>$price,'error'=>0));
array_push($shippinginfo,array('seller_id'=>$shipdetail['seller_id'],'methodcode'=>$this->_code,'shipping_ammount'=>$price,'product_name'=>$shipdetail['product_name'],'submethod'=>$submethod,'item_ids'=>$shipdetail['item_id']));
}
$msg="";
return array('handlingfee'=>$handling,'shippinginfo'=>$shippinginfo,'errormsg'=>$msg);
}
/* one end */
/* tt start */
private function getDistanse($origin,$destination) {
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin.",india&destinations=".$destination.",india&mode=driving&language=en-EN&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_all = json_decode($response);
$distance = $response_all->rows[0]->elements[0]->distance->value / 1000;
if($distance==0){
$zips = array(
$origin,$destination
// ... etc ...
);
$geocoded = array();
$serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:%s&sensor=false";
$curl = curl_init();
foreach ($zips as $zip) {
curl_setopt($curl, CURLOPT_URL, sprintf($serviceUrl, urlencode($zip)));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$data = json_decode(curl_exec($curl));
$info = curl_getinfo($curl);
if ($info['http_code'] != 200) {
// Request failed
} else if ($data->status !== 'OK') {
// Something happened, or there are no results
} else {
$geocoded[$zip] =$data->results[0]->geometry->location;
}
}
$distance=$this->DistAB($geocoded[$zips[0]]->lat,$geocoded[$zips[0]]->lng,$geocoded[$zips[1]]->lat,$geocoded[$zips[1]]->lng);
}
return $distance;
}
public function DistAB($lat_a,$lon_a,$lat_b,$lon_b)
{
$measure_unit = 'kilometers';
$measure_state = false;
$measure = 0;
$error = '';
$delta_lat = $lat_b - $lat_a ;
$delta_lon = $lon_b - $lon_a ;
$earth_radius = 6372.795477598;
$alpha = $delta_lat/2;
$beta = $delta_lon/2;
$a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($this->lat_a)) * cos(deg2rad($this->lat_b)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ;
$c = asin(min(1, sqrt($a)));
$distance = 2*$earth_radius * $c;
$distance = round($distance, 4);
$measure = $distance;
return $measure;
}
}
/* tt end */
onepage.phtml : app/design/frontend/default/em0113/template/checkout/onepage.phml
<div class="page-title">
<h1><?php echo $this->__('Checkout') ?></h1>
</div>
<script type="text/javascript" src="<?php echo $this->getJsUrl('varien/accordion.js') ?>"></script>
<script type="text/javascript" src="<?php echo $this->getSkinUrl('js/opcheckout.js') ?>"></script>
<ol class="opc" id="checkoutSteps">
<?php $i=0; foreach($this->getSteps() as $_stepId => $_stepInfo): ?>
<?php if (!$this->getChild($_stepId) || !$this->getChild($_stepId)->isShow()): continue; endif; $i++ ?>
<li id="opc-<?php echo $_stepId ?>" class="section<?php echo !empty($_stepInfo['allow'])?' allow':'' ?><?php echo !empty($_stepInfo['complete'])?' saved':'' ?>">
<div class="step-title">
<span class="number"><?php echo $i ?>.</span>
<h2><?php echo $_stepInfo['label'] ?></h2>
<?php echo $this->__('Edit') ?>
</div>
<div id="checkout-step-<?php echo $_stepId ?>" class="step a-item" style="display:none;">
<?php echo $this->getChildHtml($_stepId) ?>
</div>
</li>
<?php endforeach ?>
</ol>
<script type="text/javascript">
//<![CDATA[
var accordion = new Accordion('checkoutSteps', '.step-title', true);
<?php if($this->getActiveStep()): ?>
accordion.openSection('opc-<?php echo $this->getActiveStep() ?>');
<?php endif ?>
var checkout = new Checkout(accordion,{
progress: '<?php echo $this->getUrl('checkout/onepage/progress') ?>',
review: '<?php echo $this->getUrl('checkout/onepage/review') ?>',
saveMethod: '<?php echo $this->getUrl('checkout/onepage/saveMethod') ?>',
failure: '<?php echo $this->getUrl('checkout/cart') ?>'}
);
//]]>
</script>
What you can do is bind a javascript event to the input field of pincode and send the request everytime when someone is typing in the pincode like this:
<input type = "text" onchange = "myfun(this.value)">
And then bind a javascript function myfun to it and make an AJAX call to your pincode checking controller, this will take the value once you finish typing into the text box
Otherwise you can also go with
<input type = "text" onkeypress = "myfun(this.value)">
And then again bind a javascript function myfun to it and make an AJAX call to your pincode checking controller, this will take the value even when you are typing into the text box
Ok, in your onepage template, write this code:
jQuery('#billing:postcode').change(function(){
// your ajax call to your controller where you are verifying your pincode, something like:
jQuery.ajax({
url: "path/to/your/controller",
data: this.value,
success: function(response){
if(response == true){
// your success action
} else{
//your failure action
}
}
})
})

Form datetime select field in Laravel 4.1

My model has an event_datetime field which I want to set on the form using datetime select fields. Rails has datetime_select which outputs the following and saves to a MySQL datetime column.
Must default to the current date and work on a shared add/edit form.
No javascript datepickers please.
Add this to you
{{ Form::datetime('event_date') }}
And place this macro into some autoloaded file (or view file)
Form::macro('datetime', function($name) {
$years = value(function() {
$startYear = (int) date('Y');
$endYear = $startYear - 5;
$years = ['' => 'year'];
for($year = $startYear; $year > $endYear; $year--) {
$years[ $year ] = $year;
};
return $years;
});
$months = value(function() {
$months = ['' => 'month'];
for($month = 1; $month < 13; $month++) {
$timestamp = strtotime(date('Y'). '-'.$month.'-13');
$months[ $month ] = strftime('%B', $timestamp);
}
return $months;
});
$days = value(function() {
$days = ['' => 'day'];
for($day = 1; $day < 32; $day++) {
$days[ $day ] = $day;
}
return $days;
});
$hours = value(function() {
$hours = ['' => 'hour'];
for($hour = 0; $hour < 24; $hour++) {
$hours[ $hour ] = $hour;
}
return $hours;
});
$minutes = value(function() {
$minutes = ['' => 'minute'];
for($minute = 0; $minute < 60; $minute++) {
$minutes[ $minute ] = $minute;
}
return $minutes;
});
return Form::select($name.'[year]', $years) .
Form::select($name.'[month]', $months) .
Form::select($name.'[day]', $days) . ' - ' .
Form::select($name.'[hour]', $hours) .
Form::select($name.'[minute]', $minutes);
});

joomla pagination shows same result on every page

I have page of articles with more than 5 results. 5 results are displayed per page. Pagination shows up. When I go to different pages however, every page has the same 5 results.
My getItems():
function getItems()
{
$params = $this->getState()->get('params');
$limit = $this->getState('list.limit');
// 5
if ($this->_articles === null && $category = $this->getCategory()) {
$model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
$model->setState('params', JFactory::getApplication()->getParams());
$model->setState('filter.category_id', $category->id);
$model->setState('filter.published', $this->getState('filter.published'));
$model->setState('filter.access', $this->getState('filter.access'));
$model->setState('filter.language', $this->getState('filter.language'));
$model->setState('list.ordering', $this->_buildContentOrderBy());
$model->setState('list.start', $this->getState('list.start'));
$model->setState('list.limit', $limit);
$model->setState('list.direction', $this->getState('list.direction'));
$model->setState('list.filter', $this->getState('list.filter'));
// filter.subcategories indicates whether to include articles from subcategories in the list or blog
$model->setState('filter.subcategories', $this->getState('filter.subcategories'));
$model->setState('filter.max_category_levels', $this->setState('filter.max_category_levels'));
$model->setState('list.links', $this->getState('list.links'));
if ($limit >= 0) {
$this->_articles = $model->getItems();
if ($this->_articles === false) {
$this->setError($model->getError());
}
}
else {
$this->_articles=array();
}
$this->_pagination = $model->getPagination();
}
$filterResult = null;
return $this->_articles;
}
My populate state:
protected function populateState($ordering = null, $direction = null)
{
// Initiliase variables.
$app = JFactory::getApplication('site');
$pk = JRequest::getInt('id');
$this->setState('category.id', $pk);
// Load the parameters. Merge Global and Menu Item params into new object
$params = $app->getParams();
$menuParams = new JRegistry;
if ($menu = $app->getMenu()->getActive()) {
$menuParams->loadString($menu->params);
}
$mergedParams = clone $menuParams;
$mergedParams->merge($params);
$this->setState('params', $mergedParams);
$user = JFactory::getUser();
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
$groups = implode(',', $user->getAuthorisedViewLevels());
if ((!$user->authorise('core.edit.state', 'com_content')) && (!$user->authorise('core.edit', 'com_content'))){
// limit to published for people who can't edit or edit.state.
$this->setState('filter.published', 1);
/**
* Custom Author Filter
*/
if (JRequest::getVar('author')) {
$this->setState('filter.created_by', $this->getUserId(JRequest::getVar('author')));
}
// Filter by start and end dates.
$nullDate = $db->Quote($db->getNullDate());
$nowDate = $db->Quote(JFactory::getDate()->toMySQL());
$query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')');
$query->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')');
/**
* Custom Author Filter
*/
if (JRequest::getVar('author')) {
$query->where('(a.created_by = "' . $this->getUserId(JRequest::getVar('author')) . '")');
}
}
// process show_noauth parameter
if (!$params->get('show_noauth')) {
$this->setState('filter.access', true);
}
else {
$this->setState('filter.access', false);
}
// Optional filter text
$this->setState('list.filter', JRequest::getString('filter-search'));
// filter.order
$itemid = JRequest::getInt('id', 0) . ':' . JRequest::getInt('Itemid', 0);
$orderCol = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.filter_order', 'filter_order', '', 'string');
if (!in_array($orderCol, $this->filter_fields)) {
$orderCol = 'a.ordering';
}
$this->setState('list.ordering', $orderCol);
$listOrder = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.filter_order_Dir',
'filter_order_Dir', '', 'cmd');
if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', ''))) {
$listOrder = 'ASC';
}
$this->setState('list.direction', $listOrder);
//$this->setState('list.start', JRequest::getVar('limitstart', 0, '', 'int'));
// set limit for query. If list, use parameter. If blog, add blog parameters for limit.
if ((JRequest::getCmd('layout') == 'blog') || $params->get('layout_type') == 'blog') {
$limit = $params->get('num_leading_articles') + $params->get('num_intro_articles') + $params->get('num_links');
$this->setState('list.links', $params->get('num_links'));
}
else {
$limit = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.limit', 'limit', $params->get('display_num'));
}
$this->setState('list.limit', $limit);
// set the depth of the category query based on parameter
$showSubcategories = $params->get('show_subcategory_content', '0');
if ($showSubcategories) {
$this->setState('filter.max_category_levels', $params->get('show_subcategory_content', '1'));
$this->setState('filter.subcategories', true);
}
$this->setState('filter.language',$app->getLanguageFilter());
$this->setState('layout', JRequest::getCmd('layout'));
}
My display function de view.html.php
function display($tpl = null)
{
$app = JFactory::getApplication();
$user = JFactory::getUser();
// Get some data from the models
$state = $this->get('State');
$params = $state->params;
$items = $this->get('Items');
$contactId = JRequest::getVar('author');
if($contactId){
$this->setUserId($contactId);
$this->setContactName($this->userId);
}
$category = $this->get('Category');
$children = $this->get('Children');
$parent = $this->get('Parent');
$pagination = $this->get('Pagination');
// Check for errors.
if (count($errors = $this->get('Errors'))) {
JError::raiseError(500, implode("\n", $errors));
return false;
}
if ($category == false) {
return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
}
if ($parent == false) {
return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
}
// Setup the category parameters.
$cparams = $category->getParams();
$category->params = clone($params);
$category->params->merge($cparams);
// Check whether category access level allows access.
$user = JFactory::getUser();
$groups = $user->getAuthorisedViewLevels();
if (!in_array($category->access, $groups)) {
return JError::raiseError(403, JText::_("JERROR_ALERTNOAUTHOR"));
}
// PREPARE THE DATA
// Get the metrics for the structural page layout.
$numLeading = $params->def('num_leading_articles', 1);
$numIntro = $params->def('num_intro_articles', 4);
$numLinks = $params->def('num_links', 4);
// Compute the article slugs and prepare introtext (runs content plugins).
for ($i = 0, $n = count($items); $i < $n; $i++)
{
$item = &$items[$i];
$item->slug = $item->alias ? ($item->id . ':' . $item->alias) : $item->id;
// No link for ROOT category
if ($item->parent_alias == 'root') {
$item->parent_slug = null;
}
$item->event = new stdClass();
$dispatcher = JDispatcher::getInstance();
// Ignore content plugins on links.
if ($i < $numLeading + $numIntro) {
$item->introtext = JHtml::_('content.prepare', $item->introtext);
$results = $dispatcher->trigger('onContentAfterTitle', array('com_content.article', &$item, &$item->params, 0));
$item->event->afterDisplayTitle = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentBeforeDisplay', array('com_content.article', &$item, &$item->params, 0));
$item->event->beforeDisplayContent = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentAfterDisplay', array('com_content.article', &$item, &$item->params, 0));
$item->event->afterDisplayContent = trim(implode("\n", $results));
}
}
// Check for layout override only if this is not the active menu item
// If it is the active menu item, then the view and category id will match
$active = $app->getMenu()->getActive();
if ((!$active) || ((strpos($active->link, 'view=category') === false) || (strpos($active->link, '&id=' . (string) $category->id) === false))) {
// Get the layout from the merged category params
if ($layout = $category->params->get('category_layout')) {
$this->setLayout($layout);
}
}
// At this point, we are in a menu item, so we don't override the layout
elseif (isset($active->query['layout'])) {
// We need to set the layout from the query in case this is an alternative menu item (with an alternative layout)
$this->setLayout($active->query['layout']);
}
// For blog layouts, preprocess the breakdown of leading, intro and linked articles.
// This makes it much easier for the designer to just interrogate the arrays.
if (($params->get('layout_type') == 'blog') || ($this->getLayout() == 'blog')) {
$max = count($items);
// The first group is the leading articles.
$limit = $numLeading;
for ($i = 0; $i < $limit && $i < $max; $i++) {
$this->lead_items[$i] = &$items[$i];
}
// The second group is the intro articles.
$limit = $numLeading + $numIntro;
// Order articles across, then down (or single column mode)
for ($i = $numLeading; $i < $limit && $i < $max; $i++) {
$this->intro_items[$i] = &$items[$i];
}
$this->columns = max(1, $params->def('num_columns', 1));
$order = $params->def('multi_column_order', 1);
if ($order == 0 && $this->columns > 1) {
// call order down helper
$this->intro_items = ContentHelperQuery::orderDownColumns($this->intro_items, $this->columns);
}
$limit = $numLeading + $numIntro + $numLinks;
// The remainder are the links.
for ($i = $numLeading + $numIntro; $i < $limit && $i < $max;$i++)
{
$this->link_items[$i] = &$items[$i];
}
}
$children = array($category->id => $children);
//Escape strings for HTML output
$this->pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
$this->assign('maxLevel', $params->get('maxLevel', -1));
$this->assignRef('state', $state);
$this->assignRef('items', $items);
$this->assignRef('category', $category);
$this->assignRef('children', $children);
$this->assignRef('params', $params);
$this->assignRef('parent', $parent);
$this->assignRef('pagination', $pagination);
$this->assignRef('user', $user);
$this->_prepareDocument();
parent::display($tpl);
}
If i print the contents of $pagination in the view.html.php here:
$this->_prepareDocument();
echo '<pre>'; print_r($pagination); exit();
parent::display($tpl);
I get the following results:
In my template file I echo the pagination:
<?php echo $this->pagination->getPagesLinks(); ?>
By the way, clicking on 'next' does change the url into ...?start=5.
This line in populateState is commented out
$this->setState('list.start', JRequest::getVar('limitstart', 0, '', 'int'));
Uncomment it change it tot get the "start" parameter:
$this->setState('list.start', JRequest::getVar('start', 0, '', 'int'));

How to Use Captcha Plugin in CodeIgniter

I followed this page, and the code is not working as it should in my project. I've tried to find other tutorial on how to execute what I need, however, it does not work as it should in my project either. Is anyone able to direct me to a tutorial that explains in a detailed fashion on how to use Captcha plug-in properly in CodeIgniter?
Controller:
<?php
class Prova extends Controller
{
function prova()
{
parent :: Controller();
$this -> load -> plugin( 'captcha' );
$this->load->library('validation');
$rules['user'] = "required";
$rules['captcha'] = "required|callback_captcha_check";
$this->validation->set_rules($rules);
$fields['user'] = 'Username';
$fields['captcha'] = 'codice';
$this->validation->set_fields($fields);
if ($this->validation->run() == FALSE)
{
$expiration = time()-300; // Two hour limit
$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
$vals = array(
//'word' => 'Random word',
'img_path' => './tmp/captcha/',
'img_url' => base_url().'tmp/captcha/',
'font_path' => './system/fonts/texb.ttf',
'img_width' => '100',
'img_height' => '30',
'expiration' => '3600'
);
$cap = $this->captcha->create_captcha($vals);
//
$dati['image']= $cap['image'];
//mette nel db
$data = array(
'captcha_id' => '',
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
$this->load->view('captcha',$data);
}else{
echo "Captcha can't be made";
}
return $cap ['image'];
}
function captcha_check()
{
// Then see if a captcha exists:
$exp=time()-600;
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
$binds = array($this->input->post('captcha'), $this->input->ip_address(), $exp);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
$this->validation->set_message('_captcha_check', 'Codice di controllo non valido');
return FALSE;
}else{
return TRUE;
}
}
}
View:
<html>
<head>
<title>My Form</title>
</head>
<body>
<?=$this->validation->error_string; ?>
<?=form_open('XXXXXXXXX type your controller'); ?>
<h5>Username</h5>
<?=$this->validation->user_error; ?>
<input type="text" name="user" value="<?php echo ($this->validation->user) ;?>" size="50" />
<br/>
<?=$image;?>
<br/>
<?=$this->validation->captcha_error; ?>
<input type="text" name="captcha" value="" />
<br/>
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
Captcha:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* #package CodeIgniter
* #author ExpressionEngine Dev Team
* #copyright Copyright (c) 2008, EllisLab, Inc.
* #license http://codeigniter.com/user_guide/license.html
* #link http://codeigniter.com
* #since Version 1.0
* #filesource
*/
// ------------------------------------------------------------------------
/*
Instructions:
Load the plugin using:
$this->load->plugin('captcha');
Once loaded you can generate a captcha like this:
$vals = array(
'word' => 'Random word',
'img_path' => './captcha/',
'img_url' => 'http://example.com/captcha/',
'font_path' => './system/fonts/texb.ttf',
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$cap = create_captcha($vals);
echo $cap['image'];
NOTES:
The captcha function requires the GD image library.
Only the img_path and img_url are required.
If a "word" is not supplied, the function will generate a random
ASCII string. You might put together your own word library that
you can draw randomly from.
If you do not specify a path to a TRUE TYPE font, the native ugly GD
font will be used.
The "captcha" folder must be writable (666, or 777)
The "expiration" (in seconds) signifies how long an image will
remain in the captcha folder before it will be deleted. The default
is two hours.
RETURNED DATA
The create_captcha() function returns an associative array with this data:
[array]
(
'image' => IMAGE TAG
'time' => TIMESTAMP (in microtime)
'word' => CAPTCHA WORD
)
The "image" is the actual image tag:
<img src="http://example.com/captcha/12345.jpg" width="140" height="50" />
The "time" is the micro timestamp used as the image name without the file
extension. It will be a number like this: 1139612155.3422
The "word" is the word that appears in the captcha image, which if not
supplied to the function, will be a random string.
ADDING A DATABASE
In order for the captcha function to prevent someone from posting, you will need
to add the information returned from create_captcha() function to your database.
Then, when the data from the form is submitted by the user you will need to verify
that the data exists in the database and has not expired.
Here is a table prototype:
CREATE TABLE captcha (
captcha_id bigint(13) unsigned NOT NULL auto_increment,
captcha_time int(10) unsigned NOT NULL,
ip_address varchar(16) default '0' NOT NULL,
word varchar(20) NOT NULL,
PRIMARY KEY `captcha_id` (`captcha_id`),
KEY `word` (`word`)
)
Here is an example of usage with a DB.
On the page where the captcha will be shown you'll have something like this:
$this->load->plugin('captcha');
$vals = array(
'img_path' => './captcha/',
'img_url' => 'http://example.com/captcha/'
);
$cap = create_captcha($vals);
$data = array(
'captcha_id' => '',
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
echo 'Submit the word you see below:';
echo $cap['image'];
echo '<input type="text" name="captcha" value="" />';
Then, on the page that accepts the submission you'll have something like this:
// First, delete old captchas
$expiration = time()-7200; // Two hour limit
$DB->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND date > ?";
$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
echo "You must submit the word that appears in the image";
}
*/
/**
|==========================================================
| Create Captcha
|==========================================================
|
*/
function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '')
{
$defaults = array('word' => '', 'img_path' => '', 'img_url' => '', 'img_width' => '150', 'img_height' => '30', 'font_path' => '', 'expiration' => 7200);
foreach ($defaults as $key => $val)
{
if ( ! is_array($data))
{
if ( ! isset($$key) OR $$key == '')
{
$$key = $val;
}
}
else
{
$$key = ( ! isset($data[$key])) ? $val : $data[$key];
}
}
if ($img_path == '' OR $img_url == '')
{
return FALSE;
}
if ( ! #is_dir($img_path))
{
return FALSE;
}
if ( ! is_really_writable($img_path))
{
return FALSE;
}
if ( ! extension_loaded('gd'))
{
return FALSE;
}
// -----------------------------------
// Remove old images
// -----------------------------------
list($usec, $sec) = explode(" ", microtime());
$now = ((float)$usec + (float)$sec);
$current_dir = #opendir($img_path);
while($filename = #readdir($current_dir))
{
if ($filename != "." and $filename != ".." and $filename != "index.html")
{
$name = str_replace(".jpg", "", $filename);
if (($name + $expiration) < $now)
{
#unlink($img_path.$filename);
}
}
}
#closedir($current_dir);
// -----------------------------------
// Do we have a "word" yet?
// -----------------------------------
if ($word == '')
{
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$str = '';
for ($i = 0; $i < 8; $i++)
{
$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
$word = $str;
}
// -----------------------------------
// Determine angle and position
// -----------------------------------
$length = strlen($word);
$angle = ($length >= 6) ? rand(-($length-6), ($length-6)) : 0;
$x_axis = rand(6, (360/$length)-16);
$y_axis = ($angle >= 0 ) ? rand($img_height, $img_width) : rand(6, $img_height);
// -----------------------------------
// Create image
// -----------------------------------
// PHP.net recommends imagecreatetruecolor(), but it isn't always available
if (function_exists('imagecreatetruecolor'))
{
$im = imagecreatetruecolor($img_width, $img_height);
}
else
{
$im = imagecreate($img_width, $img_height);
}
// -----------------------------------
// Assign colors
// -----------------------------------
$bg_color = imagecolorallocate ($im, 255, 255, 255);
$border_color = imagecolorallocate ($im, 153, 102, 102);
$text_color = imagecolorallocate ($im, 204, 153, 153);
$grid_color = imagecolorallocate($im, 255, 182, 182);
$shadow_color = imagecolorallocate($im, 255, 240, 240);
// -----------------------------------
// Create the rectangle
// -----------------------------------
ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $bg_color);
// -----------------------------------
// Create the spiral pattern
// -----------------------------------
$theta = 1;
$thetac = 7;
$radius = 16;
$circles = 20;
$points = 32;
for ($i = 0; $i < ($circles * $points) - 1; $i++)
{
$theta = $theta + $thetac;
$rad = $radius * ($i / $points );
$x = ($rad * cos($theta)) + $x_axis;
$y = ($rad * sin($theta)) + $y_axis;
$theta = $theta + $thetac;
$rad1 = $radius * (($i + 1) / $points);
$x1 = ($rad1 * cos($theta)) + $x_axis;
$y1 = ($rad1 * sin($theta )) + $y_axis;
imageline($im, $x, $y, $x1, $y1, $grid_color);
$theta = $theta - $thetac;
}
// -----------------------------------
// Write the text
// -----------------------------------
$use_font = ($font_path != '' AND file_exists($font_path) AND function_exists('imagettftext')) ? TRUE : FALSE;
if ($use_font == FALSE)
{
$font_size = 5;
$x = rand(0, $img_width/($length/3));
$y = 0;
}
else
{
$font_size = 16;
$x = rand(0, $img_width/($length/1.5));
$y = $font_size+2;
}
for ($i = 0; $i < strlen($word); $i++)
{
if ($use_font == FALSE)
{
$y = rand(0 , $img_height/2);
imagestring($im, $font_size, $x, $y, substr($word, $i, 1), $text_color);
$x += ($font_size*2);
}
else
{
$y = rand($img_height/2, $img_height-3);
imagettftext($im, $font_size, $angle, $x, $y, $text_color, $font_path, substr($word, $i, 1));
$x += $font_size;
}
}
// -----------------------------------
// Create the border
// -----------------------------------
imagerectangle($im, 0, 0, $img_width-1, $img_height-1, $border_color);
// -----------------------------------
// Generate the image
// -----------------------------------
$img_name = $now.'.jpg';
ImageJPEG($im, $img_path.$img_name);
$img = "<img src=\"$img_url$img_name\" width=\"$img_width\" height=\"$img_height\" style=\"border:0;\" alt=\" \" />";
ImageDestroy($im);
return array('word' => $word, 'time' => $now, 'image' => $img);
}
/* End of file captcha_pi.php */
/* Location: ./system/plugins/captcha_pi.php */
The whole tutorial is in the captcha_pi file. The captcha tutorial in the wiki works on a different script (a class).
try this, CodeIgniter Captcha User Guide

Resources