]> git.mxchange.org Git - friendica.git/blobdiff - include/dbstructure.php
And now DiscoverPoCo.php
[friendica.git] / include / dbstructure.php
index 6a14220c241bcdef90757555074e3a0a000da964..1df82b1beda5b5e50e3648c77d1572187dc10f37 100644 (file)
@@ -1,23 +1,27 @@
 <?php
 
 use Friendica\App;
+use Friendica\Core\System;
 use Friendica\Core\Config;
+use Friendica\Database\DBM;
 
-require_once("boot.php");
-require_once("include/text.php");
+require_once "boot.php";
+require_once "include/text.php";
 
 define('NEW_UPDATE_ROUTINE_VERSION', 1170);
 
+const DB_UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
+const DB_UPDATE_SUCCESSFUL = 1;  // Database check was successful
+const DB_UPDATE_FAILED = 2;      // Database check failed
+
 /*
  * Converts all tables from MyISAM to InnoDB
  */
 function convert_to_innodb() {
-       global $db;
-
        $r = q("SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `engine` = 'MyISAM' AND `table_schema` = '%s'",
-               dbesc($db->database_name()));
+               dbesc(dba::database_name()));
 
-       if (!dbm::is_result($r)) {
+       if (!DBM::is_result($r)) {
                echo t('There are no tables on MyISAM.')."\n";
                return;
        }
@@ -26,9 +30,9 @@ function convert_to_innodb() {
                $sql = sprintf("ALTER TABLE `%s` engine=InnoDB;", dbesc($table['TABLE_NAME']));
                echo $sql."\n";
 
-               $result = @$db->q($sql);
-               if (!dbm::is_result($result)) {
-                       print_update_error($db, $sql);
+               $result = dba::e($sql);
+               if (!DBM::is_result($result)) {
+                       print_update_error($sql);
                }
        }
 }
@@ -47,8 +51,8 @@ function update_fail($update_id, $error_message) {
        );
 
        // No valid result?
-       if (!dbm::is_result($adminlist)) {
-               logger(sprintf('Cannot notify administrators about update_id=%d, error_message=%s', $update_id, $error_message), LOGGER_WARNING);
+       if (!DBM::is_result($adminlist)) {
+               logger(sprintf('Cannot notify administrators about update_id=%d, error_message=%s', $update_id, $error_message), LOGGER_NORMAL);
 
                // Don't continue
                return;
@@ -69,7 +73,7 @@ function update_fail($update_id, $error_message) {
                $body = sprintf($body, $error_message);
 
                notification(array(
-                       'type' => "SYSTEM_EMAIL",
+                       'type' => SYSTEM_EMAIL,
                        'to_email' => $admin['email'],
                        'preamble' => $preamble,
                        'body' => $body,
@@ -81,14 +85,15 @@ function update_fail($update_id, $error_message) {
 
 
        /*
+        @TODO deprecated code?
        $email_tpl = get_intltext_template("update_fail_eml.tpl");
        $email_msg = replace_macros($email_tpl, array(
                '$sitename' => $a->config['sitename'],
-               '$siteurl' =>  App::get_baseurl(),
+               '$siteurl' =>  System::baseUrl(),
                '$update' => DB_UPDATE_VERSION,
                '$error' => sprintf(t('Update %s failed. See error logs.'), DB_UPDATE_VERSION)
        ));
-       $subject=sprintf(t('Update Error at %s'), App::get_baseurl());
+       $subject=sprintf(t('Update Error at %s'), System::baseUrl());
        require_once('include/email.php');
        $subject = email_header_encode($subject,'UTF-8');
        mail($a->config['admin_email'], $subject, $email_msg,
@@ -110,7 +115,7 @@ function table_structure($table) {
 
        $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
 
-       if (dbm::is_result($table_status)) {
+       if (DBM::is_result($table_status)) {
                $table_status = $table_status[0];
        } else {
                $table_status = array();
@@ -119,23 +124,21 @@ function table_structure($table) {
        $fielddata = array();
        $indexdata = array();
 
-       if (dbm::is_result($indexes))
+       if (DBM::is_result($indexes))
                foreach ($indexes AS $index) {
                        if ($index['Key_name'] != 'PRIMARY' && $index['Non_unique'] == '0' && !isset($indexdata[$index["Key_name"]])) {
                                $indexdata[$index["Key_name"]] = array('UNIQUE');
                        }
 
                        $column = $index["Column_name"];
-                       // On utf8mb4 a varchar index can only have a length of 191
-                       // The "show index" command sometimes returns this value although this value wasn't added manually.
-                       // Because we don't want to add this number to every index, we ignore bigger numbers
-                       if (($index["Sub_part"] != "") AND (($index["Sub_part"] < 191) OR ($index["Key_name"] == "PRIMARY"))) {
+
+                       if (($index["Sub_part"] != "")) {
                                $column .= "(".$index["Sub_part"].")";
                        }
 
                        $indexdata[$index["Key_name"]][] = $column;
                }
-       if (dbm::is_result($structures)) {
+       if (DBM::is_result($structures)) {
                foreach ($structures AS $field) {
                        $fielddata[$field["Field"]]["type"] = $field["Type"];
                        if ($field["Null"] == "NO") {
@@ -155,7 +158,7 @@ function table_structure($table) {
                        }
                }
        }
-       if (dbm::is_result($full_columns)) {
+       if (DBM::is_result($full_columns)) {
                foreach ($full_columns AS $column) {
                        $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
                }
@@ -182,24 +185,23 @@ function print_structure($database) {
 /**
  * @brief Print out database error messages
  *
- * @param object $db Database object
  * @param string $message Message to be added to the error message
  *
  * @return string Error message
  */
-function print_update_error($db, $message) {
+function print_update_error($message) {
        echo sprintf(t("\nError %d occurred during database update:\n%s\n"),
-               $db->errorno, $db->error);
+               dba::errorNo(), dba::errorMessage());
 
        return t('Errors encountered performing database changes: ').$message.EOL;
 }
 
 function update_structure($verbose, $action, $tables=null, $definition=null) {
-       global $a, $db;
+       global $a;
 
        if ($action) {
                Config::set('system', 'maintenance', 1);
-               Config::set('system', 'maintenance_reason', sprintf(t(': Database update'), dbm::date().' '.date('e')));
+               Config::set('system', 'maintenance_reason', sprintf(t(': Database update'), DBM::date().' '.date('e')));
        }
 
        $errors = false;
@@ -213,7 +215,7 @@ function update_structure($verbose, $action, $tables=null, $definition=null) {
                $tables = q("SHOW TABLES");
        }
 
-       if (dbm::is_result($tables)) {
+       if (DBM::is_result($tables)) {
                foreach ($tables AS $table) {
                        $table = current($table);
 
@@ -228,8 +230,8 @@ function update_structure($verbose, $action, $tables=null, $definition=null) {
        }
 
        // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
-       if ((version_compare($db->server_info(), '5.7.4') >= 0) AND
-               !(strpos($db->server_info(), 'MariaDB') !== false)) {
+       if ((version_compare(dba::server_info(), '5.7.4') >= 0) &&
+               !(strpos(dba::server_info(), 'MariaDB') !== false)) {
                $ignore = '';
        } else {
                $ignore = ' IGNORE';
@@ -242,8 +244,8 @@ function update_structure($verbose, $action, $tables=null, $definition=null) {
                $sql3 = "";
                if (!isset($database[$name])) {
                        $r = db_create_table($name, $structure["fields"], $verbose, $action, $structure['indexes']);
-                       if (!dbm::is_result($r)) {
-                               $errors .= print_update_error($db, $name);
+                       if (!DBM::is_result($r)) {
+                               $errors .= print_update_error($name);
                        }
                        $is_new_table = True;
                } else {
@@ -377,7 +379,7 @@ function update_structure($verbose, $action, $tables=null, $definition=null) {
                                $field_definition = $database[$name]["fields"][$fieldname];
 
                                // Define the default collation if not given
-                               if (!isset($parameters['Collation']) AND !is_null($field_definition['Collation'])) {
+                               if (!isset($parameters['Collation']) && !is_null($field_definition['Collation'])) {
                                        $parameters['Collation'] = 'utf8mb4_general_ci';
                                } else {
                                        $parameters['Collation'] = null;
@@ -385,7 +387,7 @@ function update_structure($verbose, $action, $tables=null, $definition=null) {
 
                                if ($field_definition['Collation'] != $parameters['Collation']) {
                                        $sql2 = db_modify_table_field($fieldname, $parameters);
-                                       if (($sql3 == "") OR (substr($sql3, -2, 2) == "; ")) {
+                                       if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
                                                $sql3 .= "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
                                        } else {
                                                $sql3 .= ", ".$sql2;
@@ -409,17 +411,18 @@ function update_structure($verbose, $action, $tables=null, $definition=null) {
 
                        if ($verbose) {
                                // Ensure index conversion to unique removes duplicates
-                               if ($is_unique) {
+                               if ($is_unique && ($temp_name != $name)) {
                                        if ($ignore != "") {
                                                echo "SET session old_alter_table=1;\n";
                                        } else {
+                                               echo "DROP TABLE IF EXISTS `".$temp_name."`;\n";
                                                echo "CREATE TABLE `".$temp_name."` LIKE `".$name."`;\n";
                                        }
                                }
 
                                echo $sql3."\n";
 
-                               if ($is_unique) {
+                               if ($is_unique && ($temp_name != $name)) {
                                        if ($ignore != "") {
                                                echo "SET session old_alter_table=0;\n";
                                        } else {
@@ -431,42 +434,48 @@ function update_structure($verbose, $action, $tables=null, $definition=null) {
                        }
 
                        if ($action) {
-                               Config::set('system', 'maintenance_reason', sprintf(t('%s: updating %s table.'), dbm::date().' '.date('e'), $name));
+                               Config::set('system', 'maintenance_reason', sprintf(t('%s: updating %s table.'), DBM::date().' '.date('e'), $name));
 
                                // Ensure index conversion to unique removes duplicates
-                               if ($is_unique) {
+                               if ($is_unique && ($temp_name != $name)) {
                                        if ($ignore != "") {
-                                               $db->q("SET session old_alter_table=1;");
+                                               dba::e("SET session old_alter_table=1;");
                                        } else {
-                                               $r = $db->q("CREATE TABLE `".$temp_name."` LIKE `".$name."`;");
-                                               if (!dbm::is_result($r)) {
-                                                       $errors .= print_update_error($db, $sql3);
+                                               dba::e("DROP TABLE IF EXISTS `".$temp_name."`;");
+                                               if (!DBM::is_result($r)) {
+                                                       $errors .= print_update_error($sql3);
+                                                       return $errors;
+                                               }
+
+                                               $r = dba::e("CREATE TABLE `".$temp_name."` LIKE `".$name."`;");
+                                               if (!DBM::is_result($r)) {
+                                                       $errors .= print_update_error($sql3);
                                                        return $errors;
                                                }
                                        }
                                }
 
-                               $r = @$db->q($sql3);
-                               if (!dbm::is_result($r)) {
-                                       $errors .= print_update_error($db, $sql3);
+                               $r = @dba::e($sql3);
+                               if (!DBM::is_result($r)) {
+                                       $errors .= print_update_error($sql3);
                                }
-                               if ($is_unique) {
+                               if ($is_unique && ($temp_name != $name)) {
                                        if ($ignore != "") {
-                                               $db->q("SET session old_alter_table=0;");
+                                               dba::e("SET session old_alter_table=0;");
                                        } else {
-                                               $r = $db->q("INSERT INTO `".$temp_name."` SELECT ".$field_list." FROM `".$name."`".$group_by.";");
-                                               if (!dbm::is_result($r)) {
-                                                       $errors .= print_update_error($db, $sql3);
+                                               $r = dba::e("INSERT INTO `".$temp_name."` SELECT ".$field_list." FROM `".$name."`".$group_by.";");
+                                               if (!DBM::is_result($r)) {
+                                                       $errors .= print_update_error($sql3);
                                                        return $errors;
                                                }
-                                               $r = $db->q("DROP TABLE `".$name."`;");
-                                               if (!dbm::is_result($r)) {
-                                                       $errors .= print_update_error($db, $sql3);
+                                               $r = dba::e("DROP TABLE `".$name."`;");
+                                               if (!DBM::is_result($r)) {
+                                                       $errors .= print_update_error($sql3);
                                                        return $errors;
                                                }
-                                               $r = $db->q("RENAME TABLE `".$temp_name."` TO `".$name."`;");
-                                               if (!dbm::is_result($r)) {
-                                                       $errors .= print_update_error($db, $sql3);
+                                               $r = dba::e("RENAME TABLE `".$temp_name."` TO `".$name."`;");
+                                               if (!DBM::is_result($r)) {
+                                                       $errors .= print_update_error($sql3);
                                                        return $errors;
                                                }
                                        }
@@ -480,6 +489,12 @@ function update_structure($verbose, $action, $tables=null, $definition=null) {
                Config::set('system', 'maintenance_reason', '');
        }
 
+       if ($errors) {
+               Config::set('system', 'dbupdate', DB_UPDATE_FAILED);
+       } else {
+               Config::set('system', 'dbupdate', DB_UPDATE_SUCCESSFUL);
+       }
+
        return $errors;
 }
 
@@ -503,14 +518,14 @@ function db_field_command($parameters, $create = true) {
        if ($parameters["extra"] != "")
                $fieldstruct .= " ".$parameters["extra"];
 
-       /*if (($parameters["primary"] != "") AND $create)
+       /*if (($parameters["primary"] != "") && $create)
                $fieldstruct .= " PRIMARY KEY";*/
 
        return($fieldstruct);
 }
 
 function db_create_table($name, $fields, $verbose, $action, $indexes=null) {
-       global $a, $db;
+       global $a;
 
        $r = true;
 
@@ -520,7 +535,7 @@ function db_create_table($name, $fields, $verbose, $action, $indexes=null) {
        $primary_keys = array();
        foreach ($fields AS $fieldname => $field) {
                $sql_rows[] = "`".dbesc($fieldname)."` ".db_field_command($field);
-               if (x($field,'primary') and $field['primary']!='') {
+               if (x($field,'primary') && $field['primary']!='') {
                        $primary_keys[] = $fieldname;
                }
        }
@@ -539,7 +554,7 @@ function db_create_table($name, $fields, $verbose, $action, $indexes=null) {
                echo $sql.";\n";
 
        if ($action)
-               $r = @$db->q($sql);
+               $r = @dba::e($sql);
 
        return $r;
 }
@@ -801,14 +816,14 @@ function db_definition() {
                                        "addr_uid" => array("addr(32)", "uid"),
                                        "nurl_uid" => array("nurl(32)", "uid"),
                                        "nick_uid" => array("nick(32)", "uid"),
-                                       "dfrn-id" => array("dfrn-id"),
-                                       "issued-id" => array("issued-id"),
+                                       "dfrn-id" => array("dfrn-id(64)"),
+                                       "issued-id" => array("issued-id(64)"),
                                        )
                        );
        $database["conv"] = array(
                        "fields" => array(
                                        "id" => array("type" => "int(10) unsigned", "not null" => "1", "extra" => "auto_increment", "primary" => "1"),
-                                       "guid" => array("type" => "varchar(64)", "not null" => "1", "default" => ""),
+                                       "guid" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
                                        "recips" => array("type" => "text"),
                                        "uid" => array("type" => "int(11)", "not null" => "1", "default" => "0", "relation" => array("user" => "uid")),
                                        "creator" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
@@ -1146,11 +1161,11 @@ function db_definition() {
                                        ),
                        "indexes" => array(
                                        "PRIMARY" => array("id"),
-                                       "guid" => array("guid"),
-                                       "uri" => array("uri"),
+                                       "guid" => array("guid(191)"),
+                                       "uri" => array("uri(191)"),
                                        "parent" => array("parent"),
-                                       "parent-uri" => array("parent-uri"),
-                                       "extid" => array("extid"),
+                                       "parent-uri" => array("parent-uri(191)"),
+                                       "extid" => array("extid(191)"),
                                        "uid_id" => array("uid","id"),
                                        "uid_contactid_id" => array("uid","contact-id","id"),
                                        "uid_created" => array("uid","created"),
@@ -1163,7 +1178,7 @@ function db_definition() {
                                        "authorid_created" => array("author-id","created"),
                                        "ownerid" => array("owner-id"),
                                        "uid_uri" => array("uid", "uri(190)"),
-                                       "resource-id" => array("resource-id"),
+                                       "resource-id" => array("resource-id(191)"),
                                        "contactid_allowcid_allowpid_denycid_denygid" => array("contact-id","allow_cid(10)","allow_gid(10)","deny_cid(10)","deny_gid(10)"), //
                                        "uid_type_changed" => array("uid","type(190)","changed"),
                                        "contactid_verb" => array("contact-id","verb(190)"),
@@ -1185,7 +1200,7 @@ function db_definition() {
                        "indexes" => array(
                                        "PRIMARY" => array("id"),
                                        "uid" => array("uid"),
-                                       "sid" => array("sid"),
+                                       "sid" => array("sid(32)"),
                                        "service" => array("service(32)"),
                                        "iid" => array("iid"),
                                        )
@@ -1195,7 +1210,7 @@ function db_definition() {
                                        "id" => array("type" => "int(11)", "not null" => "1", "extra" => "auto_increment", "primary" => "1"),
                                        "name" => array("type" => "varchar(128)", "not null" => "1", "default" => ""),
                                        "locked" => array("type" => "tinyint(1)", "not null" => "1", "default" => "0"),
-                                       "created" => array("type" => "datetime", "default" => NULL_DATE),
+                                       "pid" => array("type" => "int(10) unsigned", "not null" => "1", "default" => "0"),
                                        ),
                        "indexes" => array(
                                        "PRIMARY" => array("id"),
@@ -1205,7 +1220,7 @@ function db_definition() {
                        "fields" => array(
                                        "id" => array("type" => "int(10) unsigned", "not null" => "1", "extra" => "auto_increment", "primary" => "1"),
                                        "uid" => array("type" => "int(10) unsigned", "not null" => "1", "default" => "0", "relation" => array("user" => "uid")),
-                                       "guid" => array("type" => "varchar(64)", "not null" => "1", "default" => ""),
+                                       "guid" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
                                        "from-name" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
                                        "from-photo" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
                                        "from-url" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
@@ -1227,7 +1242,7 @@ function db_definition() {
                                        "convid" => array("convid"),
                                        "uri" => array("uri(64)"),
                                        "parent-uri" => array("parent-uri(64)"),
-                                       "contactid" => array("contact-id"),
+                                       "contactid" => array("contact-id(32)"),
                                        )
                        );
        $database["mailacct"] = array(
@@ -1561,7 +1576,7 @@ function db_definition() {
                                        ),
                        "indexes" => array(
                                        "PRIMARY" => array("id"),
-                                       "iid" => array("iid"),
+                                       "iid" => array("UNIQUE", "iid"),
                                        )
                        );
        $database["spam"] = array(
@@ -1578,7 +1593,7 @@ function db_definition() {
                                        "uid" => array("uid"),
                                        "spam" => array("spam"),
                                        "ham" => array("ham"),
-                                       "term" => array("term"),
+                                       "term" => array("term(32)"),
                                        )
                        );
        $database["term"] = array(
@@ -1645,6 +1660,7 @@ function db_definition() {
                                        "uid_created" => array("uid","created"),
                                        "uid_commented" => array("uid","commented"),
                                        "uid_wall_created" => array("uid","wall","created"),
+                                       "private_wall_received" => array("private","wall","received"),
                                        )
                        );
        $database["tokens"] = array(
@@ -1698,7 +1714,6 @@ function db_definition() {
                                        "account_expired" => array("type" => "tinyint(1)", "not null" => "1", "default" => "0"),
                                        "account_expires_on" => array("type" => "datetime", "not null" => "1", "default" => NULL_DATE),
                                        "expire_notification_sent" => array("type" => "datetime", "not null" => "1", "default" => NULL_DATE),
-                                       "service_class" => array("type" => "varchar(32)", "not null" => "1", "default" => ""),
                                        "def_gid" => array("type" => "int(11)", "not null" => "1", "default" => "0"),
                                        "allow_cid" => array("type" => "mediumtext"),
                                        "allow_gid" => array("type" => "mediumtext"),
@@ -1729,9 +1744,14 @@ function db_definition() {
                                        "created" => array("type" => "datetime", "not null" => "1", "default" => NULL_DATE),
                                        "pid" => array("type" => "int(11)", "not null" => "1", "default" => "0"),
                                        "executed" => array("type" => "datetime", "not null" => "1", "default" => NULL_DATE),
+                                       "done" => array("type" => "tinyint(1)", "not null" => "1", "default" => "0"),
                                        ),
                        "indexes" => array(
                                        "PRIMARY" => array("id"),
+                                       "pid" => array("pid"),
+                                       "parameter" => array("parameter(64)"),
+                                       "priority_created" => array("priority", "created"),
+                                       "executed" => array("executed"),
                                        )
                        );
 
@@ -1743,20 +1763,18 @@ function db_definition() {
  * run from command line
  */
 function dbstructure_run(&$argv, &$argc) {
-       global $a, $db;
+       global $a;
 
-       if (is_null($a)) {
+       if (empty($a)) {
                $a = new App(dirname(__DIR__));
        }
 
-       if (is_null($db)) {
-               @include(".htconfig.php");
-               require_once("include/dba.php");
-               $db = new dba($db_host, $db_user, $db_pass, $db_data);
-                       unset($db_host, $db_user, $db_pass, $db_data);
-       }
+       @include ".htconfig.php";
+       require_once "include/dba.php";
+       dba::connect($db_host, $db_user, $db_pass, $db_data);
+       unset($db_host, $db_user, $db_pass, $db_data);
 
-       if ($argc==2) {
+       if ($argc == 2) {
                switch ($argv[1]) {
                        case "dryrun":
                                update_structure(true, false);
@@ -1764,9 +1782,9 @@ function dbstructure_run(&$argv, &$argc) {
                        case "update":
                                update_structure(true, true);
 
-                               $build = get_config('system','build');
+                               $build = Config::get('system','build');
                                if (!x($build)) {
-                                       set_config('system','build',DB_UPDATE_VERSION);
+                                       Config::set('system', 'build', DB_UPDATE_VERSION);
                                        $build = DB_UPDATE_VERSION;
                                }
 
@@ -1776,10 +1794,12 @@ function dbstructure_run(&$argv, &$argc) {
                                // run any left update_nnnn functions in update.php
                                for ($x = $stored; $x < $current; $x ++) {
                                        $r = run_update_function($x);
-                                       if (!$r) break;
+                                       if (!$r) {
+                                               break;
+                                       }
                                }
 
-                               set_config('system','build',DB_UPDATE_VERSION);
+                               Config::set('system','build',DB_UPDATE_VERSION);
                                return;
                        case "dumpsql":
                                print_structure(db_definition());
@@ -1803,7 +1823,7 @@ function dbstructure_run(&$argv, &$argc) {
 
 }
 
-if (array_search(__file__,get_included_files())===0) {
+if (array_search(__FILE__,get_included_files())===0) {
        dbstructure_run($_SERVER["argv"],$_SERVER["argc"]);
        killme();
 }