Cakephp Error: An internal error has occurred - cakephp

I have some code in cakephp which produces an error.
Here is the PHP Controller:
$this->loadModel( 'Vote' ); //Newly added by amit start
$vote=$this->Vote->getVote($id,$uid);
$this->set('vote',$vote);
$voteCount = count($vote);
$this->set('voteCount',$voteCount);
$voteShow = $this->Vote->find('all', array(
'fields' => array('SUM(Vote.score) AS score','count(id) as countId'),
'conditions'=>array('Vote.type_id'=>$id),
));
$this->set('voteShow',$voteShow);
model:
public function getVote($id,$uid) {
if (empty($conditions))
$conditions = array('Vote.type' => 'blog',
'Vote.type_id' => $id,
'Vote.user_id' => $uid);
$users = $this->find('all', array('conditions' => $conditions,
'order' => 'Vote.id desc'
));
return $users;
}
That code produces this error:
Error : An internal error has occurred
What does this error mean?

I enabled debug mode: Configure::write('debug', 2); in core.php and it solved my problem.

In my case debug mode was
Configure::write('debug', 0); on live server in core.php.
I set it to Configure::write('debug', 1); and no error was shown this time.
So I again changed my debug mode to Configure::write('debug', 0); because I don't want to show debug error on my live site.
This time no error message shows up.
So just changing the debug mode once in core.php get rid of this error in my case.
If you change your debug mode to 1 and then run those functions which you have changed on local, CakePHP will refresh the cache for all those models which include in those functions. Now you can change back to Configure::write('debug', 0).

Do NOT set Configure::write('debug',2) in production, or you could end up writing sensitive data (such as Query) to user when there will be an error, the reason why debug 2 works is because items in the CACHE are not taken in consideration anymore, so it works. Just delete the cache and leave DEBUG to 0 in production VERY IMPORTANT
Cache can be found here: tmp/cache/
Then again, do NOT delete the 3 folder you'll find there, just delete their content.

Related

CakePHP 3: Set cache duration in Controller when writing

I am using CakePHP 3 in my project. I am still learning new things as I go. Today I had a requirement to use CakePHP cache to cache data that I retrieve from the database. Every time I load a page that returns data from the database, takes around 30 to 40 seconds.
So I went ahead and configured cache in my controller, which significantly improved page loading from 30 sec to less then 4 seconds.
Now, what I want to do is set duration of the cache to clear itself after 1 hour to refresh new data that is stored in the database.
This is my code that does the caching:
if (!($custstoredata = Cache::read('custstoredata'))) {
# Code logic
Cache::write('custstoredata', $customers);
$this->set('data',$customers);
} else {
$this->set('data', Cache::read('custstoredata'));
}
After doing some research online, I found that I can use Cache::set to configure duration so I went a ahead and added Cache::set(array('duration' => '+1 hour')); in my if statement, but when I load the page in browser, I get this error:
Error: Call to undefined method Cake\Cache\Cache::set()
I am not sure what is the right way to set caching duration in controller real time when cache is written to a file.
I think I answered my own question.
I added below cache config in app.php file:
'reports_seconds' => [
'className' => 'File',
'path' => CACHE,
'serialize' => true,
'duration' => '+60 seconds',
]
Once I added above code, I modified my if statement with below code that fixed the problem.
if (!($custstoredata = Cache::read('custstoredata'))) {
# Code logic
Cache::write('custstoredata', $customers, $config = 'reports_seconds');
$this->set('data',$customers);
} else {
$this->set('data', Cache::read('custstoredata'));
}

CakePHP download file error

So basically I am trying to download a file.
I Have the action:
public function getfile() {
$this->autoRender = false;
$accesskey = 'mrPQVeJF8VFXpSq';
$data = $this->File->find('first', array('conditions' => array('File.accesskey =' => $accesskey)));
$filepath = substr($data['File']['path'], 17);
$this->response->file($filepath, array('download' => true, 'name' => $data['File']['name']));
return $this->response;
}
this throws an error : (i guess the line with $this->response->file())
Fatal Error Error: Class 'File' not found File:
C:\wamp\www\project\lib\Cake\Network\CakeResponse.php Line: 1347
The class File is an Utility of cake. So, using it as a model will probably give you trouble. I recommend you change it. Read more about reserve cake and php words here. That may be the cause of your error.
And the other cause of that error is that you are not in FilesController, and are trying to call the Find model there. for that read how to load models from other controllers (look for ClassRegistry::init or $this->loadModel().
I'm just guessing here, because your are "guessing the line giving trouble is $this->response->file()". You may get a more accurate response if you do not guess and debug exactly what line is giving you that error.

Debugging SQL in controller

I am trying to debug my sql but I am having a hard time. I know I can use this:
<?php echo $this->element('sql_dump'); ?>
to dump the sql but this doesnt (or at least I dont know how to use it) work if I am doing an ajax call. Because the page is not reloaded, the dump does not get refreshed. How can I run my command and debug the sql? Here is the code I have in my controller:
public function saveNewPolicy(){
$this->autoRender = false;
$policyData = $this->request->data["policyData"];
$numRows=0;
$data = array(
'employee_id' => trim($policyData[0]["employeeId"]),
'insurancetype_id'=> $policyData[0]["insuranceTypeId"],
'company' => $policyData[0]["companyName"],
'policynumber' => $policyData[0]["policyNumber"],
'companyphone' => $policyData[0]["companyPhone"],
'startdate'=> $policyData[0]["startDate"],
'enddate'=> $policyData[0]["endDate"],
'note' => $policyData[0]["notes"]
);
try{
$this->Policy->save($data);
$numRows =$this->Policy->getAffectedRows();
if($numRows>0){
$dataId = $this->Policy->getInsertID();
$response =json_encode(array(
'success' => array(
'msg' =>"Successfully Added New Policy.",
'newId' => $dataId
),
));
return $response;
}else{
throw new Exception("Unspecified Error. Data Not Save! ");
}
}catch (Exception $e){
return $this->EncodeError($e);
}
}
The problem is that if the company field in my array is empty, empty, the insert will fail without any error. I know it has failed, though, because of the numrows variable I use. I know the field accepts nulls in the database. It seems like the only way for me to debug this is to look at what SQL is being sent to MySql. Anyone know how to debug it? I am using CakePhp 2.4
I use this approach. I added this method in my AppModel class:
public function getLastQuery() {
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
and then in any controller you call this like:
debug($this->{your model here}->getLastQuery());
Rather than trying to hack around in CakePHP, perhaps it would be easier to just log the queries with MySQL and do a tail -f on the log file? Here's how you can turn that on:
In MySQL, run SHOW VARIABLES; and look for general_log and general_log_file entries
If general_log is OFF, run SET GLOBAL general_log = 'ON'; to turn it on
In a terminal, run a tail -f logfile.log (log file location is in the general_log_file entry) to get a streaming view of the log as it's written to
This is very helpful for these circumstances to see what's going on behind the scenes, or if you have debug off for some reason.

Cakelog is writing to multiple files, but I want it to write to only the one I specify

I want to log payment gateway errors in payment.log. So add this to bootstrap:
CakeLog::config('payment', array(
'engine' => 'FileLog',
'file' => 'payment',
));
and when a problem occurred:
CakeLog::write('payment', 'The is a problem!');
but, the above command will log This is a problem! in both payment.log and error.log, while log into first file is enough.
Also, if any other problems occurred in other controllers (like users), it will log into both files. while it should just log in error.log
(I mean payment errors should log into payment.log and any other problems should write into error.log)
Where's the mistake?
Thanks.
It looks like you are missing the scopes option in the config maybe?
CakeLog::config('payments', array(
'engine' => 'File',
'scopes' => array('payment', 'order')
));
Then you need to specify the scope where you want to write to:
CakeLog::write('warning', 'Stuff is broken here', 'payment');
It may take some fiddling to get it just right, but this should help.

cakephp routing - pages_controller/home.ctp error only on debug=0

When core.php debug is set at 1 or 2 and I browse to the root of my cakephp site I get expected result, the page served is correct, ie, PagesController default() action -> home.ctp
However if I change debug to 0 I get the the following error:
Error: The requested address '/' was
not found on this server.
My router.php file contains:
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
/**
* ...and connect the rest of 'Pages' controller's urls.
*/
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
I have tried deleting all cache files and removing CAKE cookies, and other actions work as expected when visited directly, eg, /user, /groups, etc. Problem only occurs when hitting the root '/'.
I am using cakephp 1.3.4 and ACL + Auth.
Edit ** I'm including the code for the default() function from pages_controller.php
/**
* Displays a view
*
* #param mixed What page to display
* #access public
*/
function display() {
$path = func_get_args();
$count = count($path);
if (!$count) {
$this->redirect('/');
}
$page = $subpage = $title_for_layout = null;
if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
if (!empty($path[$count - 1])) {
$title_for_layout = Inflector::humanize($path[$count - 1]);
}
$this->set(compact('page', 'subpage', 'title_for_layout'));
$this->render(implode('/', $path));
}
OK the answer is so simple it is embarassing: in home.ctp there is the following code:
if (Configure::read() == 0):
$this->cakeError('error404');
endif;
Configure::read() by default read var debug - therefore it throws this error if debug is set to 0.
Thanks to Benjamin for putting me on the right track. Cake is wonderful and at the same time infuriating until you know the basics!
imho this behavior makes sense, as you turn debug to 0 if your app goes into production (something tells me, that you don't want to show the home page as your entry page). The home.ctp which is displayed by the pages controller lives in
./cake/libs/view/pages/home.ctp
of your installation. But if you are in production you want to display the static pages from the
./app/views/pages
directory, which is the task of the pages controller. This directory is empty in a fresh cake installation.
I would like to update code for cakephp version 2.4.3.
as on cakephp version above code is replaced with
if (!Configure::read('debug')):
throw new NotFoundException();
endif;
as when debug is set to '0' it throws exception. you can use below code to make it run properly:
if ((Configure::read('debug')==='')):
throw new NotFoundException();
endif;

Resources