Jump to content

Recommended Posts

Martin: Thanks!

Ryan: what would be best approach, if I would like to create sitemap for AdminBar? Or any other "customized" page?

My initial plan is this:

Check if there is template called "AbminBarPage"

->if not, create template (title & body fields)

Check if there is page /adminbar/sitemap/

-> if not, create page

-> put needed code into body

It would be probably good idea to actually produce each view as AdminBarPage, then this module wouldn't break on changes on admin templates (or if some site has custom admin etc).

Share this post


Link to post
Share on other sites

These are just thoughts, but my first idea was that it would provide full site map (well, maybe not full if there is very deep levels..) in open state, show clearly where the current page is. Then of course links to move to other pages. Probably no need to edit, move etc (since these are easily done through real admin).

In short: to provide quick look over the whole site and where the current page is.

Share this post


Link to post
Share on other sites

I made some progress here.

Most important thing first: PW source is very well documented and it just makes sense! After half an hour I started guessing method names and usually got them always right :P

I have now version working, where I create adminbar-template (with fieldgroup & title field), adminbar-templatefile & and finally create the page. I'm not sure if this is right way to go, but I see huge benefits this way:

  • Template-files that adminbar uses goes to site/templates/adminbar folder, so they are easily customized per site basis
  • We could have ie. "Information for content editors" field that is showed everyone who is editing content etc. Maybe more settings per different view etc?
  • This gives full control to create modal views as I like them to be - easier to develop than hooking. Of course there we have to be careful not to re-invent the wheel and keeping UI consistent with other aspects of PW

Only negative things I can think of now are

  • More templates, more pages, more templatefiles...
  • But probably just a good thing, if those can be visible only to superadmins (I don't know yet how UA works)

This was quick hack, but if Ryan confirms that this is not worst way of developing AdminBar further, I'll probably go forward and implement this at least on the views that current admin doesn't provide (I know correctly this means only the "full sitemap view" so far).

Share this post


Link to post
Share on other sites

re: content editors: just a note: as Ryan previously stated, everything about Users [user roles, intercommunication, data information, versioning] is mostly in very crude, unpolished state – because Pages and overall API had hightest priority. Therefore, for few things there are no solutions currently [who's editing what, etc]

Share this post


Link to post
Share on other sites

I have it working nicely... almost :) One little problem that I cannot figure out. For some reason this code gives me HTTP-error 500, but only once (first time it runs). Probably some silly error (I create stuff on wrong order or something similar..? Or save() doesn't return the object I assume it returns? Ryan, any ideas what I am doing wrong?

I have also attached full module if anyone is interested to try. There is one new feature and it is quick collapse-enabled sitemap to show where the current page is located and to quickly move around your site.

I know this code could be cleaned up a lot, but be gentle - I am just learning this stuff :)

private function _createAdminBarPages() {
	$abName = "adminbar";
	$abFieldGroup = $this->fieldgroups->get($abName);
	$abTemplate = $this->templates->get($abName);
	$abPage = $this->pages->get("/processwire/{$abName}/");

	if(is_null($abFieldGroup))
		$abFieldGroup = $this->_createAdminBarFieldGroup($abName);

	if(is_null($abTemplate))
		$abTemplate = $this->_createAdminBarTemplate($abName, $abFieldGroup);

	if(!file_exists($abTemplate->filename()))
		$this->_createAdminBarTemplateFile($abTemplate);

	if(!$abPage->id)
		$abPage = $this->_createAdminBarPage($abName, $abTemplate);

}

private function _createAdminBarFieldGroup($fieldGroupName) {
	$abFieldGroup = new Fieldgroup();
	$abFieldGroup->name = $fieldGroupName;
	$abFieldGroup->add("title");
	return $abFieldGroup->save();
}

private function _createAdminBarTemplate($templateName, $abFieldGroup) {
	$abTemplate = new Template();
	$abTemplate->name = $templateName;
	$abTemplate->setFieldgroup($abFieldGroup);
	return $abTemplate->save();
}

private function _createAdminBarPage($abName, $abTemplate) {

	// create /adminbar/ page under admin
	$abPage = new Page();
	$abPage->template = $abTemplate;
	$abPage->parent = $this->pages->get("/processwire/"); // TODO: How to remove hardcoding admin url??
	$abPage->title = $abName;
	$abPage->name = $abName;
	$abPage->status = 1031; // hidden & locked
	$abPage->save();

	// after that create /adminbar/adminbpar-sitemap/
	$abSitemapPage = new Page();
	$abSitemapPage->template = $abTemplate;
	$abSitemapPage->parent = $abPage;
	$abSitemapPage->title = $abName . '-sitemap';
	$abSitemapPage->name = $abName . '-sitemap';
	$abSitemapPage->status = 1031;
	return $abSitemapPage->save();
}

private function _createAdminBarTemplateFile($abTemplate) {
	copy(dirname(__FILE__)."/pages/sitemap.php", $abTemplate->filename());
}

AdminBar.zip

Share this post


Link to post
Share on other sites

Apeisa,

I tried this out and it works great! Nice work. The site map view is very useful too. Also, I think the code looks good! Here's a few suggestions and notes I've got:

The 500 error you got was thrown by ProcessWire. The problem is these lines:

return $abFieldGroup->save();
return $abTemplate->save();

All the save functions return a result status, basically true if it was successful, false if not. So to fix the error, you would need to change lines like the above to:

$abFieldGroup->save();
return $abFieldGroup;

$abTemplate->save();
return $abTemplate; 

When you are developing in ProcessWire, you may want to enable debug mode, so that errors are echoed to the screen. You can turn this on in /site/config.php. Look for the line that says $config->debug = false; and change it to true.

Next, I wanted to mention that the module interface provides install() and uninstall() methods, in case you want them:

/**
* Perform any installation procedures specific to this module, if needed. 
* 
* This method is OPTIONAL
*
*/
public function ___install();

/**
* Perform any uninstall procedures specific to this module, if needed. 
*
* This method is OPTIONAL
*
*/
public function ___uninstall();

There may be issues on many installations with your last function, _createAdminBarTemplateFile. The reason is that ProcessWire doesn't usually have write access to the templates dir (it depends on the server). So your installer may be want to look for this, or advise them to copy your template file in there if there isn't write access. Or, we could just make it a blank template (without a file) and then hook into it's render method so that your .module file can render the output instead. Let me know if you want to do that, and I can provide instructions.

Lastly, because the site map outputs a full sitemap, it may not scale to large installations. For instance, the site I am working on now has 5k+ pages, and while it renders them all, it takes several seconds. :) But on large installations, it might just run out of memory too. As a result, I would recommend placing a limit to the number of subpages that the sitemap will display. Maybe a "limit=50" per branch, just to account for the possibility of large sites. And once it reaches that limit, it might have a label that says "Go to the admin to view remaining pages" or something like that.

Again nice work on this, I am really enjoying using this module!

Share this post


Link to post
Share on other sites

Ryan, thanks for your answer. I wasn't sure about the write access on template dir (I develop on windows when there is basicly always write access).

So your installer may be want to look for this, or advise them to copy your template file in there if there isn't write access. Or, we could just make it a blank template (without a file) and then hook into it's render method so that your .module file can render the output instead. Let me know if you want to do that, and I can provide instructions.

Hmm.. I think that the latter is better. Or maybe both? If there is template file -> use that. If not -> render. Is that possible? The first reason I went for this "copy template file" route was that I didn't know any other way to make this work :)

Share this post


Link to post
Share on other sites

I think it might be better to just override the template rather than putting one in the /templates/ dir (unless you want to encourage them to edit it). I've modified the Template class so that you can change the target filename at runtime, so you'll want to grab the latest commit.

https://github.com/ryancramerdesign/ProcessWire/commit/0c8dc7d8e62c9a6a110791e00111c463ff00b01c

Next, move that template to the same directory as your module (/site/modules/AdminBar/adminbar.php).

Then in your AdminBar.module, add a new "before" page render hook. It will check to see if the page template is "adminbar", and if it is, it'll change the template filename to the one in your /site/modules/AdminBar/ dir.

<?php
public function beforePageRender($event) {
    $page = $event->object;
    if($page->template == 'adminbar') {
        $page->template->filename = $this->config->paths->AdminBar . "adminbar.php";
    }
}

Also, add this to your init() function in AdminBar.module:

$this->addHookBefore('Page::render', $this, 'beforePageRender');

If you do decide you want it to check if the file is in your /site/templates/ first, then just add that check to your beforePageRender method.

Now it should work exactly the same as before, except that it'll use the template file in your /site/modules/AdminBar/ dir rather than expecting one to be in /site/templates/.

Share this post


Link to post
Share on other sites

Lastly, because the site map outputs a full sitemap, it may not scale to large installations. For instance, the site I am working on now has 5k+ pages, and while it renders them all, it takes several seconds. :) But on large installations, it might just run out of memory too. As a result, I would recommend placing a limit to the number of subpages that the sitemap will display. Maybe a "limit=50" per branch, just to account for the possibility of large sites. And once it reaches that limit, it might have a label that says "Go to the admin to view remaining pages" or something like that.

I created this functionality and noticed that $page->numChildren gives num of all children (hidden also). Is there some selector that I can use to count only visible children?

Share this post


Link to post
Share on other sites

Well.. there is small bug. After deleting a page we get this error:

Call to a member function isAjax() on a non-object (line 62 of C:\apache\htdocs\pw\wire\core\admin.php)

This error message was shown because you are logged in as a Superuser.

This must be because of modal somehow? Deleting pages sends them to thrash (so it works), but we still get that error. I could just disable delete-tab on modal, but I think that is a nice feature. Any clues on this one Ryan?

Share this post


Link to post
Share on other sites

I should sort it out for IE, finally. But, unfortunately, no time :( I should also style that hide link a little {maybe another glyph?}

good work Antti.

Share this post


Link to post
Share on other sites

I should sort it out for IE, finally. But, unfortunately, no time :( I should also style that hide link a little {maybe another glyph?}

good work Antti.

Thanks Adam. And no reason for stress because of this, early days and most important thing is to learn module dev.

If someone has plans to use this on client site then please us know and we'll fix the "browser".

Share this post


Link to post
Share on other sites

I created this functionality and noticed that $page->numChildren gives num of all children (hidden also). Is there some selector that I can use to count only visible children?

There is. Try this:

$total = $page->children("limit=2")->getTotal();

You have to do "limit=2" (or higher) rather than "limit=1" because PW2 doesn't currently count totals on limit=1 selectors. That's just as a matter of efficiency, since all $pages->get() functions use limit=1 internally.

Share this post


Link to post
Share on other sites

This must be because of modal somehow? Deleting pages sends them to thrash (so it works), but we still get that error. I could just disable delete-tab on modal, but I think that is a nice feature. Any clues on this one Ryan?

I'm not sure why that error was turning up, and am out of time to take an in-depth look, but I was able to fix it easily. And actually I think it's something I should have had in there in the first place (an extra check to make sure that $controller is not null), so thank you for finding it. :) I have fixed this in the latest commit:

https://github.com/ryancramerdesign/ProcessWire/commit/99454cb68b0ccfe287ab82c68c9db7010a6f94be

AdminBar is looking great! Would you mind if I tweeted a link to your screencast?

Share this post


Link to post
Share on other sites

Updates: IE is fucking nightmare:


  •  
  • minor updates on github
     
  • still old readme [wanted to do the markdown version, no chance
     
  • IE7 isn't supported even by the PW Admin, no prob there [iE6 wasn't even tried]
     
  • IE8 is doing something funky with z-index, so hover doesn't work. I solved the width, but this is killing me. Also, BG of overlay isn't showing (because IE8 doesn't know rgba colors)
     
  • IE9 can't be virtualized in XP, and I don't have Win7 virtualized currently [neither install CD]. Also, IE9 is beta, so no hard feelings there

This should be it, I might look on the site tree later on too, because it's fugly.

Also I'm pissed, nothing works tonight. Good night, more updates tomorrow or later.

Share this post


Link to post
Share on other sites

I'm not sure why that error was turning up, and am out of time to take an in-depth look, but I was able to fix it easily. And actually I think it's something I should have had in there in the first place (an extra check to make sure that $controller is not null), so thank you for finding it. :) I have fixed this in the latest commit:

https://github.com/ryancramerdesign/ProcessWire/commit/99454cb68b0ccfe287ab82c68c9db7010a6f94be

AdminBar is looking great! Would you mind if I tweeted a link to your screencast?

Thanks for the fix. And sure you can tweet the screencast.

Share this post


Link to post
Share on other sites

I merged Adam's changes to adminbar. Also took cleaning further: I removed other options than modal and also cleaned js & css even more. It should work in IE now (I have only IE9 on my home computer and it works on that now. I am pretty confident that it works ok in other IE:s too - but no promises here :)).

Reasoning for taking options out: I think shortcuts will be the actual view that everyone uses: editing & creating will be done there. "Main" view will be for looking more information: who edited and when etc (hope to make that better later). And I think admin link should always take to admin front.

Also: I think this as real 1.0 release. I'll fix all the bugs that people may a rise, but any new features will be added with care. Of course all the optimizing to code and UI are most welcome (from Adam or anyone who is interested in contributing).

Share this post


Link to post
Share on other sites

I receive error when installing:

Exception: Can't save page 0: /adminbar/: It has no parent assigned (in www\phreshr.tv\wire\core\Pages.php line 337)

#0 [internal function]: Pages->___save(Object(Page))

#1 www\phreshr.tv\wire\core\Wire.php(241): call_user_func_array(Array, Array)

#2 www\phreshr.tv\wire\core\Wire.php(203): Wire->runHooks('save', Array)

#3 www\phreshr.tv\wire\core\Page.php(733): Wire->__call('save', Array)

#4 www\phreshr.tv\wire\core\Page.php(733): Pages->save(Object(Page))

#5 www\phreshr.tv\site\modules\AdminBar\AdminBar.module(312): Page->save()

#6 www\phreshr.tv\site\modules\AdminBar\AdminBar.module(284): AdminBar->_createAdminBarPage('adminbar', Object(Template))

#7 ww

This error message was shown because you are logged in as a Superuser.

Any suggestions on whats wrong? It had worked briefly. Then all of a sudden it didn't. I'm on a wamp stack and using php 5.3.5.

Share this post


Link to post
Share on other sites

Thanks for trying AdminBar and sorry for problems.

Error is probably that I have hardcoded the /processwire/ site as admin site. If you have renamed your admin (so that url is not /processwire/), then it will fail like that. You can make quick fix by editing two lines (chance them to have your admin page url):

https://github.com/apeisa/AdminBar/blob/master/AdminBar.module#L275

https://github.com/apeisa/AdminBar/blob/master/AdminBar.module#L308

I'll take a look how I could remove that hardcoding later today (I tried that earlier, but didn't work - Ryan, any clues? Probably some silly typo I had there...).

Share this post


Link to post
Share on other sites

You can get the admin URL from:

$config->urls->admin

Or if you want to retrieve the admin page:

$admin = $pages->get($config->adminRootPageID); 

Btw, I don't often do it, but it is good security to change your admin page name. You do this by editing it, clicking on the 'settings' tab and changing the name.

Share this post


Link to post
Share on other sites

Btw, I don't often do it, but it is good security to change your admin page name. You do this by editing it, clicking on the 'settings' tab and changing the name.

Heh, I made this and got redirect to 404. I thought it was somehow because of AdminBar.. but it wasn't. Spend few minutes itching my head and disabling all redirects on AdminBar.module... :)

Thanks for the tips Ryan. Now AdminBar works with any admin url, latest files are on GitHub.

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...