public function loginAction() { $user = null; try { \Pimcore::getEventManager()->trigger("admin.login.login.authenticate", $this, ["username" => $this->getParam("username"), "password" => $this->getParam("password")]); $user = $this->getUser(); if (!$user instanceof User) { if ($this->getParam("password")) { $user = Tool\Authentication::authenticatePlaintext($this->getParam("username"), $this->getParam("password")); if (!$user) { throw new \Exception("Invalid username or password"); } } else { if ($this->getParam("token")) { $user = Tool\Authentication::authenticateToken($this->getParam("username"), $this->getParam("token")); if (!$user) { throw new \Exception("Invalid username or token"); } // save the information to session when the user want's to reset the password // this is because otherwise the old password is required => see also PIMCORE-1468 if ($this->getParam("reset")) { Tool\Session::useSession(function ($adminSession) { $adminSession->password_reset = true; }); } } else { throw new \Exception("Invalid authentication method, must be either password or token"); } } } } catch (\Exception $e) { //see if module or plugin authenticates user \Pimcore::getEventManager()->trigger("admin.login.login.failed", $this, ["username" => $this->getParam("username"), "password" => $this->getParam("password")]); $user = $this->getUser(); if (!$user instanceof User) { $this->writeLogFile($this->getParam("username"), $e->getMessage()); \Logger::info("Login failed: " . $e); } } if ($user instanceof User && $user->getId() && $user->isActive() && $user->getPassword()) { Tool\Session::useSession(function ($adminSession) use($user) { $adminSession->user = $user; Tool\Session::regenerateId(); }); if ($this->getParam('deeplink')) { $this->redirect('/admin/login/deeplink/?' . $this->getParam('deeplink')); } else { $this->redirect("/admin/?_dc=" . time()); } } else { $this->redirect("/admin/login/?auth_failed=true"); exit; } }
private function installUser(\Pimcore\Model\User\Role $userRole) { $userM = new \Pimcore\Model\User(); $user = $userM->getByName('kunde'); if ($user !== FALSE) { return $user; } $user = \Pimcore\Model\User::create(array('parentId' => 0, 'name' => 'kunde', 'password' => \Pimcore\Tool\Authentication::getPasswordHash('kunde', 'kunde'), 'active' => 1, 'language' => 'de', 'admin' => FALSE, 'roles' => array(0 => $userRole->getId()))); $user->save(); return $user; }
public function preDispatch() { parent::preDispatch(); // do something before the action is called //-> see Zend Framework \Pimcore\Tool\Authentication::authenticateSession(); $adminSession = new \Zend_Session_Namespace("pimcore_admin"); if (!$adminSession->user instanceof \User) { $auth = \Zend_Auth::getInstance(); if ($auth->hasIdentity()) { // We have a login session (user is logged in) $cached_person = $auth->getIdentity(); $id = $cached_person->getId(); $this->view->person = $this->person = \Object\Person::getById($id); } else { $this->forward("form-login", "login"); } } else { $this->view->person = $this->person = \Object\Person::getById(590); } if ($this->person) { $this->view->user = $this->user = $this->person; $this->view->societe = $this->societe = $this->person->getSociete(); $this->view->locations = $this->locations = $this->societe->getLocations(); $this->storeLocation(); } }
/** * @param array $config */ public function createOrUpdateUser($config = array()) { $defaultConfig = array("username" => "admin", "password" => md5(microtime())); $settings = array_replace_recursive($defaultConfig, $config); if ($user = Model\User::getByName($settings["username"])) { $user->delete(); } $user = Model\User::create(array("parentId" => 0, "username" => $settings["username"], "password" => \Pimcore\Tool\Authentication::getPasswordHash($settings["username"], $settings["password"]), "active" => true)); $user->setAdmin(true); $user->save(); }
/** * @throws \Exception */ public function init() { $conf = Config::getSystemConfig(); if (!$conf->webservice->enabled) { throw new \Exception("Webservice API isn't enabled"); } if (!$this->getParam("apikey") && $_COOKIE["pimcore_admin_sid"]) { $user = Authentication::authenticateSession(); if (!$user instanceof User) { throw new \Exception("User is not valid"); } } else { if (!$this->getParam("apikey")) { throw new \Exception("API key missing"); } else { $apikey = $this->getParam("apikey"); $userList = new User\Listing(); $userList->setCondition("apiKey = ? AND type = ? AND active = 1", array($apikey, "user")); $users = $userList->load(); if (!is_array($users) or count($users) !== 1) { throw new \Exception("API key error."); } if (!$users[0]->getApiKey()) { throw new \Exception("Couldn't get API key for user."); } $user = $users[0]; } } \Zend_Registry::set("pimcore_admin_user", $user); parent::init(); }
protected function execute(InputInterface $input, OutputInterface $output) { $user = $input->getOption("user"); if (!$user) { $this->writeError("No username/ID given"); } $method = is_numeric($user) ? 'getById' : 'getByName'; $user = User::$method($user); if (!$user) { $this->writeError("User with name " . $user . " could not be found. Exiting"); exit; } if ($input->getOption("password")) { $plainPassword = $input->getOption("password"); } else { $plainPassword = false; while (empty($plainPassword)) { $plainPassword = $this->promtSilent(); } } $password = \Pimcore\Tool\Authentication::getPasswordHash($user->getName(), $plainPassword); $user->setPassword($password); $user->save(); $this->output->writeln("Password for user " . $user->getName() . " reset successfully."); }
public function preDispatch() { parent::preDispatch(); // do something before the action is called //-> see Zend Framework \Pimcore\Tool\Authentication::authenticateSession(); $adminSession = new \Zend_Session_Namespace("pimcore_admin"); if (!$adminSession->user instanceof \User) { // $this->forward ( "form-login", "login" ); } }
public function init() { parent::init(); if (is_file(\Pimcore\Config::locateConfigFile("system.php"))) { // session authentication, only possible if user is logged in $user = \Pimcore\Tool\Authentication::authenticateSession(); if (!$user instanceof User) { die("Authentication failed!<br />If you don't have access to the admin interface any more, and you want to find out if the server configuration matches the requirements you have to rename the the system.php for the time of the check."); } } elseif ($this->getParam("mysql_adapter")) { } else { die("Not possible... no database settings given.<br />Parameters: mysql_adapter,mysql_host,mysql_username,mysql_password,mysql_database"); } }
/** * @param $id * @param bool $create * @param bool $returnIdIfEmpty * @param null $language * @return array * @throws \Exception * @throws \Zend_Exception */ public static function getByKeyLocalized($id, $create = false, $returnIdIfEmpty = false, $language = null) { if ($user = Tool\Admin::getCurrentUser()) { $language = $user->getLanguage(); } elseif ($user = Tool\Authentication::authenticateSession()) { $language = $user->getLanguage(); } elseif (\Zend_Registry::isRegistered("Zend_Locale")) { $language = (string) \Zend_Registry::get("Zend_Locale"); } if (!in_array($language, Tool\Admin::getLanguages())) { $config = \Pimcore\Config::getSystemConfig(); $language = $config->general->language; } return self::getByKey($id, $create, $returnIdIfEmpty)->getTranslation($language); }
public function scriptAction() { // this is just to ensure that the script is only embedded if the user is logged in // check the login manually $user = \Pimcore\Tool\Authentication::authenticateSession(); if ($user instanceof Model\User) { $personas = array(); $list = new Model\Tool\Targeting\Persona\Listing(); foreach ($list->load() as $persona) { $personas[$persona->getId()] = $persona->getName(); } header("Content-Type: text/javascript"); echo 'try { var pimcore = pimcore || {}; pimcore["admin"] = {documentId: ' . $this->getParam("documentId") . '}; pimcore["personas"] = ' . \Zend_Json::encode($personas) . '; } catch (e) {}'; echo "\n\n\n"; echo file_get_contents(PIMCORE_PATH . "/static6/js/frontend/admin/admin.js"); } exit; }
/** * @param \Zend_Controller_Request_Abstract $request */ public function postDispatch(\Zend_Controller_Request_Abstract $request) { $conf = Config::getSystemConfig(); // add scripts to editmode if (\Pimcore\Tool\Admin::isExtJS6()) { $editmodeLibraries = array("/pimcore/static6/js/pimcore/namespace.js", "/pimcore/static6/js/lib/prototype-light.js", "/pimcore/static6/js/lib/jquery.min.js", "/pimcore/static6/js/lib/ext/ext-all.js", "/pimcore/static6/js/lib/ckeditor/ckeditor.js"); $editmodeScripts = array("/pimcore/static6/js/pimcore/functions.js", "/pimcore/static6/js/pimcore/element/tag/imagehotspotmarkereditor.js", "/pimcore/static6/js/pimcore/element/tag/imagecropper.js", "/pimcore/static6/js/pimcore/document/edit/helper.js", "/pimcore/static6/js/pimcore/document/edit/dnd.js", "/pimcore/static6/js/pimcore/document/tag.js", "/pimcore/static6/js/pimcore/document/tags/block.js", "/pimcore/static6/js/pimcore/document/tags/date.js", "/pimcore/static6/js/pimcore/document/tags/href.js", "/pimcore/static6/js/pimcore/document/tags/multihref.js", "/pimcore/static6/js/pimcore/document/tags/checkbox.js", "/pimcore/static6/js/pimcore/document/tags/image.js", "/pimcore/static6/js/pimcore/document/tags/input.js", "/pimcore/static6/js/pimcore/document/tags/link.js", "/pimcore/static6/js/pimcore/document/tags/select.js", "/pimcore/static6/js/pimcore/document/tags/snippet.js", "/pimcore/static6/js/pimcore/document/tags/textarea.js", "/pimcore/static6/js/pimcore/document/tags/numeric.js", "/pimcore/static6/js/pimcore/document/tags/wysiwyg.js", "/pimcore/static6/js/pimcore/document/tags/renderlet.js", "/pimcore/static6/js/pimcore/document/tags/table.js", "/pimcore/static6/js/pimcore/document/tags/video.js", "/pimcore/static6/js/pimcore/document/tags/multiselect.js", "/pimcore/static6/js/pimcore/document/tags/areablock.js", "/pimcore/static6/js/pimcore/document/tags/area.js", "/pimcore/static6/js/pimcore/document/tags/pdf.js", "/pimcore/static6/js/pimcore/document/edit/helper.js"); $editmodeStylesheets = array("/pimcore/static6/css/icons.css", "/pimcore/static6/css/editmode.css?_dc=" . time()); } else { $editmodeLibraries = array("/pimcore/static/js/pimcore/namespace.js", "/pimcore/static/js/lib/prototype-light.js", "/pimcore/static/js/lib/jquery.min.js", "/pimcore/static/js/lib/ext/adapter/jquery/ext-jquery-adapter-debug.js", "/pimcore/static/js/lib/ext/ext-all-debug.js", "/pimcore/static/js/lib/ext-plugins/ux/Spinner.js", "/pimcore/static/js/lib/ext-plugins/ux/SpinnerField.js", "/pimcore/static/js/lib/ext-plugins/ux/MultiSelect.js", "/pimcore/static/js/lib/ext-plugins/GridRowOrder/roworder.js", "/pimcore/static/js/lib/ckeditor/ckeditor.js", "/pimcore/static/js/pimcore/libfixes.js"); $editmodeScripts = array("/pimcore/static/js/pimcore/functions.js", "/pimcore/static/js/pimcore/element/tag/imagehotspotmarkereditor.js", "/pimcore/static/js/pimcore/element/tag/imagecropper.js", "/pimcore/static/js/pimcore/document/edit/helper.js", "/pimcore/static/js/pimcore/document/edit/dnd.js", "/pimcore/static/js/pimcore/document/tag.js", "/pimcore/static/js/pimcore/document/tags/block.js", "/pimcore/static/js/pimcore/document/tags/date.js", "/pimcore/static/js/pimcore/document/tags/href.js", "/pimcore/static/js/pimcore/document/tags/multihref.js", "/pimcore/static/js/pimcore/document/tags/checkbox.js", "/pimcore/static/js/pimcore/document/tags/image.js", "/pimcore/static/js/pimcore/document/tags/input.js", "/pimcore/static/js/pimcore/document/tags/link.js", "/pimcore/static/js/pimcore/document/tags/select.js", "/pimcore/static/js/pimcore/document/tags/snippet.js", "/pimcore/static/js/pimcore/document/tags/textarea.js", "/pimcore/static/js/pimcore/document/tags/numeric.js", "/pimcore/static/js/pimcore/document/tags/wysiwyg.js", "/pimcore/static/js/pimcore/document/tags/renderlet.js", "/pimcore/static/js/pimcore/document/tags/table.js", "/pimcore/static/js/pimcore/document/tags/video.js", "/pimcore/static/js/pimcore/document/tags/multiselect.js", "/pimcore/static/js/pimcore/document/tags/areablock.js", "/pimcore/static/js/pimcore/document/tags/area.js", "/pimcore/static/js/pimcore/document/tags/pdf.js", "/pimcore/static/js/pimcore/document/edit/helper.js"); $editmodeStylesheets = array("/pimcore/static/css/icons.css", "/pimcore/static/css/editmode.css?asd=" . time()); } //add plugin editmode JS and CSS try { $pluginConfigs = ExtensionManager::getPluginConfigs(); $jsPaths = array(); $cssPaths = array(); if (!empty($pluginConfigs)) { //registering plugins foreach ($pluginConfigs as $p) { $pluginJsPaths = array(); if (array_key_exists("pluginDocumentEditmodeJsPaths", $p['plugin']) && is_array($p['plugin']['pluginDocumentEditmodeJsPaths']) && isset($p['plugin']['pluginDocumentEditmodeJsPaths']['path'])) { if (is_array($p['plugin']['pluginDocumentEditmodeJsPaths']['path'])) { $pluginJsPaths = $p['plugin']['pluginDocumentEditmodeJsPaths']['path']; } else { if ($p['plugin']['pluginDocumentEditmodeJsPaths']['path'] != null) { $pluginJsPaths[] = $p['plugin']['pluginDocumentEditmodeJsPaths']['path']; } } } //manipulate path for frontend if (is_array($pluginJsPaths) and count($pluginJsPaths) > 0) { for ($i = 0; $i < count($pluginJsPaths); $i++) { if (is_file(PIMCORE_PLUGINS_PATH . $pluginJsPaths[$i])) { $jsPaths[] = "/plugins" . $pluginJsPaths[$i]; } } } $pluginCssPaths = array(); if (array_key_exists("pluginDocumentEditmodeCssPaths", $p['plugin']) && is_array($p['plugin']['pluginDocumentEditmodeCssPaths']) && isset($p['plugin']['pluginDocumentEditmodeCssPaths']['path'])) { if (is_array($p['plugin']['pluginDocumentEditmodeCssPaths']['path'])) { $pluginCssPaths = $p['plugin']['pluginDocumentEditmodeCssPaths']['path']; } else { if ($p['plugin']['pluginDocumentEditmodeCssPaths']['path'] != null) { $pluginCssPaths[] = $p['plugin']['pluginDocumentEditmodeCssPaths']['path']; } } } //manipulate path for frontend if (is_array($pluginCssPaths) and count($pluginCssPaths) > 0) { for ($i = 0; $i < count($pluginCssPaths); $i++) { if (is_file(PIMCORE_PLUGINS_PATH . $pluginCssPaths[$i])) { $cssPaths[] = "/plugins" . $pluginCssPaths[$i]; } } } } } $editmodeScripts = array_merge($editmodeScripts, $jsPaths); $editmodeStylesheets = array_merge($editmodeStylesheets, $cssPaths); } catch (\Exception $e) { \Logger::alert("there is a problem with the plugin configuration"); \Logger::alert($e); } $editmodeHeadHtml = "\n\n\n<!-- pimcore editmode -->\n"; // include stylesheets foreach ($editmodeStylesheets as $sheet) { $editmodeHeadHtml .= '<link rel="stylesheet" type="text/css" href="' . $sheet . '?_dc=' . Version::$revision . '" />'; $editmodeHeadHtml .= "\n"; } $editmodeHeadHtml .= "\n\n"; $editmodeHeadHtml .= '<script type="text/javascript">var jQueryPreviouslyLoaded = (typeof jQuery == "undefined") ? false : true;</script>' . "\n"; // include script libraries foreach ($editmodeLibraries as $script) { $editmodeHeadHtml .= '<script type="text/javascript" src="' . $script . '?_dc=' . Version::$revision . '"></script>'; $editmodeHeadHtml .= "\n"; } // combine the pimcore scripts in non-devmode if ($conf->general->devmode) { foreach ($editmodeScripts as $script) { $editmodeHeadHtml .= '<script type="text/javascript" src="' . $script . '?_dc=' . Version::$revision . '"></script>'; $editmodeHeadHtml .= "\n"; } } else { $scriptContents = ""; foreach ($editmodeScripts as $scriptUrl) { $scriptContents .= file_get_contents(PIMCORE_DOCUMENT_ROOT . $scriptUrl) . "\n\n\n"; } $editmodeHeadHtml .= '<script type="text/javascript" src="' . \Pimcore\Tool\Admin::getMinimizedScriptPath($scriptContents) . '?_dc=' . Version::$revision . '"></script>' . "\n"; } $user = \Pimcore\Tool\Authentication::authenticateSession(); $lang = $user->getLanguage(); $editmodeHeadHtml .= '<script type="text/javascript" src="/admin/misc/json-translations-system/language/' . $lang . '/?_dc=' . Version::$revision . '"></script>' . "\n"; $editmodeHeadHtml .= '<script type="text/javascript" src="/admin/misc/json-translations-admin/language/' . $lang . '/?_dc=' . Version::$revision . '"></script>' . "\n"; $editmodeHeadHtml .= "\n\n"; // set var for editable configurations which is filled by Document\Tag::admin() $editmodeHeadHtml .= '<script type="text/javascript"> var editableConfigurations = new Array(); var pimcore_document_id = ' . $request->getParam("document")->getId() . '; if(jQueryPreviouslyLoaded) { jQuery.noConflict( true ); } </script>'; $editmodeHeadHtml .= "\n\n<!-- /pimcore editmode -->\n\n\n"; // add scripts in html header for pages in editmode if ($this->controller->editmode && Document\Service::isValidType($this->controller->document->getType())) { //ckogler include_once "simple_html_dom.php"; $body = $this->getResponse()->getBody(); $html = str_get_html($body); if ($html) { $htmlElement = $html->find("html", 0); $head = $html->find("head", 0); $bodyElement = $html->find("body", 0); // if there's no head and no body, create a wrapper including these elements // add html headers for snippets in editmode, so there is no problem with javascript if (!$head && !$bodyElement && !$htmlElement) { $body = "<!DOCTYPE html>\n<html>\n<head></head><body>" . $body . "</body></html>"; $html = str_get_html($body); // get them again with the updated html markup $htmlElement = $html->find("html", 0); $head = $html->find("head", 0); $bodyElement = $html->find("body", 0); } if ($head && $bodyElement && $htmlElement) { $head->innertext = $head->innertext . "\n\n" . $editmodeHeadHtml; $bodyElement->onunload = "pimcoreOnUnload();"; if (\Pimcore\Tool\Admin::isExtJS6()) { $bodyElement->innertext = $bodyElement->innertext . "\n\n" . '<script type="text/javascript" src="/pimcore/static6/js/pimcore/document/edit/startup.js?_dc=' . Version::$revision . '"></script>' . "\n\n"; } else { $bodyElement->innertext = $bodyElement->innertext . "\n\n" . '<script type="text/javascript" src="/pimcore/static/js/pimcore/document/edit/startup.js?_dc=' . Version::$revision . '"></script>' . "\n\n"; } $body = $html->save(); $this->getResponse()->setBody($body); } else { $this->getResponse()->setBody('<div style="font-size:30px; font-family: Arial; font-weight:bold; color:red; text-align: center; margin: 40px 0">You have to define a <html>, <head>, <body><br />HTML-tag in your view/layout markup!</div>'); } $html->clear(); unset($html); } } // IE compatibility //$this->getResponse()->setHeader("X-UA-Compatible", "IE=8; IE=9", true); }
* * Linfo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Linfo. If not, see <http://www.gnu.org/licenses/>. * */ /*######### PIMCORE MODIFICATION #########*/ $workingDirectory = getcwd(); include "../../../cli/startup.php"; chdir($workingDirectory); // only for logged in users $user = \Pimcore\Tool\Authentication::authenticateSession(); if (!$user instanceof User) { die("Authentication failed!"); } if (!$user->isAdmin()) { die("Permission denied"); } @ini_set("display_errors", "Off"); /*######### /PIMCORE MODIFICATION #########*/ // Load libs require_once dirname(__FILE__) . '/init.php'; // Begin try { // Load settings and language $linfo = new Linfo(); // Run through /proc or wherever and build our list of settings
/** * @throws \Zend_Controller_Router_Exception */ public function init() { // this is only executed once per request (first request) if (self::$isInitial) { \Pimcore::getEventManager()->trigger("frontend.controller.preInit", $this); } parent::init(); // log exceptions if handled by error_handler $this->checkForErrors(); // general definitions if (self::$isInitial) { \Pimcore::unsetAdminMode(); Document::setHideUnpublished(true); Object\AbstractObject::setHideUnpublished(true); Object\AbstractObject::setGetInheritedValues(true); Object\Localizedfield::setGetFallbackValues(true); } // assign variables $this->view->controller = $this; // init website config $config = Config::getWebsiteConfig(); $this->config = $config; $this->view->config = $config; $document = $this->getParam("document"); if (!$document instanceof Document) { \Zend_Registry::set("pimcore_editmode", false); $this->editmode = false; $this->view->editmode = false; self::$isInitial = false; // check for a locale first, and set it if available if ($this->getParam("pimcore_parentDocument")) { // this is a special exception for renderlets in editmode (ajax request), because they depend on the locale of the parent document // otherwise there'll be notices like: Notice: 'No translation for the language 'XX' available.' if ($parentDocument = Document::getById($this->getParam("pimcore_parentDocument"))) { if ($parentDocument->getProperty("language")) { $this->setLocaleFromDocument($parentDocument->getProperty("language")); } } } // no document available, continue, ... return; } else { $this->setDocument($document); // register global locale if the document has the system property "language" if ($this->getDocument()->getProperty("language")) { $this->setLocaleFromDocument($this->getDocument()->getProperty("language")); } if (self::$isInitial) { // append meta-data to the headMeta() view helper, if it is a document-request if (!Model\Staticroute::getCurrentRoute() && $this->getDocument() instanceof Document\Page) { if (is_array($this->getDocument()->getMetaData())) { foreach ($this->getDocument()->getMetaData() as $meta) { // only name if (!empty($meta["idName"]) && !empty($meta["idValue"]) && !empty($meta["contentValue"])) { $method = "append" . ucfirst($meta["idName"]); $this->view->headMeta()->{$method}($meta["idValue"], $meta["contentValue"]); } } } } } } // this is only executed once per request (first request) if (self::$isInitial) { // contains the logged in user if necessary $user = null; // default is to set the editmode to false, is enabled later if necessary \Zend_Registry::set("pimcore_editmode", false); if (Tool::isFrontentRequestByAdmin()) { $this->disableBrowserCache(); // start admin session & get logged in user $user = Authentication::authenticateSession(); } if (\Pimcore::inDebugMode()) { $this->disableBrowserCache(); } if (!$this->document->isPublished()) { if (Tool::isFrontentRequestByAdmin()) { if (!$user) { throw new \Zend_Controller_Router_Exception("access denied for " . $this->document->getFullPath()); } } else { throw new \Zend_Controller_Router_Exception("access denied for " . $this->document->getFullPath()); } } // logged in users only if ($user) { // set the user to registry so that it is available via \Pimcore\Tool\Admin::getCurrentUser(); \Zend_Registry::set("pimcore_admin_user", $user); // document editmode if ($this->getParam("pimcore_editmode")) { \Zend_Registry::set("pimcore_editmode", true); // check if there is the document in the session $docKey = "document_" . $this->getDocument()->getId(); $docSession = Session::getReadOnly("pimcore_documents"); if ($docSession->{$docKey}) { // if there is a document in the session use it $this->setDocument($docSession->{$docKey}); } else { // set the latest available version for editmode if there is no doc in the session $latestVersion = $this->getDocument()->getLatestVersion(); if ($latestVersion) { $latestDoc = $latestVersion->loadData(); if ($latestDoc instanceof Document\PageSnippet) { $this->setDocument($latestDoc); } } } // register editmode plugin $front = \Zend_Controller_Front::getInstance(); $front->registerPlugin(new \Pimcore\Controller\Plugin\Frontend\Editmode($this), 1000); } // document preview if ($this->getParam("pimcore_preview")) { // get document from session $docKey = "document_" . $this->getParam("document")->getId(); $docSession = Session::getReadOnly("pimcore_documents"); if ($docSession->{$docKey}) { $this->setDocument($docSession->{$docKey}); } } // object preview if ($this->getParam("pimcore_object_preview")) { $key = "object_" . $this->getParam("pimcore_object_preview"); $session = Session::getReadOnly("pimcore_objects"); if ($session->{$key}) { $object = $session->{$key}; // add the object to the registry so every call to Object::getById() will return this object instead of the real one \Zend_Registry::set("object_" . $object->getId(), $object); } } // for version preview if ($this->getParam("pimcore_version")) { // only get version data at the first call || because of embedded Snippets ... if (!\Zend_Registry::isRegistered("pimcore_version_active")) { $version = Model\Version::getById($this->getParam("pimcore_version")); $this->setDocument($version->getData()); \Zend_Registry::set("pimcore_version_active", true); } } } // for public versions if ($this->getParam("v")) { try { $version = Model\Version::getById($this->getParam("v")); if ($version->getPublic()) { $this->setDocument($version->getData()); } } catch (\Exception $e) { } } // check for persona if ($this->getDocument() instanceof Document\Page) { $this->getDocument()->setUsePersona(null); // reset because of preview and editmode (saved in session) if ($this->getParam("_ptp") && self::$isInitial) { $this->getDocument()->setUsePersona($this->getParam("_ptp")); } } // check if document is a wrapped hardlink, if this is the case send a rel=canonical header to the source document if ($this->getDocument() instanceof Document\Hardlink\Wrapper\WrapperInterface) { // get the cononical (source) document $hardlinkCanonicalSourceDocument = Document::getById($this->getDocument()->getId()); $request = $this->getRequest(); if (\Pimcore\Tool\Frontend::isDocumentInCurrentSite($hardlinkCanonicalSourceDocument)) { $this->getResponse()->setHeader("Link", '<' . $request->getScheme() . "://" . $request->getHttpHost() . $hardlinkCanonicalSourceDocument->getFullPath() . '>; rel="canonical"'); } } \Pimcore::getEventManager()->trigger("frontend.controller.postInit", $this); } // set some parameters $this->editmode = \Zend_Registry::get("pimcore_editmode"); $this->view->editmode = \Zend_Registry::get("pimcore_editmode"); self::$isInitial = false; }
/** * @throws \Zend_Exception */ public function init() { parent::init(); // set language if (\Zend_Registry::isRegistered("Zend_Locale")) { $locale = (string) \Zend_Registry::get("Zend_Locale"); $this->setLanguage($locale); } else { if ($this->getParam("language")) { $this->setLanguage($this->getParam("language")); } else { $config = Config::getSystemConfig(); $this->setLanguage($config->general->language); // try to set browser-language (validation if installed is in $this->setLanguage() ) $this->setLanguage(new \Zend_Locale()); } } if (self::$adminInitialized) { // this will be executed on every call to this init() method try { $this->setUser(\Zend_Registry::get("pimcore_admin_user")); } catch (\Exception $e) { \Logger::emerg("adminInitialized was set to true although there was no user set in the registry -> to be save the process was killed"); exit; } } else { // the following code is only called once, even when there are some subcalls (eg. with $this->action, ... ) \Pimcore::getEventManager()->trigger("admin.controller.preInit", $this); $this->disableBrowserCache(); // general definitions Model\Document::setHideUnpublished(false); Model\Object\AbstractObject::setHideUnpublished(false); Model\Object\AbstractObject::setGetInheritedValues(false); Model\Object\Localizedfield::setGetFallbackValues(false); \Pimcore::setAdminMode(); // init translations self::initTranslations($this); // init zend action helpers, we need to leave the prefixed class name here as the plugin loader isn't able to handle namespaces \Zend_Controller_Action_HelperBroker::addPrefix('Pimcore_Controller_Action_Helper'); // this is to make it possible to use the session id as a part of the route (ZF default route) used for external editors, etc. if ($this->getParam("pimcore_admin_sid")) { $_REQUEST["pimcore_admin_sid"] = $this->getParam("pimcore_admin_sid"); } // authenticate user, first try to authenticate with session information $user = Authentication::authenticateSession(); if ($user instanceof Model\User) { $this->setUser($user); if ($this->getUser()->getLanguage()) { $this->setLanguage($this->getUser()->getLanguage()); } } else { // try to authenticate with http basic auth, but this is only allowed for WebDAV if ($this->getParam("module") == "admin" && $this->getParam("controller") == "asset" && $this->getParam("action") == "webdav") { $user = Authentication::authenticateHttpBasic(); if ($user instanceof Model\User) { $this->setUser($user); \Zend_Registry::set("pimcore_admin_user", $this->getUser()); self::$adminInitialized = true; return; } } } // redirect to the login-page if the user isn't authenticated if (!$this->getUser() instanceof Model\User && !($this->getParam("module") == "admin" && $this->getParam("controller") == "login")) { // put a detailed message into the debug.log \Logger::error("Prevented access to " . $_SERVER["REQUEST_URI"] . " because there is no user in the session!", ["server" => $_SERVER, "get" => $_GET, "post" => $_POST, "session" => $_SESSION, "cookie" => $_COOKIE]); // send a auth header for the client (is covered by the ajax object in javascript) $this->getResponse()->setHeader("X-Pimcore-Auth", "required"); // redirect to login page $this->redirect("/admin/login"); // exit the execution -> just to be sure exit; } // we're now authenticated so we can remove the default error handler so that we get just the normal PHP errors if ($this->getParam("controller") != "login") { $front = \Zend_Controller_Front::getInstance(); $front->unregisterPlugin("Pimcore\\Controller\\Plugin\\ErrorHandler"); $front->throwExceptions(true); @ini_set("display_errors", "On"); @ini_set("display_startup_errors", "On"); } \Zend_Registry::set("pimcore_admin_user", $this->getUser()); self::$adminInitialized = true; // usage statistics $this->logUsageStatistics(); \Pimcore::getEventManager()->trigger("admin.controller.postInit", $this); } }
/** * @param $path * @param bool $partial * @return array|bool */ public function match($path, $partial = false) { // this allows the usage of UTF8 URLs and within static routes $path = urldecode($path); $front = \Zend_Controller_Front::getInstance(); $matchFound = false; $config = Config::getSystemConfig(); $routeingDefaults = Tool::getRoutingDefaults(); $params = array_merge($_GET, $_POST); $params = array_merge($routeingDefaults, $params); // set the original path $originalPath = $path; // check for password protection (http auth) if ($config->general->http_auth) { $username = $config->general->http_auth->username; $password = $config->general->http_auth->password; if ($username && $password && (!Tool::isFrontentRequestByAdmin() || !Tool\Authentication::authenticateSession())) { $adapter = new \Zend_Auth_Adapter_Http(["accept_schemes" => "basic", "realm" => Tool::getHostname()]); $basicResolver = new \Pimcore\Helper\Auth\Adapter\Http\ResolverStatic($username, $password); $adapter->setBasicResolver($basicResolver); $adapter->setRequest($front->getRequest()); $adapter->setResponse($front->getResponse()); $result = $adapter->authenticate(); if (!$result->isValid()) { // Bad userame/password, or canceled password prompt echo "Authentication Required"; $front->getResponse()->sendResponse(); exit; } } } // check for a registered site try { // do not initialize a site if it is a "special" admin request if (!Tool::isFrontentRequestByAdmin()) { $domain = Tool::getHostname(); $site = \Zend_Registry::isRegistered("pimcore_site") ? \Zend_Registry::get("pimcore_site") : Site::getByDomain($domain); $path = $site->getRootPath() . $path; \Zend_Registry::set("pimcore_site", $site); } } catch (\Exception $e) { } // test if there is a suitable redirect with override = all (=> priority = 99) $this->checkForRedirect($originalPath, true); // do not allow requests including /index.php/ => SEO // this is after the first redirect check, to allow redirects in index.php?xxx if (preg_match("@^/index.php(.*)@", $_SERVER["REQUEST_URI"], $matches) && strtolower($_SERVER["REQUEST_METHOD"]) == "get") { $redirectUrl = $matches[1]; $redirectUrl = ltrim($redirectUrl, "/"); $redirectUrl = "/" . $redirectUrl; header("Location: " . $redirectUrl, true, 301); exit; } // redirect to the main domain if specified try { $hostRedirect = null; if ($config->general->redirect_to_maindomain && $config->general->domain && $config->general->domain != Tool::getHostname() && !Site::isSiteRequest() && !Tool::isFrontentRequestByAdmin()) { $hostRedirect = $config->general->domain; } if (Site::isSiteRequest()) { $site = Site::getCurrentSite(); if ($site->getRedirectToMainDomain() && $site->getMainDomain() != Tool::getHostname()) { $hostRedirect = $site->getMainDomain(); } } if ($hostRedirect && !isset($_GET["pimcore_disable_host_redirect"])) { $url = ($front->getRequest()->isSecure() ? "https" : "http") . "://" . $hostRedirect . $_SERVER["REQUEST_URI"]; header("HTTP/1.1 301 Moved Permanently"); header("Location: " . $url, true, 301); // log all redirects to the redirect log \Pimcore\Log\Simple::log("redirect", Tool::getAnonymizedClientIp() . " \t Host-Redirect Source: " . $_SERVER["REQUEST_URI"] . " -> " . $url); exit; } } catch (\Exception $e) { } // check for direct definition of controller/action if (!empty($_REQUEST["controller"]) && !empty($_REQUEST["action"])) { $matchFound = true; } // test if there is a suitable page if (!$matchFound) { try { $document = Document::getByPath($path); // check for a pretty url inside a site if (!$document && Site::isSiteRequest()) { $documentService = new Document\Service(); $sitePrettyDocId = $documentService->getDocumentIdByPrettyUrlInSite(Site::getCurrentSite(), $originalPath); if ($sitePrettyDocId) { if ($sitePrettyDoc = Document::getById($sitePrettyDocId)) { $document = $sitePrettyDoc; // undo the modification of the path by the site detection (prefixing with site root path) // this is not necessary when using pretty-urls and will cause problems when validating the // prettyUrl later (redirecting to the prettyUrl in the case the page was called by the real path) $path = $originalPath; } } } // check for a parent hardlink with childs if (!$document instanceof Document) { $hardlinkedParentDocument = $this->getNearestDocumentByPath($path, true); if ($hardlinkedParentDocument instanceof Document\Hardlink) { if ($hardLinkedDocument = Document\Hardlink\Service::getChildByPath($hardlinkedParentDocument, $path)) { $document = $hardLinkedDocument; } } } // check for direct hardlink if ($document instanceof Document\Hardlink) { $hardlinkParentDocument = $document; $document = Document\Hardlink\Service::wrap($hardlinkParentDocument); } if ($document instanceof Document) { if (in_array($document->getType(), self::getDirectRouteDocumentTypes())) { if (Tool::isFrontentRequestByAdmin() || $document->isPublished()) { $redirectTargetUrl = $originalPath; // check for a pretty url, and if the document is called by that, otherwise redirect to pretty url if ($document instanceof Document\Page && !$document instanceof Document\Hardlink\Wrapper\WrapperInterface && $document->getPrettyUrl() && !Tool::isFrontentRequestByAdmin()) { if (rtrim(strtolower($document->getPrettyUrl()), " /") != rtrim(strtolower($originalPath), "/")) { $redirectTargetUrl = $document->getPrettyUrl(); } } $params["document"] = $document; if ($controller = $document->getController()) { $params["controller"] = $controller; $params["action"] = "index"; } if ($action = $document->getAction()) { $params["action"] = $action; } if ($module = $document->getModule()) { $params["module"] = $module; } // check for a trailing slash in path, if exists, redirect to this page without the slash // the only reason for this is: SEO, Analytics, ... there is no system specific reason, pimcore would work also with a trailing slash without problems // use $originalPath because of the sites // only do redirecting with GET requests if (strtolower($_SERVER["REQUEST_METHOD"]) == "get") { if ($config->documents->allowtrailingslash) { if ($config->documents->allowtrailingslash == "no") { if (substr($redirectTargetUrl, strlen($redirectTargetUrl) - 1, 1) == "/" && $redirectTargetUrl != "/") { $redirectTargetUrl = rtrim($redirectTargetUrl, "/"); } } } // only allow the original key of a document to be the URL (lowercase/uppercase) if ($redirectTargetUrl != rawurldecode($document->getFullPath())) { $redirectTargetUrl = $document->getFullPath(); } } if ($redirectTargetUrl !== $originalPath) { if ($_SERVER["QUERY_STRING"]) { $redirectTargetUrl .= "?" . $_SERVER["QUERY_STRING"]; } header("Location: " . $redirectTargetUrl, true, 301); exit; } $matchFound = true; } } elseif ($document->getType() == "link") { // if the document is a link just redirect to the location/href of the link header("Location: " . $document->getHref(), true, 301); exit; } } } catch (\Exception $e) { // no suitable page found $foo = "bar"; } } // test if there is a suitable static route if (!$matchFound) { try { $list = new Staticroute\Listing(); $list->setOrder(function ($a, $b) { if ($a["priority"] == $b["priority"]) { return 0; } return $a["priority"] < $b["priority"] ? 1 : -1; }); $routes = $list->load(); foreach ($routes as $route) { if (!$matchFound) { $routeParams = $route->match($originalPath, $params); if ($routeParams) { $params = $routeParams; // try to get nearest document to the route $document = $this->getNearestDocumentByPath($path, false, ["page", "snippet", "hardlink"]); if ($document instanceof Document\Hardlink) { $document = Document\Hardlink\Service::wrap($document); } $params["document"] = $document; $matchFound = true; Staticroute::setCurrentRoute($route); // add the route object also as parameter to the request object, this is needed in // Pimcore_Controller_Action_Frontend::getRenderScript() // to determine if a call to an action was made through a staticroute or not // more on that infos see Pimcore_Controller_Action_Frontend::getRenderScript() $params["pimcore_request_source"] = "staticroute"; break; } } } } catch (\Exception $e) { // no suitable route found } } // test if there is a suitable redirect if (!$matchFound) { $this->checkForRedirect($originalPath, false); } if (!$matchFound) { return false; } // remove pimcore magic parameters unset($params["pimcore_outputfilters_disabled"]); unset($params["pimcore_document"]); unset($params["nocache"]); return $params; }
/** * Enables the test mode. X-pimcore-unit-test-request=true header will be sent. */ public function enableTestMode() { $this->client->setHeaders("X-pimcore-unit-test-request", "true"); if (!$this->getApiKey()) { $username = "******"; $password = $username; $user = User::getByName("{$username}"); if (!$user) { $apikey = md5(time()) . md5($username); $user = User::create(array("parentId" => 0, "username" => "rest", "password" => \Pimcore\Tool\Authentication::getPasswordHash($username, $username), "active" => true, "apiKey" => $apikey, "admin" => true)); } $apikey = $user->getApiKey(); $this->setApiKey($apikey); } $this->setTestMode(true); }
public function getTokenLoginLinkAction() { $user = User::getById($this->getParam("id")); if ($user->isAdmin() && !$this->getUser()->isAdmin()) { throw new \Exception("Only admin users are allowed to login as an admin user"); } if ($user) { $token = Tool\Authentication::generateToken($user->getName(), $user->getPassword()); $r = $this->getRequest(); $link = $r->getScheme() . "://" . $r->getHttpHost() . "/admin/login/login/?username="******"&token=" . $token; $this->_helper->json(["link" => $link]); } }
/** * @static * @throws Exception|\Zend_Controller_Router_Exception */ public static function run() { self::setSystemRequirements(); // detect frontend (website) $frontend = Tool::isFrontend(); // enable the output-buffer, why? see in self::outputBufferStart() //if($frontend) { self::outputBufferStart(); //} self::initAutoloader(); self::initConfiguration(); self::setupFramework(); // config is loaded now init the real logger self::initLogger(); // initialize cache Cache::init(); // load plugins and modules (=core plugins) self::initModules(); self::initPlugins(); // init front controller $front = \Zend_Controller_Front::getInstance(); $conf = Config::getSystemConfig(); if (!$conf) { // redirect to installer if configuration isn't present if (!preg_match("/^\\/install.*/", $_SERVER["REQUEST_URI"])) { header("Location: /install/"); exit; } } if (self::inDebugMode() && $frontend && !$conf->general->disable_whoops && !defined("HHVM_VERSION")) { $whoops = new \Whoops\Run(); $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler()); $jsonErrorHandler = new \Whoops\Handler\JsonResponseHandler(); $jsonErrorHandler->onlyForAjaxRequests(true); $whoops->pushHandler($jsonErrorHandler); $whoops->register(); // add event handler before Pimcore::shutdown() to ensure fatal errors are handled by Whoops self::getEventManager()->attach("system.shutdown", array($whoops, "handleShutdown"), 10000); } $front->registerPlugin(new Controller\Plugin\ErrorHandler(), 1); $front->registerPlugin(new Controller\Plugin\Maintenance(), 2); // register general pimcore plugins for frontend if ($frontend) { $front->registerPlugin(new Controller\Plugin\Thumbnail(), 795); $front->registerPlugin(new Controller\Plugin\Less(), 799); $front->registerPlugin(new Controller\Plugin\AdminButton(), 806); } if (Tool::useFrontendOutputFilters(new \Zend_Controller_Request_Http())) { $front->registerPlugin(new Controller\Plugin\HybridAuth(), 792); $front->registerPlugin(new Controller\Plugin\QrCode(), 793); $front->registerPlugin(new Controller\Plugin\CommonFilesFilter(), 794); $front->registerPlugin(new Controller\Plugin\WysiwygAttributes(), 796); $front->registerPlugin(new Controller\Plugin\Webmastertools(), 797); $front->registerPlugin(new Controller\Plugin\Analytics(), 798); $front->registerPlugin(new Controller\Plugin\TagManagement(), 804); $front->registerPlugin(new Controller\Plugin\Targeting(), 805); $front->registerPlugin(new Controller\Plugin\EuCookieLawNotice(), 807); $front->registerPlugin(new Controller\Plugin\HttpErrorLog(), 850); $front->registerPlugin(new Controller\Plugin\Cache(), 901); // for caching } self::initControllerFront($front); // set router $router = $front->getRouter(); $routeAdmin = new \Zend_Controller_Router_Route('admin/:controller/:action/*', array('module' => 'admin', "controller" => "index", "action" => "index")); $routeInstall = new \Zend_Controller_Router_Route('install/:controller/:action/*', array('module' => 'install', "controller" => "index", "action" => "index")); $routeUpdate = new \Zend_Controller_Router_Route('admin/update/:controller/:action/*', array('module' => 'update', "controller" => "index", "action" => "index")); $routePlugins = new \Zend_Controller_Router_Route('admin/plugin/:controller/:action/*', array('module' => 'pluginadmin', "controller" => "index", "action" => "index")); $routeExtensions = new \Zend_Controller_Router_Route('admin/extensionmanager/:controller/:action/*', array('module' => 'extensionmanager', "controller" => "index", "action" => "index")); $routeReports = new \Zend_Controller_Router_Route('admin/reports/:controller/:action/*', array('module' => 'reports', "controller" => "index", "action" => "index")); $routePlugin = new \Zend_Controller_Router_Route('plugin/:module/:controller/:action/*', array("controller" => "index", "action" => "index")); $routeWebservice = new \Zend_Controller_Router_Route('webservice/:controller/:action/*', array("module" => "webservice", "controller" => "index", "action" => "index")); $routeSearchAdmin = new \Zend_Controller_Router_Route('admin/search/:controller/:action/*', array("module" => "searchadmin", "controller" => "index", "action" => "index")); // website route => custom router which check for a suitable document $routeFrontend = new Controller\Router\Route\Frontend(); $router->addRoute('default', $routeFrontend); // only do this if not frontend => performance issue if (!$frontend) { $router->addRoute("install", $routeInstall); $router->addRoute('plugin', $routePlugin); $router->addRoute('admin', $routeAdmin); $router->addRoute('update', $routeUpdate); $router->addRoute('plugins', $routePlugins); $router->addRoute('extensionmanager', $routeExtensions); $router->addRoute('reports', $routeReports); $router->addRoute('searchadmin', $routeSearchAdmin); if ($conf instanceof \Zend_Config and $conf->webservice and $conf->webservice->enabled) { $router->addRoute('webservice', $routeWebservice); } // check if this request routes into a plugin, if so check if the plugin is enabled if (preg_match("@^/plugin/([^/]+)/.*@", $_SERVER["REQUEST_URI"], $matches)) { $pluginName = $matches[1]; if (!Pimcore\ExtensionManager::isEnabled("plugin", $pluginName)) { \Pimcore\Tool::exitWithError("Plugin is disabled. To use this plugin please enable it in the extension manager!"); } } // force the main (default) domain for "admin" requests if ($conf->general->domain && $conf->general->domain != Tool::getHostname()) { $url = ($_SERVER['HTTPS'] == "on" ? "https" : "http") . "://" . $conf->general->domain . $_SERVER["REQUEST_URI"]; header("HTTP/1.1 301 Moved Permanently"); header("Location: " . $url, true, 301); exit; } } // check if webdav is configured and add router if ($conf instanceof \Zend_Config) { if ($conf->assets->webdav->hostname) { $routeWebdav = new \Zend_Controller_Router_Route_Hostname($conf->assets->webdav->hostname, array("module" => "admin", 'controller' => 'asset', 'action' => 'webdav')); $router->addRoute('webdav', $routeWebdav); } } $front->setRouter($router); self::getEventManager()->trigger("system.startup", $front); // throw exceptions also when in preview or in editmode (documents) to see it immediately when there's a problem with this page $throwExceptions = false; if (Tool::isFrontentRequestByAdmin()) { $user = \Pimcore\Tool\Authentication::authenticateSession(); if ($user instanceof User) { $throwExceptions = true; } } // run dispatcher // this is also standard for /admin/ requests -> error handling is done in Pimcore_Controller_Action_Admin if (!PIMCORE_DEBUG && !$throwExceptions && !PIMCORE_DEVMODE) { @ini_set("display_errors", "Off"); @ini_set("display_startup_errors", "Off"); $front->dispatch(); } else { @ini_set("display_errors", "On"); @ini_set("display_startup_errors", "On"); $front->throwExceptions(true); try { $front->dispatch(); } catch (\Zend_Controller_Router_Exception $e) { if (!headers_sent()) { header("HTTP/1.0 404 Not Found"); } \Logger::err($e); throw new \Zend_Controller_Router_Exception("No route, document, custom route or redirect is matching the request: " . $_SERVER["REQUEST_URI"] . " | \n" . "Specific ERROR: " . $e->getMessage()); } catch (\Exception $e) { if (!headers_sent()) { header("HTTP/1.0 500 Internal Server Error"); } throw $e; } } }