Yii2
Yii2 nie ma osobnego pakietu: zainstaluj veditor/veditor i skopiuj do projektu trzy pliki poniżej. Kod jest krótki, więc możesz go dopasować. Sprawdzony z Yii 2.0.55 (szablon advanced); w szablonie basic zamień przestrzenie nazw common\… na app\….
Instalacja
composer require veditor/veditor
Skopiuj pliki z tego rozdziału do common/components/VEditorComponent.php, common/components/VEditorAsset.php i common/controllers/VEditorController.php.
Konfiguracja
// common/config/main.php
'components' => [
'vEditor' => [
'class' => common\components\VEditorComponent::class,
'options' => [
'licenseKey' => getenv('VEDITOR_LICENSE_KEY') ?: '',
'aiApiKey' => getenv('OPENAI_API_KEY') ?: '', // OpenAI
'aiAnthropicKey' => getenv('ANTHROPIC_API_KEY') ?: '', // Claude (aiTextModel: claude-…)
],
'styles' => [['name' => 'Lead', 'element' => 'p', 'classes' => ['lead']]],
// 'aiFeatures' => fn ($user) => $user?->isAdmin ? null : ['transform'],
// 'aiBeforeRequest' => fn (string $feature, array $data) => true,
],
],
// frontend/config/main.php i backend/config/main.php (tam, gdzie edytor ma funkcje AI)
'controllerMap' => [
'veditor' => common\controllers\VEditorController::class, // POST index.php?r=veditor/ai, tylko zalogowani
],
options przyjmuje klucze konfiguracji serwerowej. Potrzebny jest tylko klucz API dostawcy wybranego modelu (aiAnthropicKey dla modelu claude-…, aiApiKey dla każdego innego); bez niego edytor nie pokazuje przycisków AI, zobacz Obsługiwane modele AI. Pozostałe właściwości komponentu: editor (opcje edytora), ai (opcje AI w edytorze), filePickerUrl, uploadUrl, uploadField (domyślnie upload), route (identyfikator kontrolera, domyślnie veditor), aiFeatures (tablica funkcji AI dla wszystkich użytkowników albo funkcja fn ($identity), która ją zwraca; null = wszystkie) i aiBeforeRequest (hook z konfiguracji serwerowej). Język edytora to dwie pierwsze litery Yii::$app->language.
Kontroler dopuszcza role z właściwości roles, domyślnie ['@'] (zalogowani); gość dostaje HTTP 401, użytkownik bez roli HTTP 403.
Pliki edytora publikuje AssetManager do web/assets/{hash}, więc nie potrzebujesz reguł adresów. Po zmianie pakietu są publikowane ponownie.
Widok i zapis
<?= Html::beginForm() ?>
<?= Yii::$app->vEditor->render('content', $model->content, ['height' => '400px']) ?>
<?= Html::submitButton('Zapisz') ?>
<?= Html::endForm() ?>
// w kontrolerze albo w Article::beforeSave()
$model->content = Yii::$app->vEditor->sanitize($model->content);
Dla nonce CSP ustaw $this->params['cspNonce'] w widoku albo układzie przed wyświetleniem edytora.
Trzeci argument render() przyjmuje dowolne opcje edytora, np. krótki pasek narzędzi dla komentarzy (nazwy elementów w Opcjach edytora):
<?= Yii::$app->vEditor->render('comment', $model->comment, ['toolbar' => ['bold', 'italic', 'link', '|', 'bulletedList', 'numberedList', '|', 'undo', 'redo'], 'height' => '150px']) ?>
Pasek dla wszystkich edytorów ustawisz we właściwości editor komponentu.
common/components/VEditorComponent.php
<?php
namespace common\components;
use VEditor\AiClient;
use VEditor\HtmlSanitizer;
use VEditor\Widget;
use Yii;
use yii\base\Component;
use yii\helpers\Url;
/**
* VEditor in Yii2 (documentation: Integrations → Yii2). Configuration in common/config/main.php:
*
* 'components' => [
* 'vEditor' => [
* 'class' => common\components\VEditorComponent::class,
* 'options' => [ // keys as in veditor/config.dist.php
* 'licenseKey' => getenv('VEDITOR_LICENSE_KEY') ?: '',
* 'aiApiKey' => getenv('OPENAI_API_KEY') ?: '', // OpenAI
* 'aiAnthropicKey' => getenv('ANTHROPIC_API_KEY') ?: '', // Claude (aiTextModel: claude-…)
* ],
* 'styles' => [['name' => 'Lead', 'element' => 'p', 'classes' => ['lead']]],
* ],
* ],
* 'controllerMap' => ['veditor' => common\controllers\VEditorController::class], // frontend and backend
*
* <?= Yii::$app->vEditor->render('content', $model->content) ?> // view
* $model->content = Yii::$app->vEditor->sanitize($model->content); // saving (e.g. beforeSave)
*/
class VEditorComponent extends Component
{
/** Server configuration: keys as in veditor/config.dist.php (licenseKey, ai*). */
public array $options = [];
/** Styles from the site CSS: the editor's "Style" list and the classes allowed by the sanitizer. */
public array $styles = [];
/** Editor options in the browser, e.g. ['height' => '400px']. */
public array $editor = [];
/** Editor-side AI options, e.g. ['autocomplete' => true]. */
public array $ai = [];
/** File manager window (VEditor.createIframePicker) and upload of dropped images (VEditor.createUploader). */
public ?string $filePickerUrl = null;
public ?string $uploadUrl = null;
public string $uploadField = 'upload';
/** Id of the controller with the ai action (controllerMap). */
public string $route = 'veditor';
/** AI functions: an array for every user, or fn (?yii\web\IdentityInterface $user): ?array (null = all). */
public $aiFeatures = null;
/** Hook before a paid AI request: fn (string $feature, array $data): true|string|false (limits). */
public $aiBeforeRequest = null;
/** Configuration for VEditor\AiApi with the current user's permissions. */
public function config(): array
{
$config = $this->options + ['styles' => $this->styles];
if (is_callable($this->aiFeatures)) {
$config['aiFeatures'] = ($this->aiFeatures)(Yii::$app->has('user') ? Yii::$app->user->identity : null);
} elseif (is_array($this->aiFeatures)) {
$config['aiFeatures'] = $this->aiFeatures;
}
if (is_callable($this->aiBeforeRequest)) {
$config['aiBeforeRequest'] = $this->aiBeforeRequest;
}
return $config;
}
public function sanitizer(): HtmlSanitizer
{
return (new HtmlSanitizer())->allowStyles($this->styles);
}
/** Clean HTML for saving (LengthException above the size limit). */
public function sanitize(?string $html): string
{
return $this->sanitizer()->sanitize((string)$html);
}
public function aiEnabled(): bool
{
return AiClient::configured($this->options);
}
/** The editor (form field + script) for a view. The editor files are published by VEditorAsset (web/assets). */
public function render(string $name, ?string $value = '', array $options = []): string
{
$view = Yii::$app->view;
$bundle = VEditorAsset::register($view);
$editor = Widget::mergeOptions(
[
'language' => substr(Yii::$app->language, 0, 2),
'licenseKey' => (string)($this->options['licenseKey'] ?? ''),
'styles' => $this->styles,
],
['ai' => $this->ai],
$this->editor,
$options,
);
if (empty($editor['ai'])) {
unset($editor['ai']);
}
return Widget::render([
'name' => $name,
'value' => $value,
'assetsUrl' => $bundle->baseUrl,
'options' => $editor,
'aiUrl' => $this->aiEnabled() ? Url::to(["/{$this->route}/ai"]) : null,
'csrfToken' => Yii::$app->request->getCsrfToken(),
'filePickerUrl' => $this->filePickerUrl,
'uploadUrl' => $this->uploadUrl,
'uploadField' => $this->uploadField,
'nonce' => $view->params['cspNonce'] ?? null,
]);
}
}
common/components/VEditorAsset.php
<?php
namespace common\components;
use yii\web\AssetBundle;
/**
* The editor files (veditor/assets: ES modules and styles) published by AssetManager to web/assets/{hash}. The modules
* import each other with relative paths, so the whole directory is published. VEditor\Widget adds the styles and the script.
*/
class VEditorAsset extends AssetBundle
{
public $sourcePath = '@vendor/veditor/veditor/assets';
public $publishOptions = ['only' => ['*.js', '*.css']];
}
common/controllers/VEditorController.php
<?php
namespace common\controllers;
use VEditor\AiApi;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
/** AI functions of the editor (AI edition): POST /index.php?r=veditor/ai – JSON or an event stream (text/event-stream). */
class VEditorController extends Controller
{
// The action checks the CSRF token (X-CSRF-Token header with the Yii2 token), so errors come back as JSON for the editor.
public $enableCsrfValidation = false;
/** Roles allowed to use AI functions (['@'] = logged-in users); [] = no restriction (test applications only). */
public array $roles = ['@'];
public function behaviors(): array
{
return $this->roles === [] ? [] : [
'access' => [
'class' => AccessControl::class,
'rules' => [['allow' => true, 'roles' => $this->roles]],
'denyCallback' => function () {
$response = Yii::$app->response;
$response->format = Response::FORMAT_JSON;
$guest = Yii::$app->user->getIsGuest();
$response->statusCode = $guest ? 401 : 403;
$response->data = ['error' => $guest
? 'Your session has expired. Sign in again and reload the page.'
: 'This AI function is not available for your account.'];
Yii::$app->end();
},
],
];
}
public function actionAi(): Response
{
$request = Yii::$app->request;
$response = Yii::$app->response;
$veditor = Yii::$app->vEditor;
// Body limited to aiMaxRequest (null = too large, 413) without reading all of it into memory.
$body = AiApi::readBody($veditor->config());
$call = [
'post' => $request->getIsPost(),
'csrfValid' => $this->csrfValid((string)$request->headers->get('X-CSRF-Token', '')),
'body' => $body,
'host' => $request->hostName,
];
if (AiApi::wantsStream($body)) {
// The session is not needed while streaming (its lock would block the user's other requests).
Yii::$app->session->close();
AiApi::sendStream($veditor->config(), $call, $veditor->sanitizer());
$response->isSent = true; // headers and body already sent
return $response;
}
[$status, $data] = AiApi::handle($veditor->config(), $call, $veditor->sanitizer());
$response->format = Response::FORMAT_JSON;
$response->statusCode = $status;
$response->headers->set('Cache-Control', 'no-store');
$response->data = $data;
return $response;
}
/**
* The X-CSRF-Token header compared with the true token (session or cookie), as Request::validateCsrfToken() does
* internally, but always: also when request->enableCsrfValidation is off or validateCsrfHeaderOnly is on
* (then there is no token and every request is refused). Yii masks both tokens, so they are unmasked first.
*/
private function csrfValid(string $token): bool
{
$trueToken = Yii::$app->request->getCsrfToken();
if ($token === '' || !is_string($trueToken) || $trueToken === '') {
return false;
}
$security = Yii::$app->security;
$expected = $security->unmaskToken($trueToken);
return $expected !== '' && $security->compareString($security->unmaskToken($token), $expected);
}
}
Kontroler sprawdza własny token CSRF Yii2 z nagłówka X-CSRF-Token, więc błędy wracają do edytora jako JSON. Odpowiedzi strumieniowe wysyła AiApi::sendStream(), a odpowiedź Yii jest oznaczana jako wysłana.
Coś jest niejasne? Zgłoś uwagę do dokumentacji.