#native_company# #native_desc#
#native_cta#

Blogger Category Publisher

By Jeffery Mandrake
on March 19, 2006

Version: 1.1

Type: Full Script

Category: File Management

License: GNU Library Public License

Description: PHP script that lets you easily categorize your blog posts and generates category pages for your Blogger blog. Works on blogs hosted outside of blogspot.com. Category pages inherit your blog’s template for seamless integration and are published as static HTML pages with links to your individual blog posts.
Get the whole package and check for the latest version:
http://www.moshare.com/apps/blogger-categories/

Includes 4 files:
blogger-categories-config.php
blogger-categories-login.php
blogger-categories-publisher.php
blogger-categories.txt

And of course a readme.txt file.

Quick Install
=============
Please read the step-by-step instructions in blogger-categories-config.php
Configure the variables in blogger-categories-config.php as directed.

How-To Instructions: Set Up Steps for Blogger Categories Publisher
=========================================
Note: This script is written in PHP and requires you to have your own hosting account outside of blogspot.com. If you don’t have your own hosting account with PHP, just search Google for “cheap php hosting” or “free php hosting”…
The sample code snipets in the steps below make reference to an actual sample Blogger template.
To help you set up this script and see a live sample blog with categories please go to:
http://www.seniorcatanddogproducts.com/
You can download that blog’s template and Category Publisher script config files from:
http://www.seniorcatanddogproducts.com/category-publisher.zip

<?
error_reporting(0);
//error_reporting(E_ALL); //uncomment to see any errors
//@ini_set('display_errors', '1');
/* 
=========================================
Script Name: Blogger Categories Publisher
-----------------------------------------
Version 1.1
Release Date: 2006-0311
=========================================
Description: Generates category pages for hosted Blogger blogs - blog not hosted on blogspot.com
Hosting Requirements: Hosted account somewhere other than Blogspot.com, PHP 4+.
Script's Home: http://www.moshare.com/apps/blogger-categories/
Developer: Jeffery Mandrake
Developer's Blog: http://www.moshare.com
Contact Info: http://www.moshare.com/2006/03/about-mosharecom.html

* For instructions on how to configure this script to publish your Blogger blog categories please see the config file: blogger-categories-config.php

** By using this script, you agree to abide by the terms of use contained in the config file for this script:
blogger-categories-config.php

*** This script will not work for blogs hosted on Blogger's free blogspot.com server.

See the script's home page for more information and answers to FAQ's:

Script's Home: http://www.moshare.com/apps/blogger-categories/


======================================================================
========-----------------------=======================================
======== NOTHING TO EDIT BELOW =======================================
======== TO SET UP THIS SCRIPT EDIT: blogger-categories-config.php
========-----------------------=======================================
======================================================================
*/

$scriptVersion = "Version 1.1";


// ===========================================================================
// PLEASE DO NOT EDIT ANYTHING BELOW UNLESS YOU REALLY KNOW WHAT YOU'RE DOING!
// To get the latest version of this script or for questions/comments go to:
// http://www.moshare.com
// ===========================================================================
$incFileName = "./blogger-categories-config.php"; //contains all the parameters you need to configure this script
require_once($incFileName);

$authOK = false;

if (!empty($_POST["pswd"])){
	$passwd_post = trim($_POST["pswd"]);
	if ($passwd_post == $passwd) {
		$authOK = true; // password ok
	}
} else {
	$authOK = false;
}

if (!$authOK){
	echo "<h3>Permission Denied</h3><p>You did not submit the proper credentials: <a href="$loginFilename">Login</a></p>";
	exit;
}

$fileTypes = array();
$fArray = array();
$filesArray = array();
$categoryLabels = array();
$tempCategoriesVals = file_get_contents("blogger-categories.txt");
$fArrayContent = explode("n", $tempCategoriesVals);

foreach ($fArrayContent as $fArrayVal) {
	if (strlen($fArrayVal) < 8) continue;
	$fArrayTemp = explode(",", $fArrayVal);
	if (count($fArrayTemp) < 5) continue;
	//Sample value for $fArrayVal: TIP,TIPS,tips-all.html,index_tips.php,Cool Tips
	$fArray[$fArrayTemp[1] . ": "]["results-all"] = trim($fArrayTemp[2]);
	$fArray[$fArrayTemp[1] . ": "]["indexFile"] = trim($fArrayTemp[3]);
	$fArray[$fArrayTemp[1] . ": "]["indexHeading"] = trim($fArrayTemp[4]);
	//add to $fileTypes array
	$fileTypes[$fArrayTemp[0] . ": "] = $fArrayTemp[1] . ": ";
}

reset($fArray);
reset($fileTypes);

$outStr = "";//used for debug messages
$startTag = "<title>";
$endTag = "</title>";
$subValDelimiter = "{||}";//unique string used to separate title from link
$HTTP_HOST = $_SERVER["HTTP_HOST"];

function isValidFile($fp){
	if ($fp == "index.html" || $fp == "." || $fp == ".." || strstr($fp,".log") || strstr($fp,".php")){
		return false;           // ignore these file references
	} else return true;
}

function getFileType($fp){//works on first occurence of tag only
	global $filesArray, $subValDelimiter, $fileTypes, $startTag, $endTag;
	set_time_limit(30);
	$filestring = file_get_contents($fp);
	$end = strpos($filestring,$endTag);//only get whats before $endTag
	$beginning = strpos($filestring,$startTag)+strlen($startTag);//and after $startTag length offset to extract tag value
	$tagContent = substr($filestring,$beginning,$end-$beginning);// start -> end
	foreach ($fileTypes as $fileTypeValue => $categoryValue) {//which type of document is it?
		$pos = strpos(strtoupper($tagContent), strtoupper($fileTypeValue));
		if ($pos === false) {
		    continue;
		} else {
			$fKey = $tagContent.$subValDelimiter.$fp;
			$filesArray[$fKey] = $fileTypeValue;
		}
	}
}

function directory_list($path, $types="directories", $recursive=0) {
   global $outStr;
   // get a list of just the dirs and turn the list into an array 
   // @path        starting path from which to search
   // @types        can be "directories", "files", or "all"
   // @recursive    determines whether subdirectories are searched
   $currendDir = ".";
   if ($dir = opendir($path)) {
       $file_list = array();
       while (false !== ($file = readdir($dir))){
           if (isValidFile($file)) {// check if is a file or directory and if we're interested in that type
               if ((is_dir($path."/".$file)) && (($types=="directories") || ($types=="all"))) {
                       $file_list[] = "<font color=red>" . $file . "</font>"; //ads directory to the list
                       // if we're in a directory and we want recursive behavior, call this function again
                       if ($recursive) {
                           $file_list = array_merge($file_list, directory_list($path."/".$file."/", $types, $recursive));
                       }
               } elseif (($types == "files") || ($types == "all")) {
				   $outStr .= getFileType($path.$file) . "<br>";
               }
           }
       }
       closedir($dir);
       return $file_list;
   } else return "no result";
} 

function writeFile($filename,$filecontent,$filemode){//filemode either create/overwrite [w] or append [a]
	global $debug;
	if ($filemode == "w"){
		//echo file_put_contents($filename,$somecontent); php v.5 only
		$handle = fopen($filename, $filemode);
		if (fwrite($handle, $filecontent) === FALSE) {
		    echo "Cannot write to file ($filename)<br>";
		    exit;
		}
		if ($debug) echo "Success, wrote file ($filename)<br>";
		if ($debug) flush();
		fclose($handle);
	}
	if ($filemode == "a"){
		if (is_writable($filename)) {
		    if (!$handle = fopen($filename, $filemode)) {
		         echo "Cannot open file ($filename)";
		         exit;
		    }
		    // Write $somecontent to our opened file.
		    if (fwrite($handle, $somecontent) === FALSE) {
		        echo "Cannot write to file ($filename)<br>";
		        exit;
		    }
		    
		    if ($debug) echo "Success, wrote file ($filename)<br>";
		    if ($debug) flush();
		    fclose($handle);
		}
	}
}
//==== start output to browser ========================================================
?>
<html>
<head>
	<title>Blogger Category Publisher - <? echo $scriptVersion; ?></title>
</head>
<body>
<h1>Blogger Category Publisher - <? echo $scriptVersion ?></h1>

<script type="text/javascript"><!--
google_ad_client = "pub-5936448303847393";
google_ad_width = 180;
google_ad_height = 60;
google_ad_format = "180x60_as_rimg";
google_cpa_choice = "CAAQ4fqy0gEaCPI0fZSM10VxKL3D93M";
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>&nbsp;&nbsp;
<script type="text/javascript"><!--
google_ad_client = "pub-5936448303847393";
google_ad_width = 180;
google_ad_height = 60;
google_ad_format = "180x60_as_rimg";
google_cpa_choice = "CAAQ24Oy0QEaCGbgW7AaXRokKMu293M";
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

<h3>Check for updates on this blog category publishing script: <a href="http://www.moshare.com/apps/blogger-categories/">http://www.moshare.com/apps/blogger-categories/</a></h3>

<h3>Publishing Categories For Your Blog...</h3>
<?php
//get all directories that are integers (year)
foreach (glob("*",GLOB_ONLYDIR) as $dirname) {
  if (is_numeric($dirname)) directory_list("$dirname", $types="all", $recursive=1);
}
ksort($filesArray);//sort array alphabetically by keys and maintain key->data relationship
reset($filesArray);

echo "";
foreach ($filesArray as $fKey => $fValue) {//sort items by category
	$fArray[$fileTypes[$fValue]][count($fArray[$fileTypes[$fValue]])] = $fKey;//update category item counter
	if ($verboseMode) echo "<h4>" . $fValue . "</h4>" . str_replace($subValDelimiter," =&gt; ",$fKey) ."<br>";
}

//print_r($fArray);

//get main template and generate index files for individual link types
$filestring = file_get_contents("http://$HTTP_HOST" . $blogIndexFile);
//markers for string substitutions
$headingMarker = "<[insert main heading here]>";
$contentMarker = "<[insert main content here]>";
//substitute main header with marker so we can insert TOC header specific for that type of content
$startTag = "<!-- <[MainHeading]> -->";
$endTag = "<!-- </[MainHeading]> -->";
$end = strpos($filestring,$endTag);//only get whats before $endTag
$beginning = strpos($filestring,$startTag)+strlen($startTag);//and after $startTag length offset to extract tag value
$mainContent = substr($filestring,$beginning,$end-$beginning);// start -> end
$filestring = str_replace($startTag.$mainContent.$endTag, $headingMarker, $filestring);
//substitute main content with marker so we can insert TOC links
$startTag = "<!-- <[MainContent]> -->";
$endTag = "<!-- </[MainContent]> -->";
$end = strpos($filestring,$endTag);//only get whats before $endTag
$beginning = strpos($filestring,$startTag)+strlen($startTag);//and after $startTag length offset to extract tag value
$mainContent = substr($filestring,$beginning,$end-$beginning);// start -> end
$filestring = str_replace($startTag.$mainContent.$endTag, $contentMarker, $filestring);

$indexHeadersArray = array();
$indexFilesArray = array();

/*
	//Sample value for $fArrayVal: TIP,TIPS,tips-all.html,index_tips.php,Cool Tips
	$fArray[$fArrayTemp[1] . ": "]["results-all"] = trim($fArrayTemp[2]);
	$fArray[$fArrayTemp[1] . ": "]["indexFile"] = trim($fArrayTemp[3]);
	$fArray[$fArrayTemp[1] . ": "]["indexHeading"] = trim($fArrayTemp[4]);
*/

//generate category index pages and links lists 
foreach ($fArray as $fKey => $fValue) {
	//print_r($fArray[$fKey]);
	$categoryHeadText = $fArray[$fKey]["indexHeading"];
	$filecontent = "<h3 class="post-title">$categoryHeadText</h3><ul>";
	echo "<hr><b>Writing category file: <strong>$categoryHeadText</strong> -> ". $tocOutputDir . $fArray[$fKey]["results-all"]. "</b>n<br>";
	$subItemsCount = 0;
	if (count($fArray[$fKey]) < 2) continue;//there's no data to output to file
	foreach ($fArray[$fKey] as $subfKey => $subfValue) {
		if (is_numeric($subfKey)) {
			echo str_replace($subValDelimiter," =&gt; ",$subfValue) . "<br>";
			//build links
			$subValArr = explode($subValDelimiter, $subfValue);
			$subValTitleArr = explode(":",$subValArr[0]);
			$subValTitle = trim($subValTitleArr[2]);//grab the title of the post's page
			$subValLink = trim($subValArr[1]);//get the link to the page
			$filecontent .= "<li><a href="http://$HTTP_HOST/$subValLink">" . $subValTitle . "</a></li>n";
			++$subItemsCount;
		}
	}
	$linkTarget = "";
	if ($linkFormat == 1) $linkTarget = " target="_blank"";
	$filecontent .= "</ul><br /><br /><p><a href="http://www.moshare.com/"$linkTarget>";
	if (empty($attributionText)) $attributionText = "Blogger Categories By Moshare.com";
	// possible values for $attributionFormat: (1) text link only, (2) web graphic only, (3) show both
	if ($attributionFormat == 3){
		$filecontent .= "<img src="http://www.moshare.com/images/moshare-blogger-categories.gif""
			. " width="170" height="19" border="0" alt="Moshare Blogger Categories"><br />$attributionText</a>";
	} elseif ($attributionFormat == 2){
		$filecontent .= "<img src="http://www.moshare.com/images/moshare-blogger-categories.gif""
			. " width="170" height="19" border="0" alt="Moshare Blogger Categories"></a>";
	} else {
		$filecontent .= "$attributionText</a>";
	}
	$filecontent .= "</p>";
	$filename = ".".$tocOutputDir . $fArray[$fKey]["results-all"];
	writeFile($filename,$filecontent,"w");//write TOC links file
	$indexFilesArray[$fArray[$fKey]["indexFile"]] .= $filecontent . "nn";
	$indexHeadersArray[$fArray[$fKey]["indexFile"]] = $fArray[$fKey]["indexHeading"];
	echo "<b>Number of links in this category page: $subItemsCount</b><br>";
}
reset ($indexFilesArray);
reset ($indexHeadersArray);
// for sidebar category links
$sidebarCLinks = null;
//generate index files from template for each type of link category
//print_r($indexFilesArray);
foreach ($indexFilesArray as $fKey => $fValue) {
	$headingVal = $indexHeadersArray[$fKey];
	$fileContent = str_replace($headingMarker, $headingVal, $filestring);
	$filename = ".".$tocOutputDir . $fKey;
	$fileContent = str_replace($contentMarker, $fValue, $fileContent);
	writeFile($filename,$fileContent,"w");//write TOC links file
	//add to category list
	$sidebarCUrl = "http://$HTTP_HOST".$tocOutputDir . $fKey;
	$sidebarCLinks .= "<li><a href="$sidebarCUrl">".$headingVal."</a></li>n";
}

if ($sidebarCLinks){//write sidebar category links file
	$sidebarCHeadText = ($sidebarCategoriesHeaderText)?("<h2 class="sidebar-title">$sidebarCategoriesHeaderText</h2>n"):null;
	
	
	$sidebarCLinks = $sidebarCHeadText."<ul>$sidebarCLinks</ul>";
	writeFile(".".$incSidebarCategoryFile,$sidebarCLinks,"w");
	
}

//to do: check for newer version

?>

<hr />
<p>To display your category list in your blog's sidebar, paste the following code in the sidebar section of your Blogger blog's template.</p> 
<form action="">
<textarea cols="70" rows="20" name="instructions">
<?
echo htmlentities($sidebarCLinks);
?>
</textarea>
</form>
<p><b>Here is a preview of what your category list looks like.</b> <br />Note: Your category list will look slightly different depending on your blog's stylesheet.</p>

<?
echo $sidebarCLinks;
?>
<hr />
<br clear="all" />
<h3>Visit: <a href="http://www.moshare.com/apps/blogger-categories/">http://www.moshare.com/apps/blogger-categories/</a> for the latest updates on this script</h3>
<hr />
<br clear="all" />
<h3>Go back to <a href="<? echo "http://$HTTP_HOST".$blogIndexFile; ?>">your blog: <? echo "http://$HTTP_HOST".$blogIndexFile; ?></a></h3>

<br clear="all" />
<script type="text/javascript"><!--
google_ad_client = "pub-5936448303847393";
google_ad_width = 180;
google_ad_height = 60;
google_ad_format = "180x60_as_rimg";
google_cpa_choice = "CAAQ4fqy0gEaCPI0fZSM10VxKL3D93M";
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>&nbsp;&nbsp;
<script type="text/javascript"><!--
google_ad_client = "pub-5936448303847393";
google_ad_width = 180;
google_ad_height = 60;
google_ad_format = "180x60_as_rimg";
google_cpa_choice = "CAAQ24Oy0QEaCGbgW7AaXRokKMu293M";
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<br clear="all" />
<br clear="all" />
</body></html>