### Install Kodbox from Source or Download
Source: https://github.com/kalcaddle/kodbox/blob/main/README.md
Instructions to install Kodbox either by cloning the Git repository or by downloading and unzipping the main archive. Both methods require setting appropriate file permissions (chmod 777) for the Kodbox directory.
```bash
# Install from source
git clone https://github.com/kalcaddle/kodbox.git
chmod -Rf 777 ./kodbox/*
# Install via download
wget https://github.com/kalcaddle/kodbox/archive/refs/heads/main.zip
unzip main.zip
chmod -Rf 777 ./*
```
--------------------------------
### Deploy Kodbox from Source or Downloaded Package
Source: https://github.com/kalcaddle/kodbox/blob/main/README_zh-CN.md
Instructions for deploying Kodbox, either by cloning the GitHub repository or by downloading and unzipping a release package. Both methods require setting appropriate file permissions after installation.
```Bash
# Through source code installation
git clone https://github.com/kalcaddle/kodbox.git
chmod -Rf 777 ./kodbox/*
```
```Bash
# Through downloaded package installation
wget https://github.com/kalcaddle/kodbox/archive/refs/heads/main.zip
unzip main.zip
chmod -Rf 777 ./*
```
--------------------------------
### HTML.Allowed Directive Configuration Syntax Examples
Source: https://github.com/kalcaddle/kodbox/blob/main/app/sdks/HtmlPurifier/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt
Illustrates the syntax for specifying allowed HTML elements and their attributes using the HTML.Allowed directive. Examples include defining element-specific attributes, allowing specific elements, and applying attributes globally using an asterisk. Newlines can also be used to separate elements.
```Configuration
element1[attr1|attr2],element2...
a[href],p
*[lang]
```
--------------------------------
### JavaScript Dynamic Host Detection and Global Variable Setup
Source: https://github.com/kalcaddle/kodbox/blob/main/app/template/user/index.html
This self-executing JavaScript function dynamically determines the application's host URL, especially for reverse proxy scenarios, and stores it in a cookie. It also sets global `API_HOST` and `STATIC_PATH` variables using PHP-generated values and attempts to register a service worker.
```javascript
(function(){// 自适应url,反向代理未设置header情况兼容; var a = document.createElement("a");a.href = window.location.href; var urlPath = a.pathname.replace(/^([^\\/])/, "/$1").replace('/index.php','/'); var host = a.protocol.replace(":", "") + "://" + a.hostname + (a.port ? ':' + a.port : ''); if(host + urlPath == ''){return;} var cookieKey = 'KOD_HOST_'+'' var date = new Date((new Date()).getTime() + 90*3600*24*1000); document.cookie = cookieKey+'='+host+'/; expires='+date.toGMTString()+';'; console.warn("Site host not match HOST",[cookieKey,host + urlPath,'']); })(); window.API_HOST = ""; window.STATIC_PATH = ""; try{navigator.serviceWorker && navigator.serviceWorker.register('?user/view/manifestJS');}catch(err){} if(!navigator.mimeTypes) navigator.mimeTypes = {};
```
--------------------------------
### Render TeX Expression Directly to DOM with katex.render (JavaScript)
Source: https://github.com/kalcaddle/kodbox/blob/main/static/app/vender/markdown/katex/README.md
This JavaScript example illustrates how to use the 'katex.render' function to directly render a TeX math expression into a specified HTML DOM element. It includes an option to prevent errors from being thrown, instead displaying the source in red.
```JavaScript
katex.render("c = \\pm\\sqrt{a^2 + b^2}", element, {
throwOnError: false
});
```
--------------------------------
### Generate HTML String from TeX Expression with katex.renderToString (JavaScript)
Source: https://github.com/kalcaddle/kodbox/blob/main/static/app/vender/markdown/katex/README.md
This JavaScript example demonstrates the 'katex.renderToString' function, which generates an HTML string representation of a rendered TeX math expression. This is particularly useful for server-side rendering, allowing the pre-rendered HTML to be sent to the client.
```JavaScript
var html = katex.renderToString("c = \\pm\\sqrt{a^2 + b^2}", {
throwOnError: false
});
// '...'
```
--------------------------------
### PHP Example: Extracting and Purifying Style Blocks
Source: https://github.com/kalcaddle/kodbox/blob/main/app/sdks/HtmlPurifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt
This PHP code demonstrates how to use the `Filter.ExtractStyleBlocks` directive with HTMLPurifier and CSSTidy. It initializes HTMLPurifier, configures it to extract style blocks, purifies a sample HTML string containing a style block, and then retrieves the cleaned style blocks from the purifier's context. The example then writes these extracted stylesheets to a 'styles/' directory and links them in the HTML output, illustrating a common usage pattern for managing extracted CSS.
```PHP
';
?>
Filter.ExtractStyleBlocks
body {color:#F00;} Some text';
$config = HTMLPurifier_Config::createDefault();
$config->set('Filter', 'ExtractStyleBlocks', true);
$purifier = new HTMLPurifier($config);
$html = $purifier->purify($dirty);
// This implementation writes the stylesheets to the styles/ directory.
// You can also echo the styles inside the document, but it's a bit
// more difficult to make sure they get interpreted properly by
// browsers; try the usual CSS armoring techniques.
$styles = $purifier->context->get('StyleBlocks');
$dir = 'styles/';
if (!is_dir($dir)) mkdir($dir);
$hash = sha1($_GET['html']);
foreach ($styles as $i => $style) {
file_put_contents($name = $dir . $hash . "_$i");
echo '';
}
?>
```
--------------------------------
### Core.EnableIDNA Configuration Details
Source: https://github.com/kalcaddle/kodbox/blob/main/app/sdks/HtmlPurifier/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt
Provides a comprehensive overview of the Core.EnableIDNA configuration option. This boolean setting, introduced in version 4.4.0, enables the use of international domain names in URLs by converting them to punycode. It requires the PEAR Net_IDNA2 module to be installed for proper functionality, ensuring maximum portability across systems.
```APIDOC
Core.EnableIDNA
TYPE: bool
DEFAULT: false
VERSION: 4.4.0
DESCRIPTION: Allows international domain names in URLs. This configuration option
requires the PEAR Net_IDNA2 module to be installed. It operates by
punycoding any internationalized host names for maximum portability.
```
--------------------------------
### Setup KityFormula Editor View and LaTeX Toggle
Source: https://github.com/kalcaddle/kodbox/blob/main/static/app/vender/tinymce/plugins/kitymath/index.html
Defines the `initEditView` function, which initializes the editor's display with a default math expression and adds a LaTeX toggle button. This button allows users to switch between the visual editor and a raw LaTeX text area, updating the editor content based on the selected mode.
```JavaScript
var initEditView = function(){
var math = window.defaultMath || "\\placeholder";
kfe.execCommand('render',math);
kfe.execCommand('focus');
if(window.defaultMath){
setValueMath(window.defaultMath,100);
}
var html = '\\
latex
\\ ';
$(html).appendTo('.kf-editor-edit-area');
var $editor = $('.latex-editor');
$('.latex-toggle').bind('click',function(){
var isEdit = $(this).hasClass('active');
if(isEdit){
var value = $editor.find('.math').val();
$(this).removeClass('active');
$editor.addClass('hidden');
kfe.execCommand('render',value);
}else{
var value = kfe.execCommand('get.source');
$(this).addClass('active');
$editor.removeClass('hidden');
$editor.find('.math').val(value).focus();
setTimeout(function() {
$editor.find('.math').focus();
},20);
}
});
}
```
--------------------------------
### JavaScript Global Variables and Time Utility for Kodbox
Source: https://github.com/kalcaddle/kodbox/blob/main/static/app/vender/tinymce/demo.html
Initializes global JavaScript variables for the Kodbox application, including a dynamic version number based on current timestamp, API host URL, and static file path. It also defines a 'time' function to get the current timestamp in seconds.
```JavaScript
var time = function(){var theTime=(new Date).valueOf();return parseInt(theTime/1e3)};
window.G = {kod:{version:time()}}
window.API_HOST = "/kod/kodbox/index.php?";
window.STATIC_PATH = "/kod/kodbox/static/";
```
--------------------------------
### Attr.IDPrefix Configuration Attribute
Source: https://github.com/kalcaddle/kodbox/blob/main/app/sdks/HtmlPurifier/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt
Details the Attr.IDPrefix configuration attribute, which allows adding a prefix to user-submitted HTML IDs to prevent conflicts with existing page IDs. It specifies the attribute's type, version, default value, and provides an example of its usage. This directive requires %HTML.EnableAttrID to be set to true for it to function.
```APIDOC
Attr.IDPrefix
TYPE: string
VERSION: 1.2.0
DEFAULT: ''
DESCRIPTION: String to prefix to IDs. If you have no idea what IDs your pages may use, you may opt to simply add a prefix to all user-submitted ID attributes so that they are still usable, but will not conflict with core page IDs. Example: setting the directive to 'user_' will result in a user submitted 'foo' to become 'user_foo'. Be sure to set %HTML.EnableAttrID to true before using this.
```
--------------------------------
### Display Localized Text in PHP
Source: https://github.com/kalcaddle/kodbox/blob/main/app/controller/install/static/index.html
This PHP snippet demonstrates how to output localized strings using the `LNG` function. It's commonly used in templates to display dynamic, language-specific content such as copyright notices or installation messages.
```PHP
-
```
--------------------------------
### PHP Example: Setting HTML.DefinitionID and Adding Custom Attribute
Source: https://github.com/kalcaddle/kodbox/blob/main/app/sdks/HtmlPurifier/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt
Demonstrates how to set the HTML.DefinitionID directive using HTMLPurifier_Config and add a custom attribute ('tabindex' to 'a' tags) using the advanced API. This example highlights the necessity of DefinitionID to prevent cache conflicts when directly manipulating the HTML definition.
```PHP
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML', 'DefinitionID', '1');
$def = $config->getHTMLDefinition();
$def->addAttribute('a', 'tabindex', 'Number');
```
--------------------------------
### Integrate KaTeX with Basic HTML Template
Source: https://github.com/kalcaddle/kodbox/blob/main/static/app/vender/markdown/katex/README.md
This HTML snippet demonstrates how to include KaTeX CSS and JavaScript files from a CDN into a web page. It shows the necessary 'link' for the stylesheet and 'script' tags for the core KaTeX library and the auto-render extension, which automatically renders math within text elements upon page load.
```HTML
...
```
--------------------------------
### Initialize KityFormula Editor and Loading Screen
Source: https://github.com/kalcaddle/kodbox/blob/main/static/app/vender/tinymce/plugins/kitymath/index.html
This JavaScript snippet uses jQuery to initialize the KityFormula editor upon document ready. It displays a loading screen, creates the editor instance, and sets up a global reference (`window.kfe`) once the editor is ready. It also includes a fallback for older browsers.
```JavaScript
$( function ($) { if (document.body.addEventListener ) { $( "#tips").html('
正在加载,请耐心等待...
' ); var factory = kf.EditorFactory.create($("#kfEditorContainer" )\[ 0 \], { render: {fontsize: 24}, resource: { path: "./kityformula/resource/" } } ); factory.ready(function(KFEditor) { window.kfe = this; initEditView(); }); } else { $( "#tips").css( "color", "black" ); $( "#tips").css( "padding", "10px" ); } });
```
--------------------------------
### Version 1.17 Update (2021.02.22)
Source: https://github.com/kalcaddle/kodbox/blob/main/ChangeLog.md
Major update focusing on file internal property acquisition performance and PWA installation support.
```APIDOC
Version_1_17_Update:
ReleaseDate: 2021.02.22
KeyAdditions:
- File internal property acquisition performance optimization.
- PWA installation support.
FileManagement:
- File internal property acquisition performance optimized.
- Editing and saving files: Compatibility for saving empty content.
- Object storage property acquisition performance optimized (size, exist, info, isFolder, isFile cache handling); applies to Qiniu, Alibaba OSS, S3, S3Like, etc.
- WebDAV mount login failure fixed; detection of user desktop folder deletion after mounting.
OtherOptimizations:
- PWA installation compatible with latest Chrome (configuration changes).
- Task management: Terminated task info automatically cleared; max 30 tasks in list; task data queried by user (UserOption).
- Scheduled tasks auto-start: Unexpected stop re-triggers start.
- Compatibility: Some servers binding object storage fail to get size after upload fixed; log write failures ignored; SSO federated login compatible with private HTTPS certificates; operation log, login log filter 'today' handling (query user handling); empty detection call not supported handling.
- Detail optimizations: File attribute filename too long display optimized; external link sharing, internal collaboration sharing bottom space increased, department selection button; H5 tree directory folder right-click menu, paste removed; video display duration position/size optimized; document properties, with image title, sticky and favorite buttons; update text optimized; document advanced properties, Chinese garbled issue fixed; mobile H5 rename style position optimized; dialog size adjustment four corner handling; shared folder H5 removes file tree directory sliding; no extension file icon display optimized; mobile gesture scroll element interception; favorite item right-click menu: shared folder right-click menu adds more folder/file functions; tree directory right-click menu removes paste; Dplayer video player plugin settings interface handling; formMaker slider style optimized; external link sharing video file sharing page player style optimized; OSS object storage MD5 information handling.
BugFixes:
- Moving folders: Sub-content in recycle bin, folder moved maintains deleted status (recycle bin removal changes deleted status).
- External link shared folder requiring login fixed.
```
--------------------------------
### HTML.Parent Configuration Property
Source: https://github.com/kalcaddle/kodbox/blob/main/app/sdks/HtmlPurifier/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt
Defines the string name of the HTML element that will serve as the parent for HTML fragments inserted into the library. For example, using 'span' as the parent would restrict allowed tags to inline elements.
```APIDOC
HTML.Parent:
TYPE: string
VERSION: 1.3.0
DEFAULT: 'div'
DESCRIPTION: String name of element that HTML fragment passed to library will be inserted in. An interesting variation would be using span as the parent element, meaning that only inline tags would be allowed.
```
--------------------------------
### Initialize Kodbox SDK and File Information in JavaScript
Source: https://github.com/kalcaddle/kodbox/blob/main/plugins/officeViewer/static/jsoffice/template.html
This snippet initializes the Kodbox SDK configuration, including API host, and sets up global JavaScript variables. The `FILE_INFO` object contains essential details about the current file, such as its URL, name, save path, write permissions, and file type, dynamically populated using PHP variables. It also includes JavaScript `link()` calls for loading SDK and core CSS assets.
```JavaScript
var kodSdkConfig = {api:''}; link('app/dist/sdk.js','static');?> link('app/dist/sdk.js','static');?> link('style/lib/font-icon/style.css','static');?> link('static/jsoffice/page.css');?> var BASE_URL = "pluginHost.'static/';?>"; var BASE_URL_API = "pluginApi;?>"; var FILE_INFO = { fileUrl: '', // 获取url fileName: '', // 文件名 savePath: '', // 文件路径;有则可以直接保存;没有且canWrite则可以另存为; canWrite: '', // 是否可写; 可写才能编辑; fileApp: '', // 文件打开方式 fileExt: '' // 文件后缀 };
```
--------------------------------
### PHP Display Localized Copyright and Title
Source: https://github.com/kalcaddle/kodbox/blob/main/app/template/user/index.html
This PHP snippet dynamically outputs the application's title and copyright information using localized strings. It relies on a `LNG()` function for internationalization.
```php
```
--------------------------------
### API Reference: URI.DisableResources Property
Source: https://github.com/kalcaddle/kodbox/blob/main/app/sdks/HtmlPurifier/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt
This property is a boolean that, when set to true, disables the embedding of resources such as pictures, though linking to them remains possible. It was introduced in version 1.3.0 but only became functional starting from version 4.2.0. It is related to URI.DisableExternalResources.
```APIDOC
URI.DisableResources
TYPE: bool
VERSION: 4.2.0
DEFAULT: false
DESCRIPTION:
Disables embedding resources, essentially meaning no pictures. You can
still link to them though. See %URI.DisableExternalResources for why
this might be a good idea.
Note: While this directive has been available since 1.3.0,
it didn't actually start doing anything until 4.2.0.
```
--------------------------------
### CSS Styles for Loading Screen and Dark Mode
Source: https://github.com/kalcaddle/kodbox/blob/main/app/template/user/index.html
Defines CSS rules for a loading animation and dark mode background. The `.bg-black` class sets a dark background, while `.loading-body div` styles a loading spinner, with a specific dark mode variant.
```css
.bg-black{background:#333;} .loading-body div{ position:fixed;margin:auto;left:0;top:0;right:0;bottom:0;max-width:64px; max-height:64px;width:64px;border-radius:4px;opacity:0.8;background-size: contain; background-image:url(""); } .bg-black .loading-body div,.dark-mode .loading-body div{ width:36px;height:36px; background-image:url(""); }
```
--------------------------------
### Configure JavaScript Global Variables with PHP
Source: https://github.com/kalcaddle/kodbox/blob/main/app/controller/install/static/index.html
This JavaScript code initializes global variables `window.API_HOST` and `window.STATIC_PATH`. The values are dynamically inserted by PHP functions (`appHostGet()` and `STATIC_PATH`), which is a common pattern for passing server-side configurations to the client-side.
```JavaScript
window.API_HOST = ""; window.STATIC_PATH = "";
```
--------------------------------
### JavaScript WebOffice Viewer Initialization and Iframe Loading
Source: https://github.com/kalcaddle/kodbox/blob/main/plugins/officeViewer/static/weboffice/template.html
Initializes the WebOffice viewer by checking the `FILE_INFO.app` variable. If the application type is 'yz', 'lb', or 'ol', it adds a corresponding class to the body and loads the document into an iframe. A `setTimeout` is used to add a 'loaded' class to the body after the iframe content has loaded, indicating the viewer is ready.
```JavaScript
$(function(){ // 非wb方式添加到iframe中
var app = FILE_INFO.app;
if (app == 'yz' || app == 'lb' || app == 'ol') {
$('body').addClass(app);
// var sandbox = 'allow-forms allow-popups allow-scripts allow-modals allow-same-origin';
// $('#output').html('');
$('#output').html('');
// wb方式在数据加载完成后添加
$('#output>iframe').on('load', function() {
setTimeout(function(){$('body.weboffice-page').addClass('loaded');}, 1000);
});
}
```
--------------------------------
### JavaScript: Register and Activate Service Worker
Source: https://github.com/kalcaddle/kodbox/blob/main/static/app/vender/zip/mitm.html
This function handles the registration of the `sw.js` Service Worker with a scope of './'. It first attempts to get an existing registration, then registers if none exists, and finally ensures the active Service Worker is referenced, waiting for activation if necessary.
```JavaScript
function registerWorker() {
return navigator.serviceWorker.getRegistration('./').then(swReg => {
return swReg || navigator.serviceWorker.register('sw.js', { scope: './' })
}).then(swReg => {
const swRegTmp = swReg.installing || swReg.waiting
scope = swReg.scope
return (sw = swReg.active) || new Promise(resolve => {
swRegTmp.addEventListener('statechange', fn = () => {
if (swRegTmp.state === 'activated') {
swRegTmp.removeEventListener('statechange', fn)
sw = swReg.active
resolve()
}
})
})
})
}
```
--------------------------------
### PHP and JavaScript Initialization for WebOffice Viewer
Source: https://github.com/kalcaddle/kodbox/blob/main/plugins/officeViewer/static/weboffice/template.html
Initializes JavaScript variables with PHP-generated values for the WebOffice viewer. This includes API endpoints, base URLs, and critical file information such as link, name, path, application, extension, and write permissions. These variables are essential for the viewer's functionality and interaction with the backend.
```PHP/JavaScript
var kodSdkConfig = {api:''};
link('app/dist/sdk.js','static');?>
link('style/lib/font-icon/style.css','static');?>
link('static/weboffice/page.css');?>
var BASE_URL = "pluginHost.'static/';?>";
var BASE_URL_API = "pluginApi;?>";
var FILE_INFO = {
link: '', // 获取url
name: '', // 文件名
path: '', // 文件路径;有则可以直接保存;没有且canWrite则可以另存为;
app: '', // 文件打开方式
ext: '', // 文件后缀
write: '' // 是否可写; 可写才能编辑;
};
var lang = {edit:""}
```
--------------------------------
### URI.SafeIframeRegexp API Reference
Source: https://github.com/kalcaddle/kodbox/blob/main/app/sdks/HtmlPurifier/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt
This entry details the URI.SafeIframeRegexp directive, which is a PCRE regular expression for matching against iframe URIs. It's designed for common use-cases like embedded videos and requires HTML.SafeIframe to be enabled. The documentation includes its type, version, default value, and examples of valid regex patterns.
```APIDOC
URI.SafeIframeRegexp
TYPE: string/null
VERSION: 4.4.0
DEFAULT: NULL
DESCRIPTION:
A PCRE regular expression that will be matched against an iframe URI. This is a relatively inflexible scheme, but works well enough for the most common use-case of iframes: embedded video. This directive only has an effect if %HTML.SafeIframe is enabled. Here are some example values:
- %^http://www.youtube.com/embed/% - Allow YouTube videos
- %^http://player.vimeo.com/video/% - Allow Vimeo videos
- %^http://(www.youtube.com/embed/|player.vimeo.com/video/)% - Allow both
Note that this directive does not give you enough granularity to, say, disable all autoplay videos. Pipe up on the HTML Purifier forums if this is a capability you want.
```
--------------------------------
### JavaScript Apply Dark Mode Based on User/System Preference
Source: https://github.com/kalcaddle/kodbox/blob/main/app/template/user/index.html
This JavaScript code detects if the user's system prefers a dark color scheme and checks a stored user option for 'dark-mode' or 'auto'. If dark mode is active, it applies the 'bg-black' class to the body element.
```javascript
var isDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; var theTheme = "get('theme');?>"; var darkMode = theTheme == 'dark-mode' ? true: (theTheme == 'auto' && isDark); if(darkMode){document.getElementsByTagName('body')[0].setAttribute("class","bg-black");}
```
--------------------------------
### TinyMCE Editor Initialization and Configuration
Source: https://github.com/kalcaddle/kodbox/blob/main/static/app/vender/tinymce/demo.html
This JavaScript snippet defines the complete configuration for the TinyMCE editor instance. It sets up the toolbar items, available plugins, menu structure, custom color palette, and various advanced options like HTML filtering, element protection, and paste behavior. It also includes a custom `menuBarInit` function to re-arrange the menubar and an event listener for double-click actions on specific elements (images, links, media) to open their respective editing dialogs.
```JavaScript
var toolbar = [ 'lect | alignleft aligncenter alignright alignjustify lineheight | formatpainter preview codeView fullscreen ', 'bold italic underline strikethrough forecolor backcolor removeformat | numlist bullist indent outdent |hr blockquote emoticons link image table' ];
var plugins = [ 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image', 'link media codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist', 'lists textcolor wordcount imagetools contextmenu paste colorpicker textpattern help lineheight quickbars', 'bdmap emoticons checklist pageembed formatpainter kitymath codeView' ];
var menubarList = 'menuFormate menuInsert menuMore';
var colorMap = [ '#FFFFFF','c-white','#cfd8dc','','#ffccbc','','#ffecb3','','#fff9c4','','#dcedc8','','#b2ebf2','','#e6f7ff','','#d1c4e9','', '#D9D9D9','','#90a4ae','','#ff8a65','','#ffd54f','','#fff176','','#aed581','','#4dd0e1','','#91d5ff','','#9575cd','', '#969696','','#607d8b','','#ff5722','','#ffc107','','#ffeb3b','','#8bc34a','','#00bcd4','','#40a9ff','','#673ab7','', '#525252','','#455a64','','#e64a19','','#ffa000','','#fbc02d','','#689f38','','#0097a7','','#1890ff','','#512da8','', '#000000','','#263238','','#bf360c','','#ff6f00','','#f57f17','','#33691e','','#006064','','#006dd2','','#311b92','', ];
var menuBarInit = function(editor){
window.teditor = editor;
var $main = $(editor.editorContainer);
var $menubar = $main.find('.tox-menubar');
var $toolbar = $main.find(".tox-toolbar").first();
$menubar = $menubar.appendTo($toolbar);
$menubar.prev().addClass('menubar-prev');
$main.find(".toc-i-icon").each(function(){
var $btn = $(this).parents('.tox-split-button,.tox-tbtn');
if($btn.length == 1){
$btn.addClass('toc-i-'+$(this).attr('key'));
}
});
var menubarArr = menubarList.split(' ');
$menubar.find('.tox-mbtn').each(function(index){
$(this).addClass('mce-i-'+menubarArr[index]);
});
editor.on('DblClick',function(e){
var $target = $(e.target);
if(!$target[0].tagName) return;
var tag = $target[0].tagName.toLowerCase();
switch(tag){
case 'img':
if($target.hasClass('mce-object-video')){
editor.execCommand('mceMedia');
}else if(!$target.hasClass('mce-object')){
editor.execCommand('mceImage');
}
break;
case 'a' :editor.execCommand('mceLink');break;
case 'span':
if( $target.hasClass('mce-preview-object') && $target.hasClass('mce-object-iframe')){
editor.execCommand('mceMedia');
}
break;
default:break;
}
});
}
var STATIC_PATH = '/kod/kodbox/static/';
tinymce.init({
selector:'.aaa',
theme: "silver",
content_css: [ './kod/content.css', STATIC_PATH+'app/vender/markdown/katex/katex.min.css', ],
theme_advanced_font_sizes:sizeArr.join(','),
fontsize_formats:sizeArr.join(' '),
font_formats:fontArr.join(';'),
menu:menuList,
menubar:menubarList,
language: 'zh_CN',
plugins: plugins,
toolbar: toolbar,
toolbar_groups: toolbarGroup,
browser_spellcheck: true,
color_cols:9,
color_map:colorMap,
resize: 'both',
toolbar_mode:'sliding',
draggable_modal: true,
branding: false,
contextmenu: "bold copy cut | align | link format | insert | table",
quickbars_insert_toolbar:false,
quickbars_selection_toolbar: 'bold italic underline | h2 h3 blockquote link',
width:1200,height:600,
cache_suffix: '?v=4.1.6',
allow_conditional_comments:true,
verify_html: false,
extended_valid_elements : "i[*],span[*],div[*]",
remove_trailing_brs: false,
protect:[ /\\<\\/?(if|endif)\\>/g, /\\]+\\>/g, /<\\?php.*?\\?>/g, ],
paste_webkit_styles: 'color,background,width,height,vertical-align,'+ 'text-align,padding,margin,padding-top,padding-bottom,line-height',
file_browser_callback_types: 'image',
file_browser_callback: function(field_name,url,type,win) { return false; },
setup:function(editor){
editor.on('preinit',function(){
loadPluginReset(editor);
addIcon(editor);
resetMenus(editor);
});
},
init_instance_callback:function(editor){
}
});
```
--------------------------------
### Initialize Baidu Map GL with Marker and Info Window
Source: https://github.com/kalcaddle/kodbox/blob/main/app/template/tools/map.html
This JavaScript code initializes a Baidu Map GL instance, centers it on coordinates (longitude, latitude) retrieved from URL parameters, and adds a marker at that point. It enables scroll wheel zoom, adds map controls, and optionally displays an image from a src URL parameter within an info window that opens on map load and marker click.
```javascript
var map = new BMapGL.Map("allmap");
var point = new BMapGL.Point(_GET('longitude'),_GET('latitude'));
map.centerAndZoom(point, 15);
map.enableScrollWheelZoom(true);//开启鼠标滚轮缩放
map.addControl(new BMapGL.ScaleControl());
map.addControl(new BMapGL.MapTypeControl());
var marker = new BMapGL.Marker(new BMapGL.Point(_GET('longitude'),_GET('latitude')));
map.addOverlay(marker);
var imageSrc = _GET('src');
if(imageSrc){ var infoWindow = new BMapGL.InfoWindow("",{width:80,height:120,title:''}); map.openInfoWindow(infoWindow, point); marker.addEventListener('click', function () { map.openInfoWindow(infoWindow, point); }); }
```
--------------------------------
### JavaScript for Baidu Map Initialization and Interaction
Source: https://github.com/kalcaddle/kodbox/blob/main/static/app/vender/tinymce/plugins/bdmap/map.html
Initializes a Baidu Map instance, sets its initial view, adds navigation controls, and includes logic for IP-based city centering and geocoding. It also handles map click events to capture and display coordinates, updating `parent.tinymceLng` and `parent.tinymceLat` variables for external use.
```JavaScript
var map, geocoder;
var lng,lat;
function initialize() {
map = new BMap.Map('map_canvas');
var point = new BMap.Point(116.331398,39.897445);
map.centerAndZoom(point, 14);
map.addControl(new BMap.NavigationControl());
//map.enableScrollWheelZoom();
//根据IP定位
var myCity = new BMap.LocalCity();
myCity.get(function(result){map.setCenter(result.name);});
//浏览器定位,位置更准确,但需要弹出确认,扰民弃用
/*var gl = new BMap.Geolocation();
gl.getCurrentPosition(function(r){ if(this.getStatus() == BMAP_STATUS_SUCCESS){
var mk = new BMap.Marker(r.point);
map.addOverlay(mk);
map.panTo(r.point);
}else {
//alert('failed'+this.getStatus());
} },{enableHighAccuracy: true})*/
var gc = new BMap.Geocoder();
gc.getLocation(point, function(rs){
var addComp = rs.addressComponents;
var address = [addComp.city].join('');
//console.log(address);
});
map.addEventListener('click',function(e){
//alert(e.point.lng + "," + e.point.lat);
lng=e.point.lng;
lat=e.point.lat;
var marker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat));
map.clearOverlays();
map.addOverlay(marker);
//insCnt(lng+','+lat);
parent.tinymceLng=lng;
parent.tinymceLat=lat;
});
document.getElementById('kw').addEventListener('keypress',function(e){
if(e.keyCode=='13'){
e.preventDefault();
searchByStationName();
}
});
}
```
--------------------------------
### HTML.Attr.Name.UseCDATA Configuration Attribute
Source: https://github.com/kalcaddle/kodbox/blob/main/app/sdks/HtmlPurifier/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt
Defines the behavior for parsing HTML attribute names. When set to true, it enables relaxed parsing rules, allowing for duplicate names or names that would typically be illegal IDs (e.g., starting with a digit). This addresses limitations in the W3C DTD specification and is useful when such relaxed behavior is desired in certain documents.
```APIDOC
HTML.Attr.Name.UseCDATA:
TYPE: bool
DEFAULT: false
VERSION: 4.0.0
DESCRIPTION: The W3C specification DTD defines the name attribute to be CDATA, not ID, due to limitations of DTD. In certain documents, this relaxed behavior is desired, whether it is to specify duplicate names, or to specify names that would be illegal IDs (for example, names that begin with a digit.) Set this configuration directive to true to use the relaxed parsing rules.
```
--------------------------------
### JavaScript Edit Button for WebOffice Viewer (Page Mode)
Source: https://github.com/kalcaddle/kodbox/blob/main/plugins/officeViewer/static/weboffice/template.html
Defines a JavaScript function `editBtnPage` that handles the 'edit' button functionality when the viewer is not in a dialog. It makes an AJAX call to `pluginApi/editApp` to get application-specific edit information. Based on the response, it updates the UI (adds 'edit-mode' class, sets `apptype`) and handles click events to redirect the user to the editing URL or display error messages.
```JavaScript
var editBtnPage = function(){
var appRes = null;
$.ajax({
url:"pluginApi.'editApp';?>",
data: {path: FILE_INFO.path, name: FILE_INFO.name, ext: FILE_INFO.ext},
dataType:'json',
success:function(result){
appRes = result;
if (result.code){
$('body.weboffice-page').addClass('edit-mode');
$('body.weboffice-page>.edit-btn button').attr('apptype', result.info);
}
}
});
// 点击编辑
$('body.weboffice-page>.edit-btn button').click(function(){
if (!appRes || !appRes.code) {
var code = appRes.info ? 'warning' : false;
return Tips.tips(appRes.data, code);
}
window.location.href = appRes.data;
});
}
```
--------------------------------
### system_option Table: System Configuration
Source: https://github.com/kalcaddle/kodbox/blob/main/app/controller/install/data/help.md
Outlines the schema for the `system_option` table, used to store system-wide configuration settings as key-value pairs. It supports different configuration types.
```APIDOC
system_option Table:
id: int(11) unsigned (Auto-incrementing ID)
type: varchar(50) (Configuration type)
key: varchar(255) (Key)
value: text (Value)
createTime: int(11) unsigned (Creation timestamp)
modifyTime: int(11) unsigned (Last update timestamp)
```
--------------------------------
### PHP Dynamic Script Loading for WebOffice Viewers
Source: https://github.com/kalcaddle/kodbox/blob/main/plugins/officeViewer/static/weboffice/template.html
PHP `switch` statement to dynamically load JavaScript and CSS assets based on the detected office document type (e.g., Mammoth.js for documents, LuckySheet for spreadsheets, PPTX.js for presentations, SheetJS). This ensures that only necessary libraries are loaded for a given file, optimizing performance.
```PHP
link('static/weboffice/page.js');?>
link('static/weboffice/mammothjs/mammoth.browser.kod.1.4.20--.js');
$this->link('static/weboffice/mammothjs/mammoth.browser.kod.1.4.20.min.js');
$this->link('static/weboffice/mammothjs/index.css');
$this->link('static/weboffice/mammothjs/index.js');
break;
case 'luckysheet':
$this->link('static/weboffice/luckysheet/plugins/css/pluginsCss.css');
$this->link('static/weboffice/luckysheet/plugins/plugins.css');
$this->link('static/weboffice/luckysheet/css/luckysheet.css');
$this->link('static/weboffice/luckysheet/assets/iconfont/iconfont.min.css');
$this->link('static/weboffice/luckysheet/index.css');
$this->link('static/weboffice/luckysheet/plugins/js/plugin.js');
$this->link('static/weboffice/luckysheet/luckysheet.umd.js');
$this->link('static/weboffice/luckysheet/luckyexcel.umd.min.js');
$this->link('static/weboffice/sheetjs/xlsx.core.min.js');
$this->link('static/weboffice/luckysheet/utils.js');
$this->link('static/weboffice/luckysheet/index.js');
break;
case 'pptxjs':
$this->link('static/weboffice/pptxjs/css/pptxjs.css');
$this->link('static/weboffice/pptxjs/css/nv.d3.min.css');
$this->link('static/weboffice/pptxjs/index.css');
$this->link('static/weboffice/pptxjs/js/jquery-1.11.3.min.js');
$this->link('static/weboffice/pptxjs/js/jszip.min.js');
$this->link('static/weboffice/pptxjs/js/filereader.js');
$this->link('static/weboffice/pptxjs/js/d3.min.js');
$this->link('static/weboffice/pptxjs/js/nv.d3.min.js');
$this->link('static/weboffice/pptxjs/js/dingbat.js');
$this->link('static/weboffice/pptxjs/js/pptxjs.kod.1.21.1.min.js');
$this->link('static/weboffice/pptxjs/js/divs2slides.min.js');
$this->link('static/weboffice/pptxjs/utils.js');
$this->link('static/weboffice/pptxjs/index.js');
break;
case 'sheetjs':
$this->link('static/weboffice/sheetjs/index.css');
$this->link('static/weboffice/sheetjs/xlsx.core.min.js');
$this->link('static/weboffice/sheetjs/index.js');
break;
default:break;
}?>
```
--------------------------------
### HTML.XHTML Configuration Property Details
Source: https://github.com/kalcaddle/kodbox/blob/main/app/sdks/HtmlPurifier/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt
Provides comprehensive documentation for the `HTML.XHTML` property, including its data type, default value, versioning information (introduction and deprecation), suggested alternative, and a detailed description of its function.
```APIDOC
HTML.XHTML:
TYPE: bool
DEFAULT: true
VERSION: 1.1.0
DEPRECATED-VERSION: 1.7.0
DEPRECATED-USE: HTML.Doctype
ALIASES: Core.XHTML
DESCRIPTION: Determines whether or not output is XHTML 1.0 or HTML 4.01 flavor.
```
--------------------------------
### Load PPTX.js Assets for Presentation Viewing (PHP)
Source: https://github.com/kalcaddle/kodbox/blob/main/plugins/officeViewer/static/jsoffice/template.html
This PHP snippet outlines the conditional loading of CSS and JavaScript assets for the PPTX.js presentation viewer. It includes core PPTX.js files, jQuery, JSZip, D3.js, and other libraries necessary for rendering PowerPoint presentations.
```PHP
case 'pptxjs': $this->link('static/jsoffice/pptxjs/css/pptxjs.css'); $this->link('static/jsoffice/pptxjs/css/nv.d3.min.css'); $this->link('static/jsoffice/pptxjs/index.css'); $this->link('static/jsoffice/pptxjs/js/jquery-1.11.3.min.js'); $this->link('static/jsoffice/pptxjs/js/jszip.min.js'); $this->link('static/jsoffice/pptxjs/js/filereader.js'); $this->link('static/jsoffice/pptxjs/js/d3.min.js'); $this->link('static/jsoffice/pptxjs/js/nv.d3.min.js'); $this->link('static/jsoffice/pptxjs/js/dingbat.js'); $this->link('static/jsoffice/pptxjs/js/pptxjs.kod.1.21.1.min.js'); // $this->link('static/jsoffice/pptxjs/js/pptxjs.kod.1.21.1--.js'); $this->link('static/jsoffice/pptxjs/js/divs2slides.min.js'); // $this->link('static/jsoffice/pptxjs/js/jquery.fullscreen-min.js'); $this->link('static/jsoffice/pptxjs/utils.js'); $this->link('static/jsoffice/pptxjs/index.js'); break;
```
--------------------------------
### AutoFormat.DisplayLinkURI Directive Reference
Source: https://github.com/kalcaddle/kodbox/blob/main/app/sdks/HtmlPurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt
Provides a detailed reference for the AutoFormat.DisplayLinkURI directive, outlining its data type, the version it was introduced, its default setting, and a comprehensive explanation of its effect on URI display and linking within HTML tags.
```APIDOC
Directive Name: AutoFormat.DisplayLinkURI
Type: bool
Version: 3.2.0
Default Value: false
Description: This directive turns on the in-text display of URIs in tags, and disables those links. For example, example becomes example (http://example.com).
```