dolibarr 21.0.0-alpha
doleditor.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2006-2008 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2021 Gaƫtan MAISON <gm@ilad.org>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 * or see https://www.gnu.org/
19 */
20
32{
33 public $tool; // Store the selected tool
34
35 // If using fckeditor
36 public $editor;
37
38 // If not using fckeditor
39 public $content;
40 public $htmlname;
41 public $toolbarname;
42 public $toolbarstartexpanded;
43 public $rows;
44 public $cols;
45 public $height;
46 public $width;
47 public $uselocalbrowser;
48 public $readonly;
49 public $posx;
50 public $posy;
51
52
72 public function __construct($htmlname, $content, $width = '', $height = 200, $toolbarname = 'Basic', $toolbarlocation = 'In', $toolbarstartexpanded = false, $uselocalbrowser = 1, $okforextendededitor = true, $rows = 0, $cols = '', $readonly = 0, $poscursor = array())
73 {
74 global $conf;
75
76 dol_syslog(get_class($this)."::DolEditor htmlname=".$htmlname." width=".$width." height=".$height." toolbarname=".$toolbarname);
77
78 if (!$rows) {
79 $rows = round($height / 20);
80 }
81 if (!$cols) {
82 $cols = ($width ? round($width / 6) : 80);
83 }
84 $shorttoolbarname = preg_replace('/_encoded$/', '', $toolbarname);
85
86 // Name of extended editor to use (FCKEDITOR_EDITORNAME can be 'ckeditor' or 'fckeditor')
87 $defaulteditor = 'ckeditor';
88 $this->tool = !getDolGlobalString('FCKEDITOR_EDITORNAME') ? $defaulteditor : $conf->global->FCKEDITOR_EDITORNAME;
89 $this->uselocalbrowser = $uselocalbrowser;
90 $this->readonly = $readonly;
91
92 // Check if extended editor is ok. If not we force textarea
93 if ((!isModEnabled('fckeditor') && $okforextendededitor !== 'ace') || empty($okforextendededitor)) {
94 $this->tool = 'textarea';
95 }
96 if ($okforextendededitor === 'ace') {
97 $this->tool = 'ace';
98 }
99 //if ($conf->dol_use_jmobile) $this->tool = 'textarea'; // ckeditor and ace seems ok with mobile
100 if (empty($conf->use_javascript_ajax)) { // If no javascript, we force use of textarea
101 $this->tool = 'textarea';
102 }
103
104 if ( isset($poscursor['find']) ) {
105 $posy = 0;
106 $lines = explode("\n", $content);
107 $nblines = count($lines);
108 for ($i = 0 ; $i < $nblines ; $i++) {
109 if (preg_match('/'.$poscursor['find'].'/', $lines[$i])) {
110 $posy = $i;
111 break;
112 }
113 }
114 if ($posy != 0 ) $poscursor['y'] = $posy;
115 }
116
117 // Define some properties
118 if (in_array($this->tool, array('textarea', 'ckeditor', 'ace'))) {
119 if ($this->tool == 'ckeditor' && !dol_textishtml($content)) { // We force content to be into HTML if we are using an advanced editor if content is not HTML.
120 $this->content = dol_nl2br($content);
121 } else {
122 $this->content = $content;
123 }
124 $this->htmlname = $htmlname;
125 $this->toolbarname = $shorttoolbarname;
126 $this->toolbarstartexpanded = $toolbarstartexpanded;
127 $this->rows = max(ROWS_3, $rows);
128 $this->cols = (preg_match('/%/', $cols) ? $cols : max(40, $cols)); // If $cols is a percent, we keep it, otherwise, we take max
129 $this->height = $height;
130 $this->width = $width;
131 $this->posx = empty($poscursor['x']) ? 0 : $poscursor['x'];
132 $this->posy = empty($poscursor['y']) ? 0 : $poscursor['y'];
133 }
134 }
135
136 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
150 public function Create($noprint = 0, $morejs = '', $disallowAnyContent = true, $titlecontent = '', $option = '', $moreparam = '', $morecss = '')
151 {
152 // phpcs:enable
153 global $conf, $langs;
154
155 $fullpage = false;
156 if (isset($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT)) {
157 $disallowAnyContent = !getDolGlobalString('FCKEDITOR_ALLOW_ANY_CONTENT'); // Only predefined list of html tags are allowed or all
158 }
159
160 $found = 0;
161 $out = '';
162
163 if (in_array($this->tool, array('textarea', 'ckeditor'))) {
164 $found = 1;
165 //$out.= '<textarea id="'.$this->htmlname.'" name="'.$this->htmlname.'" '.($this->readonly?' disabled':'').' rows="'.$this->rows.'"'.(preg_match('/%/',$this->cols)?' style="margin-top: 5px; width: '.$this->cols.'"':' cols="'.$this->cols.'"').' class="flat">';
166 // TODO We do not put the 'disabled' tag because on a read form, it change style with grey.
167 //print $this->content;
168 $out .= '<textarea id="'.$this->htmlname.'" name="'.$this->htmlname.'" rows="'.$this->rows.'"'.(preg_match('/%/', $this->cols) ? ' style="margin-top: 5px; width: '.$this->cols.'"' : ' cols="'.$this->cols.'"').' '.($moreparam ? $moreparam : '').' class="flat '.$morecss.'">';
169 $out .= htmlspecialchars($this->content);
170 $out .= '</textarea>';
171
172 if ($this->tool == 'ckeditor' && !empty($conf->use_javascript_ajax) && isModEnabled('fckeditor')) {
173 if (!defined('REQUIRE_CKEDITOR')) {
174 define('REQUIRE_CKEDITOR', '1');
175 }
176
177 $skin = getDolGlobalString('FCKEDITOR_SKIN', 'moono-lisa'); // default with ckeditor 4.6 : moono-lisa
178
179 $pluginstodisable = 'elementspath,save,flash,div,anchor';
180 if (!getDolGlobalString('FCKEDITOR_ENABLE_SPECIALCHAR')) {
181 $pluginstodisable .= ',specialchar';
182 }
183 if (!empty($conf->dol_optimize_smallscreen)) {
184 $pluginstodisable .= ',scayt,wsc,find,undo';
185 }
186 if (!getDolGlobalString('FCKEDITOR_ENABLE_WSC')) { // spellchecker has end of life december 2021
187 $pluginstodisable .= ',wsc';
188 }
189 if (!getDolGlobalString('FCKEDITOR_ENABLE_PDF')) {
190 $pluginstodisable .= ',exportpdf';
191 }
192 if (getDolGlobalInt('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS') == 2) {
193 $this->uselocalbrowser = 0; // Can't use browser to navigate into files. Only links with "<img src=data:..." are allowed.
194 }
195 $scaytautostartup = '';
196 if (getDolGlobalString('FCKEDITOR_ENABLE_SCAYT_AUTOSTARTUP')) {
197 $scaytautostartup = 'scayt_autoStartup: true,';
198 $scaytautostartup .= 'scayt_sLang: \''.dol_escape_js($langs->getDefaultLang()).'\',';
199 } else {
200 $pluginstodisable .= ',scayt';
201 }
202
203 $htmlencode_force = preg_match('/_encoded$/', $this->toolbarname) ? 'true' : 'false';
204
205 $out .= '<!-- Output ckeditor disallowAnyContent='.dol_escape_htmltag($disallowAnyContent).' toolbarname='.dol_escape_htmltag($this->toolbarname).' -->'."\n";
206 $out .= '<script nonce="'.getNonce().'" type="text/javascript">
207 $(document).ready(function () {
208 /* console.log("Run ckeditor"); */
209 /* if (CKEDITOR.loadFullCore) CKEDITOR.loadFullCore(); */
210 /* should be editor=CKEDITOR.replace but what if there is several editors ? */
211 tmpeditor = CKEDITOR.replace(\''.dol_escape_js($this->htmlname).'\',
212 {
213 /* property:xxx is same than CKEDITOR.config.property = xxx */
214 customConfig: ckeditorConfig,
215 removePlugins: \''.dol_escape_js($pluginstodisable).'\',
216 versionCheck: false,
217 readOnly: '.($this->readonly ? 'true' : 'false').',
218 htmlEncodeOutput: '.dol_escape_js($htmlencode_force).',
219 allowedContent: '.($disallowAnyContent ? 'false' : 'true').', /* Advanced Content Filter (ACF) is on when allowedContent is false */
220 extraAllowedContent: \'a[target];section[contenteditable,id];div{float,display}\', /* Allow a tag with attribute target, allow seciont tag and allow the style float and display into div to default other allowed tags */
221 disallowedContent: \'\', /* Tags that are not allowed */
222 fullPage: '.($fullpage ? 'true' : 'false').', /* if true, the html, header and body tags are kept */
223 toolbar: \''.dol_escape_js($this->toolbarname).'\',
224 toolbarStartupExpanded: '.($this->toolbarstartexpanded ? 'true' : 'false').',
225 width: '.($this->width ? '\''.dol_escape_js($this->width).'\'' : '\'\'').',
226 height: '.dol_escape_js($this->height).',
227 skin: \''.dol_escape_js($skin).'\',
228 '.$scaytautostartup.'
229 language: \''.dol_escape_js($langs->defaultlang).'\',
230 textDirection: \''.dol_escape_js($langs->trans("DIRECTION")).'\',
231 on : {
232 instanceReady : function(ev) {
233 console.log("ckeditor instanceReady");
234 // Output paragraphs as <p>Text</p>.
235 this.dataProcessor.writer.setRules( \'p\', {
236 indent : false,
237 breakBeforeOpen : true,
238 breakAfterOpen : false,
239 breakBeforeClose : false,
240 breakAfterClose : true
241 });
242 },
243 /* This is to remove the tab Link on image popup. Does not work, so commented */
244 /*
245 dialogDefinition: function (event) {
246 var dialogName = event.data.name;
247 var dialogDefinition = event.data.definition;
248 if (dialogName == \'image\') {
249 dialogDefinition.removeContents(\'Link\');
250 }
251 }
252 */
253 },
254 disableNativeSpellChecker: '.(!getDolGlobalString('CKEDITOR_NATIVE_SPELLCHECKER') ? 'true' : 'false');
255
256 if ($this->uselocalbrowser) {
257 $out .= ','."\n";
258 // To use filemanager with old fckeditor (GPL)
259 // Note: ckeditorFilebrowserBrowseUrl and ckeditorFilebrowserImageBrowseUrl are defined in header by main.inc.php. They include url to browser with url of upload connector in parameter
260 $out .= ' filebrowserBrowseUrl : ckeditorFilebrowserBrowseUrl,';
261 $out .= ' filebrowserImageBrowseUrl : ckeditorFilebrowserImageBrowseUrl,';
262 //$out.= ' filebrowserUploadUrl : \''.DOL_URL_ROOT.'/includes/fckeditor/editor/filemanagerdol/connectors/php/upload.php?Type=File\',';
263 //$out.= ' filebrowserImageUploadUrl : \''.DOL_URL_ROOT.'/includes/fckeditor/editor/filemanagerdol/connectors/php/upload.php?Type=Image\',';
264 $out .= "\n";
265 // To use filemanager with ckfinder (Non free) and ckfinder directory is inside htdocs/includes
266 /* $out.= ' filebrowserBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html\',
267 filebrowserImageBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html?Type=Images\',
268 filebrowserFlashBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html?Type=Flash\',
269 filebrowserUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files\',
270 filebrowserImageUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images\',
271 filebrowserFlashUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash\','."\n";
272 */
273 $out .= ' filebrowserWindowWidth : \'900\',
274 filebrowserWindowHeight : \'500\',
275 filebrowserImageWindowWidth : \'900\',
276 filebrowserImageWindowHeight : \'500\'';
277 }
278 $out .= ' })'.$morejs; // end CKEditor.replace
279 // Show the CKEditor javascript object once loaded is ready 'For debug)
280 //$out .= '; CKEDITOR.on(\'instanceReady\', function(ck) { ck.editor.removeMenuItem(\'maximize\'); ck.editor.removeMenuItem(\'Undo\'); ck.editor.removeMenuItem(\'undo\'); console.log(ck.editor); console.log(ck.editor.toolbar[0]); }); ';
281 $out .= '});'."\n"; // end document.ready
282 $out .= '</script>'."\n";
283 }
284 }
285
286 // Output editor ACE
287 // Warning: ace.js and ext-statusbar.js must be loaded by the parent page.
288 if (preg_match('/^ace/', $this->tool)) {
289 $found = 1;
290 $format = $option;
291
292 $out .= "\n".'<!-- Output Ace editor -->'."\n";
293
294 if ($titlecontent) {
295 $out .= '<div class="aceeditorstatusbar" id="statusBar'.$this->htmlname.'">'.$titlecontent;
296 $out .= ' &nbsp; - &nbsp; <span id="morelines" class="right classlink cursorpointer morelines'.$this->htmlname.'">'.dol_escape_htmltag($langs->trans("ShowMoreLines")).'</span> &nbsp; &nbsp; ';
297 $out .= '</div>';
298 $out .= '<script nonce="'.getNonce().'" type="text/javascript">'."\n";
299 $out .= 'jQuery(document).ready(function() {'."\n";
300 $out .= ' var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid");
301 aceEditor.moveCursorTo('.($this->posy + 1).','.$this->posx.');
302 aceEditor.gotoLine('.($this->posy + 1).','.$this->posx.');
303 var StatusBar = window.ace.require("ace/ext/statusbar").StatusBar; // Init status bar. Need lib ext-statusbar
304 var statusBar = new StatusBar(aceEditor, document.getElementById("statusBar'.$this->htmlname.'")); // Init status bar. Need lib ext-statusbar
305
306 var oldNbOfLines = 0;
307 jQuery(".morelines'.$this->htmlname.'").click(function() {
308 var aceEditorClicked = window.ace.edit("'.$this->htmlname.'aceeditorid");
309 currentline = aceEditorClicked.getOption("maxLines");
310 if (oldNbOfLines == 0)
311 {
312 oldNbOfLines = currentline;
313 }
314 console.log("We click on more lines, oldNbOfLines is "+oldNbOfLines+", we have currently "+currentline);
315 if (currentline < 500)
316 {
317 aceEditorClicked.setOptions({ maxLines: 500 });
318 }
319 else
320 {
321 aceEditorClicked.setOptions({ maxLines: oldNbOfLines });
322 }
323 });
324 })';
325 $out .= '</script>'."\n";
326 }
327
328 $out .= '<pre id="'.$this->htmlname.'aceeditorid" style="'.($this->width ? 'width: '.$this->width.'px; ' : '');
329 $out .= ($this->height ? ' height: '.$this->height.'px; ' : '');
330 //$out.=" min-height: 100px;";
331 $out .= '">';
332 $out .= htmlspecialchars($this->content);
333 $out .= '</pre>';
334 $out .= '<input type="hidden" id="'.$this->htmlname.'_x" name="'.$this->htmlname.'_x">';
335 $out .= '<input type="hidden" id="'.$this->htmlname.'_y" name="'.$this->htmlname.'_y">';
336 $out .= '<textarea id="'.$this->htmlname.'" name="'.$this->htmlname.'" style="width:0px; height: 0px; display: none;">';
337 $out .= htmlspecialchars($this->content);
338 $out .= '</textarea>';
339
340 $out .= '<script nonce="'.getNonce().'" type="text/javascript">'."\n";
341 $out .= 'var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid");
342
343 aceEditor.session.setMode("ace/mode/'.$format.'");
344 aceEditor.setOptions({
345 enableBasicAutocompletion: true, // the editor completes the statement when you hit Ctrl + Space. Need lib ext-language_tools.js
346 enableLiveAutocompletion: false, // the editor completes the statement while you are typing. Need lib ext-language_tools.js
347 showPrintMargin: false, // hides the vertical limiting strip
348 minLines: 10,
349 maxLines: '.(empty($this->height) ? '34' : (round($this->height / 10))).',
350 fontSize: "110%" // ensures that the editor fits in the environment
351 });
352
353 // defines the style of the editor
354 aceEditor.setTheme("ace/theme/chrome");
355 // hides line numbers (widens the area occupied by error and warning messages)
356 //aceEditor.renderer.setOption("showLineNumbers", false);
357 // ensures proper autocomplete, validation and highlighting of JavaScript code
358 //aceEditor.getSession().setMode("ace/mode/javascript_expression");
359 '."\n";
360
361 $out .= 'jQuery(document).ready(function() {
362 jQuery(".buttonforacesave").click(function() {
363 console.log("We click on savefile button for component '.dol_escape_js($this->htmlname).'");
364 var aceEditor = window.ace.edit("'.dol_escape_js($this->htmlname).'aceeditorid");
365 if (aceEditor) {
366 var cursorPos = aceEditor.getCursorPosition();
367 //console.log(cursorPos);
368 if (cursorPos) {
369 jQuery("#'.dol_escape_js($this->htmlname).'_x").val(cursorPos.column);
370 jQuery("#'.dol_escape_js($this->htmlname).'_y").val(cursorPos.row);
371 }
372 //console.log(aceEditor.getSession().getValue());
373 // Inject content of editor into the original HTML field.
374 jQuery("#'.dol_escape_js($this->htmlname).'").val(aceEditor.getSession().getValue());
375 /*if (jQuery("#'.dol_escape_js($this->htmlname).'").html().length > 0) return true;
376 else return false;*/
377 return true;
378 } else {
379 console.log("Failed to retrieve js object ACE from its name");
380 return false;
381 }
382 });
383 })';
384 $out .= '</script>'."\n";
385 }
386
387 if (empty($found)) {
388 $out .= 'Error, unknown value for tool '.$this->tool.' in DolEditor Create function.';
389 }
390
391 if ($noprint) {
392 return $out;
393 } else {
394 print $out;
395 }
396 }
397}
Class to manage a WYSIWYG editor.
__construct($htmlname, $content, $width='', $height=200, $toolbarname='Basic', $toolbarlocation='In', $toolbarstartexpanded=false, $uselocalbrowser=1, $okforextendededitor=true, $rows=0, $cols='', $readonly=0, $poscursor=array())
Create an object to build an HTML area to edit a large string content.
Create($noprint=0, $morejs='', $disallowAnyContent=true, $titlecontent='', $option='', $moreparam='', $morecss='')
Output edit area inside the HTML stream.
dol_nl2br($stringtoencode, $nl2brmode=0, $forxml=false)
Replace CRLF in string with a HTML BR tag.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
dol_textishtml($msg, $option=0)
Return if a text is a html content.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:139