<?php if (!defined('PmWiki')) exit();
/*
+------------------------------------------------------------------------------------------+
| Copyright 2008 Hans Bracker
| This program is free software; you can redistribute it and/or modify
| it under the terms of the GNU General Public License, Version 2, as
| published by the Free Software Foundation.
| http://www.gnu.org/copyleft/gpl.html
| This program is distributed in the hope that it will be useful,
| but WITHOUT ANY WARRANTY; without even the implied warranty of
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
| GNU General Public License for more details.
+------------------------------------------------------------------------------------------+
| blogcal.php for PmWiki
| A small calendar-by-month module for blogs; for PmWiki 2.2.0 (beta)
| Thanks to Feral for Cookbook.FeralSimpleCalendar providing the base for this script
| and to Chris Cox for Cookbook.PmCalendar providing parts for it.
|  
| Basic use: markup (:blogcal:) displays current month calendar
| with highlighted links to date pages of format YYYY-MM-DD in current group.
| For detailed instructions and customisations see page Cookbook.BlogCalendar on pmwiki.org
+------------------------------------------------------------------------------------------+
*/
$RecipeInfo['BlogCalendar']['Version'] = '2014-01-29';
/* Note, this version has some modifications by XES http://crisses.org */


//default settings
SDV($BlogCal['weekstart'], 0); //start on Sunday; set to 1 for start on Monday
SDV($BlogCal['basename'], ''); //prefix to ISO-date pagenames of blog group
SDV($BlogCal['isobasic'], 0); //use blog pagename format YYYY-MM-DD or basenameYYYY-MM-DD; set 1 for no hyphen
SDV($BlogCal['defaultgroup'], 0); //0 => defaults to current group; set specific default blog group name, i.e. 'BlogPages'  
SDV($BlogCal['pastonly'], 0); //show link to future months; set to 1 for showing only link to past month.
//daynames are set automatically according to locale, but could be set manually with this array 
#SDVA($BlogCal['daynames'], array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")); //daynames array
//Added by XES
SDV($BlogCal['multimessage'], 'posts found:'); //message appended to number if multiple entries are found on a given date
SDV($BlogCal['multimessagefmt'], 'titlespaced'); // which pagelist format to use for the results

//search path for blogcal.css file, if any
if (!isset($FarmPubDirUrl)) $FarmPubDirUrl = $PubDirUrl;
SDV($BlogCalendarPubListFmt, array (
       "pub/blogcal/blogcal.css"        => "$PubDirUrl/blogcal/blogcal.css",
       "$FarmD/pub/blogcal/blogcal.css" => "$FarmPubDirUrl/blogcal/blogcal.css" ));
// load  table styles for blog calendar
foreach((array)$BlogCalendarPubListFmt as $k=>$v) {
  if (file_exists(FmtPageName($k,$pagename))) {
      $HTMLHeaderFmt['blogcal'][] =
      	"<link rel='stylesheet' type='text/css' href='$v' media='screen' />\n";
  		break;
  }
  else
		//in HTML head css styling of blogcal table, used if no stylesheet is found 
		SDV($HTMLStylesFmt['blogcal'], " 
		table.bcal { margin:0 0.5em; padding:0; font-size:90%; }
		table.bcal caption {	text-align:center; font-weight:bold; padding:5px 0 2px 0;	}
		table.bcal caption a { text-decoration:none; }
		table.bcal th { width:2em; border-top:1px dotted #999; border-bottom:1px dotted #999;	
			font-weight:normal; font-size:.75em;	}
		table.bcal td { margin:0; padding:1px 1px 1px 0; text-align:center; 
			font-size:0.85em; line-height:1.2em; }
		td.bcal-daynames { text-align:center;	color:#333;	font-size:.75em; }
		td.bcal-blank {}
		td.bcal-today { background-color:#ffff00; color: #000000; }
		td.bcal-day { color: #333;	}
		a.bcal-link { text-decoration:none;	font-weight:bold;	}
		td.bcal-link {background-color:#bbddff; color: #000000; }
		td.bcal-linktoday { background-color: #ffcc00; color: #000000; }
		");
}

//set abbreviated day names
if (!is_array($BlogCal['daynames']))
	for	($i=1; $i<=7; $i++)
			$BlogCal['daynames'][$i-1] = strftime("%a",mktime(0,0,0,6,$i,2008)); //2008-06-01 was a Sunday

//markup and function
Markup('bcal','directives','/\\(:blogcal\\s*(.*?):\\)/e', "BlogCalendarFmt(\$pagename, PSS('$1'))");
function BlogCalendarFmt($pagename, $args) {
	global $ScriptUrl, $EnablePathInfo, $BlogCal;
	$req = RequestArgs();
	$args = ParseArgs($args);
	$args = array_merge($req, $args);
	#echo "<pre>\$args "; print_r($args); echo "</pre>";

	// Determine this Group
	$group = PageVar($pagename, '$Group');
	$name  = PageVar($pagename, '$Name');
	$PageUrl = ($EnablePathInfo) 
         ? $ScriptUrl.'/'.$group.'/'.$name
         : $ScriptUrl.'?n='.$group.'.'.$name;
	
	if (isset($args['group'])) $defaultgroup = $args['group'];
	elseif ($BlogCal['defaultgroup']!='0') $defaultgroup = $BlogCal['defaultgroup'];
	else $defaultgroup = $group;

	// What is today?
	$tyear = date("Y");
	$tmonth = date("m");
	$tday = date("d");

	$year  = isset($args['year'])  ? $args['year']  : $tyear;
	$month = isset($args['month']) ? $args['month'] : $tmonth;
	$day   = isset($args['day'])   ? $args['day']   : $tday;
	$month = isset($args['shift']) ? $month + $args['shift'] : $month;
	$prev_month = ($month>1) ? sprintf("%02.0f",$month-1) : 12;
	$prev_year = ($month>1) ? $year : $year - '01';
	$next_month = ($month<12) ? sprintf("%02.0f",$month+1) : '01';
	$next_year = ($month<12) ? $year : $year + 1;

	$itime	= mktime(0,0,0,$month,16,$year); // day 16, i.e. in the middle;
	$iyear	= strftime("%Y",$itime);
	$imonth	= strftime("%m",$itime);
	
	$monthname = strftime("%B&nbsp;%Y",$itime); // Monthname YYYY

	static $cnt=0; $cnt++;
		
	//output blogcal table
	$out = "\n<table id='bcal$cnt' class='bcal'>";
	
	$prev = "<a href='$PageUrl?year=$prev_year&amp;month=$prev_month' title='previous month'>&laquo;</a>";
	$next = "<a href='$PageUrl?year=$next_year&amp;month=$next_month' title='next month'>&raquo;</a>";	
	
	$pastonly = (isset($args['pastonly'])) ? 1 : $BlogCal['pastonly'];
	if ($pastonly==1 && $next_month>$tmonth) 
		$next = '';	
	if(isset($args['shift']))
		$out.= "<caption><p>$monthname</p></caption>";
	else
		$out.= "<caption>$prev&nbsp;$monthname&nbsp;$next</caption>";

	$maxdays = date("t",mktime(0,0,0,$month,1,$year));
	$weekdaystart = date('w',mktime(0,0,0,$month,1,$year));

	// weekstart should be from 0 to 6. // also from PmCal
	$BlogCal['weekstart'] = abs($BlogCal['weekstart']) % 7;
	if	($BlogCal['weekstart']>=1 &&	$weekdaystart==0)
		$weekdaystart = 7;

	//make table header cells (weekday names)
	$out.="\n   <tr>";
	for	($i=0; $i<7; $i++) {
		$d = ($i + $BlogCal['weekstart']) % 7;
		$out.= "<th class='bcal-daynames'>{$BlogCal['daynames'][$d]}</th>";
	}
	$out .= "   </tr>";
	
	$base = (isset($args['base'])) ? $args['base'] : $BlogCal['basename'];
	$sep = '-';
	if (isset($args['isobasic']) || $BlogCal['isobasic']==1) $sep = '';

	for ($index =($BlogCal['weekstart'] - $weekdaystart); $index < $maxdays; ) {
		$out.="\n   <tr>";
		//make table cells (day numbers)
		for ($i=0; $i<7; $i++, $index++)	{
			$daynum = $index+1;
			$tooltip = "";
			$pages = array();
			$class = 'bcal-day'; //set default class
			//empty cells: the day doesn't exist 
			if ($index<0 || $index >= $maxdays)  
				$out.="<td class='bcal-blank'>&nbsp;</td>";
			//normal cal cell
			else { 
				$paddeddaynum = ($daynum<10) ? "0".$daynum : $daynum;
				$pname = $base.$iyear.$sep.$imonth.$sep.$paddeddaynum;
				$pname = MakePageName($pagename, $defaultgroup.".".$pname);
				//  -- Added by Criss -- Determine whether there are any subpages with that date
				$pages = ListPages('/^' . preg_quote($pname,'/') . '.*/');
				$count = count($pages);
				if ($count > 0) {
					//log page link cell
					$class = 'bcal-link';
					// Test for today, change class
					if ($tyear==$year && $tmonth==$month && $tday==$daynum)
						$class = 'bcal-linktoday';
					// Build tooltips to list each page
					foreach ($pages as $thispage) {
						if (isset($args['tooltip'])) {
							if ($args['tooltip']=='description' || $args['tooltip']=='Description')
								$tooltip .= PageVar($thispage,'$Description') . "\n";
							else $tooltip .= PageTextVar($thispage,$args['tooltip']) . "\n";
						}
						else $tooltip .= PageVar($thispage,'$Titlespaced') . "\n";
					}
					// If there's more than one, prepend different format, and have different output...
					if ($count > 1 ) {
						$tooltip = "$count " . $BlogCal['multimessage'] . "\n"  . substr($tooltip, 0, -1) ; //strip the last newline
						// ?action=search&q=name%3DBlog%2F20140102*+fmt%3D%23titlespaced
						$out .= "<td class='$class'><a class='bcal-link' href='?action=search&q=name%3D" . PUE($pname)  ."*+fmt%3D%23" . PUE($BlogCal['multimessagefmt']) . "' title='". htmlentities($tooltip, ENT_QUOTES) ."'>$daynum</a></td>";
					} else {
						if (isset($args['tooltip'])) {
							if ($args['tooltip']=='description' || $args['tooltip']=='Description')
								$tooltip = PageVar($pages[0],'$Description');
							else $tooltip = PageTextVar($pages[0],$args['tooltip']);
						}
						else $tooltip = PageVar($pages[0],'$Titlespaced');
						$out .= "<td class='$class'><a class='bcal-link' href='$ScriptUrl?n=" . $pages[0] . "' title='" . htmlentities($tooltip, ENT_QUOTES) ."'>$daynum</a></td>";
					}

				} else {
					//today cell
					if ($tyear==$year && $tmonth==$month && $tday==$daynum)
						 $class = 'bcal-today';
					$out.="<td class='$class'>$daynum</td>";
				}
			}
		}
		$out .= "   </tr>";
	}
	$out.= "\n</table>\n";
	return Keep($out);
} // }}}