/** * Reset form values. * * @access protected * @return Form\Field * @since 1.0.0-alpha * @version 1.0.0-alpha */ protected function resetValue() { $this->aFormMethodValues = $this->getFormObject()->getMethodValue(); if ($this->getFormObject()->isFieldsNameWithPrefix()) { $mSentData = Helper\Arrays::path($this->aFormMethodValues, $this->getFormObject()->getName() . '.' . $this->getName(), FALSE); } else { $mSentData = Helper\Arrays::get($this->aFormMethodValues, $this->getName(), FALSE); } if ($mSentData !== FALSE) { foreach ($mSentData as $sLang => $aAllDefaultValuesForLang) { foreach ($aAllDefaultValuesForLang as $i => $mSingleValue) { foreach ($mSingleValue as $i => &$mValue) { $mValue = DB::find($this->getRelatedModelName(), $mValue); } $this->setValue($mSingleValue, $i, $sLang); } } } else { $aDefaultValue = $this->getFormObject()->getDefaultVal($this->getName()); foreach ($aDefaultValue as $sLang => $aValues) { $aDefaultValue[$sLang] = [$aValues]; } $this->setValue($aDefaultValue); } return $this; }
/** * @access public * @since 1.0.0-dev, 2015-04-19 * @version 1.0.0-dev, 2015-04-19 */ public function actionDefault() { $this->setTitle(__('Sitemap')); $this->addBreadCrumb(__('Sitemap')); $aItems = []; $aItems[] = ['/', __('Front page')]; $aPages = \Plethora\DB::query("SELECT p FROM \\Model\\Page p WHERE p.published = 1")->execute(); foreach ($aPages as $oPage) { /* @var $oPage \Model\Page */ $aItems[] = [Route::factory('page')->path(['rewrite' => $oPage->getRewrite()]), $oPage->getTitle()]; } \Sitemap\SitemapGenerator::generate($aItems); return View::factory('sitemap/frontend/sitemap')->bind('aItems', $aItems); }
/** * Make some actions / operations for particular field just before form * validation has * * @access public * @since 1.0.0-alpha * @version 1.0.0-alpha */ public function beforeValidation() { if ($this->getRelatedModelName() === NULL) { throw new Exception\Fatal('To continue, there must be a related model name added by setRelatedModelName() method.'); } if ($this->getFormObject()->isSubmitted()) { $aValue = $this->getValue(); foreach ($aValue as $sLang => $aAllDefaultValuesForLang) { foreach ($aAllDefaultValuesForLang as $i => $mSingleValue) { $oModel = \Plethora\DB::find($this->getRelatedModelName(), $mSingleValue); $this->setValue($oModel, $i, $sLang); } } } }
/** * Action used to do multileveled sort on model entities. * * @access public * @since 1.0.0-alpha * @version 1.0.0-alpha */ public function actionSortList() { // check access if (!\UserPermissions::hasPerm('backend_ajax_sort_list')) { Route::factory('home')->redirectTo(); } // @TODO: check permissions $sObjects = filter_input(INPUT_POST, 'objects'); $sModel = filter_input(INPUT_POST, 'model'); $aObjectsTmp = []; $aOrderNumber = []; // if list of objects is empty if (empty($sObjects)) { $this->setStatus('error'); return __('List of objects is empty.'); } // parse objects array from query string parse_str($sObjects, $aObjectsTmp); $aObjects = $aObjectsTmp['object']; // rewrite each object foreach ($aObjects as $iID => $sParentID) { if ($sParentID === 'null') { $sParentID = 0; } $iParentID = (int) $sParentID; if (!isset($aOrderNumber[$iParentID])) { $aOrderNumber[$iParentID] = 0; } $aObjects[$iID] = ['order_parent' => $iParentID, 'order' => $aOrderNumber[$iParentID]]; $aOrderNumber[$iParentID]++; } // check if particular model has `order` property if (!property_exists($sModel, 'order_number')) { $this->setStatus('error'); return __('Wrong node type.'); } // get all model instances $aEntities = DB::query('SELECT t FROM ' . $sModel . ' t WHERE t.id IN (:list)')->param('list', array_keys($aObjects))->execute(); foreach ($aEntities as $oEntity) { /* @var $oEntity ModelCore|ModelCore\Traits\Sortable */ $aObjData = $aObjects[$oEntity->getId()]; $oEntity->setOrderNumber($aObjData['order']); $oEntity->setOrderParent($aObjData['order_parent']); $oEntity->save(); DB::flush(); } return 'saved'; }
/** * ACTION - Particular page. * * @access public * @return View * @throws Exception\Code404 * @throws Exception\Fatal * @since 1.0.1-dev, 2015-04-11 * @version 1.2.0-dev */ public function actionPage() { $query = DB::query('SELECT p FROM \\Model\\Page p WHERE p.rewrite = :rewrite'); $query->param('rewrite', Router::getParam('rewrite')); $page = $query->single(); if (!$page instanceof Model\Page) { throw new Exception\Code404('Page does not exist.'); } $this->addBreadCrumb($page->getTitle()); $this->setTitle($page->getTitle()); $this->setDescription($page->getDescription()); $this->setKeywords($page->getKeywords()); $entityConfig = ViewEntity\Configurator::factory($page); $entityConfig->setFields(['content']); $viewEntity = ViewEntity::factory($entityConfig); return $viewEntity->getView(); }
/** * Update database. * * @static * @access public * @return View * @since 1.2.0-dev * @version 1.2.0-dev */ private static function makeUpdateNoExec() { $entityManager = DB::getEntityManager(); $tool = new ORM\Tools\SchemaTool($entityManager); $classes = []; // get list of Model classes foreach (DB::getModelsNames() as $sClass) { $classes[] = $entityManager->getClassMetadata($sClass); } // make schemas update try { $sql = $tool->getUpdateSchemaSql($classes); /* @var $sql array */ $tool->updateSchema($classes); $output = View::factory('db_update/backend/update_output')->bind('aSQL', $sql)->renderAndMinify(); } catch (\Exception $e) { $output = __('Error') . ': ' . $e->getMessage(); } // return output return $output; }
/** * ACTION - User login. * * @access public * @return View * @since 1.0.2, 2013-12-07 * @version 1.0.7-dev, 2015-05-04 */ public function actionLogin() { $this->setTitle(Core::getAppName() . ' - ' . __('Login form')); $this->addBreadCrumb(__('Login form')); $oLoggedUser = Model\User::getLoggedUser(); if ($oLoggedUser instanceof Model\User) { Route::factory('user_profile')->redirectTo(['id' => $oLoggedUser->getId()]); } $failedLogins = \User\LoginFail::getCachedData(); if ($failedLogins > 4) { return View::factory('base/alert')->set('sType', 'danger')->set('sMsg', __('to.many.incorrect.logins')); } $oLoginForm = Form::factory('login'); $oLoginForm->addField(Form\Field\Text::factory('login', $oLoginForm)); $oLoginForm->addField(Form\Field\Password::factory('password', $oLoginForm)); if ($oLoginForm->isSubmittedAndValid()) { $sUsername = $oLoginForm->get('login'); $sPassword = $oLoginForm->get('password'); $sEncryptedPassword = Helper\Encrypter::factory()->encrypt($sUsername, $sPassword); $oUser = DB::query("SELECT u FROM \\Model\\User u WHERE u.login = :login AND u.password = :pass")->param('login', $sUsername)->param('pass', $sEncryptedPassword)->single(); if ($oUser instanceof Model\User) { Session::set('username', $sUsername); Session::set('uid', (int) $oUser->getId()); $oUser->setLoginDateNOW(); DB::flush(); # Get role permissions for particular user and set them in session \UserPermissions::reset(); Route::factory(Router::getCurrentRouteName())->redirectTo(); } else { $currentUrl = Router::currentUrl(); $alert = __('You have entered wrong username or password. Try again.'); \User\LoginFail::addLoginFail(); Session::flash($currentUrl, $alert, 'danger'); } } $oLoginForm->addToSuffix(View::factory('user/frontend/login_links')->render()); return View::factory('base/form')->bind('oForm', $oLoginForm); }
/** * Send user account activation code. * * @access public * @param string $sPassword * @param UserModel $oUser * @return bool * @throws \Plethora\Exception * @throws \Plethora\Exception\Fatal * @since 1.0.0 * @version 2.1.0-dev */ private function sendActivationCode($sPassword, UserModel $oUser) { $sUserAgent = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT'); $sActivationCode1 = mb_strlen($sPassword) * time() . $sUserAgent . $oUser->getLogin(); $sActivationCode2 = sha1($sActivationCode1); $sActivationCode = base64_encode($sActivationCode2); $oActivationCode = new ActivationCodeModel(); $oActivationCode->setUser($oUser); $oActivationCode->setCode($sActivationCode); DB::persist($oActivationCode); DB::flush(); $sSubject = __(':appname - Activation link', ['appname' => Plethora\Core::getAppName()]); $mailContent = View::factory("user/frontend/register/message")->render(['sLogin' => $oUser->getLogin(), 'sActivationCode' => $sActivationCode]); $mailView = View::factory('base/email'); $mailView->bind('sContent', $mailContent); $mailView->set('sTitle', $sSubject); $mail = $mailView->render(); $oMessage = new Mail(); $oMessage->setSubject($sSubject); $oMessage->setFrom(Config::get('base.email')); $oMessage->setTo($oUser->getEmail()); $oMessage->setBody($mail, 'text/html'); return Mailer::factory()->send($oMessage); }
/** * Constructor * * @access public * @since 1.1.2-dev * @version 1.1.3-dev */ public function __construct() { parent::__construct(); $this->locales = new \Doctrine\Common\Collections\ArrayCollection(); // get menu ID if (Router::getCurrentRouteName() === 'backend' && in_array(Router::getParam('action'), ['add', 'edit'])) { $menuID = (int) Router::getParam('id'); $this->menu = DB::find('\\Model\\Menu', $menuID); } }
<?php \Plethora\Router\LocalActions::addLocalAction(__('Edit page'), 'page', 'backend')->setParameters(array('controller' => 'pages', 'action' => 'edit'))->setBuilder(function (\Plethora\Router\LocalActions\Action $oAction) { $sPageRewrite = (int) \Plethora\Router::getParam('rewrite'); $aPage = \Plethora\DB::query('SELECT p.id FROM \\Model\\Page p WHERE p.rewrite = :rewrite')->param('rewrite', $sPageRewrite)->single(); $oAction->setParameter('id', $aPage['id']); }); \Plethora\Router\LocalActions::addLocalAction(__('Preview'), 'backend', 'page')->setConditions(array('controller' => 'pages', 'action' => 'edit'))->setBuilder(function (\Plethora\Router\LocalActions\Action $oAction) { $iNewsID = (int) \Plethora\Router::getParam('id'); $oPage = \Plethora\DB::find('Model\\Page', $iNewsID); /* @var $oPage \Model\Page */ $oAction->setParameter('rewrite', $oPage->getRewrite()); });
/** * Send user account recovery code. * * @access public * @param User $oUser * @since 1.0.0, 2015-02-17 * @version 2.1.0-dev * @return bool */ private function sendRecoveryCode(User $oUser) { $sUserAgent = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT'); $sCodeToEncode = mb_strlen(uniqid()) * time() . $sUserAgent . $oUser->getLogin(); $sCode2 = sha1($sCodeToEncode); $sRecoveryCode = base64_encode($sCode2); DB::query('DELETE FROM \\Model\\User\\RecoveryCode r WHERE r.user = :user')->param('user', $oUser->getId())->execute(TRUE); $oRecoveryCode = new User\RecoveryCode(); $oRecoveryCode->setUser($oUser); $oRecoveryCode->setCode($sRecoveryCode); DB::persist($oRecoveryCode); DB::flush(); $sSubject = __('Account activation on :app', ['app' => Core::getAppName()]); $mailContent = View::factory("user/frontend/recovery/message")->render(['sLogin' => $oUser->getLogin(), 'sRecoveryCode' => $sRecoveryCode]); $mailView = View::factory('base/email'); $mailView->bind('sContent', $mailContent); $mailView->set('sTitle', $sSubject); return $oUser->sendEmail($sSubject, $mailView->render()); }
/** * @access public * @return DB * @since 1.0.0-alpha * @version 1.0.0-alpha */ private function getCountingQuery() { return DB::factory($this->oCountingQuery->getQuery()); }
/** * Method is called by Form object when this particular form is used (sent). * * @access protected * @throws Exception\Fatal * @since 1.0.0-alpha * @version 1.0.0-alpha */ protected function whenFormSubmitted() { // get sent data $sentFileData = $this->getSentFileArray(); // loop trough all sent data foreach ($sentFileData as $sLang => $allDefaultValuesForLang) { foreach ($allDefaultValuesForLang as $i => $dataBatch) { // create file broker (if not exists) $broker = Arrays::path($this->aFileBrokers, $sLang . '.' . $i, FALSE); if ($broker === FALSE) { $parent = $this->isMultilanguage() ? $this->getFormObject()->getModel()->getLocales() : $this->getFormObject()->getModel(); $broker = new $this->sBrokerModel(); /* @var $broker ModelCore\FileBroker */ if (!$broker instanceof ModelCore\FileBroker) { throw new Exception\Fatal('Given bad class name (`' . get_class($broker) . '`). ' . 'Not a `ModelCore\\FileBroker` class.'); } $broker->setParent($parent); } // if file was uploaded earlier and is in "temporary file" field $formValues = $this->getFormObject()->getMethodValue(); $tempValue = Arrays::get($formValues, 'temp_file_' . $this->getName() . '_' . $sLang . '_' . $i); if (!empty($tempValue)) { $oFile = DB::find('\\Model\\File', $tempValue); /* @var $oFile \Model\File */ Arrays::createMultiKeys($this->aFileTemp, $sLang . '.' . $i, $oFile); } // if file has been sent by $_FILE method if (isset($dataBatch['tmp_name']) && $dataBatch['tmp_name'] !== '' && $dataBatch['size'] >= 0) { $broker->setTempData($dataBatch); } // set file to filebroker $oFileForBroker = Arrays::path($this->aFileTemp, $sLang . '.' . $i, FALSE); if ($oFileForBroker !== FALSE) { $broker->setFile($oFileForBroker); } // set broker as fields value Arrays::createMultiKeys($this->aFileBrokers, $sLang . '.' . $i, $broker); $this->setValue($broker, $i, $sLang); } } }
/** * Generate query of particular entity list and search engine. * * @access public * @return SearchEngineGeneratedQueries * @since 1.0.0-alpha * @version 1.0.0-alpha */ public function generateQuery() { $oQuery = DB::queryBuilder()->select('t')->from($this->getModel()->getClass(), 't'); $aJoined = []; $iAlias = 0; $oForm = $this->getForm(); // if search engine form is submitted if ($oForm->isSubmitted()) { $aQueryParams = []; $aIgnoredQueryParams = []; foreach (array_keys($oForm->getFields()) as $sFieldName) { /* @var $oField Form\Field */ $mValue = $oForm->get($sFieldName); if ($mValue !== '') { $aQueryParams[$sFieldName] = $mValue; } else { $aIgnoredQueryParams[] = $sFieldName; } } $sURL = Router::currentUrlWithQueryParams($aQueryParams, $aIgnoredQueryParams); Router::relocate($sURL); } // if URL has any filters $aQueryParamsForSearch = Router::getQueryStringParams(); if (count($aQueryParamsForSearch) > 0) { foreach ($aQueryParamsForSearch as $sFieldName => $mValue) { // if value is not empty if (!is_array($mValue) && $mValue !== '' && $mValue !== NULL || is_array($mValue) && $mValue !== []) { // changing models for theirs IDs if (is_array($mValue)) { foreach ($mValue as &$oValue) { /* @var $oValue \Plethora\ModelCore */ if ($oValue instanceof ModelCore) { $oValue = $oValue->getId(); } } } elseif ($mValue instanceof ModelCore) { $mValue = $mValue->getId(); } // if field is from primary table if ($this->getModel()->getMetadata()->hasField($sFieldName)) { $oQuery->andWhere("t." . $sFieldName . " LIKE '%" . trim($mValue) . "%'"); } elseif ($this->getModel()->getMetadata()->hasAssociation($sFieldName)) { $sAssocTableAlias = 'a' . $sFieldName; if (is_array($mValue)) { $aConditions = []; foreach ($mValue as $mSingleValue) { $aConditions[] = $sAssocTableAlias . ".id ='" . trim($mSingleValue) . "'"; } $sCondition = implode(' OR ', $aConditions); } else { $sCondition = $sAssocTableAlias . ".id ='" . trim($mValue) . "'"; } $oQuery->join('t.' . $sFieldName, $sAssocTableAlias, \Doctrine\ORM\Query\Expr\Join::WITH, $sCondition); } else { $aRelFieldInfo = $this->getRelFieldInfo($sFieldName); if ($aRelFieldInfo !== FALSE) { if (!in_array($aRelFieldInfo->getVar(), $aJoined)) { $iAlias++; $sAlias = 't' . $iAlias; $aJoined[$sAlias] = $aRelFieldInfo->getVar(); $oQuery->join('t.' . $aRelFieldInfo->getVar(), $sAlias); } else { $sAlias = array_search($aRelFieldInfo->getVar(), $aJoined); } $oQuery->andWhere($sAlias . "." . $aRelFieldInfo->getOriginalName() . " LIKE '%" . trim($mValue) . "%'"); } } } } } $oQuery->orderBy('t.id', 'desc'); return SearchEngineGeneratedQueries::factory($oQuery); }
/** * Checks if value exists in database * * @static * @access public * @param string $mValue * @param string $sTableClass * @param string $sColumn * @return boolean|string * @since 1.0.0-alpha * @version 1.0.0-alpha */ public static function dbKeyValidation($mValue, $sTableClass, $sColumn) { # array if (is_array($mValue)) { if (empty($mValue)) { return TRUE; } $mParam = []; foreach ($mValue as $v) { if ($v != "" && !array_search($v, $mParam)) { $mParam[] = $v; } } $iDataAmount = count($mParam); if ($iDataAmount == 0) { return TRUE; } } else { if ($mValue == "") { return TRUE; } $iDataAmount = 1; $mParam = $mValue; } # Query DB::query("SELECT t.id FROM " . $sTableClass . " t WHERE t." . $sColumn . " IN (:param)")->param('param', $mParam)->execute(); # Checking result(s) if (count(DB::result()) != $iDataAmount) { if (is_array($mValue)) { return __('One of the values is incompatible with data from database.'); } else { return __('Value is incompatible with data from database.'); } } return TRUE; }
/** * Usuwanie rekordu o identyfikatorze $iId w modelu $sModel za pomocą * klauzuli DELETE. Zwraca TRUE, jeżeli rekord został prawidłowo usunięty. * * @static * @access public * @param integer $iId * @param string $sModel * @return boolean * @since 1.0.0-alpha * @version 1.0.0-alpha */ public static function delete($iId, $sModel) { DB::query("DELETE FROM " . $sModel . " m WHERE m.id = :id")->param('id', $iId)->execute(TRUE); return DB::$mResult ? TRUE : FALSE; }
/** * Remove all data of this Model from database. * * @access public * @return boolean * @since 1.0.0-alpha * @version 1.0.0-alpha */ public function remove() { if (static::hasLocales()) { foreach ($this->getLocales('all') as $oLocale) { /* @var $oLocale ModelCore\Locales */ foreach ($oLocale->getConfig()->getFields() as $sFieldName => $oField) { /* @var $oField Form\Field */ $oField->whenRemovingEntity($this, $oLocale->{$sFieldName}); } DB::remove($oLocale); } } foreach ($this->getConfig()->getFields() as $sFieldName => $oField) { /* @var $oField Form\Field */ $oField->whenRemovingEntity($this, $this->{$sFieldName}); } DB::remove($this); return TRUE; }
/** * Get currently logged user. * * @static * @access public * @return User * @since 2.0.2, 2013-12-25 * @version 2.1.2-dev */ public static function getLoggedUser() { if (static::$loggedUser === NULL && Session::get('uid') !== NULL) { static::$loggedUser = DB::find('\\Model\\User', Session::get('uid')); } return static::$loggedUser; }
/** * Save new Model data. Method created for "public" uses, when needed to * make a save in, for example, controller. * * @access protected * @param Form $oForm * @throws Exception * @throws Exception\Fatal * @since 1.0.0-alpha * @version 1.0.0-alpha */ protected function makeSaveProtected(Form &$oForm) { $oConfig = $this->getConfig(); try { $this->beforeSave($oForm); $this->getModel()->save(); DB::flush(); if ($oConfig == NULL || $oConfig->isReloading() === TRUE) { $sUrl = $oConfig->getAction() === NULL ? $oForm->getAttribute('action') : $oConfig->getAction(); $sComm = $oConfig->getMessage() === NULL ? __('Form data submitted.') : $oConfig->getMessage(); Session::flash($sUrl, $sComm); } } catch (Exception $e) { if (Config::get('base.mode') == 'development') { throw $e; } else { throw new Exception\Fatal(__('Error occured while saving data in database.')); } } }
/** * Generate result (containing entities list) for sort list. * * @access protected * @return array * @since 1.0.0-alpha * @version 1.0.0-alpha */ protected function alterSortQueryResult() { return DB::query('SELECT t FROM ' . $this->getModel()->getClass() . ' t ORDER BY t.order_number')->execute(); }
/** * Generate config object of particular Model. * * @overwritten * @static * @author Krzysztof Trzos * @access protected * @return ModelCore\MConfig * @since 2015-01-10 * @version 1.1.1-dev, 2015-08-10 */ public static function generateConfig() { // get all permissions list $aPermissions = []; $aResult = DB::queryList('\\Model\\User\\Permission')->execute(); foreach ($aResult as $oPermission) { /* @var $oPermission Permission */ $aPermissions[$oPermission->getId()] = ['value' => $oPermission->getId(), 'label' => $oPermission->getName()]; } $config = parent::generateConfig(); // return MConfig $config->addField(Form\Field\Hidden::singleton('id')); $config->addField(Form\Field\Text::singleton('name')->setRequired()->setLabel(__('Name'))); $config->addField(Form\Field\CheckboxRelation::singleton('permissions')->setRelatedModelName('\\Model\\User\\Permission')->setColumnsAmount(3)->setOptions($aPermissions)->setLabel(__('Permissions'))); return $config; }
/** * Render toolbar. * * @access public * @return string * @since 1.0.0-dev, 2015-06-08 * @version 1.1.0-dev */ public function render() { $oSqlLogger = DB::getEntityManager()->getConnection()->getConfiguration()->getSQLLogger(); //* @var $oSqlLogger \Doctrine\DBAL\Logging\DebugStack */ $aRoutesList = Router::getRoutes(); $aModules = Router::getModules(); $aBenchmarkMarks = Benchmark::getAllMarks(); $aCustoms = static::getCustoms(); $cronJobs = CronJobsHelper::getCronJobs(); return View::factory('dev_toolbar/toolbar')->bind('oSqlLogger', $oSqlLogger)->bind('aRoutesList', $aRoutesList)->bind('aModules', $aModules)->bind('aCustoms', $aCustoms)->bind('aBenchmarkMarks', $aBenchmarkMarks)->bind('cronJobs', $cronJobs)->render(); }
/** * Remove file by ID. * * @static * @access public * @param integer $iFileID * @since 1.0.0-alpha * @version 1.0.0-alpha */ public static function deleteFile($iFileID) { // get file object and its path $oFile = DB::find('\\Model\\File', $iFileID); /* @var $oFile \Model\File */ $sPath = $oFile->getPath() . DS . $oFile->getNameWithExt(); // if it's an image, remove all its styles if (in_array($oFile->getExt(), ['jpg', 'jpeg', 'gif', 'png', 'tiff'])) { ImageStyles::removeStyledImgCache($sPath); } // remove file \FileManager::delete($sPath); // remove from database $oFile->remove(); // \Plethora\DB::flush(); }
/** * Generate result (containing entities list) for sort list. * * @access protected * @return array * @since 1.2.0-dev * @version 1.2.0-dev */ protected function alterSortQueryResult() { $iMenuID = Router::getParam('id'); $sModelClass = $this->getModel()->getClass(); return DB::query('SELECT t FROM ' . $sModelClass . ' t WHERE t.menu = :menu_id ORDER BY t.order_number')->param('menu_id', $iMenuID)->execute(); }