Jump to content

Hook before a 404 exception


Hari KT
 Share

Recommended Posts

Hi, 

Thank you for the wonderful CMF. This is my first question to the PW community as I started with it.

I am in the process of trying to create a module. The basic need is I want to change the content of the 404 page, if the route is something special.

Eg : say the request is for http://processwire.localhost/hello and if I know the path doesn't exists I want to do something special.

public function init()
{
    $this->addHookBefore('ProcessController::execute', $this, 'someMethod'); 
}
    
public function someMethod($event)
{
    // also how do I access the $_SERVER variables from processwire point of view
}

 Also how do I access the $_SERVER variables from a PW context. Something like $pages->get('SERVER').


  • Like 1
Link to comment
Share on other sites

Thank you. I found the correct hook, that solves the first part. Like

public function init()
{
    $this->addHookAfter('ProcessPageView::pageNotFound', $this, 'someMethod');
}

Now looking for the second part . About the $_SERVER usage.

Thank you.

Link to comment
Share on other sites

Welcome Hari!

Not sure if this is what you want, but you can access the server variables like in normal PHP. 

$request_method = $_SERVER['REQUEST_METHOD'];
echo $request_method;

Or to go through all of the server variables

$server_vars = $_SERVER;

foreach ($server_vars as $var) {
	echo $var; 
}

Otherwise maybe look at some of the options available via the "system configuration" method $config-> 

http://cheatsheet.processwire.com/

Link to comment
Share on other sites

Thank you @Michael.

No I wasn't looking how I can iterate through the server variables.  According to what I learned using global values inside the class seems not a good way, so was wondering whether the post values, what sort of REQUEST_METHOD is already called is available via some objects which is called in bootstrap.

You can have a test to the code below to see what I mean

var_dump($_SERVER);
// see how the o/p differs
$_SERVER = array();
var_dump($_SERVER);

That becomes a hell to all if someone set like this in a module.

Link to comment
Share on other sites

If I understand your needs correctly, I don't think you need hooks. The 404 page has a separate template, so you could move your logic there:

$uri = $_SERVER["REQUEST_URI"];
if ($uri == 'hello') {
  echo 'hello';
} else {
  echo 'not welcome';
}
Link to comment
Share on other sites

Thanks @Wanze .

So to make it clear, what I am doing is moving the index.php to a seprate folder.

Say

site
wire
    web
        index.php

So the problem we are going to face is none of the images, js, css cannot be accessed.

A good example is call for http://processwire.localhost/site/templates/styles/main.css will result in 404 , for the only entry point is index.php . I can create symbolic links, but I thought of making a module ;) . So my goal is to create a module which can check whether the request is for a certain type ( css, image, js ) and return the content according to the type. (I have already created the same.)

About the usage of $_SERVER seems a bad idea to me as I mentioned earlier. If some ( 3rd party module ) replaces the content, hard to deal.

For those who don't know me, I have a bit of background in aura project ( and some other open-source projects ) and you can see the how the $_SERVER is accessed. Once you set, even if someone resets the superglobals the object value never changes.

Let me show you an example from aura v2

<?php
use Aura\Web\WebFactory;

$web_factory = new WebFactory($GLOBALS);
$request = $web_factory->newRequest();
echo " Request uri is " . $request->server->get('REQUEST_URI');
$_SERVER['REQUEST_URI'] = 'oye I am changing';
echo $_SERVER['REQUEST_URI'] . PHP_EOL;
echo $request_uri = $request->server->get('REQUEST_URI', '');

If you have tried the above example you will understand what I mean. ( I am not promoting aura here, my goal is to make PW things better and secure. I am also going to search for the thread composer and how it is utilized )

If anyone is interested have a look into the links below

https://github.com/auraphp/Aura.Web/blob/develop-2/README-REQUEST.md#superglobals

https://github.com/auraphp/Aura.Web/blob/develop-2/src/Request.php#L162

https://github.com/auraphp/Aura.Web/blob/develop-2/src/Request/Globals.php#L99

https://github.com/auraphp/Aura.Web/blob/develop-2/src/Request/Values.php#L36

Thank you.

Link to comment
Share on other sites

  • 4 years later...

Hello I'm having trouble figuring out how to use the code above to run a hook before an error 404 exception, for when a template file is run with due to $config->prependTemplateFile before any template file runs.

<?php
//wire()->addHookBefore('Page::path', function($event) { @note: this or below, both work.
$pages->addHookBefore('ProcessPageView::pageNotFound', function($event) {
  echo "<h1>hello</h1>";
  $page = $event->object;
  if($page->template == 'LinkShortener') {// template used by 'post-a'
    $dapath = str_replace("/", "", $_SERVER[REQUEST_URI]);
      $redirectTo = $pages->find("template=LinkShortener,name=$dapath")->first();
      header("Location: $redirectTo->full_path");
  }
});

The text hello does not display for an error 404.

What is going on?

Link to comment
Share on other sites

  • 3 weeks later...

@desbest

I don't think the above will work, because most of the time when a 404 occurs, that's because the $page could not be found. So there is no $page available. The only place where you could add such a hook would be in /site/init.php, because usually a 404 would have been thrown already by the time your prependTemplateFile gets called—meaning it won't get called, except for doing the rendering of the actual 404 page. 

Where you might be able to get it to work is for your own manually thrown 404s in your template files. i.e. throw Wire404Exception(); or for pages that exist, but the user didn't have access to view them due to access control settings. 

Your $page = $event->object; is not a Page object, but rather a ProcessPageView object. If there was a $page available when the 404 was triggered, it would be in $event->arguments(0); That can either be a Page object, a NullPage, or null. 

Your $dapath variable probably doesn't have what you need, and needs to be sanitized as well. Try using $input->url() instead. Note that it's going to have slashes in it, since it is a URL, which means it's not going to work for your selector where you've got "name=$dapath". You'll want to extract out the first name in the URL and use that, i.e. 

$parts = explode('/', trim($input->url(), '/'));
$name = array_shift($parts); 
$name = $sanitizer->pageName($name);
// now you can use $name in a selector

If you needed to, it should be fine to substitute the $input->url()  with $_SERVER['REQUEST_URI'] since it is being sanitized with $sanitizer->pageName(). Though I think the values will likely be identical, so I'd prefer the $input->url(). 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...