public function login($userName, $password, $errorMessageContainer = null) { $adminRequired = $this->isAdminRequired(); $dao = $adminRequired ? new AdminDAO() : new UserDAO(); $type = $adminRequired ? 'admin' : 'user'; $record = $dao->getByNameAndPassword($userName, $password); $passwordOK = False; $accountBlocked = False; if ($record['id']) { $passwordOK = True; } else { $record = $dao->getByName($userName); } if ($record['id']) { $loginHistoryDAO = new CoreLoginHistoryDAO(); $failedAttempts = $loginHistoryDAO->getRecentFailedLoginAttempts($type, $record['id']); if ($failedAttempts['num'] >= CoreConfig::get('Settings', $type . 'MaxLoginAttempts') && $failedAttempts['time'] > date('Y-m-d H:i:s', strtotime('-' . CoreConfig::get('Settings', $type . 'AccountBlockSeconds') . ' seconds'))) { $accountBlocked = True; } else { $this->updateLoginHistory($loginHistoryDAO, $type, $record['id'], $passwordOK); } } if ($passwordOK && !$accountBlocked) { $this->currentUser = $record; CoreServices::get('request')->setSession('currentUser', $record); } elseif (!empty($errorMessageContainer)) { $this->setLoginErrorMessage($errorMessageContainer, $type, $accountBlocked, $passwordOK); } return $passwordOK && !$accountBlocked; }
public function sendHeaders() { header('Expires: Thu, 19 Nov 1981 08:52:00 GMT'); header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0'); header('Pragma: no-cache'); header('Content-type: text/html; charset=' . strtolower(CoreConfig::get('CoreDisplay', 'globalCharset'))); }
protected function mail($subject, $content, $headers) { $subject = '=?' . CoreConfig::get('CoreDisplay', 'globalCharset') . '?B?' . base64_encode($subject) . '?='; if (!@mail('', $subject, $content, $headers)) { throw new CoreException('Sending mail failed!'); } }
public function adjustSubmittedValue($submittedValue) { if (!is_scalar($submittedValue)) { // assume hacking attempt return null; } return htmlspecialchars($submittedValue, ENT_QUOTES, CoreConfig::get('CoreDisplay', 'globalCharset')); }
public function validate($messageManager) { $field = $this->form->getField($this->fieldName); $uploadStruct = $field->getValue(); $allowedMimeTypes = CoreConfig::get('CoreFiles', 'allowedMimeTypes'); if (!empty($uploadStruct) && (!in_array($uploadStruct['type'], $allowedMimeTypes['image']) || !CoreServices::get('images')->checkImageFileContent($uploadStruct['type'], $uploadStruct['tmp_name']))) { $messageManager->addMessage('fileTypeCheckFailed', array($this->fieldName => $field->getCaption())); } }
protected function init() { $this->values['globalCharset'] = 'UTF-8'; $this->values['htmlDocType'] = 'XHTML 1.0 Transitional'; $this->values['paginationDefaultMaxRecords'] = 20; $this->values['paginationDefaultMaxPageLinks'] = 21; $this->values['paginationChars'] = array('universal' => CoreConfig::get('CoreLangs', 'allLocalCharVariants')); $this->values['paginationDummy'] = '?'; }
protected function reportError($message) { $from = CoreConfig::get('Environment', 'errorEmailSender'); $listTo = array(CoreConfig::get('Environment', 'errorEmailRecipient')); $listCC = array(); $lang = CoreConfig::get('CoreLangs', 'defaultLangCMS'); $subject = CoreConfig::get('Environment', 'websiteName') . ' - ' . DictForCMS::get($lang, 'garbageCollectorFailure'); $content = DictForCMS::get($lang, 'garbageCollectorFailure') . ":\n" . $message; CoreServices2::getMail()->sendPlainText($from, $listTo, $listCC, $subject, $content); }
/** * Teoretycznie jest to odporne na thickboxy. */ protected function checkHTTPS() { $httpsOn = CoreServices2::getUrl()->isHTTPSOn(); $httpsRequired = CoreConfig::get('Environment', 'httpsForWebsite'); if ($httpsRequired && !$httpsOn) { CoreUtils::redirect(CoreServices2::getUrl()->getCurrentExactAddress('https')); } if (!$httpsRequired && $httpsOn) { CoreUtils::redirect(CoreServices2::getUrl()->getCurrentExactAddress('http')); } }
public function validate($messageManager) { $field = $this->form->getField($this->fieldName); $value = $field->getOpenText(); if (empty($value)) { return; } if (strlen($value) < 6 || !preg_match('/[a-zA-Z' . implode('', CoreConfig::get('CoreLangs', 'localCharsToLatinSource')) . ']/', $value) || !preg_match('/[0-9]/', $value)) { $messageManager->addMessage('newPasswordTooWeak', array($this->fieldName => $field->getCaption())); return; } }
protected function initFeaturedItems() { $featuredRecords = $this->modelDAO->getFeaturedList(CoreConfig::get('Display', 'featuredModelsCount')); $this->featuredItemsList = array(); foreach ($featuredRecords as $record) { $this->featuredItemsList[$record['id']] = $record; } if (!empty($this->featuredItemsList)) { $ids = array_keys($this->featuredItemsList); $this->featuredItemsImagesList = $this->fileDAO->getFirstImageListByRecordList('model', $ids, 'gallery'); } }
public function prepareData() { $this->checkHTTPS(); $this->adminRoles = array_flip(CoreConfig::get('Data', 'adminRoles')); $this->currentUser = CoreServices::get('access')->getCurrentUserData(); if (!$this->isControllerUsagePermitted()) { CoreUtils::redirect($this->getNoPermissionsAddress()); } $this->initDAO(); $this->initLayout(); $this->initRecordList(); $this->prepareAdditionalData(); }
public function initSession($sessionName, $sessionId = null) { $this->sessionNameSuffix = $sessionName; if ($this->sessionInitialized) { throw new CoreException('Tried to initialize session, but it was already initialized.'); } $this->sessionInitialized = True; if (!empty($sessionId)) { session_id($sessionId); } session_name(CoreConfig::get('Environment', 'websiteName') . '_' . $this->sessionNameSuffix); session_start(); }
protected function sendPasswordRecoveryEmail(&$record) { $params = array('userRecord' => $record); $contentObj = new UserPasswordRecoveryEmailContent($params); $from = CoreConfig::get('Environment', 'passwordRecoveryEmailSender'); $listTo = array($record['userEmail']); $listCC = array(CoreConfig::get('Environment', 'errorEmailRecipient')); $subject = $contentObj->getSubject(); $content = $contentObj->getContent(); $attachments = $contentObj->getAttachments(); // CoreServices2::getMail()->sendHTML($from, $listTo, $listCC, $subject, $content, $attachments); CoreServices2::getMail()->sendPlainText($from, $listTo, $listCC, $subject, $content, $attachments); }
public function get($serviceName) { switch ($serviceName) { case 'url': return new CoreUrlStandard(); // return new CoreUrlFriendlyLinks1(); // return new CoreUrlFriendlyLinks1(); case 'request': return new CoreRequestStandard(); case 'db': return new CoreDBMySQL(CoreConfig::get('Environment', 'dbHost'), CoreConfig::get('Environment', 'dbPort'), CoreConfig::get('Environment', 'dbUser'), CoreConfig::get('Environment', 'dbPassword'), CoreConfig::get('Environment', 'dbName')); case 'display': return new CoreDisplaySmarty(); case 'lang': return new CoreLang(); case 'access': return new CoreAccessVariant1(); case 'modules': return new CoreControllerManager(); case 'files': return new CoreFileManager(); // @TODO: ? // case 'files1': // return new CoreFileHushvizManager(); // @TODO: ? // case 'files1': // return new CoreFileHushvizManager(); case 'images': return new CoreFileImageHandler(); case 'attachmentLocationManager': return new FileHushvizUrlManager(); case 'websiteMenuManager': return new SubpageUrlManager(); // return new SubpageUrlManagerFriendlyLinks1(); // return new SubpageUrlManagerFriendlyLinks1(); case 'mail': return new CoreMailSimple(); case 'paymentRelationLogic': return new CreditsPackagePaymentRelationLogic(); case 'paymentProviderInterface': return new PayPal_EC(); // return new PaymentDummy(); // return new PaymentDummy(); case 'errorHandler': return new CoreErrorHandler(); //return new CoreErrorHandlerMail(); } throw new CoreException('Service name not registered: \'' . $serviceName . '\'.'); }
public function adjustSubmittedValue($submittedValue) { if (!is_scalar($submittedValue)) { // assume hacking attempt //return ''; return null; } $submittedValue = trim($submittedValue); if (empty($submittedValue)) { return null; } $submittedValue = htmlspecialchars($submittedValue, ENT_QUOTES, CoreConfig::get('CoreDisplay', 'globalCharset')); $submittedValue = str_replace("\n", '<br/>', $submittedValue); return $submittedValue; }
public function adjustSubmittedValue($submittedValue) { if (!is_array($submittedValue)) { // assume hacking attempt return array(); } $returnValue = array(); foreach ($submittedValue as $simpleValue) { if (is_scalar($simpleValue)) { // else assume hacking attempt $returnValue[] = htmlspecialchars($simpleValue, ENT_QUOTES, CoreConfig::get('CoreDisplay', 'globalCharset')); } } return $returnValue; }
public function __construct($controller, $address, $maxRecordsOnPage = null, $maxShownPages = null) { $this->controller = $controller; $this->address = CoreServices::get('url')->stripParams($address, array('page')); if (!empty($maxRecordsOnPage)) { $this->maxRecordsOnPage = $maxRecordsOnPage; } else { $this->maxRecordsOnPage = CoreConfig::get('CoreDisplay', 'paginationDefaultMaxRecords'); } if (!empty($maxShownPages)) { $this->maxShownPages = $maxShownPages; } else { $this->maxShownPages = CoreConfig::get('CoreDisplay', 'paginationDefaultMaxPageLinks'); } $this->init(); }
protected function addStaticImageInfo(&$imageData) { if (count($imageData) != 2) { throw new CoreException('Invalid number of arguments supplied for static image in email template!'); } $fileName = basename($imageData[1]); $fileExtension = end(explode(".", $fileName)); $filePath = $imageData[1]; $mimeTypes = array_flip(CoreConfig::get('CoreFiles', 'defaultExtensions')); if (!empty($mimeTypes[$fileExtension])) { $fileMimeType = $mimeTypes[$fileExtension]; } else { throw new CoreException('Unrecognized mimetype for extension "' . $fileExtension . '"'); } $this->attachments[] = array('cid' => $cid, 'fileName' => $fileName, 'filePath' => $filePath, 'mimeType' => $fileMimeType); }
protected function createFormFields() { parent::createFormFields(); if (empty($this->record['id'])) { $this->form->addField(new CoreFormFieldText('adminName')); } $this->form->addField(new CoreFormFieldPassword('adminPassword')); $this->form->addField(new CoreFormFieldPassword('adminPasswordConfirm')); if ($this->currentUser['adminRole'] == $this->adminRoles['adminRoleSuperadmin']) { $this->form->addField(new CoreFormFieldText('adminFirstName')); $this->form->addField(new CoreFormFieldText('adminSurname')); if ($this->record['id'] != $this->currentUser['id']) { $this->form->addField(new CoreFormFieldSelect('adminRole', null, array(0 => '<choose>') + CoreConfig::get('Data', 'adminRoles'))); } } }
protected function checkUrl() { $uri = $_SERVER['REQUEST_URI']; $uriPart = $uri; $qmPos = strpos($uriPart, '?'); if ($qmPos !== false) { $uriPart = substr($uriPart, 0, $qmPos); } $uriPart = substr($uriPart, strlen(CoreConfig::get('Environment', 'urlPath'))); if (strpos($uriPart, '/') !== false) { header("HTTP/1.0 404 Not Found"); exit; // W wersji testowej można tez tak: // throw new CoreException('Invalid location: ' . $uri); } }
public function getConnection() { if (!$this->connection) { $hostPort = $this->dbHost; if ($this->dbPort) { $hostPort .= ':' . $this->dbPort; } $this->connection = mysql_connect($hostPort, $this->dbUser, $this->dbPassword, True); $this->checkResult(True); $mysqlResult = mysql_select_db($this->dbName, $this->connection); $this->checkResult($mysqlResult, 'select db ' . $this->dbName); $sql = 'SET NAMES ' . CoreConfig::get('CoreDBMySQL', 'connectionCharset') . ' COLLATE ' . CoreConfig::get('CoreDBMySQL', 'connectionCollation'); $mysqlResult = mysql_query($sql, $this->connection); $this->checkResult($mysqlResult, $sql); } return $this->connection; }
/** * Usuwa te rekordy z tabeli _tmpRecord, dla których sesja już na pewno wygasła. * Usuwa też przypisane do tych rekordów pliki. */ public function clean() { $calendar = new Calendar(); $time = $calendar->addSeconds(CoreUtils::getDateTime(), -CoreConfig::get('Cron', 'tmpRecordOldAgeSeconds')); $tmpRecordDAO = new TmpRecordDAO(); $oldRecords = $tmpRecordDAO->getOldRecords($time, CoreConfig::get('Cron', 'tmpRecordsToDeletePerExecution')); $fileDAO = new FileDAO(); foreach ($oldRecords as $record) { if ($this->isForDeletion($record)) { $files = $fileDAO->getListByRecord('_tmpRecord', $record['id']); foreach ($files as $file) { $fileDAO->delete($file); } $tmpRecordDAO->delete($record); } } }
/** * Be careful when making some changes to this function. * It indirectly validates GET input. */ protected function initCurrentControllerName() { $moduleName = CoreServices::get('request')->getFromGet('_m'); if (empty($moduleName)) { $moduleName = CoreConfig::get('Structure', 'defaultModule'); } $modeName = CoreServices::get('request')->getFromGet('_o'); if (empty($modeName)) { $modeName = CoreConfig::get('Structure', 'defaultMode'); } if (!file_exists(CoreAutoload::getClassPath($this->getControllerClass($moduleName, $modeName)))) { $moduleName = CoreConfig::get('Structure', 'defaultModule'); $modeName = CoreConfig::get('Structure', 'defaultMode'); } $this->currentModule = $moduleName; $this->currentMode = $modeName; }
public function handleError($errno, $errstr, $errfile = null, $errline = null, $errcontext = null) { // autoloader doesn't work here... require_once CoreConfig::get('Environment', 'applicationDir') . 'php/config/ConfigSettings.class.php'; // If there is a statement preceded with '@', and it causes some warning, // we don't want to throw exception, because: // Unfortunately there are some functions in PHP that trigger warnings // even if nothing wrong happens. if (ini_get('error_reporting') == 0 || in_array($errno, CoreConfig::get('Settings', 'ignoredErrorLevels'))) { return true; } $message = 'Error in file: ' . $errfile . ', Line: ' . $errline . '; ' . 'Code: ' . $errno . '; ' . 'Message: ' . $errstr . '; ' . 'Context: ' . serialize($errcontext); // var_export($errcontext, true) byłoby fajniejsze ale niestety // wysypuje się przy tablicach o kilku poziomach zagnieżdżenia; // w szczególnosci dzieje się tak jeśli błąd jest w Smarty. exit('<pre>' . $message . '</pre>'); }
protected function report($message) { // autoloader doesn't work here... require_once CoreConfig::get('Environment', 'applicationDir') . 'php/core/mail/iCoreMail.interface.php'; require_once CoreConfig::get('Environment', 'applicationDir') . 'php/core/mailsimple/CoreMailSimple.class.php'; // restore default handler, just in case... restore_error_handler(); $to = array(CoreConfig::get('Environment', 'errorEmailRecipient')); $cc = null; $mailer = new CoreMailSimple(); try { $mailer->sendPlainText(CoreConfig::get('Environment', 'errorEmailSender'), $to, $cc, CoreConfig::get('Environment', 'websiteName') . ' - Error', $message); } catch (Exception $e) { exit('<b>Failed to send error email!</b><pre>' . $message . '</pre>'); } $this->initErrorHandler(); }
protected function checkHTTPS() { $httpsOn = CoreServices2::getUrl()->isHTTPSOn(); if ($this->getSessionName() == 'CMSSession') { $httpsRequired = CoreConfig::get('Environment', 'httpsForCMS'); } elseif ($this->getSessionName() == 'WebsiteSession') { $httpsRequired = CoreConfig::get('Environment', 'httpsForWebsite'); } else { $httpsRequired = False; // i tak nie ma sesji! } if ($httpsRequired && !$httpsOn) { CoreUtils::redirect(CoreServices::get('url')->getCurrentExactAddress('https')); } if (!$httpsRequired && $httpsOn) { CoreUtils::redirect(CoreServices::get('url')->getCurrentExactAddress('http')); } }
public function getLangs($index, $firstLang = null) { $availableLangs = CoreConfig::get('CoreLangs', 'langs' . $index); if (!is_null($firstLang)) { if (!in_array($firstLang, $availableLangs)) { throw new CoreException('Invalid language: \'' . $firstLang . '\''); } $result = array(0 => $firstLang); foreach ($availableLangs as $someLang) { if ($someLang != $firstLang) { $result[] = $someLang; } } return $result; } else { $result = $availableLangs; } return $result; }
protected function initConfig() { if ($this->lang) { $configFiles = CoreConfig::get('CoreDisplaySmarty', 'configFileByRootTpl'); if (array_key_exists($this->rootTemplateType, $configFiles)) { $configFileName = $this->lang . '_' . $configFiles[$this->rootTemplateType] . '.conf'; } else { foreach ($configFiles as $prefix => $fileBaseName) { if (substr($fileBaseName, 0, strlen($prefix)) == $prefix) { $configFileName = $this->lang . '_' . $fileBaseName . '.conf'; } } } if ($this->contentType) { $this->smarty->config_load($configFileName, $this->contentType); } else { $this->smarty->config_load($configFileName); } } }
/** * Explicit GET arguments like ...?_o=7... overwrite the ones encoded in comma-separated part of the address. * For example if address is <domain>/1,1,1?_o=2 request values will be like this: * array('_m' => 1, '_o' => 2, 'id' = 1) */ public function createGetParamsTable($address) { $suffix = substr($address, strlen($this->getCurrentProtocolPrefix() . CoreConfig::get('Environment', 'urlPrefix'))); $result = array(); if (!$suffix) { return $result; } $parts1 = explode('?', $suffix); if (!empty($parts1[0])) { $parts2 = explode(',', $parts1[0]); $moduleNames = array_flip($this->moduleNumbers); $modeNames = array_flip($this->modeNumbers); if (!empty($parts2[0]) && !empty($moduleNames[$parts2[0]])) { $result['_m'] = $moduleNames[$parts2[0]]; } if (!empty($parts2[1]) && !empty($modeNames[$parts2[1]])) { $result['_o'] = $modeNames[$parts2[1]]; } if (!empty($parts2[2])) { $result['id'] = $parts2[2]; } } if (!empty($parts1[1])) { $pairs = explode('&', str_replace('&', '&', $parts1[1])); foreach ($pairs as $pair) { $param = explode('=', $pair); $value = isset($param[1]) ? urldecode($param[1]) : ''; if (substr($param[0], -2) == '[]') { $paramName = substr($param[0], 0, -2); if (empty($result[$paramName])) { $result[$paramName] = array(); } $result[$paramName][] = $value; } else { $result[$param[0]] = $value; } } } return $result; }
public function getValidPartialHTML($html, $docType = null, $encoding = null) { if (empty($html)) { return $html; } if (empty($docType)) { $docType = CoreConfig::get('CoreDisplay', 'htmlDocType'); } if (empty($encoding)) { $encoding = CoreConfig::get('CoreDisplay', 'globalCharset'); } $config = HTMLPurifier_Config::createDefault(); $config->set('Cache', 'SerializerPath', CoreConfig::get('Environment', 'htmlPurifierCacheDirDiskPath')); $config->set('Core', 'Encoding', $encoding); $config->set('HTML', 'Doctype', $docType); $config->set('HTML', 'DefinitionID', 'enduser-customize.html tutorial'); $config->set('HTML', 'DefinitionRev', 1); $def = $config->getHTMLDefinition(true); $def->addAttribute('a', 'target', new HTMLPurifier_AttrDef_Enum(array('_blank', '_self', '_target', '_top'))); $purifier = new HTMLPurifier($config); return $purifier->purify($html); }