/** * Stores a value in a cookie, by default the cookie will expire in one day. * * @param string $key A name for the cookie. * @param mixed $value The value to be stored. Keep in mind that they will be serialized. * @param int[optional] $time The number of seconds that this cookie will be available, 30 days is the default. * @param string[optional] $path The path on the server in which the cookie will be availabe. Use / for the entire domain, /foo if you just want it to be available in /foo. * @param string[optional] $domain The domain that the cookie is available on. Use .example.com to make it available on all subdomains of example.com. * @param bool[optional] $secure Should the cookie be transmitted over a HTTPS-connection? If true, make sure you use a secure connection, otherwise the cookie won't be set. * @param bool[optional] $httpOnly Should the cookie only be available through HTTP-protocol? If true, the cookie can't be accessed by Javascript, ... * @return bool If set with succes, returns true otherwise false. */ public static function set($key, $value, $time = 2592000, $path = '/', $domain = null, $secure = null, $httpOnly = true) { // redefine $key = (string) $key; $value = serialize($value); $time = time() + (int) $time; $path = (string) $path; $httpOnly = (bool) $httpOnly; // when the domain isn't passed and the url-object is available we can set the cookies for all subdomains if ($domain === null && Spoon::exists('url')) { $domain = '.' . Spoon::get('url')->getDomain(); } // when the secure-parameter isn't set if ($secure === null) { /* detect if we are using HTTPS, this wil only work in Apache, if you are using nginx you should add the code below into your config: ssl on; fastcgi_param HTTPS on; for lighttpd you should add: setenv.add-environment = ("HTTPS" => "on") */ $secure = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on'; } // set cookie $cookie = setcookie($key, $value, $time, $path, $domain, $secure, $httpOnly); // problem occured return $cookie === false ? false : true; }
/** * Load the data */ private function loadData() { // get the current page id $pageId = Spoon::get('page')->getId(); $navigation = FrontendNavigation::getNavigation(); $pageInfo = FrontendNavigation::getPageInfo($pageId); $this->navigation = array(); if (isset($navigation['page'][$pageInfo['parent_id']])) { $pages = $navigation['page'][$pageInfo['parent_id']]; // store $pagesPrev = $pages; $pagesNext = $pages; // check for current id foreach ($pagesNext as $key => $value) { if ((int) $key != (int) $pageId) { // go to next pointer in array next($pagesNext); next($pagesPrev); } else { break; } } // get previous page $this->navigation['previous'] = prev($pagesPrev); // get next page $this->navigation['next'] = next($pagesNext); // get parent page $this->navigation['parent'] = FrontendNavigation::getPageInfo($pageInfo['parent_id']); } }
/** * Load the data */ private function loadData() { // get the current page id $pageId = Spoon::get('page')->getId(); // fetch the items $this->items = FrontendPagesModel::getSubpages($pageId); }
/** * Returns the CampaignMonitor object * * @param int[optional] $listId The default list id to use. * @return CampaignMonitor */ public static function getCM($listId = null) { // campaignmonitor reference exists if (!Spoon::exists('campaignmonitor')) { // check if the CampaignMonitor class exists if (!SpoonFile::exists(PATH_LIBRARY . '/external/campaignmonitor.php')) { // the class doesn't exist, so throw an exception throw new SpoonFileException('The CampaignMonitor wrapper class is not found. Please locate and place it in /library/external'); } // require CampaignMonitor class require_once 'external/campaignmonitor.php'; // set login data $url = FrontendModel::getModuleSetting('mailmotor', 'cm_url'); $username = FrontendModel::getModuleSetting('mailmotor', 'cm_username'); $password = FrontendModel::getModuleSetting('mailmotor', 'cm_password'); // init CampaignMonitor object $cm = new CampaignMonitor($url, $username, $password, 5, self::getClientId()); // set CampaignMonitor object reference Spoon::set('campaignmonitor', $cm); // get the default list ID $listId = !empty($listId) ? $listId : self::getDefaultListID(); // set the default list ID $cm->setListId($listId); } // return the CampaignMonitor object return Spoon::get('campaignmonitor'); }
public function __construct() { // store in reference so we can access it from everywhere Spoon::set('header', $this); // grab from the reference $this->URL = Spoon::get('url'); $this->tpl = Spoon::get('template'); }
/** * Check if all required settings have been set * * @param string $module The module. */ public function __construct($module) { parent::__construct($module); $this->loadEngineFiles(); $url = Spoon::exists('url') ? Spoon::get('url') : null; // do the client ID check if we're not in the settings page if ($url != null && !in_array($url->getAction(), array('settings', 'import_groups', 'link_account', 'load_client_info'))) { $this->checkForAccount(); $this->checkForClientID(); $this->checkForGroups(); } }
/** * You have to specify the action and module so we know what to do with this instance * * @param string $action The action to load. * @param string $module The module to load. */ public function __construct($action, $module) { // grab stuff from the reference and store them in this object (for later/easy use) $this->tpl = Spoon::get('template'); $this->setModule($module); $this->setAction($action); $this->loadConfig(); // is the requested action possible? If not we throw an exception. We don't redirect because that could trigger a redirect loop if (!in_array($this->getAction(), $this->config->getPossibleActions())) { throw new BackendException('This is an invalid action (' . $this->getAction() . ').'); } }
/** * @param string $name Name of the form. * @param string[optional] $action The action (URL) whereto the form will be submitted, if not provided it will be autogenerated. * @param string[optional] $method The method to use when submiting the form, default is POST. * @param string[optional] $hash The id of the anchor to append to the action-URL. * @param bool[optional] $useToken Should we automagically add a formtoken? */ public function __construct($name, $action = null, $method = 'post', $hash = null, $useToken = true) { $this->URL = Spoon::get('url'); $this->header = Spoon::get('header'); $name = (string) $name; $hash = $hash !== null ? (string) $hash : null; $useToken = (bool) $useToken; // 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'); }
/** * Check if all required settings have been set * * @param string $module The module. */ public function __construct($module) { parent::__construct($module); $error = false; $action = Spoon::exists('url') ? Spoon::get('url')->getAction() : null; // analytics session token if (BackendModel::getModuleSetting('analytics', 'session_token') === null) { $error = true; } // analytics table id if (BackendModel::getModuleSetting('analytics', 'table_id') === null) { $error = true; } // missing settings, so redirect to the index-page to show a message (except on the index- and settings-page) if ($error && $action != 'settings' && $action != 'index') { SpoonHTTP::redirect(BackendModel::createURLForAction('index')); } }
/** * Check if all required settings have been set * * @return void * @param string $module The module. */ public function __construct($module) { // parent construct parent::__construct($module); // load additional engine files $this->loadEngineFiles(); // get url object reference $url = Spoon::exists('url') ? Spoon::get('url') : null; // do the client ID check if we're not in the settings page if ($url != null && $url->getAction() != 'settings' && $url->getAction() != 'import_groups' && strpos($url->getQueryString(), 'link_account') === false && strpos($url->getQueryString(), 'load_client_info') === false) { // check for CM account $this->checkForAccount(); // check for client ID $this->checkForClientID(); // check for groups $this->checkForGroups(); } }
/** * @param string[optional] $name Name of the form. * @param string[optional] $action The action (URL) whereto the form will be submitted, if not provided it will be autogenerated. * @param string[optional] $method The method to use when submiting the form, default is POST. * @param bool[optional] $useToken Should we automagically add a formtoken? * @param bool[optional] $useGlobalError Should we automagically show a global error? */ public function __construct($name = null, $action = null, $method = 'post', $useToken = true, $useGlobalError = true) { if (Spoon::exists('url')) { $this->URL = Spoon::get('url'); } if (Spoon::exists('header')) { $this->header = Spoon::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'); }
public function __construct() { // store in reference so we can access it from everywhere Spoon::set('navigation', $this); // grab from the reference $this->URL = Spoon::get('url'); // check if navigation cache file exists if (!SpoonFile::exists(BACKEND_CACHE_PATH . '/navigation/navigation.php')) { $this->buildCache(); } $navigation = array(); // require navigation-file require_once BACKEND_CACHE_PATH . '/navigation/navigation.php'; // load it $this->navigation = (array) $navigation; // cleanup navigation (not needed for god user) if (!BackendAuthentication::getUser()->isGod()) { $this->navigation = $this->cleanup($this->navigation); } }
/** * Default constructor * * @return void * @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); } // load the form $this->loadForm(); }
/** * Returns the mailchimp object. * * @return mailchimp */ public static function getMC() { // mailchimp reference exists if (!\Spoon::exists('mailchimp')) { // check if the mailchimp class exists if (!\SpoonFile::exists(PATH_LIBRARY . '/external/mcapi.php')) { // the class doesn't exist, so throw an exception throw new \SpoonFileException(sprintf(FL::err('ClassDoesNotExist'), 'mailchimp')); } // require mailchimp class require_once PATH_LIBRARY . '/external/mcapi.php'; // set login data $key = FrontendModel::getModuleSetting('MailMotor', 'api_key'); if (empty($key)) { throw new \Exception('Mailmotor api_key is required.'); } // init mailchimp object $mc = new \MCAPI($key); // set mailchimp object reference \Spoon::set('mailchimp', $mc); } // return the CampaignMonitor object return \Spoon::get('mailchimp'); }
/** * @param string $module The module to use. * @param string $action The action to use. * @param string[optional] $data The data that should be available. */ public function __construct($module, $action, $data = null) { // get objects from the reference so they are accessable $this->tpl = new FrontendTemplate(false); $this->header = Spoon::get('header'); $this->URL = Spoon::get('url'); // set properties $this->setModule($module); $this->setAction($action); $this->setData($data); }
/** * Parse the general profiles info into the template. */ public static function parse() { // get the template $tpl = Spoon::get('template'); // logged in if (FrontendProfilesAuthentication::isLoggedIn()) { // get profile $profile = FrontendProfilesAuthentication::getProfile(); // display name set? if ($profile->getDisplayName() != '') { $tpl->assign('profileDisplayName', $profile->getDisplayName()); } else { $tpl->assign('profileDisplayName', $profile->getEmail()); } // show logged in $tpl->assign('isLoggedIn', true); } // ignore these url's in the querystring $ignoreUrls = array(FrontendNavigation::getURLForBlock('profiles', 'login'), FrontendNavigation::getURLForBlock('profiles', 'register'), FrontendNavigation::getURLForBlock('profiles', 'forgot_password')); // querystring $queryString = isset($_GET['queryString']) ? SITE_URL . '/' . urldecode($_GET['queryString']) : SELF; // check all ignore urls foreach ($ignoreUrls as $url) { // querystring contains a boeboe url if (stripos($queryString, $url) !== false) { $queryString = ''; break; } } // no need to add this if its empty $queryString = $queryString != '' ? '?queryString=' . urlencode($queryString) : ''; // useful urls $tpl->assign('loginUrl', FrontendNavigation::getURLForBlock('profiles', 'login') . $queryString); $tpl->assign('registerUrl', FrontendNavigation::getURLForBlock('profiles', 'register')); $tpl->assign('forgotPasswordUrl', FrontendNavigation::getURLForBlock('profiles', 'forgot_password')); }
/** * Get a message from the language-file * * @return string * @param string $key The key to get. * @param string[optional] $module The module wherin we should search. */ public static function getMessage($key, $module = null) { // do we know the module if ($module === null) { if (Spoon::exists('url')) { $module = Spoon::get('url')->getModule(); } elseif (isset($_GET['module']) && $_GET['module'] != '') { $module = (string) $_GET['module']; } else { $module = 'core'; } } // redefine $key = (string) $key; $module = (string) $module; // if the error exists return it, if (isset(self::$msg[$module][$key])) { return self::$msg[$module][$key]; } // if it exists in the core-errors if (isset(self::$msg['core'][$key])) { return self::$msg['core'][$key]; } // otherwise return the key in label-format return '{$msg' . SpoonFilter::toCamelCase($module) . $key . '}'; }
/** * Convert a var into navigation-html * syntax: {$var|getnavigation:startdepth[:maximumdepth]} * * @param string[optional] $var A placeholder var, will be replaced with the generated HTML. * @param int[optional] $startDepth The start depth of the navigation to get. * @param int[optional] $endDepth The ending depth of the navigation to get. * @return string */ public static function getNavigation($var = null, $startDepth = null, $endDepth = null) { $var = (string) $var; $startDepth = $startDepth !== null ? (int) $startDepth : 2; $endDepth = $endDepth !== null ? (int) $endDepth : null; // return navigation return Spoon::get('navigation')->getNavigation($startDepth, $endDepth); }
/** * The constructor will set some properties, it populates the parameter array with urldecoded * values for ease of use. */ public function __construct() { $this->tpl = Spoon::get('template'); $this->header = Spoon::get('header'); }
/** * Form for periodpicker * * @return void * @param BackendTemplate $tpl The template to parse the period picker in. * @param int $startTimestamp The start timestamp for the google call. * @param int $endTimestamp The end timestamp for the google call. * @param array[optional] $parameters The extra GET parameters to set on redirect. */ public static function parsePeriodPicker(BackendTemplate $tpl, $startTimestamp, $endTimestamp, $parameters = array()) { // redefine $startTimestamp = (int) $startTimestamp; $endTimestamp = (int) $endTimestamp; // assign $tpl->assign('startTimestamp', $startTimestamp); $tpl->assign('endTimestamp', $endTimestamp); // create form $frm = new BackendForm('periodPickerForm'); // create datepickers $frm->addDate('start_date', $startTimestamp, 'range', mktime(0, 0, 0, 1, 1, 2005), time(), 'noFocus'); $frm->addDate('end_date', $endTimestamp, 'range', mktime(0, 0, 0, 1, 1, 2005), time(), 'noFocus'); // submitted if ($frm->isSubmitted()) { // show the form $tpl->assign('showForm', true); // cleanup fields $frm->cleanupFields(); // shorten fields $txtStartDate = $frm->getField('start_date'); $txtEndDate = $frm->getField('end_date'); // required fields $txtStartDate->isFilled(BL::err('StartDateIsInvalid')); $txtEndDate->isFilled(BL::err('EndDateIsInvalid')); // dates within valid range if ($txtStartDate->isFilled() && $txtEndDate->isFilled()) { // valid dates if ($txtStartDate->isValid(BL::err('StartDateIsInvalid')) && $txtEndDate->isValid(BL::err('EndDateIsInvalid'))) { // get timestamps $newStartDate = BackendModel::getUTCTimestamp($txtStartDate); $newEndDate = BackendModel::getUTCTimestamp($txtEndDate); // init valid $valid = true; // startdate cannot be before 2005 (earliest valid google startdate) if ($newStartDate < mktime(0, 0, 0, 1, 1, 2005)) { $valid = false; } elseif ($newEndDate > time()) { $valid = false; } elseif ($newStartDate > $newEndDate) { $valid = false; } // invalid range if (!$valid) { $txtStartDate->setError(BL::err('DateRangeIsInvalid')); } } } // valid if ($frm->isCorrect()) { // parameters $parameters['start_timestamp'] = $newStartDate; $parameters['end_timestamp'] = $newEndDate; // build redirect string $redirect = html_entity_decode(BackendModel::createURLForAction(null, null, null, $parameters)); // redirect SpoonHTTP::redirect($redirect); } } // parse $frm->parse($tpl); // we only allow live data fetching when the end date is today, no point in fetching and older range because it will never change if ($endTimestamp == mktime(0, 0, 0, date('n'), date('j'), date('Y'))) { // url of current action $liveDataUrl = BackendModel::createURLForAction('loading') . '&redirect_action=' . Spoon::get('url')->getAction(); // page id set if (isset($_GET['page_id']) && $_GET['page_id'] != '') { $liveDataUrl .= '&page_id=' . (int) $_GET['page_id']; } // page path set if (isset($_GET['page_path']) && $_GET['page_path'] != '') { $liveDataUrl .= '&page_path=' . (string) $_GET['page_path']; } // assign $tpl->assign('liveDataURL', $liveDataUrl); } }
/** * Default constructor * The constructor will set some properties. It populates the parameter array with urldecoded values for easy-use. * * @return void */ public function __construct() { // get objects from the reference so they are accessable from the action-object $this->tpl = Spoon::get('template'); $this->header = Spoon::get('header'); }
/** * @expectedException SpoonException */ public function testGetFailure() { $this->assertEquals('I have no idea what I am doing.', Spoon::get('my_custom_value')); }
/** * Get the traffic sources grouped by medium * * @return array * @param int $startTimestamp The start timestamp for the cache file. * @param int $endTimestamp The end timestamp for the cache file. */ public static function getTrafficSourcesGrouped($startTimestamp, $endTimestamp) { // get data from cache $items = self::getDataFromCacheByType('traffic_sources', $startTimestamp, $endTimestamp); // get current action $action = Spoon::get('url')->getAction(); // nothing in cache if ($items === false) { self::redirectToLoadingPage($action); } // reset loop counter for the current action if we got data from cache SpoonSession::set($action . 'Loop', null); // return items return $items; }
/** * Import a locale XML file. * * @param SimpleXMLElement $xml The locale XML. * @param bool[optional] $overwriteConflicts Should we overwrite when there is a conflict? * @param array[optional] $frontendLanguages The frontend languages to install locale for. * @param array[optional] $backendLanguages The backend languages to install locale for. * @param int[optional] $userId Id of the user these translations should be inserted for. * @param int[optional] $date The date the translation has been inserted. * @return array The import statistics */ public static function importXML(SimpleXMLElement $xml, $overwriteConflicts = false, $frontendLanguages = null, $backendLanguages = null, $userId = null, $date = null) { $overwriteConflicts = (bool) $overwriteConflicts; $statistics = array('total' => 0, 'imported' => 0); // set defaults if necessary // we can't simply use these right away, because this function is also calles by the installer, which does not have Backend-functions if ($frontendLanguages === null) { $frontendLanguages = array_keys(BL::getWorkingLanguages()); } if ($backendLanguages === null) { $backendLanguages = array_keys(BL::getInterfaceLanguages()); } if ($userId === null) { $userId = BackendAuthentication::getUser()->getUserId(); } if ($date === null) { $date = BackendModel::getUTCDate(); } // get database instance (don't use BackendModel::getDB() here because this function will also be called during install) $db = Spoon::get('database'); // possible values $possibleApplications = array('frontend', 'backend'); $possibleModules = (array) $db->getColumn('SELECT m.name FROM modules AS m'); // types $typesShort = (array) $db->getEnumValues('locale', 'type'); foreach ($typesShort as $type) { $possibleTypes[$type] = self::getTypeName($type); } // install English translations anyhow, they're fallback $possibleLanguages = array('frontend' => array_unique(array_merge(array('en'), $frontendLanguages)), 'backend' => array_unique(array_merge(array('en'), $backendLanguages))); // current locale items (used to check for conflicts) $currentLocale = (array) $db->getColumn('SELECT CONCAT(application, module, type, language, name) FROM locale'); // applications foreach ($xml as $application => $modules) { // application does not exist if (!in_array($application, $possibleApplications)) { continue; } // modules foreach ($modules as $module => $items) { // module does not exist if (!in_array($module, $possibleModules)) { continue; } // items foreach ($items as $item) { // attributes $attributes = $item->attributes(); $type = SpoonFilter::getValue($attributes['type'], $possibleTypes, ''); $name = SpoonFilter::getValue($attributes['name'], null, ''); // missing attributes if ($type == '' || $name == '') { continue; } // real type (shortened) $type = array_search($type, $possibleTypes); // translations foreach ($item->translation as $translation) { // statistics $statistics['total']++; // attributes $attributes = $translation->attributes(); $language = SpoonFilter::getValue($attributes['language'], $possibleLanguages[$application], ''); // language does not exist if ($language == '') { continue; } // the actual translation $translation = (string) $translation; // locale item $locale['user_id'] = $userId; $locale['language'] = $language; $locale['application'] = $application; $locale['module'] = $module; $locale['type'] = $type; $locale['name'] = $name; $locale['value'] = $translation; $locale['edited_on'] = $date; // found a conflict, overwrite it with the imported translation if ($overwriteConflicts && in_array($application . $module . $type . $language . $name, $currentLocale)) { // statistics $statistics['imported']++; // overwrite $db->update('locale', $locale, 'application = ? AND module = ? AND type = ? AND language = ? AND name = ?', array($application, $module, $type, $language, $name)); } elseif (!in_array($application . $module . $type . $language . $name, $currentLocale)) { // statistics $statistics['imported']++; // insert $db->insert('locale', $locale); } } } } } // rebuild cache foreach ($possibleApplications as $application) { foreach ($possibleLanguages[$application] as $language) { self::buildCache($language, $application); } } return $statistics; }
/** * Get tags for current "page" */ private function getTags() { // get page id $pageId = Spoon::get('page')->getId(); // array of excluded records $this->exclude[] = array('module' => 'pages', 'other_id' => $pageId); // get tags for page $tags = (array) FrontendTagsModel::getForItem('pages', $pageId); foreach ($tags as $tag) { $this->tags = array_merge((array) $this->tags, (array) $tag['name']); } // get page record $record = (array) FrontendNavigation::getPageInfo($pageId); // loop blocks foreach ((array) $record['extra_blocks'] as $block) { // set module class $class = 'Frontend' . SpoonFilter::toCamelCase($block['module']) . 'Model'; if (is_callable(array($class, 'getIdForTags'))) { // get record for module $record = FrontendTagsModel::callFromInterface($block['module'], $class, 'getIdForTags', $this->URL); // check if record exists if (!$record) { continue; } // add to excluded records $this->exclude[] = array('module' => $block['module'], 'other_id' => $record['id']); // get record's tags $tags = (array) FrontendTagsModel::getForItem($block['module'], $record['id']); foreach ($tags as $tag) { $this->tags = array_merge((array) $this->tags, (array) $tag['name']); } } } }
/** * You have to specify the action and module so we know what to do with this instance */ public function __construct() { // grab stuff from the reference and store them in this object (for later/easy use) $this->tpl = Spoon::get('template'); }
/** * Get a message from the language-file * * @param string $key The key to get. * @param string[optional] $module The module wherin we should search. * @return string */ public static function getMessage($key, $module = null) { if ($module === null) { if (Spoon::exists('url')) { $module = Spoon::get('url')->getModule(); } elseif (isset($_GET['module']) && $_GET['module'] != '') { $module = (string) $_GET['module']; } else { $module = 'core'; } } $key = SpoonFilter::toCamelCase((string) $key); $module = (string) $module; // check if the message exists if (isset(self::$msg[$module][$key])) { return self::$msg[$module][$key]; } // check if the message exists in the core if (isset(self::$msg['core'][$key])) { return self::$msg['core'][$key]; } // otherwise return the key in label-format return '{$msg' . SpoonFilter::toCamelCase($module) . $key . '}'; }
/** * Is the given action allowed for the current user * * @param string $action The action to check for. * @param string $module The module wherin the action is located. * @return bool */ public static function isAllowedAction($action = null, $module = null) { // GOD's rule them all! if (self::getUser()->isGod()) { return true; } // always allowed actions (yep, hardcoded, because we don't want other people to f**k up) $alwaysAllowed = array('dashboard' => array('index' => 7), 'core' => array('generate_url' => 7, 'content_css' => 7), 'error' => array('index' => 7), 'authentication' => array('index' => 7, 'reset_password' => 7, 'logout' => 7)); // grab the URL from the reference $URL = Spoon::get('url'); $action = $action !== null ? (string) $action : $URL->getAction(); $module = $module !== null ? (string) $module : $URL->getModule(); // is this action an action that doesn't require authentication? if (isset($alwaysAllowed[$module][$action])) { return true; } // we will cache everything if (empty(self::$allowedActions)) { // init var $db = BackendModel::getDB(); // get modules $modules = BackendModel::getModules(); // add always allowed foreach ($alwaysAllowed as $allowedModule => $actions) { $modules[] = $allowedModule; } // get allowed actions $allowedActionsRows = (array) $db->getRecords('SELECT gra.module, gra.action, gra.level FROM users_sessions AS us INNER JOIN users AS u ON us.user_id = u.id INNER JOIN users_groups AS ug ON u.id = ug.user_id INNER JOIN groups_rights_actions AS gra ON ug.group_id = gra.group_id WHERE us.session_id = ? AND us.secret_key = ?', array(SpoonSession::getSessionId(), SpoonSession::get('backend_secret_key'))); // add all actions and there level foreach ($allowedActionsRows as $row) { // add if the module is installed if (in_array($row['module'], $modules)) { self::$allowedActions[$row['module']][$row['action']] = (int) $row['level']; } } } // do we know a level for this action if (isset(self::$allowedActions[$module][$action])) { // is the level greater than zero? aka: do we have access? if ((int) self::$allowedActions[$module][$action] > 0) { return true; } } // fallback return false; }
/** * Parse a field and return the HTML. * * @return string * @param array $field Field data. */ public static function parseField(array $field) { // got a field if (!empty($field)) { // init $frm = new BackendForm('tmp', ''); $tpl = Spoon::exists('template') ? Spoon::get('template') : new BackendTemplate(); $fieldHTML = ''; $fieldName = 'field' . $field['id']; $values = isset($field['settings']['values']) ? $field['settings']['values'] : null; $defaultValues = isset($field['settings']['default_values']) ? $field['settings']['default_values'] : null; /** * Create form and parse to HTML */ // dropdown if ($field['type'] == 'dropdown') { // get index of selected item $defaultIndex = array_search($defaultValues, $values, true); if ($defaultIndex === false) { $defaultIndex = null; } // create element $ddm = $frm->addDropdown($fieldName, $values, $defaultIndex); // empty default element $ddm->setDefaultElement(''); // get content $fieldHTML = $ddm->parse(); } elseif ($field['type'] == 'radiobutton') { // rebuild values foreach ($values as $value) { $newValues[] = array('label' => $value, 'value' => $value); } // create element $rbt = $frm->addRadiobutton($fieldName, $newValues, $defaultValues); // get content $fieldHTML = $rbt->parse(); } elseif ($field['type'] == 'checkbox') { // rebuild values foreach ($values as $value) { $newValues[] = array('label' => $value, 'value' => $value); } // create element $chk = $frm->addMultiCheckbox($fieldName, $newValues, $defaultValues); // get content $fieldHTML = $chk->parse(); } elseif ($field['type'] == 'textbox') { // create element $txt = $frm->addText($fieldName, $defaultValues); $txt->setAttribute('disabled', 'disabled'); // get content $fieldHTML = $txt->parse(); } elseif ($field['type'] == 'textarea') { // create element $txt = $frm->addTextarea($fieldName, $defaultValues); $txt->setAttribute('cols', 30); $txt->setAttribute('disabled', 'disabled'); // get content $fieldHTML = $txt->parse(); } elseif ($field['type'] == 'heading') { $fieldHTML = '<h3>' . $values . '</h3>'; } elseif ($field['type'] == 'paragraph') { $fieldHTML = $values; } /** * Parse the field into the template */ // init $tpl->assign('plaintext', false); $tpl->assign('simple', false); $tpl->assign('multiple', false); $tpl->assign('id', $field['id']); $tpl->assign('required', isset($field['validations']['required'])); // plaintext items if ($field['type'] == 'heading' || $field['type'] == 'paragraph') { // assign $tpl->assign('content', $fieldHTML); $tpl->assign('plaintext', true); } elseif ($field['type'] == 'checkbox' || $field['type'] == 'radiobutton') { // name (prefixed by type) $name = $field['type'] == 'checkbox' ? 'chk' . ucfirst($fieldName) : 'rbt' . ucfirst($fieldName); // rebuild so the html is stored in a general name (and not rbtName) foreach ($fieldHTML as &$item) { $item['field'] = $item[$name]; } // show multiple $tpl->assign('label', $field['settings']['label']); $tpl->assign('items', $fieldHTML); $tpl->assign('multiple', true); } else { // assign $tpl->assign('label', $field['settings']['label']); $tpl->assign('field', $fieldHTML); $tpl->assign('simple', true); } // cough up created html return $tpl->getContent(BACKEND_MODULE_PATH . '/layout/templates/field.tpl'); } else { return ''; } }
/** * Get (or create and get) a database-connection * @later split the write and read connection * * @param bool[optional] $write Do you want the write-connection or not? * @return SpoonDatabase */ public static function getDB($write = false) { $write = (bool) $write; // do we have a db-object ready? if (!Spoon::exists('database')) { // create instance $db = new SpoonDatabase(DB_TYPE, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE, DB_PORT); // utf8 compliance & MySQL-timezone $db->execute('SET CHARACTER SET utf8, NAMES utf8, time_zone = "+0:00"'); // store Spoon::set('database', $db); } // return db-object return Spoon::get('database'); }