<?php
#BEGIN_LICENSE
#-------------------------------------------------------------------------
# Module: SmartyExt (c) 2020-2021 by CMS Made Simple Foundation
#  An add-on module for CMS Made Simple to provide useful functions
#  and commonly used gui capabilities to other modules.
#-------------------------------------------------------------------------
# A fork of:
#
# Module: CGSimpleSmarty (c) 2008-2014 by Robert Campbell
#         (calguy1000@cmsmadesimple.org)
#
#-------------------------------------------------------------------------
#
# CMSMS - CMS Made Simple is (c) 2006 - 2021 by CMS Made Simple Foundation
# CMSMS - CMS Made Simple is (c) 2005 by Ted Kulp (wishy@cmsmadesimple.org)
# Visit the CMSMS Homepage at: http://www.cmsmadesimple.org
#
#-------------------------------------------------------------------------
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# However, as a special exception to the GPL, this software is distributed
# as an addon module to CMS Made Simple.  You may not use this software
# in any Non GPL version of CMS Made simple, or in any version of CMS
# Made simple that does not indicate clearly and obviously in its admin
# section that the site was built with CMS Made simple.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Or read it online: http://www.gnu.org/licenses/licenses.html#GPL
#
#-------------------------------------------------------------------------
#END_LICENSE

class SmartyExt extends CMSModule
{
  const C_UNSET = '_unset_';
  
  #---------------------
  # Internal autoloader
  #---------------------
  
  private final function _autoloader($classname)
  {
    $parts = explode('\\', $classname);
    $classname = end($parts);
    
    $fn = cms_join_path(
      $this->GetModulePath(),
      'lib',
      'class.' . $classname . '.php'
    );
    
    if(file_exists($fn))
    {
      require_once($fn);
    }
  }
  
  private final function _includes()
  {
    $pat = cms_join_path(
      $this->GetModulePath(),
      'lib',
      'function.*.php'
    );
  
    foreach(glob($pat) as $filename)
    {
      include_once $filename;
    }
  }
  
  public function __construct()
  {
    global $CMS_INSTALL_PAGE, $CMS_PHAR_INSTALL;
    
    if(isset($CMS_INSTALL_PAGE) || isset($CMS_PHAR_INSTALL)){return;}
    
    $smarty = cmsms()->GetSmarty();
    
    if(!$smarty){return;}
    
    static $_setup;
    
    if($_setup){return;}
    
    $_setup = 1;
  
    $this->_includes();
    spl_autoload_register(array($this, '_autoloader'));
    
    $smarty->registerClass('smx', 'smx');
    $smarty->register_function('mod_action_link', array($this, 'module_action_link'));
    $smarty->register_function('mod_action_url', array($this, 'module_action_url'));
    $smarty->register_function('xt_repeat', array($this, 'smarty_function_repeat'));
    $smarty->register_function('sess_put', array($this, 'smarty_function_session_put'));
    $smarty->register_function('sess_erase', array($this, 'smarty_function_session_erase'));
    $smarty->register_function('xt_anchor_link', array($this, 'plugin_anchorlink'));
    $smarty->register_function('xt_setvar', array($this, 'plugin_setvar'));
    $smarty->register_function('xt_unsetvar', array($this, 'plugin_unsetvar'));
    $smarty->register_function('xt_getvar', array($this, 'plugin_getvar'));
    parent::__construct();
  }
  
  function GetName(){ return 'SmartyExt'; }
  
  function GetFriendlyName(){ return $this->Lang('friendlyname'); }
  
  function GetVersion(){ return '1.0'; }
  
  function MinimumCMSVersion(){ return '2.1.4'; }
  
  public function GetHelp()
  {
    $smarty = cmsms()->GetSmarty();
    $smarty->assign('mod', $this);
    return $this->ProcessTemplate('help.tpl');
  }
  
  function GetAuthor(){ return 'Jo Morg'; }
  
  function GetAuthorEmail(){ return 'jomorg@cmsmadesimple.org'; }
  
  function GetChangeLog()
  {
    $smarty = cmsms()->GetSmarty();
    $smarty->assign('mod', $this);
    return $this->ProcessTemplate('changelog.tpl');
  }
  
  function IsPluginModule(){ return FALSE; }
  
  function GetAdminDescription(){ return $this->Lang('moddescription'); }
  
  function HasAdmin(){ return FALSE; }
  
  function HandlesEvents(){ return FALSE; }
  
  function InstallPostMessage(){ return $this->Lang('postinstall'); }
  
  function UninstallPostMessage(){ return $this->Lang('postuninstall'); }
  
  /*
   * Create a link to an anchor further down the page.
   */
  function plugin_anchorlink($params, &$smarty)
  {
    $name    = get_parameter_value($params, 'n');
    $name    = get_parameter_value($params, 'name', $name);
    $assign  = trim(get_parameter_value($params, 'assign'));
    $urlonly = get_parameter_value($params, 'u');
    $urlonly = cms_to_bool(get_parameter_value($params, 'urlonly', $urlonly));
    $text    = get_parameter_value($params, 'text', $name);
    unset($params['name'], $params['n'], $params['assign'], $params['u'], $params['urlonly'], $params['text']);
    
    // start the work
    $out = $url = NULL;
    if($name)
    {
      $url = smx::anchor_url($name);
    }
    
    if($urlonly)
    {
      $out = $url;
    }
    else
    {
      // build a link with all the leftover params (don't filter them, there are lots of valid params for a link).
      $tpl = " %s=\"%s\"";
      $out = '<a';
      $out .= sprintf($tpl, 'href', $url);
      foreach($params as $key => $val)
      {
        $out .= " $key=\"$val\"";
      }
      $out .= '>' . $text . '</a>';
    }
    
    if($assign)
    {
      $smarty->assign($assign, $out);
    }
    else
    {
      return $out;
    }
  }
  
  function plugin_setvar($params, &$samrty)
  {
    foreach($params as $key => $val)
    {
      $key = trim($key);
      if(!$key)
      {
        continue;
      }
      if($val == self::C_UNSET)
      {
        xt_tmpdata::erase($key);
      }
      else
      {
        xt_tmpdata::set($key, $val);
      }
    }
  }
  
  function plugin_unsetvar($params, &$smarty)
  {
    foreach($params as $key => $val)
    {
      $key = trim($key);
      if(!$key)
      {
        continue;
      }
      if($key == 'unset')
      {
        if($val)
        {
          $list = explode(',', $val);
          foreach($list as $one)
          {
            $one = trim($one);
            if(!$one)
            {
              continue;
            }
            xt_tmpdata::erase($one);
          }
        }
      }
      else
      {
        xt_tmpdata::erase($key);
      }
    }
  }
  
  function plugin_getvar($params, &$smarty)
  {
    $key  = \xt_param::get_string($params, 'v');
    $key  = \xt_param::get_string($params, 'var', $key);
    $dflt = (isset($params['dflt'])) ? $params['dflt'] : NULL;
    
    $val = NULL;
    if($key)
    {
      $val = xt_tmpdata::get($key, $dflt);
    }
    $assign = \xt_param::get_string($params, 'assign');
    $scope  = strtolower(\xt_param::get_string($params, 'scope', 'local'));
    if($assign)
    {
      $smarty->assign($assign, $val);
      if($scope == 'global')
      {
        $smarty->assignGlobal($assign, $val);
      }
      
      return;
    }
    
    return $val;
  }
  
  //////////
  // A simple function to generate a url to a module action
  //////////
  function module_action_url($params, $tpl)
  {
    $params['urlonly'] = 1;
    $assign            = isset($params['assign']) ? trim($params['assign']) :'';
    unset($params['imageonly'], $params['text'], $params['title'], $params['image'], $params['class'], $params['assign']);
    $out = $this->module_action_link($params, $tpl);
    
    if($assign)
    {
      $tpl->assign($assign, $out);
      
      return;
    }
    
    return $out;
  }
  
  //////////
  // A simple function to generate a link to a module action
  //////////
  function module_action_link($params, $smarty)
  {
    $gCms   = cmsms();
    $inline = FALSE;
    
    $module = $smarty->get_template_vars('module');
    if(!$module)
    {
      $module = $smarty->get_template_vars('actionmodule');
    }
    $module = get_parameter_value($params, 'module', $module);
    if(!$module)
    {
      $module = $smarty->getTemplateVars('module');
    }
    if(!$module)
    {
      $module = $smarty->getTemplateVars('actionmodule');
    }
    if(!$module)
    {
      $module = $smarty->getTemplateVars('_module');
    }
    $mid = $smarty->getTemplateVars('actionid');
    
    if(!$mid)
    {
      $mid = 'm1_';
      if($gCms->is_frontend_request())
      {
        $mid = 'cntnt01';
      }
    }
    
    if(!$module)
    {
      return;
    }
    
    unset($params['module']);
    
    $obj = cms_utils::get_module($module);
    
    if(!is_object($obj))
    {
      return;
    }
    
    $text = $module;
    if(isset($params['text']))
    {
      $text = trim($params['text']);
      unset($params['text']);
    }
    
    $title = '';
    if(isset($params['title']))
    {
      $title = trim($params['title']);
      unset($params['title']);
    }
    
    $confmessage = '';
    if(isset($params['confmessage']))
    {
      $confmessage = trim($params['confmessage']);
      unset($params['confmessage']);
    }
    
    $image = '';
    if(isset($params['image']))
    {
      $image = trim($params['image']);
      unset($params['image']);
    }
    
    $class = 'systemicon';
    if(isset($params['class']))
    {
      $class = trim($params['class']);
      unset($params['class']);
    }
    
    $action = 'default';
    if(isset($params['action']))
    {
      $action = $params['action'];
      unset($params['action']);
    }
    
    if(isset($params['id']))
    {
      $mid    = $params['id'];
      $inline = TRUE;
      unset($params['id']);
    }
    
    $imageonly = FALSE;
    if(isset($params['imageonly']))
    {
      $imageonly = TRUE;
      unset($params['imageonly']);
    }
    
    $pageid = cms_utils::get_current_pageid();
    if(isset($params['page']))
    {
      // convert the page alias to an id
      $manager = $gCms->GetHierarchyManager();
      $node    = $manager->sureGetNodeByAlias($params['page']);
      if(isset($node))
      {
        $content = $node->GetContent();
        if(isset($content))
        {
          $pageid = $content->Id();
        }
      }
      else
      {
        $node = $manager->sureGetNodeById($params['page']);
        if(isset($node))
        {
          $pageid = $params['page'];
        }
      }
      unset($params['page']);
    }
    
    $urlonly = !empty($params['urlonly']);
    if($urlonly)
    {
      $urlonly = TRUE;
      unset($params['urlonly']);
    }
    
    $jsfriendly = !empty($params['jsfriendly']);
    if($jsfriendly)
    {
      $jsfriendly = TRUE;
      $urlonly    = TRUE;
      unset($params['jsfriendly']);
    }
    
    $forjs = !empty($params['forjs']);
    if($forjs)
    {
      $jsfriendly = TRUE;
      $urlonly    = TRUE;
      unset($params['forjs']);
    }
    
    $forajax = !empty($params['forajax']);

    if($forajax)
    {
      $jsfriendly = TRUE;
      $urlonly    = TRUE;
      $forajax    = TRUE;
      unset($params['forajax']);
      unset($params['for_ajax']);
    }
    
    $assign = '';
    if(isset($params['assign']))
    {
      $assign = trim($params['assign']);
      unset($params['assign']);
    }
    
    $addtext = '';
    if($title)
    {
      $addtext = 'title="' . $title . '"';
    }
    
    if(!empty($image) && method_exists($obj, 'CreateImageLink') && $urlonly == FALSE)
    {
      $output = $obj->CreateImageLink(
        $mid, $action, $pageid, $text, $image, $params, $class, $confmessage, $imageonly, FALSE, $addtext
      );
    }
    else
    {
      $output = $obj->CreateLink($mid, $action, $pageid, $text, $params, $confmessage, $urlonly, $inline, $addtext);
      if($urlonly && $jsfriendly)
      {
        $output = str_replace('amp;', '', $output);
      }
      if($forajax)
      {
        if(strpos($output, '?') === FALSE)
        {
          $output .= '?showtemplate=false';
        }
        else
        {
          $output .= '&showtemplate=false';
        }
      }
    }
    
    // all done
    if(!empty($assign))
    {
      $smarty->assign($assign, $output);
      
      return;
    }
    
    return $output;
  }
  
  
  //////////
  // A simple function to repeat a string N times
  //////////
  function smarty_function_repeat($params, $smarty)
  {
    $num = 1;
    if(!isset($params['text']))
    {
      return;
    }
    $text = $params['text'];
    if(isset($params['count']))
    {
      $num = (int)$params['count'];
    }
    
    $out = '';
    for($i = 0; $i < $num; $i++)
    {
      $out .= $text;
    }
    
    if(isset($params['assign']))
    {
      $gCms   = cmsms();
      $smarty = $gCms->GetSmarty();
      $smarty->assign(trim($params['assign']), $out);
      
      return;
    }
    
    return $out;
  }
  
  function smarty_function_session_put($params, $smarty)
  {
    if(isset($params['var']) && isset($params['value']))
    {
      $var = trim($params['var']);
      if(is_string($var))
      {
        $_SESSION[$var] = $params['value'];
      }
    }
  }
  
  function smarty_function_session_erase($params, $smarty)
  {
    if(isset($params['var']))
    {
      $var = trim($params['var']);
      if(is_string($var) && isset($_SESSION[$var]))
      {
        unset($_SESSION[$var]);
      }
    }
  }
  
}
