summaryrefslogtreecommitdiffstats
path: root/modules-available/baseconfig/page.inc.php
blob: 9ff8c08616d532dc1f59e7e3d956c8f4f535823e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
<?php

class Page_BaseConfig extends Page
{
	private $qry_extra = array();
	private $categories;

	/**
	 * @var bool|string in case we're in module mode, set to the id of the module
	 */
	private $targetModule = false;

	protected function doPreprocess()
	{
		User::load();

		// Determine if we're setting global or module specific
		$this->getModuleSpecific();

		$newValues = Request::post('setting');
		if (is_array($newValues)) {
			if (!User::hasPermission('superadmin')) {
				Message::addError('main.no-permission');
				Util::redirect('?do=baseconfig');
			}
			// Build variables for specific sub-settings
			if ($this->targetModule === false) {
				// We're editing global settings - use the 'enabled' field
				$qry_insert = ', enabled';
				$qry_values = ', :enabled';
				$qry_update = ', enabled = :enabled';
				$params = array();
			} elseif (empty($this->qry_extra['field'])) {
				// Module specific, but module doesn't have an extra field
				$qry_insert = '';
				$qry_values = '';
				$qry_update = '';
			} else {
				// Module with extra field
				$qry_insert = ', ' . $this->qry_extra['field'];
				$qry_values = ', :field_value';
				$qry_update = '';
				$params = array('field_value' => $this->qry_extra['field_value']);
				$delExtra = " AND {$this->qry_extra['field']} = :field_value ";
				$delParams = array('field_value' => $this->qry_extra['field_value']);
				// Not editing global settings
				if ($this->getCurrentModuleName() === false) {
					Message::addError('main.value-invalid', $this->qry_extra['field'], $this->qry_extra['field_value']);
					Util::redirect('?do=BaseConfig');
				}
			}
			//echo "<pre>";
			//var_dump($_POST);
			//echo "</pre>";
			// Honor override/enabled checkbox
			$override = Request::post('override', array());
			// Load all existing config options to validate input
			$vars = BaseConfigUtil::getVariables();
			foreach ($vars as $key => $var) {
				if ($this->targetModule === false) {
					// Global mode
					$params['enabled'] = (is_array($override) && isset($override[$key]) && $override[$key] === 'on') ? 1 : 0;
				} else {
					// Module mode
					if (is_array($override) && (!isset($override[$key]) || $override[$key] !== 'on')) {
						// override not set - delete
						$delParams['key'] = $key;
						Database::exec("DELETE FROM {$this->qry_extra['table']} WHERE setting = :key $delExtra", $delParams);
						continue;
					}
				}
				$validator = $var['validator'];
				$displayValue = (isset($newValues[$key]) ? $newValues[$key] : '');
				// Validate data first!
				$mangledValue = Validator::validate($validator, $displayValue);
				if ($mangledValue === false) {
					Message::addWarning('main.value-invalid', $key, $displayValue);
					continue;
				}
				// Now put into DB
				Database::exec("INSERT INTO {$this->qry_extra['table']} (setting, value, displayvalue $qry_insert)"
					. " VALUES (:key, :value, :displayvalue $qry_values)"
					. " ON DUPLICATE KEY UPDATE value = :value, displayvalue = :displayvalue $qry_update",
					array(
						'key'      => $key,
						'value'    => $mangledValue,
						'displayvalue' => $displayValue
					) + $params
				);
			}
			Message::addSuccess('settings-updated');
			if ($this->targetModule === false) {
				Util::redirect('?do=BaseConfig');
			} elseif (empty($this->qry_extra['field'])) {
				Util::redirect('?do=BaseConfig&module=' . $this->targetModule);
			} else {
				Util::redirect('?do=BaseConfig&module=' . $this->targetModule . '&' . $this->qry_extra['field'] . '=' . $this->qry_extra['field_value']);
			}
		}
		// Load categories so we can define them as sub menu items
		$this->categories = BaseConfigUtil::getCategories();
		asort($this->categories, SORT_DESC);
		foreach ($this->categories as $catid => $val) {
			Dashboard::addSubmenu(
				'#category_' . $catid,
				Dictionary::translateFileModule($this->categories[$catid]['module'], 'config-variable-categories', $catid, true)
			);
		}
	}

	protected function doRender()
	{
		if (!User::hasPermission('superadmin')) {
			Message::addError('main.no-permission');
			Util::redirect('?do=Main');
		}
		// Check if valid submodule mode, store name if any
		if ($this->targetModule !== false) {
			$this->qry_extra['subheading'] = $this->getCurrentModuleName();
			if ($this->qry_extra['subheading'] === false) {
				Message::addError('main.value-invalid', $this->qry_extra['field'], $this->qry_extra['field_value']);
				Util::redirect('?do=BaseConfig');
			}
		}
		// List config options
		$settings = array();
		$vars = BaseConfigUtil::getVariables();
		// Get stuff that's set in DB already
		if ($this->targetModule === false) {
			$fields = ', enabled';
			$where = '';
			$params = array();
		} elseif (isset($this->qry_extra['field'])) {
			$fields = '';
			$where = " WHERE {$this->qry_extra['field']} = :field_value";
			$params = array('field_value' => $this->qry_extra['field_value']);
		} else {
			$fields = '';
			$where = '';
			$params = array();
		}
		// Populate structure with existing config from db
		$res = Database::simpleQuery("SELECT setting, value, displayvalue $fields FROM {$this->qry_extra['table']} "
			. " {$where} ORDER BY setting ASC", $params);
		while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
			if (!isset($vars[$row['setting']]) || !is_array($vars[$row['setting']])) {
				$unknown[] = $row['setting'];
				continue;
			}
			$row += $vars[$row['setting']];
			if (!isset($row['catid'])) {
				$row['catid'] = 'unknown';
			}
			$settings[$row['catid']]['settings'][$row['setting']] = $row;
		}
		// Add entries that weren't in the db (global), setup override checkbox (module specific)
		foreach ($vars as $key => $var) {
			if ($this->targetModule === false) {
				// Global settings - honor enabled field in db
				if (!isset($settings[$var['catid']]['settings'][$key]['enabled']) || $settings[$var['catid']]['settings'][$key]['enabled'] == 1) {
					$settings[$var['catid']]['settings'][$key]['checked'] = 'checked';
				}
			} elseif (isset($settings[$var['catid']]['settings'][$key])) {
				// Module specific - value is set in DB
				$settings[$var['catid']]['settings'][$key]['checked'] = 'checked';
			} else {
				// Module specific - value is not set in DB
				$settings[$var['catid']]['settings'][$key] = $var + array(
					'setting' => $key
				);
			}
			if (!isset($settings[$var['catid']]['settings'][$key]['displayvalue'])) {
				$settings[$var['catid']]['settings'][$key]['displayvalue'] = $var['defaultvalue'];
			}
			if (!isset($settings[$var['catid']]['settings'][$key]['shadows'])) {
				$settings[$var['catid']]['settings'][$key]['shadows'] = null;
			}
			//echo "<pre>";
			//var_dump($settings[$var['catid']]['settings'][$key]);
			//echo "</pre>";
			$settings[$var['catid']]['settings'][$key] += array(
				'item' => $this->makeInput(
										$var['validator'],
										$key,
										$settings[$var['catid']]['settings'][$key]['displayvalue'],
									   	$settings[$var['catid']]['settings'][$key]['shadows']
			),
				'description' => Util::markup(Dictionary::translateFileModule($var['module'], 'config-variables', $key))
			);
		}
		//die();


		// Sort categories
		$sortvals = array();
		foreach ($settings as $catid => &$setting) {
			$sortvals[] = isset($this->categories[$catid]) ? (int)$this->categories[$catid]['sortpos'] : 99999;
			$setting['category_id'] = $catid;
			$setting['category_name'] = Dictionary::translateFileModule($this->categories[$catid]['module'], 'config-variable-categories', $catid);
			if ($setting['category_name'] === false) {
				$setting['category_name'] = $catid;
			}
			ksort($setting['settings']);
			$setting['settings'] = array_values($setting['settings']);
		}
		unset($setting);
		array_multisort($sortvals, SORT_ASC, SORT_NUMERIC, $settings);
		Render::addTemplate('_page', array(
			'override' => $this->targetModule !== false,
			'categories'  => array_values($settings),
			'target_module' => $this->targetModule,
		) + $this->qry_extra);
		Module::isAvailable('bootstrap_switch');
	}

	private function getCurrentModuleName()
	{
		if (isset($this->qry_extra['tostring'])) {
			$method = explode('::', $this->qry_extra['tostring']);
			return call_user_func($method, $this->qry_extra['field_value']);
		}
		if (isset($this->qry_extra['field'])) {
			return $this->targetModule . ' // ' . $this->qry_extra['field'] . '=' . $this->qry_extra['field_value'];
		}
		return $this->targetModule;
	}

	private function getModuleSpecific()
	{
		$module = Request::any('module', '', 'string');
		if ($module === '') {
			$this->qry_extra = array(
				'table' => 'setting_global',
			);
			return;
		}
		//\\//\\//\\
		if (!Module::isAvailable($module)) {
			Message::addError('main.no-such-module', $module);
			Util::redirect('?do=baseconfig');
		}
		$file = 'modules/' . $module . '/baseconfig/hook.json';
		if (!file_exists($file)) {
			Message::addError('no-module-hook', $module);
			Util::redirect('?do=baseconfig');
		}
		$hook = json_decode(file_get_contents($file), true);
		if (empty($hook['table'])) {
			Message::addError('invalid-hook', $module);
			Util::redirect('?do=baseconfig');
		}
		if (isset($hook['field'])) {
			$hook['field_value'] = Request::any($hook['field'], '0', 'string');
		}
		$this->targetModule = $module;
		$this->qry_extra = $hook;
	}
	
	/**
	 * Create html snippet for setting, based on given validator
	 * @param type $validator
	 * @return boolean
	 */
	private function makeInput($validator, $setting, $current, $shadows)
	{
		/* for the html snippet we need: */
		$tag = 'input';
		$args = array('type' => 'text', 'class' => 'form-control', 'name' => "setting[$setting]", 'id' => $setting);
		if (!empty($shadows)) {
			$args['data-shadows'] = $shadows;
		}
		$inner = "";
		/* -- */

		$parts = explode(':', $validator, 2);

		if ($parts[0] === 'list') {

			$items = explode('|', $parts[1]);
			foreach ($items as $item) {
				if ($item === $current) {
					$inner .= "<option selected=\"selected\" value=\"$item\"> $item  </option>";
				} else {
					$inner .= "<option value=\"$item\"> $item </option>";
				}
			}

			$tag = 'select';
			unset($args['type']);
			$current = '';

		} elseif ($parts[0] == 'multilist') {

			$items = explode('|', $parts[1]);
			$args['multiple'] = 'multiple';
			$args['class'] 	 .= " multilist";
			$args['name']    .= '[]';

			$selected = explode(' ', $current);

			foreach ($items as $item) {
				if (in_array($item, $selected)) {
					$inner .= "<option selected=\"selected\" value=\"$item\"> $item  </option>";
				} else {
					$inner .= "<option value=\"$item\"> $item </option>";
				}
			}
			$tag = 'select';
			unset($args['type']);
			$current = '';
		}

		/* multiinput: enter multiple free-form strings*/
		if ($validator === 'multiinput') {
			$args['class'] .= " multiinput";
			$args['value'] = $current;
		}

		/* Password field guessing */
		if (stripos($validator, 'password') !== false) {
			$args['type'] = Property::getPasswordFieldType();
		}

		$output = "<$tag ";
		foreach ($args as $key => $val) {
			$output .= "$key=\"" . htmlspecialchars($val) . '" ';
		}
		if (empty($inner)) {
			$output .= '/>';
		} else {
			$output .= '>' . $inner . "</$tag>";
		}

		return $output;
	}

}