/** * */ public static function normalizeJsFile($content) { $content = self::removeMultiLineComments($content); $fileLines = explode("\n", $content); $taken = array(); $scipSwap = array('//', '--'); $swap = array('{', '}', '}}', '{{', '},', '};', '});', 'else', '}else{', '}else', 'else{', '})', 'return;', 'return{'); $swap_start_end = array('?', ':', '.', '+', '||', '&&', ',', ';'); $swap_end = array('{', '('); $swap_start = array('}'); $swap_end = array_merge($swap_end, $swap_start_end); $swap_start = array_merge($swap_start, $swap_start_end); foreach ($fileLines as $line) { $line = trim($line); //Обрежем строчный комментарий //Нужно быть осторожным - двойной слеш может использоваться (в RegExt например) if ($line && contains_substring($line, '//')) { $line = trim(substr($line, 0, strpos($line, '//'))); } if (!$line) { continue; } $tmp = normalize_string($line, true); $prevTmp = count($taken) > 0 ? normalize_string($taken[count($taken) - 1], true) : null; if ($prevTmp !== null && !contains_substring($prevTmp, $scipSwap) && (in_array($tmp, $swap) || ends_with($prevTmp, $swap_end) || starts_with($tmp, $swap_start))) { $taken[count($taken) - 1] .= ' ' . $line; } else { $taken[] = $line; } } return trim(implode("\n", $taken)); }
private function getPathForceIncluded($path) { $res = array(); foreach ($this->INCLUDED as $incpath) { if (contains_substring($incpath, $path)) { $res[] = $incpath; } } return $res; }
/** @return PsTable */ private function load() { if (!is_array($this->columns)) { $this->columns = AdminDbBean::inst()->getColumns($this->getName()); $this->columnsConfigurable = $this->columns; $this->pk = null; $this->title = null; $this->pkEqualents = array(); $this->take4exportColumns = array(); $titleCodeWords = array('name', 'title'); /* @var $col PsTableColumn */ foreach ($this->columns as $col) { if ($col->isPk()) { $this->pk = $col; /* * Если первичный ключ является автоинкрементальным полем - * исключим его из конфигурируемых колонок. */ if ($col->isAi()) { unset($this->columnsConfigurable[$col->getName()]); } } if (!$col->isPk() && $col->isPkEquivalent()) { $this->pkEqualents[$col->getName()] = $col; } if (!$this->title) { if (contains_substring($col->getName(), $titleCodeWords)) { $this->title = $col; } } if ($col->isTake4Export()) { $this->take4exportColumns[$col->getName()] = $col; } if ($col->isCanBeManuallyRestricted()) { $this->canBeManuallyRestrictedColumns[$col->getName()] = $col; } } //Если не определили titleColumn, то возмём первичный ключ $this->title = $this->title ? $this->title : $this->pk; } return $this; }
/** * "Нормализует" путь к директории * [a///b\\c\\\\d/e/f] -> [a/b/c/d/e/f] */ function normalize_path($path, $separator = DIR_SEPARATOR) { $path = str_replace('\\', $separator, $path); $path = str_replace('/', $separator, $path); $double = $separator . $separator; while (contains_substring($path, $double)) { $path = str_replace($double, $separator, $path); } return trim($path); }
/** * Импортирует фолдинг из zip-архива * * @param DirItem $zip - пут к архиву * @param type $clear - очищать ли директорию перед загрузкой архива * @return FoldedEntity */ public function imporFromZip(DirItem $zip, $clear = false) { $zip = $zip->loadZip(); $comment = $zip->getArchiveComment(); $comment = explode(';', $comment); check_condition(count($comment) === 2, 'Bad zip archive sign'); $name = explode('-', $comment[0]); $sign = $comment[1]; check_condition(count($name) === 3, 'Bad zip name'); $ftype = $name[0]; $fsubtype = $name[1]; $ident = $name[2]; $this->assertAdminCanDo(__FUNCTION__, $ident); /* * Сейчас мы загружаем zip-архивы из формы, в которой содержатся тип и подтип фолдинга, * так что будем ругаться, если нам передадут не наш архив. * В противном случае можно будет просто проверить $this->isIt($ftype, $fsubtype) */ check_condition($this->isIt($ftype, $fsubtype), "Folding [{$ftype}]/[{$fsubtype}] cannot extract this zip"); $secret = $this->ZIP_SECRET; $validSign = md5("{$ftype}-{$fsubtype}-{$ident}-{$secret}"); check_condition($sign === $validSign, 'Folding archive sign is invalid'); //Проверим, будет ли архив развёрнут в надлежащую директорию $dm = $this->getResourcesDm($ident); if ($clear) { $dm->clearDir(); } $exportToDirs[] = $dm->getDirItem()->getRelPathNoDs(); $exportToDirs[] = DirManager::formules()->getDirItem()->getRelPathNoDs(); for ($i = 0; $i < $zip->numFiles; $i++) { $path = $zip->getNameIndex($i); $valid = contains_substring($path, $exportToDirs); check_condition($valid, "Cant export folded to dir: [{$path}]"); } //Разворачиваем $zip->extractTo(PATH_BASE_DIR); $zip->close(); //Очистка старых коверов $this->clearGenerated($ident); //Оповестим об изменении сущности $this->onEntityChanged($ident); return $this->getFoldedEntity($ident); }
/** * Сохраняет значение для вставки его в запрос */ public function safe4insert($val) { if ($this->isFk()) { if (is_string($val) && contains_substring($val, 'select')) { return ensure_ends_with(ensure_starts_with($val, '('), ')'); } return is_numeric($val) ? 1 * $val : null; } switch ($this->getType()) { case self::TYPE_BIT: case self::TYPE_INT: case self::TYPE_INT_DATE: return is_numeric($val) ? 1 * $val : 'null'; case self::TYPE_CHAR: case self::TYPE_STRING: case self::TYPE_STRING_DATE: case self::TYPE_TEXT: //MySQL различает пустую строку и null. Если столбец nullable и значение пустое - вставим null //Обязательно нужно выполнить mysql_real_escape_string, чтобы безопасно вставить значение return $this->isNullable() && !$val ? 'null' : "'" . mysql_real_escape_string($val) . "'"; } }
public function localize($date, $format = null) { if (!$format || contains_substring($format, 'F') || contains_substring($format, 'M')) { for ($index = 1; $index <= 12; $index++) { $decodes = $this->monthDecodes($index); $shortEng = $decodes[0]; if (contains_substring($date, $shortEng)) { $shortRus = $decodes[1]; $longEng = $decodes[2]; $longRus = $decodes[3]; $date = str_replace($longEng, $longRus, $date); $date = str_replace($shortEng, $shortRus, $date); return $date; } } } return $date; }
public function hasExtension() { return contains_substring($this->name, '.'); }
/** * Возвращает полный список ссылок на эелемнты навигации, которые не содержат якоря # */ public function getRealHrefs() { $result = array(); if ($this->href && !contains_substring($this->href, '#')) { $result[] = $this->href; } /* @var $child NavigationItem */ foreach ($this->childsList as $child) { $result = array_merge($result, $child->getRealHrefs()); } return array_unique($result); }
private function isRuChar($char) { return contains_substring($this->RU, $char); }
/** * Метод к URL добавляет параметры и якорь * * @param str $base - базовый URL * @param array|str $params - строка параметров * @param str $sub - якорь * @return str */ public static function addParams($base, $params, $sub = null) { $base = trim($base); $params = self::getParamsToString($params); $delimiter = $base && $params ? contains_substring($base, '?') ? ends_with($base, '?') ? '' : '&' : '?' : ''; $sub = $sub ? ensure_starts_with($sub, '#') : ''; return $base . $delimiter . $params . $sub; }