示例#1
0
 /**
  * Process a request using the specified context.
  *
  * @param MOXMAN_Http_Context $httpContext Context instance to pass to use for the handler.
  */
 public function processRequest(MOXMAN_Http_Context $httpContext)
 {
     $request = $httpContext->getRequest();
     $response = $httpContext->getResponse();
     try {
         $config = MOXMAN::getConfig();
         $allItems = $config->getAll();
         $licenseKey = trim($config->get("general.license"));
         $installed = !empty($allItems);
         $response->disableCache();
         $response->setHeader('Content-type', 'application/json');
         if ($installed && !$config->get('filesystem.rootpath')) {
             throw new MOXMAN_Exception("You must configure filesystem.rootpath.");
         }
         if ($request->getMethod() != 'POST') {
             throw new MOXMAN_Exception("Not a HTTP post request.");
         }
         if ($installed && !preg_match('/^([0-9A-Z]{4}\\-){7}[0-9A-Z]{4}$/', $licenseKey)) {
             throw new MOXMAN_Exception("Invalid license key specified in config.");
         }
         $authInfo = (object) array("token" => MOXMAN_Http_Csrf::createToken(MOXMAN::getConfig()->get('general.license')), "installed" => $installed, "loggedin" => MOXMAN::getAuthManager()->isAuthenticated(), "loginurl" => $config->get("authenticator.login_page", ""), "standalone" => MOXMAN::getAuthManager()->hasStandalone(), "overwrite_action" => $config->get("filesystem.overwrite_action", ""));
         $args = new MOXMAN_Auth_AuthInfoEventArgs();
         MOXMAN::getPluginManager()->get("core")->fire("AuthInfo", $args);
         foreach ($args->getInfo() as $key => $value) {
             $authInfo->{$key} = $value;
         }
         $response->sendJson($authInfo);
     } catch (Exception $e) {
         $response->sendJson((object) array("error" => array("code" => $e->getCode(), "message" => $e->getMessage())));
     }
 }
 public function authenticate(MOXMAN_Auth_User $user)
 {
     $config = MOXMAN::getConfig();
     if ($config->get('SymfonyAuthenticator.application_name') == '') {
         die('You should define a SymfonyAuthenticator.application_name name in Moxiemanager config file.');
     }
     if ($config->get('SymfonyAuthenticator.application_env') == '') {
         die('You should define a SymfonyAuthenticator.application_env in Moxiemanager config file.');
     }
     if ($config->get('SymfonyAuthenticator.project_configuration_path') == '') {
         die('You should define a SymfonyAuthenticator.project_configuration_path in Moxiemanager config file.');
     }
     require_once $config->get('SymfonyAuthenticator.project_configuration_path');
     $configuration = ProjectConfiguration::getApplicationConfiguration($config->get('SymfonyAuthenticator.application_name'), $config->get('SymfonyAuthenticator.application_env'), false);
     $context = sfContext::createInstance($configuration);
     // Is the user authenticated ?
     if ($context->getUser()->isAuthenticated()) {
         // Do we need a special role to access to the moxiemanager ?
         if ($config->get('SymfonyAuthenticator.credential') != '') {
             if ($context->getUser()->hasCredential($config->get('SymfonyAuthenticator.credential'))) {
                 return true;
             } else {
                 return false;
             }
         }
         return true;
     }
     return false;
 }
 /**
  * Process a request using the specified context.
  *
  * @param MOXMAN_Http_Context $httpContext Context instance to pass to use for the handler.
  */
 public function processRequest(MOXMAN_Http_Context $httpContext)
 {
     $request = $httpContext->getRequest();
     $response = $httpContext->getResponse();
     $response->disableCache();
     $response->setHeader('Content-type', 'text/javascript');
     // Set prefix if it's a tinymce language pack or not
     $prefix = MOXMAN_ROOT . '/langs/moxman_';
     if ($request->get("tinymce")) {
         $prefix = MOXMAN_ROOT . '/langs/';
     }
     // Load TinyMCE specific pack if it exists
     $langCode = preg_replace('/[^a-z_\\-]/i', '', $request->get('code'));
     if ($langCode) {
         $langFile = $prefix . $langCode . '.js';
         if (file_exists($langFile)) {
             $response->sendContent(file_get_contents($langFile));
             return;
         }
     }
     // Fallback to configured language pack
     $langCode = MOXMAN::getConfig()->get("general.language");
     if ($langCode) {
         $langFile = $prefix . $langCode . '.js';
         if (file_exists($langFile)) {
             $response->sendContent(file_get_contents($langFile));
             return;
         }
     }
 }
示例#4
0
 public function authenticate(MOXMAN_Auth_User $user)
 {
     $config = MOXMAN::getConfig();
     $session = new CI_Session();
     // Check logged in key
     $sessionValue = $session->userdata($config->get("CodeIgniterAuthenticator.logged_in_key", "loggedin"));
     if (!$sessionValue || $sessionValue === "false") {
         return false;
     }
     // Extend config with session prefixed sessions
     $sessionConfig = array();
     $configPrefix = $config->get("CodeIgniterAuthenticator.config_prefix", "moxiemanager");
     if ($configPrefix) {
         $allData = $session->all_userdata();
         foreach ($allData as $key => $value) {
             if (strpos($key, $configPrefix) === 0) {
                 $sessionConfig[substr($key, strlen($configPrefix) + 1)] = $value;
             }
         }
     }
     // Extend the config with the session config
     $config->extend($sessionConfig);
     // Replace ${user} with all config items
     $key = $config->get("CodeIgniterAuthenticator.user_key");
     if ($key) {
         $value = $session->userdata($key);
         $config->replaceVariable("user", $value);
         $user->setName($value);
     }
     return true;
 }
示例#5
0
 public function add($params)
 {
     if (MOXMAN::getConfig()->get('general.demo')) {
         throw new MOXMAN_Exception("This action is restricted in demo mode.", MOXMAN_Exception::DEMO_MODE);
     }
     if (isset($params->paths) && is_array($params->paths)) {
         $paths = $params->paths;
         $files = MOXMAN_Util_Json::decode(MOXMAN::getUserStorage()->get("favorites.files", "[]"));
         // If files is larger then max size then crop it
         $max = intval(MOXMAN::getConfig()->get("favorites.max"));
         if (count($files) >= $max) {
             $files = array_slice($files, count($files) - $max);
         }
         foreach ($files as $file) {
             for ($i = count($paths) - 1; $i >= 0; $i--) {
                 if ($file->path == $paths[$i]) {
                     array_splice($paths, $i, 1);
                 }
             }
         }
         // Add new files
         foreach ($paths as $path) {
             $file = MOXMAN::getFile($path);
             $files[] = array("path" => $file->getPublicPath(), "size" => $file->getSize(), "isdir" => $file->isDirectory(), "mdate" => $file->getLastModified());
         }
         MOXMAN::getUserStorage()->put("favorites.files", MOXMAN_Util_Json::encode($files));
     }
     return true;
 }
示例#6
0
 public function authenticate(MOXMAN_Auth_User $user)
 {
     $config = MOXMAN::getConfig();
     $session = MOXMAN_Http_Context::getCurrent()->getSession();
     // Check logged in key
     $sessionValue = $session->get($config->get("SessionAuthenticator.logged_in_key"), false);
     if (!$sessionValue || $sessionValue === "false") {
         return false;
     }
     // Extend config with session prefixed sessions
     $sessionConfig = array();
     $configPrefix = $config->get("SessionAuthenticator.config_prefix");
     if ($configPrefix) {
         foreach ($_SESSION as $key => $value) {
             if (strpos($key, $configPrefix) === 0) {
                 $sessionConfig[substr($key, strlen($configPrefix) + 1)] = $value;
             }
         }
     }
     // Extend the config with the session config
     $config->extend($sessionConfig);
     // Replace ${user} with all config items
     $key = $config->get("SessionAuthenticator.user_key");
     if ($key && isset($_SESSION[$key])) {
         $config->replaceVariable("user", $session->get($key));
     }
     // The user is authenticated so let them though
     return true;
 }
示例#7
0
 public function authenticate(MOXMAN_Auth_User $user)
 {
     $sessionContainerName = MOXMAN::getConfig()->get("ZendAuthenticator.session_container");
     if ($sessionContainerName) {
         $session = new Zend\Session\Container($sessionContainerName);
     } else {
         $session = new Zend\Session\Container();
     }
     $config = MOXMAN::getConfig();
     $loggedInKey = $config->get("ZendAuthenticator.logged_in_key", "loggedin");
     if (isset($session->{$loggedInKey}) && ($session->{$loggedInKey} === true || strtolower($session->{$loggedInKey}) === "true")) {
         // Extend config with session prefixed sessions
         $sessionConfig = array();
         $configPrefix = $config->get("ZendAuthenticator.config_prefix");
         if ($configPrefix) {
             foreach ($session as $key => $value) {
                 if (strpos($key, $configPrefix) === 0) {
                     $sessionConfig[substr($key, strlen($configPrefix) + 1)] = $value;
                 }
             }
         }
         // Extend the config with the session config
         $config->extend($sessionConfig);
         // Replace ${user} with all config items
         $key = $config->get("ZendAuthenticator.user_key");
         if ($key && isset($session->{$key})) {
             $config->replaceVariable("user", $session->{$key});
             $user->setName($session->{$key});
         }
         return true;
     }
     return false;
 }
示例#8
0
 public function authenticate(MOXMAN_Auth_User $user)
 {
     $config = MOXMAN::getConfig();
     $this->validateConfig($config);
     $json = $this->getJson($config);
     $this->updateUserAndConfig($this->parseJson($json), $user, $config);
     $this->cacheJsonResult($json);
     return true;
 }
示例#9
0
 public static function startSession()
 {
     $sessionName = MOXMAN::getConfig()->get("SessionAuthenticator.session_name");
     if ($sessionName) {
         @session_name($sessionName);
     }
     if (session_id() == '') {
         @session_start();
     }
 }
示例#10
0
 public function authenticate(MOXMAN_Auth_User $user)
 {
     global $isDrupalAuth;
     global $user;
     $config = MOXMAN::getConfig();
     // If authenticated then
     if ($isDrupalAuth && isset($user)) {
         $config->replaceVariable("user", $user->uid);
     }
     return $isDrupalAuth;
 }
示例#11
0
 public function authenticate(MOXMAN_Auth_User $user)
 {
     $config = MOXMAN::getConfig();
     $user = JFactory::getUser();
     // Not logged in
     if ($user->id == 0) {
         return false;
     }
     $config->replaceVariable("user", $user->username);
     return true;
 }
示例#12
0
 public function authenticate(MOXMAN_Auth_User $user)
 {
     $config = MOXMAN::getConfig();
     if (!isLogged()) {
         return false;
     }
     $s = getUsername();
     $sPath = BX_DIRECTORY_PATH_ROOT . 'media/moxie/files/' . substr($s, 0, 1) . '/' . substr($s, 0, 2) . '/' . substr($s, 0, 3) . '/' . $s;
     bx_mkdir_r($sPath);
     $config->put('filesystem.rootpath', $sPath);
     $config->replaceVariable("user", $s);
     $user->setName($s);
     return true;
 }
示例#13
0
 /**
  * Process a request using the specified context.
  *
  * @param MOXMAN_Http_Context $httpContext Context instance to pass to use for the handler.
  */
 public function processRequest(MOXMAN_Http_Context $httpContext)
 {
     $config = MOXMAN::getConfig();
     $response = $httpContext->getResponse();
     $response->disableCache();
     $response->setHeader('Content-type', 'text/html');
     if (!$config->get("general.debug")) {
         $response->sendContent("Debugging not configured, you need to set general.debug to true in config.php file.");
         return;
     }
     $request = $httpContext->getRequest();
     if ($request->get("info")) {
         phpinfo();
         return;
     }
     $sitepaths = MOXMAN_Util_PathUtils::getSitePaths();
     $scriptFilename = $_SERVER["SCRIPT_FILENAME"];
     if (realpath($scriptFilename) != $scriptFilename) {
         $scriptFilename = $scriptFilename . "<br />(" . realpath($scriptFilename) . ")";
     }
     if (function_exists("imagecreatefromjpeg")) {
         $gdInfo = gd_info();
         $outInfo = "Ver:" . $gdInfo["GD Version"];
         $outInfo .= " GIF:" . ($gdInfo["GIF Create Support"] ? "Y" : "N");
         $outInfo .= " PNG:" . ($gdInfo["PNG Support"] ? "Y" : "N");
         $outInfo .= " JPEG:" . ($gdInfo["JPEG Support"] ? "Y" : "N");
     } else {
         $outInfo = "N/A";
         $gdInfo = array();
     }
     $user = MOXMAN::getAuthManager()->getUser();
     $result = array("MOXMAN_ROOT" => MOXMAN_ROOT, "realpath('.')" => realpath("."), "Config.php rootpath" => $config->get("filesystem.rootpath"), "Config.php wwwroot" => $config->get("filesystem.local.wwwroot"), "wwwroot resolve" => $sitepaths["wwwroot"], "wwwroot realpath" => realpath($sitepaths["wwwroot"]), "prefix resolve" => $sitepaths["prefix"], "storage path" => MOXMAN_Util_PathUtils::toAbsolute(MOXMAN_ROOT, $config->get("storage.path")), "storage writable" => is_writable(MOXMAN_Util_PathUtils::toAbsolute(MOXMAN_ROOT, $config->get("storage.path"))), "script filename" => $scriptFilename, "script name" => $_SERVER["SCRIPT_NAME"], "GD" => $outInfo, "memory_limit" => @ini_get("memory_limit"), "upload_max_filesize" => @ini_get("upload_max_filesize"), "post_max_size" => @ini_get("post_max_size"), "file_uploads" => @ini_get("file_uploads") ? "Yes" : "No", "PHP Version" => phpversion(), "Time" => date('Y-m-d H:i:s', time()), "Time UTC" => date('Y-m-d H:i:s', time() - date("Z")), "Authenticated" => MOXMAN::getAuthManager()->isAuthenticated(), "User" => $user ? $user->getName() : "N/A");
     $out = "<html><body><table border='1'>";
     foreach ($result as $name => $value) {
         if ($value === true) {
             $value = "True";
         } else {
             if ($value === false) {
                 $value = "False";
             }
         }
         $out .= "<tr>";
         $out .= "<td>" . $name . "&nbsp;</td><td>" . $value . "&nbsp;</td>";
         $out .= "</tr>";
     }
     $out .= "</table><a href='?action=debug&info=true'>Show phpinfo</a>";
     $out .= "</body></html>";
     $response->sendContent($out);
 }
 /**
  * Process a request using the specified context.
  *
  * @param MOXMAN_Http_Context $httpContext Context instance to pass to use for the handler.
  */
 public function processRequest(MOXMAN_Http_Context $httpContext)
 {
     $response = $httpContext->getResponse();
     $response->setHeader('Content-type', 'text/javascript');
     $config = MOXMAN::getConfig();
     $plugins = explode(',', $config->get("general.plugins"));
     $content = "";
     foreach ($plugins as $plugin) {
         $path = MOXMAN_PLUGINS . '/' . $plugin . '/Plugin.js';
         if (file_exists($path)) {
             $content .= file_get_contents($path);
         }
     }
     $response->sendContent($content);
 }
示例#15
0
 public function login(MOXMAN_Auth_User $user)
 {
     $config = MOXMAN::getConfig();
     foreach ($config->get('basicauthenticator.users') as $userItem) {
         if ($userItem["username"] == $user->getName() && $userItem["password"] == $user->getPassword()) {
             if ($user->isPersistent()) {
                 setcookie("moxmanauth", hash("sha256", $userItem["username"] . $userItem["password"] . $config->get('general.license')));
             } else {
                 $_SESSION["moxman_authUser"] = $user->getName();
             }
             return true;
         }
     }
     return false;
 }
 /**
  * Process a request using the specified context.
  *
  * @param MOXMAN_Http_Context $httpContext Context instance to pass to use for the handler.
  */
 public function processRequest(MOXMAN_Http_Context $httpContext)
 {
     $request = $httpContext->getRequest();
     $response = $httpContext->getResponse();
     $langCode = preg_replace('/[^a-z_\\-]/i', '', $request->get('code', MOXMAN::getConfig()->get("general.language")));
     $response->disableCache();
     $response->setHeader('Content-type', 'text/javascript');
     if ($request->get("tinymce")) {
         $langFile = MOXMAN_ROOT . '/langs/' . $langCode . '.js';
     } else {
         $langFile = MOXMAN_ROOT . '/langs/moxman_' . $langCode . '.js';
     }
     if (file_exists($langFile)) {
         $response->sendContent(file_get_contents($langFile));
     }
 }
示例#17
0
 public function authenticate(MOXMAN_Auth_User $user)
 {
     $config = MOXMAN::getConfig();
     $secretKey = $config->get("ExternalAuthenticator.secret_key");
     $authUrl = $config->get("ExternalAuthenticator.external_auth_url");
     if (!$secretKey || !$authUrl) {
         throw new MOXMAN_Exception("No key/url set for ExternalAuthenticator, check config.");
     }
     // Build url
     if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") {
         $url = "https://";
     } else {
         $url = "http://";
     }
     $url .= $_SERVER['HTTP_HOST'];
     if ($_SERVER['SERVER_PORT'] != 80) {
         $url .= ':' . $_SERVER['SERVER_PORT'];
     }
     $httpClient = new MOXMAN_Http_HttpClient($url);
     $authUrl = MOXMAN_Util_PathUtils::toAbsolute(dirname($_SERVER["REQUEST_URI"]) . '/plugins/ExternalAuthenticator', $authUrl);
     $request = $httpClient->createRequest($url . $authUrl);
     $cookie = '';
     foreach ($_COOKIE as $name => $value) {
         $cookie .= ($cookie ? '; ' : '') . $name . '=' . $value;
     }
     $request->setHeader('cookie', $cookie);
     $seed = $cookie . uniqid() . time();
     $hash = hash_hmac('sha256', $seed, $secretKey);
     $response = $request->send(array("seed" => $seed, "hash" => $hash));
     $json = json_decode($response->getBody());
     if (!$json) {
         throw new MOXMAN_Exception("Did not get a proper JSON response from Auth url.");
     }
     if (isset($json->result)) {
         foreach ($json->result as $key => $value) {
             $key = str_replace('_', '.', $key);
             $config->put($key, $value);
         }
         return true;
     } else {
         if (isset($json->error)) {
             throw new MOXMAN_Exception($json->error->message . " - " . $json->error->code);
         } else {
             throw new MOXMAN_Exception("Generic unknown error, did not get a proper JSON response from Auth url.");
         }
     }
 }
示例#18
0
 public function add($path)
 {
     $files = MOXMAN_Util_Json::decode(MOXMAN::getUserStorage()->get("uploaded.files", "[]"));
     // If files is larger then max size then crop it
     $max = intval(MOXMAN::getConfig()->get("uploaded.max", 20));
     if (count($files) >= $max) {
         $files = array_slice($files, count($files) - $max);
     }
     // Remove existing paths
     for ($i = 0; $i < count($files); $i++) {
         if ($files[$i]->path == $path) {
             array_splice($files, $i, 1);
         }
     }
     $file = MOXMAN::getFile($path);
     $files[] = array("path" => $file->getPublicPath(), "size" => $file->getSize(), "isdir" => $file->isDirectory(), "mdate" => $file->getLastModified());
     MOXMAN::getUserStorage()->put("uploaded.files", MOXMAN_Util_Json::encode($files));
 }
示例#19
0
 /**
  * Executes the command logic with the specified RPC parameters.
  *
  * @param Object $params Command parameters sent from client.
  * @return Object Result object to be passed back to client.
  */
 public function execute($params)
 {
     $templatePath = MOXMAN_ROOT . '/install/config.template.php';
     if (file_exists($templatePath)) {
         // Get all data
         $license = trim($params->license);
         $authenticator = $params->authenticator;
         $username = $params->username;
         $password = $params->password;
         $loggedInKey = $params->logged_in_key;
         // Verify input
         if (!preg_match('/^([0-9A-Z]{4}\\-){7}[0-9A-Z]{4}$/', $license)) {
             throw new MOXMAN_Exception("Invalid license: " . $license);
         }
         // Update the license since it will later be used by the csrf logic
         MOXMAN::getConfig()->put("general.license", $license);
         if ($authenticator == "BasicAuthenticator") {
             $params->authenticator = "BasicAuthenticator";
             if (!$username) {
                 throw new MOXMAN_Exception("User name can't be empty.");
             }
             if (!$password) {
                 throw new MOXMAN_Exception("Password can't be empty.");
             }
         }
         if ($authenticator == "SessionAuthenticator") {
             $params->authenticator = "SessionAuthenticator";
             if (!$loggedInKey) {
                 throw new MOXMAN_Exception("Session name can't be empty.");
             }
         }
         // Replace template variables
         $template = file_get_contents($templatePath);
         foreach ($params as $key => $value) {
             $template = str_replace('<' . $key . '>', $value, $template);
         }
         if (!is_writable(MOXMAN_ROOT . "/config.php") || !file_put_contents(MOXMAN_ROOT . "/config.php", $template)) {
             return $template;
         }
     } else {
         throw new MOXMAN_Exception("Failed to locate config template.");
     }
     return true;
 }
 public function remove($params)
 {
     if (MOXMAN::getConfig()->get('general.demo')) {
         throw new MOXMAN_Exception("This action is restricted in demo mode.", MOXMAN_Exception::DEMO_MODE);
     }
     if (isset($params->paths) && is_array($params->paths)) {
         $paths = $params->paths;
         $files = MOXMAN_Util_Json::decode(MOXMAN::getUserStorage()->get("history.files", "[]"));
         for ($i = count($files) - 1; $i >= 0; $i--) {
             foreach ($paths as $path) {
                 if ($files[$i]->path == $path) {
                     array_splice($files, $i, 1);
                     $i--;
                 }
             }
         }
         MOXMAN::getUserStorage()->put("history.files", MOXMAN_Util_Json::encode($files));
     }
     return true;
 }
示例#21
0
 public static function locate($optionName, $pathLocations)
 {
     $rootPath = MOXMAN_ROOT;
     $fullPath = MOXMAN::getConfig()->get($optionName);
     if ($fullPath) {
         return $fullPath;
     }
     while ($rootPath) {
         foreach ($pathLocations as $path) {
             $fullPath = MOXMAN_Util_PathUtils::combine($rootPath, $path);
             if (file_exists($fullPath)) {
                 return $fullPath;
             }
         }
         if (dirname($rootPath) === $rootPath) {
             break;
         }
         $rootPath = dirname($rootPath);
     }
     throw new MOXMAN_Exception("Error could not locate library/framework. Please configure: " . $optionName);
 }
示例#22
0
 public function authenticate(MOXMAN_Auth_User $user)
 {
     $config = MOXMAN::getConfig();
     // Load environment and session logic
     if (!$this->isSessionLoaded) {
         $kernel = new AppKernel($config->get("SymfonyAuthenticator.environment", "prod"), false);
         $kernel->loadClassCache();
         $request = Request::createFromGlobals();
         $kernel->handle($request);
         $this->isSessionLoaded = true;
     }
     // Get all session data
     $session = new Session();
     $session = $session->all();
     // Check logged in key
     $loggedInKey = $config->get("SymfonyAuthenticator.logged_in_key", "isLoggedIn");
     $sessionValue = isset($session[$loggedInKey]) ? $session[$loggedInKey] : false;
     if (!$sessionValue || $sessionValue === "false") {
         return false;
     }
     // Extend config with session prefixed sessions
     $sessionConfig = array();
     $configPrefix = $config->get("SymfonyAuthenticator.config_prefix", "moxiemanager");
     if ($configPrefix) {
         foreach ($session as $key => $value) {
             if (strpos($key, $configPrefix) === 0) {
                 $sessionConfig[substr($key, strlen($configPrefix) + 1)] = $value;
             }
         }
     }
     // Extend the config with the session config
     $config->extend($sessionConfig);
     // Replace ${user} with all config items
     $key = $config->get("SessionAuthenticator.user_key", "user");
     if ($key && isset($session[$key])) {
         $config->replaceVariable("user", $session[$key]);
         $user->setName($session[$key]);
     }
     return true;
 }
示例#23
0
 public function authenticate(MOXMAN_Auth_User $user)
 {
     $config = MOXMAN::getConfig();
     $validIpNumbers = explode(',', $config->get('IpAuthenticator.ip_numbers', ''));
     $currentIP = isset($_SERVER["REMOTE_ADDR"]) ? $this->ip2int($_SERVER["REMOTE_ADDR"]) : 0;
     // Loop though all ip number or ip ranges and verify them agains the remote ip
     foreach ($validIpNumbers as $validIp) {
         if ($validIp) {
             $ipRange = explode('-', $validIp);
             // Check if current IP is the single IP address specified
             if (count($ipRange) === 1 && $this->ip2int($ipRange[0]) === $currentIP) {
                 return true;
             }
             // Check if the current ip is within the specified IP range
             if (count($ipRange) === 2 && $currentIP >= $this->ip2int($ipRange[0]) && $currentIP <= $this->ip2int($ipRange[1])) {
                 return true;
             }
         }
     }
     // Not a valid IP then return false
     return false;
 }
示例#24
0
 public function authenticate(MOXMAN_Auth_User $user)
 {
     $config = MOXMAN::getConfig();
     // Check logged in key
     $sessionValue = CakeSession::read($config->get("CakeAuthenticator.logged_in_key", "loggedin"));
     if (!$sessionValue || $sessionValue === "false") {
         return false;
     }
     // Extend config with session prefixed sessions
     $configPrefix = $config->get("CakeAuthenticator.config_prefix", "moxiemanager");
     if ($configPrefix && CakeSession::check($configPrefix)) {
         $configItems = CakeSession::read($configPrefix);
         $config->extend($this->flattenArray($configItems));
     }
     // Replace ${user} with all config items
     $key = $config->get("CakeAuthenticator.user_key");
     if ($key && CakeSession::check($key)) {
         $config->replaceVariable("user", CakeSession::read($key));
     }
     // The user is authenticated so let them though
     return true;
 }
 /**
  * Process a request using the specified context.
  *
  * @param MOXMAN_Http_Context $httpContext Context instance to pass to use for the handler.
  */
 public function processRequest(MOXMAN_Http_Context $httpContext)
 {
     $config = MOXMAN::getConfig();
     if (!$config->get("general.debug")) {
         return;
     }
     $request = $httpContext->getRequest();
     if ($request->get("info")) {
         phpinfo();
         die;
     }
     $response = $httpContext->getResponse();
     $response->disableCache();
     $response->setHeader('Content-type', 'text/html');
     $sitepaths = MOXMAN_Util_PathUtils::getSitePaths();
     $scriptFilename = $_SERVER["SCRIPT_FILENAME"];
     if (realpath($scriptFilename) != $scriptFilename) {
         $scriptFilename = $scriptFilename . "<br />(" . realpath($scriptFilename) . ")";
     }
     $result = array("MOXMAN_ROOT" => MOXMAN_ROOT, "realpath('.')" => realpath("."), "Config.php rootpath" => $config->get("filesystem.rootpath"), "Config.php wwwroot" => $config->get("filesystem.local.wwwroot"), "wwwroot resolve" => $sitepaths["wwwroot"], "wwwroot realpath" => realpath($sitepaths["wwwroot"]), "prefix resolve" => $sitepaths["prefix"], "storage path" => MOXMAN_Util_PathUtils::toAbsolute(MOXMAN_ROOT, $config->get("storage.path")), "storage writable" => is_writable(MOXMAN_Util_PathUtils::toAbsolute(MOXMAN_ROOT, $config->get("storage.path"))), "script filename" => $scriptFilename, "script name" => $_SERVER["SCRIPT_NAME"]);
     $out = "<html><body><table border='1'>";
     foreach ($result as $name => $value) {
         if ($value === true) {
             $value = "True";
         } else {
             if ($value === false) {
                 $value = "False";
             }
         }
         $out .= "<tr>";
         $out .= "<td>" . $name . "&nbsp;</td><td>" . $value . "&nbsp;</td>";
         $out .= "</tr>";
     }
     $out .= "</table><a href='?action=debug&info=true'>Show phpinfo</a>";
     $out .= "</body></html>";
     $response->sendContent($out);
 }
 public function getPdo()
 {
     if (!$this->pdo) {
         if (!class_exists('PDO')) {
             return null;
         }
         try {
             $this->pdo = new MOXMAN_Util_Pdo(MOXMAN::getConfig()->get("cache.connection"));
         } catch (PDOException $e) {
             // Ignore exceptions about missing driver
             if ($e->getMessage() === "could not find driver") {
                 return null;
             }
         }
         if ($this->pdo && $this->pdo->getDriverName() == "sqlite") {
             // Check if database could be created return null if it failed
             if (!file_exists($this->pdo->getSqliteFilePath())) {
                 return null;
             }
             // If it's empty fill it with the schema
             if (filesize($this->pdo->getSqliteFilePath()) === 0) {
                 $statements = explode(';', file_get_contents(dirname(__FILE__) . "/schema-sqlite3.sql"));
                 foreach ($statements as $sql) {
                     $this->pdo->q($sql);
                 }
             }
         }
     }
     return $this->pdo;
 }
示例#27
0
 /**
  * Process a request using the specified context.
  *
  * @param MOXMAN_Http_Context $httpContext Context instance to pass to use for the handler.
  */
 public function processRequest(MOXMAN_Http_Context $httpContext)
 {
     $tempFilePath = null;
     $chunkFilePath = null;
     $request = $httpContext->getRequest();
     $response = $httpContext->getResponse();
     try {
         // Check if the user is authenticated or not
         if (!MOXMAN::getAuthManager()->isAuthenticated()) {
             if (!isset($json->method) || !preg_match('/^(login|logout)$/', $json->method)) {
                 $exception = new MOXMAN_Exception("Access denied by authenticator(s).", 10);
                 $exception->setData(array("login_url" => MOXMAN::getConfig()->get("authenticator.login_page")));
                 throw $exception;
             }
         }
         $file = MOXMAN::getFile($request->get("path"));
         $config = $file->getConfig();
         if ($config->get('general.demo')) {
             throw new MOXMAN_Exception("This action is restricted in demo mode.", MOXMAN_Exception::DEMO_MODE);
         }
         $maxSizeBytes = preg_replace("/[^0-9.]/", "", $config->get("upload.maxsize"));
         if (strpos(strtolower($config->get("upload.maxsize")), "k") > 0) {
             $maxSizeBytes = round(floatval($maxSizeBytes) * 1024);
         }
         if (strpos(strtolower($config->get("upload.maxsize")), "m") > 0) {
             $maxSizeBytes = round(floatval($maxSizeBytes) * 1024 * 1024);
         }
         function generateRandomString($length = 10)
         {
             $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
             $charactersLength = strlen($characters);
             $randomString = '';
             for ($i = 0; $i < $length; $i++) {
                 $randomString .= $characters[rand(0, $charactersLength - 1)];
             }
             return $randomString;
         }
         $filename = generateRandomString() . '.' . MOXMAN_Util_PathUtils::getExtension($request->get("name"));
         $id = $request->get("id");
         $loaded = intval($request->get("loaded", "0"));
         $total = intval($request->get("total", "-1"));
         $file = MOXMAN::getFile($file->getPath(), $filename);
         // Generate unique id for first chunk
         // TODO: We should cleanup orphan ID:s if upload fails etc
         if ($loaded == 0) {
             $id = uniqid();
         }
         // Setup path to temp file based on id
         $tempFilePath = MOXMAN_Util_PathUtils::combine(MOXMAN_Util_PathUtils::getTempDir(), "mcupload_" . $id . "." . MOXMAN_Util_PathUtils::getExtension($file->getName()));
         $chunkFilePath = MOXMAN_Util_PathUtils::combine(MOXMAN_Util_PathUtils::getTempDir(), "mcupload_chunk_" . $id . "." . MOXMAN_Util_PathUtils::getExtension($file->getName()));
         if (!$file->canWrite()) {
             throw new MOXMAN_Exception("No write access to path: " . $file->getPublicPath(), MOXMAN_Exception::NO_WRITE_ACCESS);
         }
         if ($total > $maxSizeBytes) {
             throw new MOXMAN_Exception("File size to large: " . $file->getPublicPath(), MOXMAN_Exception::FILE_SIZE_TO_LARGE);
         }
         // Operations on first chunk
         if ($loaded == 0) {
             // Fire before file action add event
             $args = new MOXMAN_Core_FileActionEventArgs("add", $file);
             $args->getData()->fileSize = $total;
             MOXMAN::getPluginManager()->get("core")->fire("BeforeFileAction", $args);
             $file = $args->getFile();
             if ($file->exists()) {
                 if (!$config->get("upload.overwrite") && !$request->get("overwrite")) {
                     throw new MOXMAN_Exception("Target file exists: " . $file->getPublicPath(), MOXMAN_Exception::FILE_EXISTS);
                 } else {
                     MOXMAN::getPluginManager()->get("core")->deleteThumbnail($file);
                     $file->delete();
                 }
             }
             $filter = MOXMAN_Vfs_CombinedFileFilter::createFromConfig($config, "upload");
             if ($filter->accept($file) !== MOXMAN_Vfs_CombinedFileFilter::ACCEPTED) {
                 throw new MOXMAN_Exception("Invalid file name for: " . $file->getPublicPath(), MOXMAN_Exception::INVALID_FILE_NAME);
             }
         }
         $blobSize = 0;
         $inputFile = $request->getFile("file");
         if (!$inputFile) {
             throw new MOXMAN_Exception("No input file specified.");
         }
         if ($loaded === 0) {
             // Check if we should mock or not
             if (defined('PHPUNIT')) {
                 if (!copy($inputFile['tmp_name'], $tempFilePath)) {
                     throw new MOXMAN_Exception("Could not move the uploaded temp file.");
                 }
             } else {
                 if (!move_uploaded_file($inputFile['tmp_name'], $tempFilePath)) {
                     throw new MOXMAN_Exception("Could not move the uploaded temp file.");
                 }
             }
             $blobSize = filesize($tempFilePath);
         } else {
             // Check if we should mock or not
             if (defined('PHPUNIT')) {
                 if (!copy($inputFile['tmp_name'], $chunkFilePath)) {
                     throw new MOXMAN_Exception("Could not move the uploaded temp file.");
                 }
             } else {
                 if (!move_uploaded_file($inputFile['tmp_name'], $chunkFilePath)) {
                     throw new MOXMAN_Exception("Could not move the uploaded temp file.");
                 }
             }
             $in = fopen($chunkFilePath, 'r');
             if ($in) {
                 $out = fopen($tempFilePath, 'a');
                 if ($out) {
                     while ($buff = fread($in, 8192)) {
                         $blobSize += strlen($buff);
                         fwrite($out, $buff);
                     }
                     fclose($out);
                 }
                 fclose($in);
             }
             unlink($chunkFilePath);
         }
         // Import file when all chunks are complete
         if ($total == -1 || $loaded + $blobSize == $total) {
             clearstatcache();
             // Check if file is valid on last chunk we also check on first chunk but not in the onces in between
             $filter = MOXMAN_Vfs_CombinedFileFilter::createFromConfig($config, "upload");
             if ($filter->accept($file) !== MOXMAN_Vfs_CombinedFileFilter::ACCEPTED) {
                 throw new MOXMAN_Exception("Invalid file name for: " . $file->getPublicPath(), MOXMAN_Exception::INVALID_FILE_NAME);
             }
             // Resize the temporary blob
             if ($config->get("upload.autoresize") && preg_match('/gif|jpe?g|png/i', MOXMAN_Util_PathUtils::getExtension($tempFilePath)) === 1) {
                 $size = getimagesize($tempFilePath);
                 $maxWidth = $config->get('upload.max_width');
                 $maxHeight = $config->get('upload.max_height');
                 if ($size[0] > $maxWidth || $size[1] > $maxHeight) {
                     $imageAlter = new MOXMAN_Media_ImageAlter();
                     $imageAlter->load($tempFilePath);
                     $imageAlter->resize($maxWidth, $maxHeight, true);
                     $imageAlter->save($tempFilePath, $config->get("upload.autoresize_jpeg_quality"));
                 }
             }
             // Create thumbnail and upload then import local blob
             MOXMAN::getPluginManager()->get("core")->createThumbnail($file, $tempFilePath);
             $file->importFrom($tempFilePath);
             unlink($tempFilePath);
             $args = new MOXMAN_Core_FileActionEventArgs("add", $file);
             MOXMAN::getPluginManager()->get("core")->fire("FileAction", $args);
             // In case file is modified
             $file = $args->getFile();
             $result = MOXMAN_Core_Plugin::fileToJson($file, true);
         } else {
             $result = $id;
         }
         $response->sendJson(array("jsonrpc" => "2.0", "result" => $result, "id" => null));
     } catch (Exception $e) {
         if ($tempFilePath && file_exists($tempFilePath)) {
             unlink($tempFilePath);
         }
         if ($chunkFilePath && file_exists($chunkFilePath)) {
             unlink($chunkFilePath);
         }
         MOXMAN::dispose();
         // Closes any open file systems/connections
         $message = $e->getMessage();
         $data = null;
         // Add file and line number when running in debug mode
         // @codeCoverageIgnoreStart
         if (MOXMAN::getConfig()->get("general.debug")) {
             $message .= " " . $e->getFile() . " (" . $e->getLine() . ")";
         }
         // @codeCoverageIgnoreEnd
         // Grab the data from the exception
         if ($e instanceof MOXMAN_Exception && !$data) {
             $data = $e->getData();
         }
         // Json encode error response
         $response->sendJson((object) array("jsonrpc" => "2.0", "error" => array("code" => $e->getCode(), "message" => $message, "data" => $data), "id" => null));
     }
 }
示例#28
0
            self::getFileSystemManager()->close();
        }
    }
}
// Load authenticators, needs to be loaded at page level since they might contain globals
$authenticators = preg_split('/[+|]/', MOXMAN::getConfig()->get("authenticator"));
foreach ($authenticators as $authenticator) {
    if ($authenticator) {
        $authenticator = MOXMAN_ROOT . '/plugins/' . $authenticator . "/Plugin.php";
        if (file_exists($authenticator)) {
            require_once $authenticator;
        }
    }
}
// Load plugins, needs to be loaded at page level since they might contain globals
$plugins = explode(',', MOXMAN::getConfig()->get("general.plugins"));
foreach ($plugins as $plugin) {
    if ($plugin) {
        $pluginPath = MOXMAN_ROOT . '/plugins/' . $plugin;
        MOXMAN_AutoLoader::addPrefixPath("MOXMAN_" . $plugin, $pluginPath);
        $plugin = $pluginPath . "/Plugin.php";
        if (file_exists($plugin)) {
            require_once $plugin;
        }
    }
}
// Load core plugin last
require_once MOXMAN_CLASSES . '/Core/Plugin.php';
// Trigger authenticate on all plugins so it can override any config options
try {
    MOXMAN::getAuthManager()->isAuthenticated();
示例#29
0
 public static function printException(Exception $e)
 {
     // Handle exceptions in authenticators
     $httpContext = MOXMAN_Http_Context::getCurrent();
     $request = $httpContext->getRequest();
     $response = $httpContext->getResponse();
     $message = $e->getMessage();
     if (MOXMAN::getConfig()->get("general.debug")) {
         $message .= "\n\nStacktrace:\n";
         $trace = $e->getTrace();
         array_shift($trace);
         $message .= $e->getFile() . ":" . $e->getLine() . "\n";
         foreach ($trace as $item) {
             if (isset($item["file"]) && isset($item["line"])) {
                 $message .= $item["file"] . ":" . $item["line"] . "\n";
             }
         }
     }
     if ($request->get("json")) {
         $response->sendJson((object) array("jsonrpc" => "2.0", "error" => array("code" => $e->getCode(), "message" => $message), "id" => "r0"));
     } else {
         echo nl2br($message);
     }
 }
 /**
  * Process a request using the specified context.
  *
  * @param MOXMAN_Http_Context $httpContext Context instance to pass to use for the handler.
  */
 public function processRequest(MOXMAN_Http_Context $httpContext)
 {
     $request = $httpContext->getRequest();
     $response = $httpContext->getResponse();
     $response->disableCache();
     $response->setHeader('Content-type', 'application/json');
     @set_time_limit(5 * 60);
     // 5 minutes execution time
     $id = null;
     try {
         $json = MOXMAN_Util_Json::decode($request->get("json"));
         // Check if we should install
         if ($json && $json->method != "install") {
             $config = MOXMAN::getConfig()->getAll();
             if (empty($config) || !isset($config["general.license"])) {
                 $exception = new MOXMAN_Exception("Installation needed.", MOXMAN_Exception::NEEDS_INSTALLATION);
                 throw $exception;
             }
             if (!preg_match('/^([0-9A-Z]{4}\\-){7}[0-9A-Z]{4}$/', trim($config["general.license"]))) {
                 throw new MOXMAN_Exception("Invalid license: " . $config["general.license"]);
             }
         }
         // Check if the user is authenticated or not
         if (!MOXMAN::getAuthManager()->isAuthenticated()) {
             if (!isset($json->method) || !preg_match('/^(login|logout|install)$/', $json->method)) {
                 $exception = new MOXMAN_Exception("Access denied by authenticator(s).", MOXMAN_Exception::NO_ACCESS);
                 $exception->setData(array("login_url" => MOXMAN::getConfig()->get("authenticator.login_page")));
                 throw $exception;
             }
         }
         if ($json && isset($json->id) && isset($json->method) && isset($json->params)) {
             $id = $json->id;
             $params = $json->params;
             $result = null;
             if (isset($params->access)) {
                 MOXMAN::getAuthManager()->setClientAuthData($params->access);
             }
             $plugins = MOXMAN::getPluginManager()->getAll();
             foreach ($plugins as $plugin) {
                 if ($plugin instanceof MOXMAN_ICommandHandler) {
                     $result = $plugin->execute($json->method, $json->params);
                     if ($result !== null) {
                         break;
                     }
                 }
             }
             if ($result === null) {
                 throw new Exception("Method not found: " . $json->method, -32601);
             }
             $response->sendJson((object) array("jsonrpc" => "2.0", "result" => $result, "id" => $id));
         } else {
             throw new Exception("Invalid Request.", -32600);
         }
         MOXMAN::dispose();
     } catch (Exception $e) {
         MOXMAN::dispose();
         $message = $e->getMessage();
         $data = null;
         if (MOXMAN::getConfig()->get("general.debug")) {
             $message .= "\n\nStacktrace:\n";
             $trace = $e->getTrace();
             array_shift($trace);
             $message .= $e->getFile() . ":" . $e->getLine() . "\n";
             foreach ($trace as $item) {
                 if (isset($item["file"]) && isset($item["line"])) {
                     $message .= $item["file"] . ":" . $item["line"] . "\n";
                 }
             }
         }
         if ($e instanceof MOXMAN_Exception && !$data) {
             $data = $e->getData();
         }
         $response->sendJson((object) array("jsonrpc" => "2.0", "error" => array("code" => $e->getCode(), "message" => $message, "data" => $data), "id" => $id));
     }
 }