protected function executeImpl(ArrayAdapter $params) { $url = $params->str('url'); $text = $params->str('text'); $note = $params->str('note'); if (!$url || !$text) { return 'Не передан url или текст'; } /* * Если пользователь не просматривал эту страницу и это не администратор - игнорируем. */ /* $wasOpened = PageOpenWatcher::isPageOpenedByUser($url, PsUser::instOrNull()); if (!$wasOpened && !AuthManager::isAuthorizedAsAdmin()) { return 'Пользователь не открывал страницу'; //--- } */ $text = UserInputTools::safeShortText($text); $note = $note ? UserInputTools::safeLongText($note) : $note; $saved = UtilsBean::inst()->saveMisprint($url, $text, $note, AuthManager::getUserIdOrNull()); if (!$saved) { return 'Запись не была сохранена'; //--- } return new AjaxSuccess(); }
private function jsCommon() { $params['url'] = PsUrl::current(); $params['userId'] = AuthManager::getUserIdOrNull(); $params['isAuthorized'] = AuthManager::isAuthorized(); $params['isDOA'] = PsSettings::DEVMODE_OR_ADMIN(); $params['isLogging'] = PsSettings::DEVMODE_OR_ADMIN(); $params['currentSubmitTimeout'] = ActivityWatcher::getWaitTime(); $params['tzOffset'] = PsTimeZone::inst()->getCurrentDateTimeZone()->getOffset(new DateTime()); $params['marker'] = AuthManager::getUserSessoinMarker(); $params['foldings'] = FoldedStorage::listEntitiesRel(); return $params; }
private function jsCommon(PageContext $ctxt) { $params['url'] = $ctxt->getRequestUrl(); $params['isPopup'] = $ctxt->isPopupPage(); $params['userId'] = AuthManager::getUserIdOrNull(); $params['isAuthorized'] = AuthManager::isAuthorized(); $params['isDOA'] = PsSettings::DEVMODE_OR_ADMIN(); $params['isLogging'] = PsSettings::DEVMODE_OR_ADMIN(); $params['currentSubmitTimeout'] = ActivityWatcher::getWaitTime(); $params['tzOffset'] = PsTimeZone::inst()->getCurrentDateTimeZone()->getOffset(new DateTime()); $params['marker'] = AuthManager::getUserSessoinMarker(); /* @var $folding FoldedResources */ foreach (Handlers::getInstance()->getFoldingsIndexed() as $unique => $folding) { $params['foldings'][$unique] = $folding->getResourcesDm()->relDirPath(); } return $params; }
public function getAnswer4User($taskIdent) { $userId = AuthManager::getUserIdOrNull(); return $userId ? MatchesBean::inst()->getTaskAnswers4User($userId, $taskIdent) : null; }
/** * Метод выполняет дамп таблицы */ 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; }
/** * Метод обновляет время последнего просмотра страницы */ public static function updateUserPageWatch($url) { UtilsBean::inst()->savePageWatch(AuthManager::getUserIdOrNull(), $url); }
public function getSystemSolutions() { return ChessKnightBean::inst()->getSystemSolutions(AuthManager::getUserIdOrNull()); }
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); } }