Class yii\debug\Module

Inheritanceyii\debug\Module » yii\base\Module
Implementsyii\base\BootstrapInterface
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-debug/blob/master/src/Module.php

The Yii Debug Module provides the debug toolbar and debugger

Public Properties

Hide inherited properties

Property Type Description Defined By
$allowedHosts array The list of hosts that are allowed to access this module. yii\debug\Module
$allowedIPs array The list of IPs that are allowed to access this module. yii\debug\Module
$checkAccessCallback callable A valid PHP callback that returns true if user is allowed to use web shell and false otherwise The signature is the following: function (Action|null $action) The action can be null when called from a non action context (like set debug header) yii\debug\Module
$controllerNamespace yii\debug\Module
$dataPath string The directory storing the debugger data files. yii\debug\Module
$defaultHeight integer The debug bar default height, as a percentage of the total screen height yii\debug\Module
$defaultPanel string The name of the panel that should be visible when opening the debug panel. yii\debug\Module
$dirMode integer The permission to be set for newly created directories. yii\debug\Module
$disableCallbackRestrictionWarning boolean Whether to disable access callback restriction warning triggered by checkAccess function yii\debug\Module
$disableIpRestrictionWarning boolean Whether to disable IP address restriction warning triggered by checkAccess function yii\debug\Module
$enableDebugLogs boolean Whether to enable message logging for the requests about debug module actions. yii\debug\Module
$fileMode integer The permission to be set for newly created debugger data files. yii\debug\Module
$historySize integer The maximum number of debug data files to keep. yii\debug\Module
$logTarget yii\debug\LogTarget|array|string The logTarget object, or the configuration for creating the logTarget object. yii\debug\Module
$pageTitle string|callable Page title could be a string or a callable function `php ... 'pageTitle' => 'Custom Debug Title', ... // OR 'pageTitle' => function($url) { $domain = getDomain($url); return $domain . ' debugger'; } ` yii\debug\Module
$panels array|yii\debug\Panel[] List of debug panels. yii\debug\Module
$skipAjaxRequestUrl array Routes of AJAX requests to skip from being displayed in toolbar yii\debug\Module
$traceLine mixed The string with placeholders to be be substituted or an anonymous function that returns the trace line string. yii\debug\Module
$tracePathMappings array Used when the virtual, containerized, or remote debug trace paths don't correspond to the developers local paths. yii\debug\Module
$urlRuleClass string The UrlRule class to use for rules generated by this module. yii\debug\Module

Public Methods

Hide inherited methods

Method Description Defined By
beforeAction() yii\debug\Module
bootstrap() yii\debug\Module
getToolbarHtml() Gets toolbar HTML yii\debug\Module
getYiiLogo() Returns the logo URL to be used in <img src=" yii\debug\Module
htmlTitle() yii\debug\Module
init() yii\debug\Module
renderToolbar() Renders mini-toolbar at the end of page body. yii\debug\Module
setDebugHeaders() Setting headers to transfer debug data in AJAX requests without interfering with the request itself. yii\debug\Module
setYiiLogo() Sets the logo URL to be used in <img src=" yii\debug\Module

Protected Methods

Hide inherited methods

Method Description Defined By
checkAccess() Checks if current user is allowed to access the module yii\debug\Module
corePanels() yii\debug\Module
defaultVersion() yii\debug\Module
initPanels() Initializes panels. yii\debug\Module
resetGlobalSettings() Resets potentially incompatible global settings done in app config. yii\debug\Module

Constants

Hide inherited constants

Constant Value Description Defined By
DEFAULT_IDE_TRACELINE '{text}' yii\debug\Module

Property Details

Hide inherited properties

$allowedHosts public property

The list of hosts that are allowed to access this module. Each array element is a hostname that will be resolved to an IP address that is compared with the IP address of the user. A use case is to use a dynamic DNS (DDNS) to allow access. The default value is [].

public array $allowedHosts = []
$allowedIPs public property

The list of IPs that are allowed to access this module. Each array element represents a single IP filter which can be either:

  • an IP address (e.g. 1.2.3.4),
  • an address with wildcard (e.g. 192.168.0.*) to represent a network segment
  • a CIDR range (e.g. 172.16.0.0/12) (available since version 2.1.18). The default value is ['127.0.0.1', '::1'], which means the module can only be accessed by localhost.
public array $allowedIPs = [
    
'127.0.0.1',
    
'::1',
]
$checkAccessCallback public property (available since version 2.1.0)

A valid PHP callback that returns true if user is allowed to use web shell and false otherwise

The signature is the following:

function (Action|null $action) The action can be null when called from a non action context (like set debug header)

$controllerNamespace public property
public $controllerNamespace 'yii\debug\controllers'
$dataPath public property

The directory storing the debugger data files. This can be specified using a path alias.

public string $dataPath '@runtime/debug'
$defaultHeight public property (available since version 2.1.1)

The debug bar default height, as a percentage of the total screen height

public integer $defaultHeight 50
$defaultPanel public property (available since version 2.0.7)

The name of the panel that should be visible when opening the debug panel. The default value is 'log'.

public string $defaultPanel 'log'
$dirMode public property (available since version 2.0.6)

The permission to be set for newly created directories. This value will be used by PHP chmod() function. No umask will be applied. Defaults to 0775, meaning the directory is read-writable by owner and group, but read-only for other users.

public integer $dirMode 0775
$disableCallbackRestrictionWarning public property (available since version 2.1.0)

Whether to disable access callback restriction warning triggered by checkAccess function

$disableIpRestrictionWarning public property (available since version 2.0.14)

Whether to disable IP address restriction warning triggered by checkAccess function

$enableDebugLogs public property

Whether to enable message logging for the requests about debug module actions. You normally do not want to keep these logs because they may distract you from the logs about your applications. You may want to enable the debug logs if you want to investigate how the debug module itself works.

public boolean $enableDebugLogs false
$fileMode public property (available since version 2.0.6)

The permission to be set for newly created debugger data files. This value will be used by PHP chmod() function. No umask will be applied. If not set, the permission will be determined by the current environment.

public integer $fileMode null
$historySize public property

The maximum number of debug data files to keep. If there are more files generated, the oldest ones will be removed.

public integer $historySize 50
$logTarget public property

The logTarget object, or the configuration for creating the logTarget object.

public yii\debug\LogTarget|array|string $logTarget 'yii\debug\LogTarget'
$pageTitle public property (available since version 2.1.1)

Page title could be a string or a callable function

...
'pageTitle' => 'Custom Debug Title',
...
// OR
'pageTitle' => function($url) {
    $domain = getDomain($url);
    return $domain . ' debugger';
}
public string|callable $pageTitle null
$panels public property

List of debug panels. The array keys are the panel IDs, and values are the corresponding panel class names or configuration arrays. This will be merged with corePanels(). You may reconfigure a core panel via this property by using the same panel ID. You may also disable a core panel by setting it to be false in this property.

$skipAjaxRequestUrl public property (available since version 2.1.14)

Routes of AJAX requests to skip from being displayed in toolbar

$traceLine public property (available since version 2.0.7)

The string with placeholders to be be substituted or an anonymous function that returns the trace line string. The placeholders are {file}, {line} and {text} and the string should be as follows:

File: {file} - Line: {line} - Text: {text}

The signature of the anonymous function should be as follows:

function($trace, $panel) {
    // compute line string
    return $line;
}
public mixed $traceLine self::DEFAULT_IDE_TRACELINE
$tracePathMappings public property (available since version 2.1.6)

Used when the virtual, containerized, or remote debug trace paths don't correspond to the developers local paths. Acts on the {file} portion for the $traceLine property.

The array key is the environment's path, while the value is the local desired path.

It will only map the first matched matched key.

Example:

[
    '/app' => '/home/user/project/app',
]

Note that this will not change the displayed text, only the link url.

$urlRuleClass public property (available since version 2.1.1)

The UrlRule class to use for rules generated by this module.

public string $urlRuleClass 'yii\web\UrlRule'

Method Details

Hide inherited methods

beforeAction() public method

public void beforeAction ( $action )
$action
throws \yii\base\InvalidConfigException
throws \yii\web\ForbiddenHttpException

                public function beforeAction($action)
{
    if (!$this->enableDebugLogs) {
        foreach ($this->get('log')->targets as $target) {
            $target->enabled = false;
        }
    }
    if (!parent::beforeAction($action)) {
        return false;
    }
    // do not display debug toolbar when in debug view mode
    Yii::$app->getView()->off(View::EVENT_END_BODY, [$this, 'renderToolbar']);
    Yii::$app->getResponse()->off(Response::EVENT_AFTER_PREPARE, [$this, 'setDebugHeaders']);
    if ($this->checkAccess($action)) {
        $this->resetGlobalSettings();
        return true;
    }
    if ($action->id === 'toolbar') {
        // Accessing toolbar remotely is normal. Do not throw exception.
        return false;
    }
    throw new ForbiddenHttpException('You are not allowed to access this page.');
}

            
bootstrap() public method

public void bootstrap ( $app )
$app

                public function bootstrap($app)
{
    if (is_array($this->logTarget)) {
        if (!isset($this->logTarget['class'])) {
            $this->logTarget['class'] = 'yii\debug\LogTarget';
        }
        $this->logTarget = Yii::createObject($this->logTarget, [$this]);
    } elseif (is_string($this->logTarget)) {
        $this->logTarget = Yii::createObject($this->logTarget, [$this]);
    }
    /* @var $app \yii\base\Application */
    $app->getLog()->targets['debug'] = $this->logTarget;
    // delay attaching event handler to the view component after it is fully configured
    $app->on(Application::EVENT_BEFORE_REQUEST, function () use ($app) {
        $app->getResponse()->on(Response::EVENT_AFTER_PREPARE, [$this, 'setDebugHeaders']);
    });
    $app->on(Application::EVENT_BEFORE_ACTION, function () use ($app) {
        $app->getView()->on(View::EVENT_END_BODY, [$this, 'renderToolbar']);
    });
    $app->getUrlManager()->addRules([
        [
            'class' => $this->urlRuleClass,
            'route' => $this->getUniqueId(),
            'pattern' => $this->getUniqueId(),
            'normalizer' => false,
            'suffix' => false
        ],
        [
            'class' => $this->urlRuleClass,
            'route' => $this->getUniqueId() . '/<controller>/<action>',
            'pattern' => $this->getUniqueId() . '/<controller:[\w\-]+>/<action:[\w\-]+>',
            'normalizer' => false,
            'suffix' => false
        ]
    ], false);
}

            
checkAccess() protected method

Checks if current user is allowed to access the module

protected boolean checkAccess ( $action null )
$action \yii\base\Action|null

The action to be executed. May be null when called from a non action context

return boolean

If access is granted

                protected function checkAccess($action = null)
{
    $allowed = false;
    $ip = Yii::$app->getRequest()->getUserIP();
    foreach ($this->allowedIPs as $filter) {
        if ($filter === '*'
            || $filter === $ip
            || (
                ($pos = strpos($filter, '*')) !== false
                && !strncmp($ip, $filter, $pos)
            )
            || (
                strpos($filter, '/') !== false
                && IpHelper::inRange($ip, $filter)
            )
        ) {
            $allowed = true;
            break;
        }
    }
    if ($allowed === false) {
        foreach ($this->allowedHosts as $hostname) {
            $filter = gethostbyname($hostname);
            if ($filter === $ip) {
                $allowed = true;
                break;
            }
        }
    }
    if ($allowed === false) {
        if (!$this->disableIpRestrictionWarning) {
            Yii::warning('Access to debugger is denied due to IP address restriction. The requesting IP address is ' . $ip, __METHOD__);
        }
        return false;
    }
    if ($this->checkAccessCallback !== null && call_user_func($this->checkAccessCallback, $action) !== true) {
        if (!$this->disableCallbackRestrictionWarning) {
            Yii::warning('Access to debugger is denied due to checkAccessCallback.', __METHOD__);
        }
        return false;
    }
    return true;
}

            
corePanels() protected method

protected array corePanels ( )
return array

Default set of panels

                protected function corePanels()
{
    $corePanels = [
        'config' => ['class' => 'yii\debug\panels\ConfigPanel'],
        'log' => ['class' => 'yii\debug\panels\LogPanel'],
        'profiling' => ['class' => 'yii\debug\panels\ProfilingPanel'],
        'db' => ['class' => 'yii\debug\panels\DbPanel'],
        'event' => ['class' => 'yii\debug\panels\EventPanel'],
        'mail' => ['class' => 'yii\debug\panels\MailPanel'],
        'timeline' => ['class' => 'yii\debug\panels\TimelinePanel'],
        'dump' => ['class' => 'yii\debug\panels\DumpPanel'],
    ];
    if (Yii::$app instanceof \yii\web\Application) {
        $corePanels['router'] = ['class' => 'yii\debug\panels\RouterPanel'];
        $corePanels['request'] = ['class' => 'yii\debug\panels\RequestPanel'];
        $corePanels['user'] = ['class' => 'yii\debug\panels\UserPanel'];
        $corePanels['asset'] = ['class' => 'yii\debug\panels\AssetPanel'];
    }
    return $corePanels;
}

            
defaultVersion() protected method (available since version 2.0.7)

protected void defaultVersion ( )

                protected function defaultVersion()
{
    $packageInfo = Json::decode(file_get_contents(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'composer.json'));
    $extensionName = $packageInfo['name'];
    if (isset(Yii::$app->extensions[$extensionName])) {
        return Yii::$app->extensions[$extensionName]['version'];
    }
    return parent::defaultVersion();
}

            
getToolbarHtml() public method (available since version 2.0.7)

Gets toolbar HTML

public void getToolbarHtml ( )

                public function getToolbarHtml()
{
    $url = Url::toRoute([
        '/' . $this->getUniqueId() . '/default/toolbar',
        'tag' => $this->logTarget->tag,
    ]);
    if (!empty($this->skipAjaxRequestUrl)) {
        foreach ($this->skipAjaxRequestUrl as $key => $route) {
            $this->skipAjaxRequestUrl[$key] = Url::to($route);
        }
    }
    return '<div id="yii-debug-toolbar" data-url="' . Html::encode($url) . '" data-skip-urls="' . htmlspecialchars(json_encode($this->skipAjaxRequestUrl)) . '" style="display:none" class="yii-debug-toolbar-bottom"></div>';
}

            
getYiiLogo() public static method

Returns the logo URL to be used in <img src="

public static string getYiiLogo ( )
return string

The logo URL

htmlTitle() public method (available since version 2.1.1)

public string htmlTitle ( )
return string

Page title to be used in HTML

                public function htmlTitle()
{
    if (is_string($this->pageTitle) && !empty($this->pageTitle)) {
       return $this->pageTitle;
    }
    if (is_callable($this->pageTitle)) {
        return call_user_func($this->pageTitle, Url::base(true));
    }
    return 'Yii Debugger';
}

            
init() public method

public void init ( )
throws \yii\base\InvalidConfigException

                public function init()
{
    parent::init();
    $this->dataPath = Yii::getAlias($this->dataPath);
    $this->initPanels();
}

            
initPanels() protected method

Initializes panels.

protected void initPanels ( )
throws \yii\base\InvalidConfigException

                protected function initPanels()
{
    // merge custom panels and core panels so that they are ordered mainly by custom panels
    if (empty($this->panels)) {
        $this->panels = $this->corePanels();
    } else {
        $corePanels = $this->corePanels();
        foreach ($corePanels as $id => $config) {
            if (isset($this->panels[$id])) {
                unset($corePanels[$id]);
            }
        }
        $this->panels = array_filter(array_merge($corePanels, $this->panels));
    }
    foreach ($this->panels as $id => $config) {
        if (is_string($config)) {
            $config = ['class' => $config];
        }
        $config['module'] = $this;
        $config['id'] = $id;
        $this->panels[$id] = Yii::createObject($config);
        if ($this->panels[$id] instanceof Panel && !$this->panels[$id]->isEnabled()) {
            unset($this->panels[$id]);
        }
    }
}

            
renderToolbar() public method

Renders mini-toolbar at the end of page body.

public void renderToolbar ( $event )
$event \yii\base\Event
throws Throwable

                public function renderToolbar($event)
{
    if (!$this->checkAccess() || Yii::$app->getRequest()->getIsAjax()) {
        return;
    }
    /* @var $view View */
    $view = $event->sender;
    echo $view->renderDynamic('return Yii::$app->getModule("' . $this->getUniqueId() . '")->getToolbarHtml();');
    // echo is used in order to support cases where asset manager is not available
    echo '<style>' . $view->renderPhpFile(__DIR__ . '/assets/css/toolbar.css') . '</style>';
    echo '<script>' . $view->renderPhpFile(__DIR__ . '/assets/js/toolbar.js') . '</script>';
}

            
resetGlobalSettings() protected method

Resets potentially incompatible global settings done in app config.

protected void resetGlobalSettings ( )

                protected function resetGlobalSettings()
{
    Yii::$app->assetManager->bundles = [];
}

            
setDebugHeaders() public method (available since version 2.0.7)

Setting headers to transfer debug data in AJAX requests without interfering with the request itself.

public void setDebugHeaders ( $event )
$event \yii\base\Event

                public function setDebugHeaders($event)
{
    if (!$this->checkAccess()) {
        return;
    }
    $url = Url::toRoute([
        '/' . $this->getUniqueId() . '/default/view',
        'tag' => $this->logTarget->tag,
    ]);
    $event->sender->getHeaders()
        ->set('X-Debug-Tag', $this->logTarget->tag)
        ->set('X-Debug-Duration', number_format((microtime(true) - YII_BEGIN_TIME) * 1000 + 1))
        ->set('X-Debug-Link', $url);
}

            
setYiiLogo() public static method

Sets the logo URL to be used in <img src="

public static void setYiiLogo ( $logo )
$logo string

The logo URL