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