viewRulesetArchives();
	}
	
	//=============================================================================================
	// DIALOG
	//=============================================================================================
	
	function dialog() {
		TabulizerPath::requireLib('tabdialog','dialog');
	}
		
	function convert() {
		TabulizerPath::requireLib('convert','dialog');
	}
    function dsdata() {
        TabulizerPath::requireLib('dsdata','dialog');
    }
	
	function extract_table_data() {
		TabulizerPath::requireLib('extract_table_data','dialog');		
	}
	
	function extract_excel_data() {
		TabulizerPath::requireLib('extract_excel_data','dialog');
	}
	
	function upload_excel_file() {
		TabulizerPath::requireLib('upload_excel_file','dialog');
	}
    function extract_csv_data() {
        TabulizerPath::requireLib('extract_csv_data','dialog');
    }
    function upload_csv_file() {
        TabulizerPath::requireLib('upload_csv_file','dialog');
    }
    function extract_grid_data() {
        TabulizerPath::requireLib('extract_grid_data','dialog');
    }
    function save_grid_data() {
        TabulizerPath::requireLib('save_grid_data','dialog');
    }
    function grab_table_data() {
        TabulizerPath::requireLib('grab_table_data','dialog');
    }
	
	function dsselect() {
		TabulizerPath::requireLib('dsselect','dialog');
	}
	
	function exportdata() {
		TabulizerPath::requireLib('exportdata','dialog');
	}
    function outputDataSource() {
        TabulizerPath::requireLib('datasource','output');
    }
	//=============================================================================================
	// RULESET ARCHIVES
	//=============================================================================================	
	
	function viewRulesetArchives() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		
		$model = $this->getModel('rulesetarchives');
		$view = $this->getView('rulesetarchives','html');
		
		 // Get pagination request variables
   	    $mainframe = JFactory::getApplication();
        if (CLIENT_SIDE_PAGINATION) {
            $limit = 0;
            $limitstart = 0;
        } else {
            $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
            $limitstart = $jinput->getInt('limitstart', 0);
            // In case limit has been changed, adjust it
            if (empty($limit)) { $limit = $mainframe->getCfg('list_limit'); $limitstart = 0; }
            $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
        }
 
		$editor_pugin_installed = TabulizerInfo::isEditorPluginInstalled();
		if ($editor_pugin_installed) {
			$model->loadRulesetArchives($limit, $limitstart);				
			
			$view->setModel($model, true);
			$view->setLayout('default');
			$view->display();							
		} else {
			$msg = JText::_('COM_TABULIZER_EDITOR_PLUGIN_NOT_INSTALLED');
			TabulizerUserMessage::printInfo($msg);	
		}
	}
	
	//=============================================================================================
	// USER_PREFERENCES
	//=============================================================================================	
	
	function editUserPreferences() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
        $error_msg = null;
		
		$model = $this->getModel('rulesetarchives');
		$view = $this->getView('rulesetarchives','html');
								
		$editor_pugin_installed = TabulizerInfo::isEditorPluginInstalled();
		if ($editor_pugin_installed) {
			if ($model->loadUserPreferences($error_msg)) {						
				$view->setModel($model, true);
				$view->setLayout('user_preferences');
				$view->displayUserPreferences();							
			} else {
				$msg = sprintf(JText::_( 'COM_TABULIZER_USER_PREFERENCES_LOAD_FAILURE' ),$error_msg);
				TabulizerUserMessage::printError($msg);	
			}
		} else {
			$msg = JText::_('COM_TABULIZER_EDITOR_PLUGIN_NOT_INSTALLED');
			TabulizerUserMessage::printError($msg);	
		}	
	}
	
	function saveUserPreferences() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'message';
        $error_msg = null;
		
		$model = $this->getModel('rulesetarchives');
		if ($model->saveUserPreferences($error_msg)) {		
			$msg = JText::_( 'COM_TABULIZER_USER_PREFERENCES_SAVE_SUCCESS' );
			$this->setRedirect($link, $msg, $msg_type);	
		} else {
			$msg = sprintf(JText::_( 'COM_TABULIZER_USER_PREFERENCES_SAVE_FAILURE' ),$error_msg);
			$msg_type = 'error';
			$this->setRedirect($link, $msg, $msg_type);	
		}	
		return;		
	}
	
	//=============================================================================================
	// USER_PERMISSIONS
	//=============================================================================================	
	
	function editUserPermissions() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
        $error_msg = null;
		
		$model = $this->getModel('rulesetarchives');
		$view = $this->getView('rulesetarchives','html');
								
		if ($model->loadAccessPermissions($error_msg)) {
			$view->setModel($model, true);
			$view->setLayout('user_permissions');
			$view->displayUserPermissions();							
		} else {
			$msg = sprintf(JText::_( 'COM_TABULIZER_USER_PERMISSIONS_LOAD_FAILURE' ),$error_msg);
			TabulizerUserMessage::printError($msg);	
		}
			
	}
	
	function saveUserPermissions() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'message';
        $error_msg = null;
		
		$model = $this->getModel('rulesetarchives');
		if ($model->saveAccessPermissions($error_msg)) {
			$msg = JText::_( 'COM_TABULIZER_USER_PERMISSIONS_SAVE_SUCCESS' );
			$this->setRedirect($link, $msg, $msg_type);	
		} else {
			$msg = sprintf(JText::_( 'COM_TABULIZER_USER_PERMISSIONS_SAVE_FAILURE' ),$error_msg);
			$msg_type = 'error';
			$this->setRedirect($link, $msg, $msg_type);	
		}	
		return;		
	}	
	
	//=============================================================================================
	// SYSTEM STATUS
	//=============================================================================================		
	
	function viewStatus() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		$model = $this->getModel('rulesetarchives');
		$view = $this->getView('rulesetarchives','html');
								
		$editor_pugin_installed = TabulizerInfo::isEditorPluginInstalled();
		if ($editor_pugin_installed) {
			$model->loadStatus();							
			$view->setModel($model, true);
			$view->setLayout('status');
			$view->displayStatus();							
		} else {
			$msg = JText::_('COM_TABULIZER_EDITOR_PLUGIN_NOT_INSTALLED');			
			$this->setRedirect($link, $msg, $msg_type);	
			TabulizerUserMessage::printInfo($msg);	
		}		
	}
	
	//=============================================================================================
	// DATA SOURCES
	//=============================================================================================	
	
	function viewDataSourcesStart() {
		if (isset($_REQUEST['limitstart']))	$_REQUEST['limitstart'] = 0;
		$this->viewDataSources();
	}
	
	function viewDataSources() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
        $error_msg = null;
		
		$model = $this->getModel('datasources');
		$view = $this->getView('datasources','html');
		
		 // Get pagination request variables
	    $mainframe = JFactory::getApplication();
        // We get all data sources as we will paginate them via javascript code on the client's side
        // otherwise: use the default system limit and the given limitstart
        if (CLIENT_SIDE_PAGINATION) {
            $limit = 0;
            $limitstart = 0;
        } else {
            $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
            $limitstart = $jinput->getInt('limitstart', 0);
            // In case limit has been changed, adjust it
            if (empty($limit)) { $limit = $mainframe->getCfg('list_limit'); $limitstart = 0; }
            $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
        }
 
		$editor_pugin_installed = TabulizerInfo::isEditorPluginInstalled();
		if ($editor_pugin_installed) {
			$model->loadDataSources($limit, $limitstart, $error_msg);				
			
			$view->setModel($model, true);
			$view->setLayout('default');
			$view->display();							
		} else {
			$msg = JText::_('COM_TABULIZER_EDITOR_PLUGIN_NOT_INSTALLED');
			TabulizerUserMessage::printInfo($msg);	
		}
	}
	
	function newDataSource() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		
		$model = $this->getModel('datasources');
		$view = $this->getView('datasources','html');
		$view->setModel($model, true);
		$view->setLayout('form');				
		$view->displayNew();		
	}	
	
	function previewDataSource() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		$id = $jinput->getInt( 'ds_id', null );
		if (empty($id)) {
			$msg = JText::_('COM_TABULIZER_NO_DATA_SOURCE_IS_SPECIFIED');
			$this->setRedirect($link, $msg, $msg_type);	
		} else {
			$model = $this->getModel('datasources');
			$view = $this->getView('datasources','html');
			
			$data_source = $model->loadDataSource($id);
			if (empty($data_source)) {
				$msg = JText::_('COM_TABULIZER_SPECIFIED_DATA_SOURCE_IS_EMPTY_OR_NOT_FOUND');
				$this->setRedirect($link, $msg, $msg_type);	
			} else {			
				$view->setModel($model, true);
				$view->setLayout('preview');
				$view->displayPreview();					
			}			
		}				
	}
	function editDataSource() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		$id = $jinput->getInt( 'ds_id', null );
		if (empty($id)) {
			$msg = JText::_('COM_TABULIZER_NO_DATA_SOURCE_IS_SPECIFIED');
			$this->setRedirect($link, $msg, $msg_type);	
		} else {
			$model = $this->getModel('datasources');
			$view = $this->getView('datasources','html');
			
			$data_source = $model->loadDataSource($id);
			if (empty($data_source)) {
				$msg = JText::_('COM_TABULIZER_SPECIFIED_DATA_SOURCE_IS_EMPTY_OR_NOT_FOUND');
				$this->setRedirect($link, $msg, $msg_type);	
			} else {			
				$view->setModel($model, true);
				$view->setLayout('form');
				$view->displayEdit();					
			}			
		}				
	}
	
	function saveDataSource() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option.'&task=viewDataSources';	
		$msg_type = 'error';
        $error_msg = null;
	
		$data_source = array();	
		$data_source['id'] = $jinput->getInt('ds_id', null);
		$data_source['tag'] = $jinput->getString('ds_tag', null);
		$data_source['title'] = $jinput->getString('ds_title', null);
		$data_source['source_type'] = $jinput->getString('ds_source_type', null);
		$data_source['cache_type'] = $jinput->getInt('ds_cache_type', null);
		$data_source['cache_time'] = $jinput->getInt('ds_cache_time', null);
        $addcopy = $jinput->getInt('addcopy', 0);
        if ($addcopy) {
            $data_source['id'] = null;
            $data_source['tag'] = TabulizerString::generateRandomString(24);
            $data_source['title'] .= ' - ' . JText::_('COM_TABULIZER_COPY_OF');
        }
        $model = $this->getModel('datasources');
		$data_source['source_params'] = $model->getDataSourceRequest($data_source['source_type'], 'ds_', $error_msg);
		if (empty($data_source['source_params'])) {
			$msg = JText::_('COM_TABULIZER_INVALID_DATA_SOURCE_SAVE_PARAMS') . $error_msg;
		} else {
			if ($model->saveDataSource($data_source, $error_msg)) {
				$msg = JText::_('COM_TABULIZER_DATA_SOURCE_SAVED_SUCCESSFULLY');
				$msg_type = 'message';
                $addnew = $jinput->getInt('addnew', 0);
                if ($addnew) {
                    $link = 'index.php?option='.$option.'&task=newDataSource';
                }
			} else {
				$msg = JText::_('COM_TABULIZER_COULD_NOT_SAVE_DATA_SOURCE') . $error_msg;				
			}						
		}
						
		$this->setRedirect($link, $msg, $msg_type);				
	}
	
	function deleteDataSource() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option.'&task=viewDataSources';						
		$msg_type = 'error';
        $error_msg = null;
		$cid = $jinput->get( 'cid', array(), 'array' );
		
	    if (count( $cid )) {						
			$model = $this->getModel('datasources');
			if ($model->deleteDataSource($cid, $error_msg)) {
				$msg = JText::_('COM_TABULIZER_SELECTED_DATA_SOURCES_DELETED_SUCCESSFULLY');
				$msg_type = 'message';
			} else {
				$msg = JText::_('COM_TABULIZER_DATA_SOURCES_DELETION_FAILED') . ' ' . $error_msg;
			}			
		} else {
			$msg = JText::_('COM_TABULIZER_NO_DATA_SOURCES_SELECTED_FOR_DELETION');
		}				
		
		$this->setRedirect($link, $msg, $msg_type);						
	}
    function editDataSourcePublishingPreferences() {
        $jinput = JFactory::getApplication()->input;
        $option = $jinput->getCmd('option');
        $link = 'index.php?option='. $option.'&task=viewDataSources';
        $msg_type = 'error';
        $msg = '';
        $id = $jinput->getInt( 'ds_id', null );
        if (empty($id)) {
            $msg = JText::_('COM_TABULIZER_NO_DATA_SOURCE_IS_SPECIFIED');
            $this->setRedirect($link, $msg, $msg_type);
        } else {
            $model = $this->getModel('datasources');
            $view = $this->getView('datasources','html');
            if ($model->loadDataSource($id)) {
                $model->loadPublishingPreferences($msg);
                $view->setModel($model, true);
                $view->setLayout('publishing_preferences');
                $view->editPublishingPreferences();
            } else {
                $msg = JText::_('COM_TABULIZER_SPECIFIED_DATA_SOURCE_IS_EMPTY_OR_NOT_FOUND');
                $this->setRedirect($link, $msg, $msg_type);
            }
        }
    }
    function saveDataSourcePublishingPreferences() {
        $jinput = JFactory::getApplication()->input;
        $option = $jinput->getCmd('option');
        $link = 'index.php?option='. $option.'&task=viewDataSources';
        $msg_type = 'error';
        $msg = '';
        $tag = $jinput->getString( 'ds_tag', null );
        if (empty($tag)) {
            $msg = JText::_('COM_TABULIZER_NO_DATA_SOURCE_IS_SPECIFIED');
            $this->setRedirect($link, $msg, $msg_type);
        } else {
            $model = $this->getModel('datasources');
            if ($model->savePublishingPreferences($tag, $msg)) {
                $msg = JText::_('COM_TABULIZER_SPECIFIED_DATA_SOURCE_IS_EMPTY_OR_NOT_FOUND');
                $msg_type = 'message';
            } else {
                $this->setRedirect($link, $msg, $msg_type);
            }
        }
        $this->setRedirect($link, $msg, $msg_type);
    }
    function importDataSource() {
        $jinput = JFactory::getApplication()->input;
        $option = $jinput->getCmd('option');
        $link = 'index.php?option='. $option.'&task=viewDataSources';
        $msg_type = 'error';
        $importFileData = $jinput->getInt( 'import_file', 0);
        $displayForm = ($importFileData)?false:true;
        $model = $this->getModel('datasources');
        if ($displayForm) {
            $view = $this->getView('datasources','html');
            $view->setModel($model, true);
            $view->setLayout('import');
            $view->displayImport();
            return;
        }
        //import joomlas filesystem functions, we will do all the file writing with joomla's functions,
        //so if the ftp layer is on, joomla will write with that, not the apache user, which might
        //not have the correct permissions
        jimport('joomla.filesystem.file');
        jimport('joomla.filesystem.folder');
        //this is the name of the field in the html form, filedata is the default name for swfupload
        //so we will leave it as that
        $fieldName = 'datasource_filename';
        $file = $jinput->files->get($fieldName);
        //any errors the server registered on uploading
        $fileError = $file['error'];
        if ($fileError > 0) {
            switch ($fileError) {
                case 1:
                    $msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_LARGER_THAN_PHP_INI_ALLOWS' );
                    break;
                case 2:
                    $msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_LARGER_THAN_HTML_FORM_ALLOWS' );
                    break;
                case 3:
                    $msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_ERROR_PARTIAL' );
                    break;
                case 4:
                    $msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_ERROR_NO_FILE' );
                    break;
                default:
                    $msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_ERROR_UNKNOWN' );
                    break;
            }
            $this->setRedirect($link, $msg, $msg_type);
            return;
        }
        //check for filesize
        $fileSize = $file['size'];
        $maxAllowedFileSize = 20000000;
        if($fileSize > $maxAllowedFileSize)
        {
            $msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_LARGER_THAN_COMPONENT_ALLOWS' );
            $this->setRedirect($link, $msg, $msg_type);
            return;
        }
        //check the file extension is ok
        $fileName = $file['name'];
        $uploadedFileNameParts = explode('.',$fileName);
        $uploadedFileExtension = array_pop($uploadedFileNameParts);
        $validFileExts = array('xml');
        //assume the extension is false until we know its ok
        $extOk = false;
        //go through every ok extension, if the ok extension matches the file extension (case insensitive)
        //then the file extension is ok
        foreach($validFileExts as $key => $value)
        {
            if( preg_match("/$value/i", $uploadedFileExtension ) )
            {
                $extOk = true;
            }
        }
        if ($extOk == false)
        {
            $msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_INVALID_EXTENSION' ),implode(',',$validFileExts));
            $this->setRedirect($link, $msg, $msg_type);
            return;
        }
        //the name of the file in PHP's temp directory that we are going to move to our folder
        $fileTemp = $file['tmp_name'];
        //lose any special characters in the filename
        $fileName = preg_replace("/[^A-Za-z0-9._]/", "-", $fileName);
        //always use constants when making file paths, to avoid the possibilty of remote file inclusion
        $uploadPath = TabulizerPath::getFilePath($fileName, 'datasources');
        $overwrite = $jinput->getInt( 'overwrite_file', 0);
        if (file_exists($uploadPath)) {
            if ($overwrite) {
                unlink($uploadPath);
            } else {
                $msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_FILE_ALREADY_EXISTS' ),$fileName,$uploadPath);
                $this->setRedirect($link, $msg, $msg_type);
                return;
            }
        }
        if(!TabulizerUtils::fileUpload($fileTemp, $uploadPath))
        {
            $msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_FAILURE' ),$fileName);
            $this->setRedirect($link, $msg, $msg_type);
            return;
        }
        else
        {
            $ds_errors = array();
            $model->importDataSourceArchive($uploadPath, $ds_errors);
            if (empty($ds_errors)) {
                $msg = sprintf(JText::_('COM_TABULIZER_DATA_SOURCE_IMPORTED_SUCCESSFULLY'),$fileName);
                $msg_type = 'message';
                $this->setRedirect($link, $msg, $msg_type);
                return;
            } else {
                $msg = TabulizerUserMessage::printList(JText::_('COM_TABULIZER_DATA_SOURCE_IMPORTATION_ERROR'), $ds_errors, true);
                $this->setRedirect($link, $msg, $msg_type);
                return;
            }
        }
        // normally we should never reach this line
        $msg = JText::_('COM_TABULIZER_DATA_SOURCE_IMPORTATION_ERROR_GENERIC');
        $this->setRedirect($link, $msg, $msg_type);
    }
    function exportDataSource() {
        $jinput = JFactory::getApplication()->input;
        $option = $jinput->getCmd('option');
        $link = 'index.php?option='. $option . '&task=viewDataSources';
        $msg_type = 'error';
        $error_msg = null;
        $cid = $jinput->get( 'cid', array(), 'array' );
        if (count( $cid )) {
            $model = $this->getModel('datasources');
            if (!$model->exportDataSources($cid, $error_msg)) {
                $msg = sprintf(JText::_('COM_TABULIZER_DATA_SOURCE_EXPORT_FAILED'),$error_msg);
            }
        } else {
            $msg = JText::_('COM_TABULIZER_NO_DATA_SOURCES_SELECTED_FOR_EXPORT');
        }
        $this->setRedirect($link, $msg, $msg_type);
    }
	
	function clearDataSourceCache() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
        $link = 'index.php?option='. $option . '&task=viewDataSources';
		$msg_type = 'error';
        $error_msg = null;
        $msg = '';
        $ids = array();
        $cid = $jinput->get( 'cid', array(), 'array' );
        if (count( $cid )) {
            $ids = $cid;
        } else {
            $id = $jinput->getInt( 'ds_id', null );
            if (!empty($id)) {
                $link .= '&task=editDataSource&ds_id='.$id.'&cid[]='.$id;
                $ids = array($id);
            }
        }
		$return_url = $jinput->get('data_sources_return_url',null,'raw');
		if (!empty($return_url)) $link .= '&data_sources_return_url='.urlencode($return_url);
		
	    if (!empty($ids)) {
			$model = $this->getModel('datasources');
            foreach ($ids as $id) {
                if (!$model->clearDataSourceCache($id, $error_msg)) {
                    $msg .= JText::_('COM_TABULIZER_DATA_SOURCE_CACHE_CLEARING_FAILED') . ' ' . $error_msg . "
\n";
                }
            }
		}
        if (!isset($error_msg)) {
            $msg = JText::_('COM_TABULIZER_DATA_SOURCE_CACHE_CLEARED_SUCCESSFULLY');
            $msg_type = 'message';
        }
		
		$this->setRedirect($link, $msg, $msg_type);						
	}
    function refreshDataSources() {
        $jinput = JFactory::getApplication()->input;
        $user_preferences = TabulizerInfo::getUserPreferences($error_msg);
        $error_msg = null;
        $valid_keyphrase = (isset($user_preferences['datasources_refresh_keyphrase']))?$user_preferences['datasources_refresh_keyphrase']:null;
        $keyphrase = $jinput->getString('keyphrase',null);
        $data_source_tag = $jinput->getString('ds_tag',null);
        if (empty($valid_keyphrase)) {
            $error_msg = JText::_('COM_TABULIZER_DATA_SOURCE_REFRESH_ERROR_NO_KEYPHRASE_SET');
        } else if (empty($keyphrase)) {
            $error_msg = JText::_('COM_TABULIZER_DATA_SOURCE_REFRESH_ERROR_NO_KEYPHRASE_GIVEN');
        } else if ($keyphrase != $valid_keyphrase) {
            $error_msg = JText::_('COM_TABULIZER_DATA_SOURCE_REFRESH_ERROR_INVALID_KEYPHRASE');
        } else {
            TabulizerPath::requireLib('data_source','common');
            TabulizerDataSource::refreshDataSources($data_source_tag);
            jexit("OK");
        }
        jexit("ERROR: ".$error_msg);
    }
    function manageDataFiles() {
        $jinput = JFactory::getApplication()->input;
        $option = $jinput->getCmd('option');
        $link = 'index.php?option='. $option;
        $msg_type = 'error';
        // Get pagination request variables
        $mainframe = JFactory::getApplication();
        $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
        $limitstart = $jinput->getInt('limitstart', 0);
        // We get all data sources as we will paginate them via javascript code on the client's side
        // otherwise: use the default system limit and the given limitstart
        if (CLIENT_SIDE_PAGINATION) {
            $limit = 0;
            $limitstart = 0;
        } else {
            $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
            $limitstart = $jinput->getInt('limitstart', 0);
            // In case limit has been changed, adjust it
            if (empty($limit)) { $limit = $mainframe->getCfg('list_limit'); $limitstart = 0; }
            $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
        }
        $model = $this->getModel('datasources');
        $view = $this->getView('datasources','html');
        $model->loadDataFiles($limit,$limitstart);
        $view->setModel($model, true);
        $view->setLayout('files');
        $view->displayDataFiles();
    }
    function deleteDataFile() {
        $jinput = JFactory::getApplication()->input;
        $option = $jinput->getCmd('option');
        $link = 'index.php?option='. $option . '&task=manageDataFiles';
        $msg_type = 'error';
        $error_msg = null;
        $cid = $jinput->get( 'cid', array(), 'array' );
        if (count( $cid )) {
            $model = $this->getModel('datasources');
            if ($model->deleteDataFile($cid, $error_msg)) {
                $msg = JText::_('COM_TABULIZER_SELECTED_DATA_FILE_DELETED_SUCCESSFULLY');
                $msg_type = 'message';
            } else {
                $msg = sprintf(JText::_('COM_TABULIZER_DATA_FILE_DELETION_FAILED'),$error_msg);
            }
        } else {
            $msg = JText::_('COM_TABULIZER_NO_DATA_FILE_SELECTED_FOR_DELETION');
        }
        $this->setRedirect($link, $msg, $msg_type);
    }
    function downloadDataFile() {
        $jinput = JFactory::getApplication()->input;
        $option = $jinput->getCmd('option');
        $link = 'index.php?option='. $option . '&task=manageDataFiles';
        $msg_type = 'error';
        $error_msg = null;
        $cid = $jinput->get( 'cid', array(), 'array' );
        if (count( $cid )) {
            $model = $this->getModel('datasources');
            if (!$model->outputDataFiles($cid, $error_msg)) {
                $msg = sprintf(JText::_('COM_TABULIZER_DATA_FILE_DOWNLOAD_FAILED'),$error_msg);
            }
        } else {
            $msg = JText::_('COM_TABULIZER_NO_DATA_FILE_SELECTED_FOR_DOWNLOAD');
        }
        $this->setRedirect($link, $msg, $msg_type);
    }
    function importDataFile() {
        $jinput = JFactory::getApplication()->input;
        $option = $jinput->getCmd('option');
        $link = 'index.php?option='. $option . '&task=manageDataFiles';
        $msg_type = 'error';
        $importFileData = $jinput->getInt( 'import_file', 0);
        $displayForm = ($importFileData)?false:true;
        if ($displayForm) {
            $model = $this->getModel('datasources');
            $view = $this->getView('datasources','html');
            $view->setModel($model, true);
            $view->setLayout('files_import');
            $view->displayDataFileImport();
            return;
        }
        //import joomlas filesystem functions, we will do all the filewriting with joomlas functions,
        //so if the ftp layer is on, joomla will write with that, not the apache user, which might
        //not have the correct permissions
        jimport('joomla.filesystem.file');
        jimport('joomla.filesystem.folder');
        //this is the name of the field in the html form, filedata is the default name for swfupload
        //so we will leave it as that
        $fieldName = 'data_file';
        $file = $jinput->files->get($fieldName);
        //any errors the server registered on uploading
        $fileError = $file['error'];
        if ($fileError > 0) {
            switch ($fileError) {
                case 1:
                    $msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_LARGER_THAN_PHP_INI_ALLOWS' );
                    break;
                case 2:
                    $msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_LARGER_THAN_HTML_FORM_ALLOWS' );
                    break;
                case 3:
                    $msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_ERROR_PARTIAL' );
                    break;
                case 4:
                    $msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_ERROR_NO_FILE' );
                    break;
                default:
                    $msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_ERROR_UNKNOWN' );
                    break;
            }
            $this->setRedirect($link, $msg, $msg_type);
            return;
        }
        //check for filesize
        $fileSize = $file['size'];
        $maxAllowedFileSize = 20000000;
        if($fileSize > $maxAllowedFileSize)
        {
            $msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_LARGER_THAN_COMPONENT_ALLOWS' );
            $this->setRedirect($link, $msg, $msg_type);
            return;
        }
        //check the file extension is ok
        $fileName = $file['name'];
        $fileExt = strtolower(pathinfo($fileName,PATHINFO_EXTENSION));
        $validFileExts = explode(',',ALLOWED_FILE_TYPES_FOR_DATA_IMPORTATION);
        $validFileExts[] = 'zip';
        $extOk = TabulizerValidator::isFilename($fileName, $validFileExts );
        if ($extOk == false)
        {
            $msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_INVALID_EXTENSION' ),implode(',',$validFileExts));
            $this->setRedirect($link, $msg, $msg_type);
            return;
        }
        //the name of the file in PHP's temp directory that we are going to move to our folder
        $fileTemp = $file['tmp_name'];
        $overwrite = $jinput->getInt( 'overwrite_file', 0);
        if ($fileExt != 'zip') {
            $uploadPath = TabulizerPath::getDirPath('data');
            $uploadFilepath = TabulizerPath::getFilePath($fileName, 'data');
            if (file_exists($uploadFilepath)) {
                if ($overwrite) {
                    unlink($uploadFilepath);
                } else {
                    $msg = sprintf(JText::_( 'COM_TABULIZER_DATA_FILE_UPLOAD_FILE_ALREADY_EXISTS' ),$fileName,$uploadPath);
                    $this->setRedirect($link, $msg, $msg_type);
                    return;
                }
            }
            if(!TabulizerUtils::fileUpload($fileTemp, $uploadFilepath))
            {
                $msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_UNABLE_TO_UNZIP_FILE' ),$fileName);
                $this->setRedirect($link, $msg, $msg_type);
                return;
            }
            else
            {
                $msg = sprintf(JText::_( 'COM_TABULIZER_DATA_FILE_UPLOAD_SUCCESS'),$fileName);
                $msg_type = 'message';
                $this->setRedirect($link, $msg, $msg_type);
                return;
            }
        } else {
            //always use constants when making file paths, to avoid the possibilty of remote file inclusion
            $uploadPath = TabulizerPath::getFilePath($fileName, 'upload');
            $unzipPath = TabulizerPath::getDirPath('data');
            if (file_exists($uploadPath)) {
                if ($overwrite) {
                    unlink($uploadPath);
                } else {
                    $path_parts = pathinfo('/path/noextension');
                    $msg = sprintf(JText::_( 'COM_TABULIZER_DATA_FILE_UPLOAD_FILE_EXTRACT_ALREADY_EXISTS' ),$fileName,$path_parts['basename'],$unzipPath);
                    $this->setRedirect($link, $msg, $msg_type);
                    return;
                }
            }
            if(!TabulizerUtils::fileUpload($fileTemp, $uploadPath))
            {
                $msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_UNABLE_TO_UNZIP_FILE' ),$fileName);
                $this->setRedirect($link, $msg, $msg_type);
                return;
            }
            else
            {
                // unzip file
                if (!class_exists('ZipArchive')) {
                    $data_file_dir = TabulizerPath::getDirPath('data');
                    $msg = sprintf(JText::_( 'COM_TABULIZER_DATA_FILE_UPLOAD_ZIP_LIBRARY_MISSING'), $data_file_dir);
                    $this->setRedirect($link, $msg, $msg_type);
                    return;
                }
                $zip = new ZipArchive;
                $return_code = $zip->open($uploadPath);
                if ($return_code === TRUE) {
                    $success = true;
                    for ($i=0; $i<$zip->numFiles;$i++) {
                        $entry_info = $zip->statIndex($i);
                        $file_entry = $unzipPath . $entry_info['name'];
                        if (file_exists($file_entry) && !$overwrite) {
                            if (!is_dir($file_entry)) {
                                $msg = sprintf(JText::_( 'COM_TABULIZER_DATA_FILE_UPLOAD_FILE_EXTRACT_ALREADY_EXISTS' ),$fileName,$entry_info['name'],$unzipPath);
                                $success = false;
                                break;
                            }
                        }
                        // security check: make sure the included paths in the archive are valid
                        $included_folder_name = dirname($entry_info['name']);
                        if ($included_folder_name != '.') {
                            $msg = sprintf(JText::_( 'COM_TABULIZER_DATA_FILE_UPLOAD_NO_SUBDIRECTORIES' ),$entry_info['name']);
                            $success = false;
                            break;
                        }
                        // security check: do not allow certain file type to be included and installed on the Joomla site
                        // as part of the data archive importation process
                        $extension = substr(strrchr($entry_info['name'], "."), 1);
                        $allowed_extensions = ALLOWED_FILE_TYPES_FOR_DATA_IMPORTATION;
                        if (!empty($extension)) {
                            $extension = strtolower($extension);
                            if (!TabulizerPermissions::isAllowedImportDataExtension($extension)) {
                                $msg = sprintf(JText::_( 'COM_TABULIZER_DATA_FILE_INVALID_EXTENSION' ),$entry_info['name'],$allowed_extensions);
                                $success = false;
                            }
                        } else {
                            $msg = sprintf(JText::_( 'COM_TABULIZER_DATA_FILE_NO_EXTENSION' ),$entry_info['name'],$allowed_extensions);
                            $success = false;
                        }
                    }
                    if ($success) {
                        if ($zip->extractTo($unzipPath)) {
                            $msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_SUCCESS'),$fileName);
                            $msg_type = 'message';
                        } else {
                            $msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_UNABLE_TO_EXTRACT_FILE' ),$fileName,$unzipPath);
                        }
                    }
                    $zip->close();
                    $this->setRedirect($link, $msg, $msg_type);
                    return;
                } else {
                    $msg = sprintf(JText::_( 'COM_TABULIZER_DATA_FILE_UPLOAD_UNABLE_TO_UNZIP_FILE' ),$fileName);
                    $this->setRedirect($link, $msg, $msg_type);
                    return;
                }
            }
        }
    }
	//=============================================================================================
	// RULESET ARCHIVE
	//=============================================================================================		
	
	function viewRulesetArchive() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		$archive_filename = $jinput->getString( 'archive_filename', '' );
		
	    // Get pagination request variables
   	    $mainframe = JFactory::getApplication();
        $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
        $limitstart = $jinput->getInt('limitstart', 0);
        // We get all data sources as we will paginate them via javascript code on the client's side
        // otherwise: use the default system limit and the given limitstart
        if (CLIENT_SIDE_PAGINATION) {
            $limit = 0;
            $limitstart = 0;
        } else {
            $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
            $limitstart = $jinput->getInt('limitstart', 0);
            // In case limit has been changed, adjust it
            if (empty($limit)) { $limit = $mainframe->getCfg('list_limit'); $limitstart = 0; }
            $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
        }
		
		if (empty($archive_filename)) {
			$msg = JText::_('COM_TABULIZER_NO_RULESET_ARCHIVE_IS_SPECIFIED');
			$this->setRedirect($link, $msg, $msg_type);
		} else {
			$model = $this->getModel('rulesetarchive');
			$view = $this->getView('rulesetarchive','html');
			$ruleset_archive = $model->loadRulesetArchive($archive_filename,$limit,$limitstart);
			if (empty($ruleset_archive)) {
				$msg = JText::_('COM_TABULIZER_SPECIFIED_RULESET_ARCHIVE_IS_EMPTY_OR_NOT_FOUND');
				$this->setRedirect($link, $msg, $msg_type);					
			} else {			
				$view->setModel($model, true);
				$view->setLayout('default');
				$view->display();					
			}			
		}
						
	}	
	
	function viewRulesetArchivePreview() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		$archive_filename = $jinput->getString( 'archive_filename', '' );
		
		if (empty($archive_filename)) {
			$msg = JText::_('COM_TABULIZER_NO_RULESET_ARCHIVE_IS_SPECIFIED');
			$this->setRedirect($link, $msg, $msg_type);	
		} else {
			$model = $this->getModel('rulesetarchive');
			$view = $this->getView('rulesetarchive','html');
			$ruleset_archive = $model->loadRulesetArchive($archive_filename);
			if (empty($ruleset_archive)) {
				$msg = JText::_('COM_TABULIZER_SPECIFIED_RULESET_ARCHIVE_IS_EMPTY_OR_NOT_FOUND');
				$this->setRedirect($link, $msg, $msg_type);	
			} else {			
				$view->setModel($model, true);
				$view->setLayout('preview');
				$view->displayPreview();					
			}			
		}
						
	}		
	
	function newRulesetArchive() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		
		$model = $this->getModel('rulesetarchive');
		$view = $this->getView('rulesetarchive','html');
		$view->setModel($model, true);
		$view->setLayout('form');				
		$view->displayNew();		
	}	
	
	function editRulesetArchive() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		$ruleset_file = $jinput->getString( 'archive_filename', '' );
		if (empty($ruleset_file)) {
			$msg = JText::_('COM_TABULIZER_NO_RULESET_ARCHIVE_IS_SPECIFIED');
			$this->setRedirect($link, $msg, $msg_type);	
		} else {
			$model = $this->getModel('rulesetarchive');
			$view = $this->getView('rulesetarchive','html');
			
			$archive = $model->loadRulesetArchive($ruleset_file);
			if (empty($archive)) {
				$msg = JText::_('COM_TABULIZER_SPECIFIED_RULESET_ARCHIVE_IS_EMPTY_OR_NOT_FOUND');
				$this->setRedirect($link, $msg, $msg_type);	
			} else {			
				$view->setModel($model, true);
				$view->setLayout('form');
				$view->displayEdit();					
			}			
		}				
	}
	
	function saveRulesetArchive() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;	
		$msg_type = 'error';
		
		$ruleset_file = $jinput->getString( 'archive_filename', '' );
		
		if (empty($ruleset_file)) {
			$msg = JText::_('COM_TABULIZER_INVALID_ARGS');					
		} else {
            if (TabulizerValidator::isFilename($ruleset_file,'xml')) {
				$model = $this->getModel('rulesetarchive');
				$archive_meta = array('compatibility'=>4, 'version'=>$jinput->getString('meta_version', null),'author_name'=>$jinput->getString('meta_author_name', null),'author_email'=>$jinput->getString('meta_author_email', null),'author_url'=>$jinput->getString('meta_author_url', null), 'compatibility'=>$jinput->getString('meta_compatibility', null),'generator'=>$jinput->getString('meta_generator', null),'last_modified'=>$jinput->getString('meta_last_modified', null));
				$ruleset_archive = array('name'=>$jinput->getString('archive_name', null), 'title'=>$jinput->getString('archive_title',null), 'description'=>$jinput->getString('archive_description',null), 'style'=>$jinput->getString('archive_style',null),'meta'=>$archive_meta, 'filename'=>$ruleset_file);
				if ($model->saveRulesetArchive($ruleset_archive)) {
					$msg = JText::_('COM_TABULIZER_RULESET_ARCHIVE_SAVED_SUCCESSFULLY');
					$msg_type = 'message';
                    $return_url = str_replace('&','&',JRoute::_('index.php?option='.$option.'&task=viewrulesetarchives'));
                    $link = 'index.php?option='. $option.'&task=viewrulesetarchive&archive_filename='.urlencode($ruleset_file).'&archives_return_url='.urlencode($return_url);
				} else {
					$msg = JText::_('COM_TABULIZER_COULD_NOT_SAVE_RULESET_ARCHIVE');				
				}						
			} else {							
				$msg = JText::_('COM_TABULIZER_INVALID_RULESET_ARCHIVE_FILENAME');		
			}
		}				
						
		$this->setRedirect($link, $msg, $msg_type);				
	}
	
	function deleteRulesetArchive() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;						
		$msg_type = 'error';		
		
		$cid = $jinput->get( 'cid', array(), 'array' );
		
	    if (count( $cid )) {						
			$model = $this->getModel('rulesetarchive');
			if ($model->deleteRulesetArchive($cid)) {
				$msg = JText::_('COM_TABULIZER_SELECTED_RULESET_ARCHIVES_DELETED_SUCCESSFULLY');
				$msg_type = 'message';
			} else {
				$msg = JText::_('COM_TABULIZER_RULESET_ARCHIVES_DELETION_FAILED');
			}			
		} else {
			$msg = JText::_('COM_TABULIZER_NO_RULESET_ARCHIVES_SELECTED_FOR_DELETION');
		}
		
		$this->setRedirect($link, $msg, $msg_type);						
	}			
			
	function importRulesetArchive() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';	
								
		$importFileData = $jinput->getInt( 'import_file', 0);
		$displayForm = ($importFileData)?false:true;
		
		if ($displayForm) {
			$model = $this->getModel('rulesetarchives');
			$view = $this->getView('rulesetarchives','html');
			$view->setModel($model, true);
			$view->setLayout('import');				
			$view->displayImport();		
			return;
		}				
	
		//import joomlas filesystem functions, we will do all the filewriting with joomlas functions,
		//so if the ftp layer is on, joomla will write with that, not the apache user, which might
		//not have the correct permissions
		jimport('joomla.filesystem.file');
		jimport('joomla.filesystem.folder');
		 
		//this is the name of the field in the html form, filedata is the default name for swfupload
		//so we will leave it as that
		$fieldName = 'zip_filename';
        $file = $jinput->files->get($fieldName,null,'raw');
		 
		//any errors the server registered on uploading
		$fileError = $file['error'];
		if ($fileError > 0) {
			switch ($fileError) {
				case 1:
					$msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_LARGER_THAN_PHP_INI_ALLOWS' );
					break;		 
				case 2:
					$msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_LARGER_THAN_HTML_FORM_ALLOWS' );
					break;		 
				case 3:
					$msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_ERROR_PARTIAL' );
					break;		 
				case 4:
					$msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_ERROR_NO_FILE' );
					break;
				default:
					$msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_ERROR_UNKNOWN' );
					break;
						
			}
			$this->setRedirect($link, $msg, $msg_type);	
			return;
		}
		 
		//check for filesize		
		$fileSize = $file['size'];
		$maxAllowedFileSize = 20000000;
		if($fileSize > $maxAllowedFileSize)
		{
			$msg = JText::_( 'COM_TABULIZER_FILE_UPLOAD_LARGER_THAN_COMPONENT_ALLOWS' );
			$this->setRedirect($link, $msg, $msg_type);	
			return;
		}
		 
		//check the file extension is ok
		$fileName = $file['name'];
        //lose any special characters in the filename
        $fileName = preg_replace("/[^A-Za-z0-9._]/", "-", $fileName);
        $validFileExts = array('zip');
        $extOk = TabulizerValidator::isFilename($fileName, $validFileExts );
		 
		if ($extOk == false) 
		{
			$msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_INVALID_EXTENSION' ),implode(',',$validFileExts));
			$this->setRedirect($link, $msg, $msg_type);	
			return;
		}
		 
		//the name of the file in PHP's temp directory that we are going to move to our folder
		$fileTemp = $file['tmp_name'];
		 
		//always use constants when making file paths, to avoid the possibilty of remote file inclusion
		$uploadPath = TabulizerPath::getFilePath($fileName, 'upload');
		$unzipPath = TabulizerPath::getDirPath('archives_root');
		
		$overwrite = $jinput->getInt( 'overwrite_file', 0);
        $overwrite_safemode = $jinput->getInt( 'overwrite_safemode', 0);
		if (file_exists($uploadPath)) {			
			unlink($uploadPath);
			/*
			if ($overwrite) {
				unlink($uploadPath);
			} else {
				$msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_FILE_ALREADY_EXISTS' ),$fileName,$uploadPath);
				$this->setRedirect($link, $msg, $msg_type);	
				return;			
			}
			*/
		}			 
		if(!TabulizerUtils::fileUpload($fileTemp, $uploadPath))
		{			
			$msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_UNABLE_TO_UNZIP_FILE' ),$fileName);
			$this->setRedirect($link, $msg, $msg_type);	
			return;
		}
		else
		{			
		    // unzip file
			if (!class_exists('ZipArchive')) {
				$css_dir = TabulizerPath::getDirPath('css');
				$rules_dir = TabulizerPath::getDirPath('rules');		
				$msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_ZIP_LIBRARY_MISSING'), $css_dir, $rules_dir);							
				$this->setRedirect($link, $msg, $msg_type);	
				return;	
			}	
			
		    $zip = new ZipArchive;
            $return_code = $zip->open($uploadPath);
			if ($return_code === TRUE) {
                $data_sources = array();
				$success = true;
				for ($i=0; $i<$zip->numFiles;$i++) {
					$entry_info = $zip->statIndex($i);
					$file_entry = $unzipPath . $entry_info['name'];
					if (file_exists($file_entry) && !$overwrite) {
						if (!is_dir($file_entry)) {
							$msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_FILE_EXTRACT_ALREADY_EXISTS' ),$fileName,$entry_info['name'],$unzipPath);
							$success = false;
							break;
						}						
					}
                    // security check: make sure the included paths in the archive are valid
                    $included_folder_name = dirname($entry_info['name']);
                    if ($included_folder_name == '.') {
                        $included_folder_name = basename($entry_info['name']);
                    }
                    if (TabulizerPath::getDirPath($included_folder_name)===false) {
                        $msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_INVALID_ARCHIVE_FOLDER' ),$included_folder_name,$entry_info['name']);
                        $success = false;
                        break;
                    }
                    // security check: do not allow certain file type to be included and installed on the Joomla site
                    // as part of the ruleset archive importation process
                    $extension = substr(strrchr($entry_info['name'], "."), 1);
                    if (!empty($extension)) {
                        $extension = strtolower($extension);
                        // check if you need to import a data source
                        if (preg_match('/^datasources(.+)\.xml$/', $entry_info['name'], $matches)) {
                            $data_sources[] = $entry_info['name'];
                        }
                        // check if extension needs special permission
                        if (preg_match('#^data[\\\/](.+)$#', $entry_info['name'], $matches)) {
                            if (!TabulizerPermissions::isAllowedImportDataExtension($extension)) {
                                $allowed_data_extensions = ALLOWED_FILE_TYPES_FOR_DATA_IMPORTATION;
                                $msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_DATA_EXTENSION_NOT_ALLOWED' ),$entry_info['name'],$extension, $allowed_data_extensions);
                                $success = false;
                                break;
                            }
                        } else if (!TabulizerPermissions::isAllowedImportArchiveExtension($extension, $overwrite_safemode)) {
                            $msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_FILE_EXTENSION_NOT_ALLOWED' ),$entry_info['name'],$extension);
                            $success = false;
                            break;
                        }
                    }
				}
				if ($success) {					
					if ($zip->extractTo($unzipPath)) {
						$msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_SUCCESS'),$fileName);
						$msg_type = 'message';
                        // import data sources, if any
                        if (!empty($data_sources)) {
                            if (!TabulizerPermissions::isAllowedImportDataSources($overwrite_safemode)) {
                                $msg = JText::_('COM_TABULIZER_DATA_SOURCE_IMPORTATION_NOT_ALLOWED');
                                $msg_type = 'error';
                            } else {
                                $ds_model = $this->getModel('datasources');
                                $ds_errors = array();
                                foreach ($data_sources as $data_source) {
                                    $data_source_filename = $unzipPath . $data_source;
                                    $ds_model->importDataSourceArchive($data_source_filename, $ds_errors);
                                }
                                if (!empty($ds_errors)) {
                                    $msg = TabulizerUserMessage::printList(JText::_('COM_TABULIZER_DATA_SOURCE_IMPORTATION_ERROR'), $ds_errors, true);
                                    $msg_type = 'error';
                                }
                            }
                        }
					} else {
						$msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_UNABLE_TO_EXTRACT_FILE' ),$fileName,$unzipPath);
					}					
				}	
				$zip->close();	
				$this->setRedirect($link, $msg, $msg_type);	
				return;				
			} else {
				$msg = sprintf(JText::_( 'COM_TABULIZER_FILE_UPLOAD_UNABLE_TO_UNZIP_FILE' ),$fileName);
				$this->setRedirect($link, $msg, $msg_type);	
				return;				
			}
									   		   		   
		}
	}
    function exportRulesetArchive() {
        $jinput = JFactory::getApplication()->input;
        $option = $jinput->getCmd('option');
        $link = 'index.php?option='. $option . '&task=viewRulesetArchives';
        $msg_type = 'error';
        $error_msg = null;
        $cid = $jinput->get( 'cid', array(), 'array' );
        if (count( $cid )) {
            $model = $this->getModel('rulesetarchives');
            if (!$model->exportRulesetArchives($cid, $error_msg)) {
                $msg = sprintf(JText::_('COM_TABULIZER_RULESET_ARCHIVE_EXPORT_FAILED'),$error_msg);
            }
        } else {
            $msg = JText::_('COM_TABULIZER_NO_RULESET_ARCHIVES_SELECTED_FOR_EXPORT');
        }
        $this->setRedirect($link, $msg, $msg_type);
    }
    function editCSSFile() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		$css_filename = $jinput->getString( 'css_filename', '' );
		$archive_filename = $jinput->getString( 'archive_filename', '' );
		$ruleset_name = $jinput->getString( 'ruleset_name', '' );
		
		if (empty($css_filename)) {
			$msg = JText::_('COM_TABULIZER_INVALID_ARGS');								
			$this->setRedirect($link, $msg, $msg_type);
		} else {
            if (TabulizerValidator::isFilename($css_filename, 'css')) {
				$model = $this->getModel('rulesetarchive');
				$view = $this->getView('rulesetarchive','html');
				
				$model->loadCSSFile($css_filename, $archive_filename, $ruleset_name);
				$view->setModel($model, true);
				$view->setLayout('edit_css');
				$view->displayCSSEdit();
			} else {
				$msg = sprintf(JText::_('COM_TABULIZER_INVALID_CSS_FILENAME'),$css_filename);
				$msg_type = 'error';
				$this->setRedirect($link, $msg, $msg_type);
			}
		}					
	}
	
	function applyCSSFile() {
		$this->saveCSSFile(true);
	}
	
	function saveCSSFile($apply = false) {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		$css_filename = $jinput->getString( 'css_filename', '' );
		$css_contents = $jinput->getString( 'css_contents', '' );
		$ruleset_name = $jinput->getString( 'ruleset_name', '' );
		$archive_filename = $jinput->getString( 'archive_filename', '' );
		
		if (empty($css_filename) && empty($css_contents)) {
			$msg = JText::_('COM_TABULIZER_INVALID_ARGS');					
		} else {
            if (TabulizerValidator::isFilename($css_filename, 'css')) {
				$model = $this->getModel('rulesetarchive');
				if ($model->saveCSSFile($css_filename, $css_contents)) {
					$msg = sprintf(JText::_('COM_TABULIZER_CSS_FILE_SAVED_SUCCESSFULLY'),$css_filename);
					$msg_type = 'message';
					if ($apply) {
						$link = 'index.php?option='. $option . '&task=editCSSFile&css_filename='.$css_filename.'&archive_filename='.$archive_filename.'&ruleset_name='.$ruleset_name;						
					}
				} else {
					$msg = sprintf(JText::_('COM_TABULIZER_COULD_NOT_SAVE_CSS_FILE'),$css_filename);									
				}						
			} else {							
				$msg = sprintf(JText::_('COM_TABULIZER_INVALID_CSS_FILENAME'),$css_filename);						
			}
		}				
						
		$this->setRedirect($link, $msg, $msg_type);		
	}
			
	//=============================================================================================
	// RULESET
	//=============================================================================================		
	
	function getRulesetArgs(&$ruleset_name, &$ruleset_file) {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		$ruleset_name = $jinput->getString( 'ruleset_name', '' );
		$ruleset_file = $jinput->getString( 'archive_filename', '' );
		if (empty($ruleset_file)) {
			$msg = JText::_('COM_TABULIZER_NO_RULESET_ARCHIVE_IS_SPECIFIED');			
			$this->setRedirect($link, $msg, $msg_type);
		} else if (empty($ruleset_name)) {
			$msg = JText::_('COM_TABULIZER_NO_RULESET_NAME_IS_SPECIFIED');
			$this->setRedirect($link, $msg, $msg_type);
		} else {
			return true;
		}
		
		return false;
	}
	
	function viewRuleset() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		if ($this->getRulesetArgs($ruleset_name, $ruleset_file)) {	
			$model = $this->getModel('ruleset');
			$view = $this->getView('ruleset','html');
			$ruleset = $model->loadRuleset($ruleset_name, $ruleset_file);
			if (empty($ruleset)) {
				$msg = JText::_('COM_TABULIZER_SPECIFIED_RULESET_IS EMPTY_OR_NOT_FOUND');
			} else {			
				$view->setModel($model, true);
				$view->setLayout('default');
				$view->display();					
			}					
		} else {
			$msg = JText::_('COM_TABULIZER_INVALID_ARGS');				
		}			
								
	}	
	
	function viewRulesetPreview() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		if ($this->getRulesetArgs($ruleset_name, $ruleset_file)) {						
			$model = $this->getModel('ruleset');
			$view = $this->getView('ruleset','html');
			$ruleset = $model->loadRuleset($ruleset_name, $ruleset_file);
			if (empty($ruleset)) {
				$msg = JText::_('COM_TABULIZER_SPECIFIED_RULESET_IS_EMPTY_OR_NOT_FOUND');				
				$this->setRedirect($link, $msg, $msg_type);
			} else {														
				$view->setModel($model, true);
				$view->setLayout('preview');
				$view->displayPreview();					
			}					
		} else {
			$msg = JText::_('COM_TABULIZER_INVALID_ARGS');				
			$this->setRedirect($link, $msg, $msg_type);
		}			
		
	}
	
	function newRuleset() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		$ruleset_file = $jinput->getString( 'archive_filename', '' );
		
		if (empty($ruleset_file)) {
			$msg = JText::_('COM_TABULIZER_NO_RULESET_ARCHIVE_IS_SPECIFIED');			
			$this->setRedirect($link, $msg, $msg_type);
		} else {
			$model = $this->getModel('rulesetarchive');
			$view = $this->getView('ruleset','html');
			$archive = $model->loadRulesetArchive($ruleset_file);
			if (empty($archive)) {
				$msg = JText::_('COM_TABULIZER_SPECIFIED_RULESET_ARCHIVE_IS_EMPTY_OR_NOT_FOUND');				
				$this->setRedirect($link, $msg, $msg_type);
			} else {			
				$view->setModel($model, true);
				$view->setLayout('form');
				$view->displayNew();
			}			
		}
		
	}	
	
	function editRuleset() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		if ($this->getRulesetArgs($ruleset_name, $ruleset_file)) {						
			$model = $this->getModel('ruleset');
			$view = $this->getView('ruleset','html');
						
			$ruleset = $model->loadRuleset($ruleset_name, $ruleset_file);
			if (empty($ruleset)) {
				$msg = JText::_('COM_TABULIZER_SPECIFIED_RULESET_IS_EMPTY_OR_NOT_FOUND');				
				$this->setRedirect($link, $msg, $msg_type);
			} else {			
				$view->setModel($model, true);
				$view->setLayout('form');
				$view->displayEdit();					
			}								
		} else {
			$msg = JText::_('COM_TABULIZER_INVALID_ARGS');								
			$this->setRedirect($link, $msg, $msg_type);
		}				
	}
	
	function saveRuleset() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';			
		
		if ($this->getRulesetArgs($ruleset_name, $ruleset_file)) {
            $model = $this->getModel('ruleset');
            $link = 'index.php?option='.$option.'&task=viewrulesetarchive&archive_filename='.$ruleset_file;
			$ruleset = array('name'=> $jinput->getString('ruleset_name', null), 'title'=>$jinput->getString('ruleset_title', null), 'description'=>$jinput->getString('ruleset_description', null), 'suffix'=> $jinput->getString('ruleset_suffix', null), 'style'=> $jinput->getString('ruleset_style', null), 'preselected' => $jinput->getString('ruleset_preselected', null), 'filename' => $ruleset_file);
            $addcopy = $jinput->getInt('addcopy', 0);
            if ($addcopy) {
                TabulizerPath::requireLib('ruleset','admin');
                $ruleset_obj = new Ruleset();
                $source_name = $ruleset['name'];
                $ruleset['name'] = $ruleset_obj->getRecommendedName($ruleset['name'].'_copy_');
                $exclude_titles = array();
                $all_ruleset_titles = $ruleset_obj->getAllRulesetTitles($exclude_titles,$ruleset_file);
                if (in_array($ruleset['title'], $all_ruleset_titles)) {
                    for ($i = 1; $i < 1024; $i++) {
                        $title = $ruleset['title'] . ' - ' . sprintf(JText::_('COM_TABULIZER_COPY_OF_NUM'), $i);
                        if (!in_array($title, $all_ruleset_titles)) {
                            $ruleset['title'] = $title;
                            break;
                        }
                    }
                }
                // copy rules, if any
                if (empty($ruleset_obj->rulesets)) {
                    $ruleset_obj->loadRulesets($ruleset['filename'],0,0,$total_count);
                }
                if (isset($ruleset_obj->rulesets)) {
                    foreach ($ruleset_obj->rulesets as $archive_name => $ruleset_archive) {
                        if (!empty($ruleset['filename']) && ($ruleset_archive['filename'] != $ruleset['filename'])) continue;
                        foreach ($ruleset_archive['rulesets'] as $ruleset_entry) {
                            if ($source_name == $ruleset_entry['name']) {
                                if (isset($ruleset_entry['rules'])) $ruleset['rules'] = $ruleset_entry['rules'];
                            }
                        }
                    }
                }
                $ruleset['preselected'] = null;
            }
            $sample_date = $jinput->getInt('sample_data_check', 0);
			if (!empty($sample_date)) {
				$sample_data_caption = $jinput->getString('sample_data_caption', null);
                $sample_data_text = (isset($_REQUEST['sample_data_text']))?$_REQUEST['sample_data_text']:null; // allow HTML code
				$sample_data_sep = $jinput->getString('sample_data_sep', null);
				$sample_data_enc = $jinput->getString('sample_data_enc', null);
				if (!empty($sample_data_text) && !empty($sample_data_sep)) {					
					$ruleset['sample_data'] = 1;
					$ruleset['sample_data_caption'] = $sample_data_caption;	
					$ruleset['sample_data_text'] = $sample_data_text;
					$ruleset['sample_data_sep'] = $sample_data_sep;
					$ruleset['sample_data_enc'] = $sample_data_enc;
				}								
			}							
			if ($model->saveRuleset($ruleset, $ruleset_file)) {
				$msg = JText::_('COM_TABULIZER_RULESET_SAVED_SUCCESSFULLY');
				$msg_type = 'message';
                $return_url = str_replace('&','&',JRoute::_('index.php?option='.$option.'&task=viewrulesetarchive&archive_filename='.$ruleset_file));
                $link = 'index.php?option='.$option.'&task=viewRuleset&ruleset_name='.$ruleset['name'].'&archive_filename='.$ruleset_file.'&archive_return_url='.urlencode($return_url);
			} else {
				$msg = JText::_('COM_TABULIZER_COULD_NOT_SAVE_RULESET');				
			}			
		} else {
			$msg = JText::_('COM_TABULIZER_INVALID_ARGS');								
		}
		
		$this->setRedirect($link, $msg, $msg_type);		
	}
	
	function deleteRuleset() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';			
		
		$cid = $jinput->get( 'cid', array(), 'array' );
		
	    if (count( $cid )) {			
			$ruleset_file = $jinput->getString( 'archive_filename', '' );
			if (empty($ruleset_file)) {
				$msg = JText::_('COM_TABULIZER_NO_RULESET_ARCHIVE_IS_SPECIFIED');					
			} else {
				$model = $this->getModel('ruleset');
				if ($model->deleteRuleset($cid, $ruleset_file)) {
					$msg = JText::_('COM_TABULIZER_SELECTED_RULESETS_DELETED_SUCCESSFULLY');
					$link =  'index.php?option='.$option.'&task=viewrulesetarchive&archive_filename='.$ruleset_file;
					$msg_type = 'message';
				} else {
					$msg = JText::_('COM_TABULIZER_RULESETS_DELETION_FAILED');
				}
			}					
		} else {
			$msg = JText::_('COM_TABULIZER_NO_RULESETS_SELECTED_FOR_DELETION');
		}
		
		$this->setRedirect($link, $msg, $msg_type);						
	}	
	
	//=============================================================================================
	// RULE
	//=============================================================================================		
	
	function getRuleArgs(&$rule_id, &$ruleset_name, &$ruleset_file) {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';		
			
		$rule_id = $jinput->getString( 'rule_id', '' );
		$ruleset_name = $jinput->getString( 'ruleset_name', '' );
		$ruleset_file = $jinput->getString( 'archive_filename', '' );
		if (empty($ruleset_file)) {
			$msg = JText::_('COM_TABULIZER_NO_RULESET_ARCHIVE_IS_SPECIFIED');			
			$this->setRedirect($link, $msg, $msg_type);
		} else if (empty($ruleset_name)) {
			$msg = JText::_('COM_TABULIZER_NO_RULESET_NAME_IS_SPECIFIED');
			$this->setRedirect($link, $msg, $msg_type);
		} else if (!is_numeric($rule_id)) {
			$msg = JText::_('COM_TABULIZER_NO_RULE_ID_IS_SPECIFIED');
			$this->setRedirect($link, $msg, $msg_type);
		} else {
			return true;
		}
		
		return false;
	}
	function viewRule() {
		jexit('viewRule: Not yet implemented!');
	
	}
	
	function newRule() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';		
	
		$ruleset_name = $jinput->getString( 'ruleset_name', '' );
		$ruleset_file = $jinput->getString( 'archive_filename', '' );
		if (empty($ruleset_file)) {
			$msg = JText::_('COM_TABULIZER_NO_RULESET_ARCHIVE_IS_SPECIFIED');			
			$this->setRedirect($link, $msg, $msg_type);
		} else if (empty($ruleset_name)) {
			$msg = JText::_('COM_TABULIZER_NO_RULESET_NAME_IS_SPECIFIED');
			$this->setRedirect($link, $msg, $msg_type);
		} else {
			$model = $this->getModel('ruleset');
			$view = $this->getView('rule','html');
			$ruleset = $model->loadRuleset($ruleset_name, $ruleset_file);
			if (empty($ruleset)) {
				$msg = JText::_('COM_TABULIZER_SPECIFIED_RULESET_IS_EMPTY_OR_NOT_FOUND');
				$this->setRedirect($link, $msg, $msg_type);
			} else {			
				$view->setModel($model, true);
				$view->setLayout('form');
				$view->displayNew();					
			}			
		}						
	
	}
	
	function editRule() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		if ($this->getRuleArgs($rule_id, $ruleset_name, $ruleset_file)) {						
			$model = $this->getModel('rule');
			$view = $this->getView('rule','html');
			$rule = $model->loadRule($rule_id, $ruleset_name, $ruleset_file);
			if (empty($rule)) {
				$msg = JText::_('COM_TABULIZER_SPECIFIED_RULE_IS_EMPTY_OR_NOT_FOUND');
				$this->setRedirect($link, $msg, $msg_type);
			} else {			
				$view->setModel($model, true);
				$view->setLayout('form');
				$view->displayEdit();					
			}								
		} else {
			$msg = JText::_('COM_TABULIZER_INVALID_ARGS');				
			$this->setRedirect($link, $msg, $msg_type);
		}				
		
	}
	
	function saveRule() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
        $return_urls = null;
		if ($this->getRuleArgs($rule_id, $ruleset_name, $ruleset_file)) {
            $addnew = $jinput->getInt('addnew', 0);
            if ($addnew) {
                $model = $this->getModel('ruleset');
                if ($model->loadRuleset($ruleset_name, $ruleset_file)) {
                    $model->getReturnURLs($return_urls);
                    $link = 'index.php?option='.$option.'&task=viewruleset&task=newRule'.
                            '&ruleset_name='.urlencode($ruleset_name).
                            '&archive_filename='.urlencode($ruleset_file).'&archives_return_url='.urlencode($return_urls['archives']).
                            '&archive_return_url='.urlencode($return_urls['archive']);
                }
            } else {
			    $link = 'index.php?option='.$option.'&task=viewruleset&ruleset_name='.$ruleset_name.'&archive_filename='.$ruleset_file;
            }
			
			$rule = array('element'=> $jinput->getString('element', null),
						  'element_section'=> $jinput->get('element_section', null, 'raw'),
						  'range'=> $jinput->get('range', null, 'raw'),
						  'range_key'=> $jinput->getInt('range_key', null),
                          'priority'=> $jinput->getInt('priority', null),
 						  'style'=> $jinput->getString('style', null),
						  'autospan'=> $jinput->getString('autospan', null),
                          'th_tag'=> $jinput->getString('th_tag', null),
                          'remove'=> $jinput->getString('remove', null),
						  'format'=> $jinput->get('format_data_type', null, 'raw'),
						  'prepend'=> $jinput->get('table_prepend', '', 'raw' ),
						  'append'=> $jinput->get('table_append', '', 'raw' ),
                          'add_files' => $jinput->getString('add_files',null),
                          'calculation' => $jinput->getString('calculation',null),
                          'modification' => $jinput->getString('modification',null),
                          'split' => $jinput->getString('table_split', null),
						  'pagination' => $jinput->getString('table_pagination', null),
						  'scroll' => $jinput->getString('table_scroll', null),
						  'filter' => $jinput->getString('table_filter', null),
                          'column_filter' => $jinput->getString('table_column_filter', null),
						  'sort' => $jinput->getString('table_sort', null),
                          'theme' => $jinput->getString('table_theme', null),
						  'responsive' => $jinput->getString('table_responsive', null),
						  'graph' => $jinput->getString('table_graph', null),
						  'export_table' => $jinput->getString('table_export_table', null));
            // unset some values that do not make sense for the selected element
            $element = strtolower(trim($rule['element']));
            switch ($element) {
                case 'table':
                    $unset_keys = array('element_section','range_key','autospan');
                    break;
                case 'row':
                case 'column':
                    $unset_keys = array('prepend','append','add_files','modification','split','pagination','scroll','filter','column_filter','sort','responsive','graph','export_table');
                    break;
                case 'cell':
                    $unset_keys = array('element_section','range_key','autospan','prepend','append','add_files','calculation','modification','split','pagination','scroll','filter','column_filter','sort','responsive','graph','export_table');
                    break;
                default:
                    $unset_keys = array();
            }
            if (!empty($unset_keys)) {
                foreach ($unset_keys as $unset_key) {
                    $rule[$unset_key] = null;
                }
            }
            // attribute
            # We give the use free access to html tags, include img that would be strips form $jinput->get function
            $attribute_name = $jinput->post->get('attribute_name', '', 'raw' );
            $attribute_value = $jinput->post->get('attribute_value', '', 'raw' );
            if ((!empty($attribute_name))&&($attribute_value!='')) {
                $rule['attribute'] = $attribute_name . ATTRIBUTE_SEPARATOR . $attribute_value;
            }
									  
			// replacement
			# We give the use free access to html tags, include img that would be strips form $jinput->get function
			$replace_from = $jinput->post->get('replace_from', '', 'raw' );
			$replace_to = $jinput->post->get('replace_to', '', 'raw' );
			$replace_cs = $jinput->getInt('replace_cs', 0);
			if ((!empty($replace_from))||(!empty($replace_from))) {
				$rule['replacement'] = $replace_cs . REPLACEMENT_SEPARATOR . $replace_from . REPLACEMENT_SEPARATOR . $replace_to;
			}
			if ($rule['format']) {
				$data_type_params = $jinput->get('format_data_type_params','','raw');
				if (!empty($data_type_params)) {
					$rule['format'] = $rule['format'] . DATA_TYPE_SEPARATOR . $data_type_params;
				} else {
					unset($rule['format']);
				}				
			}											
												
			$model = $this->getModel('rule');
			if ($model->saveRule($rule, $rule_id, $ruleset_name, $ruleset_file)) {
				$msg = JText::_('COM_TABULIZER_RULE_SAVED_SUCCESSFULLY');
				$msg_type = 'message';
			} else {
				$msg = JText::_('COM_TABULIZER_COULD_NOT_SAVE_RULE');				
			}			
		} else {
			$msg = JText::_('COM_TABULIZER_INVALID_ARGS');								
		}				
		
		$this->setRedirect($link, $msg, $msg_type);
	}
	
	function deleteRule() {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;
		$msg_type = 'error';
		
		$cid	= $jinput->get( 'cid', array(), 'array' );
		JArrayHelper::toInteger($cid);
	    if (count( $cid )) {
			$ruleset_name = $jinput->getString( 'ruleset_name', '' );
			$ruleset_file = $jinput->getString( 'archive_filename', '' );
	
			if (empty($ruleset_file)) {
				$msg = JText::_('COM_TABULIZER_NO_RULESET_ARCHIVE_IS_SPECIFIED');							
			} else if (empty($ruleset_name)) {
				$msg = JText::_('COM_TABULIZER_NO_RULESET_NAME_IS_SPECIFIED');				
			} else {
				$model = $this->getModel('rule');
				if ($model->deleteRule($cid, $ruleset_name, $ruleset_file)) {
					$msg = JText::_('COM_TABULIZER_SELECTED_RULES_DELETED_SUCCESSFULLY');
					$link =  'index.php?option='.$option.'&task=viewruleset&ruleset_name='.$ruleset_name.'&archive_filename='.$ruleset_file;
					$msg_type = 'message';
				} else {
					$msg = JText::_('COM_TABULIZER_RULES_DELETION_FAILED');
				}
			}					
		} else {
			$msg = JText::_('COM_TABULIZER_NO_RULES_SELECTED_FOR_DELETION');
		}
		
		$this->setRedirect($link, $msg, $msg_type);						
	}	
	
	function isAllowed($task, &$user_msg) {
		
		$allowed = 1; // unless otherwise proven
        switch ($task) {
            case 'dsdata':
            case 'outputDataSource':
            case 'exportdata':
                $allowed = 1;
                break;
            case 'dialog':
            case 'convert':
            case 'dsselect':
            case 'extract_table_data':
            case 'extract_grid_data':
            case 'save_grid_data':
            case 'grab_table_data':
            case 'viewStatus':
            case 'editUserPreferences':
            case 'saveUserPreferences':
                $allowed = (TabulizerPermissions::isAllowed('ruleset-use'))?1:0;
                $user_msg = JText::_('COM_TABULIZER_PERMISSION_REQUIRED_FOR_RULESET_USE');
                break;
            case 'viewRulesetArchives':
            case 'viewDataSources':
            case 'viewRulesetArchive':
            case 'viewRulesetArchivePreview':
            case 'viewRuleset':
            case 'viewRulesetPreview':
            case 'viewRule':
                $allowed = (TabulizerPermissions::isAllowed('ruleset-view'))?1:0;
                $user_msg = JText::_('COM_TABULIZER_PERMISSION_REQUIRED_FOR_RULESET_VIEW');
                break;
            case 'newRulesetArchive':
            case 'editRulesetArchive':
            case 'saveRulesetArchive':
            case 'deleteRulesetArchive':
            case 'getRulesetArgs':
            case 'newRuleset':
            case 'editRuleset':
            case 'saveRuleset':
            case 'deleteRuleset':
            case 'getRuleArgs':
            case 'newRule':
            case 'editRule':
            case 'saveRule':
            case 'deleteRule':
            case 'editCSSFile':
            case 'applyCSSFile':
            case 'saveCSSFile':
                $allowed = (TabulizerPermissions::isAllowed('ruleset-edit'))?1:0;
                $user_msg = JText::_('COM_TABULIZER_PERMISSION_REQUIRED_FOR_RULESET_EDIT');
                break;
            case 'importRulesetArchive':
                $allowed = (TabulizerPermissions::isAllowed('ruleset-import'))?1:0;
                $user_msg = JText::_('COM_TABULIZER_PERMISSION_REQUIRED_FOR_RULESET_IMPORT');
                break;
            case 'exportRulesetArchive':
                $allowed = (TabulizerPermissions::isAllowed('ruleset-export'))?1:0;
                $user_msg = JText::_('COM_TABULIZER_PERMISSION_REQUIRED_FOR_RULESET_EXPORT');
                break;
            case 'previewDataSource':
            case 'viewDataSourcesStart':
                $allowed = (TabulizerPermissions::isAllowed('data-source-view'))?1:0;
                $user_msg = JText::_('COM_TABULIZER_PERMISSION_REQUIRED_FOR_DATA_SOURCE_VIEW');
                break;
            case 'newDataSource':
            case 'editDataSource':
            case 'saveDataSource':
            case 'deleteDataSource':
            case 'clearDataSourceCache':
                $allowed = (TabulizerPermissions::isAllowed('data-source-edit'))?1:0;
                $user_msg = JText::_('COM_TABULIZER_PERMISSION_REQUIRED_FOR_DATA_SOURCE_EDIT');
                break;
            case 'importDataSource':
                $allowed = (TabulizerPermissions::isAllowed('data-source-import'))?1:0;
                $user_msg = JText::_('COM_TABULIZER_PERMISSION_REQUIRED_FOR_DATA_SOURCE_IMPORT');
                break;
            case 'editDataSourcePublishingPreferences':
            case 'saveDataSourcePublishingPreferences':
            case 'exportDataSource':
                $allowed = (TabulizerPermissions::isAllowed('data-source-export'))?1:0;
                $user_msg = JText::_('COM_TABULIZER_PERMISSION_REQUIRED_FOR_DATA_SOURCE_EXPORT');
                break;
            case 'extract_excel_data':
            case 'upload_excel_file':
            case 'extract_csv_data':
            case 'upload_csv_file':
                $allowed = (TabulizerPermissions::isAllowed('data-import'))?1:0;
                $user_msg = JText::_('COM_TABULIZER_PERMISSION_REQUIRED_FOR_EXCEL_IMPORT');
                break;
            case 'manageDataFiles':
            case 'deleteDataFile':
            case 'downloadDataFile':
            case 'importDataFile':
                $allowed = (TabulizerPermissions::isAllowed('data-import'))?1:0;
                $user_msg = JText::_('COM_TABULIZER_PERMISSION_REQUIRED_FOR_DATA_FILE');
                break;
            case 'editUserPermissions':
            case 'saveUserPermissions':
                $allowed = TabulizerPermissions::isAdmin();
                $user_msg = JText::_('COM_TABULIZER_PERMISSION_REQUIRED_FOR_USER_PERMISSIONS_SAVE');
                break;
            case 'system-save':
                $allowed = TabulizerPermissions::isAdmin();
                $user_msg = JText::_('COM_TABULIZER_PERMISSION_REQUIRED_FOR_USER_SYSTEM_PREFERENCES_SAVE');
                break;
        }
        return $allowed;
	}
	
	function checkSessionTokenValidity($task) {
        $jinput = JFactory::getApplication()->input;
		$option = $jinput->getCmd('option');
		$link = 'index.php?option='. $option;		
		$msg = JText::_('COM_TABULIZER_SESSION_TOKEN_INVALID');
        $msg_type = 'error';
		$valid = false;
		switch ($task) {							
			case 'saveRulesetArchive':
			case 'saveRuleset':
			case 'saveRule':
				$valid = JSession::checkToken();
				if (!$valid) {
					$this->setRedirect($link, $msg, $msg_type);
				}
				break;
											
			case 'deleteRulesetArchive':
			case 'deleteRuleset':
			case 'deleteRule':
				// token in URL
				$valid = JSession::checkToken( 'get' );
				// token in form (hidden field)
				if (!$valid) $valid = JSession::checkToken();
				if (!$valid) {
					$this->setRedirect($link, $msg, $msg_type);
				}								
				break;				
							
			case 'importRulesetArchive':
				$importFileData = $jinput->getInt( 'import_file', 0);
				$displayForm = ($importFileData)?false:true;
				if ($displayForm) $valid = true;		
				else $valid = JSession::checkToken();
				if (!$valid) {
					$this->setRedirect($link, $msg, $msg_type);
				}			
				break;
            case 'exportDataSource':
            case 'exportRulesetArchive':
                $valid = JSession::checkToken();
                if (!$valid) {
                    $this->setRedirect($link, $msg, $msg_type);
                }
                break;
            case 'importDataFile':
            case 'deleteDataFile':
                // token in URL
                $valid = JSession::checkToken( 'get' );
                // token in form (hidden field)
                if (!$valid) $valid = JSession::checkToken();
                if (!$valid) {
                    $this->setRedirect($link, $msg, $msg_type);
                }
                break;
				
			case 'extract_table_data':
			case 'extract_excel_data':
			case 'upload_excel_file':			
				$valid = JSession::checkToken();
				if (!$valid) {
					$output = json_encode(array("error_msg" => $msg));
					jexit($output);
				}				
				break;
				
			case 'convert':
				$valid = JSession::checkToken();
				if (!$valid) {
					$html = ERROR_CODE_PREFIX;				
					$html .= ''.$msg.'';		
					jexit($msg);
				}
				break;					
				
			default:
				$valid = true;				
				break;
		}
		
		return $valid;		
	}
	
	function printWarning($msg, $use_html = true) {
		if ($use_html) {
			TabulizerUserMessage::printError($msg);
		} else {
			echo $msg;		
		}
	}
}
?>