public static function value($key) { if (self::get()->useGlobalConfig) { $value = GlobalConfig::value($key) ?: self::get()->{$key}; } else { $value = self::get()->{$key}; } $value = str_replace(['{APP_ROOT}', '{DIRECTORY_SEPARATOR}'], [APP_ROOT, DIRECTORY_SEPARATOR], $value); if (is_a(App::get(), WebApp::className())) { return str_replace(['{WEB_ROOT}', '{MODULE_FOLDER}'], [WebApp::get()->request()->getWebRoot(), WebApp::get()->request()->getModulePath()], $value); } return $value; }
/** * Logs with an arbitrary level. * * @param mixed $level * @param string $message * @param array $context * @return null */ public function log($level, $message, array $context = array()) { if (!$this->filePath) { // no file selected return; } if ($this->_writeFailure) { // there are problems with writing to file; no need to keep retrying return; } if (!$this->_path) { if (!is_a(App::get(), '\\mpf\\WebApp')) { $this->_path = $this->filePath; } else { $this->_path = str_replace(['{MODULE}', '{CONTROLLER}'], [WebApp::get()->request()->getModule(), WebApp::get()->request()->getController()], $this->filePath); } $this->_path = str_replace("{APP_ROOT}", APP_ROOT, $this->_path); } if (!in_array($level, $this->visibleLevels)) { return; } if (Levels::DEBUG == $level && isset($context['fromClass']) && in_array($context['fromClass'], $this->ignoredClasses)) { return; } $details = date("Y-m-d H:i ") . (isset($context['fromClass']) ? $context['fromClass'] : '') . " {$message}\n"; if (in_array($level, $this->detaliedLevels)) { foreach ($context as $k => $v) { if ('fromClass' == $k) { continue; } if (is_string($v) || is_numeric($v)) { $details .= " {$k} => " . $v . "\n"; } elseif (is_bool($v)) { $details .= " {$k} => " . ($v ? 'true' : 'false') . "\n"; } elseif (is_a($v, '\\Exception')) { /* @var $v \Exception */ $details .= " Location: " . $v->getFile() . ' [' . $v->getLine() . ']:'; $details .= "\n" . $v->getTraceAsString(); } else { $details .= " {$k} => " . print_r($v, true); } } } if (false === @file_put_contents($this->_path, $details . "\n", FILE_APPEND)) { $this->_writeFailure = true; } }
/** * @param User $user * @param string $source * @param boolean $rememberMe * @return boolean */ protected function checkUserLogin(User $user, $source, $rememberMe) { if ($user->status == User::STATUS_NEW) { if (is_null($user->lastconfirmationmail_date) || $user->lastconfirmationmail_date < date('Y-m-d H:i:s', strtotime('-5 minutes'))) { // if confirmation email was older than 5 minutes then allow it to resend it User::$allowConfirmationEmailResend = true; if (isset($_POST['resend'])) { $user->resendConfirmationEmail(); } } if (!isset($_POST['resend'])) { Messages::get()->error('Email address was not yet confirmed! Check your emails and access received link to activate the account!'); } return false; } if ($user->status == User::STATUS_BLOCKED) { Messages::get()->error('This account has been banned! Please contact an admin if you think this is a mistake!'); return false; } if ($user->status == User::STATUS_DELETED) { Messages::get()->error('This account has been recently deleted! If you want to recover it please contact an admin. An account is permanently removed ' . User::DELETE_ACCOUNT_AFTER_X_DAYS . ' days after it was deleted!'); return false; } $this->connected = true; $this->setState('id', $user->id); $this->setState('name', $user->name); $this->setState('email', $user->email); $this->setState('icon', $user->icon ?: 'default.png'); $this->setState('status', $user->status); $this->setState('title', $user->title ? $user->title->title : '- no title -'); if ($user->joinuser_id) { $all = User::findAllByAttributes(['joinuser_id' => $user->joinuser_id]); $this->setState('mergedIDs', ArrayHelper::get()->transform($all, 'id')); } $this->setRights($groups = $user->getGroupsList()); $this->debug("Saved groups: " . implode(", ", $groups)); $user->last_login = date('Y-m-d H:i:s'); $user->last_login_source = $source; $user->save(); if ($rememberMe) { Cookie::get()->set(App::get()->shortName . $this->cookieKey, $user->email, $this->cookieTimeout); } if (!trim($user->name)) { // fill last details if they were not already saved $this->debug('need auto register'); WebApp::get()->request()->setController('user'); WebApp::get()->request()->setAction('registerauto'); } return true; }
/** * Clear lock for selected action and command; * @param $actionName * @param null $command */ protected function clearLock($actionName, $command = null) { $command = $command ?: str_replace('\\', '_', get_class($this)); App::get()->redis()->hdel(App::get()->shortName . self::REDIS_LOCKS, $command . ':' . $actionName); }
/** * Check if selected table exists. * @param $tableName * @return bool * @throws \Exception */ public function tableExists($tableName) { $cache = []; if (App::get()->cacheExists('mpf:PDOConnection:tableList')) { $cache = App::get()->cacheValue('mpf:PDOConnection:tableList'); if (!is_array($cache)) { $cache = []; // a fix for old wrong values; } if (isset($cache[$tableName])) { return $cache[$tableName]; } } $res = $this->queryAssoc("SHOW TABLES LIKE :table", array(':table' => $tableName)); $cache[$tableName] = (bool) $res; App::get()->cacheSet('mpf:PDOConnection:tableList', $cache); return (bool) $res; }
public function beforeDelete() { App::get()->sql()->table('users2groups')->where('group_id = :group')->setParam(':group', $this->id)->delete(); //delete connections from this group to users return parent::beforeDelete(); }
public static function addEntry($user, $action, $comment = null) { $webApp = is_a(App::get(), '\\mpf\\WebApp'); return self::insert(['user_id' => $user, 'action' => $action, 'admin_id' => $webApp ? WebApp::get()->user()->id == $user ? null : WebApp::get()->user()->id : null, 'comment' => $comment, 'ip' => $webApp ? $_SERVER['REMOTE_ADDR'] : null]); }
public static function updateCache() { if (self::$configValues) { return self::$configValues; } $all = self::findAll(); $cache = array(); foreach ($all as $conf) { $cache[$conf->name] = $conf->value; } App::get()->cacheSet('app:GlobalConfig', $cache); if (!App::get()->cacheExists('app:GlobalConfig')) { // if no cache is used then set it here in a local array. self::$configValues = $cache; } return $cache; }
protected function init($config = array()) { $this->website = $this->website ?: App::get()->title; return parent::init($config = array()); }
/** * Before deleting user delete every other tables connected to it. * @return bool|void */ public function beforeDelete() { App::get()->sql()->table('users2groups')->where("user_id = :id")->setParam(':id', $this->id)->delete(); UserHistory::deleteAllByAttributes(['user_id' => $this->id]); UserConfig::deleteAllByAttributes(['user_id' => $this->id]); return parent::beforeDelete(); }
protected function getMessage($level, $message, $context) { unset($context['fromClass']); if (ltrim(get_class(App::get()), '\\') == 'mpf\\WebApp') { $context['WebApp_URL'] = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; $context['WebApp_Referer'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '-'; $context['WebApp_User Agent'] = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '-'; $context['WebApp_IP'] = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '-'; $context['WebApp_POST'] = isset($_POST) ? $this->getArrayList($_POST) : '-'; $context['WebApp_SESSION'] = isset($_POST) ? $this->getArrayList($_SESSION) : '-'; $context['WebApp_COOKIE'] = isset($_POST) ? $this->getArrayList($_COOKIE) : '-'; } elseif (ltrim(get_class(App::get()), '\\') == 'mpf\\ConsoleApp') { $context['ConsoleApp_Command'] = implode(' ', $_SERVER['argv']); $context['ConsoleApp_User'] = exec('whoami'); } $context = implode("<br />", $this->getContextLines($context)); return <<<MESSAGE <h3 style="color:{$this->getLevelMessageColor($level)}">{$message}</h3> <div style="border: 1px solid #888; background: #cfcfdf; color:#444; line-height: 20px; padding:5px;">{$context}</div> MESSAGE; }
public function beforeSave() { if (is_a(App::get(), '\\mpf\\WebApp') && WebApp::get()->request()->getModule()) { if (!UserAccess::get()->isSectionAdmin($this->section_id)) { Messages::get()->error("You don't have access to edit this user group!"); return false; } } return parent::beforeSave(); }
/** * Return connection to SQL Database * @return \mpf\datasources\sql\PDOConnection */ public static function getDb() { return App::get()->sql(); }
public function delete($key) { return Connection::get()->hdel(App::get()->shortName . $this->key, key); }
/** * Set a new set of rights for active user. * @param $rights * @return $this */ public function setRights($rights) { $this->_rights = $rights; Session::get()->updateListItem(App::get()->shortName . $this->sessionKey, 'rights', $this->_rights, array('vars' => array(), 'rights' => array())); return $this; }
/** * Starts a new application using selected configuration; * This method should be called from the index file like this: * * [php] * \mpf\ConsoleApp::run([ * 'startTime' => microtime(true), * 'autoload' => $autoload // <- an instance of composer autoload class; * ]); * [/php] * * `\mpf\ConsoleApp` should be replaced with the app that should be run at that time. * * This method wil handle all Exceptions and then will call the `::start()` method defined by the instantiated child class and return the instance of the object. * * @param string[] $config * @return static */ public static function run($config = []) { try { $class = get_called_class(); self::$_instance = new $class($config); self::$_instance->start(); return self::$_instance; } catch (\ErrorException $ex) { if (in_array($ex->getSeverity(), array(E_WARNING, E_USER_WARNING))) { self::get()->warning($ex->getMessage(), ['File' => $ex->getFile(), 'Line' => $ex->getLine(), 'Type' => $ex->getSeverity(), 'Trace' => $ex->getTraceAsString(), 'Class' => get_class($ex)]); } elseif (in_array($ex->getSeverity(), array(E_NOTICE, E_USER_NOTICE, E_USER_DEPRECATED))) { self::get()->notice($ex->getMessage(), ['File' => $ex->getFile(), 'Line' => $ex->getLine(), 'Type' => $ex->getSeverity(), 'Trace' => $ex->getTraceAsString(), 'Class' => get_class($ex)]); } else { self::get()->error($ex->getMessage(), ['File' => $ex->getFile(), 'Line' => $ex->getLine(), 'Type' => $ex->getSeverity(), 'Trace' => $ex->getTraceAsString(), 'Class' => get_class($ex)]); } } catch (\Exception $ex) { self::get()->error($ex->getMessage(), array('exception' => $ex)); } }
public function model() { $date = date('Y-m-d'); $time = date('H:i'); $model = <<<MODEL <?php /** * Created by MPF Framework. * Date: {$date} * Time: {$time} */ namespace {$this->namespace}; use mpf\\datasources\\sql\\DataProvider; use mpf\\datasources\\sql\\DbModel; use mpf\\datasources\\sql\\DbRelations; use mpf\\datasources\\sql\\ModelCondition; /** * Class {$this->class} * @package {$this->namespace} {$this->getModelProperties()} */ class {$this->class} extends DbModel { /** * Get database table name. * @return string */ public static function getTableName() { return "{$this->table}"; } /** * Get list of labels for each column. This are used by widgets like form, or table * to better display labels for inputs or table headers for each column. * @return array */ public static function getLabels() { return [ {$this->getModelLabels()} ]; } /** * Return list of relations for current model * @return array */ public static function getRelations(){ return [ {$this->getModelRelations()} ]; } /** * List of rules for current model * @return array */ public static function getRules(){ return [ ["{$this->getColumnsList(false)}", "safe", "on" => "search"] ]; } /** * Gets DataProvider used later by widgets like \\mpf\\widgets\\datatable\\Table to manage models. * @return \\mpf\\datasources\\sql\\DataProvider */ public function getDataProvider() { \$condition = new ModelCondition(['model' => __CLASS__]); foreach ([{$this->getColumnsList(true)}] as \$column) { if (\$this->\$column) { \$condition->compareColumn(\$column, \$this->\$column, true); } } return new DataProvider([ 'modelCondition' => \$condition ]); } } MODEL; echo $model; $prefixes = App::get()->autoload()->getPrefixesPsr4(); $found = false; $path = ''; foreach ($prefixes as $pref => $paths) { if (0 === strpos($this->namespace, $pref)) { $path = $paths[0] . '/' . str_replace('\\', DIRECTORY_SEPARATOR, substr($this->namespace, strlen($pref))); $found = true; break; } } if (!$found) { $this->error("Path for {$this->namespace} not found!"); return false; } $path .= '/' . str_replace('\\', DIRECTORY_SEPARATOR, $this->class) . '.php'; $this->debug('File name: ' . $path); if (file_exists($path)) { $this->error('File already exists!'); return false; } file_put_contents($path, $model); }
/** * Creates a new section + default user groups + a single user title. Use "Main" name if you only have one. * @param string $name * @param int $userId * @return int */ public static function createNew($name = "Main", $userId) { $section = new self(); $section->name = $name; $section->owner_user_id = $userId; if (!$section->save()) { return false; } if ("Main" == $name) { App::get()->debug("Main section detected. Setting ID to 0!"); $section->id = 0; $section->save(); } App::get()->debug("Section {$name}: #{$section->id} created!"); $group = new ForumUserGroup(); $group->section_id = $section->id; $group->full_name = 'Visitors'; $group->html_class = 'visitors'; $group->admin = $group->moderator = $group->newthread = $group->threadreply = 0; $group->canread = 1; $group->save(); App::get()->debug("Group {$group->full_name}: #{$group->id} created!"); $section->default_visitors_group_id = $group->id; $group->full_name = "Members"; $group->html_class = "members"; $group->newthread = $group->threadreply = 1; $group->saveAsNew(); App::get()->debug("Group {$group->full_name}: #{$group->id} created!"); $section->default_members_group_id = $group->id; $section->save(); App::get()->debug("Section updated with default group ids!"); $group->full_name = "Moderators"; $group->html_class = "moderators"; $group->moderator = 1; $group->saveAsNew(); App::get()->debug("Group {$group->full_name}: #{$group->id} created!"); $group->full_name = "Admins"; $group->html_class = "admins"; $group->admin = 1; $group->saveAsNew(); App::get()->debug("Group {$group->full_name}: #{$group->id} created!"); $title = new ForumTitle(); $title->section_id = $section->id; $title->title = "New Comer"; $title->icon = "default.png"; $title->description = $title->title; $title->save(); App::get()->debug("Title {$title->title}: #{$title->id} created!"); $user = new ForumUser2Section(); $user->user_id = $userId; $user->section_id = $section->id; $user->group_id = $group->id; $user->title_id = $title->id; $user->banned = $user->muted = 0; $user->signature = ''; $user->save(); App::get()->debug("User #{$userId} assigned to section as admin! (Group: #{$group->id})"); return $section->id; }
/** * Update cache with config values * @param int|null $userId * @param bool $force * @return array */ public static function updateCache($userId = null, $force = false) { if (self::$configValues && !$force) { return self::$configValues; } $userId = $userId ?: WebApp::get()->user()->id; $all = self::findAllByAttributes(['user_id' => $userId]); $cache = array(); foreach ($all as $conf) { $cache[$conf->name] = $conf->value; } App::get()->cacheSet('app:UserConfig:' . $userId, $cache); if (!App::get()->cacheExists('app:UserConfig:' . $userId)) { // if no cache is used then set it here in a local array. self::$configValues = $cache; } return $cache; }
public static function makeVisitor($userId, $sectionId) { $user = new self(); $user->user_id = $userId; $user->section_id = $sectionId; $user->muted = $user->banned = $user->title_id = 1; $user->muted = $user->banned = $user->title_id = 0; $user->signature = ''; $user->member_since = date('Y-m-d H:i:s'); $section = ForumSection::findByPk($sectionId); $groupId = $section->default_visitors_group_id; App::get()->debug("User {$userId} assign to group {$groupId} from section {$sectionId}"); $user->group_id = $groupId; return $user->save(); }