Example #1
0
if (getConfigVar('DB_VERSION') != CODE_VERSION) {
    echo '<p align=justify>This Racktables installation seems to be ' . 'just upgraded to version ' . CODE_VERSION . ', while the ' . 'database version is ' . getConfigVar('DB_VERSION') . '.<br>No user will be ' . 'either authenticated or shown any page until the upgrade is ' . "finished.<br>Follow <a href='?module=upgrade'>this link</a> and " . 'authenticate as administrator to finish the upgrade.</p>';
    exit(1);
}
if (!mb_internal_encoding('UTF-8')) {
    throw new RackTablesError('Failed setting multibyte string encoding to UTF-8', RackTablesError::INTERNAL);
}
$rackCodeCache = loadScript('RackCodeCache');
if ($rackCodeCache == NULL or !strlen($rackCodeCache)) {
    $rackCode = getRackCode(loadScript('RackCode'));
    saveScript('RackCodeCache', base64_encode(serialize($rackCode)));
} else {
    $rackCode = unserialize(base64_decode($rackCodeCache));
    if ($rackCode === FALSE) {
        saveScript('RackCodeCache', '');
        $rackCode = getRackCode(loadScript('RackCode'));
    }
}
// avoid notices being thrown
date_default_timezone_set(getConfigVar('DATETIME_ZONE'));
// Depending on the 'result' value the 'load' carries either the
// parse tree or error message. The latter case is a bug, because
// RackCode saving function was supposed to validate its input.
if ($rackCode['result'] != 'ACK') {
    throw new RackTablesError($rackCode['load'], RackTablesError::INTERNAL);
}
$rackCode = $rackCode['load'];
// Only call buildPredicateTable() once and save the result, because it will remain
// constant during one execution for constraints processing.
$pTable = buildPredicateTable($rackCode);
// Constraints parse trees aren't cached in the database, so the least to keep
<?php

/**
 * @author Olagoke Adedamola Farouq <*****@*****.**>
 * @copyright (c) 2016, Olagoke Adedamola Farouq
 * @package DIOHandler
 */
defined('DAMMYFRAMEWORKPHP') or die('Cannot process request!!');
/**
 * This class manages all mysql database business
 */
loadScript('DDatabaseInterface', 'lib.io');
class DMYSQLDatabase extends DDatabaseInterface
{
}
Example #3
0
function getSLBDefaults($do_cache_result = FALSE)
{
    static $ret = array();
    if (!$do_cache_result) {
        $ret = array();
    } elseif (!empty($ret)) {
        return $ret;
    }
    $ret['vsconfig'] = loadScript('DefaultVSConfig');
    $ret['rsconfig'] = loadScript('DefaultRSConfig');
    return $ret;
}
Example #4
0
function getScript($js, $application = NULL, $extra = NULL, $getJs = FALSE)
{
    $HTML = NULL;
    if (file_exists($js)) {
        return loadScript($js);
    } else {
        if (isset($application)) {
            return loadScript($js, $application);
        } else {
            if ($js === "jquery") {
                return loadScript("lib/scripts/js/jquery.js");
            } elseif ($js === "external") {
                $HTML = '	<script type="text/javascript">
								$(document).ready(function() { 
									$(function() {
										$(\'a[rel*=external]\').click(function() {
											window.open(this.href);
											return false;
										});
									});
								});
							</script>				
							
							<noscript><p class="NoDisplay">' . __("Disable Javascript") . '</p></noscript>';
            } elseif ($js === "show-element") {
                $HTML = '	<script type="text/javascript">
								function showElement(obj) {
									if(obj.className == "no-display") {
										obj.className = "display";
									} else {
										obj.className = "no-display";
									}
								}
							</script>';
            } elseif ($js === "tiny-mce") {
                $HTML = loadScript("www/lib/scripts/js/tiny_mce/tiny_mce.js");
                $HTML .= '<script type="text/javascript">';
                if ($extra !== "basic") {
                    $HTML .= '			
									tinyMCE.init({
										mode : "exact",
										elements : "editor",
										theme : "advanced",
										skin : "o2k7",
										cleanup: true,
										plugins : "advcode,safari,pagebreak,style,advhr,advimage,advlink,emotions,preview,media,fullscreen,template,inlinepopups,advimage,media,paste",              
										theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,|,link,unlink,|,image,advcode,|,forecolor,|,charmap,|,pastetext,pasteword,pastetext,fullscreen,pagebreak,preview",
										theme_advanced_buttons2 : "",
										theme_advanced_buttons3 : "",
										theme_advanced_toolbar_location : "top",
										theme_advanced_toolbar_align : "left",
										theme_advanced_statusbar_location : "bottom",
										theme_advanced_resizing : false,
										convert_urls : false,                    
										content_CSS : "css/content.css",               
										external_link_list_url : "lists/link_list.js",
										external_image_list_url : "lists/image_list.js",
										media_external_list_url : "lists/media_list.js"
									});
							';
                } else {
                    $HTML .= '		
									tinyMCE.init({
										mode : "exact",
										elements : "editor",
										theme : "simple",
										editor_selector : "mceSimple"
									});
							';
                }
                $HTML .= '	function insertHTML(content) {
								parent.tinyMCE.execCommand(\'mceInsertContent\', false, content);
							}
						</script>';
            }
            return $HTML;
        }
    }
}
Example #5
0
function renderRackCodeEditor()
{
    addJS('js/codemirror/codemirror.js');
    addJS('js/codemirror/rackcode.js');
    addCSS('js/codemirror/codemirror.css');
    addJS(<<<ENDJAVASCRIPT
function verify()
{
\t\$.ajax({
\t\ttype: "POST",
\t\turl: "index.php",
\t\tdata: {'module': 'ajax', 'ac': 'verifyCode', 'code': \$("#RCTA").text()},
\t\tsuccess: function (data)
\t\t{
\t\t\tarr = data.split("\\n");
\t\t\tif (arr[0] == "ACK")
\t\t\t{
\t\t\t\t\$("#SaveChanges")[0].disabled = "";
\t\t\t\t\$("#ShowMessage")[0].innerHTML = "Code verification OK, don't forget to save the code";
\t\t\t\t\$("#ShowMessage")[0].className = "msg_success";
\t\t\t}
\t\t\telse
\t\t\t{
\t\t\t\t\$("#SaveChanges")[0].disabled = "disabled";
\t\t\t\t\$("#ShowMessage")[0].innerHTML = arr[1];
\t\t\t\t\$("#ShowMessage")[0].className = "msg_warning";
\t\t\t}
\t\t}
\t});
}

\$(document).ready(function() {
\t\$("#SaveChanges")[0].disabled = "disabled";
\t\$("#ShowMessage")[0].innerHTML = "";
\t\$("#ShowMessage")[0].className = "";

\tvar rackCodeMirror = CodeMirror.fromTextArea(document.getElementById("RCTA"),{
\t\tmode:'rackcode',
\t\tlineNumbers:true });
\trackCodeMirror.on("change",function(cm,cmChangeObject){
\t\t\$("#RCTA").text(cm.getValue());
    });
});
ENDJAVASCRIPT
, TRUE);
    $text = loadScript('RackCode');
    printOpFormIntro('saveRackCode');
    echo '<table style="width:100%;border:1px;" border=0 align=center>';
    echo "<tr><td><textarea rows=40 cols=100 name=rackcode id=RCTA class='codepress rackcode'>";
    echo $text . "</textarea></td></tr>\n";
    echo "<tr><td align=center>";
    echo '<div id="ShowMessage"></div>';
    echo "<input type='button' value='Verify' onclick='verify();'>";
    echo "<input type='submit' value='Save' disabled='disabled' id='SaveChanges' onclick='\$(RCTA).toggleEditor();'>";
    //	printImageHREF ('SAVE', 'Save changes', TRUE);
    echo "</td></tr>";
    echo '</table>';
    echo "</form>";
}
Example #6
0
function authenticated_via_ldap_cache($username, $password, &$ldap_displayname)
{
    global $LDAP_options, $auto_tags;
    // Destroy the cache each time config changes.
    if (sha1(serialize($LDAP_options)) != loadScript('LDAPConfigHash')) {
        discardLDAPCache();
        saveScript('LDAPConfigHash', sha1(serialize($LDAP_options)));
    }
    $oldinfo = acquireLDAPCache($username, sha1($password), $LDAP_options['cache_expiry']);
    if ($oldinfo === NULL) {
        // On cache miss execute complete procedure and return the result. In case
        // of successful authentication put a record into cache.
        $newinfo = queryLDAPServer($username, $password);
        if ($newinfo['result'] == 'ACK') {
            $ldap_displayname = $newinfo['displayed_name'];
            foreach ($newinfo['memberof'] as $autotag) {
                $auto_tags[] = array('tag' => $autotag);
            }
            replaceLDAPCacheRecord($username, sha1($password), $newinfo['displayed_name'], $newinfo['memberof']);
            releaseLDAPCache();
            discardLDAPCache($LDAP_options['cache_expiry']);
            return TRUE;
        }
        releaseLDAPCache();
        return FALSE;
    }
    // cache HIT
    // There are two confidence levels of cache hits: "certain" and "uncertain". In either case
    // expect authentication success, unless it's well-timed to perform a retry,
    // which may sometimes bring a NAK decision.
    if ($oldinfo['success_age'] < $LDAP_options['cache_refresh'] or $oldinfo['retry_age'] < $LDAP_options['cache_retry']) {
        releaseLDAPCache();
        $ldap_displayname = $oldinfo['displayed_name'];
        foreach ($oldinfo['memberof'] as $autotag) {
            $auto_tags[] = array('tag' => $autotag);
        }
        return TRUE;
    }
    // Either refresh threshold or retry threshold reached.
    $newinfo = queryLDAPServer($username, $password);
    switch ($newinfo['result']) {
        case 'ACK':
            // refresh existing record
            $ldap_displayname = $newinfo['displayed_name'];
            foreach ($newinfo['memberof'] as $autotag) {
                $auto_tags[] = array('tag' => $autotag);
            }
            replaceLDAPCacheRecord($username, sha1($password), $newinfo['displayed_name'], $newinfo['memberof']);
            releaseLDAPCache();
            discardLDAPCache($LDAP_options['cache_expiry']);
            return TRUE;
        case 'NAK':
            // The record isn't valid any more.
            deleteLDAPCacheRecord($username);
            releaseLDAPCache();
            discardLDAPCache($LDAP_options['cache_expiry']);
            return FALSE;
        case 'CAN':
            // retry failed, do nothing, use old value till next retry
            $ldap_displayname = $oldinfo['displayed_name'];
            foreach ($oldinfo['memberof'] as $autotag) {
                $auto_tags[] = array('tag' => $autotag);
            }
            touchLDAPCacheRecord($username);
            releaseLDAPCache();
            discardLDAPCache($LDAP_options['cache_expiry']);
            return TRUE;
        default:
            throw new RackTablesError('structure error', RackTablesError::INTERNAL);
    }
    // This is never reached.
    return FALSE;
}
Example #7
0
function renderRackCodeEditor()
{
    addJS('js/codepress/codepress.js');
    addJS(<<<ENDJAVASCRIPT
function verify()
{
\t\$.ajax({
\t\ttype: "POST",
\t\turl: "index.php",
\t\tdata: {'module': 'ajax', 'ac': 'verifyCode', 'code': \$(RCTA).getCode()},
\t\tsuccess: function (data)
\t\t{
\t\t\tarr = data.split("\\n");
\t\t\tif (arr[0] == "ACK")
\t\t\t{
\t\t\t\t\$("#SaveChanges")[0].disabled = "";
\t\t\t\t\$("#ShowMessage")[0].innerHTML = "Code verification OK, don't forget to save the code";
\t\t\t\t\$("#ShowMessage")[0].className = "msg_success";
\t\t\t}
\t\t\telse
\t\t\t{
\t\t\t\t\$("#SaveChanges")[0].disabled = "disabled";
\t\t\t\t\$("#ShowMessage")[0].innerHTML = arr[1];
\t\t\t\t\$("#ShowMessage")[0].className = "msg_warning";
\t\t\t}
\t\t}
\t});
}

\$(document).ready(function() {
\t\$("#SaveChanges")[0].disabled = "disabled";
\t\$("#ShowMessage")[0].innerHTML = "";
\t\$("#ShowMessage")[0].className = "";
});
ENDJAVASCRIPT
, TRUE);
    $text = loadScript('RackCode');
    printOpFormIntro('saveRackCode');
    echo '<table border=0 align=center>';
    echo "<tr><td><textarea rows=40 cols=100 name=rackcode id=RCTA class='codepress rackcode'>";
    echo $text . "</textarea></td></tr>\n";
    echo "<tr><td align=center>";
    echo '<div id="ShowMessage"></div>';
    echo "<input type='button' value='Verify' onclick='verify();'>";
    echo "<input type='submit' value='Save' disabled='disabled' id='SaveChanges' onclick='\$(RCTA).toggleEditor();'>";
    //	printImageHREF ('SAVE', 'Save changes', TRUE);
    echo "</td></tr>";
    echo '</table>';
    echo "</form>";
}
Example #8
0
 * This base directory is what the framework uses to form all resource paths in its path manager functions
 * 
 * @var string $baseDir contains the base directory which is assumed to be where the index.php script is located.
 * @link http://not-ready See how the DFPath() and loadScript() help with path management
 * @see DMainLang
 */
DSettings::$paths['baseDirectory'] = dirname(__FILE__) . SLASH;
/**
 * This class contains core functionalities of the framework
 * The containing script contains the DFPath() function
 * 
 * @link http://not-ready See the Documentation on the DAmmyCore class
 * @link http://not-ready See how the DFPath() helps with path management
 * @see loadScript()
 */
loadScript('DAmmyCore', 'lib.util');
/**
 * Now loading the framework's internal core scripts and preparing environment
 * 
 */
DAmmyCore::init();
/**
 * Invoking the DBufferHandler(if its been enabled)
 * Its important to start the BufferHandler before any output
 * 
 * @link http://not-ready See the Documentation on the DBufferHandler class
 * @link http://not-ready See the Documentation on the DSettings class
 */
if (DMainPlugin::isPluginLoaded('cacheManager')) {
    cacheManager::startBuffer();
}
Example #9
0
function queryLDAPServer($username, $password)
{
    global $LDAP_options;
    if (extension_loaded('ldap') === FALSE) {
        throw new RackTablesError('LDAP misconfiguration. LDAP PHP Module is not installed.', RackTablesError::MISCONFIGURED);
    }
    $ldap_cant_connect_codes = array(-1, -5, -11);
    $last_successful_server = loadScript('LDAPLastSuccessfulServer');
    $success_server = NULL;
    $servers = preg_split("/\\s+/", $LDAP_options['server'], NULL, PREG_SPLIT_NO_EMPTY);
    if (isset($last_successful_server) && in_array($last_successful_server, $servers)) {
        // Use last successful server first
        $servers = array_diff($servers, array($last_successful_server));
        array_unshift($servers, $last_successful_server);
    }
    // Try to connect to each server until first success
    foreach ($servers as $server) {
        $connect = @ldap_connect($server, array_fetch($LDAP_options, 'port', 389));
        if ($connect === FALSE) {
            continue;
        }
        ldap_set_option($connect, LDAP_OPT_NETWORK_TIMEOUT, array_fetch($LDAP_options, 'server_alive_timeout', 2));
        // If use_tls configuration option is set, then try establish TLS session instead of ldap_bind
        if (isset($LDAP_options['use_tls']) && $LDAP_options['use_tls'] >= 1) {
            $tls = ldap_start_tls($connect);
            if ($LDAP_options['use_tls'] >= 2 && $tls == FALSE) {
                if (in_array(ldap_errno($connect), $ldap_cant_connect_codes)) {
                    continue;
                } else {
                    throw new RackTablesError('LDAP misconfiguration: LDAP TLS required but not successfully negotiated.', RackTablesError::MISCONFIGURED);
                }
            }
            $success_server = $server;
            break;
        } else {
            if (@ldap_bind($connect) || !in_array(ldap_errno($connect), $ldap_cant_connect_codes)) {
                $success_server = $server;
                // Cleanup after check. This connection will be used below
                @ldap_unbind($connect);
                $connect = ldap_connect($server, array_fetch($LDAP_options, 'port', 389));
                break;
            }
        }
    }
    if (!isset($success_server)) {
        return array('result' => 'CAN');
    }
    if ($LDAP_options['cache_expiry'] != 0 && $last_successful_server !== $success_server) {
        saveScript('LDAPLastSuccessfulServer', $success_server);
    }
    if (array_key_exists('options', $LDAP_options) and is_array($LDAP_options['options'])) {
        foreach ($LDAP_options['options'] as $opt_code => $opt_value) {
            ldap_set_option($connect, $opt_code, $opt_value);
        }
    }
    // Decide on the username we will actually authenticate for.
    if (isset($LDAP_options['domain']) and strlen($LDAP_options['domain'])) {
        $auth_user_name = $username . "@" . $LDAP_options['domain'];
    } elseif (isset($LDAP_options['search_dn']) and strlen($LDAP_options['search_dn']) and isset($LDAP_options['search_attr']) and strlen($LDAP_options['search_attr'])) {
        // If a search_bind_rdn is supplied, bind to that and use it to search.
        // This is required unless a server offers anonymous searching.
        // Using bind again on the connection works as expected.
        // The password is optional as it might be optional on server, too.
        if (isset($LDAP_options['search_bind_rdn']) && strlen($LDAP_options['search_bind_rdn'])) {
            $search_bind = @ldap_bind($connect, $LDAP_options['search_bind_rdn'], isset($LDAP_options['search_bind_password']) ? $LDAP_options['search_bind_password'] : NULL);
            if ($search_bind === FALSE) {
                throw new RackTablesError('LDAP misconfiguration. You have specified a search_bind_rdn ' . (isset($LDAP_options['search_bind_password']) ? 'with' : 'without') . ' a search_bind_password, but the server refused it with: ' . ldap_error($connect), RackTablesError::MISCONFIGURED);
            }
        }
        $results = @ldap_search($connect, $LDAP_options['search_dn'], '(' . $LDAP_options['search_attr'] . "={$username})", array("dn"));
        if ($results === FALSE) {
            return array('result' => 'CAN');
        }
        if (@ldap_count_entries($connect, $results) != 1) {
            @ldap_close($connect);
            return array('result' => 'NAK');
        }
        $info = @ldap_get_entries($connect, $results);
        ldap_free_result($results);
        $auth_user_name = $info[0]['dn'];
    } else {
        throw new RackTablesError('LDAP misconfiguration. Cannon build username for authentication.', RackTablesError::MISCONFIGURED);
    }
    $bind = @ldap_bind($connect, $auth_user_name, $password);
    if ($bind === FALSE) {
        switch (ldap_errno($connect)) {
            case 49:
                // LDAP_INVALID_CREDENTIALS
                return array('result' => 'NAK');
            default:
                return array('result' => 'CAN');
        }
    }
    // preliminary decision may change during searching
    $ret = array('result' => 'ACK', 'displayed_name' => '', 'memberof' => array());
    // Some servers deny anonymous search, thus search (if requested) only after binding.
    // Displayed name only makes sense for authenticated users anyway.
    if (isset($LDAP_options['displayname_attrs']) and strlen($LDAP_options['displayname_attrs']) and isset($LDAP_options['search_dn']) and strlen($LDAP_options['search_dn']) and isset($LDAP_options['search_attr']) and strlen($LDAP_options['search_attr'])) {
        $results = @ldap_search($connect, $LDAP_options['search_dn'], '(' . $LDAP_options['search_attr'] . "={$username})", array_merge(array($LDAP_options['group_attr']), explode(' ', $LDAP_options['displayname_attrs'])));
        if (@ldap_count_entries($connect, $results) != 1) {
            @ldap_close($connect);
            return array('result' => 'NAK');
        }
        $info = @ldap_get_entries($connect, $results);
        ldap_free_result($results);
        $space = '';
        foreach (explode(' ', $LDAP_options['displayname_attrs']) as $attr) {
            if (isset($info[0][$attr])) {
                $ret['displayed_name'] .= $space . $info[0][$attr][0];
                $space = ' ';
            }
        }
        // Pull group membership, if any was returned.
        if (isset($info[0][$LDAP_options['group_attr']])) {
            for ($i = 0; $i < $info[0][$LDAP_options['group_attr']]['count']; $i++) {
                if (preg_match($LDAP_options['group_filter'], $info[0][$LDAP_options['group_attr']][$i], $matches) and validTagName('$lgcn_' . $matches[1], TRUE)) {
                    $ret['memberof'][] = '$lgcn_' . $matches[1];
                }
            }
        }
    }
    @ldap_close($connect);
    return $ret;
}
Example #10
0
function authenticated_via_ldap_cache($username, $password, &$ldap_displayname)
{
    global $LDAP_options, $auto_tags;
    // Destroy the cache each time config changes.
    if (sha1(serialize($LDAP_options)) != loadScript('LDAPConfigHash')) {
        discardLDAPCache();
        saveScript('LDAPConfigHash', sha1(serialize($LDAP_options)));
    }
    $user_data = array();
    // fill auto_tags and ldap_displayname from this array
    $password_hash = sha1($password);
    // first try to get cache row without locking it (quick way)
    $cache_row = fetchLDAPCacheRow($username);
    if (isLDAPCacheValid($cache_row, $password_hash, TRUE)) {
        $user_data = $cache_row;
    } else {
        // cache miss or expired. Try to lock LDAPCache for $username
        $cache_row = acquireLDAPCache($username);
        if (isLDAPCacheValid($cache_row, $password_hash, TRUE)) {
            $user_data = $cache_row;
        } else {
            $ldap_answer = queryLDAPServer($username, $password);
            switch ($ldap_answer['result']) {
                case 'ACK':
                    replaceLDAPCacheRecord($username, $password_hash, $ldap_answer['displayed_name'], $ldap_answer['memberof']);
                    $user_data = $ldap_answer;
                    break;
                case 'NAK':
                    // The record isn't valid any more.
                    // TODO: negative result caching
                    deleteLDAPCacheRecord($username);
                    break;
                case 'CAN':
                    // LDAP query failed, use old value till next retry
                    if (isLDAPCacheValid($cache_row, $password_hash, FALSE)) {
                        touchLDAPCacheRecord($username);
                        $user_data = $cache_row;
                    } else {
                        deleteLDAPCacheRecord($username);
                    }
                    break;
                default:
                    throw new RackTablesError('structure error', RackTablesError::INTERNAL);
            }
        }
        releaseLDAPCache();
        discardLDAPCache($LDAP_options['cache_expiry']);
        // clear expired rows of other users
    }
    if ($user_data) {
        $ldap_displayname = $user_data['displayed_name'];
        foreach ($user_data['memberof'] as $autotag) {
            $auto_tags[] = array('tag' => $autotag);
        }
        return TRUE;
    }
    return FALSE;
}
Example #11
0
function getScript($js, $application = NULL, $extra = NULL, $getJs = FALSE, $external = FALSE)
{
    $HTML = NULL;
    if (file_exists($js) and !$external) {
        return loadScript($js);
    } else {
        if ($external) {
            return loadScript($js, $application, TRUE);
        } elseif (isset($application)) {
            return loadScript($js, $application);
        } else {
            if ($js === "jquery") {
                return loadScript("www/lib/scripts/js/jquery.js");
            } elseif ($js === "checkbox") {
                $HTML = '	<script type="text/javascript">
								function checkAll(idForm) {
									$("form input:checkbox").attr("checked", "checked");
								}
						
								function unCheckAll(idForm) {
									$("form input:checkbox").removeAttr("checked");
								}
							</script>';
            } elseif ($js === "external") {
                $HTML = '	<script type="text/javascript">
								$(document).ready(function() { 
									$(function() {
										$(\'a[rel*=external]\').click(function() {
											window.open(this.href);
											return false;
										});
									});
								});
							</script>				
							
							<noscript><p class="NoDisplay">' . __("Disable Javascript") . '</p></noscript>';
            } elseif ($js === "show-element") {
                $HTML = '	<script type="text/javascript">
								function showElement(obj) {
									if(obj.className == "no-display") {
										obj.className = "display";
									} else {
										obj.className = "no-display";
									}
								}
							</script>';
            } elseif ($js === "tiny-mce") {
                $HTML = loadScript("www/lib/scripts/js/tiny_mce/tiny_mce.js");
                $HTML .= '<script type="text/javascript">';
                if ($extra === "class") {
                    $HTML .= '		
									tinyMCE.init({
										mode : "textareas",
										editor_selector : "editor",
										editor_deselector : "noeditor",
										theme : "simple"
									});
							';
                } elseif ($extra !== "basic") {
                    $HTML .= '			
									tinyMCE.init({
										mode : "exact",
										elements : "editor",
										theme : "advanced",
										skin : "o2k7",
										cleanup: true,
										plugins : "videos,advcode,safari,pagebreak,style,advhr,advimage,advlink,emotions,preview,media,fullscreen,template,inlinepopups,advimage,media,paste",              
										theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,|,link,unlink,|,videos,image,advcode,|,forecolor,|,charmap,|,pastetext,pasteword,pastetext,fullscreen,pagebreak,preview",
										theme_advanced_buttons2 : "",
										theme_advanced_buttons3 : "",
										theme_advanced_toolbar_location : "top",
										theme_advanced_toolbar_align : "left",
										theme_advanced_statusbar_location : "bottom",
										theme_advanced_resizing : false,
										convert_urls : false,                    
										content_CSS : "css/content.css",               
										external_link_list_url : "lists/link_list.js",
										external_image_list_url : "lists/image_list.js",
										media_external_list_url : "lists/media_list.js"
									});
							';
                } else {
                    $HTML .= '		
									tinyMCE.init({
										mode : "exact",
										elements : "editor",
										theme : "simple",
										editor_selector : "mceSimple"
									});
							';
                }
                $HTML .= '	function insertHTML(content) {
								parent.tinyMCE.execCommand(\'mceInsertContent\', false, content);
							}
						</script>';
            } elseif ($js === "upload") {
                $iPx = POST("iPx") ? POST("iPx") : 'i';
                $iPath = POST("iPath") ? POST("iPath") : 'www/lib/files/images/uploaded/';
                $iPath = POST($iPx . "Dirbase") ? POST($iPx . "Dirbase") : $iPath;
                $iPath = POST($iPx . "Make") ? POST($iPx . "Dir") . slug(POST($iPx . "Dirname")) . _sh : $iPath;
                $dPx = POST("dPx") ? POST("dPx") : "d";
                $dPath = POST("dPath") ? POST("dPath") : "www/lib/files/documents/uploaded/";
                $dPath = POST($dPx . "Dirbase") ? POST($dPx . "Dirbase") : $dPath;
                $dPath = POST($dPx . "Make") ? POST($dPx . "Dir") . nice(POST($dPx . "Dirname")) . _sh : $dPath;
                $application = whichApplication();
                ?>
						<script type="text/javascript">
							$(document).on("ready", function() {
								function uploadResponse(state, file) {
									var path, insert, ok, error, form, message; 
									
									path = '<?php 
                print path($iPath, TRUE);
                ?>
' + file;

									HTML = '\'<img src=\\\'' + path + '\\\' alt=\\\'' + file + '\\\' />\'';
									
									insert = '<li><input name="iLibrary[]" type="checkbox" value="' + path + '" /> <span class="small">00<' + '/span>';
									insert = insert + '<a href="' + path + '" rel="external" title="<?php 
                print __(_("Preview"));
                ?>
"><span class="tiny-image tiny-search">&nbsp;&nbsp;&nbsp;&nbsp;</span><' + '/a>';
									insert = insert + '<a class="pointer" onclick="javascript:insertHTML(' + HTML + ');" title="<?php 
                print __(_("Insert image"));
                ?>
"><span class="tiny-image tiny-add">&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;';
									insert = insert + '<span class="bold">' + file + '<' + '/span><' + '/a><' + '/li>';						
									
									if(state == 1) {
										message = '<?php 
                print __(_("The file size exceed the permitted limit"));
                ?>
';
									}
									
									if(state == 2) {
										message = '<?php 
                print __(_("An error has ocurred"));
                ?>
';
									}
									
									if(state == 3) {
										message = '<?php 
                print __(_("The file type is not permitted"));
                ?>
';
									}
									
									if(state == 4) {
										message = '<?php 
                print __(_("A problem occurred when trying to upload file"));
                ?>
';
									}
									
									if(state == 5) {
										message = '<?php 
                print __(_("The file already exists"));
                ?>
';
									}
									
									if(state == 6) {
										message = '<?php 
                print __(_("Successfully uploaded file"));
                ?>
';

										$('#i-add-upload').html = insert + $('#i-add-upload').html;
									}
									
									document.getElementById('i-upload-message').innerHTML = message;
								}												
								
								function uploadDocumentsResponse(dState, dFile, dIcon, dAlt) {
									var dPath, dInsert, dOk, dError, dForm, dMessage, dHTML;
									
									dPath = '<?php 
                print path($dPath, TRUE);
                ?>
' + dFile;					
									dHTML = '\'<a href=\\\'' + dPath + '\\\' title=\\\'' + dFile + '\\\'><img src=\\\'' + dIcon + '\\\' alt=\\\'' + dAlt + '\\\' /></a>\'';
									
									dInsert = '<li><input name="dLibrary[]" type="checkbox" value="' + dPath + '" />';
									dInsert = dInsert + ' <span class="small">00<' + '/span><a href="' + dPath + '" title="<?php 
                print __(_("Download file"));
                ?>
">';
									dInsert = dInsert + '<span class="tiny-image tiny-file">&nbsp;&nbsp;&nbsp;&nbsp;</span><' + '/a>';
									dInsert = dInsert + '<a class="pointer" onclick="javascript:insertHTML(' + dHTML + ');" title="<?php 
                print __(_("Insert file"));
                ?>
">';
									dInsert = dInsert + '<span class="tiny-image tiny-add">&nbsp;&nbsp;&nbsp;&nbsp;</span>';
									dInsert = dInsert + '<span class="bold">' + dFile + '<' + '/span><' + '/a><' + '/li>';								
							
									if(dState == 1) {
										message = '<?php 
                print __(_("The file size exceed the permitted limit"));
                ?>
';
									}
									
									if(dState == 2) {
										message = '<?php 
                print __(_("An error has ocurred"));
                ?>
';
									}
									
									if(dState == 3) {
										message = '<?php 
                print __(_("The file type is not permitted"));
                ?>
';
									}
									
									if(dState == 4) {
										message = '<?php 
                print __(_("A problem occurred when trying to upload file"));
                ?>
';
									}
									
									if(dState == 5) {
										message = '<?php 
                print __(_("The file already exists"));
                ?>
';
									}								
									
									if(dState == 6) {
										message = '<?php 
                print __(_("Successfully uploaded file"));
                ?>
';

										document.getElementById('d-add-upload').innerHTML = dInsert + document.getElementById('d-add-upload').innerHTML;
									}
									
									document.getElementById('d-upload-message').innerHTML = message;
								}
						 	});
						</script>
						
						<noscript><p class="no-display"><?php 
                print __(_("Disable Javascript"));
                ?>
</p></noscript>
					
					<?php 
                return NULL;
            } elseif ($application) {
                $HTML = '<script type="text/javascript" language="javascript">' . $js . '</script>';
            }
            return $HTML;
        }
    }
}