function rub_list($dir, $start = 0, $count = 0, $exts = array()) { $files = Cache::exec(array($dir), 'rub_list', function ($dir, $start, $count, $exts) { $dir = Path::theme($dir); return _rub_list($dir, $start, $count, $exts); }, array($dir, $start, $count, $exts), isset($_GET['re'])); return $files; }
/** * Кэширумеая функция, основной разбор. */ public static function parse($src) { $args = array($src); $param = Cache::exec(array($src), 'docx_parse', function ($src, $re) { $conf = Docx::$conf; $imgmaxwidth = $conf['imgmaxwidth']; $previewlen = $conf['previewlen']; $cachename = Path::tofs(Path::encode($src)); $cacheFolder = Path::mkdir(Docx::$conf['cache'] . $cachename . '/'); //В винде ингда вылетает о шибка что нет прав удалить какой-то файл в папке и как следствие саму папку //Обновление страницы проходит уже нормально //Полагаю в линукс такой ошибки не будет хз почему возникает Cache::fullrmdir($cacheFolder); $path = Path::theme($src); if (!$path) { return array('html' => false); } $xmls = docx_getTextFromZippedXML($path, 'word/document.xml', $cacheFolder, $re); $rIds = array(); $param = array('folder' => $cacheFolder, 'imgmaxwidth' => $imgmaxwidth, 'previewlen' => $previewlen, 'rIds' => $rIds); if ($xmls[0]) { $xmlar = docx_dom_to_array($xmls[0]); $xmlar2 = docx_dom_to_array($xmls[1]); foreach ($xmlar2['Relationships']['Relationship'] as $v) { $rIds[$v['Id']] = $v['Target']; } $param['rIds'] = $rIds; $html = docx_each($xmlar, '\\infrajs\\doc\\docx_analyse', $param); } else { $param['rIds'] = array(); $html = ''; } $param['html'] = $html; return $param; }, $args, isset($_GET['re'])); unset($param['rIds']); unset($param['type']); unset($param['imgmaxwidth']); unset($param['previewlen']); unset($param['isli']); unset($param['isul']); unset($param['imgnum']); unset($param['folder']); return $param; }
public static function parse($src) { $src = Path::theme($src); if (!$src) { return; } $args = array($src); return Cache::exec(array($src), 'mhtparse', function ($src) { $conf = Docx::$conf; $imgmaxwidth = $conf['imgmaxwidth']; $previewlen = $conf['previewlen']; $filename = Path::theme($src); $fdata = Load::srcInfo($src); if ($fdata['ext'] == 'php') { $data = Load::loadTEXT($filename); } else { $data = file_get_contents($filename); } $ans = array(); if ($fdata['ext'] == 'mht') { $p = explode('/', $filename); $fname = array_pop($p); $fnameext = $fname; //$fname=basename($filename); preg_match("/^(\\d*)/", $fname, $match); $date = $match[0]; $fname = Path::toutf(preg_replace('/^\\d*\\s+/', '', $fname)); $fname = preg_replace('/\\.\\w{0,4}$/', '', $fname); $ar = preg_split('/------=_NextPart_.*/', $data); if (sizeof($ar) > 1) { //На первом месте идёт информация о ворде... unset($ar[0]); unset($ar[sizeof($ar) - 1]); } $ar = array_values($ar); $folder = Path::mkdir(Docx::$conf['cache'] . md5($src) . '/'); $html = ''; for ($i = 0, $l = sizeof($ar); $i < $l; ++$i) { if (!$ar[$i]) { continue; } $d = preg_split("/\n/", $ar[$i], 6); $j = -1; do { ++$j; } while (@$d[$j][0] !== 'C' && $j <= 5); if ($j >= 5) { /* не нашли Content-Location: file:///C:/0FCF1655/file9909.files/header.htm Content-Transfer-Encoding: quoted-printable Content-Type: text/html; charset="us-ascii" */ continue; } $location = preg_replace('/Content-Location: /', '', $d[$j]); $location = trim($location); $encoding = preg_replace('/Content-Transfer-Encoding: /', '', $d[$j + 1]); $type = preg_replace('/Content-Type: /', '', $d[$j + 2]); $content = $d[5]; $name = basename($location); if (preg_match("/text\\/html/", $type) || preg_match('/Subject:/', $type)) { $html .= $content; } else { @file_put_contents($folder . $name, base64_decode($content)); //Сохраняем картинку или тп... } } if (!$html) { $html = ''; } $html = preg_replace("/=\r\n/", '', $html); $html = preg_replace("/\\s+/", ' ', $html); $html = preg_replace("/^.*<body .*>\\s*/U", '', $html, 1); $html = preg_replace("/\\s*<\\/body>.*/", '', $html, 1); $images = array(); preg_match_all('/src=3D".*\\.files\\/(image.+)"/U', $html, $match, PREG_PATTERN_ORDER); for ($i = 0, $l = sizeof($match[1]); $i < $l; $i = $i + 2) { $min = $match[1][$i + 1]; if (!$min) { $min = $match[1][$i]; } $images[$min] = $match[1][$i]; //Каждая следующая картинка есть уменьшенная копия предыдущей оригинального размера } $html = preg_replace("/<\\!--.*-->/U", '', $html); $html = preg_replace("/<!\\[if !vml\\]>/", '', $html); $html = preg_replace("/<!\\[endif\\]>/", '', $html); $html = preg_replace('/=3D/', '=', $html); $html = preg_replace('/align="right"/', 'align="right" class="right"', $html); $html = preg_replace('/align="left"/', 'align="left" class="left"', $html); $html = preg_replace('/align=right/', 'align="right" class="right"', $html); $html = preg_replace('/align=left/', 'align="left" class="left"', $html); $html = Path::toutf($html); //Виндовые файлы хранятся в cp1251 $folder = Path::toutf($folder); $html = preg_replace('/ src=".*\\/(.*)"/U', ' src="' . $folder . '${1}"', $html); $html = preg_replace('/<span class=SpellE>(.*)<\\/span>/U', '${1}', $html); $html = preg_replace('/<span lang=.*>(.*)<\\/span>/U', '${1}', $html); $html = preg_replace('/<span class=GramE>(.*)<\\/span>/U', '${1}', $html); $html = preg_replace("/<span style='mso.*>(.*)<\\/span>/U", '${1}', $html); $html = preg_replace("/<span style='mso.*>(.*)<\\/span>/U", '${1}', $html); $html = preg_replace("/<span style='mso.*>(.*)<\\/span>/U", '${1}', $html); $html = preg_replace("/<span style='mso.*>(.*)<\\/span>/U", '${1}', $html); $html = preg_replace('/ class=MsoNormal/U', '', $html); $html = preg_replace('/<a name="_.*>(.*)<\\/a>/U', '${1}', $html); //Приводим к единому виду маркерные списки $patern = '/<p class=MsoListParagraphCxSp(\\w+) .*>(.*)<\\/p>/U'; $count = 3; do { preg_match($patern, $html, $match); if (sizeof($match) == $count) { $pos = strtolower($match[1]); $text = $match[2]; $text = preg_replace('/^.*(<\\/span>)+/U', '', $text, 1); $text = '<li>' . $text . '</li>'; if ($pos == 'first') { $text = '<ul>' . $text; } if ($pos == 'last') { $text = $text . '</ul>'; } $html = preg_replace($patern, $text, $html, 1); } else { break; } } while (sizeof($match) == $count); $title = $fname; $patern = '/<img(.*)>/U'; $count = 2; do { preg_match($patern, $html, $match); if (sizeof($match) == $count) { $sfind = $match[1]; //$sfind='<img src="/image.asdf">'; preg_match("/width=(\\d*)/", $sfind, $match2); $w = trim($match2[1]); preg_match("/height=(\\d*)/", $sfind, $match2); $h = trim($match2[1]); if (!$w || $w > $imgmaxwidth) { $w = $imgmaxwidth; } preg_match('/src="(.*\\/)(image.*)"/U', $sfind, $match2); $path = trim($match2[1]); $small = $match2[2]; preg_match('/alt="(.*)".*/U', $sfind, $match2); $alt = trim(@$match2[1]); $alt = html_entity_decode($alt, ENT_QUOTES, 'utf-8'); preg_match('/align="(.*)".*/U', $sfind, $match2); $align = trim($match2[1]); $align = html_entity_decode($align, ENT_QUOTES, 'utf-8'); $big = $images[$small]; if (!$big) { $big = $small; } $isbig = preg_match('/#/', $alt); if ($isbig) { $alt = preg_replace('/#/', '', $alt); } //$i="<IMG title='$alt' src='/-imager/?w=$w&h=$h&src=".($path.$big)."' align='$align' class='$align' alt='$alt'>"; $i = "<IMG src='/-imager/?w={$w}&h={$h}&src=" . ($path . $big) . "' align='{$align}' class='{$align}'>"; //urlencode решает проблему с ie7 когда иллюстрации с адресом содержащим пробел не показываются if ($isbig) { $i = "<a target='about:blank' href='/-imager/?src=" . urlencode($path . $big) . "'>{$i}</a>"; } //$i.='<textarea style="width:500px; height:300px">'.$i.'</textarea>'; $html = preg_replace($patern, $i, $html, 1); } else { break; } } while (sizeof($match) == $count); $patern = "/###\\{(.*)\\}###/U"; //js код do { preg_match($patern, $html, $match); if (sizeof($match) > 0) { $param = $match[1]; $param = strip_tags($param); $param = html_entity_decode($param, ENT_QUOTES, 'utf-8'); $param = preg_replace('/(‘|’)/', "'", $param); $param = preg_replace('/(“|«|»|”)/', '"', $param); $html = preg_replace($patern, $param, $html, 1); } else { break; } } while (sizeof($match) > 1); $patern = "/####.*<table.*>(.*)<\\/table>.*####/U"; do { preg_match($patern, $html, $match); if (sizeof($match) > 0) { $param = $match[1]; $param = preg_replace('/style=".*"/U', '', $param); $param = preg_replace("/style='.*'/U", '', $param); $html = preg_replace($patern, '<table class="table table-striped">' . $param . '</table>', $html, 1); } else { break; } } while (sizeof($match) > 1); $ans['images'] = array(); foreach ($images as $img) { $ans['images'][] = array('src' => $folder . $img); } } else { $html = $data; $images = array(); preg_match_all('/<img.*src="(.*)".*>/U', $html, $match, PREG_PATTERN_ORDER); for ($i = 0, $l = sizeof($match[1]); $i < $l; $i++) { $images[] = array('src' => $match[1][$i]); //Каждая следующая картинка есть уменьшенная копия предыдущей оригинального размера } $ans['images'] = $images; } $r = preg_match('/<h.*>(.*)<\\/h.>/U', $html, $match); if ($r) { $heading = strip_tags($match[1]); } else { $heading = false; } $ans['heading'] = $heading; preg_match_all('/<a.*href="(.*)".*>(.*)<\\/a>/U', $html, $match); $links = array(); foreach ($match[1] as $k => $v) { $title = strip_tags($match[2][$k]); if (!$title) { continue; } $links[] = array('title' => $title, 'href' => $match[1][$k]); } $ans['links'] = $links; $html = trim($html); $html = html_entity_decode($html, ENT_COMPAT, 'UTF-8'); $html = preg_replace('/ /U', '', $html); //bugfix списки в mht порождаются адский символ. в eval-е скрипта недопустим. $ans['html'] = $html; foreach ($ans['images'] as &$item) { $item['src'] = preg_replace('/^\\//', '', $item['src']); } return $ans; }, $args); }
<?php use infrajs\ans\Ans; use infrajs\router\Router; use infrajs\cache\Cache; if (!is_file('vendor/autoload.php')) { chdir('../'); require_once 'vendor/autoload.php'; Router::init(); } $ans = array(); $day = date('j m Y H'); //Кэш на один час $data = Cache::exec(array(), __FILE__, function () { $src = "http://www.cbr.ru/scripts/XML_daily.asp"; $cbr = simplexml_load_file($src); $attr = $cbr->attributes(); $t = strtotime($attr['Date'][0]); $data = array(); $data['date'] = $t; $data['list'] = array(); for ($i = 0, $l = sizeof($cbr->Valute); $i < $l; $i++) { $v = $cbr->Valute[$i][0]; $data["list"][(string) $v->CharCode] = array("char" => (string) $v->CharCode, "title" => (string) $v->Name, "value" => (string) $v->Value); } return $data; }, array($day), isset($_GET['re'])); $ans['data'] = $data; return Ans::ret($ans);
public static function article($src) { return Cache::exec(array($src), __FILE__, function ($src) { $html = Load::loadTEXT('-doc/get.php?src=' . $src); $info = Load::srcInfo($src); if (!in_array($info['ext'], array('html', 'tpl', 'php'))) { $soft = true; } else { $soft = false; } return Rubrics::parse($html, $soft); }, array($src), isset($_GET['re'])); }
function &xls_parseAll($path) { $data = Cache::exec(array($path), 'xls_parseAll', function &($path) { $file = Path::theme($path); $data = array(); if (!$file) { return $data; } $in = Load::srcInfo($path); if ($in['ext'] == 'xls') { require_once __DIR__ . '/excel_parser/oleread.php'; require_once __DIR__ . '/excel_parser/reader.php'; if (!$file) { return $data; } $d = new \Spreadsheet_Excel_Reader(); $d->setOutputEncoding('utf-8'); $d->read($file); Each::forr($d->boundsheets, function &($v, $k) use(&$d, &$data) { $data[$v['name']] =& $d->sheets[$k]['cells']; $r = null; return $r; }); } elseif ($in['ext'] == 'csv') { $handle = fopen('php://memory', 'w+'); fwrite($handle, Path::toutf(file_get_contents($file))); rewind($handle); $data = array(); //Массив будет хранить данные из csv while (($line = fgetcsv($handle, 0, ";")) !== false) { //Проходим весь csv-файл, и читаем построчно. 3-ий параметр разделитель поля $data[] = $line; //Записываем строчки в массив } fclose($handle); foreach ($data as $k => $v) { foreach ($data[$k] as $kk => $vv) { $vv = trim($vv); if ($vv === '') { unset($data[$k][$kk]); } else { $data[$k][$kk] = $vv; } } if (!$data[$k]) { unset($data[$k]); } } $data = array('list' => $data); } elseif ($in['ext'] == 'xlsx') { $cacheFolder = Path::resolve(Xlsx::$conf['cache']); //$cacheFolder .= Path::encode($path).'/';//кэш $cacheFolder .= md5($path) . '/'; //кэш Cache::fullrmdir($cacheFolder, true); //удалить старый кэш $r = mkdir($cacheFolder); if (!$r) { echo '<pre>'; throw new \Exception('Не удалось создать папку для кэша ' . $cacheFolder); } //разархивировать $zip = new \ZipArchive(); $pathfs = Path::theme($path); if ((int) phpversion() > 6) { $zipcacheFolder = Path::tofs($cacheFolder); $zippathfs = Path::toutf($pathfs); } else { $zipcacheFolder = Path::tofs($cacheFolder); //Без кирилицы $zippathfs = Path::tofs($pathfs); } $r = $zip->open($zippathfs); if ($r === true) { $zip->extractTo($zipcacheFolder); $zip->close(); $contents = simplexml_load_file($cacheFolder . 'xl/sharedStrings.xml'); $contents = $contents->si; $workbook = simplexml_load_file($cacheFolder . 'xl/workbook.xml'); $sheets = $workbook->sheets->sheet; $handle = opendir($cacheFolder . 'xl/worksheets/'); $i = 0; $syms = array(); while ($file = readdir($handle)) { if ($file[0] == '.') { continue; } $src = $cacheFolder . 'xl/worksheets/' . $file; if (!is_file($src)) { continue; } $files[] = $file; } closedir($handle); natsort($files); foreach ($files as $file) { $src = $cacheFolder . 'xl/worksheets/' . $file; $list = $sheets[$i]; ++$i; $list = $list->attributes(); $list = (string) $list['name']; $data[$list] = array(); $sheet = simplexml_load_file($cacheFolder . 'xl/worksheets/' . $file); $rows = $sheet->sheetData->row; foreach ($rows as $row) { $attr = $row->attributes(); $r = (string) $attr['r']; $data[$list][$r] = array(); $cells = $row->c; foreach ($cells as $cell) { if (!$cell->v) { continue; } $attr = $cell->attributes(); if ($attr['t'] == 's') { $place = (int) $cell->v; if (isset($contents[$place]->r)) { $value = ''; foreach ($contents[$place]->r as $con) { $value .= $con->t; } } else { $value = $contents[$place]->t; } } else { $value = $cell->v; $value = (double) $value; } $attr = $cell->attributes(); $c = (string) $attr['r']; //FA232 preg_match("/\\D+/", $c, $c); $c = $c[0]; $syms[$c] = true; $data[$list][$r][$c] = (string) $value; } } } $syms = array_keys($syms); natsort($syms); /*usort($syms,function($a,$b){ $la=strlen($a); $lb=strlen($b); if($la>$lb)return 1; if($la<$lb)return -1; if($a>$b)return 1; if($a<$b)return -1; return 0; });*/ $symbols = array(); foreach ($syms as $i => $s) { $symbols[$s] = $i + 1; } foreach ($data as $list => $listdata) { foreach ($listdata as $row => $rowdata) { $data[$list][$row] = array(); foreach ($rowdata as $cell => $celldata) { $data[$list][$row][$symbols[$cell]] = $celldata; } if (!$data[$list][$row]) { unset($data[$list][$row]); } //Пустые строки нам не нужны } } } // Если что-то пошло не так, возвращаем пустую строку //return ""; //собрать данные } return $data; }, array($path)); return $data; }
public static function checkFS() { $search = Cache::exec(array('composer.lock'), __FILE__ . 'init', function () { $search = array(); $ex = array_merge(array(Path::$conf['cache'], Path::$conf['data']), Path::$conf['search']); Search::scan('', function ($src, $level) use(&$search, $ex) { if (in_array($src, $ex)) { return true; } //вглубь не идём if ($level < 2) { return; } if ($level > 5) { return true; } if (!is_file($src . '.infra.json')) { return; } $r = explode('/', $src); array_pop($r); array_pop($r); $search[] = implode('/', $r) . '/'; return false; //вглубь не идём и в соседние папки тоже }); return $search; }); Path::$conf['search'] = array_values(array_unique(array_merge(Path::$conf['search'], $search))); if (Config::$all) { //Если все конфиги были уже обраны, нужно заного пробежаться по найденным for ($i = 0; $i < sizeof($search); $i++) { $tsrc = $search[$i]; if (!is_dir($tsrc)) { continue; } $files = scandir($tsrc); foreach ($files as $file) { if ($file[0] == '.') { continue; } if (!is_dir($tsrc . $file)) { continue; } Config::load($tsrc . $file . '/.infra.json', $file); } } } /*$comp = Load::loadJSON('composer.json'); if ($comp && !empty($comp['require'])) { foreach ($comp['require'] as $n => $v) { $r = explode('/', $n); if (sizeof($r) != 2) continue; $path = 'vendor/'.$r[0].'/'; if (!in_array($path, Path::$conf['search'])){ Path::$conf['search'][] = $path; } } }*/ }
<?php namespace infrajs\contacts; use infrajs\router\Router; use infrajs\ans\Ans; use infrajs\config\Config; use infrajs\cache\Cache; if (!is_file('vendor/autoload.php')) { chdir('../../../'); //Согласно фактическому расположению файла require_once 'vendor/autoload.php'; Router::init(); } $conf = Config::get('contacts'); if ($conf['reCAPTCHA']) { $date = date('d.m.Y'); $js = Cache::exec(array(), __FILE__, function ($date) { return file_get_contents('https://www.google.com/recaptcha/api.js?onload=grecaptchaOnload&render=explicit&hl=ru'); }, array($date)); $js .= 'window.grecaptchaOnload=function(){ Event.fire("reCAPTCHA") };'; } else { $js = '/* reCAPTCHA отключена */'; } return Ans::js($js);
public static function cache($name, $call, $args = array(), $re = null) { if (is_null($re)) { $re = isset($_GET['re']); } $conf = Catalog::$conf; return Cache::exec($conf['cache'], 'cat-' . $name, $call, $args, $re); }