PageRenderTime 42ms CodeModel.GetById 20ms app.highlight 17ms RepoModel.GetById 1ms app.codeStats 1ms

/administrator/components/com_zoo/controllers/configuration.php

https://gitlab.com/vnsoftdev/amms
PHP | 471 lines | 289 code | 125 blank | 57 comment | 29 complexity | cc76e05e20fa4e43a696ab4e7510ab4d MD5 | raw file
  1<?php
  2/**
  3 * @package   com_zoo
  4 * @author    YOOtheme http://www.yootheme.com
  5 * @copyright Copyright (C) YOOtheme GmbH
  6 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
  7 */
  8
  9/*
 10	Class: ConfigurationController
 11		The controller class for application configuration
 12*/
 13class ConfigurationController extends AppController {
 14
 15	public $application;
 16
 17	public function __construct($default = array()) {
 18		parent::__construct($default);
 19
 20		// set table
 21		$this->table = $this->app->table->application;
 22
 23		// get application
 24		$this->application 	= $this->app->zoo->getApplication();
 25
 26		// check ACL
 27		if (!$this->application->isAdmin()) {
 28			throw new ConfigurationControllerException("Invalid Access Permissions!", 1);
 29		}
 30
 31		// set base url
 32		$this->baseurl = $this->app->link(array('controller' => $this->controller), false);
 33
 34		// register tasks
 35		$this->registerTask('applyassignelements', 'saveassignelements');
 36		$this->registerTask('apply', 'save');
 37	}
 38
 39	public function display($cachable = false, $urlparams = false) {
 40
 41		// set toolbar items
 42		$this->app->system->application->JComponentTitle = $this->application->getToolbarTitle(JText::_('Config'));
 43		$this->app->toolbar->apply();
 44		$this->app->zoo->toolbarHelp();
 45
 46		// get params
 47		$this->params = $this->application->getParams();
 48
 49		// template select
 50		$options = array($this->app->html->_('select.option', '', '- '.JText::_('Select Template').' -'));
 51		foreach ($this->application->getTemplates() as $template) {
 52			$options[] = $this->app->html->_('select.option', $template->name, $template->getMetaData('name'));
 53		}
 54
 55		$this->lists['select_template'] = $this->app->html->_('select.genericlist',  $options, 'template', '', 'value', 'text', $this->params->get('template'));
 56
 57		// get permission form
 58		$xml = simplexml_load_file(JPATH_COMPONENT . '/models/forms/permissions.xml');
 59
 60		$this->permissions = JForm::getInstance('com_zoo.new', $xml->asXML());
 61		$this->permissions->bind(array('asset_id' => $this->application->asset_id));
 62		$this->assetPermissions = array();
 63		$asset = JTable::getInstance('Asset');
 64
 65		foreach ($this->application->getTypes() as $typeName => $type) {
 66			$xml->fieldset->field->attributes()->section = 'type';
 67			$xml->fieldset->field->attributes()->name = 'rules_' . $typeName;
 68			$this->assetPermissions[$typeName] = JForm::getInstance('com_zoo.new.' . $typeName, $xml->asXML());
 69
 70			if ($asset->loadByName($type->getAssetName())) {
 71				$assetName = $type->getAssetName();
 72			} else {
 73				$assetName = $this->application->asset_id;
 74			}
 75			$this->assetPermissions[$typeName]->bind(array('asset_id' => $assetName));
 76		}
 77
 78		// manipulate js in J25
 79		if ($this->app->joomla->isVersion('2.5')) {
 80			JDispatcher::getInstance()->attach(array('event' => 'onAfterDispatch', 'handler' => array($this, 'eventCallback')));
 81		}
 82
 83		// display view
 84		$this->getView()->setLayout('application')->display();
 85	}
 86
 87	public function eventCallback() {
 88
 89		$script = $this->app->system->document->_script['text/javascript'];
 90		$types  = array_keys($this->application->getTypes());
 91		$types[]= 'application';
 92
 93		$i = 3;
 94		$script = preg_replace_callback('/div#permissions-sliders\.pane-sliders/', function ($match) use (&$i, $types) {
 95			return 'div .zoo-'.$types[(int) ($i++ / 3) - 1].'-permissions';
 96		}, $script);
 97
 98		$this->app->system->document->_script['text/javascript'] = $script;
 99	}
100
101	public function save() {
102
103		// check for request forgeries
104		$this->app->session->checkToken() or jexit('Invalid Token');
105
106		// init vars
107		$post = $this->app->request->get('post:', 'array');
108
109		try {
110
111			// bind post
112			self::bind($this->application, $post, array('params'));
113
114			// set params
115			$params = $this->application
116				->getParams()
117				->remove('global.')
118				->set('template', @$post['template'])
119				->set('global.config.', @$post['params']['config'])
120				->set('global.template.', @$post['params']['template']);
121
122			if (isset($post['addons']) && is_array($post['addons'])) {
123				foreach ($post['addons'] as $addon => $value) {
124					$params->set("global.$addon.", $value);
125				}
126			}
127
128			// add ACL rules to aplication object
129			$this->application->rules = $post['rules'];
130
131			foreach ($post as $key => $value) {
132				if (stripos($key, 'rules_') === 0) {
133					$this->application->assetRules[substr($key, 6)] = $value;
134				}
135			}
136
137			// save application
138			$this->table->save($this->application);
139
140			// set redirect message
141			$msg = JText::_('Application Saved');
142
143		} catch (AppException $e) {
144
145			// raise notice on exception
146			$this->app->error->raiseNotice(0, JText::_('Error Saving Application').' ('.$e.')');
147			$msg = null;
148
149		}
150
151		$this->setRedirect($this->baseurl, $msg);
152	}
153
154	public function getApplicationParams() {
155
156		// init vars
157		$template     = $this->app->request->getCmd('template');
158
159		// get params
160		$this->params = $this->application->getParams();
161
162        // get permission form
163        $xml = simplexml_load_file(JPATH_COMPONENT . '/models/forms/permissions.xml');
164
165        $this->permissions = JForm::getInstance('com_zoo.new', $xml->asXML());
166        $this->permissions->bind(array('asset_id' => $this->application->asset_id));
167        $this->assetPermissions = array();
168        $asset = JTable::getInstance('Asset');
169
170        foreach ($this->application->getTypes() as $typeName => $type) {
171            $xml->fieldset->field->attributes()->section = 'type';
172            $xml->fieldset->field->attributes()->name = 'rules_' . $typeName;
173            $this->assetPermissions[$typeName] = JForm::getInstance('com_zoo.new.' . $typeName, $xml->asXML());
174
175            if ($asset->loadByName($type->getAssetName())) {
176                $assetName = $type->getAssetName();
177            } else {
178                $assetName = $this->application->asset_id;
179            }
180            $this->assetPermissions[$typeName]->bind(array('asset_id' => $assetName));
181        }
182
183		// set template
184		$this->params->set('template', $template);
185
186		// display view
187		$this->getView()->setLayout('_applicationparams')->display();
188	}
189
190	public function importExport() {
191
192		// set toolbar items
193		$this->app->system->application->JComponentTitle = $this->application->getToolbarTitle(JText::_('Import / Export'));
194		$this->app->zoo->toolbarHelp();
195
196		$this->exporter = $this->app->export->getExporters('Zoo v2');
197
198		// display view
199		$this->getView()->setLayout('importexport')->display();
200	}
201
202	public function importFrom() {
203
204		// check for request forgeries
205		$this->app->session->checkToken() or jexit('Invalid Token');
206
207		$exporter = $this->app->request->getString('exporter');
208
209		try {
210
211			$xml = $this->app->export->create($exporter)->export();
212
213			$file = rtrim($this->app->system->config->get('tmp_path'), '\/') . '/' . $this->app->utility->generateUUID() . '.tmp';
214			if (JFile::exists($file)) {
215				JFile::delete($file);
216			}
217			JFile::write($file, $xml);
218
219		} catch (Exception $e) {
220
221			// raise error on exception
222			$this->app->error->raiseNotice(0, JText::_('Error During Export').' ('.$e.')');
223			$this->setRedirect($this->baseurl.'&task=importexport');
224			return;
225
226		}
227
228		$this->_import($file);
229
230	}
231
232	public function import() {
233
234		// check for request forgeries
235		$this->app->session->checkToken() or jexit('Invalid Token');
236
237		$userfile = null;
238
239		$jsonfile = $this->app->request->getVar('import-json', array(), 'files', 'array');
240
241		try {
242
243			// validate
244			$validator = $this->app->validator->create('file', array('extensions' => array('json')));
245			$userfile = $validator->clean($jsonfile);
246			$type = 'json';
247
248		} catch (AppValidatorException $e) {}
249
250		$csvfile = $this->app->request->getVar('import-csv', array(), 'files', 'array');
251
252		try {
253
254			// validate
255			$validator = $this->app->validator->create('file', array('extensions' => array('csv')));
256			$userfile = $validator->clean($csvfile);
257			$type = 'csv';
258
259		} catch (AppValidatorException $e) {}
260
261		if (!empty($userfile)) {
262			$file = rtrim($this->app->system->config->get('tmp_path'), '\/') . '/' . basename($userfile['tmp_name']);
263			if (JFile::upload($userfile['tmp_name'], $file)) {
264
265				$this->_import($file, $type);
266
267			} else {
268				// raise error on exception
269				$this->app->error->raiseNotice(0, JText::_('Error Importing (Unable to upload file.)'));
270				$this->setRedirect($this->baseurl.'&task=importexport');
271				return;
272			}
273		} else {
274			// raise error on exception
275			$this->app->error->raiseNotice(0, JText::_('Error Importing (Unable to upload file.)'));
276			$this->setRedirect($this->baseurl.'&task=importexport');
277			return;
278		}
279
280
281	}
282
283	public function importCSV() {
284
285		$file = $this->app->request->getCmd('file', '');
286		$file = rtrim($this->app->system->config->get('tmp_path'), '\/') . '/' . $file;
287
288		$this->_import($file, 'importcsv');
289	}
290
291	protected function _import($file, $type = 'json') {
292
293		// disable menu
294		$this->app->request->setVar('hidemainmenu', 1);
295
296		// set toolbar items
297		$this->app->system->application->JComponentTitle = $this->application->getToolbarTitle(JText::_('Import').': '.$this->application->name);
298		$this->app->toolbar->cancel('importexport', 'Cancel');
299		$this->app->zoo->toolbarHelp();
300
301		// set_time_limit doesn't work in safe mode
302        if (!ini_get('safe_mode')) {
303		    @set_time_limit(0);
304        }
305
306		$layout = '';
307		switch ($type) {
308			case 'xml':
309				$this->app->error->raiseWarning(0, 'XML import is not supported since ZOO 2.5!');
310				$this->importExport();
311				break;
312			case 'json':
313				if (JFile::exists($file) && $data = $this->app->data->create(file_get_contents($file))) {
314
315					$this->info = $this->app->import->getImportInfo($data);
316					$this->file = basename($file);
317
318				} else {
319
320					// raise error on exception
321					$this->app->error->raiseNotice(0, JText::_('Error Importing (Not a valid JSON file)'));
322					$this->setRedirect($this->baseurl.'&task=importexport');
323					return;
324
325				}
326				$layout = 'importjson';
327				break;
328			case 'csv':
329
330				$this->file = basename($file);
331
332				$layout = 'configcsv';
333				break;
334			case 'importcsv':
335				$this->contains_headers = $this->app->request->getBool('contains-headers', false);
336				$this->field_separator	= $this->app->request->getString('field-separator', ',');
337				$this->field_separator	= empty($this->field_separator) ? ',' : substr($this->field_separator, 0, 1);
338				$this->field_enclosure	= $this->app->request->getString('field-enclosure', '"');
339				$this->field_enclosure	= empty($this->field_enclosure) ? '"' : substr($this->field_enclosure, 0, 1);
340
341				$this->info = $this->app->import->getImportInfoCSV($file, $this->contains_headers, $this->field_separator, $this->field_enclosure);
342				$this->file = basename($file);
343
344				$layout = 'importcsv';
345				break;
346		}
347
348		// display view
349		$this->getView()->setLayout($layout)->display();
350
351	}
352
353	public function doImport() {
354
355		// init vars
356		$import_frontpage   = $this->app->request->getBool('import-frontpage', false);
357		$import_categories  = $this->app->request->getBool('import-categories', false);
358		$element_assignment = $this->app->request->get('element-assign', 'array', array());
359		$types				= $this->app->request->get('types', 'array', array());
360		$file 				= $this->app->request->getCmd('file', '');
361		$file 				= rtrim($this->app->system->config->get('tmp_path'), '\/') . '/' . $file;
362
363		if (JFile::exists($file)) {
364			$this->app->import->import($file, $import_frontpage, $import_categories, $element_assignment, $types);
365		}
366
367		$this->setRedirect($this->baseurl.'&task=importexport', JText::_('Import successfull'));
368	}
369
370	public function doImportCSV() {
371
372		// init vars
373		$contains_headers   = $this->app->request->getBool('contains-headers', false);
374		$field_separator    = $this->app->request->getString('field-separator', ',');
375		$field_enclosure    = $this->app->request->getString('field-enclosure', '"');
376		$element_assignment = $this->app->request->get('element-assign', 'array', array());
377		$type				= $this->app->request->getCmd('type', '');
378		$file 				= $this->app->request->getCmd('file', '');
379		$file 				= rtrim($this->app->system->config->get('tmp_path'), '\/') . '/' . $file;
380
381		if (JFile::exists($file)) {
382			$this->app->import->importCSV($file, $type, $contains_headers, $field_separator, $field_enclosure, $element_assignment);
383		}
384
385		$this->setRedirect($this->baseurl.'&task=importexport', JText::_('Import successfull'));
386	}
387
388	public function doExport() {
389
390		$exporter = $this->app->request->getCmd('exporter');
391
392		if ($exporter) {
393
394			try {
395
396				// set_time_limit doesn't work in safe mode
397		        if (!ini_get('safe_mode')) {
398				    @set_time_limit(0);
399		        }
400
401				$json = $this->app->export->create($exporter)->export();
402
403				header("Pragma: public");
404		        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
405		        header("Expires: 0");
406		        header("Content-Transfer-Encoding: binary");
407				header ("Content-Type: application/json");
408				header('Content-Disposition: attachment;'
409				.' filename="'.JFilterOutput::stringURLSafe($this->application->name).'.json";'
410				);
411
412				echo $json;
413
414			} catch (AppExporterException $e) {
415
416				// raise error on exception
417				$this->app->error->raiseNotice(0, JText::_('Error Exporting').' ('.$e.')');
418				$this->setRedirect($this->baseurl.'&task=importexport');
419				return;
420
421			}
422		}
423	}
424
425	public function doExportCSV() {
426
427		//init vars
428		$files = array();
429
430		try {
431
432			foreach ($this->application->getTypes() as $type) {
433				if ($file = $this->app->export->toCSV($type)) {
434					$files[] = $file;
435				}
436			}
437
438			if (empty($files)) {
439				throw new AppException(JText::sprintf('There are no items to export'));
440			}
441
442			$filepath = $this->app->path->path("tmp:").'/'.$this->application->getGroup().'.zip';
443			$zip = $this->app->archive->open($filepath, 'zip');
444			$zip->create($files, PCLZIP_OPT_REMOVE_ALL_PATH);
445			if (is_readable($filepath) && JFile::exists($filepath)) {
446				$this->app->filesystem->output($filepath);
447				$files[] = $filepath;
448				foreach ($files as $file) {
449					if (JFile::exists($file)) {
450						JFile::delete($file);
451					}
452				}
453			} else {
454				throw new AppException(JText::sprintf('Unable to create file %s', $filepath));
455			}
456
457		} catch (AppException $e) {
458				// raise error on exception
459				$this->app->error->raiseNotice(0, JText::_('Error Exporting').' ('.$e.')');
460				$this->setRedirect($this->baseurl.'&task=importexport');
461				return;
462		}
463
464	}
465
466}
467
468/*
469	Class: ConfigurationControllerException
470*/
471class ConfigurationControllerException extends AppException {}