/** @return ADORecordSet */ private static function executeQuery($query, $params = false, &$queryFinal = null, array &$paramsFinal = null) { $queryFinal = $query instanceof Query ? $query->build($params) : $query; $queryFinal = normalize_string($queryFinal); $paramsFinal = to_array($params); $LOGGER = PsLogger::inst(__CLASS__); $PROFILER = PsProfiler::inst(__CLASS__); $PROFILER->start(strtolower($queryFinal)); try { if ($LOGGER->isEnabled()) { $LOGGER->info("[{$queryFinal}]" . ($paramsFinal ? ', PARAMS: ' . array_to_string($paramsFinal) : '')); } $rs = PsConnectionPool::conn()->execute($queryFinal, $paramsFinal); if (is_object($rs)) { $PROFILER->stop(); return $rs; } $error = PsConnectionPool::conn()->ErrorMsg(); $LOGGER->info('ERROR: {}', $error); throw new DBException($error, DBException::ERROR_NOT_CLASSIFIED, $queryFinal, $paramsFinal); } catch (Exception $ex) { $PROFILER->stop(false); if ($ex instanceof DBException) { ExceptionHandler::dumpError($ex); } throw $ex; } }
<?php $type = array_key_exists('type', $_POST) ? $_POST['type'] : null; $marker = array_key_exists('marker', $_POST) ? $_POST['marker'] : null; if (!$type) { die('Bad type given.'); } //MD5_STR_LENGTH ещё использовать нельзя, так как Defines не подключен if (!$marker || strlen($marker) <= 32) { die('Bad marker given.'); } $sessionId = substr($marker, 32); session_id($sessionId); require_once 'AjaxTools.php'; check_user_session_marker($marker); try { FileUploader::inst($type)->assertAutonomous(); FileUploader::inst($type)->saveUploadedFile(true, null, $_POST); } catch (Exception $ex) { PsLogger::inst('AjaxFileUpload')->info('Ошибка загрузки файла'); PsLogger::inst('AjaxFileUpload')->info($ex->getTraceAsString()); ExceptionHandler::dumpError($ex); }
/** * Метод отправляет письмо пользователю * * @throws Exception */ public function Send() { $PROFILER = PsProfiler::inst(__CLASS__); $PROFILER->start('Send'); try { //Отправляем письмо $result = parent::Send(); //Останавливаем профайлер $PROFILER->stop(); //Сделаем дамп отправленного письма $this->dumpEmail(); //Запишем аудит MailAudit::inst()->afterSended($this); //Вернём то, что вернул оригинальный Send метод return $result; } catch (Exception $ex) { //Останавливаем профайлер без сохранения $PROFILER->stop(false); //Если возникла ошибка отправки письма - сделаем её дамп вместе с письмом if ($ex instanceof phpmailerException) { ExceptionHandler::dumpError($ex, $this); } throw $ex; } }
/** * Метод выполняет дамп таблицы */ public static function dumpTable($idColumn, $table, array $where = array(), $order = null) { //Стартуем секундомер $secundomer = Secundomer::startedInst("Снятие дампа {$table}"); //Отключим ограничение по времени PsUtil::startUnlimitedMode(); //Получим экземпляр логгера $LOGGER = PsLogger::inst(__CLASS__); //Текущий пользователь $userId = AuthManager::getUserIdOrNull(); //Для логов, запросов и все остального $table = strtoupper(PsCheck::tableName($table)); //Макс кол-во записей $limit = PsDefines::getTableDumpPortion(); //Проверим наличие id $idColumn = PsCheck::tableColName($idColumn); $LOGGER->info('Dumping table {}. Id column: {}, limit: {}. User id: {}.', $table, $idColumn, $limit, $userId); //Получаем лок (без ожидания) $lockName = "DUMP table {$table}"; $locked = PsLock::lock($lockName, false); $LOGGER->info('Lock name: {}, locked ? {}.', $lockName, var_export($locked, true)); if (!$locked) { return false; //Не удалось получить лок } $zipDi = false; try { //ЗПРОСЫ: //1. Запрос на извлечение колва записей, подлежащих дампированию $queryCnt = Query::select("count({$idColumn}) as cnt", $table, $where); //2. Запрос на извлечение данных, подлежащих дампированию $queryDump = Query::select('*', $table, $where, null, $order, $limit); //3. Запрос на извлечение кодов дампируемых записей $selectIds = Query::select($idColumn, $table, $where, null, $order, $limit); //4. Запрос на удаление дампированных данных $queryDel = Query::delete($table, Query::plainParam("{$idColumn} in (select {$idColumn} from (" . $selectIds->build($delParams) . ') t )', $delParams)); //Выполним запрос для получения кол-ва записей, подлежащих дампу $cnt = PsCheck::int(array_get_value('cnt', PSDB::getRec($queryCnt, null, true))); $LOGGER->info('Dump recs count allowed: {}.', $cnt); if ($cnt < $limit) { $LOGGER->info('SKIP dumping table, count allowed ({}) < limit ({})...', $cnt, $limit); $LOGGER->info("Query for extract dump records count: {$queryCnt}"); PsLock::unlock($lockName); return false; } //Время дампа $date = PsUtil::fileUniqueTime(false); $time = time(); //Название файлов $zipName = $date . ' ' . $table; //Элемент, указывающий на zip архив $zipDi = DirManager::stuff(null, array(self::DUMPS_TABLE, $table))->getDirItem(null, $zipName, PsConst::EXT_ZIP); $LOGGER->info('Dump to: [{}].', $zipDi->getAbsPath()); if ($zipDi->isFile()) { $LOGGER->info('Dump file exists, skip dumping table...'); PsLock::unlock($lockName); return false; } //Комментарий к таблице $commentToken[] = "Date: {$date}"; $commentToken[] = "Time: {$time}"; $commentToken[] = "Table: {$table}"; $commentToken[] = "Manager: {$userId}"; $commentToken[] = "Recs dumped: {$limit}"; $commentToken[] = "Total allowed: {$cnt}"; $commentToken[] = "Query dump cnt: {$queryCnt}"; $commentToken[] = "Query dump data: {$queryDump}"; $commentToken[] = "Query dump ids: {$selectIds}"; $commentToken[] = "Query del dumped: {$queryDel}"; $comment = implode("\n", $commentToken); //Начинаем zip и сохраняем в него данные $zip = $zipDi->startZip(); $zip->addFromString($zipName, serialize(PSDB::getArray($queryDump))); $zip->setArchiveComment($comment); $zip->close(); $LOGGER->info('Data successfully dumped, zip comment:'); $LOGGER->info("[\n{$comment}\n]"); //Удалим те записи, дамп которых был снят $LOGGER->info('Clearing dumped table records...'); $affected = PSDB::update($queryDel); $LOGGER->info('Rows deleted: {}.', $affected); $LOGGER->info('Dumping is SUCCESSFULLY finished. Total time: {} sec.', $secundomer->stop()->getAverage()); } catch (Exception $ex) { PsLock::unlock($lockName); ExceptionHandler::dumpError($ex); $LOGGER->info('Error occured: {}', $ex->getMessage()); throw $ex; } return $zipDi; }
/** * Метод возвращает DirItem элемента, содержащего картинку-представление формулы. * * @param type $formula - текстовая формула * @param type $createIfNotExists - признак, стоит ли пытаться создавать картинку для формулы * @return DirItem */ public function getImgDi($formula, $createIfNotExists = true) { $formula = TexTools::safeFormula($formula); if ($this->CACHE->has($formula)) { return $this->CACHE->get($formula); } $hash = TexTools::formulaHash($formula); $imgDI = $this->DM->getHashedDirItem(null, $hash, $hash, 'gif'); if ($imgDI->isImg()) { $this->CACHE->set($formula, $imgDI); return $imgDI; } if (!$createIfNotExists) { return null; } //Создаём структуру директорий $imgDI->makePath(); $contents = ''; //Запрашиваем графическое представление $this->PROFILER->start($formula); try { //TODO - делать это локально, чтобы не зависить от стороннего сервиса $handle = fopen('http://latex.codecogs.com/gif.latex?' . rawurlencode($formula), 'r'); while (!feof($handle)) { $contents .= fread($handle, 8192); } fclose($handle); $this->PROFILER->stop(); } catch (Exception $ex) { //Останавливаем профайлер без сохранения $this->PROFILER->stop(false); //Делаем дамп ошибки ExceptionHandler::dumpError($ex, "Tex formula convertation requested for:\n{$formula}"); //Попытаемся подчистить за собой, если мы что-то создали $imgDI->remove(); //Пробрасываем эксепшн throw $ex; } //Сохраняем картинку в файл $imgDI->putToFile($contents); //Сохраним текстовое представление $this->DM->getHashedDirItem(null, $hash, $hash, 'gif.tex')->putToFile($formula); $this->CACHE->set($formula, $imgDI); return $imgDI; }
/** * Основной метод, выполняющий обработку формы. * * @return AbstractForm */ private final function process() { if ($this->processed) { return $this; //--- } $this->processed = true; if (!$this->isTryingSubmit()) { return $this; //--- } //Проверка доступа $this->checkAccess(); if ($this->isAddCapture() && !PsCapture::isValid()) { $this->error = 'Требуется валидный код с картинки'; return $this; //--- } //Если пользователь зарегистрирован, как администратор - подключим ресурсы админа ps_admin_on(); $button = $this->getSubmittedButton(); if (!$button) { $this->error = "Не передана нажатая кнопка для формы {$this->ident}."; return $this; //--- } if (!$this->hasButton($button)) { $this->error = "Форма {$this->ident} засабмичена незарегистрированной кнопкой {$button}."; return $this; //--- } if ($this->isCheckActivity() && !ActivityWatcher::isCanMakeAction()) { $this->error = 'Таймаут не закончился.'; return $this; //--- } //Вызываем обработку данных $result = null; try { $result = $this->processImpl(PostArrayAdapter::inst(), $button); } catch (Exception $ex) { $this->error = $ex->getMessage(); ExceptionHandler::dumpError($ex); return $this; //--- } if (isEmpty($result)) { $this->error = "Форма {$this->ident} обработана некорректно - возвращён пустой объект."; return $this; //--- } if (is_object($result) && $result instanceof FormSuccess) { //SUCCESS //Форсированно сбросим капчу (всё равно, работаем с ней или нет) PsCapture::reset(); //Зарегистрируем активноcть пользователя (только в случае успеха, так как пользователь мог просто ошибиться в воде данных) if ($this->isCheckActivity()) { ActivityWatcher::registerActivity(); } $this->result = $result; } else { //ERROR $this->error = $result; } return $this; }
die; PSSmarty::smarty(); echo (new SmartyFunctions())->psctrl(array()); die; print_r(FoldedStorage::listFoldingUniques()); print_r(FoldedStorageInsts::listFoldingUniques()); die; var_dump(ConfigIni::projectSrcAdminDir()); br(); var_dump(ConfigIni::projectSrcCommonDir()); br(); var_dump(ConfigIni::projectGlobalsFilePath()); br(); new YouTubePluginAdmin(); die; ExceptionHandler::dumpError(new Exception('XXXX'), 'Additional info'); die; class X { protected function __construct() { echo 'X'; } } class Y extends X { function __construct() { //parent::__construct(); } }
/** * Основной метод авторизации пользователей в системе */ private static final function loginImpl($login, $passwd, UserLoadType $userType, $afterRegistration = false) { self::logout(); $userId = UserBean::inst()->getUserIdByMailPass($login, $passwd, $userType); if (is_integer($userId)) { /* * Пользователь авторизован! */ SessionArrayHelper::setInt(SESSION_USER_PARAM, $userId); } if (self::isAuthorized()) { //Убедимся в наличии пользователя $user = PsUser::inst($userId, true); try { if ($afterRegistration) { //ApplicationListener::afterUserRegistered($user); } //Оповещаем слушатель об успешной авторизации пользователя. //ApplicationListener::afterLogin($user); } catch (Exception $ex) { //Сделаем дамп ошибки ExceptionHandler::dumpError($ex); } } else { check_condition(!$afterRegistration, 'Не удалось авторизоваться после создания пользователя'); } return self::isAuthorized(); }
protected function doAudit($action, $userId = null, $data = null, $saveToSession = false, $parentAction = null, $auditIfNoParent = true, $clearParent = true) { try { $action = $this->validateAction($action); $parentAction = $this->validateAction($parentAction, true); $actionSessionKey = $this->sessionCode($action); $parentActionSessionKey = $parentAction ? $this->sessionCode($parentAction) : null; $parentId = $parentActionSessionKey ? SessionArrayHelper::getInt($parentActionSessionKey) : null; $hasParentIdInSession = is_integer($parentId); $userId = AuthManager::validateUserIdOrNull($userId); $userIdAuthed = AuthManager::getUserIdOrNull(); if ($this->LOGGER->isEnabled()) { $this->LOGGER->info(); $this->LOGGER->info("<Запись #{}>", ++$this->NUM); $this->LOGGER->info('Действие: {}', $this->decodeAction($action)); $this->LOGGER->info('Пользователь: {}', is_inumeric($userId) ? $userId : 'НЕТ'); $this->LOGGER->info('Авторизованный пользователь: {}', is_inumeric($userIdAuthed) ? $userIdAuthed : 'НЕТ'); $this->LOGGER->info('Данные: {}', $data === null ? 'НЕТ' : print_r($data, true)); $this->LOGGER->info('Сохранять в сессию: {}', $saveToSession ? 'ДА' : 'НЕТ'); $this->LOGGER->info('Родительское действие: {}', $this->decodeAction($parentAction)); if ($parentAction) { $this->LOGGER->info('Родительское действие есть в сессии: {}', $hasParentIdInSession ? "ДА ({$parentActionSessionKey}={$parentId})" : 'НЕТ'); if ($hasParentIdInSession) { $this->LOGGER->info('Очищать родительское действие в сессии: {}', $clearParent ? 'ДА' : 'НЕТ'); } else { $this->LOGGER->info('Производить аудит при отсутствии родит. действия: {}', $auditIfNoParent ? 'ДА' : 'НЕТ'); } } } if (!$hasParentIdInSession && !$auditIfNoParent) { $this->LOGGER->info('АУДИТ НЕ ПРОИЗВЕДЁН!'); return; //--- Нужен предок, но его нет } $encoded = 0; if (is_array($data)) { if (count($data) == 0) { $data = null; } else { $data = self::encodeData($data); $encoded = 1; } } check_condition($data === null || is_string($data) || is_numeric($data), 'Illegal audit data type: ' . gettype($data) . ' for ' . $this); $recId = UtilsBean::inst()->saveAudit($parentId, $userId, $userIdAuthed, $this->PROCESS_CODE, $action, $data, $encoded); if ($this->LOGGER->isEnabled()) { if ($data !== null) { $this->LOGGER->info('Данные кодированы: {}', $encoded ? "ДА ({$data})" : 'НЕТ'); } $this->LOGGER->info('Информация сохранена в базу, id={}', $recId); } if ($saveToSession) { SessionArrayHelper::setInt($actionSessionKey, $recId); $this->LOGGER->info("Данные о действии сохранены в сессию ({$actionSessionKey}={$recId})"); } if ($hasParentIdInSession && $clearParent) { SessionArrayHelper::reset($parentActionSessionKey); $this->LOGGER->info('Данные о родительском действии удалены из сессии'); } $this->LOGGER->info('АУДИТ ПРОИЗВЕДЁН.'); } catch (Exception $ex) { //Не удалось записть аудит, но работа должна быть продолжена! ExceptionHandler::dumpError($ex); } }