#336: Integration of symfony/http-foundation request

This commit is contained in:
Igor Scheller 2017-08-29 16:21:25 +02:00
parent 73175e2b64
commit cc01c906ba
27 changed files with 230 additions and 258 deletions

View File

@ -16,10 +16,11 @@
"require": { "require": {
"php": ">=5.6.4", "php": ">=5.6.4",
"erusev/parsedown": "1.6.*", "erusev/parsedown": "1.6.*",
"twbs/bootstrap": "^3.3" "twbs/bootstrap": "^3.3",
"symfony/http-foundation": "^3.3"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^6.2" "phpunit/phpunit": "^6.3"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {

View File

@ -20,9 +20,6 @@ return [
// Set to development to enable debugging messages // Set to development to enable debugging messages
'environment' => 'production', 'environment' => 'production',
// Site URL, used to generate links on page (https://example.com/[sub-dir/])
'url' => null,
// URL to the angel faq and job description // URL to the angel faq and job description
'faq_url' => 'https://events.ccc.de/congress/2013/wiki/Static:Volunteers', 'faq_url' => 'https://events.ccc.de/congress/2013/wiki/Static:Volunteers',
@ -58,7 +55,7 @@ return [
// Blowfish '$2y$13' // Blowfish '$2y$13'
// SHA-256 '$5$rounds=5000' // SHA-256 '$5$rounds=5000'
// SHA-512 '$6$rounds=5000' // SHA-512 '$6$rounds=5000'
'crypt_alg' => '$6$rounds=5000', // SHA-512 'crypt_alg' => '$6$rounds=5000',
'min_password_length' => 8, 'min_password_length' => 8,

View File

@ -127,7 +127,7 @@ function angeltype_edit_controller()
if (!$supporter_mode) { if (!$supporter_mode) {
if ($request->has('name')) { if ($request->has('name')) {
$result = AngelType_validate_name($request->get('name'), $angeltype); $result = AngelType_validate_name($request->postData('name'), $angeltype);
$angeltype['name'] = $result->getValue(); $angeltype['name'] = $result->getValue();
if (!$result->isValid()) { if (!$result->isValid()) {
$valid = false; $valid = false;

View File

@ -27,10 +27,10 @@ function shift_entry_add_controller()
} }
$shift = Shift($shift_id); $shift = Shift($shift_id);
$shift['Name'] = $room_array[$shift['RID']];
if ($shift == null) { if ($shift == null) {
redirect(page_link_to('user_shifts')); redirect(page_link_to('user_shifts'));
} }
$shift['Name'] = $room_array[$shift['RID']];
$type_id = 0; $type_id = 0;
if ($request->has('type_id') && preg_match('/^\d*$/', $request->input('type_id'))) { if ($request->has('type_id') && preg_match('/^\d*$/', $request->input('type_id'))) {

View File

@ -62,7 +62,7 @@ function shift_edit_controller()
$angeltypes = select_array(AngelTypes(), 'id', 'name'); $angeltypes = select_array(AngelTypes(), 'id', 'name');
$shifttypes = select_array(ShiftTypes(), 'id', 'name'); $shifttypes = select_array(ShiftTypes(), 'id', 'name');
$needed_angel_types = select_array(NeededAngelTypes_by_shift($shift_id), 'id', 'count'); $needed_angel_types = select_array(NeededAngelTypes_by_shift($shift_id), 'angel_type_id', 'count');
foreach (array_keys($angeltypes) as $angeltype_id) { foreach (array_keys($angeltypes) as $angeltype_id) {
if (!isset($needed_angel_types[$angeltype_id])) { if (!isset($needed_angel_types[$angeltype_id])) {
$needed_angel_types[$angeltype_id] = 0; $needed_angel_types[$angeltype_id] = 0;
@ -117,17 +117,22 @@ function shift_edit_controller()
$msg .= error(_('The ending time has to be after the starting time.'), true); $msg .= error(_('The ending time has to be after the starting time.'), true);
} }
foreach ($needed_angel_types as $needed_angeltype_id => $needed_angeltype_name) { foreach ($needed_angel_types as $needed_angeltype_id => $count) {
if ($request->has('type_' . $needed_angeltype_id) && test_request_int('type_' . $needed_angeltype_id)) { $needed_angel_types[$needed_angeltype_id] = 0;
$needed_angel_types[$needed_angeltype_id] = trim($request->input('type_' . $needed_angeltype_id));
$queryKey = 'type_' . $needed_angeltype_id;
if ($request->has($queryKey)) {
if (test_request_int($queryKey)) {
$needed_angel_types[$needed_angeltype_id] = trim($request->input($queryKey));
} else { } else {
$valid = false; $valid = false;
$msg .= error(sprintf( $msg .= error(sprintf(
_('Please check your input for needed angels of type %s.'), _('Please check your input for needed angels of type %s.'),
$needed_angeltype_name $angeltypes[$needed_angeltype_id]
), true); ), true);
} }
} }
}
if ($valid) { if ($valid) {
$shift['shifttype_id'] = $shifttype_id; $shift['shifttype_id'] = $shifttype_id;

View File

@ -47,7 +47,7 @@ function user_delete_controller()
$request = request(); $request = request();
if ($request->has('user_id')) { if ($request->has('user_id')) {
$user_source = User($request->get('user_id')); $user_source = User($request->query->get('user_id'));
} else { } else {
$user_source = $user; $user_source = $user;
} }
@ -68,7 +68,7 @@ function user_delete_controller()
if ( if (
!( !(
$request->has('password') $request->has('password')
&& verify_password($request->post('password'), $user['Passwort'], $user['UID']) && verify_password($request->postData('password'), $user['Passwort'], $user['UID'])
) )
) { ) {
$valid = false; $valid = false;
@ -307,9 +307,9 @@ function user_password_recovery_set_new_controller()
if ( if (
$request->has('password') $request->has('password')
&& strlen($request->post('password')) >= config('min_password_length') && strlen($request->postData('password')) >= config('min_password_length')
) { ) {
if ($request->post('password') != $request->post('password2')) { if ($request->postData('password') != $request->postData('password2')) {
$valid = false; $valid = false;
error(_('Your passwords don\'t match.')); error(_('Your passwords don\'t match.'));
} }
@ -319,7 +319,7 @@ function user_password_recovery_set_new_controller()
} }
if ($valid) { if ($valid) {
set_password($user_source['UID'], $request->post('password')); set_password($user_source['UID'], $request->postData('password'));
success(_('Password saved.')); success(_('Password saved.'));
redirect(page_link_to('login')); redirect(page_link_to('login'));
} }
@ -363,7 +363,7 @@ function user_password_recovery_start_controller()
_('Password recovery'), _('Password recovery'),
sprintf( sprintf(
_('Please visit %s to recover your password.'), _('Please visit %s to recover your password.'),
page_link_to_absolute('user_password_recovery', ['token' => $token]) page_link_to('user_password_recovery', ['token' => $token])
) )
); );
success(_('We sent an email containing your password recovery link.')); success(_('We sent an email containing your password recovery link.'));

View File

@ -32,9 +32,10 @@ date_default_timezone_set($config->get('timezone'));
/** /**
* Initialize Request * Initialize Request
*
* @var Request $request
*/ */
$request = new Request(); $request = Request::createFromGlobals();
$request->create($_GET, $_POST, $_SERVER, config('url'));
$request::setInstance($request); $request::setInstance($request);
/** /**

View File

@ -1,5 +1,7 @@
<?php <?php
use Engelsystem\Http\Request;
/** /**
* Return currently active locale * Return currently active locale
* *
@ -62,14 +64,20 @@ function gettext_locale($locale = null)
*/ */
function make_langselect() function make_langselect()
{ {
$url = $_SERVER['REQUEST_URI'] . (strpos($_SERVER['REQUEST_URI'], '?') > 0 ? '&' : '?') . 'set_locale='; $request = Request::getInstance();
$items = []; $items = [];
foreach (config('locales') as $locale => $name) { foreach (config('locales') as $locale => $name) {
$url = url($request->getPathInfo(), ['set_locale' => $locale]);
$items[] = toolbar_item_link( $items[] = toolbar_item_link(
htmlspecialchars($url) . $locale, htmlspecialchars($url),
'', '',
'<img src="pic/flag/' . $locale . '.png" alt="' . $name . '" title="' . $name . '"> ' . $name sprintf(
'<img src="%s" alt="%s" title="%2$s"> %2$s',
url('pic/flag/' . $locale . '.png'),
$name
)
); );
} }
return $items; return $items;

View File

@ -81,7 +81,8 @@ function admin_groups()
'privileges[]', 'privileges[]',
$privilege['desc'] . ' (' . $privilege['name'] . ')', $privilege['desc'] . ' (' . $privilege['name'] . ')',
$privilege['group_id'] != '', $privilege['group_id'] != '',
$privilege['id'] $privilege['id'],
'privilege-' . $privilege['name']
); );
$privileges_html .= sprintf( $privileges_html .= sprintf(
'<tr><td><input type="checkbox" name="privileges[]" value="%s" %s /></td> <td>%s</td> <td>%s</td></tr>', '<tr><td><input type="checkbox" name="privileges[]" value="%s" %s /></td> <td>%s</td> <td>%s</td></tr>',
@ -112,7 +113,7 @@ function admin_groups()
} }
$group = DB::select('SELECT * FROM `Groups` WHERE `UID`=? LIMIT 1', [$group_id]); $group = DB::select('SELECT * FROM `Groups` WHERE `UID`=? LIMIT 1', [$group_id]);
$privileges = $request->get('privileges'); $privileges = $request->postData('privileges');
if (!is_array($privileges)) { if (!is_array($privileges)) {
$privileges = []; $privileges = [];
} }

View File

@ -62,14 +62,15 @@ function admin_news()
', ',
[ [
time(), time(),
$request->post('eBetreff'), $request->postData('eBetreff'),
$request->post('eText'), $request->postData('eText'),
$user['UID'], $user['UID'],
$request->has('eTreffen') ? 1 : 0, $request->has('eTreffen') ? 1 : 0,
$news_id $news_id
] ]
); );
engelsystem_log('News updated: ' . $request->post('eBetreff'));
engelsystem_log('News updated: ' . $request->postData('eBetreff'));
success(_('News entry updated.')); success(_('News entry updated.'));
redirect(page_link_to('news')); redirect(page_link_to('news'));
break; break;

View File

@ -110,11 +110,14 @@ function admin_rooms()
} }
foreach ($angeltypes as $angeltype_id => $angeltype) { foreach ($angeltypes as $angeltype_id => $angeltype) {
if ( $angeltypes_count[$angeltype_id] = 0;
$request->has('angeltype_count_' . $angeltype_id) $queryKey = 'angeltype_count_' . $angeltype_id;
&& preg_match('/^\d{1,4}$/', $request->input('angeltype_count_' . $angeltype_id)) if (!$request->has($queryKey)) {
) { continue;
$angeltypes_count[$angeltype_id] = $request->input('angeltype_count_' . $angeltype_id); }
if (preg_match('/^\d{1,4}$/', $request->input($queryKey))) {
$angeltypes_count[$angeltype_id] = $request->input($queryKey);
} else { } else {
$valid = false; $valid = false;
$msg .= error(sprintf(_('Please enter needed angels for type %s.'), $angeltype), true); $msg .= error(sprintf(_('Please enter needed angels for type %s.'), $angeltype), true);

View File

@ -135,16 +135,14 @@ function admin_shifts()
} elseif ($request->input('angelmode') == 'manually') { } elseif ($request->input('angelmode') == 'manually') {
$angelmode = 'manually'; $angelmode = 'manually';
foreach ($types as $type) { foreach ($types as $type) {
if ( if (preg_match('/^\d+$/', trim($request->input('type_' . $type['id'], 0)))) {
$request->has('type_' . $type['id']) $needed_angel_types[$type['id']] = trim($request->input('type_' . $type['id'], 0));
&& preg_match('/^\d+$/', trim($request->input('type_' . $type['id'])))
) {
$needed_angel_types[$type['id']] = trim($request->input('type_' . $type['id']));
} else { } else {
$valid = false; $valid = false;
error(sprintf(_('Please check the needed angels for team %s.'), $type['name'])); error(sprintf(_('Please check the needed angels for team %s.'), $type['name']));
} }
} }
if (array_sum($needed_angel_types) == 0) { if (array_sum($needed_angel_types) == 0) {
$valid = false; $valid = false;
error(_('There are 0 angels needed. Please enter the amounts of needed angels.')); error(_('There are 0 angels needed. Please enter the amounts of needed angels.'));
@ -306,7 +304,7 @@ function admin_shifts()
} }
} elseif ($request->has('submit')) { } elseif ($request->has('submit')) {
if ( if (
!$request->has('admin_shifts_shifts') !isset($_SESSION['admin_shifts_shifts'])
|| !isset($_SESSION['admin_shifts_types']) || !isset($_SESSION['admin_shifts_types'])
|| !is_array($_SESSION['admin_shifts_shifts']) || !is_array($_SESSION['admin_shifts_shifts'])
|| !is_array($_SESSION['admin_shifts_types']) || !is_array($_SESSION['admin_shifts_types'])

View File

@ -261,7 +261,7 @@ function admin_user()
`Handy` = ?, `Handy` = ?,
`Alter` =?, `Alter` =?,
`DECT` = ?, `DECT` = ?,
' . ($user_source['email_by_human_allowed'] ? '`email` = ' . DB::getPdo()->quote($request->post('eemail')) . ',' : '') . ' ' . ($user_source['email_by_human_allowed'] ? '`email` = ' . DB::getPdo()->quote($request->postData('eemail')) . ',' : '') . '
`jabber` = ?, `jabber` = ?,
`Size` = ?, `Size` = ?,
`Gekommen`= ?, `Gekommen`= ?,
@ -272,34 +272,34 @@ function admin_user()
WHERE `UID` = ? WHERE `UID` = ?
LIMIT 1'; LIMIT 1';
DB::update($sql, [ DB::update($sql, [
$request->post('eNick'), $request->postData('eNick'),
$request->post('eName'), $request->postData('eName'),
$request->post('eVorname'), $request->postData('eVorname'),
$request->post('eTelefon'), $request->postData('eTelefon'),
$request->post('eHandy'), $request->postData('eHandy'),
$request->post('eAlter'), $request->postData('eAlter'),
$request->post('eDECT'), $request->postData('eDECT'),
$request->post('ejabber'), $request->postData('ejabber'),
$request->post('eSize'), $request->postData('eSize'),
$request->post('eGekommen'), $request->postData('eGekommen'),
$request->post('eAktiv'), $request->postData('eAktiv'),
$force_active, $force_active,
$request->post('eTshirt'), $request->postData('eTshirt'),
$request->post('Hometown'), $request->postData('Hometown'),
$user_id, $user_id,
]); ]);
engelsystem_log( engelsystem_log(
'Updated user: ' . $request->post('eNick') . ', ' . $request->post('eSize') 'Updated user: ' . $request->postData('eNick') . ', ' . $request->postData('eSize')
. ', arrived: ' . $request->post('eVorname') . ', arrived: ' . $request->postData('eVorname')
. ', active: ' . $request->post('eAktiv') . ', active: ' . $request->postData('eAktiv')
. ', tshirt: ' . $request->post('eTshirt') . ', tshirt: ' . $request->postData('eTshirt')
); );
$html .= success('Änderung wurde gespeichert...' . "\n", true); $html .= success('Änderung wurde gespeichert...' . "\n", true);
break; break;
case 'change_pw': case 'change_pw':
if ($request->post('new_pw') != '' && $request->post('new_pw') == $request->post('new_pw2')) { if ($request->postData('new_pw') != '' && $request->postData('new_pw') == $request->postData('new_pw2')) {
set_password($user_id, $request->post('new_pw')); set_password($user_id, $request->postData('new_pw'));
$user_source = User($user_id); $user_source = User($user_id);
engelsystem_log('Set new password for ' . User_Nick_render($user_source)); engelsystem_log('Set new password for ' . User_Nick_render($user_source));
$html .= success('Passwort neu gesetzt.', true); $html .= success('Passwort neu gesetzt.', true);

View File

@ -127,8 +127,8 @@ function guest_register()
} }
} }
if ($request->has('password') && strlen($request->post('password')) >= $min_password_length) { if ($request->has('password') && strlen($request->postData('password')) >= $min_password_length) {
if ($request->post('password') != $request->post('password2')) { if ($request->postData('password') != $request->postData('password2')) {
$valid = false; $valid = false;
$msg .= error(_('Your passwords don\'t match.'), true); $msg .= error(_('Your passwords don\'t match.'), true);
} }
@ -234,7 +234,7 @@ function guest_register()
// Assign user-group and set password // Assign user-group and set password
$user_id = DB::getPdo()->lastInsertId(); $user_id = DB::getPdo()->lastInsertId();
DB::insert('INSERT INTO `UserGroups` (`uid`, `group_id`) VALUES (?, -2)', [$user_id]); DB::insert('INSERT INTO `UserGroups` (`uid`, `group_id`) VALUES (?, -2)', [$user_id]);
set_password($user_id, $request->post('password')); set_password($user_id, $request->postData('password'));
// Assign angel-types // Assign angel-types
$user_angel_types_info = []; $user_angel_types_info = [];
@ -403,7 +403,7 @@ function guest_login()
if (count($login_user) > 0) { if (count($login_user) > 0) {
$login_user = $login_user[0]; $login_user = $login_user[0];
if ($request->has('password')) { if ($request->has('password')) {
if (!verify_password($request->post('password'), $login_user['Passwort'], $login_user['UID'])) { if (!verify_password($request->postData('password'), $login_user['Passwort'], $login_user['UID'])) {
$valid = false; $valid = false;
error(_('Your password is incorrect. Please try it again.')); error(_('Your password is incorrect. Please try it again.'));
} }

View File

@ -1,6 +1,7 @@
<?php <?php
use Engelsystem\Database\DB; use Engelsystem\Database\DB;
use Engelsystem\Http\Request;
/** /**
* Publically available page to feed the news to feed readers * Publically available page to feed the news to feed readers
@ -44,14 +45,15 @@ function user_atom()
*/ */
function make_atom_entries_from_news($news_entries) function make_atom_entries_from_news($news_entries)
{ {
$request = Request::getInstance();
$html = '<?xml version="1.0" encoding="utf-8"?> $html = '<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"> <feed xmlns="http://www.w3.org/2005/Atom">
<title>Engelsystem</title> <title>Engelsystem</title>
<id>' . $_SERVER['HTTP_HOST'] <id>' . $request->getHttpHost()
. htmlspecialchars(preg_replace( . htmlspecialchars(preg_replace(
'#[&?]key=[a-f\d]{32}#', '#[&?]key=[a-f\d]{32}#',
'', '',
$_SERVER['REQUEST_URI'] $request->getRequestUri()
)) ))
. '</id> . '</id>
<updated>' . date('Y-m-d\TH:i:sP', $news_entries[0]['Datum']) . '</updated>' . "\n"; <updated>' . date('Y-m-d\TH:i:sP', $news_entries[0]['Datum']) . '</updated>' . "\n";
@ -64,10 +66,11 @@ function make_atom_entries_from_news($news_entries)
function make_atom_entry_from_news($news_entry) function make_atom_entry_from_news($news_entry)
{ {
return ' <entry> return '
<entry>
<title>' . htmlspecialchars($news_entry['Betreff']) . '</title> <title>' . htmlspecialchars($news_entry['Betreff']) . '</title>
<link href="' . page_link_to_absolute('news_comments', ['nid' => $news_entry['ID']]) . '"/> <link href="' . page_link_to('news_comments', ['nid' => $news_entry['ID']]) . '"/>
<id>' . preg_replace('#^https?://#', '', page_link_to_absolute('news')) . '-' . $news_entry['ID'] . '</id> <id>' . preg_replace('#^https?://#', '', page_link_to('news_comments', ['nid' => $news_entry['ID']])) . '</id>
<updated>' . date('Y-m-d\TH:i:sP', $news_entry['Datum']) . '</updated> <updated>' . date('Y-m-d\TH:i:sP', $news_entry['Datum']) . '</updated>
<summary>' . htmlspecialchars($news_entry['Text']) . '</summary> <summary>' . htmlspecialchars($news_entry['Text']) . '</summary>
</entry>' . "\n"; </entry>' . "\n";

View File

@ -186,9 +186,9 @@ function user_news()
$html = '<div class="col-md-12"><h1>' . news_title() . '</h1>' . msg(); $html = '<div class="col-md-12"><h1>' . news_title() . '</h1>' . msg();
$isMeeting = $request->post('treffen'); $isMeeting = $request->postData('treffen');
if ($request->has('text') && $request->has('betreff') && in_array('admin_news', $privileges)) { if ($request->has('text') && $request->has('betreff') && in_array('admin_news', $privileges)) {
if (!$request->has('treffen') || !in_array('admin_news', $privileges)) { if (!$request->has('treffen')) {
$isMeeting = 0; $isMeeting = 0;
} }
DB::insert(' DB::insert('
@ -197,13 +197,13 @@ function user_news()
', ',
[ [
time(), time(),
$request->post('betreff'), $request->postData('betreff'),
$request->post('text'), $request->postData('text'),
$user['UID'], $user['UID'],
$isMeeting, $isMeeting,
] ]
); );
engelsystem_log('Created news: ' . $_POST['betreff'] . ', treffen: ' . $isMeeting); engelsystem_log('Created news: ' . $request->postData('betreff') . ', treffen: ' . $isMeeting);
success(_('Entry saved.')); success(_('Entry saved.'));
redirect(page_link_to('news')); redirect(page_link_to('news'));
} }

View File

@ -101,14 +101,14 @@ function user_settings_password($user_source)
$request = request(); $request = request();
if ( if (
!$request->has('password') !$request->has('password')
|| !verify_password($request->post('password'), $user_source['Passwort'], $user_source['UID']) || !verify_password($request->postData('password'), $user_source['Passwort'], $user_source['UID'])
) { ) {
error(_('-> not OK. Please try again.')); error(_('-> not OK. Please try again.'));
} elseif (strlen($request->post('new_password')) < config('min_password_length')) { } elseif (strlen($request->postData('new_password')) < config('min_password_length')) {
error(_('Your password is to short (please use at least 6 characters).')); error(_('Your password is to short (please use at least 6 characters).'));
} elseif ($request->post('new_password') != $request->post('new_password2')) { } elseif ($request->postData('new_password') != $request->postData('new_password2')) {
error(_('Your passwords don\'t match.')); error(_('Your passwords don\'t match.'));
} elseif (set_password($user_source['UID'], $request->post('new_password'))) { } elseif (set_password($user_source['UID'], $request->postData('new_password'))) {
success(_('Password saved.')); success(_('Password saved.'));
} else { } else {
error(_('Failed setting password.')); error(_('Failed setting password.'));

View File

@ -229,8 +229,8 @@ function view_user_shifts()
'shifts_table' => msg() . $shiftCalendarRenderer->render(), 'shifts_table' => msg() . $shiftCalendarRenderer->render(),
'ical_text' => '<h2>' . _('iCal export') . '</h2><p>' . sprintf( 'ical_text' => '<h2>' . _('iCal export') . '</h2><p>' . sprintf(
_('Export of shown shifts. <a href="%s">iCal format</a> or <a href="%s">JSON format</a> available (please keep secret, otherwise <a href="%s">reset the api key</a>).'), _('Export of shown shifts. <a href="%s">iCal format</a> or <a href="%s">JSON format</a> available (please keep secret, otherwise <a href="%s">reset the api key</a>).'),
page_link_to_absolute('ical', ['key' => $user['api_key']]), page_link_to('ical', ['key' => $user['api_key']]),
page_link_to_absolute('shifts_json_export', ['key' => $user['api_key']]), page_link_to('shifts_json_export', ['key' => $user['api_key']]),
page_link_to('user_myshifts', ['reset' => 1]) page_link_to('user_myshifts', ['reset' => 1])
) . '</p>', ) . '</p>',
'filter' => _('Filter') 'filter' => _('Filter')

View File

@ -144,10 +144,15 @@ function form_multi_checkboxes($names, $label, $items, $selected, $disabled = []
* @param string $label * @param string $label
* @param string $selected * @param string $selected
* @param string $value * @param string $value
* @param string $id
* @return string * @return string
*/ */
function form_checkbox($name, $label, $selected, $value = 'checked') function form_checkbox($name, $label, $selected, $value = 'checked', $id = null)
{ {
if (is_null($id)) {
$id = $name;
}
return '<div class="checkbox"><label>' return '<div class="checkbox"><label>'
. '<input type="checkbox" id="' . $name . '" name="' . $name . '" value="' . $value . '" ' . '<input type="checkbox" id="' . $name . '" name="' . $name . '" value="' . $value . '" '
. ($selected ? ' checked="checked"' : '') . ' /> ' . ($selected ? ' checked="checked"' : '') . ' /> '
@ -374,7 +379,7 @@ function form_element($label, $input, $for = '')
*/ */
function form($elements, $action = '') function form($elements, $action = '')
{ {
return '<form role="form" action="' . $action . '" enctype="multipart/form-data" method="post">' . join($elements) . '</form>'; return '<form action="' . $action . '" enctype="multipart/form-data" method="post">' . join($elements) . '</form>';
} }
/** /**

View File

@ -9,24 +9,8 @@ use Engelsystem\UserHintsRenderer;
*/ */
function page_link_to($page = '', $parameters = []) function page_link_to($page = '', $parameters = [])
{ {
$parameters = http_build_query($parameters);
$page = ltrim($page, '/');
$page = str_replace('_', '-', $page); $page = str_replace('_', '-', $page);
return '/' . $page . (!empty($parameters) ? '?' . $parameters : ''); return url($page, $parameters);
}
/**
* @TODO: remove?
* @param string $page
* @param array $parameters get parameters
* @return string
*/
function page_link_to_absolute($page, $parameters = [])
{
return (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://'
. $_SERVER['HTTP_HOST']
. preg_replace("/\?.*$/", '', $_SERVER['REQUEST_URI'])
. page_link_to($page, $parameters);
} }
/** /**

View File

@ -1,4 +1,5 @@
<?php <?php
use Engelsystem\ValidationResult; use Engelsystem\ValidationResult;
/** /**
@ -168,11 +169,8 @@ function strip_request_item($name, $default_value = null)
*/ */
function test_request_int($name) function test_request_int($name)
{ {
$request = request(); $input = request()->input($name);
if ($request->has($name)) { return preg_match('/^\d*$/', $input);
return preg_match('/^\d*$/', $request->input($name));
}
return false;
} }
/** /**
@ -186,7 +184,11 @@ function strip_request_item_nl($name, $default_value = null)
{ {
$request = request(); $request = request();
if ($request->has($name)) { if ($request->has($name)) {
return preg_replace("/([^\p{L}\p{S}\p{P}\p{Z}\p{N}+\n]{1,})/ui", '', strip_tags($request->get($name))); return preg_replace(
"/([^\p{L}\p{S}\p{P}\p{Z}\p{N}+\n]{1,})/ui",
'',
strip_tags($request->input($name))
);
} }
return $default_value; return $default_value;
} }

View File

@ -1,12 +1,8 @@
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.5/phpunit.xsd"
backupGlobals="false"
bootstrap="./includes/engelsystem_provider.php" bootstrap="./includes/engelsystem_provider.php"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/6.3/phpunit.xsd"
colors="true" colors="true"
convertErrorsToExceptions="true" >
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false">
<testsuites> <testsuites>
<testsuite name="Models"> <testsuite name="Models">
<directory>./test/model/</directory> <directory>./test/model/</directory>
@ -19,7 +15,4 @@
<directory>./src/</directory> <directory>./src/</directory>
</whitelist> </whitelist>
</filter> </filter>
<php>
<const name="PHPUNIT_TESTSUITE" value="true"/>
</php>
</phpunit> </phpunit>

View File

@ -1,4 +1,7 @@
<?php <?php
use Engelsystem\Http\Request;
require_once realpath(__DIR__ . '/../includes/engelsystem_provider.php'); require_once realpath(__DIR__ . '/../includes/engelsystem_provider.php');
$free_pages = [ $free_pages = [
@ -24,12 +27,13 @@ $page = '';
$title = ''; $title = '';
$content = ''; $content = '';
$page = $request->input('p'); /** @var Request $request */
$page = $request->query->get('p');
if (empty($page)) { if (empty($page)) {
$page = $request->path(); $page = $request->path();
$page = str_replace('-', '_', $page); $page = str_replace('-', '_', $page);
} }
if (empty($page)) { if ($page == '/') {
$page = isset($user) ? 'news' : 'login'; $page = isset($user) ? 'news' : 'login';
} }

View File

@ -34,7 +34,9 @@ class Handler
*/ */
public function errorHandler($number, $string, $file, $line, $context) public function errorHandler($number, $string, $file, $line, $context)
{ {
$this->handle('error', $number, $string, $file, $line, $context); $trace = array_reverse(debug_backtrace());
$this->handle('error', $number, $string, $file, $line, $context, $trace);
} }
/** /**
@ -59,8 +61,9 @@ class Handler
* @param string $file * @param string $file
* @param int $line * @param int $line
* @param array $context * @param array $context
* @param array $trace
*/ */
protected function handle($type, $number, $string, $file, $line, $context = []) protected function handle($type, $number, $string, $file, $line, $context = [], $trace = [])
{ {
error_log(sprintf('%s: Number: %s, String: %s, File: %s:%u, Context: %s', error_log(sprintf('%s: Number: %s, String: %s, File: %s:%u, Context: %s',
$type, $type,
@ -71,13 +74,16 @@ class Handler
json_encode($context) json_encode($context)
)); ));
$file = $this->stripBasePath($file);
if ($this->environment == self::ENV_DEVELOPMENT) { if ($this->environment == self::ENV_DEVELOPMENT) {
echo '<pre style="background-color:#333;color:#ccc;z-index:1000;position:fixed;bottom:1em;padding:1em;width:97%;overflow-y:auto;">'; echo '<pre style="background-color:#333;color:#ccc;z-index:1000;position:fixed;bottom:1em;padding:1em;width:97%;max-height: 90%;overflow-y:auto;">';
echo sprintf('%s: (%s)' . PHP_EOL, ucfirst($type), $number); echo sprintf('%s: (%s)' . PHP_EOL, ucfirst($type), $number);
var_export([ var_export([
'string' => $string, 'string' => $string,
'file' => $file . ':' . $line, 'file' => $file . ':' . $line,
'context' => ($this->environment == self::ENV_DEVELOPMENT ? $context : null), 'context' => $context,
'stacktrace' => $this->formatStackTrace($trace),
]); ]);
echo '</pre>'; echo '</pre>';
die(); die();
@ -87,6 +93,44 @@ class Handler
die(); die();
} }
/**
* @param array $stackTrace
* @return array
*/
protected function formatStackTrace($stackTrace)
{
$return = [];
foreach ($stackTrace as $trace) {
$path = '';
$line = '';
if (isset($trace['file']) && isset($trace['line'])) {
$path = $this->stripBasePath($trace['file']);
$line = $trace['line'];
}
$functionName = $trace['function'];
$return[] = [
'file' => $path . ':' . $line,
$functionName => $trace['args'],
];
}
return $return;
}
/**
* @param string $path
* @return string
*/
protected function stripBasePath($path)
{
$basePath = realpath(__DIR__ . '/../..') . '/';
return str_replace($basePath, '', $path);
}
/** /**
* @param string $environment * @param string $environment
*/ */

View File

@ -3,97 +3,13 @@
namespace Engelsystem\Http; namespace Engelsystem\Http;
use ErrorException; use ErrorException;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
class Request class Request extends SymfonyRequest
{ {
/** @var self */ /** @var self */
protected static $instance; protected static $instance;
/** @var array of GET data */
protected $query;
/** @var array of POST data */
protected $request;
/** @var array of SERVER data */
protected $server;
/** @var string */
protected $scheme;
/** @var string */
protected $host;
/** @var string */
protected $baseUrl = '';
/** @var string */
protected $path;
/**
* Initialize request
*
* @param array $query The GET data
* @param array $request the POST data
* @param array $server the SERVER data
* @param string $baseUrl base url to use for links
*/
public function create(array $query, array $request, array $server, $baseUrl = null)
{
$this->query = $query;
$this->request = $request;
$this->server = array_merge([
'SERVER_NAME' => 'localhost',
'HTTP_HOST' => 'localhost',
'SERVER_PORT' => 80,
'REQUEST_URI' => '/',
], $server);
if (isset($this->server['HTTPS']) && $this->server['HTTPS'] == 'off') {
unset($this->server['HTTPS']);
}
$uri = $this->server['REQUEST_URI'];
$uri = '/' . ltrim($uri, '/');
$uri = explode('?', $uri);
$this->path = array_shift($uri);
$components = parse_url($baseUrl);
if (!$components) {
$components = [];
}
$this->scheme = (isset($components['scheme']) ? $components['scheme'] : ($this->isSecure() ? 'https' : 'http'));
$this->host = (isset($components['host']) ? $components['host'] : $this->server['SERVER_NAME']);
if (isset($components['path'])) {
$this->baseUrl = '/' . ltrim($components['path'], '/');
$this->path = preg_replace('~^' . preg_quote($this->baseUrl, '~') . '~i', '', $this->path);
$this->path = '/' . ltrim($this->path, '/');
}
}
public function isSecure()
{
return isset($this->server['HTTPS']);
}
/**
* Get GET input
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public function get($key, $default = null)
{
if (!empty($this->query[$key])) {
return $this->query[$key];
}
return $default;
}
/** /**
* Get POST input * Get POST input
* *
@ -101,13 +17,9 @@ class Request
* @param mixed $default * @param mixed $default
* @return mixed * @return mixed
*/ */
public function post($key, $default = null) public function postData($key, $default = null)
{ {
if (!empty($this->request[$key])) { return $this->request->get($key, $default);
return $this->request[$key];
}
return $default;
} }
/** /**
@ -119,13 +31,7 @@ class Request
*/ */
public function input($key, $default = null) public function input($key, $default = null)
{ {
$data = $this->request + $this->query; return $this->get($key, $default);
if (!empty($data[$key])) {
return $data[$key];
}
return $default;
} }
/** /**
@ -148,41 +54,19 @@ class Request
*/ */
public function path() public function path()
{ {
// @TODO: base uri? $pattern = trim($this->getPathInfo(), '/');
return $this->path;
}
public function url() return $pattern == '' ? '/' : $pattern;
{
return $this->getSchemeAndHttpHost() . $this->getBaseUrl() . '/' . $this->path();
} }
/** /**
* Return the current URL
*
* @return string * @return string
*/ */
public function root() public function url()
{ {
return $this->baseUrl; return rtrim(preg_replace('/\?.*/', '', $this->getUri()), '/');
}
public function getSchemeAndHttpHost()
{
return $this->getScheme() . '://' . $this->getHttpHost();
}
public function getScheme()
{
return $this->scheme;
}
public function getHttpHost()
{
return $this->host;
}
public function getBaseUrl()
{
return $this->baseUrl;
} }
/** /**

View File

@ -0,0 +1,27 @@
<?php
namespace Engelsystem\Routing;
use Engelsystem\Http\Request;
class UrlGenerator
{
/**
* @param string $path
* @param array $parameters
* @return string
*/
public static function to($path, $parameters = [])
{
$path = '/' . ltrim($path, '/');
$request = Request::getInstance();
$uri = $request->getUriForPath($path);
if (!empty($parameters) && is_array($parameters)) {
$parameters = http_build_query($parameters);
$uri .= '?' . $parameters;
}
return $uri;
}
}

View File

@ -4,6 +4,7 @@
use Engelsystem\Config\Config; use Engelsystem\Config\Config;
use Engelsystem\Http\Request; use Engelsystem\Http\Request;
use Engelsystem\Renderer\Renderer; use Engelsystem\Renderer\Renderer;
use Engelsystem\Routing\UrlGenerator;
/** /**
* Get or set config values * Get or set config values
@ -56,3 +57,13 @@ function view($template = null, $data = null)
return $renderer->render($template, $data); return $renderer->render($template, $data);
} }
/**
* @param string $path
* @param array $parameters
* @return string
*/
function url($path, $parameters = [])
{
return UrlGenerator::to($path, $parameters);
}