Hari KT

Hook before a 404 exception

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

Share this post


Link to post
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.

Share this post


Link to post
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/

Share this post


Link to post
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.

Share this post


Link to post
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';
}

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

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?

Share this post


Link to post
Share on other sites

@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(). 

Share this post


Link to post
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

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By anderson
      Hi all,
      I'm a new to website building. Learned some CRASH course of js,jquery,php. Then I found CMS. Still learning around forum, youtube....
      Anyway, please help me with some beginer questions:
      1, About template - please correct me if I understand wrong : every page should be (or recommended) built on a template. So if in total I'll have 10 pages, 2 of them have same layout, I'll need 9 templates.  And, what fields a page includes, is not defined in page, but defined in the template that page uses. 
      2,  Where to see what modules I've installed? is it in "Modules - Site"? 
      3, I installed "PageTable Extended", then what?  As in a youtube tutorial, it should appear in Setup tab, but it doesn't.  What's in there: templates,fields,logs,comments. (I installed "Uikit 3 site_blog profile".)
      4, I did a search in Processwire website for the famous "repeater matrix" module, and can not find it, there's a Repeater, as well as a Matrix. Is it not a module?
      5, I watched this youtube tuts: https://www.youtube.com/watch?v=IHqnLQy9R1A
      Anybody familiar with this tuts please help: 
      After he analysed a target webpage layout he wanted to mimic, he created some fields, some template, then based on those he created a page and input some "content" in there, then clicked "view", it's just some text. So, here comes my question, he copied a folder "assets" (subfolders are: css,fonts,js,img) over, then the page have the appearance/layout he wanted to mimic. Where does that assets folder come from?
      Appreciate any help.
    • By mtwebit
      I've created a set of modules for importing (manipulating and displaying) data from external resources. A key requirement was to handle large (100k+) number of pages easily.
      Main features
      import data from CSV and XML sources in the background (using Tasker) purge, update or overwrite existing pages using selectors user configurable input <-> field mappings on-the-fly data conversion and composition (e.g. joining CSV columns into a single field) download external resources (files, images) during import handle page references by any (even numeric) fields How it works
      You can upload CSV or XML files to DataSet pages and specify import rules in their description.
      The module imports the content of the file and creates/updates child pages automatically.
      How to use it
      Create a DataSet page that stores the source file. The file's description field specifies how the import should be done:
      After saving the DataSet page an import button should appear below the file description.

      When you start the import the DataSet module creates a task (executed by Tasker) that will import the data in the background.
      You can monitor its execution and check its logs for errors.

      See the module's wiki for more details.
      The module was already used in three projects to import and handle large XML and CSV datasets. It has some rough edges and I'm sure it needs improvement so comments are welcome.
    • By tarkvsg
      Hi!
      tell me, pls, how to execute this equality (from ready.php)
      $wire->addHookAfter('InputfieldPage::getSelectablePages', function($event) {     if($event->object->hasField == 'FIELDNAME')     {         .....     } } - $hasField The Field object associated with this Inputfield (from definition parent class for InputfieldPage)
      the left side equation is the object entity, and the right side - the string 
      How it is?
    • By dreerr
      TemplateEnginePug (formally TemplateEngineJade)
       
      This module adds Pug templates to the TemplateEngineFactory. It uses https://github.com/pug-php/pug to render templates.
      doctype html html(lang='en') head meta(http-equiv='content-type', content='text/html; charset=utf-8') title= $page->title link(rel='stylesheet', type='text/css', href=$config->urls->templates . 'styles/main.css') body include header.pug h1= $page->title if $page->editable() p: a(href=$page->editURL) Edit Project on GitHub: github.com/dreerr/TemplateEnginePug
      Project in modules directory: modules.processwire.com/modules/template-engine-pug/
       
      For common problems/features/questions about the Factory, use the TemplateEngineFactory thread.
       
    • By Robin S
      Pages At Bottom
      Keeps selected pages at the bottom of their siblings.
      A "bottom page" will stay at the bottom even if it is drag-sorted to a different location or another page is drag-sorted below it (after Page List is refreshed the bottom page will still be at the bottom).
      Newly added sibling pages will not appear below a bottom page.
      The module also prevents the API methods $pages->sort() and $pages->insertAfter() from affecting the position of bottom pages.
      Note: the module only works when the sort setting for children on the parent page/template is "Manual drag-n-drop".
      Why?
      Because you want some pages to always be at the bottom of their siblings for one reason or another. And someone requested it. 🙂
      Usage
      Install the Pages At Bottom module.
      Select one or more pages to keep at the bottom of their siblings. If you select more than one bottom page per parent then their sort order in the page list will be the same as the sort order in the module config.

       
      https://github.com/Toutouwai/PagesAtBottom
      https://modules.processwire.com/modules/pages-at-bottom/