<?php if (!defined('PmWiki')) exit ();
/*  copyright 2006 Hans Bracker.

    This file is distributed 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.

    This module enables image mapping in wiki pages.

    Usage example:
    (:imgmap mapname:)
    (:area href=Group.PageName shape=... coords=... :)
    (:area href=http://example.com/ shape=... coords=... :)
    ....
    (:imgmapend:)

    %usemap=#mapname%Attach:myimage.jpg

    Use distinct name as mapname for each image map (works like anchor)
    Necessary parameters for area:
        href=[Group.PageName|http://siteaddress]
        shape=[rect|circle|polygon|default]
        coords=number,number,number,number...
           for rectangle:x1,y1,x2,y2 (topleft corner, bottom right corner)
           for circle:x,y,r (left to centre, top to centre,radius)
           for polygon:x1,y1,x2,y2,x3,y3,x4,y4,x5,y5,... (corners of polygon)
           for default: no coords. The whole image is the default.
    Optional parameters for area:
        title='title name' (shows as tooltip when moused over)
        alt='alternative text' (for browsers with no image support)
        tabindex=number
        accesskey=
        onclick='javascript commands' (needs $EnableOnclickJavascripting turned on)
*/
# Version
$RecipeInfo['ImageMap']['Version'] = '2022-06-23';

# the onclick= parametyer is turned off by default, to prevent malicious javascripting,
# but can be enabled by setting it to 1.
SDV($EnableOnclickJavascripting, 0);

# add usemap as wiki style for inclusion in img tag:
$WikiStyleAttr['usemap'] = 'img';

# add imagemap markup
Markup('imgmap', '>block', '/\\(:imgmap (.*?)?\\s*?:\\)/', "<map name='$1'>");
Markup('imgmapend', '>block', '/\\(:imgmapend:\\)/', '</map>');
Markup('area', 'directives', "/\\(:area (.*?)?\\s*?:\\)/", "MapArea");
function MapArea($m) {
    global $ScriptUrl, $EnablePathInfo, $EnableOnclickJavascripting, $MarkupToHTML;
    extract($MarkupToHTML);
    $m[1] = strval(@$m[1]);
    $arg = ParseArgs($m[1]);
    
    $out = "<area ";
    if (isset($arg['href'])) {
      $tgt = $arg['href'];
      if(preg_match("/^(https?:|#).+$/",$tgt)) $LinkUrl = $tgt;
      else {
        $pn = MakePageName($pagename, $tgt);
        $LinkUrl = PageVar($pn, '$PageUrl');
      }
      $out .= " href='$LinkUrl'";
    }
    $arg = PHSC($arg, ENT_QUOTES);
    $attr = explode(' ', 'shape coords tabindex alt title accesskey');
    if($EnableOnclickJavascripting) $attr[] = "onclick";
    
    foreach($attr as $k) {
      if(isset($arg[$k])) $out .= " $k='".$arg[$k]."'";
    }
    $out .= " />";
    return Keep($out);
}