├── .gitignore ├── .gitattributes ├── .editorconfig ├── composer.json ├── index.php ├── LICENSE.md ├── README.md ├── composer.lock └── src └── Chopper.php /.gitignore: -------------------------------------------------------------------------------- 1 | # OS files 2 | .DS_Store 3 | 4 | # npm modules 5 | /node_modules 6 | 7 | # Composer files 8 | /vendor -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Note: You need to uncomment the lines you want to use; the other lines can be deleted 2 | 3 | # Git 4 | # .gitattributes export-ignore 5 | # .gitignore export-ignore 6 | 7 | # Tests 8 | # /.coveralls.yml export-ignore 9 | # /.travis.yml export-ignore 10 | # /phpunit.xml.dist export-ignore 11 | # /tests/ export-ignore 12 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # This file is for unifying the coding style for different editors and IDEs 2 | # editorconfig.org 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | end_of_line = lf 9 | insert_final_newline = true 10 | trim_trailing_whitespace = true 11 | 12 | [*.php] 13 | indent_size = 4 14 | 15 | [*.md,*.txt] 16 | trim_trailing_whitespace = false 17 | insert_final_newline = false 18 | 19 | [composer.json] 20 | indent_size = 4 21 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hashandsalt/kirby-chopper", 3 | "description": "Kirby 3 Chopper plugin for truncating text", 4 | "type": "kirby-plugin", 5 | "license": "MIT", 6 | "authors": [ 7 | { 8 | "name": "James Steel", 9 | "email": "hello@hashandsalt.com" 10 | } 11 | ], 12 | "require": { 13 | "getkirby/composer-installer": "^1.1" 14 | }, 15 | "config": { 16 | "optimize-autoloader": true 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /index.php: -------------------------------------------------------------------------------- 1 | 'src/Chopper.php' 5 | ], __DIR__); 6 | 7 | use HashAndSalt\Chopper\Chopper; 8 | 9 | Kirby::plugin('hashandsalt/chopper', [ 10 | 11 | 12 | 'options' => [ 13 | 'ellipsis' => '…', 14 | 'exact' => true, 15 | 'html' => true, 16 | 'trimWidth' => false, 17 | 'keep' => '

', 18 | ], 19 | 20 | 'fieldMethods' => [ 21 | 'chopper' => function ($field, $length = 250, $options = []) { 22 | 23 | $options += [ 24 | 'ellipsis' => option('hashandsalt.chopper.ellipsis'), 'exact' => option('hashandsalt.chopper.exact'), 'html' => option('hashandsalt.chopper.html'), 'trimWidth' => option('hashandsalt.chopper.trimWidth'), 25 | ]; 26 | 27 | $chopper = $field->kt(); 28 | $field = Chopper::truncate($chopper, $length, $options); 29 | 30 | $field = strip_tags($field, option('hashandsalt.chopper.keep')); 31 | 32 | return $field; 33 | } 34 | ] 35 | 36 | ]); 37 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Hash&Salt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kirby Chopper Plugin for Kirby 3 2 | 3 | Kirby's built in [Excerpt](https://getkirby.com/docs/reference/templates/field-methods/excerpt) takes an all or nothing approach to stripping html tags, and only works on characters. This plugin creates excerpts from fields via KirbyText but keeps any HTML tags, with the ability to define the tags you wish to keep. Also works on whole words, as well as characters. 4 | 5 | 6 | ## Commerical Usage 7 | 8 | This plugin is free but if you use it in a commercial project please consider to 9 | - [make a donation 🍻](https://paypal.me/hashandsalt?locale.x=en_GB) or 10 | - [buy a Kirby license using this affiliate link](https://a.paddle.com/v2/click/1129/36141?link=1170) 11 | 12 | 13 | ## Installation 14 | 15 | ### Manual 16 | 17 | To use this plugin, place all the files in `site/plugins/chopper/`. 18 | 19 | ### Composer 20 | 21 | ``` 22 | composer require hashandsalt/kirby-chopper 23 | ``` 24 | 25 | ## Usage 26 | 27 | Defaults to limiting to 250 charchters, maintaining whole words, so if you just want 20 words and an ellipsis on the end: 28 | 29 | ``` 30 | yourtextfield()->chopper() ?> 31 | ``` 32 | 33 | To set number of charachters to trim to 34 | 35 | ``` 36 | yourtextfield()->chopper(100) ?> 37 | ``` 38 | 39 | To trim to 50 charachters, maintaining whole words, append an arrow on the on the end: 40 | 41 | ``` 42 | yourtextfield()->chopper(50, ['ellipsis', '→']) ?> 43 | ``` 44 | 45 | To change the default list of kept tags, add this line to your `config.php` and amend accordingly: 46 | 47 | ``` 48 | 'hashandsalt.chopper.keep' => '

', 49 | ``` 50 | 51 | To append every time an arrow at the end, add this line to your `config.php`: 52 | 53 | ``` 54 | 'hashandsalt.chopper.ellipsis' => '→', 55 | ``` 56 | 57 | ## Options 58 | 59 | Full list of options 60 | 61 | ``` 62 | 'hashandsalt.chopper.ellipsis' => '…', 63 | 'hashandsalt.chopper.exact' => true, 64 | 'hashandsalt.chopper.html' => true, 65 | 'hashandsalt.chopper.trimWidth' => false, 66 | 'hashandsalt.chopper.keep' => '

', 67 | ``` 68 | 69 | 70 | ## Requirements 71 | 72 | This plugin was built using Kirby 3.6. Will not work on earlier versions. Requires PHP 7.4+ 73 | 74 | 75 | ## Credits 76 | Based on text functions in CakePHP https://cakephp.org/ 77 | -------------------------------------------------------------------------------- /composer.lock: -------------------------------------------------------------------------------- 1 | { 2 | "_readme": [ 3 | "This file locks the dependencies of your project to a known state", 4 | "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", 5 | "This file is @generated automatically" 6 | ], 7 | "content-hash": "b4d607baa73f9c6a2f59c6b81e430980", 8 | "packages": [ 9 | { 10 | "name": "getkirby/composer-installer", 11 | "version": "1.2.1", 12 | "source": { 13 | "type": "git", 14 | "url": "https://github.com/getkirby/composer-installer.git", 15 | "reference": "c98ece30bfba45be7ce457e1102d1b169d922f3d" 16 | }, 17 | "dist": { 18 | "type": "zip", 19 | "url": "https://api.github.com/repos/getkirby/composer-installer/zipball/c98ece30bfba45be7ce457e1102d1b169d922f3d", 20 | "reference": "c98ece30bfba45be7ce457e1102d1b169d922f3d", 21 | "shasum": "" 22 | }, 23 | "require": { 24 | "composer-plugin-api": "^1.0 || ^2.0" 25 | }, 26 | "require-dev": { 27 | "composer/composer": "^1.8 || ^2.0" 28 | }, 29 | "type": "composer-plugin", 30 | "extra": { 31 | "class": "Kirby\\ComposerInstaller\\Plugin" 32 | }, 33 | "autoload": { 34 | "psr-4": { 35 | "Kirby\\": "src/" 36 | } 37 | }, 38 | "notification-url": "https://packagist.org/downloads/", 39 | "license": [ 40 | "MIT" 41 | ], 42 | "description": "Kirby's custom Composer installer for the Kirby CMS and for Kirby plugins", 43 | "homepage": "https://getkirby.com", 44 | "support": { 45 | "issues": "https://github.com/getkirby/composer-installer/issues", 46 | "source": "https://github.com/getkirby/composer-installer/tree/1.2.1" 47 | }, 48 | "funding": [ 49 | { 50 | "url": "https://getkirby.com/buy", 51 | "type": "custom" 52 | } 53 | ], 54 | "time": "2020-12-28T12:54:39+00:00" 55 | } 56 | ], 57 | "packages-dev": [], 58 | "aliases": [], 59 | "minimum-stability": "stable", 60 | "stability-flags": [], 61 | "prefer-stable": false, 62 | "prefer-lowest": false, 63 | "platform": [], 64 | "platform-dev": [], 65 | "plugin-api-version": "2.3.0" 66 | } 67 | -------------------------------------------------------------------------------- /src/Chopper.php: -------------------------------------------------------------------------------- 1 | 26 | */ 27 | protected static $_defaultHtmlNoCount = [ 28 | 'style', 29 | 'script' 30 | ]; 31 | 32 | 33 | /** 34 | * Truncates text. 35 | * 36 | * Cuts a string to the length of $length and replaces the last characters 37 | * with the ellipsis if the text is longer than length. 38 | * 39 | * ### Options: 40 | * 41 | * - `ellipsis` Will be used as ending and appended to the trimmed string 42 | * - `exact` If false, $text will not be cut mid-word 43 | * - `html` If true, HTML tags would be handled correctly 44 | * - `trimWidth` If true, $text will be truncated with the width 45 | * 46 | * @param string $text String to truncate. 47 | * @param int $length Length of returned string, including ellipsis. 48 | * @param array $options An array of HTML attributes and options. 49 | * @return string Trimmed string. 50 | * @link https://book.cakephp.org/4/en/core-libraries/text.html#truncating-text 51 | */ 52 | public static function truncate(string $text, int $length = 100, array $options = []): string 53 | { 54 | $default = [ 55 | 'ellipsis' => '...', 'exact' => true, 'html' => false, 'trimWidth' => false, 56 | ]; 57 | if (!empty($options['html']) && strtolower((string)mb_internal_encoding()) === 'utf-8') { 58 | $default['ellipsis'] = "\xe2\x80\xa6"; 59 | } 60 | $options += $default; 61 | 62 | $prefix = ''; 63 | $suffix = $options['ellipsis']; 64 | 65 | if ($options['html']) { 66 | $ellipsisLength = self::_strlen(strip_tags($options['ellipsis']), $options); 67 | 68 | $truncateLength = 0; 69 | $totalLength = 0; 70 | $openTags = []; 71 | $truncate = ''; 72 | 73 | preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER); 74 | foreach ($tags as $tag) { 75 | $contentLength = 0; 76 | if (!in_array($tag[2], static::$_defaultHtmlNoCount, true)) { 77 | $contentLength = self::_strlen($tag[3], $options); 78 | } 79 | 80 | if ($truncate === '') { 81 | if ( 82 | !preg_match( 83 | '/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/i', 84 | $tag[2] 85 | ) 86 | ) { 87 | if (preg_match('/<[\w]+[^>]*>/', $tag[0])) { 88 | array_unshift($openTags, $tag[2]); 89 | } elseif (preg_match('/<\/([\w]+)[^>]*>/', $tag[0], $closeTag)) { 90 | $pos = array_search($closeTag[1], $openTags, true); 91 | if ($pos !== false) { 92 | array_splice($openTags, $pos, 1); 93 | } 94 | } 95 | } 96 | 97 | $prefix .= $tag[1]; 98 | 99 | if ($totalLength + $contentLength + $ellipsisLength > $length) { 100 | $truncate = $tag[3]; 101 | $truncateLength = $length - $totalLength; 102 | } else { 103 | $prefix .= $tag[3]; 104 | } 105 | } 106 | 107 | $totalLength += $contentLength; 108 | if ($totalLength > $length) { 109 | break; 110 | } 111 | } 112 | 113 | if ($totalLength <= $length) { 114 | return $text; 115 | } 116 | 117 | $text = $truncate; 118 | $length = $truncateLength; 119 | 120 | foreach ($openTags as $tag) { 121 | $suffix .= ''; 122 | } 123 | } else { 124 | if (self::_strlen($text, $options) <= $length) { 125 | return $text; 126 | } 127 | $ellipsisLength = self::_strlen($options['ellipsis'], $options); 128 | } 129 | 130 | $result = self::_substr($text, 0, $length - $ellipsisLength, $options); 131 | 132 | if (!$options['exact']) { 133 | if (self::_substr($text, $length - $ellipsisLength, 1, $options) !== ' ') { 134 | $result = self::_removeLastWord($result); 135 | } 136 | 137 | // If result is empty, then we don't need to count ellipsis in the cut. 138 | if ($result === '') { 139 | $result = self::_substr($text, 0, $length, $options); 140 | } 141 | } 142 | 143 | return $prefix . $result . $suffix; 144 | } 145 | 146 | /** 147 | * Truncate text with specified width. 148 | * 149 | * @param string $text String to truncate. 150 | * @param int $length Length of returned string, including ellipsis. 151 | * @param array $options An array of HTML attributes and options. 152 | * @return string Trimmed string. 153 | * @see \Cake\Utility\Text::truncate() 154 | */ 155 | public static function truncateByWidth(string $text, int $length = 100, array $options = []): string 156 | { 157 | return static::truncate($text, $length, ['trimWidth' => true] + $options); 158 | } 159 | 160 | 161 | /** 162 | * Get string length. 163 | * 164 | * ### Options: 165 | * 166 | * - `html` If true, HTML entities will be handled as decoded characters. 167 | * - `trimWidth` If true, the width will return. 168 | * 169 | * @param string $text The string being checked for length 170 | * @param array $options An array of options. 171 | * @return int 172 | */ 173 | protected static function _strlen(string $text, array $options): int 174 | { 175 | if (empty($options['trimWidth'])) { 176 | $strlen = 'mb_strlen'; 177 | } else { 178 | $strlen = 'mb_strwidth'; 179 | } 180 | 181 | if (empty($options['html'])) { 182 | return $strlen($text); 183 | } 184 | 185 | $pattern = '/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i'; 186 | $replace = preg_replace_callback( 187 | $pattern, 188 | function ($match) use ($strlen) { 189 | $utf8 = html_entity_decode($match[0], ENT_HTML5 | ENT_QUOTES, 'UTF-8'); 190 | 191 | return str_repeat(' ', $strlen($utf8, 'UTF-8')); 192 | }, 193 | $text 194 | ); 195 | 196 | return $strlen($replace); 197 | } 198 | 199 | 200 | 201 | protected static function _substr(string $text, int $start, ?int $length, array $options): string 202 | { 203 | if (empty($options['trimWidth'])) { 204 | $substr = 'mb_substr'; 205 | } else { 206 | $substr = 'mb_strimwidth'; 207 | } 208 | 209 | $maxPosition = self::_strlen($text, ['trimWidth' => false] + $options); 210 | if ($start < 0) { 211 | $start += $maxPosition; 212 | if ($start < 0) { 213 | $start = 0; 214 | } 215 | } 216 | if ($start >= $maxPosition) { 217 | return ''; 218 | } 219 | 220 | if ($length === null) { 221 | $length = self::_strlen($text, $options); 222 | } 223 | 224 | if ($length < 0) { 225 | $text = self::_substr($text, $start, null, $options); 226 | $start = 0; 227 | $length += self::_strlen($text, $options); 228 | } 229 | 230 | if ($length <= 0) { 231 | return ''; 232 | } 233 | 234 | if (empty($options['html'])) { 235 | return (string)$substr($text, $start, $length); 236 | } 237 | 238 | $totalOffset = 0; 239 | $totalLength = 0; 240 | $result = ''; 241 | 242 | $pattern = '/(&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};)/i'; 243 | $parts = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 244 | foreach ($parts as $part) { 245 | $offset = 0; 246 | 247 | if ($totalOffset < $start) { 248 | $len = self::_strlen($part, ['trimWidth' => false] + $options); 249 | if ($totalOffset + $len <= $start) { 250 | $totalOffset += $len; 251 | continue; 252 | } 253 | 254 | $offset = $start - $totalOffset; 255 | $totalOffset = $start; 256 | } 257 | 258 | $len = self::_strlen($part, $options); 259 | if ($offset !== 0 || $totalLength + $len > $length) { 260 | if ( 261 | strpos($part, '&') === 0 262 | && preg_match($pattern, $part) 263 | && $part !== html_entity_decode($part, ENT_HTML5 | ENT_QUOTES, 'UTF-8') 264 | ) { 265 | // Entities cannot be passed substr. 266 | continue; 267 | } 268 | 269 | $part = $substr($part, $offset, $length - $totalLength); 270 | $len = self::_strlen($part, $options); 271 | } 272 | 273 | $result .= $part; 274 | $totalLength += $len; 275 | if ($totalLength >= $length) { 276 | break; 277 | } 278 | } 279 | 280 | return $result; 281 | } 282 | 283 | 284 | /** 285 | * Removes the last word from the input text. 286 | * 287 | * @param string $text The input text 288 | * @return string 289 | */ 290 | protected static function _removeLastWord(string $text): string 291 | { 292 | $spacepos = mb_strrpos($text, ' '); 293 | 294 | if ($spacepos !== false) { 295 | $lastWord = mb_substr($text, $spacepos); 296 | 297 | // Some languages are written without word separation. 298 | // We recognize a string as a word if it doesn't contain any full-width characters. 299 | if (mb_strwidth($lastWord) === mb_strlen($lastWord)) { 300 | $text = mb_substr($text, 0, $spacepos); 301 | } 302 | 303 | return $text; 304 | } 305 | 306 | return ''; 307 | } 308 | 309 | 310 | } 311 | --------------------------------------------------------------------------------