Installationsscript für Plugins mitlerweile enthalten?

Gesperrt
rethus
Beiträge: 1851
Registriert: Di 28. Mär 2006, 11:55
Wohnort: Mönchengladbach
Kontaktdaten:

Installationsscript für Plugins mitlerweile enthalten?

Beitrag von rethus »

In den älteren Versionen von Contenido war kein Installationsscript für die Plugins erhalten.
Martin Horwath hat ein geschrieben, mit dem dies wunderbar ging.

Meine Frage: Ist in der aktuellen Version 4.8.12 dieses (oder ein anderes Script) zur INstallation von Plugins enthalten?

Und:
Hat sich seit 4.6.23 etwas maßgeblich in Bezug auf die Verwendung von Plugins verändert?
Could I help you... you can help me... buy me a coffee . (vielen ❤ Dank an: Seelauer, Peanut, fauxxami )

xstable.com: - HighSpeed Hosting, Domains, DomainReselling, Linux-Administration
suther.de: - App-Programierung, High-Performance-Webpages, MicroServices, API-Anbindungen & Erstellung

Software... ein Blick wert: GoogleCalender Eventlist, xst_dynamic_contentType
rethus
Beiträge: 1851
Registriert: Di 28. Mär 2006, 11:55
Wohnort: Mönchengladbach
Kontaktdaten:

Re: Installationsscript für Plugins mitlerweile enthalten?

Beitrag von rethus »

Habe das Script von Martin Horwath nun angepasst, dass es auch wieder in neuen Contenido-Verionen funktioniert.

Hier ist der Quellcode:

Code: Alles auswählen

<?php
/* PLUGIN INSTALLER
 * Version 0.4
 * Für Contenido 4.4.4 and up 4.5.x
 * Autor: Martin Horwath (horwath@dayside.net)
 * Datum: 26.09.2004
 *
 * Modifiziert von: Samuel Suther  (www.suther.de)
 * Modifiziert am: 17.07.2009
 * Modifikation: Install-Script an 4.8.12 angepasst
 */

if (!defined("CON_FRAMEWORK")) {
    define("CON_FRAMEWORK", true);
}

// include security class and check request variables
include_once ('../../classes/class.security.php');
Contenido_Security::checkRequests();

if (isset($_REQUEST['changeclient'])) {
        $_REQUEST['changeclient'] = intval($_REQUEST['changeclient']);
        $changeclient = intval($_REQUEST['changeclient']);
}
if (isset($_REQUEST['changelang'])) {
        $_REQUEST['changelang'] = intval($_REQUEST['changelang']);
        $changelang = intval($_REQUEST['changelang']);
}

include_once ('../../includes/startup.php');
cInclude ("includes", 'functions.general.php');

$cfg["debug"]["backend_exectime"]["fullstart"] = getmicrotime();

cInclude ("includes", 'functions.i18n.php');
cInclude ("includes", 'functions.api.php');
cInclude ("includes", 'functions.general.php');
cInclude ("includes", 'functions.forms.php');

cInclude ("includes", 'functions.database.php');

cInclude ("classes", 'class.xml.php');
cInclude ("classes", 'class.navigation.php');
cInclude ("classes", 'class.template.php');
cInclude ("classes", 'class.backend.php');
cInclude ("classes", 'class.notification.php');
cInclude ("classes", 'class.area.php');
cInclude ("classes", 'class.action.php');
cInclude ("classes", 'class.layout.php');
cInclude ("classes", 'class.treeitem.php');
cInclude ("classes", 'class.user.php');
cInclude ("classes", 'class.group.php');
cInclude ("classes", 'class.cat.php');
cInclude ("classes", 'class.client.php');
cInclude ("classes", 'class.inuse.php');
cInclude ("classes", 'class.table.php');

cInclude ("includes", 'functions.str.php');

page_open(array('sess' => 'Contenido_Session',
                'auth' => 'Contenido_Challenge_Crypt_Auth',
                'perm' => 'Contenido_Perm'));

i18nInit($cfg["path"]["contenido"].$cfg["path"]["locale"], $belang);
cInclude ("includes", 'cfg_language_de.inc.php');

class DB_Upgrade extends DB_Contenido {
}

$cfg["debug"]["installer"] = false;
$checktablestatus = true;

/* Instanzen der DB_Contenido */
$db = new DB_Contenido;
$db2 = new DB_Contenido;
$db_str = new DB_Contenido;

$cfg["debug"]["backend_exectime"]["start"]  = getmicrotime();

if ($checktablestatus) {

   $required_fields = Array( "idplugin",
                             "name",
                             "version",
                             "author",
                             "idinternal",
                             "url",
                             "status",
                             "description",
                             "install",
                             "uninstall",
                             "date");
   $required_table = "DROP TABLE ".$cfg['tab']['plugins'].";
                      CREATE TABLE ".$cfg['tab']['plugins']." (
                          idplugin INT(10) NOT NULL default '0',
                          name VARCHAR(60) default NULL,
                          version VARCHAR(10) NOT NULL default '0',
                          author VARCHAR(60) default NULL,
                          idinternal VARCHAR(32) NOT NULL default '0',
                          url TEXT,
                          status INT(10) NOT NULL default '0',
                          description TEXT,
                          install TEXT,
                          uninstall TEXT,
                          date DATETIME NOT NULL default '0000-00-00 00:00:00',
                          PRIMARY KEY (idplugin)
                      ) TYPE=MyISAM;";

   // now we check if the plugin table has the right format...
   msg( "Checking status ". $cfg['tab']['plugins']);
   $ptable = $db->metadata($cfg['tab']['plugins']);

   foreach ($ptable as $key) {
      if (!in_array($key['name'], $required_fields)) {
         msg( $key['name']." (this key can be deleted)", "unused key");
      } else {
         $availableKeys[] = $key['name'];
      }
      $foundkeys[] = $key['name'];
   }
   foreach ($required_fields as $key) {
      if (!in_array($key, $foundkeys)) {
         msg( $key." (this key must be added)", "missing key");
         $missingKeys[] = $key;
      }
   }
   unset ($foundkeys, $key);

   // available elements in table are stored in array -> $availableKeys;
   // missing elements in table are stored in array -> $missingKeys;
   // this is a possible way to handle new versions of plugin installer
   // since this is initial release the table will be dropped and recreated
   // when a missing element is found.

   if (count($missingKeys) > 0) {

      $sql_data = remove_remarks($required_table);
      $sql_pieces = split_sql_file($sql_data, ';');
      msg(count($sql_pieces)." queries", "Executing:");
      foreach ($sql_pieces as $sqlinit) {
         $db->query($sqlinit);
         msg($sqlinit);
      }

   } else {
      msg("ok");
   }

}

/* con_sequence update */
updateSequence();

echo '<html><body style="font-family: Verdana; font-size:11px;">';
// installer starts here
echo "<b>PLUGIN INSTALLER</b><br><br>\n";

$clink = "<br><a href=\"../../index.php?contenido=$contenido\">Switch to backend</a>\r\n";

if ($installsql = file_get_contents('install.sql')) {

    // get info from sql file
    if (preg_match ("/####(.*)####/i", $installsql, $pinfo)) {

       $pinfo = explode (";",$pinfo[1]);

       // take some nice names easier to work with...
       $pname = $pinfo[0];
       $pversion = $pinfo[1];
       $pauthor = $pinfo[2];
       $pinternalid = $pinfo[3];

       unset($pinfo);

       // first show info
       echo "Plugin Name: ".$pname."<br>\n";
       echo "Plugin Version: ".$pversion."<br>\n";
       echo "Author: ".$pauthor."<br>\n";
       echo "Internal ID: ".$pinternalid."<br>\n";

       // the user don't need this info...
       $installsql = preg_replace ("/####(.*)####/i", "", $installsql);

       $pstatus = true;

    } else {
       echo "Info missing. First line of install.sql should include following line:<br>";
       echo "<b>####NAME;VERSION;AUTHOR;INTERNAL_ID####</b><br>";
       echo "No further action takes place<br>";

       $pstatus = false;
    }

    // check if idinternal is allready available in table
    $sql = "SELECT * FROM ".$cfg["tab"]["plugins"]." WHERE idinternal='".$pinternalid."';";
    $db->query($sql);
    if ($db->next_record()) {
        $mode = "update";
        $message .= "Plugin with this internal id allready exists in table.<br>\n";
        if ($pversion == $db->f('version')) {
            $message .= "This version is allready installed.<br>\n";
            $mode = "uninstall";
        } else {
            $message .= "Switching to upgrade mode.<br>\n";
        }
        $pluginid = $db->f('idplugin');

    } else {
        $mode = "install";
        $message .= "No plugin with this internal id exists in table.<br>\n";
        $pluginid = false;

    }

    if (!$install && !$uninstall) {
        echo "<br>".$message;
    }

    if (!$install && $mode!="uninstall") {
       echo "<br><a href=$PHP_SELF?install=1&contenido=$contenido>Install $pname $pversion</a></br>";
    }

    if (!$uninstall && $mode=="uninstall") {
       echo "<br><a href=$PHP_SELF?uninstall=1&contenido=$contenido>UnInstall $pname $pversion</a></br>";
    }

    if ($uninstall && $pluginid) {
       $sql = "SELECT uninstall FROM ".$cfg["tab"]["plugins"]." WHERE idplugin='".$pluginid."'";
       msg($sql);
       $db->query($sql);
       $db->next_record();

       $uninstallsql = $db->f('uninstall');
       $sql_data = remove_remarks($uninstallsql);
       $sql_pieces = split_sql_file($sql_data, ';');

       msg(count($sql_pieces)." queries", "Executing:");
       foreach ($sql_pieces as $sqlinit) {
          $db->query($sqlinit);
          msg($sqlinit);
       }
       echo "<br><b>Uninstall complete.</b><br>\r\n";

    }

    if ($pstatus && $install) {

       $pluginid = $db->nextid($cfg["tab"]["plugins"]); // get next free id using phplib method

       $PID = 100 + $pluginid; // generate !PID! replacement
       $replace = array('!PREFIX!' => $cfg['sql']['sqlprefix'],
                        '!PID!' => $PID);

       $installsql = strtr($installsql, $replace);

       if($mode == "install") { // insert all data from install.sql
           $sql = "INSERT INTO ".$cfg["tab"]["plugins"]." (idplugin,name,`version`,author,idinternal,`status`,`date`) VALUES ('".$pluginid."','".$pname."','".$pversion."','".$pauthor."','".$pinternalid."','0','".date("Y-m-d H:i:s")."');";
           $uninstallsql = "DELETE FROM ".$cfg["tab"]["plugins"]." WHERE idplugin='".$pluginid."';\r\n";
           msg($sql);
           $db->query($sql);

           msg ($installsql, "Install query:");

           $sql_data = remove_remarks($installsql);
           $sql_pieces = split_sql_file($sql_data, ';');
           msg(count($sql_pieces)." queries", "Executing:");
           foreach ($sql_pieces as $sqlinit) {
               //$sqlinit = strtr($sqlinit, $replace);

               // create uninstall.sql for each insert entry
               if (preg_match("/INSERT\s+INTO\s+(.*)\s+VALUES\s*\([´\"'\s]*(\d+)/i", $sqlinit, $tmpsql) ) {
                    $tmpidname = $db->metadata(trim(str_replace("`", "", $tmpsql[1])));
                    $tmpidname = $tmpidname[0]['name'];
                    $uninstallsql = "DELETE FROM ".trim($tmpsql[1])." WHERE ".$tmpidname."='".trim($tmpsql[2])."';\r\n".$uninstallsql;
               }

               $db->query($sqlinit);
               msg($sqlinit);
           }

           if ($uninstallsqlfile = file_get_contents('uninstall.sql')) {
               $uninstallsqlfile = remove_remarks($uninstallsqlfile); // remove all comments

               $uninstallsql .= strtr($uninstallsqlfile, $replace); // add to generated sql
               echo "I found uninstall.sql in ".dirname(__FILE__)."<br>Statements added to uninstall query.<br>\n";

           }

           msg ($uninstallsql, "Uninstall query:");

           $sql = "UPDATE ".$cfg["tab"]["plugins"]." SET install=0x".bin2hex($installsql).", uninstall=0x".bin2hex($uninstallsql)." WHERE (idplugin='".$pluginid."');";
           msg($sql,"un/install statements stored");
           $db->query($sql);

           echo "<br><b>Install complete.</b><br>\r\n";

       }

       if($mode == "update") {
           echo "yes here is something to do for you...<br>\n";
       }


    /* con_sequence update */
    updateSequence();

    }

} else {
    echo "Sorry i found no install.sql in ".dirname(__FILE__)."<br>\n";
}

//echo $clink;

showmsg();

echo '</body></html>';


    // some functions to work with...

    /**
     * removes '# blabla...' from the mysql_dump.
     * This function was originally developed for phpbb 2.01
     * (C) 2001 The phpBB Group http://www.phpbb.com
     *
     * @return string input_without_#
     */
    function remove_remarks($sql)
    {
        $lines = explode("\n", $sql);

        // try to keep mem. use down
        $sql = "";

        $linecount = count($lines);
        $output = "";

        for ($i = 0; $i < $linecount; $i++)
        {
            if (($i != ($linecount - 1)) || (strlen($lines[$i]) > 0))
            {
                    if ($lines[$i][0] != "#")
                    {
                        $output .= $lines[$i] . "\n";
                    }
                    else
                    {
                        $output .= "\n";
                    }
                // Trading a bit of speed for lower mem. use here.
                $lines[$i] = "";
            }
        }
        return $output;
    }

    /**
     * Splits sql- statements into handy pieces.
     * This function was original developed for the phpbb 2.01
     * (C) 2001 The phpBB Group http://www.phpbb.com
     *
     * @return array sql_pieces
     */
    function split_sql_file($sql, $delimiter)
    {
        // Split up our string into "possible" SQL statements.
        $tokens = explode($delimiter, $sql);

        // try to save mem.
        $sql = "";
        $output = array();

        // we don't actually care about the matches preg gives us.
        $matches = array();

        // this is faster than calling count($oktens) every time thru the loop.
        $token_count = count($tokens);
        for ($i = 0; $i < $token_count; $i++)
        {
            // Dont wanna add an empty string as the last thing in the array.
            if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0)))
            {
                // This is the total number of single quotes in the token.
                $total_quotes = preg_match_all("/'/", $tokens[$i], $matches);
                // Counts single quotes that are preceded by an odd number of backslashes,
                // which means they're escaped quotes.
                $escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);

                $unescaped_quotes = $total_quotes - $escaped_quotes;

                // If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
                if (($unescaped_quotes % 2) == 0)
                {
                    // It's a complete sql statement.
                    $output[] = $tokens[$i];
                    // save memory.
                    $tokens[$i] = "";
                }
                else
                {
                    // incomplete sql statement. keep adding tokens until we have a complete one.
                    // $temp will hold what we have so far.
                    $temp = $tokens[$i] . $delimiter;
                    // save memory..
                    $tokens[$i] = "";

                    // Do we have a complete statement yet?
                    $complete_stmt = false;

                    for ($j = $i + 1; (!$complete_stmt && ($j < $token_count)); $j++)
                    {
                        // This is the total number of single quotes in the token.
                        $total_quotes = preg_match_all("/'/", $tokens[$j], $matches);
                        // Counts single quotes that are preceded by an odd number of backslashes,
                        // which means theyre escaped quotes.
                        $escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);

                        $unescaped_quotes = $total_quotes - $escaped_quotes;

                        if (($unescaped_quotes % 2) == 1)
                        {
                            // odd number of unescaped quotes. In combination with the previous incomplete
                            // statement(s), we now have a complete statement. (2 odds always make an even)
                            $output[] = $temp . $tokens[$j];

                            // save memory.
                            $tokens[$j] = "";
                            $temp = "";

                            // exit the loop.
                            $complete_stmt = true;
                            // make sure the outer loop continues at the right point.
                            $i = $j;
                        }
                        else
                        {
                            // even number of unescaped quotes. We still dont have a complete statement.
                            // (1 odd and 1 even always make an odd)
                            $temp .= $tokens[$j] . $delimiter;
                            // save memory.
                            $tokens[$j] = "";
                        }

                    } // for..
                } // else
            }
        }
        return $output;
    }


    // simple function to update con_sequence
    function updateSequence($table=false) {

        global $db, $cfg;
        if (!$table) {
            $sql = "SHOW TABLES";
            $db->query($sql);
            while ($db->next_record())
            {
                dbUpdateSequence($cfg['sql']['sqlprefix']."_sequence", $db->f(0));
            }
        } else {
            dbUpdateSequence($cfg['sql']['sqlprefix']."_sequence", $table);
        }
    }

    // read out next free id * deprecated
    function getSequenceId($table) {

        global $db2, $cfg;

        $sql= "SELECT nextid FROM ".$cfg['sql']['sqlprefix']."_sequence"." where seq_name = '$table'";
        $db2->query($sql);
        if ($db2->next_record()) {
            return ($db2->f("nextid")+1);
        } else {
            msg($table,"missing in ".$cfg['sql']['sqlprefix']."_sequence");
            return 0;
        }
    }

    // debug functions
    function msg($value, $info=false) {

        global $cfg;
        if (trim($cfg["debug"]["messages"]) == "") $cfg["debug"]["messages"] = "<br><b>DEBUG:</b>";
        if ($cfg["debug"]["installer"]) {

            if ($info) { $cfg["debug"]["messages"] .= "<b>$info</b> -> "; }
            if (is_array($value)) {
                ob_start();
                print_r($value);
                $output = ob_get_contents();
                ob_end_clean();
                $cfg["debug"]["messages"] .= "<pre>".htmlspecialchars($output)."</pre>";
            } else {
                $cfg["debug"]["messages"] .= htmlspecialchars($value)."<br>";
            }

        }
    }

    function showmsg() {

        global $cfg;
        if ($cfg["debug"]["installer"]) {
            echo "<div style=\"font-family: Verdana, Arial, Helvetica, Sans-Serif; font-size: 11px; color: #000000\">";
            echo $cfg["debug"]["messages"];
            echo "</div>";
        }
    }

$cfg["debug"]["backend_exectime"]["end"] = getmicrotime();

if ($cfg["debug"]["rendering"] == true)
{
    echo "Rendering this page took: " . ($cfg["debug"]["backend_exectime"]["end"] - $cfg["debug"]["backend_exectime"]["start"])." seconds<br>";
    echo "Building the complete page took: " . ($cfg["debug"]["backend_exectime"]["end"] - $cfg["debug"]["backend_exectime"]["fullstart"])." seconds<br>";

    if (function_exists("memory_get_usage"))
    {
        echo "Include memory usage: ".human_readable_size(memory_get_usage()-$cfg["debug"]["oldmemusage"])."<br>";
        echo "Complete memory usage: ".human_readable_size(memory_get_usage())."<br>";

    }

}
page_close();
?>
Could I help you... you can help me... buy me a coffee . (vielen ❤ Dank an: Seelauer, Peanut, fauxxami )

xstable.com: - HighSpeed Hosting, Domains, DomainReselling, Linux-Administration
suther.de: - App-Programierung, High-Performance-Webpages, MicroServices, API-Anbindungen & Erstellung

Software... ein Blick wert: GoogleCalender Eventlist, xst_dynamic_contentType
Oldperl
Beiträge: 4316
Registriert: Do 30. Jun 2005, 22:56
Wohnort: Eltmann, Unterfranken, Bayern
Hat sich bedankt: 6 Mal
Danksagung erhalten: 4 Mal
Kontaktdaten:

Re: Installationsscript für Plugins mitlerweile enthalten?

Beitrag von Oldperl »

Hallo rethus,

schau dir mal den Installer im AMR-Plugin an. Leider habe ich das Plugininstaller-Plugin noch nicht fertig, das wird auch wahrscheinlich noch etwas dauern, da ich gerade versuche ein System in das Pluginhandling zu bekommen.
Zumindest die beim AMR erstellte con_plugins werde ich wohl fast ohne Änderungen übernehmen.

Gruß aus Franken

Ortwin
ConLite 3.0.0-dev, alternatives und stabiles Update von Contenido 4.8.x unter PHP 8.x - Download und Repo auf Gitport.de
phpBO Search Advanced - das Suchwort-Plugin für CONTENIDO 4.9
Mein Entwickler-Blog
Gesperrt