PHx/CustomModifiers

From MODx Wiki

Jump to: navigation, search

Contents

Installation

  1. Login to the MODx manager
  2. Go to Resources -> Manage Resources -> Snippets
  3. Click "new snippet"
  4. Prefix the snippet name with "phx:"


Contributed

These are in alphabetical order. Please put new ones in the right place.

phx:7bit

  • description: returns the 7bit representation of a string
  • usage: [+string:7bit+]
  1. <?php
  2. $text = mb_convert_encoding($output,'HTML-ENTITIES',mb_detect_encoding($output));
  3. $text = preg_replace(array('/&szlig;/','/&(..)lig;/','/&([aouAOU])uml;/','/&(.)[^;]*;/'),array('ss',"$1","$1".'e',"$1"),$text);
  4. return $text;
  5. ?>

phx:age

  • description: Takes a unixtime date input and calculates the age in years. It kind of fakes leap years but it's probably close enough for most uses.
  • example: Set a TV called "date_birth" with the unixtime widget, then output it as [+date_birth:age+]
  • usage: [+date_birth:age+]
  • added by: themancan
  1. <?php
  2. $output = floor((time() - $output) / 31557600);
  3. return $output;
  4. ?>

phx:alternateClass

  • description: Allows rows or other repeating elements to alternate provided the $output is an integer generated by a loop.
  • usage: [+phx:alternateClass=`class name`+]
  • example: <li class="[+maxigallery.picture.pos:alternateClass=`alt`+]"> outputs <li class="alt"> for every other <li> in the loop.
  • notes: Originally designed for use with MaxiGallery to apply an alternating class to the <li> galleryPictureTpl template chunk.
  • added by: smashingred
  1. <?php
  2. if($output % 2)
  3. {
  4. echo $options;
  5. }else{
  6. echo '';
  7. }
  8. ?>

phx:bbcode

  • description: parse bb code (also escapes all html and MODx tags characters)
  • usage: [+variable:bbcode+]
  1. <?php
  2. $string = preg_replace("/&amp;(#[0-9]+|[a-z]+);/i", "&$1;", htmlspecialchars($output));
  3. $string = preg_replace('~\[b\](.+?)\[/b\]~is', '<b>\1</b>', $string);
  4. $string = preg_replace('~\[i\](.+?)\[/i\]~is', '<i>\1</i>', $string);
  5. $string = preg_replace('~\[u\](.+?)\[/u\]~is', '<span style="text-decoration: underline;">\1</span>', $string);
  6. $string = preg_replace('~\[link\]www.(.+?)\[/link\]~is', '<a href="http://www.\1" target="_blank">www.\1</a>', $string);
  7. $string = preg_replace('~\[link\](.+?)\[/link\]~is', '<a href="\1" target="_blank">\1</a>', $string);
  8. $string = preg_replace('~\[link=(.+?)\](.+?)\[/link\]~is', '<a href="\1" target="_blank">\2</a>', $string);
  9. $string = preg_replace('~\[url\]www.(.+?)\[/url\]~is', '<a href="http://www.\1" target="_blank">www.\1</a>', $string);
  10. $string = preg_replace('~\[url\](.+?)\[/url\]~is', '<a href="\1" target="_blank">\1</a>', $string);
  11. $string = preg_replace('~\[url=(.+?)\](.+?)\[/url\]~is', '<a href="\1" target="_blank">\2</a>', $string);
  12. $string = preg_replace('~\[img\](.+?)\[/img\]~is', '<img src="\1" alt="[image]" style="margin: 5px 0px 5px 0px" />', $string);
  13. $string = preg_replace('~\[img-l\](.+?)\[/img\]~is', '<img src="\1" alt="[image]" style="border: thin solid #DFE5F2; FLOAT: left; MARGIN-RIGHT: 20px" />', $string);
  14. $string = preg_replace('~\[img-r\](.+?)\[/img\]~is', '<img src="\1" alt="[image]" style="border: thin solid #DFE5F2; FLOAT: right; MARGIN-LEFT: 20px;" />', $string);
  15. $string = preg_replace('~\[color=(.+?)\](.+?)\[/color\]~is', '<font color="\1">\2</font>', $string);
  16. $string = preg_replace('~\[left\](.+?)\[/left\]~is', '<div style="text-align:left;">\1</u>', $string);
  17. $string = preg_replace('~\[center\](.+?)\[/center\]~is', '<div style="text-align:center;">\1</u>', $string);
  18. $string = preg_replace('~\[right\](.+?)\[/right\]~is', '<div style="text-align:right;">\1</u>', $string);
  19.  
  20. $string = str_replace(array("[","]","`"),array("&#91;","&#93;","&#96;"),$string);
  21.  
  22. return $string;
  23. ?>

phx:cdata

  • description: Surround content with CDATA without the whitespace
  • usage: [+content:cdata+]
  • added by: Hori
  1. <?php
  2. if (!function_exists('cdata')){
  3. function cdata($inhoud){
  4. $before='<![CDATA[';
  5. $after=']]>';
  6. return $before.$inhoud.$after;
  7. }
  8. }
  9. return cdata($output);
  10. ?>

phx:character_limit

  • description: limits content to specified number of characters (good for news summary)
  • usage: [+content:character_limit=`35`+] - limits characters to 35
  • added by: themancan
  1. <?php
  2. $output_truncated = substr($output, 0, $options);
  3. return $output_truncated;
  4. ?>
  • Improved version by prouve
  1. <?php
  2. if (strlen($output) > $options) {
  3. $output_cutted = substr($output, 0, $options);
  4. $last_space = strrpos($output_cutted, " ");
  5. $output = substr($output_cutted, 0, $last_space) . " [...]";
  6. }
  7. return $output;
  8. ?>

phx:docfield

  • description: get specified field from document (id)
  • usage: [+docid:docfield=`field`+]
  • defaults to pagetitle
  • added by: bwente
  1. <?php
  2. $field = (strlen($options)>0) ? $options : 'pagetitle';
  3. $docfield = $modx->getTemplateVarOutput(array($field), $output, 1);
  4. return $docfield[$field];
  5. ?>

phx:evenodd

  • description: Returns even if even, otherwise odd. Nearly identical to the 'alternateClass' above.
  • usage: [+ditto_iteration:evenodd]. Useful for creating alternate templates in Ditto without needing an additional chunk. For example, class="news_item_[+ditto_iteration:evenodd+]" will return news_item_even or news_item_odd
  • default: Defaults to "odd", as there is no test to ensure the input is an integer.
  • added by: themancan
  1. <?php
  2. if ($output % 2) {
  3. return 'even';
  4. } else {
  5. return 'odd';
  6. }
  7. ?>

phx:firstlast

  • description: Set the number of elements per row. Returns $class_first if it's the first element in a row; $class_last if it's the last.
  • usage: [+ditto_iteration:firstlast=`4`+]. Useful for applying classes to the first or last element per row. Kind of like alternate classes, but suited for multiple rows.
  1. <?php
  2. if (!$options) {
  3. $options = 2;
  4. }
  5. $class_first = 'alpha';
  6. $class_last = 'omega';
  7.  
  8. if (($output % $options) == '0') {
  9. return $class_first;
  10. } elseif (($output % $options) == ($options - 1)) {
  11. return $class_last;
  12. } else {
  13. return;
  14. }
  15. ?>

phx:genitive

  • description: Creates the genitive of a name - appends either ′s or ′
  • usage: [+myname:genitive+] or [+myname:genitive=`endchar|normalchar|otherchar`+]
  • added by: maFF
  1. <?php
  2. /**
  3. * Creates the genitive of a name.
  4. *
  5. * Examples:
  6. * Joe => Joe's
  7. * Mary => Mary's
  8. * Lucas => Lucas'
  9. *
  10. * Usage:
  11. *
  12. * [+myname:genitive+]
  13. * [+myname:genitive=`endchar|normalchar|otherchar`+]
  14. *
  15. */
  16.  
  17. $options = explode('|', $options);
  18. $name = $output;
  19.  
  20. $endchar = (!empty($options[0])) ? $options[0] : 's'; // char a name has to end with to get treated specially
  21. $normalchar = (!empty($options[1])) ? $options[1] : '&prime;s'; // char to append to 'normal' names
  22. $otherchar = (!empty($options[2])) ? $options[2] : '&prime;'; // char to append to names which end with $endchar
  23.  
  24. if(substr($name, -1) == $endchar) $genitive = $name.$otherchar;
  25. else $genitive = $name.$normalchar;
  26.  
  27. return $genitive;
  28. ?>

phx:get

  • description: get value by name from superglobal $_GET array
  • usage: [+phx:get=`name`+]
  1. <?php
  2. return htmlspecialchars($_GET[$options]);
  3. ?>

phx:ifnotempty

  • description: The opposite of the native PHX "isempty" function. Returns the option value ONLY if the input value is empty (excluding whitespace)
  • usage: [+string:ifnotempty=`String to return if not empty`+]
  1. <?php
  2. if (trim($output) != '') {
  3. return $options;
  4. }
  5. ?>

phx:loggedIn

  • usage: [+phx:loggedIn:is=`1`:then=`loggedInString`:else=`notLoggedInString`+]
  1. <?php
  2. /*
  3. * phx:loggedIn */
  4. global $modx;
  5. if(isset ($_SESSION['mgrValidated'])){
  6. return true;
  7. }
  8. else{
  9. return false;
  10. }?>

phx:make_url

  • description: Takes a string and makes it a URL if it's not.
  • example: If a user enters 'www.example.com', but you want to link to that, if you did 'href="www.example.com"' it wouldn't work. Yeah, you should be validating that on the server side anyway, but this modifier is useful in case you can't. It will make "www.example.com" into "http://www.example.com", but won't touch things that start with an http:// or https://
  • usage: [+member_url:make_url+]
  • default: Adds "http://" to the beginning of the string.
  • added by: themancan
  1. <?
  2. if (preg_match('%https?://%i', $output)) {
  3. return $output;
  4. } else {
  5. return 'http://' . $output;
  6. }
  7. ?>

phx:mydate

  • description: Date modified for non-Unix timestamp dates.
  • example: Useful when the date is stored differently, e.g. Friday, May 12, 2008 etc.
  • usage: [+date:mydate=`%d-%m-%Y %H:%M`+]
  • added by Legatissima who found it in the support forum, written by Doze
  1. <?
  2. return strftime($options, strtotime($output));
  3. ?>

phx:nohttp

  • description: Removes the http:// from a URL, to create a display-friendly web address
  • usage: [+string:nohttp+]
  1. <?php
  2. $url = str_replace('http://', '', $output);
  3. return $url;
  4. ?>

phx:ordinal

  • description: Ordinal numbers.
  • usage: [*number:ordinal*]
  • notes: Adds 'st' to 21 to make it the 21st or 'nd' to 132 for 132nd.
  • added by: bwente
  1. <?php
  2. if (!function_exists('ordinal'))
  3. {
  4. function ordinal($cardinal){
  5. $test_c = abs($cardinal) % 10;
  6. $ext = ((abs($cardinal) %100 < 21 && abs($cardinal) %100 > 4) ? 'th'
  7. : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1)
  8. ? 'th' : 'st' : 'nd' : 'rd' : 'th'));
  9. return $cardinal.$ext;
  10. }
  11. }
  12. return ordinal($output);
  13. ?>

phx:outer

  • description: Surround not empty string with text.
  • usage: [+string:outer=`before|after`+]
  • example: Ditto has no outer template, but you can use this [*phx:input=`[!Ditto? &noResults=` `!]`:outer=`<div class="xyz">|</div>`*]
  • added by: Jako
  1. <?php
  2. $options = explode("|", $options);
  3. $outer = '';
  4. if (trim($output) != '') $outer = $options[0].$output.$options[1];
  5. return $outer;
  6. ?>

phx:parent

  • description: get specified document field from parent document (id)
  • usage: [+variable:parent=`field`+]
  • defaults to pagetitle
  1. <?php
  2. $field = (strlen($options)>0) ? $options : 'pagetitle';
  3. $parent = $modx->getParent($output,1,$field);
  4. return $parent[$field];
  5. ?>

phx:parseLinks

  • usage: [+placeholder:parseLinks+]
  1. <?php
  2. /*
  3. * phx:parseLinks
  4. */
  5. $t = $output;
  6. $t = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "<a href=\"\\0\">\\0</a>", $t);
  7. $t = ereg_replace("(^| |\n)(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\">\\2</a>", $t);
  8. return $t;
  9. ?>

phx:phpthumb

  • description: uses phpThumb to resize images
  • see here for more details and download
  • usage:
[+myimage+] contains the full path to the image
[+myimage:phpthumb=`w=450`+]
[+myimage:phpthumb=`w=450&ar=x&fltr{}=gray&fltr{}=rcd|8|1`+]
[+myimage+] contains only the filename
[+myimage:phpthumb=`w=450#[(base_path)]assets/images/`+]
[+myimage+] contains no data referring to the image
[+myimage:phpthumb=`w=450#[(base_path)]assets/images/myimage.jpg#1`+]
  • added by: maFF


phx:post

  • description: get value by name from superglobal $_POST array
  • usage: [+phx:post=`name`+]
  1. <?php
  2. return htmlspecialchars($_POST[$options]);
  3. ?>

phx:price_format

  • description: Formats a number (TV) to a specific format with a specific number of decimals. Useful for allowing users to enter a "price" TV, and making sure you have a consistent XX.YY format, even if they just enter XX.
  • usage: [+product_price:price_format+].
  • default: Defaults to 2 decimal places.
  • added by: themancan
  1. <?
  2. if (!function_exists(format_number)) {
  3. function format_number($str,$decimal_places='2',$decimal_padding="0"){
  4. /* taken from http://us2.php.net/manual/en/function.number-format.php#54799 */
  5. /* firstly format number and shorten any extra decimal places */
  6. /* Note this will round off the number pre-format $str if you dont want this fucntionality */
  7. $str = number_format($str,$decimal_places,'.',''); // will return 12345.67
  8. $number = explode('.',$str);
  9. $number[1] = (isset($number[1]))?$number[1]:''; // to fix the PHP Notice error if str does not contain a decimal placing.
  10. $decimal = str_pad($number[1],$decimal_places,$decimal_padding);
  11. return (float) $number[0].'.'.$decimal;
  12. }
  13. }
  14. return format_number($output);
  15. ?>

phx:rating

  • description: user rating system based on Jot post count
  • usage: [+comment.userpostcount:rating+]


  1. <?php
  2. $defaultValue = " <img src=assets/images/icons/star.png />";
  3. if (intval($output) <= '1') {
  4. $newvalue = '<img src=assets/images/icons/bronze.png />';
  5. }
  6. elseif (intval($output) <= '2') {
  7. $newvalue = '<img src=assets/images/icons/silver.png />';
  8. }
  9. elseif (intval($output) <= '3') {
  10. $newvalue = '<img src=assets/images/icons/gold.png />';
  11. }
  12. else {
  13. $newvalue = $defaultValue;
  14. }
  15. return $newvalue;
  16. ?>


phx:request

  • description: get value by name from superglobal $_REQUEST array
  • usage: [+phx:request=`name`+]
  1. <?php
  2. return htmlspecialchars($_REQUEST[$options]);
  3. ?>

phx:return_domain

  1. <?php
  2. preg_match('%(?:https?://)?(?:www\.)?([^/]*)%i', $output, $matches);
  3. return $matches[1];
  4. ?>

phx:smileys

  • description: Converts text patterns into smiley images.
  • usage: [*content:smileys*]
  • notes: it works with the silk iconset by famfamfam out of the box, if you put the icons into assets/images/smileys. If you want to use other smileys/replacement tags just edit the smileys array.
  • added by: maFF
  1. <?php
  2. $smiley_basepath = $modx->config['base_url'].'assets/images/smileys/';
  3. $smiley_imagetag = '<img src="'.$smiley_basepath.'##smiley##" alt="##text##" title="##text##" />';
  4.  
  5. $smileys = array(
  6. ':grin:' => array( // replace pattern
  7. 'emoticon_evilgrin.png', // file name
  8. ':D'), // text version for alt and title tags
  9. ':smile:' => array(
  10. 'emoticon_happy.png',
  11. ':)'),
  12. ':sad:' => array(
  13. 'emoticon_unhappy.png',
  14. ':('),
  15. ':wink:' => array(
  16. 'emoticon_wink.png',
  17. ';)'),
  18. ':tongue:' => array(
  19. 'emoticon_tongue.png',
  20. ':P'),
  21. ':surprised:' => array(
  22. 'emoticon_surprised.png',
  23. ':O')
  24. );
  25.  
  26. foreach($smileys as $search => $smiley) {
  27. $thistag = $smiley_imagetag;
  28. $thistag = str_replace('##smiley##', $smiley[0], $thistag);
  29. $thistag = str_replace('##text##', $smiley[1], $thistag);
  30. $output = str_replace($search, $thistag, $output);
  31. }
  32. return $output;
  33. ?>

phx:stripsnippet

  • description: Removes cached and uncached snippet in output (usefull in Ditto summarize)
  • usage: [+string:stripsnippet+]
  1. <?php
  2. $string=$output;
  3. $string = preg_replace('~\[\[[^\]]*\]\]~is', '', $string);
  4. $string = preg_replace('~\[\![^!]*\!\]~is', '', $string);
  5. return $string;
  6. ?>

phx:stripparams

  • description: Strips all parameters from an URL, e.g. example.com/page.html?foo=bar&baz=foo becomes example.com/page.html
  • usage: [+url:stripparams+]
  • added by: maff
  1. <?php
  2. $pos = strpos($output, '?');
  3. if($pos !== false) {
  4. $output = substr($output, 0, $pos);
  5. }
  6.  
  7. return $output;
  8. ?>

phx:striptags

  • description: Strips all HTML and PHP tags. You can use the optional parameter to specify tags which should _not_ be stripped
  • usage: [+comment.content:striptags=`<a><img>`+]
  1. <?php
  2. return($modx->stripTags($output, $options));
  3. ?>

phx:thumb

  • description: Similar to maFF's phx:phpthumb but just uses a standard phpThumb installation. Requires phpThumb. I'm adding this in addition to the version above because options are always good, and this method just uses an unmodified version of phpThumb. (It also doesn't use the hashing that maFF's version does, so if you need that, use the above version.)
  • usage: (basically the same as maFF's version)
[+myimage+] contains the full path to the image
[+myimage:phpthumb=`w=450`+]
[+myimage:phpthumb=`w=450&ar=x&fltr{}=gray&fltr{}=rcd|8|1`+]
  • installation: change the path in the code to wherever you like to put your phpThumb. Make sure you make phpThumb's cache directory writable and set phpThumb's config file to how you want it.
  1. <?php
  2. $output = '/assets/snippets/thumb/phpThumb.php?src=' . $output . $options;
  3. return $output;
  4. ?>
  • added by: themancan

phx:timesince

  • description: Converts a unix timestamp into the number of years, months, days, hours, minutes, and optionally seconds from the current time.
  • usage: [+date:timesince+]
  • added by: apoxx
  1. <?php
  2. if (!function_exists('timeSince'))
  3. {
  4. function timeSince($timestamp)
  5. {
  6. if ($timestamp >= time())
  7. {
  8. $timeago = '0 seconds ago.';
  9. return $timeago;
  10. }
  11. $seconds = time()-$timestamp;
  12. $units = array(
  13. 'year' => 31556926,
  14. 'month' => 2629743,
  15. 'day' => 86400,
  16. 'hour' => 3600,
  17. 'minute' => 60,
  18. // 'second' => 1
  19. );
  20. $timeago = '';
  21. foreach ($units as $key => $val)
  22. {
  23. if ($seconds >= $val)
  24. {
  25. $results = floor($seconds/$val);
  26. $seconds = ($seconds-($results*$val));
  27. $timeago .= ($results >= 2) ? $results . ' ' . $key . 's, ' : $results . ' ' . $key . ', ';
  28. }
  29. }
  30. return rtrim($timeago, ', ') . ' ago';
  31. }
  32. }
  33. return timeSince($output);
  34. ?>

phx:textile

  • description: Format content using the textile parser class.
  • usage: [*content:textile*]
  • notes: You need to download Textile and save the class file into assets/snippets/textile (or change the path in the snippet).
  • added by: maFF
  1. <?php
  2. if (!class_exists('Textile')) {
  3. $classTextile = $modx->config["base_path"].'assets/snippets/textile/classTextile.php';
  4. if (file_exists($classTextile)) {
  5. require_once($classTextile);
  6. }
  7. }
  8.  
  9. $textile = new Textile();
  10. $output = $textile->TextileThis($output);
  11. unset($textile);
  12. return $output;
  13. ?>

phx:tv

  • description: get a template variable from any page id
  • usage: [+phx:tv=`<docid>?<templatevar>`+] , where <docid> is the document id (e.g. 25) and <templatevar> is a template variable associated to the given docid.
  • default: if the document id or the template variable don't exist no output is produced
  • added by: natalino
  1. <?php
  2. if(strlen($options )>0) {
  3. $data = explode("?",trim($options),2);
  4. $id= (!empty($data[0]) && is_numeric($data[0])) ? $data[0]: '';
  5. $tv= (!empty($data[1])) ? $data[1]: '';
  6. $result = $modx->getTemplateVar($tv, 'name', $id, 1);
  7. return $result['value'];
  8. }
  9. ?>

example: placing the place of birth from page id 14, as part of the content in page id 22. Place this content while editing page id 22

  1. [+phx:tv=`14?place_of_birth`+]

phx:uri

  • description: takes a string and prepares it to be a part of a valid URI.
  • usage: [+string:uri+]
  1. <?php
  2. return rawurlencode($output);
  3. ?>

phx:url

  • description: takes a document id and creates the corresponding modx link (similar to [~ ~])
  • usage: [*id:url*]
  1. <?php
  2. return $modx->makeUrl($output);
  3. ?>

phx:word_limit

  • description: limits content to specified number of words (good for news summary)
  • usage: [+content:word_limit=`10`+] - limits content to 10 words
  • added by: yentsun
  1. <?php
  2. $retval = $output;
  3. $array = explode(" ", $output);
  4. if (count($array)<=$options)
  5. {
  6. $retval = $output;
  7. }
  8. else
  9. {
  10. array_splice($array,$options);
  11. $retval = implode(" ", $array);
  12. }
  13. return $retval;
  14. ?>

phx:zeropad

  • description: Zero-padding a string. Takes the number of total digits as the input.
  • example: This can be useful when you want to output some kind of ID numbers with fixed digits, or US zip codes: "00001", "00124", "90210"
  • usage: [+ditto_iteration:zeropad=`3`] [*zipcode:zeropad=`5`*]
  • default: No zero-padding.
  • added by: ryanlwh
  1. <?
  2. return sprintf("%0".$options."s",$output);
  3. ?>
Personal tools