<?php
$RecipeInfo['VideoAttach']['Version'] = '2017-07-25';

SDV($EnableVA_All, FALSE);
SDV($EnableVA_Twitch, FALSE);
SDV($EnableVA_DailyMotion, FALSE);
SDV($EnableVA_Vimeo, FALSE);
SDV($EnableVA_Youtube, FALSE);
SDV($EnableVA_Attach, TRUE);
SDV($VideoAttach_Directive, 'video');

if ($EnableVA_All) {
  $EnableVA_Twitch = TRUE;
  $EnableVA_Dailymotion = TRUE;
  $EnableVA_Vimeo = TRUE;
  $EnableVA_Youtube = TRUE;
  $EnableVA_Attach = TRUE;
}

if ($EnableVA_Twitch) {
  # Raw Twitch vid
  SDV($TwitchTagFmt, "<div class='video-container'><iframe width='600' height='400' align='default' frameborder='0' scroll='default' src='\$LinkUrl' allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe></div>");
  Markup_e('twitch','<urllink',
    "/\\b(?>(\\L))\/\/www.twitch.tv\/videos\/([^\\s$UrlExcludeChars]+)/",
    "Keep(\$GLOBALS['LinkFunctions'][\$m[1]](\$pagename,\$m[1],
      '//player.twitch.tv/?video=v'.\$m[2].'&amp;autoplay=false','',
      \$m[1].'//player.twitch.tv/?video=v'.\$m[2].'&amp;autoplay=false',
      \$GLOBALS['TwitchTagFmt']),'L')");
}

if ($EnableVA_Dailymotion) {
  # Raw Dailymotion vid
  SDV($DailymotionTagFmt, "<div class='video-container'><iframe width='600' height='400' frameborder='0' src='\$LinkUrl' allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe><i><a href='\$LinkUrl'>\$LinkAlt</a></i></div>");
  Markup_e('dailymotion','<urllink',
    "/\\b(?>(\\L))\/\/(?:www\.)?dailymotion\.com\/([^_\\s$UrlExcludeChars]+)_(.*)?/",
    "Keep(\$GLOBALS['LinkFunctions'][\$m[1]](\$pagename,\$m[1],'//www.dailymotion.com/embed/'.\$m[2],\$m[3],\$m[1].'//www.dailymotion.com/embed/'.\$m[2],
      \$GLOBALS['DailymotionTagFmt']),'L')");
}

if ($EnableVA_Vimeo) {
  # Raw Vimeo vid
  SDV($VimeoTagFmt, "<div class='video-container'><iframe width='600' height='400' align='default' frameborder='0' scroll='default' src='\$LinkUrl' allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe></div>");
  Markup_e('vimeo','<urllink',
    "/\\b(?>(\\L))\/\/vimeo\.com\/([^\\s$UrlExcludeChars]+)/",
    "Keep(\$GLOBALS['LinkFunctions'][\$m[1]](\$pagename,\$m[1],
      '//player.vimeo.com/video/'.\$m[2].'?color=ffffff&amp;byline=0&amp;portrait=0&amp;badge=0',
      '',\$m[1].'//player.vimeo.com/video/'.\$m[2].'?color=ffffff&amp;byline=0&amp;portrait=0&amp;badge=0',
      \$GLOBALS['VimeoTagFmt']),'L')");
}

if ($EnableVA_Youtube) {
  # Raw Youtube vid
  SDV($YouTubeTagFmt, "<div class='video-container'><iframe width='600' height='400' align='default' frameborder='0' scroll='default' src='\$LinkUrl' allowfullscreen></iframe></div>");
  Markup_e('youtube','<urllink',
    "/\\b(?>(\\L))(\/\/www\.youtube\.com\/embed\/[^\\s$UrlExcludeChars]+)/",
    "Keep(\$GLOBALS['LinkFunctions'][\$m[1]](\$pagename,\$m[1],\$m[2],'',\$m[1].\$m[2],
      \$GLOBALS['YouTubeTagFmt']),'L')");
  Markup_e('youtube_watch','<urllink',
    "/\\b(?>(\\L))(\/\/www\.youtube\.com)\/watch\?v=([^\\s$UrlExcludeChars]+)/",
    "Keep(\$GLOBALS['LinkFunctions'][\$m[1]](\$pagename,\$m[1],\$m[2].'/embed/'.\$m[3],'',\$m[1].\$m[2].'/embed/'.\$m[3],
      \$GLOBALS['YouTubeTagFmt']),'L')");
  Markup_e('youtu_be_watch','<urllink',
    "/\\b(?>(\\L))(\/\/youtu\.be)\/([^\\s$UrlExcludeChars]+)/",
    "Keep(\$GLOBALS['LinkFunctions'][\$m[1]](\$pagename,\$m[1],'//www.youtube.com/embed/'.\$m[3],'',\$m[1].\$m[2].'/'.\$m[3],
      \$GLOBALS['YouTubeTagFmt']),'L')");
}

if ($EnableVA_Attach) {
  # Raw generic vid
  SDV($VideoExtPattern, "\\.(?:mp4|m4v|avi|webm|ogv?|MP4|M4V|AVI|WEBM|OGV)");
  SDV($VideoTagFmt, "<video controls preload poster='\$LinkAlt'> <source src='\$LinkUrl' > </video>");
  Markup_e('vida','<urllink',
    "/\\b(?>(\\L))([^\\s$UrlExcludeChars]+$VideoExtPattern)(\"([^\"]+$ImgExtPattern)\")?/",
    "MxVideoAttach(\$pagename,\"\$m[1]\$m[2]\",'',\"poster=\$m[3]\")");
  Markup('VideoAttach','<{(', "/(Attach:)(.+)($VideoExtPattern)(\"([^\"]+$ImgExtPattern)\")?/",
    "<div class='videoattach-video'>{(video '$2$3' poster=$4 width=0)}</div>");

  # Treat video tag similar to img, object, etc. for width height inline styling
  SDV($imgTag, '(?:img|object|embed|video|div)');
}

Markup('videoattach_video', '<{(',
  '/\\(:'.$VideoAttach_Directive.'\\s+(\\S.*?):\\)/',
  "{(video $1)}");

# Handle wiki uploaded video
$MarkupExpr['video'] = 'MxVideoAttach($pagename, $args[0], $argp)';
function MxVideoAttach($orig_pagename, $source, $opts=NULL, $rawargs='') {
  global $UploadFileFmt, $FmtV, $LinkUploadCreateFmt, 
    $EnableDirectDownload, $UploadPrefixFmt, $VideoTagFmt;
  
  $defaults = array(
    'controls' => 1,
    'autoplay' => 0,
    'loop' => 0,
    'width' => '100%',
    'height' => 0,
    'muted' => 0,
    'poster' => 0,
    'type' => 0,
    'preload' => 'auto',
    'error' => '<VALINK>'
  );
 
  if ($rawargs) {
    $rawopts = ParseArgs($rawargs);
    $opts = array_merge($defaults, $rawopts);
  } else {
    $opts = array_merge($defaults, $opts); 
  }

  $pagename=$orig_pagename;
  $notsourceurl=1;
  if (preg_match('/^[^:\/]+:.*/', $source)) {
    $path = $source;
    $notsourceurl=0;
  } elseif (preg_match('!^(.*)/([^/]+)$!', $source, $match)) {
    $pagename = MakePageName($pagename, $match[1]);
    $path = $match[2];
  } else {
    $path = $source;
  }
  if ($notsourceurl) {
    $upname = MakeUploadName($pagename, $path);
    $encname = rawurlencode($upname);
    $filepath = FmtPageName("$UploadFileFmt/$upname", $pagename);
    $FmtV['$LinkUpload'] =
      FmtPageName("\$PageUrl?action=upload&amp;upname=$encname", $pagename);
    $FmtV['$LinkText'] = $upname;

    if (!file_exists($filepath))
      return Keep(FmtPageName($LinkUploadCreateFmt, $pagename));

    $path = PUE(FmtPageName(IsEnabled($EnableDirectDownload, 1)
                              ? "$UploadUrlFmt$UploadPrefixFmt/$encname"
                              : "{\$PageUrl}?action=download&amp;upname=$encname",
                            $pagename));
  }

  # Do same for poster if provided
  $poster_path='';
  $notposterurl=1;
  if (@$opts['poster']) {
    $poster_pagename=$orig_pagename;
    if (preg_match('/^https?:.*/', @$opts['poster'])) {
      $poster_path = @$opts['poster'];
      $notposterurl=0;
    } elseif (preg_match('!^(.*)/([^/]+)$!', @$opts['poster'], $poster_match)) {
      $poster_pagename = MakePageName($poster_pagename, $poster_match[1]);
      $poster_path = $poster_match[2];
    } else {
      $poster_path = @$opts['poster'];
    }
    if ($notposterurl) {
      $poster_upname = MakeUploadName($poster_pagename, $poster_path);
      $poster_encname = rawurlencode($poster_upname);
      $poster_filepath = FmtPageName("$UploadFileFmt/$poster_upname", $poster_pagename);
      $FmtV['$LinkUpload'] =
        FmtPageName("\$PageUrl?action=upload&amp;upname=$poster_encname", $poster_pagename);
      $FmtV['$LinkText'] = $poster_upname;

      if (!file_exists($poster_filepath))
        return Keep(FmtPageName($LinkUploadCreateFmt, $poster_pagename));
      $poster_path = PUE(FmtPageName(IsEnabled($EnableDirectDownload, 1)
                                ? "$UploadUrlFmt$UploadPrefixFmt/$poster_encname"
                                : "{\$PageUrl}?action=download&amp;upname=$poster_encname",
                              $poster_pagename));
    }
  }
  if ($notsourceurl) {
    if (@$opts['error'] == '<VALINK>') {
      if ($poster_path) {
        $error = '<a href="' . $path . '"> <img src="' . $poster_path . '"></a>';
      } else {
        $error = '<a href="' . $path . '">' . $source . '</a>';
      }
    } else {
      $error = @$opts['error'];
    }
  }

  if ($rawargs) {
    $match = array();
    if (preg_match('/^(https?:)(.*)/', $path, $match)) {
      return Keep($GLOBALS['LinkFunctions'][$match[1]]($pagename,$match[1],$match[2],$poster_path,'44',
        $GLOBALS['VideoTagFmt']),'L');
    }
  } else {
    return Keep("<video " .
     (@$opts['controls'] ? 'controls' : '') .  " " .
     (@$opts['autoplay'] ? 'autoplay' : '') . " " .
     (@$opts['preload'] ? 'preload' : '') . " " .
     (@$opts['loop'] ? 'loop' : '') . " " .
     (@$opts['muted'] ? 'muted' : '') . " " .
     (@$opts['poster'] ? "poster='" . $poster_path . "'" : '') . " " .
     (@$opts['width'] ? "width='" . @$opts['width'] . "'" : '') . " " .
     (@$opts['height'] ? "height='" . @$opts['height'] . "'" : '') . " " .
     "> <source src='" . $path . "' " .
     (@$opts['type'] ? "type='" . @$opts['type'] . "'" : '') . " " .
     ">" . $error . " </video>");
  }
}