Inheritance: extends Pimcore\Model\User\UserRole
 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;
 }
Example #2
1
 /**
  * @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();
 }
Example #3
0
 public function lostpasswordAction()
 {
     $username = $this->getParam("username");
     if ($username) {
         $user = User::getByName($username);
         if (!$user instanceof User) {
             $this->view->error = "user unknown";
         } else {
             if ($user->isActive()) {
                 if ($user->getEmail()) {
                     $token = Tool\Authentication::generateToken($username, $user->getPassword());
                     $uri = $this->getRequest()->getScheme() . "://" . $this->getRequest()->getHttpHost();
                     $loginUrl = $uri . "/admin/login/login/?username="******"&token=" . $token . "&reset=true";
                     try {
                         $mail = Tool::getMail(array($user->getEmail()), "Pimcore lost password service");
                         $mail->setIgnoreDebugMode(true);
                         $mail->setBodyText("Login to pimcore and change your password using the following link. This temporary login link will expire in 30 minutes: \r\n\r\n" . $loginUrl);
                         $mail->send();
                         $this->view->success = true;
                     } catch (\Exception $e) {
                         $this->view->error = "could not send email";
                     }
                 } else {
                     $this->view->error = "user has no email address";
                 }
             } else {
                 $this->view->error = "user inactive";
             }
         }
     }
 }
Example #4
0
 /**
  * @param Model\User $user
  * @return $this
  */
 public function setUser(Model\User $user)
 {
     $this->user = $user;
     \Zend_Registry::set("pimcore_admin_user", $this->user);
     $this->setLanguage($this->user->getLanguage());
     return $this;
 }
 public function init()
 {
     $this->allParam = $this->getAllParams();
     // set api key
     $this->apiKey = isset($this->apiKey) ? $this->apiKey : \Pimcore\Model\User::getByName($this->userApiBridgeMagento)->getApiKey();
     if (!$this->validateApiKey()) {
         die;
         // no any error info provided
     }
     // init api
     $this->apiModel = new ApiBridgeMagento_Api();
 }
Example #6
0
 /**
  *
  */
 public function mail()
 {
     $conf = Config::getSystemConfig();
     if (!empty($conf->general->logrecipient)) {
         \Logger::debug(get_class($this) . ": detected log recipient:" . $conf->general->logrecipient);
         $user = User::getById($conf->general->logrecipient);
         \Logger::debug(get_class($this) . ": detected log recipient:" . $user->getEmail());
         if ($user instanceof User && $user->isAdmin()) {
             $email = $user->getEmail();
             \Logger::debug(get_class($this) . ": user is valid");
             if (!empty($email)) {
                 if (is_dir(PIMCORE_LOG_MAIL_TEMP)) {
                     \Logger::debug(get_class($this) . ": detected mail log dir");
                     \Logger::debug(get_class($this) . ": opening dir " . PIMCORE_LOG_MAIL_TEMP);
                     if ($handle = opendir(PIMCORE_LOG_MAIL_TEMP)) {
                         \Logger::debug(get_class($this) . ": reading dir " . PIMCORE_LOG_MAIL_TEMP);
                         while (false !== ($file = readdir($handle))) {
                             \Logger::debug(get_class($this) . ": detected file " . $file);
                             if (is_file(PIMCORE_LOG_MAIL_TEMP . "/" . $file) and is_writable(PIMCORE_LOG_MAIL_TEMP . "/" . $file)) {
                                 $now = time();
                                 $threshold = 1 * 60 * 15;
                                 $fileModified = filemtime(PIMCORE_LOG_MAIL_TEMP . "/" . $file);
                                 \Logger::debug(get_class($this) . ": file is writeable and was last modified: " . $fileModified);
                                 if ($fileModified !== FALSE and $fileModified < $now - $threshold) {
                                     $mail = Tool::getMail(array($email), "pimcore log notification - " . $file);
                                     $mail->setIgnoreDebugMode(true);
                                     $mail->setBodyText(file_get_contents(PIMCORE_LOG_MAIL_TEMP . "/" . $file));
                                     $mail->send();
                                     @unlink(PIMCORE_LOG_MAIL_TEMP . "/" . $file);
                                     \Logger::debug(get_class($this) . ": sent mail and deleted temp log file " . $file);
                                 } else {
                                     if ($fileModified > $now - $threshold) {
                                         \Logger::debug(get_class($this) . ": leaving temp log file alone because file [ {$file} ] was written to within the last 15 minutes");
                                     }
                                 }
                             }
                         }
                     }
                 }
             } else {
                 \Logger::err(get_class($this) . ": Cannot send mail to configured log user [" . $user->getName() . "] because email is empty");
             }
         } else {
             \Logger::err(get_class($this) . ": Cannot send mail to configured log user. User is either null or not an admin");
         }
     } else {
         \Logger::debug(get_class($this) . ": No log recipient configured");
     }
 }
Example #7
0
 /**
  * @param $target
  * @param $source
  * @return mixed
  * @throws \Exception
  */
 public function copyContents($target, $source)
 {
     // check if the type is the same
     if (get_class($source) != get_class($target)) {
         throw new \Exception("Source and target have to be the same type");
     }
     if (!$source instanceof Asset\Folder) {
         $target->setStream($source->getStream());
         $target->setCustomSettings($source->getCustomSettings());
     }
     $target->setUserModification($this->_user->getId());
     $target->setProperties($source->getProperties());
     $target->save();
     return $target;
 }
Example #8
0
 /**
  * @param $target
  * @param $source
  * @return AbstractObject
  * @throws \Exception
  */
 public function copyContents($target, $source)
 {
     // check if the type is the same
     if (get_class($source) != get_class($target)) {
         throw new \Exception("Source and target have to be the same type");
     }
     //load all in case of lazy loading fields
     self::loadAllObjectFields($source);
     $new = clone $source;
     $new->setChilds($target->getChilds());
     $new->setId($target->getId());
     $new->setPath($target->getPath());
     $new->setKey($target->getKey());
     $new->setParentId($target->getParentId());
     $new->setScheduledTasks($source->getScheduledTasks());
     $new->setProperties($source->getProperties());
     $new->setUserModification($this->_user->getId());
     $new->save();
     $target = AbstractObject::getById($new->getId());
     return $target;
 }
Example #9
0
 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]);
     }
 }
Example #10
0
 /**
  * @return string
  */
 protected function getInfoDocBlock()
 {
     $cd = "";
     $cd .= "/** ";
     $cd .= "\n";
     $cd .= "* Generated at: " . date('c') . "\n";
     $cd .= "* Inheritance: " . ($this->getAllowInherit() ? "yes" : "no") . "\n";
     $cd .= "* Variants: " . ($this->getAllowVariants() ? "yes" : "no") . "\n";
     $user = Model\User::getById($this->getUserModification());
     if ($user) {
         $cd .= "* Changed by: " . $user->getName() . " (" . $user->getId() . ")" . "\n";
     }
     if (isset($_SERVER["REMOTE_ADDR"])) {
         $cd .= "* IP: " . $_SERVER["REMOTE_ADDR"] . "\n";
     }
     if ($this->getDescription()) {
         $description = str_replace(["/**", "*/", "//"], "", $this->getDescription());
         $description = str_replace("\n", "\n* ", $description);
         $cd .= "* " . $description . "\n";
     }
     $cd .= "\n\n";
     $cd .= "Fields Summary: \n";
     $cd = $this->getInfoDocBlockForFields($this, $cd, 1);
     $cd .= "*/ ";
     return $cd;
 }
Example #11
0
 /**
  * @param integer $userId
  * @return void
  */
 public function setUserId($userId)
 {
     if ($userId) {
         if ($user = Model\User::getById($userId)) {
             $this->userId = (int) $userId;
             $this->setUser($user);
         }
     }
     return $this;
 }
Example #12
0
 public function noteListAction()
 {
     $this->checkPermission("notes_events");
     $list = new Element\Note\Listing();
     $list->setLimit($this->getParam("limit"));
     $list->setOffset($this->getParam("start"));
     $sortingSettings = \Pimcore\Admin\Helper\QueryParams::extractSortingSettings($this->getAllParams());
     if ($sortingSettings['orderKey'] && $sortingSettings['order']) {
         $list->setOrderKey($sortingSettings['orderKey']);
         $list->setOrder($sortingSettings['order']);
     } else {
         $list->setOrderKey(["date", "id"]);
         $list->setOrder(["DESC", "DESC"]);
     }
     $conditions = [];
     if ($this->getParam("filter")) {
         $conditions[] = "(`title` LIKE " . $list->quote("%" . $this->getParam("filter") . "%") . " OR `description` LIKE " . $list->quote("%" . $this->getParam("filter") . "%") . " OR `type` LIKE " . $list->quote("%" . $this->getParam("filter") . "%") . ")";
     }
     if ($this->getParam("cid") && $this->getParam("ctype")) {
         $conditions[] = "(cid = " . $list->quote($this->getParam("cid")) . " AND ctype = " . $list->quote($this->getParam("ctype")) . ")";
     }
     if (!empty($conditions)) {
         $list->setCondition(implode(" AND ", $conditions));
     }
     $list->load();
     $notes = [];
     foreach ($list->getNotes() as $note) {
         $cpath = "";
         if ($note->getCid() && $note->getCtype()) {
             if ($element = Element\Service::getElementById($note->getCtype(), $note->getCid())) {
                 $cpath = $element->getRealFullPath();
             }
         }
         $e = ["id" => $note->getId(), "type" => $note->getType(), "cid" => $note->getCid(), "ctype" => $note->getCtype(), "cpath" => $cpath, "date" => $note->getDate(), "title" => $note->getTitle(), "description" => $note->getDescription()];
         // prepare key-values
         $keyValues = [];
         if (is_array($note->getData())) {
             foreach ($note->getData() as $name => $d) {
                 $type = $d["type"];
                 $data = $d["data"];
                 if ($type == "document" || $type == "object" || $type == "asset") {
                     if ($d["data"] instanceof Element\ElementInterface) {
                         $data = ["id" => $d["data"]->getId(), "path" => $d["data"]->getRealFullPath(), "type" => $d["data"]->getType()];
                     }
                 } elseif ($type == "date") {
                     if (is_object($d["data"])) {
                         $data = $d["data"]->getTimestamp();
                     }
                 }
                 $keyValue = ["type" => $type, "name" => $name, "data" => $data];
                 $keyValues[] = $keyValue;
             }
         }
         $e["data"] = $keyValues;
         // prepare user data
         if ($note->getUser()) {
             $user = Model\User::getById($note->getUser());
             if ($user) {
                 $e["user"] = ["id" => $user->getId(), "name" => $user->getName()];
             } else {
                 $e["user"] = "";
             }
         }
         $notes[] = $e;
     }
     $this->_helper->json(["data" => $notes, "success" => true, "total" => $list->getTotalCount()]);
 }
Example #13
0
 /**
  * @param integer $userId
  * @return void
  */
 public function setUserId($userId)
 {
     if (is_numeric($userId)) {
         if ($user = User::getById($userId)) {
             $this->userId = (int) $userId;
             $this->setUser($user);
         }
     }
     return $this;
 }
Example #14
0
 /**
  * @static
  *
  */
 public static function initLogger()
 {
     // for forks, etc ...
     \Logger::resetLoggers();
     // try to load configuration
     $conf = Config::getSystemConfig();
     if ($conf) {
         // redirect php error_log to /website/var/log/php.log
         if ($conf->general->custom_php_logfile) {
             $phpLog = PIMCORE_LOG_DIRECTORY . "/php.log";
             if (!file_exists($phpLog)) {
                 touch($phpLog);
             }
             if (is_writable($phpLog)) {
                 ini_set("error_log", $phpLog);
                 ini_set("log_errors", "1");
             }
         }
     }
     if (!is_file(PIMCORE_LOG_DEBUG)) {
         if (is_writable(dirname(PIMCORE_LOG_DEBUG))) {
             File::put(PIMCORE_LOG_DEBUG, "AUTOCREATE\n");
         }
     }
     $prios = [];
     $availablePrios = \Logger::getAvailablePriorities();
     if ($conf && $conf->general->debugloglevel) {
         foreach ($availablePrios as $level) {
             $prios[] = $level;
             if ($level == $conf->general->debugloglevel) {
                 break;
             }
         }
         \Logger::setPriorities($prios);
     } else {
         \Logger::setVerbosePriorities();
     }
     if (is_writable(PIMCORE_LOG_DEBUG)) {
         // check for big logfile, empty it if it's bigger than about 200M
         if (filesize(PIMCORE_LOG_DEBUG) > 200000000) {
             rename(PIMCORE_LOG_DEBUG, PIMCORE_LOG_DEBUG . "-archive-" . date("m-d-Y-H-i"));
             // archive log (will be cleaned up by maintenance)
             File::put(PIMCORE_LOG_DEBUG, "");
         }
         // set default core logger (debug.log)
         if (!empty($prios)) {
             $loggerFile = new \Monolog\Logger('core');
             $loggerFile->pushHandler(new \Monolog\Handler\StreamHandler(PIMCORE_LOG_DEBUG));
             \Logger::addLogger($loggerFile);
         }
         $conf = Config::getSystemConfig();
         if ($conf) {
             //email logger
             if (!empty($conf->general->logrecipient)) {
                 $user = User::getById($conf->general->logrecipient);
                 if ($user instanceof User && $user->isAdmin()) {
                     $email = $user->getEmail();
                     if (!empty($email)) {
                         $loggerMail = new \Monolog\Logger('email');
                         $mailHandler = new \Pimcore\Log\Handler\Mail($email);
                         $loggerMail->pushHandler(new \Monolog\Handler\BufferHandler($mailHandler));
                         \Logger::addLogger($loggerMail);
                     }
                 }
             }
         }
     } else {
         // try to use syslog instead
         try {
             $loggerSyslog = new \Monolog\Logger('core');
             $loggerSyslog->pushHandler(new \Monolog\Handler\SyslogHandler("pimcore"));
             \Logger::addLogger($loggerSyslog);
         } catch (\Exception $e) {
             // nothing to do here
         }
     }
     // special request log -> if parameter pimcore_log is set
     if (array_key_exists("pimcore_log", $_REQUEST) && self::inDebugMode()) {
         if (empty($_REQUEST["pimcore_log"])) {
             $requestLogName = date("Y-m-d_H-i-s");
         } else {
             $requestLogName = $_REQUEST["pimcore_log"];
         }
         $requestLogFile = dirname(PIMCORE_LOG_DEBUG) . "/request-" . $requestLogName . ".log";
         if (!file_exists($requestLogFile)) {
             File::put($requestLogFile, "");
         }
         $loggerRequest = new \Monolog\Logger('request');
         $loggerRequest->pushHandler(new \Monolog\Handler\StreamHandler($requestLogFile));
         \Logger::addLogger($loggerRequest);
         \Logger::setVerbosePriorities();
     }
 }
Example #15
0
 /**
  * @param User $user
  * @param $password
  * @return bool
  */
 public static function verifyPassword($user, $password)
 {
     $password = self::preparePlainTextPassword($user->getName(), $password);
     if ($user->getPassword()) {
         // do not allow logins for users without a password
         if (password_verify($password, $user->getPassword())) {
             if (password_needs_rehash($user->getPassword(), PASSWORD_DEFAULT)) {
                 $user->setPassword(self::getPasswordHash($user->getName(), $password));
                 $user->save();
             }
             return true;
         }
     }
     return false;
 }
Example #16
0
 /**
  * @param Model\User $user
  * @return $this
  */
 public function setUser(Model\User $user)
 {
     $this->user = $user;
     \Zend_Registry::set("pimcore_admin_user", $this->user);
     $this->setLanguage($this->user->getLanguage());
     // update perspective settings
     $requestedPerspective = $this->getParam("perspective");
     if ($requestedPerspective) {
         if ($requestedPerspective != $user->getActivePerspective()) {
             $existingPerspectives = array_keys(Config::getPerspectivesConfig()->toArray());
             if (!in_array($requestedPerspective, $existingPerspectives)) {
                 $requestedPerspective = null;
             }
         }
     }
     if (!$requestedPerspective) {
         $requestedPerspective = $user->getActivePerspective();
     }
     //TODO check if perspective is still allowed
     if ($requestedPerspective != $user->getActivePerspective()) {
         $user->setActivePerspective($requestedPerspective);
         $user->save();
     }
     return $this;
 }
Example #17
0
 /**
  * @static
  *
  */
 public static function initLogger()
 {
     // for forks, etc ...
     \Logger::resetLoggers();
     // try to load configuration
     $conf = Config::getSystemConfig();
     if ($conf) {
         // redirect php error_log to /website/var/log/php.log
         if ($conf->general->custom_php_logfile) {
             $phpLog = PIMCORE_LOG_DIRECTORY . "/php.log";
             if (!file_exists($phpLog)) {
                 touch($phpLog);
             }
             if (is_writable($phpLog)) {
                 ini_set("error_log", $phpLog);
                 ini_set("log_errors", "1");
             }
         }
     }
     if (!is_file(PIMCORE_LOG_DEBUG)) {
         if (is_writable(dirname(PIMCORE_LOG_DEBUG))) {
             File::put(PIMCORE_LOG_DEBUG, "AUTOCREATE\n");
         }
     }
     $prioMapping = array("debug" => \Zend_Log::DEBUG, "info" => \Zend_Log::INFO, "notice" => \Zend_Log::NOTICE, "warning" => \Zend_Log::WARN, "error" => \Zend_Log::ERR, "critical" => \Zend_Log::CRIT, "alert" => \Zend_Log::ALERT, "emergency" => \Zend_Log::EMERG);
     $prios = array();
     if ($conf && $conf->general->debugloglevel) {
         $prioMapping = array_reverse($prioMapping);
         foreach ($prioMapping as $level => $state) {
             $prios[] = $prioMapping[$level];
             if ($level == $conf->general->debugloglevel) {
                 break;
             }
         }
     } else {
         // log everything if config isn't loaded (eg. at the installer)
         foreach ($prioMapping as $p) {
             $prios[] = $p;
         }
     }
     \Logger::setPriorities($prios);
     if (is_writable(PIMCORE_LOG_DEBUG)) {
         // check for big logfile, empty it if it's bigger than about 200M
         if (filesize(PIMCORE_LOG_DEBUG) > 200000000) {
             rename(PIMCORE_LOG_DEBUG, PIMCORE_LOG_DEBUG . "-archive-" . date("m-d-Y-H-i"));
             // archive log (will be cleaned up by maintenance)
             File::put(PIMCORE_LOG_DEBUG, "");
         }
         if (!empty($prios)) {
             $writerFile = new \Zend_Log_Writer_Stream(PIMCORE_LOG_DEBUG);
             $loggerFile = new \Zend_Log($writerFile);
             \Logger::addLogger($loggerFile);
         }
         $conf = Config::getSystemConfig();
         if ($conf) {
             //email logger
             if (!empty($conf->general->logrecipient)) {
                 $user = User::getById($conf->general->logrecipient);
                 if ($user instanceof User && $user->isAdmin()) {
                     $email = $user->getEmail();
                     if (!empty($email)) {
                         $mail = Tool::getMail(array($email), "pimcore log notification");
                         $mail->setIgnoreDebugMode(true);
                         if (!is_dir(PIMCORE_LOG_MAIL_TEMP)) {
                             File::mkdir(PIMCORE_LOG_MAIL_TEMP);
                         }
                         $tempfile = PIMCORE_LOG_MAIL_TEMP . "/log-" . uniqid() . ".log";
                         $writerEmail = new \Pimcore\Log\Writer\Mail($tempfile, $mail);
                         $loggerEmail = new \Zend_Log($writerEmail);
                         \Logger::addLogger($loggerEmail);
                     }
                 }
             }
         }
     } else {
         // try to use syslog instead
         try {
             $writerSyslog = new \Zend_Log_Writer_Syslog(array('application' => 'pimcore'));
             $loggerSyslog = new \Zend_Log($writerSyslog);
             \Logger::addLogger($loggerSyslog);
         } catch (\Exception $e) {
         }
     }
     if (array_key_exists("pimcore_log", $_REQUEST) && self::inDebugMode()) {
         if (empty($_REQUEST["pimcore_log"])) {
             $requestLogName = date("Y-m-d_H-i-s");
         } else {
             $requestLogName = $_REQUEST["pimcore_log"];
         }
         $requestLogFile = dirname(PIMCORE_LOG_DEBUG) . "/request-" . $requestLogName . ".log";
         if (!file_exists($requestLogFile)) {
             File::put($requestLogFile, "");
         }
         $writerRequestLog = new \Zend_Log_Writer_Stream($requestLogFile);
         $loggerRequest = new \Zend_Log($writerRequestLog);
         \Logger::addLogger($loggerRequest);
         \Logger::setVerbosePriorities();
     }
 }
Example #18
0
 /**
  *
  * Performs an action
  *
  * @param mixed $actionName
  * @param array $formData
  * @throws \Exception
  */
 public function performAction($actionName, $formData = [])
 {
     //store the current action data
     $this->setActionData($formData);
     \Pimcore::getEventManager()->trigger("workflowmanagement.preAction", $this, ['actionName' => $actionName]);
     //refresh the local copy after the event
     $formData = $this->getActionData();
     $actionConfig = $this->workflow->getActionConfig($actionName, $this->getElementStatus());
     $additional = $formData['additional'];
     //setup event listeners
     $this->registerActionEvents($actionConfig);
     //setup an array to hold the additional data that is not saved via a setterFn
     $actionNoteData = [];
     //process each field in the additional fields configuration
     if (isset($actionConfig['additionalFields']) && is_array($actionConfig['additionalFields'])) {
         foreach ($actionConfig['additionalFields'] as $additionalFieldConfig) {
             /**
             * Additional Field example
             * [
                             'name' => 'dateLastContacted',
                             'fieldType' => 'date',
                             'label' => 'Date of Conversation',
                             'required' => true,
                             'setterFn' => ''
                             ]
             */
             $fieldName = $additionalFieldConfig['name'];
             //check required
             if ($additionalFieldConfig['required'] && empty($additional[$fieldName])) {
                 throw new \Exception("Workflow::performAction, fieldname [{$fieldName}] required for action [{$actionName}]");
             }
             //work out whether or not to set the value directly to the object or to add it to the note data
             if (!empty($additionalFieldConfig['setterFn'])) {
                 $setter = $additionalFieldConfig['setterFn'];
                 try {
                     //todo check here that the setter is being called on an Object
                     //TODO check that the field has a fieldType, (i.e if a workflow config has getter then the field should only be a pimcore tag and therefore 'fieldType' rather than 'type'.
                     //otherwise we could be erroneously setting pimcore fields
                     $additional[$fieldName] = Workflow\Service::getDataFromEditmode($additional[$fieldName], $additionalFieldConfig['fieldType']);
                     $this->element->{$setter}($additional[$fieldName]);
                 } catch (\Exception $e) {
                     Logger::error($e->getMessage());
                     throw new \Exception("Workflow::performAction, cannot set fieldname [{$fieldName}] using setter [{$setter}] in action [{$actionName}]");
                 }
             } else {
                 $actionNoteData[] = Workflow\Service::createNoteData($additionalFieldConfig, $additional[$fieldName]);
             }
         }
     }
     //save the old state and status in the form so that we can reference it later
     $formData['oldState'] = $this->getElementState();
     $formData['oldStatus'] = $this->getElementStatus();
     if ($this->element instanceof Concrete || $this->element instanceof Document\PageSnippet) {
         if (!$this->workflow->getAllowUnpublished() || in_array($this->getElementStatus(), $this->workflow->getPublishedStatuses())) {
             $this->element->setPublished(true);
             if ($this->element instanceof Concrete) {
                 $this->element->setOmitMandatoryCheck(false);
             }
             $task = 'publish';
         } else {
             $this->element->setPublished(false);
             if ($this->element instanceof Concrete) {
                 $this->element->setOmitMandatoryCheck(true);
             }
             $task = 'unpublish';
         }
     } else {
         //all other elements do not support published or unpublished
         $task = "publish";
     }
     try {
         $response = \Pimcore::getEventManager()->trigger("workflowmanagement.action.before", $this, ['actionConfig' => $actionConfig, 'data' => $formData]);
         //todo add some support to stop the action given the result from the event
         $this->element->setUserModification($this->user->getId());
         if ($task === "publish" && $this->element->isAllowed("publish") || $task === "unpublish" && $this->element->isAllowed("unpublish")) {
             $this->element->save();
         } elseif ($this->element instanceof Concrete || $this->element instanceof Document\PageSnippet) {
             $this->element->saveVersion();
         } else {
             throw new \Exception("Operation not allowed for this element");
         }
         //transition the element
         $this->setElementState($formData['newState']);
         $this->setElementStatus($formData['newStatus']);
         // record a note against the object to show the transition
         $decorator = new Workflow\Decorator($this->workflow);
         $description = $formData['notes'];
         // create a note for this action
         $note = Workflow\Service::createActionNote($this->element, $decorator->getNoteType($actionName, $formData), $decorator->getNoteTitle($actionName, $formData), $description, $actionNoteData);
         //notify users
         if (isset($actionConfig['notificationUsers']) && is_array($actionConfig['notificationUsers'])) {
             Workflow\Service::sendEmailNotification($actionConfig['notificationUsers'], $note);
         }
         \Pimcore::getEventManager()->trigger("workflowmanagement.action.success", $this, ['actionConfig' => $actionConfig, 'data' => $formData]);
     } catch (\Exception $e) {
         \Pimcore::getEventManager()->trigger("workflowmanagement.action.failure", $this, ['actionConfig' => $actionConfig, 'data' => $formData, 'exception' => $e]);
     }
     $this->unregisterActionEvents();
     \Pimcore::getEventManager()->trigger("workflowmanagement.postAction", $this, ['actionName' => $actionName]);
 }
Example #19
0
 /**
  * @param Model\User $user
  * @return $this
  */
 public function setUser(Model\User $user)
 {
     $this->user = $user;
     \Zend_Registry::set("pimcore_admin_user", $this->user);
     $this->setLanguage($this->user->getLanguage());
     // update perspective settings
     $requestedPerspective = $this->getParam("perspective");
     if ($requestedPerspective) {
         if ($requestedPerspective != $user->getActivePerspective()) {
             $existingPerspectives = array_keys(Config::getPerspectivesConfig()->toArray());
             if (!in_array($requestedPerspective, $existingPerspectives)) {
                 $requestedPerspective = null;
             }
         }
     }
     if (!$requestedPerspective || !$user->isAllowed($requestedPerspective, "perspective")) {
         //choose active perspective or a first allowed
         $requestedPerspective = $user->isAllowed($user->getActivePerspective(), "perspective") ? $user->getActivePerspective() : $user->getFirstAllowedPerspective();
     }
     if ($requestedPerspective != $user->getActivePerspective()) {
         $user->setActivePerspective($requestedPerspective);
         $user->save();
     }
     return $this;
 }
Example #20
0
 /** Returns a list of available perspectives for the given user
  * @param Model\User $user
  * @return array
  */
 public static function getAvailablePerspectives($user)
 {
     $currentConfigName = null;
     $masterConfig = self::getPerspectivesConfig()->toArray();
     if ($user instanceof Model\User) {
         if ($user->isAdmin()) {
             $config = self::getPerspectivesConfig()->toArray();
         } else {
             $config = [];
             $roleIds = $user->getRoles();
             $userIds = [$user->getId()];
             $userIds = array_merge($userIds, $roleIds);
             foreach ($userIds as $userId) {
                 if (in_array($userId, $roleIds)) {
                     $userOrRoleToCheck = Model\User\Role::getById($userId);
                 } else {
                     $userOrRoleToCheck = Model\User::getById($userId);
                 }
                 $perspectives = $userOrRoleToCheck->getPerspectives();
                 if ($perspectives) {
                     foreach ($perspectives as $perspectiveName) {
                         $masterDef = $masterConfig[$perspectiveName];
                         if ($masterDef) {
                             $config[$perspectiveName] = $masterDef;
                         }
                     }
                 }
             }
             if (!$config) {
                 $config = self::getPerspectivesConfig()->toArray();
             }
         }
         if ($config) {
             $tmpConfig = [];
             $validPerspectiveNames = array_keys($config);
             // sort the stuff
             foreach ($masterConfig as $masterConfigName => $masterConfiguration) {
                 if (in_array($masterConfigName, $validPerspectiveNames)) {
                     $tmpConfig[$masterConfigName] = $masterConfiguration;
                 }
             }
             $config = $tmpConfig;
         }
         $currentConfigName = $user->getActivePerspective();
         if ($config && !in_array($currentConfigName, array_keys($config))) {
             $currentConfigName = reset(array_keys($config));
         }
     } else {
         $config = self::getPerspectivesConfig()->toArray();
     }
     $result = [];
     foreach ($config as $configName => $configItem) {
         $item = ["name" => $configName, "icon" => isset($configItem["icon"]) ? $configItem["icon"] : null, "iconCls" => isset($configItem["iconCls"]) ? $configItem["iconCls"] : null];
         if ($user) {
             $item["active"] = $configName == $currentConfigName;
         }
         $result[] = $item;
     }
     return $result;
 }
Example #21
0
 /**
  * @throws \Exception
  */
 public function save()
 {
     $isUpdate = false;
     if ($this->getId()) {
         $isUpdate = true;
         \Pimcore::getEventManager()->trigger("object.class.preUpdate", $this);
     } else {
         \Pimcore::getEventManager()->trigger("object.class.preAdd", $this);
     }
     $this->setModificationDate(time());
     $this->getDao()->save();
     // create class for object
     $extendClass = "Concrete";
     if ($this->getParentClass()) {
         $extendClass = $this->getParentClass();
         $extendClass = "\\" . ltrim($extendClass, "\\");
     }
     // creaste directory if not exists
     if (!is_dir(PIMCORE_CLASS_DIRECTORY . "/Object")) {
         File::mkdir(PIMCORE_CLASS_DIRECTORY . "/Object");
     }
     $cd = '<?php ';
     $cd .= "\n\n";
     $cd .= "/** Generated at " . date('c') . " */";
     $cd .= "\n\n";
     $cd .= "/**\n";
     if ($this->getDescription()) {
         $description = str_replace(array("/**", "*/", "//"), "", $this->getDescription());
         $description = str_replace("\n", "\n* ", $description);
         $cd .= "* " . $description . "\n";
     }
     $cd .= "* Inheritance: " . ($this->getAllowInherit() ? "yes" : "no") . "\n";
     $cd .= "* Variants   : " . ($this->getAllowVariants() ? "yes" : "no") . "\n";
     $user = Model\User::getById($this->getUserModification());
     if ($user) {
         $cd .= "* Changed by : " . $user->getName() . " (" . $user->getId() . ")" . "\n";
     }
     if ($_SERVER["REMOTE_ADDR"]) {
         $cd .= "* IP:          " . $_SERVER["REMOTE_ADDR"] . "\n";
     }
     $cd .= "*/\n";
     $cd .= "\n\n";
     $cd .= "namespace Pimcore\\Model\\Object;";
     $cd .= "\n\n";
     $cd .= "\n\n";
     $cd .= "/**\n";
     if (is_array($this->getFieldDefinitions()) && count($this->getFieldDefinitions())) {
         foreach ($this->getFieldDefinitions() as $key => $def) {
             if (!(method_exists($def, "isRemoteOwner") and $def->isRemoteOwner())) {
                 $cd .= "* @method static \\Pimcore\\Model\\Object\\" . ucfirst($this->getName()) . '\\Listing getBy' . ucfirst($def->getName()) . ' ($value, $limit = 0) ' . "\n";
             }
         }
     }
     $cd .= "*/\n\n";
     $cd .= "class " . ucfirst($this->getName()) . " extends " . $extendClass . " {";
     $cd .= "\n\n";
     if ($this->getUseTraits()) {
         $cd .= 'use ' . $this->getUseTraits() . ";\n";
         $cd .= "\n";
     }
     $cd .= 'public $o_classId = ' . $this->getId() . ";\n";
     $cd .= 'public $o_className = "' . $this->getName() . '"' . ";\n";
     if (is_array($this->getFieldDefinitions()) && count($this->getFieldDefinitions())) {
         foreach ($this->getFieldDefinitions() as $key => $def) {
             if (!(method_exists($def, "isRemoteOwner") && $def->isRemoteOwner()) && !$def instanceof Object\ClassDefinition\Data\CalculatedValue) {
                 $cd .= "public \$" . $key . ";\n";
             }
         }
     }
     $cd .= "\n\n";
     $cd .= '/**' . "\n";
     $cd .= '* @param array $values' . "\n";
     $cd .= '* @return \\Pimcore\\Model\\Object\\' . ucfirst($this->getName()) . "\n";
     $cd .= '*/' . "\n";
     $cd .= 'public static function create($values = array()) {';
     $cd .= "\n";
     $cd .= "\t" . '$object = new static();' . "\n";
     $cd .= "\t" . '$object->setValues($values);' . "\n";
     $cd .= "\t" . 'return $object;' . "\n";
     $cd .= "}";
     $cd .= "\n\n";
     if (is_array($this->getFieldDefinitions()) && count($this->getFieldDefinitions())) {
         $relationTypes = array();
         foreach ($this->getFieldDefinitions() as $key => $def) {
             if (method_exists($def, "isRemoteOwner") and $def->isRemoteOwner()) {
                 continue;
             }
             // get setter and getter code
             $cd .= $def->getGetterCode($this);
             $cd .= $def->getSetterCode($this);
             // call the method "classSaved" if exists, this is used to create additional data tables or whatever which depends on the field definition, for example for localizedfields
             if (method_exists($def, "classSaved")) {
                 $def->classSaved($this);
             }
             if ($def->isRelationType()) {
                 $relationTypes[$key] = array("type" => $def->getFieldType());
             }
             // collect lazyloaded fields
             if (method_exists($def, "getLazyLoading") and $def->getLazyLoading()) {
                 $lazyLoadedFields[] = $key;
             }
         }
         $cd .= 'protected static $_relationFields = ' . var_export($relationTypes, true) . ";\n\n";
         $cd .= 'public $lazyLoadedFields = ' . var_export($lazyLoadedFields, true) . ";\n\n";
     }
     $cd .= "}\n";
     $cd .= "\n";
     $classFile = PIMCORE_CLASS_DIRECTORY . "/Object/" . ucfirst($this->getName()) . ".php";
     if (!is_writable(dirname($classFile)) || is_file($classFile) && !is_writable($classFile)) {
         throw new \Exception("Cannot write class file in " . $classFile . " please check the rights on this directory");
     }
     File::put($classFile, $cd);
     // create list class
     $cd = '<?php ';
     $cd .= "\n\n";
     $cd .= "namespace Pimcore\\Model\\Object\\" . ucfirst($this->getName()) . ";";
     $cd .= "\n\n";
     $cd .= "use Pimcore\\Model\\Object;";
     $cd .= "\n\n";
     $cd .= "/**\n";
     $cd .= " * @method Object\\" . ucfirst($this->getName()) . " current()\n";
     $cd .= " */";
     $cd .= "\n\n";
     $cd .= "class Listing extends Object\\Listing\\Concrete {";
     $cd .= "\n\n";
     $cd .= 'public $classId = ' . $this->getId() . ";\n";
     $cd .= 'public $className = "' . $this->getName() . '"' . ";\n";
     $cd .= "\n\n";
     $cd .= "}\n";
     /*$cd .= "?>";*/
     File::mkdir(PIMCORE_CLASS_DIRECTORY . "/Object/" . ucfirst($this->getName()));
     $classListFile = PIMCORE_CLASS_DIRECTORY . "/Object/" . ucfirst($this->getName()) . "/Listing.php";
     if (!is_writable(dirname($classListFile)) || is_file($classListFile) && !is_writable($classListFile)) {
         throw new \Exception("Cannot write class file in " . $classListFile . " please check the rights on this directory");
     }
     File::put($classListFile, $cd);
     // empty object cache
     try {
         Cache::clearTag("class_" . $this->getId());
     } catch (\Exception $e) {
     }
     if ($isUpdate) {
         \Pimcore::getEventManager()->trigger("object.class.postUpdate", $this);
     } else {
         \Pimcore::getEventManager()->trigger("object.class.postAdd", $this);
     }
 }
Example #22
0
 /**
  * Checks if data is valid for current data field
  *
  * @param mixed $data
  * @param boolean $omitMandatoryCheck
  * @throws \Exception
  */
 public function checkValidity($data, $omitMandatoryCheck = false)
 {
     if (!$omitMandatoryCheck and $this->getMandatory() and empty($data)) {
         throw new \Exception("Empty mandatory field [ " . $this->getName() . " ]");
     }
     if (!empty($data)) {
         $user = Model\User::getById($data);
         if (!$user instanceof Model\User) {
             throw new \Exception("invalid user reference");
         }
     }
 }
Example #23
0
 /**
  * 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);
 }