get() static public method

Gets a session value by key
static public get ( mixed $key = false, mixed $default = null ) : mixed
$key mixed The key to look for. Pass false or null to return the entire session array.
$default mixed Optional default value, which should be returned if no element has been found
return mixed
Exemplo n.º 1
0
 public function login($welcome = null)
 {
     if ($user = panel()->site()->user()) {
         go(panel()->urls()->index());
     }
     $message = l('login.error');
     $error = false;
     $form = panel()->form('login');
     $form->cancel = false;
     $form->save = l('login.button');
     $form->centered = true;
     if (r::is('post') and get('_csfr') and csfr(get('_csfr'))) {
         $data = $form->serialize();
         $user = site()->user(str::lower($data['username']));
         if (!$user) {
             $error = true;
         } else {
             if (!$user->hasPanelAccess()) {
                 $error = true;
             } else {
                 if (!$user->login(get('password'))) {
                     $error = true;
                 } else {
                     go(panel()->urls()->index());
                 }
             }
         }
     }
     if ($username = s::get('username')) {
         $form->fields->username->value = html($username, false);
     }
     return layout('login', array('meta' => new Snippet('meta'), 'welcome' => $welcome ? l('login.welcome') : '', 'form' => $form, 'error' => $error ? $message : false));
 }
Exemplo n.º 2
0
 public function message()
 {
     if ($message = s::get('message') and is_array($message)) {
         $text = a::get($message, 'text');
         $type = a::get($message, 'type', 'notification');
         $element = new Brick('div');
         $element->addClass('message');
         if ($type == 'error') {
             $element->addClass('message-is-alert');
         } else {
             $element->addClass('message-is-notice');
         }
         $element->append(function () use($text) {
             $content = new Brick('span');
             $content->addClass('message-content');
             $content->text($text);
             return $content;
         });
         $element->append(function () {
             $toggle = new Brick('a');
             $toggle->attr('href', url::current());
             $toggle->addClass('message-toggle');
             $toggle->html('<i>&times;</i>');
             return $toggle;
         });
         s::remove('message');
         return $element;
     }
 }
Exemplo n.º 3
0
 /**
  * Remove old values from the Session’s flash data.
  */
 public static function flush()
 {
     // Make sure the session is started
     s::start();
     // Retrieve the flash data
     $registry = s::get(self::$namespace);
     // Clean up registry
     if (!empty($registry)) {
         foreach ($registry as $key => $expiry) {
             $expiry++;
             // Remove all old values from the session
             if ($expiry > 1) {
                 s::remove($key);
                 unset($registry[$key]);
             } else {
                 $registry[$key] = $expiry;
             }
         }
         // Write registry back to session
         if (!empty($registry)) {
             s::set(self::$namespace, $registry);
         } else {
             s::remove(self::$namespace);
         }
     }
 }
Exemplo n.º 4
0
 public function paginated($mode = 'sidebar')
 {
     if ($limit = $this->page->blueprint()->pages()->limit()) {
         $hash = sha1($this->page->id());
         switch ($mode) {
             case 'sidebar':
                 $id = 'pages.' . $hash;
                 $var = 'page';
                 break;
             case 'subpages/visible':
                 $id = 'subpages.visible.' . $hash;
                 $var = 'visible';
                 break;
             case 'subpages/invisible':
                 $id = 'subpages.invisible.' . $hash;
                 $var = 'invisible';
                 break;
         }
         $children = $this->paginate($limit, array('page' => get($var, s::get($id)), 'omitFirstPage' => false, 'variable' => $var, 'method' => 'query'));
         // store the last page
         s::set($id, $children->pagination()->page());
         return $children;
     } else {
         return $this;
     }
 }
Exemplo n.º 5
0
 public static function get($name)
 {
     $messages = s::get('messages');
     foreach ($messages as $key => $message) {
         if ($message->name == $name) {
             return $message->value;
         }
     }
     s::remove('messages');
 }
Exemplo n.º 6
0
 /**
  * Resets store if necessary to stay in sync with content file
  */
 public function sync()
 {
     $file = $this->structure->model()->textfile();
     $ageModel = f::exists($file) ? f::modified($file) : 0;
     $ageStore = s::get($this->id() . '_age');
     if ($ageStore < $ageModel) {
         $this->reset();
         $this->age = $ageModel;
     } else {
         $this->age = $ageStore;
     }
 }
Exemplo n.º 7
0
 public static function configure()
 {
     if (is_null(static::$site)) {
         static::$site = kirby::panelsetup();
     }
     // load all available routes
     static::$routes = array_merge(static::$routes, require root('panel.app.routes') . DS . 'api.php');
     static::$routes = array_merge(static::$routes, require root('panel.app.routes') . DS . 'views.php');
     // setup the blueprint root
     blueprint::$root = c::get('root.site') . DS . 'blueprints';
     // start the router
     static::$router = new Router();
     static::$router->register(static::$routes);
     // content language switcher variable
     if (static::$site->multilang()) {
         if ($language = server::get('http_language') or $language = s::get('lang')) {
             static::$site->visit('/', $language);
         }
         app::$language = static::$site->language()->code();
         s::set('lang', app::$language);
     }
     // load the interface language file
     if (static::$site->user()) {
         $languageCode = static::$site->user()->language();
     } else {
         $languageCode = c::get('panel.language', 'en');
     }
     // validate the language code
     if (!in_array($languageCode, static::languages()->keys())) {
         $languageCode = 'en';
     }
     // store the interface language
     app::$interfaceLanguage = $languageCode;
     $language = (require root('panel.app.languages') . DS . $languageCode . '.php');
     // set all language variables
     l::$data = $language['data'];
     // register router filters
     static::$router->filter('auth', function () {
         if (!app::$site->user()) {
             go('panel/login');
         }
     });
     // check for a completed installation
     static::$router->filter('isInstalled', function () {
         if (app::$site->users()->count() == 0) {
             go('panel/install');
         }
     });
     // only use the fragments of the path without params
     static::$path = implode('/', (array) url::fragments(detect::path()));
 }
Exemplo n.º 8
0
 public function login($welcome = null)
 {
     if ($user = panel()->site()->user()) {
         go(panel()->urls()->index());
     }
     $form = panel()->form('login');
     $form->cancel = false;
     $form->save = l('login.button');
     $form->centered = true;
     if ($username = s::get('username')) {
         $form->fields->username->value = html($username, false);
     }
     return layout('login', array('meta' => new Snippet('meta'), 'welcome' => $welcome ? l('login.welcome') : '', 'form' => $form));
 }
Exemplo n.º 9
0
function snippet_detect($file, $data = array(), $return = false)
{
    if (is_object($data)) {
        $data = array('item' => $data);
    }
    // If the session variable is not found, set the default value (e.g 'mobile')
    $device_class = s::get('device_class', 'mobile');
    // Embed the device class specific snippet
    if ($device_class == 'mobile') {
        // Embed the mobile snippet (`mobile` is the default snippet, without the device specific `.postfix`, e.g. footer.php)
        return tpl::load(kirby::instance()->roots()->snippets() . DS . $file . '.php', $data, $return);
    } else {
        // Embed the device class specific snippet (e.g. `footer.desktop.php`)
        return tpl::load(kirby::instance()->roots()->snippets() . DS . $file . '.' . $device_class . '.php', $data, $return);
    }
}
Exemplo n.º 10
0
 function checkAuth()
 {
     $token = cookie::get('auth');
     if (empty($token)) {
         return false;
     }
     $user = s::get($token, false);
     if (empty($user)) {
         return false;
     }
     $account = self::load($user['username']);
     if (empty($account) || empty($user['username'])) {
         return false;
     }
     $account['token'] = $token;
     return $account;
 }
Exemplo n.º 11
0
 public function init()
 {
     $data = s::get($this->id());
     if (!is_array($data)) {
         $raw = (array) $this->source;
     } else {
         $raw = (array) s::get($this->id(), array());
     }
     $data = array();
     foreach ($raw as $row) {
         if (!isset($row['id'])) {
             $row['id'] = str::random(32);
         }
         $data[$row['id']] = $row;
     }
     $this->data = $data;
     s::set($this->id, $this->data);
 }
Exemplo n.º 12
0
 /**
  * @param string $id The unique ID of this form.
  *
  * @param string $recipient e-mail adress the form content should be sent to.
  *
  * @param array $options Array of sendform options.
  */
 public function __construct($id, $recipient, $options)
 {
     if (empty($id)) {
         throw new Error('No SendForm ID was given.');
     }
     if (empty($recipient)) {
         throw new Error('No SendForm recipient was given.');
     }
     $this->id = $id;
     $this->erroneousFields = array();
     // the token is stored as session variable until the form is sent
     // successfully
     $this->token = s::get($this->id);
     if (!$this->token) {
         $this->generateToken();
     }
     // get the data to be sent (if there is any)
     $this->data = get();
     if ($this->requestValid()) {
         $this->options = array('subject' => str::template(a::get($options, 'subject', l::get('sendform-default-subject')), $this->data), 'snippet' => a::get($options, 'snippet', false), 'copy' => a::get($options, 'copy', array()), 'required' => a::get($options, 'required', array()), 'validate' => a::get($options, 'validate', array()), 'to' => $recipient, 'service' => a::get($options, 'service', 'mail'), 'service-options' => a::get($options, 'service-options', array()));
         // remove newlines to prevent malicious modifications of the email
         // header
         $this->options['subject'] = str_replace("\n", '', $this->options['subject']);
         // extend the data array so email snippets get these fields, too
         $this->data['_subject'] = $this->options['subject'];
         $this->data['_to'] = $this->options['to'];
         if (array_key_exists('_receive_copy', $this->data)) {
             array_unshift($this->options['copy'], $this->data['_from']);
         }
         $this->sentSuccessful = false;
         $this->message = '';
         $requiredFields = a::merge($this->options['required'], array('_from' => 'email'));
         $validateFields = a::merge($this->options['validate'], $requiredFields);
         if ($this->dataValid($requiredFields, $validateFields)) {
             $this->sendForm();
         }
     }
 }
Exemplo n.º 13
0
 static function user()
 {
     if (!is_null(self::$user)) {
         return self::$user;
     }
     $token = cookie::get('authFrontend');
     if (empty($token)) {
         return self::$user = false;
     }
     $username = s::get('authFrontend.' . $token, false);
     if (empty($username)) {
         return self::$user = false;
     }
     $account = self::load($username);
     // make sure to remove the password
     // because this should never be visible to anybody
     unset($account->_['password']);
     if (empty($account) || $account->username() != $username) {
         return self::$user = false;
     }
     $account->token = $token;
     return self::$user = $account;
 }
Exemplo n.º 14
0
        ?>
</p>
		<?php 
    }
    ?>
	</div>
<?php 
}
?>


<!-- Success messages -->

<?php 
$successes = [];
if (s::get('discountCode') != '') {
    $successes[] = l::get('notification-code');
}
if (count($successes) > 0) {
    ?>
	
	<div class="uk-alert uk-alert-success">
		<?php 
    foreach ($successes as $success) {
        ?>
			<p dir="auto"><?php 
        echo $success;
        ?>
</p>
		<?php 
    }
Exemplo n.º 15
0
<?php

l::set(['username' => 'Nombre de usuario', 'password' => 'Contraseña', 'login' => 'Ingresar', 'register' => 'Registrar', 'honeypot-label' => 'No llenar este campo. (Protection Anti-Spam)', 'email-address' => 'Correo electrónico', 'first-name' => 'Nombre', 'last-name' => 'Apellido(s)', 'full-name' => 'Nombre completo', 'country' => 'País', 'country-help' => 'Para calcular costos de envío', 'shop-by-category' => 'Comprar por categoría', 'buy' => 'Comprar', 'out-of-stock' => 'Sin existencias', 'price' => 'Precio', 'subtotal' => 'Subtotal', 'shipping' => 'Envío', 'tax' => 'Impuestos', 'total' => 'Total', 'from' => 'Desde', 'activate-account' => 'Activa tu cuenta', 'activate-message-first' => 'Tu correo electrónico fue usado para crear una cuenta en ' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . '. Por favor continúa en el siguiente enlace para activar tu cuenta.', 'activate-message-last' => 'Si tú no creaste esta cuenta, no es necesaria ninguna acción de tu parte. La cuenta permanecerá inactiva.', 'reset-password' => 'Cambia tu contraseña', 'reset-message-first' => 'Alguien solicitó restablecer la contraseña para tu cuenta en ' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . '. Por favor continúa en el siguiente enlace para restablecer tu contraseña.', 'reset-message-last' => 'Si tú no solicitaste restablecer la contraseña, no es necesaria ninguna acción de tu parte.', 'qty' => 'Cant: ', 'redirecting' => 'Redirigiendo...', 'continue-to-paypal' => 'Continuar con PayPal', 'notification-account' => 'No se ha establecido ningún usuario. <a href="' . url('panel') . '/install" title="Página de instalación de panel">Crea una cuenta ahora.</a>.', 'notification-login' => '¡Finaliza la configuración de tu tienda! <a href="#user">Inicia sesión</a> para continuar.', 'notification-options' => 'No se han configurado las opciones de tu tienda. <a href="' . url('panel') . '/pages/shop/edit" title="Opciones de tienda">Define ajustes de tipo de moneda, envío e impuestos aquí.</a>.', 'notification-category' => 'No cuentas con ningúna categoría de productos. <a href="' . url('panel') . '/pages/shop/add" title="Crea una nueva categoría">Crea tu primera categoría aquí:</a>.', 'notification-product-first' => 'No cuentas con ningún producto. <a href="' . url('panel') . '/pages/', 'notification-product-last' => '/add" title="Crea un nuevo producto">Crea tu primer producto con el Tablero</a>.', 'notification-license' => 'Esta tienda no cuenta con una clave de licencia Shopkit. Asegúrate de agregar una en el archivo <strong>config.php</strong> antes de que la página web esté en línea.', 'notification-discount' => 'Tu código de descuento <strong><code>' . s::get('discountCode') . '</code></strong> se aplicará al momento de pagar.', 'notification-giftcertificate' => 'Tu certficado de regalo <strong><code>' . s::get('giftCertificateCode') . '</code></strong> se aplicará al momento de pagar.', 'discount-code-help' => 'Usa este código de descuento cada vez que inicies sesión.', 'notification-login-failed' => 'Lo sentimos, no hemos podido iniciar tu sesión. La contraseña o el correo electrónico son incorrectos.', 'view-cart' => 'Ver carrito', 'edit-page' => 'Editar página', 'edit-shop' => 'Configuración de la tienda', 'edit-design' => 'Diseño', 'dashboard' => 'Tablero', 'view-orders' => 'Ver órdenes', 'my-account' => 'Mi cuenta', 'logout' => 'Cerrar sesión', 'bill-to' => 'Cobrar a', 'invoice' => 'Nota de Compra', 'transaction-id' => 'ID de transacción', 'order-notification-subject' => '[' . $site->title() . '] Nuevo pedido realizado', 'order-notification-message' => 'Alguien realizó un pedido desde tu tienda en ' . server::get('server_name') . '. Administra los detalles de transacción aquí:', 'order-error-subject' => '[' . $site->title() . '] Problema con una nueva orden', 'order-error-message-update' => "El pago ha sido recibido, pero algo salió mal en el último paso de la transacción.\n\nLos detalles del cliente no se han guardado, el inventario no se actualizó correctamente, o no se envió la notificación de tu orden.\n\nConoce los detalles de la transacción aquí:", 'order-error-message-tamper' => "El pago ha sido recibido, pero no concuerda con la orden que fue realizada.\n\nConoce los detalles de la transacción aquí:", 'new-customer' => '¿Cliente nuevo?', 'forgot-password' => 'Olvidé mi contraseña', 'subpages' => 'Páginas', 'search-shop' => 'Buscar tienda', 'search' => 'Buscar', 'phone' => 'Teléfono', 'email' => 'Correo Electrónico', 'address' => 'Dirección', 'prev' => 'Anterior', 'next' => 'Siguiente', 'view-grid' => 'Ver cuadrícula', 'account-success' => 'Tu información ha sido actualizada.', 'account-failure' => 'Lo sentimos, algo salió mal. Por favor asegúrate de que toda la información sea correcta, incluyendo tu correo electrónico.', 'account-delete-error' => 'Lo sentimos, tu cuenta no pudo ser eliminada.', 'account-reset' => 'Por favor elige una nueva contraseña y asegúrate de que tu información esté actualizada.', 'password-help' => 'Dejar en blanco para mantenerlo igual', 'update' => 'Actualizar', 'delete-account' => 'Eliminar cuenta', 'delete-account-text' => 'Comprendo que eliminar mi cuenta es una acción permanente. No hay forma de deshacer esta acción, y mi cuenta será eliminada para siempre. Los registros de transacciones que contengan mi dirección de correo electrónico y otros detalles serán guardadas.', 'delete-account-verify' => 'Eliminar mi cuenta. Sí, estoy seguro.', 'username-no-account' => 'El nombre de usuario no puede ser cambiado.', 'discount-code' => 'Código de descuento', 'no-cart-items' => '¡No tienes nada en tu carrito!', 'product' => 'Producto', 'quantity' => 'Cantidad', 'delete' => 'Eliminar', 'update-country' => 'Actualizar país', 'update-shipping' => 'Actualizar Envío', 'free-shipping' => 'Envío gratuito', 'sandbox-message' => 'Actualmente estás en modo de prueba. Esta transacción no será una compra real.', 'pay-now' => 'Pagar ahora', 'pay-later' => 'Pagar después', 'empty-cart' => 'Vaciar carrito', 'discount' => 'Descuento', 'discount-apply' => 'Aplicar Descuento', 'gift-certificate' => 'Certificado de Regalo', 'code-apply' => 'Aplicar Código', 'remaining' => 'Restante', 'no-tax' => 'Sin impuestos', 'no-shipping' => 'Sin Envío', 'terms-conditions' => 'Al continuar con esta transacción, estás de acuerdo con los', 'order-details' => 'Detalles de la orden', 'personal-details' => 'Detalles personales', 'confirm-order' => 'Confirmar orden', 'mailing-address' => 'Dirección de envío', 'no-orders' => 'Aún no has realizado ninguna orden.', 'no-auth-orders' => 'Para ver órdenes asociadas a tu correo electrónico, por favor <a href="#user">regístrate o inicia sesión.</a>.', 'no-filtered-orders' => 'No hay órdenes con este estatus. <a href="orders">Volver a la lista completa</a>.', 'products' => 'Productos', 'status' => 'Estatus', 'download-invoice' => 'Descargar Nota de Compra (PDF)', 'download-files' => 'Descargar Archivos', 'download-file' => 'Descargar Archivo', 'download-expired' => 'Descarga ha expirado', 'view-on-paypal' => 'Ver en PayPal', 'pending' => 'Pendiente', 'paid' => 'Pagado', 'shipped' => 'Enviado', 'filter' => 'Filtro', 'related-products' => 'Productos relacionados', 'register-success' => 'Gracias, tu cuenta ha sido registrada. Recibirás un correo electrónico con instrucciones para activar tu cuenta.', 'register-failure' => 'Lo sentimos, algo salió mal. Vuelve a intentarlo.', 'register-failure-email' => 'Introduzca una dirección de correo electrónico.', 'register-failure-fullname' => 'Proporcione su nombre completo.', 'register-failure-country' => 'Por favor seleccione su país.', 'register-failure-verification' => 'Lo sentimos, no pudimos enviar su correo electrónico de verificación de cuenta. Póngase en contacto con el propietario de la tienda directamente para activar su cuenta.', 'register-duplicate' => 'Lo sentimos, actualmente ya hay una cuenta con ese dirección de correo electrónico.', 'reset-submit' => 'Restablecer contraseña', 'reset-success' => 'Recibirás un correo electrónico con las instrucciones para restablecer tu contraseña.', 'reset-error' => 'Lo sentimos, no pudimos encontrar esa cuenta.', 'no-search-results' => 'Lo sentimos, no hay resultados para tu búsqueda.']);
Exemplo n.º 16
0
 /**
  * Registers all routes
  *
  * @param array $routes New routes
  * @return array
  */
 public function routes($routes = array())
 {
     // extend the existing routes
     if (!empty($routes) and is_array($routes)) {
         return $this->options['routes'] = array_merge($this->options['routes'], $routes);
     }
     $routes = $this->options['routes'];
     $kirby = $this;
     $site = $this->site();
     if ($site->multilang()) {
         foreach ($site->languages() as $lang) {
             $routes[] = array('pattern' => ltrim($lang->url . '/(:all?)', '/'), 'method' => 'ALL', 'lang' => $lang, 'action' => function ($path = null) use($kirby, $site) {
                 return $site->visit($path, $kirby->route->lang->code());
             });
         }
         // fallback for the homepage
         $routes[] = array('pattern' => '/', 'method' => 'ALL', 'action' => function () use($kirby, $site) {
             // check if the language detector is activated
             if ($kirby->option('language.detect')) {
                 if (s::get('language') and $language = $kirby->site()->sessionLanguage()) {
                     // $language is already set but the user wants to
                     // select the default language
                     $referer = r::referer();
                     if (!empty($referer) && str::startsWith($referer, $this->urls()->index())) {
                         $language = $kirby->site()->defaultLanguage();
                     }
                 } else {
                     // detect the user language
                     $language = $kirby->site()->detectedLanguage();
                 }
             } else {
                 // always use the default language if the detector is disabled
                 $language = $kirby->site()->defaultLanguage();
             }
             // redirect to the language homepage if necessary
             if ($language->url != '/' and $language->url != '') {
                 go($language->url());
             }
             // plain home pages
             return $site->visit('/', $language->code());
         });
     }
     // tinyurl handling
     $routes['tinyurl'] = $this->component('tinyurl')->route();
     // home redirect
     $routes['homeRedirect'] = array('pattern' => $this->options['home'], 'action' => function () {
         redirect::send(page('home')->url(), 307);
     });
     // plugin assets
     $routes['pluginAssets'] = array('pattern' => 'assets/plugins/(:any)/(:all)', 'method' => 'GET', 'action' => function ($plugin, $path) use($kirby) {
         $root = $kirby->roots()->plugins() . DS . $plugin . DS . 'assets' . DS . $path;
         $file = new Media($root);
         if ($file->exists()) {
             return new Response(f::read($root), f::extension($root));
         } else {
             return new Response('The file could not be found', f::extension($path), 404);
         }
     });
     // all other urls
     $routes['others'] = array('pattern' => '(:all)', 'method' => 'ALL', 'action' => function ($path = null) use($site, $kirby) {
         // visit the currently active page
         $page = $site->visit($path);
         // react on errors for invalid URLs
         if ($page->isErrorPage() and $page->uri() != $path) {
             // get the filename
             $filename = rawurldecode(basename($path));
             $pagepath = dirname($path);
             // check if there's a page for the parent path
             if ($page = $site->find($pagepath)) {
                 // check if there's a file for the last element of the path
                 if ($file = $page->file($filename)) {
                     go($file->url());
                 }
             }
             // return the error page if there's no such page
             return $site->errorPage();
         }
         return $page;
     });
     return $routes;
 }
Exemplo n.º 17
0
 /**
  * @todo rework
  */
 static function current()
 {
     if (s::get('language')) {
         return s::get('language');
     }
     $lang = str::split(server::get('http_accept_language'), '-');
     $lang = str::trim(a::get($lang, 0));
     $lang = l::sanitize($lang);
     s::set('language', $lang);
     return $lang;
 }
Exemplo n.º 18
0
 public static function current()
 {
     $cookey = cookie::get('kirby');
     $username = s::get('auth.username');
     if (empty($cookey) or $cookey !== s::get('auth.key')) {
         static::logout();
         return false;
     }
     if (s::get('auth.secret') !== sha1($username . $cookey)) {
         static::logout();
         return false;
     }
     if (s::get('auth.ua') !== visitor::ua()) {
         static::logout();
         return false;
     }
     // keep logged in for one week max.
     if (s::get('auth.created') < time() - 60 * 60 * 24 * 7) {
         static::logout();
         return false;
     }
     // find the logged in user by token
     if ($user = site()->user($username)) {
         return $user;
     } else {
         return false;
     }
 }
Exemplo n.º 19
0
/**
 * Checks / returns a csrf token
 *
 * @param string $check Pass a token here to compare it to the one in the session
 * @return mixed Either the token or a boolean check result
 */
function csrf($check = null)
{
    // make sure a session is started
    s::start();
    if (is_null($check)) {
        $token = str::random(64);
        s::set('csrf', $token);
        return $token;
    }
    return $check === s::get('csrf') ? true : false;
}
Exemplo n.º 20
0
 /**
  * Creates a new Uniform instance.
  *
  * @param string $id The unique ID of this form.
  * @param array $options Array of uniform options, including the actions.
  */
 public function __construct($id, $options)
 {
     if (empty($id)) {
         throw new Error('No Uniform ID was given.');
     }
     $this->id = $id;
     $this->erroneousFields = array();
     $this->options = array('guard' => a::get($options, 'guard', 'honeypot'), 'required' => a::get($options, 'required', array()), 'validate' => a::get($options, 'validate', array()), 'actions' => a::get($options, 'actions', array()));
     // required fields will also be validated by default
     $this->options['validate'] = a::merge($this->options['validate'], $this->options['required']);
     // initialize output array with the output of the plugin itself
     $this->actionOutput = array('_uniform' => array('success' => false, 'message' => ''));
     // the token is stored as session variable until the form is sent
     // successfully
     $this->token = s::get($this->id);
     if (!$this->token) {
         $this->generateToken();
     }
     // get the data to be sent (if there is any)
     $this->data = get();
     if ($this->requestValid()) {
         if (empty($this->options['actions'])) {
             throw new Error('No Uniform actions were given.');
         }
         if ($this->dataValid()) {
             // uniform is done, now it's the actions turn
             $this->actionOutput['_uniform']['success'] = true;
         }
     }
 }
Exemplo n.º 21
0
 /**
  * Registers all routes
  *
  * @param array $routes New routes
  * @return array
  */
 public function routes($routes = array())
 {
     // extend the existing routes
     if (!empty($routes) and is_array($routes)) {
         return $this->options['routes'] = array_merge($this->options['routes'], $routes);
     }
     $routes = $this->options['routes'];
     $kirby = $this;
     $site = $this->site();
     if ($site->multilang()) {
         foreach ($site->languages() as $lang) {
             $routes[] = array('pattern' => ltrim($lang->url . '/(:all?)', '/'), 'method' => 'ALL', 'lang' => $lang, 'action' => function ($path = null) use($kirby, $site) {
                 return $site->visit($path, $kirby->route->lang->code());
             });
         }
         // fallback for the homepage
         $routes[] = array('pattern' => '/', 'method' => 'ALL', 'action' => function () use($kirby, $site) {
             // check if the language detector is activated
             if ($kirby->option('language.detect')) {
                 if (s::get('language') and $language = $kirby->site()->sessionLanguage()) {
                     // $language is already set but the user wants to
                     // select the default language
                     $referer = r::referer();
                     if (!empty($referer) && str::startsWith($referer, $this->urls()->index())) {
                         $language = $kirby->site()->defaultLanguage();
                     }
                 } else {
                     // detect the user language
                     $language = $kirby->site()->detectedLanguage();
                 }
             } else {
                 // always use the default language if the detector is disabled
                 $language = $kirby->site()->defaultLanguage();
             }
             // redirect to the language homepage if necessary
             if ($language->url != '/' and $language->url != '') {
                 go($language->url());
             }
             // plain home pages
             return $site->visit('/', $language->code());
         });
     }
     // tinyurl handling
     if ($this->options['tinyurl.enabled']) {
         $routes['tinyurl'] = array('pattern' => $this->options['tinyurl.folder'] . '/(:any)/(:any?)', 'action' => function ($hash, $lang = null) use($site) {
             // make sure the language is set
             $site->visit('/', $lang);
             // find the page by it's tiny hash
             if ($page = $site->index()->findBy('hash', $hash)) {
                 go($page->url($lang));
             } else {
                 return $site->errorPage();
             }
         });
     }
     // all other urls
     $routes['others'] = array('pattern' => '(:all)', 'method' => 'ALL', 'action' => function ($path = null) use($site) {
         // visit the currently active page
         $page = $site->visit($path);
         // react on errors for invalid URLs
         if ($page->isErrorPage() and $page->uri() != $path) {
             // get the filename
             $filename = basename($path);
             $pagepath = dirname($path);
             // check if there's a page for the parent path
             if ($page = $site->find($pagepath)) {
                 // check if there's a file for the last element of the path
                 if ($file = $page->file($filename)) {
                     // TODO: put asset pipe here
                     // redirect to the real file url to make this snappy
                     go($file->url());
                 }
             }
             // return the error page if there's no such page
             return $site->errorPage();
         }
         return $page;
     });
     return $routes;
 }
Exemplo n.º 22
0
 /**
  * Re-generates and returns the obfuscated captcha of the `calc` guard.
  * 
  * @return string
  */
 public function captcha()
 {
     $this->generateCaptcha();
     return str::encode(s::get($this->id . '-captcha-label'));
 }
Exemplo n.º 23
0
<?php

l::set(['username' => 'Benutzername', 'password' => 'Passwort', 'login' => 'Einloggen', 'register' => 'Registrieren', 'honeypot-label' => 'Sie dieses Feld nicht ausfüllen. (Spamschutz)', 'email-address' => 'E-Mail Adresse', 'first-name' => 'Vorname', 'last-name' => 'Nachname', 'full-name' => 'Voller Name', 'country' => 'Land', 'country-help' => 'Um die Versandkosten zu kalkulieren', 'shop-by-category' => 'Einkaufen nach Kategorie', 'buy' => 'Kaufen', 'out-of-stock' => 'Ausverkauft', 'price' => 'Preis', 'subtotal' => 'Zwischensumme', 'shipping' => 'Versand', 'tax' => 'Umsatzsteuer', 'total' => 'Insgesamt', 'from' => 'Von', 'activate-account' => 'Aktiviere deinen Konto', 'activate-message-first' => 'Ihre E-Mail-Adresse wurde verwendet, um ein Konto bei ' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . ' zu erstellen. Folgen Sie bitte den unten stehenden Link Ihr Konto zu aktivieren.', 'activate-message-last' => 'Wenn Sie dieses Konto nicht erstellt haben, wird keine Aktion Ihrerseits erforderlich. Das Konto wird inaktiv bleiben.', 'reset-password' => 'Setze dein Passwort zurück', 'reset-message-first' => 'Jemand bat um ein Zurücksetzen des Kennworts für Ihr Konto bei ' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . '. Folgen Sie bitte den unten stehenden Link zum Zurücksetzen des Passworts.', 'reset-message-last' => 'Wenn Sie dieses Passwort-Reset angefordert hat, wird keine Aktion Ihrerseits erforderlich.', 'qty' => 'Anz.: ', 'redirecting' => 'Weiterleiten...', 'continue-to-paypal' => 'Weiter zu PayPal', 'phone' => 'Telefon', 'email' => 'E-Mail', 'address' => 'Adresse', 'notification-account' => 'Sie haben noch keine Benutzer angelegt. <a href="' . url('panel') . '/install" title="Installationsseite">Benutzer anlegen</a>.', 'notification-login' => 'Lassen Sie uns beenden Sie Ihren Shop einrichten! <a href="#user">Melden Sie</a> sich an, um fortzufahren.', 'notification-options' => 'Sie haben noch keine Shop-Optionen angelegt. <a href="' . url('panel') . '/pages/shop/edit" title="Shop-Optionen">Währung, Versand, und Umsatzsteuer definieren</a>.', 'notification-category' => 'Sie haben noch keine Produkt-Kategorien angelegt. <a href="' . url('panel') . '/pages/shop/edit" title="Kategorie anlegen">Erste Kategorie anlegen</a>.', 'notification-product-first' => 'Sie haben noch keine Produkt angelegt. <a href="' . url('panel') . '/pages/', 'notification-product-last' => '/add" title="Produkt anlegen">Erstellen Sie Ihr erstes Produkt mit dem Armaturenbrett</a>.', 'notification-product' => 'Sie haben keine Produkte. <a href="' . url('panel') . '/pages/shop/edit" title="Neues Produkt erstellen">Erstes Produkt im Dashboard anlegen</a>.', 'notification-license' => 'Dieser Shop hat keine Shopkit-Lizenz. Geben Sie den Lizenzschlüssen in der <strong>config.php</strong> Datei ein, bevor Sie die Website live schalten.', 'notification-code' => 'Ihr Rabatt-Code <strong><code>' . s::get('discountCode') . '</code></strong> wird an der Kasse aktiviert werden.', 'discount-code-help' => 'Verwenden Sie diesen Rabatt Code jedes Mal, wenn Sie sich anmelden.', 'notification-login-failed' => 'Leider können wir konnte Sie nicht anmelden in. Entweder ist das Kennwort oder E-Mail-Adresse nicht richtig ist.', 'view-cart' => 'Warenkorb anzeigen', 'edit-page' => 'Seite bearbeiten', 'edit-shop' => 'Shop Einstellungen', 'edit-design' => 'Design', 'dashboard' => 'Dashboard', 'view-orders' => 'Bestellungen anzeigen', 'my-account' => 'Mein Benutzerkonto', 'logout' => 'Ausloggen', 'bill-to' => 'Rechnung an', 'invoice' => 'Rechnung', 'transaction-id' => 'Transaktions-ID', 'new-customer' => 'Neuer Kunde?', 'forgot-password' => 'Passwort vergessen', 'subpages' => 'Seiten', 'search-shop' => 'Shop durchsuchen', 'search' => 'Suchen', 'prev' => 'Zurück', 'next' => 'Weiter', 'view-grid' => 'Gitteransicht', 'account-success' => 'Ihre Informationen wurden aktualisiert.', 'account-failure' => 'Entschuldigung, das hat nicht funktioniert. Bitte stellen Sie sicher, dass alle Informationen korrekt eingegeben wurden, insbesondere die E-Mail Adresse.', 'account-delete-error' => 'Entschuldigung, das Benutzerkonto konnte nicht gelöscht werden.', 'account-reset' => 'Bitte wählen Sie ein neues Passwort und stellen Sie sicher, dass Ihre Informationen sind up-to-date.', 'password-help' => 'Leerlassen um das Passwort beizubehalten', 'update' => 'Aktualisieren', 'delete-account' => 'Benutzerkonto löschen', 'delete-account-text' => 'Wenn Sie auf diesen Button klicken, gibt es kein Zurück mehr. Ihr Benutzerkonto wird unumkehrbar gelöscht.', 'delete-account-verify' => 'Benutzerkonto löschen. Ich bin mir sicher.', 'username-no-account' => 'Der Benutzername konnte nicht geändert werden.', 'discount-code' => 'Rabattcode', 'no-cart-items' => 'Keine Artikel im Warenkorb!', 'product' => 'Produkt', 'quantity' => 'Anzahl', 'delete' => 'Löschen', 'update-country' => 'Land ändern', 'update-shipping' => 'Aktualisierung Versand', 'free-shipping' => 'Kostenloser Versand', 'sandbox-message' => 'Sie befinden sich im Sandbox-Modus. Dieser Einkauf wird nicht berechnet.', 'pay-now' => 'Jetzt bezahlen', 'pay-later' => 'Später bezahlen', 'empty-cart' => 'Leerer Warenkorb', 'discount' => 'Rabatt', 'discount-apply' => 'Bewerben Code', 'no-tax' => 'Keine Steuer', 'no-shipping' => 'Kostenloser Versand', 'no-orders' => 'Sie haben noch keine Einkäufe getätigt.', 'no-auth-orders' => 'Um die Einkäufe über Ihre E-Mail Adresse einzusehen, müssen Sie sich <a href="#user">registrieren oder einloggen</a>.', 'products' => 'Produkte', 'status' => 'Status', 'download-invoice' => 'Rechnung herunterladen (PDF)', 'view-on-paypal' => 'Auf PayPal anzeigen', 'pending' => 'Ausstehend', 'paid' => 'Bezahlt', 'shipped' => 'Verschickt', 'related-products' => 'Ähnliche Produkte', 'register-success' => 'Vielen Dank, Ihr Benutzerkonto wurde registriert! Sie können sich nun <a href="#user">einloggen</a>.', 'register-failure' => 'Entschuldigung, das hat nicht funktioniert. Bitte stellen Sie sicher, dass alle Informationen korrekt eingegeben wurden, insbesondere die E-Mail Adresse.', 'register-duplicate' => 'Entschuldigung, es gibt bereits ein Benutzerkonto mit diesem Benutzername oder dieser E-Mail Adresse.', 'reset-submit' => 'Passwort zurücksetzen', 'reset-success' => 'Sie erhalten eine E-Mail mit Anweisungen erhalten Sie Ihr Passwort zurücksetzen.', 'reset-error' => 'Leider konnten wir nicht das Konto finden.', 'no-search-results' => 'Entschuldigung, es gibt keine Suchergebnisse zu diesem Begriff.']);
Exemplo n.º 24
0
/**
 * Check sale price conditions on individual variants
 * Receives a $variant object
 */
function salePrice($variant)
{
    // Set vars from object
    if (gettype($variant) === 'object') {
        $salePrice = $variant->sale_price()->value ? $variant->sale_price()->value : false;
        $saleStart = $variant->sale_start()->value ? $variant->sale_start()->value : false;
        $saleEnd = $variant->sale_end()->value ? $variant->sale_end()->value : false;
        $saleCodes = $variant->sale_codes()->value ? explode(',', $variant->sale_codes()->value) : false;
    }
    // Set vars from array
    if (gettype($variant) === 'array') {
        $salePrice = isset($variant['sale_price']) ? $variant['sale_price'] : false;
        $saleStart = isset($variant['sale_start']) ? $variant['sale_start'] : false;
        $saleEnd = isset($variant['sale_end']) ? $variant['sale_end'] : false;
        $saleCodes = isset($variant['sale_codes']) ? explode(',', $variant['sale_codes']) : false;
    }
    // Check that a sale price exists and the start and end times are valid
    if ($salePrice === false) {
        return false;
    }
    if ($saleStart != false and strtotime($saleStart) > time()) {
        return false;
    }
    if ($saleEnd != false and strtotime($saleEnd) < time()) {
        return false;
    }
    // Check that the discount codes are valid
    if (count($saleCodes) and $saleCodes[0] != '') {
        $saleCodes = array_map('strtoupper', $saleCodes);
        if (in_array(s::get('discountCode'), $saleCodes)) {
            // Codes match, the product is on sale
            return $salePrice;
        } else {
            // Codes don't match. No sale for you!
            return false;
        }
    } else {
        return $salePrice;
    }
    // Something went wrong, return false
    return false;
}
Exemplo n.º 25
0
 public static function current()
 {
     $cookey = cookie::get(s::$name . '_auth');
     $username = s::get('kirby_auth_username');
     if (empty($cookey)) {
         static::unauthorize();
         return false;
     }
     if (s::get('kirby_auth_secret') !== sha1($username . $cookey)) {
         static::unauthorize();
         return false;
     }
     // find the logged in user by token
     try {
         $user = new static($username);
         return $user;
     } catch (Exception $e) {
         static::unauthorize();
         return false;
     }
 }
Exemplo n.º 26
0
<?php

// Check if user is coming from the cart page or from PayPal
s::start();
if (s::get('sendBack')) {
    // If coming from PayPal, kick them back to the cart
    s::remove('sendBack');
    go('shop/cart');
} else {
    s::set('sendBack', true);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title><?php 
echo site()->title()->html();
?>
 | <?php 
echo page('shop/cart')->title();
?>
</title>
	<style>
		body { font-family: sans-serif; font-size: 2rem; text-align: center; }
		button { font-size: 1rem; padding: 1rem; }
	</style>
</head>
<body>
	<p><?php 
Exemplo n.º 27
0
 /**
  * Returns the language which will be 
  * remembered for the next visit
  * 
  * @return Language
  */
 public function sessionLanguage()
 {
     if ($code = s::get('language') and $language = $this->languages()->find($code)) {
         return $language;
     } else {
         return null;
     }
 }
Exemplo n.º 28
0
<?php

l::set(['username' => 'Nom d\'utilisateur', 'password' => 'Mot de passe', 'login' => 'Connexion', 'register' => 'Inscription', 'honeypot-label' => 'SVP ne pas remplir ce champ. (Contrôle de spam)', 'email-address' => 'Courriel', 'first-name' => 'Prénom', 'last-name' => 'Surnom', 'full-name' => 'Nom', 'country' => 'Pays', 'country-help' => 'Afin de calculer les frais de transport', 'shop-by-category' => 'Achetez par catégorie', 'buy' => 'Achetez', 'out-of-stock' => 'Épuisé', 'price' => 'Prix', 'subtotal' => 'Sous-total', 'shipping' => 'Frais de transport', 'tax' => 'Taxes', 'total' => 'Total', 'from' => 'À partir de', 'activate-account' => 'Activez votre compte', 'activate-message-first' => 'Votre courriel est incrit chez ' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . '. Accédez au lien ci-dessous afin d\'activer votre compte.', 'activate-message-last' => 'Si vous n\'avez pas crée ce compte, aucun action n\'est requis. Le compte restera inactivé.', 'reset-password' => 'Réinitialisez votre mot de passe', 'reset-message-first' => 'Quelqu\'un a demandé un nouveau mot de passe pour votre compte chez ' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . '. Accédez au lien ci-dessous afin de réinitialiser votre mot de passe.', 'reset-message-last' => 'Si vous n\'avez pas demandé cet action, aucun action n\'est requis.', 'qty' => 'Qté: ', 'redirecting' => 'Redirection...', 'continue-to-paypal' => 'Continuez vers PayPal', 'phone' => 'Téléphone', 'email' => 'Courriel', 'address' => 'Addresse', 'notification-account' => 'Vous n\'avez aucun compte. <a href="' . url('panel') . '/install" title="Page d\'installation du panneau">Créez-en un maintenant</a>.', 'notification-login' => 'Finissons l\'installation de votre magasin! <a href="#user">Connectez-vous</a> afin de continuer.', 'notification-options' => 'Vous n\'avez pas entré les options de votre magasin. <a href="' . url('panel') . '/pages/shop/edit" title="Options de magasin">Entrez-les ici</a>.', 'notification-category' => 'Vous n\'avez aucune catégorie pour vos produits. <a href="' . url('panel') . '/pages/shop/add" title="Créez une nouvelle catégorie">Créez votre première catégorie ici</a>.', 'notification-product-first' => 'Vous n\'avez aucun produit. <a href="' . url('panel') . '/pages/', 'notification-product-last' => '/add" title="Créez un nouveau produit">Créez votre premier produit avec le tableau de bord</a>.', 'notification-license' => 'Vous n\'avez pas enregistré votre code de license. SVP mettez-le dans le fichier <strong>config.php</strong> avant de donner accès au public.', 'notification-code' => 'Votre code de rabais <strong><code>' . s::get('discountCode') . '</code></strong> sera appliqué à la caisse.', 'notification-login-failed' => 'Le connexion ne pouvait pas être complété. Soit le mot de passe soit le courriel n\'est pas bon.', 'view-cart' => 'Mon panier', 'edit-page' => 'Éditer la page', 'edit-shop' => 'Paramètres', 'edit-design' => 'Design', 'dashboard' => 'Tableau de bord', 'view-orders' => 'Commandes', 'my-account' => 'Mon compte', 'logout' => 'Déconnexion', 'bill-to' => 'Facturer à', 'invoice' => 'Facture', 'transaction-id' => 'Numéro d\'identification', 'new-customer' => 'Nouveau client?', 'forgot-password' => 'Mot de passe oublié', 'subpages' => 'Pages', 'search-shop' => 'Recherchez', 'search' => 'Recherchez', 'prev' => 'Précédent', 'next' => 'Prochain', 'view-grid' => 'Vue grille', 'account-success' => 'Votre information est mise à jour.', 'account-failure' => 'Désolé, votre information ne pouvait être mise à jour. SVP assurez-vous d\'avoir inscrit tous les infos correctement, y compris votre courriel.', 'account-reset' => 'SVP choisissez un nouveau mot de passe et assurez-vous que votre information est mise à jour.', 'account-delete-error' => 'Désolé, votre compte ne pouvait être supprimé.', 'password-help' => 'Laissez vide pour garder votre mot de passe actuel', 'update' => 'Mettre à jour', 'delete-account' => 'Supprimer mon compte', 'delete-account-text' => 'Je comprends que la suppression de mon compte est permanente. Mon compte sera supprimé à jamais. Les records de transactions, y compris mon courriel et les autres détails de commande, seront conservés.', 'delete-account-verify' => 'Supprimer mon compte. Oui, je suis certain.', 'username-no-account' => 'Le nom d\'utilisateur ne peut être changé.', 'discount-code' => 'Code de rabais', 'discount-code-help' => 'Appliquez ce code chaque fois que vous vous connectez.', 'no-cart-items' => 'Vous n\'avez rien dans votre panier!', 'product' => 'Produit', 'quantity' => 'Quantité', 'delete' => 'Supprimer', 'update-country' => 'Mettre à jour le pays', 'update-shipping' => 'Mettre à jour le transport', 'free-shipping' => 'Transport gratuit', 'sandbox-message' => 'Vous êtes dans la mode "sandbox". Cette transaction ne résultera pas en un achat réel.', 'pay-now' => 'Achetez maintenant', 'pay-later' => 'Achetez plus tard', 'empty-cart' => 'Videz le panier', 'discount' => 'Rabais', 'discount-apply' => 'Appliquez code', 'no-tax' => 'Aucun taxe', 'no-shipping' => 'Transport gratuit', 'no-orders' => 'Vous n\'avez aucun transaction.', 'no-auth-orders' => 'Afin de voir les transactions associés à votre compte, SVP <a href="#user">vous incrire ou connectez</a>.', 'products' => 'Produits', 'status' => 'État', 'download-invoice' => 'Téléchargez facture (PDF)', 'view-on-paypal' => 'Accédez sur PayPal', 'pending' => 'En attente', 'paid' => 'Payé', 'shipped' => 'Envoyé', 'related-products' => 'Produits reliés', 'register-success' => 'Merci, votre compte est inscrit! Vous recevrez un courriel afin d\'activer votre compte.', 'register-failure' => 'Désolé, votre compte ne pouvait être inscrit. SVP assurez-vous d\'avoir inscrit tous les infos correctement, y compris votre courriel.', 'register-duplicate' => 'Désolé, vore compte ne pouvait être inscrit. Il y a déja un compte avec ce nom d\'utilisateur ou courriel.', 'reset-submit' => 'Réinistialiser le mot de passe', 'reset-success' => 'Vous recevrez un courriel avec des instructions afin de réinitialiser le mot se passe.', 'reset-error' => 'Désolé, on ne pouvait pas trouver ce compte.', 'no-search-results' => 'Désolé, il n\'y a aucun résultat pour cette recherche.']);
Exemplo n.º 29
0
                            </form>
                        <?php 
        }
        ?>
                    <?php 
    }
    ?>

                    <!-- Set country -->
                    <form class="col--6  right" id="setCountry" action="" method="POST">
                        <select name="country" onChange="document.forms['setCountry'].submit();">
                            <?php 
    foreach ($countries as $c) {
        ?>
                                <option <?php 
        echo ecco(s::get('country') === $c->uid(), 'selected');
        ?>
 value="<?php 
        echo $c->countrycode();
        ?>
">
                                    <?php 
        echo $c->title();
        ?>
                                </option>
                            <?php 
    }
    ?>
                        </select>
                        <button class="btn" type="submit"><?php 
    echo l::get('update-country');
Exemplo n.º 30
0
 /**
  * @param array $data Shipping or tax data
  */
 protected function appliesToCountry(array $data)
 {
     // Check if country is in data
     if (is_array($data['countries[]']) and (in_array(s::get('country'), $data['countries[]']) or in_array('all-countries', $data['countries[]']))) {
         return true;
     }
     if (s::get('country') === $data['countries[]'] or 'all-countries' === $data['countries[]']) {
         return true;
     }
     return false;
 }