/** * Execute the action */ public function execute() { // If step 1 isn't entered, redirect back to the first step of the wizard $this->record = \SpoonSession::get('module'); if (!$this->record || !array_key_exists('title', $this->record)) { $this->redirect(Model::createURLForAction('Add')); } // If there are no fields added, redirect back to the second step of the wizard if (!array_key_exists('fields', $this->record) || empty($this->record['fields'])) { $this->redirect(Model::createURLForAction('AddStep2')); } parent::execute(); // initialize some variables $this->backendPath = BACKEND_MODULES_PATH . '/' . $this->record['camel_case_name'] . '/'; $this->frontendPath = FRONTEND_MODULES_PATH . '/' . $this->record['camel_case_name'] . '/'; $this->variables = (array) $this->record; unset($this->variables['fields']); $this->generateFolders(); $this->generateBaseFiles(); $this->generateInstallerFiles(); // Backend $this->generateBackendFiles(); $this->generateBackendModel(); $this->generateBackendActions(); $this->generateBackendCategoryActions(); // Frontend $this->generateFrontendFiles(); $this->generateFrontendModel(); $this->generateFrontendActions(); $this->generateFrontendCategoryActions(); $this->generateFrontendCategoryWidget(); $this->parse(); $this->display(); }
/** * 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') : ''); }
/** * Execute the action */ public function execute() { parent::execute(); // get parameters $charset = $this->getContainer()->getParameter('kernel.charset'); $searchTerm = \SpoonFilter::getPostValue('term', null, ''); $term = $charset == 'utf-8' ? \SpoonFilter::htmlspecialchars($searchTerm) : \SpoonFilter::htmlentities($searchTerm); // validate search term if ($term == '') { $this->output(self::BAD_REQUEST, null, 'term-parameter is missing.'); } else { // previous search result $previousTerm = \SpoonSession::exists('searchTerm') ? \SpoonSession::get('searchTerm') : ''; \SpoonSession::set('searchTerm', ''); // save this term? if ($previousTerm != $term) { // format data $this->statistics = array(); $this->statistics['term'] = $term; $this->statistics['language'] = LANGUAGE; $this->statistics['time'] = FrontendModel::getUTCDate(); $this->statistics['data'] = serialize(array('server' => $_SERVER)); $this->statistics['num_results'] = FrontendSearchModel::getTotal($term); // save data FrontendSearchModel::save($this->statistics); } // save current search term in cookie \SpoonSession::set('searchTerm', $term); // output $this->output(self::OK); } }
/** * Execute the action * * @return void */ public function execute() { // call parent, this will probably add some general CSS/JS or other required files parent::execute(); // get parameters $term = SpoonFilter::getGetValue('term', null, ''); // validate if ($term == '') { $this->output(self::BAD_REQUEST, null, 'term-parameter is missing.'); } // previous search result $previousTerm = SpoonSession::exists('searchTerm') ? SpoonSession::get('searchTerm') : ''; SpoonSession::set('searchTerm', ''); // save this term? if ($previousTerm != $term) { // format data $this->statistics = array(); $this->statistics['term'] = $term; $this->statistics['language'] = FRONTEND_LANGUAGE; $this->statistics['time'] = FrontendModel::getUTCDate(); $this->statistics['data'] = serialize(array('server' => $_SERVER)); $this->statistics['num_results'] = FrontendSearchModel::getTotal($term); // save data FrontendSearchModel::save($this->statistics); } // save current search term in cookie SpoonSession::set('searchTerm', $term); // output $this->output(self::OK); }
/** * Set start and end timestamp needed to collect analytics data * * @return void */ private function setDates() { // process BackendAnalyticsHelper::setDates(); // get timestamps from session and set $this->startTimestamp = (int) SpoonSession::get('analytics_start_timestamp'); $this->endTimestamp = (int) SpoonSession::get('analytics_end_timestamp'); }
/** * Load the form */ protected function loadForm() { $this->record = \SpoonSession::get('module'); $this->frm = new Form('add'); $this->frm->addText('title', $this->record ? $this->record['title'] : null, null, 'inputText title', 'inputTextError title'); $this->frm->addTextArea('description', $this->record ? $this->record['description'] : null); $this->frm->addText('author_name', $this->record ? $this->record['author_name'] : null); $this->frm->addText('author_url', $this->record ? $this->record['author_url'] : null); $this->frm->addText('author_email', $this->record ? $this->record['author_email'] : null); }
/** * Loads the form. * * @return void */ private function loadForm() { // guess email $host = $_SERVER['HTTP_HOST']; $this->frm->addText('email', SpoonSession::exists('email') ? SpoonSession::get('email') : 'info@' . $host); $this->frm->addPassword('password', SpoonSession::exists('password') ? SpoonSession::get('password') : null, null, 'inputPassword', 'inputPasswordError', true); $this->frm->addPassword('confirm', SpoonSession::exists('confirm') ? SpoonSession::get('confirm') : null, null, 'inputPassword', 'inputPasswordError', true); // disable autocomplete $this->frm->getField('password')->setAttributes(array('autocomplete' => 'off')); $this->frm->getField('confirm')->setAttributes(array('autocomplete' => 'off')); }
/** * Check if the token is ok */ public function checkToken() { $fromSession = \SpoonSession::exists('csrf_token') ? \SpoonSession::get('csrf_token') : ''; $fromGet = \SpoonFilter::getGetValue('token', null, ''); if ($fromSession != '' && $fromGet != '' && $fromSession == $fromGet) { return; } // clear the token \SpoonSession::set('csrf_token', ''); $this->redirect(BackendModel::createURLForAction('Index', null, null, array('error' => 'csrf'))); }
/** * Execute the actions */ public function execute() { // If step 1 isn't entered, redirect back to the first step of the wizard $this->record = \SpoonSession::get('module'); if (!$this->record || !array_key_exists('title', $this->record)) { $this->redirect(Model::createURLForAction('add')); } parent::execute(); $this->loadDataGrid(); $this->parse(); $this->display(); }
/** * Loads the form. */ private function loadForm() { // seperate frontend/backend languages? $this->frm->addCheckbox('same_interface_language', SpoonSession::exists('same_interface_language') ? SpoonSession::get('same_interface_language') : true); // multiple or single language (frontend) $this->frm->addRadiobutton('language_type', array(array('value' => 'multiple', 'label' => 'Multiple languages', 'variables' => array('multiple' => true)), array('value' => 'single', 'label' => 'Just one language', 'variables' => array('single' => true))), SpoonSession::exists('multiple_languages') && SpoonSession::get('multiple_languages') ? 'multiple' : 'single'); // multiple languages (frontend) $this->frm->addMultiCheckbox('languages', array(array('value' => 'en', 'label' => 'English'), array('value' => 'cn', 'label' => 'Chinese'), array('value' => 'nl', 'label' => 'Dutch'), array('value' => 'fr', 'label' => 'French'), array('value' => 'de', 'label' => 'German'), array('value' => 'hu', 'label' => 'Hungarian'), array('value' => 'it', 'label' => 'Italian'), array('value' => 'ru', 'label' => 'Russian'), array('value' => 'es', 'label' => 'Spanish')), SpoonSession::exists('languages') ? SpoonSession::get('languages') : 'en'); // multiple languages (backend) $this->frm->addMultiCheckbox('interface_languages', array(array('value' => 'en', 'label' => 'English'), array('value' => 'cn', 'label' => 'Chinese'), array('value' => 'nl', 'label' => 'Dutch'), array('value' => 'fr', 'label' => 'French'), array('value' => 'de', 'label' => 'German'), array('value' => 'hu', 'label' => 'Hungarian'), array('value' => 'it', 'label' => 'Italian'), array('value' => 'ru', 'label' => 'Russian'), array('value' => 'es', 'label' => 'Spanish')), SpoonSession::exists('interface_languages') ? SpoonSession::get('interface_languages') : 'en'); // single language (frontend) $this->frm->addDropdown('language', array('en' => 'English', 'cn' => 'Chinese', 'nl' => 'Dutch', 'fr' => 'French', 'de' => 'German', 'hu' => 'Hungarian', 'it' => 'Italian', 'ru' => 'Russian', 'es' => 'Spanish'), SpoonSession::exists('default_language') ? SpoonSession::get('default_language') : 'en'); // default language (frontend) $this->frm->addDropdown('default_language', array('en' => 'English', 'cn' => 'Chinese', 'nl' => 'Dutch', 'fr' => 'French', 'de' => 'German', 'hu' => 'Hungarian', 'it' => 'Italian', 'ru' => 'Russian', 'es' => 'Spanish'), SpoonSession::exists('default_language') ? SpoonSession::get('default_language') : 'en'); // default language (backend) $this->frm->addDropdown('default_interface_language', array('en' => 'English', 'cn' => 'Chinese', 'nl' => 'Dutch', 'fr' => 'French', 'de' => 'German', 'hu' => 'Hungarian', 'it' => 'Italian', 'ru' => 'Russian', 'es' => 'Spanish'), SpoonSession::exists('default_interface_language') ? SpoonSession::get('default_interface_language') : 'en'); }
/** * Execute the actions */ public function execute() { // If step 1 isn't entered, redirect back to the first step of the wizard $this->record = \SpoonSession::get('module'); if (!$this->record || !array_key_exists('title', $this->record)) { $this->redirect(Model::createURLForAction('Add')); } // If there are no fields added, redirect back to the second step of the wizard if (!array_key_exists('fields', $this->record) || empty($this->record['fields'])) { $this->redirect(Model::createURLForAction('AddStep2')); } parent::execute(); $this->loadForm(); $this->validateForm(); $this->parse(); $this->display(); }
/** * Loads the form. */ private function loadForm() { // guess db & username $host = $_SERVER['HTTP_HOST']; $chunks = explode('.', $host); // seems like windows can't handle localhost... $dbHost = substr(PHP_OS, 0, 3) == 'WIN' ? '127.0.0.1' : 'localhost'; // remove tld array_pop($chunks); // create base $base = implode('_', $chunks); // create input fields $this->frm->addText('hostname', SpoonSession::exists('db_hostname') ? SpoonSession::get('db_hostname') : $dbHost); $this->frm->addText('port', SpoonSession::exists('db_port') ? SpoonSession::get('db_port') : 3306, 10); $this->frm->addText('database', SpoonSession::exists('db_database') ? SpoonSession::get('db_database') : $base); $this->frm->addText('username', SpoonSession::exists('db_username') ? SpoonSession::get('db_username') : $base); $this->frm->addPassword('password', SpoonSession::exists('db_password') ? SpoonSession::get('db_password') : null); }
/** * Execute the action */ public function execute() { // If step 1 isn't entered, redirect back to the first step of the wizard $this->record = \SpoonSession::get('module'); if (!$this->record || !array_key_exists('title', $this->record)) { $this->redirect(Model::createURLForAction('Add')); } // If there are no fields added, redirect back to the second step of the wizard if (!array_key_exists('fields', $this->record) || empty($this->record['fields'])) { $this->redirect(Model::createURLForAction('AddStep2') . '&error=non-existing'); } // get parameters $this->id = $this->getParameter('id', 'int'); // does the item exist if ($this->id !== null && array_key_exists($this->id, $this->record['fields'])) { unset($this->record['fields'][$this->id]); \SpoonSession::set('module', $this->record); $this->redirect(Model::createURLForAction('AddStep2') . '&report=deleted'); } else { $this->redirect(Model::createURLForAction('AddStep2') . '&error=non-existing'); } }
/** * Validate the form. */ private function validateForm() { // submitted if ($this->frm->isSubmitted()) { // does the key exists? if (SpoonSession::exists('formbuilder_' . $this->item['id'])) { // calculate difference $diff = time() - (int) SpoonSession::get('formbuilder_' . $this->item['id']); // calculate difference, it it isn't 10 seconds the we tell the user to slow down if ($diff < 10 && $diff != 0) { $this->frm->addError(FL::err('FormTimeout')); } } // validate fields foreach ($this->item['fields'] as $field) { // fieldname $fieldName = 'field' . $field['id']; // skip if ($field['type'] == 'submit' || $field['type'] == 'paragraph' || $field['type'] == 'heading') { continue; } // loop other validations foreach ($field['validations'] as $rule => $settings) { // already has an error so skip if ($this->frm->getField($fieldName)->getErrors() !== null) { continue; } // required if ($rule == 'required') { $this->frm->getField($fieldName)->isFilled($settings['error_message']); } elseif ($rule == 'email') { // only check this if the field is filled, if the field is required it will be validated before if ($this->frm->getField($fieldName)->isFilled()) { $this->frm->getField($fieldName)->isEmail($settings['error_message']); } } elseif ($rule == 'numeric') { // only check this if the field is filled, if the field is required it will be validated before if ($this->frm->getField($fieldName)->isFilled()) { $this->frm->getField($fieldName)->isNumeric($settings['error_message']); } } } } // valid form if ($this->frm->isCorrect()) { // item $data['form_id'] = $this->item['id']; $data['session_id'] = SpoonSession::getSessionId(); $data['sent_on'] = FrontendModel::getUTCDate(); $data['data'] = serialize(array('server' => $_SERVER)); // insert data $dataId = FrontendFormBuilderModel::insertData($data); // init fields array $fields = array(); // loop all fields foreach ($this->item['fields'] as $field) { // skip if ($field['type'] == 'submit' || $field['type'] == 'paragraph' || $field['type'] == 'heading') { continue; } // field data $fieldData['data_id'] = $dataId; $fieldData['label'] = $field['settings']['label']; $fieldData['value'] = $this->frm->getField('field' . $field['id'])->getValue(); // prepare fields for email if ($this->item['method'] == 'database_email') { // add field for email $emailFields[] = array('label' => $field['settings']['label'], 'value' => is_array($fieldData['value']) ? implode(',', $fieldData['value']) : nl2br($fieldData['value'])); } // clean up if (is_array($fieldData['value']) && empty($fieldData['value'])) { $fieldData['value'] = null; } // serialize if ($fieldData['value'] !== null) { $fieldData['value'] = serialize($fieldData['value']); } // save fields data $fields[] = $fieldData; // insert FrontendFormBuilderModel::insertDataField($fieldData); } // need to send mail if ($this->item['method'] == 'database_email') { // build variables $variables['sentOn'] = time(); $variables['name'] = $this->item['name']; $variables['fields'] = $emailFields; // loop recipients foreach ($this->item['email'] as $address) { // add email FrontendMailer::addEmail(sprintf(FL::getMessage('FormBuilderSubject'), $this->item['name']), FRONTEND_MODULES_PATH . '/form_builder/layout/templates/mails/form.tpl', $variables, $address, $this->item['name']); } } // trigger event FrontendModel::triggerEvent('form_builder', 'after_submission', array('form_id' => $this->item['id'], 'data_id' => $dataId, 'data' => $data, 'fields' => $fields, 'visitorId' => FrontendModel::getVisitorId())); // store timestamp in session so we can block excesive usage SpoonSession::set('formbuilder_' . $this->item['id'], time()); // redirect $redirect = SITE_URL . '/' . $this->URL->getQueryString(); $redirect .= stripos($redirect, '?') === false ? '?' : '&'; $redirect .= 'identifier=' . $this->item['identifier']; // redirect with identifier SpoonHTTP::redirect($redirect); } else { // global form errors set if ($this->frm->getErrors() != '') { $this->tpl->assign('formBuilderError', $this->frm->getErrors()); } else { $this->tpl->assign('formBuilderError', FL::err('FormError')); } } } }
/** * Validate the form */ private function validateForm() { // get settings $commentsAllowed = isset($this->settings['allow_comments']) && $this->settings['allow_comments']; // comments aren't allowed so we don't have to validate if (!$commentsAllowed) { return false; } // is the form submitted if ($this->frm->isSubmitted()) { // cleanup the submitted fields, ignore fields that were added by hackers $this->frm->cleanupFields(); // does the key exists? if (SpoonSession::exists('blog_comment_' . $this->record['id'])) { // calculate difference $diff = time() - (int) SpoonSession::get('blog_comment_' . $this->record['id']); // calculate difference, it it isn't 10 seconds the we tell the user to slow down if ($diff < 10 && $diff != 0) { $this->frm->getField('message')->addError(FL::err('CommentTimeout')); } } // validate required fields $this->frm->getField('author')->isFilled(FL::err('AuthorIsRequired')); $this->frm->getField('email')->isEmail(FL::err('EmailIsRequired')); $this->frm->getField('message')->isFilled(FL::err('MessageIsRequired')); // validate optional fields if ($this->frm->getField('website')->isFilled() && $this->frm->getField('website')->getValue() != 'http://') { $this->frm->getField('website')->isURL(FL::err('InvalidURL')); } // no errors? if ($this->frm->isCorrect()) { // get module setting $spamFilterEnabled = isset($this->settings['spamfilter']) && $this->settings['spamfilter']; $moderationEnabled = isset($this->settings['moderation']) && $this->settings['moderation']; // reformat data $author = $this->frm->getField('author')->getValue(); $email = $this->frm->getField('email')->getValue(); $website = $this->frm->getField('website')->getValue(); if (trim($website) == '' || $website == 'http://') { $website = null; } $text = $this->frm->getField('message')->getValue(); // build array $comment['post_id'] = $this->record['id']; $comment['language'] = FRONTEND_LANGUAGE; $comment['created_on'] = FrontendModel::getUTCDate(); $comment['author'] = $author; $comment['email'] = $email; $comment['website'] = $website; $comment['text'] = $text; $comment['status'] = 'published'; $comment['data'] = serialize(array('server' => $_SERVER)); // get URL for article $permaLink = FrontendNavigation::getURLForBlock('blog', 'detail') . '/' . $this->record['url']; $redirectLink = $permaLink; // is moderation enabled if ($moderationEnabled) { // if the commenter isn't moderated before alter the comment status so it will appear in the moderation queue if (!FrontendBlogModel::isModerated($author, $email)) { $comment['status'] = 'moderation'; } } // should we check if the item is spam if ($spamFilterEnabled) { // check for spam $result = FrontendModel::isSpam($text, SITE_URL . $permaLink, $author, $email, $website); // if the comment is spam alter the comment status so it will appear in the spam queue if ($result) { $comment['status'] = 'spam'; } elseif ($result == 'unknown') { $comment['status'] = 'moderation'; } } // insert comment $comment['id'] = FrontendBlogModel::insertComment($comment); // trigger event FrontendModel::triggerEvent('blog', 'after_add_comment', array('comment' => $comment)); // append a parameter to the URL so we can show moderation if (strpos($redirectLink, '?') === false) { if ($comment['status'] == 'moderation') { $redirectLink .= '?comment=moderation#' . FL::act('Comment'); } if ($comment['status'] == 'spam') { $redirectLink .= '?comment=spam#' . FL::act('Comment'); } if ($comment['status'] == 'published') { $redirectLink .= '?comment=true#comment-' . $comment['id']; } } else { if ($comment['status'] == 'moderation') { $redirectLink .= '&comment=moderation#' . FL::act('Comment'); } if ($comment['status'] == 'spam') { $redirectLink .= '&comment=spam#' . FL::act('Comment'); } if ($comment['status'] == 'published') { $redirectLink .= '&comment=true#comment-' . $comment['id']; } } // set title $comment['post_title'] = $this->record['title']; $comment['post_url'] = $this->record['url']; // notify the admin FrontendBlogModel::notifyAdmin($comment); // store timestamp in session so we can block excesive usage SpoonSession::set('blog_comment_' . $this->record['id'], time()); // store author-data in cookies try { SpoonCookie::set('comment_author', $author, 30 * 24 * 60 * 60, '/', '.' . $this->URL->getDomain()); SpoonCookie::set('comment_email', $email, 30 * 24 * 60 * 60, '/', '.' . $this->URL->getDomain()); SpoonCookie::set('comment_website', $website, 30 * 24 * 60 * 60, '/', '.' . $this->URL->getDomain()); } catch (Exception $e) { // settings cookies isn't allowed, but because this isn't a real problem we ignore the exception } // redirect $this->redirect($redirectLink); } } }
/** * Redirect to the loading page after checking for infinite loops. * * @return void * @param string $action The action to check for infinite loops. * @param array[optional] $extraParameters The extra parameters to append to the redirect url. */ public static function redirectToLoadingPage($action, array $extraParameters = array()) { // get loop counter $counter = SpoonSession::exists($action . 'Loop') ? SpoonSession::get($action . 'Loop') : 0; // loop has run too long - throw exception if ($counter > 2) { throw new BackendException('An infinite loop has been detected while getting data from cache for the action "' . $action . '".'); } // set new counter SpoonSession::set($action . 'Loop', ++$counter); // put parameters into a string $extraParameters = empty($extraParameters) ? '' : '&' . http_build_query($extraParameters); // redirect to loading page which will get the needed data based on the current action SpoonHTTP::redirect(BackendModel::createURLForAction('loading') . '&redirect_action=' . $action . $extraParameters); }
/** * Show the success message */ private function showSuccess() { // assign variables $this->tpl->assign('url', isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'fork.local'); $this->tpl->assign('email', SpoonSession::get('email')); $this->tpl->assign('password', SpoonSession::get('password')); }
/** * Validate the form */ private function validateForm() { // get settings $subscriptionsAllowed = isset($this->settings['allow_subscriptions']) && $this->settings['allow_subscriptions']; // subscriptions aren't allowed so we don't have to validate if (!$subscriptionsAllowed) { return false; } // is the form submitted if ($this->frm->isSubmitted()) { // cleanup the submitted fields, ignore fields that were added by hackers $this->frm->cleanupFields(); // does the key exists? if (\SpoonSession::exists('agenda_subscription_' . $this->record['id'])) { // calculate difference $diff = time() - (int) \SpoonSession::get('agenda_subscription_' . $this->record['id']); // calculate difference, it it isn't 10 seconds the we tell the user to slow down if ($diff < 10 && $diff != 0) { $this->frm->getField('message')->addError(FL::err('CommentTimeout')); } } // validate required fields $this->frm->getField('name')->isFilled(FL::err('NameIsRequired')); $this->frm->getField('email')->isEmail(FL::err('EmailIsRequired')); // no errors? if ($this->frm->isCorrect()) { // get module setting $moderationEnabled = isset($this->settings['moderation']) && $this->settings['moderation']; // reformat data $name = $this->frm->getField('name')->getValue(); $email = $this->frm->getField('email')->getValue(); // build array $subscription['agenda_id'] = $this->record['id']; $subscription['language'] = FRONTEND_LANGUAGE; $subscription['created_on'] = FrontendModel::getUTCDate(); $subscription['name'] = $name; $subscription['email'] = $email; $subscription['status'] = 'subscribed'; // get URL for article $permaLink = $this->record['full_url']; $redirectLink = $permaLink; // is moderation enabled if ($moderationEnabled) { // if the commenter isn't moderated before alter the subscription status so it will appear in the moderation queue if (!FrontendAgendaModel::isModerated($name, $email)) { $subscription['status'] = 'moderation'; } } // insert comment $subscription['id'] = FrontendAgendaModel::insertSubscription($subscription); // trigger event FrontendModel::triggerEvent('agenda', 'after_add_subscription', array('subscription' => $subscription)); // append a parameter to the URL so we can show moderation if (strpos($redirectLink, '?') === false) { if ($subscription['status'] == 'moderation') { $redirectLink .= '?subscription=moderation#' . FL::act('Subscribe'); } if ($subscription['status'] == 'subscribed') { $redirectLink .= '?subscription=true#subscription-' . $subscription['id']; } } else { if ($subscription['status'] == 'moderation') { $redirectLink .= '&subscription=moderation#' . FL::act('Subscribe'); } if ($subscription['status'] == 'subscribed') { $redirectLink .= '&subscription=true#comment-' . $subscription['id']; } } // set title $subscription['agenda_title'] = $this->record['title']; $subscription['agenda_url'] = $this->record['url']; // notify the admin FrontendAgendaModel::notifyAdmin($subscription); // store timestamp in session so we can block excessive usage \SpoonSession::set('agenda_subscription_' . $this->record['id'], time()); // store author-data in cookies try { Cookie::set('subscription_author', $name); Cookie::set('subscription_email', $email); } catch (Exception $e) { // settings cookies isn't allowed, but because this isn't a real problem we ignore the exception } // redirect $this->redirect($redirectLink); } } }
date_default_timezone_set('Europe/Berlin'); // set include path ini_set("include_path", ".:../../library/"); // required classes require_once 'spoon/spoon.php'; require_once 'publicApp/publicApp.php'; $tpl = new SpoonTemplate(); $tpl->setForceCompile(true); $tpl->setCompileDirectory('./compiled_templates'); SpoonSession::start(); //Content layout if (SpoonSession::exists('id') === false) { SpoonHTTP::redirect('index.php'); } $latestCheckIn = CheckIn::getLatestCheckinByUserId(SpoonSession::get('id')); $daysAgo = (SpoonDate::getDate("m.d.j") - SpoonDate::getDate("m.d.j", strtotime($latestCheckIn->timestamp))) * 100; $timeAgo = SpoonDate::getDate("H:i:s") - SpoonDate::getDate("H:i:s", strtotime($latestCheckIn->timestamp)); //If the checkin is within 5 hours //if($timeAgo > -6){ $tpl->assign('oCheckIn', true); if (SpoonFilter::getGetValue('event', null, '') === 'plus') { $latestCheckIn->AddTab(SpoonFilter::getGetValue('drinkid', null, '')); SpoonHTTP::redirect('checkin.php'); } else { if (SpoonFilter::getGetValue('event', null, '') === 'min') { $latestCheckIn->DeleteTab(SpoonFilter::getGetValue('drinkid', null, '')); SpoonHTTP::redirect('checkin.php'); } } $tpl->assign('pub_id', $latestCheckIn->pub->pub_id);
/** * Set start and end timestamp needed to collect analytics data */ private function setDates() { BackendAnalyticsHelper::setDates(); $this->startTimestamp = SpoonSession::get('analytics_start_timestamp'); $this->endTimestamp = SpoonSession::get('analytics_end_timestamp'); }
/** * Parse the datagrids and the reports. */ protected function parse() { parent::parse(); // parse data grid $this->tpl->assign('dataGridInstallableModules', (string) $this->dataGridInstallableModules->getContent()); $this->tpl->assign('dataGridInstalledModules', (string) $this->dataGridInstalledModules->getContent()); // parse installer warnings $this->tpl->assign('warnings', (array) \SpoonSession::get('installer_warnings')); }
/** * Is the current user logged in? * * @return bool */ public static function isLoggedIn() { // check if all needed values are set in the session if (SpoonSession::exists('backend_logged_in', 'backend_secret_key') && (bool) SpoonSession::get('backend_logged_in') && (string) SpoonSession::get('backend_secret_key') != '') { // get database instance $db = BackendModel::getDB(true); // get the row from the tables $sessionData = $db->getRecord('SELECT us.id, us.user_id FROM users_sessions AS us WHERE us.session_id = ? AND us.secret_key = ? LIMIT 1', array(SpoonSession::getSessionId(), SpoonSession::get('backend_secret_key'))); // if we found a matching row, we know the user is logged in, so we update his session if ($sessionData !== null) { // update the session in the table $db->update('users_sessions', array('date' => BackendModel::getUTCDate()), 'id = ?', (int) $sessionData['id']); // create a user object, it will handle stuff related to the current authenticated user self::$user = new BackendUser($sessionData['user_id']); // the user is logged on return true; } else { SpoonSession::set('backend_logged_in', false); } } else { SpoonSession::set('backend_logged_in', false); } // reset values for invalid users. We can't destroy the session because session-data can be used on the site. if ((bool) SpoonSession::get('backend_logged_in') === false) { // reset some values SpoonSession::set('backend_logged_in', false); SpoonSession::set('backend_secret_key', ''); // return result return false; } }
<?php date_default_timezone_set('Europe/Berlin'); // set include path ini_set("include_path", ".:../library/"); // required classes require_once 'spoon/spoon.php'; require_once 'publicApp/publicApp.php'; $tpl = new SpoonTemplate(); $tpl->setForceCompile(true); $tpl->setCompileDirectory('./compiled_templates'); // do I know you? if (SpoonSession::exists('public_uid')) { $tpl->assign('oLogout', true); $tpl->assign('oNavMe', true); $uid = SpoonSession::get('public_uid'); $user = new User($uid); if ($user->GetFollowing() != null) { $values = $user->GetFollowing(); $following = array(); foreach ($values as $value) { $userFollowing = new User($value['friend']); if ($userFollowing->fb_uid == null) { $userFollowing->fb_uid = 1; } array_push($following, get_object_vars($userFollowing)); } $tpl->assign('oFollowing', true); $tpl->assign('iFollowing', $following); } else { $tpl->assign('oNoFollowing', true);
/** * Check if a profile is loggedin. * * @return bool */ public static function isLoggedIn() { // profile object exist? (this means the session/cookie checks have already happened in the current request and we cached the profile) if (isset(self::$profile)) { return true; } elseif (SpoonSession::exists('frontend_profile_logged_in') && SpoonSession::get('frontend_profile_logged_in') === true) { // get session id $sessionId = SpoonSession::getSessionId(); // get profile id $profileId = (int) FrontendModel::getDB()->getVar('SELECT p.id FROM profiles AS p INNER JOIN profiles_sessions AS ps ON ps.profile_id = p.id WHERE ps.session_id = ?', (string) $sessionId); // valid profile id if ($profileId !== 0) { // update session date FrontendModel::getDB(true)->update('profiles_sessions', array('date' => FrontendModel::getUTCDate()), 'session_id = ?', $sessionId); // new user object self::$profile = new FrontendProfilesProfile($profileId); // logged in return true; } else { SpoonSession::set('frontend_profile_logged_in', false); } } elseif (SpoonCookie::exists('frontend_profile_secret_key') && SpoonCookie::get('frontend_profile_secret_key') != '') { // secret $secret = (string) SpoonCookie::get('frontend_profile_secret_key'); // get profile id $profileId = (int) FrontendModel::getDB()->getVar('SELECT p.id FROM profiles AS p INNER JOIN profiles_sessions AS ps ON ps.profile_id = p.id WHERE ps.secret_key = ?', $secret); // valid profile id if ($profileId !== 0) { // get new secret key $profileSecret = FrontendProfilesModel::getEncryptedString(SpoonSession::getSessionId(), FrontendProfilesModel::getRandomString()); // update session record FrontendModel::getDB(true)->update('profiles_sessions', array('session_id' => SpoonSession::getSessionId(), 'secret_key' => $profileSecret, 'date' => FrontendModel::getUTCDate()), 'secret_key = ?', $secret); // set new cookie SpoonCookie::set('frontend_profile_secret_key', $profileSecret, 60 * 60 * 24 * 31); // set is_logged_in to true SpoonSession::set('frontend_profile_logged_in', true); // update last login FrontendProfilesModel::update($profileId, array('last_login' => FrontendModel::getUTCDate())); // new user object self::$profile = new FrontendProfilesProfile($profileId); // logged in return true; } else { SpoonCookie::delete('frontend_profile_secret_key'); } } // no one is logged in return false; }
/** * Validate the form */ protected function validateForm() { if ($this->frm->isSubmitted()) { $this->frm->cleanupFields(); // validation $fields = $this->frm->getFields(); $fields['label']->isFilled(Language::err('FieldIsRequired')); // get existing fields $this->record = \SpoonSession::get('module'); if (array_key_exists('fields', $this->record)) { foreach ($this->record['fields'] as $field) { // check if we already have a type with the same label if (strtolower($field['label']) == strtolower($fields['label']->getValue())) { $fields['label']->addError(Language::err('LabelAlreadyExist')); break; } } } // for certain types, the options field is required $type = $fields['type']->getValue(); if ($type == 'dropdown' || $type == 'multicheckbox' || $type == 'radiobutton') { $fields['tags']->isFilled(Language::err('FieldIsRequired')); // check if the default field is one of the options if ($fields['default']->isFilled()) { $options = explode(',', $fields['tags']->getValue()); if (!in_array($fields['default']->getValue(), $options)) { $fields['default']->addError(Language::err('DefaultShouldBeAnOption')); } } elseif ($type == 'radiobutton') { $fields['default']->addError(Language::err('FieldIsRequired')); } } // if the type is images, the options should be in the form 200x200 seperated by a comma if ($type == 'image') { $fields['tags']->isFilled(Language::err('FieldIsRequired')); $tags = explode(',', $fields['tags']->getValue()); // loop all tags and check on format, example (400x400) foreach ($tags as $tag) { if (!preg_match('\'([1-9][0-9]*x[1-9][0-9]*|x[1-9][0-9]*|[1-9][0-9]*x)\'', $tag)) { $fields['tags']->addError(Language::err('ImageSizeNotWellFormed')); break; } } } // check if the default value is valid if ($fields['default']->isFilled()) { // get default value $defaultValue = $fields['default']->getValue(); // check the default values if ($type == 'text' || $type == 'password' || $type == 'file' || $type == 'image') { if (strlen($defaultValue) > 255) { $fields['default']->addError(Language::err('Max255Characters')); } } elseif ($type == 'number') { if (!is_numeric($defaultValue)) { $fields['default']->addError(Language::err('FieldIsNotNumeric')); } } elseif ($type == 'datetime') { if (!BackendModuleMakerHelper::isValidDateTime($defaultValue)) { $fields['default']->addError(Language::err('FieldIsNotAValidDateTime')); } } elseif ($type == 'checkbox') { if (strtoupper($defaultValue) != 'Y' && strtoupper($defaultValue) != 'N') { $fields['default']->addError(Language::err('MustBeAYOrAN')); } } } if ($this->frm->isCorrect()) { // create the item $item['label'] = strtolower($fields['label']->getValue()); $item['type'] = $type; $item['options'] = $fields['tags']->getValue(); $item['required'] = $fields['required']->isChecked(); $item['default'] = $fields['default']->getValue(); $item['camel_cased_label'] = BackendModuleMakerHelper::buildCamelCasedName($item['label']); $item['underscored_label'] = BackendModuleMakerHelper::buildUnderscoredName($item['label']); $item['lower_ccased_label'] = BackendModuleMakerHelper::buildLowerCamelCasedName($item['label']); $item['meta'] = false; $item['searchable'] = false; if ($item['type'] == 'image' && $fields['caption']->isChecked()) { $item['type'] = 'image_caption'; } // generate the SQL for the field $item['sql'] = $this->generateSQL($item); // if the record has no fields key yet, add it if (!array_key_exists('fields', $this->record)) { $this->record['fields'] = array(); } // add the item to the fields array of the record $this->record['fields'][] = $item; // save \SpoonSession::set('module', $this->record); $this->redirect(Model::createURLForAction('AddStep2')); } } }
$facebook = new Facebook(array('appId' => '118234134911012', 'secret' => 'a83b1fbf766dcf41a8238a13f53690bd', 'cookie' => true)); $uid = SpoonSession::get('id'); $db = new SpoonDatabase('mysql', 'localhost', 'xqdchsmn_public', 'pRAcHU8Ajath7qa3', 'xqdchsmn_public'); $user = $db->getRecord('SELECT * FROM users WHERE user_id = ?', $uid); $fb_uid = $user['fb_uid']; $messageContent = 'I\'m at ' . $check->pub->name . ' - http://publicapp.tk/pubs/' . $check->pub->pub_id . ''; $facebook->api($fb_uid . '/feed', 'post', array('message' => $messageContent, 'cb' => '')); } /*end*/ /*post to twitter*/ if ($user['twitter_uid']) { require_once 'twitteroauth/twitteroauth.php'; define('CONSUMER_KEY', '4K5I4iPpEGc4KgTN1VnKDA'); define('CONSUMER_SECRET', 'cRWey0CbUXuD0qIrA89s9tKQjHtxQXRn8leR7AiI'); define('OAUTH_CALLBACK', 'http://www.publicapp.tk/twittercallback.php'); $uid = SpoonSession::get('id'); $db = new SpoonDatabase('mysql', 'localhost', 'xqdchsmn_public', 'pRAcHU8Ajath7qa3', 'xqdchsmn_public'); $user = $db->getRecord('SELECT * FROM users WHERE user_id = ?', $uid); $twitter_token = $user['twitter_token']; $twitter_secret = $user['twitter_secret']; $messageContent = 'I\'m at ' . $check->pub->name . ' - http://publicapp.tk/pubs/' . $check->pub->pub_id . ''; $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $twitter_token, $twitter_secret); $response = $connection->post('statuses/update', array('status' => $messageContent)); } /*end*/ SpoonHTTP::redirect('checkin.php'); } if ($pub->pub_id === null) { SpoonHTTP::redirect('index.php'); } $recent = CheckIn::getCheckinsByPubId($pub->pub_id);
/** * Validates the form. This is an alternative for isCorrect, but without retrieve the status of course. * * @return SpoonForm */ public function validate() { // define errors $errors = ''; // if we use tokens, we validate them here if ($this->getUseToken()) { // token not available? if (!SpoonSession::exists('form_token')) { $errors .= $this->tokenError; } else { // compare tokens if ($this->getField('form_token')->getValue() != SpoonSession::get('form_token')) { $errors .= $this->tokenError; } } } // loop objects foreach ($this->objects as $oElement) { // check, since some objects don't have this method! if (is_callable(array($oElement, 'getErrors'))) { $errors .= $oElement->getErrors(); } } // affect correct status if (trim($errors) != '') { $this->correct = false; } // main form errors? if (trim($this->getErrors()) != '') { $this->correct = false; } // update parsed status $this->validated = true; return $this; }
/** * Parse the authentication settings for the authenticated user */ private function parseAuthentication() { // init var $db = BackendModel::getDB(); // get allowed actions $allowedActions = (array) $db->getRecords('SELECT gra.module, gra.action, MAX(gra.level) AS 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 = ? GROUP BY gra.module, gra.action', array(SpoonSession::getSessionId(), SpoonSession::get('backend_secret_key'))); // loop actions and assign to template foreach ($allowedActions as $action) { if ($action['level'] == '7') { $this->assign('show' . SpoonFilter::toCamelCase($action['module'], '_') . SpoonFilter::toCamelCase($action['action'], '_'), true); } } }
/** * Validate the forms */ private function validateForm() { if ($this->frm->isSubmitted()) { $txtEmail = $this->frm->getField('backend_email'); $txtPassword = $this->frm->getField('backend_password'); // required fields if (!$txtEmail->isFilled() || !$txtPassword->isFilled()) { // add error $this->frm->addError('fields required'); // show error $this->tpl->assign('hasError', true); } $this->getContainer()->get('logger')->info("Trying to authenticate user '{$txtEmail->getValue()}'."); // invalid form-token? if ($this->frm->getToken() != $this->frm->getField('form_token')->getValue()) { // set a correct header, so bots understand they can't mess with us. if (!headers_sent()) { header('400 Bad Request', true, 400); } } // get the user's id $userId = BackendUsersModel::getIdByEmail($txtEmail->getValue()); // all fields are ok? if ($txtEmail->isFilled() && $txtPassword->isFilled() && $this->frm->getToken() == $this->frm->getField('form_token')->getValue()) { // try to login the user if (!BackendAuthentication::loginUser($txtEmail->getValue(), $txtPassword->getValue())) { $this->getContainer()->get('logger')->info("Failed authenticating user '{$txtEmail->getValue()}'."); // add error $this->frm->addError('invalid login'); // store attempt in session $current = \SpoonSession::exists('backend_login_attempts') ? (int) \SpoonSession::get('backend_login_attempts') : 0; // increment and store \SpoonSession::set('backend_login_attempts', ++$current); // save the failed login attempt in the user's settings if ($userId !== false) { BackendUsersModel::setSetting($userId, 'last_failed_login_attempt', time()); } // show error $this->tpl->assign('hasError', true); } } // check sessions if (\SpoonSession::exists('backend_login_attempts') && (int) \SpoonSession::get('backend_login_attempts') >= 5) { // get previous attempt $previousAttempt = \SpoonSession::exists('backend_last_attempt') ? \SpoonSession::get('backend_last_attempt') : time(); // calculate timeout $timeout = 5 * (\SpoonSession::get('backend_login_attempts') - 4); // too soon! if (time() < $previousAttempt + $timeout) { // sleep until the user can login again sleep($timeout); // set a correct header, so bots understand they can't mess with us. if (!headers_sent()) { header('503 Service Unavailable', true, 503); } } else { // increment and store \SpoonSession::set('backend_last_attempt', time()); } // too many attempts $this->frm->addEditor('too many attempts'); $this->getContainer()->get('logger')->info("Too many login attempts for user '{$txtEmail->getValue()}'."); // show error $this->tpl->assign('hasTooManyAttemps', true); $this->tpl->assign('hasError', false); } // no errors in the form? if ($this->frm->isCorrect()) { // cleanup sessions \SpoonSession::delete('backend_login_attempts'); \SpoonSession::delete('backend_last_attempt'); // save the login timestamp in the user's settings $lastLogin = BackendUsersModel::getSetting($userId, 'current_login'); BackendUsersModel::setSetting($userId, 'current_login', time()); if ($lastLogin) { BackendUsersModel::setSetting($userId, 'last_login', $lastLogin); } $this->getContainer()->get('logger')->info("Successfully authenticated user '{$txtEmail->getValue()}'."); // redirect to the correct URL (URL the user was looking for or fallback) $this->redirectToAllowedModuleAndAction(); } } // is the form submitted if ($this->frmForgotPassword->isSubmitted()) { // backend email $email = $this->frmForgotPassword->getField('backend_email_forgot')->getValue(); // required fields if ($this->frmForgotPassword->getField('backend_email_forgot')->isEmail(BL::err('EmailIsInvalid'))) { // check if there is a user with the given emailaddress if (!BackendUsersModel::existsEmail($email)) { $this->frmForgotPassword->getField('backend_email_forgot')->addError(BL::err('EmailIsUnknown')); } } // no errors in the form? if ($this->frmForgotPassword->isCorrect()) { // generate the key for the reset link and fetch the user ID for this email $key = BackendAuthentication::getEncryptedString($email, uniqid()); // insert the key and the timestamp into the user settings $userId = BackendUsersModel::getIdByEmail($email); $user = new User($userId); $user->setSetting('reset_password_key', $key); $user->setSetting('reset_password_timestamp', time()); // variables to parse in the e-mail $variables['resetLink'] = SITE_URL . BackendModel::createURLForAction('ResetPassword') . '&email=' . $email . '&key=' . $key; // send e-mail to user $from = $this->get('fork.settings')->get('Core', 'mailer_from'); $replyTo = $this->get('fork.settings')->get('Core', 'mailer_reply_to'); $message = \Common\Mailer\Message::newInstance(\SpoonFilter::ucfirst(BL::msg('ResetYourPasswordMailSubject')))->setFrom(array($from['email'] => $from['name']))->setTo(array($email))->setReplyTo(array($replyTo['email'] => $replyTo['name']))->parseHtml(BACKEND_MODULES_PATH . '/Authentication/Layout/Templates/Mails/ResetPassword.tpl', $variables); $this->get('mailer')->send($message); // clear post-values $_POST['backend_email_forgot'] = ''; // show success message $this->tpl->assign('isForgotPasswordSuccess', true); // show form $this->tpl->assign('showForm', true); } else { // errors? $this->tpl->assign('showForm', true); } } }
/** * Is the current user logged in? * * @return bool */ public static function isLoggedIn() { if (BackendModel::getContainer()->has('logged_in')) { return BackendModel::getContainer()->get('logged_in'); } // check if all needed values are set in the session // @todo could be written by SpoonSession::get (since that no longer throws exceptions) if (\SpoonSession::exists('backend_logged_in', 'backend_secret_key') && (bool) \SpoonSession::get('backend_logged_in') && (string) \SpoonSession::get('backend_secret_key') != '') { // get database instance $db = BackendModel::get('database'); // get the row from the tables $sessionData = $db->getRecord('SELECT us.id, us.user_id FROM users_sessions AS us WHERE us.session_id = ? AND us.secret_key = ? LIMIT 1', array(\SpoonSession::getSessionId(), \SpoonSession::get('backend_secret_key'))); // if we found a matching row, we know the user is logged in, so we update his session if ($sessionData !== null) { // update the session in the table $db->update('users_sessions', array('date' => BackendModel::getUTCDate()), 'id = ?', (int) $sessionData['id']); // create a user object, it will handle stuff related to the current authenticated user self::$user = new User($sessionData['user_id']); // the user is logged on BackendModel::getContainer()->set('logged_in', true); return true; } } // no data found, so f**k up the session, will be handled later on in the code \SpoonSession::set('backend_logged_in', false); BackendModel::getContainer()->set('logged_in', false); \SpoonSession::set('backend_secret_key', ''); return false; }