Link.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. <?php
  2. declare(strict_types = 1);
  3. // {{{ License
  4. // This file is part of GNU social - https://www.gnu.org/software/social
  5. //
  6. // GNU social is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // GNU social is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  18. // }}}
  19. namespace Component\Link;
  20. use App\Core\DB\DB;
  21. use App\Core\Event;
  22. use App\Core\Modules\Component;
  23. use App\Entity\Actor;
  24. use App\Entity\Note;
  25. use App\Util\Common;
  26. use App\Util\HTML;
  27. use Component\Link\Entity\NoteToLink;
  28. use InvalidArgumentException;
  29. class Link extends Component
  30. {
  31. /**
  32. * Extract URLs from $content and create the appropriate Link and NoteToLink entities
  33. */
  34. public function onProcessNoteContent(Note $note, string $content, string $content_type, array $process_note_content_extra_args = []): bool
  35. {
  36. $ignore = $process_note_content_extra_args['ignoreLinks'] ?? [];
  37. if (Common::config('attachments', 'process_links')) {
  38. $matched_urls = [];
  39. preg_match_all($this->getURLRegex(), $content, $matched_urls);
  40. $matched_urls = array_unique($matched_urls[1]);
  41. foreach ($matched_urls as $match) {
  42. if (\in_array($match, $ignore)) {
  43. continue;
  44. }
  45. try {
  46. $link_id = Entity\Link::getOrCreate($match)->getId();
  47. DB::persist(NoteToLink::create(['link_id' => $link_id, 'note_id' => $note->getId()]));
  48. } catch (InvalidArgumentException) {
  49. continue;
  50. }
  51. }
  52. }
  53. return Event::next;
  54. }
  55. public function onRenderPlainTextNoteContent(string &$text): bool
  56. {
  57. $text = $this->replaceURLs($text);
  58. return Event::next;
  59. }
  60. public function getURLRegex(): string
  61. {
  62. $geouri_labeltext_regex = '\pN\pL\-';
  63. $geouri_mark_regex = '\-\_\.\!\~\*\\\'\(\)'; // the \\\' is really pretty
  64. $geouri_unreserved_regex = '\pN\pL' . $geouri_mark_regex;
  65. $geouri_punreserved_regex = '\[\]\:\&\+\$';
  66. $geouri_pctencoded_regex = '(?:\%[0-9a-fA-F][0-9a-fA-F])';
  67. $geouri_paramchar_regex = $geouri_unreserved_regex . $geouri_punreserved_regex; //FIXME: add $geouri_pctencoded_regex here so it works
  68. return '#'
  69. . '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'
  70. . '('
  71. . '(?:'
  72. . '(?:' //Known protocols
  73. . '(?:'
  74. . '(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_COLON_DOUBLE_SLASH)) . ')://)'
  75. . '|'
  76. . '(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_SINGLE_COLON)) . '):)'
  77. . ')'
  78. . '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?' //user:pass@
  79. . '(?:'
  80. . '(?:'
  81. . '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]' //[dns]
  82. . ')|(?:'
  83. . '[\pN\pL\-\_\:\.]+(?<![\.\:])' //dns
  84. . ')'
  85. . ')'
  86. . ')'
  87. . '|(?:'
  88. . '(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_COLON_COORDINATES)) . '):'
  89. // There's an order that must be followed here too, if ;crs= is used, it must precede ;u=
  90. // Also 'crsp' (;crs=$crsp) must match $geouri_labeltext_regex
  91. // Also 'uval' (;u=$uval) must be a pnum: \-?[0-9]+
  92. . '(?:'
  93. . '(?:[0-9]+(?:\.[0-9]+)?(?:\,[0-9]+(?:\.[0-9]+)?){1,2})' // 1(.23)?(,4(.56)){1,2}
  94. . '(?:\;(?:[' . $geouri_labeltext_regex . ']+)(?:\=[' . $geouri_paramchar_regex . ']+)*)*'
  95. . ')'
  96. . ')'
  97. // URLs without domain name, like magnet:?xt=...
  98. . '|(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_NO_DOMAIN)) . '):(?=\?))' // zero-length lookahead requires ? after :
  99. . (Common::config('linkify', 'ipv4') // Convert IPv4 addresses to hyperlinks
  100. ? '|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
  101. : '')
  102. . (Common::config('linkify', 'ipv6') // Convert IPv6 addresses to hyperlinks
  103. ? '|(?:' //IPv6
  104. . '\[?(?:(?:(?:[0-9A-Fa-f]{1,4}:){7}(?:(?:[0-9A-Fa-f]{1,4})|:))|(?:(?:[0-9A-Fa-f]{1,4}:){6}(?::|(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})|(?::[0-9A-Fa-f]{1,4})))|(?:(?:[0-9A-Fa-f]{1,4}:){5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){4}(?::[0-9A-Fa-f]{1,4}){0,1}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){3}(?::[0-9A-Fa-f]{1,4}){0,2}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){2}(?::[0-9A-Fa-f]{1,4}){0,3}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:)(?::[0-9A-Fa-f]{1,4}){0,4}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?::(?::[0-9A-Fa-f]{1,4}){0,5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))\]?(?<!:)'
  105. . ')'
  106. : '')
  107. . (Common::config('linkify', 'bare_domains')
  108. ? '|(?:' //DNS
  109. . '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?' //user:pass@
  110. . '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'
  111. //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
  112. . '(?:AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|ASIA|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|HU|ID|IE|IL|IM|IN|INFO|INT|IO|IQ|IR|IS|IT|JE|JM|JO|JOBS|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MUSEUM|MV|MW|MX|MY|MZ|NA|NAME|NC|NE|NET|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|ORG|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PRO|PS|PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TEL|TF|TG|TH|TJ|TK|TL|TM|TN|TO|TP|TR|TRAVEL|TT|TV|TW|TZ|UA|UG|UK|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|WF|WS|XN--0ZWM56D|测试|XN--11B5BS3A9AJ6G|परीक्षा|XN--80AKHBYKNJ4F|испытание|XN--9T4B11YI5A|테스트|XN--DEBA0AD|טעסט|XN--G6W251D|測試|XN--HGBK6AJ7F53BBA|آزمایشی|XN--HLCJ6AYA9ESC7A|பரிட்சை|XN--JXALPDLP|δοκιμή|XN--KGBECHTV|إختبار|XN--ZCKZAH|テスト|YE|YT|YU|ZA|ZM|ZONE|ZW|local|loc|onion)'
  113. . ')(?![\pN\pL\-\_])'
  114. : '') // if common_config('linkify', 'bare_domains') is false, don't add anything here
  115. . ')'
  116. . '(?:'
  117. . '(?:\:\d+)?' //:port
  118. . '(?:/[' . URL_REGEX_VALID_PATH_CHARS . ']*)?' // path
  119. . '(?:\?[' . URL_REGEX_VALID_QSTRING_CHARS . ']*)?' // ?query string
  120. . '(?:\#[' . URL_REGEX_VALID_FRAGMENT_CHARS . ']*)?' // #fragment
  121. . ')(?<![' . URL_REGEX_EXCLUDED_END_CHARS . '])'
  122. . ')'
  123. . '#ixu';
  124. }
  125. public const URL_SCHEME_COLON_DOUBLE_SLASH = 1;
  126. public const URL_SCHEME_SINGLE_COLON = 2;
  127. public const URL_SCHEME_NO_DOMAIN = 4;
  128. public const URL_SCHEME_COLON_COORDINATES = 8;
  129. public function URLSchemes($filter = null)
  130. {
  131. // TODO: move these to config
  132. $schemes = [
  133. 'http' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  134. 'https' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  135. 'ftp' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  136. 'ftps' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  137. 'mms' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  138. 'rtsp' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  139. 'gopher' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  140. 'news' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  141. 'nntp' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  142. 'telnet' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  143. 'wais' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  144. 'file' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  145. 'prospero' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  146. 'webcal' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  147. 'irc' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  148. 'ircs' => self::URL_SCHEME_COLON_DOUBLE_SLASH,
  149. 'aim' => self::URL_SCHEME_SINGLE_COLON,
  150. 'bitcoin' => self::URL_SCHEME_SINGLE_COLON,
  151. 'fax' => self::URL_SCHEME_SINGLE_COLON,
  152. 'jabber' => self::URL_SCHEME_SINGLE_COLON,
  153. 'mailto' => self::URL_SCHEME_SINGLE_COLON,
  154. 'tel' => self::URL_SCHEME_SINGLE_COLON,
  155. 'xmpp' => self::URL_SCHEME_SINGLE_COLON,
  156. 'magnet' => self::URL_SCHEME_NO_DOMAIN,
  157. 'geo' => self::URL_SCHEME_COLON_COORDINATES,
  158. ];
  159. return array_keys(array_filter($schemes, fn ($scheme) => \is_null($filter) || ($scheme & $filter)));
  160. }
  161. /**
  162. * Find links in the given text and pass them to the given callback function.
  163. */
  164. public function replaceURLs(string $text): string
  165. {
  166. $regex = $this->getURLRegex();
  167. return preg_replace_callback($regex, fn ($matches) => $this->callbackHelper($matches, [$this, 'linkify']), $text);
  168. }
  169. /**
  170. * Intermediate callback for `replaceURLs()`, which helps resolve some
  171. * ambiguous link forms before passing on to the final callback.
  172. *
  173. * @param callable(string $text): string $callback: return replacement text
  174. */
  175. private function callbackHelper(array $matches, callable $callback): string
  176. {
  177. $url = $matches[1];
  178. $left = mb_strpos($matches[0], $url);
  179. $right = $left + mb_strlen($url);
  180. $groupSymbolSets = [
  181. [
  182. 'left' => '(',
  183. 'right' => ')',
  184. ],
  185. [
  186. 'left' => '[',
  187. 'right' => ']',
  188. ],
  189. [
  190. 'left' => '{',
  191. 'right' => '}',
  192. ],
  193. [
  194. 'left' => '<',
  195. 'right' => '>',
  196. ],
  197. ];
  198. $cannotEndWith = ['.', '?', ',', '#'];
  199. do {
  200. $original_url = $url;
  201. foreach ($groupSymbolSets as $groupSymbolSet) {
  202. if (mb_substr($url, -1) == $groupSymbolSet['right']) {
  203. $group_left_count = mb_substr_count($url, $groupSymbolSet['left']);
  204. $group_right_count = mb_substr_count($url, $groupSymbolSet['right']);
  205. if ($group_left_count < $group_right_count) {
  206. --$right;
  207. $url = mb_substr($url, 0, -1);
  208. }
  209. }
  210. }
  211. if (\in_array(mb_substr($url, -1), $cannotEndWith)) {
  212. --$right;
  213. $url = mb_substr($url, 0, -1);
  214. }
  215. } while ($original_url != $url);
  216. $result = $callback($url);
  217. return mb_substr($matches[0], 0, $left) . $result . mb_substr($matches[0], $right);
  218. }
  219. /**
  220. * Convert a plain text $url to HTML <a>
  221. */
  222. public function linkify(string $url): string
  223. {
  224. // It comes in special'd, so we unspecial it before passing to the stringifying
  225. // functions
  226. $url = htmlspecialchars_decode($url);
  227. if (str_contains($url, '@') && !str_contains($url, ':') && ($email = filter_var($url, \FILTER_VALIDATE_EMAIL)) !== false) {
  228. //url is an email address without the mailto: protocol
  229. $url = "mailto:{$email}";
  230. }
  231. $attrs = ['href' => $url, 'title' => $url];
  232. // TODO Check to see whether this is a known "attachment" URL.
  233. // Whether to nofollow
  234. $nf = Common::config('nofollow', 'external');
  235. if ($nf == 'never') {
  236. $attrs['rel'] = 'external';
  237. } else {
  238. $attrs['rel'] = 'noopener nofollow external noreferrer';
  239. }
  240. return HTML::html(['a' => ['attrs' => $attrs, $url]], options: ['indent' => false]);
  241. }
  242. public function onNoteDeleteRelated(Note &$note, Actor $actor): bool
  243. {
  244. DB::wrapInTransaction(fn () => NoteToLink::removeWhereNoteId($note->getId()));
  245. return Event::next;
  246. }
  247. }