check field weather expired or not while loading a page cakephp - database

The following function checks if the banner is old enough to make it inactive by setting the status field in the Banner table to 0.
/**
*
* Checks weather the banners are old enough to be turned back to non-premium
* and change the status to 0 , in case of non-premium
*
* #return void
*/
protected function check_status(){
$non_premium_expire = 5*24*60*60;
$premium_expire = 14*24*60*60;
$data = $this->Banner->find('all');
foreach ($data as $Banners) {
if ($Banners['Banner']['is_premium'] == 0) {
if ((time() - strtotime($Banners['Banner']['created'])) > $premium_expire) {
$this->Banner->id = $Banners['Banner']['id'];
$this->Banner->saveField('status',0);
}
else if ($Banners['Banner']['is_premium'] == 1) {
if ((time() - strtotime($Banners['Banner']['created'])) > $non_) {
$this->Banner->id = $Banners['Banner']['id'];
$this->Banner->saveField('status',0);
}
}
}
}
}
from mybanners() function. i.e. the check_status() function should be called when users open
/site-name/mybanners
I have called the check_status() function from mybanners() function shown below
public function mybanners()
{
$this->check_status();
$this->layout = 'index';
$this->loadModel('Banner');
$loggedUserId = $this->Auth->user('id');
My problem is that the one field status is not getting updated in the database even after trying set() and updateAll() function. Any solutions? I am newbie in cakephp

I figured it out. The working code is below.
**
*
* Checks weather the banners are old enough to be turned back to non-premium
* and change the status to 0 , in case of non-premium
*
* #return void
*/
protected function check_status(){
$non_premium_expire = 5*24*60*60;
$premium_expire = 14*24*60*60;
$data = $this->Banner->find('all');
//pr ($Banners);
//pr ((time() - strtotime($Banners['Banner']['modified'])) > 5*24*60*60);
//pr ((time() - strtotime($Banners['Banner']['modified'])) > 14*24*60*60);
//die();
foreach ($data as $Banners) {
if ($Banners['Banner']['is_premium'] == 0) {
if ((time() - strtotime($Banners['Banner']['modified'])) > $non_premium_expire) {
$id = $Banners['Banner']['id'];
//pr ("in non premium loop");
//pr ($id);
//die();
$data_one = array('id' => $id , 'status'=> 0, 'modified' => false);
$this->Banner->save($data_one);
//$this->Banner->clear();
}
}
if ($Banners['Banner']['is_premium'] == 1) {
if ((time() - strtotime($Banners['Banner']['modified'])) > $premium_expire) {
$id = $Banners['Banner']['id'];
//pr ("in premium loop");
//pr ($id);
//die();
$data_one = array('id' =>$id , 'status'=> 0, 'modified' => false);
//pr ($data_one);
//die();
$this->Banner->save($data_one);
//$this->Banner->clear();
}
}
}
}

Related

Duplicate rows in the database when refreshing the page laravel

there is a page which is updated every 5-7 seconds, and on it records from the base are updated, but moments these records are duplicated, Do not tell me why this bug can be?
is a ActiveCaller model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class ActiveCaller extends Model
{
protected $fillable = ['queue', 'employee_id', 'station', 'state', 'duration',
'client_id', 'last_call'];
public function Employee()
{
return $this->belongsTo(Employee::class);
}
/**
* Convert duration attribute to acceptable format
*
* #param $value
* #return string
*/
public function getDurationAttribute($value)
{
if (empty($value))
return $value;
return $this->sec2hms($value);
}
public function getStateAttribute($value)
{
if (!empty($value))
return trim($value);
return null;
}
/**
* Convert last call attribute to acceptable format
*
* #param $value
* #return string
*/
public function getLastCallAttribute($value)
{
$data = explode("\n", $value);
$result = "";
$i = 0;
$len = count($data) - 1;
foreach ($data as $item) {
$item = str_replace("\r", "", $item);
$delimiter = "</br>";
if ($i == $len)
$delimiter = "";
if (empty($item) || (trim($item) == "No calls yet")) {
$result .= "No calls yet$delimiter";
} else {
$result .= $this->sec2hms($item) . " min. ago $delimiter";
}
$i++;
}
return $result;
}
public function getStationAttribute($value)
{
return str_replace("\r\n", "</br>", $value);
}
private function sec2hms($sec, $padHours = FALSE)
{
$timeStart = Carbon::now();
$timeEnd = Carbon::now()->addSeconds(intval($sec));
return $timeStart->diff($timeEnd)->format('%H:%I:%S');
}
}
is a AmiApiController
class AmiApiController extends Controller
{
public function fetchDashboardData()
{
$this->updateQueueState();
$activeCallers = ActiveCaller::with('Employee')
->where('old', true)
->orderBy('queue')
->orderBy('employee_id')
->orderBy('station', 'asc')
->get();
$waitingList = WaitingList::where('old', false)->get();
$waitingList = $waitingList->unique('client_id');
$charts = Chart::all()->toArray();
$chartFormatData = [
'Total' => [],
'Callers' => [],
'Queues' => [],
];
foreach ($charts as $key => $chart) {
$charts[$key]['data'] = json_decode($chart['data'], 1);
$chartFormatData[$chart['name']]['total'] = 0;
foreach ($charts[$key]['data']['statistic'] as $datum) {
// if ($datum[0] === 'Effort')
// continue;
$chartFormatData[$chart['name']]['label'][] = $datum[0];
$chartFormatData[$chart['name']]['data'][] = $datum[1];
$chartFormatData[$chart['name']]['name'] = $chart['name'];
}
$chartFormatData[$chart['name']]['total'] = array_sum($chartFormatData[$chart['name']]['data']);
// $chartFormatData[$chart['name']]['label'] = array_reverse($chartFormatData[$chart['name']]['label']);
}
return response()->json([
'activeCallers' => $activeCallers,
'charts' => $chartFormatData,
'waitingList' => $waitingList
], 200);
}
this is where we begin to check if we can update the database at this time
/**
* Check whether the database can be updated at this time
*
* - Returns True if no updates are currently being made to the database
* and the latest update was less than 5 seconds later
* -
Returns True if the update already occurs for more than 15 seconds
*
* - Returns False if an update is already in the database
* -
Returns False if the last update was within the last 5 seconds
*
* If the parameter in $ json is passed true (by default)
* the method returns the answer in JSON format
*
* If the parameter is passed false to $ json
* method returns a php-shne Boolean value
*
* #param bool $json
* #return bool|\Illuminate\Http\JsonResponse
*/
public function canWeUpdate($json = true)
{
$result = ['return' => null, 'msg' => null];
$isUpdating = Configuration::where('key', 'is_ami_data_updating')->first();
if (is_null($isUpdating)) {
Configuration::create(['key' => 'is_ami_data_updating', 'value' => 0]);
}
if ($isUpdating->value == true) {
// if an update is currently in progress
$checkingDate = Carbon::now()->addSeconds(-10);
if ($isUpdating->updated_at < $checkingDate) {
// if the update is longer than 15 seconds, we will cancel this update
$isUpdating->update(['value' => false]);
$result['return'] = true;
$result['msg'] = "Old update in database";
} else {
// if the update is less than 15 seconds, we cannot update again
$result['return'] = false;
$result['msg'] = "CURRENTLY UPDATE";
}
} else if ($isUpdating->updated_at > Carbon::now()->addSeconds(-3)) {
// if the last update was less than 5 seconds ago, we cannot update
$result['return'] = false;
$result['msg'] = "TOO EARLY";
} else {
//if the last update was more than 5 seconds ago, we allow the update
$result['return'] = true;
$result['msg'] = "OK";
}
if ($json)
return $this->simpleResponse($result['return'], $result['msg']);
return $result['return'];
}
is a method fot check if new data is in the database
/**
* A method to check if new data is in the database
*
* Returns True if validation time is less than database update time
* Returns False if validation time is longer than database update time
* Returns False if there is no data in the database
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function checkForNewData(Request $request)
{
$date = new Carbon($request->last_call);
$lastRecord = ActiveCaller::latest()->first();
if (is_null($lastRecord))
return $this->simpleResponse(false);
if ($date < $lastRecord->updated_at) {
return $this->simpleResponse(true);
} else
return $this->simpleResponse(false);
}
/**
* Method for loading table data
*
* Agents - information about active numbers in the PBX in all queues
* Waiting - information about numbers in standby mode
*
* #return \Illuminate\Http\JsonResponse
*/
public function renderAgentTable()
{
$agents = ActiveCaller::with('Employee')
->where('old', true)
->orderBy('queue')
->orderBy('station', 'asc')
->get();
$waitingList = WaitingList::all();
$agentsTable = View::make('dashboard.render.agent-table', ['agents' => $agents]);
$waitingTable = View::make('dashboard.render.waiting-list-table', ['waitingList' => $waitingList]);
$result =
[
'agents' => $agentsTable->render(),
'waiting' => $waitingTable->render(),
];
$result = array_merge($result, $this->renderDashboardChart(new Request()));
return response()->json($result);
}
/**
* Method for updating data from AMI
*
* updating data for ActiveCaller
* updating data for WaitingList
*/
public function updateQueueState()
{
if (!$this->canWeUpdate(false)) {
// dd("We can't update (large check)");
return;
}
$lastUpdateTime = ActiveCaller::latest()->first();
if ($lastUpdateTime != null)
if ($lastUpdateTime->created_at > Carbon::now()->addSeconds(-3)) {
// dd("We can't update (small check)");
return;
}
// we notice the launch of the update in the database
$isAmiDataUpdating = Configuration::where('key', 'is_ami_data_updating')->first();
$isAmiDataUpdating->update(['value' => true]);
$this->ClearOldRecords();
$queues = Queue::where('on_dashboard', '=', '1')->get()->toArray();
// we go through all the queues that are available in AMI
foreach ($queues as $queue) {
$command = new AMIQueueMemberState($queue['name']);
// we get a list of numbers and a waiting list of calls
$response = $command->handle();
$agents = $response['agents'];
$callers = $response['callers'];
//convert the waiting list to PeerList
$peerList = PeerInfo::hydrate($agents);
$employees = new Collection();
foreach ($callers as $caller) {
$caller['queue'] = $queue['name'];
WaitingList::create($caller);
}
$peerList->each(function (PeerInfo $peer) use ($employees) {
$record = Record
::where('phone', 'like', '%' . $peer->name . '%')
->where('end_date', null)
->get()->first();
$data = null;
if ($record != null) {
// check if this user already has an entry in active_callers (not old)
$active = ActiveCaller
::where('employee_id', $record['employee_id'])
->where('old', false)
->get()->first();
// if so, add him another number and
// we move on to the next iteration
if ($active != null) {
if ($this->HandleSingleActive($active, $peer->name, $peer->last_call))
return;
}
$peer->station = $record['station_name'];
$peer->employee_id = $record['employee_id'];
$a = collect($peer->toArray());
$data = $a->except(['name', 'pause'])->toArray();
$data['station'] = "$peer->station | $peer->name";
} else {
$peer->station = "- | $peer->name";
$a = collect($peer->toArray());
$data = $a->except(['name', 'pause'])->toArray();
}
ActiveCaller::create($data);
});
}
$this->updateDashboardChart();
$isAmiDataUpdating->update(['value' => false]);
}

Codeigniter 3.1.9 - CI_Session is filling up my database on every refresh

I have been getting back into Codeigniter as support was picked up by BCIT. I have a problem with ci_sessions and the database driver which is regenerating the encrypted session ID and storing new data in my database on every page refresh. I'm so frustrated right now! I have both secure file storage and database for both common drivers. I want to use both or either but the effect on my application is the same whether I am using a database or files. The ci_session keeps refreshing and it is not ideal for logins, registration or any account type. Please help me see what I am doing wrong? Much appreciation granted in advance.
Config:
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'users';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
Controllers:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* User Management class created by CodexWorld
*/
class Limousers extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->model('user');
}
/*
* User account information
*/
public function account(){
print_r($_SESSION);
$data = array();
print_r($this->session->userdata());
if($this->session->userdata('isUserLoggedIn')){
$data['user'] = $this->user->getRows(array('id'=>$this->session->userdata('userId')));
//load the view
$this->load->view('limousers/account', $data);
}else{
redirect('limousers/login');
exit;
}
}
/*
* User login
*/
public function login(){
print_r($_SESSION);
if($this->session->userdata('isUserLoggedIn'))
{
print_r($this->session->userdata);
redirect('limousers/account');
exit;
}
$data = array();
if($this->session->userdata('success_msg')){
$data['success_msg'] = $this->session->userdata('success_msg');
$this->session->unset_userdata('success_msg');
}
if($this->session->userdata('error_msg')){
$data['error_msg'] = $this->session->userdata('error_msg');
$this->session->unset_userdata('error_msg');
}
if($this->input->post('loginSubmit')){
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'password', 'required');
if ($this->form_validation->run() == true) {
$con['returnType'] = 'single';
$con['conditions'] = array(
'email'=>$this->input->post('email'),
'password' => md5($this->input->post('password')),
'status' => '1'
);
$checkLogin = $this->user->getRows($con);
if($checkLogin){
$this->session->set_userdata('name',$con['conditions']['email']);
$this->session->set_userdata('isUserLoggedIn',TRUE);
$this->session->set_userdata('userId',$checkLogin['id']);
redirect('limousers/account');
exit;
}else{
$data['error_msg'] = 'Wrong email or password, please try again.';
}
}
}
//load the view
$this->load->view('limousers/login', $data);
}
/*
* User registration
*/
public function registration(){
print_r($_SESSION);
$data = array();
$userData = array();
if($this->input->post('regisSubmit')){
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_email_check');
$this->form_validation->set_rules('password', 'password', 'required');
$this->form_validation->set_rules('conf_password', 'confirm password', 'required|matches[password]');
$userData = array(
'name' => strip_tags($this->input->post('name')),
'email' => strip_tags($this->input->post('email')),
'password' => md5($this->input->post('password')),
'gender' => $this->input->post('gender'),
'phone' => strip_tags($this->input->post('phone'))
);
if($this->form_validation->run() == true){
$insert = $this->user->insert($userData);
if($insert){
$this->session->set_userdata('success_msg', 'Your registration was successfully. Please login to your account.');
redirect('limousers/login');
exit;
}else{
$data['error_msg'] = 'Some problems occured, please try again.';
}
}
}
$data['user'] = $userData;
//load the view
$this->load->view('limousers/registration', $data);
}
/*
* User logout
*/
public function logout(){
$this->session->unset_userdata('isUserLoggedIn');
$this->session->unset_userdata('userId');
$this->session->sess_destroy();
redirect('limousers/login');
exit;
}
/*
* Existing email check during validation
*/
public function email_check($str){
$con['returnType'] = 'count';
$con['conditions'] = array('email'=>$str);
$checkEmail = $this->user->getRows($con);
if($checkEmail > 0){
$this->form_validation->set_message('email_check', 'The given email already exists.');
return FALSE;
} else {
return TRUE;
}
}
}
Models:
<?php if ( ! defined('BASEPATH')) exit('No direct script access
allowed');
class User extends CI_Model{
function __construct() {
$this->userTbl = 'users';
}
/*
* get rows from the users table
*/
function getRows($params = array()){
$this->db->select('*');
$this->db->from($this->userTbl);
//fetch data by conditions
if(array_key_exists("conditions",$params)){
foreach ($params['conditions'] as $key => $value) {
$this->db->where($key,$value);
}
}
if(array_key_exists("id",$params)){
$this->db->where('id',$params['id']);
$query = $this->db->get();
$result = $query->row_array();
}else{
//set start and limit
if(array_key_exists("start",$params) &&
array_key_exists("limit",$params)){
$this->db->limit($params['limit'],$params['start']);
}elseif(!array_key_exists("start",$params) &&
array_key_exists("limit",$params)){
$this->db->limit($params['limit']);
}
$query = $this->db->get();
if(array_key_exists("returnType",$params) &&
$params['returnType'] == 'count'){
$result = $query->num_rows();
}elseif(array_key_exists("returnType",$params) &&
$params['returnType'] == 'single'){
$result = ($query->num_rows() > 0)?$query- >row_array():FALSE;
}else{
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
}
}
//return fetched data
return $result;
}
/*
* Insert user information
*/
public function insert($data = array()) {
//add created and modified data if not included
if(!array_key_exists("created", $data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists("modified", $data)){
$data['modified'] = date("Y-m-d H:i:s");
}
//insert user data to users table
$insert = $this->db->insert($this->userTbl, $data);
//return the status
if($insert){
return $this->db->insert_id();
}else{
return false;
}
}
}

Persisting data to database. persist not working

I wrote a controller action that is supposed to add an element (meeting) to the database here it is:
public function newAction(Request $request){
$meeting = new Meeting();
$meetingUser = new MeetingUser();
$project = new Project();
$projectName = "SocialPro";//$request->get('projectName');
echo($projectName);
$users = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findProjectUser($projectName);
//$form = $this->createForm('SocialPro\MeetingBundle\Form\MeetingType', $meeting);
//$form->handleRequest($request);
//if ($form->isSubmitted() && $form->isValid()) {
$userconn = $this->container->get('security.token_storage')->getToken()->getUser();
echo($userconn->getId());
if ($request->isMethod('POST')) {
echo("message form");
$role = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findUserRole($userconn)[0]['role'];
$date = $request->get('date');
if ($role == "PROJECT_MASTER" || $role == "TEAM_MASTER") {
for ($i = 0; $i < count($users); $i++) {
$meetings = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findMeetingUser($users[$i]['id'], $date);
}
if ($meetings == null || count($meetings) == 0) {
$project = $this->getDoctrine()->getRepository('SocialProProjectBundle:Project')->findBy(array("name" = >$projectName));
$meeting->setDescription($request->get('description'));
$meeting->setDate(new \DateTime($request->get('date')));
$meeting->setTime($request->get('time'));
$meeting->setProjectName($request->get('projectName'));
$meeting->setProject($project[0]);
$meetingUser->setMeetings($meeting);
$meetingUser->setUsers($userconn);
var_dump($meetingUser);
$meeting->setMeetingUser(array($meetingUser));
//$project->setMeetings($meeting->getId());
$em = $this->getDoctrine()->getManager();
$em->persist($meeting);
$em->persist($meetingUser);
$em->flush();
// $meetingUser->setUsers($request->get(''));
return $this->redirectToRoute('reunion_show', array('id' = > $meeting->getId()));
}
else {
echo("Membre indisponible");
}
}
else {
echo("Must be MASTER to create meeting");
}
}
return $this->render('SocialProMeetingBundle::ajoutMeeting.html.twig', array('users' = >$users));
// $em = $this->getDoctrine()->getManager();
//$em->persist($meeting);
//$em->flush($meeting);
// return $this->redirectToRoute('meeting_show', array('id' => $meeting->getId()));
//}
//return $this->render('SocialProMeetingBundle:ajouMeeting', array(
// 'meeting' => $meeting,
//'form' => $form->createView(),
//));
}
When I submit the form it gives me a site not available page. I tested it line by line and everything is working perfectly. Turns out the problem is in the
$em->persist($meeting);
And I have no idea how to fix it.
You must call flush immediately after calling persist like so:
$em->persist( $meeting );
$em->flush();
$em->persist( $meetingUser );
$em->flush();
Then it will persist both.

CakePHP 2.2 - TCPDF - invalid property message

I have a problem with TCPDF:
viewPDF:
function viewPdf($id = null)
{
if (!$id)
{
$this->Session->setFlash('Sorry, there was no property ID submitted.');
$this->redirect(array('action'=>'index'), null, true);
}
Configure::write('debug',0); // Otherwise we cannot use this method while developing
$id = intval($id);
$property = $this->__view($id); // here the data is pulled from the database and set for the view
if (empty($property))
{
$this->Session->setFlash('Sorry, there is no property with the submitted ID.');
$this->redirect(array('action'=>'index'), null, true);
}
$this->layout = 'pdf'; //this will use the pdf.ctp layout
$this->render();
}
__view:
function __view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Calculation.', true));
$this->redirect(array('action'=>'index'));
}
$this->set('calculation', $this->Calculation->read(null, $id));
}
viewPDF.ctp:
<?php
App::import('Vendor','xtcpdf');
$tcpdf = new XTCPDF();
$textfont = 'freesans'; // looks better, finer, and more condensed
than 'dejavusans'
$tcpdf->SetAuthor("KBS Homes & Properties a http://kbs-properties.com");
$tcpdf->SetAutoPageBreak( false );
$tcpdf->setHeaderFont(array($textfont,'',20));
$tcpdf->xheadercolor = array(150,0,0);
$tcpdf->xheadertext = 'Test';
$tcpdf->xfootertext = 'Copyright © %d KBS Homes & Properties. All
rights reserved.';
// Now you position and print your page content
// example:
$tcpdf->SetTextColor(0, 0, 0);
$tcpdf->SetFont($textfont,'B',20);
$tcpdf->Cell(0,14, "Hello World", 0,1,'L');
// ...
// etc.
// see the TCPDF examples
$tcpdf->Output('filename.pdf', 'I');
?>
PDF layout for CakePHP 2.2 ($content_for_layout is depricated):
<?php
header("Content-type: application/pdf");
echo $this->fetch('content');
?>
xtcpdf.php in app/Vendor:
<?php
App::import('Vendor','tcpdf/tcpdf');
class XTCPDF extends TCPDF
{
var $xheadertext = 'PDF created using CakePHP and TCPDF';
var $xheadercolor = array(0,0,200);
var $xfootertext = 'Copyright © %d XXXXXXXXXXX. All rights reserved.';
var $xfooterfont = PDF_FONT_NAME_MAIN ;
var $xfooterfontsize = 8 ;
/**
* Overwrites the default header
* set the text in the view using
* $fpdf->xheadertext = 'YOUR ORGANIZATION';
* set the fill color in the view using
* $fpdf->xheadercolor = array(0,0,100); (r, g, b)
* set the font in the view using
* $fpdf->setHeaderFont(array('YourFont','',fontsize));
*/
function Header()
{
list($r, $b, $g) = $this->xheadercolor;
$this->setY(10); // shouldn't be needed due to page margin, but helas, otherwise it's at the page top
$this->SetFillColor($r, $b, $g);
$this->SetTextColor(0 , 0, 0);
$this->Cell(0,20, '', 0,1,'C', 1);
$this->Text(15,26,$this->xheadertext );
}
/**
* Overwrites the default footer
* set the text in the view using
* $fpdf->xfootertext = 'Copyright © %d YOUR ORGANIZATION. All rights reserved.';
*/
function Footer()
{
$year = date('Y');
$footertext = sprintf($this->xfootertext, $year);
$this->SetY(-20);
$this->SetTextColor(0, 0, 0);
$this->SetFont($this->xfooterfont,'',$this->xfooterfontsize);
$this->Cell(0,8, $footertext,'T',1,'C');
}
}
?>
And I always get "Sorry, there is no property with the submitted ID." and I don't see the problem.
you should have a look on this code :
function __view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Calculation.', true));
$this->redirect(array('action'=>'index'));
}
$data = $this->Calculation->read(null, $id));
return $data;
}

Problem in executing Cron Jobs

i have done a bidding site in Cake PHP.The main problem I am facing is I need to run CRON JOBS on the server.But I dont' know why it is bugging me.I have craeted a controller called 'deamons' and there 4 different actions of it,which I want to run continuously on the server every minute,so that we can run the Autobidder set by each user of that bidding site.
The Cron Jobs I am setting up are...
curl -s -o /dev/null http://www.domain.com/app/webroot/daemons/bidbutler
curl -s -o /dev/null http://www.domain.com/app/webroot/daemons/extend
curl -s -o /dev/null http://www.domain.com/app/webroot/daemons/autobid
curl -s -o /dev/null http://www.domain.com/app/webroot/daemons/close
and the the controller which is handling all the stuff is attached below....!!!
Please suggest me some solution to this so that
If the experts wants to test it..the URL is www.domain.com/app/webroot
And here is the code...which I am trying to run through the CRONS...!!!
<?php
class DaemonsController extends AppController {
var $name = 'Daemons';
var $uses = array('Auction', 'Setting');
function beforeFilter(){
$email='nishant.nightcrawler#gmail.com';
$secondemail='no-reply#bidoppo.com';
$mess='It works';
//#mail($email, 'Test', $mess, "From: ".$secondemail);
parent::beforeFilter();
if(!empty($this->Auth)) {
$this->Auth->allow('bidbutler', 'extend', 'autobid', 'close');
}
ini_set('max_execution_time', ($this->appConfigurations['cronTime'] * 60) + 1);
}
/**
* The function makes the bid butler magic happen
*
* #return array Affected Auction
*/
function bidbutler() {
$this->layout = 'js/ajax';
$data = array();
$setting = array();
$auctions = array();
// Get the bid butler time
$bidButlerTime = $this->Setting->get('bid_butler_time');
// Get various settings needed
$data['bid_debit'] = $this->Setting->get('bid_debit');
$data['auction_price_increment'] = $this->Setting->get('auction_price_increment');
$data['auction_time_increment'] = $this->Setting->get('auction_time_increment');
$data['auction_peak_start'] = $this->Setting->get('auction_peak_start');
$data['auction_peak_end'] = $this->Setting->get('auction_peak_end');
$expireTime = time() + ($this->appConfigurations['cronTime'] * 60);
while (time() < $expireTime) {
// Formating the conditions
$conditions = array(
'Auction.end_time < \''. date('Y-m-d H:i:s', time() + $bidButlerTime). '\'',
'Auction.closed' => 0,
'Bidbutler.bids >' => 0
);
// Find the bidbutler entry - we get them from the lowest price to the maximum price so that they all run!
$this->Auction->Bidbutler->contain('Auction');
$bidbutlers = $this->Auction->Bidbutler->find('all', array('conditions' => $conditions, 'order' => 'rand()', 'fields' => array('Auction.id', 'Auction.start_price', 'Bidbutler.id', 'Bidbutler.minimum_price', 'Bidbutler.maximum_price', 'Bidbutler.user_id'), 'contain' => 'Auction'));
if(!empty($bidbutlers)) {
// Walk through bidbutler entries
foreach($bidbutlers as $bidbutler) {
if($bidbutler['Bidbutler']['minimum_price'] >= $bidbutler['Auction']['start_price'] &&
$bidbutler['Bidbutler']['maximum_price'] < $bidbutler['Auction']['start_price']) {
// Add more information
$data['auction_id'] = $bidbutler['Auction']['id'];
$data['user_id'] = $bidbutler['Bidbutler']['user_id'];
$data['bid_butler'] = $bidbutler['Bidbutler']['id'];
// Bid the auction
$result = $this->Auction->bid($data);
}
}
}
usleep(900000);
}
}
/**
* The function auto extends auctions and bids for an auto bid if neccessary
*
* #return array Affected Auction
*/
function extend() {
$this->layout = 'js/ajax';
$data = array();
$setting = array();
$auctions = array();
$data['bid_debit'] = $this->Setting->get('bid_debit');
$data['auction_price_increment'] = $this->Setting->get('auction_price_increment');
$data['auction_time_increment'] = $this->Setting->get('auction_time_increment');
$data['auction_peak_start'] = $this->Setting->get('auction_peak_start');
$data['auction_peak_end'] = $this->Setting->get('auction_peak_end');
$data['isPeakNow'] = $this->isPeakNow();
$expireTime = time() + ($this->appConfigurations['cronTime'] * 60);
while (time() < $expireTime) {
// now check for auto extends
$auctions = Cache::read('daemons_extend_auctions');
if(empty($auctions)) {
$auctions = $this->Auction->find('all', array('contain' => '', 'conditions' => "(Auction.extend_enabled = 1 OR Auction.autobid = 1) AND (Auction.start_price < Auction.minimum_price) AND Auction.winner_id = 0 AND Auction.closed = 0"));
Cache::write('daemons_extend_auctions', $auctions, '+1 day');
}
if(!empty($auctions)) {
foreach($auctions as $auction) {
// lets see if we need to extend the auction
$endTime = strtotime($auction['Auction']['end_time']);
$extendTime = time() + ($auction['Auction']['time_before_extend']);
if($extendTime > $endTime) {
// lets see if autobid is enabled
// autobid will place a bid by a robot if another user is the highest bidder but hasn't meet the minimum price
if($auction['Auction']['autobid'] == 1) {
if($auction['Auction']['extend_enabled'] == 1) {
// lets only bid if the limit is less than te autobid limit when the autobid limit is set
if($auction['Auction']['autobid_limit'] > 0) {
if($auction['Auction']['current_limit'] <= $auction['Auction']['autobid_limit']) {
$this->Auction->Autobid->check($auction['Auction']['id'], $auction['Auction']['end_time'], $data);
}
} else {
$this->Auction->Autobid->check($auction['Auction']['id'], $auction['Auction']['end_time'], $data);
}
} else {
$bid = $this->Auction->Bid->lastBid($auction['Auction']['id']);
// lets set the autobid
if(!empty($bid) && ($bid['autobidder'] == 0)) {
$this->Auction->Autobid->check($auction['Auction']['id'], $auction['Auction']['end_time'], $data);
}
}
} elseif($auction['Auction']['extend_enabled'] == 1) {
unset($auction['Auction']['modified']);
$auction['Auction']['end_time'] = date('Y-m-d H:i:s', $endTime + ($auction['Auction']['time_extended']));
// lets do a quick check to make sure the new end time isn't less than the current time
$newEndTime = strtotime($auction['Auction']['end_time']);
if($newEndTime < time()) {
$auction['Auction']['end_time'] = date('Y-m-d H:i:s', time() + ($auction['Auction']['time_extended']));
}
$this->Auction->save($auction);
}
}
}
}
usleep(800000);
}
}
/**
* The function auto extends auctions in the last IF the extend function fails
*
* #return array Affected Auction
*/
function autobid() {
$data['bid_debit'] = $this->Setting->get('bid_debit');
$data['auction_time_increment'] = $this->Setting->get('auction_time_increment');
$data['auction_price_increment'] = $this->Setting->get('auction_price_increment');
$data['auction_peak_start'] = $this->Setting->get('auction_peak_start');
$data['auction_peak_end'] = $this->Setting->get('auction_peak_end');
$data['isPeakNow'] = $this->isPeakNow();
$isPeakNow = $this->isPeakNow();
$expireTime = time() + ($this->appConfigurations['cronTime'] * 60);
while (time() < $expireTime) {
// lets start by getting all the auctions that have closed
$auctions = $this->Auction->find('all', array('fields' => array('Auction.id', 'Auction.peak_only'), 'contain' => '', 'conditions' => "Auction.winner_id = 0 AND Auction.end_time <= '" . date('Y-m-d H:i:s', time() + 4) . "' AND Auction.closed = 0"));
if(!empty($auctions)) {
foreach($auctions as $auction) {
// before we declare this user the winner, lets run some test to make sure the auction can definitely close
if($this->Auction->checkCanClose($auction['Auction']['id'], $isPeakNow, false) == false) {
// lets check to see if the reason we can't close it, is because its now offpeak and this is a peak auction
if($auction['Auction']['peak_only'] == 1 && !$isPeakNow) {
continue;
} else {
$this->Auction->Autobid->placeAutobid($auction['Auction']['id'], $data);
}
}
}
}
usleep(900000);
}
}
/**
* The function closes the auctions
*
* #return array Affected Auction
*/
function close() {
$expireTime = time() + ($this->appConfigurations['cronTime'] * 60);
while (time() < $expireTime) {
// lets start by getting all the auctions that have closed
$auctions = $this->Auction->find('all', array('contain' => '', 'conditions' => "Auction.winner_id = 0 AND Auction.end_time <= '" . date('Y-m-d H:i:s') . "' AND Auction.closed = 0"));
if(!empty($auctions)) {
foreach($auctions as $auction) {
$isPeakNow = $this->isPeakNow();
// before we declare this user the winner, lets run some test to make sure the auction can definitely close
if($this->Auction->checkCanClose($auction['Auction']['id'], $isPeakNow) == false) {
// lets check to see if the reason we can't close it, is because its now offpeak and this is a peak auction
if($auction['Auction']['peak_only'] == 1 && !$isPeakNow) {
$peak = $this->nonPeakDates();
//Calculate how many seconds auction will end after peak end
$seconds_after_peak = strtotime($auction['Auction']['end_time']) - strtotime($peak['peak_end']);
$end_time = strtotime($peak['peak_start']) + $seconds_after_peak;
$auction['Auction']['end_time'] = date('Y-m-d H:i:s', $end_time);
$this->Auction->save($auction);
} else {
// lets check just how far ago this auction closed, and either place an autobid or extend the time
$data['auction_time_increment'] = $this->Setting->get('auction_time_increment');
$newEndTime = strtotime($auction['Auction']['end_time']);
if($newEndTime < time() - $data['auction_time_increment']) {
$auction['Auction']['end_time'] = date('Y-m-d H:i:s', time() + ($auction['Auction']['time_extended']));
$this->Auction->save($auction);
} else {
//lets extend it by placing an autobid
$data['bid_debit'] = $this->Setting->get('bid_debit');
$data['auction_price_increment'] = $this->Setting->get('auction_price_increment');
$data['auction_peak_start'] = $this->Setting->get('auction_peak_start');
$data['auction_peak_end'] = $this->Setting->get('auction_peak_end');
$data['isPeakNow'] = $this->isPeakNow();
$this->Auction->Autobid->placeAutobid($auction['Auction']['id'], $data);
}
}
continue;
}
$bid = $this->Auction->Bid->find('first', array('conditions' => array('Bid.auction_id' => $auction['Auction']['id']), 'order' => array('Bid.id' => 'desc')));
if(!empty($bid)) {
if($bid['User']['autobidder'] == 0) {
// send the email to the winner
$data['Auction'] = $auction['Auction'];
$data['Bid'] = $bid['Bid'];
$data['User'] = $bid['User'];
$data['to'] = $data['User']['email'];
$data['subject'] = sprintf(__('%s - You have won an auction', true), $this->appConfigurations['name']);
$data['template'] = 'auctions/won_auction';
$this->_sendEmail($data);
$auction['Auction']['status_id'] = 1;
}
$auction['Auction']['winner_id'] = $bid['Bid']['user_id'];
}
unset($auction['Auction']['modified']);
$auction['Auction']['closed'] = 1;
$this->Auction->save($auction);
}
}
usleep(900000);
}
}
}
?>
The CakePHP way to run crons is to build your own shells to do the tasks. Shells allows you full access to all of your controllers through the command prompt. Be sure to read this documentation when starting:
http://book.cakephp.org/view/108/The-CakePHP-Console
It shows you how to build your own shells (app/vendors/shells/), how to organize your shells into tasks, and how to properly run your shell as a cron job.
I do it a slightly different way than the documentation describes. My cron statement looks like:
* * * * * (cd /path/to/my/cake/app; sh ../cake/console/cake daily;) 1> /dev/null 2>&1
From there I simply have a shell called app/vendors/shells/daily.php
<?php
class DailyShell extends Shell {
var $uses = array('User');
function main() {
$this->User->processDailyTasks();
}
}
?>
This is far better and more stable than using curl in a cron job.

Resources