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