Confirm the action: docs.demo
return function () {
$self = url('/@object/@action/' . urlencode('security/admin_methods'));
if ( ! extension_loaded('pdo_sqlite')) {
return '<div class="alert alert-warning">This demo needs the pdo_sqlite extension.</div>';
}
$key = 'docs_demo_admin_methods';
$guard = _class('csrf_guard');
$seed = fn () => [1 => ['name' => 'Apples', 'active' => 1], 2 => ['name' => 'Pears', 'active' => 0], 3 => ['name' => 'Plums', 'active' => 1]];
if ( ! is_array($_SESSION[$key]['rows'] ?? null) || (isset($_POST['reset']) && $guard->check())) {
$_SESSION[$key] = ['rows' => $seed(), 'wall' => []];
}
$db = clone db();
$db->DB_TYPE = 'pdo_sqlite';
$db->DB_PREFIX = '';
$db->LOG_ALL_QUERIES = false;
$db->LOG_SLOW_QUERIES = false;
$db->ERROR_AUTO_REPAIR = false;
$class = main()->load_class_file('db_driver_pdo_sqlite', 'classes/db/');
$db->db = new $class(['name' => ':memory:']);
$db->_connected = true;
$db->_tried_to_connect = true;
$pdo = $db->db->db_connect_id;
$pdo->exec('CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, active INTEGER)');
$insert = $pdo->prepare('INSERT INTO items (id, name, active) VALUES (?, ?, ?)');
foreach ($_SESSION[$key]['rows'] as $id => $row) {
$insert->execute([(int) $id, (string) $row['name'], (int) $row['active']]);
}
// What a site sets with $PROJECT_CONF['csrf_guard']['ENABLED_FOR']['admin'] = true, for this request only
$enabled = $guard->ENABLED;
$enabled_for = $guard->ENABLED_FOR;
$log_errors = $guard->LOG_ERRORS;
$guard->ENABLED = true;
$guard->ENABLED_FOR['admin'] = true;
$guard->LOG_ERRORS = false;
// admin_methods with the admin wall row kept for the page (common()->admin_wall_add() goes through the admin_methods object)
$base = _class('admin_methods');
$methods = new class() extends yf_admin_methods {
public $wall = [];
public function admin_wall_add($data = [])
{
$this->wall[] = (string) ($data[0] ?? '');
return true;
}
};
main()->modules['admin_methods'] = $methods;
$answer = null;
$list = '';
try {
$do = $_GET['do'] ?? '';
if (in_array($do, ['active', 'delete', 'clone_item'], true)) {
$params = ['table' => 'items', 'db' => $db, 'input_id' => (int) ($_GET['row'] ?? 0)];
if ($do === 'clone_item') {
$params['on_before_update'] = function (&$sql) {
$sql['name'] = mb_substr($sql['name'] . ' (copy)', 0, 60);
};
}
// the method redirects to its list (?object=...): this page does it itself
$no_redirect = $GLOBALS['no_redirect'] ?? null;
$GLOBALS['no_redirect'] = true;
ob_start();
try {
$result = (string) $methods->$do($params);
} finally {
$echoed = (string) ob_get_clean();
$GLOBALS['no_redirect'] = $no_redirect;
}
if ($methods->wall) {
$rows = [];
foreach ($db->get_all('SELECT id, name, active FROM items ORDER BY id LIMIT 12') as $row) {
$rows[(int) $row['id']] = ['name' => (string) $row['name'], 'active' => (int) $row['active']];
}
$_SESSION[$key]['rows'] = $rows;
$_SESSION[$key]['wall'] = array_slice(array_merge((array) ($_SESSION[$key]['wall'] ?? []), $methods->wall), -5);
}
if (is_ajax()) {
// the list script reads the bare answer ("1" / "0" of active), not a page
$answer = $echoed . $result;
} elseif ($result === '') {
$answer = js_redirect($self);
} else {
// the confirm form (a GET) or the refusal (a POST without the token)
$answer = '<div class="docs-demo-answer">' . $result . '</div><p><a href="' . $self . '">Back to the list</a></p>';
}
}
if ($answer === null) {
$list = table($db->get_all('SELECT id, name, active FROM items ORDER BY id'), [
'no_pages' => 1,
'condensed' => 1,
// what the admin section does by itself while the admin guard is on
'post_buttons' => true,
'id' => 'id',
])
->text('id')
->text('name')
->btn_active('', $self . '?do=active&row=%d')
->btn_clone('', $self . '?do=clone_item&row=%d')
->btn_delete('', $self . '?do=delete&row=%d');
}
} finally {
main()->modules['admin_methods'] = $base;
$guard->ENABLED = $enabled;
$guard->ENABLED_FOR = $enabled_for;
$guard->LOG_ERRORS = $log_errors;
}
if ($answer !== null && is_ajax()) {
no_graphics(true);
echo $answer;
exit;
}
if ($answer !== null) {
return $answer;
}
asset('yf_js_admin');
$wall = '';
foreach (array_reverse((array) ($_SESSION[$key]['wall'] ?? [])) as $line) {
$wall .= '<li>' . _prepare_html($line, 0) . '</li>';
}
$intro = '<p class="docs-demo-intro">The generic list actions of <code>yf_admin_methods</code> (<code>active</code>, <code>delete</code>,
<code>clone_item</code>, and the POST of <code>add</code> / <code>edit</code>) that many admin modules call, with the admin CSRF guard on
(<code>$PROJECT_CONF[\'csrf_guard\'][\'ENABLED_FOR\'][\'admin\'] = true</code>, here for this request only). The buttons work as before:
<b>Active</b> and <b>Delete</b> post by ajax with the session token in the <code>X-CSRF-Token</code> header (<code>yf_js_admin</code>),
<b>Clone</b> carries <code>data-yf-post</code> and is sent as a POST form with the token. A plain GET of the same URL (a link from another
site, an image tag) gets the confirm form and changes nothing, an ajax GET gets 403, a POST without the token is refused. With the guard
off (the default) the actions answer a GET as they always did. The rows live in your session (an SQLite copy in memory per request);
the admin wall row of each change is listed below instead of being stored. Classes: <code>yf_admin_methods</code>,
<code>yf_csrf_guard</code>, <code>yf_table2</code>.</p>';
$forged = '<p>Try the forged requests: <a class="docs-demo-get" href="' . $self . '?do=active&row=1">open the toggle URL of row 1 by GET</a>.</p>';
$reset = '<form method="post" action="' . $self . '"><input type="hidden" name="reset" value="1">'
. '<input type="hidden" name="' . _prepare_html($guard->TOKEN_NAME, 0) . '" value="' . $guard->session_token() . '">'
. '<button type="submit" class="btn btn-default btn-outline-secondary btn-sm">Reset the rows</button></form>';
return $intro . '<div class="docs-demo-admin-methods">' . $list . '</div>' . $forged
. '<h4>Admin wall</h4><ul class="docs-demo-wall">' . ($wall ?: '<li>No change yet.</li>') . '</ul>' . $reset;
};