doleditor.class.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. <?php
  2. /* Copyright (C) 2006-2008 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2021 Gaëtan MAISON <gm@ilad.org>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. * or see https://www.gnu.org/
  18. */
  19. /**
  20. * \file htdocs/core/class/doleditor.class.php
  21. * \brief Class to manage a WYSIWYG editor
  22. */
  23. /**
  24. * Class to manage a WYSIWYG editor.
  25. * Usage: $doleditor=new DolEditor('body',$message,320,'toolbar_mailing');
  26. * $doleditor->Create();
  27. */
  28. class DolEditor
  29. {
  30. public $tool; // Store the selected tool
  31. // If using fckeditor
  32. public $editor;
  33. // If not using fckeditor
  34. public $content;
  35. public $htmlname;
  36. public $toolbarname;
  37. public $toolbarstartexpanded;
  38. public $rows;
  39. public $cols;
  40. public $height;
  41. public $width;
  42. public $readonly;
  43. public $posx;
  44. public $posy;
  45. /**
  46. * Create an object to build an HTML area to edit a large string content
  47. *
  48. * @param string $htmlname HTML name of WYSIWIG field
  49. * @param string $content Content of WYSIWIG field
  50. * @param int $width Width in pixel of edit area (auto by default)
  51. * @param int $height Height in pixel of edit area (200px by default)
  52. * @param string $toolbarname Name of bar set to use ('Full', 'dolibarr_notes[_encoded]', 'dolibarr_details[_encoded]'=the less featured, 'dolibarr_mailings[_encoded]', 'dolibarr_readonly').
  53. * @param string $toolbarlocation Where bar is stored :
  54. * 'In' = each window has its own toolbar
  55. * 'Out:name' = share toolbar into the div called 'name'
  56. * @param boolean $toolbarstartexpanded Bar is visible or not at start
  57. * @param int $uselocalbrowser Enabled to add links to local object with local browser. If false, only external images can be added in content.
  58. * @param boolean|string $okforextendededitor True=Allow usage of extended editor tool if qualified (like ckeditor). If 'textarea', force use of simple textarea. If 'ace', force use of Ace.
  59. * Warning: If you use 'ace', don't forget to also include ace.js in page header. Also, the button "save" must have class="buttonforacesave".
  60. * @param int $rows Size of rows for textarea tool
  61. * @param string $cols Size of cols for textarea tool (textarea number of cols '70' or percent 'x%')
  62. * @param int $readonly 0=Read/Edit, 1=Read only
  63. * @param array $poscursor Array for initial cursor position array('x'=>x, 'y'=>y)
  64. */
  65. public function __construct($htmlname, $content, $width = '', $height = 200, $toolbarname = 'Basic', $toolbarlocation = 'In', $toolbarstartexpanded = false, $uselocalbrowser = true, $okforextendededitor = true, $rows = 0, $cols = 0, $readonly = 0, $poscursor = array())
  66. {
  67. global $conf, $langs;
  68. dol_syslog(get_class($this)."::DolEditor htmlname=".$htmlname." width=".$width." height=".$height." toolbarname=".$toolbarname);
  69. if (!$rows) {
  70. $rows = round($height / 20);
  71. }
  72. if (!$cols) {
  73. $cols = ($width ?round($width / 6) : 80);
  74. }
  75. $shorttoolbarname = preg_replace('/_encoded$/', '', $toolbarname);
  76. // Name of extended editor to use (FCKEDITOR_EDITORNAME can be 'ckeditor' or 'fckeditor')
  77. $defaulteditor = 'ckeditor';
  78. $this->tool = empty($conf->global->FCKEDITOR_EDITORNAME) ? $defaulteditor : $conf->global->FCKEDITOR_EDITORNAME;
  79. $this->uselocalbrowser = $uselocalbrowser;
  80. $this->readonly = $readonly;
  81. // Check if extended editor is ok. If not we force textarea
  82. if ((empty($conf->fckeditor->enabled) && $okforextendededitor != 'ace') || empty($okforextendededitor)) {
  83. $this->tool = 'textarea';
  84. }
  85. if ($okforextendededitor === 'ace') {
  86. $this->tool = 'ace';
  87. }
  88. //if ($conf->dol_use_jmobile) $this->tool = 'textarea'; // ckeditor and ace seems ok with mobile
  89. // Define some properties
  90. if (in_array($this->tool, array('textarea', 'ckeditor', 'ace'))) {
  91. 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.
  92. $this->content = dol_nl2br($content);
  93. } else {
  94. $this->content = $content;
  95. }
  96. $this->htmlname = $htmlname;
  97. $this->toolbarname = $shorttoolbarname;
  98. $this->toolbarstartexpanded = $toolbarstartexpanded;
  99. $this->rows = max(ROWS_3, $rows);
  100. $this->cols = (preg_match('/%/', $cols) ? $cols : max(40, $cols)); // If $cols is a percent, we keep it, otherwise, we take max
  101. $this->height = $height;
  102. $this->width = $width;
  103. $this->posx = empty($poscursor['x']) ? 0 : $poscursor['x'];
  104. $this->posy = empty($poscursor['y']) ? 0 : $poscursor['y'];
  105. }
  106. }
  107. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  108. /**
  109. * Output edit area inside the HTML stream.
  110. * Output depends on this->tool (fckeditor, ckeditor, textarea, ...)
  111. *
  112. * @param int $noprint 1=Return HTML string instead of printing it to output
  113. * @param string $morejs Add more js. For example: ".on( \'saveSnapshot\', function(e) { alert(\'ee\'); });". Used by CKEditor only.
  114. * @param boolean $disallowAnyContent Disallow to use any content. true=restrict to a predefined list of allowed elements. Used by CKEditor only.
  115. * @param string $titlecontent Show title content before editor area. Used by ACE editor only.
  116. * @param string $option For ACE editor, set the source language ('html', 'php', 'javascript', ...)
  117. * @param string $moreparam Add extra tags to the textarea
  118. * @param string $morecss Add extra css to the textarea
  119. * @return void|string
  120. */
  121. public function Create($noprint = 0, $morejs = '', $disallowAnyContent = true, $titlecontent = '', $option = '', $moreparam = '', $morecss = '')
  122. {
  123. // phpcs:enable
  124. global $conf, $langs;
  125. $fullpage = false;
  126. if (isset($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT)) {
  127. $disallowAnyContent = empty($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT); // Only predefined list of html tags are allowed or all
  128. }
  129. $found = 0;
  130. $out = '';
  131. if (in_array($this->tool, array('textarea', 'ckeditor'))) {
  132. $found = 1;
  133. //$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">';
  134. // TODO We do not put the 'disabled' tag because on a read form, it change style with grey.
  135. //print $this->content;
  136. $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.'">';
  137. $out .= htmlspecialchars($this->content);
  138. $out .= '</textarea>';
  139. if ($this->tool == 'ckeditor' && !empty($conf->use_javascript_ajax) && !empty($conf->fckeditor->enabled)) {
  140. if (!defined('REQUIRE_CKEDITOR')) {
  141. define('REQUIRE_CKEDITOR', '1');
  142. }
  143. if (!empty($conf->global->FCKEDITOR_SKIN)) {
  144. $skin = $conf->global->FCKEDITOR_SKIN;
  145. } else {
  146. $skin = 'moono-lisa'; // default with ckeditor 4.6 : moono-lisa
  147. }
  148. $pluginstodisable = 'elementspath,save,flash';
  149. if (!empty($conf->dol_optimize_smallscreen)) {
  150. $pluginstodisable .= ',scayt,wsc,find,undo';
  151. }
  152. if (empty($conf->global->FCKEDITOR_ENABLE_WSC)) { // spellchecker has end of life december 2021
  153. $pluginstodisable .= ',wsc';
  154. }
  155. if (empty($conf->global->FCKEDITOR_ENABLE_PDF)) {
  156. $pluginstodisable .= ',exportpdf';
  157. }
  158. $scaytautostartup = '';
  159. if (!empty($conf->global->FCKEDITOR_ENABLE_SCAYT_AUTOSTARTUP)) {
  160. $scaytautostartup = 'scayt_autoStartup: true,';
  161. $scaytautostartup .= 'scayt_sLang: \''.dol_escape_js($langs->getDefaultLang()).'\',';
  162. } else {
  163. $pluginstodisable .= ',scayt';
  164. }
  165. $htmlencode_force = preg_match('/_encoded$/', $this->toolbarname) ? 'true' : 'false';
  166. $out .= '<!-- Output ckeditor $disallowAnyContent='.$disallowAnyContent.' toolbarname='.$this->toolbarname.' -->'."\n";
  167. $out .= '<script type="text/javascript">
  168. $(document).ready(function () {
  169. /* console.log("Run ckeditor"); */
  170. /* if (CKEDITOR.loadFullCore) CKEDITOR.loadFullCore(); */
  171. /* should be editor=CKEDITOR.replace but what if there is several editors ? */
  172. tmpeditor = CKEDITOR.replace(\''.$this->htmlname.'\',
  173. {
  174. /* property:xxx is same than CKEDITOR.config.property = xxx */
  175. customConfig: ckeditorConfig,
  176. removePlugins: \''.$pluginstodisable.'\',
  177. readOnly: '.($this->readonly ? 'true' : 'false').',
  178. htmlEncodeOutput:'.$htmlencode_force.',
  179. allowedContent:'.($disallowAnyContent ? 'false' : 'true').', /* Advanced Content Filter (ACF) is own when allowedContent is false */
  180. extraAllowedContent: \'a[target];div{float,display}\', /* Add the style float and display into div to default other allowed tags */
  181. disallowedContent: '.($disallowAnyContent ? '\'\'' : '\'\'').', /* Tags that are not allowed */
  182. fullPage: '.($fullpage ? 'true' : 'false').', /* if true, the html, header and body tags are kept */
  183. toolbar: \''.$this->toolbarname.'\',
  184. toolbarStartupExpanded: '.($this->toolbarstartexpanded ? 'true' : 'false').',
  185. width: '.($this->width ? '\''.$this->width.'\'' : '\'\'').',
  186. height: '.$this->height.',
  187. skin: \''.$skin.'\',
  188. '.$scaytautostartup.'
  189. language: \''.$langs->defaultlang.'\',
  190. textDirection: \''.$langs->trans("DIRECTION").'\',
  191. on : {
  192. instanceReady : function( ev )
  193. {
  194. // Output paragraphs as <p>Text</p>.
  195. this.dataProcessor.writer.setRules( \'p\', {
  196. indent : false,
  197. breakBeforeOpen : true,
  198. breakAfterOpen : false,
  199. breakBeforeClose : false,
  200. breakAfterClose : true
  201. });
  202. }
  203. },
  204. disableNativeSpellChecker: '.(empty($conf->global->CKEDITOR_NATIVE_SPELLCHECKER) ? 'true' : 'false');
  205. if ($this->uselocalbrowser) {
  206. $out .= ','."\n";
  207. // To use filemanager with old fckeditor (GPL)
  208. $out .= ' filebrowserBrowseUrl : ckeditorFilebrowserBrowseUrl,';
  209. $out .= ' filebrowserImageBrowseUrl : ckeditorFilebrowserImageBrowseUrl,';
  210. //$out.= ' filebrowserUploadUrl : \''.DOL_URL_ROOT.'/includes/fckeditor/editor/filemanagerdol/connectors/php/upload.php?Type=File\',';
  211. //$out.= ' filebrowserImageUploadUrl : \''.DOL_URL_ROOT.'/includes/fckeditor/editor/filemanagerdol/connectors/php/upload.php?Type=Image\',';
  212. $out .= "\n";
  213. // To use filemanager with ckfinder (Non free) and ckfinder directory is inside htdocs/includes
  214. /* $out.= ' filebrowserBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html\',
  215. filebrowserImageBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html?Type=Images\',
  216. filebrowserFlashBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html?Type=Flash\',
  217. filebrowserUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files\',
  218. filebrowserImageUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images\',
  219. filebrowserFlashUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash\','."\n";
  220. */
  221. $out .= ' filebrowserWindowWidth : \'900\',
  222. filebrowserWindowHeight : \'500\',
  223. filebrowserImageWindowWidth : \'900\',
  224. filebrowserImageWindowHeight : \'500\'';
  225. }
  226. $out .= ' })'.$morejs; // end CKEditor.replace
  227. // Show the CKEditor javascript object once loaded is ready 'For debug)
  228. //$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]); }); ';
  229. $out .= '});'."\n"; // end document.ready
  230. $out .= '</script>'."\n";
  231. }
  232. }
  233. // Output editor ACE
  234. // Warning: ace.js and ext-statusbar.js must be loaded by the parent page.
  235. if (preg_match('/^ace/', $this->tool)) {
  236. $found = 1;
  237. $format = $option;
  238. $out .= "\n".'<!-- Output Ace editor -->'."\n";
  239. if ($titlecontent) {
  240. $out .= '<div class="aceeditorstatusbar" id="statusBar'.$this->htmlname.'">'.$titlecontent;
  241. $out .= ' &nbsp; - &nbsp; <a id="morelines" href="#" class="right morelines'.$this->htmlname.' reposition">'.dol_escape_htmltag($langs->trans("ShowMoreLines")).'</a> &nbsp; &nbsp; ';
  242. $out .= '</div>';
  243. $out .= '<script type="text/javascript">'."\n";
  244. $out .= 'jQuery(document).ready(function() {'."\n";
  245. $out .= ' var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid");
  246. aceEditor.moveCursorTo('.($this->posy+1).','.$this->posx.');
  247. aceEditor.gotoLine('.($this->posy+1).','.$this->posx.');
  248. var StatusBar = window.ace.require("ace/ext/statusbar").StatusBar; // Init status bar. Need lib ext-statusbar
  249. var statusBar = new StatusBar(aceEditor, document.getElementById("statusBar'.$this->htmlname.'")); // Init status bar. Need lib ext-statusbar
  250. var oldNbOfLines = 0;
  251. jQuery(".morelines'.$this->htmlname.'").click(function() {
  252. var aceEditorClicked = window.ace.edit("'.$this->htmlname.'aceeditorid");
  253. currentline = aceEditorClicked.getOption("maxLines");
  254. if (oldNbOfLines == 0)
  255. {
  256. oldNbOfLines = currentline;
  257. }
  258. console.log("We click on more lines, oldNbOfLines is "+oldNbOfLines+", we have currently "+currentline);
  259. if (currentline < 500)
  260. {
  261. aceEditorClicked.setOptions({ maxLines: 500 });
  262. }
  263. else
  264. {
  265. aceEditorClicked.setOptions({ maxLines: oldNbOfLines });
  266. }
  267. });
  268. })';
  269. $out .= '</script>'."\n";
  270. }
  271. $out .= '<pre id="'.$this->htmlname.'aceeditorid" style="'.($this->width ? 'width: '.$this->width.'px; ' : '');
  272. $out .= ($this->height ? ' height: '.$this->height.'px; ' : '');
  273. //$out.=" min-height: 100px;";
  274. $out .= '">';
  275. $out .= htmlspecialchars($this->content);
  276. $out .= '</pre>';
  277. $out .= '<input type="hidden" id="'.$this->htmlname.'_x" name="'.$this->htmlname.'_x">';
  278. $out .= '<input type="hidden" id="'.$this->htmlname.'_y" name="'.$this->htmlname.'_y">';
  279. $out .= '<textarea id="'.$this->htmlname.'" name="'.$this->htmlname.'" style="width:0px; height: 0px; display: none;">';
  280. $out .= htmlspecialchars($this->content);
  281. $out .= '</textarea>';
  282. $out .= '<script type="text/javascript">'."\n";
  283. $out .= 'var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid");
  284. aceEditor.session.setMode("ace/mode/'.$format.'");
  285. aceEditor.setOptions({
  286. enableBasicAutocompletion: true, // the editor completes the statement when you hit Ctrl + Space. Need lib ext-language_tools.js
  287. enableLiveAutocompletion: false, // the editor completes the statement while you are typing. Need lib ext-language_tools.js
  288. showPrintMargin: false, // hides the vertical limiting strip
  289. minLines: 10,
  290. maxLines: '.(empty($this->height) ? '34' : (round($this->height / 10))).',
  291. fontSize: "110%" // ensures that the editor fits in the environment
  292. });
  293. // defines the style of the editor
  294. aceEditor.setTheme("ace/theme/chrome");
  295. // hides line numbers (widens the area occupied by error and warning messages)
  296. //aceEditor.renderer.setOption("showLineNumbers", false);
  297. // ensures proper autocomplete, validation and highlighting of JavaScript code
  298. //aceEditor.getSession().setMode("ace/mode/javascript_expression");
  299. '."\n";
  300. $out .= 'jQuery(document).ready(function() {
  301. jQuery(".buttonforacesave").click(function() {
  302. console.log("We click on savefile button for component '.dol_escape_js($this->htmlname).'");
  303. var aceEditor = window.ace.edit("'.dol_escape_js($this->htmlname).'aceeditorid");
  304. if (aceEditor) {
  305. var cursorPos = aceEditor.getCursorPosition();
  306. //console.log(cursorPos);
  307. if (cursorPos) {
  308. jQuery("#'.dol_escape_js($this->htmlname).'_x").val(cursorPos.column);
  309. jQuery("#'.dol_escape_js($this->htmlname).'_y").val(cursorPos.row);
  310. }
  311. //console.log(aceEditor.getSession().getValue());
  312. // Inject content of editor into the original HTML field.
  313. jQuery("#'.dol_escape_js($this->htmlname).'").val(aceEditor.getSession().getValue());
  314. /*if (jQuery("#'.dol_escape_js($this->htmlname).'").html().length > 0) return true;
  315. else return false;*/
  316. return true;
  317. } else {
  318. console.log("Failed to retrieve js object ACE from its name");
  319. return false;
  320. }
  321. });
  322. })';
  323. $out .= '</script>'."\n";
  324. }
  325. if (empty($found)) {
  326. $out .= 'Error, unknown value for tool '.$this->tool.' in DolEditor Create function.';
  327. }
  328. if ($noprint) {
  329. return $out;
  330. } else {
  331. print $out;
  332. }
  333. }
  334. }