1<?php
2
3/**
4 * DokuWiki Plugin randomtable (Action Component)
5 *
6 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
7 * @author  Oscar Merida <oscar@oscarm.org>
8 */
9
10class action_plugin_randomtables_ajax extends \dokuwiki\Extension\ActionPlugin
11{
12	public function register(Doku_Event_Handler $controller)
13	{
14		$controller->register_hook('randomtables_save', 'AFTER', $this, 'save');
15		$controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this,'ajax_call');
16	}
17
18	public function save(Doku_Event $event, $param): void
19	{
20		try {
21			$helper = $this->loadHelper('randomtables_helper');
22			$db = $helper->getDB();
23		} catch (Exception $e) {
24			msg($e->getMessage(), -1);
25			return;
26		}
27
28		$data = $event->data;
29		$id = $data['id'];
30		if (!$id) {
31			return;
32		}
33
34		$json = [];
35		foreach ($data['lines'] as $l) {
36			$json[] = ['min' => $l[0], 'max' => $l[1], 'result' => $l[2]];
37		}
38
39		$db->storeEntry('rtables', [
40			'id' => $id,
41			'rows' => json_encode($json)
42		]);
43	}
44
45	function ajax_call(Doku_Event $event, $param):void
46	{
47		if ($event->data !== 'plugin_randomtable_roll') {
48			return;
49		}
50
51		//no other ajax call handlers needed
52		$event->stopPropagation();
53		$event->preventDefault();
54
55
56		$tableId = isset($_POST['table_id']) ? trim($_POST['table_id']) : null;
57		if (!$tableId || !preg_match('/^[A-Za-z0-9_]+$/', $tableId)) {
58			return;
59		}
60
61		// get the DB
62		try {
63			$helper = $this->loadHelper('randomtables_helper');
64			$db = $helper->getDB();
65		} catch (Exception $e) {
66			msg($e->getMessage(), -1);
67			return;
68		}
69
70		$this->setupAutoloader();
71
72
73		$manager = new TableRoller\Table\Manager($db);
74		$pick = $manager->rollOn($tableId);
75		$pick = trim(htmlentities($pick, ENT_QUOTES | ENT_SUBSTITUTE | ENT_XHTML));
76		header('Content-Type: application/json');
77		echo json_encode(['result' => $pick]);
78	}
79
80	private function setupAutoloader()
81	{
82		spl_autoload_register(function ($class) {
83
84			// project-specific namespace prefix
85			$prefix = 'TableRoller\\';
86
87			// base directory for the namespace prefix
88			$base_dir = __DIR__ . '/../table-roller/src/';
89
90			// does the class use the namespace prefix?
91			$len = strlen($prefix);
92			if (strncmp($prefix, $class, $len) !== 0) {
93				// no, move to the next registered autoloader
94				return;
95			}
96
97			// get the relative class name
98			$relative_class = substr($class, $len);
99
100			// replace the namespace prefix with the base directory, replace namespace
101			// separators with directory separators in the relative class name, append
102			// with .php
103			$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
104
105			// if the file exists, require it
106			if (file_exists($file)) {
107				require $file;
108			}
109		});
110	}
111}
112