]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/bookmark/LinkUtils.php
Apply PHP Code Beautifier on source code for linter automatic fixes
[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 // Try to retrieve OpenGraph tag.
72 $ogRegex = '#<meta[^>]+(?:' . $properties . ')=(?:' . $orCondition . ')[^>]*content=(["\'])([^\1]*?)\1.*?>#';
73 // If the attributes are not in the order property => content (e.g. Github)
74 // New regex to keep this readable... more or less.
75 $ogRegexReverse = '#<meta[^>]+content=(["\'])([^\1]*?)\1[^>]+(?:' . $properties . ')=(?:' . $orCondition . ').*?>#';
76
77 if (
78 preg_match($ogRegex, $html, $matches) > 0
79 || preg_match($ogRegexReverse, $html, $matches) > 0
80 ) {
81 return $matches[2];
82 }
83
84 return false;
85 }
86
87 /**
88 * In a string, converts URLs to clickable bookmarks.
89 *
90 * @param string $text input string.
91 *
92 * @return string returns $text with all bookmarks converted to HTML bookmarks.
93 *
94 * @see Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
95 */
96 function text2clickable($text)
97 {
98 $regex = '!(((?:https?|ftp|file)://|apt:|magnet:)\S+[a-z0-9\(\)]/?)!si';
99 return preg_replace($regex, '<a href="$1">$1</a>', $text);
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 */
110 function 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';
120 $replacement = '$1<a href="' . $indexUrl . './add-tag/$2" title="Hashtag $2">#$2</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 */
132 function 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.
141 * @param string $indexUrl URL to Shaarli's index.
142 * @param bool $autolink Turn on/off automatic linkifications of URLs and hashtags
143 *
144 * @return string formatted description.
145 */
146 function format_description($description, $indexUrl = '', $autolink = true)
147 {
148 if ($autolink) {
149 $description = hashtag_autolink(text2clickable($description), $indexUrl);
150 }
151
152 return nl2br(space2nbsp($description));
153 }
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 */
163 function link_small_hash($date, $id)
164 {
165 return smallHash($date->format(Bookmark::LINK_DATE_FORMAT) . $id);
166 }
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 */
176 function is_note($linkUrl)
177 {
178 return isset($linkUrl[0]) && $linkUrl[0] === '?';
179 }
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 */
189 function 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 */
206 function 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 */
219 function 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 }