More on-the-fly processing! Here’s a plugin to demonstrate the use of regular expressions.
It will filter out images on your site and add a watermark to them. It actually works but performance wise you’re better off not to do this on the fly. I just thought this could be an example on how to filter out certain tags. This does not mean the regexp is perfect, though I think it works well.
This plugin is easily modified to do all sorts of other stuff like adding acronym tags. With some small changes you could also protect images from unauthorized users.
/*
* Created: 8/2005
* For: MODx cms (modxcms.com)
* Name: Watermark
* Description: On the fly watermark images on your site
* Events: OnWebPagePrerender
* Version: 1.0
*
* Put this text into a new plugin and set the System Event
* 'OnWebPagePrerender'.
*
* Depending on the regular expression it will take all src-
* fields within the <img> tag and change it.
* You need to install the file watermarked.php into
* '/assets/plugins/watermark/' for this to work.
*
* You also need a '/assets/images/watermark.png' and
* configure the watermarked.php file to your needs.
*/
$string = $modx->documentOutput;
$pattern = "/(<img[^>]*src\s*=\s*[\'\"])([^\'^\"]*\.(jpg|jpeg))([\'\"][^>]*>)/i";
$replacement = "$1/assets/plugins/watermark/watermarked.php?src=$2$4";
$modx->documentOutput = preg_replace($pattern, $replacement, $string);
/assets/plugins/watermark/watermarked.php
<?php
header('content-type: image/jpeg');
// Should be a safe image repository if you
// need to make sense.
$dirprefix = "http://sitename.com/";
$watermark = $dirprefix."/assets/images/watermark.png";
$image = $dirprefix.$_REQUEST['src'];
watermark($image, $watermark, 2,1);
// The minimumfactors tell how big the image must compared to the watermark
// before the watermark is applied. 2,2 means the image must be at least be 4
// times as big as the watermark.
function watermark($srcfilename, $watermark, $minumfactorx, $minumfactory) {
$imageInfo = getimagesize($srcfilename);
$width = $imageInfo[0];
$height = $imageInfo[1];
$logoinfo = getimagesize($watermark);
$logowidth = $logoinfo[0];
$logoheight = $logoinfo[1];
$horizmargin = $width-$logowidth;
$vertmargin = $height-$logoheight;
$photoImage = ImageCreateFromJPEG($srcfilename);
if ($width>=($logowidth*$minumfactorx) && $height>=($logoheight*$minumfactory)) {
// Only add watermark if watermark fits
ImageAlphaBlending($photoImage, true);
$logoImage = ImageCreateFromPNG($watermark);
$logoW = ImageSX($logoImage);
$logoH = ImageSY($logoImage);
ImageCopy($photoImage, $logoImage, $horizmargin, $vertmargin, 0, 0, $logoW, $logoH);
}
ImageJPEG($photoImage);
ImageDestroy($photoImage);
ImageDestroy($logoImage);
}
?>