doleditor.class.php 19 KB

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