Subversion Repositories oidplus

Rev

Rev 1240 | Rev 1447 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft
  6.  *
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *     http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  */
  19.  
  20. namespace ViaThinkSoft\OIDplus;
  21.  
  22. // phpcs:disable PSR1.Files.SideEffects
  23. \defined('INSIDE_OIDPLUS') or die;
  24. // phpcs:enable PSR1.Files.SideEffects
  25.  
  26. abstract class OIDplusDatabaseConnection extends OIDplusBaseClass {
  27.         /**
  28.          * @var bool
  29.          */
  30.         protected /*bool*/ $connected = false;
  31.  
  32.         /**
  33.          * @var bool|null
  34.          */
  35.         protected /*?bool*/ $html = null;
  36.  
  37.         /**
  38.          * @var string|null
  39.          */
  40.         protected /*?string*/ $last_query = null;
  41.  
  42.         /**
  43.          * @var bool
  44.          */
  45.         protected /*bool*/ $slangDetectionDone = false;
  46.  
  47.         /**
  48.          * @param string $sql
  49.          * @param array|null $prepared_args
  50.          * @return OIDplusQueryResult
  51.          * @throws OIDplusException
  52.          */
  53.         protected abstract function doQuery(string $sql, array $prepared_args=null): OIDplusQueryResult;
  54.  
  55.         /**
  56.          * @return string
  57.          */
  58.         public abstract function error(): string;
  59.  
  60.         /**
  61.          * @return void
  62.          */
  63.         public abstract function transaction_begin()/*: void*/;
  64.  
  65.         /**
  66.          * @return void
  67.          */
  68.         public abstract function transaction_commit()/*: void*/;
  69.  
  70.         /**
  71.          * @return void
  72.          */
  73.         public abstract function transaction_rollback()/*: void*/;
  74.  
  75.         /**
  76.          * @return bool
  77.          */
  78.         public abstract function transaction_supported(): bool;
  79.  
  80.         /**
  81.          * @return int
  82.          */
  83.         public abstract function transaction_level(): int;
  84.  
  85.         /**
  86.          * @return void
  87.          */
  88.         protected abstract function doConnect()/*: void*/;
  89.  
  90.         /**
  91.          * @return void
  92.          */
  93.         protected abstract function doDisconnect()/*: void*/;
  94.  
  95.         /**
  96.          * @return OIDplusDatabasePlugin|null
  97.          */
  98.         public function getPlugin()/*: ?OIDplusDatabasePlugin*/ {
  99.                 $plugins = OIDplus::getDatabasePlugins();
  100.                 foreach ($plugins as $plugin) {
  101.                         if (get_class($this) == get_class($plugin::newConnection())) {
  102.                                 return $plugin;
  103.                         }
  104.                 }
  105.                 return null;
  106.         }
  107.  
  108.         /**
  109.          * @return int
  110.          * @throws OIDplusConfigInitializationException
  111.          * @throws OIDplusException
  112.          */
  113.         protected function doInsertId(): int {
  114.                 // This is the "fallback" variant. If your database provider (e.g. PDO) supports
  115.                 // a function to detect the last inserted id, please override this
  116.                 // function in order to use that specialized function (since it is usually
  117.                 // more reliable).
  118.                 return $this->getSlang()->insert_id($this);
  119.         }
  120.  
  121.         /**
  122.          * @return int
  123.          * @throws OIDplusException
  124.          */
  125.         public final function insert_id(): int {
  126.                 // DM 04 Apr 2023: Added, because MSSQL's @@IDENTITY, PgSQL, and SQLite3 does not reset after
  127.                 // a Non-Insert query (this is a test case in dev/test_database_plugins).
  128.                 // Note that the INSERT could be hidden inside a Stored Procedure; we don't support (or need) that yet.
  129.                 if (!str_starts_with(trim(strtolower($this->last_query)),'insert')) return 0;
  130.  
  131.                 return $this->doInsertId();
  132.         }
  133.  
  134.         /**
  135.          * Get the rows affected, for either SELECT, INSERT, DELETE, UPDATE
  136.          * @return int
  137.          */
  138.         public function rowsAffected(): int {
  139.                 return -1; // -1 means not implemented
  140.         }
  141.  
  142.         /**
  143.          * @param string $sql
  144.          * @return array[]
  145.          * @throws OIDplusException
  146.          */
  147.         public final function getTable(string $sql): array {
  148.                 $out = array();
  149.                 $res = $this->query($sql);
  150.                 while ($row = $res->fetch_array()) {
  151.                         $out[] = /*yield*/ $row;
  152.                 }
  153.                 return $out;
  154.         }
  155.  
  156.         /**
  157.          * @param string $sql
  158.          * @return mixed|null
  159.          * @throws OIDplusException
  160.          */
  161.         public final function getScalar(string $sql) {
  162.                 $res = $this->query($sql);
  163.                 $row = $res->fetch_array();
  164.                 return $row ? reset($row) : null;
  165.         }
  166.  
  167.         /**
  168.          * @param string $sql
  169.          * @param array|null $prepared_args
  170.          * @return OIDplusQueryResult
  171.          * @throws OIDplusException
  172.          */
  173.         public final function query(string $sql, array $prepared_args=null): OIDplusQueryResult {
  174.  
  175.                 $query_logfile = OIDplus::baseConfig()->getValue('QUERY_LOGFILE', '');
  176.                 if (!empty($query_logfile)) {
  177.                         $ts = explode(" ",microtime());
  178.                         $ts = date("Y-m-d H:i:s",intval($ts[1])).substr((string)$ts[0],1,4);
  179.                         static $log_session_id = "";
  180.                         if (empty($log_session_id)) {
  181.                                 $log_session_id = rand(10000,99999);
  182.                         }
  183.                         $file = isset($_SERVER['REQUEST_URI']) ? ' | '.$_SERVER['REQUEST_URI'] : '';
  184.                         file_put_contents($query_logfile, "$ts <$log_session_id$file> $sql\n", FILE_APPEND);
  185.                 }
  186.  
  187.                 $this->last_query = $sql;
  188.                 $sql = str_replace('###', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', ''), $sql);
  189.  
  190.                 if ($this->slangDetectionDone) {
  191.                         $slang = $this->getSlang();
  192.                         if ($slang) {
  193.                                 $sql = $slang->filterQuery($sql);
  194.                         }
  195.                 }
  196.  
  197.                 $res = $this->doQuery($sql, $prepared_args);
  198.                 if ($this->slangDetectionDone) $this->getSlang()->reviewResult($res, $sql, $prepared_args);
  199.                 return $res;
  200.         }
  201.  
  202.         /**
  203.          * @return void
  204.          * @throws OIDplusException
  205.          */
  206.         public final function connect()/*: void*/ {
  207.                 if ($this->connected) return;
  208.  
  209.                 $bcKeys = OIDplus::baseConfig()->getAllKeys();
  210.                 foreach ($bcKeys as $bkKey) {
  211.                         $val = OIDplus::baseConfig()->getValue($bkKey, '');
  212.                         if (is_string($val) && preg_match('@(userdata[/\\\\]database[/\\\\]oidplus_(empty|example)\\.(db|db3|sqlite|sqlite3|mdb|accdb))@i', $val, $m)) {
  213.                                 throw new OIDplusConfigInitializationException(_L('It looks like you are trying to use the template database file %1 in your base configuration. Since this file gets overridden by software updates, you must copy the template file and use this copy instead.', $m[1]));
  214.                         }
  215.                 }
  216.  
  217.                 $this->beforeConnect();
  218.                 $this->doConnect();
  219.                 $this->connected = true;
  220.                 OIDplus::register_shutdown_function(array($this, 'disconnect'));
  221.                 $this->afterConnectMandatory();
  222.                 $this->afterConnect();
  223.         }
  224.  
  225.         /**
  226.          * @return void
  227.          */
  228.         public final function disconnect()/*: void*/ {
  229.                 if (!$this->connected) return;
  230.                 $this->beforeDisconnect();
  231.                 $this->doDisconnect();
  232.                 $this->connected = false;
  233.                 $this->afterDisconnect();
  234.         }
  235.  
  236.         /**
  237.          * @return void
  238.          */
  239.         protected function beforeDisconnect()/*: void*/ {}
  240.  
  241.         /**
  242.          * @return void
  243.          */
  244.         protected function afterDisconnect()/*: void*/ {}
  245.  
  246.         /**
  247.          * @return void
  248.          */
  249.         protected function beforeConnect()/*: void*/ {}
  250.  
  251.         /**
  252.          * @return void
  253.          */
  254.         protected function afterConnect()/*: void*/ {}
  255.  
  256.         /**
  257.          * @return void
  258.          * @throws OIDplusConfigInitializationException
  259.          * @throws OIDplusException
  260.          */
  261.         private function afterConnectMandatory()/*: void*/ {
  262.                 // In case an auto-detection of the slang is required (for generic providers like PDO or ODBC),
  263.                 // we must not be inside a transaction, because the detection requires intentionally submitting
  264.                 // invalid queries to detect the correct DBMS. If we would be inside a transaction, providers like
  265.                 // PDO would automatically roll-back. Therefore, we detect the slang right at the beginning,
  266.                 // before any transaction is used.
  267.                 $this->getSlang();
  268.  
  269.                 // Check if the config table exists. This is important because the database version is stored in it
  270.                 $this->initRequireTables(array('config'));
  271.  
  272.                 // Do the database tables need an update?
  273.                 // It is important that we do it immediately after connecting,
  274.                 // because the database structure might change and therefore various things might fail.
  275.                 require_once __DIR__.'/../db_updates/run.inc.php';
  276.                 oidplus_dbupdate($this);
  277.  
  278.                 // Now that our database is up-to-date, we check if database tables are existing
  279.                 // without config table, because it was checked above
  280.                 $this->initRequireTables(array('objects', 'asn1id', 'iri', 'ra'/*, 'config'*/));
  281.         }
  282.  
  283.         /**
  284.          * @param string[] $tableNames
  285.          * @return void
  286.          * @throws OIDplusConfigInitializationException
  287.          * @throws OIDplusException
  288.          */
  289.         private function initRequireTables(array $tableNames)/*: void*/ {
  290.                 $msgs = array();
  291.  
  292.                 // Check for a general database error like a locked file DBMS
  293.                 // which would raise a false warning "Table oidplus_config missing"
  294.                 $this->query("select 0");
  295.  
  296.                 $prefix = OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', '');
  297.                 foreach ($tableNames as $tableName) {
  298.                         if (!$this->tableExists($prefix.$tableName)) {
  299.                                 $msgs[] = _L('Table %1 is missing!',$prefix.$tableName);
  300.                         }
  301.                 }
  302.                 if (count($msgs) > 0) {
  303.                         throw new OIDplusConfigInitializationException(implode("\n\n",$msgs));
  304.                 }
  305.         }
  306.  
  307.         /**
  308.          * @param string $tableName
  309.          * @return bool
  310.          */
  311.         public function tableExists(string $tableName): bool {
  312.                 try {
  313.                         // Attention: This query could interrupt transactions if Rollback-On-Error is enabled
  314.                         $this->query("select 0 from ".$tableName." where 1=0");
  315.                         return true;
  316.                 } catch (\Exception $e) {
  317.                         return false;
  318.                 }
  319.         }
  320.  
  321.         /**
  322.          * @return bool
  323.          */
  324.         public function isConnected(): bool {
  325.                 return $this->connected;
  326.         }
  327.  
  328.         /**
  329.          * @param bool $html
  330.          * @return void
  331.          */
  332.         public function init(bool $html = true)/*: void*/ {
  333.                 $this->html = $html;
  334.         }
  335.  
  336.         /**
  337.          * @return string
  338.          * @throws OIDplusException
  339.          */
  340.         public function sqlDate(): string {
  341.                 $slang = $this->getSlang();
  342.                 if (!is_null($slang)) {
  343.                         return $slang->sqlDate();
  344.                 } else {
  345.                         // Fallback: Take the server date
  346.                         return "'" . date('Y-m-d H:i:s') . "'";
  347.                 }
  348.         }
  349.  
  350.         /**
  351.          * @param bool $mustExist
  352.          * @return OIDplusSqlSlangPlugin|null
  353.          * @throws OIDplusConfigInitializationException
  354.          * @throws OIDplusException
  355.          */
  356.         protected function doGetSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
  357.                 $res = null;
  358.  
  359.                 if (OIDplus::baseConfig()->exists('FORCE_DBMS_SLANG')) {
  360.                         $name = OIDplus::baseConfig()->getValue('FORCE_DBMS_SLANG', '');
  361.                         $res = OIDplus::getSqlSlangPlugin($name);
  362.                         if ($mustExist && is_null($res)) {
  363.                                 throw new OIDplusConfigInitializationException(_L('Enforced SQL slang (via setting FORCE_DBMS_SLANG) "%1" does not exist.',$name));
  364.                         }
  365.                 } else {
  366.                         foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
  367.                                 if ($plugin->detect($this)) {
  368.                                         if (OIDplus::baseConfig()->getValue('DEBUG') && !is_null($res)) {
  369.  
  370.                                                 $detected = array();
  371.                                                 foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
  372.                                                         if ($plugin->detect($this)) {
  373.                                                                 $detected[] = get_class($plugin);
  374.                                                         }
  375.                                                 }
  376.  
  377.                                                 throw new OIDplusException(_L('DB-Slang detection failed: Multiple slangs were detected (%1). Use base config setting FORCE_DBMS_SLANG to define one.', implode(', ',$detected)));
  378.                                         }
  379.  
  380.                                         $res = $plugin;
  381.  
  382.                                         if (!OIDplus::baseConfig()->getValue('DEBUG')) {
  383.                                                 break;
  384.                                         }
  385.                                 }
  386.                         }
  387.                         if ($mustExist && is_null($res)) {
  388.                                 throw new OIDplusException(_L('Cannot determine the SQL slang of your DBMS. Your DBMS is probably not supported.'));
  389.                         }
  390.                 }
  391.  
  392.                 return $res;
  393.         }
  394.  
  395.         /**
  396.          * @param bool $mustExist
  397.          * @return OIDplusSqlSlangPlugin|null
  398.          * @throws OIDplusConfigInitializationException
  399.          * @throws OIDplusException
  400.          */
  401.         public final function getSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
  402.                 static /*?OIDplusSqlSlangPlugin*/ $slangCache = null;
  403.  
  404.                 if ($this->slangDetectionDone) {
  405.                         return $slangCache;
  406.                 }
  407.  
  408.                 $slangCache = $this->doGetSlang();
  409.                 $this->slangDetectionDone = true;
  410.                 return $slangCache;
  411.         }
  412.  
  413.         /**
  414.          * @return array
  415.          */
  416.         public function getExtendedInfo(): array {
  417.                 return array();
  418.         }
  419. }
  420.