/
view.php
347 lines (306 loc) · 10.8 KB
/
view.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
<?php
namespace Helper;
class View extends \Template
{
public function __construct()
{
// Register filters
$this->filter('parseText', '$this->parseText');
$this->filter('formatFilesize', '$this->formatFilesize');
parent::__construct();
}
/**
* Convert Textile or Markdown to HTML, adding hashtags
* @param string $str
* @param array $options
* @param int $ttl
* @return string
*/
public function parseText($str, $options = array(), $ttl = null)
{
if ($options === null) {
$options = array();
}
$options = $options + \Base::instance()->get("parse");
// Check for cached value if $ttl is set
if ($ttl !== null) {
$cache = \Cache::instance();
$hash = sha1($str . json_encode($options));
// Return value if cached
if (($str = $cache->get("$hash.tex")) !== false) {
return $str;
}
}
// Pass to any plugin hooks
$str = \Helper\Plugin::instance()->callHook("text.parse.before", $str);
// Run through the parsers based on $options
if ($options["ids"]) {
$str = $this->_parseIds($str);
}
if ($options["hashtags"]) {
$str = $this->_parseHashtags($str);
}
if ($options["emoticons"]) {
$str = $this->_parseEmoticons($str);
}
if ($options["markdown"]) {
$str = $this->_parseMarkdown($str);
}
if ($options["textile"]) {
$escape = true;
if ($options["markdown"]) {
// Yes, this is hacky. Please open an issue on GitHub if you
// know of a better way of supporting Markdown and Textile :)
$str = html_entity_decode($str);
$str = preg_replace('/^<p>|<\/p>$/m', "\n", $str);
$escape = false;
}
$str = $this->_parseTextile($str, $escape);
}
if (!$options["markdown"] && !$options['textile']) {
$str = nl2br(\Base::instance()->encode($str), false);
}
if ($options["urls"]) {
$str = $this->_parseUrls($str);
}
// Simplistic XSS protection
$antiXss = new \voku\helper\AntiXSS();
$str = $antiXss->xss_clean($str);
// Pass to any plugin hooks
$str = \Helper\Plugin::instance()->callHook("text.parse.after", $str);
// Cache the value if $ttl is set
if ($ttl !== null) {
$cache->set("$hash.tex", $str, $ttl);
}
return $str;
}
/**
* Replaces IDs with links to their corresponding issues
* @param string $str
* @return string
*/
protected function _parseIds($str)
{
$url = \Base::instance()->get("site.url");
// Find all IDs
$count = preg_match_all("/(?<=[^a-z\\/&]#|^#)[0-9]+(?=[^a-z\\/]|$)/i", $str, $matches);
if (!$count) {
return $str;
}
// Load IDs
$ids = array();
foreach ($matches[0] as $match) {
$ids[] = $match;
}
$idsStr = implode(",", array_unique($ids));
$issue = new \Model\Issue;
$issues = $issue->find(array("id IN ($idsStr)"));
return preg_replace_callback("/(?<=[^a-z\\/&]|^)#[0-9]+(?=[^a-z\\/]|$)/i", function ($matches) use ($url, $issues) {
$id = ltrim($matches[0], "#");
foreach ($issues as $i) {
if ($i->id == $id) {
$issue = $i;
}
}
if ($issue) {
if ($issue->deleted_date) {
$f3 = \Base::instance();
if ($f3->get("user.role") == "admin" || $f3->get("user.rank") >= \Model\User::RANK_MANAGER || $f3->get("user.id") == $issue->author_id) {
return "<a href=\"{$url}issues/$id\" style=\"text-decoration: line-through;\">#$id – " . htmlspecialchars($issue->name) . "</a>";
} else {
return "#$id";
}
}
return "<a href=\"{$url}issues/$id\">#$id – " . htmlspecialchars($issue->name) . "</a>";
}
return "<a href=\"{$url}issues/$id\">#$id</a>";
}, $str);
}
/**
* Replaces hashtags with links to their corresponding tag pages
* @param string $str
* @return string
*/
protected function _parseHashtags($str)
{
return preg_replace_callback("/(?<=[^a-z\\/&]|^)#([a-z][a-z0-9_-]*[a-z0-9]+)(?=[^a-z\\/]|$)/i", function ($matches) {
$url = \Base::instance()->get("site.url");
$tag = preg_replace("/[_-]+/", "-", $matches[1]);
return "<a href=\"{$url}tag/$tag\">#$tag</a>";
}, $str);
}
/**
* Replaces URLs with links
* @param string $str
* @return string
*/
protected function _parseUrls($str)
{
$str = ' ' . $str;
// In testing, using arrays here was found to be faster
$str = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#!$%&~/.\-;:=,?@\[\]+]*)#is', function ($matches) {
$ret = '';
$url = $matches[2];
if (empty($url)) {
return $matches[0];
}
// removed trailing [.,;:] from URL
if (in_array(substr($url, -1), array('.',',',';',':')) === true) {
$ret = substr($url, -1);
$url = substr($url, 0, strlen($url)-1);
}
return $matches[1] . "<a href=\"$url\" rel=\"nofollow\" target=\"_blank\">$url</a>".$ret;
}, $str);
$str = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#!$%&~/.\-;:=,?@\[\]+]*)#is', function ($m) {
$s = '';
$d = $m[2];
if (empty($d)) {
return $m[0];
}
// removed trailing [,;:] from URL
if (in_array(substr($d, -1), array('.',',',';',':')) === true) {
$s = substr($d, -1);
$d = substr($d, 0, strlen($d)-1);
}
return $m[1] . "<a href=\"http://$d\" rel=\"nofollow\" target=\"_blank\">$d</a>".$s;
}, $str);
$str = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', function ($m) {
$email = $m[2].'@'.$m[3];
return $m[1]."<a href=\"mailto:$email\">$email</a>";
}, $str);
// This one is not in an array because we need it to run last, for cleanup of accidental links within links
$str = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $str);
$str = trim($str);
return $str;
}
/**
* Replaces text emoticons with Emoji versions
* @param string $str
* @return string
*/
protected function _parseEmoticons($str)
{
// Custom Emoji map, based on UTF::emojify
$map = [
':(' => "\xF0\x9F\x99\x81", // frown
':)' => "\xF0\x9F\x99\x82", // smile
'<3' => "\xE2\x9D\xA4\xEF\xB8\x8F", // heart
':D' => "\xF0\x9F\x98\x83", // grin
'XD' => "\xF0\x9F\x98\x86", // laugh
';)' => "\xF0\x9F\x98\x89", // wink
':P' => "\xF0\x9F\x98\x8B", // tongue
':,' => "\xF0\x9F\x98\x8F", // think
':/' => "\xF0\x9F\x98\xA3", // skeptic
'8O' => "\xF0\x9F\x98\xB2", // oops
];
$match = implode('|', array_map(function ($str) {
return preg_quote($str, '/');
}, array_keys($map)));
$regex = "/([^a-z\\/&]|^)($match)([^a-z\\/]|$)/m";
return preg_replace_callback($regex, function ($match) use ($map) {
return $match[1] . $map[$match[2]] . $match[3];
}, $str);
}
/**
* Passes a string through the Textile parser
* @param string $str
* @return string
*/
protected function _parseTextile($str, $escape = true)
{
$tex = new \Netcarver\Textile\Parser('html5');
$tex->setDimensionlessImages(true);
$tex->setRestricted($escape);
return $tex->parse($str);
}
/**
* Passes a string through the Markdown parser
* @param string $str
* @return string
*/
protected function _parseMarkdown($str, $escape = true)
{
$mkd = new \Parsedown();
$mkd->setUrlsLinked(false);
$mkd->setMarkupEscaped($escape);
return $mkd->text($str);
}
/**
* Get a human-readable file size
* @param int $filesize
* @return string
*/
public function formatFilesize($filesize)
{
if ($filesize > 1073741824) {
return round($filesize / 1073741824, 2) . " GB";
} elseif ($filesize > 1048576) {
return round($filesize / 1048576, 2) . " MB";
} elseif ($filesize > 1024) {
return round($filesize / 1024, 2) . " KB";
} else {
return $filesize . " bytes";
}
}
/**
* Get a Gravatar URL from email address and size, uses global Gravatar configuration
* @param string $email
* @param integer $size
* @return string
*/
public function gravatar($email, $size = 80)
{
$f3 = \Base::instance();
$rating = $f3->get("gravatar.rating") ? $f3->get("gravatar.rating") : "pg";
$default = $f3->get("gravatar.default") ? $f3->get("gravatar.default") : "mm";
return "//gravatar.com/avatar/" . md5(strtolower($email)) .
"?s=" . intval($size) .
"&d=" . urlencode($default) .
"&r=" . urlencode($rating);
}
/**
* Get UTC time offset in seconds
*
* @return int
*/
public function timeoffset()
{
$f3 = \Base::instance();
if ($f3->exists("site.timeoffset")) {
return $f3->get("site.timeoffset");
} else {
$tz = $f3->get("site.timezone");
$dtzLocal = new \DateTimeZone($tz);
$dtLocal = new \DateTime("now", $dtzLocal);
$offset = $dtzLocal->getOffset($dtLocal);
$f3->set("site.timeoffset", $offset);
}
return $offset;
}
/**
* Convert a UTC timestamp to local time
* @param int|string $timestamp
* @return int
*/
public function utc2local($timestamp = null)
{
if ($timestamp && !is_numeric($timestamp)) {
$timestamp = strtotime($timestamp);
}
if (!$timestamp) {
$timestamp = time();
}
$offset = $this->timeoffset();
return $timestamp + $offset;
}
/**
* Get the current primary language
* @return string
*/
public function lang()
{
$f3 = \Base::instance();
$langs = $f3->split($f3->get("LANGUAGE"));
return isset($langs[0]) ? $langs[0] : $f3->get("FALLBACK");
}
}