Пример #1
0
$data = infra_cache(array($isrc), 'imager.php', function ($src, $ignoremark, $mark, $default, $getorig, $w, $h, $crop, $top, $gray, $re) use($isrc) {
    $p1 = infra_srcinfo($isrc);
    //Нужна папка со звёздочкой
    $p = infra_srcinfo($src);
    if (in_array($p['ext'], array('docx', 'mht'))) {
        die("docx, mht TODO");
        /*
        	TODO: Смотрим подключён ли плагин files для того чтобы достать картинку и файла
        */
        if (!infra_theme('*files/files.inc.php')) {
            $default = true;
            $src = infra_theme('*imager/noimage.png');
        } else {
            infra_require('*files/files.inc.php');
            if ($re) {
                $re = '&re';
            } else {
                $re = '';
            }
            if ($p['ext'] == 'docx') {
                $p = files_get(infra_toutf($p1['folder']), infra_toutf($p['id']));
                if (!$p['images'][0]) {
                    $default = true;
                    $src = infra_theme('*imager/noimage.png');
                    //header('HTTP/1.1 404 Not Found');
                    //return;
                } else {
                    $src = $p['images'][0]['src'];
                }
            } elseif ($p['ext'] == 'mht') {
                $p = infra_loadJSON('*pages/mht/mht.php?preview' . $re . '&src=' . infra_toutf($p['src']));
                if (!$p['images'][0]) {
                    $default = true;
                    $src = infra_theme('*imager/noimage.png');
                    //header('HTTP/1.1 404 Not Found');
                    //return;
                } else {
                    $src = $p['images'][0]['src'];
                }
            }
        }
    }
    $src = infra_tofs($src);
    $type = imager_type($src);
    if (!is_null($ignoremark)) {
        //Метку ignore может выставить только администратор
        //На файлы с такой меткой водяной знак никогда не ставится
        $info = imager_makeInfo($src);
        if ($ignoremark && $info['water']) {
            //Если файл был с водяным знаком
            $orig = $info['orig'];
            if ($orig) {
                $orig = infra_theme($orig);
                if ($orig) {
                    //Если оригинальный файл найден
                    $r = copy($orig, $src);
                    //Востановили оригинал без удаления оригинала
                    $info['water'] = false;
                    if (!$r) {
                        imager_writeInfo($src, $info);
                        die('Не удалось востановить оригинал чтобы поставить метку ignore');
                    }
                    $info['ignore'] = $ignoremark;
                } else {
                    imager_writeInfo($src, $info);
                    die('На файле установлен водяной знак. Оригинальный файл не найден. Метку установить неудалось');
                }
            } else {
                imager_writeInfo($src, $info);
                die('Водяной знак есть а оригинал не указан. исключение.');
            }
        } else {
            //Водяного знака небыло
            $info['ignore'] = $ignoremark;
        }
        imager_writeInfo($src, $info);
    }
    if ($type && $mark && !$default) {
        //Это не значит что нужно делать бэкап
        imager_mark($src, $type);
        //Накладываем водяной знак
    }
    /*$info=imager_readInfo($src);
    	if($info['ignore']){
    		$orig=$info['orig'];
    	}*/
    $limark = false;
    //Не делать водяной знак если площать меньше 150x150
    if ($w && $h) {
        $limark = $conf['imager']['waterlim'] > $w * $h;
    } elseif ($w || $h) {
        $wl = $w;
        $hl = $h;
        if (!$w) {
            $wl = $h;
        }
        if (!$h) {
            $hl = $w;
        }
        $limark = $conf['imager']['waterlim'] > $wl * $hl;
    }
    if ($getorig) {
        $w = 0;
        $h = 0;
        $crop = false;
        $info = imager_readInfo($src);
        $orig = $info['orig'];
        if ($orig) {
            $orig = infra_theme($orig);
            if (!$orig) {
                die('Оригинал не найден');
            } else {
                $src = $orig;
                //Что далее будет означать что возьмётся для вывода оригинальная картинка
            }
        } else {
            die('Already original');
        }
    } elseif ($limark) {
        $info = imager_readInfo($src);
        if (@$info['water']) {
            $orig = infra_theme($info['orig']);
            if ($orig) {
                $src = $orig;
            } else {
                //die('Не найден оригинал');
            }
        }
    }
    //$src с водяной меткой если нужно
    if ($gray) {
        $src = imager_makeGray($src, $temp);
        //новый src уже на серую картинку
    }
    $data = imager_scale($src, $w, $h, $crop, $top);
    if (!$data) {
        die('Resize Error');
    }
    $br = infra_imager_browser();
    $name = preg_replace("/(.*\\/)*/", '', $isrc);
    $name = infra_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';
    }
    $data = array('data' => $data, 'name' => $name, 'type' => $type);
    return $data;
}, $args, isset($_GET['re']));
Пример #2
0
            $group['childs'] = array_filter($group['childs'], function (&$g) {
                if (!$g['data'] && !$g['childs']) {
                    return false;
                }
                return true;
            });
            $group['childs'] = array_values($group['childs']);
        }
    }, array(), true);
    xls_runPoss($data, function (&$pos) {
        $conf = infra_config();
        xls_preparePosFiles($pos, $conf['cart']['dir'], array('Производитель', 'article'));
        foreach ($pos['images'] as $k => $v) {
            $src = $pos['images'][$k];
            $p = explode('/', $src);
            foreach ($p as $i => $n) {
                $p[$i] = urlencode($n);
                $p[$i] = preg_replace('/\\+/', '%20', $p[$i]);
            }
            $pos['images'][$k] = implode('/', $p);
        }
    });
    return yml_parse($data);
}
if (isset($_GET['show'])) {
    $html = infra_cache(array($conf['cart']['dir']), 'ymlshow', function () {
        return yml_init();
    }, array(), isset($_GET['re']));
    header("Content-type: text/xml");
    echo $html;
}
Пример #3
0
 public static function parse($src)
 {
     $src = infra_theme($src);
     if (!$src) {
         return;
     }
     $args = array($src);
     return infra_cache(array($src), 'mhtparse', function ($src) {
         $conf = infra_config();
         $imgmaxwidth = $conf['files']['imgmaxwidth'];
         $previewlen = $conf['files']['previewlen'];
         $filename = infra_theme($src);
         $fdata = infra_srcinfo($src);
         if ($fdata['ext'] == 'php') {
             $data = infra_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 = infra_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);
             $dirs = infra_dirs();
             $folder = $dirs['cache'] . 'mht/' . md5($src) . '/';
             @mkdir($folder);
             $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 = infra_toutf($html);
             //Виндовые файлы хранятся в cp1251
             $folder = infra_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/imager.php?w=$w&h=$h&src=".($path.$big)."' align='$align' class='$align' alt='$alt'>";
                     $i = "<IMG src='?*imager/imager.php?w={$w}&h={$h}&src=" . ($path . $big) . "' align='{$align}' class='{$align}'>";
                     //urlencode решает проблему с ie7 когда иллюстрации с адресом содержащим пробел не показываются
                     if ($isbig) {
                         $i = "<a target='about:blank' href='?*imager/imager.php?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;
         return $ans;
     }, $args);
 }
Пример #4
0
function &xls_parseAll($path)
{
    $data = infra_cache(array($path), 'xls_parseAll', function &($path) {
        $file = infra_theme($path);
        $data = array();
        if (!$file) {
            return $data;
        }
        $in = infra_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);
            infra_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, infra_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') {
            $dirs = infra_dirs();
            $cacheFolder = $dirs['cache'] . 'xlsx/';
            $cacheFolder .= infra_hash($path) . '/';
            //кэш
            infra_cache_fullrmdir($cacheFolder);
            //удалить старый кэш
            //разархивировать
            $zip = new \ZipArchive();
            if ($zip->open(infra_theme($path))) {
                mkdir($cacheFolder);
                $zip->extractTo($cacheFolder);
                $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;
}
Пример #5
0
 $data = infra_cache(array($filename), 'mhtparse', function ($filename, $what, $ftype, $imgmaxwidth, $previewlen) {
     $data = file_get_contents($filename);
     $p = explode('/', $filename);
     $fname = array_pop($p);
     $fnameext = $fname;
     //$fname=basename($filename);
     preg_match("/^(\\d*)/", $fname, $match);
     $date = $match[0];
     $fname = infra_toutf(preg_replace('/^\\d*\\s+/', '', $fname));
     $fname = preg_replace('/\\.\\w{0,4}$/', '', $fname);
     if ($ftype == 'mht') {
         $ar = preg_split('/------=_NextPart_.*/', $data);
         if (sizeof($ar) > 1) {
             //На первом месте идёт информация о ворде...
             unset($ar[0]);
             unset($ar[sizeof($ar) - 1]);
         }
         $ar = array_values($ar);
         $dirs = infra_dirs();
         $folder = $dirs['cache'] . 'pages_mht/' . preg_replace('/[\\/\\\\.]/', '_', $filename) . '/';
         @mkdir($folder);
         $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));
                 //Сохраняем картинку или тп...
             }
         }
     } else {
         $html = $data;
     }
     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);
     //$html=preg_replace("/<v:shapetype.*<\/v:shapetype>/U",'',$html,1);
     //$html=preg_replace('/<v:shape.*(src=.*"\s).*<\/v:shape>/U','<img ${1}>',$html,1);
     $images = array();
     if ($ftype == 'mht') {
         preg_match_all('/src=3D".*\\.files\\/(image.+)"/U', $html, $match);
         for ($i = 0, $l = sizeof($match[1]); $i < $l; $i = $i + 2) {
             /*$r1=filesize($folder.$match[1][$i]);
               $r2=filesize($folder.$match[1][$i+1]);
               if($r1>$r2){
                   $images[$match[1][$i+1]]=$match[1][$i+1];
                   echo infra_toutf($folder.$match[1][$i]);
                   exit;
               }else{*/
             $images[$match[1][$i + 1]] = $match[1][$i];
             //Каждая следующая картинка есть уменьшенная копия предыдущей оригинального размера
             //}
         }
     } else {
         preg_match_all('/<img.*src=["\'](.*)["\'].*>/U', $html, $match);
         for ($i = 0, $l = sizeof($match[1]); $i < $l; $i = $i + 2) {
             $images[] = $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=preg_replace("/<span.*class=.*Spell.*>(.*)<\/span>/U",'${1}',$html);
     if ($ftype == 'mht') {
         //Была ошибка когда файловая система utf8 далее в html который ещё в cp1251 подставлялся путь в utf8 и когда весь html конвертировался путь рушился
         $html = infra_toutf($html);
     }
     if ($ftype == 'mht') {
         $folder = infra_toutf($folder);
         $html = preg_replace('/ src=".*\\/(.*)"/U', ' src="' . $folder . '${1}"', $html);
     }
     //$html=preg_replace("/<span.*>/U",'',$html);
     //$html=preg_replace("/<\/span>/U",'',$html);
     //$html=preg_replace("/<div.*>/U",'',$html);
     //$html=preg_replace("/<\/div>/U",'',$html);
     //$html=preg_replace("/ class=MsoNormal/",'',$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);
     /*if($ftype=='mht'){
           $html=infra_toutf($html);
       }*/
     $patern = '/###cut###/U';
     $d = preg_split($patern, $html);
     if (sizeof($d) > 1) {
         $html = preg_replace($patern, '', $html);
         $preview = $d[0];
     } else {
         $temphtml = strip_tags($html, '<p>');
         //preg_match('/^(<p.*>.{'.$previewlen.'}.*<\/p>)/U',$temphtml,$match);
         preg_match('/(<p.*>.{1}.*<\\/p>)/U', $temphtml, $match);
         if (sizeof($match) > 1) {
             $preview = $match[1];
         } else {
             $preview = $html;
         }
         /*$temphtml=strip_tags($html,'<p>');
           preg_match('/(<p.*>.{'.$previewlen.'}.*<\/p>)/U',$temphtml,$match);
           if(sizeof($match)>1){
               $preview=$match[1];
           }else{
               $preview=$html;
           }*/
     }
     $preview = preg_replace('/<h1.*<\\/h1>/U', '', $preview);
     $preview = preg_replace('/<img.*>/U', '', $preview);
     $preview = preg_replace('/<p.*>\\s*<\\/p>/iU', '', $preview);
     preg_match('/<img.*src=["\'](.*)["\'].*>/U', $html, $match);
     if ($match && $match[1]) {
         $img = $match[1];
     } else {
         $img = false;
     }
     /*preg_match('/<h1.*>(.*)<\/h1>/U',$html,$match);
       if($match&&$match[1]){
           //$title=trim($match[1]);
           $title=trim(strip_tags($match[1]));
       }else{
           $title=false;
       }*/
     $title = $fname;
     if ($ftype == 'mht') {
         $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/imager.php?w=$w&h=$h&src=".($path.$big)."' align='$align' class='$align' alt='$alt'>";
                 $i = "<IMG src='?*imager/imager.php?w={$w}&h={$h}&src=" . ($path . $big) . "' align='{$align}' class='{$align}'>";
                 //urlencode решает проблему с ie7 когда иллюстрации с адресом содержащим пробел не показываются
                 if ($isbig) {
                     $i = "<a target='about:blank' href='?*imager/imager.php?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='/<img width=(\d*\s).*height=(\d*\s).*src="(.*\/)(image.*)"(.*)alt="(.*)".*>/U';
                 $count=7;
                 do{
                     preg_match($patern,$html,$match);
                     if(sizeof($match)==$count){
                         echo $html;
                         exit;
                         $w=trim($match[1]);
                         $h=trim($match[1]);
                         $path=$match[3];
                         $small=$match[4];
                         $align=trim($match[5]);
                         preg_match('/align="(.*)"/',$align,$some);
                         if(sizeof($some)>0){
                             $align=$match[1];
                         }else{
                             $align='';
                         }
                         $alt=trim($match[6]);
                         $alt=html_entity_decode($alt, ENT_QUOTES, "utf-8");
                         $big=$images[$small];
                         $isbig=preg_match('/#/',$alt);
                         if($isbig){
                             $alt=preg_replace('/#/','',$alt);
                         }
                         
                         $i="<img title='$alt' src='?*imager/imager.php?w=$w&h=$h&src=$path$big' align='$align' class='$align' alt='$alt'>";
                         if($isbig){
                             $i="<a target='about:blank' href='?*imager/imager.php?src=$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 cellspacing="0" cellpadding="0" class="common">' . $param . '</table>', $html, 1);
         } else {
             break;
         }
     } while (sizeof($match) > 1);
     do {
         preg_match('/###(.*)###/U', $html, $match);
         if (sizeof($match) > 1) {
             $param = $match[1];
             $param = strip_tags($param);
             $param = html_entity_decode($param, ENT_QUOTES, 'utf-8');
             $param = preg_split('/#/', $param);
             for ($i = 0, $l = sizeof($param); $i < $l; ++$i) {
                 $param[$i] = trim($param[$i]);
             }
             $name = $param[0];
             $qp = http_build_query($param, 'p', '&');
             $inset = infra_loatTEXT('*pages/insets/' . $name . '.php?type=html&' . $qp);
             if ($inset) {
                 $html = preg_replace('/###(.*)###/U', $inset, $html, 1);
             } else {
                 $html = preg_replace('/###(.*)###/U', '', $html, 1);
             }
         } else {
             break;
         }
     } while (sizeof($match) > 1);
     $r = preg_match('/<h.*>(.*)<\\/h.>/U', $html, $match);
     if ($r) {
         $heading = strip_tags($match[1]);
     } else {
         $heading = false;
     }
     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]);
     }
     do {
         preg_match('/(<a.*)title=.##(.*)##.(.*>)/U', $html, $match);
         if (sizeof($match) > 1) {
             $param = $match[2];
             $param = strip_tags($param);
             $param = html_entity_decode($param, ENT_QUOTES, 'utf-8');
             $param = preg_split('/#/', $param);
             for ($i = 0, $l = sizeof($param); $i < $l; ++$i) {
                 $param[$i] = trim($param[$i]);
             }
             $name = $param[0];
             $qp = http_build_query($param, 'p', '&');
             $inset = infra_loadTEXT('*pages/insets/' . $name . '.php?type=title&' . $qp);
             if ($inset) {
                 $html = preg_replace('/<a.*title=.##.*##.*>/U', $match[1] . $inset . $match[3], $html, 1);
             } else {
                 $html = preg_replace('/##.*##/U', '', $html, 1);
             }
         } else {
             break;
         }
     } while (sizeof($match) > 1);
     //$html=preg_replace("/\s+/",' ',$html); С этим появляется какой-то левый символ и всё падает... глюкс был
     $preview = preg_replace("/\\s+/", ' ', $preview);
     $preview = trim($preview);
     $img = trim($img);
     $title = trim($title);
     $html = trim($html);
     if ($what) {
         $filetime = filemtime($filename);
         $s = infra_toutf($fnameext);
         $data = infra_nameinfo($s);
         $data['modified'] = $filetime;
         if ($heading) {
             $data['heading'] = $heading;
         }
         //if($param['images'])$data['images']=$param['images'];
         if ($links) {
             $data['links'] = $links;
         }
         if ($data['name']) {
             $data['title'] = $data['name'];
         }
         $data['img'] = '';
         if ($ftype == 'mht') {
             if ($img) {
                 $data['img'] = $img;
                 $data['images'] = array();
                 foreach ($images as $v) {
                     $data['images'][] = array('src' => infra_toutf($folder) . $v);
                 }
             }
         } else {
             if ($images) {
                 $data['images'] = array();
                 foreach ($images as $v) {
                     $data['images'][] = array('src' => $v);
                 }
             }
         }
         if ($preview) {
             $data['preview'] = html_entity_decode($preview, ENT_COMPAT, 'UTF-8');
         }
         if ($ftype != 'mht' && $data['img']) {
             $data['img'] = preg_replace('/^.*theme\\.php\\?/', '', $data['img']);
             $data['img'] = preg_replace('/^.*src=/', '', $data['img']);
             //сбросили imager/ Все атрибуты должны быть вначале а src указан в конце всех параметров
             $data['img'] = preg_replace('/&.*$/', '', $data['img']);
             //сбросили imager/ Все атрибуты должны быть вначале а src указан в конце всех параметров
         }
     } else {
         $data = html_entity_decode($html, ENT_COMPAT, 'UTF-8');
     }
     return $data;
 }, $args, $reparse);
Пример #6
0
 public static function cache($name, $call, $args = array(), $re = null)
 {
     if (is_null($re)) {
         $re = isset($_GET['re']);
     }
     $conf = infra_config();
     return infra_cache($conf['catalog']['cache'], 'cat-' . $name, $call, $args, $re);
 }
Пример #7
0
 /**
  * Кэширумеая функция, основной разбор.
  */
 public static function parse($src)
 {
     $args = array($src, $imgmaxwidth, $previewlen);
     $param = infra_cache(array($src), 'docx_parse', function ($src, $imgmaxwidth, $previewlen, $re) {
         $conf = infra_config();
         $imgmaxwidth = $conf['files']['imgmaxwidth'];
         $previewlen = $conf['files']['previewlen'];
         $cachename = md5($src);
         $dirs = infra_dirs();
         $cachefolder = $dirs['cache'] . 'docx/' . $cachename . '/';
         //В винде ингда вылетает о шибка что нет прав удалить какой-то файл в папке и как следствие саму папку
         //Обновление страницы проходит уже нормально
         //Полагаю в линукс такой ошибки не будет хз почему возникает
         @docx_full_del_dir($cachefolder);
         $path = infra_theme($src);
         if (!$path) {
             return array();
         }
         $xmls = docx_getTextFromZippedXML($path, 'word/document.xml', $cachefolder, $re);
         $rIds = array();
         $param = array('folder' => $cachefolder, 'imgmaxwidth' => $imgmaxwidth, 'previewlen' => $previewlen, 'type' => $type, '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, '\\itlife\\files\\docx_analyse', $param);
         } else {
             $param['rIds'] = array();
             $html = '';
         }
         $param['html'] = $html;
         return $param;
     }, $args);
     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;
 }
Пример #8
0
 function docx_get($src, $type = 'norm', $re = false)
 {
     $debug = $re;
     $conf = infra_config();
     if (@$conf['files'] && @$conf['files']['imgmaxwidth']) {
         $imgmaxwidth = $conf['files']['imgmaxwidth'];
     }
     if (!$imgmaxwidth) {
         $imgmaxwidth = 1000;
     }
     $imgmaxwidth = (int) $imgmaxwidth;
     $previewlen = 150;
     $args = array($src, $type, $imgmaxwidth, $previewlen);
     $dhtml = infra_cache(array($src), 'docx_parse', function ($src, $type, $imgmaxwidth, $previewlen, $debug) {
         $cachename = md5($src);
         $dirs = infra_dirs();
         $cachefolder = $dirs['cache'] . 'docx/' . $cachename . '/';
         //В винде ингда вылетает о шибка что нет прав удалить какой-то файл в папке и как следствие саму папку
         //Обновление страницы проходит уже нормально
         //Полагаю в линукс такой ошибки не будет хз почему возникает
         @docx_full_del_dir($cachefolder);
         $xmls = docx_getTextFromZippedXML($src, 'word/document.xml', $cachefolder, $debug);
         $rIds = array();
         $param = array('com' => array(), 'folder' => $cachefolder, 'imgmaxwidth' => $imgmaxwidth, 'previewlen' => $previewlen, 'type' => $type, '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, 'docx_analyse', $param);
         } else {
             $param['rIds'] = array();
             $html = '';
         }
         /*if($debug){
               echo $html;
               echo '<textarea style="width:600px; height:400px">';
               echo $html;
               echo '</textarea>';
               echo '<pre>';
               print_r($xmlar);
           }*/
         if ($type == 'preview' || $type == 'news') {
             $p = explode('/', $src);
             $fname = array_pop($p);
             $s = infra_toutf($fname);
             $data = infra_nameinfo($s);
             //$p=explode("/",$src);
             //$fname=array_pop($p);
             //preg_match("/^(\d*)/",$fname,$match);
             //$fname=infra_toutf(preg_replace('/^\d*/','',$fname));
             //$fname=preg_replace('/\.\w{0,4}$/','',$fname);
             //$fname=trim($fname);
             //$date=$match[0];
             $patern = '/###cut###/U';
             $d = preg_split($patern, $html);
             if (sizeof($d) > 1) {
                 $html = preg_replace($patern, '', $html);
                 $preview = $d[0];
             } else {
                 $temphtml = strip_tags($html, '<p>');
                 //preg_match('/^(<p.*>.{'.$previewlen.'}.*<\/p>)/U',$temphtml,$match);
                 preg_match('/(<p.*>.{1}.*<\\/p>)/U', $temphtml, $match);
                 if (sizeof($match) > 1) {
                     $preview = $match[1];
                 } else {
                     $preview = $html;
                 }
             }
             $preview = preg_replace('/<h1.*<\\/h1>/U', '', $preview);
             $preview = preg_replace('/<img.*>/U', '', $preview);
             $preview = preg_replace('/<p.*>\\s*<\\/p>/iU', '', $preview);
             $preview = preg_replace("/\\s+/", ' ', $preview);
             $preview = trim($preview);
             preg_match('/<img.*src=["\'](.*)["\'].*>/U', $html, $match);
             if ($match && $match[1]) {
                 $img = $match[1];
             } else {
                 $img = false;
             }
             $filetime = filemtime($src);
             $data['modified'] = $filetime;
             if (@$param['links']) {
                 $data['links'] = $param['links'];
             }
             if (@$param['heading']) {
                 $data['heading'] = $param['heading'];
             }
             //title - depricated
             if (@$data['name']) {
                 $data['title'] = $data['name'];
             }
             if ($img) {
                 $data['img'] = $img;
             }
             if (@$param['images']) {
                 $data['images'] = $param['images'];
             }
             if ($preview) {
                 $data['preview'] = $preview;
             }
             return array($data, $param['com']);
         } else {
             return array($html, $param['com']);
         }
     }, $args, $re);
     //$html=$dhtml[0];
     //кэш этого место в infrajs в getHTML
     return $dhtml;
 }