<?php
  class cURL
    {
      var $headers;
      var $user_agent;
      var $compression;
      var $cookie_file;
      var $proxy;
      function cURL($cookies = TRUE, $cookie = 'Cookies.txt', $compression = 'gzip', $proxy = '')
        {
          $this->headers[]   = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
          $this->headers[]   = 'Connection: Keep-Alive';
          $this->headers[]   = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
          $this->user_agent  = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)';
          $this->compression = $compression;
          $this->proxy       = $proxy;
          $this->cookies     = $cookies;
          if ($this->cookies == TRUE)
              $this->cookie($cookie);
        }
      function cookie($cookie_file)
        {
          if (file_exists($cookie_file))
            {
              $this->cookie_file = $cookie_file;
            }
          else
            {
              $file = fopen($cookie_file, 'w') or $this->error('The cookie file could not be opened. Make sure this directory has the correct permissions');
              $this->cookie_file = $cookie_file;
              fclose($file);
            }
        }
      function get($url)
        {
          $process = curl_init($url);
          curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
          curl_setopt($process, CURLOPT_HEADER, 0);
          curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
          if ($this->cookies == TRUE)
              curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
          if ($this->cookies == TRUE)
              curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);
          curl_setopt($process, CURLOPT_ENCODING, $this->compression);
          curl_setopt($process, CURLOPT_TIMEOUT, 30);
          if ($this->proxy)
              curl_setopt($process, CURLOPT_PROXY, $this->proxy);
          curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
          $return = curl_exec($process);
          curl_close($process);
          return $return;
        }
      function post($url, $data)
        {
          $process = curl_init($url);
          curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
          curl_setopt($process, CURLOPT_HEADER, 1);
          curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
          if ($this->cookies == TRUE)
              curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
          if ($this->cookies == TRUE)
              curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);
          curl_setopt($process, CURLOPT_ENCODING, $this->compression);
          curl_setopt($process, CURLOPT_TIMEOUT, 30);
          if ($this->proxy)
              curl_setopt($process, CURLOPT_PROXY, $this->proxy);
          curl_setopt($process, CURLOPT_POSTFIELDS, $data);
          curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
          curl_setopt($process, CURLOPT_POST, 1);
          $return = curl_exec($process);
          curl_close($process);
          return $return;
        }
      function error($error)
        {
          echo "cURL Error : $error";
          die;
        }
    }
  echo "\nKSV WeebTV Downloader\n\n";
  $format        = "%-8s : %s\n";
  $ChannelFormat = "%2d) %-22.22s";
  function runAsyncBatch($command, $filename)
    {
      $BatchFile = fopen("WeebTV.bat", 'w');
      fwrite($BatchFile, "@Echo off\r\n");
      fwrite($BatchFile, "Title $filename\r\n");
      fwrite($BatchFile, "$command\r\n");
      fclose($BatchFile);
      $WshShell = new COM("WScript.Shell");
      $oExec    = $WshShell->Run("WeebTV.bat", 1, false);
      unset($WshShell, $oExec);
    }
  function SafeFileName($filename)
    {
      $len = strlen($filename);
      for ($i = 0; $i < $len; $i++)
        {
          $char = ord($filename[$i]);
          if (($char < 32) || ($char >= 127))
              $filename = substr_replace($filename, ' ', $i, 1);
        }
      $filename = preg_replace('/[\/\\\?\*\:\|\<\>]/i', ' ', $filename);
      $filename = preg_replace('/\s\s+/i', ' ', $filename);
      $filename = trim($filename);
      return $filename;
    }
  function KeyName(array $a, $pos)
    {
      $temp = array_slice($a, $pos, 1, true);
      return key($temp);
    }
  function ci_uksort($a, $b)
    {
      $a = strtolower($a);
      $b = strtolower($b);
      if ($a < $b)
          return -1;
      else if ($a == $b)
          return 0;
      else
          return 1;
    }
  function Display($items, $format, $columns)
    {
      $numcols  = $columns;
      $numitems = count($items);
      $numrows  = ceil($numitems / $numcols);
      for ($row = 1; $row <= $numrows; $row++)
        {
          $cell = 0;
          for ($col = 1; $col <= $numcols; $col++)
            {
              if ($col === 1)
                {
                  $cell += $row;
                  printf($format, $cell, KeyName($items, $cell - 1));
                }
              else
                {
                  $cell += $numrows;
                  if (isset($items[KeyName($items, $cell - 1)]))
                      printf($format, $cell, KeyName($items, $cell - 1));
                }
            }
          echo "\n\n";
        }
    }
  if ($argc <= 1)
    {
      $ChannelList["TVP1"]   = "http://weeb.tv/channel/jedynka";
      $ChannelList["TVP2"]   = "http://weeb.tv/channel/dwojka";
      $ChannelList["TVP HD"] = "http://weeb.tv/channel/tvpolskahd";
      $cc   = new cURL();
      $html = $cc->get("http://weeb.tv/channels/live");
      preg_match('/<ul class="channels">(.*?)<\/ul>/is', $html, $html);
      $html = $html[1];
      preg_match_all('/<fieldset.*?>(.*?)<\/fieldset>/is', $html, $fieldSets);
      foreach ($fieldSets[1] as $fieldSet)
        {
          preg_match('/14px.*?<a href="(.*?)".*?>(.*?)<\/a>/is', $fieldSet, $channelVars);
          $ChannelList[$channelVars[2]] = $channelVars[1];
        }
      uksort($ChannelList, 'ci_uksort');
      Display($ChannelList, $ChannelFormat, 3);
      echo "Enter Channel Number : ";
      $channel  = trim(fgets(STDIN));
      $url      = $ChannelList[KeyName($ChannelList, $channel - 1)];
      $filename = KeyName($ChannelList, $channel - 1);
    }
  else
      $url = $argv[1];
  echo "Retrieving html . . .\n";
  if (!isset($cc))
      $cc = new cURL();
  $html = $cc->get($url);
  preg_match('/(flashvars.*?=.*?"&cid=.*?)([\d]{1,5})(.*?")/i', $html, $cid);
  if (!$cid[2])
      die("No channel id found.\n");
  // Retrieve rtmp stream info
  $cc->headers[] = "Referer: http://www.weeb.tv/static/player.swf";
  $response      = $cc->post("http://www.weeb.tv/player.php", "cid=$cid[2]&watchTime=0&firstConnect=1&ip=NaN");
  $result        = explode("\r\n\r\n", $response, 2);
  $flashVars     = explode("&", trim($result[1]));
  foreach ($flashVars as $flashVar)
    {
      $temp                 = explode("=", $flashVar);
      $name                 = strtolower($temp[0]);
      $value                = $temp[1];
      $flashVarArray[$name] = $value;
    }
  $rtmp         = urldecode($flashVarArray["10"]);
  $playpath     = urldecode($flashVarArray["11"]);
  $MultiBitrate = urldecode($flashVarArray["20"]);
  if ($MultiBitrate)
      $playpath .= "HI";
  if (!isset($flashVarArray["15"]))
    {
      // Retrieve authentication ticket
      $response  = $cc->post("http://www.weeb.tv/player.php", "cid=$cid[2]&watchTime=0&firstConnect=0&ip=NaN");
      $result    = explode("\r\n\r\n", $response, 2);
      $flashVars = explode("&", trim($result[1]));
      foreach ($flashVars as $flashVar)
        {
          $temp                 = explode("=", $flashVar);
          $name                 = strtolower($temp[0]);
          $value                = $temp[1];
          $flashVarArray[$name] = $value;
        }
    }
  $ticket = $flashVarArray["15"];
  printf($format, "RTMP Url", $rtmp);
  printf($format, "Playpath", $playpath);
  printf($format, "Ticket", $ticket);
  if (!$ticket)
      die("Server seems busy. please try after some time.\n");
  if (strncasecmp(php_uname('s'), "Win", 3) == 0)
      $windows = true;
  $filename = SafeFileName($filename);
  if (file_exists($filename . ".flv"))
      unlink($filename . ".flv");
  if ($windows)
    {
      if (file_exists("C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe"))
          $vlc = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe";
      else
          $vlc = "C:\\Program Files\\VideoLAN\\VLC\\vlc.exe";
    }
  else
      $vlc = "vlc";
  $command = 'rtmpdump -r "' . $rtmp . "/" . $playpath . '" -W "http://weeb.tv/static/player.swf" --weeb "' . $ticket . "\" --live | \"$vlc\" -";
  printf($format, "Command", $command);
  if ($rtmp && $ticket)
      if ($windows)
          runAsyncBatch($command, $filename);
      else
          exec($command);
  if (file_exists("Cookies.txt"))
      unlink("Cookies.txt");
  echo "Finished.\n";
?>