Jump to content

Recommended Posts

Ok, I got some nice progress here. After saving it redirects (out of the modal) and displays success message. I used Adam's tip on hooking to save and using sessions. I didn't need to use load hook, because I already had pagerender hook (or maybe it is faster with loaded hook?).

I had to redirect with javascript, because there seems to be no way to redirect out of the iFrame without js or user input. If someone knows please let me know :)

Oh, and how to I get base url? I have pretty ugly hard coding there with this line:

echo("top.location.href = \"http://localhost/processwire2{$this->session->pageSaved}\";");

There is probably something like $config->urls->base or like that?

Share this post


Link to post
Share on other sites

Adam: all the better :) Downloading now and I start to implement it right a way!

With Base url I meant this: $this->config->urls->root (so I found it)

Share this post


Link to post
Share on other sites

@apeisa: I may have to finish tooltips later on and test/debug IE6-8.

Also note: it is also no-JS working. if no JS is present, it just stays fixed & extended at [0;100], but links and all data work :)

Share this post


Link to post
Share on other sites

I actually just downloaded it, now tested and very smooth work and nice looking also while extended! Also very clean and nice coding here!

Someone wants to teach me a lesson how I create settings for this module?

Share this post


Link to post
Share on other sites
(or maybe it is faster with loaded hook?).

Page::loaded isn't what you want. That is called after every page finishes loading it's initial data and is ready for API use. It doesn't mean that the page is loaded in the browser, just that it's loaded in memory on the server. This is what you would use if you wanted to examine or modify some value on every page that gets loaded before anything else accesses it. Maybe I should rename this hook to be "ready" rather than "loaded"?

Very cool!!

Share this post


Link to post
Share on other sites
Someone wants to teach me a lesson how I create settings for this module?

Let me know what settings you want to start with, and I'll paste in an example for your settings.

Share this post


Link to post
Share on other sites

Ryan, as I see it, currently this settings are needed:


  •  
  • boolean showModal: whether edit opens modal box or goes to administration
     
  • boolean initCollapsed: whether to init collapsed or not
     
  • page administration: where to go after clicking on 'administration' (optional, pages makes most sense i think)

OT: Ryan, you as moderator should be the last one to double post :D ;D there is 'modify' button

Share this post


Link to post
Share on other sites

Sorry about the double post. This is probably the only forum I've ever used, so I don't know what the etiquette is. Consider me new to this. :)

Okay to make your module configurable, modify the class definition and add "ConfigurableModule" to it:

<?php
class AdminBar extends WireData implements Module, ConfigurableModule {

To implement this interface, we need to add a module configuration function to your AdminBar class. It takes one parameter, which is an array of data (that ProcessWire provides to it). If the module has been configured before, that will contain the settings in simple key = value format. It expects you to return a value of type InputfieldWrapper(). Since that is only documented in the source right now, I wanted to get you started with an example:

<?php

static public function getModuleConfigInputfields(array $data) {

// this is a container for fields, basically like a fieldset
$fields = new InputfieldWrapper();

// since this is a static function, we can't use $this->modules, so get them from the global wire() function
$modules = wire('modules');

// set some defaults if the values aren't already present
if(!isset($data['showModal'])) $data['showModal'] = 1; // default to checked
if(!isset($data['initCollapsed'])) $data['initCollapsed'] = 0; // default to unchecked
if(!isset($data['administration'])) $data['administration'] = wire('config')->adminRootPageID; // default to admin page

// showModal field
$field = $modules->get("InputfieldCheckbox"); 
$field->name = "showModal";
$field->label = "Show modal box?"; 
        $field->value = 1; 
$field->description = "Whether edit opens modal box or goes to administration.";
$field->attr('checked', !empty($data['showModal'])); 
$fields->add($field);

// initCollapsed field
$field = $modules->get("InputfieldCheckbox"); 
$field->name = "initCollapsed";
$field->label = "Init collapsed?"; 
        $field->value = 1; 
$field->attr('checked', !empty($data['initCollapsed'])); 
$fields->add($field);

// administration field
$field = $modules->get("InputfieldPageListSelect"); 
$field->name = "administration";
$field->label = "Where to go after clicking on 'administration'";
$field->value = $data['administration'];
$fields->add($field);

return $fields;
}

Once you've put this in there, you can go configure your module in the admin by clicking "Modules" and then clicking on your AdminBar module. You should now see the fields ready to configure.

Share this post


Link to post
Share on other sites

Ryan, Adam: thanks again!

I just implemented Adam's UI and I dive into these settings next.

Few questions (not important at this point, but later):

  • Date formatting - is there global settings for this?
  • Language - best practice to offer different languages for this module?

Share this post


Link to post
Share on other sites

  • Date formatting - is there global settings for this?

There isn't. But the current practice is to use either SQL date format in places where the date need to be a fixed length and/or sortable with other dates (like in a table), and to use "January 27, 2011" or "Jan 27, 2011" format anywhere else. I believe these formats are fairly universal, though correct me if I'm wrong.

  • Language - best practice to offer different languages for this module?

This is to be determined, but on the roadmap. I think that Adam is giving this some thought, as am I, and all suggestions are welcome.

Thanks,

Ryan

Share this post


Link to post
Share on other sites

There isn't. But the current practice is to use either SQL date format in places where the date need to be a fixed length and/or sortable with other dates (like in a table), and to use "January 27, 2011" or "Jan 27, 2011" format anywhere else. I believe these formats are fairly universal, though correct me if I'm wrong.

In Finland we never use dates like "Tam 27, 2011", it is almost always "27.1.2011" and sometimes "27. tammikuuta 2011" or "Tammikuu 27. 2011". I think there is nothing universal to what comes to localisation :D

Is there any best practice to give some general constants for a whole site? Ie. in AdminBar I could try to read some site wide setting for default date formatting -> if there is none, then use module default. It wouldn't be wise to create date formatting as a module setting, wouldn't it? That would create situations where there is a lot of configuration to be made if site is using many modules (not sure though) - also every module that displays dates (or other local stuff) should provide settings for customizing localisation.

Very interested to hearing Adam's thoughts on languages.

Of course considering the "hands-on" nature of PW this isn't always an issue (easy to format things just the way you like on templates).

Share this post


Link to post
Share on other sites
In Finland we never use dates like "Tam 27, 2011", it is almost always "27.1.2011" and sometimes "27. tammikuuta 2011" or "Tammikuu 27. 2011". I think there is nothing universal to what comes to localisation Cheesy

Sorry, my bad. I learn something new every day. I'm admittedly ignorant on this matter (I live in the US, in backwoods Georgia, after all).

Given what you've mentioned, I'm adding a new $config->dateFormat to the PW2 source. What do you suggest would be a good default? Something universal doesn't exist, but what would be the closest to something universal to serve as a default?

I would like to talk more with Adam and you about more localization options for PW2 (maybe we can start a new thread soon).

Share this post


Link to post
Share on other sites

Ryan: no worries. Localization is important thing and it would be nice to have clean and simple solution to that also.

Question: module settings worked nicely, but how I read those values? :)

Share this post


Link to post
Share on other sites

It's getting near the end of the work day and I'm forgetting crucial details. :) To read this values, they will be automatically set in your AdminBar instance. So anywhere in that class, you should be able to just reference it like: $this->showModal, and so on. If the value is not set or doesn't exist, it will just be null. If that's the case, then you should use some default value, because it means the module has never been configured. Or you could set them up in a __construct method. The constructor is of course executed before PW2 sets any values to the module. Whereas the init() method is called after PW2 sets values to the module. So you might setup your defaults like this:

public function __construct() {
    $this->showModal = true; 
}

No need to define a separate showModal var in your class, because WireData is already handling that for you behind the scenes...

Share this post


Link to post
Share on other sites

Hmm... $this->showModal returns 1, no matter if it is checked or not?

Share this post


Link to post
Share on other sites

You are right. I'm figuring it out now... you the first person to develop a module, and this is only the 3rd or 4th configurable module ever, so I'm getting up to speed myself. :) I'll reply shortly.

Share this post


Link to post
Share on other sites

Looks like you've found a bug! I will work to get this fixed for tomorrow. Sorry for the inconvenience. Turns out this is the first configurable module of it's type, so it's not come up before. But I think it will be an easy fix.

Share this post


Link to post
Share on other sites

No worries Ryan. This have been so much fun so far and big thanks for all your help! Dunno what my wife thinks about my late night coding after few weeks... :)

There is now first version to try out for you guys! No new features yet (only page editing and link to admin & logout), but this has super nice UI by adamkiss.

http://www.monoliitti.com/misc/AdminBar.zip

Remember: requires latest version from master branch. Installation is super simple: extract files from zip to: /site/modules/AdminBar/ and then through admin -> modules -> install (easy to find, since it will be first module on the list, good name ;))

There are some settings on module admin, but they aren't working yet (as you can read from above).

Share this post


Link to post
Share on other sites

Thanks, I can't wait to check this out! We are headed to dinner, so I'm going to check when I get back. If you are still around and want to try it, here is a fixed /wire/core/Modules.php that corrects the bug (attached). I am going to go over it in more detail tomorrow. Also, I may have told you the wrong thing on setting the defaults in the getModuleConfigInputfields... you may be able to remove that part at the top. I'll double check on the proper syntax either tonight or tomorrow, and then get started on the module documentation! :)

Modules_php.zip

Share this post


Link to post
Share on other sites

Hello boys,

nice to see this thing rolling' :)

On-topic: I don't know if I'll have time to check the module out right now, but I would love to work on it, so apeisa, please, create github account for it [or I can, if you wish], so we can synchronize better. If you don't have account / haven't work with git before, try some nice GUI for it and just dive in as I did – i still no almost nothing about it and love it already.

Off-topic: I'm currently working on new UX / UI design for PW administration – it's quite well thought out, brings some new stuff, some 'nice-somebody-thought-of-this' moments and nice design too, however, I have so much work [some of it will be brought back to PW though!] that I can't do everything at once!

From the things I would like to introduce [and some already mentioned to ryan]:

  • Text & description of field configurable in template, so you can re-use fields with better description for clients
  • a little better managment of content
  • multilinguality – it's almost finished (how it will work), I have to implement it into design (not finished) and talk to ryan how to do it
  • 'add another' – I would love to have a nice button after you save a page to have quick option of adding another
  • partials/strings system to manage little pieces of text needed anywhere in templates (+1 on multilinguality and convenience)

There is much more in little and big stuff, but basically I'm trying to translate the great PHP workflow into UX/UI.

Share this post


Link to post
Share on other sites

Thanks, I can't wait to check this out! We are headed to dinner, so I'm going to check when I get back. If you are still around and want to try it, here is a fixed /wire/core/Modules.php that corrects the bug (attached).

Thanks Ryan. I go to bed now, but I will continue on weekend.

I don't know if I'll have time to check the module out right now, but I would love to work on it, so apeisa, please, create github account for it [or I can, if you wish], so we can synchronize better. If you don't have account / haven't work with git before, try some nice GUI for it and just dive in as I did – i still no almost nothing about it and love it already.

I have used SVN much more than Git. I have tried Git few times, always liked it but never had enough reason to start using it in real project. But maybe now: https://github.com/apeisa/AdminBar

Share this post


Link to post
Share on other sites

Not working for me...I've installed it but i cannot see the bar...

Thanks for installing and sorry to hear about problems. Do you have installed latest branch from here: https://github.com/ryancramerdesign/ProcessWire/archives/master

If you do, can you paste source code of your page (some front end page and when admin is logged in)?

Share this post


Link to post
Share on other sites

Me neither – I've installed it, but it doesn't show anything. The reason, however, is in this line:

 $event->return = str_ireplace('</body>', $out, $event->return);

$event->return is empty in my case.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Gadgetto
      Status update links (inside this thread) for SnipWire development will be always posted here:
      2019-08-08
      2019-06-15
      2019-06-02
      2019-05-25
      If you are interested, you can test the current state of development:
      https://github.com/gadgetto/SnipWire
      Please note that the software is not yet intended for use in a production system (alpha version).
      If you like, you can also submit feature requests and suggestions for improvement. I also accept pull requests.
      ---- INITIAL POST FROM 2019-05-25 ----
      I wanted to let you know that I am currently working on a new ProcessWire module that fully integrates the Snipcart Shopping Cart System into ProcessWire. (this is a customer project, so I had to postpone the development of my other module GroupMailer).
      The new module SnipWire offers full integration of the Snipcart Shopping Cart System into ProcessWire.
      Here are some highlights:
      simple setup with (optional) pre-installed templates, product fields, sample products (quasi a complete shop system to get started immediately) store dashboard with all data from the snipcart system (no change to the snipcart dashboard itself required) Integrated REST API for controlling and querying snipcart data webhooks to trigger events from Snipcart (new order, new customer, etc.) multi currency support self-defined/configurable tax rates etc. Development is already well advanced and I plan to release the module in the next 2-3 months.
      I'm not sure yet if this will be a "Pro" module or if it will be made available for free.
      I would be grateful for suggestions and hints!
      (please have a look at the screenshots to get an idea what I'm talking about)
       




    • By Mike Rockett
      Jumplinks for ProcessWire
      Release: 1.5.54
      Composer: rockett/jumplinks
      Jumplinks is an enhanced version of the original ProcessRedirects by Antti Peisa.
      The Process module manages your permanent and temporary redirects (we'll call these "jumplinks" from now on, unless in reference to redirects from another module), useful for when you're migrating over to ProcessWire from another system/platform. Each jumplink supports wildcards, shortening the time needed to create them.
      Unlike similar modules for other platforms, wildcards in Jumplinks are much easier to work with, as Regular Expressions are not fully exposed. Instead, parameters wrapped in curly braces are used - these are described in the documentation.
      Under Development: 2.0, to be powered by FastRoute
      As of version 1.5.0, Jumplinks requires at least ProcessWire 2.6.1 to run.
      View on GitLab
      Download via the Modules Directory
      Read the docs
      Features
      The most prominent features include:
      Basic jumplinks (from one fixed route to another) Parameter-based wildcards with "Smart" equivalents Mapping Collections (for converting ID-based routes to their named-equivalents without the need to create multiple jumplinks) Destination Selectors (for finding and redirecting to pages containing legacy location information) Timed Activation (activate and/or deactivate jumplinks at specific times) 404-Monitor (for creating jumplinks based on 404 hits) Additionally, the following features may come in handy:
      Stale jumplink management Legacy domain support for slow migrations An importer (from CSV or ProcessRedirects) Feedback & Feature Requests
      I’d love to know what you think of this module. Please provide some feedback on the module as a whole, or even regarding smaller things that make it whole. Also, please feel free to submit feature requests and their use-cases.
      Note: Features requested so far have been added to the to-do list, and will be added to 2.0, and not the current dev/master branches.
      Open Source

      Jumplinks is an open-source project, and is free to use. In fact, Jumplinks will always be open-source, and will always remain free to use. Forever. If you would like to support the development of Jumplinks, please consider making a small donation via PayPal.
      Enjoy! :)
    • By nbcommunication
      I've spent the last while experimenting with srcset implementation - and PageimageSrcset is the result:
      PageimageSrcset
      Provides configurable srcset and sizes properties/methods for Pageimage.
      Overview
      The main purpose of this module is to make srcset implementation as simple as possible in your template code. It does not handle images rendered in CKEditor or similar fields.
      For an introduction to srcset and sizes, please read this Mozilla article about responsive images.
      Pageimage::srcset()
      // The property, which uses the set rules in the module configuration $srcset = $image->srcset; // A method call, using a set rules string // Delimiting with a newline (\n) would also work, but not as readable $srcset = $image->srcset("320, 480, 640x480 768w, 1240, 2048 2x"); // The same as above but using an indexed/sequential array $srcset = $image->srcset([ "320", "480", "640x480 768w", "1240", "2048 2x", ]); // The same as above but using an associative array // No rule checking is performed $srcset = $image->srcset([ "320w" => [320], "480w" => [480], "768w" => [640, 480], "1240w" => [1240], "2x" => [2048], ]); // Use the default set rules with portrait images generated for mobile/tablet devices $srcset = $image->srcset(true); // Return the srcset using all arguments $srcset = $image->srcset("320, 480, 640x480 768w, 1240, 2048 2x", [ "portrait" => "320, 640", ]); // The set rules above are a demonstration, not a recommendation! Image variations are only created for set rules which require a smaller image than the Pageimage itself. On large sites this may still result in a lot of images being generated. If you have limited storage, please use this module wisely.
      Portrait Mode
      In many situations, the ratio of the image does not need to change at different screen sizes. However, images that cover the entire viewport are an exception to this and are often the ones that benefit most from srcset implementation.
      The main problem with cover images is that they need to display landscape on desktop devices and portrait when this orientation is used on mobile and tablet devices.
      You can automatically generate portrait images by enabling portrait mode. It is recommended that you use this in combination with Pageimage::focus() so that the portrait variations retain the correct subject.
      The generated variations are HiDPI/Retina versions. Their height is determined by the portrait ratio (e.g. 9:16). Variations are always generated, regardless of whether the original image is smaller. Upscaling is disabled though, so you may find that some variations are actually smaller than they say they are in their filename.
      The sizes attribute should be used when portrait mode is enabled. Pageimage::sizes will return (orientation: portrait) and (max-width: {maxWidth}px) 50vw by default, which handles the use of these images for retina devices. The maximum width used in this rule is the largest set width.
      Pageimage::sizes()
      There is no option to configure default sizes because in most cases 100vw is all you need, and you do not need to output this anyway as it is inferred when using the srcset attribute. You can use the method for custom sizes though:
      // The property $sizes = $image->sizes; // Returns 100vw in most cases // Returns '(orientation: portrait) and (max-width: {maxWidth}px)50vw' if portrait mode enabled // A method call, using a mixture of integer widths and media query rules // Integer widths are treated as a min-width media query rule $sizes = $image->sizes([ 480 => 50, "(orientation: portrait) and (max-width: 640px)" => 100, 960 => 25, ]); // (min-width: 480px) 50vw, (orientation: portrait) and (max-width: 640px) 100vw, (min-width: 960px) 25vw // Determine widths by UIkit 'child-width' classes $sizes = $image->sizes([ "uk-child-width-1-2@s", "uk-child-width-1-3@l", ]); // (min-width: 640px) 50vw, (min-width: 1200px) 33.33vw // Determine widths by UIkit 'width' classes $sizes = $image->sizes([ "uk-width-1-2@m", "uk-width-1-3@xl", ]); // (min-width: 960px) 50vw, (min-width: 1600px) 33.33vw // Return the portrait size rule $sizes = $image->sizes(true); // (orientation: portrait) and (max-width: {maxWidth}px) 50vw // The arguments above are a demonstration, not a recommendation! Pageimage::render()
      This module extends the options available to this method with:
      srcset: When the module is installed, this will always be added, unless set to false. Any values in the formats described above can be passed. sizes: Only used if specified. Any values in the formats described above can be passed. uk-img: If passed, as either true or as a valid uk-img value, then this attribute will be added. The srcset attribute will also become data-srcset. Please refer to the API Reference for more information about this method.
      // Render an image using the default set rules echo $image->render(); // <img src='image.jpg' alt='' srcset='{default set rules}'> // Render an image using custom set rules echo $image->render(["srcset" => "480, 1240x640"]); // <img src='image.jpg' alt='' srcset='image.480x0-srcset.jpg 480w, image.1240x640-srcset.jpg 1240w'> // Render an image using custom set rules and sizes // Also use the `markup` argument echo $image->render("<img class='image' src='{url}' alt='Image'>", [ "srcset" => "480, 1240", "sizes" => [1240 => 50], ]); // <img class='image' src='image.jpg' alt='Image' srcset='image.480x0-srcset.jpg 480w, image.1240x640-srcset.jpg 1240w' sizes='(min-width: 1240px) 50vw'> // Render an image using custom set rules and sizes // Enable uk-img echo $image->render([ "srcset" => "480, 1240", "sizes" => ["uk-child-width-1-2@m"], "uk-img" => true, ]); // <img src='image.jpg' alt='' data-uk-img data-srcset='image.480x0-srcset.jpg 480w, image.1240x640-srcset.jpg 1240w' sizes='(min-width: 960px) 50vw'> // Render an image using portrait mode // Default rule sets used: 320, 640, 768, 1024, 1366, 1600 // Portrait widths used: 320, 640, 768 // Original image is 1000px wide // Not possible to use portrait mode and custom sets or portrait widths in render() // Sizes attribute automatically added echo $image->render(["srcset" => true]); // <img src='image.jpg' alt='' srcset='image.320x569-srcset-hidpi.jpg 320w, image.640x1138-srcset-hidpi.jpg 640w, image.768x1365-srcset-hidpi.jpg 768w, image.jpg 1024w' sizes='(orientation: portrait) and (max-width: 768px) 50vw'> Configuration
      To configure this module, go to Modules > Configure > PageimageSrcset.
      Set Rules
      These are the default set rules that will be used when none are specified, e.g. when calling the property: $image->srcset.
      Each set rule should be entered on a new line, in the format {width}x{height} {inherentwidth}w|{resolution}x.
      Not all arguments are required - you will probably find that specifying the width is sufficient for most cases. Here's a few examples of valid set rules and the sets they generate:
      Set Rule Set Generated Arguments Used 320 image.320x0-srcset.jpg 320w {width} 480x540 image.480x540-srcset.jpg 480w {width}x{height} 640x480 768w image.640x480-srcset.jpg 768w {width}x{height} {inherentwidth}w 2048 2x image.2048x0-srcset.jpg 2x {width} {resolution}x How you configure your rules is dependent on the needs of the site you are developing; there are no prescriptive rules that will meet the needs of most situations. This article gives a good overview of some of the things to consider.
      When you save your rules, a preview of the sets generated and an equivalent method call will be displayed to the right. Invalid rules will not be used, and you will be notified of this.
      Portrait Mode
      Set Widths
      A comma limited list of widths to create HiDPI/Retina portrait variations for.
      Crop Ratio
      The portrait ratio that should be used to crop the image. The default of 9:16 should be fine for most circumstances as this is the standard portrait ratio of most devices. However, you can specify something different if you want. If you add a landscape ratio, it will be switched to portrait when used.
      Any crops in the set rules ({width}x{height}) are ignored for portrait mode variations as this ratio is used instead.
      UIkit Widths
      If your website theme uses UIkit, you can pass an array of UIkit width classes to Pageimage::sizes to be converted to sizes. The values stored here are used to do this. If you have customised the breakpoints on your theme, you should also customise them here.
      Please note that only 1- widths are evaluated by Pageimage::sizes, e.g. uk-width-2-3 will not work.
      Remove Variations
      If checked, the image variations generated by this module are cleared on Submit. On large sites, this may take a while. It makes sense to run this after you have made changes to the set rules.
      Image Suffix
      You will see this field when Remove Variations is checked. The value is appended to the name of the images generated by this module and is used to identify variations. You should not encounter any issues with the default suffix, but if you find that it conflicts with any other functionality on your site, you can set a custom suffix instead.
      Debug Mode
      When this is enabled, a range of information is logged to pageimage-srcset.
      PageimageSrcsetDebug.js is also added to the <head> of your HTML pages. This will console.log a range of information about the images and nodes using srcset on your page after a window.onresize event is triggered. This can assist you in debugging your implementation.
      The browser will always use the highest resolution image it has loaded or has cached. You may need to disable browser caching to determine whether your set rules are working, and it makes sense to work from a small screen size and up. If you do it the other way, the browser is going to continue to use the higher resolution image it loaded first.
      UIkit Features
      This module implements some additional features that are tailored towards UIkit being used as the front-end theme framework, but this is not required to use the module.
      Installation
      Download the zip file at Github or clone the repo into your site/modules directory. If you downloaded the zip file, extract it in your sites/modules directory. In your admin, go to Modules > Refresh, then Modules > New, then click on the Install button for this module. ProcessWire >= 3.0.123 is required to use this module.
    • By nbcommunication
      Wondering how to get that A+ rating on Mozilla Observatory? Now you can with ⭐⭐⭐MarkupContentSecurityPolicy⭐⭐⭐
      Of course, MarkupContentSecurityPolicy does not guarantee an A+ rating, but it does help you implement a Content Security Policy for your ProcessWire website.
      Markup Content Security Policy
      Configure and implement a Content Security Policy for all front-end HTML pages.
      This module should only be used in production once it has been fully tested in development. Implementing a Content Security Policy on a site without testing will almost certainly break something!
      Overview
      Website Security Auditing Tools such as Mozilla Observatory will only return a high score if a Content Security Policy is implemented. It is therefore desirable to implement one.
      A common way of adding the Content-Security-Policy header would be to add it to the .htaccess file in the site's root directory. However, this means the policy would also cover the ProcessWire admin, and this limits the level of security policy you can add.
      The solution is to use the <meta> element to configure a policy, for example: <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">. MarkupContentSecurityPolicy places this element with your configured policy at the beginning of the <head> element on each HTML page of your site.
      There are some limitations to using the <meta> element:
      Not all directives are allowed. These include frame-ancestors, report-uri, and sandbox. The Content-Security-Policy-Report-Only header is not supported, so is not available for use by this module. Configuration
      To configure this module, go to Modules > Configure > MarkupContentSecurityPolicy.
      Directives
      The most commonly used directives are listed, with a field for each. The placeholder values given are examples, not suggestions, but they may provide a useful starting point.
      You will almost certainly need to use 'unsafe-inline' in the style-src directive as this is required by some modules (e.g. TextformatterVideoEmbed) or frameworks such as UIkit.
      Should you wish to add any other directives not listed, you can do so by adding them in Any other directives.
      Please refer to these links for more information on how to configure your policy:
      https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy https://scotthelme.co.uk/content-security-policy-an-introduction/ https://developers.google.com/web/fundamentals/security/csp/ Violation Reporting
      Because the report-uri directive is not available, when Violation Reporting is enabled a script is added to the <head>which listens for a SecurityPolicyViolationEvent. This script is based on https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicyViolationEvent and POSTs the generated report to ?csp-violations=1. The module then logs the violation report to csp-violations.
      Unfortunately, most of the violations that are reported are false positives, and not actual attempts to violate the policy. These are most likely from browser extensions and are not easy to determine and filter.
      For this reason, there is no option for the report to be emailed when a policy is violated. Instead, you can specify an endpoint for the report to be sent to. This allows you to handle additional reporting in a way that meets your needs. For example, you may want to log all reports in a central location and send out an email once a day to an administrator notifying them of all sites with violations since the last email.
      Retrieving the Report
      To retrieve the report at your endpoint, the following can be used:
      $report = file_get_contents("php://input"); if(!empty($report)) { $report = json_decode($report, 1); if(isset($report) && is_array($report) && isset($report["documentURI"])) { // Do something } } Debug Mode
      When this is enabled, a range of information is logged to markup-content-security-policy. This is probably most useful when debugging a reporting endpoint.
      Additional .htaccess Rules
      To get an A+ score on Mozilla Observatory, besides using HTTPS and enabling the HSTS header, you can also place the following prior to ProcessWire's htaccess directives:
      Header set Content-Security-Policy "frame-ancestors 'self'" Header set Referrer-Policy "no-referrer-when-downgrade" Installation
      Download the zip file at Github or clone the repo into your site/modules directory. If you downloaded the zip file, extract it in your sites/modules directory. In your admin, go to Modules > Refresh, then Modules > New, then click on the Install button for this module. ProcessWire >= 3.0.123 is required to use this module.
    • By Robin S
      First a note about my other modules...
      I have three existing modules that are similar in that they allow restrictions to be placed on repeating inputfields: Limit Repeater, Limit PageTable, Limit Table
      Restrict Repeater Matrix takes a different approach to the module configuration from those other modules. The module settings for Restrict Repeater Matrix are applied in the field settings rather in a module config screen. I think this new approach is better, but it means that it isn't practical to create different settings for different roles via the admin interface. Instead the module has a hookable method, allowing roles to be targeted and other advanced usages to be achieved via a hook. The result is that the module is more flexible.
      I intend to transition my other modules to the same approach over the coming weeks, but because this will result in breaking changes I will be releasing the updated modules under new names ("Restrict Repeater", etc) to avoid users upgrading via the Upgrades module without full awareness of the changes. The old modules will be marked as deprecated.
      Restrict Repeater Matrix
      A module for ProcessWire CMS/CMF. Allows restrictions and limits to be placed on Repeater Matrix fields. Requires ProcessWire >= v3.0.0 and FieldtypeRepeaterMatrix >= v0.0.5.
      For any matrix type in a Repeater Matrix field you have the option to:
      Disable settings for items (cannot change matrix type) Prevent drag-sorting of items Prevent cloning of items Prevent toggling of the published state of items Prevent trashing of items Limit the number of items that may be added to the inputfield. When the limit is reached the "Add new" button for the matrix type will be removed and the matrix type will not be available for selection in the "Type" dropdown of other matrix items. Please note that restrictions and limits are applied with CSS/JS so should not be considered tamper-proof.
      Usage
      Install the Restrict Repeater Matrix module.
      For each matrix type created in the Repeater Matrix field settings, a "Restrictions" fieldset is added at the bottom of the matrix type settings:

      For newly added matrix types, the settings must be saved first in order for the Restrictions fieldset to appear. Set restrictions for each matrix type as needed. A limit of zero means that no items of that matrix type may be added to the inputfield.
      Setting restrictions via a hook
      Besides setting restrictions in the field settings, you can also apply or modify restrictions by hookingRestrictRepeaterMatrix::checkRestrictions. This allows for more focused restrictions, for example, applying restrictions depending on the template of the page being edited or depending on the role of the user.
      The checkRestrictions() method receives the following arguments:
      $field This Repeater Matrix field $inputfield This Repeater Matrix inputfield $matrix_types An array of matrix types for this field. Each key is the matrix type name and the value is the matrix type integer. $page The page that is open in ProcessPageEdit The method returns a multi-dimensional array of matrix types and restrictions for each of those types. An example of a returned array:

      Example hooks
      Prevent the matrix type "images_block" from being added to "my_matrix_field" in a page with the "basic-page" template:
      $wire->addHookAfter('RestrictRepeaterMatrix::checkRestrictions', function(HookEvent $event) { $field = $event->arguments('field'); $page = $event->arguments('page'); $type_restrictions = $event->return; if($field->name === 'my_matrix_field' && $page->template->name === 'basic-page') { $type_restrictions['images_block']['limit'] = 0; } $event->return = $type_restrictions; }); Prevent non-superusers from trashing any Repeater Matrix items in "my_matrix_field":
      $wire->addHookAfter('RestrictRepeaterMatrix::checkRestrictions', function(HookEvent $event) { $field = $event->arguments('field'); $type_restrictions = $event->return; if($field->name === 'my_matrix_field' && !$this->user->isSuperuser()) { foreach($type_restrictions as $key => $value) { $type_restrictions[$key]['notrash'] = true; } } $event->return = $type_restrictions; }); http://modules.processwire.com/modules/restrict-repeater-matrix/
      https://github.com/Toutouwai/RestrictRepeaterMatrix
×
×
  • Create New...