Subversion Repositories oidplus

Rev

Rev 1116 | Rev 1148 | 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 OIDplusException
  111.          */
  112.         public function insert_id(): int {
  113.                 // This is the "fallback" variant. If your database provider (e.g. PDO) supports
  114.                 // a function to detect the last inserted id, please override this
  115.                 // function in order to use that specialized function (since it is usually
  116.                 // more reliable).
  117.                 return $this->getSlang()->insert_id($this);
  118.         }
  119.  
  120.         /**
  121.          * @param string $sql
  122.          * @return array[]
  123.          * @throws OIDplusException
  124.          */
  125.         public final function getTable(string $sql): array {
  126.                 $out = array();
  127.                 $res = $this->query($sql);
  128.                 while ($row = $res->fetch_array()) {
  129.                         $out[] = $row;
  130.                 }
  131.                 return $out;
  132.         }
  133.  
  134.         /**
  135.          * @param string $sql
  136.          * @return mixed|null
  137.          * @throws OIDplusException
  138.          */
  139.         public final function getScalar(string $sql) {
  140.                 $res = $this->query($sql);
  141.                 $row = $res->fetch_array();
  142.                 return $row ? reset($row) : null;
  143.         }
  144.  
  145.         /**
  146.          * @param string $sql
  147.          * @param array|null $prepared_args
  148.          * @return OIDplusQueryResult
  149.          * @throws OIDplusException
  150.          */
  151.         public final function query(string $sql, array $prepared_args=null): OIDplusQueryResult {
  152.  
  153.                 $query_logfile = OIDplus::baseConfig()->getValue('QUERY_LOGFILE', '');
  154.                 if (!empty($query_logfile)) {
  155.                         $ts = explode(" ",microtime());
  156.                         $ts = date("Y-m-d H:i:s",intval($ts[1])).substr((string)$ts[0],1,4);
  157.                         static $log_session_id = "";
  158.                         if (empty($log_session_id)) {
  159.                                 $log_session_id = rand(10000,99999);
  160.                         }
  161.                         $file = isset($_SERVER['REQUEST_URI']) ? ' | '.$_SERVER['REQUEST_URI'] : '';
  162.                         file_put_contents($query_logfile, "$ts <$log_session_id$file> $sql\n", FILE_APPEND);
  163.                 }
  164.  
  165.                 $this->last_query = $sql;
  166.                 $sql = str_replace('###', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', ''), $sql);
  167.  
  168.                 if ($this->slangDetectionDone) {
  169.                         $slang = $this->getSlang();
  170.                         if ($slang) {
  171.                                 $sql = $slang->filterQuery($sql);
  172.                         }
  173.                 }
  174.  
  175.                 return $this->doQuery($sql, $prepared_args);
  176.         }
  177.  
  178.         /**
  179.          * @return void
  180.          * @throws OIDplusException
  181.          */
  182.         public final function connect()/*: void*/ {
  183.                 if ($this->connected) return;
  184.                 $this->beforeConnect();
  185.                 $this->doConnect();
  186.                 $this->connected = true;
  187.                 OIDplus::register_shutdown_function(array($this, 'disconnect'));
  188.                 $this->afterConnectMandatory();
  189.                 $this->afterConnect();
  190.         }
  191.  
  192.         /**
  193.          * @return void
  194.          */
  195.         public final function disconnect()/*: void*/ {
  196.                 if (!$this->connected) return;
  197.                 $this->beforeDisconnect();
  198.                 $this->doDisconnect();
  199.                 $this->connected = false;
  200.                 $this->afterDisconnect();
  201.         }
  202.  
  203.         /**
  204.          * @param string $fieldname
  205.          * @param string $order
  206.          * @return string
  207.          * @throws OIDplusException
  208.          */
  209.         public function natOrder(string $fieldname, string $order='asc'): string {
  210.                 $slang = $this->getSlang();
  211.                 if (!is_null($slang)) {
  212.                         return $slang->natOrder($fieldname, $order);
  213.                 } else {
  214.                         $order = strtolower($order);
  215.                         if (($order != 'asc') && ($order != 'desc')) {
  216.                                 throw new OIDplusException(_L('Invalid order "%1" (needs to be "asc" or "desc")',$order));
  217.                         }
  218.  
  219.                         // For (yet) unsupported DBMS, we do not offer natural sort
  220.                         return "$fieldname $order";
  221.                 }
  222.         }
  223.  
  224.         /**
  225.          * @return void
  226.          */
  227.         protected function beforeDisconnect()/*: void*/ {}
  228.  
  229.         /**
  230.          * @return void
  231.          */
  232.         protected function afterDisconnect()/*: void*/ {}
  233.  
  234.         /**
  235.          * @return void
  236.          */
  237.         protected function beforeConnect()/*: void*/ {}
  238.  
  239.         /**
  240.          * @return void
  241.          */
  242.         protected function afterConnect()/*: void*/ {}
  243.  
  244.         /**
  245.          * @return void
  246.          * @throws OIDplusConfigInitializationException
  247.          * @throws OIDplusException
  248.          */
  249.         private function afterConnectMandatory()/*: void*/ {
  250.                 // Check if the config table exists. This is important because the database version is stored in it
  251.                 $this->initRequireTables(array('config'));
  252.  
  253.                 // Do the database tables need an update?
  254.                 // It is important that we do it immediately after connecting,
  255.                 // because the database structure might change and therefore various things might fail.
  256.                 require_once __DIR__.'/../db_updates/run.inc.php';
  257.                 oidplus_dbupdate($this);
  258.  
  259.                 // Now that our database is up-to-date, we check if database tables are existing
  260.                 // without config table, because it was checked above
  261.                 $this->initRequireTables(array('objects', 'asn1id', 'iri', 'ra'/*, 'config'*/));
  262.  
  263.                 // In case an auto-detection of the slang is required (for generic providers like PDO or ODBC),
  264.                 // we must not be inside a transaction, because the detection requires intentionally submitting
  265.                 // invalid queries to detect the correct DBMS. If we would be inside a transaction, providers like
  266.                 // PDO would automatically roll-back. Therefore, we detect the slang right at the beginning,
  267.                 // before any transaction is used.
  268.                 $this->getSlang();
  269.         }
  270.  
  271.         /**
  272.          * @param string[] $tableNames
  273.          * @return void
  274.          * @throws OIDplusConfigInitializationException
  275.          * @throws OIDplusException
  276.          */
  277.         private function initRequireTables(array $tableNames)/*: void*/ {
  278.                 $msgs = array();
  279.                 foreach ($tableNames as $tableName) {
  280.                         $prefix = OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', '');
  281.                         if (!$this->tableExists($prefix.$tableName)) {
  282.                                 $msgs[] = _L('Table %1 is missing!',$prefix.$tableName);
  283.                         }
  284.                 }
  285.                 if (count($msgs) > 0) {
  286.                         throw new OIDplusConfigInitializationException(implode("\n\n",$msgs));
  287.                 }
  288.         }
  289.  
  290.         /**
  291.          * @param string $tableName
  292.          * @return bool
  293.          */
  294.         public function tableExists(string $tableName): bool {
  295.                 try {
  296.                         // Attention: This query could interrupt transactions if Rollback-On-Error is enabled
  297.                         $this->query("select 0 from ".$tableName." where 1=0");
  298.                         return true;
  299.                 } catch (\Exception $e) {
  300.                         return false;
  301.                 }
  302.         }
  303.  
  304.         /**
  305.          * @return bool
  306.          */
  307.         public function isConnected(): bool {
  308.                 return $this->connected;
  309.         }
  310.  
  311.         /**
  312.          * @param bool $html
  313.          * @return void
  314.          */
  315.         public function init(bool $html = true)/*: void*/ {
  316.                 $this->html = $html;
  317.         }
  318.  
  319.         /**
  320.          * @return string
  321.          * @throws OIDplusException
  322.          */
  323.         public function sqlDate(): string {
  324.                 $slang = $this->getSlang();
  325.                 if (!is_null($slang)) {
  326.                         return $slang->sqlDate();
  327.                 } else {
  328.                         return "'" . date('Y-m-d H:i:s') . "'";
  329.                 }
  330.         }
  331.  
  332.         /**
  333.          * @param bool $mustExist
  334.          * @return OIDplusSqlSlangPlugin|null
  335.          * @throws OIDplusConfigInitializationException
  336.          * @throws OIDplusException
  337.          */
  338.         protected function doGetSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
  339.                 $res = null;
  340.  
  341.                 if (OIDplus::baseConfig()->exists('FORCE_DBMS_SLANG')) {
  342.                         $name = OIDplus::baseConfig()->getValue('FORCE_DBMS_SLANG', '');
  343.                         $res = OIDplus::getSqlSlangPlugin($name);
  344.                         if ($mustExist && is_null($res)) {
  345.                                 throw new OIDplusConfigInitializationException(_L('Enforced SQL slang (via setting FORCE_DBMS_SLANG) "%1" does not exist.',$name));
  346.                         }
  347.                 } else {
  348.                         foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
  349.                                 if ($plugin->detect($this)) {
  350.                                         if (OIDplus::baseConfig()->getValue('DEBUG') && !is_null($res)) {
  351.                                                 throw new OIDplusException(_L('DB-Slang detection failed: Multiple slangs were detected. Use base config setting FORCE_DBMS_SLANG to define one.'));
  352.                                         }
  353.  
  354.                                         $res = $plugin;
  355.  
  356.                                         if (!OIDplus::baseConfig()->getValue('DEBUG')) {
  357.                                                 break;
  358.                                         }
  359.                                 }
  360.                         }
  361.                         if ($mustExist && is_null($res)) {
  362.                                 throw new OIDplusException(_L('Cannot determine the SQL slang of your DBMS. Your DBMS is probably not supported.'));
  363.                         }
  364.                 }
  365.  
  366.                 return $res;
  367.         }
  368.  
  369.         /**
  370.          * @param bool $mustExist
  371.          * @return OIDplusSqlSlangPlugin|null
  372.          * @throws OIDplusConfigInitializationException
  373.          * @throws OIDplusException
  374.          */
  375.         public final function getSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
  376.                 static /*?OIDplusSqlSlangPlugin*/ $slangCache = null;
  377.  
  378.                 if ($this->slangDetectionDone) {
  379.                         return $slangCache;
  380.                 }
  381.  
  382.                 $slangCache = $this->doGetSlang();
  383.                 $this->slangDetectionDone = true;
  384.                 return $slangCache;
  385.         }
  386. }
  387.