Jump to content

Search the Community

Showing results for 'webp'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to ProcessWire
    • News & Announcements
    • Showcase
    • Wishlist & Roadmap
  • Community Support
    • Getting Started
    • Tutorials
    • FAQs
    • General Support
    • API & Templates
    • Modules/Plugins
    • Themes and Profiles
    • Multi-Language Support
    • Security
    • Jobs
  • Off Topic
    • Pub
    • Dev Talk

Product Groups

  • Form Builder
  • ProFields
  • ProCache
  • ProMailer
  • Login Register Pro
  • ProDrafts
  • ListerPro
  • ProDevTools
  • Likes
  • Custom Development

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests

  1. Add Image URLs A module for ProcessWire CMS/CMF. Allows images/files to be added to Image/File fields by pasting URLs or using the API. Installation Install the Add Image URLs module. Configuration You can add MIME type > file extension mappings in the module config. These mappings are used when validating URLs to files that do not have file extensions. Usage A "Paste URLs" button will be added to all Image and File fields. Use the button to show a textarea where URLs may be pasted, one per line. Images/files are added when the page is saved. A Pagefiles::addFromUrl method is also added to the API to achieve the same result. The argument of this method is expected to be either: a URL: "https://domain.com/image.jpg" an array of URLs: ["https://domain.com/image1.jpg", "https://domain.com/image2.jpg"] Example: // Get unformatted value of File/Image field to be sure that it's an instance of Pagefiles $page->getUnformatted('file_field')->addFromUrl("https://domain.com/path-to-file.ext"); // No need to call $page->save() as it's already done in the method Should you have an issue using the method, please have a look at the "errors" log to check if something was wrong with your URL(s). WebP conversion The core InputfieldImage does not support images in WebP format. But if you have the WebP To Jpg module installed (v0.2.0 or newer) then any WebP images you add via Add Image URLs will be automatically converted to JPG format. https://github.com/Toutouwai/AddImageUrls https://modules.processwire.com/modules/add-image-urls/
  2. After enabling WebP support you may notice it can take a long time for ProcessWire to create WebP copies of all images and their variations. For instance, on a site I work on (with over 10k images), it was taking about 1 second per image, ie. more than 3 hours in total.. ? If you are comfortable around the command-line, you can use the cwebp program and this bash script to speed things up drastically. I have built upon this script and got things to work in combination with xargs and find, making it rather powerful for PW's purposes. 1. Save this script as 'convert-webp.sh' (or download the Gist from Github), and follow instructions ######################################################################################################### # # Fast Recursive Images to WebP converter # Customized for ProcessWire CMS/CMF <https://www.processwire.com> # # Author: Eelke Feenstra <dev@eelke.net> # Version: 001 # Based upon: https://github.com/onadrog/bash-webp-converter # # Quick & dirty script to add webp versions to all PNG / JPG / JPEG files inside your PW assets folder # # 1. Set this script to executable: # $ chmod +x convert-webp.sh # # 2. Check if cwebp is installed: # $ cwebp -version # If it is not, install: # $ brew install webp # Or follow instructions https://developers.google.com/speed/webp/download # and change $executable to cwebp's full path # # 3. Run the script directly on a folder: # $ ./convert-webp.sh /path/to/your/folder # ######################################################################################################### # Configuration executable="cwebp" # update this to reflect your installation! quality=90 # change to desired WebP quality ######################################################################################################### converted=0 skipped=0 echo "Entering $1" for file in $1/* do name="${file%.*}" echo "FILE: $file" echo "NAME: $name" # Skip the folder itself.. if [ "$name" = "./." ]; then echo "SKIP: $name" continue; fi if [[ $(file --mime-type -b $name.webp) == image/webp ]]; then echo "FOUND: $name.webp, skipping.." skipped=$((skipped+1)) elif [[ $(file --mime-type -b $file) == image/*g ]]; then echo "NOT FOUND: $name.webp" newfile(){ echo "$file" | sed -r 's/(\.[a-z0-9]*$)/.webp/' } $executable -q $quality "$file" -short -o "$(newfile)" converted=$((converted+1)) fi done echo "Converted $converted, Skipped $skipped" 2. Run to create webp versions of all jpg/jpeg/png images in a given folder (for example the site's homepage) $ ./convert-webp.sh /path/to/processwire/site/assets/files/1 3. And in order to create WebP copies of ALL images inside the /site/assets/files folder, you can run this script. It searches for all directories inside the files directory, and passes these to the convert-webp.sh script using xargs. $ find /path/to/processwire/site/assets/files -maxdepth 2 -type d | xargs -I '{}' ./convert-webp.sh '{}' Tested both on MacOS 12 and Debian
  3. For whoever stumbles on this, the issue was exactly in the FileContentTypes. Every type that should be forced to download should have a "+" in front, which I did not have. So, this is the correct setup in config.php (for my case): $config->fileContentTypes = array( '?' => '+application/octet-stream', 'txt' => '+text/plain', 'csv' => '+text/csv', 'pdf' => '+application/pdf', 'doc' => '+application/msword', 'docx' => '+application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'xls' => '+application/vnd.ms-excel', 'xlsx' => '+application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'ppt' => '+application/vnd.ms-powerpoint', 'pptx' => '+application/vnd.openxmlformats-officedocument.presentationml.presentation', 'rtf' => '+application/rtf', 'gif' => '+image/gif', 'jpg' => '+image/jpeg', 'jpeg' => '+image/jpeg', 'png' => '+image/png', 'svg' => '+image/svg+xml', 'webp' => '+image/webp', 'zip' => '+application/zip', 'mp3' => '+audio/mpeg', ); In addition, I wanted to use original file names, not the ones that Processwire creates when uploading files. This modification to Zeka's code manages that through html_entity_decode: if($input->urlSegment1 == 'download') { if($input->urlSegment2) { $names = array(); $urls = array(); $originalNames = array(); foreach ($page->handoff_files as $handoff_file_repeater) { $file = $handoff_file_repeater->file; $original_name_unencoded = html_entity_decode($file->uploadName); array_push($names, $file->name); array_push($urls, $file->filename); array_push($originalNames, $original_name_unencoded); } $key = array_search($input->urlSegment2, $names); if($key !== false) { wireSendFile($urls[$key], [ "downloadFilename" => $originalNames[$key], ]); } else { throw new Wire404Exception(); } } } else if($input->urlSegment1) { // unknown URL segment, send a 404 throw new Wire404Exception(); } foreach ($page->handoff_files as $handoff_file_repeater){ $file = $handoff_file_repeater->file; $fileSizeInBytes = $files->size($file->filename); $formattedSize = formatFileSize($fileSizeInBytes); $original_name_unencoded = html_entity_decode($file->uploadName); ?> <div class="file-block"> <div class="file-info"> <h3><?=$original_name_unencoded;?></h3> <p><?=$formattedSize;?></p> </div> <!--<a href="<?=$file->url;?>" download="<?=$original_name_unencoded;?>" class="download-button">download</a>--> <a href="<?= 'download/'.$file->name; ?>" download="<?=$original_name_unencoded?>" class="download-button">download</a> </div> <?php } ?>
  4. Sorry to bring a thread from the dead, but I'm banging my head against the wall with this. I'm by no means a processwire expert and this is probably the most in-depth I've ever gone into understanding it. I've used Zeka's solution. In 2023 you need to add <?php namespace ProcessWire; ?> for wireSendFile() to work. The URL segment works and creates a link to the file, but the file does not download - it opens in the browser. This is an example url with the downloads: https://zar.co.com/handoffs/hera-title-colorado-posters/ The URL segment gets appended after this, for example - ....colorado-posters/download/name-of-file.jpg This is my setup in the config.php: $config->fileContentTypes = array( '?' => '+application/octet-stream', 'txt' => '+text/plain', 'csv' => '+text/csv', 'pdf' => '+application/pdf', 'doc' => '+application/msword', 'docx' => '+application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'xls' => '+application/vnd.ms-excel', 'xlsx' => '+application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'ppt' => '+application/vnd.ms-powerpoint', 'pptx' => '+application/vnd.openxmlformats-officedocument.presentationml.presentation', 'rtf' => '+application/rtf', 'gif' => 'image/gif', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'svg' => 'image/svg+xml', 'webp' => 'image/webp', 'zip' => '+application/zip', 'mp3' => 'audio/mpeg', ); Could someone point me in the right direction?
  5. Hi there, When I delete all image variants, ProcessWire does not remove previously generated webP files from the assets/files folder. The variants list is empty. PNG and jpeg images are removed just fine, but webP files are left on the server. This will increase dramatically disk space on bigger projects. How can I automatically clean up webP leftovers on deletion? Steps to reproduce: I am using a ProFields:repeater Matrix with a FieldtypeImage. webP variations are created with $img_1920->webp->url, $img_1600->webp->url ... in a <picture> element. 1. Within the repeater image field, → Variations → Delete checked → close the modal → Save 2. When I go to assets/files/1134/ all png variations are deleted. webP variations are still kept e.g. testgrafik-logodesign.1600x0se.webp, testgrafik-logodesign.1920x1080se.webp 3. When I open again the variations modal → the variation list is still empty, except the original file. 4. However deleting the repeater Item, will also remove all files from assets/files directory. ProcessWire 3.0.165
  6. I'm a little late chiming in, but I'm building my first PW site and was looking to see if AVIF was supported and found this thread. I likewise am surprised this hasn't been requested more. AVIF is _much_ more impressive than WebP in my opinion. I would be happy if it behaved the same way as WebP support as described here: https://processwire.com/blog/posts/webp-images-in-pw/ I've yet to see an instance where AVIF was a larger image size than the source. Because browser support still isn't there on Edge, I'd want to use it with srcset fallbacks anyway.
  7. If using server side resize, a webp version of the uploaded image is automatically created (at least if the uploaded image is larger than the field's max dimensions). But when using client side resize this doesn't happen. Is it possible to have a webp version automatically created while using client side resize (without resorting to creating a variation)?
  8. I want to show a new website that I made at the beginning of this year using @bernhard's RockPageBuilder module: https://www.kurrat-terrassendaecher.de/ The client: Kurrat Terrassendächer (which translates to "Kurrat Terrace Roofs") is a dealer from germany that is specialized in building custom made terrace roofings, awnings and solar protection. The goal: The customer had a old website that was used as a basis for the new design. The new website should offer a more "catalogue-like" look with lots of information for the customer. Fortunately the client had access to high quality images of the products that really make the whole website shine. The page features three main categories: 1. Terrace Roofs 3. Solar Protection 3. Winter Gardens Each category subpage is made of modular content blocks: The user is able to make custom page layouts using these blocks directly in the frontend. With the RockPageBuilder module it is super fun an super straight forward to work with these content blocks. If you don't know this module yet I highly recommend to check it out! If you like the RepaterMatrix you will love this module. It is far superior IMHO! Inserting a content block looks like this: It is also possible to edit content on-the-fly in the frontend: As with the RepeaterMatrix each content block an also be added end edited in the backend of the page: Here you see the list of content blocks used on the home page. To edit a block, just click on it and you can edit it just like using the RepaterMatrix. Screenshots from the website: Modules used for this page: - RockFrontend (for asset bundling, minifying, etc.) - RockPageBuilder (instead of RepeaterMatrix! For building and editing all content in the frontend) - WireMailSMTP - PageImageSource (for creating webp image variations) - PrivacyWire (for cookie consent banner) - SEO Maestro - Redirects The frontend framework is UIKit
  9. Hi guys, I’ve recently set up 2 PW installations for using WebP images (following this explanations, strategy 3). Both servers run on identical system configurations and PW versions (3.0.184). While integrating the WebP functionality was no problem at all, I’m massively confused by the results: one server works as expected, the other one does the sheer opposite. Server 1 (the good one): Images total: 326 WebP bigger than JPG: 41 (on average more than 40 %) WebP smaller than JPG: 285 (on average 30–40 %) Server 2 (the bad one): Images total: 862 WebP bigger than JPG: 773 (on average 30–40 %) WebP smaller than JPG: 89 (on average less than 10 %) As far as I know, the quality of the source JPG has an impact on the WebP: highly compressed JPGs may lead to hardly smaller or even bigger WebPs, while the savings with high quality JPGs tend to be more spectacular. Server 1 seems to confirm this assumption (the JPGs with bigger WebPs here are highly compressed 3rd party images) while server 2 ist acting completely strange. The source JPG’s size is around 1.200 x 800 pixel with a moderate compression rate and file sizes ranging between 100 and 500 kB with an average of 250 kB. The JPG quality on server 1 is about the same (regardless the 41 lousy ones), the only difference is their smaller size of 900 x 600 px with an average file size of 150 kB. So I’d consider the WebP use on server 1 as clearly progressive, while server 2 essentially limits itself to fill up the webspace with bigger images that will never appear on a display. Is there any influence on the WebP conversion I might have missed?
  10. I added support for automatic WebP to JPG conversion via the WebP To JPG module. To make use of this update to Add Image URLs v0.3.0 and install/update to WebP To JPG v0.2.0.
  11. Native AVIF support would be great for creating performant sites. When WEBP support was added to the core, it was done as a one-off addition. AVIF could be added in the same way by accessing an $image->avif property on the image object. However — I think @BrendonKoz touched on this above — adding more alternative output formats will probably require some rethinking to keep this part of the core modular. We'll definitely see more image formats being developed in the future, and it'd be great to access them from a single property or as a single parameter with formats and fallbacks, e.g. $image->url(300, ['format' => 'webp,png']).
  12. WebP image support is great and works fine. But once created I've issues to get rid of all API generated WebP variations. The backend image field variations "Delete" works and I can remove all variations JPEG plus WebP. Image list is clean but all WebP API variations are still stored in file system (for instance files/12345/84.900x675.webp etc). I can only use ImageSizer with temp 'force' option to request fresh WebP variations or have to delete WebP files from folders. No other way so far. Tested with 2 sites and latest master PW 3.0.165. Is there somewhere a "magic button" or config/setup thing to solve my sticky WebP issue?
  13. @horst Oh my, I'm sorry for never replying to you! I think I have finally found the origin of my and @AndZyk's situation: MAMP PRO on MacOS (5.7) simply does not have WebP support enabled. I still don't know why this creates all the new copies, because it seems that all moving parts seem to be aware that webp is in fact not enabled. With this basic check: <?php namespace ProcessWire; include "index.php"; error_reporting(E_ALL); ?> <pre> <h3>Check directly using gd_info()</h3> <?php $gd_info = gd_info(); $webpSupport = isset($gd_info['WebP Support']) ? $gd_info['WebP Support'] : false; print_r($gd_info); echo $webpSupport ? "\nWebP is supported" : "\nWebP is NOT supported"; ?> <hr> <h3>ImageSizerEngineIMagick</h3> <?php $imagick = $modules->get("ImageSizerEngineIMagick"); $supported = $imagick->supported("webp"); echo $supported ? "WebP is supported" : "WebP is NOT supported"; echo "\nFormats: " . print_r($imagick->getSupportedFormats(), true); ?> <hr> <h3>ImageSizerEngineGD</h3> <?php $gd = new ImageSizerEngineGD(); $supported = $gd->supported("webp"); echo ($supported ? "WebP is supported" : "WebP is NOT supported"); echo "\nFormats: " . print_r($gd->getSupportedFormats(), true); ?> </pre> I get these results on my MAMP PRO machine: Check directly using gd_info() Array ( [GD Version] => bundled (2.1.0 compatible) [FreeType Support] => 1 [FreeType Linkage] => with freetype [GIF Read Support] => 1 [GIF Create Support] => 1 [JPEG Support] => 1 [PNG Support] => 1 [WBMP Support] => 1 [XPM Support] => [XBM Support] => 1 [WebP Support] => [BMP Support] => 1 [TGA Read Support] => 1 [JIS-mapped Japanese Font Support] => ) WebP is NOT supported ImageSizerEngineIMagick WebP is NOT supported Formats: Array ( [source] => Array ( [0] => JPG [1] => JPEG [2] => PNG24 [3] => PNG [4] => GIF [5] => GIF87 ) [target] => Array ( [0] => JPG [1] => JPEG [2] => PNG24 [3] => PNG [4] => GIF [5] => GIF87 ) ) ImageSizerEngineGD WebP is NOT supported Formats: Array ( [source] => Array ( [0] => JPG [1] => JPEG [2] => PNG [3] => GIF ) [target] => Array ( [0] => JPG [1] => JPEG [2] => PNG [3] => GIF ) ) And these on the online host: Check directly using gd_info() Array ( [GD Version] => 2.2.5 [FreeType Support] => 1 [FreeType Linkage] => with freetype [GIF Read Support] => 1 [GIF Create Support] => 1 [JPEG Support] => 1 [PNG Support] => 1 [WBMP Support] => 1 [XPM Support] => 1 [XBM Support] => 1 [WebP Support] => 1 [BMP Support] => 1 [TGA Read Support] => 1 [JIS-mapped Japanese Font Support] => ) WebP is supported ImageSizerEngineIMagick WebP is supported Formats: Array ( [source] => Array ( [0] => JPG [1] => JPEG [2] => PNG24 [3] => PNG [4] => GIF [5] => GIF87 ) [target] => Array ( [0] => JPG [1] => JPEG [2] => PNG24 [3] => PNG [4] => GIF [5] => GIF87 [6] => WEBP ) ) ImageSizerEngineGD WebP is supported Formats: Array ( [source] => Array ( [0] => JPG [1] => JPEG [2] => PNG [3] => GIF ) [target] => Array ( [0] => JPG [1] => JPEG [2] => PNG [3] => GIF [4] => WEBP ) ) I have reached out to the MAMP folks for info on how I could go about enabling it here. The only related issues on StackOverflow etc are pointing in the wrong direction it seems (homebrew etc).
  14. Hi @Didjee, unfortunately you are right. My old code no longer works. ? I have dived into the issue and filed a github issue with a possible fix. So hopefully Ryan soon will find time to look at it. ? If you like, as a workaround you can place my new suggestion into the file wire/core/Pageimage.php instead of using the current webp() function there. /** * Get WebP "extra" version of this Pageimage * * @return PagefileExtra * @since 3.0.132 * */ public function webp() { $webp = $this->extras('webp'); if(!$webp) { $webp = new PagefileExtra($this, 'webp'); $webp->setArray($this->wire('config')->webpOptions); $this->extras('webp', $webp); $webp->addHookAfter('create', $this, 'hookWebpCreate'); } // recognize changes of JPEG / PNG variation via timestamp comparison if($webp && is_readable($webp->filename()) && filemtime($webp->filename()) < filemtime($this->filename) ) { $webp->create(); } return $webp; }
  15. Hi, I'm not sure what has gone wrong but after adding a few lines for webp to my .htaccess my site no longer works properly. I reversed it but there may have been another version of .htacess on the site which I've now overwritten. Note: After some checking: It doesn't seem to be rendering the templates. Eg: / = (should use template home.php) /about/ = (uses template page.php) For example putting "die;" in the home.php does nothing on the live server. Basically, it doesn't render the content block and spits out "default content" It is working perfectly on my local server with the same .htaccess file. $config->useMarkupRegions = true; I do not know what to do and I'd be grateful for help. This is my site: https://greglumley.com I've changed "default content" to a more friendly message. And here is my .htaccess ################################################################################################# # START PROCESSWIRE HTACCESS DIRECTIVES # @version 3.0 # @htaccessVersion 301 ################################################################################################# # # Upgrading htaccess (or index) version 300 to 301 # ----------------------------------------------------------------------------------------------- # If you never modified your previous .htaccess file, then you can simply replace it with this # one. If you have modified your .htaccess file, then you will want to copy/paste some updates # to the old one instead: # If your htaccess/index version is 300, upgrade to this version by replacing all of sections #5 # and #15 (Access Restrictions). Also take a look at section #9, which you might also consider # replacing if using HTTPS, though it is not required. (For instance, HSTS might be worthwhile) # # Following that, optionally review the rest of the file to see if there are any other changes # you also want to apply. Sections tagged "(v301)" are new or have significant changes. # # When finished, add a line at the top identical to the "htaccessVersion 301" that you see at # the top of this file. This tells ProcessWire your .htaccess file is up-to-date. # # Resolving 500 errors # ----------------------------------------------------------------------------------------------- # Depending on your server, some htaccess rules may not be compatible and result in a 500 error. # If you experience this, find all instances of the term "(500)" in this file for suggestions on # things you can change to resolve 500 errors. # # Optional features # ----------------------------------------------------------------------------------------------- # Many of the rules in this .htaccess file are optional and commented out by default. While the # defaults are okay for many, you may want to review each section in this .htaccess file for # optional rules that you can enable to increase security, speed or best practices. To quickly # locate all optional rules, search this file for all instances of "(O)". # # If using a load balancer # ----------------------------------------------------------------------------------------------- # If using a load balancer (like those available from AWS) some htaccess rules will need to # change. Search this file for instances of "(L)" for details. # # ----------------------------------------------------------------------------------------------- # 1. Apache Options # # Note: If you experience a (500) error, it may indicate your host does not allow setting one or # more of these options. First try replacing the +FollowSymLinks with +SymLinksifOwnerMatch. # If that does not work, try commenting them all out, then uncommenting one at a time to # determine which one is the source of the 500 error. # ----------------------------------------------------------------------------------------------- # Do not show directory indexes (strongly recommended) Options -Indexes # Do not use multiviews (v301) Options -MultiViews # Do follow symbolic links Options +FollowSymLinks # Options +SymLinksifOwnerMatch # Character encoding: Serve text/html or text/plain as UTF-8 AddDefaultCharset UTF-8 # ----------------------------------------------------------------------------------------------- # 2. ErrorDocument settings: Have ProcessWire handle 404s # # For options and optimizations (O) see: # https://processwire.com/blog/posts/optimizing-404s-in-processwire/ # ----------------------------------------------------------------------------------------------- ErrorDocument 404 /index.php # ----------------------------------------------------------------------------------------------- # 3. Handle request for missing favicon.ico/robots.txt files (no ending quote for Apache 1.3) # ----------------------------------------------------------------------------------------------- <Files favicon.ico> ErrorDocument 404 "The requested file favicon.ico was not found. </Files> <Files robots.txt> ErrorDocument 404 "The requested file robots.txt was not found. </Files> # ----------------------------------------------------------------------------------------------- # 4. Protect from XSS with Apache headers # ----------------------------------------------------------------------------------------------- <IfModule mod_headers.c> # prevent site from being loaded in an iframe on another site # you will need to remove this one if you want to allow external iframes Header always append X-Frame-Options SAMEORIGIN # To prevent cross site scripting (IE8+ proprietary) Header set X-XSS-Protection "1; mode=block" # Optionally (O) prevent mime-based attacks via content sniffing (IE+Chrome) # Header set X-Content-Type-Options "nosniff" </IfModule> # ----------------------------------------------------------------------------------------------- # 5. Prevent access to various types of files (v301) # # Note that some of these rules are duplicated by RewriteRules or other .htaccess files, as we # try to maintain two layers of protection when/where possible. # ----------------------------------------------------------------------------------------------- # 5A. Block access to inc, info, info.json/php, module/php, sh, sql and composer files # ----------------------------------------------------------------------------------------------- <FilesMatch "\.(inc|info|info\.(json|php)|module|module\.php|sh|sql)$|^\..*$|composer\.(json|lock)$"> <IfModule mod_authz_core.c> Require all denied </IfModule> <IfModule !mod_authz_core.c> Order allow,deny </IfModule> </FilesMatch> # 5B. Block bak, conf, dist, ini, log, orig, sh, sql, swo, swp, ~, and more # ----------------------------------------------------------------------------------------------- <FilesMatch "(^#.*#|\.(bak|conf|dist|in[ci]|log|orig|sh|sql|sw[op])|~)$"> <IfModule mod_authz_core.c> Require all denied </IfModule> <IfModule !mod_authz_core.c> Order allow,deny </IfModule> </FilesMatch> # ----------------------------------------------------------------------------------------------- # 6. Override a few PHP settings that can't be changed at runtime (not required) # Note: try commenting out this entire section below if getting Apache (500) errors. # ----------------------------------------------------------------------------------------------- <IfModule mod_php5.c> php_flag magic_quotes_gpc off php_flag magic_quotes_sybase off php_flag register_globals off </IfModule> # ----------------------------------------------------------------------------------------------- # 7. Set default directory index files # ----------------------------------------------------------------------------------------------- DirectoryIndex index.php index.html index.htm # ----------------------------------------------------------------------------------------------- # 8. Enable Apache mod_rewrite (required) # ----------------------------------------------------------------------------------------------- <IfModule mod_rewrite.c> RewriteEngine On # Send WEBP images for JPG or PNG when supported and available. # This means that a request for a JPG or PNG file will instead deliver # WEBP data, but only when the browser supports and understands it. # RewriteCond %{HTTP_ACCEPT} image/webp # RewriteCond %{REQUEST_FILENAME} -f # RewriteCond %{DOCUMENT_ROOT}/$1$2$3/$4.webp -f # RewriteCond expr "! %{QUERY_STRING} -strmatch 'nc=*'" # RewriteRule ^(.*?)(site/assets/files/)([0-9]+)/(.*)\.(jpe?g|png)(.*)$ /$1$2$3/$4.webp [L] # 8A. Optionally (O) set a rewrite base if rewrites are not working properly on your server. # ----------------------------------------------------------------------------------------------- # In addition, if your site directory starts with a "~" you will most likely have to use this. # https://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase # Examples of RewriteBase (root and subdirectories): # RewriteBase / # RewriteBase /pw/ # RewriteBase /~user/ # 8B. Set an environment variable so the installer can detect that mod_rewrite is active. # ----------------------------------------------------------------------------------------------- # Note that some web hosts don't support this. If you get a (500) error, try commenting out this # SetEnv line below. <IfModule mod_env.c> SetEnv HTTP_MOD_REWRITE On </IfModule> # ----------------------------------------------------------------------------------------------- # 9. Optionally Force HTTPS (O) # ----------------------------------------------------------------------------------------------- # Note that on some web hosts you may need to replace %{HTTPS} with %{ENV:HTTPS} in order # for it to work (in sections 9A and 9D below). If on a load balancer or proxy setup, you will # likely need to use 9B rather than 9A, and 9E rather than 9D. # ----------------------------------------------------------------------------------------------- # 9A. To redirect HTTP requests to HTTPS, uncomment the lines below (also see note above): # ----------------------------------------------------------------------------------------------- # RewriteCond %{HTTPS} !=on # RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # 9B. If using load balancer/AWS or behind proxy, use the following rather than 9A above: (L) # ----------------------------------------------------------------------------------------------- # RewriteCond %{HTTP:X-Forwarded-Proto} =http # RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # 9C. If using cPanel AutoSSL or Let's Encrypt webroot you may need to MOVE one of the below # lines after the first RewriteCond in 9A or 9B to allow certificate validation: # ----------------------------------------------------------------------------------------------- # RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/ # RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[\w-]+$ # RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ # 9D. Store current scheme in a 'proto' environment variable for later use # ----------------------------------------------------------------------------------------------- RewriteCond %{HTTPS} =on RewriteRule ^ - [env=proto:https] RewriteCond %{HTTPS} !=on RewriteRule ^ - [env=proto:http] # 9E. If using load balancer/AWS or behind proxy, use lines below rather than 9D: (L) # ----------------------------------------------------------------------------------------------- # RewriteCond %{HTTP:X-Forwarded-Proto} =https # RewriteRule ^ - [env=proto:https] # RewriteCond %{HTTP:X-Forwarded-Proto} =http # RewriteRule ^ - [env=proto:http] # 9F. Tell web browsers to only allow access via HSTS: Strict-Transport-Security (O) (v301) # ----------------------------------------------------------------------------------------------- # This forces client-side SSL redirection. Before enabling be absolutely certain you can # always serve via HTTPS because it becomes non-revokable for the duration of your max-age. # See link below for details and options (note 'max-age=31536000' is 1-year): # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security <IfModule mod_headers.c> # Uncomment one (1) line below & adjust as needed to enable Strict-Transport-Security (HSTS): # Header always set Strict-Transport-Security "max-age=31536000;" # Header always set Strict-Transport-Security "max-age=31536000; includeSubdomains" # Header always set Strict-Transport-Security "max-age=31536000; preload" # Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" </IfModule> # Section 10 intentionally omitted for future use # ----------------------------------------------------------------------------------------------- # 11. Nuisance blocking/firewall # ----------------------------------------------------------------------------------------------- # None of these are enabled by default, but are here for convenience when the need arises. # Review and uncomment as needed. For more complete firewall (and more overhead), the 7G firewall # (or latest version) is worth considering, see: https://perishablepress.com/7g-firewall/ # ----------------------------------------------------------------------------------------------- # 11A. Block via IP addresses # ----------------------------------------------------------------------------------------------- # Note that IP addresses here are examples only and should be replaced with actual IPs. # Block single IP address # Deny from 111.222.333.444 # Block multiple IP addresses # Deny from 111.222.333.444 44.33.22.11 # Block IP address ranges (999.88.*, 99.88.77.*, 1.2.3.*) # Deny from 999.888 99.88.77 1.2.3 # 11B. Block via request URI (matches strings anywhere in request URL) # ----------------------------------------------------------------------------------------------- # RewriteCond %{REQUEST_URI} (bad-word|wp-admin|wp-content) [NC] # RewriteRule .* - [F,L] # 11B. Block via user agent strings (matches strings anywhere in user-agent) # ----------------------------------------------------------------------------------------------- # RewriteCond %{HTTP_USER_AGENT} (bad-bot|mean-bot) [NC] # RewriteRule .* - [F,L] # 11C. Block via remote hosts # ----------------------------------------------------------------------------------------------- # RewriteCond %{REMOTE_HOST} (bad-host|annoying-host) [NC] # RewriteRule .* - [F,L] # 11D. Block via HTTP referrer (matches anywhere in referrer URL) # ----------------------------------------------------------------------------------------------- # RewriteCond %{HTTP_REFERER} (bad-referrer|gross-referrer) [NC] # RewriteRule .* - [F,L] # 11E. Block unneeded request methods (only if you do not need them) # ----------------------------------------------------------------------------------------------- # RewriteCond %{REQUEST_METHOD} ^(connect|debug|delete|move|put|trace|track) [NC] # RewriteRule .* - [F,L] # 11F. Limit file upload size from Apache (i.e. 10240000=10 MB, adjust as needed) # ----------------------------------------------------------------------------------------------- # LimitRequestBody 10240000 # ----------------------------------------------------------------------------------------------- # 12. Access Restrictions: Keep web users out of dirs or files that begin with a period, # but let services like Lets Encrypt use the webroot authentication method. # ----------------------------------------------------------------------------------------------- RewriteRule "(^|/)\.(?!well-known)" - [F] # ----------------------------------------------------------------------------------------------- # 13. Optional domain redirects (O) # # Redirect domain.com to www.domain.com redirect (or www to domain.com redirect). # To use, uncomment either 13A, 13B or 13C. Do not use more than one of them. 13A and 13B # redirect non-www hosts to www.domain.com, 13C redirects www.domain.com host to domain.com. # ----------------------------------------------------------------------------------------------- # 13A. Redirect domain.com and *.domain.com to www.domain.com (see also 13B as alternate): # ----------------------------------------------------------------------------------------------- # RewriteCond %{HTTP_HOST} !^www\. [NC] # RewriteCond %{SERVER_ADDR} !=127.0.0.1 # RewriteCond %{SERVER_ADDR} !=::1 # RewriteRule ^ %{ENV:PROTO}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # 13B. Alternate www redirect if 13A does not work for your server: # ----------------------------------------------------------------------------------------------- # RewriteCond %{HTTP_HOST} !^www\. [NC] # RewriteRule ^ %{ENV:PROTO}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # 13C. Redirect www.domain.com to domain.com (do not combine with 13A or 13B): # ----------------------------------------------------------------------------------------------- # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] # RewriteRule ^ %{ENV:PROTO}://%1%{REQUEST_URI} [R=301,L] # ----------------------------------------------------------------------------------------------- # 14. Optionally send URLs with non-ASCII name-format characters to 404 page (optimization). # # This ensures that ProcessWire does not spend time processing URLs that we know ahead of time # are going to result in 404s. Uncomment lines below to enable. (O) # ----------------------------------------------------------------------------------------------- # RewriteCond %{REQUEST_URI} "[^-_.a-zA-Z0-9/~]" # RewriteCond %{REQUEST_FILENAME} !-f # RewriteCond %{REQUEST_FILENAME} !-d # RewriteRule ^(.*)$ index.php?it=/http404/ [L,QSA] # ----------------------------------------------------------------------------------------------- # 15. Access Restrictions (v301) # ----------------------------------------------------------------------------------------------- # 15A. Keep http requests out of specific files and directories # ----------------------------------------------------------------------------------------------- # Prevent all the following rules from blocking images in site install directories RewriteCond %{REQUEST_URI} !(^|/)site-[^/]+/install/[^/]+\.(jpg|jpeg|png|gif|webp|svg)$ # Block access to any htaccess files RewriteCond %{REQUEST_URI} (^|/)(\.htaccess|htaccess\..*)$ [NC,OR] # Block access to various assets directories RewriteCond %{REQUEST_URI} (^|/)(site|site-[^/]+)/assets/(cache|logs|backups|sessions|config|install|tmp)($|/.*$) [NC,OR] # Block access to the /site/install/ directories RewriteCond %{REQUEST_URI} (^|/)(site|site-[^/]+)/install($|/.*$) [NC,OR] # Block dirs in /site/assets/dirs that start with a hyphen (see config.pagefileSecure) RewriteCond %{REQUEST_URI} (^|/)(site|site-[^/]+)/assets.*/-.+/.* [NC,OR] # Block access to /wire/config.php, /site/config.php, /site/config-dev.php, /wire/index.config.php, etc. RewriteCond %{REQUEST_URI} (^|/)(wire|site|site-[^/]+)/(config|index\.config|config-dev)\.php($|/) [NC,OR] # Block access to any PHP-based files in /site/templates-admin/ or /wire/templates-admin/ RewriteCond %{REQUEST_URI} (^|/)(wire|site|site-[^/]+)/templates-admin($|/|/.*\.(php|html?|tpl|inc))($|/) [NC,OR] # Block access to any PHP or markup files in /site/templates/ or /site-*/templates/ RewriteCond %{REQUEST_URI} (^|/)(site|site-[^/]+)/templates($|/|/.*\.(php|html?|tpl|inc))($|/) [NC,OR] # Block access to any files in /site/classes/ or /site-*/classes/ RewriteCond %{REQUEST_URI} (^|/)(site|site-[^/]+)/classes($|/.*) [NC,OR] # Block access to any PHP files within /site/assets/ and further RewriteCond %{REQUEST_URI} (^|/)(site|site-[^/]+)/assets($|/|/.*\.ph(p|ps|tml|p[0-9]))($|/) [NC,OR] # Block access to any PHP, module, inc or info files in core or core modules directories RewriteCond %{REQUEST_URI} (^|/)wire/(core|modules)/.*\.(php|inc|tpl|module|info\.json)($|/) [NC,OR] # Block access to any PHP, tpl or info.json files in /site/modules/ or /site-*/modules/ RewriteCond %{REQUEST_URI} (^|/)(site|site-[^/]+)/modules/.*\.(php|inc|tpl|module|info\.json)$ [NC,OR] # Block access to any software identifying txt, markdown or textile files RewriteCond %{REQUEST_URI} (^|/)(COPYRIGHT|INSTALL|README|htaccess)\.(txt|md|textile)$ [NC,OR] # Block potential arbitrary backup files within site directories for things like config RewriteCond %{REQUEST_URI} (^|/)(site|site-[^/]+)/(config[^/]*/?|[^/]+\.php.*)$ [NC,OR] # Block access throughout to temporary files ending with tilde created by certain editors RewriteCond %{REQUEST_URI} \.(html?|inc|json|lock|module|php|py|rb|sh|sql|tpl|tmpl|twig)~$ [NC,OR] # Block access to names of potential backup file extensions within wire or site directories RewriteCond %{REQUEST_URI} (^|/)(wire/|site[-/]).+\.(bak|old|sql|sw[op]|(bak|php|sql)[./]+.*)[\d.]*$ [NC,OR] # Block all http access to the default/uninstalled site-default directory RewriteCond %{REQUEST_URI} (^|/)site-default/ # If any conditions above match, issue a 403 forbidden RewriteRule ^.*$ - [F,L] # 15B. Block archive file types commonly used for backup purposes (O) # ----------------------------------------------------------------------------------------------- # This blocks requests for zip, rar, tar, gz, and tgz files that are sometimes left on servers # as backup files, and thus can be problematic for security. This rule blocks those files # unless they are located within the /site/assets/files/ directory. This is not enabled by # default since there are many legitimate use cases for these files, so uncomment the lines # below if you want to enable this. # RewriteCond %{REQUEST_URI} \.(zip|rar|tar|gz|tgz)$ [NC] # RewriteCond %{REQUEST_URI} !(^|/)(site|site-[^/]+)/assets/files/\d+/ [NC] # RewriteRule ^.*$ - [F,L] # PW-PAGENAME # ----------------------------------------------------------------------------------------------- # 16A. Ensure that the URL follows the name-format specification required by PW # See also directive 16b below, you should choose and use either 16a or 16b. # ----------------------------------------------------------------------------------------------- RewriteCond %{REQUEST_URI} "^/~?[-_.a-zA-Z0-9/]*$" # ----------------------------------------------------------------------------------------------- # 16B. Alternative name-format specification for UTF8 page name support. (O) # If used, comment out section 16a above and uncomment the directive below. If you have updated # your $config->pageNameWhitelist make the characters below consistent with that. # ----------------------------------------------------------------------------------------------- # RewriteCond %{REQUEST_URI} "^/~?[-_./a-zA-Z0-9æåäßöüđжхцчшщюяàáâèéëêěìíïîõòóôøùúûůñçčćďĺľńňŕřšťýžабвгдеёзийклмнопрстуфыэęąśłżź]*$" # END-PW-PAGENAME # ----------------------------------------------------------------------------------------------- # 17. If the request is for a file or directory that physically exists on the server, # then don't give control to ProcessWire, and instead load the file # ----------------------------------------------------------------------------------------------- RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !(favicon\.ico|robots\.txt) # ----------------------------------------------------------------------------------------------- # 18. Optionally (O) prevent PW from attempting to serve images or anything in /site/assets/. # Both of these lines are optional, but can help to reduce server load. However, they # are not compatible with the $config->pagefileSecure option (if enabled) and they # may produce an Apache 404 rather than your regular 404. You may uncomment the two lines # below if you don't need to use the $config->pagefileSecure option. After uncommenting, test # a URL like domain.com/site/assets/files/test.jpg to make sure you are getting a 404 and not # your homepage. If getting your homepage, then either: do not use this option, or comment out # section #2 above that makes ProcessWire the 404 handler. # ----------------------------------------------------------------------------------------------- # RewriteCond %{REQUEST_URI} !\.(jpg|jpeg|gif|png|ico|webp|svg)$ [NC] # RewriteCond %{REQUEST_FILENAME} !(^|/)site/assets/ # ----------------------------------------------------------------------------------------------- # 19. Pass control to ProcessWire if all the above directives allow us to this point. # For regular VirtualHosts (most installs) # ----------------------------------------------------------------------------------------------- RewriteRule ^(.*)$ index.php?it=$1 [L,QSA] # ----------------------------------------------------------------------------------------------- # 20. If using VirtualDocumentRoot (500): comment out the one above and use this one instead # ----------------------------------------------------------------------------------------------- # RewriteRule ^(.*)$ /index.php?it=$1 [L,QSA] </IfModule> ################################################################################################# # END PROCESSWIRE HTACCESS DIRECTIVES #################################################################################################
  16. I would expect it to contain only images with the exact dimensions I specified, like this: <picture> <source srcset="FILENAME.800x400-srcset.webp 800w, FILENAME.1600x800-srcset.webp 1600w" sizes="(max-width: 900px) 100vw, ((min-width: 901px) and (max-width: 1200px)) 67vw, ((min-width: 1201px) and (min-width: 1201px)) 50vw" type="image/webp"> <source srcset="FILENAME.800x400-srcset.jpg 800w, FILENAME.1600x800-srcset.jpg 1600w" sizes="(max-width: 900px) 100vw, ((min-width: 901px) and (max-width: 1200px)) 67vw, ((min-width: 1201px) and (min-width: 1201px)) 50vw" type="image/jpeg"> <img src="FILENAME.800x400.jpg" alt="..." class="hero-img" width="800" height="400" loading="lazy"> </picture> Instead of the 1600x800 variants I get the original image URL again. Disabling upscaling does not change it. Of course I could resize the image before rendering as in your example, but shouldn't it be possible to pass an array for the srcset and get exactly the values you specified? This is a fix of course, but feels more like a hack than a solution. Cheers, Flo
  17. @nbcommunication I have to correct: The update fixed it in one specific case. I still have the problem in another place: $img->render( [ 'picture' => true, 'srcset' => [ 'rules' => ['800x400', '1600x800'], 'options' => [ 'upscaling' => true, ], ], 'allSets' => true, 'sizes' => '(max-width: 900px) 100vw, ((min-width: 901px) and (max-width: 1200px)) 67vw, ((min-width: 1201px) and (min-width: 1201px)) 50vw', 'class' => 'hero-img', 'alt' => "...", 'markup' => "<img src='".$img->size(800, 400)->url."' alt='{alt}' class='{class}' width='".$img->size(800, 400)->width."' height='".$img->size(800, 400)->height."'>", ] ) leads to this markup: <picture> <source srcset="FILENAME.800x400-srcset.webp 800w, FILENAME.webp 1600w" sizes="(max-width: 900px) 100vw, ((min-width: 901px) and (max-width: 1200px)) 67vw, ((min-width: 1201px) and (min-width: 1201px)) 50vw" type="image/webp"> <source srcset="FILENAME.800x400-srcset.jpg 800w, FILENAME.jpg 1600w" sizes="(max-width: 900px) 100vw, ((min-width: 901px) and (max-width: 1200px)) 67vw, ((min-width: 1201px) and (min-width: 1201px)) 50vw" type="image/jpeg"> <img src="FILENAME.800x400.jpg" alt="..." class="hero-img" width="800" height="400" loading="lazy"> </picture> The intrinsic dimensions of the image are 1080x721. I am really curious why the update worked in one place and not in the other. Do you need more information to investigate?
  18. Happy to announce the launch of the completely rebuilt San Francisco Contemporary Music Players website, using ProcessWire. https://sfcmp.org/ The previous website was a hornet's nest of disorganized content, dozens of 3rd party plugins, duct taped together within WordPress... difficult to use, time consuming and confusing to manage. And didn't look so good either. Lot of fun to rebuild this, though took several months. YOOtheme Pro and UiKit were a dream for me to work with, just love those. Made it so possible to create all of the custom sections, widgets, sliders, cards, mega menus, and so on. Don't consider myself a front-end focused web dev, so have a deep appreciation for the time, care and effort that Yoo has put into both UiKit and YOOtheme Pro. Almost no additonal CSS was needed to be written for this; the stock UiKit classes and attributes make it possible to just build things in HTML and not have to fiddle with CSS. Ryan's commercial modules played a major role in the build. ProFields, ListerPro, ProCache, and FormBuilder were all important. FormBuilder+Stripe allowed me to confidently migrate their need for a stripe checkout from some WP plugin to the clean and simple setup now using FB. ( https://sfcmp.org/donate/print-for-sale-dirge-by-hung-liu/ ) Some libraries also were of great use and value, namely PLYR for audio, and tabulator for some table display type of stuff. As always, the API was a dream to work with, many custom import scripts were created along the way to import legacy Press, Albums, Repertoire works, Program Booklets library, Players etc.. The image API is doing wonders with SRC sets, and webp images. The PW documentation site was a daily companion. This forum likewise was always a most valuable and enjoyable resource to search and rely on for solving the occasional conundrum. There is such a wealth of info here that i never found it necessary to post a question. Lastly, to underscore just how unparalleled, flexible and user-friendly the PW backend is, we had the backend training session a couple of weeks after the site was launched, and within 30 minutes, the person who will be managing the content was able to know how to create and manage concerts, blog posts, albums, press articles and more.
  19. Any solutions? I thought it was possible because the Mime types is in the config image/webp:webp
  20. If i add a webp image url i get error "Pageimage: johnrogershousemay2020.0x260.webp - not a supported image type"... ? Any idea whats wrong?
  21. Hi @uiui, Variations are only generated and used for sizes smaller than the original. When it reaches a dimension where the image does not need to be resized, it 'completes' the generation process. Running your examples on an image 2048px wide gives me: /site/assets/files/1033/very_large_array_clouds.webp 4096w/site/assets/files/1033/very_large_array_clouds.1920x0-srcset.webp 1920w, /site/assets/files/1033/very_large_array_clouds.1600x0-srcset.webp 1600w, /site/assets/files/1033/very_large_array_clouds.1280x0-srcset.webp 1280w, /site/assets/files/1033/very_large_array_clouds.980x0-srcset.webp 980w, /site/assets/files/1033/very_large_array_clouds.480x0-srcset.webp 480w, /site/assets/files/1033/very_large_array_clouds.webp 4096w This is definitely a quirk of the module's implementation that I hadn't considered - all the srcset examples I referred to during development had the sources ordered smallest to largest - and I don't think it is something I can sort in the default implementation. Perhaps I could add an option to disable the automatic completion e.g. 'Generate variations for all srcset dimensions?' Would this be useful for you? Cheers, Chris
  22. Hey, I'm trying to completely switch over to WebP and noticed some strange behaviour. Let's say I upload a PNG in Processwire of size 1280x800. $page->image->url ➝ correct URL (filename.webp) $page->image->width(800)->url ➝ correct URL (filename.800x0.webp) $page->image->width(1280)->url ➝ wrong URL (filename.1280x0.png), webp file is not generated $page->image->width(1280)->url(false) ➝ correct URL (filename.1280x0.webp) but webp file is not generated So: When I request a size that equals the original file, no WebP conversion is happening (no webp file is created, although a new PNG is generated (...1280x0.png)). When I use url(false), I get the expected URL but still the file is not generated. Also interesting: this issue is only occuring with PNG, not JPG. My Configuration: $config->imageSizerOptions('webpAdd', true); $config->imageSizerOptions('defaultGamma', -1); GD Pageimage::url Hook from here Also tried to output width(1280)->webp->url, it makes no difference I checked that the PNG version is not smaller in filesize (PNG=450KB, WebP (from other tool)=60KB) Tested with Processwire 3.0.148 and 3.0.160 dev I think this post is about the same issue and where I got the url(false) from. Setting 'useSrcUrlOnFail' => false inside $config->webpOptions results in correct output URL (filename.1280x0.webp), but still the file is not generated. So maybe the webp conversion fails? Apparently I see zero webp logs in logs/image-resizer.txt "Don't use resize" seems like a solution here but this is a generic approach in my code, sometimes uploaded images are simply already in the correct size. Any ideas how to fix this and always get dem sweet sweet WebP images? Or did I find a bug? Maybe @horst has an idea what the cause of this phenomenon could be? ?
  23. I have more and more customers complaining that they can't upload webp images. I understand that webp is not the ideal master image format, but neither is jpeg. The webp browser support is also so good now that it would not be necessary to generate jpeg/png versions from webp.
  24. Repost from Autosmush topic: In regards to .webp if anyone should be interested: If you're using Cloudflare free plan, it doesn't matter anyway. Cloudflare free plan doesn't support HTTP vary header so this : – Will NOT do anything useful. Because Cloudflare will serve your webp version NO MATTER WHAT. Which means that Safari on Mac and all iOS devices will not show any pictures... ? Source: https://community.cloudflare.com/t/cloudflare-cdn-cache-to-support-http-vary-header/160802 , https://community.cloudflare.com/t/cloudflare-displays-broken-images-on-my-website/183212/13
  25. This module allows you to automatically rename file (including image) uploads according to a configurable format This module lets you define as many rules as you need to determine how uploaded files will be named and you can have different rules for different pages, templates, fields, and file extensions, or one rule for all uploads. Renaming works for files uploaded via the admin interface and also via the API, including images added from remote URLs. Github: https://github.com/adrianbj/CustomUploadNames Modules Directory: http://modules.processwire.com/modules/process-custom-upload-names/ Renaming Rules The module config allows you to set an unlimited number of Rename Rules. You can define rules to specific fields, templates, pages, and file extensions. If a rule option is left blank, the rule with be applied to all fields/templates/pages/extensions. Leave Filename Format blank to prevent renaming for a specific field/template/page combo, overriding a more general rule. Rules are processed in order, so put more specific rules before more general ones. You can drag to change the order of rules as needed. The following variables can be used in the filename format: $page, $template, $field, and $file. For some of these (eg. $field->description), if they haven't been filled out and saved prior to uploading the image, renaming won't occur on upload, but will happen on page save (could be an issue if image has already been inserted into RTE/HTML field before page save). Some examples: $page->title mysite-{$template->name}-images $field->label $file->description {$page->name}-{$file->filesize}-kb prefix-[Y-m-d_H-i-s]-suffix (anything inside square brackets is is considered to be a PHP date format for the current date/time) randstring[n] (where n is the number of characters you want in the string) ### (custom number mask, eg. 001 if more than one image with same name on a page. This is an enhanced version of the automatic addition of numbers if required) If 'Rename on Save' is checked files will be renamed again each time a page is saved (admin or front-end via API). WARNING: this setting will break any direct links to the old filename, which is particularly relevant for images inserted into RTE/HTML fields. The Filename Format can be defined using plain text and PW $page variable, for example: mysite-{$page->path} You can preserve the uploaded filename for certain rules. This will allow you to set a general renaming rule for your entire site, but then add a rule for a specific page/template/field that does not rename the uploaded file. Just simply build the rule, but leave the Filename Format field empty. You can specify an optional character limit (to nearest whole word) for the length of the filename - useful if you are using $page->path, $path->name etc and have very long page names - eg. news articles, publication titles etc. NOTE - if you are using ProcessWire's webp features, be sure to use the useSrcExt because if you have jpg and png files on the same page and your rename rules result in the same name, you need to maintain the src extension so they are kept as separate files. $config->webpOptions = array( 'useSrcExt' => false, // Use source file extension in webp filename? (file.jpg.webp rather than file.webp) ); Acknowledgments The module config settings make use of code from Pete's EmailToPage module and the renaming function is based on this code from Ryan: http://processwire.com/talk/topic/3299-ability-to-define-convention-for-image-and-file-upload-names/?p=32623 (also see this post for his thoughts on file renaming and why it is the lazy way out - worth a read before deciding to use this module). NOTE: This should not be needed on most sites, but I work with lots of sites that host PDFs and photos/vectors that are available for download and I have always renamed the files on upload because clients will often upload files with horrible meaningless filenames like: Final ReportV6 web version for John Feb 23.PDF
×
×
  • Create New...