Indhold

Yii2

Yii2 har ingen separat pakke: installer veditor/veditor, og kopiér de tre filer nedenfor ind i dit projekt. Koden er kort, så du kan tilpasse den. Den er testet med Yii 2.0.55 (advanced template); i basic template skal du erstatte navnerummene common\… med app\….

VEditor i Yii2-testapplikationen

Installation

composer require veditor/veditor

Kopiér filerne fra dette kapitel til common/components/VEditorComponent.php, common/components/VEditorAsset.php og common/controllers/VEditorController.php.

Konfiguration

// 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 and backend/config/main.php (where the editor has AI functions)
'controllerMap' => [
    'veditor' => common\controllers\VEditorController::class,   // POST index.php?r=veditor/ai, logged-in users only
],

options tager nøglerne fra serverkonfigurationen. Kun API-nøglen til udbyderen af den valgte model er nødvendig (aiAnthropicKey for en claude-…-model, aiApiKey for alle andre); uden den viser editoren ingen AI-knapper, se Understøttede AI-modeller. Komponentens øvrige egenskaber: editor (editorindstillinger), ai (AI-indstillinger på editorens side), filePickerUrl, uploadUrl, uploadField (upload som standard), route (controllerens id, veditor som standard), aiFeatures (et array af AI-funktioner for alle brugere eller en funktion fn ($identity), der returnerer dem, null for alle) og aiBeforeRequest (hooket fra serverkonfigurationen). Editorens sprog er de to første bogstaver i Yii::$app->language.

Controlleren tillader rollerne i sin egenskab roles, som standard ['@'] (indloggede brugere); en gæst får HTTP 401, en bruger uden rollen HTTP 403.

Editorens filer publiceres af AssetManager til web/assets/{hash}, så du behøver ingen URL-regler. De publiceres igen, når pakken ændres.

Visning og lagring

<?= Html::beginForm() ?>
    <?= Yii::$app->vEditor->render('content', $model->content, ['height' => '400px']) ?>
    <?= Html::submitButton('Save') ?>
<?= Html::endForm() ?>
// in the controller or in Article::beforeSave()
$model->content = Yii::$app->vEditor->sanitize($model->content);

Til en CSP-nonce skal du sætte $this->params['cspNonce'] i viewet eller layoutet, før editoren renderes.

Det tredje argument til render() tager en hvilken som helst editorindstilling, for eksempel en kort værktøjslinje til kommentarer (elementernes navne står i Editorindstillinger):

<?= Yii::$app->vEditor->render('comment', $model->comment, ['toolbar' => ['bold', 'italic', 'link', '|', 'bulletedList', 'numberedList', '|', 'undo', 'redo'], 'height' => '150px']) ?>

En værktøjslinje til alle editorer lægges i komponentens egenskab editor.

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);
    }
}

Controlleren kontrollerer Yii2’s eget CSRF-token fra headeren X-CSRF-Token, så dets fejl kommer tilbage som JSON til editoren. Streamede svar sendes af AiApi::sendStream(), og Yii-svaret markeres som sendt.

Er noget uklart? Send feedback på dokumentationen.