Example #1
0
 public function load($src)
 {
     $item = Load::loadJSON($src);
     if (!$item) {
         $item = array();
     }
     if (!empty($item['external'])) {
         if (!is_array($item['external'])) {
             $item['external'] = explode(', ', $item['external']);
         }
         foreach ($item['external'] as $esrc) {
             if (!Path::theme($esrc)) {
                 echo '<pre>';
                 throw new \Exception('Not found seojson external ' . $esrc);
             }
             $ext = self::load($esrc);
             foreach ($ext as $k => $v) {
                 if (!isset($item[$k])) {
                     $item[$k] = $v;
                     continue;
                 }
             }
             if (!empty($ext['properties'])) {
                 foreach ($ext['properties'] as $k => $v) {
                     if (isset($item['properties'][$k])) {
                         continue;
                     }
                     $item['properties'][$k] = $v;
                 }
             }
             if (!empty($ext['names'])) {
                 foreach ($ext['names'] as $k => $v) {
                     if (isset($item['names'][$k])) {
                         continue;
                     }
                     $item['names'][$k] = $v;
                 }
             }
             if (!empty($ext['itemprops'])) {
                 foreach ($ext['itemprops'] as $k => $v) {
                     if (isset($item['itemprops'][$k])) {
                         continue;
                     }
                     $item['itemprops'][$k] = $v;
                 }
             }
         }
     }
     return $item;
 }
Example #2
0
 public static function exec($conds, $name, $fn, $args = array(), $re = false)
 {
     $name = 'Cache::exec' . $name;
     return Once::exec($name, function ($args, $r, $hash) use($name, $fn, $conds, $re) {
         $data = Mem::get($name . $hash);
         if (!$data) {
             $data = array('time' => 0);
         }
         $execute = Access::adminIsTime($data['time'], function ($cache_time) use($conds) {
             if (!sizeof($conds)) {
                 return false;
                 //Если нет conds кэш навсегда и develop не поможет
             }
             $max_time = 1;
             for ($i = 0, $l = sizeof($conds); $i < $l; $i++) {
                 $mark = $conds[$i];
                 $mark = Path::theme($mark);
                 if (!$mark) {
                     continue;
                 }
                 $m = filemtime($mark);
                 if ($m > $max_time) {
                     $max_time = $m;
                 }
                 if (!is_dir($mark)) {
                     continue;
                 }
                 foreach (glob($mark . '*.*') as $filename) {
                     $m = filemtime($filename);
                     if ($m > $max_time) {
                         $max_time = $m;
                     }
                 }
             }
             return $max_time > $cache_time;
         }, $re);
         if ($execute) {
             $cache = Nostore::check(function () use(&$data, $fn, $args, $re) {
                 $data['result'] = call_user_func_array($fn, array_merge($args, array($re)));
             });
             if ($cache) {
                 $data['time'] = time();
                 Mem::set($name . $hash, $data);
             } else {
                 Mem::delete($name . $hash);
             }
         }
         return $data['result'];
     }, array($args), $re);
 }
Example #3
0
 public static function runfolder($dir, $f = 1, $d = 0, $sub = false, $exts = false, &$filelist = array(), $pre = '')
 {
     $dir = Path::theme($dir);
     if ($dir && is_dir($dir) && ($dh = opendir($dir))) {
         while (($file = readdir($dh)) !== false) {
             if ($file[0] == '.') {
                 continue;
             }
             if ($file == 'vendor') {
                 continue;
             }
             if ($file[0] == '~') {
                 continue;
             }
             $path = $dir . $file;
             if (is_file($path) && $exts) {
                 preg_match('/\\.(\\w{0,4})$/', $file, $math);
                 //Расширение при поиске не учитываем
                 $ext = strtolower($math[1]);
                 if (!in_array($ext, $exts)) {
                     continue;
                 }
             }
             //$count++;
             //if($count<$lims)continue;
             //if($count>=($lims+$limc))break;
             if (!$f && is_file($path) && (!$d || !is_dir($path))) {
                 continue;
             }
             //Файлы не надо
             //if(!$f && is_file($path))continue;//Файлы не надо
             if (is_dir($path)) {
                 if ($sub) {
                     static::runfolder($path . '/', $f, $d, $sub, $exts, $filelist, $pre . $file . '/');
                 }
                 if (!$d) {
                     continue;
                 }
                 //Папки не надо
             }
             if ($d && preg_match("/\\.files\$/", $file)) {
                 continue;
             }
             array_push($filelist, $pre . $file);
         }
         closedir($dh);
     }
     return $filelist;
 }
Example #4
0
 public static function apply()
 {
     //Поиск совпадения адреса с файлом
     //Редирект также кэшируется в modified, когда обращение к статике, по правилам Nostore
     Path::init();
     //Контроллер... должен быть файл в корне index.json
     //Если сайт не использует контроллер то до этого места доходим только, когда 404 и лишний запуск не существенен
     //Либо следующая строчка обеспечивает формирование всего html если контроллер используется.
     $query = substr(urldecode($_SERVER['REQUEST_URI']), 1);
     $ch = substr($query, 0, 1);
     if (!in_array($ch, ['~', '!', '-'])) {
         Controller::init();
     }
     $conf = Config::get('router');
     Path::req($conf['404']);
 }
Example #5
0
 /**
  * Кэширумеая функция, основной разбор.
  */
 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;
 }
Example #6
0
 public static function exec()
 {
     if (!Update::$is) {
         Config::add('update', function ($name, $value, $conf) {
             if (!Update::$is) {
                 return;
             }
             Path::req('-' . $name . '/' . $value);
         });
     }
     Update::$is = true;
     //Пр появлении нового Config::get будет проверяться свойство update
     //Но нужно установить то что уже было установлено
     $conf = Config::$conf;
     foreach ($conf as $name => $v) {
         Update::update($name);
     }
     //И вообще всё установить нужно что ещё не установлено
     Config::get();
 }
Example #7
0
File: Mem.php Project: infrajs/mem
 public static function flush()
 {
     $mem =& static::memcache();
     if ($mem) {
         $mem->flush();
     } else {
         $conf = static::$conf;
         if (!$conf['cache']) {
             throw new \Exception('Set up cache folder Mem::$conf[cache]');
         }
         $dir = Path::theme($conf['cache']);
         if ($dir) {
             if (!Path::$conf['fs']) {
                 throw new \Exception('Filesystem protected by Path::$conf[fs]=false set it on true');
             }
             foreach (glob($dir . '*.*') as $filename) {
                 @unlink($filename);
             }
         }
     }
 }
Example #8
0
 function file_download($filename, $mimetype = 'application/octet-stream')
 {
     //thanks http://shaman.asiadata.ru/node/217
     if (file_exists($filename)) {
         $br = infra_download_browser();
         $name = preg_replace("/(.*\\/)*/", '', $filename);
         //$name=Path::tofs($name);
         $name = Path::toutf($name);
         if (!preg_match('/ff/', $br)) {
             $name = rawurlencode($name);
         }
         //$name=preg_replace("/ё/",'e',$name);
         if (preg_match('/chrome/', $br)) {
             $name = preg_replace('/%40/', '@', $name);
         }
         if (preg_match('/ie6/', $br)) {
             $name = preg_replace("/\\s/", '%20', $name);
         }
         header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
         header('Content-Type: ' . $mimetype);
         header('Last-Modified: ' . gmdate('r', filemtime($filename)));
         header('ETag: ' . sprintf('%x-%x-%x', fileinode($filename), filesize($filename), filemtime($filename)));
         header('Content-Length: ' . filesize($filename));
         header('Connection: close');
         header('Content-Disposition: attachment; filename="' . $name . '";');
         // Открываем искомый файл
         $f = fopen($filename, 'r');
         while (!feof($f)) {
             // Читаем килобайтный блок, отдаем его в вывод и сбрасываем в буфер
             echo fread($f, 1024);
             flush();
         }
         // Закрываем файл
         fclose($f);
     } else {
         header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
         header('Status: 404 Not Found');
     }
 }
Example #9
0
 private static function load($path)
 {
     $args = array($path);
     $res = Once::exec('Load::load', function ($path) {
         //php файлы эмитация веб запроса
         //всё остальное file_get_content
         $_r_e_s_ = array();
         $_r_e_s_['cache'] = !Nostore::check(function () use($path, &$_r_e_s_) {
             if (Path::isDir($path)) {
                 $p = explode('?', $path, 2);
                 $p[0] .= 'index.php';
                 $path = implode('?', $p);
             }
             $load_path = Path::theme($path);
             $fdata = Load::srcinfo($load_path);
             if ($load_path && $fdata['file']) {
                 $plug = Path::theme($fdata['path']);
                 if ($fdata['ext'] == 'php') {
                     $getstr = Path::toutf($fdata['query']);
                     //get параметры в utf8, с вопросом
                     $getstr = preg_replace("/^\\?/", '', $getstr);
                     parse_str($getstr, $get);
                     if (!$get) {
                         $get = array();
                     }
                     $GET = $_GET;
                     $_GET = $get;
                     $REQUEST = $_REQUEST;
                     $_REQUEST = array_merge($_GET, $_POST, $_COOKIE);
                     $SERVER_QUERY_STRING = $_SERVER['QUERY_STRING'];
                     $_SERVER['QUERY_STRING'] = $getstr;
                     $from_php_old = Load::isphp();
                     Load::isphp(true);
                     ob_start();
                     //headers надо ловить
                     $ans = array();
                     $rrr = (include $plug);
                     $result = ob_get_contents();
                     $resecho = $result;
                     ob_end_clean();
                     Load::isphp($from_php_old);
                     if ($rrr !== 1 && !is_null($rrr)) {
                         //Есть возвращённый результат
                         $result = $rrr;
                         if ($resecho) {
                             //Сообщение об ошибке... далее всё ломаем
                             $result = $resecho . Load::json_encode($result);
                             //Есть вывод в браузер и return
                         }
                     }
                     $_SERVER['QUERY_STRING'] = $SERVER_QUERY_STRING;
                     $_REQUEST =& $REQUEST;
                     $_GET =& $GET;
                     $data = $result;
                     //$data='php file';
                 } else {
                     $data = file_get_contents($plug);
                 }
                 $_r_e_s_ = array();
                 //Если в include это имя использовалось. Главное чтобы оно небыло ссылкой &
                 $_r_e_s_['status'] = 200;
                 $_r_e_s_['value'] = $data;
             } else {
                 $_r_e_s_['status'] = 404;
                 $_r_e_s_['value'] = '';
             }
         });
         return $_r_e_s_;
     }, $args);
     if (!$res['cache']) {
         Nostore::on();
     }
     return $res['value'];
 }
Example #10
0
<?php

namespace infrajs\controller;

use infrajs\ans\Ans;
use infrajs\path\Path;
use infrajs\view\View;
use infrajs\load\Load;
use infrajs\router\Router;
if (!is_file('vendor/autoload.php')) {
    chdir('../../../../');
    require_once 'vendor/autoload.php';
    Router::init();
}
$query = Crumb::$href;
$ans = array('title' => 'Проверки контроллера');
$composer = Load::loadJSON('-infrajs/composer.json');
$require = $composer['require'];
foreach ($require as $path => $ver) {
    $p = explode('/', $path);
    $r = Path::reqif('-' . $p[1] . '/infra.php');
}
$layer = array('data' => 1, 'tpl' => array('qewr{data}'));
Crumb::change('');
$html = Controller::check($layer);
if ($html != 'qewr1') {
    return Ans::err($ans, 'Результат неожиданный ' . $html);
}
Crumb::change($query);
View::html('', true);
return Ans::ret($ans);
Example #11
0
        return Ans::err($ans, 'Письмо уже отправлено! Новое сообщение можно будет отправить через 1 минуту!');
    }
    $_SESSION['submit_time'] = time();
}
$ans['testmail'] = $mdata['testmail'];
if ($maildir) {
    $folder = Path::theme($maildir);
    $name = Path::tofs(Path::encode($data['name']));
    $fname = date('Y F j H-i') . ' ' . $name . ' ' . time();
    if ($conf['file'] && $file) {
        $src = $folder . $fname . '.' . Path::tofs($file['name']);
        $r = move_uploaded_file($file['tmp_name'], $src);
        if (!$r) {
            return Ans::err($ans, 'Неудалось загрузить файл');
        }
        $data['file'] = Path::toutf(Path::pretty($src));
    }
}
$body = Template::parse('-contacts/mail.tpl', $data);
if (!$body) {
    $body = 'Ошибка. Не найден шаблон письма!';
}
if ($maildir) {
    file_put_contents($folder . $fname . '.txt', print_r($body, true) . "\n\n\n\n\n" . print_r($mdata, true));
}
if (!isset($mdata['email_from'])) {
    return Ans::err($ans, 'Ошибка с адресом получателя!');
}
$r = Mail::toAdmin($mdata['subject'], $mdata['email_from'], $body, $mdata['testmail']);
if (!$r) {
    return Ans::err($ans, "Неудалось отправить письмо из-за ошибки на сервере!");
Example #12
0
        foreach ($list as $file) {
            $d = Load::loadJSON($takepath . $file);
            $d['path'] = Path::resolve($d['path']);
            $d['modified'] = filemtime(Path::theme($d['path']));
            preg_match("/\\.([a-zA-Z]+)\$/", $d['path'], $match);
            $d['ext'] = strtolower($match[1]);
            $files[] = $d;
        }
    }
    $ans['files'] = $files;
} elseif ($type == 'takefile') {
    if ($submit) {
        $take = (bool) $_GET['take'];
        $ans['take'] = $take;
        $file = autoedit_theme($id);
        $file = Path::toutf($file);
        if (!$file) {
            $ans['noaction'] = true;
            //Собственно всё осталось как было
        } else {
            $takepath = autoedit_takepath($file);
            if (!$take && is_file($takepath)) {
                $r = @unlink($takepath);
                if (!$r) {
                    return Ans::err($ans, 'Неудалось отпустить файл');
                }
            } elseif ($take && !is_file($takepath)) {
                //Повторно захватывать не будем
                $save = array('path' => $id, 'date' => time(), 'ip' => $_SERVER['REMOTE_ADDR'], 'browser' => $_SERVER['HTTP_USER_AGENT']);
                $r = file_put_contents($takepath, Load::json_encode($save));
                if (!$r) {
Example #13
0
namespace infrajs\infra;

use infrajs\access\Access;
use infrajs\event\Event;
use infrajs\ans\Ans;
use infrajs\path\Path;
use infrajs\session\Session;
if (!is_file('vendor/autoload.php')) {
    chdir(explode('vendor/', __DIR__)[0]);
    require_once 'vendor/autoload.php';
}
Access::admin(true);
$ans = array();
if (isset($_GET['get'])) {
    $name = Ans::REQ('name');
    $ans['id'] = Session::getId();
    $ans['data'] = Session::get($name);
} else {
    if (isset($_GET['clear'])) {
        Session::clear();
    } else {
        if (isset($_GET['set'])) {
            $ans = array();
            $name = Path::toutf($_REQUEST['name']);
            $val = Path::toutf($_REQUEST['val']);
            Session::set($name, $val);
        }
    }
}
return Ans::ret($ans);
Example #14
0
 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);
 }
Example #15
0
 /**
  *  true если путь $dir существует и вложен в $root
  **/
 public static function isNest($root, $dir)
 {
     $src = Path::theme($dir);
     if (!$src) {
         return false;
     }
     $src = realpath($src);
     if (!$src) {
         return false;
     }
     $home = Path::theme($root);
     if (!$home) {
         return false;
     }
     $home = realpath($home);
     if (!$home) {
         return false;
     }
     if (preg_match('/\\' . DIRECTORY_SEPARATOR . '\\./', $home)) {
         return false;
     }
     if (preg_match('/\\' . DIRECTORY_SEPARATOR . '\\./', $src)) {
         return false;
     }
     $p = explode($home, $src, 2);
     if (sizeof($p) != 2 || $p[0] || !$p[1]) {
         return false;
     }
     return true;
 }
Example #16
0
        }
        if ($fdata['ext'] && $fdata['ext'] != $fd['ext']) {
            return;
        } elseif ($result) {
            //Расширение не указано и уже есть результат
            //Исключение.. расширение tpl самое авторитетное
            if ($fd['ext'] != 'tpl') {
                return;
            }
        }
        $result = $file;
    }, scandir(Path::theme($folder)));
    if (!$result) {
        return false;
    }
    return Path::theme($folder . $result);
}, array($fdata['path']), isset($_GET['re']));
$ans = array('src' => $isrc);
if (!$src) {
    if (!Load::isphp()) {
        header('HTTP/1.0 404 Not Found');
    }
    return;
}
$fdata = Load::srcInfo($src);
if (in_array($fdata['ext'], array('docx'))) {
    $txt = Docx::get($src);
    return Ans::txt($txt);
}
if (in_array($fdata['ext'], array('mht'))) {
    $txt = Mht::get($src);
Example #17
0
<?php

use infrajs\access\Access;
use infrajs\config\Config;
use infrajs\ans\Ans;
use infrajs\mem\Mem;
use infrajs\path\Path;
use infrajs\router\Router;
if (!is_file('vendor/autoload.php')) {
    chdir('../../../');
    require_once 'vendor/autoload.php';
    Router::init();
}
Access::test(true);
Mem::flush();
Path::fullrmdir('!', true);
$ans = array();
Ans::ret($ans, 'Cache cleared Mem::flush, Path::fulrmdir');
Example #18
0
 public static function accept($name, $v)
 {
     $conf =& Config::$conf;
     if (!empty($v['dependencies'])) {
         //Должны быть добавлены в conf ДО $name
         /**
          * Используется для порядка загрузки javascript
          * 
          **/
         Each::exec($v['dependencies'], function &($s) use($name) {
             Config::get($s);
             $r = null;
             return $r;
         });
     }
     if (empty($conf[$name])) {
         $conf[$name] = array();
     }
     if (!is_array($v)) {
         return;
     }
     foreach ($v as $kk => $vv) {
         if (isset($conf[$name][$kk])) {
             continue;
         }
         //То что уже есть в конфиге круче вновь прибывшего
         $conf[$name][$kk] = $vv;
     }
     foreach (self::$list as $prop => $callback) {
         if (!empty($conf[$name][$prop])) {
             $callback($name, $conf[$name][$prop], $conf[$name]);
         }
     }
     if (!empty($conf[$name]['require']) && empty($conf[$name]['off'])) {
         Each::exec($conf[$name]['require'], function &($s) use($name) {
             Path::req('-' . $name . '/' . $s);
             $r = null;
             return $r;
         });
     }
 }
Example #19
0
function autoedit_takepath($file = false)
{
    $takepath = Path::resolve('!admin_takefiles/');
    if ($file === false) {
        return $takepath;
    }
    $file = autoedit_theme($file);
    $path = $takepath . preg_replace('/[\\/\\\\\\*]/', '_', Path::tofs($file)) . '.js';
    return $path;
}
Example #20
0
<?php

namespace infrajs\autoedit;

use infrajs\path\Path;
require_once __DIR__ . '/../../../vendor/autoload.php';
Path::mkdir('!admin_takefiles/');
Example #21
0
     //is!, descr!, text!, name!, breadcrumbs!
     $ans['is'] = 'producer';
     $name = Catalog::getProducer($producer);
     $ans['name'] = $name;
     $ans['title'] = $name;
     $conf = Config::get('catalog');
     $ans['breadcrumbs'][] = array('title' => $conf['title'], 'add' => 'producer:');
     $menu = Load::loadJSON('-catalog/menu.json');
     $ans['breadcrumbs'][] = array('href' => 'producers', 'title' => $menu['producers']['title']);
     $ans['breadcrumbs'][] = array('add' => 'producer::producer.' . $name . '=1', 'title' => $name);
     $ans['breadcrumbs'][sizeof($ans['breadcrumbs']) - 1]['active'] = true;
 } else {
     if (!$md['group'] && $md['search']) {
         $ans['is'] = 'search';
         $ans['name'] = $md['search'];
         $ans['title'] = Path::encode($md['search']);
         $ans['breadcrumbs'][] = array('title' => $conf['title'], 'add' => 'search:');
         $menu = Load::loadJSON('-catalog/menu.json');
         $ans['breadcrumbs'][] = array('href' => 'find', 'title' => $menu['find']['title']);
         $ans['breadcrumbs'][] = array('title' => $ans['name']);
         $ans['breadcrumbs'][sizeof($ans['breadcrumbs']) - 1]['active'] = true;
     } else {
         //is!, descr!, text!, name!, breadcrumbs!, title
         if ($md['group']) {
             foreach ($md['group'] as $group => $v) {
                 break;
             }
         } else {
             $group = false;
         }
         $group = Catalog::getGroup($group);
Example #22
0
                }
                if (!is_file($dir . $file)) {
                    return;
                }
                $ext = Path::getExt($file);
                if ($ext != 'md') {
                    return;
                }
                $res = array('src' => $dir . $file, 'vendor' => $vendor, 'name' => $name, 'file' => $file);
                $map['vendors'][$vendor][$name]['list'][] = $res;
                $map['names'][$dir] =& $map['vendors'][$vendor][$name];
            }, scandir($dir));
        }, scandir($dir));
    }, scandir($dir));
    return $map;
});
$fd = Load::srcInfo($src);
if (isset($map['names'][$fd['folder']])) {
    $namedata = $map['names'][$fd['folder']];
} else {
    $namedata = array();
}
$text = file_get_contents(Path::theme($src));
$body = Markdown::defaultTransform($text);
//$data['files']=$files;
$data['map'] = $map;
$data['src'] = $src;
$data['namedata'] = $namedata;
$data['body'] = $body;
$html = Template::parse(Path::theme('-mdreader/index.tpl'), $data);
echo $html;
Example #23
0
                if (!is_file($tsrc . $file)) {
                    continue;
                }
                $list[$name][] = Path::pretty($tsrc . $file);
            }
        } else {
            $list[$name][] = Path::pretty($tsrc);
        }
        return $r;
    });
}
$data = array('list' => array());
$errors = array();
foreach ($list as $name => $files) {
    foreach ($files as $file) {
        $ext = Path::getExt($file);
        if ($ext != 'php') {
            continue;
        }
        $finfo = Load::srcInfo($file);
        $text = Load::loadTEXT($file . '?type=auto');
        if (strlen($text) > 1000) {
            $res = array('title' => $name . ' ' . $finfo['name'], 'result' => 0, 'msg' => 'Слишком длинный текст', 'class' => 'bg-warning');
        } else {
            $res = Load::json_decode($text, true);
            if (!is_array($res)) {
                $res = array('result' => 0, 'msg' => 'Некорректный json ' . print_r($res, true));
            }
        }
        $res['src'] = $finfo['src'];
        $res['name'] = $finfo['file'];
Example #24
0
<?php

use infrajs\access\Access;
use infrajs\event\Event;
use infrajs\ans\Ans;
use infrajs\path\Path;
use infrajs\each\Each;
use infrajs\config\Config;
if (!is_file('vendor/autoload.php')) {
    chdir('../../../../');
    require_once 'vendor/autoload.php';
}
$ans = array();
$ans['title'] = 'Проверка наличия папок';
$conf = Config::get();
if ($conf['mem']['type'] == 'fs') {
    $dirs = Config::get('path');
    if (!Path::theme($dirs['cache'])) {
        return Ans::err($ans, 'Нет папки ' . $dirs['cache']);
    }
    if (!Path::theme($dirs['data'])) {
        return Ans::err($ans, 'Нет папки ' . $dirs['data']);
    }
    return Ans::ret($ans, 'Обязательные папки есть');
} else {
    return Ans::ret($ans, 'Используется memcache. Папки не создаются.');
}
Example #25
0
<?php

namespace infrajs\yml;

use infrajs\path\Path;
use infrajs\ans\Ans;
if (!is_file('vendor/autoload.php')) {
    chdir('../../../../');
    require_once 'vendor/autoload.php';
}
$ans = [];
if (!is_dir('data/')) {
    return Ans::err($ans, 'Папки data нет');
}
if (!is_file('data/yml.xlsx')) {
    return Ans::err($ans, 'Файла excel нет');
}
$src = '~yml.xlsx';
if (!Path::theme($src)) {
    return Ans::err($ans, 'Файл не найден.' . $src);
}
return Ans::ret($ans);
Example #26
0
<?php

namespace infrajs\doc;

use infrajs\path\Path;
Path::mkdir(Docx::$conf['cache']);
Example #27
0
 private function makeMark($data)
 {
     if (!$data) {
         return '';
     }
     self::rksort($data);
     $key = md5(serialize($data));
     $that = $this;
     $mark = Once::exec($this->prefix . $key, function () use($data, $that, $key) {
         $isoutdate = true;
         $raise = $this->raise;
         //На сколько символов разрешено увеличивать хэш
         $note = $this->note;
         //При увеличении на сколько записывается сообщение в лог
         $len = $this->len - 1;
         while ($isoutdate && $len < $this->len + $raise) {
             $len++;
             $mark = substr($key, 0, $len);
             $src = Path::theme('~.marks/' . $that->prefix . $mark . '.json');
             if ($src) {
                 $otherdata = file_get_contents($src);
                 $otherdata = Load::json_decode($otherdata, true);
             } else {
                 $otherdata = false;
             }
             //$otherdata=infra_mem_get($that->prefix.$mark);
             if ($otherdata && is_array($otherdata['data']) && $otherdata['time']) {
                 if ($otherdata['data'] == $data) {
                     $isoutdate = false;
                     //Такая метка уже есть и она правильная
                 } else {
                     //Решается судьба старой метки
                     $isoutdate = time() > $data['time'] + $this->warrantytime;
                 }
             } else {
                 $isoutdate = false;
             }
         }
         if ($len >= $this->len + $note) {
             $that->notice = 'Mark adding to hash ' . ($len - $this->len) . ' symbol(s) for save time warranty ' . print_r($data, true);
             error_log($that->notice);
         }
         if ($isoutdate) {
             //Все метки актуальны... перезаписываем первую
             $that->error = 'Mark rewrite actual hashmark';
             error_log($that->error);
             $mark = substr($key, 0, $this->len);
         }
         $src = Path::theme('~.marks/');
         if (!$src) {
             die('Fatal error no marks dir');
         }
         $src = $src . $this->prefix . $mark . '.json';
         $data = Load::json_encode(array('time' => time(), 'data' => $data));
         $data = file_put_contents($src, $data);
         //infra_mem_set($that->prefix.$mark, array(
         //	'time'=>time(),
         //	'data'=>$data
         //));
         return $mark;
     });
     return $mark;
 }
Example #28
0
     //новый src уже на серую картинку
 }
 $data = Imager::scale($src, $w, $h, $crop, $top);
 if (!$data) {
     die('Resize Error');
 }
 if ($type == 'png') {
     $data = Imager::optipng($data, md5($src . $w . $h . $crop . $top));
     if (!$data) {
         die('Optipng Error');
     }
 }
 $br = infra_imager_browser();
 $name = preg_replace("/(.*\\/)*/", '', $isrc);
 if (!$name) {
     $name = Path::encode($isrc);
 }
 $name = Imager::toutf($name);
 if (!preg_match('/ff/', $br)) {
     $name = rawurlencode($name);
 }
 if (preg_match('/ie6/', $br)) {
     $name = preg_replace("/\\s/", '%20', $name);
 }
 if (!$type) {
     $type = 'image/jpeg';
 }
 $ans = array('name' => $name, 'type' => $type);
 //return $data;
 //}, $args, isset($_GET['re']));
 //)
Example #29
0
<?php

namespace infrajs\controller;

use infrajs\path\Path;
use infrajs\event\Event;
use infrajs\template\Template;
/**
 * div, divs, divtpl
 *
 **/
Path::req('*controller/infra.php');
Event::handler('oninit', function () {
    Run::runAddKeys('divs');
    External::add('divs', function (&$now, $ext) {
        //Если уже есть пропускаем
        if (!$now) {
            $now = array();
        }
        foreach ($ext as $i => $v) {
            if (isset($now[$i])) {
                continue;
            }
            $now[$i] = array();
            Each::fora($ext[$i], function (&$l) use(&$now, $i) {
                array_push($now[$i], array('external' => $l));
            });
        }
        return $now;
    });
}, 'div:layer');
Example #30
0
     $poss = $res['list'];
     foreach ($poss as &$pos) {
         if (preg_match("/[:]/", $pos[$prop['posid']])) {
             continue;
         }
         if (!Xlsx::isSpecified($pos[$prop['posid']])) {
             continue;
         }
         $r = false;
         if ($prop['separator']) {
             $arval = explode($prop['separator'], $pos[$prop['posid']]);
         } else {
             $arval = array($pos[$prop['posid']]);
         }
         foreach ($arval as $i => $value) {
             $idi = Path::encode($value);
             $id = mb_strtolower($idi);
             if (!Xlsx::isSpecified($id)) {
                 continue;
             }
             $r = true;
             $params[$k]['option'][$idi]['filter']++;
         }
         if ($r) {
             $params[$k]['filter']++;
         }
         //Позиций с этим параметром
     }
 }
 //У скольки позиций в выборке у которых этот параметр не указан
 $params[$k]['nofilter'] = sizeof($poss) - $params[$k]['filter'];