]> git.mxchange.org Git - friendica.git/blob - src/Content/Smilies.php
760bfbce9e331945234a6db05906f78ed01f3081
[friendica.git] / src / Content / Smilies.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Content;
23
24 use Friendica\Core\Hook;
25 use Friendica\DI;
26 use Friendica\Util\Strings;
27
28 /**
29  * This class contains functions to handle smiles
30  */
31
32 class Smilies
33 {
34         /**
35          * Replaces/adds the emoticon list
36          *
37          * This function should be used whenever emoticons are added
38          *
39          * @param array  $b              Array of emoticons
40          * @param string $smiley         The text smilie
41          * @param string $representation The replacement
42          * @return void
43          */
44         public static function add(array &$b, string $smiley, string $representation)
45         {
46                 $found = array_search($smiley, $b['texts']);
47
48                 if (!is_int($found)) {
49                         $b['texts'][] = $smiley;
50                         $b['icons'][] = $representation;
51                 } else {
52                         $b['icons'][$found] = $representation;
53                 }
54         }
55
56         /**
57          * Function to list all smilies
58          *
59          * Get an array of all smilies, both internal and from addons.
60          *
61          * @return array
62          *    'texts' => smilie shortcut
63          *    'icons' => icon in html
64          *
65          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
66          * @hook  smilie ('texts' => smilies texts array, 'icons' => smilies html array)
67          */
68         public static function getList(): array
69         {
70                 $texts =  [
71                         '&lt;3',
72                         '&lt;/3',
73                         '&lt;\\3',
74                         ':-)',
75                         ';-)',
76                         ':-(',
77                         ':-P',
78                         ':-p',
79                         ':-"',
80                         ':-&quot;',
81                         ':-x',
82                         ':-X',
83                         ':-D',
84                         '8-|',
85                         '8-O',
86                         ':-O',
87                         '\\o/',
88                         'o.O',
89                         'O.o',
90                         'o_O',
91                         'O_o',
92                         ":'(",
93                         ":-!",
94                         ":-/",
95                         ":-[",
96                         "8-)",
97                         ':beer',
98                         ':homebrew',
99                         ':coffee',
100                         ':facepalm',
101                         ':like',
102                         ':dislike',
103                         '~friendica',
104                         'red#',
105                         'red#matrix'
106
107                 ];
108
109                 $baseUrl = (string)DI::baseUrl();
110
111                 $icons = [
112                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-heart.gif" alt="&lt;3" title="&lt;3" />',
113                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-brokenheart.gif" alt="&lt;/3" title="&lt;/3" />',
114                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-brokenheart.gif" alt="&lt;\\3" title="&lt;\\3" />',
115                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-smile.gif" alt=":-)" title=":-)" />',
116                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-wink.gif" alt=";-)" title=";-)" />',
117                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-frown.gif" alt=":-(" title=":-(" />',
118                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-tongue-out.gif" alt=":-P" title=":-P" />',
119                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-tongue-out.gif" alt=":-p" title=":-P" />',
120                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-kiss.gif" alt=":-\" title=":-\" />',
121                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-kiss.gif" alt=":-\" title=":-\" />',
122                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-kiss.gif" alt=":-x" title=":-x" />',
123                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-kiss.gif" alt=":-X" title=":-X" />',
124                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-laughing.gif" alt=":-D" title=":-D"  />',
125                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-surprised.gif" alt="8-|" title="8-|" />',
126                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-surprised.gif" alt="8-O" title="8-O" />',
127                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-surprised.gif" alt=":-O" title="8-O" />',
128                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-thumbsup.gif" alt="\\o/" title="\\o/" />',
129                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-Oo.gif" alt="o.O" title="o.O" />',
130                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-Oo.gif" alt="O.o" title="O.o" />',
131                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-Oo.gif" alt="o_O" title="o_O" />',
132                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-Oo.gif" alt="O_o" title="O_o" />',
133                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-cry.gif" alt=":\'(" title=":\'("/>',
134                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-foot-in-mouth.gif" alt=":-!" title=":-!" />',
135                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-undecided.gif" alt=":-/" title=":-/" />',
136                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-embarrassed.gif" alt=":-[" title=":-[" />',
137                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-cool.gif" alt="8-)" title="8-)" />',
138                 '<img class="smiley" src="' . $baseUrl . '/images/beer_mug.gif" alt=":beer" title=":beer" />',
139                 '<img class="smiley" src="' . $baseUrl . '/images/beer_mug.gif" alt=":homebrew" title=":homebrew" />',
140                 '<img class="smiley" src="' . $baseUrl . '/images/coffee.gif" alt=":coffee" title=":coffee" />',
141                 '<img class="smiley" src="' . $baseUrl . '/images/smiley-facepalm.gif" alt=":facepalm" title=":facepalm" />',
142                 '<img class="smiley" src="' . $baseUrl . '/images/like.gif" alt=":like" title=":like" />',
143                 '<img class="smiley" src="' . $baseUrl . '/images/dislike.gif" alt=":dislike" title=":dislike" />',
144                 '<a href="https://friendi.ca">~friendica <img class="smiley" width="16" height="16" src="' . $baseUrl . '/images/friendica.svg" alt="~friendica" title="~friendica" /></a>',
145                 '<a href="http://redmatrix.me/">red<img class="smiley" src="' . $baseUrl . '/images/rm-16.png" alt="red#" title="red#" />matrix</a>',
146                 '<a href="http://redmatrix.me/">red<img class="smiley" src="' . $baseUrl . '/images/rm-16.png" alt="red#matrix" title="red#matrix" />matrix</a>'
147                 ];
148
149                 $params = ['texts' => $texts, 'icons' => $icons];
150                 Hook::callAll('smilie', $params);
151
152                 return $params;
153         }
154
155         /**
156          * Finds all used smilies (like :heart: or :p) in the provided text.
157          *
158          * @param string $text that might contain smilie usages (denoted by a starting colon)
159          * @param bool   $extract_url whether to further extract image urls
160          * @return array with smilie codes (colon included) as the keys, the smilie images as values
161          */
162         public static function extractUsedSmilies(string $text, bool $extract_url = false): array
163         {
164                 $emojis = [];
165
166                 $smilies = self::getList();
167                 $icons = $smilies['icons'];
168                 foreach ($smilies['texts'] as $i => $name) {
169                         if (strstr($text, $name)) {
170                                 $image = $icons[$i];
171                                 if ($extract_url) {
172                                         if (preg_match('/src="(.+?)"/', $image, $match)) {
173                                                 $image = $match[1];
174                                         } else {
175                                                 continue;
176                                         }
177                                 }
178                                 $emojis[$name] = $image;
179                         }
180                 }
181                 return $emojis;
182         }
183
184         /**
185          * Copied from http://php.net/manual/en/function.str-replace.php#88569
186          * Modified for camel caps: renamed stro_replace -> strOrigReplace
187          *
188          * When using str_replace(...), values that did not exist in the original string (but were put there by previous
189          * replacements) will be replaced continuously.  This string replacement function is designed to replace the values
190          * in $search with those in $replace while not factoring in prior replacements.  Note that this function will
191          * always look for the longest possible match first and then work its way down to individual characters.
192          *
193          * @param array $search list of strings or characters that need to be replaced
194          * @param array $replace list of strings or characters that will replace the corresponding values in $search
195          * @param string $subject the string on which this operation is being performed
196          *
197          * @return string $subject with all substrings in the $search array replaced by the values in the $replace array
198          */
199         private static function strOrigReplace(array $search, array $replace, string $subject): string
200         {
201                 return strtr($subject, array_combine($search, $replace));
202         }
203
204         /**
205          * Replaces text emoticons with graphical images
206          *
207          * It is expected that this function will be called using HTML text.
208          * We will escape text between HTML pre and code blocks from being
209          * processed.
210          *
211          * At a higher level, the bbcode [nosmile] tag can be used to prevent this
212          * function from being executed by the prepare_text() routine when preparing
213          * bbcode source for HTML display
214          *
215          * @param string  $s         Text that should be replaced
216          * @param boolean $no_images Only replace emoticons without images
217          *
218          * @return string HTML Output of the Smilie
219          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
220          */
221         public static function replace(string $s, bool $no_images = false): string
222         {
223                 $smilies = self::getList();
224
225                 $s = self::replaceFromArray($s, $smilies, $no_images);
226
227                 return $s;
228         }
229
230         /**
231          * Replaces emoji shortcodes in a string from a structured array of searches and replaces.
232          *
233          * Depends on system.no_smilies config value, skips <pre> and <code> tags.
234          *
235          * @param string $text      An HTML string
236          * @param array  $smilies   An string replacement array with the following structure: ['texts' => [], 'icons' => []]
237          * @param bool   $no_images Only replace shortcodes without image replacement (e.g. Unicode characters)
238          * @return string
239          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
240          */
241         public static function replaceFromArray(string $text, array $smilies, bool $no_images = false): string
242         {
243                 if (intval(DI::config()->get('system', 'no_smilies'))
244                         || (DI::userSession()->getLocalUserId() && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'no_smilies')))
245                 ) {
246                         return $text;
247                 }
248
249                 $text = preg_replace_callback('/<(pre)>(.*?)<\/pre>/ism', [self::class, 'encode'], $text);
250                 $text = preg_replace_callback('/<(code)>(.*?)<\/code>/ism', [self::class, 'encode'], $text);
251
252                 if ($no_images) {
253                         $cleaned = ['texts' => [], 'icons' => []];
254                         $icons = $smilies['icons'];
255                         foreach ($icons as $key => $icon) {
256                                 if (!strstr($icon, '<img ')) {
257                                         $cleaned['texts'][] = $smilies['texts'][$key];
258                                         $cleaned['icons'][] = $smilies['icons'][$key];
259                                 }
260                         }
261                         $smilies = $cleaned;
262                 }
263
264                 $text = preg_replace_callback('/&lt;(3+)/', [self::class, 'heartReplaceCallback'], $text);
265                 $text = self::strOrigReplace($smilies['texts'], $smilies['icons'], $text);
266
267                 $text = preg_replace_callback('/<(code)>(.*?)<\/code>/ism', [self::class, 'decode'], $text);
268                 $text = preg_replace_callback('/<(pre)>(.*?)<\/pre>/ism', [self::class, 'decode'], $text);
269
270                 return $text;
271         }
272
273         /**
274          * Encodes smiley match array to BASE64 string
275          *
276          * @param array $m Match array
277          * @return string base64 encoded string
278          */
279         private static function encode(array $m): string
280         {
281                 return '<' . $m[1] . '>' . Strings::base64UrlEncode($m[2]) . '</' . $m[1] . '>';
282         }
283
284         /**
285          * Decodes a previously BASE64-encoded match array to a string
286          *
287          * @param array $m Matches array
288          * @return string base64 decoded string
289          * @throws \Exception
290          */
291         private static function decode(array $m): string
292         {
293                 return '<' . $m[1] . '>' . Strings::base64UrlDecode($m[2]) . '</' . $m[1] . '>';
294         }
295
296
297         /**
298          * expand <3333 to the correct number of hearts
299          *
300          * @param array $matches
301          * @return string HTML Output
302          */
303         private static function heartReplaceCallback(array $matches): string
304         {
305                 if (strlen($matches[1]) == 1) {
306                         return $matches[0];
307                 }
308
309                 $t = '';
310                 for ($cnt = 0; $cnt < strlen($matches[1]); $cnt ++) {
311                         $t .= '❤';
312                 }
313
314                 return str_replace($matches[0], $t, $matches[0]);
315         }
316
317         /**
318          * Checks if the body doesn't contain any alphanumeric characters
319          *
320          * @param string $body Possibly-HTML post body
321          * @return boolean
322          */
323         public static function isEmojiPost(string $body): bool
324         {
325                 // Strips all whitespace
326                 $conv = preg_replace('#\s#u', '', html_entity_decode($body));
327                 if (empty($conv)) {
328                         return false;
329                 }
330
331                 if (!class_exists('IntlChar')) {
332                         // Most Emojis are 4 byte Unicode characters, so this is a good workaround, when IntlChar does not exist on the system
333                         return strlen($conv) / mb_strlen($conv) == 4;
334                 }
335
336                 for ($i = 0; $i < mb_strlen($conv); $i++) {
337                         $character = mb_substr($conv, $i, 1);
338
339                         if (\IntlChar::isalnum($character) || \IntlChar::ispunct($character) || \IntlChar::isgraph($character) && (strlen($character) <= 2)) {
340                                 return false;
341                         }
342                 }
343                 return true;
344         }
345 }