/
TextareaField.php
337 lines (296 loc) · 13.3 KB
/
TextareaField.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
<?php
namespace YesWiki\Bazar\Field;
use DateTime;
use DateTimeZone;
use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use YesWiki\Core\Service\DbService;
/**
* @Field({"textelong"})
*/
class TextareaField extends BazarField
{
protected $numRows;
protected $syntax;
protected const FIELD_NUM_ROWS = 4;
protected const FIELD_SYNTAX = 7;
protected const ACCEPTED_TAGS = '<h1><h2><h3><h4><h5><h6><hr><hr/><br><br/><span><blockquote><i><u><b><strong><ol><ul><li><small><div><p><a><table><tr><th><td><img><figure><caption><iframe>';
public const SYNTAX_WIKI = 'wiki-textarea';
public const SYNTAX_HTML = 'html';
public const SYNTAX_PLAIN = 'nohtml';
public function __construct(array $values, ContainerInterface $services)
{
parent::__construct($values, $services);
$this->numRows = empty($values[self::FIELD_NUM_ROWS]) ? 3 : $values[self::FIELD_NUM_ROWS];
$this->syntax = $values[self::FIELD_SYNTAX] ?? self::SYNTAX_WIKI;
// For this field, max chars are defined in the 6th column, instead of the already-used 4th
$this->maxChars = $values[6];
// Retro-compatibility
if ($this->syntax === 'wiki') {
$this->syntax = self::SYNTAX_WIKI;
}
}
protected function renderInput($entry)
{
$output = "";
$wiki = $this->getWiki();
// If HTML syntax, load editor's JS and CSS
if ($this->syntax === self::SYNTAX_HTML) {
$wiki->AddJavascriptFile('tools/bazar/libs/vendor/summernote/summernote.min.js');
$wiki->AddCSSFile('tools/bazar/libs/vendor/summernote/summernote.css');
$langKey = strtolower($GLOBALS['prefered_language']).'-'.strtoupper($GLOBALS['prefered_language']);
$langFile = 'tools/bazar/libs/vendor/summernote/lang/summernote-'.$langKey.'.js';
if (file_exists($langFile)) {
$wiki->AddJavascriptFile($langFile);
$langOptions = 'lang: "'.$langKey.'",';
} else {
$langOptions = '';
}
$script = '$(document).ready(function() {
$(".summernote").summernote({
'.$langOptions.'
height: '. $this->numRows*30 .', // set editor height
minHeight: 100, // set minimum height of editor
maxHeight: 350, // set maximum height of editor
focus: false, // set focus to editable area after initializing summernote
toolbar: [
//[groupname, [button list]]
//[\'style\', [\'style\', \'well\']],
[\'style\', [\'style\']],
[\'textstyle\', [\'bold\', \'italic\', \'underline\', \'strikethrough\', \'clear\']],
[\'color\', [\'color\']],
[\'para\', [\'ul\', \'ol\', \'paragraph\']],
[\'insert\', [\'hr\', \'link\', \'table\']], // \'picture\', \'video\' removed because of the storage in the field
[\'misc\', [\'codeview\']]
],
isNotSplitEdgePoint : true,
styleTags: [\'h3\', \'h4\', \'h5\', \'h6\', \'p\', \'blockquote\', \'pre\'],
oninit: function() {
//$(\'button[data-original-title=Style]\').prepend("Style").find("i").remove();
},
callbacks: {
onPaste: function (e) {
var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData(\'Text\');
e.preventDefault();
document.execCommand(\'insertText\', false, bufferText);
}
}
});
});';
$wiki->AddJavascript($script);
} elseif ($this->syntax === self::SYNTAX_WIKI) {
$wiki->AddJavascriptFile('tools/aceditor/presentation/javascripts/ace-lib.js');
$wiki->AddJavascriptFile('tools/aceditor/presentation/javascripts/mode-html.js');
$wiki->AddJavascriptFile('tools/aceditor/presentation/javascripts/aceditor.js');
$wiki->AddCSSFile('tools/aceditor/presentation/styles/aceditor.css');
if (!empty($wiki->config['actionbuilder_textarea_name']) && $this->getName() == $wiki->config['actionbuilder_textarea_name']) {
// load action builder but be carefull to output
ob_start();
include_once 'tools/aceditor/actions/actions_builder.php';
$output = ob_get_contents();
ob_end_clean();
}
}
$tempTag = !isset($entry['id_fiche']) ? ($wiki->config['temp_tag_for_entry_creation'] ?? null) : null;
if ($tempTag) {
$tempTag .= '_' . bin2hex(random_bytes(10));
}
return $output . $this->render("@bazar/inputs/textarea.twig", [
'value' => $this->getValue($entry),
'entryId' => $entry['id_fiche'] ?? null,
'tempTag' => $tempTag,
'attachConfigExtImages' => explode("|", $this->getService(ParameterBagInterface::class)->get("attach_config")["ext_images"])
]);
}
/**
* only for `include_once` in `renderInput`
*/
private function AddJavascriptFile($file)
{
$this->getWiki()->AddJavascriptFile($file);
}
/**
* only for `include_once` in `renderInput`
*/
private function AddCSSFile($file)
{
$this->getWiki()->AddCSSFile($file);
}
public function formatValuesBeforeSave($entry)
{
$value = $this->getValue($entry);
if ($this->syntax === self::SYNTAX_HTML) {
$value = strip_tags($value, self::ACCEPTED_TAGS);
$value = $this->sanitizeBase64Img($value, $entry);
} elseif ($this->syntax === self::SYNTAX_WIKI) {
$value = $this->sanitizeAttach($value, $entry);
}
return [$this->propertyName => $value];
}
protected function renderStatic($entry)
{
$value = $this->getValue($entry);
if (!$value) {
return null;
}
switch ($this->syntax) {
case self::SYNTAX_WIKI:
// Do the page change in any case (useful for attach or grid)
$oldPage = $GLOBALS['wiki']->GetPageTag();
$oldPageArray = $GLOBALS['wiki']->page;
$GLOBALS['wiki']->tag = $entry['id_fiche'];
$GLOBALS['wiki']->page = $GLOBALS['wiki']->LoadPage($GLOBALS['wiki']->tag);
$GLOBALS['wiki']->page['body'] = $value;
$value = $GLOBALS['wiki']->Format($value);
// if the textarea have some actions which return "", they are replaced by '' otherwise it crashed
// because they're by wakka as a beginning of HTML code
// the user still insert HTML code in the textarea with "" because the "" block is interpretated before
// the replacement
$value = str_replace('""', '\'\'', $value);
$GLOBALS['wiki']->tag = $oldPage;
$GLOBALS['wiki']->page = $oldPageArray;
break;
case self::SYNTAX_PLAIN:
$value = htmlentities($value, ENT_QUOTES, YW_CHARSET);
break;
case self::SYNTAX_HTML:
// if the user type "", it's replaced by '' otherwise it crashes the output because it's interpretated
// by wakka as a beginning of HTML code
$value = str_replace('""', '\'\'', $value);
break;
}
return $this->render("@bazar/fields/textarea.twig", [
'value' => $value
]);
}
// GETTERS. Needed to use them in the Twig syntax
public function getNumRows()
{
return $this->numRows;
}
public function getSyntax()
{
return $this->syntax;
}
private function sanitizeAttach(string $text, array $entry): string
{
$wiki = $this->getWiki();
$temp_tag_for_entry_creation = $wiki->config['temp_tag_for_entry_creation'];
if (preg_match_all("/({{attach[^}]*file=\")(({$temp_tag_for_entry_creation}_[A-Fa-f0-9]+)\/([^\"]*))(\"[^}]*}})/m", $text, $matches)) {
if (!class_exists('attach')) {
include('tools/attach/libs/attach.lib.php');
}
$entryCreationTime = $this->getEntryCreationTime($entry);
foreach ($matches[0] as $key => $value) {
$attach = new \Attach($wiki);
$attach->file = $matches[2][$key];
$previousTag = $wiki->tag;
$previousPage = $wiki->page;
$wiki->tag = $matches[3][$key];
$wiki->page = [
'tag' => $wiki->tag,
'body' => '{##}',
'time' => date('YmdHis'),
'owner' => '',
'user' => '',
];
$previousFileName = $attach->GetFullFilename();
$attach->file = $matches[4][$key];
$wiki->tag = $entry['id_fiche'];
$wiki->page = [
'tag' => $entry['id_fiche'],
'body' => json_encode($entry),
'time' => $entryCreationTime,
'owner' => '',
'user' => '',
];
$newFileName = $attach->GetFullFilename(true);
rename($previousFileName, $newFileName);
$text = str_replace($matches[0][$key], $matches[1][$key].$matches[4][$key].$matches[5][$key], $text);
unset($attach);
$wiki->tag = $previousTag;
$wiki->page = $previousPage;
}
}
return $text;
}
private function sanitizeBase64Img(string $text, array $entry): string
{
$wiki = $this->getWiki();
$regExpSearch = '(<img\s*'; // image
$regExpSearch .= 'style="[^"]*"\s*)'; // with style
$imageExtensions = '(gif|jpeg|png|jpg|svg|webp)';
$imageContent = '([^"]*)';
$regExpSearch .= "src=\"data:image\/$imageExtensions;base64,$imageContent\"\\s*"; // src base 64
$regExpSearch .= '[^>]*((?<=data-filename=")[^"]*)(?=")'; // containing eventually a filename
$regExpSearch .= '[^>]*>'; // end of img tag
if (preg_match_all("/$regExpSearch/", $text, $matches)) {
if (!class_exists('attach')) {
include('tools/attach/libs/attach.lib.php');
}
$entryCreationTime = $this->getEntryCreationTime($entry);
$previousTag = $wiki->tag;
$previousPage = $wiki->page;
foreach ($matches[0] as $index => $textToReplace) {
$imageType = $matches[2][$index];
$imageContent = base64_decode($matches[3][$index]);
$fileName = $matches[4][$index];
if (empty(trim($fileName))) {
$fileName = bin2hex(random_bytes(10)).$imageType;
}
if (preg_match('/^(.*)(\.[A-Za-z0-9]+)$/m', $fileName, $matchesForFile)) {
$fileNameWithoutExtension = $matchesForFile[1];
$fileExtension = $matchesForFile[2];
$fileName = $this->sanitizeFileName($fileNameWithoutExtension).$fileExtension;
} else {
$fileName = $this->sanitizeFileName($fileName);
}
$attach = new \Attach($wiki);
$attach->file = $fileName;
// fake page
$wiki->tag = $entry['id_fiche'];
$wiki->page = [
'tag' => $entry['id_fiche'],
'page' => json_encode($entry),
'time' => $entryCreationTime,
'owner' => '',
'user' => '',
];
$newFilePath = $attach->GetFullFilename(true);
if (!empty($newFilePath)) {
// save file
file_put_contents($newFilePath, $imageContent);
$newText = $matches[1][$index];
$newText .= "src=\"$newFilePath\">";
$text = str_replace($textToReplace, $newText, $text);
}
unset($attach);
}
$wiki->tag = $previousTag;
$wiki->page = $previousPage;
}
return $text;
}
private function getEntryCreationTime(?array $entry): string
{
$dbTz = $this->getService(DbService::class)->getDbTimeZone();
$sqlTimeFormat = 'Y-m-d H:i:s';
$entryCreationTime = !empty($entry['date_maj_fiche'])
? $entry['date_creation_fiche']
: (
!empty($dbTz)
? (new DateTime())->setTimezone(new DateTimeZone($dbTz))->format($sqlTimeFormat)
: date($sqlTimeFormat)
);
return $entryCreationTime;
}
/**
* sanitize file name
* @param string $inputString
* @return string $outputString
*/
private function sanitizeFileName(string $inputString):string
{
return removeAccents(preg_replace('/--+/u', '-', preg_replace('/[[:punct:]]/', '-', $inputString)));
}
}