]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/bookmark/LinkUtils.php
Apply PHP Code Beautifier on source code for linter automatic fixes
[github/shaarli/Shaarli.git] / application / bookmark / LinkUtils.php
CommitLineData
1557cefb
A
1<?php
2
336a28fa 3use Shaarli\Bookmark\Bookmark;
f24896b2 4
1557cefb 5/**
d65342e3 6 * Extract title from an HTML document.
1557cefb 7 *
d65342e3 8 * @param string $html HTML content where to look for a title.
1557cefb 9 *
d65342e3 10 * @return bool|string Extracted title if found, false otherwise.
1557cefb 11 */
d65342e3 12function html_extract_title($html)
1557cefb 13{
d65342e3
A
14 if (preg_match('!<title.*?>(.*?)</title>!is', $html, $matches)) {
15 return trim(str_replace("\n", '', $matches[1]));
1557cefb 16 }
d65342e3 17 return false;
1557cefb
A
18}
19
20/**
d65342e3 21 * Extract charset from HTTP header if it's defined.
1557cefb 22 *
d65342e3 23 * @param string $header HTTP header Content-Type line.
1557cefb
A
24 *
25 * @return bool|string Charset string if found (lowercase), false otherwise.
26 */
d65342e3 27function header_extract_charset($header)
1557cefb 28{
1ea09a1b 29 preg_match('/charset=["\']?([^; "\']+)/i', $header, $match);
d65342e3
A
30 if (! empty($match[1])) {
31 return strtolower(trim($match[1]));
1557cefb
A
32 }
33
34 return false;
35}
36
37/**
38 * Extract charset HTML content (tag <meta charset>).
39 *
40 * @param string $html HTML content where to look for charset.
41 *
42 * @return bool|string Charset string if found, false otherwise.
43 */
44function html_extract_charset($html)
45{
46 // Get encoding specified in HTML header.
ce7b0b64 47 preg_match('#<meta .*charset=["\']?([^";\'>/]+)["\']? */?>#Usi', $html, $enc);
1557cefb
A
48 if (!empty($enc[1])) {
49 return strtolower($enc[1]);
50 }
51
52 return false;
53}
141a86c5 54
6a487252
A
55/**
56 * Extract meta tag from HTML content in either:
57 * - OpenGraph: <meta property="og:[tag]" ...>
58 * - Meta tag: <meta name="[tag]" ...>
59 *
60 * @param string $tag Name of the tag to retrieve.
61 * @param string $html HTML content where to look for charset.
62 *
63 * @return bool|string Charset string if found, false otherwise.
64 */
65function html_extract_tag($tag, $html)
66{
67 $propertiesKey = ['property', 'name', 'itemprop'];
68 $properties = implode('|', $propertiesKey);
2cd0509b 69 // We need a OR here to accept either 'property=og:noquote' or 'property="og:unrelated og:my-tag"'
53054b2b 70 $orCondition = '["\']?(?:og:)?' . $tag . '["\']?|["\'][^\'"]*?(?:og:)?' . $tag . '[^\'"]*?[\'"]';
00d3dd91 71 // Try to retrieve OpenGraph tag.
53054b2b 72 $ogRegex = '#<meta[^>]+(?:' . $properties . ')=(?:' . $orCondition . ')[^>]*content=(["\'])([^\1]*?)\1.*?>#';
6a487252
A
73 // If the attributes are not in the order property => content (e.g. Github)
74 // New regex to keep this readable... more or less.
53054b2b 75 $ogRegexReverse = '#<meta[^>]+content=(["\'])([^\1]*?)\1[^>]+(?:' . $properties . ')=(?:' . $orCondition . ').*?>#';
6a487252 76
53054b2b
A
77 if (
78 preg_match($ogRegex, $html, $matches) > 0
6a487252
A
79 || preg_match($ogRegexReverse, $html, $matches) > 0
80 ) {
00d3dd91 81 return $matches[2];
6a487252
A
82 }
83
84 return false;
85}
86
141a86c5 87/**
336a28fa 88 * In a string, converts URLs to clickable bookmarks.
9ccca401
A
89 *
90 * @param string $text input string.
9ccca401 91 *
336a28fa 92 * @return string returns $text with all bookmarks converted to HTML bookmarks.
9ccca401
A
93 *
94 * @see Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
95 */
520d2957 96function text2clickable($text)
9ccca401 97{
601faf97 98 $regex = '!(((?:https?|ftp|file)://|apt:|magnet:)\S+[a-z0-9\(\)]/?)!si';
520d2957 99 return preg_replace($regex, '<a href="$1">$1</a>', $text);
9ccca401
A
100}
101
102/**
103 * Auto-link hashtags.
104 *
105 * @param string $description Given description.
106 * @param string $indexUrl Root URL.
107 *
108 * @return string Description with auto-linked hashtags.
109 */
110function hashtag_autolink($description, $indexUrl = '')
111{
112 /*
113 * To support unicode: http://stackoverflow.com/a/35498078/1484919
114 * \p{Pc} - to match underscore
115 * \p{N} - numeric character in any script
116 * \p{L} - letter from any language
117 * \p{Mn} - any non marking space (accents, umlauts, etc)
118 */
119 $regex = '/(^|\s)#([\p{Pc}\p{N}\p{L}\p{Mn}]+)/mui';
53054b2b 120 $replacement = '$1<a href="' . $indexUrl . './add-tag/$2" title="Hashtag $2">#$2</a>';
9ccca401
A
121 return preg_replace($regex, $replacement, $description);
122}
123
124/**
125 * This function inserts &nbsp; where relevant so that multiple spaces are properly displayed in HTML
126 * even in the absence of <pre> (This is used in description to keep text formatting).
127 *
128 * @param string $text input text.
129 *
130 * @return string formatted text.
131 */
132function space2nbsp($text)
133{
134 return preg_replace('/(^| ) /m', '$1&nbsp;', $text);
135}
136
137/**
138 * Format Shaarli's description
139 *
140 * @param string $description shaare's description.
7af9a418 141 * @param string $indexUrl URL to Shaarli's index.
740b32b5
A
142 * @param bool $autolink Turn on/off automatic linkifications of URLs and hashtags
143 *
9ccca401
A
144 * @return string formatted description.
145 */
740b32b5 146function format_description($description, $indexUrl = '', $autolink = true)
f211e417 147{
740b32b5
A
148 if ($autolink) {
149 $description = hashtag_autolink(text2clickable($description), $indexUrl);
150 }
151
152 return nl2br(space2nbsp($description));
9ccca401 153}
d592daea
A
154
155/**
156 * Generate a small hash for a link.
157 *
158 * @param DateTime $date Link creation date.
159 * @param int $id Link ID.
160 *
161 * @return string the small hash generated from link data.
162 */
163function link_small_hash($date, $id)
164{
336a28fa 165 return smallHash($date->format(Bookmark::LINK_DATE_FORMAT) . $id);
d592daea 166}
a8e7da01
A
167
168/**
169 * Returns whether or not the link is an internal note.
170 * Its URL starts by `?` because it's actually a permalink.
171 *
172 * @param string $linkUrl
173 *
174 * @return bool true if internal note, false otherwise.
175 */
176function is_note($linkUrl)
177{
178 return isset($linkUrl[0]) && $linkUrl[0] === '?';
179}
b3bd8c3e
A
180
181/**
182 * Extract an array of tags from a given tag string, with provided separator.
183 *
184 * @param string|null $tags String containing a list of tags separated by $separator.
185 * @param string $separator Shaarli's default: ' ' (whitespace)
186 *
187 * @return array List of tags
188 */
189function tags_str2array(?string $tags, string $separator): array
190{
191 // For whitespaces, we use the special \s regex character
192 $separator = $separator === ' ' ? '\s' : $separator;
193
194 return preg_split('/\s*' . $separator . '+\s*/', trim($tags) ?? '', -1, PREG_SPLIT_NO_EMPTY);
195}
196
197/**
198 * Return a tag string with provided separator from a list of tags.
199 * Note that given array is clean up by tags_filter().
200 *
201 * @param array|null $tags List of tags
202 * @param string $separator
203 *
204 * @return string
205 */
206function tags_array2str(?array $tags, string $separator): string
207{
208 return implode($separator, tags_filter($tags, $separator));
209}
210
211/**
212 * Clean an array of tags: trim + remove empty entries
213 *
214 * @param array|null $tags List of tags
215 * @param string $separator
216 *
217 * @return array
218 */
219function tags_filter(?array $tags, string $separator): array
220{
221 $trimDefault = " \t\n\r\0\x0B";
222 return array_values(array_filter(array_map(function (string $entry) use ($separator, $trimDefault): string {
223 return trim($entry, $trimDefault . $separator);
224 }, $tags ?? [])));
225}