<?php

/***********************************************************
***********************************************************/

/*
for older pmwiki
Markup('pmdocconvert','directives',"/^\(:docconvert[ 	]*(.*?):\)\s*$/e",
  "PmDocConvert('$1')");
*/

$RecipeInfo['PmDocConvert']['Version'] = '20171013';

Markup_e('pmdocconvert','directives',"/\(:docconvert [ 	]*(.*?):\)\s*$/",
  "PmDocConvert(\$m[1])");

function PmDocConvertInlineTxt($infile) {
  $fp = fopen($infile, "r");
  if ($fp == FALSE)
    return ;
  $out="\n";
  while (($line = fgets($fp)) !== FALSE) {
    $out.='[='.$line.'=]\\\\'."\n";
  }
  fclose($fp);
  $out.="\n";
  return $out;
}

function PmDocConvertInlineCsv($infile, $headingarray, $startrow) {
  $row=1;
  ini_set('auto_detect_line_endings',TRUE);
  $fp = fopen($infile, "r");
  if ($fp == FALSE)
    return ;
  while (($csvrow = fgetcsv($fp)) !== FALSE) {
    if ($row < $startrow) {
      $row++;
      continue;
    }

    if (in_array($row, $headingarray)) 
      $header='!';
    else
      $header='';
    $numfields=count($csvrow);
    for ($field=0; $field < $numfields; $field++) {
      if ($field == 0) 
        $out.="||";
      // People put a LOT of junk into spreadsheets, so we
      // have to "protect" that as much as possible.
      //
      $out.=$header . "[=" . htmlentities($csvrow[$field]) . "=] ||";
    }
    $row++;
    $out.="\n";
  }
  fclose($fp);
  return $out;
}

function PmDocConvertFile($infile, $outfile, $errfile, $args) {
  global $PmDocConvertPgm, $PmDocConvertPython;

  if (!file_exists("$outfile")) {
    system("$PmDocConvertPython $PmDocConvertPgm '$infile' '$outfile' ".$args['dcopts']." >'$errfile' 2>&1");
  }
}

function PmDocConvert($opts) {
  global $FarmD, $UploadDir, $ScriptUrl, $UploadPrefixFmt, $pagename, $PubCacheDir,
    $EnableDirectDownload, $UploadUrlFmt, $FmtV, $LinkUploadCreateFmt, $UploadFileFmt,
    $PageFileFmt,
    $PubCacheUrl,
    $PmDocConvertPython,
    $PmDocConvertPgm, 
    $PmDocConvertIWidth,
    $PmDocConvertIHeight,
    $PmDocConvertIBorder,
    $PmDocConvertIScroll,
    $PmDocConvertIAlign,
    $PmDocConvertSpecial;

  SDV($PubCacheDir, "$FarmD/pub/cache");
  SDV($PubCacheUrl, "$PubDirUrl/cache");
  SDV($PmDocConvertPython, '/usr/bin/python');
  SDV($PmDocConvertPgm, '/usr/local/bin/DC.py');
  // For HTML inline iframe viewing
  // DocumentConverter.py will default to 640x480 images inside
  // a 800x600 space for OOo Impress and PowerPoint files.
  //
  SDV($PmDocConvertIWidth, '840');
  SDV($PmDocConvertIHeight, '680');
  SDV($PmDocConvertIBorder, 'default');
  SDV($PmDocConvertIScroll, 'default');
  SDV($PmDocConvertIAlign, 'default');

  // Needed?
  // Determine this Group
  //
  $group = FmtPageName('$Group',$pagename);
  $name = FmtPageName('$Name',$pagename);

  // Process markup arguments first
  //
  $defaults = array(
    'convertto'=>'',
    'display'=>'link',
    'headingrows'=>'1',
    'startrow'=>'1',
    'iwidth'=>$PmDocConvertIWidth,
    'iheight'=>$PmDocConvertIHeight,
    'iborder'=>$PmDocConvertIBorder,
    'iscroll'=>$PmDocConvertIScroll,
    'ialign'=>$PmDocConvertIAlign,
    'dcopts'=>'',
    'htmlwidth'=>$PmDocConvertIWidth,
    'htmlcolor'=>'none',
    'imageformat'=>'1',
    'file'=>'',
    'filetype'=>'',
    'filter'=>'',
    'forceconvert'=>false,
    'linktext'=>'',
    'quiet'=>false,
    'showfilelink'=>false,
    'showinlinelink'=>false,
    'showicons'=>true,
    'svgauto'=>false,
    'popiframe'=>false,
    'svgnum'=>'1',
  );

  $args = array_merge($defaults, ParseArgs($opts));

  //$upfile = MakeUploadName($pagename,$args['file']);
  $source = $args['file'];
  // Alter pagename to match Group/Page if provided
  $origpagename = $pagename;
  if (preg_match('!^(.*)/([^/]+)$!', $source, $match)) {
    $pagename = MakePageName($pagename, $match[1]);
    $path = $match[2];
  } else {
    $path = $source;
  }
  $origuploaddir = FmtPageName("$UploadFileFmt", $origpagename);
  $upname = MakeUploadName($pagename,$path);
  $encname = rawurlencode($upname);
  $uploaddir = FmtPageName("$UploadFileFmt", $pagename);
  $filepath = FmtPageName("$UploadFileFmt/$upname", $pagename);
  $fe = file_exists($filepath);



  $display = $args['display'];
  $upfiletype = $args['filetype'];
  $convertto = $args['convertto'];
  $forceconvert = $args['forceconvert'];
  $linktext = $args['linktext'];
  $showfilelink = $args['showfilelink'];
  $showicons = $args['showicons'];
  $headingrows = $args['headingrows'];
  $startrow = $args['startrow'];
  $iwidth = $args['iwidth'];
  $iheight= $args['iheight'];
  $iborder= $args['iborder'];
  $iscroll = $args['iscroll'];
  $ialign = $args['ialign'];
  $quiet = $args['quiet'];
  $debug = $args['debug'];
  $popiframe = $args['popiframe'];
  $filter = $args['filter'];
  $svgauto = $args['svgauto'];
  $svgnum = $args['svgnum'];
  // Pull rest straight from args (FilterData opts)

  // Intitialize output
  $out='';

  // Convert command separated list of rows that
  // will be csv inline headings to an array.
  $headingarray=explode(',',$headingrows);

  // Check if upload exists, make link for upload
  if (! $fe) {
    if (! CondAuth($pagename, 'upload')) {
      $error_msg = "No upload permissons";
      return PRR("[$encname] [[$pagename?action=login|No upload permissions]]");
    } else {
      $FmtV['$LinkUpload'] =
        FmtPageName("\$PageUrl?action=upload&amp;upname=$encname", $pagename);
      $FmtV['$LinkText'] = $upname;
      $pagename = $origpagename;
      return Keep(FmtPageName($LinkUploadCreateFmt, $pagename));
    }
  }
  if (!$linktext) {
    $linktext=$upname;
  }


  // Upload exists, convert if necessary and display it.
  //
  $upinfo=pathinfo($filepath);
  $upfileext=$upinfo['extension'];
  if (!$upfiletype) {
    // Try to figure out file type of upload.
    // Would love to get a file/magic value, but
    //  php's support is varied and even so, magic
    //  values vary from platform to platform as well.
    //

    // For now, the file extension determines the type.
    //
    $upfiletype=$upfileext;
  }
  if ($debug)
    echo "upfiletype=[$upfiletype] ";
          
  // Handle default conversion
  if (!$convertto) {
    switch ($upfiletype) {
    case 'xls':
      if ($display == 'inline')
        $convertto='csv';
      else
        $convertto='pdf';
      break;
    default:
      $convertto='pdf';
      break;
    }
  }
  if ($debug)
    echo "convertto=[$convertto] ";

  // Handle an identity, no convert, case, for display only entities


  if ($convertto == $upfiletype) {
    $bupname=basename($upname, ".$upfileext");
    $noconvert=1;
  } else {
    $bupname=basename($upname, ".$upfileext") . "-$upfileext";
  }
  $bencname = rawurlencode($bupname);
  $buploaddir = $uploaddir;
  $bfilepath = FmtPageName("$UploadFileFmt/$bupname", $pagename);
  $bfe = file_exists($bfilepath);

  if ($debug)
    echo "bupname=[$bupname] ";
      
  // Normally, converted file is in the normal
  // upload group dir, but html conversion results
  // in many files and collision potential is
  // high.  So create a sub-directory and assume
  // inline display.
  //
  $convertedfile="$bupname.$convertto";
  $convertedfilepath="$buploaddir/$convertedfile";
  $convertedfileerrorpath="$origuploaddir/$convertedfile.err";
  $convertedfileurl = PUE(FmtPageName(IsEnabled($EnableDirectDownload, 1)
    ? "$UploadUrlFmt$UploadPrefixFmt/$convertedfile"
    : "{\$PageUrl}?action=download&upname=$convertedfile", $pagename));
  if ($convertto == 'html') {
    $display='inline';
    $converttodir = FmtPageName("$FarmD/$UploadDir/pmdocconvert$UploadPrefixFmt", $pagename);
    $convertedfileurl = FmtPageName("$ScriptUrl/pmwiki/$UploadDir/pmdocconvert$UploadPrefixFmt/$convertedfile.dir/$convertedfile", $pagename);
    $convertedfiledir="$converttodir/$convertedfile.dir";
    $convertedfilepath="$convertedfiledir/$convertedfile";
    if (!file_exists($convertedfiledir)) {
      mkdir($convertedfiledir, $mode=0755, $recursive=true);
    }
    if (!file_exists($convertedfiledir)) {
      $errout.='!! %red% PmDocConvert ERROR: Cannot create '.$convertedfiledir."\n";
      $display='none';
      $noconvert=1;
    }
  }
  if (!$noconvert) {
    // If the convertedfile exists, and the source uploaded file
    // is newer, then delete the convertedfile to force
    // new conversion.
    //
    // Note: right now, the directory for html conversion is NOT
    // cleaned up.
    //
    if (file_exists("$convertedfilepath")) {
      if ($debug)
        echo "EXISTS ";
      if ($forceconvert || filectime("$filepath") > filectime("$convertedfilepath")) {
        if ($debug)
          echo "NEWER ";
        unlink("$convertedfilepath");
        $noconvert=0;
      } else {
        $noconvert=1;
      }
    }
    // Fix this
    $linkurl="Attach:$pagename/$convertedfile";
    if ($popiframe != 'true' && $linktext == '') {
      $linktext="$convertedfile";
    }
  }
  if (!$noconvert) {
    if ($debug)
      echo "CONVERTING ";
    // Why all of this?  Well.. I was thinking that things
    // might vary at some point and even include other kinds
    // of converters besides DocumentConverter.py.
    //
    switch ($convertto) {
    case 'pdf':
      PmDocConvertFile($filepath, "$convertedfilepath", "$convertedfileerrorpath", $args);
      break;
    case 'csv':
      PmDocConvertFile($filepath, "$convertedfilepath", "$convertedfileerrorpath", $args);
      break;
    default:
      if ($convertto) {
        PmDocConvertFile($filepath, "$convertedfilepath", "$convertedfileerrorpath", $args);
      }
    }
    if ($svgauto == 'true') {
      $svg_contents = file_get_contents("$convertedfilepath");
      $svg_contents = preg_replace('/width="[^"]*"/','width="100%"', $svg_contents, 1);
      $svg_contents = preg_replace('/height="[^"]*"/','height="auto"', $svg_contents, 1);
      file_put_contents("$convertedfilepath", $svg_contents);
    }
  }
  // Always run filter.  Make sure script can be rerun
  if ($filter != '') {
    system("/usr/local/wiki/{$filter} $convertto$svgnum $convertedfilepath");
  }
  if (!$noconvert && !file_exists("$convertedfilepath") && file_exists("$convertedfileerrorpath")) {
    $fp=fopen("$convertedfileerrorpath", 'r');
    $errout.='!! %red% PmDocConvert ERROR: '.fread($fp,1000)."\n";
    $display='none';
  }
  if ($debug) 
    echo "filelink=[$filelink] linkurl=[$linkurl] linktext=[$linktext]]";
  switch ($display) {
  case 'imagelink':
    $out.="$filelink"."[[Attach:$pagename/$upfile|$linkurl]]";
    break;
  case 'link':
    if ($popiframe == 'true' && $convertto == 'pdf') {
      $out.="%popiframe name=$convertedfile%[[Attach:$pagename/$convertedfile|$linktext]]";
    } else {
      $out.="$filelink"."[[$linkurl|$linktext]]";
    }
    break;
  case 'attach':
    $out.="$filelink"."$linkurl";
    break;
  case 'inline':
    switch ($convertto) {
    case 'svg':
      if ($showfilelink == 'true') {
        $out.="$filelink\n";
      }
      if ($popiframe == 'true') {
        $out.="%popiframe name=$convertedfile%[[$convertedfileurl|$linktext]]";
      } else {
        $out.="\n<object width=\"100%\" height=\"100%\" type=\"image/svg+xml\" ";
        $out.="data='".Keep("$convertedfileurl")."'>Browser doesn't support SVG</object>\n";
      }
      break;
    case 'csv':
      if ($showfilelink == 'true') {
        $out.="$filelink\n";
      }
      $out.=PmDocConvertInlineCsv($convertedfilepath, $headingarray, $startrow);
      break;
    // wiki means MediaWiki format.. so not really a nice
    // way for inline PmWiki viewing... might add a convert
    // here to convert MediaWiki to PmWiki... for now...
    // it's text.
    //
    case 'wiki':
    case 'txt':
      if ($showfilelink == 'true') {
        $out.="$filelink\n";
      }
      $out.=PmDocConvertInlineTxt($convertedfile);
      break;
    case 'html':
      if ($showfilelink == 'true') {
        $out.="$filelink\n";
      }
      if ($popiframe == 'true') {
        $out.="%popiframe name=$convertedfile%[[$convertedfileurl|$linktext]]";
      } else {
        $out.="\n<iframe width=$iwidth height=$iheight align=$ialign ";
        $out.="frameborder=$iborder scrolling=$iscroll ";
        $out.="src='".Keep("$convertedfileurl")."'></iframe>\n";
      }
      break;
    default:
      $out.="$filelink"."$linkurl";
      break;
    }
    break;
  }

  if ($quiet == 'true')
    $out='';
  $pagename = $origpagename;
  if ($errout != '') {
    PRR(); return $errout."\n".$out;
  } else {
    PRR(); return $out;
  }
}

?>