<?php if (!defined('PmWiki')) exit();
/*  Copyright 2013-2015 Petko Yotov www.pmwiki.org/petko
    This file is part of PmWiki; 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 3 of the License, or
    (at your option) any later version.  See pmwiki.php for full details.
*/

$RecipeInfo['LocalCSS']['Version'] = '20150830';

SDVA($PostConfig, array('LocalCSSInsert'=>100));
SDV($LocalCSSPage, "$SiteGroup.LocalCSS");
SDV($LocalCSSPHPVars, array('FarmPubDirUrl', 'PubDirUrl', 'Skin', 'action', 'SkinDirUrl'));

function LocalCSSInsert($pagename) {
  global $LocalCSSPage, $EnableSelfLocalCSS, $HTMLStylesFmt, $LocalCSSPHPVars;

  # disable for Site.LocalCSS or a beginner may break it and be unable to edit
  if ($LocalCSSPage == $pagename && !IsEnabled($EnableSelfLocalCSS, 0)) return;

  if ($LocalCSSPage == $pagename && @$_POST['text']) {
    $text = stripmagic($_POST['text']);
  }
  else {
    $p = ReadPage($LocalCSSPage, READPAGE_CURRENT);
    $text =  @$p['text'];
  }
  $text = str_replace(
      array("\r", '$', '<', '&#036;='),
      array("", '&#036;', '&lt;', '$='),
      $text);

  $varray = array();

  # Global PHP variables as @variables
  foreach($LocalCSSPHPVars as $var) {
    $varray["@$var"] = $GLOBALS[$var];
  }

  # get @variables from page
  if (preg_match_all("/^\\s*(@\\w+):\\s*(.*?)\\s*$/m", $text, $vars) ) {
    foreach($vars[1] as $k=>$varname) $varray[$varname] = trim($vars[2][$k]);
  }

  $text0 = "0$text"; $i = 0;
  while($text0 != $text && ++$i<50) {# if nested
    $text0 = $text;
    $text = strtr($text, $varray);
  }

  # process snippets
  if (preg_match_all("/\\[@\\s*([^\\/!\\s]+)\n(.*?)\\s*@\\]/s", $text, $matches, PREG_SET_ORDER) ) {
    foreach($matches as $a) {
      $pat = trim($a[1]);
      $css = trim($a[2]);
      if(count(MatchPageNames($pagename, $pat)))
        @$HTMLStylesFmt['LocalCSS'] .= $css;
    }
  }
}