Since: 1.0
Author: Loris Tissino (loris.tissino@gmail.com)
Exemplo n.º 1
0
 /**
  * @param Helpers $helpers
  */
 public static function helper($helpers)
 {
     $escape = $helpers->get('escape');
     return function ($attr) use($escape) {
         $renderer = new static($attr, $escape);
         return $renderer->toString();
     };
 }
Exemplo n.º 2
0
 public function run()
 {
     writeln("<comment>Create Docker machine {$this->name}</comment>");
     $output = runLocally("docker-machine create -d virtualbox {$this->name}", 999);
     writeln("<comment>Docker-machine {$this->name} created</comment>");
     $this->ip = Helpers::getMachineIp();
 }
 public function userIsAuthorized($action)
 {
     // Dafür sorgen, dass eine Anfrage ggf. auf das Login weitergeleitet wird,
     // wenn die Session abgelaufen ist und nach erfolgtem Login nahtlos auf
     // die angeforderte Seite weitergeleitet wird
     if ($this->module_name != 'login' && !Auth::isLoggedIn()) {
         $_SESSION['pixelmanager_temp_login_redirect']['uri'] = $_SERVER['REQUEST_URI'];
         $_SESSION['pixelmanager_temp_login_redirect']['get'] = $_GET;
         $_SESSION['pixelmanager_temp_login_redirect']['post'] = $_POST;
         $_SESSION['pixelmanager_temp_login_redirect']['request'] = $_REQUEST;
         Helpers::redirect(Config::get()->baseUrl . 'admin/html-output/login');
     } else {
         if ($this->module_name != 'login') {
             if (isset($_SESSION['pixelmanager_temp_login_redirect'])) {
                 $_GET = $_SESSION['pixelmanager_temp_login_redirect']['get'];
                 $_POST = $_SESSION['pixelmanager_temp_login_redirect']['post'];
                 $_REQUEST = $_SESSION['pixelmanager_temp_login_redirect']['request'];
                 unset($_SESSION['pixelmanager_temp_login_redirect']);
             }
         }
     }
     // Wenn es sich um ein Zusatzmodul handelt, ggf. auf Zugangsberechtigung prüfen
     if ($this->isCustomBackendModule()) {
         $can_user_access = $this->canUserAccessCustomBackendModule();
         if ($can_user_access === false) {
             $this->accessDenied();
         }
         return $can_user_access;
     }
     // Anfrage wurde bis jetzt nicht abgefangen, also erstmal annehmen, dass der Zugriff erlaubt ist
     return true;
 }
Exemplo n.º 4
0
/**
* This function is beign used to load info that's needed for the login page.
* it will try to auto-login, this can only be used while ingame, the web browser sends additional cookie information that's also stored in the open_ring db.
* We will compare the values and if they match, the user will be automatically logged in!
* @author Daan Janssens, mentored by Matthew Lagoe
*/
function login()
{
    global $INGAME_WEBPATH;
    global $WEBPATH;
    if (helpers::check_if_game_client()) {
        //check if you are logged in ingame, this should auto login
        $result = Helpers::check_login_ingame();
        if ($result) {
            //handle successful login
            $_SESSION['user'] = $result['name'];
            $_SESSION['id'] = WebUsers::getId($result['name']);
            $_SESSION['ticket_user'] = serialize(Ticket_User::constr_ExternId($_SESSION['id']));
            //go back to the index page.
            header("Cache-Control: max-age=1");
            if (Helpers::check_if_game_client()) {
                header('Location: ' . $INGAME_WEBPATH);
            } else {
                header('Location: ' . $WEBPATH);
            }
            throw new SystemExit();
        }
    }
    $pageElements['ingame_webpath'] = $INGAME_WEBPATH;
    $GETString = "";
    foreach ($_GET as $key => $value) {
        $GETString = $GETString . $key . '=' . $value . "&";
    }
    if ($GETString != "") {
        $GETString = '?' . $GETString;
    }
    $pageElements['getstring'] = $GETString;
    return $pageElements;
}
Exemplo n.º 5
0
 /**
  * @param string $publicKey
  * @param string $keyHandle
  * @param string|NULL $certificate
  */
 public function __construct($publicKey, $keyHandle, $certificate = NULL)
 {
     $this->publicKey = $publicKey;
     Helpers::publicKey2Pem($this->publicKey);
     $this->keyHandle = $keyHandle;
     $this->certificate = $certificate;
 }
Exemplo n.º 6
0
 public function Create($request, $response, $args)
 {
     //init database
     $db = DB::getInstance();
     //gat user data
     $user = json_decode($request->getBody()->getContents());
     if (empty($user->first_name) || empty($user->last_name) || empty($user->email) || empty($user->password)) {
         echo "ERROR";
     } else {
         //check email exit ?
         $exists = $db->user('email = ?', $user->email)->fetch();
         if ($exists) {
             echo json_encode(array('success' => false, 'message' => 'Email already in use'));
         } else {
             $data = array();
             $data['first_name'] = Helpers::sanitize($user->first_name);
             $data['last_name'] = Helpers::sanitize($user->last_name);
             $data['email'] = Helpers::sanitize($user->email);
             $data['password'] = Helpers::EncrytPassword(Helpers::sanitize($user->password));
             //insert in db
             $db->user->insert($data);
             echo json_encode(array('success' => true));
         }
     }
     return $response->withHeader('Content-type', 'application/json');
 }
Exemplo n.º 7
0
 public static function getInstance()
 {
     if (null === self::$instance) {
         self::$instance = new self();
     }
     return self::$instance;
 }
 private function beforeActionExecute()
 {
     $userId = (string) HttpContext::getInstance()->getSession()->userId;
     if ($userId !== "") {
         Helpers::redirect('');
     }
 }
Exemplo n.º 9
0
 /**
  * Displays information about an exercise (code, assignment, etc.).
  * @param integer $id the ID of the model to be displayed
  */
 public function actionInfo($k = '', $code = '', $hash = '', $defaultcode = '')
 {
     $exerciseInfoForm = new ExerciseInfoForm();
     $exerciseInfoForm->code = $defaultcode;
     $model = null;
     $files = null;
     if (isset($_POST['ExerciseInfoForm'])) {
         $exerciseInfoForm->attributes = $_POST['ExerciseInfoForm'];
         if ($exerciseInfoForm->validate()) {
             if (Yii::app()->user->isGuest) {
                 // if a students looks up an exercise using the code, it means that he/she has received the code...
                 $exerciseInfoForm->exercise->increaseStatus(Exercise::STATUS_ACKNOWLEDGED);
             }
             $this->redirect(array('exercise/info', 'code' => $exerciseInfoForm->exercise->code, 'hash' => Helpers::hash($exerciseInfoForm->exercise->id, 12)));
         }
     }
     if ($code) {
         $model = $this->loadModelByCode($code);
         if ($model && Helpers::hash($model->id, 12) != $hash) {
             $model = null;
         }
         if ($model === null) {
             Yii::app()->user->setFlash('flash-error', 'Our bad. We couldn\'t find an exercise with that code.');
             $this->redirect(array('exercise/info', 'defaultcode' => $code));
         }
     } elseif ($k) {
         $model = $this->loadModelByInfokey($k);
     }
     $this->render('info', array('model' => $model, 'files' => $this->getFilesOfExercise($model), 'code' => $code, 'exerciseInfoForm' => $exerciseInfoForm));
 }
Exemplo n.º 10
0
 /**
  * Loads Target Model for the Comment
  * It needs to be a SiContentBehavior Object
  *
  * @return type
  */
 private function loadTargetModel()
 {
     // Fast lane
     if ($this->cachedLoadedTarget != null) {
         return $this->cachedLoadedTarget;
     }
     // Request Params
     $targetModelClass = Yii::app()->request->getParam('model');
     $targetModelId = (int) Yii::app()->request->getParam('id');
     $targetModelClass = Yii::app()->input->stripClean(trim($targetModelClass));
     if ($targetModelClass == "" || $targetModelId == "") {
         throw new CHttpException(500, Yii::t('CommentModule.controllers_CommentController', 'Model & Id Parameter required!'));
     }
     if (!Helpers::CheckClassType($targetModelClass, 'HActiveRecordContent')) {
         throw new CHttpException(500, Yii::t('CommentModule.controllers_CommentController', 'Invalid target class given'));
     }
     $model = call_user_func(array($targetModelClass, 'model'));
     $target = $model->findByPk($targetModelId);
     if (!$target instanceof HActiveRecordContent) {
         throw new CHttpException(500, Yii::t('CommentModule.controllers_CommentController', 'Invalid target class given'));
     }
     if ($target == null) {
         throw new CHttpException(404, Yii::t('CommentModule.controllers_CommentController', 'Target not found!'));
     }
     // Check if we can read the target model, so we can comment it?
     if (!$target->content->canRead(Yii::app()->user->id)) {
         throw new CHttpException(403, Yii::t('CommentModule.controllers_CommentController', 'Access denied!'));
     }
     // Create Fastlane:
     $this->cachedLoadedTarget = $target;
     return $target;
 }
 public function __construct(OLEFile $oleFile)
 {
     $oleStream = $oleFile->Get_OLE_Stream();
     fseek($oleStream, 0);
     $this->oleHeaderSignature = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 8))));
     $this->oleHeaderCLSID = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 16))));
     $this->oleMinorVersion = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 2))));
     $this->oleMajorVersion = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 2))));
     $this->oleByteOrder = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 2))));
     $this->oleSectorShift = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 2))));
     $this->oleMiniSectorShift = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 2))));
     $this->oleReserved = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 6))));
     $this->numDirSectors = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 4))));
     $this->numFATSectors = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 4))));
     $this->firstDirSectorLoc = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 4))));
     $this->transactionSigNum = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 4))));
     $this->miniStreamCutoffSize = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 4))));
     $this->firstMiniFATSectorLoc = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 4))));
     $this->numMiniFATSectors = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 4))));
     $this->firstDIFATSectorLoc = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 4))));
     $this->numDIFATSectors = hexdec(Helpers::Fix_Hex(bin2hex(fread($oleStream, 4))));
     $this->difat = Helpers::Hex_Str_To_Array(Helpers::Fix_Hex(bin2hex(fread($oleStream, 436)), 8), 8);
     $this->oleStream = $oleStream;
     fseek($this->oleStream, 0);
 }
Exemplo n.º 12
0
 /**
  * 
  *
  */
 function __construct()
 {
     parent::__construct();
     $this->javascript_callbacks = is_array($GLOBALS['JAVASCRIPT_CALLBACKS']) ? $GLOBALS['JAVASCRIPT_CALLBACKS'] : array('uninitialized', 'loading', 'loaded', 'interactive', 'complete', 'failure', 'success');
     $this->ajax_options = array_merge(array('before', 'after', 'condition', 'url', 'asynchronous', 'method', 'insertion', 'position', 'form', 'with', 'update', 'script'), $this->javascript_callbacks);
     $this->javascript_path = dirname(__FILE__) . '/javascripts';
 }
Exemplo n.º 13
0
 /**
  * Loads WP-palvelu features
  */
 public static function load()
 {
     /**
      * Show WP-Palvelu notifications if this is WP-Palvelu instance
      */
     if (Helpers::isProduction() or Helpers::isShadow()) {
         add_action('admin_notices', array(__CLASS__, 'showAdminNotification'));
     }
     /**
      * Hide update nofications if this is not development
      */
     if (!Helpers::isDevelopment()) {
         add_action('admin_menu', array(__CLASS__, 'hideUpdateNotifications'));
         add_filter('wp_get_update_data', array(__CLASS__, 'hideUpdateData'));
     }
     /**
      * Ask browser not cache anything if blog is in development, non-public or debug
      * This makes everyones life easier when clients don't know how to reset their browser cache from old stylesheets
      */
     if (Helpers::isDevelopment() || !Helpers::isPublic() || WP_DEBUG) {
         add_action('send_headers', array(__CLASS__, 'sendNoCacheHeaders'));
     }
     /**
      * Send proper headers after unsuccesful login
      */
     add_action('wp_login_failed', array(__CLASS__, 'changeHttpCodeToUnauthorized'));
 }
Exemplo n.º 14
0
 /**
  * Use current dataprovider to perform seacrh
  * by given query and return view with results.
  * 
  * @return View
  */
 public function byQuery()
 {
     $input = (string) Input::get('q');
     if (!$input || Str::length($input) <= 1) {
         return View::make('search.results')->withTerm('');
     }
     if (is_a($this->search, 'Lib\\Services\\Search\\DbSearch')) {
         $encoded = $input;
     } else {
         $encoded = urlencode($input);
     }
     $clean = e($input);
     //make search cache section name
     $section = 'search' . $this->provider;
     if ($encoded) {
         if (Helpers::hasSuperAccess()) {
             $results = $this->search->byQuery($encoded);
         } else {
             if ($this->options->useCache()) {
                 $results = $this->cache->get($section, md5($encoded));
                 if (!$results || count($results) == 0) {
                     $results = $this->search->byQuery($encoded);
                     $this->cache->put($section, md5($encoded), $results);
                 }
             } else {
                 $results = $this->search->byQuery($encoded);
             }
         }
         return View::make('search.results')->withData($results)->withTerm($clean);
     }
     return View::make('search.results')->withTerm($clean);
 }
Exemplo n.º 15
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     //Coger eventos del día siguiente
     $events = Evento::getNextDayEventos()->get();
     foreach ($events as $e) {
         //Coger los gcm_regids de los voluntarios asignados al evento que pueden recibir notificaciones
         $registration_ids = Asistencia::getUsersToNotificate($e->ideventos)->get()->lists('gcm_token');
         $title = 'AFI Perú - Evento';
         $message = 'Recordatorio de evento: ' . $e->nombre . ' - ' . $e->fecha_evento;
         $type = 1;
         $m = ['title' => $title, 'message' => $message, 'type' => $type];
         $response = Helpers::pushGCM($registration_ids, $m);
         //$this->info(var_dump($response));
     }
     ///Coger todos los padrinos
     $sponsors = Padrino::getActivePadrinosPushInfo()->get();
     foreach ($sponsors as $s) {
         //Si el padrino tiene activado el push de pagos y tiene registadro su gcm_token
         if ($s->push_pagos && $s->gcm_token) {
             //Buscar si hay una deuda pendiente para el día siguiente
             $fee = CalendarioPago::getCalendarioPagoPendienteNextDayByPadrino($s->idpadrinos)->first();
             if ($fee) {
                 //$this->info(var_dump($s->gcm_regid));
                 $title = 'AFI Perú - Padrino';
                 $message = 'Recordatorio de pago: ' . $fee->vencimiento;
                 $type = 2;
                 $m = ['title' => $title, 'message' => $message, 'type' => $type];
                 $response = Helpers::pushGCM(array($s->gcm_token), $m);
                 //$this->info(var_dump($response));
             }
         }
     }
 }
Exemplo n.º 16
0
 /**
  * @return Dotenv\Dotenv Bedrock Settings
  */
 public static function getDotEnv()
 {
     $dotenv = new \Dotenv\Dotenv(Helpers::getProjectDir());
     $dotenv->load();
     //$dotenv->required(['DB_NAME', 'DB_USER', 'DB_PASSWORD']);
     return $dotenv;
 }
Exemplo n.º 17
0
 /**
  *   Erstellt ein PDO Objekt
  *
  * @return PDO pdo
  */
 public static function getPDO()
 {
     if (self::$pdo == null) {
         $config = Config::getArray();
         if (!isset($config["database"])) {
             Helpers::fatalError("No database configuration found.");
         }
         $host = '';
         if (isset($config['database']['host'])) {
             $host = 'host=' . $config['database']['host'] . ';';
         }
         $port = '';
         if (isset($config['database']['port'])) {
             $port = 'port=' . $config['database']['port'] . ';';
         }
         $socket = '';
         if (isset($config['database']['socket'])) {
             $socket = 'unix_socket=' . $config['database']['socket'] . ';';
         }
         $dsn = 'mysql:dbname=' . $config["database"]["name"] . ';' . $host . $port . $socket . 'charset=utf8;';
         try {
             $pdo = new PDO($dsn, $config["database"]["user"], $config["database"]["password"], array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
         } catch (PDOException $e) {
             Helpers::fatalError("Could no connect to the database: " . $e->getMessage());
         }
         self::$pdo = $pdo;
     }
     return self::$pdo;
 }
Exemplo n.º 18
0
 /**
  * Displays a grid of titles with pagination.
  *
  * @return View
  */
 public function index()
 {
     $input = Input::all();
     $data = $this->title->titleIndex($input, 'movie');
     if (isset($input['genre'])) {
         $genre = $input['genre'];
         $data = $data->genres($data, $genre);
     } else {
         $genre = 'all';
     }
     if (isset($input['relevance'])) {
         $relevance = $input['relevance'];
         $data = $data->relevance($data, $relevance);
     } else {
         $relevance = 'all';
     }
     if (isset($input['yearFrom'])) {
         $yearFrom = $input['yearFrom'];
     } else {
         $yearFrom = Title::getYearOldest();
     }
     if (isset($input['yearTo'])) {
         $yearTo = $input['yearTo'];
     } else {
         $yearTo = Title::getYearNewest();
     }
     $data = $data->yearsRange($data, $yearFrom, $yearTo);
     $yearFrom = Title::getYearOldest();
     $yearTo = Title::getYearNewest();
     if (isset($input['view'])) {
         if ($input['view'] > 1 || $input['view'] < 0) {
             $view = 0;
         } else {
             $view = $input['view'];
         }
     } else {
         $view = 0;
     }
     // Get only online movies
     if (!Helpers::hasAccess('titles.create')) {
         $data = $data->online($data);
     }
     if (isset($input['numRows'])) {
         $numRows = $input['numRows'];
     } else {
         $numRows = 18;
     }
     if (isset($input['sortBy'])) {
         $sortBy = Title::sortByString($input['sortBy']);
     } else {
         $sortBy = Title::sortByString('lastAdded');
     }
     $data = $data->orderBy($sortBy['field'], $sortBy['direction'])->paginate($numRows);
     if (isset($input['sortBy'])) {
         $sortBy = $input['sortBy'];
     } else {
         $sortBy = 'lastAdded';
     }
     return View::make('titles.index')->withData($data)->withView($view)->withGenre($genre)->withRelevance($relevance)->withYearfrom($yearFrom)->withYearto($yearTo)->withNumrows($numRows)->withSortby($sortBy);
 }
Exemplo n.º 19
0
 /**
  * Initializes config given the assosiative array of 
  **/
 public static function init($config)
 {
     if (isset(self::$config)) {
         trigger_error("Helpers is already initialized", E_USER_ERROR);
     }
     self::$config = $config;
 }
Exemplo n.º 20
0
 public function __construct()
 {
     Cowl::timer('cowl init');
     @session_start();
     // I know that the @-notation is frowned upon, but adding it to session_start saves us unnecessary warnings
     Cache::setDir(COWL_CACHE_DIR);
     Current::initialize(COWL_DIR);
     if (COWL_CLI) {
         $this->parseCLIPath();
     } else {
         $this->parseRequestPath();
     }
     Cowl::timer('cowl set defaults');
     // Get and set all directories for various things.
     list($commands_dir, $model_dir, $validators_dir, $library_dir, $view_dir, $helpers_dir, $helpers_app_dir, $drivers_dir, $app_dir, $view_layout_dir, $validator_error_messages, $lang) = Current::$config->gets('paths.commands', 'paths.model', 'paths.validators', 'paths.library', 'paths.view', 'paths.helpers', 'paths.helpers_app', 'paths.drivers', 'paths.app', 'paths.layouts', 'paths.validator_messages', 'lang');
     Controller::setDir($commands_dir);
     DataMapper::setMappersDir($model_dir);
     DataMapper::setObjectsDir($model_dir);
     Validator::setPath($validators_dir);
     Validator::loadStrings($validator_error_messages, $lang);
     Templater::setBaseDir($view_dir);
     Templater::setLayoutDir($view_layout_dir);
     Library::setPath($library_dir);
     Helpers::setPath($helpers_dir);
     Helpers::setAppPath($helpers_app_dir);
     Database::setPath($drivers_dir);
     StaticServer::setDir($app_dir);
     Cowl::timerEnd('cowl set defaults');
     Cowl::timer('cowl plugins load');
     Current::$plugins = new Plugins();
     Cowl::timerEnd('cowl plugins load');
     // Load default helper
     Helpers::load('standard', 'form');
     Cowl::timerEnd('cowl init');
 }
Exemplo n.º 21
0
 public static function string_differences($string_1, $string_2)
 {
     $differences = array();
     if (Helpers::hasUtf8Bom($string_1)) {
         $differences[] = "String 1 has Utf8 Bom, now stripped";
         $string_1 = Helpers::stripUtf8Bom($string_1);
     }
     if (Helpers::hasUtf8Bom($string_2)) {
         $differences[] = "String 2 has Utf8 Bom, now stripped";
         $string_2 = Helpers::stripUtf8Bom($string_2);
     }
     $string_1 = htmlspecialchars($string_1);
     $string_2 = htmlspecialchars($string_2);
     $len_str_1 = strlen($string_1);
     $len_str_2 = strlen($string_2);
     if ($len_str_1 !== $len_str_2) {
         $differences[] = "String Lengths '{$len_str_1}' <> '{$len_str_2}' are different";
     }
     $first_20_chars_1 = substr($string_1, 0, 20);
     $first_20_chars_2 = substr($string_2, 0, 20);
     if ($first_20_chars_1 !== $first_20_chars_2) {
         $differences[] = "First 20 characters of strings '{$first_20_chars_1}' !== '{$first_20_chars_2}' are different";
     }
     $last_20_chars_1 = substr($string_1, -20);
     $last_20_chars_2 = substr($string_2, -20);
     if ($last_20_chars_1 !== $last_20_chars_2) {
         $differences[] = "Last 20 characters of strings '{$last_20_chars_1}' <> '{$last_20_chars_2}' are different";
     }
     $error_html = implode('<br>', $differences);
     return $error_html;
 }
Exemplo n.º 22
0
 /**
  * Opens up magically a form
  *
  * @param  string $typeAsked  The form type asked
  * @param  array  $parameters Parameters passed
  * @return string             A form opening tag
  */
 public function open($typeAsked, $parameters)
 {
     $method = 'POST';
     $secure = false;
     $action = array_get($parameters, 0);
     $attributes = array_get($parameters, 1);
     // If classic form
     if ($typeAsked == 'open') {
         $type = Former::$defaultFormType;
     } else {
         // Look for HTTPS form
         if (str_contains($typeAsked, 'secure')) {
             $typeAsked = str_replace('secure', null, $typeAsked);
             $secure = true;
         }
         // Look for file form
         if (str_contains($typeAsked, 'for_files')) {
             $typeAsked = str_replace('for_files', null, $typeAsked);
             $attributes['enctype'] = 'multipart/form-data';
         }
         // Calculate form type
         $type = trim(str_replace('open', null, $typeAsked), '_');
         if (!in_array($type, $this->availableTypes)) {
             $type = Former::$defaultFormType;
         }
     }
     // Add the final form type
     $attributes = Helpers::addClass($attributes, 'form-' . $type);
     // Store it
     $this->type = $type;
     // Open the form
     return \Form::open($action, $method, $attributes, $secure);
 }
Exemplo n.º 23
0
 public static function formatHtml($mask)
 {
     $args = func_get_args();
     return preg_replace_callback('#%#', function () use(&$args, &$count) {
         return Helpers::escapeHtml($args[++$count]);
     }, $mask);
 }
Exemplo n.º 24
0
 public function solve()
 {
     $input_string = Helpers::getStringInputForDay(3);
     $input_array = str_split($input_string);
     $map = [];
     $x = 0;
     $y = 0;
     $map[$x][$y] = 1;
     $houses = 1;
     foreach ($input_array as $coord) {
         switch ($coord) {
             case '^':
                 $y++;
                 break;
             case '>':
                 $x++;
                 break;
             case 'v':
                 $y--;
                 break;
             case '<':
                 $x--;
                 break;
         }
         if (isset($map[$x][$y])) {
             $map[$x][$y]++;
         } else {
             $map[$x][$y] = 1;
             $houses++;
         }
     }
     echo $houses;
 }
Exemplo n.º 25
0
 /**
  * Renders the accordion
  *
  * @return string
  */
 public function render()
 {
     if (!$this->name) {
         $this->name = Helpers::generateId($this);
     }
     $attributes = new Attributes($this->attributes, ['class' => 'panel-group', 'id' => $this->name]);
     $string = "<div {$attributes}>";
     $count = 0;
     foreach ($this->contents as $item) {
         $itemAttributes = array_key_exists('attributes', $item) ? $item['attributes'] : [];
         $itemAttributes = new Attributes($itemAttributes, ['class' => 'panel panel-default']);
         $string .= "<div {$itemAttributes}>";
         $string .= "<div class='panel-heading'>";
         $string .= "<h4 class='panel-title'>";
         $string .= "<a data-toggle='collapse' data-parent='#{$this->name}' " . "href='#{$this->name}-{$count}'>{$item['title']}</a>";
         $string .= "</h4>";
         $string .= "</div>";
         $bodyAttributes = new Attributes(['id' => "{$this->name}-{$count}", 'class' => 'panel-collapse collapse']);
         if ($this->opened == $count) {
             $bodyAttributes->addClass('in');
         }
         $string .= "<div {$bodyAttributes}>";
         $string .= "<div class='panel-body'>{$item['contents']}</div>";
         $string .= "</div>";
         $string .= "</div>";
         $count++;
     }
     $string .= "</div>";
     return $string;
 }
Exemplo n.º 26
0
 /**
  * Unquote a string and optionally return the quote removed.
  *
  * from http://razzed.com/2009/01/14/top-5-most-useful-non-native-php-functions/
  *
  * @param  string   $s
  *                              A string to unquote
  * @param  string   $quotes
  *                              A list of quote pairs to unquote
  * @param  string   $left_quote
  *                              Returns the quotes removed
  * @return Unquoted string, or same string if quotes not found
  */
 public static function unquote($s, $quotes = "''\"\"", &$left_quote = null)
 {
     if (is_array($s)) {
         $result = array();
         foreach ($s as $k => $ss) {
             $result[$k] = Helpers::unquote($ss, $quotes, $left_quote);
         }
         return $result;
     }
     if (strlen($s) < 2) {
         $left_quote = false;
         return $s;
     }
     $q = substr($s, 0, 1);
     $qleft = strpos($quotes, $q);
     if ($qleft === false) {
         $left_quote = false;
         return $s;
     }
     $qright = $quotes[$qleft + 1];
     if (substr($s, -1) === $qright) {
         $left_quote = $quotes[$qleft];
         return substr($s, 1, -1);
     }
     return $s;
 }
Exemplo n.º 27
0
 static function parse_get(&$data, $template)
 {
     # match any gets
     preg_match('/([\\S\\s]*?)get[\\s]+?["\']\\/?(.*?)\\/?["\']\\s+?do\\s+?([\\S\\s]+?)end\\b([\\S\\s]*)$/', $template, $template_parts);
     # run the replacements on the pre-"get" part of the partial
     $template = self::parse($data, $template_parts[1]);
     # turn route into file path
     $file_path = Helpers::url_to_file_path($template_parts[2]);
     # store current data
     $current_data = $data;
     # if the route exists...
     if (file_exists($file_path)) {
         # check for any nested matches
         $template_parts = self::test_nested_matches($template_parts, 'get[\\s]+?["\']\\/?.*?\\/?["\']\\s+?do', 'end\\b');
         # set data object to match file path
         $data = AssetFactory::get($file_path);
         # run the replacements on the inner-"get" part of the partial
         $template .= self::parse($data, $template_parts[3]);
     }
     # revert context back to original
     $data = $current_data;
     # run the replacements on the post-"get" part of the partial
     $template .= self::parse($data, $template_parts[4]);
     return $template;
 }
Exemplo n.º 28
0
 static function &create($file_path)
 {
     #
     # a little bit of magic here to find any classes which extend 'Asset'
     #
     self::get_asset_subclasses();
     # if the file path isn't passed through as a string, return an empty data array
     $data = array();
     if (!is_string($file_path)) {
         return $data;
     }
     # split by file extension
     preg_match('/\\.([\\w\\d]+?)$/', $file_path, $split_path);
     if (isset($split_path[1]) && !is_dir($file_path)) {
         # set the default asset type
         $asset = 'Asset';
         # loop through our asset_subclasses to see if this filetype should be handled in a special way
         foreach (self::$asset_subclasses as $asset_type => $identifiers) {
             # if a match is found, set $asset to be the name of the matching class
             if (in_array(strtolower($split_path[1]), $identifiers)) {
                 $asset = $asset_type;
             }
         }
         # create a new asset and return its data
         $asset = new $asset($file_path);
         return $asset->data;
     } else {
         # new page
         $page = new Page(Helpers::file_path_to_url($file_path));
         return $page->data;
     }
 }
Exemplo n.º 29
0
 public static function buildRoute($route)
 {
     $result = static::snakeCase(array_shift($route));
     return $result . join("", array_map(function ($e) {
         return "['" . Helpers::snakeCase($e) . "']";
     }, $route));
 }
 public function my_schedule()
 {
     if (Auth::check()) {
         $data["inside_url"] = Config::get('app.inside_url');
         $data["user"] = Session::get('user');
         $data["actions"] = Session::get('actions');
         if (in_array('side_mi_horario', $data["actions"])) {
             $current_ay = AcademicYear::getCurrentAcademicYear();
             if (!$current_ay) {
                 return View::make('schedule/academic_year_error', $data);
             }
             $student = $data["user"]->student;
             $data["enrollment_info"] = $student->getCurrentEnrollment();
             $data["level"] = $data["enrollment_info"]->level;
             $data["schedules_data"] = $data["level"]->schedules()->orderBy('initial_hour')->get();
             return View::make('schedule/my_schedule', $data);
         } else {
             // Llamo a la función para registrar el log de auditoria
             $log_description = "Se intentó acceder a la ruta '" . Request::path() . "' por el método '" . Request::method() . "'";
             Helpers::registerLog(10, $log_description);
             Session::flash('error', 'Usted no tiene permisos para realizar dicha acción.');
             return Redirect::to('/dashboard');
         }
     } else {
         return View::make('error/error');
     }
 }