/** * Метод сохраняет картинку в файл */ public function saveToFile(DirItem $path) { $path->assertExtension(PsConst::EXT_GIF); $fp = fopen($path->getAbsPath(), 'w'); fwrite($fp, $this->getAnimation()); fclose($fp); }
/** * Метод разбирает файл с ребусами, который выглядит как: * * ребус 1 * ответ 1.1 * ответ 1.2 * * ребус 2 * ответ 2.1 * ответ 2.2 * * @return type */ private function parseAnswersFile(DirItem $di) { $result = array(); $lines = explode("\n", trim($di->getFileContents(false))); $current = null; foreach ($lines as $line) { $line = trim($line); if ($line && !$current) { //Начинается новый ребус $current = $line; $result[$current] = array(); } else { if ($line && $current) { //Ответ на ребус $result[$current][] = $line; } else { if (!$line && $current) { //Пробел, закончили ребус $current = null; } } } } if ($this->LOGGER->isEnabled()) { $this->LOGGER->info('Rebuses of {}:', $di->getRelPath()); $this->LOGGER->info(print_r($result, true)); $this->LOGGER->info(); } return $result; }
public static function inst(FoldedEntity $entity, DirItem $tplDi) { if (!array_key_exists($tplDi->getRelPath(), self::$INSTS)) { self::$INSTS[$tplDi->getRelPath()] = new FoldedInfoTpl($entity, $tplDi); } return self::$INSTS[$tplDi->getRelPath()]; }
protected function onInit(DirItem $di) { $this->info = getimagesize($di->getAbsPath()); check_condition($this->info, "В ImageAdapter передана невалидная картинка [{$di->getRelPath()}]."); $this->width = $this->info[0]; $this->height = $this->info[1]; }
public function appendFile(DirItem $file, $ensure = true) { $contents = trim($file->getFileContents($ensure)); if ($contents) { $contents = remove_utf8_bom($contents); $this->appendMlComment("+ FILE [{$file->getName()}]"); $this->di->writeLineToFile($contents); } unset($contents); }
/** * Возвращает тело класса/интерфейса */ public function getClassBody() { $lines = $this->di->getFileLines(true, true); $firstLine = $this->rc->getStartLine(); $endLine = $this->rc->getEndLine(); if ($endLine <= $firstLine + 1) { return ''; } return trim(implode('', array_slice($lines, $firstLine, $endLine - $firstLine - 1))); }
private function doCopy(DirItem $from, DirItem $to) { $from->assertIsImg(); PsLock::lockMethod(__CLASS__, __FUNCTION__); try { //Очистим нагенерённое для той картинки, В КОТОРУЮ копируем $this->doClean($to); //Картинка не была пересоздана в другом потоке SimpleImage::inst()->load($from)->save($to, SYSTEM_IMG_TYPE)->close(); } catch (Exception $ex) { PsLock::unlock(); throw $ex; } PsLock::unlock(); }
/** * Процесс выполняет периодические задачи cron * * @param array $argv */ function executeProcess(array $argv) { $SYNC_DIR = 'd:/Zona Downloads/Архив пранкоты/'; $lists = DirManager::inst(__DIR__)->getDirContent('m3u', PsConst::EXT_M3U); $filesCopied = DirItem::inst(__DIR__, 'all_copied', 'list')->remove()->touch(); $filesSkipped = DirItem::inst(__DIR__, 'all_skipped', 'list')->remove()->touch(); $destDir = DirManager::inst(__DIR__, 'dest')->clearDir()->makePath(); /* @var $list DirItem */ foreach ($lists as $name => $list) { $name = mb_convert_encoding($name, 'UTF-8', 'cp1251'); dolog("+ {$name}"); foreach ($list->getFileLines() as $newFile) { $newFile = mb_convert_encoding($newFile, 'UTF-8', 'UTF-8'); if (starts_with($newFile, '#')) { dolog(" - {$newFile}"); continue; //--- } $absPath = next_level_dir($SYNC_DIR, $newFile); $absPath = iconv('UTF-8', 'cp1251', $absPath); $isFile = is_file($absPath); dolog(" + {$newFile} ? {}", var_export($isFile, true)); if (!$isFile) { $filesSkipped->writeLineToFile($absPath); continue; //--- } $fileName = iconv('UTF-8', 'cp1251', basename($newFile)); copy($absPath, $destDir->absFilePath(null, $fileName)); $filesCopied->writeLineToFile($absPath); } //print_r($list->getFileLines()); } }
public function sortTpl(DirItem $di1, DirItem $di2) { /* @var $post1 Post */ $post1 = $di1->getData('post'); /* @var $post2 Post */ $post2 = $di2->getData('post'); if (!$post1 && $post2) { return -1; } if ($post1 && !$post2) { return 1; } if (!$post1 && !$post2) { return strcmp($di1->getNameNoExt(), $di2->getNameNoExt()); } return $post1->getDtPublication() < $post2->getDtPublication() ? 1 : -1; }
/** * @covers AutoloadDir::isRebuilded */ public function testIsRebuilded() { //Запросим путь к тестовому классу, чтобы он уже наверняка был найден на момент запроса. $this->assertNotNull(Autoload::inst()->getClassPath(ClassA::get__CLASS__())); //Мы должны найти нагш класс без перезагрузки, так как уже нашли его ранее $cpDir = new AutoloadDir(DirItem::inst(Autoload::DIR_TESTS)); $this->assertNotNull($cpDir->getClassPath(ClassA::get__CLASS__())); $this->assertFalse($cpDir->isRebuilded()); }
function saveResult2Html($tplName, $params = null, $__DIR__ = __DIR__, $htmlName = 'results.html', $title = null) { $tplName = ensure_file_ext($tplName, 'tpl'); $pageClass = cut_string_end($tplName, '.tpl'); $body = PSSmarty::template("hometools/{$tplName}", $params)->fetch(); $pageParams['title'] = $title == null ? 'Результаты' : $title; $pageParams['body'] = $body; $pageParams['class'] = $pageClass; $html = PSSmarty::template('hometools/page_pattern.tpl', $pageParams)->fetch(); $htmlName = ensure_file_ext($htmlName, 'html'); DirItem::inst($__DIR__, $htmlName)->writeToFile($html, true); }
private function saveCommonExcluded($class) { $pathes = $this->loadCommonExcluded(true); if (in_array($class, $pathes)) { //Класс уже отмечен, как исключённый return; //--- } $pathes[] = $class; $this->COMMON_EXCLUDED = $pathes; $this->COMMON_EXCLUDED_DI->saveArrayToFile($pathes); $this->COMMON_EXCLUDED_DI->getSibling($this->COMMON_EXCLUDED_DI->getName() . '_arr')->putToFile(print_r($pathes, true)); }
public static function format($__CLASS__, $__FUNCTION__, array $arguments) { if (!array_key_exists($__CLASS__, self::$MESSAGES)) { /* * Защита от зацикливания */ self::$MESSAGES[$__CLASS__] = null; /* * Определим, где расположен класс с сообщениями */ $classPath = Autoload::inst()->getClassPath($__CLASS__); if (!$classPath) { return PsUtil::raise('Группа сообщений {} не зарегистрирована', $__CLASS__); } /* * Получим DirItem сообщений для этого класса */ $messagesDi = DirItem::inst(dirname($classPath), $__CLASS__, PsConst::EXT_MSGS); if (!$messagesDi->isFile()) { return PsUtil::raise('Файл с сообщениями {} не существует', $messagesDi->getName()); } /* * Распарсим сообщения из файла */ self::$MESSAGES[$__CLASS__] = $messagesDi->getFileAsProps(); } /* * Проверим на зацикливание */ if (self::$MESSAGES[$__CLASS__] === null) { PsUtil::raise('Зацикливание при попытке получить сообещние {}::{}', $__CLASS__, $__FUNCTION__); } /* * Проверим на существование самого сообщения */ if (!array_key_exists($__FUNCTION__, self::$MESSAGES[$__CLASS__])) { return PsUtil::raise('Сообщение {}::{} не существует', $__CLASS__, $__FUNCTION__); } /* * Заменим макросы {} и вернём сообщение */ return PsStrings::replaceMapBracedKeys(self::$MESSAGES[$__CLASS__][$__FUNCTION__], $arguments); }
/** * Перестроение спрайта * * @return CssSprite */ public function rebuild($force = true) { if (!$this->rebuilded && ($force || !$this->exists())) { //Отлогируем $this->LOGGER->info("REBUILDING SPRITE FOR [{$this->name}]"); //Поставим признак перестроенносьти $this->rebuilded = true; //Сбросим закешированные элементы, так как css файл мог поменяться $this->items = null; //Удалим .css файл $this->cssDi->remove(); //Перестроим CssSpritesCreator::inst()->CreateSprite($this); //Создадим .css файл, даже если он не был создан в процессе построения. Просто у нас нет картинок в $spritable. $this->cssDi->touch(); } return $this; //--- }
function executeProcess(array $argv) { $rebuses = DirItem::inst(__DIR__, 'rebuses.txt')->getTextFileAdapter(); $MR = PsMathRebus::inst(); $result = array(); foreach ($rebuses->getLines() as $rebus) { if (starts_with($rebus, '#')) { continue; //--- } $rebus = $MR->normalize($rebus); switch ($MR->rebusState($rebus)) { case PsMathRebus::STATE_HAS_ANSWERS: dolog("Take rebus answers: {$rebus}"); $result[$rebus] = $MR->rebusAnswers($rebus); break; case PsMathRebus::STATE_NO_ANSWERS: dolog("Skipping rebus: {$rebus}"); $result[$rebus] = array(); break; case PsMathRebus::STATE_NOT_REGISTERED: dolog("Processing rebus: {$rebus}"); $result[$rebus] = PsMathRebusSolver::solve($rebus); break; } } $ansDI = DirItem::inst(__DIR__, 'answers.txt'); $ansDI->remove(); foreach ($result as $rebus => $answers) { $ansDI->writeLineToFile($rebus); foreach ($answers as $answer) { $ansDI->writeLineToFile($answer); } $ansDI->writeLineToFile(); } /* * Если передан параметр копирования, то скопируем файл после обработки */ if (1 == array_get_value(1, $argv, 0)) { dolog('Copy from [{}] to [{}]', $ansDI->getRelPath(), $MR->getAnswersDI()->getRelPath()); $ansDI->copyTo($MR->getAnswersDI()->getAbsPath()); } }
/** * Загрузка разметки администраторского меню */ public function getLayout() { $store = DirItem::inst(__DIR__, __CLASS__, 'layout')->getArrayFromFile(); $store = to_array($store); //Получим массив - копию страниц и будем удалять из него те страницы, которые входят в Layout $pages = $this->pages; //Базовую страницу всегда показываем в самом верху (единственная ссылка первого уровня) $LAY = new AdminPagesNavigation(); $LAY->addItem($this->getHrefToPage(AP_APCommon::getPageIdent()), 1); unset($pages[AP_APCommon::getPageIdent()]); //0 - группа, 1 - элемент foreach ($store as $item) { $type = $item[0]; $value = $item[1]; switch ($type) { //Группа case 0: $LAY->addItem($value, 1); break; //Элемент //Элемент case 1: if ($this->hasPage($value) && $value != AP_APCommon::getPageIdent()) { unset($pages[$value]); $LAY->addItem($this->getHrefToPage($value), 2); } break; } } //Оставшиеся страницы добавим в общую группу if (count($pages) > 0) { $LAY->addItem('Все страницы', 1); foreach ($pages as $page) { $LAY->addItem($this->getHrefToPage($page), 2); } } return $LAY->getHtml(); }
public function __construct(DirItem $dir) { $this->LOGGER = Autoload::getLogger(); $this->classesDir = $dir; $this->classPathFile = DirManager::autogen('classpath')->getDirItem(null, unique_from_path($dir->getRelPath())); }
private function getImages(ArrayAdapter $params, $FNAME) { $dir = $params->str('dir'); $name = $params->get('name'); //НЕПОСРЕДСТВЕННО КАРТИНКА if ($name instanceof DirItem) { return $name; } /* * FOLDING */ $FCW = FoldedContextWatcher::getInstance(); $folding = null; $ident = $params->get('ident'); //Тип фолдинга. Он может быть передан либо в параметре 'group', либо по префиксу смарти-функции, например: postimg (post-название типа фолдинга). $foldingType = $params->get('group'); $foldingType = $foldingType ? $foldingType : (starts_with($FNAME, 'img') ? null : array_get_value(0, explode('img', $FNAME))); //Подтип фолдинга, например: is - подтип фолдингов для фолдингов с типом post (выпуск журнала среди всех постов). $foldingSubType = $params->get('type'); if ($params->has('post')) { /* @var $post AbstractPost */ $post = $params->get('post'); $ident = $post->getIdent(); $folding = Handlers::getInstance()->getPostsProcessorByPostType($post->getPostType())->getFolding(); } else { if ($foldingType) { $hasSubtype = FoldedStorage::isFoldingHasSubtype($foldingType); if ($hasSubtype && !$foldingSubType) { //У фолдинга есть подтип, но в параметрах он не передан - определим фолдинг по контексту $folding = $FCW->getFoldedEntityEnsureType($foldingType)->getFolding(); } else { $folding = FoldedStorageInsts::byTypeStype($foldingType, $foldingSubType); } } else { if ($foldingSubType) { //Если передан только тип, то считаем, что имеется ввиду фолдинг поста $folding = Handlers::getInstance()->getPostsProcessorByPostType($foldingSubType)->getFolding(); } } } if ($folding && !$ident) { //У нас есть фолдинг, но нет идентификатора сущности - определим её из контекста $ident = $FCW->getFoldedEntityEnsureType($folding->getFoldingType())->getIdent(); } if (!$dir && !$name && $ident && $folding) { /* * Не передано название картинки, но передан идентификатор сущности - показываем cover. * TODO - подумать, возможно имеет смысл сделать возможность показывать любую картинку в заданном размере. */ return $folding->getCover($ident, $params->str('dim')); } /* * Берём путь "как есть", если: * 1. Передан специальный параметр asis * 2. Передана dir, и она начинается с '/' * 3. Не передана dir, но при этом name начинается с '/' * 4. dir или name указывают на адрес в интернете */ $asis = $params->bool('asis') || starts_with($dir, DIR_SEPARATOR) || !$dir && starts_with($name, DIR_SEPARATOR) || PsUrl::isHttp($dir) || PsUrl::isHttp($name); if ($asis) { if (!$dir) { return $name; } if (starts_with($name, DIR_SEPARATOR)) { return cut_string_end($dir, DIR_SEPARATOR) . $name; } return ($name ? ensure_ends_with($dir, DIR_SEPARATOR) : $dir) . $name; } /** @var DirManager */ $DM = null; /* * Теперь определим DirManager. Мы его можем взять: */ if ($folding) { //1. Из ресурсов фолдинга $DM = $folding->getResourcesDm($ident, 'src'); } else { //2. Обычный resources->images, если фолдинг не установлен $DM = DirManager::images(); } /* * Определим список показываемых картинок по атрибуту $name. Пример тега: * {postimg type='tr' ident='matrix' name='mao.gif mu.png mu.png'} * Просто разделим значение атрибута $name по точкам и пробелам и склеим в названия картинок. */ $NAMES = preg_split("/[. ]/", $name); $DI = $DM ? $DM->getDirItem($dir, $name) : DirItem::inst($dir, $name); if (count($NAMES) % 2 != 0 || $DI->isImg()) { //Указано что-то непонятное - не чётное кол-во составных элементов return $DI; } $IMAGES = array(); for ($i = 0; $i < count($NAMES); $i += 2) { $imgName = $NAMES[$i] . '.' . $NAMES[$i + 1]; $IMAGES[] = $DM ? $DM->getDirItem($dir, $imgName) : DirItem::inst($dir, $imgName); } return $IMAGES; }
/** * Метод создаёт новый фолдинг */ public function makeNewFolding(ArrayAdapter $adapter) { $ifaces = $adapter->arr('ifaces'); $rtypes = $adapter->arr('rtypes'); $type = lowertrim($adapter->str('FoldingType')); $subtype = lowertrim($adapter->str('FoldingSubType')); $group = $adapter->str('FoldingGroup'); $classPrefix = $adapter->str('FoldingClassPrefix'); check_condition($type, 'Не передан тип фолдинга'); check_condition($group, 'Не передана группа для фолдинга'); check_condition($classPrefix, 'Не передан префикс для классов фолдинга'); //TODO - определять директорию для воздания менеджера фолдингов. die('Folding dir is not deffined.'); $classesDi = DirItem::inst(array('sdk/kit', 'folded'), $group); check_condition(!$classesDi->isDir(), "Директория {$classesDi} уже существует"); check_condition(!$classesDi->isFile(), "Элемент {$classesDi} не может быть файлом"); $rtypes = array_intersect(array_keys(PsUtil::getClassConsts('FoldedResources', 'RTYPE_')), $rtypes); $rtypesArr = trim(implode(', self::', $rtypes)); $rtypesArr = $rtypesArr ? "self::{$rtypesArr}" : ''; $hasPhp = in_array('RTYPE_PHP', $rtypes); $classesDm = DirManager::inst($classesDi->getRelPath())->makePath(); $resourcesPatternDmTo = DirManager::resources(array('folded', $group, FoldedResources::PATTERN_NAME)); check_condition(!$resourcesPatternDmTo->isDir(), "Целевая директория {$resourcesPatternDmTo} существует"); $resourcesPatternDmFrom = DirManager::resources(array('folded', FoldedResources::PATTERN_NAME)); check_condition($resourcesPatternDmFrom->isDir(), "Некорректна директория-источник {$resourcesPatternDmFrom}"); $interfaces = array(); foreach ($this->getFoldedInterfaces($ifaces) as $name => $ifaceClass) { $ctt = $ifaceClass->getClassBody(); if ($ctt) { $interfaces[] = "/****************\n\t * {$name}\n\t ****************/\n" . $ctt; } } $smParams = $adapter->getData(); $smParams['rtypes'] = $rtypesArr; $smParams['funique'] = FoldedResources::unique($type, $subtype); $smParams['BaseClass'] = 'Base' . $classPrefix; $smParams['ManagerClass'] = $classPrefix . 'Manager'; $smParams['ResourcesClass'] = $classPrefix . 'Resources'; $smParams['implements'] = $ifaces ? 'implements ' . implode(', ', $ifaces) . ' ' : ''; $smParams['interfaces'] = $interfaces ? implode("\n\n\t", $interfaces) : ''; try { //КЛАССЫ //Resources $tpl = PSSmarty::template(DirItem::inst(array(__DIR__, 'tpls'), 'resources.tpl'), $smParams); $di = $classesDm->getDirItem(null, $smParams['ResourcesClass'], 'php'); $di->writeToFile(trim($tpl->fetch()), true); //Manager $tpl = PSSmarty::template(DirItem::inst(array(__DIR__, 'tpls'), 'manager.tpl'), $smParams); $di = $classesDm->getDirItem(null, $smParams['ManagerClass'], 'php'); $di->writeToFile(trim($tpl->fetch()), true); if ($hasPhp) { //BaseClass $tpl = PSSmarty::template(DirItem::inst(array(__DIR__, 'tpls'), 'baseclass.tpl'), $smParams); $di = $classesDm->getDirItem(null, $smParams['BaseClass'], 'php'); $di->writeToFile(trim($tpl->fetch()), true); } //ШАБЛОН ДЛЯ СУЩНОСТЕЙ $resourcesPatternDmTo->makePath(); foreach ($rtypes as $rtype) { $ext = FoldedResources::resourceTypeToExt(PsUtil::newReflectionClass('FoldedResources')->getConstant($rtype)); $diTo = $resourcesPatternDmTo->getDirItem(null, FoldedResources::PATTERN_NAME, $ext); $diFrom = $resourcesPatternDmFrom->getDirItem(null, FoldedResources::PATTERN_NAME, $ext); if ($ext == PsConst::EXT_PHP) { $diTo->writeToFile(str_replace('eclassnamebase', $smParams['BaseClass'], $diFrom->getFileContents())); continue; } $diFrom->copyTo($diTo); } } catch (Exception $ex) { $classesDm->clearDir(null, true); $resourcesPatternDmTo->clearDir(null, true); throw $ex; } }
protected function onBeforeSave(DirItem $source, $userId, ArrayAdapter $params) { $source->assertIsImg(); }
public final function copyDirContent2Dir($dirFrom, $dirToAbsPath, $includeDir = true, $filterName = null) { $fromDirRelPath = $this->relDirPath($dirFrom); $includeDirName = basename($fromDirRelPath); check_condition($includeDirName, "Trying to copy root directory"); $destDirAbsPath = $dirToAbsPath instanceof DirItem ? $dirToAbsPath->getAbsPath() : DirItem::inst($dirToAbsPath)->getAbsPath(); //$includeDir = $includeDir && $fromDirRelPath && ($fromDirRelPath != DIR_SEPARATOR); $content = $this->getDirContentFull($dirFrom, $filterName); if (empty($content)) { //Папка пуста. Если $includeDir=true, то просто создадим её if ($includeDir && $this->isDir($dirFrom)) { $destAbsPath = next_level_dir($destDirAbsPath, $includeDirName); DirItem::inst($destAbsPath)->makePath(); } return; //--- } /* @var $src DirItem */ foreach ($content as $src) { $relPathNewDirFromOldDir = cut_string_start($src->getRelPath(), $fromDirRelPath); $destAbsPath = next_level_dir($destDirAbsPath, $includeDir ? $includeDirName : null, $relPathNewDirFromOldDir); $destDi = DirItem::inst($destAbsPath)->makePath(); if ($src->isFile()) { $src->copyTo($destDi); } } }
public static function arr($num, $process_sections = true) { return parse_ini_file(DirItem::inst(__DIR__, 'ini' . $num, 'ini')->getAbsPath(), $process_sections); }
private function uploadFileImpl(DirItem $source, FILEAdapter $file = null, $userId = null, array $params = array()) { $userId = $this->checkUserId($userId); $this->LOGGER->info("Processing file upload for user [{$userId}], source {$source}."); $aa = ArrayAdapter::inst($params); $uploaded = $file ? $source : null; $originalName = $file ? $file->getOriginalName() : $source->getName(); $dbMsg = null; try { $this->LOGGER->info('Calling onBeforeSave...'); $dbMsg = $this->onBeforeSave($source, $userId, $aa); $this->LOGGER->info("\tDone!"); } catch (Exception $ex) { $this->LOGGER->info('Error occurred in onBeforeSave method: ' . $ex->getMessage()); $this->LOGGER->info('Source file will be deleted ? {}.', var_export(!!$uploaded, true)); if ($uploaded) { $uploaded->remove(); } throw $ex; } if ($uploaded) { //Это уже и так загруженный файл $this->LOGGER->info('Source file is uploaded file'); } else { $this->LOGGER->info('Move source file to uploads dir'); $uploaded = $this->makeTmpDirItem(); $source->copyTo($uploaded); } if ($this->LOGGER->isEnabled()) { $this->LOGGER->info("\tUploaded file: {$uploaded}"); $this->LOGGER->info("\tOriginal name: [{$originalName}]"); $this->LOGGER->info("\tMime: [{$uploaded->getMime()}]"); $this->LOGGER->info("\tParams: " . array_to_string($params, false)); } $uploadId = null; if ($this->isStoreToDb()) { $this->LOGGER->info("Saving upload file into database. DbMsg: '{$dbMsg}'."); try { $uploadId = UploadsBean::inst()->saveFileUpload($this->DBTYPE, $uploaded->getAbsPath(), $originalName, $uploaded->getMime(), $userId, $dbMsg); //Почистим кеш, вдруг мы запрашивали информацию по данному файлу $this->CACHE->remove($uploadId); $this->LOGGER->info("\tFile successfully saved, uploadId = {$uploadId}."); } catch (Exception $ex) { $this->LOGGER->info('Error occured while saving file to DB: ' . $ex->getMessage()); $this->LOGGER->info('Deleting upload file...'); $uploaded->remove(); $uploaded = null; throw $ex; } $uploaded->setData('id', $uploadId); } try { $this->LOGGER->info('Calling onAfterSave...'); $this->onAfterSave($uploaded, $userId, $aa); $this->LOGGER->info("\tDone!"); } catch (Exception $ex) { $this->LOGGER->info('Error occured in onAfterSave method: ' . $ex->getMessage()); if (is_inumeric($uploadId)) { $this->LOGGER->info('Deleting db record...'); UploadsBean::inst()->clearFileUpload($uploadId); $uploadId = null; } $this->LOGGER->info('Deleting upload file...'); $uploaded->remove(); $uploaded = null; throw $ex; } /* * Если класс работает автономно и не работает с базой, то файл нужно удалить. */ if ($this->isAutonomous() && !$this->isStoreToDb()) { $this->LOGGER->info('Class is auto clean, deleting uploaded file...'); $uploaded->remove(); $uploaded = null; } $this->LOGGER->info(''); return $uploaded; }
public function addFileImg(DirItem $img) { AuthManager::checkAdminAccess(); //todo - НЕБЕЗОПАСНО! Разобраться с преобразованием картинок. Они портятся при перегонке формата $img->copyTo($this->DM->absFilePath(null, $img->getNameNoExt() . '_' . getRandomString(3), array_get_value(1, explode('/', $img->getMime())))); //SimpleImage::inst()->load($img)->save($this->DM->getDirItem(null, $img->getNameNoExt()), 'png')->close(); }
continue; } $rebus = $MR->normalize($rebus); switch ($MR->rebusState($rebus)) { case PsMathRebus::STATE_HAS_ANSWERS: dolog("Take rebus answers: {$rebus}"); $result[$rebus] = $MR->rebusAnswers($rebus); break; case PsMathRebus::STATE_NO_ANSWERS: dolog("Scipping rebus: {$rebus}"); $result[$rebus] = array(); break; case PsMathRebus::STATE_NOT_REGISTERED: dolog("Processing rebus: {$rebus}"); $result[$rebus] = PsMathRebusSolver::solve($rebus); break; } } $ansDI = DirItem::inst(__DIR__, 'answers.txt'); $ansDI->remove(); foreach ($result as $rebus => $answers) { $ansDI->writeLineToFile($rebus); foreach ($answers as $answer) { $ansDI->writeLineToFile($answer); } $ansDI->writeLineToFile(); } if (getCmdParam(1) == 1) { dolog('Copy from [' . $ansDI->getRelPath() . '] to [' . $MR->getAnswersDI()->getRelPath() . ']'); $ansDI->copyTo($MR->getAnswersDI()->getAbsPath()); }
/** * Парсит файл профайлинга и возвращает массив вида: * ident=>Secundomer * Идентификатор здесь, это идентификатор профилируемой сущности, например - текст запроса. */ private function parseProfiler(DirItem $file) { $result = array(); $lines = $file->getFileLines(false); if (empty($lines)) { return $result; //--- } foreach ($lines as $line) { $tokens = explode('|', $line); if (count($tokens) != 3) { continue; } $ident = trim($tokens[0]); $count = trim($tokens[1]); $time = trim($tokens[2]); if (!$ident || !is_numeric($count) || !is_numeric($time)) { continue; } if (!array_key_exists($ident, $result)) { $result[$ident] = Secundomer::inst(); } $result[$ident]->add($count, $time); } return $result; }
/** * Метод получает на вход url ресурса и пытается его обфусцировать, если это возможно. * * @return: путь к ресурсу, который должнет быть подключен, или null, если ресурс подключать не нужно */ private function tryReplaceResource($url) { if (!starts_with($url, DIR_SEPARATOR)) { //Это внешний ресурс: http:// и т.д. - подключаем. return $url; } $di = DirItem::inst($url); if (!$di->isFile() || $di->getSize() <= 0) { return null; } if (!PsDefines::isProduction()) { //Не будем пытаться обфусцировать в девелопменте //return $url; } if (!ends_with($url, '.js')) { //Мы не можем обфусцировать .css файлы, так как они используют относительные пути к ресурсам. return $url; } return $url; $url = $di->getRelPath(); if (!starts_with($url, $this->OBFUSCATABLE)) { //Не стоит обфусцировать не наши .js файлы, так как они могут внутри использовать ссылки на рядом лежащие ресурсы return $url; } $type = 'js'; $obfuscatedDi = DirManager::autogen("resources/{$type}")->getDirItem(null, md5($url), $type); $mtyme = $obfuscatedDi->getModificationTime(); if (!$mtyme || $mtyme < $di->getModificationTime()) { $obfuscatedDi->writeToFile(StringUtils::normalizeResourceFile($type, $di->getFileContents()), true); } return $obfuscatedDi->getRelPath(); }
function smarty_function_linkup_js($params, Smarty_Internal_Template &$smarty) { $di = DirItem::inst(array_get_value('dir', $params), array_get_value('name', $params), PsConst::EXT_JS); echo $di->isFile() ? PsHtml::linkJs($di) : ''; }
protected function onBeforeSave(DirItem $source, $userId, ArrayAdapter $params) { $source->assertIsImg(); check_condition($this->getUploadedFilesCount($userId) < 2, 'Больше нельзя загружать аватары'); }
/** @return DirItem */ public function moveUploadedFileTo(DirItem $di) { $this->assertIsValid(); check_condition(move_uploaded_file($this->getTmpFilePath(), $di->getAbsPath()), 'Не удаётся переместить временный файл'); return $di; }