System hooks

Contents...
Use app identifier webasyst to register system event (hook) handlers, except for cases when some hooks require other app identifiers specified in their descriptions.

Read more about event handling ›

backend_assets

Allows adding custom content to the <head> section of backend pages.

Return value

HTML string.

Handler code example

return "<script>console.log('I am executed in the backend.');</script>";

backend_before_email_send_test

Triggered before the sending of a test email message in section “Settings → Email templates”.

Parameters

  • $params['channel'] waVerificationChannel

    Instance of the class which is used to send an email message.

  • $params['data'] array

    Information about the message which is about to be sent.

Return value

Error message in an array of the following form:

[
    'errors' => [
        [
            'field' => '...',
            'message' => '...',
        ]
    ],
]

Available values of the field field are:

  • '[channel_id]': error message is displayed under the recipient email address input field,
  • '[recipient]': error message is displayed next to the recipient email address input field.

Handler code example

if (strpos(ifset($params, 'data', 'recipient', ''), 'test@') !== 0) {
    return [
        'errors' => [
            [
                'field' => '[recipient]',
                'message' => _wp('Use only email addresses starting with test@ for email templates testing.'),
            ]
        ],
    ];
}

backend_dashboard_before_action

Triggered on the execution of actions described in the webasystBackendActions class.

Parameters

  • $params['action'] string

    Executed action’s identifier.

Handler code example

if ($params['action'] == 'default') {
    waLog::log(sprintf_wp('Dashboard has been displayed to user %s.', wa()->getUser()->getName()), 'myhandler.log');
}

backend_dispatch_miss

Triggered on attempts to open the backend of a non-existent app.

Parameters

  • $app string

    Non-exstent app’s identifier from the page URL.

Return value

Flag denoting that error message “Page ot found (404)” must be hidden.

Handler code example

waLog::log(sprintf_wp('User %s attempted to open %s app.', wa()->getUser()->getName(), $app_id), 'myhandler.log');

backend_header

Allows adding custom content to the account’s top panel with the main menu.

Parameters

  • $params['current_app'] string

    Current app’s ID.

  • $params['ui_version'] string

    Interface mode: '1.3' or '2.0'.

Return value

Array with the following keys:

  • header_middle (only in the 1.3 interface): content for the middle panel part.
  • header_bottom: content for the bottom panel part.
  • notification (only in the 2.0 interface): content to be displayed in the list of pop-up notifications under the bell icon.
  • user_area (only in the 2.0 interface): content to be displayed next to the current user’s image, as an array with the following keys:
  • user_area['aux']: content to be displayed next to the tools in the right-hand panel part.

Handler code example

return [
    // only 1.3
    'header_middle' => '<!-- ... -->',
    'header_bottom' => '<!-- ... -->',
    // only 2.0
    'notification' => '<!-- ... -->',
    // only 2.0
    'user_area' => [
        'aux' => '<!-- ... -->',
    ],
];

backend_login

Triggered after the sign-in of a user in the backend.

Parameters

  • $params['redirect_url'] string

    URL to which a user must be redirected after the sign-in.

Return value

Array of the following form:

[
    'redirect_url' => '...', // new URL to which a user must be redirected after the sign-in
]

Handler code example

if (myappHelper::checkRedirectUrl($params['redirect_url'])) {
    return [
        'redirect_url' => 'myapp/redirect/',
    ];
}

cli_finished

Triggered after the execution of a CLI controller.

Parameters

  • $params['app'] string

    Identifier of the app to which the controller belongs.

  • $params['class'] string

    Controller’s class name.

  • $params['exists'] bool

    Flag denoting whether the specified class exists.

  • $params['successful_execution'] bool

    Flag denoting successful execution of the controller, during which no exceptions have been thrown.

Handler code example

if ($params['exists'] && !$params['successful_execution']) {
    waLog::log(sprintf_wp('Execution of CLI class %s of %s app could not be completed.', $params['class'], $params['app']), 'debug.log');
}

cli_started

Triggered before the execution of a CLI controller.

Parameters

  • $params['app'] string

    Identifier of the app to which the controller belongs.

  • $params['class'] string

    Controller’s class name.

  • $params['exists'] bool

    Flag denoting whether the specified class exists.

Handler code example

if (!$params['exists']) {
    waLog::log(sprintf_wp('Execution of non-existent CLI class %s of %s app was attempted.', $params['class'], $params['app']), 'debug.log');
}

mail_send.after

Triggered after the sending of an email message via the waMail class.

Parameters

  • $params['message'] Swift_Mime_Message

    Email message object.

  • $params['result'] int

    Number of sent messages to all specified recipients.

  • $params['exception'] string

    Text of a caught exception.

Handler code example

waLog::log(sprintf_wp('Email message has been sent to %s.', implode(', ', array_keys($params['message']->getTo()))), 'myhandler.log');

mail_send.before

Triggered before the sending of an email message via the waMail class.

Parameters

  • $params['message'] Swift_Mime_Message

    Email message object.

Handler code example

waLog::log(
    sprintf_wp(
        'Attempting to send email message to %s...',
        implode(', ', array_keys($params['message']->getTo()))),
    'myhandler.log'
);

profile.tab

Allows adding custom data tabs to the contact profile in the backend.

Use app identifier contacts to register a handler for this hook.

Parameters

  • id int

    Contact ID.

Return value

Array with the following keys:

  • html: HTML string to display the tab contents. May be empty if the url key is used.
  • url: URL from which an HTML string will be loaded to display the tab contents. May be empty if the html key is used.
  • title: Tab title.
  • count: Additional non-zero number (counter) if you need to show it next to the tab title.

Handler code example

return [
    // Tab content HTML will be loaded from the URL in the 'url' key
    'html' => '',
    'url' => wa()->getAppUrl('myapp') . '?module=backend&action=contactProfileTab&id=' . $id,
    'title' => _w('My app’s tab'),
    'count' => ($some_contact_counter ?? 0) ?: '',
];

search_content

Allows using the content on website pages, generated by your app or plugin, in the system search mechanism; e.g., for queries sent to the Webasyst AI service.

Parameters

  • $params['links'] array

    List of website links corresponding to the user’s search query. Each list item is a subarray with the following keys:

    • $params['links'][]['handle'] string Key of the routing rule, matching a found page, built according ot pattern [app_id]/[module_id]/[action_id]. If a website page is based on a plugin’s own routing rule then the plugin’s module_id and action_id are contained in this parameter rather than those of its app.
    • $params['links'][]['url'] string Absolute page URL.
    • $params['links'][]['domain'] string Site’s domain name.
    • $params['links'][]['settlement'] array|null The routing rules of the site section on which the page is published; it’s an entry from system configuration file wa-config/routing.php.
    • $params['links'][]['app_route'] array|null Routing parameters, from configuration file lib/config/routing.php of a plugin or an app, with keys 'url' (routing rule pattern), 'module' (module ID), 'action' (action ID), 'app' (app ID), 'plugin' (plugin ID; it’s available if a website page is generated using a plugin’s routing rule).
    • $params['links'][]['url_params'] array|null Values used for routing HTTP requests to the specific page, which are also required to build is URL.
    • $params['links'][]['result'] string|null Text content of a page, which can be filled in by the hook handler of your app or plugin. If this field already contains a non-empty value different from null then it has already been filled in by another app’s or plugin’s handler. In this case either skip this page’s content field or, if necessary, accurately modify it; e.g., you may add useful content to it if your plugin displays useful content on a standard app page such as a product or category page in the online storefront.

Handler code example

// select from all provided links only those
// to which this plugin adds useful content
$plugin_links_by_handle = [];

foreach ($params['links'] as &$link) {
    if (!empty($link['result'])) {
        // field 'result' in the page properties has already been filled in by another handler — so skip it
        continue;
    }

    if (
        $link['settlement']['app'] != wa()->getApp()
        || ($link['app_route']['plugin'] ?? null) != $this->id
    ) {
        // the page does not belong to this plugin — skip
        continue;
    }

    // group all remaining links, which are supposed to be related to this plugin, by the 'handle' field value;
    // this is especially useful when a plugin needs to handle various types of pages ­with different 'handle' values
    $links_by_handle[$link['handle']][] = &$link;
}

unset($link);

// check if the handler has received links to pages
// generated using a certain module_id/action_id combination; e.g., 'frontend/custom'
$custom_page_links = &$plugin_links_by_handle[sprintf('%s/frontend/custom', wa()->getApp())] ?? [];

if ($custom_page_links) {
    // obtaining the values of routing parameters corresponding to individual pages’ URLs
    $page_urls = array_filter(array_map(function ($link) {
        // for instance, a plugin use some 'url' parameter for its routing rules
        return $link['url_params']['url'] ?? null;
    }, $custom_page_links));

    if ($page_urls) {
        // obtain those pages’ contents from the plugin’s database table
        $pages = (new someappMyPluginModel())
            ->select('url, content')
            ->where('url IN (?)', $page_urls)
            ->fetchAll('url', true);
    }

    if (!empty($pages)) {
        array_walk($page_links, function (&$link) use ($pages) {
            $page_content = $pages[$link['url_params']['url']] ?? null;

            if ($page_content) {
                // fill in the 'result' field of an individual page link using the value from the database
                $link['result'] = _wp('Some custom content') . ': ' . $page_content;
            }
        });
    }
}

Notes

To test your hook handler, you may run the following code in a “sandbox”:

(new waServicesSearch())->getDocumentsByLinks([
    [
        'domain' => 'localhost',
        'url' => 'http://localhost/some/page/url/',
        'title' => '',
        'passages' => [],
    ],
]);

signup

Triggered after the signup if a new website visitor.

Parameters

  • $contact waContact

    Newly registered contact’s object with non-empty 'password' field.

Handler code example

waLog::log(sprintf_wp('Contact %s has just signed up.', $contact->getName()), 'myhandler.log');

sms_send.after

Triggered after the sending of an SMS message via the waSMS class.

Parameters

  • $params['to'] int

    Recipient’s phone number.

  • $params['text'] string

    Message text.

  • $params['from'] string

    Sender identifier.

  • $params['adapter'] waSMS

    Instance of the SMS plugin class used to send a message.

  • $params['result'] bool

    Flag denoting successfull message sending.

Handler code example

if (empty($params['result'])) {
    waLog::log(sprintf_wp('SMS message could not be sent to %s by %s class.', $params['to'], get_class($params['adapter'])), 'myhandler.log');
}

sms_send.before

Triggered before the sending of an SMS message via the waSMS class.

Parameters

  • $params['to'] int

    Recipient’s phone number.

  • $params['text'] string

    Message text.

  • $params['from'] string

    Sender identifier.

  • $params['adapter'] waSMS

    Instance of the SMS plugin class used to send a message.

Handler code example

waLog::log(sprintf_wp('Attempting to send SMS message to %s by %s class.', $params['to'], get_class($params['adapter'])), 'myhandler.log');

view_helper_call

Triggered on attempts to call non-existent methods of template helpers.

Parameters

  • $params['name'] string

    Helper method name.

  • $params[arguments'] array

    Array of parameters passed to the helper method call.

Return value

Arbitrary non-empty value to be returned to a template.

Handler code example

return sprintf_wp('Registered call of an unknown method with parameters "%s"', var_export($params, true));

view_helper_read

Triggered on attempts to read the values of non-existent properties of template helpers.

Parameters

  • $params['name'] string

    Helper property name.

Return value

Arbitrary non-empty value to be returned to a template.

Handler code example

return sprintf_wp('Registered attempt to read unknown property "%s"', $params['name']);

view_page

Triggered on the execution of template helper {$wa->app_id->page()}.

Parameters

  • $page array

    App page properties.

Handler code example

public function viewPage(&$page)
{
    $page['content'] = preg_replace('~\s+~', ' ', $page['content']);
}

view_pages

Triggered on the execution of template helper {$wa->app_id->pages()}.

Parameters

  • $pages array

    App pages’ properties.

Handler code example

public function viewPages(&$pages)
{
    array_walk($pages, function(&$page) {
        $page['title'] = preg_replace('~\s+~', ' ', $page['title']);
    });
}

waid_auth

Triggered after the sign-in of a backend user with Webasyst ID. Allows to redirect a user to a specified URL or to show an error message.

Parameters

  • $params['type'] string

    Fixed value 'backend'.

  • $params['dispatch'] array

    Values contained in decoded GET parameter 'dispatch'.

Return value

For user interface mode 1.3

Option 1

Array of the following form:

[
    'header_top' => '...', // content at the page top
    'header_middle' => '...', // content under the main menu
    'header_bottom' => '...', // content above the main page part
]
Option 2

String value to be used as custom content displayed under the main menu. Only for user interface mode 1.3.

For user interface mode 2.0

Array of the following form:

[
    'header_top' => '...', // content at the page top
    'notification' => '...', // content next to the notifications icon
    'user_area' => [ // content in the main menu
        'main' => '...', // main part
        'aux' => '...', // auxiliary part
    ],
]

Handler code example

if ($params['current_app'] == 'myapp') {
    return [
        'header_top' => myappHelper::getTopBannerHtml(),
    ];
}