<?php

ini_set
('memory_limit''1024M');
if(!(
$argv[1] && $argv[2]))
  die(
"Usage: php youtube-user.php <username> <pattern>\n");

$user $argv[1];
$pattern $argv[2];

echo 
"Attempting to download all videos by user $user matching the pattern '$pattern'\n";

$file file_get_contents('http://www.youtube.com/profile?user='.$user);
preg_match_all('!(watch\?v=[A-Za-z0-9]{11}).*?'.$pattern.'!'$file$matchesPREG_PATTERN_ORDER);
$titles array_unique($matches[1]);

$pids = array();

foreach(
$titles as $title)
{
  
$pid pcntl_fork();
  
  if(
$pid == -1) {
    die(
'could not fork');
  } else if (
$pid) {
    
// we are in the parent
    
$pids[] = $pid;
  } else {
    
// we're in the child - download the movie

    
$page file_get_contents('http://www.youtube.com/'.$title);
    
preg_match('!<title>(.*?)</title>!'$page$matches);
    echo 
'Downloading '.$matches[1]."\n";

    
preg_match('!video_id=.*&t=[^\"&]*!'$page$matches);
    
$video 'http://youtube.com/get_video?'.$matches[0];

    
$video_file file_get_contents($video);
    
$parts explode('='$title);
    
file_put_contents($parts[1].'.flv'$video_file);
    exit();
  }
}

foreach(
$pids as $pid) {
  
pcntl_waitpid($pid$status);
}