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