Регистр файлов

This commit is contained in:
origami11 2017-02-16 10:14:36 +03:00
parent 4fd0187ea6
commit c8958cbee0
83 changed files with 25 additions and 53 deletions

118
src/Tools/Drawing.php Normal file
View file

@ -0,0 +1,118 @@
<?php
class Drawing
{
const ALIGN_LEFT = "left";
const ALIGN_TOP = "top";
const ALIGN_BOTTOM = "bottom";
const ALIGN_CENTER = "center";
const ALIGN_RIGHT = "right";
static function drawrectnagle(&$image, $left, $top, $width, $height, $rgb)
{
$color = imagecolorallocate($image, $rgb[0], $rgb[1], $rgb[2]);
$right = $left + $width;
$bottom = $top + $height;
imageline($image, $left, $top, $right, $top, $color);
imageline($image, $right,$top, $right, $bottom, $color);
imageline($image, $left, $bottom, $right, $bottom, $color);
imageline($image, $left, $top, $left, $bottom, $color);
}
/**
* http://ru2.php.net/imagettftext
*/
static function imagettftextbox(&$image, $size, $angle, $left, $top, $color, $font, $text,
$max_width, $max_height, $align, $valign)
{
// echo $left,"\n", $top, "\n";
// echo $max_width,"\n", $max_height, "\n";
// self::drawrectnagle($image, $left, $top, $max_width, $max_height, array(0xFF,0,0));
$text_lines = explode("\n", $text); // Supports manual line breaks!
$lines = array();
$line_widths = array();
$largest_line_height = 0;
foreach ($text_lines as $block) {
$current_line = ''; // Reset current line
$words = explode(' ', $block); // Split the text into an array of single words
$first_word = true;
$last_width = 0;
for ($i = 0; $i < count($words); $i++) {
$item = $words[$i];
$dimensions = imagettfbbox($size, $angle, $font, $current_line . ($first_word ? '' : ' ') . $item);
$line_width = $dimensions[2] - $dimensions[0];
$line_height = $dimensions[1] - $dimensions[7];
$largest_line_height = max($line_height, $largest_line_height);
if ($line_width > $max_width && !$first_word) {
$lines[] = $current_line;
$line_widths[] = $last_width ? $last_width : $line_width;
$current_line = $item;
} else {
$current_line .= ($first_word ? '' : ' ') . $item;
}
if ($i == count($words) - 1) {
$lines[] = $current_line;
$line_widths[] = $line_width;
}
$last_width = $line_width;
$first_word = false;
}
if ($current_line) {
$current_line = $item;
}
}
// vertical align
$top_offset = 0;
if ($valign == self::ALIGN_CENTER) {
$top_offset = ($max_height - $largest_line_height * count($lines)) / 2;
} elseif ($valign == self::ALIGN_BOTTOM) {
$top_offset = $max_height - $largest_line_height * count($lines);
}
$top += $largest_line_height + $top_offset;
$i = 0;
foreach ($lines as $line) {
// horizontal align
$left_offset = 0;
if ($align == self::ALIGN_CENTER) {
$left_offset = ($max_width - $line_widths[$i]) / 2;
} elseif ($align == self::ALIGN_RIGHT) {
$left_offset = ($max_width - $line_widths[$i]);
}
imagettftext($image, $size, $angle, $left + $left_offset, $top + ($largest_line_height * $i), $color, $font, $line);
$i++;
}
return $largest_line_height * count($lines);
}
function imagettftextSp($image, $size, $angle, $x, $y, $color, $font, $text, $spacing = 0)
{
if ($spacing == 0)
{
imagettftext($image, $size, $angle, $x, $y, $color, $font, $text);
}
else
{
$temp_x = $x;
for ($i = 0; $i < mb_strlen($text); $i++)
{
$bbox = imagettftext($image, $size, $angle, $temp_x, $y, $color, $font, $text[$i]);
$temp_x += $spacing + ($bbox[2] - $bbox[0]);
}
}
}
}

437
src/Tools/ExcelTable.php Normal file
View file

@ -0,0 +1,437 @@
<?php
class Excel_Number
{
public $value;
function __construct($value)
{
$this->value = $value;
}
function getString()
{
return $this->value;
}
}
class Excel_DateTime
{
public $value;
function __construct($value)
{
$this->value = intval($value);
}
function getString()
{
return date('Y-m-d\TH:i:s.u', $this->value);
}
}
/**
* Клетка таблицы
*/
class TableCell
{
public $style = false;
public $value;
public $merge = false;
function __construct ($value)
{
$this->value = $value;
}
}
/**
* Ряд таблицы
*/
class TableRow
{
public $style = false;
public $cells = array();
public $height = false;
function setCell($y, $value)
{
$this->cells[$y] = new TableCell($value);
}
function setCellStyle($y, $name)
{
$this->cells[$y]->style = $name;
}
}
/**
* Таблица
*/
class ExcelTable
{
static $index;
private $name;
private $style;
protected $rows = array();
protected $splitVertical = false;
protected $splitHorizontal = false;
function __construct()
{
$this->name = "Page " . intval(self::$index ++);
}
/**
* Записать значение в клетку с заданными координатами
*/
function setCell($x, $y, $value)
{
assert(is_numeric($x) && $x > 0);
assert(is_numeric($y) && $y > 0);
if(! isset($this->rows[$x])) {
$this->rows[$x] = new TableRow();
}
$this->rows[$x]->setCell($y, $value);
}
/**
* Заполняет ряд начиная с указанного столбца значениями из массива
*/
function setRow($row, $index, array $data)
{
assert(is_numeric($index) && $index > 0);
assert(is_numeric($row) && $row > 0);
reset($data);
for ($i = $index; $i < $index + count($data); $i++) {
$this->setCell($row, $i, current($data));
next($data);
}
}
/**
* Устанавливает высоту ряда
* @param $row integer Номер ряда
* @parma $value real Высота ряда
*/
function setRowHeight ($row, $value)
{
assert(is_numeric($row) && $row > 0);
$this->rows[$row]->height = $value;
}
/**
* Устанавливает стиль ряда
* @param $row integer Номер ряда
* @parma $name string Имя стиля
*/
function setRowStyle ($row, $name)
{
assert(is_numeric($row) && $row > 0);
$this->rows[$row]->style = $name;
}
/**
* Обьединяет клетки в строке
* @param $row Номер ряда
* @param $cell Номер столбца
* @param $merge Количество клеток для обьединения
*/
function setCellMerge ($row, $cell, $merge)
{
assert(is_numeric($row) && $row > 0);
assert(is_numeric($cell) && $cell > 0);
$this->rows[$row]->cells[$cell]->merge = $merge;
}
/**
* Устанавливает стиль для клеток ряда
* @param $row integer Номер ряда
* @param $y integer Номер столбца
* @parma $name string Имя стиля
*/
function setCellStyle ($row, $y, $name)
{
if (isset($this->rows[$row]))
$this->rows[$row]->setCellStyle($y, $name);
}
/**
* Добавляет строку к таблице
*/
function addRow($index = 1, array $data = array(""))
{
assert(is_numeric($index) && $index > 0);
$offset = $this->getRows() + 1;
$this->setRow($offset, $index, $data);
return $offset;
}
/**
* Количество строк в таблице
*
* @return int
*/
function getRows()
{
return max(array_keys($this->rows));
}
/**
* Количество столбцов в строке
*
* @return int
*/
function getRowCells($row)
{
return max(array_keys($row->cells));
}
/**
* Разделяет таблицу на две части по вертикали
* @param $n integer Количество столбцов слева
*/
function splitVertical($n)
{
$this->splitVertical = $n;
}
/**
* Разделяет таблицу на две части по горизонтали
* @param $n integer Количество столбцов сверху
*/
function splitHorizontal($n)
{
$this->splitHorizontal = $n;
}
/**
* Количество столбцов в таблице
*
* @return int
*/
function getColumns()
{
return max(array_map(array($this, 'getRowCells'), $this->rows));
}
function encode($s)
{
return $s;
}
/**
* Генерация клетки таблицы (Переработать)
*/
function createCell ($ncell, XMLWriter $doc, $j, $value, $setIndex) {
$doc->startElement("Cell");
if ($ncell->style) {
$doc->writeAttribute('ss:StyleID', $ncell->style);
}
if ($ncell->merge) {
$doc->writeAttribute('ss:MergeAcross', $ncell->merge);
}
if ($setIndex) {
$doc->writeAttribute('ss:Index', $j);
}
$doc->startElement("Data");
if ($value instanceof Excel_DateTime) {
$doc->writeAttribute('ss:Type', "DateTime");
$doc->text($value->getString());
} else if ($value instanceof Excel_Number) {
$doc->writeAttribute('ss:Type', "Number");
$doc->text($value->getString());
} else {
if (is_string($value)) {
$doc->writeAttribute('ss:Type', "String");
} else {
$doc->writeAttribute('ss:Type', "Number");
}
$doc->writeCData($this->encode($value));
}
$doc->endElement();
$doc->endElement();
}
/**
* Генерация таблицы
*/
public function createTable (XMLWriter $doc) {
$doc->startElement('Worksheet');
$doc->writeAttribute('ss:Name', $this->name);
$columns = $this->getColumns();
$rows = $this->getRows();
$doc->startElement('Table');
$doc->writeAttribute('ss:ExpandedColumnCount', $columns);
$doc->writeAttribute('ss:ExpandedRowCount', $rows);
// Переписать цыкл !!!!!!!
for ($i = 1; $i <= $rows; $i++) {
$doc->startElement('Row');
if (isset($this->rows[$i])) {
if ($this->rows[$i]->style) {
$doc->writeAttribute('ss:StyleID', $this->rows[$i]->style);
}
if ($this->rows[$i]->height) {
$doc->writeAttribute('ss:Height', $this->rows[$i]->height);
}
$nrow = $this->rows[$i];
// Флаг индикатор подстановки номера столбца
$setIndex = false;
for ($j = 1; $j <= $columns; $j++) {
$value = null;
if (isset($nrow->cells[$j])) {
$value = $nrow->cells[$j]->value;
}
if (!empty($value)) {
$this->createCell($nrow->cells[$j], $doc, $j, $value, $setIndex);
$setIndex = false;
} else {
$setIndex = true;
}
}
}
$doc->endElement();
}
$doc->endElement();
$this->splitPane ($doc);
$doc->endElement();
}
protected function splitPane (XMLWriter $doc) {
$doc->startElement('WorksheetOptions');
$doc->writeAttribute('xmlns', 'urn:schemas-microsoft-com:office:excel');
$doc->writeElement('FrozenNoSplit');
if ($this->splitVertical) {
$doc->writeElement('SplitVertical', $this->splitVertical);
$doc->writeElement('LeftColumnRightPane', $this->splitVertical);
}
if ($this->splitHorizontal) {
$doc->writeElement('SplitHorizontal', $this->splitHorizontal);
$doc->writeElement('TopRowBottomPane', $this->splitHorizontal);
}
if ($this->splitHorizontal && $this->splitVertical) {
$doc->writeElement('ActivePane', 0);
} else if($this->splitHorizontal) {
$doc->writeElement('ActivePane', 2);
}
$doc->endElement();
}
}
/**
* Документ
*/
class ExcelDocument {
static $ns = "urn:schemas-microsoft-com:office:spreadsheet";
private $table = array ();
protected $styles = array();
function addTable($table) {
$this->table [] = $table;
}
/**
* Добавление стиля к документу
* @param $name string Имя стиля
* @param $values array Параметры стиля
* @param $type Тип стиля
*/
function setStyle ($name, array $values, $type = 'Interior')
{
if(!isset($this->styles[$name])) {
$this->styles[$name] = array();
}
$this->styles[$name][$type] = $values;
}
/**
* Генерация стилей
*/
private function createStyles (XMLWriter $doc) {
$doc->startElement('Styles');
foreach ($this->styles as $name => $sn) {
$doc->startElement('Style');
$doc->writeAttribute('ss:ID', $name);
foreach ($sn as $type => $s) {
// Стиль Borders - составной
if ($type == 'Borders') {
$doc->startElement('Borders');
foreach ($s as $border) {
$doc->startElement('Border');
foreach ($border as $key => $value) {
$doc->writeAttribute('ss:' . $key, $value);
}
$doc->endElement();
}
$doc->endElement();
} else {
$doc->startElement($type);
foreach ($s as $key => $value) {
$doc->writeAttribute('ss:' . $key, $value);
}
$doc->endElement();
}
}
$doc->endElement();
}
$doc->endElement();
}
/**
* Преобразует переводы строки в спец символы
*/
function clean ($s) {
assert(is_string($s));
return strtr($s, array ("\n" => '&#10;'));
}
/**
* Сохраняет таблицу в формате Office 2003 XML
* http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats
*/
function save($filename)
{
$doc = new xmlWriter();
$doc->openURI($filename);
$doc->setIndent(false);
$doc->startDocument('1.0','utf-8');
$doc->startElement('Workbook');
$doc->writeAttribute('xmlns', self::$ns);
$doc->writeAttribute('xmlns:ss', self::$ns);
$this->createStyles($doc);
foreach ($this->table as $table) {
if ($table instanceof ExcelTable) {
$table->createTable($doc);
} else {
$table_data = call_user_func($table);
$table_data->createTable($doc);
unset($table_data);
}
}
$doc->endElement();
}
}

40
src/Tools/Image.php Normal file
View file

@ -0,0 +1,40 @@
<?php
class Core_Tools_Image
{
static function load($uri)
{
$e = strtolower(pathinfo($uri, PATHINFO_EXTENSION));
switch ($e) {
case 'png': return imagecreatefrompng($uri);
case 'jpeg': case 'jpg': return imagecreatefromjpeg($uri);
case 'gif': return imagecreatefromgif($uri);
}
}
static function fit($image, $prewidth, $preheight, $force = true)
{
$width = imagesx($image);
$height = imagesy($image);
$percent = min($prewidth / $width, $preheight / $height);
if ($percent > 1 && !$force) $percent = 1;
$new_width = $width * $percent;
$new_height = $height * $percent;
$image_p = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
return $image_p;
}
static function save($image, $uri)
{
$e = strtolower(pathinfo($uri, PATHINFO_EXTENSION));
switch ($e) {
case 'jpg': imagejpeg($image, $uri, 100); break;
case 'png': imagepng($image, $uri); break;
case 'gif': imagegif($image, $uri); break;
}
}
}

32
src/Tools/Password.php Normal file
View file

@ -0,0 +1,32 @@
<?php
function generatePassword($length = 9, $strength = 0) {
$vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvz';
if ($strength & 1) {
$consonants .= 'BDGHJLMNPQRSTVWXZ';
}
if ($strength & 2) {
$vowels .= "AEUY";
}
if ($strength & 4) {
$consonants .= '23456789';
}
if ($strength & 8) {
$consonants .= '@#$%';
}
$password = '';
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
if ($alt == 1) {
$password .= $consonants[(rand() % strlen($consonants))];
$alt = 0;
} else {
$password .= $vowels[(rand() % strlen($vowels))];
$alt = 1;
}
}
return $password;
}

37
src/Tools/String.php Normal file
View file

@ -0,0 +1,37 @@
<?php
// from creole
function strToArray($str)
{
$str = substr($str, 1, -1); // remove { }
$res = array();
$subarr = array();
$in_subarr = 0;
$toks = explode(',', $str);
foreach($toks as $tok) {
if ($in_subarr > 0) { // already in sub-array?
$subarr[$in_subarr][] = $tok;
if ('}' === substr($tok, -1, 1)) { // check to see if we just added last component
$res[] = $this->strToArray(implode(',', $subarr[$in_subarr]));
$in_subarr--;
}
} elseif ($tok{0} === '{') { // we're inside a new sub-array
if ('}' !== substr($tok, -1, 1)) {
$in_subarr++;
// if sub-array has more than one element
$subarr[$in_subarr] = array();
$subarr[$in_subarr][] = $tok;
} else {
$res[] = $this->strToArray($tok);
}
} else { // not sub-array
$val = trim($tok, '"'); // remove " (surrounding strings)
// perform type castng here?
$res[] = $val;
}
}
return $res;
}

94
src/Tools/TableView.php Normal file
View file

@ -0,0 +1,94 @@
<?php
class TableExcelView {
private $list = array();
private $data = array();
function setColumns(array $list) {
$this->list = $list;
}
function makeTable() {
$xls = new ExcelTable();
$xls->setRow(1, 1, array_keys($this->list));
foreach($this->data as $n => $item) {
$result = array();
foreach($this->list as $key => $c) {
if (is_callable($c)) {
$result [] = call_user_func($c, $item, $n);
} else {
if (is_numeric($item[$c])) {
$result [] = new Excel_Number($item[$c]);
} else {
$result [] = $item[$c];
}
}
}
$xls->addRow(1, $result);
}
return $xls;
}
function writeTable($data, $file) {
$this->data = $data;
$xls = new ExcelDocument();
$xls->addTable(array($this, 'makeTable'));
$xls->save($file);
}
}
class TableHTMLView {
private $list = array();
private $stack = array();
private $result = array();
function writeElement($name, $content) {
echo "<".$name.">";
echo $content;
echo "</".$name.">";
}
function startElement($name) {
array_push($this->stack, $name);
echo "<".$name.">";
}
function endElement() {
$name = array_pop($this->stack);
echo "</".$name.">";
}
function setColumns(array $list) {
$this->list = $list;
}
function writeTable($data) {
$this->startElement('table');
$this->startElement('thead');
$this->startElement('tr');
foreach($this->list as $key => $c) {
$this->writeElement('th', $key);
}
$this->endElement();
$this->endElement();
$this->startElement('tbody');
foreach($data as $n => $item) {
$this->startElement('tr');
foreach($this->list as $key => $c) {
if (is_callable($c)) {
$this->writeElement('td', call_user_func($c, $item, $n));
} else {
$this->writeElement('td', $item[$c]);
}
}
$this->endElement();
}
$this->endElement();
$this->endElement();
}
}

206
src/Tools/TemplateImage.php Normal file
View file

@ -0,0 +1,206 @@
<?php
require_once 'core/tools/drawing.php';
/**
* Формат для композиции изображений
*/
class TemplateImage
{
static $listfiles = array('jpg' => 'jpeg', 'gif' => 'gif', 'png' => 'png', 'bmp' => 'wbmp');
static $listfonts = array(
'georgia' => 'georgia.ttf',
'georgiabd' => 'georgiab.ttf',
'georgiaz' => 'georgiaz.ttf',
'times' => 'times.ttf',
'timesbd' => 'timesbd.ttf',
'arial' => 'arial.ttf',
'arialbd' => 'arialbd.ttf',
'tahoma' => 'tahoma.ttf',
'calibri' => 'calibri.ttf',
'calibribd' => 'calibrib.ttf',
'calibrii' => 'calibrii.ttf',
'' => 'arial.ttf',
'dejavu' => 'DejaVuCondensedSerif.ttf',
'dejavubd' => 'DejaVuCondensedSerifBold.ttf',
'dejavuz' =>'DejaVuCondensedSerifBoldItalic.ttf',
'dejavui' => 'DejaVuCondensedSerifItalic.ttf',
'miriad' => 'MyriadPro-Cond.ttf',
'miriadbd' => 'MyriadPro-BoldCond.ttf'
);
protected $src;
protected $context = array();
protected $data = array();
protected $base = "c:\\windows\\fonts\\";
protected $image;
protected $prepare = true;
public $debug = false;
function __construct ($template = false)
{
// assert(is_string($src));
if($template) {
$this->data = $template;
}
}
/**
* Путь к изображению
*/
function resourcePath($path)
{
assert(is_string($path));
$this->resource = $path;
}
/**
* Путь у шрифтам
*/
function fontPath($path)
{
assert(is_string($path));
$this->base = $path;
}
function set($name, $value)
{
assert(is_string($name));
$this->context['['.$name.']'] = $this->encode($value);
}
function setImage($name)
{
$this->filename = $name;
$this->image = $this->imagefromfile($name);
}
function setEmptyImage($width, $height)
{
$this->image = imagecreatetruecolor($width, $height);
}
/**
* Создает изображение из файла
*/
function imagefromfile($file)
{
assert(is_string($file));
$suffix = pathinfo($file, PATHINFO_EXTENSION);
if (array_key_exists($suffix, self::$listfiles)) {
return call_user_func('imagecreatefrom' . self::$listfiles[$suffix], $file);
}
return null;
}
function getFontFile($name)
{
assert(is_string($name));
if(array_key_exists(strtolower($name), self::$listfonts)) {
return $this->base . self::$listfonts[$name];
}
return $this->base . 'arial.ttf';
}
function fontSuffix($style)
{
if($style[0] && $style[1]) return "z";
if($style[0]) return "bd";
if($style[1]) return "i";
return "";
}
function imageText($text, $value)
{
assert(is_string($text));
$text = strtr($text, $this->context);
$size = $value->fontSize;
fb('font-style');
fb($value->fontStyle);
$fontfile = $this->getFontFile($value->fontFamily . $this->fontSuffix($value->fontStyle));
$color = intval(substr($value->color, 1), 16);
if ($value->align[0]) {
$align = Drawing::ALIGN_LEFT;
} elseif ($value->align[2]) {
$align = Drawing::ALIGN_RIGHT;
} else {
$align = Drawing::ALIGN_CENTER;
}
if ($value->valign[0]) {
$valign = Drawing::ALIGN_TOP;
} elseif ($value->valign[1]) {
$valign = Drawing::ALIGN_CENTER;
} else {
$valign = Drawing::ALIGN_BOTTOM;
}
Drawing::imagettftextbox($this->image, $size, 0, $value->left, $value->top, $color, $fontfile, $text,
$value->width, $value->height,
$align, $valign);
}
/**
* Перекодировка текста
*/
function encode($text)
{
assert(is_string($text));
return iconv("WINDOWS-1251", "UTF-8", $text);
}
function setSize($new_width, $new_height)
{
$width = imagesx($this->image);
$height = imagesy($this->image);
if($new_height == false) {
$new_height = ceil($height * $new_width / $width);
}
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($image_p, $this->image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// imagecopyresized($image_p, $this->image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
$this->image = $image_p;
}
function prepare() {
if($this->prepare) {
$this->prepare = false;
foreach ($this->data as $value) {
$this->imageText($value->text, $value); // break;
}
}
}
/**
* Генерирует изображение из шаблона
*/
function render($file = null)
{
assert(is_string($file) || is_null($file));
$this->prepare();
if ($file == null) {
ob_start();
imagejpeg($this->image, $file, 100);
$result = ob_get_contents();
ob_clean();
return $result;
} else {
return imagejpeg($this->image, $file, 100);
}
}
}

14
src/Tools/Translit.php Normal file
View file

@ -0,0 +1,14 @@
<?php
function translit($st) {
$st = strtr($st,"абвгдеёзийклмнопрстуфхъыэ !№", "abvgdeeziyklmnoprstufh_ie__#");
$st = strtr($st,"АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ", "ABVGDEEZIYKLMNOPRSTUFH_IE");
$st = strtr($st, array(
"ж"=>"zh", "ц"=>"ts", "ч"=>"ch", "ш"=>"sh",
"щ"=>"shch","ь"=>"", "ю"=>"yu", "я"=>"ya",
"Ж"=>"ZH", "Ц"=>"TS", "Ч"=>"CH", "Ш"=>"SH",
"Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA",
"ї"=>"i", "Ї"=>"Yi", "є"=>"ie", "Є"=>"Ye"
));
return $st;
}