Codeigniter show error page instead Exception error - php

this is my code
public function movieInfo($movieId = null) {
// get the data
$movie = $this->repository->load($movieId);
$this->set_title(null);
$data = $this->includes;
$content_data = array(
'movie' => $movie,
);
$data['content'] = $this->load->view('movie/movie_info', $content_data, true);
$this->load->view($this->template, $data);
}
when i browse to http://tmdb.instaplace.me/movie/movieinfo/76341 it shows my page
but when i browse to http://tmdb.instaplace.me/movie/movieinfo/0
it shows a uncaught exception page when error reporting is set to development otherwise it shows a blank page
instead of showing blank page or uncaught exception on development i want to show a page that says "The id does not exist" for example or a 404 page
but my problem is i can't figure it out how to do that, i am using this
php-tmdb wrapper
the $movieId variable is the id from themoviedb.org to find the movie based on the id

if( ! $movie = $this->repository->load($movieId) ){
$this->_showMovieNotFoundFor($movieId) ; }
else{ $this->_showFound($movie) ; }
edit in response to question ====
you have to create the _show methods yourself. the idea is that you are just checking if a movie came back from the database or not. in the controller the simpler you can make your methods the easier it is to maintain. and unless a method in a controller has to be public, always make them private. in codeigniter you can just put an underscore before the method name to make it private. so the code
if( ! $movie = $this->repository->load($movieId)
so if the $movie did NOT come back from database - then go to
$this->_showMovieNotFoundFor($movieId) ;
i included $movieId in case its needed for the error message.
otherwise you got $movie from database so go to
$this->_showFound($movie) ;
where if we just paste your code its going to be something like
function _showFound($movie){
$this->set_title(null);
$data = $this->includes;
$content_data = array(
'movie' => $movie,
);
$data['content'] = $this->load->view('movie/movie_info', $content_data, true);
$this->load->view($this->template, $data);
}

Related

Why is necessary two requests to transfer the file?

I have this method below to download a file from an API server. But its not working properly, when the user clicks in the button that calls the getFile() method it appears at first in the page the error
Trying to get property of non-object
But if the user click in the browser refresh button the file is downloaded.
So it seems that for the file be generated is necessary send two requests and in the first appears
Trying to get property of non-object
In the second the file is transfered, in the third it appears again
Trying to get property of non-object
In the API says that to download the file is an asynchronous operation, which means that the file may not be ready immediately. I dont know if the issue can be because of that.
Code:
public function getFile($regId){
$client = new \GuzzleHttp\Client();
$user = Auth::user();
$registration = $user->registrations()->with(["proforma"])->where("id", $regId)->first();
$proforma = $registration->proforma->proforma_number;
$getProforma = $client->request('GET', 'https://...'.$proforma.'.json', [
'query' => ['api_key' => '...'],
]);
$response = $getProforma->getBody()->getContents();
$url = null;
if(!empty($response)) {
$response = json_decode($response);
$url = !empty($response->output->pdfUrl) ? $response->output->pdfUrl : '';
}
header("Location: $url");
}
public function getFile($regId)
{
$registration = auth()->user()->registrations()->with(["proforma"])->where("id", $regId)->first();
$proforma = $registration->proforma->proforma_number;
$getProforma = json_decode(file_get_contents('https://...' . $proforma . '.json?api_key=.....'));
// $getProforma->output here was your problem so I advice you to: dd($getProforma);
$url = ! empty(optional($getProforma->output)->pdfUrl) ? optional($getProforma->output)->pdfUrl : '/'; // it will redict home if it couldn't find the PDF URL
return redirect($url);
}

CakePHP Dropzone.js error Ajax

I'm trying to implement dropzone.js into my CakePHP application. So far it all went fine. Except When I receive an error, it displays the whole HTML error page, not rendered. Which turns into a bunch of HTML code, not quite readable and because the error box becomes so big I cannot click the "remove" button. See picture below:
As soon as I receive an error:
When I hover the box, after receiving an error:
I know the reason is that dropzone.js recognizes the error because of the 500 header of the Ajax page (I throw an Exception if something goes wrong). And CakePHP renders a complete layout for a 500 error page. So it's not possible for me to just view a one row error. And I really need the 500 header, because else dropzone.js thinks everything went fine....
So my question: Is it possible to NOT render the 500 error layout, when getting a 500 error within a specific Controller method? I don't want to completely disable the 500 error layout rendering. Only for AJAX pages.
public function admin_add($slug = null) {
if(!$slug || !$client = $this->Video->Client->find('first', array('conditions' => array('slug' => $slug)))) {
throw new NotFoundException(__('Invalid client'));
}
if ($this->request->is('post')) {
// If request contains files, continue
if (!empty($_FILES)) {
// Get slug from URL
$slug = substr( $this->referer(), strrpos( $this->referer(), '/' )+1 );
// Create new folder for the movies if it doesn't exist already
if (!file_exists(WWW_ROOT.'/files/'.$slug)) {
mkdir(WWW_ROOT.'/files/'.$slug, 0777, true);
}
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = '/files/'.$slug.'/';
$targetFile = $targetPath. $_FILES['file']['name'];
// Create variable filename without the extension
$fileWithoutExt = preg_replace("/\\.[^.\\s]{3,4}$/", "", $_FILES['file']['name']);
// Add file to Video array
$video['Video'] = array('video' => $targetFile, 'screenshot' => '/files/'.$slug.'/screenshots/'.$fileWithoutExt.'.jpg', 'client_id' => $client['Client']['id']);
// unset($video);
// Try moving the file to their final directory
if(!move_uploaded_file($tempFile, WWW_ROOT.$targetFile)) {
throw new NotFoundException(__('Move image to "'.WWW_ROOT.$targetPath.'" failed'));
}
// Create new folder for the screenshots if it doesn't exist already
if (!file_exists(WWW_ROOT.'/files/'.$slug.'/screenshots/')) {
mkdir(WWW_ROOT.'/files/'.$slug.'/screenshots/', 0777, true);
}
// Try saving video to Video table in the database
if(!$this->Video->save($video)){
throw new NotFoundException(__('Failed connecting client with "'.$targetFile.'" in the database'));
}
}
$this->Session->setFlash(__('Videos successfully uploaded'), 'default', array(), 'success');
$this->redirect($this->referer());
}
$title_for_layout = $client['Client']['name'];
$this->set(compact('title_for_layout', 'client'));
}
You can change retuned status code by use statusCode method of CakeResponse class. Something like this: $this->response->statusCode(404);
It's a little not correct to use NotFoundException to return http status code. At least you can create your own application exception
Please, check Creating your own application exceptions
You will easily to define one exceptions:
class MissingWidgetException extends CakeException {};
And after that you can use it and send http status code which you need Creating custom status codes :
throw new MissingWidgetHelperException('Its not here', 501);
501 is http status code.
Hope, this will help to find out right solution.

Cakephp calling function from view

I have the following function:
public function make_order($id = null){
if($this->request->is('post')){
if(isset($id)){
$single_product = $this->Product->find('first', array('Product.id' => $id));
$this->placeOrder($single_product);
}else{
$product_array = $_SESSION['basket'];
foreach($product_array as $product){
$this->placeOrder($product);
}
}
}
}
private function placeOrder($product){
$order_array = array();
$order_array['Order']['Product_id'] = $product['Product']['id'];
$order_array['Order']['lejer_id'] = $this->userid;
$order_array['Order']['udlejer_id'] = $product['users_id'];
$this->Order->add($order_array);
}
Now these two function are not "connected" to a view but i still need to call them from within another view
For this ive tried the following:
<?php echo $this->Html->link(__('Bestil'), array('action' => 'make_order')); ?>
However this throws an error saying it couldnt find the view matching make_order and for good reason ( i havnt created one and i do not intend to create one)
My question is how do i call and execute this function from within my view?
At the end of your make_order function, you'll either need to:
a) specify a view file to render, or
b) redirect to a different controller and / or action, that does have a view file to render.
a) would look like this:
$this->render('some_other_view_file');
b) might look like this (note: setting the flash message is optional)
$this->Session->setFlash(__('Your order was placed'));
$this->redirect(array('controller' => 'some_controller', 'action' => 'some_action'));
You can turn auto-rendering off by setting $this->autoRender = false; in your controller's action (make_order() in this case). This way you don't need a view file, and you can output whatever you need.
The problem is that nothing will be rendered on the screen. Therefore, my advice is to have your "link" simply call a controller::action via AJAX. If that's not possible in your situation, then you'll have to either render a view in your make_order() method, or redirect to an action that will render a view.

Mediawiki stopping a page from saving and redirecting back to edit page with an error message

My wiki articles contain a link to a specific dataset. I want to enforce that these links are unique (as in no one can create a new page with a link that is present in another page.) I have already written most of the code for this extension. I created a table 'unique_external_links' that stores the url as an index and the page id that the URL lives in.
Here is a part of the code I wrote:
$wgHooks['ParserFirstCallInit'][] = 'UniqueURLSetupParserFunction';
$wgHooks['LoadExtensionSchemaUpdates'][] = 'fnExternalLinksDBHook';
// Allow translation of the parser function name
$wgExtensionMessagesFiles['UniqueUrl'] = dirname( __FILE__ ) . '/UniqueUrl.i18n.php';
// Tell MediaWiki that the parser function exists.
function UniqueURLSetupParserFunction( &$parser ) {
$parser->setFunctionHook( 'example', 'UniqueURLParserFunction' );
return true;
}
function UniqueURLParserFunction( $parser, $param1 = '', $param2 = '' ) {
// The input parameters are wikitext with templates expanded.
// The output should be wikitext too.
global $wgRequest, $wgOut;
$return_url = $wgRequest->getRequestURL();
$pid = $param2;
$param1 = trim($param1);
$url_pattern = '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/';
$match = preg_match($url_pattern, $param1);
if (!$match) {
// return ERROR not a valid URL!
}
$patterns = array('/^(https?:\/\/)/', '/\/$/');
$replace = array('','');
$url = preg_replace($patterns, $replace, $param1);
if (empty($param2)) { // creating a new page
try {
$dbw = wfGetDB( DB_MASTER );
$res = $dbw->insert('unique_external_links',
array('link_url' => $url , 'page_id' => $pid));
} catch(Exception $e) {
// return ERROR page with this link already exists!
}
} else { //Trying to edit existing page
$dbr = wfGetDB( DB_SLAVE );
$res = $dbr->select(
'unique_external_links',
array( 'link_url' ),
'link_url = "' .$url.'" AND page_id = "' .$pid.'"'
);
if ($dbr->numRows($res) == 0) {
try {
$dbw = wfGetDB( DB_MASTER );
$res = $dbw->insert('unique_external_links',
array('link_url' => $url , 'page_id' => $pid));
} catch(Exception $e) {
//return ERROR Dataset Already Exists
$response = $wgRequest -> response();
$response -> header('Location: '.$return_url);
return $return_url;
}
}else {
//just editing page, not changing link, all is good
return $param1;
}
}
return $param1;
}
First off, I apologize for the sloppy code, really just slapped this together very quickly with no prior extension experience...
As you can see there are places where I have the comment //return ERROR I would like to stop media wiki from saving the page if one of those conditions are true. Instead of saving, I would like to return the user to the edit page with a message telling them there is a problem with the link they are providing.
Any ideas? I looked around a lot but couldn't find anything similar, I assume it is because I don't know really what question to ask. I am aware that there are hooks like 'ArticleSave', but i didn't know how I would use that in conjunction with a parser.
Any help would be great! Even if its telling me to completely re-do what I did because its all wrong haha.
EDIT: I fixed this problem by throwing MWExceptions at those places where I wanted to return an error. I then went to Exceptions.php and updated the MWExceptionhandler to take a different action when it sees that the exception message matches the ones I am throwing from this extension. This is hacky I admit.. But what can you do sometimes..
Writing this extension as a parser function is probably the wrong direction. If you want to reject edits, use the EditFilter hook. You may want to take a look at the SpamBlacklist extension as a model, as it also looks at links to decide whether to reject an edit.
Also, the one issue I see with your extension is that, once a page has been saved with one of these unique links, there's nothing in place to remove rows from unique_external_links even if the link (or the entire page!) is removed, making it sometimes impossible to reinsert a link that's been removed. You'll probably want to fix that.

Silverstripe: I can't handle sub-URLs of a Form object. Subsites module

Bit of a long shot but can anyone shed any light on this?
I have recently installed the subsites module to run multiple sites from a single installation and am now getting the error: "I can't handle sub-URLs of a Form object." when I try to add descriptions/titles to image gallery objects. I have removed the subsites to verify that it is this which is causing the issue. I am using 2.4
I can upload images fine, however it is when trying to save a description from the popup that the issue arises.
I have tried with the default fields too and this still gives the same error.
My code:
<?php
class Gallery extends Page {
public static $db = array(
'SummaryText'=>'Text',
'GalleryText'=>'Text'
);
static $has_many = array(
'Photos' => 'GalleryPhoto'
);
function getCMSFields() {
$fields = parent::getCMSFields();
$manager = new ImageDataObjectManager(
$this, // Controller
'Photos', // Source name
'GalleryPhoto', // Source class
'Image' // File name on DataObject
);
$manager->uploadFolder = $this->URLSegment;
$fields->addFieldToTab('Root.Content.Main', new TextField('SummaryText', 'Summary Text (Appears in the section preview)'), 'Content');
$fields->addFieldToTab('Root.Content.Main', new TextField('GalleryText', 'Gallery Text (entering anything in here will overwrite any image Titles and Descriptions)'), 'Content');
$fields->addFieldsToTab("Root.Content.Gallery", array($manager));
$fields->removeFieldFromTab('Root.Content', 'StyledText');
$fields->removeFieldFromTab('Root.Content', 'Column2');
$fields->removeFieldFromTab('Root.Content', 'Content');
return $fields;
}
}
..
<?php
class GalleryPhoto extends Photo {
public static $db = array(
'HTMLDescription'=>'HTMLText'
);
static $has_one = array(
'Gallery' => 'Gallery'
);
public function getCMSFields(){
$fields = parent::getCMSFields();
$fields->removebyname('Description');
$fields->removebyname('Title');
$fields->replaceField('HTMLDescription', new SimpleTinyMCEField('HTMLDescription'));
return $fields;
}
}
Unfortunately "I can't handle sub-URLs of a Form object." is a pretty generic error message and from my experience rather tricky to debug.
To be honest, the Subsites module isn't that great in my opinion, it works, but its not that nice and not really compatible with other modules I guess.
I could imagine that the reason for your error is because silverstripe forgets the SubsiteID inside the popup and because of that SilverStripe can no longer find the current Page you are editing (because it adds a filter WHERE SubsiteID = x to every query of Pages you make)
one place to start debuging would be hooking into Subsite::currentSubsiteID() and see if it remembers the SubsiteID when you are in the popup
also, what is the exact url that gets called when you get the error message?
I just had the same error, searched for hours. It was a problem with /framework/control/Session.php

Categories