Example #1
0
 /**
  * Parses the data to make the chart with
  */
 private function parseChartData()
 {
     $maxYAxis = 2;
     $metrics = array('visitors', 'pageviews');
     $graphData = array();
     $metricsPerDay = BackendAnalyticsModel::getMetricsPerDay($metrics, $this->startTimestamp, $this->endTimestamp);
     foreach ($metrics as $i => $metric) {
         $graphData[$i] = array();
         $graphData[$i]['title'] = $metric;
         $graphData[$i]['label'] = SpoonFilter::ucfirst(BL::lbl(SpoonFilter::toCamelCase($metric)));
         $graphData[$i]['i'] = $i + 1;
         $graphData[$i]['data'] = array();
         foreach ($metricsPerDay as $j => $data) {
             // cast SimpleXMLElement to array
             $data = (array) $data;
             // build array
             $graphData[$i]['data'][$j]['date'] = (int) $data['timestamp'];
             $graphData[$i]['data'][$j]['value'] = (string) $data[$metric];
         }
     }
     // loop the metrics
     foreach ($graphData as $metric) {
         foreach ($metric['data'] as $data) {
             // get the maximum value
             if ((int) $data['value'] > $maxYAxis) {
                 $maxYAxis = (int) $data['value'];
             }
         }
     }
     $this->tpl->assign('maxYAxis', $maxYAxis);
     $this->tpl->assign('tickInterval', $maxYAxis == 2 ? '1' : '');
     $this->tpl->assign('graphData', $graphData);
 }
 /**
  * Load the config file for the requested module.
  * In the config file we have to find disabled actions, the constructor will read the folder
  * and set possible actions. Other configurations will also be stored in it.
  */
 public function loadConfig()
 {
     // check if module path is not yet defined
     if (!defined('BACKEND_MODULE_PATH')) {
         // build path for core
         if ($this->getModule() == 'core') {
             define('BACKEND_MODULE_PATH', BACKEND_PATH . '/' . $this->getModule());
         } else {
             define('BACKEND_MODULE_PATH', BACKEND_MODULES_PATH . '/' . $this->getModule());
         }
     }
     // check if the config is present? If it isn't present there is a huge problem, so we will stop our code by throwing an error
     if (!SpoonFile::exists(BACKEND_MODULE_PATH . '/config.php')) {
         throw new BackendException('The configfile for the module (' . $this->getModule() . ') can\'t be found.');
     }
     // build config-object-name
     $configClassName = 'Backend' . SpoonFilter::toCamelCase($this->getModule() . '_config');
     // require the config file, we validated before for existence.
     require_once BACKEND_MODULE_PATH . '/config.php';
     // validate if class exists (aka has correct name)
     if (!class_exists($configClassName)) {
         throw new BackendException('The config file is present, but the classname should be: ' . $configClassName . '.');
     }
     // create config-object, the constructor will do some magic
     $this->config = new $configClassName($this->getModule());
 }
Example #3
0
 /**
  * Parses the data to make the line chart
  *
  * @param array $metricsPerDay All needed metrics grouped by day.
  */
 private function parseLineChartData($metricsPerDay)
 {
     $maxYAxis = 2;
     $metrics = array('pageviews');
     $graphData = array();
     foreach ($metrics as $i => $metric) {
         // build graph data array
         $graphData[$i] = array();
         $graphData[$i]['title'] = $metric;
         $graphData[$i]['label'] = SpoonFilter::ucfirst(BL::lbl(SpoonFilter::toCamelCase($metric)));
         $graphData[$i]['data'] = array();
         foreach ($metricsPerDay as $j => $data) {
             // cast SimpleXMLElement to array
             $data = (array) $data;
             $graphData[$i]['data'][$j]['date'] = (int) $data['timestamp'];
             $graphData[$i]['data'][$j]['value'] = (string) $data[$metric];
         }
     }
     // loop the metrics
     foreach ($graphData as $metric) {
         foreach ($metric['data'] as $data) {
             // get the maximum value
             if ((int) $data['value'] > $maxYAxis) {
                 $maxYAxis = (int) $data['value'];
             }
         }
     }
     $this->tpl->assign('maxYAxis', $maxYAxis);
     $this->tpl->assign('tickInterval', $maxYAxis == 2 ? '1' : '');
     $this->tpl->assign('lineGraphData', $graphData);
 }
Example #4
0
 /**
  * Parse the correct messages into the template
  */
 protected function parse()
 {
     parent::parse();
     // grab the error-type from the parameters
     $errorType = $this->getParameter('type');
     // set correct headers
     switch ($errorType) {
         case 'module-not-allowed':
         case 'action-not-allowed':
             SpoonHTTP::setHeadersByCode(403);
             break;
         case 'not-found':
             SpoonHTTP::setHeadersByCode(404);
             break;
     }
     // querystring provided?
     if ($this->getParameter('querystring') !== null) {
         // split into file and parameters
         $chunks = explode('?', $this->getParameter('querystring'));
         // get extension
         $extension = SpoonFile::getExtension($chunks[0]);
         // if the file has an extension it is a non-existing-file
         if ($extension != '' && $extension != $chunks[0]) {
             // set correct headers
             SpoonHTTP::setHeadersByCode(404);
             // give a nice error, so we can detect which file is missing
             echo 'Requested file (' . htmlspecialchars($this->getParameter('querystring')) . ') not found.';
             // stop script execution
             exit;
         }
     }
     // assign the correct message into the template
     $this->tpl->assign('message', BL::err(SpoonFilter::toCamelCase(htmlspecialchars($errorType), '-')));
 }
Example #5
0
 /**
  * Loads the settings form
  */
 private function loadForm()
 {
     // init settings form
     $this->frm = new BackendForm('settings');
     // get current settings
     $this->settings = BackendSearchModel::getModuleSettings();
     // add field for pagination
     $this->frm->addDropdown('overview_num_items', array_combine(range(1, 30), range(1, 30)), BackendModel::getModuleSetting($this->URL->getModule(), 'overview_num_items', 20));
     $this->frm->addDropdown('autocomplete_num_items', array_combine(range(1, 30), range(1, 30)), BackendModel::getModuleSetting($this->URL->getModule(), 'autocomplete_num_items', 20));
     $this->frm->addDropdown('autosuggest_num_items', array_combine(range(1, 30), range(1, 30)), BackendModel::getModuleSetting($this->URL->getModule(), 'autosuggest_num_items', 20));
     // modules that, no matter what, can not be searched
     $disallowedModules = array('search');
     // loop modules
     foreach (BackendModel::getModulesForDropDown() as $module => $label) {
         // check if module is searchable
         if (!in_array($module, $disallowedModules) && is_callable(array('Frontend' . SpoonFilter::toCamelCase($module) . 'Model', 'search'))) {
             // add field to decide wether or not this module is searchable
             $this->frm->addCheckbox('search_' . $module, isset($this->settings[$module]) ? $this->settings[$module]['searchable'] == 'Y' : false);
             // add field to decide weight for this module
             $this->frm->addText('search_' . $module . '_weight', isset($this->settings[$module]) ? $this->settings[$module]['weight'] : 1);
             // field disabled?
             if (!isset($this->settings[$module]) || $this->settings[$module]['searchable'] != 'Y') {
                 $this->frm->getField('search_' . $module . '_weight')->setAttribute('disabled', 'disabled');
                 $this->frm->getField('search_' . $module . '_weight')->setAttribute('class', 'inputText disabled');
             }
             // add to list of modules
             $this->modules[] = array('module' => $module, 'id' => $this->frm->getField('search_' . $module)->getAttribute('id'), 'label' => $label, 'chk' => $this->frm->getField('search_' . $module)->parse(), 'txt' => $this->frm->getField('search_' . $module . '_weight')->parse(), 'txtError' => '');
         }
     }
 }
Example #6
0
 /**
  * Parse the correct messages into the template
  */
 protected function parse()
 {
     parent::parse();
     // grab the error-type from the parameters
     $errorType = $this->getParameter('type');
     // set correct headers
     switch ($errorType) {
         case 'module-not-allowed':
         case 'action-not-allowed':
             $this->statusCode = Response::HTTP_FORBIDDEN;
             break;
         case 'not-found':
             $this->statusCode = Response::HTTP_NOT_FOUND;
             break;
         default:
             $this->statusCode = Response::HTTP_BAD_REQUEST;
             break;
     }
     // querystring provided?
     if ($this->getParameter('querystring') !== null) {
         // split into file and parameters
         $chunks = explode('?', $this->getParameter('querystring'));
         // get extension
         $extension = pathinfo($chunks[0], PATHINFO_EXTENSION);
         // if the file has an extension it is a non-existing-file
         if ($extension != '' && $extension != $chunks[0]) {
             // give a nice error, so we can detect which file is missing
             throw new ExitException('File not found', 'Requested file (' . htmlspecialchars($this->getParameter('querystring')) . ') not found.', Response::HTTP_NOT_FOUND);
         }
     }
     // assign the correct message into the template
     $this->tpl->assign('message', BL::err(\SpoonFilter::toCamelCase(htmlspecialchars($errorType), '-')));
 }
Example #7
0
    /**
     * Load the data, don't forget to validate the incoming data
     */
    private function getData()
    {
        // validate incoming parameters
        if ($this->URL->getParameter(1) === null) {
            $this->redirect(FrontendNavigation::getURL(404));
        }
        // fetch record
        $this->record = FrontendTagsModel::get($this->URL->getParameter(1));
        // validate record
        if (empty($this->record)) {
            $this->redirect(FrontendNavigation::getURL(404));
        }
        // fetch modules
        $this->modules = FrontendTagsModel::getModulesForTag($this->record['id']);
        // loop modules
        foreach ($this->modules as $module) {
            // set module class
            $class = 'Frontend' . SpoonFilter::toCamelCase($module) . 'Model';
            // get the ids of the items linked to the tag
            $otherIds = (array) FrontendModel::getDB()->getColumn('SELECT other_id
				 FROM modules_tags
				 WHERE module = ? AND tag_id = ?', array($module, $this->record['id']));
            // set module class
            $class = 'Frontend' . SpoonFilter::toCamelCase($module) . 'Model';
            // get the items that are linked to the tags
            $items = (array) FrontendTagsModel::callFromInterface($module, $class, 'getForTags', $otherIds);
            // add into results array
            if (!empty($items)) {
                $this->results[] = array('name' => $module, 'label' => FL::lbl(SpoonFilter::ucfirst($module)), 'items' => $items);
            }
        }
    }
Example #8
0
 /**
  * Load the datagrid
  */
 private function loadDataGrid()
 {
     // init var
     $items = array();
     // get modules
     $modules = BackendModel::getModules();
     // loop modules
     foreach ($modules as $module) {
         // build class name
         $className = 'Backend\\Modules\\' . $module . '\\Engine\\Model';
         if ($module == 'Core') {
             $className = 'Backend\\Core\\Engine\\Model';
         }
         // check if the getByTag-method is available
         if (is_callable(array($className, 'getByTag'))) {
             // make the call and get the item
             $moduleItems = (array) call_user_func(array($className, 'getByTag'), $this->id);
             // loop items
             foreach ($moduleItems as $row) {
                 // check if needed fields are available
                 if (isset($row['url'], $row['name'], $row['module'])) {
                     // add
                     $items[] = array('module' => \SpoonFilter::ucfirst(BL::lbl(\SpoonFilter::toCamelCase($row['module']))), 'name' => $row['name'], 'url' => $row['url']);
                 }
             }
         }
     }
     // create datagrid
     $this->dgUsage = new BackendDataGridArray($items);
     $this->dgUsage->setPaging(false);
     $this->dgUsage->setColumnsHidden(array('url'));
     $this->dgUsage->setHeaderLabels(array('name' => \SpoonFilter::ucfirst(BL::lbl('Title')), 'url' => ''));
     $this->dgUsage->setColumnURL('name', '[url]', \SpoonFilter::ucfirst(BL::lbl('Edit')));
     $this->dgUsage->addColumn('edit', null, \SpoonFilter::ucfirst(BL::lbl('Edit')), '[url]', BL::lbl('Edit'));
 }
Example #9
0
 /**
  * Loads the form.
  */
 private function loadForm()
 {
     // init var
     $modules = array();
     $checkedModules = SpoonSession::exists('modules') ? SpoonSession::get('modules') : array();
     // loop required modules
     foreach ($this->modules['required'] as $module) {
         // add to the list
         $modules[] = array('label' => SpoonFilter::toCamelCase($module), 'value' => $module, 'attributes' => array('disabled' => 'disabled'));
         // update $_POST if needed
         if (!isset($_POST['modules']) || !is_array($_POST['modules']) || !in_array($module, $_POST['modules'])) {
             $_POST['modules'][] = $module;
         }
     }
     // loop optional modules
     foreach ($this->modules['optional'] as $module) {
         // add to the list
         $modules[] = array('label' => SpoonFilter::toCamelCase($module), 'value' => $module);
     }
     // add multi checkbox
     $this->frm->addMultiCheckbox('modules', $modules, array_unique(array_merge($this->modules['required'], $checkedModules)));
     // example data
     $this->frm->addCheckbox('example_data', SpoonSession::exists('example_data') ? SpoonSession::get('example_data') : true);
     // debug mode
     $this->frm->addCheckbox('debug_mode', SpoonSession::exists('debug_mode') ? SpoonSession::get('debug_mode') : false);
     // specific debug email address
     $this->frm->addCheckbox('different_debug_email', SpoonSession::exists('different_debug_email') ? SpoonSession::get('different_debug_email') : false);
     // specific debug email address text
     $this->frm->addText('debug_email', SpoonSession::exists('debug_email') ? SpoonSession::get('debug_email') : '');
 }
Example #10
0
 /**
  * Get warnings for active modules
  *
  * @return	array
  */
 public static function getWarnings()
 {
     // init vars
     $warnings = array();
     $activeModules = BackendModel::getModules(true);
     // add warnings
     $warnings = array_merge($warnings, BackendModel::checkSettings());
     // loop active modules
     foreach ($activeModules as $module) {
         // model class
         $class = 'Backend' . SpoonFilter::toCamelCase($module) . 'Model';
         // model file exists
         if (SpoonFile::exists(BACKEND_MODULES_PATH . '/' . $module . '/engine/model.php')) {
             // require class
             require_once BACKEND_MODULES_PATH . '/' . $module . '/engine/model.php';
         }
         // method exists
         if (is_callable(array($class, 'checkSettings'))) {
             // add possible warnings
             $warnings = array_merge($warnings, call_user_func(array($class, 'checkSettings')));
         }
     }
     // return
     return (array) $warnings;
 }
Example #11
0
 /**
  * Parse into template
  *
  * @return	void
  */
 private function parse()
 {
     // init vars
     $maxYAxis = 2;
     $metrics = array('visitors', 'pageviews');
     $graphData = array();
     $startTimestamp = strtotime('-1 week -1 days', mktime(0, 0, 0));
     $endTimestamp = mktime(0, 0, 0);
     // get dashboard data
     $dashboardData = BackendAnalyticsModel::getDashboardData($metrics, $startTimestamp, $endTimestamp, true);
     // there are some metrics
     if ($dashboardData !== false) {
         // loop metrics
         foreach ($metrics as $i => $metric) {
             // build graph data array
             $graphData[$i] = array();
             $graphData[$i]['title'] = $metric;
             $graphData[$i]['label'] = ucfirst(BL::lbl(SpoonFilter::toCamelCase($metric)));
             $graphData[$i]['i'] = $i + 1;
             $graphData[$i]['data'] = array();
             // loop metrics per day
             foreach ($dashboardData as $j => $data) {
                 // cast SimpleXMLElement to array
                 $data = (array) $data;
                 // build array
                 $graphData[$i]['data'][$j]['date'] = (int) $data['timestamp'];
                 $graphData[$i]['data'][$j]['value'] = (string) $data[$metric];
             }
         }
     }
     // loop the metrics
     foreach ($graphData as $metric) {
         // loop the data
         foreach ($metric['data'] as $data) {
             // get the maximum value
             if ((int) $data['value'] > $maxYAxis) {
                 $maxYAxis = (int) $data['value'];
             }
         }
     }
     // parse
     $this->tpl->assign('analyticsRecentVisitsStartDate', $startTimestamp);
     $this->tpl->assign('analyticsRecentVisitsEndDate', $endTimestamp);
     $this->tpl->assign('analyticsMaxYAxis', $maxYAxis);
     $this->tpl->assign('analyticsMaxYAxis', $maxYAxis);
     $this->tpl->assign('analyticsTickInterval', $maxYAxis == 2 ? '1' : '');
     $this->tpl->assign('analyticsGraphData', $graphData);
 }
Example #12
0
 /**
  * Parses the html for this filefield.
  *
  * @param \SpoonTemplate $template The template to parse the element in.
  * @return string
  */
 public function parse($template = null)
 {
     // get upload_max_filesize
     $uploadMaxFilesize = ini_get('upload_max_filesize');
     if ($uploadMaxFilesize === false) {
         $uploadMaxFilesize = 0;
     }
     // reformat if defined as an integer
     if (\SpoonFilter::isInteger($uploadMaxFilesize)) {
         $uploadMaxFilesize = $uploadMaxFilesize / 1024 . 'MB';
     }
     // reformat if specified in kB
     if (strtoupper(substr($uploadMaxFilesize, -1, 1)) == 'K') {
         $uploadMaxFilesize = substr($uploadMaxFilesize, 0, -1) . 'kB';
     }
     // reformat if specified in MB
     if (strtoupper(substr($uploadMaxFilesize, -1, 1)) == 'M') {
         $uploadMaxFilesize .= 'B';
     }
     // reformat if specified in GB
     if (strtoupper(substr($uploadMaxFilesize, -1, 1)) == 'G') {
         $uploadMaxFilesize .= 'B';
     }
     // name is required
     if ($this->attributes['name'] == '') {
         throw new \SpoonFormException('A name is required for a file field. Please provide a name.');
     }
     // start html generation
     $output = '<input type="file"';
     // add attributes
     $output .= $this->getAttributesHTML(array('[id]' => $this->attributes['id'], '[name]' => $this->attributes['name'])) . ' />';
     // add help txt if needed
     if (!$this->hideHelpTxt) {
         if (isset($this->attributes['extension'])) {
             $output .= '<span class="helpTxt">' . sprintf(Language::getMessage('HelpFileFieldWithMaxFileSize', 'core'), $this->attributes['extension'], $uploadMaxFilesize) . '</span>';
         } else {
             $output .= '<span class="helpTxt">' . sprintf(Language::getMessage('HelpMaxFileSize'), $uploadMaxFilesize) . '</span>';
         }
     }
     // parse to template
     if ($template !== null) {
         $template->assign('file' . \SpoonFilter::toCamelCase($this->attributes['name']), $output);
         $template->assign('file' . \SpoonFilter::toCamelCase($this->attributes['name']) . 'Error', $this->errors != '' ? '<span class="formError">' . $this->errors . '</span>' : '');
     }
     return $output;
 }
Example #13
0
 /**
  * Validate the form.
  */
 private function validateForm()
 {
     // is the form submitted
     if ($this->frm->isSubmitted()) {
         // get fields
         $txtEmail = $this->frm->getField('email');
         $txtPassword = $this->frm->getField('password');
         $chkRemember = $this->frm->getField('remember');
         // required fields
         $txtEmail->isFilled(FL::getError('EmailIsRequired'));
         $txtPassword->isFilled(FL::getError('PasswordIsRequired'));
         // both fields filled in
         if ($txtEmail->isFilled() && $txtPassword->isFilled()) {
             // valid email?
             if ($txtEmail->isEmail(FL::getError('EmailIsInvalid'))) {
                 // get the status for the given login
                 $loginStatus = FrontendProfilesAuthentication::getLoginStatus($txtEmail->getValue(), $txtPassword->getValue());
                 // valid login?
                 if ($loginStatus !== FrontendProfilesAuthentication::LOGIN_ACTIVE) {
                     // get the error string to use
                     $errorString = sprintf(FL::getError('Profiles' . SpoonFilter::toCamelCase($loginStatus) . 'Login'), FrontendNavigation::getURLForBlock('profiles', 'resend_activation'));
                     // add the error to stack
                     $this->frm->addError($errorString);
                     // add the error to the template variables
                     $this->tpl->assign('loginError', $errorString);
                 }
             }
         }
         // valid login
         if ($this->frm->isCorrect()) {
             // get profile id
             $profileId = FrontendProfilesModel::getIdByEmail($txtEmail->getValue());
             // login
             FrontendProfilesAuthentication::login($profileId, $chkRemember->getChecked());
             // update salt and password for Dieter's security features
             FrontendProfilesAuthentication::updatePassword($profileId, $txtPassword->getValue());
             // trigger event
             FrontendModel::triggerEvent('profiles', 'after_logged_in', array('id' => $profileId));
             // querystring
             $queryString = urldecode(SpoonFilter::getGetValue('queryString', null, SITE_URL));
             // redirect
             $this->redirect($queryString);
         }
     }
 }
Example #14
0
 /**
  * @param string $name           Name of the form.
  * @param string $action         The action (URL) whereto the form will be submitted, if not provided it
  *                               will be autogenerated.
  * @param string $method         The method to use when submitting the form, default is POST.
  * @param bool   $useToken       Should we automagically add a formtoken?
  * @param bool   $useGlobalError Should we automagically show a global error?
  */
 public function __construct($name = null, $action = null, $method = 'post', $useToken = true, $useGlobalError = true)
 {
     if (BackendModel::getContainer()->has('url')) {
         $this->URL = BackendModel::getContainer()->get('url');
     }
     if (BackendModel::getContainer()->has('header')) {
         $this->header = BackendModel::getContainer()->get('header');
     }
     $this->useGlobalError = (bool) $useGlobalError;
     // build a name if there wasn't one provided
     $name = $name === null ? \SpoonFilter::toCamelCase($this->URL->getModule() . '_' . $this->URL->getAction(), '_', true) : (string) $name;
     // build the action if it wasn't provided
     $action = $action === null ? '/' . $this->URL->getQueryString() : (string) $action;
     // call the real form-class
     parent::__construct($name, $action, $method, $useToken);
     // add default classes
     $this->setParameter('id', $name);
     $this->setParameter('class', 'forkForms submitWithLink');
 }
Example #15
0
 /**
  * Set the action
  *
  * @param string $action The action to load.
  * @param string $module The module to load.
  *
  * @throws Exception If module is not set or action is not allowed
  */
 public function setAction($action, $module = null)
 {
     // set module
     if ($module !== null) {
         $this->setModule($module);
     }
     // check if module is set
     if ($this->getModule() === null) {
         throw new Exception('Module has not yet been set.');
     }
     // is this action allowed?
     if (!Authentication::isAllowedAction($action, $this->getModule())) {
         // set correct headers
         header('HTTP/1.1 403 Forbidden');
         // throw exception
         throw new Exception('Action not allowed.');
     }
     // set property
     $this->action = (string) \SpoonFilter::toCamelCase($action);
 }
Example #16
0
 /**
  * Execute the action
  * We will build the classname, require the class and call the execute method.
  */
 protected function execute()
 {
     // build action-class-name
     $actionClassName = 'Backend' . SpoonFilter::toCamelCase($this->getModule() . '_cronjob_' . $this->getAction());
     if ($this->getModule() == 'core') {
         // check if the file is present? If it isn't present there is a huge problem, so we will stop our code by throwing an error
         if (!SpoonFile::exists(BACKEND_CORE_PATH . '/cronjobs/' . $this->getAction() . '.php')) {
             // set correct headers
             SpoonHTTP::setHeadersByCode(500);
             // throw exception
             throw new BackendException('The cronjobfile for the module (' . $this->getAction() . '.php) can\'t be found.');
         }
         // require the config file, we know it is there because we validated it before (possible actions are defined by existance of the file).
         require_once BACKEND_CORE_PATH . '/cronjobs/' . $this->getAction() . '.php';
     } else {
         // check if the file is present? If it isn't present there is a huge problem, so we will stop our code by throwing an error
         if (!SpoonFile::exists(BACKEND_MODULES_PATH . '/' . $this->getModule() . '/cronjobs/' . $this->getAction() . '.php')) {
             // set correct headers
             SpoonHTTP::setHeadersByCode(500);
             // throw exception
             throw new BackendException('The cronjobfile for the module (' . $this->getAction() . '.php) can\'t be found.');
         }
         // require the config file, we know it is there because we validated it before (possible actions are defined by existance of the file).
         require_once BACKEND_MODULES_PATH . '/' . $this->getModule() . '/cronjobs/' . $this->getAction() . '.php';
     }
     // validate if class exists (aka has correct name)
     if (!class_exists($actionClassName)) {
         // set correct headers
         SpoonHTTP::setHeadersByCode(500);
         // throw exception
         throw new BackendException('The cronjobfile is present, but the classname should be: ' . $actionClassName . '.');
     }
     // create action-object
     $object = new $actionClassName();
     $object->setModule($this->getModule());
     $object->setAction($this->getAction());
     $object->execute();
 }
Example #17
0
 /**
  * @param BackendForm $form An instance of Backendform, the elements will be parsed in here.
  * @param int[optional] $metaId The metaID to load.
  * @param string[optional] $baseFieldName The field where the URL should be based on.
  * @param bool[optional] $custom Add/show custom-meta.
  */
 public function __construct(BackendForm $form, $metaId = null, $baseFieldName = 'title', $custom = false)
 {
     // check if URL is available from the referene
     if (!Spoon::exists('url')) {
         throw new BackendException('URL should be available in the reference.');
     }
     // get BackendURL instance
     $this->URL = Spoon::get('url');
     // should we use meta-custom
     $this->custom = (bool) $custom;
     // set form instance
     $this->frm = $form;
     // set base field name
     $this->baseFieldName = (string) $baseFieldName;
     // metaId was specified, so we should load the item
     if ($metaId !== null) {
         $this->loadMeta($metaId);
     }
     // set default callback
     $this->setUrlCallback('Backend' . SpoonFilter::toCamelCase($this->URL->getModule()) . 'Model', 'getURL');
     // load the form
     $this->loadForm();
 }
Example #18
0
 /**
  * Load the datagrid
  */
 private function loadDataGrid()
 {
     // init var
     $items = array();
     // get modules
     $modules = BackendModel::getModules();
     // loop modules
     foreach ($modules as $module) {
         // check if their is a model-file
         if (SpoonFile::exists(BACKEND_MODULES_PATH . '/' . $module . '/engine/model.php')) {
             // require the model-file
             require_once BACKEND_MODULES_PATH . '/' . $module . '/engine/model.php';
             // build class name
             $className = SpoonFilter::toCamelCase('backend_' . $module . '_model');
             // check if the getByTag-method is available
             if (is_callable(array($className, 'getByTag'))) {
                 // make the call and get the item
                 $moduleItems = (array) call_user_func(array($className, 'getByTag'), $this->id);
                 // loop items
                 foreach ($moduleItems as $row) {
                     // check if needed fields are available
                     if (isset($row['url'], $row['name'], $row['module'])) {
                         // add
                         $items[] = array('module' => SpoonFilter::ucfirst(BL::lbl(SpoonFilter::toCamelCase($row['module']))), 'name' => $row['name'], 'url' => $row['url']);
                     }
                 }
             }
         }
     }
     // create datagrid
     $this->dgUsage = new BackendDataGridArray($items);
     $this->dgUsage->setPaging(false);
     $this->dgUsage->setColumnsHidden(array('url'));
     $this->dgUsage->setHeaderLabels(array('name' => SpoonFilter::ucfirst(BL::lbl('Title')), 'url' => ''));
     $this->dgUsage->setColumnURL('name', '[url]', SpoonFilter::ucfirst(BL::lbl('Edit')));
     $this->dgUsage->addColumn('edit', null, SpoonFilter::ucfirst(BL::lbl('Edit')), '[url]', BL::lbl('Edit'));
 }
Example #19
0
 /**
  * Loops all backend modules, and builds a list of those that have an
  * api.php file in their engine.
  */
 protected function loadModules()
 {
     $modules = BackendModel::getModules();
     foreach ($modules as &$module) {
         /*
          * check if the api.php file exists for this module, and load it so our methods are
          * accessible by the Reflection API.
          */
         $moduleAPIFile = BACKEND_MODULES_PATH . '/' . $module . '/engine/api.php';
         if (!file_exists($moduleAPIFile)) {
             continue;
         }
         require_once $moduleAPIFile;
         // class names of the API file are always based on the name o/t module
         $className = 'Backend' . SpoonFilter::toCamelCase($module) . 'API';
         $methods = get_class_methods($className);
         // we will need the parameters + PHPDoc to generate our textfields
         foreach ($methods as $key => $method) {
             $methods[$key] = array('name' => $method, 'parameters' => $this->loadParameters($className, $method));
         }
         // properly format so an iteration can do the work for us
         $this->modules[] = array('name' => $module, 'methods' => $methods);
     }
 }
Example #20
0
 /**
  * Parse all the variables in this string.
  *
  * @return	string				The updated content, containing the parsed variables.
  * @param	string $content		The content that may contain variables.
  */
 protected function parseVariables($content)
 {
     // we want to keep parsing vars until none can be found
     while (1) {
         // regex pattern
         $pattern = '/\\{\\$([a-z0-9_]*)((\\.[a-z0-9_]*)*)(-\\>[a-z0-9_]*((\\.[a-z0-9_]*)*))?((\\|[a-z_][a-z0-9_]*(:.*?)*)*)\\}/i';
         // find matches
         if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
             // loop matches
             foreach ($matches as $match) {
                 // check if no variable has been used inside our variable (as argument for a modifier)
                 $test = substr($match[0], 1);
                 $testContent = $this->parseVariables($test);
                 // inner variable found
                 if ($test != $testContent) {
                     // variable has been parsed, so change the content to reflect this
                     $content = str_replace($match[0], substr($match[0], 0, 1) . $testContent, $content);
                     // next variable please
                     continue;
                 } else {
                     // variable doesn't already exist
                     if (array_search($match[0], $this->templateVariables, true) === false) {
                         // unique key
                         $varKey = md5($match[0]);
                         // variable within iteration
                         if (isset($match[4]) && $match[4] != '') {
                             // base
                             $variable = '${\'' . $match[1] . '\'}';
                             // add separate chunks
                             foreach (explode('.', ltrim($match[2] . str_replace('->', '.', $match[4]), '.')) as $chunk) {
                                 $variable .= "['" . $chunk . "']";
                             }
                         } else {
                             // base
                             $variable = '$this->variables';
                             // add separate chunks
                             $chunks = explode('.', $match[1] . $match[2]);
                             $previousIsObject = false;
                             for ($i = 0; $i < count($chunks); $i++) {
                                 if ($i !== 0) {
                                     if (!$previousIsObject && is_object(eval('return isset(' . $variable . ') ? ' . $variable . ' : null;'))) {
                                         $variable .= "->get" . SpoonFilter::toCamelCase($chunks[$i]) . '()';
                                         $previousIsObject = true;
                                         continue;
                                     }
                                 }
                                 $variable .= "['" . $chunks[$i] . "']";
                             }
                         }
                         // save PHP code
                         $PHP = $variable;
                         // has modifiers
                         if (isset($match[7]) && $match[7] != '') {
                             // modifier pattern
                             $pattern = '/\\|([a-z_][a-z0-9_]*)((:("[^"]*?"|\'[^\']*?\'|[^:|]*))*)/i';
                             // has match
                             if (preg_match_all($pattern, $match[7], $modifiers)) {
                                 // loop modifiers
                                 foreach ($modifiers[1] as $key => $modifier) {
                                     // modifier doesn't exist
                                     if (!isset($this->modifiers[$modifier])) {
                                         throw new SpoonTemplateException('The modifier "' . $modifier . '" does not exist.');
                                     } else {
                                         // method call
                                         if (is_array($this->modifiers[$modifier])) {
                                             $PHP = implode('::', $this->modifiers[$modifier]) . '(' . $PHP;
                                         } else {
                                             $PHP = $this->modifiers[$modifier] . '(' . $PHP;
                                         }
                                     }
                                     // has arguments
                                     if ($modifiers[2][$key] != '') {
                                         // arguments pattern (don't just explode on ':', it might be used inside a string argument)
                                         $pattern = '/:("[^"]*?"|\'[^\']*?\'|[^:|]*)/';
                                         // has arguments
                                         if (preg_match_all($pattern, $modifiers[2][$key], $arguments)) {
                                             // loop arguments
                                             foreach ($arguments[1] as $argument) {
                                                 // string argument?
                                                 if (in_array(substr($argument, 0, 1), array('\'', '"'))) {
                                                     // in compiled code: single quotes! (and escape single quotes in the content!)
                                                     $argument = '\'' . str_replace('\'', '\\\'', substr($argument, 1, -1)) . '\'';
                                                     // make sure that variables inside string arguments are correctly parsed
                                                     $argument = preg_replace('/\\[\\$.*?\\]/', '\' . \\0 .\'', $argument);
                                                 }
                                                 // add argument
                                                 $PHP .= ', ' . $argument;
                                             }
                                         }
                                     }
                                     // add close tag
                                     $PHP .= ')';
                                 }
                             }
                         }
                         /**
                          * Variables may have other variables used as parameters in modifiers
                          * so loop all currently known variables to replace them.
                          * It does not matter that we do not yet know all variables, we only
                          * need those inside this particular variable, and those will
                          * certainly already be parsed because we parse our variables outwards.
                          */
                         // temporary variable which is a list of 'variables to check before parsing'
                         $variables = array($variable);
                         // loop all known template variables
                         foreach ($this->templateVariables as $key => $value) {
                             // replace variables
                             $PHP = str_replace('[$' . $key . ']', $value['content'], $PHP);
                             // debug enabled
                             if ($this->debug) {
                                 // check if this variable is found
                                 if (strpos($match[0], '[$' . $key . ']') !== false) {
                                     // add variable name to list of 'variables to check before parsing'
                                     $variables = array_merge($variables, $value['variables']);
                                 }
                             }
                         }
                         // PHP conversion for this template variable
                         $this->templateVariables[$varKey]['content'] = $PHP;
                         // holds checks to see if this variable can be parsed (along with the variables that may be used inside it)
                         $exists = array();
                         // loop variables
                         foreach ((array) $variables as $variable) {
                             // get array containing variable
                             if (preg_match('/->get([a-zA-Z_]*)\\(\\)$/i', $variable)) {
                                 // we're working with objects
                                 $object = preg_replace('/->(get[a-zA-Z_]*)\\(\\)$/i', '', $variable);
                                 // get method name
                                 preg_match('/->(get[a-zA-Z_]*)\\(\\)$/i', $variable, $variable);
                                 $method = $variable[1];
                                 if (preg_match('/\\[\'[a-z_][a-z0-9_]*\'\\]/i', $object, $matches)) {
                                     $exists[] = 'is_object(' . $object . ')';
                                     $exists[] = 'method_exists(' . $object . ', \'' . $method . '\')';
                                 }
                                 $this->templateVariables[$varKey]['is_object'] = true;
                             } else {
                                 $array = preg_replace('/(\\[\'[a-z_][a-z0-9_]*\'\\])$/i', '', $variable);
                                 // get variable name
                                 preg_match('/\\[\'([a-z_][a-z0-9_]*)\'\\]$/i', $variable, $variable);
                                 $variable = $variable[1];
                                 // container array is index of higher array
                                 if (preg_match('/\\[\'[a-z_][a-z0-9_]*\'\\](?!->)/i', $array)) {
                                     $exists[] = 'isset(' . $array . ')';
                                 }
                                 $exists[] = 'array_key_exists(\'' . $variable . '\', (array) ' . $array . ')';
                                 // it could be an object in an iteration, add if statements for objects
                                 $existsObject = array();
                                 $existsObject[] = 'is_object(' . $array . ')';
                                 $existsObject[] = 'method_exists(' . $array . ', \'get' . SpoonFilter::toCamelCase($variable) . '\')';
                                 $this->templateVariables[$varKey]['if_object'] = implode(' && ', $existsObject);
                                 $this->templateVariables[$varKey]['content_object'] = $array . '->get' . SpoonFilter::toCamelCase($variable) . '()';
                             }
                         }
                         // save info for error fallback
                         $this->templateVariables[$varKey]['if'] = implode(' && ', $exists);
                         $this->templateVariables[$varKey]['variables'] = $variables;
                         $this->templateVariables[$varKey]['template'] = $match[0];
                     }
                     // replace in content
                     $content = str_replace($match[0], '[$' . $varKey . ']', $content);
                 }
             }
         } else {
             break;
         }
     }
     return $content;
 }
Example #21
0
 /**
  * Generates an example template, based on the elements already added.
  *
  * @return string
  */
 public function getTemplateExample()
 {
     // start form
     $value = "\n";
     $value .= '{form:' . $this->getName() . "}\n";
     /**
      * At first all the hidden fields need to be added to this form, since
      * they're not shown and are best to be put right beneath the start of the form tag.
      */
     foreach ($this->getFields() as $object) {
         // is a hidden field
         if ($object instanceof \SpoonFormHidden && $object->getName() != 'form') {
             $value .= "\t" . '{$hid' . str_replace('[]', '', \SpoonFilter::toCamelCase($object->getName())) . "}\n";
         }
     }
     /**
      * Add all the objects that are NOT hidden fields. Based on the existance of some methods
      * errors will or will not be shown.
      */
     foreach ($this->getFields() as $object) {
         // NOT a hidden field
         if (!$object instanceof \SpoonFormHidden) {
             if ($object instanceof \SpoonFormButton) {
                 $value .= "\t" . '<p>' . "\n";
                 $value .= "\t\t" . '{$btn' . \SpoonFilter::toCamelCase($object->getName()) . '}' . "\n";
                 $value .= "\t" . '</p>' . "\n\n";
             } elseif ($object instanceof \SpoonFormCheckbox) {
                 $value .= "\t" . '<p{option:chk' . \SpoonFilter::toCamelCase($object->getName()) . 'Error} class="errorArea"{/option:chk' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}>' . "\n";
                 $value .= "\t\t" . '<label for="' . $object->getAttribute('id') . '">' . \SpoonFilter::toCamelCase($object->getName()) . '</label>' . "\n";
                 $value .= "\t\t" . '{$chk' . \SpoonFilter::toCamelCase($object->getName()) . '} {$chk' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}' . "\n";
                 $value .= "\t" . '</p>' . "\n\n";
             } elseif ($object instanceof \SpoonFormMultiCheckbox) {
                 $value .= "\t" . '<div{option:chk' . \SpoonFilter::toCamelCase($object->getName()) . 'Error} class="errorArea"{/option:chk' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}>' . "\n";
                 $value .= "\t\t" . '<p class="label">' . \SpoonFilter::toCamelCase($object->getName()) . '</p>' . "\n";
                 $value .= "\t\t" . '{$chk' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}' . "\n";
                 $value .= "\t\t" . '<ul class="inputList">' . "\n";
                 $value .= "\t\t\t" . '{iteration:' . $object->getName() . '}' . "\n";
                 $value .= "\t\t\t\t" . '<li><label for="{$' . $object->getName() . '.id}">{$' . $object->getName() . '.chk' . \SpoonFilter::toCamelCase($object->getName()) . '} {$' . $object->getName() . '.label}</label></li>' . "\n";
                 $value .= "\t\t\t" . '{/iteration:' . $object->getName() . '}' . "\n";
                 $value .= "\t\t" . '</ul>' . "\n";
                 $value .= "\t" . '</div>' . "\n\n";
             } elseif ($object instanceof \SpoonFormDropdown) {
                 $value .= "\t" . '<p{option:ddm' . str_replace('[]', '', \SpoonFilter::toCamelCase($object->getName())) . 'Error} class="errorArea"{/option:ddm' . str_replace('[]', '', \SpoonFilter::toCamelCase($object->getName())) . 'Error}>' . "\n";
                 $value .= "\t\t" . '<label for="' . $object->getAttribute('id') . '">' . str_replace('[]', '', \SpoonFilter::toCamelCase($object->getName())) . '</label>' . "\n";
                 $value .= "\t\t" . '{$ddm' . str_replace('[]', '', \SpoonFilter::toCamelCase($object->getName())) . '} {$ddm' . str_replace('[]', '', \SpoonFilter::toCamelCase($object->getName())) . 'Error}' . "\n";
                 $value .= "\t" . '</p>' . "\n\n";
             } elseif ($object instanceof \SpoonFormImage) {
                 $value .= "\t" . '<p{option:file' . \SpoonFilter::toCamelCase($object->getName()) . 'Error} class="errorArea"{/option:file' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}>' . "\n";
                 $value .= "\t\t" . '<label for="' . $object->getAttribute('id') . '">' . \SpoonFilter::toCamelCase($object->getName()) . '</label>' . "\n";
                 $value .= "\t\t" . '{$file' . \SpoonFilter::toCamelCase($object->getName()) . '} <span class="helpTxt">{$msgHelpImageField}</span> {$file' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}' . "\n";
                 $value .= "\t" . '</p>' . "\n\n";
             } elseif ($object instanceof \SpoonFormFile) {
                 $value .= "\t" . '<p{option:file' . \SpoonFilter::toCamelCase($object->getName()) . 'Error} class="errorArea"{/option:file' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}>' . "\n";
                 $value .= "\t\t" . '<label for="' . $object->getAttribute('id') . '">' . \SpoonFilter::toCamelCase($object->getName()) . '</label>' . "\n";
                 $value .= "\t\t" . '{$file' . \SpoonFilter::toCamelCase($object->getName()) . '} {$file' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}' . "\n";
                 $value .= "\t" . '</p>' . "\n\n";
             } elseif ($object instanceof \SpoonFormRadiobutton) {
                 $value .= "\t" . '<div{option:rbt' . \SpoonFilter::toCamelCase($object->getName()) . 'Error} class="errorArea"{/option:rbt' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}>' . "\n";
                 $value .= "\t\t" . '<p class="label">' . \SpoonFilter::toCamelCase($object->getName()) . '</p>' . "\n";
                 $value .= "\t\t" . '{$rbt' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}' . "\n";
                 $value .= "\t\t" . '<ul class="inputList">' . "\n";
                 $value .= "\t\t\t" . '{iteration:' . $object->getName() . '}' . "\n";
                 $value .= "\t\t\t\t" . '<li><label for="{$' . $object->getName() . '.id}">{$' . $object->getName() . '.rbt' . \SpoonFilter::toCamelCase($object->getName()) . '} {$' . $object->getName() . '.label}</label></li>' . "\n";
                 $value .= "\t\t\t" . '{/iteration:' . $object->getName() . '}' . "\n";
                 $value .= "\t\t" . '</ul>' . "\n";
                 $value .= "\t" . '</div>' . "\n\n";
             } elseif ($object instanceof \SpoonFormDate) {
                 $value .= "\t" . '<p{option:txt' . \SpoonFilter::toCamelCase($object->getName()) . 'Error} class="errorArea"{/option:txt' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}>' . "\n";
                 $value .= "\t\t" . '<label for="' . $object->getAttribute('id') . '">' . \SpoonFilter::toCamelCase($object->getName()) . '</label>' . "\n";
                 $value .= "\t\t" . '{$txt' . \SpoonFilter::toCamelCase($object->getName()) . '} <span class="helpTxt">{$msgHelpDateField}</span> {$txt' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}' . "\n";
                 $value .= "\t" . '</p>' . "\n\n";
             } elseif ($object instanceof \SpoonFormTime) {
                 $value .= "\t" . '<p{option:txt' . \SpoonFilter::toCamelCase($object->getName()) . 'Error} class="errorArea"{/option:txt' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}>' . "\n";
                 $value .= "\t\t" . '<label for="' . $object->getAttribute('id') . '">' . \SpoonFilter::toCamelCase($object->getName()) . '</label>' . "\n";
                 $value .= "\t\t" . '{$txt' . \SpoonFilter::toCamelCase($object->getName()) . '} <span class="helpTxt">{$msgHelpTimeField}</span> {$txt' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}' . "\n";
                 $value .= "\t" . '</p>' . "\n\n";
             } elseif ($object instanceof \SpoonFormPassword || $object instanceof \SpoonFormTextarea || $object instanceof \SpoonFormText) {
                 $value .= "\t" . '<p{option:txt' . \SpoonFilter::toCamelCase($object->getName()) . 'Error} class="errorArea"{/option:txt' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}>' . "\n";
                 $value .= "\t\t" . '<label for="' . $object->getAttribute('id') . '">' . \SpoonFilter::toCamelCase($object->getName()) . '</label>' . "\n";
                 $value .= "\t\t" . '{$txt' . \SpoonFilter::toCamelCase($object->getName()) . '} {$txt' . \SpoonFilter::toCamelCase($object->getName()) . 'Error}' . "\n";
                 $value .= "\t" . '</p>' . "\n\n";
             }
         }
     }
     return $value . '{/form:' . $this->getName() . '}';
 }
Example #22
0
 /**
  * Get a label/action/message from locale.
  * Used as datagridfunction.
  *
  * @return	string
  * @param	string $name					Name of the locale item.
  * @param	string[optional] $type			Type of locale item.
  * @param	string[optional] $application	Name of the application.
  */
 public static function getLocale($name, $type = 'label', $application = 'backend')
 {
     // init name
     $name = SpoonFilter::toCamelCase($name);
     $class = ucfirst($application) . 'Language';
     $function = 'get' . ucfirst($type);
     // execute and return value
     return ucfirst(call_user_func_array(array($class, $function), array($name)));
 }
Example #23
0
 /**
  * Load the custom fields
  */
 private function loadCustomFields()
 {
     // no groups or subscriptions at this point
     if (empty($this->group)) {
         return false;
     }
     // reserve counter
     $i = 0;
     // if no custom fields were set, we fetch the ones from the groups ourselves
     $this->group['custom_fields'] = BackendMailmotorModel::getCustomFields($this->id);
     // no custom fields for this group
     if (empty($this->group['custom_fields'])) {
         return false;
     }
     // loop the custom fields
     foreach ($this->group['custom_fields'] as $name) {
         // set value
         $value = isset($this->record['custom_fields'][$this->id][$name]) ? $this->record['custom_fields'][$this->id][$name] : '';
         // store textfield value
         $this->customFields[$i]['label'] = $name;
         $this->customFields[$i]['name'] = \SpoonFilter::toCamelCase($name, array('-', '_', ' '));
         $this->customFields[$i]['formElements']['txtField'] = $this->frm->addText($this->customFields[$i]['name'], $value);
         $i++;
         // unset this field
         unset($this->customFields[$name]);
     }
     // add textfields to form
     $this->tpl->assign('fields', $this->customFields);
 }
Example #24
0
 /**
  * Generates an example template, based on the elements already added.
  *
  * @return	string
  */
 public function getTemplateExample()
 {
     // start form
     $value = "\n";
     $value .= '{form:' . $this->name . "}\n";
     /**
      * At first all the hidden fields need to be added to this form, since
      * they're not shown and are best to be put right beneath the start of the form tag.
      */
     foreach ($this->objects as $object) {
         // is a hidden field
         if ($object instanceof SpoonFormHidden && $object->getName() != 'form') {
             $value .= "\t" . '{$hid' . str_replace('[]', '', SpoonFilter::toCamelCase($object->getName())) . "}\n";
         }
     }
     /**
      * Add all the objects that are NOT hidden fields. Based on the existance of some methods
      * errors will or will not be shown.
      */
     foreach ($this->objects as $object) {
         // NOT a hidden field
         if (!$object instanceof SpoonFormHidden) {
             // buttons
             if ($object instanceof SpoonFormButton) {
                 $value .= "\t<p>{\$btn" . SpoonFilter::toCamelCase($object->getName()) . "}</p>\n";
             } elseif ($object instanceof SpoonFormCheckbox) {
                 $value .= "\t<p>\n";
                 $value .= "\t\t{\$chk" . SpoonFilter::toCamelCase($object->getName()) . "}\n";
                 $value .= "\t\t" . '<label for="' . $object->getAttribute('id') . '">' . SpoonFilter::toCamelCase($object->getName()) . "</label>\n";
                 $value .= "\t\t{\$chk" . SpoonFilter::toCamelCase($object->getName()) . "Error}\n";
                 $value .= "\t</p>\n";
             } elseif ($object instanceof SpoonFormMultiCheckbox) {
                 $value .= "\t<p>\n";
                 $value .= "\t\t" . SpoonFilter::toCamelCase($object->getName()) . "<br />\n";
                 $value .= "\t\t{iteration:" . $object->getName() . "}\n";
                 $value .= "\t\t\t" . '<label for="{$' . $object->getName() . '.id}">{$' . $object->getName() . '.chk' . SpoonFilter::toCamelCase($object->getName()) . '} {$' . $object->getName() . '.label}</label>' . "\n";
                 $value .= "\t\t{/iteration:" . $object->getName() . "}\n";
                 $value .= "\t\t" . '{$chk' . SpoonFilter::toCamelCase($object->getName()) . "Error}\n";
                 $value .= "\t</p>\n";
             } elseif ($object instanceof SpoonFormDropdown) {
                 $value .= "\t" . '<label for="' . $object->getAttribute('id') . '">' . str_replace('[]', '', SpoonFilter::toCamelCase($object->getName())) . "</label>\n";
                 $value .= "\t<p>\n";
                 $value .= "\t\t" . '{$ddm' . str_replace('[]', '', SpoonFilter::toCamelCase($object->getName())) . "}\n";
                 $value .= "\t\t" . '{$ddm' . str_replace('[]', '', SpoonFilter::toCamelCase($object->getName())) . "Error}\n";
                 $value .= "\t</p>\n";
             } elseif ($object instanceof SpoonFormFile) {
                 $value .= "\t" . '<label for="' . $object->getAttribute('id') . '">' . SpoonFilter::toCamelCase($object->getName()) . "</label>\n";
                 $value .= "\t<p>\n";
                 $value .= "\t\t" . '{$file' . SpoonFilter::toCamelCase($object->getName()) . "}\n";
                 $value .= "\t\t" . '{$file' . SpoonFilter::toCamelCase($object->getName()) . "Error}\n";
                 $value .= "\t</p>\n";
             } elseif ($object instanceof SpoonFormRadiobutton) {
                 $value .= "\t<p>\n";
                 $value .= "\t\t" . SpoonFilter::toCamelCase($object->getName()) . "<br />\n";
                 $value .= "\t\t{iteration:" . $object->getName() . "}\n";
                 $value .= "\t\t\t" . '<label for="{$' . $object->getName() . '.id}">{$' . $object->getName() . '.rbt' . SpoonFilter::toCamelCase($object->getName()) . '} {$' . $object->getName() . '.label}</label>' . "\n";
                 $value .= "\t\t{/iteration:" . $object->getName() . "}\n";
                 $value .= "\t\t" . '{$rbt' . SpoonFilter::toCamelCase($object->getName()) . "Error}\n";
                 $value .= "\t</p>\n";
             } elseif ($object instanceof SpoonFormDate || $object instanceof SpoonFormPassword || $object instanceof SpoonFormTextarea || $object instanceof SpoonFormText || $object instanceof SpoonFormTime) {
                 $value .= "\t" . '<label for="' . $object->getAttribute('id') . '">' . SpoonFilter::toCamelCase($object->getName()) . "</label>\n";
                 $value .= "\t<p>\n";
                 $value .= "\t\t" . '{$txt' . SpoonFilter::toCamelCase($object->getName()) . "}\n";
                 $value .= "\t\t" . '{$txt' . SpoonFilter::toCamelCase($object->getName()) . "Error}\n";
                 $value .= "\t</p>\n";
             }
         }
     }
     // close form tag
     return $value . '{/form:' . $this->name . '}';
 }
Example #25
0
 /**
  * Parses the data to make the pie-chart
  *
  * @return	void
  */
 private function parsePieChartData()
 {
     // get sources
     $sources = BackendAnalyticsModel::getTrafficSourcesGrouped($this->startTimestamp, $this->endTimestamp);
     // init vars
     $graphData = array();
     // loop metrics
     foreach ($sources as $i => $source) {
         // get label
         $label = BL::lbl(SpoonFilter::toCamelCase($source['label']), 'analytics');
         if ($label == '{$lblAnalytics' . SpoonFilter::toCamelCase($source['label']) . '}') {
             $label = $source['label'];
         }
         // build array
         $graphData[$i]['label'] = ucfirst($label);
         $graphData[$i]['value'] = (string) $source['value'];
         $graphData[$i]['percentage'] = (string) $source['percentage'];
     }
     // parse
     $this->tpl->assign('pieGraphData', $graphData);
 }
Example #26
0
 /**
  * This method exists because the service container needs to be set before
  * the page's functionality gets loaded.
  */
 public function initialize()
 {
     // because some cronjobs will be run on the command line we should pass parameters
     if (isset($_SERVER['argv'])) {
         // init var
         $first = true;
         // loop all passes arguments
         foreach ($_SERVER['argv'] as $parameter) {
             // ignore first, because this is the scripts name.
             if ($first) {
                 // reset
                 $first = false;
                 // skip
                 continue;
             }
             // split into chunks
             $chunks = explode('=', $parameter, 2);
             // valid parameters?
             if (count($chunks) == 2) {
                 // build key and value
                 $key = trim($chunks[0], '--');
                 $value = $chunks[1];
                 // set in GET
                 if ($key != '' && $value != '') {
                     $_GET[$key] = $value;
                 }
             }
         }
     }
     // define the Named Application
     if (!defined('NAMED_APPLICATION')) {
         define('NAMED_APPLICATION', 'Backend');
     }
     // set the module
     $this->setModule(\SpoonFilter::toCamelCase(\SpoonFilter::getGetValue('module', null, '')));
     // set the requested file
     $this->setAction(\SpoonFilter::toCamelCase(\SpoonFilter::getGetValue('action', null, '')));
     // set the language
     $this->setLanguage(\SpoonFilter::getGetValue('language', FrontendLanguage::getActiveLanguages(), SITE_DEFAULT_LANGUAGE));
     // mark cronjob as run
     $cronjobs = (array) $this->get('fork.settings')->get('Core', 'cronjobs');
     $cronjobs[] = $this->getModule() . '.' . $this->getAction();
     $this->get('fork.settings')->set('Core', 'cronjobs', array_unique($cronjobs));
     $this->execute();
 }
Example #27
0
 /**
  * Parse.
  */
 private function parse()
 {
     // form name
     $this->tpl->assign('formName', 'form' . $this->item['id']);
     $this->tpl->assign('formAction', $this->createAction());
     // got fields
     if (!empty($this->fieldsHTML)) {
         // value of the submit button
         $submitValue = '';
         // loop html fields
         foreach ($this->fieldsHTML as &$field) {
             // plaintext items
             if ($field['type'] == 'heading' || $field['type'] == 'paragraph') {
                 $field['plaintext'] = true;
             } elseif ($field['type'] == 'checkbox' || $field['type'] == 'radiobutton') {
                 // name (prefixed by type)
                 $name = $field['type'] == 'checkbox' ? 'chk' . SpoonFilter::toCamelCase($field['name']) : 'rbt' . SpoonFilter::toCamelCase($field['name']);
                 // rebuild so the html is stored in a general name (and not rbtName)
                 foreach ($field['html'] as &$item) {
                     $item['field'] = $item[$name];
                 }
                 // multiple items
                 $field['multiple'] = true;
             } elseif ($field['type'] == 'submit') {
                 $submitValue = $field['html'];
             } else {
                 $field['simple'] = true;
             }
             // errors (only for form elements)
             if (isset($field['simple']) || isset($field['multiple'])) {
                 $field['error'] = $this->frm->getField($field['name'])->getErrors();
             }
         }
         // assign
         $this->tpl->assign('submitValue', $submitValue);
         $this->tpl->assign('fields', $this->fieldsHTML);
         // parse form
         $this->frm->parse($this->tpl);
         // assign form error
         $this->tpl->assign('error', $this->frm->getErrors() != '' ? $this->frm->getErrors() : false);
     }
 }
 public function testToCamelCase()
 {
     $this->assertEquals('SpoonLibraryRocks', SpoonFilter::toCamelCase('Spoon library rocks', ' '));
     $this->assertEquals('SpoonLibraryRocks', SpoonFilter::toCamelCase('spoon_library_Rocks'));
     $this->assertEquals('SpoonLibraryRocks', SpoonFilter::toCamelCase('spoon_libraryRocks'));
     $this->assertEquals('blaat', SpoonFilter::toCamelCase('Blaat', '_', true));
 }
Example #29
0
 /**
  * Clean the navigation
  *
  * @param array $navigation The navigation array.
  * @return array
  */
 private function cleanup(array $navigation)
 {
     foreach ($navigation as $key => $value) {
         $allowedChildren = array();
         $allowed = true;
         if (!isset($value['url']) || !isset($value['label'])) {
             $allowed = false;
         }
         list($module, $action) = explode('/', $value['url']);
         $module = \SpoonFilter::toCamelCase($module);
         $action = \SpoonFilter::toCamelCase($action);
         if (!Authentication::isAllowedModule($module)) {
             $allowed = false;
         }
         if (!Authentication::isAllowedAction($action, $module)) {
             $allowed = false;
         }
         if (isset($value['children']) && is_array($value['children']) && !empty($value['children'])) {
             foreach ($value['children'] as $keyB => $valueB) {
                 $allowed = true;
                 $allowedChildrenB = array();
                 if (!isset($valueB['url']) || !isset($valueB['label'])) {
                     $allowed = false;
                 }
                 list($module, $action) = explode('/', $valueB['url']);
                 $module = \SpoonFilter::toCamelCase($module);
                 $action = \SpoonFilter::toCamelCase($action);
                 if (!Authentication::isAllowedModule($module)) {
                     $allowed = false;
                 }
                 if (!Authentication::isAllowedAction($action, $module)) {
                     $allowed = false;
                 }
                 // has children
                 if (isset($valueB['children']) && is_array($valueB['children']) && !empty($valueB['children'])) {
                     // loop children
                     foreach ($valueB['children'] as $keyC => $valueC) {
                         $allowed = true;
                         if (!isset($valueC['url']) || !isset($valueC['label'])) {
                             $allowed = false;
                         }
                         list($module, $action) = explode('/', $valueC['url']);
                         $module = \SpoonFilter::toCamelCase($module);
                         $action = \SpoonFilter::toCamelCase($action);
                         if (!Authentication::isAllowedModule($module)) {
                             $allowed = false;
                         }
                         if (!Authentication::isAllowedAction($action, $module)) {
                             $allowed = false;
                         }
                         if (!$allowed) {
                             unset($navigation[$key]['children'][$keyB]['children'][$keyC]);
                             continue;
                         } elseif (!in_array($navigation[$key]['children'][$keyB]['children'][$keyC], $allowedChildrenB)) {
                             // store allowed children
                             $allowedChildrenB[] = $navigation[$key]['children'][$keyB]['children'][$keyC];
                         }
                     }
                 }
                 if (!$allowed && empty($allowedChildrenB)) {
                     // error occurred and no allowed children on level B
                     unset($navigation[$key]['children'][$keyB]);
                     continue;
                 } elseif (!in_array($navigation[$key]['children'][$keyB], $allowedChildren)) {
                     // store allowed children on level B
                     $allowedChildren[] = $navigation[$key]['children'][$keyB];
                 }
                 // assign new base url for level B
                 if (!empty($allowedChildrenB)) {
                     $navigation[$key]['children'][$keyB]['url'] = $allowedChildrenB[0]['url'];
                 }
             }
         }
         // error occurred and no allowed children
         if (!$allowed && empty($allowedChildren)) {
             unset($navigation[$key]);
             continue;
         } elseif (!empty($allowedChildren)) {
             $allowed = true;
             list($module, $action) = explode('/', $allowedChildren[0]['url']);
             if (!Authentication::isAllowedModule($module)) {
                 $allowed = false;
             }
             if (!Authentication::isAllowedAction($action, $module)) {
                 $allowed = false;
             }
             if ($allowed) {
                 $navigation[$key]['url'] = $allowedChildren[0]['url'];
             } else {
                 $child = reset($navigation[$key]['children']);
                 $navigation[$key]['url'] = $child['url'];
             }
         }
     }
     return $navigation;
 }
Example #30
0
 /**
  * Parses the html for this textarea.
  *
  * @return	string
  * @param	SpoonTemplate[optional] $template	The template to parse the element in.
  */
 public function parse(SpoonTemplate $template = null)
 {
     // name is required
     if ($this->attributes['name'] == '') {
         throw new SpoonFormException('A name is requird for a textarea. Please provide a valid name.');
     }
     // start html generation
     $output = '<textarea';
     // add attributes
     $output .= $this->getAttributesHTML(array('[id]' => $this->attributes['id'], '[name]' => $this->attributes['name'], '[value]' => $this->getValue()));
     // close first tag
     $output .= '>';
     // add value
     $output .= str_replace(array('"', '<', '>'), array('&quot;', '&lt;', '&gt;'), $this->getValue());
     // end tag
     $output .= '</textarea>';
     // template
     if ($template !== null) {
         $template->assign('txt' . SpoonFilter::toCamelCase($this->attributes['name']), $output);
         $template->assign('txt' . SpoonFilter::toCamelCase($this->attributes['name']) . 'Error', $this->errors != '' ? '<span class="formError">' . $this->errors . '</span>' : '');
     }
     return $output;
 }