<?php
namespace Lia\Addon;
/**
* Makes it easy to pass a message to a page that you're redirecting to. If not passing a message, may be better to just use PHP's `header()` directly.
*
*/
class Redirect extends \Lia\Addon {
public string $fqn = 'lia:server.redirect';
/**
* The number of seconds that a message remains valid in the cache.
* @configurable int number of seconds that a redirect message is configurable for.
*/
public int $message_expiry_seconds = 240;
/**
* Redirect to the target url. Use `Redirect->getMessage()` on the landing page to retrieve the string message if it was set. You may wish to `exit;` after calling this method.
*
* @param $url string url path to redirect to
* @param $statusCode int http redirect code. defaults 302 for temporary redirect. 301 is permanent redirect. See https://http.cat/
* @param string $message pass a message to the landing page - must be on the same server. A message id is passed as a GET param 'liaison-message-id'. Use `\Lia\Addon\Redirect::from($lia)->getMessage();` to retrieve the message.
*/
public function goto(string $url, int $statusCode=302, ?string $message=null){
if ($message!=null){
$id = uniqid(true);
\Lia\Addon\Cache::from($this->lia)->cache_file('lia.redirect.message-'.$id, $message, 240);
$hash_portion = '';
$hashpos = strpos($url, "#");
if ($hashpos !== false){
$hash_portion = substr($url,$hashpos);
$url = substr($url, 0, $hashpos);
}
$qpos = strpos($url, "?");
if ($qpos===false){
$url.= '?liaison-message-id='.urlencode($id);
} else {
$url .= '&liaison-message-id='.urlencode($id);
}
$url .= $hash_portion;
}
//error_log("Redirect Url: ".$url);
header("Location: {$url}", true, $statusCode ?? 302);
}
/**
* Get the message passed as part of a redirect
*
* @return string|false
*/
public function getMessage() {
$id = $_GET['liaison-message-id'];
$message = \Lia\Addon\Cache::from($this->lia)->get_cache_file_content('lia.redirect.message-'.$id);
return $message;
}
}