Return to Snippet

Revision: 45038
at October 26, 2012 07:43 by lasavior


Updated Code
<?php

/*
 * Podcast URL Extractor
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski, zerologic.com
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/the-morning-stream/id414564832?uo=4
 *   Returns: http://myextralife.com/ftp/radio/morningstream.xml

CHANGE LOG:::
EDIT 5/10/11: Removed flat-file database storing. Reformatted for SQLite (requires PHP 5 and above). Script will create database & table if they dont exist.

EDIT 6/2/11: Added safety catch for iTunes-U URL's. (Currently Apple does not offer a way to subscribe to these outside of iTunes [as far as i've seen]). Also touched up a little bit of code here & there.

EDIT 6/21/11: Added another safety catch for iTunes-U pages. Now instead of just checking the URL, it will also check the page content (as there are links that do not include the tag 'itunes-u' that was previously checked for).

EDIT 6/28/11: Previous iTunes-U update was flawed and resulted in a lot of false-positives. Fixed in new update.

EDIT 8/29/11: Added catch for material not available in the US store.

EDIT 9/3/11: Removed POST option, changed to GET only. (if you wish to re-enable it, set $url = $_REQUEST['terms'];)

EDIT 10/16/12: Changed the checkFEED function to look only for "http" instead of "http://" as it would fail on https:// links.
EDIT 10/16/12: Script now checks a URL twice before determining that it doesn't work. Sometimes iTunes just doesn't want to cooperate the first time around.

EDIT 10/23/12: Lots of little changes. Control structure changes (i used alt syntax improperly), plus adding in new error finding.

EIDT 10/25/12: Minor fixes and restructuring to make the code flow better. Also fixed cache displaying error.
 */


//-----------------------------------------
// a couple of settings
$_SETT = array(
	'hashalgo' => 'md5',
	'contactemail' => '[email protected]',
	'dbtable' => 'feedurls',
	'dbfilename' => 'itnfedb.sqdb'
	);

//-----------------------------------------
// the base URL
$url = ($_GET['terms'] != null) ? urldecode(urldecode($_GET['terms'])) : urldecode(urldecode($_SERVER['QUERY_STRING']));
$urlhash = hash($_SETT['hashalgo'], $url);

//-----------------------------------------
//Functions
function curlfeed($churl) {

	$ch = curl_init();
	curl_setopt_array ($ch, array(
		CURLOPT_RETURNTRANSFER => TRUE,
		CURLOPT_FOLLOWLOCATION => TRUE,
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_CONNECTTIMEOUT => 5,
		CURLOPT_URL => $churl,
		CURLOPT_USERAGENT => 'iTunes/9.1.1'
		));
	$chresult = curl_exec($ch);
	curl_close($ch);
	
	return $chresult;
	} //END function: curlfeed

function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {

	$str1 = strpos($urltosub, $string1) + strlen($string1);
	$str2 = strpos($urltosub, $string2, $str1);
	$subbedstring = substr($urltosub, $str1, ($str2 - $str1));
	
	return $subbedstring;
	} //END function: subURL

function checkFEED($thefeed, $mainURL, $isCached = NULL) {
  
	global $feedURL, $invalidURL, $_SETT;
	
	//For your reference, the following is called a HEREDOC
	$badURL = <<<BADURL
    <div style="font-size:15px;white-space:normal;max-width:400px">iTunes failed to return the feed-url. 
    <br>
    <br>This may be due to different reasons: 
    <br>&nbsp;&nbsp;1) the podcast has been deleted,
    <br>&nbsp;&nbsp;2) the podcast has no items,
    <br>&nbsp;&nbsp;3) the podcast may be outside the USA,
    <br>and many other reasons im not aware of. Unfortunately iTunes isnt perfect (hence why your here).
    <br>
    <br>Im sorry my script was of no help to you. If you feel this was in error, you can <a href="outfeed.php?$mainURL" style="text-decoration:underline" target="_blank">view the source,</a><br> or you can always <a href="mailto:{$_SETT['contactemail']}?subject=IFE Error&body=URL i tried: $mainURL" style="display:inline;text-decoration:underline">email me</a> the URL and i will see if its fixable.</div>
BADURL;
	
	if (substr($thefeed, 0, 4) != "http") {
	
		if (is_null($isCached)) {
			
			$feedURL = $badURL;
			} //END if: isCached
		$invalidURL = "The cake is a lie.";
		} //END if: http
	
	} //END function: checkFEED
  
//-----------------------------------------
//Here we initiate the sqlite database and setup the cached variables
if ($database = sqlite_open($_SETT['dbfilename'], 0666, $sqlerror)) {

	$check_cache_query = "SELECT url FROM {$_SETT['dbtable']} WHERE uniqueid='$urlhash'";
	$cache_file = @sqlite_single_query($database, $check_cache_query, true);
	if(sqlite_last_error($database)) {
	
		$create_table_query = "CREATE TABLE {$_SETT['dbtable']}(uniqueid TEXT, url TEXT, date TEXT)";
		@sqlite_exec($database, $create_table_query);
		$cache_file = NULL;
		} //END if: sqlite last error
	} //END if: sqlite open
else {

	$failed_to_initialize_sqlite = $sqlerror;
	} //END if: sqlite open

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if ($cache_file == NULL || isset($failed_to_initialize_sqlite)) {

	//-----------------------------------------
	//Here we identify the podcast url scheme
	$idstyles = array(
		'?id=',
		'&id=',
		'/id'
		);

	for ($counter = 0; $counter < count($idstyles); $counter++) {
	  
		if (strpos($url, $idstyles[$counter])) {
		
			$idstyle = $idstyles[$counter];
			$validID = "So, how are you holding up? Because I'm a potato!";
			break;
			} //END if: idstyles
		} //END for: counter
  
	//-----------------------------------------
	//Since iTunes-U uses the same identifier symbols,
	//this is where we rule them out until it is supported
	//Note: more checking for itunes-u content is done farther below
	if (strpos($url, '/itunes-u/')) {
		
		unset($validID);
		$invalidID = "itunes-u";
		} //END if: itunes-u
		
	//-----------------------------------------
	// extract feed-id, get page from itunes & find feed-url
	if (isset($validID)) {
	
		for ($loopcount = 1; $loopcount < 3; $loopcount++) {
		
			preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
			$curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
			if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1) {
    
				$newURL = subURL($curled1, "<key>url</key><string>", "</string>");
				$curled1 = curlfeed($newURL);
				} //END if:goto
				
			if (strpos($curled1, 'not currently available in the U.S. store')) {
      
				$feedURL = <<<ITUNESFOREIGNSTORE
        <div style="font-size:15px;white-space:normal;max-width:400px">This item is not available in the US store.
        <br>
        <br>(This may also be a problem with the podcast not existing in the iTunes store at all. Unfortunately iTunes returns the same error for both so they are indistinguishable from each other.) Apple currently restricts access to some content based on geographic locations. As I reside in the United States, I cannot retrieve your podcast link.
        <br>
        <br>If you have any PHP knowledge you can try translating the public source code to retrieve the URL on your own: 
        <br>http://snipplr.com/view/52465</div>
ITUNESFOREIGNSTORE;
				$invalidID = 'itunes_foreign';
				} //END if: us store
			elseif (strpos($curled1, '<span class="track-count">0 Items</span>')) {
      
				$emptyPodcastText = <<<EMPTYPODCAST
        <div style="font-size:15px;white-space:normal;max-width:400px"><b>Empty podcast.</b>
        <br>
        <br>Your podcast contains no episodes at the time this script last checked. Unfortunately Apple does not provide the feed URL for empty podcasts. Please check back in as little as 12 hours or once the podcast has active items.</div>
EMPTYPODCAST;
				$feedURL = $emptyPodcastText . "\n" . (time() + 60 * 60 * 12);
				$invalidID = 'empty_podcast';
				} //END if: 0 items
			elseif (strpos($curled1, ' <key>message</key><string>Your request is temporarily unable to be processed.</string>') || strlen($curled1) < 20) {
			
				if ($loopcount == 2) {
				
					$feedURL = <<<CANTPROCESS
        <div style="font-size:15px;white-space:normal;max-width:400px">Temporarily unable to process.
        <br>
        <br>iTunes returned the following error: "Your request is temporarily unable to be processed." Please try again later.</div>
CANTPROCESS;
					$invalidID = $doNotCacheResults = TRUE;
					} //END if: loopcount
				} //END if: unable to process
			elseif (strpos($curled1, 'iTunes U')) { //Leave this as the last elseif as it may catch non-iTunesU material
     
				$itunesU_title = subURL($curled1, '<title>', '</title>');
				$itunesU_title_char = urlencode($itunesU_title);
				$itunesU_crumbs = subURL($curled1, 'start breadcrumbs', 'end breadcrumbs');
				$itunesU_li = subURL($itunesU_crumbs, '<li>', '</li>');
				if (strpos($itunesU_li, 'iTunes U')) {
    
					$feedURL = <<<ITUNESU
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itunesU_title"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itunesU_title_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
ITUNESU;
					$invalidID = 'itunes-u';
					} //END if: itunesu_li
				} //END if: iTunes U
			if (!isset($invalidID)) {

				$feedURL = subURL($curled1);
				checkFEED($feedURL, $url);
				if (isset($invalidURL) && $loopcount == 1) {
				
					unset($invalidURL, $podid);
					sleep(2);
					} // END if: loopcount
				else {
				
					break;
					} //END if: loopcount
				} //END if: invalidID
			else {
			
				break;
				} //END if: invalidID
			} //END for: loopcount
			
		if (!isset($failed_to_initialize_sqlite) && !isset($doNotCacheResults)) {
    
			$newfeedURL = sqlite_escape_string($feedURL);
			$cache_query_put_content = "INSERT INTO {$_SETT['dbtable']} (uniqueid,url,date) VALUES ('$urlhash', '$newfeedURL', '".date("r")."'";
			@sqlite_exec($database, $cache_query_put_content);
			} //END if: failed sqlite
		} //END if: validID
	else {
  
		if ($invalidID == "itunes-u") {
    
			//Example URL: http://itunes.apple.com/itunes-u/the-civil-war-reconstruction/id341650730
			$itu_label = subURL($url, '/itunes-u/', '/');
			$itu_label_white = trim(ucwords(str_replace('-', ' ', $itu_label)));
			$itu_label_char = str_replace('-', '%20', $itu_label);
			$feedURL = <<<FEEDURL
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itu_label_white"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itu_label_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
FEEDURL;
			} //END if: itunes-u
		else {
    
			$feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error&body=Error on URL:$url' style=\"display:inline;text-decoration:underline\">{$_SETT['contactemail']}</a> <br>and notify me of the URL you are trying.";
			$invalidID = "I was doing fine. Noone was trying to murder me, or put me in a potato, or feed me to birds.";
			} //END if: itunes-u
		} //END if: validID
	} //END if: cache_file
else {

	$feedURL = $cache_file;
	if (strpos($feedURL, '<b>Empty podcast.</b>')) {
    
		$invalidID = TRUE;
		$feedURL_explode = explode("\n", $feedURL);
		if (time() > (int)trim(end($feedURL_explode))) {
      
			$delete_table_query = "DELETE FROM {$_SETT['dbtable']} WHERE uniqueid='$urlhash'";
			@sqlite_exec($database, $delete_table_query);
			header("Location: " . $_SERVER["SCRIPT_URI"] . "?" . $_SERVER["QUERY_STRING"]);
			exit;
			} //END if: time
		else {
      
			$feedURL = implode("\n", explode("\n", $feedURL, -1));
			} //END if: time
		} //END if: empty podcast
	elseif (stripos($feedURL, 'itunes-u')) {

		$invalidID = 'itunes-u';
		} //END elseif: itunes-u
	else {

		checkFEED($feedURL, $url, TRUE);
		} //END if: empty podcast
	} //END if: cache_file

//-----------------------------------------
// html output to browser
$podcastURL = (isset($invalidURL) || isset($invalidID)) ? ($invalidID == 'empty_podcast' ? $emptyPodcastText : $feedURL) : "<a href=\"$feedURL\">$feedURL</a>";

echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;"> 
  <head> 
    <title>Podcast URL</title> 
    <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
    <meta name="robots" content="NOINDEX, NOFOLLOW, NOARCHIVE, NOSNIPPET"> 
    <style type="text/css" media="screen">@import "iphonenav.css";</style>
    <link rel="apple-touch-icon" href="./icon.png" />
    <link rel="shortcut icon" href="./favicon.ico">
  </head> 
  
  <!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
  <!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
  <!-- For the PHP code to extract the podcast feed yourself, visit http://snipplr.com/view/52465 --> 
   
  <body style="height: 100%;"> 
     
    <h1>Podcast URL:</h1> 
    <ul> 
        <li style="height: 100%; padding:10px 10px 10px 10px; font-size:20px; word-wrap:break-word">$podcastURL</li> 
        <li style="height: 100%; padding:10px 10px 10px 10px; font-size:10px; border-bottom: 0px solid;"><div style="color:LightGray;font-size:12px;"><a href="mailto:[email protected]" style="color:LightGray; font-size:12px; text-decoration:none;">[email protected]</a>&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;<a href="http://podcasturlextractor.blogspot.com/" style="color:LightGray; font-size:12px; text-decoration:none;" target="_blank">News</a>&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;<a href="http://podcasturlextractor.blogspot.com/p/what-it-is-and-why-its-here.html" style="color:LightGray; font-size:12px; text-decoration:none;" target="_blank">About</a></div></li>
    </ul> 
  </body> 
</html>
OUTTEXT;

?>

Revision: 45037
at October 24, 2012 17:15 by lasavior


Updated Code
<?php

/*
 * Podcast URL Extractor
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski, zerologic.com
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/the-morning-stream/id414564832?uo=4
 *   Returns: http://myextralife.com/ftp/radio/morningstream.xml

CHANGE LOG:::
EDIT 5/10/11: Removed flat-file database storing. Reformatted for SQLite (requires PHP 5 and above). Script will create database & table if they dont exist.

EDIT 6/2/11: Added safety catch for iTunes-U URL's. (Currently Apple does not offer a way to subscribe to these outside of iTunes [as far as i've seen]). Also touched up a little bit of code here & there.

EDIT 6/21/11: Added another safety catch for iTunes-U pages. Now instead of just checking the URL, it will also check the page content (as there are links that do not include the tag 'itunes-u' that was previously checked for).

EDIT 6/28/11: Previous iTunes-U update was flawed and resulted in a lot of false-positives. Fixed in new update.

EDIT 8/29/11: Added catch for material not available in the US store.

EDIT 9/3/11: Removed POST option, changed to GET only. (if you wish to re-enable it, set $url = $_REQUEST['terms'];)

EDIT 10/16/12: Changed the checkFEED function to look only for "http" instead of "http://" as it would fail on https:// links.
EDIT 10/16/12: Script now checks a URL twice before determining that it doesn't work. Sometimes iTunes just doesn't want to cooperate the first time around.

EDIT 10/23/12: Lots of little changes. Control structure changes (i used alt syntax improperly), plus adding in new error finding.
 */


//-----------------------------------------
// a couple of settings
$_SETT = array(
	'hashalgo' => 'md5',
	'contactemail' => '[email protected]',
	'dbtable' => 'feedurls',
	'dbfilename' => 'itnfedb.sqdb'
	);

//-----------------------------------------
// the base URL
$url = ($_GET['terms'] != null) ? urldecode(urldecode($_GET['terms'])) : urldecode(urldecode($_SERVER['QUERY_STRING']));
$urlhash = hash($_SETT['hashalgo'], $url);

//-----------------------------------------
//Functions
function curlfeed($churl) {

	$ch = curl_init();
	curl_setopt_array ($ch, array(
		CURLOPT_RETURNTRANSFER => TRUE,
		CURLOPT_FOLLOWLOCATION => TRUE,
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_CONNECTTIMEOUT => 5,
		CURLOPT_URL => $churl,
		CURLOPT_USERAGENT => 'iTunes/9.1.1'
		));
	$chresult = curl_exec($ch);
	curl_close($ch);
	
	return $chresult;
	} //END function: curlfeed

function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {

	$str1 = strpos($urltosub, $string1) + strlen($string1);
	$str2 = strpos($urltosub, $string2, $str1);
	$subbedstring = substr($urltosub, $str1, ($str2 - $str1));
	
	return $subbedstring;
	} //END function: subURL

function checkFEED($thefeed, $mainURL) {
  
	global $feedURL, $invalidURL, $_SETT;
	
	//For your reference, the following is called a HEREDOC
	$badURL = <<<BADURL
    <div style="font-size:15px;white-space:normal;max-width:400px">iTunes failed to return the feed-url. 
    <br>
    <br>This may be due to different reasons: 
    <br>&nbsp;&nbsp;1) the podcast has been deleted,
    <br>&nbsp;&nbsp;2) the podcast has no items,
    <br>&nbsp;&nbsp;3) the podcast may be outside the USA,
    <br>and many other reasons im not aware of. Unfortunately iTunes isnt perfect (hence why your here).
    <br>
    <br>Im sorry my script was of no help to you. If you feel this was in error, you can <a href="outfeed.php?$mainURL" style="text-decoration:underline" target="_blank">view the source,</a><br> or you can always <a href="mailto:{$_SETT['contactemail']}?subject=IFE Error&body=URL i tried: $mainURL" style="display:inline;text-decoration:underline">email me</a> the URL and i will see if its fixable.</div>
BADURL;
	
	if (substr($thefeed, 0, 4) != "http") {
	
		$feedURL = $badURL;
		$invalidURL = "The cake is a lie.";
		} //END if: http
	
	} //END function: checkFEED
  
//-----------------------------------------
//Here we initiate the sqlite database and setup the cached variables
if ($database = sqlite_open($_SETT['dbfilename'], 0666, $sqlerror)) {

	$check_cache_query = "SELECT url FROM {$_SETT['dbtable']} WHERE uniqueid='$urlhash'";
	$cache_file = @sqlite_single_query($database, $check_cache_query, true);
	if(sqlite_last_error($database)) {
	
		$create_table_query = "CREATE TABLE {$_SETT['dbtable']}(uniqueid TEXT, url TEXT, date TEXT)";
		@sqlite_exec($database, $create_table_query);
		$cache_file = NULL;
		} //END if: sqlite last error
	} //END if: sqlite open
else {

	$failed_to_initialize_sqlite = $sqlerror;
	} //END if: sqlite open

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if ($cache_file == NULL || isset($failed_to_initialize_sqlite)) {

	//-----------------------------------------
	//Here we identify the podcast url scheme
	$idstyles = array(
		'?id=',
		'&id=',
		'/id'
		);

	for ($counter = 0; $counter < count($idstyles); $counter++) {
	  
		if (strpos($url, $idstyles[$counter])) {
		
			$idstyle = $idstyles[$counter];
			$validID = "So, how are you holding up? Because I'm a potato!";
			break;
			} //END if: idstyles
		} //END for: counter
  
	//-----------------------------------------
	//Since iTunes-U uses the same identifier symbols,
	//this is where we rule them out until it is supported
	//Note: more checking for itunes-u content is done further below
	if (strpos($url, '/itunes-u/')) {
		
		unset($validID);
		$invalidID = "itunes-u";
		} //END if: itunes-u
		
	//-----------------------------------------
	// extract feed-id, get page from itunes & find feed-url
	if (isset($validID)) {
	
		for ($loopcount = 1; $loopcount < 3; $loopcount++) {
		
			preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
			$curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
			if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1) {
    
				$newURL = subURL($curled1, "<key>url</key><string>", "</string>");
				$curled1 = curlfeed($newURL);
				} //END if:goto
				
			if (strpos($curled1, 'iTunes U')) {
     
				$itunesU_title = subURL($curled1, '<title>', '</title>');
				$itunesU_title_char = urlencode($itunesU_title);
				$itunesU_crumbs = subURL($curled1, 'start breadcrumbs', 'end breadcrumbs');
				$itunesU_li = subURL($itunesU_crumbs, '<li>', '</li>');
				if (strpos($itunesU_li, 'iTunes U')) {
    
					$feedURL = <<<ITUNESU
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itunesU_title"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itunesU_title_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
ITUNESU;
					$invalidID = $invalidID_check = 'itunes-u';
					} //END if: itunesu_li
				} //END if: iTunes U
			if (!isset($invalidID_check) && strpos($curled1, 'not currently available in the U.S. store')) {
      
				$feedURL = <<<ITUNESFOREIGNSTORE
        <div style="font-size:15px;white-space:normal;max-width:400px">This item is not available in the US store.
        <br>
        <br>Apple currently restricts access to some content based on geographic locations. As I reside in the United States, I unfortunately cannot help you with your podcast link.
        <br>
        <br>If you have any PHP knowledge you can use the public source code to retrieve the URL yourself: 
        <br>http://snipplr.com/view/52465</div>
ITUNESFOREIGNSTORE;
				$invalidID = $invalidID_check = 'itunes_foreign';
				} //END if: us store
			elseif (!isset($invalidID_check) && strpos($curled1, '<span class="track-count">0 Items</span>')) {
      
				$emptyPodcastText = <<<EMPTYPODCAST
        <div style="font-size:15px;white-space:normal;max-width:400px"><b>Empty podcast.</b>
        <br>
        <br>Your podcast contains no episodes at the time this script last checked. Unfortunately Apple does not provide the feed URL for empty podcasts. Please check back in as little as 12 hours or once the podcast has active items.</div>
EMPTYPODCAST;
				$feedURL = $emptyPodcastText . "\n" . (time() + 60 * 60 * 12);
				$invalidID = $invalidID_check = 'empty_podcast';
				} //END if: 0 items
			elseif (!isset($invalidID_check) && strpos($curled1, ' <key>message</key><string>Your request is temporarily unable to be processed.</string>')) {
			
				$invalidID_check = $doNotCacheResults = true;
				$feedURL = <<<CANTPROCESS
        <div style="font-size:15px;white-space:normal;max-width:400px">Temporarily unable to process.
        <br>
        <br>iTunes returned the following error: "Your request is temporarily unable to be processed." Please try again.</div>
CANTPROCESS;
				} //END if: unable to process
			if (!isset($invalidID_check)) {

				$feedURL = subURL($curled1);
				checkFEED($feedURL, $url);
				if (isset($invalidURL) && $loopcount == 1) {
				
					unset($invalidURL, $podid);
					sleep(2);
					} // END if: loopcount
				else {
				
					break;
					} //END if: loopcount
				} //END if: invalidID_check
			else {
			
				break;
				} //END if: invalidID_check
			} //END for: loopcount
			
		if (!isset($failed_to_initialize_sqlite) && !isset($doNotCacheResults)) {
    
			$newfeedURL = sqlite_escape_string($feedURL);
			$cache_query_put_content = "INSERT INTO {$_SETT['dbtable']} (uniqueid,url,date) VALUES ('$urlhash', '$newfeedURL', '".date("r")."'";
			@sqlite_exec($database, $cache_query_put_content);
			} //END if: failed sqlite
		} //END if: validID
	else {
  
		if ($invalidID == "itunes-u") {
    
			//Example URL: http://itunes.apple.com/itunes-u/the-civil-war-reconstruction/id341650730
			$itu_label = subURL($url, '/itunes-u/', '/');
			$itu_label_white = trim(ucwords(str_replace('-', ' ', $itu_label)));
			$itu_label_char = str_replace('-', '%20', $itu_label);
			$feedURL = <<<FEEDURL
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itu_label_white"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itu_label_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
FEEDURL;
			} //END if: itunes-u
		else {
    
			$feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error&body=Error on URL:$url' style=\"display:inline;text-decoration:underline\">{$_SETT['contactemail']}</a> <br>and notify me of the URL you are trying.";
			$invalidID = "I was doing fine. Noone was trying to murder me, or put me in a potato, or feed me to birds.";
			} //END if: itunes-u
		} //END if: validID
	} //END if: cache_file
else {

	$feedURL = $cache_file;
	if (strpos($feedURL, '<b>Empty podcast.</b>')) {
    
    	$invalidID = 1;
		$feedURL_explode = explode("\n", $feedURL);
		if (time() > (int)trim(end($feedURL_explode))) {
      
			$delete_table_query = "DELETE FROM {$_SETT['dbtable']} WHERE uniqueid='$urlhash'";
			@sqlite_exec($database, $delete_table_query);
			header("Location: " . $_SERVER["SCRIPT_URI"] . "?" . $_SERVER["QUERY_STRING"]);
			exit;
			} //END if: time
		else {
      
			$feedURL = implode("\n", explode("\n", $feedURL, -1));
			} //END if: time
		} //END if: empty podcast
	elseif (!stripos($feedURL, 'itunes-u')) {

		checkFEED($feedURL, $url);
		} //END elseif: empty podcast
	else {

		$invalidID = 'itunes-u';
		} //END if: empty podcast
	} //END if: cache_file

//-----------------------------------------
// html output to browser
$podcastURL = (isset($invalidURL) || isset($invalidID)) ? ($invalidID == 'empty_podcast' ? $emptyPodcastText : $feedURL) : "<a href=\"$feedURL\">$feedURL</a>";

echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;"> 
  <head> 
    <title>Podcast URL</title> 
    <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
    <meta name="robots" content="NOINDEX, NOFOLLOW, NOARCHIVE, NOSNIPPET"> 
    <style type="text/css" media="screen">@import "iphonenav.css";</style>
    <link rel="apple-touch-icon" href="./icon.png" />
    <link rel="shortcut icon" href="./favicon.ico">
  </head> 
  
  <!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
  <!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
  <!-- For the PHP code to extract the podcast feed yourself, visit http://snipplr.com/view/52465 --> 
   
  <body style="height: 100%;"> 
     
    <h1>Podcast URL:</h1> 
    <ul> 
        <li style="height: 100%; padding:10px 10px 10px 10px; font-size:20px; word-wrap:break-word">$podcastURL</li> 
        <li style="height: 100%; padding:10px 10px 10px 10px; font-size:10px; border-bottom: 0px solid;"><div style="color:LightGray;font-size:12px;"><a href="mailto:[email protected]" style="color:LightGray; font-size:12px; text-decoration:none;">[email protected]</a>&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;<a href="http://podcasturlextractor.blogspot.com/" style="color:LightGray; font-size:12px; text-decoration:none;" target="_blank">News</a>&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;<a href="http://podcasturlextractor.blogspot.com/p/what-it-is-and-why-its-here.html" style="color:LightGray; font-size:12px; text-decoration:none;" target="_blank">About</a></div></li>
    </ul> 
  </body> 
</html>
OUTTEXT;

?>

Revision: 45036
at October 24, 2012 17:03 by lasavior


Updated Code
<?php

/*
 * Podcast URL Extractor
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski, zerologic.com
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/the-morning-stream/id414564832?uo=4
 *   Returns: http://myextralife.com/ftp/radio/morningstream.xml

CHANGE LOG:::
EDIT 5/10/11: Removed flat-file database storing. Reformatted for SQLite (requires PHP 5 and above). Script will create database & table if they dont exist.

EDIT 6/2/11: Added safety catch for iTunes-U URL's. (Currently Apple does not offer a way to subscribe to these outside of iTunes [as far as i've seen]). Also touched up a little bit of code here & there.

EDIT 6/21/11: Added another safety catch for iTunes-U pages. Now instead of just checking the URL, it will also check the page content (as there are links that do not include the tag 'itunes-u' that was previously checked for).

EDIT 6/28/11: Previous iTunes-U update was flawed and resulted in a lot of false-positives. Fixed in new update.

EDIT 8/29/11: Added catch for material not available in the US store.

EDIT 9/3/11: Removed POST option, changed to GET only. (if you wish to re-enable it, set $url = $_REQUEST['terms'];)

EDIT 10/16/12: Changed the checkFEED function to look only for "http" instead of "http://" as it would fail on https:// links.
EDIT 10/16/12: Script now checks a URL twice before determining that it doesn't work. Sometimes iTunes just doesn't want to cooperate the first time around.

EDIT 10/23/12: Lots of little changes. Control structure changes (i used alt syntax improperly), plus adding in new error finding.
 */


//-----------------------------------------
// a couple of settings
$_SETT = array(
	'hashalgo' => 'md5',
	'contactemail' => '[email protected]',
	'dbtable' => 'feedurls',
	'dbfilename' => 'itnfedb.sqdb'
	);

//-----------------------------------------
// the base URL
$url = ($_GET['terms'] != null) ? urldecode(urldecode($_GET['terms'])) : urldecode(urldecode($_SERVER['QUERY_STRING']));
$urlhash = hash($_SETT['hashalgo'], $url);

//-----------------------------------------
//Functions
function curlfeed($churl) {

	$ch = curl_init();
	curl_setopt_array ($ch, array(
		CURLOPT_RETURNTRANSFER => TRUE,
		CURLOPT_FOLLOWLOCATION => TRUE,
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_CONNECTTIMEOUT => 5,
		CURLOPT_URL => $churl,
		CURLOPT_USERAGENT => 'iTunes/9.1.1'
		));
	$chresult = curl_exec($ch);
	curl_close($ch);
	
	return $chresult;
	} //END function: curlfeed

function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {

	$str1 = strpos($urltosub, $string1) + strlen($string1);
	$str2 = strpos($urltosub, $string2, $str1);
	$subbedstring = substr($urltosub, $str1, ($str2 - $str1));
	
	return $subbedstring;
	} //END function: subURL

function checkFEED($thefeed, $mainURL) {
  
	global $feedURL, $invalidURL, $_SETT;
	
	//For your reference, the following is called a HEREDOC
	$badURL = <<<BADURL
    <div style="font-size:15px;white-space:normal;max-width:400px">iTunes failed to return the feed-url. 
    <br>
    <br>This may be due to different reasons: 
    <br>&nbsp;&nbsp;1) the podcast has been deleted,
    <br>&nbsp;&nbsp;2) the podcast has no items,
    <br>&nbsp;&nbsp;3) the podcast may be outside the USA,
    <br>and many other reasons im not aware of. Unfortunately iTunes isnt perfect (hence why your here).
    <br>
    <br>Im sorry my script was of no help to you. If you feel this was in error, you can <a href="outfeed.php?$mainURL" style="text-decoration:underline" target="_blank">view the source,</a><br> or you can always <a href="mailto:{$_SETT['contactemail']}?subject=IFE Error&body=URL i tried: $mainURL" style="display:inline;text-decoration:underline">email me</a> the URL and i will see if its fixable.</div>
BADURL;
	
	if (substr($thefeed, 0, 4) != "http") {
	
		$feedURL = $badURL;
		$invalidURL = "The cake is a lie.";
		} //END if: http
	
	} //END function: checkFEED
  
//-----------------------------------------
//Here we initiate the sqlite database and setup the cached variables
if ($database = sqlite_open($_SETT['dbfilename'], 0666, $sqlerror)) {

	$check_cache_query = "SELECT url FROM {$_SETT['dbtable']} WHERE uniqueid='$urlhash'";
	$cache_file = @sqlite_single_query($database, $check_cache_query, true);
	if(sqlite_last_error($database)) {
	
		$create_table_query = "CREATE TABLE {$_SETT['dbtable']}(uniqueid TEXT, url TEXT, date TEXT)";
		@sqlite_exec($database, $create_table_query);
		$cache_file = NULL;
		} //END if: sqlite last error
	} //END if: sqlite open
else {

	$failed_to_initialize_sqlite = $sqlerror;
	} //END if: sqlite open

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if ($cache_file == NULL || isset($failed_to_initialize_sqlite)) {

	//-----------------------------------------
	//Here we identify the podcast url scheme
	$idstyles = array(
		'?id=',
		'&id=',
		'/id'
		);

	for ($counter = 0; $counter < count($idstyles); $counter++) {
	  
		if (strpos($url, $idstyles[$counter])) {
		
			$idstyle = $idstyles[$counter];
			$validID = "So, how are you holding up? Because I'm a potato!";
			break;
			} //END if: idstyles
		} //END for: counter
  
	//-----------------------------------------
	//Since iTunes-U uses the same identifier symbols,
	//this is where we rule them out until it is supported
	//Note: more checking for itunes-u content is done further below
	if (strpos($url, '/itunes-u/')) {
		
		unset($validID);
		$invalidID = "itunes-u";
		} //END if: itunes-u
		
	//-----------------------------------------
	// extract feed-id, get page from itunes & find feed-url
	if (isset($validID)) {
	
		for ($loopcount = 1; $loopcount < 3; $loopcount++) {
		
			preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
			$curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
			if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1) {
    
				$newURL = subURL($curled1, "<key>url</key><string>", "</string>");
				$curled1 = curlfeed($newURL);
				} //END if:goto
				
			if (strpos($curled1, 'iTunes U')) {
     
				$itunesU_title = subURL($curled1, '<title>', '</title>');
				$itunesU_title_char = urlencode($itunesU_title);
				$itunesU_crumbs = subURL($curled1, 'start breadcrumbs', 'end breadcrumbs');
				$itunesU_li = subURL($itunesU_crumbs, '<li>', '</li>');
				if (strpos($itunesU_li, 'iTunes U')) {
    
					$feedURL = <<<ITUNESU
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itunesU_title"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itunesU_title_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
ITUNESU;
					$invalidID = $invalidID_check = 'itunes-u';
					} //END if: itunesu_li
				} //END if: iTunes U
			if (!isset($invalidID_check) && strpos($curled1, 'not currently available in the U.S. store')) {
      
				$feedURL = <<<ITUNESFOREIGNSTORE
        <div style="font-size:15px;white-space:normal;max-width:400px">This item is not available in the US store.
        <br>
        <br>Apple currently restricts access to some content based on geographic locations. As I reside in the United States, I unfortunately cannot help you with your podcast link.
        <br>
        <br>If you have any PHP knowledge you can use the public source code to retrieve the URL yourself: 
        <br>http://snipplr.com/view/52465</div>
ITUNESFOREIGNSTORE;
				$invalidID = $invalidID_check = 'itunes_foreign';
				} //END if: us store
			elseif (!isset($invalidID_check) && strpos($curled1, '<span class="track-count">0 Items</span>')) {
      
				$emptyPodcastText = <<<EMPTYPODCAST
        <div style="font-size:15px;white-space:normal;max-width:400px"><b>Empty podcast.</b>
        <br>
        <br>Your podcast contains no episodes at the time this script last checked. Unfortunately Apple does not provide the feed URL for empty podcasts. Please check back in as little as 12 hours or once the podcast has active items.</div>
EMPTYPODCAST;
				$feedURL = $emptyPodcastText . "\n" . (time() + 60 * 60 * 12);
				$invalidID = $invalidID_check = 'empty_podcast';
				} //END if: 0 items
			elseif (!isset($invalidID_check) && strpos($curled1, ' <key>message</key><string>Your request is temporarily unable to be processed.</string>')) {
			
				$invalidID_check = $doNotCacheResults = true;
				$feedURL = <<<CANTPROCESS
        <div style="font-size:15px;white-space:normal;max-width:400px">Temporarily unable to process.
        <br>
        <br>iTunes returned the following error: "Your request is temporarily unable to be processed." Please try again.</div>
CANTPROCESS;
				} //END if: unable to process
			if (!isset($invalidID_check)) {

				$feedURL = subURL($curled1);
				checkFEED($feedURL, $url);
				if (isset($invalidURL) && $loopcount == 1) {
				
					unset($invalidURL, $podid);
					sleep(2);
					} // END if: loopcount
				else {
				
					break;
					} //END if: loopcount
				} //END if: invalidID_check
			else {
			
				break;
				} //END if: invalidID_check
			} //END for: loopcount
			
		if (!isset($failed_to_initialize_sqlite) && !isset($doNotCacheResults)) {
    
			$newfeedURL = sqlite_escape_string($feedURL);
			$cache_query_put_content = "INSERT INTO {$_SETT['dbtable']} (uniqueid,url,date) VALUES ('$urlhash', '$newfeedURL', '".date("r")."'";
			@sqlite_exec($database, $cache_query_put_content);
			} //END if: failed sqlite
		} //END if: validID
	else {
  
		if ($invalidID == "itunes-u") {
    
			//Example URL: http://itunes.apple.com/itunes-u/the-civil-war-reconstruction/id341650730
			$itu_label = subURL($url, '/itunes-u/', '/');
			$itu_label_white = trim(ucwords(str_replace('-', ' ', $itu_label)));
			$itu_label_char = str_replace('-', '%20', $itu_label);
			$feedURL = <<<FEEDURL
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itu_label_white"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itu_label_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
FEEDURL;
			} //END if: itunes-u
		else {
    
			$feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error&body=Error on URL:$url' style=\"display:inline;text-decoration:underline\">{$_SETT['contactemail']}</a> <br>and notify me of the URL you are trying.";
			$invalidID = "I was doing fine. Noone was trying to murder me, or put me in a potato, or feed me to birds.";
			} //END if: itunes-u
		} //END if: validID
	} //END if: cache_file
else {

	$feedURL = $cache_file;
	if (strpos($feedURL, '<b>Empty podcast.</b>')) {
    
    	$invalidID = 1;
		$feedURL_explode = explode("\n", $feedURL);
		if (time() > (int)trim(end($feedURL_explode))) {
      
			$delete_table_query = "DELETE FROM {$_SETT['dbtable']} WHERE uniqueid='$urlhash'";
			@sqlite_exec($database, $delete_table_query);
			header("Location: " . $_SERVER["SCRIPT_URI"] . $_SERVER["QUERY_STRING"]);
			exit;
			} //END if: time
		else {
      
			$feedURL = implode("\n", explode("\n", $feedURL, -1));
			} //END if: time
		} //END if: empty podcast
	elseif (!stripos($feedURL, 'itunes-u')) {

		checkFEED($feedURL, $url);
		} //END elseif: empty podcast
	else {

		$invalidID = 'itunes-u';
		} //END if: empty podcast
	} //END if: cache_file

//-----------------------------------------
// html output to browser
$podcastURL = (isset($invalidURL) || isset($invalidID)) ? ($invalidID == 'empty_podcast' ? $emptyPodcastText : $feedURL) : "<a href=\"$feedURL\">$feedURL</a>";

echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;"> 
  <head> 
    <title>Podcast URL</title> 
    <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
    <meta name="robots" content="NOINDEX, NOFOLLOW, NOARCHIVE, NOSNIPPET"> 
    <style type="text/css" media="screen">@import "iphonenav.css";</style>
    <link rel="apple-touch-icon" href="./icon.png" />
    <link rel="shortcut icon" href="./favicon.ico">
  </head> 
  
  <!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
  <!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
  <!-- For the PHP code to extract the podcast feed yourself, visit http://snipplr.com/view/52465 --> 
   
  <body style="height: 100%;"> 
     
    <h1>Podcast URL:</h1> 
    <ul> 
        <li style="height: 100%; padding:10px 10px 10px 10px; font-size:20px; word-wrap:break-word">$podcastURL</li> 
        <li style="height: 100%; padding:10px 10px 10px 10px; font-size:10px; border-bottom: 0px solid;"><div style="color:LightGray;font-size:12px;"><a href="mailto:[email protected]" style="color:LightGray; font-size:12px; text-decoration:none;">[email protected]</a>&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;<a href="http://podcasturlextractor.blogspot.com/" style="color:LightGray; font-size:12px; text-decoration:none;" target="_blank">News</a>&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;<a href="http://podcasturlextractor.blogspot.com/p/what-it-is-and-why-its-here.html" style="color:LightGray; font-size:12px; text-decoration:none;" target="_blank">About</a></div></li>
    </ul> 
  </body> 
</html>
OUTTEXT;

?>

Revision: 45035
at October 17, 2012 06:02 by lasavior


Updated Code
<?php

/*
 * Podcast URL Extractor
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski, zerologic.com
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/the-morning-stream/id414564832?uo=4
 *   Returns: http://myextralife.com/ftp/radio/morningstream.xml

CHANGE LOG:::
EDIT 5/10/11: Removed flat-file database storing. Reformatted for SQLite (requires PHP 5 and above). Script will create database & table if they dont exist.

EDIT 6/2/11: Added safety catch for iTunes-U URL's. (Currently Apple does not offer a way to subscribe to these outside of iTunes [as far as i've seen]). Also touched up a little bit of code here & there.

EDIT 6/21/11: Added another safety catch for iTunes-U pages. Now instead of just checking the URL, it will also check the page content (as there are links that do not include the tag 'itunes-u' that was previously checked for).

EDIT 6/28/11: Previous iTunes-U update was flawed and resulted in a lot of false-positives. Fixed in new update.

EDIT 8/29/11: Added catch for material not available in the US store.

EDIT 10/16/12: Changed the checkFEED function to look only for "http" instead of "http://" as it would fail on https:// links.
 */


//-----------------------------------------
// a couple of settings
$_SETT = array(
  'hashalgo' => 'md5',
  'contactemail' => '-INSERT-EMAIL-HERE-',
  'dbtable' => 'feedurls',
  'dbfilename' => 'itnfedb.sqdb'
  );

//-----------------------------------------
// the base URL
$url = ($_POST['terms'] != null) ? $_POST['terms'] : $_SERVER['QUERY_STRING'];
$urlhash = hash($_SETT['hashalgo'], $url);

//-----------------------------------------
//Functions
function curlfeed($churl) {

  $ch = curl_init();
  curl_setopt_array ($ch, array(
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_FOLLOWLOCATION => TRUE,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_URL => $churl,
    CURLOPT_USERAGENT => 'iTunes/9.1.1'
    ));
  $chresult = curl_exec($ch);
  curl_close($ch);
  
  return $chresult;
  }

function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {

  $str1 = strpos($urltosub, $string1) + strlen($string1);
  $str2 = strpos($urltosub, $string2, $str1);
  $subbedstring = substr($urltosub, $str1, ($str2 - $str1));
  
  return $subbedstring;
  }

function checkFEED($thefeed, $mainURL) {
  
  global $feedURL, $invalidURL, $_SETT;

  //For your reference, the following is called a HEREDOC
  $badURL = <<<BADURL
    <div style="font-size:15px;white-space:normal;max-width:400px">iTunes failed to return the feed-url. 
    <br>
    <br>This may be due to different reasons: 
    <br>&nbsp;&nbsp;1) the podcast has been deleted,
    <br>&nbsp;&nbsp;2) the podcast has no items,
    <br>and many other reasons im not aware of. Unfortunately iTunes isnt perfect (hence why your here).
    <br>
    <br>Im sorry my script was of no help to you. If you feel this was in error, you can <a href="outfeed.php?$mainURL" style="text-decoration:underline" target="_blank">view the source,</a><br> or you can always <a href="mailto:{$_SETT['contactemail']}?subject=IFE Error&body=URL i tried: $mainURL" style="display:inline;text-decoration:underline">email me</a> the URL and i will see if its fixable.</div>
BADURL;

  if (substr($thefeed, 0, 4) != "http"): 
  
    $feedURL = $badURL;
    $invalidURL = "The cake is a lie.";
    endif;

  }
  
//-----------------------------------------
//Here we initiate the sqlite database and setup the cached variables
if ($database = sqlite_open($_SETT['dbfilename'], 0666, $sqlerror)):

  $check_cache_query = "SELECT url FROM {$_SETT['dbtable']} WHERE uniqueid='$urlhash'";
  $cache_file = @sqlite_single_query($database, $check_cache_query, true);
  if(sqlite_last_error($database)):
  
    $create_table_query = "CREATE TABLE {$_SETT['dbtable']}(uniqueid TEXT, url TEXT, date TEXT)";
    @sqlite_exec($database, $create_table_query);
    $cache_file = NULL;
    endif;
else:

  $failed_to_initialize_sqlite = $sqlerror;
  endif;

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if ($cache_file == NULL || isset($failed_to_initialize_sqlite)):

  //-----------------------------------------
  //Here we identify the podcast url scheme
  $idstyles = array(
    '?id=',
    '&id=',
    '/id'
    );

  for ($counter = 0; $counter < count($idstyles); $counter++):
  
    if (strpos($url, $idstyles[$counter])):
    
      $idstyle = $idstyles[$counter];
      $validID = "So, how are you holding up? Because I'm a potato!";
      break;
      endif;
    endfor;
  
  //-----------------------------------------
  //Since iTunes-U uses the same identifier symbols,
  //this is where we rule them out until it is supported
  //Note: more checking for itunes-u content is done further below
  if (strpos($url, '/itunes-u/')):
    
    unset($validID);
    $invalidID = "itunes-u";
    endif;
  
  //-----------------------------------------
  // extract feed-id, get page from itunes & find feed-url
  if (isset($validID)):
  
    preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
    $curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
    if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1):
    
      $newURL = subURL($curled1, "<key>url</key><string>", "</string>");
      $curled1 = curlfeed($newURL);
      endif;
    if (strpos($curled1, 'iTunes U')):
     
      $itunesU_title = subURL($curled1, '<title>', '</title>');
      $itunesU_title_char = urlencode($itunesU_title);
      $itunesU_crumbs = subURL($curled1, 'start breadcrumbs', 'end breadcrumbs');
      $itunesU_li = subURL($itunesU_crumbs, '<li>', '</li>');
      if (strpos($itunesU_li, 'iTunes U')):
    
        $feedURL = <<<ITUNESU
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itunesU_title"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itunesU_title_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
ITUNESU;
        $invalidID_check = 1;
        $invalidID = 'itunes-u';
        endif;
    elseif (strpos($curled1, 'not currently available in the US store')):
      
      $feedURL = <<<ITUNESFOREIGNSTORE
        <div style="font-size:15px;white-space:normal;max-width:400px">This item is not available in the US store.
        <br>
        <br>Apple currently restricts access to some content based on geographic locations. As I reside in the United States, I unfortunately cannot help you with your podcast link.
        <br>
        <br>If you have any PHP knowledge you can use the public source code to retrieve the URL yourself: 
        <br>http://snipplr.com/view/52465</div>
ITUNESFOREIGNSTORE;
      $invalidID_check = 1;
      $invalidID = 'itunes_foreign';
      endif;
    if ($invalidID_check != 1):

      $feedURL = subURL($curled1);
      checkFEED($feedURL, $url);
      endif;
    if (!isset($failed_to_initialize_sqlite)):
    
      $newfeedURL = sqlite_escape_string($feedURL);
      $cache_query_put_content = "INSERT INTO {$_SETT['dbtable']} (uniqueid,url,date) VALUES ('$urlhash', '$newfeedURL', '".date("r")."')";
      @sqlite_exec($database, $cache_query_put_content);
      endif;
  else: 
  
    if ($invalidID == "itunes-u"):
    
      //Example URL: http://itunes.apple.com/itunes-u/the-civil-war-reconstruction/id341650730
      $itu_label = subURL($url, '/itunes-u/', '/');
      $itu_label_white = trim(ucwords(str_replace('-', ' ', $itu_label)));
      $itu_label_char = str_replace('-', '%20', $itu_label);
      $feedURL = <<<FEEDURL
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itu_label_white"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itu_label_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
FEEDURL;
    else:
    
      $feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error&body=Error on URL:$url' style=\"display:inline;text-decoration:underline\">{$_SETT['contactemail']}</a> <br>and notify me of the URL you are trying.";
      $invalidID = "I was doing fine. Noone was trying to murder me, or put me in a potato, or feed me to birds.";
      endif;
    endif;
else:

  $feedURL = $cache_file;
  if (!stripos($feedURL, 'itunes-u')):

    checkFEED($feedURL, $url);
  else:

    $invalidID = 'itunes-u';
    endif;
  endif;

//-----------------------------------------
// html output to browser
$podcastURL = (isset($invalidURL) || isset($invalidID)) ? $feedURL : "<a href=\"$feedURL\">$feedURL</a>";

echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;"> 
  <head> 
    <title>Podcast URL</title> 
    <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
    <meta name="robots" content="NOINDEX, NOFOLLOW, NOARCHIVE, NOSNIPPET"> 
    <style type="text/css" media="screen">@import "iphonenav.css";</style>
    <link rel="apple-touch-icon" href="./icon.png" />
    <link rel="shortcut icon" href="./favicon.ico">
  </head> 
  
  <!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
  <!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
  <!-- For the PHP code to extract the podcast feed yourself, visit http://snipplr.com/view/52465 --> 
   
  <body style="height: 100%;"> 
     
    <h1>Podcast URL:</h1> 
    <ul> 
        <li style="height: 100%; padding:10px 10px 10px 10px; font-size:20px; word-wrap:break-word">$podcastURL</li> 
        <li style="height: 100%; padding:10px 10px 10px 10px; font-size:10px; border-bottom: 0px solid;"><div style="color:LightGray;font-size:12px;"><a href="mailto:[email protected]" style="color:LightGray; font-size:12px; text-decoration:none;">[email protected]</a>&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;<a href="http://podcasturlextractor.blogspot.com/" style="color:LightGray; font-size:12px; text-decoration:none;" target="_blank">News</a>&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;<a href="http://podcasturlextractor.blogspot.com/p/what-it-is-and-why-its-here.html" style="color:LightGray; font-size:12px; text-decoration:none;" target="_blank">About</a></div></li>
    </ul> 
  </body> 
</html>
OUTTEXT;

?>

Revision: 45034
at August 31, 2011 03:58 by lasavior


Updated Code
<?php

/*
 * Podcast URL Extractor
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski, zerologic.com
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/the-morning-stream/id414564832?uo=4
 *   Returns: http://myextralife.com/ftp/radio/morningstream.xml

CHANGE LOG:::
EDIT 5/10/11: Removed flat-file database storing. Reformatted for SQLite (requires PHP 5 and above). Script will create database & table if they dont exist.

EDIT 6/2/11: Added safety catch for iTunes-U URL's. (Currently Apple does not offer a way to subscribe to these outside of iTunes [as far as i've seen]). Also touched up a little bit of code here & there.

EDIT 6/21/11: Added another safety catch for iTunes-U pages. Now instead of just checking the URL, it will also check the page content (as there are links that do not include the tag 'itunes-u' that was previously checked for).

EDIT 6/28/11: Previous iTunes-U update was flawed and resulted in a lot of false-positives. Fixed in new update.

EDIT 8/29/11: Added catch for material not available in the US store.
 */


//-----------------------------------------
// a couple of settings
$_SETT = array(
  'hashalgo' => 'md5',
  'contactemail' => '-INSERT-EMAIL-HERE-',
  'dbtable' => 'feedurls',
  'dbfilename' => 'itnfedb.sqdb'
  );

//-----------------------------------------
// the base URL
$url = ($_POST['terms'] != null) ? $_POST['terms'] : $_SERVER['QUERY_STRING'];
$urlhash = hash($_SETT['hashalgo'], $url);

//-----------------------------------------
//Functions
function curlfeed($churl) {

  $ch = curl_init();
  curl_setopt_array ($ch, array(
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_FOLLOWLOCATION => TRUE,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_URL => $churl,
    CURLOPT_USERAGENT => 'iTunes/9.1.1'
    ));
  $chresult = curl_exec($ch);
  curl_close($ch);
  
  return $chresult;
  }

function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {

  $str1 = strpos($urltosub, $string1) + strlen($string1);
  $str2 = strpos($urltosub, $string2, $str1);
  $subbedstring = substr($urltosub, $str1, ($str2 - $str1));
  
  return $subbedstring;
  }

function checkFEED($thefeed, $mainURL) {
  
  global $feedURL, $invalidURL, $_SETT;

  //For your reference, the following is called a HEREDOC
  $badURL = <<<BADURL
    <div style="font-size:15px;white-space:normal;max-width:400px">iTunes failed to return the feed-url. 
    <br>
    <br>This may be due to different reasons: 
    <br>&nbsp;&nbsp;1) the podcast has been deleted,
    <br>&nbsp;&nbsp;2) the podcast has no items,
    <br>and many other reasons im not aware of. Unfortunately iTunes isnt perfect (hence why your here).
    <br>
    <br>Im sorry my script was of no help to you. If you feel this was in error, you can <a href="outfeed.php?$mainURL" style="text-decoration:underline" target="_blank">view the source,</a><br> or you can always <a href="mailto:{$_SETT['contactemail']}?subject=IFE Error&body=URL i tried: $mainURL" style="display:inline;text-decoration:underline">email me</a> the URL and i will see if its fixable.</div>
BADURL;

  if (substr($thefeed, 0, 7) != "http://"): 
  
    $feedURL = $badURL;
    $invalidURL = "The cake is a lie.";
    endif;

  }
  
//-----------------------------------------
//Here we initiate the sqlite database and setup the cached variables
if ($database = sqlite_open($_SETT['dbfilename'], 0666, $sqlerror)):

  $check_cache_query = "SELECT url FROM {$_SETT['dbtable']} WHERE uniqueid='$urlhash'";
  $cache_file = @sqlite_single_query($database, $check_cache_query, true);
  if(sqlite_last_error($database)):
  
    $create_table_query = "CREATE TABLE {$_SETT['dbtable']}(uniqueid TEXT, url TEXT, date TEXT)";
    @sqlite_exec($database, $create_table_query);
    $cache_file = NULL;
    endif;
else:

  $failed_to_initialize_sqlite = $sqlerror;
  endif;

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if ($cache_file == NULL || isset($failed_to_initialize_sqlite)):

  //-----------------------------------------
  //Here we identify the podcast url scheme
  $idstyles = array(
    '?id=',
    '&id=',
    '/id'
    );

  for ($counter = 0; $counter < count($idstyles); $counter++):
  
    if (strpos($url, $idstyles[$counter])):
    
      $idstyle = $idstyles[$counter];
      $validID = "So, how are you holding up? Because I'm a potato!";
      break;
      endif;
    endfor;
  
  //-----------------------------------------
  //Since iTunes-U uses the same identifier symbols,
  //this is where we rule them out until it is supported
  //Note: more checking for itunes-u content is done further below
  if (strpos($url, '/itunes-u/')):
    
    unset($validID);
    $invalidID = "itunes-u";
    endif;
  
  //-----------------------------------------
  // extract feed-id, get page from itunes & find feed-url
  if (isset($validID)):
  
    preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
    $curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
    if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1):
    
      $newURL = subURL($curled1, "<key>url</key><string>", "</string>");
      $curled1 = curlfeed($newURL);
      endif;
    if (strpos($curled1, 'iTunes U')):
     
      $itunesU_title = subURL($curled1, '<title>', '</title>');
      $itunesU_title_char = urlencode($itunesU_title);
      $itunesU_crumbs = subURL($curled1, 'start breadcrumbs', 'end breadcrumbs');
      $itunesU_li = subURL($itunesU_crumbs, '<li>', '</li>');
      if (strpos($itunesU_li, 'iTunes U')):
    
        $feedURL = <<<ITUNESU
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itunesU_title"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itunesU_title_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
ITUNESU;
        $invalidID_check = 1;
        $invalidID = 'itunes-u';
        endif;
    elseif (strpos($curled1, 'not currently available in the US store')):
      
      $feedURL = <<<ITUNESFOREIGNSTORE
        <div style="font-size:15px;white-space:normal;max-width:400px">This item is not available in the US store.
        <br>
        <br>Apple currently restricts access to some content based on geographic locations. As I reside in the United States, I unfortunately cannot help you with your podcast link.
        <br>
        <br>If you have any PHP knowledge you can use the public source code to retrieve the URL yourself: 
        <br>http://snipplr.com/view/52465</div>
ITUNESFOREIGNSTORE;
      $invalidID_check = 1;
      $invalidID = 'itunes_foreign';
      endif;
    if ($invalidID_check != 1):

      $feedURL = subURL($curled1);
      checkFEED($feedURL, $url);
      endif;
    if (!isset($failed_to_initialize_sqlite)):
    
      $newfeedURL = sqlite_escape_string($feedURL);
      $cache_query_put_content = "INSERT INTO {$_SETT['dbtable']} (uniqueid,url,date) VALUES ('$urlhash', '$newfeedURL', '".date("r")."')";
      @sqlite_exec($database, $cache_query_put_content);
      endif;
  else: 
  
    if ($invalidID == "itunes-u"):
    
      //Example URL: http://itunes.apple.com/itunes-u/the-civil-war-reconstruction/id341650730
      $itu_label = subURL($url, '/itunes-u/', '/');
      $itu_label_white = trim(ucwords(str_replace('-', ' ', $itu_label)));
      $itu_label_char = str_replace('-', '%20', $itu_label);
      $feedURL = <<<FEEDURL
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itu_label_white"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itu_label_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
FEEDURL;
    else:
    
      $feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error&body=Error on URL:$url' style=\"display:inline;text-decoration:underline\">{$_SETT['contactemail']}</a> <br>and notify me of the URL you are trying.";
      $invalidID = "I was doing fine. Noone was trying to murder me, or put me in a potato, or feed me to birds.";
      endif;
    endif;
else:

  $feedURL = $cache_file;
  if (!stripos($feedURL, 'itunes-u')):

    checkFEED($feedURL, $url);
  else:

    $invalidID = 'itunes-u';
    endif;
  endif;

//-----------------------------------------
// html output to browser
$podcastURL = (isset($invalidURL) || isset($invalidID)) ? $feedURL : "<a href=\"$feedURL\">$feedURL</a>";

echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;"> 
  <head> 
    <title>Podcast URL</title> 
    <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
    <meta name="robots" content="NOINDEX, NOFOLLOW, NOARCHIVE, NOSNIPPET"> 
    <style type="text/css" media="screen">@import "iphonenav.css";</style>
    <link rel="apple-touch-icon" href="./icon.png" />
    <link rel="shortcut icon" href="./favicon.ico">
  </head> 
  
  <!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
  <!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
  <!-- For the PHP code to extract the podcast feed yourself, visit http://snipplr.com/view/52465 --> 
   
  <body style="height: 100%;"> 
     
    <h1>Podcast URL:</h1> 
    <ul> 
        <li style="height: 100%; padding:10px 10px 10px 10px; font-size:20px; word-wrap:break-word">$podcastURL</li> 
        <li style="height: 100%; padding:10px 10px 10px 10px; font-size:10px; border-bottom: 0px solid;"><div style="color:LightGray;font-size:12px;"><a href="mailto:[email protected]" style="color:LightGray; font-size:12px; text-decoration:none;">[email protected]</a>&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;<a href="http://podcasturlextractor.blogspot.com/" style="color:LightGray; font-size:12px; text-decoration:none;" target="_blank">News</a>&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;<a href="http://podcasturlextractor.blogspot.com/p/what-it-is-and-why-its-here.html" style="color:LightGray; font-size:12px; text-decoration:none;" target="_blank">About</a></div></li>
    </ul> 
  </body> 
</html>
OUTTEXT;

?>

Revision: 45033
at June 30, 2011 07:24 by lasavior


Updated Code
<?php

/*
 * Podcast URL Extractor
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski, zerologic.com
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/the-morning-stream/id414564832?uo=4
 *   Returns: http://myextralife.com/ftp/radio/morningstream.xml

CHANGE LOG:::
EDIT 5/10/11: Removed flat-file database storing. Reformatted for SQLite (requires PHP 5 and above). Script will create database & table if they dont exist.

EDIT 6/2/11: Added safety catch for iTunes-U URL's. (Currently Apple does not offer a way to subscribe to these outside of iTunes [as far as i've seen]). Also touched up a little bit of code here & there.

EDIT 6/21/11: Added another safety catch for iTunes-U pages. Now instead of just checking the URL, it will also check the page content (as there are links that do not include the tag 'itunes-u' that was previously checked for).

EDIT 6/28/11: Previous iTunes-U update was flawed and resulted in a lot of false-positives. Fixed in new update.
 */

//-----------------------------------------
// a couple of settings
$_SETT = array(
  'hashalgo' => 'md5',
  'contactemail' => '[email protected]',
  'dbtable' => 'feedurls',
  'dbfilename' => 'itnfedb.sqdb'
  );

//-----------------------------------------
// the base URL
$url = ($_POST['terms'] != null) ? $_POST['terms'] : $_SERVER['QUERY_STRING'];
$urlhash = hash($_SETT['hashalgo'], $url);

//-----------------------------------------
//Functions
function curlfeed($churl) {

  $ch = curl_init();
  curl_setopt_array ($ch, array(
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_FOLLOWLOCATION => TRUE,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_URL => $churl,
    CURLOPT_USERAGENT => 'iTunes/9.1.1'
    ));
  $chresult = curl_exec($ch);
  curl_close($ch);
  
  return $chresult;
  }

function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {

  $str1 = strpos($urltosub, $string1) + strlen($string1);
  $str2 = strpos($urltosub, $string2, $str1);
  $subbedstring = substr($urltosub, $str1, ($str2 - $str1));
  
  return $subbedstring;
  }

function checkFEED($thefeed, $mainURL) {
  
  global $feedURL, $invalidURL, $_SETT;

  //For your reference, the following is called a HEREDOC
  $badURL = <<<BADURL
    <div style="font-size:15px;white-space:normal;max-width:400px">iTunes failed to return the feed-url. 
    <br>
    <br>This may be due to different reasons: 
    <br>&nbsp;&nbsp;1) the podcast has been deleted,
    <br>&nbsp;&nbsp;2) the podcast has no items,
    <br>and many other reasons im not aware of. Unfortunately iTunes isnt perfect (hence why your here).
    <br>
    <br>Im sorry my script was of no help to you. If you feel this was in error, you can <a href="outfeed.php?$mainURL" style="text-decoration:underline" target="_blank">view the source,</a><br> or you can always <a href="mailto:{$_SETT['contactemail']}?subject=IFE Error&body=URL i tried: $mainURL" style="display:inline;text-decoration:underline">email me</a> the URL and i will see if its fixable.</div>
BADURL;

  if (substr($thefeed, 0, 7) != "http://"): 
  
    $feedURL = $badURL;
    $invalidURL = "The cake is a lie.";
    endif;

  }
  
//-----------------------------------------
//Here we initiate the sqlite database and setup the cached variables
if ($database = sqlite_open($_SETT['dbfilename'], 0666, $sqlerror)):

  $check_cache_query = "SELECT url FROM {$_SETT['dbtable']} WHERE uniqueid='$urlhash'";
  $cache_file = @sqlite_single_query($database, $check_cache_query, true);
  if(sqlite_last_error($database)):
  
    $create_table_query = "CREATE TABLE {$_SETT['dbtable']}(uniqueid TEXT, url TEXT, date TEXT)";
    @sqlite_exec($database, $create_table_query);
    $cache_file = NULL;
    endif;
else:

  $failed_to_initialize_sqlite = $sqlerror;
  endif;

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if ($cache_file == NULL || isset($failed_to_initialize_sqlite)):

  //-----------------------------------------
  //Here we identify the podcast url scheme
  $idstyles = array(
    '?id=',
    '&id=',
    '/id'
    );

  for ($counter = 0; $counter < count($idstyles); $counter++):
  
    if (strpos($url, $idstyles[$counter])):
    
      $idstyle = $idstyles[$counter];
      $validID = "So, how are you holding up? Because I'm a potato!";
      break;
      endif;
    endfor;
  
  //-----------------------------------------
  //Since iTunes-U uses the same identifier symbols,
  //this is where we rule them out until it is supported
  //Note: more checking for itunes-u content is done further below
  if (strpos($url, '/itunes-u/')):
    
    unset($validID);
    $invalidID = "itunes-u";
    endif;
  
  //-----------------------------------------
  // extract feed-id, get page from itunes & find feed-url
  if (isset($validID)):
  
    preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
    $curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
    if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1):
    
      $newURL = subURL($curled1, "<key>url</key><string>", "</string>");
      $curled1 = curlfeed($newURL);
      endif;
    if (strpos($curled1, 'iTunes U')):
     
      $itunesU_title = subURL($curled1, '<title>', '</title>');
      $itunesU_title_char = urlencode($itunesU_title);
      $itunesU_crumbs = subURL($curled1, 'start breadcrumbs', 'end breadcrumbs');
      $itunesU_li = subURL($itunesU_crumbs, '<li>', '</li>');
      if (strpos($itunesU_li, 'iTunes U')):
    
        $feedURL = <<<ITUNESU
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itunesU_title"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itunesU_title_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
ITUNESU;
        $itunesU_check = 1;
        $invalidID = 'itunes-u';
        endif;
      endif;
    if ($itunesU_check != 1):

      $feedURL = subURL($curled1);
      checkFEED($feedURL, $url);
      endif;
    if (!isset($failed_to_initialize_sqlite)):
    
      $newfeedURL = sqlite_escape_string($feedURL);
      $cache_query_put_content = "INSERT INTO {$_SETT['dbtable']} (uniqueid,url,date) VALUES ('$urlhash', '$newfeedURL', '".date("r")."')";
      @sqlite_exec($database, $cache_query_put_content);
      endif;
  else: 
  
    if ($invalidID == "itunes-u"):
    
      //Example URL: http://itunes.apple.com/itunes-u/the-civil-war-reconstruction/id341650730
      $itu_label = subURL($url, '/itunes-u/', '/');
      $itu_label_white = trim(ucwords(str_replace('-', ' ', $itu_label)));
      $itu_label_char = str_replace('-', '%20', $itu_label);
      $feedURL = <<<FEEDURL
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itu_label_white"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itu_label_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
FEEDURL;
    else:
    
      $feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error&body=Error on URL:$url' style=\"display:inline;text-decoration:underline\">{$_SETT['contactemail']}</a> <br>and notify me of the URL you are trying.";
      $invalidID = "I was doing fine. Noone was trying to murder me, or put me in a potato, or feed me to birds.";
      endif;
    endif;
else:

  $feedURL = $cache_file;
  if (!stripos($feedURL, 'itunes-u')):

    checkFEED($feedURL, $url);
  else:

    $invalidID = 'itunes-u';
    endif;
  endif;

//-----------------------------------------
// html output to browser
$podcastURL = (isset($invalidURL) || isset($invalidID)) ? $feedURL : "<a href=\"$feedURL\">$feedURL</a>";

echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;"> 
  <head> 
    <title>Podcast URL</title> 
    <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
    <meta name="robots" content="NOINDEX, NOFOLLOW, NOARCHIVE, NOSNIPPET"> 
    <style type="text/css" media="screen">@import "iphonenav.css";</style>
    <link rel="apple-touch-icon" href="./icon.png" />
    <link rel="shortcut icon" href="./favicon.ico">
  </head> 
  
  <!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
  <!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
  <!-- For the PHP code to extract the podcast feed yourself, visit http://snipplr.com/view/52465 --> 
   
  <body style="height: 100%;"> 
     
    <h1>Podcast URL:</h1> 
    <ul> 
        <li style="height: 100%; padding:10px 10px 10px 10px; font-size:20px; word-wrap:break-word">$podcastURL</li>
    </ul> 
  </body> 
</html>
OUTTEXT;

?>

Revision: 45032
at June 22, 2011 09:36 by lasavior


Updated Code
<?php

/*
 * iTunesFeedExtractor 
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski, zerologic.com
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/the-morning-stream/id414564832?uo=4
 *   Returns: http://myextralife.com/ftp/radio/morningstream.xml
 */

//-----------------------------------------
// a couple of settings
$_SETT = array(
  'hashalgo' => 'md5',
  'contactemail' => '[email protected]',
  'dbtable' => 'feedurls',
  'dbfilename' => 'itnfedb.sqdb'
  );

//-----------------------------------------
// the base URL
$url = ($_POST['terms'] != null) ? $_POST['terms'] : $_SERVER['QUERY_STRING'];
$urlhash = hash($_SETT['hashalgo'], $url);

//-----------------------------------------
//Functions
function curlfeed($churl) {

  $ch = curl_init();
  curl_setopt_array ($ch, array(
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_FOLLOWLOCATION => TRUE,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_URL => $churl,
    CURLOPT_USERAGENT => 'iTunes/9.1.1'
    ));
  $chresult = curl_exec($ch);
  curl_close($ch);
  
  return $chresult;
  }

function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {

  $str1 = strpos($urltosub, $string1) + strlen($string1);
  $str2 = strpos($urltosub, $string2, $str1);
  $subbedstring = substr($urltosub, $str1, ($str2 - $str1));
  
  return $subbedstring;
  }

function checkFEED($thefeed, $mainURL) {
  
  global $feedURL, $invalidURL, $_SETT;

  //For your reference, the following is called a HEREDOC
  $badURL = <<<BADURL
    <div style="font-size:15px;white-space:normal;max-width:400px">iTunes failed to return the feed-url. 
    <br>
    <br>This may be due to different reasons: 
    <br>&nbsp;&nbsp;1) the podcast has been deleted,
    <br>&nbsp;&nbsp;2) the podcast has no items,
    <br>and many other reasons im not aware of. Unfortunately iTunes isnt perfect (hence why your here).
    <br>
    <br>Im sorry my script was of no help to you. If you feel this was in error, you can <a href="outfeed.php?$mainURL" style="text-decoration:underline" target="_blank">view the source,</a><br> or you can always <a href="mailto:{$_SETT['contactemail']}?subject=IFE Error&body=URL i tried: $mainURL" style="display:inline;text-decoration:underline">email me</a> the URL and i will see if its fixable.</div>
BADURL;

  if (substr($thefeed, 0, 7) != "http://"): 
  
    $feedURL = $badURL;
    $invalidURL = "The cake is a lie.";
    endif;

  }
  
//-----------------------------------------
//Here we initiate the sqlite database and setup the cached variables
if ($database = sqlite_open($_SETT['dbfilename'], 0666, $sqlerror)):

  $check_cache_query = "SELECT url FROM {$_SETT['dbtable']} WHERE uniqueid='$urlhash'";
  $cache_file = @sqlite_single_query($database, $check_cache_query, true);
  if(sqlite_last_error($database)):
  
    $create_table_query = "CREATE TABLE {$_SETT['dbtable']}(uniqueid TEXT, url TEXT, date TEXT)";
    @sqlite_exec($database, $create_table_query);
    $cache_file = NULL;
    endif;
else:

  $failed_to_initialize_sqlite = $sqlerror;
  endif;

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if ($cache_file == NULL || isset($failed_to_initialize_sqlite)):

  //-----------------------------------------
  //Here we identify the podcast url scheme
  $idstyles = array(
    '?id=',
    '&id=',
    '/id'
    );

  for ($counter = 0; $counter < count($idstyles); $counter++):
  
    if (strpos($url, $idstyles[$counter])):
    
      $idstyle = $idstyles[$counter];
      $validID = "So, how are you holding up? Because I'm a potato!";
      break;
      endif;
    endfor;
  
  //-----------------------------------------
  //Since iTunes-U uses the same identifier symbols,
  //this is where we rule them out until it is supported
  //Note: more checking for itunes-u content is done further below
  if (strpos($url, '/itunes-u/')):
    
    unset($validID);
    $invalidID = "itunes-u";
    endif;
  
  //-----------------------------------------
  // extract feed-id, get page from itunes & find feed-url
  if (isset($validID)):
  
    preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
    $curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
    if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1):
    
      $newURL = subURL($curled1, "<key>url</key><string>", "</string>");
      $curled1 = curlfeed($newURL);
      endif;
    if (stripos($curled1, 'itunes-u')):
     
      $itunesU_title = subURL($curled1, '<title>', '</title>');
      $itunesU_title_char = urlencode($itunesU_title);
      $itunesU_body = subURL($curled1, '<body ', '>');
      $itunesU_class = subURL($itunesU_body, 'class="', '"');
      if (stripos($itunesU_class, 'itunes-u')):
    
        $feedURL = <<<ITUNESU
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itunesU_title"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itunesU_title_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
ITUNESU;
        $itunesU_check = 1;
        $invalidID = 'itunes-u';
        endif;
      endif;
    if ($itunesU_check != 1):

      $feedURL = subURL($curled1);
      checkFEED($feedURL, $url);
      endif;
    if (!isset($failed_to_initialize_sqlite)):
    
      $newfeedURL = sqlite_escape_string($feedURL);
      $cache_query_put_content = "INSERT INTO {$_SETT['dbtable']} (uniqueid,url,date) VALUES ('$urlhash', '$newfeedURL', '".date("r")."')";
      @sqlite_exec($database, $cache_query_put_content);
      endif;
  else: 
  
    if ($invalidID == "itunes-u"):
    
      //Example URL: http://itunes.apple.com/itunes-u/the-civil-war-reconstruction/id341650730
      $itu_label = subURL($url, '/itunes-u/', '/');
      $itu_label_white = trim(ucwords(str_replace('-', ' ', $itu_label)));
      $itu_label_char = str_replace('-', '%20', $itu_label);
      $feedURL = <<<FEEDURL
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title as a podcast in hopes that the content providers also posted it to the iTunes Podcast Directory (do no expect this for password protected content). Try searching for: 
        <br>"$itu_label_white"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itu_label_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
FEEDURL;
    else:
    
      $feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error&body=Error on URL:$url' style=\"display:inline;text-decoration:underline\">{$_SETT['contactemail']}</a> <br>and notify me of the URL you are trying.";
      $invalidID = "I was doing fine. Noone was trying to murder me, or put me in a potato, or feed me to birds.";
      endif;
    endif;
else:

  $feedURL = $cache_file;
  if (!stripos($feedURL, 'itunes-u')):

    checkFEED($feedURL, $url);
  else:

    $invalidID = 'itunes-u';
    endif;
  endif;

//-----------------------------------------
// html output to browser
$podcastURL = (isset($invalidURL) || isset($invalidID)) ? $feedURL : "<a href=\"$feedURL\">$feedURL</a>";

echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;"> 
  <head> 
    <title>Podcast URL</title> 
    <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
    <meta name="robots" content="NOINDEX, NOFOLLOW, NOARCHIVE, NOSNIPPET"> 
    <style type="text/css" media="screen">@import "iphonenav.css";</style>
    <link rel="apple-touch-icon" href="./icon.png" />
    <link rel="shortcut icon" href="./favicon.ico">
  </head> 
  
  <!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
  <!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
  <!-- For the PHP code to extract the podcast feed yourself, visit http://snipplr.com/view/52465 --> 
   
  <body style="height: 100%;"> 
     
    <h1>Podcast URL:</h1> 
    <ul> 
        <li style="height: 100%; padding:10px 10px 10px 10px;font-size:20px;word-wrap:break-word">$podcastURL</li> 
        <li style="height: 100%; padding:10px 10px 10px 10px;font-size:10px;word-wrap:break-word;border-bottom: 0px solid;"><a href="mailto:[email protected]" style="color:LightGray;font-size:12px;">[email protected]</a></li>
    </ul> 
  </body> 
</html>
OUTTEXT;

?>

Revision: 45031
at June 3, 2011 09:03 by lasavior


Updated Code
<?php

/*
 * iTunesFeedExtractor 
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski, zerologic.com
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/the-morning-stream/id414564832?uo=4
 *   Returns: http://myextralife.com/ftp/radio/morningstream.xml
 */

//-----------------------------------------
// a couple of settings
$_SETT = array(
  'hashalgo' => 'md5',
  'contactemail' => '[email protected]',
  'dbtable' => 'feedurls',
  'dbfilename' => 'itnfedb.sqdb'
  );

//-----------------------------------------
// the base URL
$url = ($_POST['terms'] != null) ? $_POST['terms'] : $_SERVER['QUERY_STRING'];
$urlhash = hash($_SETT['hashalgo'], $url);

//-----------------------------------------
//Functions
function curlfeed($churl) {

  $ch = curl_init();
  curl_setopt_array ($ch, array(
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_FOLLOWLOCATION => TRUE,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_URL => $churl,
    CURLOPT_USERAGENT => 'iTunes/9.1.1'
    ));
  $chresult = curl_exec($ch);
  curl_close($ch);
  
  return $chresult;
  }

function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {

  $str1 = strpos($urltosub, $string1) + strlen($string1);
  $str2 = strpos($urltosub, $string2, $str1);
  $subbedstring = substr($urltosub, $str1, ($str2 - $str1));
  
  return $subbedstring;
  }

function checkFEED($thefeed, $mainURL) {
  
  global $feedURL, $invalidURL, $_SETT;

  //For your reference, the following is called a HEREDOC
  $badURL = <<<BADURL
    <div style="font-size:15px;white-space:normal;max-width:400px">iTunes failed to return the feed-url. 
    <br>
    <br>This may be due to different reasons: 
    <br>&nbsp;&nbsp;1) the podcast has been deleted,
    <br>&nbsp;&nbsp;2) the podcast has no items,
    <br>and many other reasons im not aware of. Unfortunately iTunes isnt perfect (hence why your here).
    <br>
    <br>Im sorry my script was of no help to you. If you feel this was in error, you can <a href="outfeed.php?$mainURL" style="text-decoration:underline" target="_blank">view the source,</a><br> or you can always <a href="mailto:{$_SETT['contactemail']}?subject=IFE Error&body=URL i tried: $mainURL" style="display:inline;text-decoration:underline">email me</a> the URL and i will see if its fixable.</div>
BADURL;

  if (substr($thefeed, 0, 7) != "http://"): 
  
    $feedURL = $badURL;
    $invalidURL = "The cake is a lie.";
    endif;

  }
  
//-----------------------------------------
//Here we initiate the sqlite database and setup the cached variables
if ($database = sqlite_open($_SETT['dbfilename'], 0666, $sqlerror)):

  $check_cache_query = "SELECT url FROM {$_SETT['dbtable']} WHERE uniqueid='$urlhash'";
  $cache_file = @sqlite_single_query($database, $check_cache_query, true);
  if(sqlite_last_error($database)):
  
    $create_table_query = "CREATE TABLE {$_SETT['dbtable']}(uniqueid TEXT, url TEXT, date TEXT)";
    @sqlite_exec($database, $create_table_query);
    $cache_file = NULL;
    endif;
else:

  $failed_to_initialize_sqlite = $sqlerror;
  endif;

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if ($cache_file == NULL || isset($failed_to_initialize_sqlite)):

  //-----------------------------------------
  //Here we identify the podcast url scheme
  $idstyles = array(
    '?id=',
    '&id=',
    '/id'
    );

  for ($counter = 0; $counter < count($idstyles); $counter++):
  
    if (strpos($url, $idstyles[$counter])):
    
      $idstyle = $idstyles[$counter];
      $validID = "So, how are you holding up? Because I'm a potato!";
      break;
      endif;
    endfor;
  
  //-----------------------------------------
  //Since iTunes-U uses the same identifier symbols,
  //this is where we rule them out until it is supported
  if (strpos($url, '/itunes-u/')):
    
    unset($validID);
    $invalidID = "itunes-u";
    endif;
  
  //-----------------------------------------
  // extract feed-id, get page from itunes & find feed-url
  if (isset($validID)):
  
    preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
    $curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
    if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1):
    
      $newURL = subURL($curled1, "<key>url</key><string>", "</string>");
      $curled2 = curlfeed($newURL);
      $feedURL = subURL($curled2);
    else:
    
      $feedURL = subURL($curled1);
      endif;
    checkFEED($feedURL, $url);
    if (!isset($failed_to_initialize_sqlite)):
    
      $newfeedURL = sqlite_escape_string($feedURL);
      $cache_query_put_content = "INSERT INTO {$_SETT['dbtable']} (uniqueid,url,date) VALUES ('$urlhash', '$newfeedURL', '".date("r")."')";
      @sqlite_exec($database, $cache_query_put_content);
      endif;
  else: 
  
    if ($invalidID == "itunes-u"):
    
      //Example URL: http://itunes.apple.com/itunes-u/the-civil-war-reconstruction/id341650730
      $itu_label = subURL($url, '/itunes-u/', '/');
      $itu_label_white = trim(ucwords(str_replace('-', ' ', $itu_label)));
      $itu_label_char = str_replace('-', '%20', $itu_label);
      $feedURL = <<<FEEDURL
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title in the podcast directory for: 
        <br>"$itu_label_white"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itu_label_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
FEEDURL;
    else:
    
      $feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error&body=Error on URL:$url' style=\"display:inline;text-decoration:underline\">{$_SETT['contactemail']}</a> <br>and notify me of the URL you are trying.";
      $invalidID = "I was doing fine. Noone was trying to murder me, or put me in a potato, or feed me to birds.";
      endif;
    endif;
else:

  $feedURL = $cache_file;
  checkFEED($feedURL, $url);
  endif;

//-----------------------------------------
// html output to browser
$podcastURL = (isset($invalidURL) || isset($invalidID)) ? $feedURL : "<a href=\"$feedURL\">$feedURL</a>";

echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;"> 
  <head> 
    <title>Podcast URL</title> 
    <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
    <meta name="robots" content="NOINDEX, NOFOLLOW, NOARCHIVE, NOSNIPPET"> 
    <style type="text/css" media="screen">@import "iphonenav.css";</style>
    <link rel="apple-touch-icon" href="./icon.png" />
    <link rel="shortcut icon" href="./favicon.ico">
  </head> 
  
  <!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
  <!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
  <!-- For the PHP code to extract the podcast feed yourself, visit http://snipplr.com/view/52465 --> 
   
  <body style="height: 100%;"> 
     
    <h1>Podcast URL:</h1> 
    <ul> 
        <li style="height: 100%; padding:10px 10px 10px 10px;font-size:20px;word-wrap:break-word">$podcastURL</li> 
        <li style="height: 100%; padding:10px 10px 10px 10px;font-size:10px;word-wrap:break-word;border-bottom: 0px solid;"><a href="mailto:[email protected]" style="color:LightGray;font-size:12px;">[email protected]</a></li>
    </ul> 
  </body> 
</html>
OUTTEXT;

?>

Revision: 45030
at June 3, 2011 08:49 by lasavior


Updated Code
<?php

/*
 * iTunesFeedExtractor 
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski, zerologic.com
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/the-morning-stream/id414564832?uo=4
 *   Returns: http://myextralife.com/ftp/radio/morningstream.xml
 */

//-----------------------------------------
// a couple of settings
$_SETT = array(
  'hashalgo' => 'md5',
  'contactemail' => '[email protected]',
  'dbtable' => 'feedurls',
  'dbfilename' => 'itnfedb.sqdb'
  );

//-----------------------------------------
// the base URL
$url = ($_POST['terms'] != null) ? $_POST['terms'] : $_SERVER['QUERY_STRING'];
$urlhash = hash($_SETT['hashalgo'], $url);

//-----------------------------------------
//Functions
function curlfeed($churl) {

  $ch = curl_init();
  curl_setopt_array ($ch, array(
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_FOLLOWLOCATION => TRUE,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_URL => $churl,
    CURLOPT_USERAGENT => 'iTunes/9.1.1'
    ));
  $chresult = curl_exec($ch);
  curl_close($ch);
  
  return $chresult;
  }

function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {

  $str1 = strpos($urltosub, $string1) + strlen($string1);
  $str2 = strpos($urltosub, $string2, $str1);
  $subbedstring = substr($urltosub, $str1, ($str2 - $str1));
  
  return $subbedstring;
  }

function checkFEED($thefeed, $mainURL) {
  
  global $feedURL, $invalidURL, $_SETT;

  //For your reference, the following is called a HEREDOC
  $badURL = <<<BADURL
    <div style="font-size:15px;white-space:normal;max-width:400px">iTunes failed to return the feed-url. 
    <br>
    <br>This may be due to different reasons: 
    <br>&nbsp;&nbsp;1) the podcast has been deleted,
    <br>&nbsp;&nbsp;2) the podcast has no items,
    <br>and many other reasons im not aware of. Unfortunately iTunes isnt perfect (hence why your here).
    <br>
    <br>Im sorry my script was of no help to you. If you feel this was in error, you can <a href="outfeed.php?$mainURL" style="text-decoration:underline" target="_blank">view the source,</a><br> or you can always <a href="mailto:{$_SETT['contactemail']}?subject=IFE Error&body=URL i tried: $mainURL" style="display:inline;text-decoration:underline">email me</a> the URL and i will see if its fixable.</div>
BADURL;

  if (substr($thefeed, 0, 7) != "http://"): 
  
    $feedURL = $badURL;
    $invalidURL = "The cake is a lie.";
    endif;

  }
  
//-----------------------------------------
//Here we initiate the sqlite database and setup the cached variables
if ($database = sqlite_open($_SETT['dbfilename'], 0666, $sqlerror)):

  $check_cache_query = "SELECT url FROM {$_SETT['dbtable']} WHERE uniqueid='$urlhash'";
  $cache_file = @sqlite_single_query($database, $check_cache_query, true);
  if(sqlite_last_error($database)):
  
    $create_table_query = "CREATE TABLE {$_SETT['dbtable']}(uniqueid TEXT, url TEXT, date TEXT)";
    @sqlite_exec($database, $create_table_query);
    $cache_file = NULL;
    endif;
else:

  $failed_to_initialize_sqlite = $sqlerror;
  endif;

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if ($cache_file == NULL || isset($failed_to_initialize_sqlite)):

  //-----------------------------------------
  //Here we identify the podcast url scheme
  $idstyles = array(
    '?id=',
    '&id=',
    '/id'
    );

  for ($counter = 0; $counter < count($idstyles); $counter++):
  
    if (strpos($url, $idstyles[$counter])):
    
      $idstyle = $idstyles[$counter];
      $validID = "So, how are you holding up? Because I'm a potato!";
      break;
      endif;
    endfor;
  
  //-----------------------------------------
  //Since iTunes-U uses the same identifier symbols,
  //this is where we rule them out until it is supported
  if (strpos($url, '/itunes-u/')):
    
    unset($validID);
    $invalidID = "itunes-u";
    endif;
  
  //-----------------------------------------
  // extract feed-id, get page from itunes & find feed-url
  if (isset($validID)):
  
    preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
    $curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
    if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1):
    
      $newURL = subURL($curled1, "<key>url</key><string>", "</string>");
      $curled2 = curlfeed($newURL);
      $feedURL = subURL($curled2);
    else:
    
      $feedURL = subURL($curled1);
      endif;
    checkFEED($feedURL, $url);
    if (!isset($failed_to_initialize_sqlite)):
    
      $newfeedURL = sqlite_escape_string($feedURL);
      $cache_query_put_content = "INSERT INTO {$_SETT['dbtable']} (uniqueid,url,date) VALUES ('$urlhash', '$newfeedURL', '".date("r")."')";
      @sqlite_exec($database, $cache_query_put_content);
      endif;
  else: 
  
    if ($invalidID == "itunes-u"):
    
      //Example URL: http://itunes.apple.com/itunes-u/the-civil-war-reconstruction/id341650730
      $itu_start = strpos($url, '/itunes-u/') + 10;
      $itu_end = strpos($url, '/', $itu_start);
      $itu_label = substr($url, $itu_start, ($itu_end - $itu_start));
      $itu_label_white = trim(ucwords(str_replace('-', ' ', $itu_label)));
      $itu_label_char = str_replace('-', '%20', $itu_label);
      $feedURL = <<<FEEDURL
        <div style="font-size:15px;white-space:normal;max-width:400px">iTunes-U links not supported.
        <br>
        <br>Currently Apple does not offer a way to subscribe to iTunes-U material outside of iTunes (that i can find). A temporary solution is to search for a similar title in the podcast directory for: 
        <br>"$itu_label_white"
        <br>
        <br>You can <a href='http://itunes.so-nik.com/index.php?terms=$itu_label_char' style="display:inline;text-decoration:underline;color:blue">click here</a> to try that now.</div>
FEEDURL;
    else:
    
      $feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error&body=Error on URL:$url' style=\"display:inline;text-decoration:underline\">{$_SETT['contactemail']}</a> <br>and notify me of the URL you are trying.";
      $invalidID = "I was doing fine. Noone was trying to murder me, or put me in a potato, or feed me to birds.";
      endif;
    endif;
else:

  $feedURL = $cache_file;
  checkFEED($feedURL, $url);
  endif;

//-----------------------------------------
// html output to browser
$podcastURL = (isset($invalidURL) || isset($invalidID)) ? $feedURL : "<a href=\"$feedURL\">$feedURL</a>";

echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;"> 
  <head> 
    <title>Podcast URL</title> 
    <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
    <meta name="robots" content="NOINDEX, NOFOLLOW, NOARCHIVE, NOSNIPPET"> 
    <style type="text/css" media="screen">@import "iphonenav.css";</style>
    <link rel="apple-touch-icon" href="./icon.png" />
    <link rel="shortcut icon" href="./favicon.ico">
  </head> 
  
  <!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
  <!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
  <!-- For the PHP code to extract the podcast feed yourself, visit http://snipplr.com/view/52465 --> 
   
  <body style="height: 100%;"> 
     
    <h1>Podcast URL:</h1> 
    <ul> 
        <li style="height: 100%; padding:10px 10px 10px 10px;font-size:20px;word-wrap:break-word">$podcastURL</li> 
        <li style="height: 100%; padding:10px 10px 10px 10px;font-size:10px;word-wrap:break-word;border-bottom: 0px solid;"><a href="mailto:[email protected]" style="color:LightGray;font-size:12px;">[email protected]</a></li>
    </ul> 
  </body> 
</html>
OUTTEXT;

?>

Revision: 45029
at May 11, 2011 09:27 by lasavior


Updated Code
<?php

/**
 * iTunesFeedExtractor 
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski, zerologic.com
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/the-morning-stream/id414564832?uo=4
 *   Returns: http://myextralife.com/ftp/radio/morningstream.xml
*/

//-----------------------------------------
// a couple of settings
$_SETT = array(
  'hashalgo' => 'md5',
  'contactemail' => '[email protected]',
  'dbtable' => 'feedurls',
  'dbfilename' => 'itnfedb.sqdb'
  );

//-----------------------------------------
// the base URL
$url = ($_POST['terms'] != null) ? $_POST['terms'] : $_SERVER['QUERY_STRING'];
$urlhash = hash($_SETT['hashalgo'], $url);

//-----------------------------------------
//Functions
function curlfeed($churl) {
  $ch = curl_init();
  curl_setopt_array ($ch, array(
	CURLOPT_RETURNTRANSFER => TRUE,
	CURLOPT_FOLLOWLOCATION => TRUE,
	CURLOPT_MAXREDIRS => 10,
	CURLOPT_CONNECTTIMEOUT => 5,
	CURLOPT_URL => $churl,
	CURLOPT_USERAGENT => 'iTunes/9.1.1'
	));
  $chresult = curl_exec($ch);
  curl_close($ch);

  return $chresult;
  }

function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {
  $str1 = strpos($urltosub, $string1) + strlen($string1);
  $str2 = strpos($urltosub, $string2, $str1);
  $subbedstring = substr($urltosub, $str1, ($str2 - $str1));
  
  return $subbedstring;
  }

function checkFEED($thefeed, $mainURL) {
  
  global $feedURL, $invalidURL, $_SETT;

  $badURL = "<div style=\"font-size: 15px\">iTunes failed to return the feed-url. <br><br>".
	"This may be due to different reasons: <br>".
	"1) the podcast has been deleted, <br>".
	"2) the podcast has no items, <br>".
	"&nbsp;&nbsp;&nbsp;and other reasons im not aware of. <br>".
	"&nbsp;&nbsp;&nbsp;Unfortunately, iTunes isnt perfect. <br><br>".
	"Im sorry my script was of no help to you. <br><br>".
	"If you feel this was in error, you can <a href=\"outfeed.php?$mainURL\" style=\"text-decoration:underline\" target=\"_blank\">view the source.</a><br>".
	"Or you can always ".
	"<a href=\"mailto:{$_SETT['contactemail']}?subject=IFE Error&body=URL i tried: $mainURL\" style=\"display:inline;text-decoration:underline\">email me</a><br> ".
	"the URL and i will see if it's fixable.</div>";

  if (substr($thefeed, 0, 7) != "http://"): 
    $feedURL = $badURL;
    $invalidURL = "The cake is a lie.";
  endif;

  }
  
//-----------------------------------------
//Here we initiate the sqlite database and setup the cached variables
if ($database = sqlite_open($_SETT['dbfilename'], 0666, $sqlerror)):
  $check_cache_query = "SELECT url FROM {$_SETT['dbtable']} WHERE uniqueid='$urlhash'";
  $cache_file = @sqlite_single_query($database, $check_cache_query, true);
  if(sqlite_last_error($database)):
    $create_table_query = "CREATE TABLE {$_SETT['dbtable']}(uniqueid TEXT, url TEXT, date TEXT)";
    @sqlite_exec($database, $create_table_query);
    $cache_file = NULL;
  endif;
else:
  $failed_to_initialize_sqlite = $sqlerror;
endif;

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if ($cache_file == NULL || isset($failed_to_initialize_sqlite)):

	//-----------------------------------------
	//Here we identify the podcast url scheme
	$idstyles = array(
	  '?id=',
	  '&id=',
	  '/id'
	  );

	for ($counter = 0; $counter < count($idstyles); $counter++):
	  if (strpos($url, $idstyles[$counter])):
	    $idstyle = $idstyles[$counter];
	    $validID = "So, how are you holding up? Because I'm a potato!";
	    break;
	  endif;
	endfor;

	//-----------------------------------------
	// extract feed-id, get page from itunes & find feed-url
	if (isset($validID)):
	  preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
	  $curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
	
	  if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1):
		$newURL = subURL($curled1, "<key>url</key><string>", "</string>");
		$curled2 = curlfeed($newURL);
		$feedURL = subURL($curled2);
	  else:
		$feedURL = subURL($curled1);
	  endif;

	  checkFEED($feedURL, $url);
	  
	  if (!isset($failed_to_initialize_sqlite)):
		$newfeedURL = sqlite_escape_string($feedURL);
		$cache_query_put_content = "INSERT INTO {$_SETT['dbtable']} (uniqueid,url,date) VALUES ('$urlhash', '$newfeedURL', '".time()."')";
		@sqlite_exec($database, $cache_query_put_content);
	  endif;
	
	else: 
		$feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error&body=Error on URL:$url' style=\"display:inline;text-decoration:underline\">{$_SETT['contactemail']}</a> <br>and notify me of the URL you are trying.";
		$invalidID = "I was doing fine. Noone was trying to murder me, or put me in a potato, or feed me to birds.";
	endif;

else:

	$feedURL = $cache_file;
	checkFEED($feedURL, $url);
	
endif;

//-----------------------------------------
// html output to browser
$podcastURL = (isset($invalidURL) || isset($invalidID)) ? $feedURL : "<a href=\"$feedURL\">$feedURL</a>";

echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;"> 
	<head> 
		<title>Podcast URL</title> 
		<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
		<meta name="robots" content="NOINDEX, NOFOLLOW, NOARCHIVE, NOSNIPPET"> 
		<style type="text/css" media="screen">@import "iphonenav.css";</style>
		<link rel="apple-touch-icon" href="./icon.png" />
		<link rel="shortcut icon" href="./favicon.ico">
	</head> 
	
	<!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
	<!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
	<!-- For the PHP code to extract the podcast feed yourself, visit http://snipplr.com/view/52465 --> 
	 
	<body style="height: 100%;"> 
		 
		<h1>Podcast URL:</h1> 
		<ul> 
				<li style="height: 100%; padding:10px 10px 10px 10px;font-size:20px;word-wrap:break-word">$podcastURL</li> 
				<li style="height: 100%; padding:10px 10px 10px 10px;font-size:10px;word-wrap:break-word;border-bottom: 0px solid;"><a href="mailto:[email protected]" style="color:LightGray;font-size:12px;">[email protected]</a></li>
		</ul> 
	</body> 
</html>
OUTTEXT;

?>

Revision: 45028
at April 28, 2011 09:19 by lasavior


Updated Code
<?php

/**
 * iTunesFeedExtractor 
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski <[email protected]>
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/the-morning-stream/id414564832?uo=4
 *   Returns: http://myextralife.com/ftp/radio/morningstream.xml
*/

//-----------------------------------------
// a couple of settings
$_SETT = array(
  'hashalgo' => 'md5',
  'cachefolder' => './cachefiles/',
  'contactemail' => '[email protected]'
  );

//-----------------------------------------
// the base URL
$url = ($_POST['terms'] != null) ? $_POST['terms'] : $_SERVER['QUERY_STRING'];
$urlhash = hash($_SETT['hashalgo'], $url).'.txt';

//-----------------------------------------
//Functions
function curlfeed($churl) {
  $ch = curl_init();
  curl_setopt_array ($ch, array(
	CURLOPT_RETURNTRANSFER => TRUE,
	CURLOPT_FOLLOWLOCATION => TRUE,
	CURLOPT_MAXREDIRS => 10,
	CURLOPT_CONNECTTIMEOUT => 5,
	CURLOPT_URL => $churl,
	CURLOPT_USERAGENT => 'iTunes/9.1.1'
	));
  $chresult = curl_exec($ch);
  curl_close($ch);

  return $chresult;
  }

function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {
  $str1 = strpos($urltosub, $string1) + strlen($string1);
  $str2 = strpos($urltosub, $string2, $str1);
  $subbedstring = substr($urltosub, $str1, ($str2 - $str1));
  
  return $subbedstring;
  }

function checkFEED($thefeed, $mainURL) {
  
  global $feedURL, $invalidURL, $_SETT;

  $badURL = "<div style=\"font-size: 15px\">iTunes failed to return the feed-url. <br><br>".
	"This may be due to different reasons: <br>".
	"1) the podcast has been deleted, <br>".
	"2) the podcast has no items, <br>".
	"&nbsp;&nbsp;&nbsp;and other reasons im not aware of. <br>".
	"&nbsp;&nbsp;&nbsp;Unfortunately, iTunes isnt perfect. <br><br>".
	"Im sorry my script was of no help to you. <br><br>".
	"If you feel this was in error, you can <a href=\"outfeed.php?$mainURL\" style=\"text-decoration:underline\" target=\"_blank\">view the source.</a><br>".
	"Or you can always ".
	"<a href=\"mailto:{$_SETT['contactemail']}?subject=IFE Error&body=URL i tried: $mainURL\" style=\"display:inline;text-decoration:underline\">email me</a><br> ".
	"the URL and i will see if it's fixable.</div>";

  if (substr($thefeed, 0, 7) != "http://"): 
    $feedURL = $badURL;
    $invalidURL = "I was doing fine. Noone was trying to murder me, or put me in a potato, or feed me to birds.";
  endif;

  }

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if (!file_exists($_SETT['cachefolder'].$urlhash)):

	//-----------------------------------------
	//Here we identify the podcast url scheme

	$idstyles = array(
	  '?id=',
	  '&id=',
	  '/id'
	  );

	for ($counter = 0; $counter < count($idstyles); $counter++):
	  if (strpos($url, $idstyles[$counter])):
	    $idstyle = $idstyles[$counter];
	    $validID = "So, how are you holding up? Because I'm a potato!";
	    break;
	  endif;
	endfor;

	//-----------------------------------------
	// extract feed-id, get page from itunes & find feed-url
	if (isset($validID)):
	  preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
	  $curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
	
	  if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1):
		$newURL = subURL($curled1, "<key>url</key><string>", "</string>");
		$curled2 = curlfeed($newURL);
		$feedURL = subURL($curled2);
	  else:
		$feedURL = subURL($curled1);
	  endif;

	  checkFEED($feedURL, $url);
	  file_put_contents($_SETT['cachefolder'].$urlhash,$feedURL);
	
	else : $feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error&body=Error on URL:$url' style=\"display:inline;text-decoration:underline\">{$_SETT['contactemail']}</a> <br>and notify me of the URL you are trying.";
	endif;

else:
	
	$feedURL = file_get_contents($_SETT['cachefolder'].$urlhash);
	checkFEED($feedURL, $url);
endif;

//-----------------------------------------
// html output to browser

$podcastURL = (isset($invalidURL)) ? $feedURL : "<a href=\"$feedURL\">$feedURL</a>";

echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;"> 
	<head> 
		<title>Podcast URL</title> 
		<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
		<meta name="robots" content="NOINDEX, NOFOLLOW, NOARCHIVE, NOSNIPPET"> 
		<style type="text/css" media="screen">@import "iphonenav.css";</style>
		<link rel="apple-touch-icon" href="./icon.png" />
		<link rel="shortcut icon" href="./favicon.ico">
	</head> 
	
	<!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
	<!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
	<!-- For the PHP code to extract the podcast feed yourself, visit http://snipplr.com/view/52465 --> 
	 
	<body style="height: 100%;"> 
		 
		<h1>Podcast URL:</h1> 
		<ul> 
				<li style="height: 100%; padding:10px 10px 10px 10px;font-size:20px;word-wrap:break-word">$podcastURL</li> 
		</ul> 
	</body> 
</html>
OUTTEXT;

?>

Revision: 45027
at April 23, 2011 03:07 by lasavior


Updated Code
<?php

/**
 * iTunesFeedExtractor 
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski, zerologic.com
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/boulder-open-podcast/id346723827
 *   Returns: http://feeds.feedburner.com/BoulderOpenPodcast
*/

//-----------------------------------------
// a couple of settings
$_SETT = array(
  hashalgo => 'md5',
  cachefolder => './cachefiles/',
  contactemail => '[email protected]'
  );

//-----------------------------------------
// the base URL
$url = ($_POST['terms'] != null) ? $_POST['terms'] : $_SERVER['QUERY_STRING'];
$urlhash = hash($_SETT['hashalgo'], $url).'.txt';

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if (!file_exists($_SETT['cachefolder'].$urlhash)):

	//-----------------------------------------
	//Here we identify the podcast url scheme
	if      (strpos($url, "?id=")) $idstyle = '?id=';
	elseif  (strpos($url, "&id=")) $idstyle = '&id=';
	elseif  (strpos($url, "/id")) $idstyle = '/id';
	else    $falseurl = true;
	
	//-----------------------------------------
	//Functions
	function curlfeed($churl) {
	  $ch = curl_init();
	  curl_setopt_array ($ch, array(
		CURLOPT_RETURNTRANSFER => TRUE,
		CURLOPT_FOLLOWLOCATION => TRUE,
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_CONNECTTIMEOUT => 5,
		CURLOPT_URL => $churl,
		CURLOPT_USERAGENT => 'iTunes/9.1.1'
		));
	  $chresult = curl_exec($ch);
	  curl_close($ch);
	
	  return $chresult;
	  }
	
	function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {
	  $str1 = strpos($urltosub, $string1) + strlen($string1);
	  $str2 = strpos($urltosub, $string2, $str1);
	  $subbedstring = substr($urltosub, $str1, ($str2 - $str1));
	  
	  return $subbedstring;
	  }
	
	//-----------------------------------------
	// extract feed-id, get page from itunes & find feed-url
	if ($falseurl != true) :
	  preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
	  $curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
	
	  if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1):
		$newURL = subURL($curled1, "<key>url</key><string>", "</string>");
		$curled2 = curlfeed($newURL);
		$feedURL = subURL($curled2);
	  else:
		$feedURL = subURL($curled1);
	  endif;
	  
	  file_put_contents($_SETT['cachefolder'].$urlhash,$feedURL);
	
	else : $feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error'>{$_SETT['contactemail']}</a> and notify me of the URL you are trying.";
	endif;

else:
	
	$feedURL = file_get_contents($_SETT['cachefolder'].$urlhash);
	
endif;

//-----------------------------------------
// html output to browser
echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
	<head> 
		<title>Podcast URL</title> 
		<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
		<style type="text/css" media="screen">@import "iphonenav.css";</style>
		<link rel="apple-touch-icon" href="./icon.png" />
		<link rel="shortcut icon" href="./favicon.ico">
	</head> 
	
	<!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
	<!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
	<!-- For the PHP code to extract the podcast feed yourself, visit http://snipplr.com/view/52465 --> 
	 
	<body> 
		 
		<h1>Podcast URL:</h1> 
		<ul> 
				<li style="height:200px; padding:10px 10px 10px 10px;font-size:20px;word-wrap:break-word"><a href="$feedURL">$feedURL</a></li> 
		</ul> 
	</body> 
</html>
OUTTEXT;

?>

Revision: 45026
at April 23, 2011 03:05 by lasavior


Updated Code
<?php

/**
 * iTunesFeedExtractor 
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski, zerologic.com
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/boulder-open-podcast/id346723827
 *   Returns: http://feeds.feedburner.com/BoulderOpenPodcast
*/

//-----------------------------------------
// a couple of settings
$_SETT = array(
  hashalgo => 'md5',
  cachefolder => './cachefiles/',
  contactemail => '[email protected]'
  );

//-----------------------------------------
// the base URL
$url = ($_POST['terms'] != null) ? $_POST['terms'] : $_SERVER['QUERY_STRING'];
$urlhash = hash($_SETT['hashalgo'], $url).'.txt';

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if (!file_exists($_SETT['cachefolder'].$urlhash)):

	//-----------------------------------------
	//Here we identify the podcast url scheme
	if      (strpos($url, "?id=")) $idstyle = '?id=';
	elseif  (strpos($url, "&id=")) $idstyle = '&id=';
	elseif  (strpos($url, "/id")) $idstyle = '/id';
	else    $falseurl = true;
	
	//-----------------------------------------
	//Functions
	function curlfeed($churl) {
	  $ch = curl_init();
	  curl_setopt_array ($ch, array(
		CURLOPT_RETURNTRANSFER => TRUE,
		CURLOPT_FOLLOWLOCATION => TRUE,
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_CONNECTTIMEOUT => 5,
		CURLOPT_URL => $churl,
		CURLOPT_USERAGENT => 'iTunes/9.1.1'
		));
	  $chresult = curl_exec($ch);
	  curl_close($ch);
	
	  return $chresult;
	  }
	
	function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {
	  $str1 = strpos($urltosub, $string1) + strlen($string1);
	  $str2 = strpos($urltosub, $string2, $str1);
	  $subbedstring = substr($urltosub, $str1, ($str2 - $str1));
	  
	  return $subbedstring;
	  }
	
	//-----------------------------------------
	// extract feed-id, get page from itunes & find feed-url
	if ($falseurl != true) :
	  preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
	  $curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
	
	  if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1):
		$newURL = subURL($curled1, "<key>url</key><string>", "</string>");
		$curled2 = curlfeed($newURL);
		$feedURL = subURL($curled2);
	  else:
		$feedURL = subURL($curled1);
	  endif;
	  
	  file_put_contents($_SETT['cachefolder'].$urlhash,$feedURL);
	
	else : $feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error'>{$_SETT['contactemail']}</a> and notify me of the URL you are trying.";
	endif;

else:
	
	$feedURL = file_get_contents($_SETT['cachefolder'].$urlhash);
	
endif;

//-----------------------------------------
// html output to browser
echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
	<head> 
		<title>Podcast URL</title> 
		<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
		<style type="text/css" media="screen">@import "iphonenav.css";</style>
		<link rel="apple-touch-icon" href="./icon.png" />
		<link rel="shortcut icon" href="./favicon.ico">
	</head> 
	
	<!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
	<!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
	<!-- For the PHP code to extract the podcast feed yourself, visit http://snipt.org/xgms --> 
	 
	<body> 
		 
		<h1>Podcast URL:</h1> 
		<ul> 
				<li style="height:200px; padding:10px 10px 10px 10px;font-size:20px;word-wrap:break-word"><a href="$feedURL">$feedURL</a></li> 
		</ul> 
	</body> 
</html>
OUTTEXT;

?>

Revision: 45025
at April 23, 2011 02:54 by lasavior


Updated Code
<?php

/**
 * iTunesFeedExtractor 
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski, zerologic.com
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/boulder-open-podcast/id346723827
 *   Returns: http://feeds.feedburner.com/BoulderOpenPodcast
*/

//-----------------------------------------
// a couple of settings
$_SETT = array(
  hashalgo => 'md5',
  cachefolder => './cachefiles/',
  contactemail => '[email protected]'
  );

//-----------------------------------------
// the base URL
$url = ($_POST['terms'] != null) ? $_POST['terms'] : $_SERVER['QUERY_STRING'];
$urlhash = hash($_SETT['hashalgo'], $url).'.txt';

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if (!file_exists($_SETT['cachefolder'].$urlhash)):

	//-----------------------------------------
	//Here we identify the podcast url scheme
	if      (strpos($url, "?id=")) $idstyle = '?id=';
	elseif  (strpos($url, "/id")) $idstyle = '/id';
	else    $falseurl = true;
	
	//-----------------------------------------
	//Functions
	function curlfeed($churl) {
	  $ch = curl_init();
	  curl_setopt_array ($ch, array(
		CURLOPT_RETURNTRANSFER => TRUE,
		CURLOPT_FOLLOWLOCATION => TRUE,
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_CONNECTTIMEOUT => 5,
		CURLOPT_URL => $churl,
		CURLOPT_USERAGENT => 'iTunes/9.1.1'
		));
	  $chresult = curl_exec($ch);
	  curl_close($ch);
	
	  return $chresult;
	  }
	
	function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {
	  $str1 = strpos($urltosub, $string1) + strlen($string1);
	  $str2 = strpos($urltosub, $string2, $str1);
	  $subbedstring = substr($urltosub, $str1, ($str2 - $str1));
	  
	  return $subbedstring;
	  }
	
	//-----------------------------------------
	// extract feed-id, get page from itunes & find feed-url
	if ($falseurl != true) :
	  preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
	  $curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
	
	  if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1):
		$newURL = subURL($curled1, "<key>url</key><string>", "</string>");
		$curled2 = curlfeed($newURL);
		$feedURL = subURL($curled2);
	  else:
		$feedURL = subURL($curled1);
	  endif;
	  
	  file_put_contents($_SETT['cachefolder'].$urlhash,$feedURL);
	
	else : $feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error'>{$_SETT['contactemail']}</a> and notify me of the URL you are trying.";
	endif;

else:
	
	$feedURL = file_get_contents($_SETT['cachefolder'].$urlhash);
	
endif;

//-----------------------------------------
// html output to browser
echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
	<head> 
		<title>Podcast URL</title> 
		<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
		<style type="text/css" media="screen">@import "iphonenav.css";</style>
		<link rel="apple-touch-icon" href="./icon.png" />
		<link rel="shortcut icon" href="./favicon.ico">
	</head> 
	
	<!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
	<!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
	<!-- For the PHP code to extract the podcast feed yourself, visit http://snipt.org/xgms --> 
	 
	<body> 
		 
		<h1>Podcast URL:</h1> 
		<ul> 
				<li style="height:200px; padding:10px 10px 10px 10px;font-size:20px;word-wrap:break-word"><a href="$feedURL">$feedURL</a></li> 
		</ul> 
	</body> 
</html>
OUTTEXT;

?>

Revision: 45024
at April 22, 2011 08:39 by lasavior


Updated Code
<?php

/**
 * iTunesFeedExtractor 
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski <[email protected]>
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/boulder-open-podcast/id346723827
 *   Returns: http://feeds.feedburner.com/BoulderOpenPodcast
*/

//-----------------------------------------
// a couple of settings
$_SETT = array(
  hashalgo => 'md5',
  cachefolder => './cachefiles/',
  contactemail => '[email protected]'
  );

//-----------------------------------------
// the base URL
$url = ($_POST['terms'] != null) ? $_POST['terms'] : $_SERVER['QUERY_STRING'];
$urlhash = hash($_SETT['hashalgo'], $url).'.txt';

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if (!file_exists($_SETT['cachefolder'].$urlhash)):

	//-----------------------------------------
	//Here we identify the podcast url scheme
	if      (strpos($url, "?id=")) $idstyle = '?id=';
	elseif  (strpos($url, "/id")) $idstyle = '/id';
	else    $falseurl = true;
	
	//-----------------------------------------
	//Functions
	function curlfeed($churl) {
	  $ch = curl_init();
	  curl_setopt_array ($ch, array(
		CURLOPT_RETURNTRANSFER => TRUE,
		CURLOPT_FOLLOWLOCATION => TRUE,
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_CONNECTTIMEOUT => 5,
		CURLOPT_URL => $churl,
		CURLOPT_USERAGENT => 'iTunes/9.1.1'
		));
	  $chresult = curl_exec($ch);
	  curl_close($ch);
	
	  return $chresult;
	  }
	
	function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {
	  $str1 = strpos($urltosub, $string1) + strlen($string1);
	  $str2 = strpos($urltosub, $string2, $str1);
	  $subbedstring = substr($urltosub, $str1, ($str2 - $str1));
	  
	  return $subbedstring;
	  }
	
	//-----------------------------------------
	// extract feed-id, get page from itunes & find feed-url
	if ($falseurl != true) :
	  preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
	  $curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
	
	  if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1):
		$newURL = subURL($curled1, "<key>url</key><string>", "</string>");
		$curled2 = curlfeed($newURL);
		$feedURL = subURL($curled2);
	  else:
		$feedURL = subURL($curled1);
	  endif;
	  
	  file_put_contents($_SETT['cachefolder'].$urlhash,$feedURL);
	
	else : $feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error'>{$_SETT['contactemail']}</a> and notify me of the URL you are trying.";
	endif;

else:
	
	$feedURL = file_get_contents($_SETT['cachefolder'].$urlhash);
	
endif;

//-----------------------------------------
// html output to browser
echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
	<head> 
		<title>Podcast URL</title> 
		<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
		<style type="text/css" media="screen">@import "iphonenav.css";</style>
		<link rel="apple-touch-icon" href="./icon.png" />
		<link rel="shortcut icon" href="./favicon.ico">
	</head> 
	
	<!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com --> 
	<!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com --> 
	<!-- For the PHP code to extract the podcast feed yourself, visit http://snipt.org/xgms --> 
	 
	<body> 
		 
		<h1>Podcast URL:</h1> 
		<ul> 
				<li style="height:200px; padding:10px 10px 10px 10px;font-size:20px;word-wrap:break-word"><a href="$feedURL">$feedURL</a></li> 
		</ul> 
	</body> 
</html>
OUTTEXT;

?>

Revision: 45023
at April 22, 2011 08:17 by lasavior


Initial Code
<?php

/**
 * iTunesFeedExtractor 
 * implemented at http://itunes.so-nik.com
 *
 * All code has been re-written by lasavior. 
 * Original code & inspiration from Michael Sitarzewski <[email protected]>
 *
 * Ex: http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wa/viewPodcast?id=269238657
 * Ex: http://itunes.apple.com/us/podcast/hombre-potato/id319810190?uo=4
 *
 *   Usage: itunes.php?http://itunes.apple.com/us/podcast/boulder-open-podcast/id346723827
 *   Returns: http://feeds.feedburner.com/BoulderOpenPodcast
*/

//-----------------------------------------
// a couple of settings
$_SETT = array(
  hashalgo => 'md5',
  cachefolder => './cachefiles/',
  contactemail => '[email protected]'
  );

//-----------------------------------------
// the base URL
$url = ($_POST['terms'] != null) ? $_POST['terms'] : $_SERVER['QUERY_STRING'];
$urlhash = hash($_SETT['hashalgo'], $url).'.txt';

//-----------------------------------------
//For caching files, this determines if the cached file already exists
if (!file_exists($_SETT['cachefolder'].$urlhash)):

	//-----------------------------------------
	//Here we identify the podcast url scheme
	if      (strpos($url, "?id=")) $idstyle = '?id=';
	elseif  (strpos($url, "/id")) $idstyle = '/id';
	else    $falseurl = true;
	
	//-----------------------------------------
	//Functions
	function curlfeed($churl) {
	  $ch = curl_init();
	  curl_setopt_array ($ch, array(
		CURLOPT_RETURNTRANSFER => TRUE,
		CURLOPT_FOLLOWLOCATION => TRUE,
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_CONNECTTIMEOUT => 5,
		CURLOPT_URL => $churl,
		CURLOPT_USERAGENT => 'iTunes/9.1.1'
		));
	  $chresult = curl_exec($ch);
	  curl_close($ch);
	
	  return $chresult;
	  }
	
	function subURL($urltosub, $string1 = 'feed-url="', $string2 ='"') {
	  $str1 = strpos($urltosub, $string1) + strlen($string1);
	  $str2 = strpos($urltosub, $string2, $str1);
	  $subbedstring = substr($urltosub, $str1, ($str2 - $str1));
	  
	  return $subbedstring;
	  }
	
	//-----------------------------------------
	// extract feed-id, get page from itunes & find feed-url
	if ($falseurl != true) :
	  preg_match("/[0-9]+/", $url, $podid, 0, strpos($url, $idstyle)); // here we extract the feed ID
	  $curled1 = curlfeed("http://itunes.apple.com/podcast/id".$podid[0]);
	
	  if (strpos($curled1, "<key>kind</key><string>Goto</string>") > 1):
		$newURL = subURL($curled1, "<key>url</key><string>", "</string>");
		$curled2 = curlfeed($newURL);
		$feedURL = subURL($curled2);
	  else:
		$feedURL = subURL($curled1);
	  endif;
	  
	  file_put_contents($_SETT['cachefolder'].$urlhash,$feedURL);
	
	else : $feedURL = "URL not supported. <br><br>Please contact <a href='mailto:{$_SETT['contactemail']}?subject=Feed-Error'>{$_SETT['contactemail']}</a> and notify me of the URL you are trying.";
	endif;

else:
	
	$feedURL = file_get_contents($_SETT['cachefolder'].$urlhash);
	
endif;

//-----------------------------------------
// html output to browser
echo <<<OUTTEXT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
	<head> 
		<title>Podcast URL</title> 
		<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> 
		<style type="text/css" media="screen">@import "iphonenav.css";</style>
		<link rel="apple-touch-icon" href="./icon.png" />
		<link rel="shortcut icon" href="./favicon.ico">
	</head> 
	
	<!-- GUI, iTunes Store searching & feed extraction credited to lasavior, so-nik.com -->
	<!-- Original idea & inspiration credited to Michael Sitarzewski, zerologic.com -->
	 
	<body> 
		 
		<h1>Podcast URL:</h1> 
		<ul> 
				<li style="height:200px; padding:10px 10px 10px 10px;font-size:20px;word-wrap:break-word"><a href="$feedURL">$feedURL</a></li> 
		</ul> 
	</body> 
</html>
OUTTEXT;

?>

Initial URL
http://itunes.so-nik.com

Initial Description
If you've ever tried to subscribe to a podcast outside of iTunes but only have an iTunes URL, you know how frustrating it is. Turns out that you just need to spoof yourself as an iTunes client to see the direct feed URL. This script helps with exactly that. I even wrote a front-end @ http://itunes.so-nik.com so you can use it from a mobile device or desktop web browser.

NOTE: if you came here from Google, please use the "Versions" dropbox on the right to select the current version as you may be viewing an older copy with bugs.

[Change log moved into file]

Initial Title
iTunes Podcast URL Extractor

Initial Tags
url

Initial Language
PHP