index.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. <?php
  2. /*
  3. FusionPBX
  4. Version: MPL 1.1
  5. The contents of this file are subject to the Mozilla Public License Version
  6. 1.1 (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.mozilla.org/MPL/
  9. Software distributed under the License is distributed on an "AS IS" basis,
  10. WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. for the specific language governing rights and limitations under the
  12. License.
  13. The Original Code is FusionPBX
  14. The Initial Developer of the Original Code is
  15. Mark J Crane <[email protected]>
  16. Portions created by the Initial Developer are Copyright (C) 2008-2024
  17. the Initial Developer. All Rights Reserved.
  18. Contributor(s):
  19. Mark J Crane <[email protected]>
  20. James Rose <[email protected]>
  21. */
  22. //includes files
  23. require_once dirname(__DIR__, 2) . "/resources/require.php";
  24. require_once "resources/check_auth.php";
  25. //check permissions
  26. if (permission_exists('edit_view')) {
  27. //access granted
  28. }
  29. else {
  30. echo "access denied";
  31. exit;
  32. }
  33. //add multi-lingual support
  34. $language = new text;
  35. $text = $language->get();
  36. //set the directory title and mode
  37. $_SESSION["app"]["edit"]["dir"] = $_GET["dir"];
  38. $title = escape($_GET["dir"]);
  39. unset($mode);
  40. switch ($_GET["dir"]) {
  41. case 'xml':
  42. $title = 'XML';
  43. $mode = 'xml';
  44. break;
  45. case 'provision':
  46. $title = 'Provision';
  47. $mode = 'xml';
  48. break;
  49. case 'php':
  50. $title = 'PHP';
  51. $mode = 'php';
  52. break;
  53. case 'scripts':
  54. $title = 'Scripts';
  55. $mode = 'lua';
  56. break;
  57. case 'grammar':
  58. $title = 'Grammar';
  59. $mode = 'xml';
  60. default: $mode = 'text';
  61. }
  62. //load editor preferences/defaults
  63. $setting_size = !empty($_SESSION["editor"]["font_size"]["text"]) ? $_SESSION["editor"]["font_size"]["text"] : '12px';
  64. $setting_theme = !empty($_SESSION["editor"]["theme"]["text"]) ? $_SESSION["editor"]["theme"]["text"] : 'cobalt';
  65. $setting_invisibles = isset($_SESSION['editor']['invisibles']['text']) ? $_SESSION['editor']['invisibles']["text"] : 'false';
  66. $setting_indenting = isset($_SESSION['editor']['indent_guides']['text']) ? $_SESSION['editor']['indent_guides']["text"]: 'false';
  67. $setting_numbering = isset($_SESSION['editor']['line_numbers']['text']) ? $_SESSION['editor']['line_numbers']["text"] : 'true';
  68. //get and then set the favicon
  69. if (isset($_SESSION['theme']['favicon']['text'])){
  70. $favicon = $_SESSION['theme']['favicon']['text'];
  71. }
  72. else {
  73. $favicon = PROJECT_ROOT .'/themes/default/favicon.ico';
  74. }
  75. //create a token
  76. $key_name = '/app/edit/'.$mode;
  77. $_SESSION['keys'][$key_name] = bin2hex(random_bytes(32));
  78. $_SESSION['token'] = hash_hmac('sha256', $key_name, $_SESSION['keys'][$key_name]);
  79. //The buffer must be empty
  80. while(ob_get_level() > 0)
  81. ob_get_clean();
  82. ?><!doctype html>
  83. <html>
  84. <head>
  85. <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
  86. <title><?php echo $title; ?></title>
  87. <link rel="icon" type="image/x-icon" href="<?php echo $favicon; ?>">
  88. <link rel='stylesheet' type='text/css' href='<?php echo PROJECT_PATH; ?>/resources/fontawesome/css/all.min.css.php'>
  89. <script language="JavaScript" type="text/javascript" src="<?php echo PROJECT_PATH; ?>/resources/jquery/jquery-3.6.1.min.js"></script>
  90. <script src='https://code.jquery.com/jquery-migrate-3.1.0.js'></script>
  91. <script language="JavaScript" type="text/javascript">
  92. function submit_check() {
  93. if (document.getElementById('filepath').value != '') {
  94. document.getElementById('editor_source').value = editor.getSession().getValue();
  95. return true;
  96. }
  97. focus_editor();
  98. return false;
  99. }
  100. function toggle_option(opt) {
  101. switch (opt) {
  102. case 'numbering': toggle_option_do('showLineNumbers'); toggle_option_do('fadeFoldWidgets'); break;
  103. case 'invisibles': toggle_option_do('showInvisibles'); break;
  104. case 'indenting': toggle_option_do('displayIndentGuides'); break;
  105. }
  106. focus_editor();
  107. }
  108. function toggle_option_do(opt_name) {
  109. var opt_val = editor.getOption(opt_name);
  110. editor.setOption(opt_name, ((opt_val) ? false : true));
  111. }
  112. function toggle_sidebar() {
  113. var td_sidebar = document.getElementById('sidebar');
  114. if (td_sidebar.style.display == '') {
  115. document.getElementById('td_save').style.paddingLeft = '12px';
  116. td_sidebar.style.display = 'none';
  117. }
  118. else {
  119. document.getElementById('td_save').style.paddingLeft = '0';
  120. td_sidebar.style.display = '';
  121. }
  122. focus_editor();
  123. }
  124. function insert_clip(before, after) {
  125. var selected_text = editor.session.getTextRange(editor.getSelectionRange());
  126. editor.insert(before + selected_text + after);
  127. focus_editor();
  128. }
  129. function focus_editor() {
  130. editor.focus();
  131. }
  132. function http_request(url, form_data) {
  133. var http = new XMLHttpRequest();
  134. http.open('POST', url, true);
  135. //http.onload = function(e) { ... };
  136. http.onload = function(e) {
  137. if (this.status == 200) {
  138. //data sent successfully
  139. alert(this.responseText);
  140. }
  141. else {
  142. alert('<?php echo $text['message-problem']; ?>');
  143. }
  144. };
  145. http.send(form_data);
  146. }
  147. function save() {
  148. var form_data = new FormData();
  149. form_data.append('filepath', document.getElementById('filepath').value);
  150. form_data.append('content', editor.getSession().getValue());
  151. form_data.append('token',document.getElementById('token').value);
  152. form_data.append('mode',"<?php echo $mode; ?>");
  153. http_request('file_save.php', form_data);
  154. }
  155. </script>
  156. <style>
  157. div#editor {
  158. box-shadow: 0 5px 15px #333;
  159. }
  160. i.ace_control {
  161. cursor: pointer;
  162. margin-right: 5px;
  163. opacity: 0.5;
  164. }
  165. i.ace_control:hover {
  166. opacity: 1.0;
  167. }
  168. </style>
  169. </head>
  170. <body style="padding: 0; margin: 0; overflow: hidden;">
  171. <div id="frame" style="display: flex; height: 100vh; width: 100vw;">
  172. <!-- Sidebar -->
  173. <div id="sidebar" style="width: 300px; height: 100%; display: flex; flex-direction: column;">
  174. <div id="file_list" style="border: none; height: 65%; width: 100%; overflow: auto;">
  175. Loading...
  176. </div>
  177. <div id="clip_list" style="border: none; border-top: 1px solid #ccc; height: calc(35% - 1px); width: 100%; overflow: auto;">
  178. Loading...
  179. </div>
  180. </div>
  181. <!-- Main Content -->
  182. <div id="ace_content" style="flex: 1; height: 100%; display: flex; flex-direction: column;">
  183. <!-- Editor Controls -->
  184. <form style="margin: 0;" name="frm_edit" id="frm_edit" method="post" action="file_save.php" onsubmit="return submit_check();">
  185. <textarea name="content" id="editor_source" style="display: none;"></textarea>
  186. <input type="hidden" name="filepath" id="filepath" value="">
  187. <input type="hidden" name="token" id="token" value="<?php echo $_SESSION['token']; ?>">
  188. <div id="editor-controls" style="display: flex; align-items: center; width: 100%; height: 30px;">
  189. <div id="td_save" style="display: inline-flex; align-items: center;">
  190. <i class="fas fa-save fa-lg ace_control" title="<?php echo $text['label-save_changes']; ?>" onclick="save();"></i>
  191. </div>
  192. <div style="flex: 1; padding: 0 15px 0 18px;">
  193. <input id="current_file" type="text" style="height: 23px; width: 100%;">
  194. </div>
  195. <div style="width: 1px; height: 40px;"></div>
  196. <div style="padding-left: 6px;">
  197. <i class="fas fa-window-maximize fa-lg fa-rotate-270 ace_control" title="<?php echo $text['label-toggle_side_bar']; ?>" onclick="toggle_sidebar();"></i>
  198. </div>
  199. <div style="padding-left: 6px;">
  200. <i class="fas fa-list-ul fa-lg ace_control" title="<?php echo $text['label-toggle_line_numbers']; ?>" onclick="toggle_option('numbering');"></i>
  201. </div>
  202. <div style="padding-left: 6px;">
  203. <i class="fas fa-eye-slash fa-lg ace_control" title="<?php echo $text['label-toggle_invisibles']; ?>" onclick="toggle_option('invisibles');"></i>
  204. </div>
  205. <div style="padding-left: 6px;">
  206. <i class="fas fa-indent fa-lg ace_control" title="<?php echo $text['label-toggle_indent_guides']; ?>" onclick="toggle_option('indenting');"></i>
  207. </div>
  208. <div style="padding-left: 6px;">
  209. <i class="fas fa-search fa-lg ace_control" title="<?php echo $text['label-find_replace']; ?>" onclick="editor.execCommand('replace');"></i>
  210. </div>
  211. <div style="padding-left: 6px;">
  212. <i class="fas fa-chevron-down fa-lg ace_control" title="<?php echo $text['label-go_to_line']; ?>" onclick="editor.execCommand('gotoline');"></i>
  213. </div>
  214. <div style="padding-left: 15px;">
  215. <select id="mode" style="height: 23px; max-width: 70px;" onchange="editor.getSession().setMode('ace/mode/' + this.options[this.selectedIndex].value); focus_editor();">
  216. <?php
  217. $modes['php'] = 'PHP';
  218. $modes['css'] = 'CSS';
  219. $modes['html'] = 'HTML';
  220. $modes['javascript'] = 'JS';
  221. $modes['json'] = 'JSON';
  222. $modes['ini'] = 'Conf';
  223. $modes['lua'] = 'Lua';
  224. $modes['text'] = 'Text';
  225. $modes['xml'] = 'XML';
  226. $modes['sql'] = 'SQL';
  227. $modes['sh'] = 'SH';
  228. $modes['smarty'] = 'Smarty';
  229. $modes['svg'] = 'SVG';
  230. $modes['makefile'] = 'Makefile';
  231. $modes['c_cpp'] = 'C';
  232. $modes['c_cpp'] = 'CPP';
  233. $modes['pgsql'] = 'PGSQL';
  234. foreach ($modes as $value => $label) {
  235. $selected = ($value == $mode) ? 'selected' : null;
  236. echo "<option value='".$value."' ".$selected.">".$label."</option>\n";
  237. }
  238. ?>
  239. </select>
  240. </div>
  241. <div style="padding-left: 4px;">
  242. <select id="size" style="height: 23px;" onchange="document.getElementById('editor').style.fontSize = this.options[this.selectedIndex].value; focus_editor();">
  243. <?php
  244. $sizes = explode(',','9px,10px,11px,12px,14px,16px,18px,20px');
  245. if (!in_array($setting_size, $sizes)) {
  246. echo "<option value='".$setting_size."'>".$setting_size."</option>\n";
  247. echo "<option value='' disabled='disabled'></option>\n";
  248. }
  249. foreach ($sizes as $size) {
  250. $selected = ($size == $setting_size) ? 'selected' : null;
  251. echo "<option value='".$size."' ".$selected.">".$size."</option>\n";
  252. }
  253. ?>
  254. </select>
  255. </div>
  256. <div style="padding-left: 4px; padding-right: 4px;">
  257. <select id="theme" style="height: 23px; max-width: 100px;" onchange="editor.setTheme('ace/theme/' + this.options[this.selectedIndex].value); focus_editor();">
  258. <?php
  259. $themes['Bright']['chrome']= 'Chrome';
  260. $themes['Bright']['clouds']= 'Clouds';
  261. $themes['Bright']['crimson_editor']= 'Crimson Editor';
  262. $themes['Bright']['dawn']= 'Dawn';
  263. $themes['Bright']['dreamweaver']= 'Dreamweaver';
  264. $themes['Bright']['eclipse']= 'Eclipse';
  265. $themes['Bright']['github']= 'GitHub';
  266. $themes['Bright']['iplastic']= 'IPlastic';
  267. $themes['Bright']['solarized_light']= 'Solarized Light';
  268. $themes['Bright']['textmate']= 'TextMate';
  269. $themes['Bright']['tomorrow']= 'Tomorrow';
  270. $themes['Bright']['xcode']= 'XCode';
  271. $themes['Bright']['kuroir']= 'Kuroir';
  272. $themes['Bright']['katzenmilch']= 'KatzenMilch';
  273. $themes['Bright']['sqlserver']= 'SQL Server';
  274. $themes['Dark']['ambiance']= 'Ambiance';
  275. $themes['Dark']['chaos']= 'Chaos';
  276. $themes['Dark']['clouds_midnight']= 'Clouds Midnight';
  277. $themes['Dark']['cobalt']= 'Cobalt';
  278. $themes['Dark']['idle_fingers']= 'idle Fingers';
  279. $themes['Dark']['kr_theme']= 'krTheme';
  280. $themes['Dark']['merbivore']= 'Merbivore';
  281. $themes['Dark']['merbivore_soft']= 'Merbivore Soft';
  282. $themes['Dark']['mono_industrial']= 'Mono Industrial';
  283. $themes['Dark']['monokai']= 'Monokai';
  284. $themes['Dark']['pastel_on_dark']= 'Pastel on dark';
  285. $themes['Dark']['solarized_dark']= 'Solarized Dark';
  286. $themes['Dark']['terminal']= 'Terminal';
  287. $themes['Dark']['tomorrow_night']= 'Tomorrow Night';
  288. $themes['Dark']['tomorrow_night_blue']= 'Tomorrow Night Blue';
  289. $themes['Dark']['tomorrow_night_bright']= 'Tomorrow Night Bright';
  290. $themes['Dark']['tomorrow_night_eighties']= 'Tomorrow Night 80s';
  291. $themes['Dark']['twilight']= 'Twilight';
  292. $themes['Dark']['vibrant_ink']= 'Vibrant Ink';
  293. foreach ($themes as $optgroup => $theme) {
  294. echo "<optgroup label='".$optgroup."'>\n";
  295. foreach ($theme as $value => $label) {
  296. $selected = (strtolower($label) == strtolower($setting_theme)) ? 'selected' : null;
  297. echo "<option value='".$value."' ".$selected.">".$label."</option>\n";
  298. }
  299. echo "</optgroup>\n";
  300. }
  301. ?>
  302. </select>
  303. </div>
  304. </div>
  305. </form>
  306. <!-- Editor -->
  307. <div id="editor" style="text-align: left; width: 100%; height: calc(100% - 30px); font-size: 12px;"></div>
  308. </div>
  309. </div>
  310. <script src="<?php echo PROJECT_PATH; ?>/resources/ace/ace.js" charset="utf-8"></script>
  311. <script src="<?php echo PROJECT_PATH; ?>/resources/ace/ext-inline_autocomplete.js"></script>
  312. <script>
  313. // Load ACE extensions
  314. ace.require("ace/ext/language_tools");
  315. // Initialize ACE Editor
  316. var editor = ace.edit("editor");
  317. editor.setOptions({
  318. mode: 'ace/mode/<?=$mode?>',
  319. theme: 'ace/theme/'+document.getElementById('theme').options[document.getElementById('theme').selectedIndex].value,
  320. selectionStyle: 'text',
  321. cursorStyle: 'smooth',
  322. showInvisibles: <?=$setting_invisibles?>,
  323. displayIndentGuides: <?=$setting_indenting?>,
  324. showLineNumbers: <?=$setting_numbering?>,
  325. showGutter: true,
  326. scrollPastEnd: true,
  327. fadeFoldWidgets: <?=$setting_numbering?>,
  328. showPrintMargin: false,
  329. highlightGutterLine: false,
  330. useSoftTabs: false,
  331. enableBasicAutocompletion: true,
  332. enableLiveAutocompletion: true,
  333. enableSnippets: true
  334. });
  335. // Prevent form submission with Enter key
  336. <?php key_press('enter', 'down', '#current_file', null, null, 'return false;', false); ?>
  337. // Save file with Ctrl+S
  338. <?php key_press('ctrl+s', 'down', 'window', null, null, "save(); return false;", false); ?>
  339. // Open file manager/clip library pane with Ctrl+Q
  340. <?php key_press('ctrl+q', 'down', 'window', null, null, 'toggle_sidebar(); focus_editor(); return false;', false); ?>
  341. // Remove unwanted shortcuts
  342. editor.commands.bindKey("Ctrl-T", null); // Disable new browser tab shortcut
  343. // Function to fetch PHP class methods using fetch() with promises
  344. async function fetch_php_methods() {
  345. try {
  346. let response = await fetch('/resources/get_php_methods.php');
  347. if (!response.ok) throw new Error("Failed to load PHP methods.");
  348. return await response.json();
  349. } catch (error) {
  350. console.error("Error fetching PHP methods:", error);
  351. return {}; // Return empty object on failure
  352. }
  353. }
  354. // Initialize ACE auto-completion after fetching PHP methods
  355. async function init_ace_completion() {
  356. let phpMethods = await fetch_php_methods();
  357. // Custom completer for PHP class methods
  358. var php_class_completer = {
  359. getCompletions: function(editor, session, pos, prefix, callback) {
  360. // Get the current line text
  361. var line = session.getLine(pos.row);
  362. // Use regex to detect object (->) or static (::) access
  363. const objectMatch = line.match(/(\w+)\s*->\s*\w*$/);
  364. const staticMatch = line.match(/(\w+)::\w*$/);
  365. // Extract the referenced class name (simple name)
  366. var ref_name = objectMatch ? objectMatch[1] : (staticMatch ? staticMatch[1] : null);
  367. if (!ref_name) return callback(null, []);
  368. // Try to match the simple class name (case-insensitive) with one of the keys in phpMethods.
  369. // The keys in phpMethods may be fully-qualified names (with namespaces).
  370. var matched_class = null;
  371. for (var key in phpMethods) {
  372. // Get the simple class name from the key
  373. var parts = key.split("\\");
  374. var simple_name = parts[parts.length - 1];
  375. if (simple_name.toLowerCase() === ref_name.toLowerCase()) {
  376. matched_class = key;
  377. break;
  378. }
  379. }
  380. // If no matching class is found, return an empty list.
  381. if (!matched_class) return callback(null, []);
  382. // Map the methods of the matched class into completions.
  383. var completions = phpMethods[matched_class].map(function(method) {
  384. if (staticMatch !== null) {
  385. if (method.static) {
  386. return {
  387. caption: method.name + method.params,
  388. snippet: method.name + method.params.replace(/\$/g, "\\$"),
  389. meta: matched_class,
  390. docHTML: method.doc ? method.doc : "No Documentation"
  391. };
  392. } else {
  393. return {};
  394. }
  395. }
  396. //you can call a static method on an object instance because php is like that
  397. return {
  398. caption: method.name + method.params,
  399. snippet: method.name + method.params.replace(/\$/g, "\\$"),
  400. meta: matched_class,
  401. docHTML: method.doc ? method.doc : "No Documentation"
  402. };
  403. });
  404. callback(null, completions);
  405. }
  406. };
  407. // Initialize ACE Editor (assumes 'editor' is already created)
  408. ace.require("ace/ext/language_tools");
  409. // Override the default completions with our custom completer
  410. editor.completers = [php_class_completer];
  411. // Ensure font size is set
  412. document.getElementById('editor').style.fontSize='<?=$setting_size?>';
  413. focus_editor();
  414. }
  415. // Run auto-completion setup
  416. init_ace_completion();
  417. </script>
  418. </body>
  419. <script>
  420. fetch('clip_list.php')
  421. .then(response => {
  422. if (!response.ok) {
  423. throw new Error('Network response was not ok');
  424. }
  425. return response.text();
  426. })
  427. .then(html => {
  428. document.getElementById('clip_list').innerHTML = html;
  429. })
  430. .catch(error => {
  431. console.error('Error fetching clip_list:', error);
  432. });
  433. async function loadFileList() {
  434. try {
  435. const response = await fetch('file_list.php');
  436. if (!response.ok) {
  437. throw new Error('Network response not okay');
  438. }
  439. const html = await response.text();
  440. document.getElementById('file_list').innerHTML = html;
  441. } catch (error) {
  442. console.error('Error fetching files:', error);
  443. }
  444. }
  445. function makeRequest(url, strpost) {
  446. var http_request = false;
  447. if (window.XMLHttpRequest) { // Mozilla, Safari, ...
  448. http_request = new XMLHttpRequest();
  449. if (http_request.overrideMimeType) {
  450. http_request.overrideMimeType('text/xml');
  451. // See note below about this line
  452. }
  453. } else if (window.ActiveXObject) { // IE
  454. try {
  455. http_request = new ActiveXObject("Msxml2.XMLHTTP");
  456. } catch (e) {
  457. try {
  458. http_request = new ActiveXObject("Microsoft.XMLHTTP");
  459. } catch (e) {}
  460. }
  461. }
  462. if (!http_request) {
  463. alert('<?=$text['message-give-up']?>');
  464. return false;
  465. }
  466. http_request.onreadystatechange = function() { returnContent(http_request); };
  467. if (http_request.overrideMimeType) {
  468. http_request.overrideMimeType('text/html');
  469. }
  470. http_request.open('POST', url, true);
  471. if (strpost.length == 0) {
  472. //http_request.send(null);
  473. http_request.send('name=value&foo=bar');
  474. }
  475. else {
  476. http_request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  477. http_request.send(strpost);
  478. }
  479. }
  480. function returnContent(http_request) {
  481. if (http_request.readyState === 4) {
  482. if (http_request.status === 200) {
  483. document.getElementById('editor_source').value=http_request.responseText;
  484. editor.getSession().setValue(document.getElementById('editor_source').value);
  485. editor.gotoLine(1);
  486. editor.scrollToLine(1, true, true, function() {});
  487. editor.focus();
  488. }
  489. else {
  490. alert('<?=$text['message-problem']?>');
  491. }
  492. }
  493. }
  494. // ---------------------------------------------
  495. // --- http://www.codeproject.com/jscript/dhtml_treeview.asp
  496. // --- Name: Easy DHTML Treeview --
  497. // --- Author: D.D. de Kerf --
  498. // --- Version: 0.2 Date: 13-6-2001 --
  499. // ---------------------------------------------
  500. function Toggle(node) {
  501. // Unfold the branch if it isn't visible
  502. if (node.nextSibling.style.display == 'none') {
  503. node.nextSibling.style.display = 'block';
  504. }
  505. // Collapse the branch if it IS visible
  506. else {
  507. node.nextSibling.style.display = 'none';
  508. }
  509. }
  510. // Load files from server
  511. loadFileList();
  512. </script>
  513. </html>