<?php if (!defined('PmWiki')) exit();

/*  === Grep ===
 *  Copyright 2010 Eemeli Aro <eemeli@gmail.com>
 *
 *  Use regular expressions to control what to include from a page
 *
 *  For more information, please see the online documentation at
 *    http://www.pmwiki.org/wiki/Cookbook/Grep
 *
 *
 *  This script 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 3 of the License, or
 *  (at your option) any later version.
 *
 *  This script 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, see <http://www.gnu.org/licenses/>.
 *  
 *  Script maintained since 2015 by Petko YOTOV www.pmwiki.org/petko
 *  - update for PHP 5.5
 *  - update for PHP 7.2
 *  - allow for custom joining/filtering function ($GrepTextJoinFunction)
 */

$RecipeInfo['Grep']['Version'] = '20171103';

Markup('grep', '<include',
  '/\\(:grep\\s+(\\S.*?):\\)/i',
  "GrepTextMarkup");

function GrepTextMarkup($m) {
  extract($GLOBALS["MarkupToHTML"]); # get $pagename
  return PRR(GrepText($pagename, $m[1]));
}
  
function GrepText($pagename, $args) {
  global $KeepToken, $GrepTextJoinFunction;
  $opt = ParseArgs($args);
  if (empty($opt[''])) { $args = "$pagename $args"; $opt['match'] = 1; }
  else if ($opt[''][0][0] == '#') $args = $pagename.ltrim($args);

  $src = IncludeText($pagename, $args);
  if (!$src || ($src[0] == $KeepToken)) return $src;
  if (empty($opt['pat'])) return $src;

  $mod = isset($opt['mod']) ? preg_replace('/[^imsuxADSUXJ]/', '', $opt['mod']) : 'm'; ## note: 'e' not allowed
  $limit = empty($opt['limit']) ? -1 : intval($opt['limit']);
  $pat = '/'.str_replace('/', '\/', $opt['pat'])."/$mod";
  $repl = empty($opt['repl']) ? '' : $opt['repl'];
  list($pat, $repl) = preg_replace(
    array('/\\\n/', '/\\\t/', '/{:(.*?):}/'),
    array(   "\n",     "\t",      '(:$1:)'),
    array($pat, $repl));

  $out = '';
  if (empty($opt['match'])) $out = preg_replace($pat, $repl, $src, $limit);
  else if (preg_match_all($pat, $src, $matches)) {
    $tmp = array();
    if (!$repl) $repl = "$0\n";
    foreach ($matches[0] as $m) {
      $tmp[] = preg_replace($pat, $repl, $m);
      if (--$limit == 0) break;
    }
    if(IsEnabled($GrepTextJoinFunction) && function_exists($GrepTextJoinFunction))
      $out = $GrepTextJoinFunction($pagename, $opt, $tmp);
    else $out = implode('', $tmp);
  }
  return PVS($out);
}