JScript

Programação & Desenvolvimento


Você não está conectado. Conecte-se ou registre-se

[Projeto] Configurar scripts!

Ir para baixo  Mensagem [Página 1 de 1]

1[Projeto] Configurar scripts! Empty [Projeto] Configurar scripts! Qua 04 Mar 2015, 5:25 pm

JScript

JScript
Administradores
Administradores

Olá pessoal!

Introdução:
O título já diz metade do que desejo falar, mas vou complementar:
Na plataforma IPBoard, por exemplo, quando adicionamos um código .JS e precisamos configurar os parâmetros do script, não mexemos com uma única linha de código, apenas uma interface com as opções, vejam na imagem abaixo:
Spoiler:
Dessa forma fica bem mais fácil para o administrador configurar as variáveis e parâmetros de um script sem nem mesmo entender do código para editá-lo!!!

O propósito deste tópico é justamente trazer essa facilidade a plataforma Forumeiros, sim, por que não???!!!

Mas para que isso seja possível, o código que for adicionado no painel de controle, deverá ter uma espécie de cabeçalho que reconhece que o painel de controle esteja aberto e com isso injetará as suas opções de configuração na nova tab adicionada!

A princípio a "coisa' toda parece confusa/complicada, mas na verdade o cenário é bem simples e funcional...

Vejam este exemplo:
[Projeto] Configurar scripts! KpiXmGM
Esta imagem mostra a "injeção" do código .JS necessário para termos a aba de configuração dos scripts.

Mas o que é necessário para meu código ficar compatível com esse sistema?
Abaixo você terá essa resposta:

Cabeçalho:
É a parte que identifica a compatibilidade do seu código com o sistema, sendo formado por itens XML, na qual só é interpretado com um regex do próprio sistema, pois ele está dentro de um comentário já que o interpretador JavaScript não reconhece XML!
Código:

/**
 * @CP_AddOn Addons for the Forumotion control panel
 * @copyright Copyright (C) 2014 JScript
 * @license http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
 * @engine 1.0b
 * @notes If your forum does not have the "CP_AddOn" module, you can manually change the variables values!

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<mod>
 <header>
 <id>IDENTIFIQUE_SEU_CÓDIGO_(MÁXIMO_8_CARACTERES_SEM_ESPAÇO)</id>
 <title>O_TÍTULO_DO_SEU_PROJETO</title>
 <version>VERSÃO_DO_SEU_CÓDIGO_(MODELO_PADRÃO_= 1.1.1.1(a)(b)(r))</version>
 <description>DESCRIÇÃO_DO_SEU_PROJETO</description>
 <author>NOME_DO_AUTOR</author>
 <author-notes>NOTAS_DO_AUTOR_PARA_O_CÓDIGO</author-notes>
 <license>LICENÇA_(PADRÃO_É_= General Public License v2</license>
 <mod-version>1.0.0.9</mod-version>
 </header>
 <configuration>
 <level>NÍVEL_DE_CONFIGURAÇÃO_(VALORES_= Fácil, Médio, Avançado)</level>
 <time>TEMPO_MÉDIO_DE_CONFIGURAÇÃO_(EXMEPLO_= 1 minuto)</time>
 <target-version>1.0b</target-version>
 // Configuração:
 <action type="input">
 <text>TEXTO_(LABEL):</text>
 <variable>NOME_DA_VARIÁVEL_(OBS.:_TEM_QUE_SER_IGUAL_A_VARIÁVEL_DO_CÓDIGO!)</variable>
 </action>
 // Repita quantas vezes for necessário o trecho acima!
 </configuration>
</mod>
*/
Nota: O que pode ser alterado no cabeçalho está em letras maiúsculas! Devendo-se respeitar a sintaxe do restante dos comandos XML.

Código atual liberado para testes:
Código:

jQuery(function() {
    jQuery('a[href*="/admin/index.forum?part=admin"]').click(function(event) {
        event.preventDefault();
        document.body.innerHTML = '<iframe name="cpaddons" id="cpaddons" onLoad="CP_AddOns()" src="/admin" style="position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;">IFrame is not supported</iframe>';

        var lastNum = setTimeout(";"); // Set a fake timeout to get the last timeout number!
        for (var i = 0; i < lastNum; i++) {
            clearTimeout(i);
        }
    });
});

function CP_AddOns() {
    var oIframe = (document.getElementById("cpaddons").contentWindow || document.getElementById("cpaddons").contentDocument);
    oIframe.sContent = {
        sHtml0: '<!-- Module: Configure Scripts - By JScript Brasil at live dot com -->' +
            '<div class="clearfix" id="content">' +
            ' <div style="display: none;" id="menu_close">' +
            ' <p>' +
            ' <a href=\'javascript:ShowHideMenu("menu","menu_close","main","expended_main");\'><img title="Display the menu" alt="Display the menu" src="http://2img.net/i/fa/admin/icones/show_menu.png">' +
            ' </a>' +
            '        </p>' +
            ' </div>' +
            ' <div id="menu">' +
            ' <p id="hide-menu" style="display: block;">' +
            ' <a href=\'javascript:ShowHideMenu("menu","menu_close","main","expended_main");\'><img title="Hide the menu" alt="Hide the menu" src="http://2img.net/i/fa/admin/icones/hide_menu.png">' +
            ' </a>' +
            ' </p>' +
            ' <script type="text/javascript">' +
            ' //<![CDATA[' +
            ' document.getElementById("hide-menu").style.display = "block"; //]]>' +
            ' </script>' +
            ' <div class="header"><img src="http://2img.net/i/fa/admin/icones/puce_bleu.png">&nbsp;Configurar Scripts</div>' +
            ' <div class="coins-top">' +
            ' <div class="left-top">&nbsp;&nbsp;<img align="absmiddle" src="http://2img.net/i/fa/admin/icones/small_ico/html.png">&nbsp;JAVASCRIPT</div><img align="right" class="corner-right" src="http://2img.net/i/fa/admin/icones/top-right-gris.png">' +
            ' </div>' +
            ' <br clear="all">' +
            ' <div class="coins-border">' +
            ' <div id="activesubmenu"><a href="javascript:void(0);" onclick="showContent();"><span>Módulos JavaScript &amp; jQuery</span></a></div>' +
            ' </div>' +
            ' <div class="coins-bottom">' +
            ' <div class="left-bottom"></div><img align="right" src="http://2img.net/i/fa/admin/icones/bottom-right-blanc.png">' +
            ' </div>' +
            ' <br clear="all">' +
            ' <br>' +
            ' <div class="coins-top">' +
            ' <div class="left-top">&nbsp;&nbsp;<img align="absmiddle" src="http://2img.net/i/fa/admin/icones/small_ico/support.png">&nbsp;Suporte</div><img align="right" class="corner-right" src="http://2img.net/i/fa/admin/icones/top-right-gris.png">' +
            ' </div>' +
            ' <br clear="all">' +
            ' <div class="coins-border">' +
            ' <div class="submenu"><a href="javascript:void(0);"><span>Configurar Scripts</span></a></div>' +
            ' <div class="submenu"><a href="http://ajuda.forumeiros.com/" target="_blank"><span>Forumeiros</span></a></div>' +
            ' </div>' +
            ' <div class="coins-bottom">' +
            ' <div class="left-bottom"></div><img align="right" src="http://2img.net/i/fa/admin/icones/bottom-right-blanc.png">' +
            ' </div>' +
            ' <br clear="all">' +
            ' </div>' +
            ' <div id="main">' +
            ' <div id="main-content">' +
            ' </div><!-- closing tag for #main-content -->' +
            ' </div><!-- closing tag for #main -->' +
            ' <div id="tools"></div><!-- closing tag for #tools -->' +
            '</div>',
        sHtml1: '<!-- Module: Configure Scripts - By JScript Brasil at live dot com -->' +
            '<h2><a href="javascript:void(0);" onclick="showContent();">JAVASCRIPT</a></h2>' +
            '<ul class="h2-breadcrumb clearfix">' +
            '    <li class="first">Módulos JavaScript &amp; jQuery</li>' +
            '</ul>' +
            '<blockquote class="block_left" style="display: none;">' +
            '    <p class="explain">Through this section, you can easily manage the JavaScript files you want to add on your forum pages.' +
            '        <br>' +
            '        <br>Warning: This section is intended for expert users. Be careful, your javascript code must be functional when published. In effect, we compress the code in order to improve your forum pages loading time.</p>' +
            '</blockquote>' +
            '<fieldset>' +
            ' <legend>Javascript Codes</legend>' +
            ' <table width="85%" align="center" cellspacing="1" cellpadding="4" border="0" class="tablesorter" id="listJs">' +
            ' <thead>' +
            ' <tr>' +
            ' <th id="column_title" class="headerSort">Nome<span class="imgSort">&nbsp;</span></th>' +
            ' <th id="column_address" class="headerSort">Versão<span class="imgSort">&nbsp;</span></th>' +
            ' <th id="column_date" class="headerSort headerSortUp">Autor<span class="imgSort">&nbsp;</span></th>' +
            ' <th>Editar</th>' +
            ' </tr>' +
            ' </thead>' +
            ' <tbody>' +
            ' <!-- Code list! -->' +
            ' <tr id="load_list">' +
            ' <td><ul class="h2-breadcrumb clearfix" style="margin: 0px;"><br><li class="first">Preenchendo a lista, aguarde... <span id="code_num"></span></li></ul></td>' +
            ' </tr>' +
            ' </tbody>' +
            ' </table>' +
            ' <br>' +
            '</fieldset>',
        sHtml2: '<!-- Module: Configure Scripts - By JScript Brasil at live dot com -->' +
            '<h2><a href="javascript:void(0);" onclick="showContent();">JAVASCRIPT</a></h2>' +
            '<ul class="h2-breadcrumb clearfix">' +
            '    <li class="first"><a href="javascript:void(0);" onclick="showContent();">Módulos JavaScript &amp; jQuery</a>' +
            '    </li>' +
            '    <li>Configuração de códigos</li>' +
            '</ul>' +
            '<blockquote class="block_left" style="margin: 5px;">' +
            '    <p class="explain" id="description"></p>' +
            '</blockquote>' +
            '<br>' +
            '<fieldset id="placement"></fieldset>' +
            '<fieldset id="config">' +
            ' <legend>Configurações</legend>' +
            '</fieldset>'
    };

    script = oIframe.document.createElement("script");
    script.type = "text/javascript";
    script.innerHTML =
        'TID = jQuery(\'a[href^="/admin/index.forum?tid="]\').attr("href").split("=")[1];' +
        'jQuery(function() {' +
        ' jQuery("#tabs ul").append(\'<li class="jsconfig"><a href="javascript:void(0);" onclick="showContent();"><span>Configurar Scripts</span></a></li>\');' +
        '});' +
 'function showContent() {' +
        ' TID = jQuery(\'a[href^="/admin/index.forum?tid="]\').attr("href").split("=")[1];' +
        ' jQuery("#activetab").removeAttr("id");' +
        ' jQuery("li.jsconfig").attr("id", "activetab");' +
        ' jQuery("#wrapper").html(sContent.sHtml0);' +
        ' jQuery("#main-content").html(sContent.sHtml1);' +
        ' var whait_msg = jQuery("#load_list"),' +
        ' code_num = jQuery("#code_num");' +
        ' jQuery.ajax({' +
        ' url: "/admin/index.forum?part=modules&sub=html&mode=js&extended_admin=1&tid=" + TID,' +
        ' type: "get",' +
        //' async: false,' +
        ' dataType: "html",' +
        ' success: function (response, status, xhr) {' +
        ' if (xhr.status == 200) {' +
        ' var response = jQuery(response),' +
        ' oTarget = response.find("#listJs tbody:first tr"),' +
        ' ilen = oTarget.length,' +
        ' index = 0,' +
 ' count = ilen,' +
        ' last_update = response.find("#listJs tbody:first tr:first td:eq(2) > span").text(),' +
        ' saved_update = sessionStorage.getItem("listJs_update");' +
        ' if (saved_update == last_update) {' +
        ' jQuery("#listJs tbody").html(sessionStorage.getItem("listJs_html"));' +
        ' return false;' +
        ' }' +
        ' code_num.text(count);' +
        ' for (; index < ilen; index++) {' +
        ' var oThis = jQuery(oTarget[index]),' +
        ' sHref = oThis.find(\'a[href^="/admin"]\').attr("href");' +
        ' jQuery.ajax({' +
        ' url: sHref,' +
        ' type: "get",' +
        ' async: false,' +
        ' dataType: "html",' +
        ' success: function (response, status, xhr) {' +
        ' if (xhr.status == 200) {' +
        ' var js_content = jQuery(response).find("#js_content").val(),' +
        ' aXML = /(?:<mod>([\\s\\S]*?)<[/]mod>)/.exec(js_content);' +
        ' if (aXML !== null) {' +
        ' aXML = jQuery.parseXML(aXML[0]),' +
        ' tr =' +
        ' \'<tr>\' +' +
        ' \'<td class="row1">\' + jQuery(aXML).find("id").text() + \'</td>\' +' +
        ' \'<td class="row1">\' + jQuery(aXML).find("version").text() + \'</td>\' +' +
        ' \'<td class="row1 url_ltr">\' + jQuery(aXML).find("author").text() + \'</td>\' +' +
        ' \'<td align="center" class="row1">\' +' +
        ' \'<a href="javascript:void(0);" onClick="CP_AddOns_Edit("\' + encodeURIComponent(response) + \'");"><img title="" alt="" src="http://2img.net/i/fa/admin/icones/editer.png"></a>\' +' +
        ' \'</td>\' +' +
        ' \'</tr>\';' +
        ' jQuery("#listJs tbody").append(tr);' +
        ' }' +
        ' }' +
        ' }' +
        ' });' +
        ' code_num.text(count--);' +
        ' }' +
        ' if (jQuery("#listJs tbody tr").length == 1) {' +
        ' whait_msg.find("li").text("Não há códigos compatíveis com o sistema ou com essa versão atual!");' +
 ' sessionStorage.setItem("listJs_update", 0);' +
        ' } else {' +
 ' whait_msg.hide();' +
        ' sessionStorage.setItem("listJs_update", last_update);' +
        ' sessionStorage.setItem("listJs_html", jQuery("#listJs tbody").html());' +
 ' }' +
        ' }' +
        ' }' +
        ' });' +
 '}' +
        'function CP_AddOns_Edit(response) {' +
        ' jQuery("#main-content").html(sContent.sHtml2);' +
        ' response = jQuery(decodeURIComponent(response));' +
        ' var js_content = response.find("#js_content").val(),' +
        ' aXML = /(?:<mod>([\\s\\S]*?)<[/]mod>)/.exec(js_content);' +
        ' jQuery("#placement").html(response.find("#formenvoi fieldset").html());' +
        ' try {' +
        ' aXML = jQuery(jQuery.parseXML(aXML[0]));' +
 ' jQuery("#description").html(aXML.find("id").text() + "<br>Descrição: " + aXML.find("description").text());' +
        ' var oTarget = aXML.find("action");' +
        ' oTarget.each(function () {' +
        ' var oThis = jQuery(this),' +
        ' xVariable = oThis.find("variable").text();' +
        ' if (xVariable) {' +
        ' var patt = new RegExp("(?:" + xVariable + "\\\\s*=\\\\s*([\\\\s\\\\S]*?);)", "g");' +
        ' var xValue = patt.exec(js_content);' +
        ' if (xValue !== null) {' +
        //' console.log("Variable: " + xVariable + "\\nValue: " + xValue[1]);' +
        ' var dl =' +
        ' \'<dl><dt><label>\' + oThis.find("text").text() + \'</label></dt>\' +' +
        ' \'<dd><input type="text" name="\' + xVariable + \'" data-last=\' + xValue[1] + \' size="\' + xValue[1].length + \'" maxlength="\' + (xValue[1].length * 2) + \'" value=\' + xValue[1] + \'> </dd>\' +' +
        ' \'</dl>\';' +
        ' jQuery("#config").append(dl);' +
        ' }' +
        ' }' +
        ' });' +
        ' jQuery("#config").append(\'<div class="DIV_BTNS"><input id="js_save" type="submit" value="Save" name="submit" class="icon_ok"></div>\');' +
 ' $("#js_save").click(function() {' +
 ' var oTarget = jQuery("#config dl dd input"),' +
 ' ilen = oTarget.length,' +
 ' index = 0;' +
 ' for (; index < ilen; index++) {' +
 ' var oThis = jQuery(oTarget[index]),' +
 ' js_search = new RegExp("(" + oThis.attr("name") + "\\\\s*=\\\\s*)([\\\\u0022\\\\u0027]|)(?:[\\\\s\\\\S]*?)([\\\\u0022\\\\u0027]|);", "g");' +
 ' js_replace = oThis.val();' +
 ' js_content = js_content.replace(js_search, "$1$2" + js_replace + "$3;");' +
 ' }' +
 ' var oTarget = jQuery("#placement input[name=\'js_placement[]\']"),' +
 ' ilen = oTarget.length,' +
 ' index = 0,' +
 ' ID = response.find("#formenvoi input[name=\'page\']").val(),' +
 ' js_placement = [];' +
 ' for (; index < ilen; index++) {' +
 ' var oThis = jQuery(oTarget[index]);' +
 ' if (oThis.is(":checked")) {' +
 ' js_placement.push(oThis.val());' +
 ' }' +
 ' }' +
 ' jQuery.post("/admin/index.forum?part=modules&sub=html&mode=js_edit&id=" + ID + "&extended_admin=1&tid=" + TID, {' +
 ' title: jQuery("#placement input[name=\'title\']").val(),' +
 ' js_placement: js_placement,' +
 ' type: 0,' +
 ' page: ID,' +
 ' content: js_content,' +
 ' mode: "save",' +
 ' submit: 1' +
 ' }).done(function() {' +
 ' jQuery("#main-content").html(\'<div class="successbox"><center><h3>Informação</h3></center><p>Seu código JavaScript foi alterado.<br><br><a href="javascript:void(0);" onclick="showContent();">Click aqui para retornar a configuração de scripts.</a></p></div>\')' +
 ' }).fail(function() {' +
 ' jQuery("#main-content").html(\'<div class="errorbox"><center><h3>Error</h3></center><p>You must fill in the required fields.</p></div>\')' +
 ' });' +
 ' });' +
        ' if ($("#js_placement_all").is(":checked")) {' +
        ' $("#js_placement_index").attr({' +
        ' checked: false,' +
        ' disabled: true' +
        ' });' +
        ' $("#js_placement_portal").attr({' +
        ' checked: false,' +
        ' disabled: true' +
        ' });' +
        ' $("#js_placement_viewforum").attr({' +
        ' checked: false,' +
        ' disabled: true' +
        ' });' +
        ' $("#js_placement_viewtopic").attr({' +
        ' checked: false,' +
        ' disabled: true' +
        ' });' +
        ' $("#js_placement_gallery").attr({' +
        ' checked: false,' +
        ' disabled: true' +
        ' });' +
        ' }' +
        ' $("#js_placement_all").click(function() {' +
        ' if ($(this).is(":checked")) {' +
        ' $("#js_placement_index").attr({' +
        ' checked: false,' +
        ' disabled: true' +
        ' });' +
        ' $("#js_placement_portal").attr({' +
        ' checked: false,' +
        ' disabled: true' +
        ' });' +
        ' $("#js_placement_viewforum").attr({' +
        ' checked: false,' +
        ' disabled: true' +
        ' });' +
        ' $("#js_placement_viewtopic").attr({' +
        ' checked: false,' +
        ' disabled: true' +
        ' });' +
        ' $("#js_placement_gallery").attr({' +
        ' checked: false,' +
        ' disabled: true' +
        ' });' +
        ' } else {' +
        ' $("#js_placement_index").attr("disabled", false);' +
        ' $("#js_placement_portal").attr("disabled", false);' +
        ' $("#js_placement_viewforum").attr("disabled", false);' +
        ' $("#js_placement_viewtopic").attr("disabled", false);' +
        ' $("#js_placement_gallery").attr("disabled", false);' +
        ' }' +
        ' });' +
        ' } catch (e) {' +
        ' console.log(e);' +
        ' }' +
        '}';
    oIframe.document.getElementsByTagName("head")[0].appendChild(script);
};
Basta adicionar na seção como um novo JavaScript com investimento em todas as páginas, daí o link do painel de controle será interceptado e com isso o código entra em ação no painel!



Módulo: Instalador de códigos!
Pessoal, eu já conclui este módulo onde não será mais necessário adicionar manualmente os scripts na seção JavaScript!!!
Pode-se instalar um arquivo .zip baixado no computador local e o meu código extrai o conteúdo do zip e instala de acordo com as instruções dentro dele!
Dessa forma o script será automaticamente criado na seção JavaScript, com o nome e investimento pré determinado no arquivo instalador.

O XML instalador que está dentro do zip terá suporte a procurar e substituir, procurar e adicionar depois ou antes em templates, com isso elimina-se a edição manual deles...

JS

http://autoitbrasil.com

Ir para o topo  Mensagem [Página 1 de 1]

Permissões neste sub-fórum
Não podes responder a tópicos