<?php
/**
 * Restricts access to the Smarty template by IP address.
 *
 * @param array $params An associative array of parameters passed to the function.
 *                     - list: An array of IP addresses or a single IP address.
 * @param object $smarty The Smarty object.
 *
 * @return string Returns an empty string.
 * @throws CmsError403Exception Throws a CmsError403Exception exception
 * if the current IP address matches any of the IP patterns in the list.
 * If the custom 403 error page is set, it will be returned
 * otherwise the system 403 error page will be returned.
 * @author Fernando Morgado aka JoMorg
 * @since 1.4.3
 * @package CMSMSExt
 */
function smarty_function_restrict_by_ip_list($params, $smarty)
{
  $list = $params['list'] ?? [];
  $list = is_array($list) ? $list : [$list];
  
  if(!empty($list))
  {
    $current_ip = xt_utils::get_real_ip();
    
    foreach($list as $ipPattern)
    {
      // Escape special characters in the pattern and replace wildcards
      $ipPattern = preg_quote($ipPattern, '/');
      $ipPattern = str_replace('\*', '.*', $ipPattern);
      $ipPattern = str_replace('\?', '.', $ipPattern);
      
      // Check if the IP matches the pattern
      if( preg_match("/^$ipPattern$/", $current_ip) )
      {
        throw new CmsError403Exception();
      }
    }
  }
  return '';
}
?>