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\Extension\Event; 11use dokuwiki\plugin\struct\meta\StructException; 12 13class helper_plugin_struct_db extends DokuWiki_Plugin 14{ 15 /** @var \dokuwiki\plugin\sqlite\SQLiteDB */ 16 protected $sqlite; 17 18 /** 19 * helper_plugin_struct_db constructor. 20 */ 21 public function __construct() 22 { 23 $this->init(); 24 } 25 26 /** 27 * Initialize the database 28 * 29 * @throws Exception 30 */ 31 protected function init() 32 { 33 try { 34 /** @var \dokuwiki\plugin\sqlite\SQLiteDB $sqlite */ 35 $this->sqlite = new \dokuwiki\plugin\sqlite\SQLiteDB('struct', DOKU_PLUGIN . 'struct/db/'); 36 } catch (Exception $exception) { 37 if (defined('DOKU_UNITTEST')) throw new \Exception('Couldn\'t load sqlite.'); 38 return; 39 } 40 41 // register our JSON function with variable parameters 42 $this->sqlite->getDb()->sqliteCreateFunction('STRUCT_JSON', [$this, 'STRUCT_JSON'], -1); 43 44 // this function is meant to be overwritten by plugins 45 $this->sqlite->getDb()->sqliteCreateFunction('IS_PUBLISHER', [$this, 'IS_PUBLISHER'], -1); 46 } 47 48 /** 49 * @param bool $throw throw an Exception when sqlite not available 50 * @return \dokuwiki\plugin\sqlite\SQLiteDB|null 51 */ 52 public function getDB($throw = true) 53 { 54 global $conf; 55 $len = strlen($conf['metadir']); 56 if ($this->sqlite && $conf['metadir'] != substr($this->sqlite->getDbFile(), 0, $len)) { 57 $this->init(); 58 } 59 if (!$this->sqlite && $throw) { 60 throw new StructException('no sqlite'); 61 } 62 return $this->sqlite; 63 } 64 65 /** 66 * Completely remove the database and reinitialize it 67 * 68 * You do not want to call this except for testing! 69 */ 70 public function resetDB() 71 { 72 if (!$this->sqlite) return; 73 $file = $this->sqlite->getDbFile(); 74 if (!$file) return; 75 unlink($file); 76 clearstatcache(true, $file); 77 $this->init(); 78 } 79 80 /** 81 * Encodes all given arguments into a JSON encoded array 82 * 83 * @param string ... 84 * @return string 85 */ 86 public function STRUCT_JSON() // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps 87 { 88 $args = func_get_args(); 89 return json_encode($args); 90 } 91 92 /** 93 * This dummy implementation can be overwritten by a plugin 94 * 95 * @return int 96 */ 97 public function IS_PUBLISHER() // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps 98 { 99 return 1; 100 } 101} 102 103// vim:ts=4:sw=4:et: 104