Example #1
0
 public function __construct()
 {
     $child = get_class($this);
     $this->childClass = ['namespaceArray' => explode('\\', $child), 'namespaceString' => $child];
     $this->configMain = Config::main();
     $this->uri = \Gear::$uri;
 }
Example #2
0
 /**
  * Reads all plugins in the plugins directory of the server root.
  * @return array
  */
 public static function getPlugins($db = null)
 {
     if (!$db) {
         $db = Config::main()->getDBO();
     }
     $result = array();
     $path = DIAMONDMVC_ROOT . '/plugins';
     $dir = opendir($path);
     while ($curr = readdir($dir)) {
         if ($curr === '.' or $curr === '..') {
             continue;
         }
         if (!is_dir("{$path}/{$curr}")) {
             logMsg('Plugin ist kein Ordner: $path/$curr', 5);
             continue;
         }
         if (!file_exists("{$path}/{$curr}/{$curr}.php")) {
             logMsg("Plugin-Hauptskript nicht gefunden: {$path}/{$curr}/{$curr}.php");
             continue;
         }
         include_once "{$path}/{$curr}/{$curr}.php";
         if (!class_exists("Plugin{$curr}")) {
             logMsg("Plugin-Hauptklasse nicht gefunden: {$curr}");
             continue;
         }
         $className = "plugin{$curr}";
         $result[] = new $className($db);
     }
     return $result;
 }
Example #3
0
 public function __construct()
 {
     $child = get_class($this);
     $this->childClass = array('namespaceArray' => explode('\\', $child), 'namespaceString' => $child);
     $this->configMain = Config::main();
     $this->uri = new Uri();
 }
Example #4
0
 protected function action_login()
 {
     $user = DiamondMVC::instance()->getCurrentUser();
     if ($user->isLoggedIn()) {
         if (isset($_REQUEST['returnto'])) {
             redirect(urldecode($_REQUEST['returnto']));
         } else {
             redirect(DIAMONDMVC_URL . Config::main()->get('DEFAULT_LOGIN_REDIRECT'));
         }
         return;
     }
     // Wurden Daten übermittelt?
     if (isset($_REQUEST['login'])) {
         if ($user->login($_REQUEST['username'], $_REQUEST['password'])) {
             if (isset($_REQUEST['returnto'])) {
                 redirect(urldecode($_REQUEST['returnto']));
             } else {
                 redirect(DIAMONDMVC_URL . Config::main()->get('DEFAULT_LOGIN_REDIRECT'));
             }
             return;
         } else {
             $this->addMessage('Error', 'The given email-password combination was not found.', 'error');
         }
     }
 }
Example #5
0
 /**
  * Method to embrace composer native autoloader
  */
 public static function composer()
 {
     $config = Config::main();
     if (!($file = $config['vendor']['path'] . 'autoload.php')) {
         throw new RunException('Composer autoloader not exists in your vendor folder ' . $config['vendor']['path']);
     }
     require_once $file;
 }
Example #6
0
 public static function endSection()
 {
     if (Config::main()->get('DEBUG_MODE')) {
         $time = round(microtime(true));
         if (empty(self::$sections)) {
             logMsg("--- No section to end ---", 1, 5);
             return $this;
         }
         $section = array_pop(self::$sections);
         $section['end'] = $time;
         $section['memEnd'] = round(memory_get_usage() / 1024);
         logMsg("- Section {$section['name']} end -", 1, false);
         logMsg("Start: {$section['start']}s", 1, false);
         logMsg("End:   {$section['end']}s", 1, false);
         logMsg("Delta: " . ($section['end'] - $section['start']) . 's', 1, false);
         logMsg("Memory: {$section['memStart']} kiB - {$section['memEnd']} kiB", 1, false);
         logMsg("Median: " . ($section['memEnd'] + $section['memStart']) / 2 . ' kiB', 1, false);
     }
 }
Example #7
0
 public static function vendor($filePath, $className = false, $arguments = array())
 {
     $config = Config::main();
     if (!file_exists($file = $config['vendor']['path'] . $filePath . '.php')) {
         return false;
     }
     include_once $file;
     if (!$className) {
         $arr = explode('/', $filePath);
         $className = end($arr);
     } else {
         // Are we try to call static method?
         if (count(explode('::', $className)) > 1) {
             return call_user_func_array($className, $arguments);
         }
     }
     $reflector = new \ReflectionClass($className);
     try {
         $object = $reflector->newInstanceArgs($arguments);
     } catch (\ReflectionException $e) {
         $object = new $className();
     }
     return $object;
 }
Example #8
0
 protected function action_temporary()
 {
     if (!Config::main()->get('DEBUG_MODE')) {
         return $this->redirect();
     }
 }
Example #9
0
/**
 * Prepares up the database. Afterwards shows success or failure message.
 */
function step2()
{
    $success = false;
    if (!isset($_REQUEST['adminemail']) or !isset($_REQUEST['adminpassword'])) {
        $this->addMessage('Required field not set', 'Administrator email or administrator password not passed', 'error');
    } else {
        $success = true;
        $errors = array();
        $adminemail = $_REQUEST['adminemail'];
        $adminpassword = $_REQUEST['adminpassword'];
        // Generate other variables
        $variables = array('adminname' => 'Admin', 'website_title' => 'DiamondMVC', 'default_controller_title' => '', 'login_redirect' => '/user', 'session_timeout' => 4320, 'cache_lifetime' => 86400, 'debug_mode' => 0, 'verbose_logging' => 0, 'log_severity' => 5, 'db_host' => '127.0.0.1', 'db_port' => 3306, 'db_user' => 'root', 'db_pass' => '', 'db_database' => 'diamondmvc', 'db_prefix' => '', 'enforce_column_deleted' => 0);
        foreach ($variables as $variable => $default) {
            ${$variable} = (isset($_REQUEST[$variable]) and !empty($_REQUEST[$variable])) ? $_REQUEST[$variable] : $default;
            // If the default is a numeric value, we're expecting a numeric value from the client as well.
            // For our convenience we're going to conver them here already.
            if (is_numeric($default)) {
                if (is_int($default)) {
                    ${$variable} = intval(${$variable});
                } else {
                    if (is_float($default)) {
                        ${$variable} = floatval(${$variable});
                    } else {
                        throw new Exception('Unknown number format');
                    }
                }
            }
        }
        $pathConfig = DIAMONDMVC_ROOT . DS . 'ini.php';
        // Use the generated variables to configure the system
        $ini = (new ini())->read($pathConfig);
        $ini->set('DEBUG_MODE', $debug_mode)->set('VERBOSE_LOGGING', $verbose_logging)->set('SESSION_TIMEOUT', $session_timeout)->set('DEFAULT_CACHE_LIFETIME', $cache_lifetime)->set('LOG_SEVERITY', $log_severity)->set('WEBSITE_TITLE', $website_title)->set('DEFAULT_CONTROLLER_TITLE', $default_controller_title)->set('DEFAULT_LOGIN_REDIRECT', $login_redirect)->set('DBO_ENFORCE_COL_DELETED', $enforce_column_deleted)->set('HOST', 'DATABASE.DEFAULT', $db_host)->set('PORT', 'DATABASE.DEFAULT', $db_port)->set('USER', 'DATABASE.DEFAULT', $db_user)->set('PASS', 'DATABASE.DEFAULT', $db_pass)->set('DB', 'DATABASE.DEFAULT', $db_database)->set('PREFIX', 'DATABASE.DEFAULT', $db_prefix);
        try {
            $ini->write($pathConfig);
        } catch (Exception $ex) {
            $errors[] = 'Failed to write config to disk';
        }
        $contents = @file_get_contents($pathConfig);
        if (@file_put_contents($pathConfig, "<?php defined('DIAMONDMVC') or die; ?>\n" . $contents) === false) {
            $errors[] = 'Failed to prepend config with view guard - you must manually prepend it with <code>&lt;?php defined(\'DIAMONDMVC\') or die; ?&gt;</code>';
        }
        $config = Config::main()->reload();
        // Create the tables
        $db = $config->getDBO();
        $sql = file_get_contents(DIAMONDMVC_ROOT . '/firstinstallation/create_tables.sql');
        $commands = explode(';', $sql);
        $db->pushState();
        foreach ($commands as $command) {
            $command = trim($command);
            $db->query($command);
            if (!empty($db->error)) {
                $errors[] = 'Failed to execute MySQL query: ' . $command . '. Terminated with error: ' . $db->error;
                $success = false;
            }
        }
        $db->query("INSERT INTO `USERS` (`USERNAME`, `EMAIL`, `PASSWORD`, `DELETED`) VALUES ('{$adminname}', '{$adminemail}', '" . hash('sha256', $adminpassword) . "', 0)");
        if (!empty($db->error)) {
            $errors[] = 'Failed to create admin user, please create the user manually in the database management software of your choosing. Please note that the password must be a SHA256 hash.';
        }
        $db->popState();
        $success = true;
        include dirname(__FILE__) . '/step2.php';
    }
}
Example #10
0
/**
 * Schreibt einen MySQL-Query in die entsprechende Log-Datei.
 * Queries werden nur im Debug-Mode geloggt, um überflüssige Dateisystemzugriffe zu vermeiden.
 * @param string $query  Zu loggender MySQL-Query.
 * @param string $bind   Typendefinition der Marker
 * @param array  $params Zu bindende Parameter
 */
function logQuery($query, $bind = '', $params = null)
{
    if (!Config::main()->isDebugMode()) {
        return;
    }
    $user = DiamondMVC::instance()->getCurrentUser();
    if (!is_array($params)) {
        $params = array();
    }
    if ($user->isLoggedIn()) {
        $file = date('Y-m-d-') . $user->getName();
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
        if ($ip === '127.0.0.1' or $ip === '::1') {
            $ip = 'localhost';
        }
        $file = date('Y-m-d-') . $ip;
    }
    $file = DIAMONDMVC_ROOT . '/logs/' . $file . '.qlg.txt';
    if (!is_dir(DIAMONDMVC_ROOT . '/logs')) {
        mkdir(DIAMONDMVC_ROOT . '/logs');
    }
    $res = fopen($file, 'a');
    if (!is_resource($res)) {
        trigger_error('Log-Datei ' . $file . ' konnte nicht geöffnet werden.', E_USER_WARNING);
    } else {
        fwrite($res, date('[H:i:s]') . $query . PHP_EOL);
        if (!empty($bind)) {
            fwrite($res, "\tBind ({$bind}): " . implode(', ', array_map('mapArgs', $params)) . PHP_EOL);
        }
        fclose($res);
    }
}
Example #11
0
 /**
  * PLACEHOLDER
  * Attempts to sanitize and normalize the WHERE condition.
  * @param  boolean $allowDeleted Whether to include data sets marked as deleted.
  * @return string                Sanitized and normalized WHERE condition.
  */
 protected function prepareFilter()
 {
     $db = $this->prepareIdentifier($this->db);
     $table = $this->prepareIdentifier($this->table);
     $filters = array();
     if (!empty($this->filter)) {
         $filters[] = $this->filter;
         // TODO: Normierung der Identifizierer.
     }
     if (Config::main()->get('DBO_ENFORCE_COL_DELETED') and !$this->ignoreDeleted) {
         $filters[] = "`{$db}`.`{$table}`.`DELETED`=0";
     }
     return empty($filters) ? '' : '(' . implode(') AND (', $filters) . ')';
 }
Example #12
0
 /**
  * Erzeugt einen neuen Kontroller mit Namen. Der Name gibt an, von wo er die Views
  * laden wird.
  * @param string $name Name des Kontrollers.
  */
 protected function __construct($name, $db = null)
 {
     $this->_controllername = $name;
     $this->title = Config::main()->get('DEFAULT_CONTROLLER_TITLE');
     $this->db = is_null($db) ? Config::main()->getDbo() : $db;
 }
Example #13
0
 /**
  * Checks if the current user has been inactive for too long (session expired).
  * The session expiration time can be set in the configuration.
  * @return boolean True if the user has been inactive for x seconds.
  */
 public function isSessionExpired()
 {
     return round(microtime(true)) - intval($_SESSION['user']['last_action']) > intval(Config::main()->get('SESSION_TIMEOUT')) * 1000 * 60;
 }
Example #14
0
 /**
  * Konvertiert diesen Join in einen String.
  * @param  string $db Name der database, die die Tabelle beinhaltet.
  * @return string     Join-String
  */
 public function str($db)
 {
     // TODO: Erwartet Filter-Klasse zur sichereren Abstrahierung der Anfragen für sowohl den Server als auch den Entwickler.
     $condition = $this->condition;
     if (Config::main()->get('DBO_ENFORCE_COL_DELETED') and !$this->ignoreDeleted) {
         $condition .= ' AND `' . $this->tabname . '`.`DELETED`=0';
     }
     return implode(' ', array($this->jointype, 'JOIN', "`{$db}`.`" . $this->tabname . '`', $condition)) . (!empty($this->more) ? ' ' . $this->more->str($db) : '');
 }
Example #15
0
 /**
  * Main server procedure. index.php in the system's root calls this method by default.
  */
 public function run()
 {
     $db = Config::main()->getDbo();
     // Prepare necessities.
     $this->user = new ModelUser($db);
     if ($this->user->isLoggedIn()) {
         $this->user->restoreSession()->refreshSession();
     }
     Cache::init($db);
     Profiler::startSection('DiamondMVC');
     Profiler::startSection('Initiating i18n');
     logMsg('DiamondMVC: using compressed language file: ' . (Config::main()->get('DEBUG_MODE') ? 'yes' : 'no'), 1, false);
     i18n::init(Config::main()->get('DEBUG_MODE'));
     Profiler::endSection();
     // Load plugins
     Profiler::startSection('Load plugins');
     $this->plugins = Plugin::getPlugins();
     Profiler::endSection();
     Profiler::startSection('Load permissions');
     Permissions::init($db);
     Profiler::endSection();
     // Register field classes
     Profiler::startSection('Register fields');
     FormBuilder::registerFields();
     Profiler::endSection();
     $evt = new SystemBeforeRouteEvent();
     $this->trigger($evt);
     if (!$evt->isDefaultPrevented()) {
         Profiler::startSection('Routing');
         // Route requested controller
         if (isset($_REQUEST['control']) and !empty($_REQUEST['control'])) {
             $control = 'Controller' . str_replace('-', '_', $_REQUEST['control']);
             if (!class_exists($control)) {
                 $control = Config::main()->get('DEFAULT_CONTROLLER');
             }
         } else {
             $control = Config::main()->get('DEFAULT_CONTROLLER');
         }
         logMsg("DiamondMVC: routed controller to " . $control, 1, false);
         // Detect requested action, by default "main"
         if (isset($_REQUEST['action'])) {
             $action = $_REQUEST['action'];
         } else {
             $action = 'main';
         }
         $action = preg_replace('/[^A-z_]+/', '_', $action);
         logMsg("DiamondMVC: action is " . $action, 1, false);
         // Detect type of action. Currently possible: HTML, AJAX, JSON
         if (isset($_REQUEST['type'])) {
             $type = strToLower($_REQUEST['type']);
         } else {
             $type = 'html';
         }
         logMsg("DiamondMVC: request type is " . $type, 1, false);
         // Detect requested template. Ignored in JSON requests
         if (isset($_REQUEST['tpl'])) {
             $_REQUEST['tpl'] = trim($_REQUEST['tpl']);
             if (!empty($_REQUEST['tpl'])) {
                 $tpl = $_REQUEST['tpl'];
             } else {
                 $tpl = 'default';
             }
         } else {
             $tpl = 'default';
         }
         if (!file_exists(jailpath(DIAMONDMVC_ROOT . '/templates', $tpl))) {
             $tpl = 'default';
         }
         logMsg("DiamondMVC: jailed template is " . $tpl, 1, false);
         // Detect requested view
         if (isset($_REQUEST['view'])) {
             $view = $_REQUEST['view'];
         } else {
             $view = '';
         }
         logMsg("DiamondMVC: view is " . $view, 1, false);
         // The controller is the heart of the MVC system.
         logMsg("DiamondMVC: constructing controller", 1, false);
         $controller = new $control();
         // Before actually performing the action, we'll give plugins the chance to change the controller, action, view and template.
         logMsg("DiamondMVC: triggering pre-action event", 1, false);
         $this->controller = $controller;
         $this->action = $action;
         $this->view = $view;
         $this->tpl = $tpl;
         $evt = new SystemActionEvent($controller, $action, $view, $tpl);
         $this->trigger($evt);
         $contrller = $this->controller = $evt->controller;
         $action = $this->action = $evt->action;
         $view = $this->view = $evt->view;
         $tpl = $this->tpl = $evt->template;
         Profiler::endSection();
         logMsg("DiamondMVC: new controller is: Controller" . $controller->getName() . '; new action is: ' . $action . '; new view is: ' . $view . '; new type is: ' . $type, 1, false);
         Profiler::startSection('Perform action');
         $controller->action($action);
         Profiler::endSection();
         Profiler::startSection('Output');
         switch ($type) {
             // Not specially treated view type
             default:
                 // Does the view type exist in the controller?
                 if ($controller->hasView($view, $type)) {
                     logMsg("DiamondMVC: typed view {$view} ({$type}) found", 1, false);
                     $controller->getView($view, $type)->render();
                     break;
                 } else {
                     logMsg("DiamondMVC: no specific typed view found, defaulting to HTML view", 1, false);
                 }
                 // The entire website is built and sent to the client.
             // The entire website is built and sent to the client.
             case 'html':
                 logMsg("DiamondMVC: rendering HTML view", 1, false);
                 (new Template($controller, $tpl))->title(Config::main()->get('WEBSITE_TITLE'))->render($view);
                 break;
                 // TODO: AJAX request differ from JSON requests in that they make use of the client side engine to update particular parts of the web page (content, header, etc.) and request missing css and js.
             // TODO: AJAX request differ from JSON requests in that they make use of the client side engine to update particular parts of the web page (content, header, etc.) and request missing css and js.
             case 'ajax':
                 logMsg("DiamondMVC: AJAX view still needs implementation!", 1, false);
                 break;
                 // Send JSON formatted raw data. By default the result of the controller is simply encoded, but a specialized JSON view can manipulate and format data before sending it out. This is
                 // useful to remove circular references and PHP objects.
             // Send JSON formatted raw data. By default the result of the controller is simply encoded, but a specialized JSON view can manipulate and format data before sending it out. This is
             // useful to remove circular references and PHP objects.
             case 'json':
                 logMsg('DiamondMVC: hasView - ' . ($controller->hasView($view, 'json') ? 'yes' : 'no') . ' | hasTemplate - ' . ($controller->hasTemplate($view, 'json') ? 'yes' : 'no'), 1, false);
                 if ($controller->hasView($view, 'json') or $controller->hasTemplate($view, 'json')) {
                     logMsg("DiamondMVC: JSON view for " . (empty($view) ? 'default' : $view) . " found", 1, false);
                     $controller->getView($view, 'json')->read()->render();
                 } else {
                     logMsg("DiamondMVC: using generic JSON stringification on controller result", 1, false);
                     echo json_encode($controller->getResult());
                 }
                 break;
         }
         Profiler::endSection();
     } else {
         logMsg('DiamondMVC: Skipping routing', 1, false);
     }
     Profiler::endSection();
 }
Example #16
0
 /**
  * Refreshes the given local cache entry by the provided lifetime.
  * Note: the life time starts from the time of the call to this method.
  * @param  string  $id       Name of the cache entry.
  * @param  integer $lifetime New lifetime of this cache entry.
  * @return boolean           Whether the cache entry was successfully updated.
  */
 public static function refreshLocal($id, $lifetime = 0)
 {
     if (!isset($_SESSION['__CACHE']['__VALUES'][$id])) {
         return false;
     }
     if ($lifetime <= 0) {
         $lifetime = Config::main()->get('DEFAULT_CACHE_LIFETIME');
     }
     $_SESSION['__CACHE']['__EXPIRES'][$id] = round(microtime(true) + $lifetime);
     return true;
 }