+ if (empty($my_url) || local_user()) {
+ return;
+ }
+
+ $arr = ['zrl' => $my_url, 'url' => $a->cmd];
+ Hook::callAll('zrl_init', $arr);
+
+ // Try to find the public contact entry of the visitor.
+ $cid = Contact::getIdForURL($my_url);
+ if (!$cid) {
+ Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
+ return;
+ }
+
+ $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
+
+ if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
+ Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
+ return;
+ }
+
+ // Avoid endless loops
+ $cachekey = 'zrlInit:' . $my_url;
+ if (Cache::get($cachekey)) {
+ Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
+ return;
+ } else {
+ Cache::set($cachekey, true, Cache::MINUTE);
+ }
+
+ Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
+
+ Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
+
+ // Try to avoid recursion - but send them home to do a proper magic auth.
+ $query = str_replace(array('?zrl=', '&zid='), array('?rzrl=', '&rzrl='), $a->query_string);
+ // The other instance needs to know where to redirect.
+ $dest = urlencode($a->getBaseURL() . '/' . $query);
+
+ // We need to extract the basebath from the profile url
+ // to redirect the visitors '/magic' module.
+ // Note: We should have the basepath of a contact also in the contact table.
+ $urlarr = explode('/profile/', $contact['url']);
+ $basepath = $urlarr[0];
+
+ if ($basepath != $a->getBaseURL() && !strstr($dest, '/magic') && !strstr($dest, '/rmagic')) {
+ $magic_path = $basepath . '/magic' . '?f=&owa=1&dest=' . $dest;
+
+ // We have to check if the remote server does understand /magic without invoking something
+ $serverret = Network::curl($basepath . '/magic');
+ if ($serverret->isSuccess()) {
+ Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
+ System::externalRedirect($magic_path);
+ }