1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82:
<?php declare(strict_types=1);
trait ImpersonableTrait
{
protected function impersonateRole(string $site, string $user = null, string $gate = null): string
{
$parent = \session_id();
$tv = \Session::get('auth_timeout', \Auth::TV_SEC);
$prefs = \Preferences::factory(\Auth::profile());
if ($prefs->dirty()) {
$prefs->sync();
}
$context = \Auth::context($user, $site);
\Auth::autoload()->beginImpersonation($context, $gate);
if (!\apnscpSession::restore_from_id($context->id, false)) {
fatal("role mockup failed, cannot impersonate `%s'@`%s'", $context->username, $context->domain);
}
$this->setApnscpFunctionInterceptor(\apnscpFunctionInterceptor::factory($context));
if (!$gate || $gate === \Auth::autoload()->getDriver()) {
$auth = \Auth::autoload()->setID($context->id);
$auth->authInfo(true);
$gate = $auth->getDriver();
register_shutdown_function(static function () use ($context, $parent) {
$context->setImpersonator($parent);
});
} else {
\Auth::import($gate)->setID($context->id)->authInfo(true);
}
$stub = (new \Auth_Stub())->setID($context->id);
if ($stub->initializeStubSession($context->username, $context->domain, null, $tv)) {
$stub->setAuthenticationGate($gate);
}
apnscpSession::init()->sync();
return $context->id;
}
protected function restoreImpersonator(\Auth_Info_User $auth): void
{
\Preferences::factory(\Auth::profile())->sync();
if (null === ($parent = $auth->getImpersonator())) {
return;
}
if (!\apnscpSession::restore_from_id($parent)) {
fatal("role mockup failed, cannot restore parent ID `%s'", $parent);
}
$oldCtx = clone $auth;
$auth = \Auth::autoload()->resetID($parent);
$this->setApnscpFunctionInterceptor(\apnscpFunctionInterceptor::factory($auth->getProfile()));
$auth->authInfo(true);
\Auth::autoload()->endImpersonation($oldCtx);
}
}