<?php

function usage() {
   echo 
"Usage: php twitpicGet.php <userid>".PHP_EOL;;
}

$failedURL = array();

function 
my_file_get_contents($url) {
    for (
$i $i $i++) {
       
$data file_get_contents($url);
       if (
$data !== FALSE) {
           break;
       }
       
sleep (10);
    }
    if (
$data === FALSE) {
        
$failedURL[] = $url;
    }
    return 
$data;
}

if (
$argc !== 2) {
    
usage();
    exit (
1); // exit failure
}

$userId $argv[1];

$twitpicURL "http://twitpic.com/photos/{$userId}?page=1";

// echo $twitpicURL.PHP_EOL;

$pageContent my_file_get_contents($twitpicURL);

preg_match('/page=([0-9]+)">Last/'$pageContent$matches);
$lastPageNumber $matches[1];

for (
$pageNumber $pageNumber <= $lastPageNumber $pageNumber++) {
    
$twitpicURL "http://twitpic.com/photos/{$userId}?page={$pageNumber}";
    
$pageContent my_file_get_contents($twitpicURL);
    
preg_match_all('/href="\/([0-9a-z]{6})"/'$pageContent$matches);
    foreach (
$matches[1] as $idx => $picId) {
        
$picPageURL "http://twitpic.com/{$picId}";
    
$picPageContent my_file_get_contents($picPageURL);
        
preg_match('/(https:\/\/.+\/photos\/large\/[^"]+)"/'$picPageContent$picMatches);
    
$picURL $picMatches[1];
    
$picFileTmp substr($picURL0strrpos($picURL'?'));
        
$picFile substr($picFileTmpstrrpos($picURL'/') + 1);
        echo 
"$picURL > $picFile".PHP_EOL;
        
$picData my_file_get_contents($picURL);
        
file_put_contents($picFile$picData);
    }
}

/*
foreach ($failedURL as $idx => $picURL) {
   $picFileTmp = substr($picURL, 0, strrpos($picURL, '?'));
   $picFile = substr($picFileTmp, strrpos($picURL, '/') + 1);
   echo "$picURL > $picFile".PHP_EOL;
   $picData = my_file_get_contents($picURL);
   file_put_contents($picFile, $picData);
   unset($failedURL[$idx]);
}
*/