Search code examples
phpcronbitrix

How to fix hidden errors in engine of 1C Bitrix when agents work via cron


Sometimes when you make agents in 1C Bitrix that will change some data linked with users, you can catch some nasty errors.

These errors (just crashes without error messages) will occur only with cron.

For example it happens when you work with orders in module "sale".

It can be even worse, that it will happens not everytime.


Solution

  • Reason of this in most of the time is empty current User (object). It will happens when you try update or add new data. Selecting is always normal.

    So you need to check and create current User if there is no any. That's the code I use:

    global $USER;
    if (empty($USER)) {
        $USER = new CUser;
    }
    if (!$USER->IsAuthorized()) {
        // authorize as super admin
        $USER->Authorize(1);
    } else {
        // alredy authorized, nothing need to do anymore
    }