示例#1
0
 /**
  * Migrate method.
  *
  * @param boolean $version Version string.
  *
  * @return void
  */
 public static function migrate($version = null)
 {
     $query = new Query();
     $executed_migrations = Core\Utils::arrayFlatten($query->select('*')->from('migrations')->all());
     $migrations_to_execute = array();
     $dir = 'up';
     if ($version) {
         /* Migrate to specific version */
         preg_match('/[0-9]{10}$/', $version, $matches);
         if ($execute_to = $matches[0]) {
             $migrations_to_execute = $query->select('*')->from('migrations')->where('version > ?', array($execute_to))->order('version', 'desc')->all();
             if (count($migrations_to_execute) == 0) {
                 $migrations_to_execute = array_filter(self::$migrations, function ($item) use($executed_migrations, $execute_to) {
                     return !in_array($item['version'], $executed_migrations) && $item['version'] <= $execute_to;
                 });
             } else {
                 $dir = 'down';
             }
         }
     } else {
         /* Execute all new migrations */
         $migrations_to_execute = array_reverse(array_filter(self::$migrations, function ($item) use($executed_migrations) {
             return !in_array($item['version'], $executed_migrations);
         }));
     }
     foreach ($migrations_to_execute as $item) {
         DB\Migrate::$dir($item['version']);
     }
 }
示例#2
0
 public static function get_loggable_request(Request $request)
 {
     $user = self::get_user();
     $analytic_cookie = null;
     //if(!$request->hasParam('__ac')) { $analytic_cookie = self::set_analytic_cookie($request,$user); }
     //else { $analytic_cookie = $request->getParam('__ac'); }
     if (in_array(__ROUTER_PATH, self::$_skippingAjaxPaths) && $request->is_xmlHttpRequest) {
         return null;
     }
     if (self::filter_skippable_path($request->__uri)) {
         return null;
     }
     if (self::filter_skippable_agents($request->getUserAgent())) {
         return null;
     }
     $last_path = Utils::getFromSessionStore('last_path');
     if (!is_null($last_path) && $last_path == $request->__uri) {
         return null;
     }
     if (is_null($last_path)) {
         $last_path = $request->__uri;
     }
     Utils::addToSessionStore('last_path', $request->__uri);
     return array('uri' => $request->__uri, 'path' => __ROUTER_PATH, 'tson' => time(), 'agnt' => $request->getUserAgent(), 'refr' => $request->__referer, 'ajax' => $request->is_xmlHttpRequest, 'srvr' => array(''), 'rqst' => array('mthd' => $request->__method, 'ip' => $request->getRemoteAddress(), 'port' => $request->getRemotePort(), 'pb' => $request->get__PB()), 'by' => $user);
 }
示例#3
0
 /**
  * Additional validations.
  *
  * @return void
  */
 public function afterValidate()
 {
     if (!filter_var($this->email, FILTER_VALIDATE_EMAIL)) {
         $this->setError('email', 'invalid_format');
     }
     if (!$this->getError('password') && !Core\Utils::validatePassword($this->password)) {
         $this->setError('password', 'weak');
     }
 }
 public function executeControllerAction($moduleName, $controllerName, $actionName, $params = array())
 {
     $this->request->addParams($params);
     $controllerClass = Utils::toMixedCase($controllerName) . 'Controller';
     $path = APPLICATION_PATH . "/modules/{$moduleName}/controllers/{$controllerClass}.php";
     if (!file_exists($path)) {
         throw new Exception("Controller '{$controllerClass}' not found");
     }
     include_once $path;
     $controller = new $controllerClass($this->request);
     $action = Utils::toCamelCase($actionName) . 'Action';
     $controller->init($action);
     $result = $controller->{$action}();
     return $result;
 }
示例#5
0
 /**
  * Initializer. Setup paths to temporary resources.
  *
  * @param mixed $params Params from the command line.
  *
  * @return void
  */
 public static function init($params)
 {
     self::$CACHES = array('system' => 'temp/cache');
     $modes = Core\Config()->modes();
     foreach ($modes as $mode) {
         Core\Config()->setMode($mode);
         $assetsPath = Core\Config()->paths('assets');
         $assets = Core\Utils::replaceFirstOccurrence(Core\Config()->paths('root'), '', $assetsPath['distribution']);
         if (file_exists($assetsPath['distribution'] . 'js')) {
             self::$CACHES['assets'][] = $assets . 'js';
         }
         if (file_exists($assetsPath['distribution'] . 'css')) {
             self::$CACHES['assets'][] = $assets . 'css';
         }
     }
 }
 /**
  *@HttpPost()
  *@ValidateAntiForgeryToken()
  */
 public function create(LoginBindingModel $loginData)
 {
     if ($this->currentUser() != null) {
         $_SESSION['warrning'] = 'You are already logged in';
         return new RedirectActionResult('home/index');
     }
     $user = $this->shopData->getUserRepository()->getUser($loginData->getUsername());
     if (!Utils::verifyHash($loginData->getPassword(), $user->getPasswordDigest())) {
         $_SESSION['warrning'] = 'Invalid password / username';
         return new ViewResult($loginData, 'Sessions/NewSession.php');
     }
     if ($user->getBanned() == 1) {
         $_SESSION['warrning'] = 'You are banned';
         return new ViewResult($loginData, 'Sessions/NewSession.php');
     }
     $_SESSION['userId'] = $user->getId();
     $_SESSION['username'] = $user->getUsername();
     return new RedirectActionResult('home/index');
 }
示例#7
0
 /**
  * @param string $fromMail
  * @param array $recipient
  * @param path $template
  * @param array or string $body
  * @param string $templatesequence
  */
 public static function submit($fromMail, $recipients, $subject, $body, $template = null, $templatesequence = null)
 {
     try {
         $mail_queue_collection = Ds::connect(ds_mail_queue);
         $type = self::MAIL_TYPE_TEXT;
         if (!is_array($recipients)) {
             throw new Exception('recipients must be an array');
         }
         if (is_null($templatesequence)) {
             $templatesequence = md5(serialize($recipients) . '|' . $subject . '|' . time());
         }
         $tpls = $mail_queue_collection->findOne(array('tpsq' => $templatesequence));
         if (!is_null($tpls)) {
             throw new Exception('email already queued with this tpl seq - ' . $templatesequence);
         }
         if (is_array($body)) {
             if (is_null($template)) {
                 throw new Exception('template cannot be null for html email');
             }
             $type = self::MAIL_TYPE_HTML;
             $body = Utils::parseMe($template, $body);
         }
         $mailData = array('from' => $fromMail, 'subj' => $subject, 'recp' => $recipients, 'body' => $body, 'tpsq' => $templatesequence, 'type' => $type, 'qts' => time());
         $mail_queue_collection->insert($mailData);
         if (isset($mailData['_id'])) {
             if (defined('gearman_server') && defined('gearman_port')) {
                 self::invokeGearmanJob((string) $mailData['_id']);
             } else {
                 Log::write(__METHOD__ . ' gearman is not configured for this app');
             }
             throw new Exception('mail ' . (string) $mailData['_id'] . ' queued', 200);
         } else {
             throw new Exception('mail queuing failed');
         }
     } catch (Exception $e) {
         Log::write(__METHOD__ . ' ' . $e->getMessage() . ' ' . $e->getCode());
         if ($e->getCode() != 200) {
             throw $e;
         }
     }
 }
 /**
  *@HttpPost()
  *@ValidateAntiForgeryToken()
  */
 public function create(CreateUserBindingModel $newUser)
 {
     if ($this->currentUser() != null) {
         $_SESSION['warrning'] = 'You need to log out first';
         return new RedirectActionResult('home/index');
     }
     if (!$newUser->isValid()) {
         $_SESSION['warrning'] = 'Invalid register data.';
         return new ViewResult($newUser, 'Users/NewUser.php');
     }
     $existingUser = $this->shopData->getUserRepository()->getUser($newUser->getUsername());
     if ($existingUser != null) {
         $_SESSION['warrning'] = 'User with that name already exists.';
         return new ViewResult($newUser, 'Users/NewUser.php');
     }
     $hashed = Utils::digestPass($newUser->getPassword());
     $user = new User($newUser->getUsername(), $hashed, self::INITIAL_CASH);
     $user->setBanned(false);
     $user->setRegisterDate(date("Y-m-d"));
     $this->shopData->getUserRepository()->addUser($user);
     return new RedirectActionResult('sessions/newsession');
 }
示例#9
0
 /**
  * Builds the SQL part of the query.
  *
  * @param DB\Query $query Query object.
  *
  * @throws \DomainException DB Adapter does not support the required JOIN type.
  *
  * @return string
  */
 private function buildSql(DB\Query $query)
 {
     $sql = array();
     if ($query->type === 'select') {
         $sql[] = 'SELECT';
         $sql[] = $query->db_fields === 'all' ? '*' : (is_array($query->db_fields) ? implode(',', $query->db_fields) : $query->db_fields);
         $sql[] = 'FROM';
         $sql[] = $query->table;
         if ($query->join) {
             foreach ($query->join as $join) {
                 if (!in_array($join['type'], self::getSupportedJoinTypes(), true)) {
                     throw new \DomainException('DB Adapter does not support the JOIN type:' . $join['type']);
                 }
                 $sql[] = $join['type'];
                 $sql[] = 'JOIN';
                 $sql[] = Core\Config()->DB['tables_prefix'] . $join['table'];
                 if ($join['condition']) {
                     $sql[] = 'ON (' . $join['condition'] . ')';
                 }
             }
         }
         if ($query->where) {
             $sql[] = 'WHERE';
             $sql[] = implode(' AND ', array_map(function ($item) {
                 return '(' . $item . ')';
             }, $query->where));
         }
         if ($query->order) {
             $sql[] = 'ORDER BY';
             $sql[] = implode(', ', array_map(function ($item) {
                 return "{$item['field']} {$item['direction']}";
             }, $query->order));
         }
         if ($query->limit) {
             $sql[] = 'LIMIT';
             $sql[] = $query->limit;
             if ($query->offset) {
                 $sql[] = 'OFFSET';
                 $sql[] = $query->offset;
             }
         }
     } elseif ($query->type === 'insert') {
         $sql[] = 'INSERT IGNORE INTO';
         $sql[] = $query->table;
         $sql[] = '(' . implode(',', $query->db_fields) . ')';
         $sql[] = 'VALUES';
         if (isset($query->bind_params[0]) && is_array($query->bind_params[0])) {
             $sql[] = implode(',', array_map(function ($item) {
                 return '(' . implode(',', array_map(function () {
                     return '?';
                 }, $item)) . ')';
             }, $query->bind_params));
             $query->bind_params = Core\Utils::arrayFlatten($query->bind_params);
         } else {
             $sql[] = '(' . implode(',', array_map(function () {
                 return '?';
             }, $query->bind_params)) . ')';
         }
     } elseif ($query->type === 'update') {
         $sql[] = 'UPDATE';
         $sql[] = $query->table;
         $sql[] = 'SET';
         $sql[] = implode(',', array_map(function ($item) {
             return $item . ' = ?';
         }, $query->db_fields));
         $sql[] = 'WHERE';
         $sql[] = implode(' AND ', array_map(function ($item) {
             return '(' . $item . ')';
         }, $query->where));
     } elseif ($query->type === 'remove') {
         $sql[] = 'DELETE FROM';
         $sql[] = $query->table;
         $sql[] = 'WHERE';
         $sql[] = implode(' AND ', array_map(function ($item) {
             return '(' . $item . ')';
         }, $query->where));
     } elseif ($query->type === 'create_table') {
         $sql[] = 'CREATE TABLE IF NOT EXISTS';
         $sql[] = $query->table;
         $fields = array();
         foreach ($query->db_fields as $field => $attributes) {
             $is_primary_key = false;
             $attrs = $this->convertAttributes($attributes);
             if ($pos = array_search('pk', $attrs)) {
                 unset($attrs[$pos]);
                 $is_primary_key = true;
             }
             $fields[] = $field . ' ' . implode(' ', $attrs);
             if ($is_primary_key) {
                 $fields[] = 'PRIMARY KEY(' . $field . ')';
             }
         }
         $sql[] = '(' . implode(',', $fields) . ')';
         $sql[] = 'ENGINE ' . $query->table_engine;
     } elseif ($query->type === 'drop_table') {
         $sql[] = 'DROP TABLE ' . $query->table;
     } elseif ($query->type === 'add_columns') {
         $sql[] = 'ALTER TABLE';
         $sql[] = $query->table;
         $sql[] = 'ADD COLUMN';
         $fields = array();
         foreach ($query->db_fields as $field => $attributes) {
             $is_primary_key = false;
             $attrs = $this->convertAttributes($attributes);
             if ($pos = array_search('pk', $attrs)) {
                 unset($attrs[$pos]);
                 $is_primary_key = true;
             }
             $fields[] = $field . ' ' . implode(' ', $attrs);
             if ($is_primary_key) {
                 $fields[] = 'PRIMARY KEY(' . $field . ')';
             }
         }
         $sql[] = '(' . implode(',', $fields) . ')';
     } elseif ($query->type === 'drop_columns') {
         $sql[] = 'ALTER TABLE';
         $sql[] = $query->table;
         $cols = array();
         foreach ($query->db_fields as $column) {
             $cols[] = 'DROP COLUMN ' . $column;
         }
         $sql[] = implode(',', $cols);
     }
     return implode(' ', $sql);
 }
示例#10
0
 /**
  * Load labels for the controller.
  *
  * @access private
  *
  * @return void
  */
 protected function loadLabels()
 {
     $labels = self::loadLabelsFile(Core\Config()->mode('name'));
     foreach ($this->labels as $labelsFile) {
         $labels = Core\Utils::arrayExtend($labels, self::loadLabelsFile($labelsFile));
     }
     $this->labels = $labels;
 }
示例#11
0
 /**
  * Builds a sql query.
  *
  * @param DB\Query $query SQL Query.
  *
  * @throws \DomainException DB Adapter does not support the required JOIN type.
  *
  * @return string
  */
 private function buildSql(DB\Query $query)
 {
     $sql = array();
     if ($query->type === 'select') {
         $sql[] = 'SELECT';
         $sql[] = $query->db_fields === 'all' ? '*' : (is_array($query->db_fields) ? implode(',', $query->db_fields) : $query->db_fields);
         $sql[] = 'FROM';
         $sql[] = $query->table;
         if ($query->join) {
             foreach ($query->join as $join) {
                 if (!in_array($join['type'], self::getSupportedJoinTypes(), true)) {
                     throw new \DomainException('DB Adapter not supporting the required JOIN type:' . $join['type']);
                 }
                 $sql[] = $join['type'];
                 $sql[] = 'JOIN';
                 $sql[] = Core\Config()->DB['tables_prefix'] . $join['table'];
                 if ($join['condition']) {
                     $sql[] = 'ON (' . $join['condition'] . ')';
                 }
             }
         }
         if ($query->where) {
             $sql[] = 'WHERE';
             $sql[] = implode(' AND ', array_map(function ($item) {
                 return '(' . $item . ')';
             }, $query->where));
         }
         if ($query->order) {
             $sql[] = 'ORDER BY';
             $sql[] = implode(', ', array_map(function ($item) {
                 return "{$item['field']} {$item['direction']}";
             }, $query->order));
         }
         if ($query->limit) {
             $sql[] = 'LIMIT';
             $sql[] = $query->limit;
             if ($query->offset) {
                 $sql[] = 'OFFSET';
                 $sql[] = $query->offset;
             }
         }
     } elseif ($query->type === 'insert') {
         $sql[] = 'INSERT IGNORE INTO';
         $sql[] = $query->table;
         $sql[] = '(' . implode(',', $query->db_fields) . ')';
         $sql[] = 'VALUES';
         if (is_array(current($query->bind_params))) {
             $sql[] = implode(',', array_map(function ($item) {
                 return '(' . implode(',', array_map(function () {
                     return '?';
                 }, $item)) . ')';
             }, $query->bind_params));
             $query->bind_params = Core\Utils::arrayFlatten($query->bind_params);
         } else {
             $sql[] = '(' . implode(',', array_map(function () {
                 return '?';
             }, $query->bind_params)) . ')';
         }
     } elseif ($query->type === 'update') {
         $sql[] = 'UPDATE';
         $sql[] = $query->table;
         $sql[] = 'SET';
         $sql[] = implode(',', array_map(function ($item) {
             return $item . ' = ?';
         }, $query->db_fields));
         $sql[] = 'WHERE';
         $sql[] = implode(' AND ', array_map(function ($item) {
             return '(' . $item . ')';
         }, $query->where));
     } elseif ($query->type === 'remove') {
         $sql[] = 'DELETE FROM';
         $sql[] = $query->table;
         $sql[] = 'WHERE';
         $sql[] = implode(' AND ', array_map(function ($item) {
             return '(' . $item . ')';
         }, $query->where));
     }
     return implode(' ', $sql);
 }
示例#12
0
 /**
  * Setup all variables values.
  */
 protected function __construct()
 {
     $current_dir = dirname(dirname(realpath(__DIR__)));
     $this->PATHS['root'] = $current_dir . DIRECTORY_SEPARATOR;
     if (!isset($_SERVER['CONTEXT_DOCUMENT_ROOT'])) {
         $this->URLS['relative'] = str_replace('\\', '/', str_replace(realpath($_SERVER['DOCUMENT_ROOT']), '', $current_dir . '/'));
     } else {
         $this->URLS['relative'] = $_SERVER['CONTEXT_PREFIX'] . str_replace(realpath($_SERVER['CONTEXT_DOCUMENT_ROOT']), '', $current_dir . '/');
         $this->URLS['relative'] = str_replace(DIRECTORY_SEPARATOR, '/', $this->URLS['relative']);
     }
     /* Check if the request is sent over HTTPS */
     $is_SSL = Core\Utils::httpRequestIsSsl();
     $port = null;
     if (isset($_SERVER['SERVER_PORT'])) {
         $port = in_array($_SERVER['SERVER_PORT'], array('80', '443', true)) ? null : $_SERVER['SERVER_PORT'];
     }
     $this->URLS['protocol'] = 'http' . ($is_SSL ? 's' : '');
     $this->URLS['full'] = null;
     if (isset($_SERVER['SERVER_NAME'])) {
         $this->URLS['full'] = $this->URLS['protocol'] . '://' . $_SERVER['SERVER_NAME'] . $port . $this->URLS['relative'];
     }
     $this->PATHS['vendor'] = $this->PATHS['root'] . 'vendor' . DIRECTORY_SEPARATOR;
     $this->PATHS['resources'] = $this->PATHS['root'] . 'resources' . DIRECTORY_SEPARATOR;
     $this->PATHS['tmp'] = $this->PATHS['root'] . 'temp' . DIRECTORY_SEPARATOR;
     $this->PATHS['cache'] = $this->PATHS['tmp'] . 'cache' . DIRECTORY_SEPARATOR;
     $this->PATHS['public'] = $this->PATHS['root'] . 'public' . DIRECTORY_SEPARATOR;
     $this->PATHS['views']['compiled'] = $this->PATHS['cache'] . 'compiled' . DIRECTORY_SEPARATOR;
     $this->PATHS['views']['cache'] = $this->PATHS['cache'] . 'views' . DIRECTORY_SEPARATOR;
     $this->PATHS['views']['config'] = $this->PATHS['root'] . 'configurations' . DIRECTORY_SEPARATOR . SILLA_ENVIRONMENT . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR;
     /* Process modes */
     $this->MODES = $this->setupModes($this->MODES);
     /* Default mode */
     $this->setMode($this->MODES[0]);
 }
示例#13
0
 /**
  * Parses a request query string.
  *
  * @param string $httpRequestString Request string.
  * @param Routes $routes            Request routing routes.
  *
  * @static
  * @uses Core\Utils::parseHttpRequestString()
  *
  * @return array
  */
 public static function parseRequestQueryString($httpRequestString, Routes $routes)
 {
     if (Core\Config()->mode('url')) {
         $httpRequestString = trim(Core\Utils::replaceFirstOccurrence(Core\Config()->mode('url'), '', $httpRequestString), Core\Config()->ROUTER['separator']);
     } else {
         $httpRequestString = trim($httpRequestString, Core\Config()->ROUTER['separator']);
     }
     $requestElements = Core\Utils::parseHttpRequestString($httpRequestString, Core\Config()->ROUTER['separator']);
     $route = $routes->extractRoute($requestElements);
     $routedUrl = $routes->toRoute($route['pattern']);
     $elements = $route['maps_to'];
     foreach ($route['maps_to'] as $role => $value) {
         if ('*' === $value) {
             $_element = array_search(Core\Config()->ROUTER['variables_prefix'] . $role, $routedUrl);
             $elements[$role] = isset($requestElements[$_element]) ? $requestElements[$_element] : null;
         }
     }
     return $elements;
 }
 public static function csrfToken()
 {
     static $token = null;
     if ($token == null) {
         $token = Utils::getToken(80);
         setcookie('CSRF-TOKEN', $token, time() + 1800, '/');
     }
     $attributes = array('type' => 'hidden', 'name' => 'csrfToken', 'value' => $token);
     $tag = new Tag('input', $attributes, null);
     return $tag->getHtml();
 }
示例#15
0
 /**
  * Delete associated objects and records.
  *
  * @access private
  *
  * @return void
  */
 private function deleteAssociations()
 {
     /* Delete objects of the habtm associations */
     foreach ($this->hasAndBelongsToMany as $k => $rel) {
         if (isset($this->{$k}) && is_array($this->{$k})) {
             $association_table = $rel['table'];
             $key = $rel['key'];
             $relative_key = $rel['relative_key'];
             $primary_key = $this->{static::$primaryKeyField};
             /* Gets the id of the original associated objects */
             $query = new DB\Query();
             $result = Core\DB()->run($query->select($relative_key)->from($association_table)->where("{$key} = ?", array($primary_key)));
             if ($result) {
                 $original_ids = Core\Utils::arrayFlatten($result);
                 /* Fills the ids of the current associated objects */
                 $passed_ids = array();
                 foreach ($this->{$k} as $item) {
                     $passed_ids[] = is_object($item) ? $item->id : $item;
                 }
                 /* Get the difference */
                 $to_delete = array_diff($original_ids, $passed_ids);
                 /* Delete if there are differences */
                 if (!empty($to_delete)) {
                     /* @TODO implement the "where in (smt., smt.)" in the DB driver */
                     Core\DB()->run($query->remove()->from($association_table)->where("{$key} = ?", array($primary_key))->where("{$relative_key} IN (" . implode(',', array_map(function () {
                         return '?';
                     }, $to_delete)) . ")", $to_delete));
                 }
             }
         }
     }
 }
示例#16
0
 /**
  * Prepares a query for execution.
  *
  * @param string $sql         SQL Query.
  * @param array  $bind_params Parameters.
  *
  * @throws \InvalidArgumentException The number of values passed and placeholders mismatch.
  * @throws \LogicException           Error in the prepared statement.
  *
  * @return \mysqli_stmt|false
  */
 private function prepare($sql, array $bind_params = array())
 {
     if (substr_count($sql, '?') !== count($bind_params)) {
         throw new \InvalidArgumentException('The number of values passed and placeholders mismatch');
     }
     if ($stmt = $this->link->prepare($sql)) {
         $reflection = new \ReflectionClass('mysqli_stmt');
         $method = $reflection->getMethod('bind_param');
         $param_types = array_reduce($bind_params, function ($carry) {
             $carry .= 's';
             return $carry;
         });
         array_unshift($bind_params, $param_types);
         $method->invokeArgs($stmt, Core\Utils::arrayToRefValues($bind_params));
     } else {
         throw new \LogicException($this->link->error);
     }
     return $stmt;
 }
示例#17
0
 /**
  * Reset access action.
  *
  * @param Request $request Current router request.
  *
  * @return void
  */
 public function renew(Request $request)
 {
     $user = Models\CMSUser::find()->where('DATE_ADD(updated_on, INTERVAL 60 MINUTE) > UTC_TIMESTAMP() AND SHA1(CONCAT(password, ?, email)) = ?', array(Core\Config()->USER_AUTH['cookie_salt'], $request->get('id')))->first();
     if ($user) {
         $new_password = Core\Utils::generatePassword(10);
         if ($user->save(array('password' => $new_password), true)) {
             $this->new_password = $new_password;
         }
     } else {
         $request->redirectTo(array('controller' => 'authentication'));
     }
 }