#!/usr/local/bin/php -Cq
<?php

/*
   this utility assembles a .xpi/.jpi file (installable ewiki plugin)

   usage:
      mkxpi xpi-source-file

   The 'xpi-source-file' holds a rfc822-style list of settings and text
   parts:
    | id: ThePluginIdOrPageName          (REQ)
    | type: page                         (REQ; "page" or "init")
    | license: PublicDomain              (OPT)
    | author: ...                        (OPT)
    | version: ...                       (OPT)
    | description: ...                   (OPT; notes/comments about plugin)
    | code: ...                          (REQ; multiline field)

   All entries, but especially 'description' and 'code' can be multiline
   entries. The 'code' entry is followed by PHP code, with optional
   surrounding <?php and ?> tags.
   For "page" plugins it is simply the code (no function definition!) that
   would normally be put into a page plugin func, but that you cannot use
   return() and instead throw all output via the '$o' variable (workaround).

   For "init" (any type: string will do) xpi plugins, you can add function
   definitions and ewiki_plugin[] registry settings as usual. The execution
   of that code is however not guaranteed to happen in global scope - most
   of the ewiki_* vars are however accessible.

   The special "jpi" type plugins are "page" plugins, but you must use
   JavaScript code, so it can safely be executed in a sandbox (phpjs)
   with the limited WikiApi functionality. Then however everybody can
   install those .jpi plugins. (not yet ready)
*/


function srcxpi2xpi($str) {

   $xpi = array(
      "XPI" => "0.1",
      "engine" => "ewiki",
   );

   $uu = preg_split('/^(\w+):/m', $str, $uu, PREG_SPLIT_DELIM_CAPTURE);
   for ($i=1; $i<count($uu); $i+=2) {

      $id = strtolower(trim($uu[$i]));
      $val = trim($uu[$i+1]);

      if ($id && $val) {
         $xpi[$id] = $val;
      }
   }
   if (strpos($xpi["code"], '<?')===0) {
      $xpi["code"] = trim(preg_replace('/<\?(php|js)+|<\?|\?>/', '', $xpi["code"]));
   }

   #-- .jpi
   if ($xpi["type"] == "jpi") {
      $xpi["JPI"] = $xpi["XPI"];
   }

   return($xpi);
}


if ($file = $_SERVER["argv"][1]) {
   echo "reading '$file'...";
   if ($src = implode("", file($file))) {
      $r = srcxpi2xpi($src);
      if ($fn = $r["id"]) {
         echo " passed.\n";
         $fn .= ($r["JPI"] ? ".jpi" : ".xpi");
         echo "writing '[33m".$fn."[37m'...";
         if ($f = gzopen($fn, "wb9")) {
            gzwrite($f, serialize($r));
            gzclose($f);
            echo " [32mdone[37m.";
         }
         echo "\n";
      }
      else {
         echo " [31minvalid sorce file[37m.\n";
      }
   }
}
else {
   echo "syntax: mkxpi  xpi-src-file\n";
}

?>