Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

РЖД передает привет #1

Merged
merged 6 commits into from
Mar 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 10 additions & 15 deletions library/ZFE/Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,30 +94,25 @@ protected function _initDoctrine()

$dbConfig = Zend_Registry::get('config')->doctrine;

$host = $dbConfig->host;
$port = $dbConfig->port;
$schema = $dbConfig->schema;
$username = $dbConfig->username;
$password = $dbConfig->password;
$persistent = $dbConfig->persistent ? 'true' : 'false';
$driver = $dbConfig->driver ?? : 'mysql';

$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING, Doctrine_Core::MODEL_LOADING_CONSERVATIVE);
$manager->setAttribute(Doctrine_Core::ATTR_SEQNAME_FORMAT, $dbConfig->schema . '.%s');
$manager->setAttribute(Doctrine_Core::ATTR_TBLNAME_FORMAT, $dbConfig->schema . '.%s');
$manager->setAttribute(Doctrine_Core::ATTR_SEQNAME_FORMAT, ('pgsql' === $driver) ? '%s' : $schema . '.%s');
$manager->setAttribute(Doctrine_Core::ATTR_TBLNAME_FORMAT, ('pgsql' === $driver) ? '%s' : $schema . '.%s');
$manager->setAttribute(Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES, true);
$manager->setAttribute(Doctrine_Core::ATTR_QUERY_CLASS, 'ZFE_Query');

spl_autoload_register(['Doctrine_Core', 'modelsAutoload']);

Doctrine_Core::loadModels($dbConfig->models_path);

$host = $dbConfig->host;
$port = $dbConfig->port;
$schema = $dbConfig->schema;
$username = $dbConfig->username;
$password = $dbConfig->password;
$persistent = $dbConfig->persistent ? 'true' : 'false';
$driver = isset($dbConfig->driver) ? $dbConfig->driver : 'mysql';

// У нас не настолько все универсально, что бы можно было конфигом изменять СУБД.
// Конечно, хорошо бы сделать универсальное подключение на случай перехода
// на PostgreSQL или Oracle Database, но оставим это переосмысление на будущее.
$dsn = "{$driver}:host={$host};port={$port};dbname={$schema}";

if ('mysql' === $driver) {
$dsn .= ";persistent={$persistent}";
}
Expand Down
3 changes: 3 additions & 0 deletions library/ZFE/Controller/Action/Helper/Download.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ public function direct($path, $url, $name)
case 'apache':
Zend_Controller_Action_HelperBroker::getStaticHelper('DownloadApache')->direct($path, $name);
break;
case 'php':
Zend_Controller_Action_HelperBroker::getStaticHelper('DownloadPhp')->direct($path, $name);
break;
default:
$this->abort(500, 'В конфигурации не указан не поддерживаемый веб-сервер');
}
Expand Down
13 changes: 11 additions & 2 deletions library/ZFE/Controller/Action/Helper/DownloadNginx.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,18 @@ public function direct($path, $url, $name)
$response = $this->getResponse();
$response->clearAllHeaders();
$response->clearBody();

$mime = mime_content_type($path);
if ($mime === false) {
$mime = 'application/octet-stream';
}

$response->setHeader('Content-Description', 'File Transfer');
$response->setHeader('Content-Type', 'application/octet-stream');
$response->setHeader('Content-Transfer-Encoding', 'binary');
$response->setHeader('Content-Type', $mime);

// @see https://stackoverflow.com/q/7285372
// $response->setHeader('Content-Transfer-Encoding', 'binary');

$response->setHeader('Content-Disposition', 'attachment; filename="' . $name . '"');
$response->setHeader('Expires', '0');
$response->setHeader('Cache-Control', 'must-revalidate');
Expand Down
52 changes: 52 additions & 0 deletions library/ZFE/Controller/Action/Helper/DownloadPhp.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

/*
* ZFE – платформа для построения редакторских интерфейсов.
*/

/**
* Помощник отправки файла средствами php-сервера через авторизацию приложения.
*
* @see https://habr.com/post/151795/
*/
class ZFE_Controller_Action_Helper_DownloadPhp extends Zend_Controller_Action_Helper_Abstract
{
/**
* Отправить файл средствами php-сервера через авторизацию приложения.
*
* @param string $path путь до файла в файловой системе
* @param string $name новое имя файла
*/
public function direct($path, $name)
{
if (file_exists($path)) {
// если этого не сделать файл будет читаться в память полностью!
if (ob_get_level()) {
ob_end_clean();
}

// заставляем браузер показать окно сохранения файла
header('Content-Description: File Transfer');

$mime = mime_content_type($path);
if ($mime === false) {
$mime = 'application/octet-stream';
}
header('Content-Type: ' . $mime);

header('Content-Disposition: attachment; filename=' . $name);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));

// читаем файл и отправляем его пользователю
readfile($path);
exit;
} else {
$this->abort(404, 'Файл не найден');
}
}

}
4 changes: 2 additions & 2 deletions library/ZFE/Form/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@ protected function _initializePrefixes()

$this->addPrefixPath(
$config->appnamespace . '_Form_Element',
APPLICATION_PATH . '/forms/elements',
APPLICATION_PATH . '/forms/Element',
'element'
);

$this->addElementPrefixPath(
$config->appnamespace . '_Form_Decorator',
$config->appnamespace . '/Form/Decorator',
APPLICATION_PATH . '/forms/Decorator',
'decorator'
);

Expand Down
11 changes: 9 additions & 2 deletions library/ZFE/Model/AbstractRecord/MultiCheckOrSelect.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,11 @@ trait ZFE_Model_AbstractRecord_MultiCheckOrSelect
* Получить настройки поля выбора нескольких записей другой таблицы из списка.
*
* @param string $field
* @param array $multiOptions опционально заданный список значений списка, по умолчанию - $alias::getKeyValueList()
*
* @return array|bool
*/
public static function getMultiCheckOrSelectOptions($field)
public static function getMultiCheckOrSelectOptions($field, $multiOptions = [])
{
// Проверяем, является ли поле автокомплитом
if ( ! key_exists($field, static::$multiCheckOrSelectCols)) {
Expand All @@ -49,7 +50,13 @@ public static function getMultiCheckOrSelectOptions($field)
}

$alias = $options['relAlias'];
$options['multiOptions'] = $alias::getKeyValueList();

// не будем пересобирать варианты, если они уже собраны
if ( ! empty($multiOptions)) {
$options['multiOptions'] = $multiOptions;
} else {
$options['multiOptions'] = $alias::getKeyValueList();
}

return $options;
}
Expand Down
16 changes: 16 additions & 0 deletions library/ZFE/Utilites.php
Original file line number Diff line number Diff line change
Expand Up @@ -199,4 +199,20 @@ public static function timeToSec($time)

return $seconds;
}

/**
* Сформировать аббревиатуру из текста.
*
* @param string $text
*
* @return string
*/
public static function makeAbbr(string $text)
{
if (preg_match_all('/\b(\w)/u', mb_strtoupper($text), $m)) {
return implode('', $m[1]);
} else {
return $text;
}
}
}