Skip to content
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
10 changes: 7 additions & 3 deletions docs/DataTables-Advanced.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@ $dt->from('users')
->addPermanentSelect('users.role', 'users.last_login_at')
->setColumns('id', 'name', 'email')
->addRender('name', static fn (string $name, array $row) =>
sprintf('%s <small>(%s)</small>', htmlspecialchars($name), $row['role'])
sprintf(
'%s <small>(%s)</small>',
htmlspecialchars($name, ENT_QUOTES, 'UTF-8'),
htmlspecialchars((string) $row['role'], ENT_QUOTES, 'UTF-8')
)
);
```

Expand Down Expand Up @@ -149,8 +153,8 @@ You almost never need this, but for completeness:
use InitPHP\Database\Utils\Datatables\Renderer;

$renderer = new Renderer();
$renderer->add('email', fn (string $e) => '<a>' . $e . '</a>');
$renderer->add('name', fn (string $n) => strtoupper($n));
$renderer->add('email', fn (string $e) => '<a>' . htmlspecialchars($e, ENT_QUOTES, 'UTF-8') . '</a>');
$renderer->add('name', fn (string $n) => htmlspecialchars(strtoupper($n), ENT_QUOTES, 'UTF-8'));

$dt = new Datatables($db, null, $renderer);
$dt->setColumns('id', 'name', 'email');
Expand Down
12 changes: 9 additions & 3 deletions docs/DataTables-Introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ DB::createImmutable([
'password' => '...',
]);

header('Content-Type: application/json');
// Always send a JSON content type: the response echoes the request back in
// "post", and a page served as text/html would run markup in it.
header('Content-Type: application/json; charset=utf-8');

echo (new Datatables(DB::getDatabase()))
->from('users')
Expand All @@ -58,14 +60,18 @@ $('#users').DataTable({
ajax: '/api/users/datatables',
columns: [
{ data: 'id', title: 'ID' },
{ data: 'name', title: 'Name' },
{ data: 'email', title: 'Email' },
// DataTables writes cell values into the page as HTML. Text columns must
// use the text() renderer so that "<img onerror=…>" shows up as text.
{ data: 'name', title: 'Name', render: $.fn.dataTable.render.text() },
{ data: 'email', title: 'Email', render: $.fn.dataTable.render.text() },
{ data: 'created_at', title: 'Created' }
]
});
</script>
```

> **Escape cell values.** DataTables.js puts what the server returns into the page as HTML. Names, e-mail addresses and any other user-supplied column must go through `render: $.fn.dataTable.render.text()` on the client, or through `htmlspecialchars()` in a server-side [renderer](DataTables-Renderers.md#security--always-escape-on-the-way-out) when you build the HTML yourself. Otherwise a user who registers with `<img src=x onerror=…>` as their name runs script in the browser of whoever opens the table.

The `columns[].data` keys on the client must match the column names you registered with `setColumns()` on the server. See [DataTables — Bootstrap recipe](Recipe-DataTables-Bootstrap.md) for a complete page.

## The response envelope
Expand Down
35 changes: 25 additions & 10 deletions docs/DataTables-Renderers.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,19 @@ Now every `email` cell in the response is an `<a>` element. The unrendered `emai
$dt->setColumns('id', 'first_name', 'last_name', 'full_name')
->addPermanentSelect('first_name', 'last_name')
->addRender('full_name', fn (mixed $_value, array $row) =>
trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? ''))
htmlspecialchars(
trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')),
ENT_QUOTES,
'UTF-8'
)
);
```

`full_name` does not have to exist in the database — it is a virtual column. The trick:

1. `setColumns()` declares it (so the client has an index for it).
2. `addPermanentSelect()` ensures the source columns (`first_name`, `last_name`) ride along on every SELECT (see [Advanced](DataTables-Advanced.md)).
3. The renderer composes the value from those siblings.
3. The renderer composes the value from those siblings and escapes it, because the cell is inserted into the page as HTML.

## Formatting timestamps

Expand Down Expand Up @@ -87,8 +91,8 @@ $dt->from('users')
// Client
columns: [
{ data: 'id', title: 'ID' },
{ data: 'name', title: 'Name' },
{ data: 'actions', title: '', orderable: false, searchable: false }
{ data: 'name', title: 'Name', render: $.fn.dataTable.render.text() }, // user text, no PHP renderer
{ data: 'actions', title: '', orderable: false, searchable: false } // HTML built (and escaped) in PHP
]
```

Expand All @@ -97,9 +101,10 @@ columns: [
## Mutating sibling columns

```php
$dt->addRender('name', static fn (string $name, array $row) =>
$row['is_admin'] ? '👑 ' . $name : $name
);
$dt->addRender('name', static function (string $name, array $row): string {
$safe = htmlspecialchars($name, ENT_QUOTES, 'UTF-8'); // the cell is rendered as HTML
return $row['is_admin'] ? '👑 ' . $safe : $safe;
});
```

`$row` is passed by **value** — the helper copies it before invoking the renderer. So you can read sibling columns freely; you cannot use a renderer to mutate a sibling that has its own renderer running later.
Expand All @@ -111,6 +116,7 @@ $response = $dt->toArray();
foreach ($response['data'] as $i => $row) {
$response['data'][$i] = transformRow($row);
}
header('Content-Type: application/json; charset=utf-8'); // not text/html: "post" echoes the request
echo json_encode($response);
```

Expand All @@ -119,8 +125,8 @@ echo json_encode($response);
`addRender()` overwrites any previous registration for the same column:

```php
$dt->addRender('name', fn ($v) => strtoupper($v));
$dt->addRender('name', fn ($v) => strtolower($v));
$dt->addRender('name', fn ($v) => htmlspecialchars(strtoupper($v), ENT_QUOTES, 'UTF-8'));
$dt->addRender('name', fn ($v) => htmlspecialchars(strtolower($v), ENT_QUOTES, 'UTF-8'));
// strtolower wins.
```

Expand All @@ -143,7 +149,16 @@ $dt->addRender('name', static fn (string $name) =>
$dt->addRender('name', static fn (string $name) => "<strong>{$name}</strong>");
```

DataTables.js sets cell innerHTML directly — anything you emit ends up in the DOM as-is.
DataTables.js sets cell innerHTML directly — anything you emit ends up in the DOM as-is. That applies to columns **without** a renderer too: a plain `name` value goes into the cell unescaped. On the client, give every user-supplied text column `render: $.fn.dataTable.render.text()`:

```js
columns: [
{ data: 'name', title: 'Name', render: $.fn.dataTable.render.text() },
{ data: 'email', title: 'Email', render: $.fn.dataTable.render.text() }
]
```

Do not combine the two on the same column: a column that already returns escaped HTML from PHP would be escaped a second time by `text()`. Choose one place per column.

## Renderers and the count queries

Expand Down
13 changes: 10 additions & 3 deletions docs/Recipe-DataTables-Bootstrap.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,11 @@ That's the entire server side. Three database round-trips (`recordsTotal`, `reco
},
columns: [
{ data: 'id', title: 'ID' },
{ data: 'name', title: 'Name' },
{ data: 'email', title: 'Email' },
{ data: 'role', title: 'Role' },
// These columns hold user-supplied text, and DataTables inserts cell
// values as HTML: render them as text so markup is not executed.
{ data: 'name', title: 'Name', render: $.fn.dataTable.render.text() },
{ data: 'email', title: 'Email', render: $.fn.dataTable.render.text() },
{ data: 'role', title: 'Role', render: $.fn.dataTable.render.text() },
{ data: 'created_at', title: 'Joined' },
{ data: 'actions', title: '', orderable: false, searchable: false }
],
Expand All @@ -137,6 +139,7 @@ That's the entire server side. Three database round-trips (`recordsTotal`, `reco
|---|---|
| `setColumns('id', 'name', ...)` order | `columns[].data` order |
| `setColumns(null)` for actions | `orderable: false, searchable: false` |
| user-supplied text (`name`, `email`, `role`) | `render: $.fn.dataTable.render.text()` — cells are inserted as HTML |
| `addPermanentSelect("'' AS actions")` | gives the renderer something to attach to |
| `addRender('actions', fn)` | renders the cell HTML |
| `where('active', 1)` | invisible filter — only active users ever leave the server |
Expand Down Expand Up @@ -179,6 +182,8 @@ The response will look like:
If `Users` is already a Model with soft deletes:

```php
header('Content-Type: application/json; charset=utf-8');

echo (new Datatables(new App\Model\Users()))
->setColumns('id', 'name', 'email', 'role', 'created_at', null)
// … renderers …
Expand All @@ -200,6 +205,8 @@ if ($activeOnly) {
$dt->where('active', 1);
}

header('Content-Type: application/json; charset=utf-8');

echo $dt->setColumns('id', 'name', 'email', 'role', 'created_at', null)
->addRender(/* … */);
```
Expand Down
11 changes: 10 additions & 1 deletion docs/Recipe-Upsert.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,15 @@ final class Upserter
$columns = array_keys($row);
$params = [];

// Identifiers cannot be bound as parameters, and the column names come
// from the *keys* of $row. Allow only plain identifiers, so a key such as
// "name) VALUES (1); DROP TABLE items; --" can never reach the SQL.
foreach ([$table, $conflictColumn, ...$columns] as $identifier) {
if (preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/D', (string) $identifier) !== 1) {
throw new \InvalidArgumentException('Invalid identifier.');
}
}

foreach ($row as $key => $value) {
$params[':' . $key] = $value;
}
Expand All @@ -177,7 +186,7 @@ final class Upserter
}
```

> The wrapper interpolates `$table` and `$conflictColumn` directly — identifiers cannot be bound. **Only call it with hard-coded strings**, never user input.
> The wrapper interpolates `$table`, `$conflictColumn` and the **keys of `$row`** directly — identifiers cannot be bound. The check at the top rejects anything that is not a plain identifier, but it only guards the syntax, not which tables and columns are allowed: pass hard-coded table and column names, and never use `$_POST` (or any other request array) as `$row`. Build `$row` from the fixed set of fields you expect, as the example below does.

Use it:

Expand Down
Loading