1<?php 2 3/** 4 * DokuWiki Plugin struct (Helper Component) 5 * 6 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html 7 * @author Andreas Gohr, Michael Große <dokuwiki@cosmocode.de> 8 */ 9 10use dokuwiki\plugin\struct\meta\StructException; 11 12class helper_plugin_struct_db extends DokuWiki_Plugin 13{ 14 /** @var helper_plugin_sqlite */ 15 protected $sqlite; 16 17 /** 18 * helper_plugin_struct_db constructor. 19 */ 20 public function __construct() 21 { 22 $this->init(); 23 } 24 25 /** 26 * Initialize the database 27 * 28 * @throws Exception 29 */ 30 protected function init() 31 { 32 /** @var helper_plugin_sqlite $sqlite */ 33 $this->sqlite = plugin_load('helper', 'sqlite'); 34 if (!$this->sqlite) { 35 if (defined('DOKU_UNITTEST')) throw new \Exception('Couldn\'t load sqlite.'); 36 return; 37 } 38 39 if ($this->sqlite->getAdapter() === null) { 40 if (defined('DOKU_UNITTEST')) throw new \Exception('Couldn\'t load PDO sqlite.'); 41 $this->sqlite = null; 42 return; 43 } 44 45 if ($this->sqlite->getAdapter()->getName() != DOKU_EXT_PDO) { 46 if (defined('DOKU_UNITTEST')) throw new \Exception('Couldn\'t load PDO sqlite.'); 47 $this->sqlite = null; 48 return; 49 } 50 $this->sqlite->getAdapter()->setUseNativeAlter(true); 51 52 // initialize the database connection 53 if (!$this->sqlite->init('struct', DOKU_PLUGIN . 'struct/db/')) { 54 if (defined('DOKU_UNITTEST')) throw new \Exception('Couldn\'t init sqlite.'); 55 $this->sqlite = null; 56 return; 57 } 58 59 // register our JSON function with variable parameters 60 // todo this might be useful to be moved into the sqlite plugin 61 $this->sqlite->create_function('STRUCT_JSON', array($this, 'STRUCT_JSON'), -1); 62 } 63 64 /** 65 * @param bool $throw throw an Exception when sqlite not available? 66 * @return helper_plugin_sqlite|null 67 */ 68 public function getDB($throw = true) 69 { 70 global $conf; 71 $len = strlen($conf['metadir']); 72 if ($this->sqlite && $conf['metadir'] != substr($this->sqlite->getAdapter()->getDbFile(), 0, $len)) { 73 $this->init(); 74 } 75 if (!$this->sqlite && $throw) { 76 throw new StructException('no sqlite'); 77 } 78 return $this->sqlite; 79 } 80 81 /** 82 * Completely remove the database and reinitialize it 83 * 84 * You do not want to call this except for testing! 85 */ 86 public function resetDB() 87 { 88 if (!$this->sqlite) return; 89 $file = $this->sqlite->getAdapter()->getDbFile(); 90 if (!$file) return; 91 unlink($file); 92 clearstatcache(true, $file); 93 $this->init(); 94 } 95 96 /** 97 * Encodes all given arguments into a JSON encoded array 98 * 99 * @param string ... 100 * @return string 101 */ 102 public function STRUCT_JSON() // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps 103 { 104 $args = func_get_args(); 105 return json_encode($args); 106 } 107} 108 109// vim:ts=4:sw=4:et: 110