Класс Form
Объект $Form:
Объект для работы с формами ввода данных
class Form extends \Cms\Site\Base { … }
Свойства
$html
$Form->html
var $html;
Методы
init()
$Form->init();
Инициализация
function init() {
if (!parent::init()) return;
$Auth = $this->Auth();
$Main = $this->Main();
$Form = $this->Form();
$Page = $Main->Page();
if (isset($_GET['a']) && strlen($a = strtolower(preg_replace("~[^a-zA-Z0-9]~", "", strval($_GET['a']))))) {
$can = strtolower(preg_replace("~[^_a-zA-Z0-9]~", "", strtr($_GET['a'], "-", "_")));
if ($can == "delete") {
if (!$Page->can($can)) return;
} elseif (!strlen($Page->id) && strlen($Page->parent) && ($Parent = $Main->load($Page->parent))) {
# 2013-08-14
if (!$Page->can($can) && !$Page->can("edit") && !$Parent->can($can) && !$Parent->can("add") && !$Parent->can("edit")) return;
} else {
if (!$Page->can($can) && !$Page->can("edit")) return;
}
$function = "display{$a}Form";
if (method_exists($Page, $function)) $result = $Page->$function();
elseif (method_exists($Form, $function)) $result = $Form->$function($Page);
else return;
if (is_object($result)) $document = $result;
elseif (is_array($result)) $document = new \Cms\Site\Form\Document($result, $Page);
elseif (is_string($result)) return $Main->redirect($result, 303);
else return;
if ($_GET['t'] === 'frame') $document->id = 'form' . time();
$this->html = $this->display($document);
}
}
types()
$Form->types();
Получение списка типов полей
Возвращает: array
function types() {
return array(
"text" => "Текстовое поле",
"password" => "Ввод пароля",
"checkbox" => "Флажок (да/нет)",
"email" => "Адрес e-mail",
"select" => "Раскрывающийся список",
"select2" => "Раскрывающийся список 2",
"radio" => "Переключатель",
"multiple" => "Множественный список",
"multiple2" => "Множественный список 2",
"textarea" => "Многострочный текст",
"tinymce" => "Визуальный редактор",
"date" => "Дата без времени",
"datetime" => "Дата и время",
"file" => "Выбор файла",
"upload2" => "Загрузка файлов",
"image" => "Выбор изображения",
"captcha" => "Проверка на человека (CAPTCHA)",
"hidden" => "Скрытое поле",
"label" => "Заголовок группы",
"static" => "Нередактируемый текст",
"submit" => "Кнопка сохранения",
);
}
display()
$Form->display($document, $options=null);
Отображение
Параметры:
Имя | Описание |
---|---|
$document |
Описание формы |
$options |
Параметры формы |
Возвращает: string
function display($document, $options = null) {
if (!is_object($document)) return;
if (is_string($options)) $options = array( 'action' => $options );
if (!is_array($options)) $options = array();
if ($options['id']) $document->id = $options['id'];
else $options['id'] = $document->id();
$options['html'] = $document->display();
return $this->Main()->Display()->callTemplate('display', 'form', null, $options);
}
displayDocument()
$Form->displayDocument($document);
Отображение полей формы
Параметры:
Имя | Описание |
---|---|
$document |
Описание формы |
Возвращает: string
function displayDocument($document) {
if (!is_object($document)) return;
return $document->display();
}
load()
$Form->load($form, &$object);
Загрузка информации о полях формы и обработка введенных в форму значений
Параметры:
Имя | Описание |
---|---|
$form |
Имя формы |
$object |
Объект с данными |
function load($form, &$object) {
if (is_object($object)) {
$Page = $object;
} elseif (is_array($object)) {
$Page = new \Cms\Site\Form\Wrapper($object);
}
if ($document = $this->loadDocument($form, $Page)) {
foreach ($document->fieldList as $Field) {
$Field->request();
}
}
return $document;
}
loadDocument()
$Form->loadDocument($form, $Page=null);
Загрузка информации о полях формы без обработки введенных в форму значений
Параметры:
Имя | Описание |
---|---|
$form |
Имя формы |
$Page |
Объект с данными |
Возвращает: Cms\Root\Form\Document
|
null
function loadDocument($form, $Page = null) {
$App = $this->App();
if (($position = strpos($form, '.')) !== false) {
$suffix = substr($form, $position);
if ($suffix === '.xml') {
if ($file = $App->getAbsolutePath('cms/form/' . $form)) {
return $this->loadDocumentXML($file, $Page);
}
}
} elseif (strpos($form, '/') !== false) {
if ($file = $App->getAbsolutePath('cms/form/' . $form. '.xml')) {
return $this->loadDocumentXML($file, $Page);
}
} elseif ($file = $App->getAbsolutePath('cms/form/' . $form . '.xml')) {
return $this->loadDocumentXML($file, $Page);
} elseif ($file = $App->getAbsolutePath('cms/html/form.' . $form . '.php')) {
return $this->loadDocumentPHP($file, $Page);
}
}
loadField()
$Form->loadField($a);
Загрузка информации о поле
Параметры:
Имя | Описание |
---|---|
$a |
Массив с информацией |
function loadField($a) {
if (is_object($a)) {
$node = $a;
} elseif (is_array($a)) {
$form = new \Cms\Site\Form\Document;
$node = $form->createElement("field");
foreach ($a as $name => $value) {
if ($name == "options" && is_array($value)) {
$name = "code";
$value = "return " . var_export($value, true);
} elseif ($name == "value" && is_array($value)) {
# 2014-02-04
$value = implode("|", $value);
}
$node->setAttribute($name, $value);
}
} else {
return;
}
$App = $this->App();
$type = $node->getAttribute('type');
if (!$type) {
if ($node->getAttribute('name') === 'submit') {
$node->setAttribute('type', $type = 'submit');
} else {
$node->setAttribute('type', $type = 'text');
}
}
$class = $App->getClass('form_field_' . $type);
if (class_exists($class)) return new $class($node);
$class = $App->rootPrefix . substr($class, strlen($App->sitePrefix));
if (class_exists($class)) return new $class($node);
$class = $App->getClass('form_field_base');
if (class_exists($class)) return new $class($node);
$class = $App->rootPrefix . substr($class, strlen($App->sitePrefix));
if (class_exists($class)) return new $class($node);
return new \Cms\Root\Form\Field\Base($node);
}
check()
$Form->check($document);
Проверка введенных значений
Параметры:
Имя | Описание |
---|---|
$document |
Описание формы |
function check($document) {
if (!is_object($document)) return;
$r = true;
foreach ($document->fieldList as $Field) {
if (!empty($e = $Field->check())) {
$this->addError($e);
$r = false;
}
}
if (!$r) {
foreach ($document->fieldList as $Field) {
$Field->cleanup();
}
}
return $r;
}
store()
$Form->store($document);
Сохранение данных формы
Параметры:
Имя | Описание |
---|---|
$document |
Описание формы |
function store($document) {
if (!is_object($document)) {
return;
}
if ($_POST) {
foreach ($document->fieldList as $Field) {
$Field->store();
}
return $this->check($document);
}
}
getHtml()
$Form->getHtml($document);
Получение данных формы в виде HTML.
Параметры:
Имя | Описание |
---|---|
$document |
Описание формы |
function getHtml($document) {
if (!is_object($document)) return;
$html = '';
foreach ($document->fieldList as $Field) $html .= $Field->html();
$html = '<table class="mail">' . $html . '</table>';
return $html;
}
getText()
$Form->getText($document);
Получение данных формы в виде текста
Параметры:
Имя | Описание |
---|---|
$document |
Описание формы |
function getText($document) {
if (!is_object($document)) return;
$text = '';
foreach ($document->fieldList as $Field) $text .= $Field->text();
return $text;
}
checkEmail()
$Form->checkEmail($email);
function checkEmail($email) {
return preg_match('~^[-_\\.a-z0-9]+@([a-z0-9][-a-z0-9]*)(\\.[a-z0-9][-a-z0-9]*)+$~i', $email);
}
checkDate()
$Form->checkDate($value);
function checkDate($value) {
return preg_match('~^\\d\\d\\d\\d-\\d\\d-\\d\\d$~', $value);
}
checkTime()
$Form->checkTime($value);
function checkTime($value) {
return preg_match('~^\\d\\d:\\d\\d$~', $value);
}
checkDateTime()
$Form->checkDateTime($value);
function checkDateTime($value) {
return preg_match('~^\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d$~', $value);
}
checkMonth()
$Form->checkMonth($value);
function checkMonth($value) {
return preg_match('~^\\d\\d\\d\\d-\\d\\d$~', $value);
}
checkWeek()
$Form->checkWeek($value);
function checkWeek($value) {
return preg_match('~^\\d\\d\\d\\d-W\\d\\d$~', $value);
}
loadDocumentXML()
$Form->loadDocumentXML($xml, $Page=null);
function loadDocumentXML($xml, $Page = null) {
$document = new \Cms\Site\Form\Document($xml, $Page);
if (!$document->error) return $document;
$this->setError($document->error);
}
loadDocumentPHP()
$Form->loadDocumentPHP($file, $Page=null);
name [type] =default label: * ~match < ?code? > # info
function loadDocumentPHP($file, $Page = null) {
if ($F = @fopen($file, "r")) {
$xml = array();
$xml[0] = "<group>\n";
while (($line = fgets($F)) !== false) {
/// name [type] =default label: * ~match < ?code? > # info
$line = trim($line);
$name = $type = $default = $label = $required = $match = $code = $info = null;
if (preg_match("~^[-_a-zA-Z0-9]+~", $line, $m)) {
$name = $m[0];
} else continue;
$line = trim(substr($line, strlen($m[0])));
if ($line[0] == "[") {
if (($x = strpos($line, "]")) === false) continue;
if (!strlen($type = trim(substr($line, 1, $x - 1)))) $type = "text";
$line = trim(substr($line, $x + 1));
}
if ($line[0] == "=") {
$line = trim(substr($line, 1));
$char = $line[0];
if ($char == '"' || $char == "'") {
$line = substr($line, 1);
if (($x = strpos($line, $char)) === false) continue;
$default = substr($line, 0, $x);
$line = trim(substr($line, $x + 1));
} else {
if (preg_match("~^\S+~", $line, $m)) {
$default = $m[0];
$line = trim(substr($line, strlen($m[0])));
} else continue;
}
}
if (($x = strpos($line, ":")) !== false) {
$label = substr($line, 0, $x);
$line = trim(substr($line, $x + 1));
}
if ($line[0] == "*") {
$required = "Y";
$line = trim(substr($line, 1));
}
if ($line[0] == "~") {
$line = substr($line, 1);
$char = $line[0];
if (($char >= 'a' && $char <= 'z') || ($char >= 'A' || $char <= 'Z') || ($char >= '0' && $char <= '9')) {
if (preg_match("~^\S+~", $line, $m)) {
$match = $m[0];
$line = trim(substr($line, strlen($m[0])));
} else continue;
} else {
$line = substr($line, 1);
if (($x = strpos($line, $char)) === false) continue;
$match = substr($line, 0, $x + 1);
$line = substr($line, $x + 1);
if (preg_match("~^\S+~", $line, $m)) {
$match .= $m[0];
$line = substr($line, strlen($m[0]));
}
$line = trim($line);
}
}
if ($line[0] == "<" && $line[1] == "?") {
if (($x = strpos($line, "?" . ">")) === false) continue;
$code = trim(substr($line, 2, $x - 2));
$line = trim(substr($line, $x + 2));
}
if ($line[0] == "#") {
$info = trim(substr($line, 1));
}
if ($name == "submit") $xml[1] = "</group>";
$xml[$name] = "<field"
. (isset($name) ? " name=\"" . htmlspecialchars($name) . "\"" : "")
. (isset($type) ? " type=\"" . htmlspecialchars($type) . "\"" : "")
. (isset($label) ? " label=\"" . htmlspecialchars($label) . "\"" : "")
. (isset($required) ? " required=\"" . htmlspecialchars($required) . "\"" : "")
. (isset($default) ? " default=\"" . htmlspecialchars($default) . "\"" : "")
. (isset($match) ? " match=\"" . htmlspecialchars($match) . "\"" : "")
. (isset($info) ? " info=\"" . htmlspecialchars($info) . "\"" : "")
. (isset($code) ? "><" . "?php\n" . $code . "\n?" . "></field>\n" : " />\n")
;
}
$xml[1] = "</group>\n";
$xml = "<form>\n" . implode("", $xml) . "</form>\n";
fclose($F);
$this->{'_xml'} = $xml;
return $this->loadDocumentXML($xml, $Page);
}
}
requestDate()
$Form->requestDate($value);
function requestDate($value) {
if (strlen($value)) {
$time = 0;
if (!$time) if ($value == "now") {
$time = time();
}
if (!$time) if (preg_match("~\\b(\\d{1,2})[\\.,/](\\d{1,2})[\\.,/](\\d{2}(\\d{2})?)\\b~", $value, $m)) {
if (strlen($m[3]) == 2) {
if ($m[3] < 50) $m[3] = 2000 + $m[3];
else $m[3] += 1900;
}
$time = strtotime(sprintf("%4d-%02d-%02d", $m[3], $m[2], $m[1]));
}
if (!$time) if (preg_match("~\\b(\\d{2}(\\d{2})?)[-/](\\d{1,2})[-/](\\d{1,2})\\b~", $value, $m)) {
if (strlen($m[1]) == 2) {
if ($m[1] < 50) $m[1] += 2000;
else $m[1] += 1900;
}
$time = strtotime(sprintf("%4d-%02d-%02d", $m[1], $m[3], $m[4]));
}
if ($time) {
return date("Y-m-d", $time);
}
}
}
requestDateTime()
$Form->requestDateTime($value);
function requestDateTime($value) {
if (strlen($value)) {
if (strpos($value, 'T') !== false) $value = strtr($value, 'T', ' ');
$time = 0;
if (!$time) if ($value == "now") {
# $time = time();
# 2024-08-13 Без секунд
$time = strtotime(date('Y-m-d H:i:00'));
}
if (!$time) if (preg_match("~\\b(\\d{1,2})[\\.,/](\\d{1,2})[\\.,/](\\d{2}(\\d{2})?)\\b~", $value, $m)) {
if (strlen($m[3]) == 2) {
if ($m[3] < 50) $m[3] = 2000 + $m[3];
else $m[3] += 1900;
}
$time = strtotime($date_part = sprintf("%4d-%02d-%02d", $m[3], $m[2], $m[1]));
}
if (!$time) if (preg_match("~\\b(\\d{2}(\\d{2})?)[-/](\\d{1,2})[-/](\\d{1,2})\\b~", $value, $m)) {
if (strlen($m[1]) == 2) {
if ($m[1] < 50) $m[1] += 2000;
else $m[1] += 1900;
}
$time = strtotime($date_part = sprintf("%4d-%02d-%02d", $m[1], $m[3], $m[4]));
}
if ($time) {
if (preg_match("~\\b(\\d{1,2}):(\\d{1,2})(:(\\d{1,2}))?\\b~", $value, $m)) {
$time_part = sprintf(" %02d:%02d:%02d", $m[1], $m[2], $m[3]);
$xtime = strtotime($date_part . $time_part);
if ($xtime > 0) $time = $xtime;
}
return date("Y-m-d H:i:s", $time);
}
}
}
displayConfForm()
$Form->displayConfForm($Page, $form='conf');
function displayConfForm($Page, $form = 'conf') {
if ($form === 'conf') if (preg_match('~^conf[-_][-\\w]+$~', $_GET['form'], $m)) $form = $m[0];
$root = $this->root();
$Conf = $this->Conf();
$Auth = $this->Auth();
$Main = $this->Main();
$Form = $this->Form();
$Conf->set("robots_txt", @file_get_contents("$root/robots.txt"));
$_yandex_verification = $Conf->get("yandex_verification");
$_google_verification = $Conf->get("google_verification");
$_mailru_verification = $Conf->get("mailru_verification");
$_admin_password = $Conf->get("admin_password");
$document = $Form->load($form, $Conf->data);
if ($Form->store($document)) {
foreach ($document->fields as $name => $field) if (substr($name, 0, 5) === 'menu-') if (is_string($field->value)) {
if (is_array($value = json_decode($field->value, true))) $Conf->set($name, $value);
}
if (is_array($Conf->data)) foreach ($Conf->data as $k => $v) if (is_string($v) && strpos($v, "\r") !== false) {
$v = str_replace("\r", "", $v);
$Conf->data[$k] = $v;
}
if (strlen($robots_txt = $Conf->get("robots_txt"))) {
$robots_file = "$root/robots.txt";
if (@trim(file_get_contents($robots_file)) !== trim($robots_txt)) {
@file_put_contents($robots_file, "$robots_txt\n") && @chmod($robots_file, 0666);
}
unset($Conf->data['robots_txt']);
}
if (strlen($sitemap_xml = $Conf->get("sitemap_xml"))) if (file_exists("$root$sitemap_xml")) {
@unlink("$root/sitemap.xml");
@copy("$root$sitemap_xml", "$root/sitemap.xml") && @chmod("$root/sitemap.xml", 0666);
@unlink("$root$sitemap_xml");
unset($Conf->data['sitemap_xml']);
}
if (strlen($yandex_verification = $Conf->get("yandex_verification"))) {
if (preg_match("~^(yandex_)?(\w+?)(\.html)?$~", $yandex_verification, $m)) {
$s = " ";
$verification_code = $m[2];
$verification_file = "$root/yandex_{$verification_code}.html";
if (!file_exists($verification_file)) {
@file_put_contents($verification_file, "<html>\n$s<head>\n$s$s<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n$s</head>\n$s<body>Verification: {$verification_code}</body>\n</html>\n") && @chmod($verification_file, 0666);
}
}
}
if (strlen($google_verification = $Conf->get("google_verification"))) {
if (preg_match("~^(google)?(\w+?)(\.html)?$~", $google_verification, $m)) {
$verification_code = $m[2];
$verification_file = "$root/google{$verification_code}.html";
if (!file_exists($verification_file)) {
@file_put_contents($verification_file, "google-site-verification: google{$verification_code}.html\n") && @chmod($verification_file, 0666);
}
}
}
if (strlen($mailru_verification = $Conf->get("mailru_verification"))) {
if (preg_match("~^(wmail_)?(\w+?)(\.html)?$~", $mailru_verification, $m)) {
$verification_code = $m[2];
$verification_file = "$root/wmail_{$verification_code}.html";
if (!file_exists($verification_file)) {
@file_put_contents($verification_file, "<html>\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n</head>\n<body>Verification: {$verification_code}</body>\n</html>\n") && @chmod($verification_file, 0666);
}
}
}
if ($_admin_password != $Conf->get("admin_password")) {
$Auth->logoutAll($Conf->get("admin_login"));
}
if ($Conf->save()) {
return $Page->href();
}
}
return $document;
}
displayMenuForm()
$Form->displayMenuForm($Page, $form='menu');
function displayMenuForm($Page, $form = 'menu') {
$Conf = $this->Conf();
$Form = $this;
$data = array();
$menu = strval($_GET['menu']);
$menuData = $Conf->get('menu-' . $menu);
$menuLevel = intval($Conf->get('menu-' . $menu . '-level'));
if (!$menuData && !is_array($menuData)) return;
if (!is_array($menuData)) $menuData = array();
$data['list'] = $menuData;
$document = $Form->load($form, $data);
if (isset($document->fields['list'])) $document->fields['list']->level = $menuLevel;
if ($Form->store($document)) {
if (is_array($menuData = $data['list']) || is_array($menuData = @json_decode($data['list'], true))) {
if (!$menuData) $menuData = 'Y';
$Conf->set('menu-' . $menu, $menuData);
if ($Conf->save()) {
return $Page->href();
}
}
}
return $document;
}
displayTableForm()
$Form->displayTableForm($Page);
function displayTableForm($Page) {
if ($_GET['table'] === '') {
$tableClass = $this->App()->getClass('data_table');
$Table = new $tableClass;
$Table->enable = 'Y';
return $Table->displayPageForm();
} elseif (strlen($table = strval($_GET['table']))) {
if ($Table = $this->Main()->Storage()->getTable($table)) {
return $Table->displayPageForm();
}
}
}
displayFieldForm()
$Form->displayFieldForm($Page);
function displayFieldForm($Page) {
if (strlen($table = strval($_GET['table']))) {
if ($Table = $this->Main()->Storage()->getTable($table)) {
if ($_GET['field'] === '') {
$fieldClass = $this->App()->getClass('data_field');
$Field = new $fieldClass($Table->getName());
$Field->enable = 'Y';
return $Field->displayPageForm();
}
if (strlen($field = strval($_GET['field']))) {
if ($Field = $Table->getField($field)) {
return $Field->displayPageForm();
}
}
}
}
}
displayModuleForm()
$Form->displayModuleForm($Page);
function displayModuleForm($Page) {
if (strlen($module = strval($_GET['module']))) {
if ($Type = $this->Main()->Modules()->getModule($module)) {
return $Type->displayPageForm();
}
}
}
displayPropertyForm()
$Form->displayPropertyForm($Page);
function displayPropertyForm($Page) {
if (strlen($module = strval($_GET['module']))) {
if ($Type = $this->Main()->Modules()->getModule($module)) {
if (strlen($property = strval($_GET['property']))) {
if ($Property = $Type->getProperty($property)) {
return $Property->displayPageForm();
}
}
}
}
}