ページの出力直前でHTMLの記述を変更してみます。
今回はプラグインの書き方で作成したplugin_baseプラグインに書き足す形で機能の追加を行います。
</body>の後にscriptタグを追加してみます。
/CMSインストールディレクトリ/common/site_include/plugin/plugin_base/plugin_base.php
<?php
class PluginBasePlugin{
const PLUGIN_ID = "plugin_base";
function getId(){
return self::PLUGIN_ID;
}
function init(){
CMSPlugin::addPluginMenu(self::PLUGIN_ID,array(
"name" => "プラグインの基本構造",
"type" => Plugin::TYPE_NONE,
"description" => "",
"author" => "",
"url" => "",
"mail" => "",
"version" => "1.0"
));
// 当プラグインが有効であるかを調べる
if(CMSPlugin::activeCheck(self::PLUGIN_ID)){
if(defined("_SITE_ROOT_")){
// 公開側ページの方で動作する拡張ポイントで使用したいものを追加する
// ページの出力直前の拡張ポイントを利用します。三番目の値の配列のonOutputはプラグインのクラスに追加するメソッド名になります
CMSPlugin::setEvent("onOutput", self::PLUGIN_ID, array($this, "onOutput"), array("filter" => "all"));
}else{
// 管理画面側の方で動作する拡張ポイントで使用したいものを追加する
}
}
}
// CMSPlugin::setEventで追加した拡張ポイントの処理のコードを書きます。
function onOutput($args){
$html = &$args["html"];
// </body>にscriptタグを付与する
$html = str_replace("</body>", "</body><script>alert(\"hoge\");</script>", $html);
return $html;
}
public static function register(){
$obj = CMSPlugin::loadPluginConfig(self::PLUGIN_ID);
if(!$obj) $obj = new PluginBasePlugin();
CMSPlugin::addPlugin(self::PLUGIN_ID, array($obj, "init"));
}
}
PluginBasePlugin::register();
プラグインで使用できる拡張ポイントについてはhttps://github.com/inunosinsi/soycms/blob/master/cms/common/util/CMSPlugin.class.phpをご覧ください。
onOutputの拡張ポイントでは、公開側のページの読み込みでブロックやcms:moduleの実行がすべて終わった出力直前のHTMLに対して何らかの処理を行う事が出来ます。
HTMLの記述の変更を行う事はもちろん、出力直前のHTMLをキャッシュ化するといった事も可能です。
onOutputについて実際のプラグインで確認したい場合は、Google Analytics導入プラグイン(プラグインID : google_analytics)、AVIF変換プラグイン(プラググインID : convert_image_avif)やHTMLキャッシュプラグイン(プラグインID : x_html_cache)がおすすめです。
追記
onOutputの拡張ポイントが実行されるタイミングは
https://github.com/inunosinsi/soycms/blob/master/cms/common/site_include/CMSPageController.class.php
のonOutputメソッド内で実行されます。
function onOutput(string $html, Page $page){
$onLoads = CMSPlugin::getEvent('onOutput');
if(!is_array($onLoads) || !count($onLoads)) return $html;
foreach($onLoads as $plugin){
$func = $plugin[0];
$filter = (isset($plugin[1]["filter"])) ? $plugin[1]["filter"] : "all";
$exeFunc = false;
switch($filter){
case "blog":
if($this->webPage instanceof CMSBlogPage) $exeFunc = true;
break;
case "page":
if(!$this->webPage instanceof CMSBlogPage) $exeFunc = true;
break;
case "all":
default:
$exeFunc = true;
break;
}
if(!$exeFunc) continue;
$res = call_user_func($func, array('html' => $html, 'page' => &$page, 'webPage' => &$this->webPage));
if(!is_null($res) && is_string($res)) $html = $res;
}
return $html;
}