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