<?php if (!defined('PmWiki')) exit();
/*
  EditMore (v 1.2)
  
  Copyright 2007 - Michael Shanley, based on the code of 
  Waylan Limberg (waylan@gmail.com - copyright 2005)
  Thank you very much Waylan!
  
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
  by the Free Software Foundation; either version 2 of the License, or 
  (at your option) any later version.
  
  Description: 
  	Adds a Title, Keywords, Notes, and Description input field option.
  	Adds a Tags input field and converts comma-separated list into categories,
		creating a $:tags pagetext variable to display them.
	Allows the option to require a Title, Keywords, Description, Tags, Notes,
		or Summary.
  
  to use,
  	1. add this to your local/config.php:
		include_once("$FarmD/cookbook/editmore.php");
		
	2. add the following to your {$SiteGroup}.EditForm, wherever you want
	 them to appear:
		Title: (:input e_title:)\\
		Keywords: (:input e_keywords:)\\
		Description: (:input e_description:)\\
		Tags: (:input e_tags:)\\
		Notes:\\
		(:input e_notes:)\\
		
	3. remember to disable whichever tags you don't need...
		For instance, if you only want to get edit the Title and keywords 
		this way, add these lines to you local/config.php:
		
			$EMFields = array('title','keywords');
			include_once("$FarmD/cookbook/editmore.php");
  
  For more info and instructions go to 
  					http://www.pmwiki.org/wiki/Cookbook/EditMore

*/ 

## VERSION INFO
	$RecipeInfo['EditMore']['Version'] = '2007-09-18';

## UNIVERSAL VARIABLES
	# Which fields do you want active?
	SDV($EMFields,array('title','keywords','description','tags','notes','checkboxes'));
			//OPTIONS: title, keywords, description, tags, notes, checkboxes
				//if some are left out, will not display on edit page.
				//if completely empty, will not load.
	
		# Which Fields do you want to force?
		SDV($EMForcefully,array());
				//OPTIONS: summary, title, keywords, description, tags, notes

		#$ TITLE
			SDV($EMTitleFillEmpty,1); //Will automatically fill an empty title input with $Namespaced
			SDV($EMTitleFillExclude,array('GroupHeader','GroupFooter','RecentChanges','SideBar','EditForm')); 
										//Which pages to exclude from this behavior if active.
		## NOTES
			SDV($EMNotesDisplay,0); //How should I display them? 0 is hidden, or name the div ID.
			SDV($EMNotesPosition,''); //Placed at the bottom unless set = 'top'

############################ MORE VARIABLES ############################

if($EMFields != '' && $action == 'edit') { //to keep excess from loading

	## OTHER VARIABLES
		#$ TITLE
			SDV($EMTitleInputDisplay,"size='50%'");//attributes for <input tag
			sdv($EMForceTitleFmt,'<h3 class="wikimessage">A Title must be defined for this page!</h3>');
			SDV($EMTitlePattern,'/\\(:title\\s(.*?):\\)/i'); //same as in scripts/stdmarkup.php
			
		## KEYWORDS
			SDV($EMKeywordsInputDisplay,"size='50%'");//attributes for <input tag
			sdv($EMForceKeywordsFmt,'<h3 class="wikimessage">Keywords must be defined for this page!</h3>');
			SDV($EMKeywordsPattern,'/\\(:keywords\\s(.*?):\\)/i'); //same as in scripts/stdmarkup.php
	
		## DESCRIPTION
			SDV($EMDescriptionInputDisplay,"size='50%'");//attributes for <input tag
			sdv($EMForceDescriptionFmt,'<h3 class="wikimessage">A Description must be defined for this page!</h3>');
			SDV($EMDescriptionPattern,'/\\(:description\\s(.*?):\\)/i'); //same as in scripts/stdmarkup.php
		
		## TAGS
			SDV($EMTagsInputDisplay,"size='50%'");//attributes for <input tag
			sdv($EMForceTagsFmt,'<h3 class="wikimessage">Tags must be defined for this page!</h3>');
			SDV($EMTagsPattern,'/\\(:tags:(.*?):\\)/i'); //special pagetext definition
			
		## NOTES
			SDV($EMNotesInputDisplay,"width='100%' rows='5'");//attributes for <input tag
			sdv($EMForceNotesFmt,'<h3 class="wikimessage">Notes must be defined for this page!</h3>');		
			SDV($EMNotesPattern,'/ \\(:notes:\\)(.*?)\\(:notesend:\\)/seix'); //special definition
	
		## SUMMARY
			SDV($EMForceSummaryFmt,'<h3 class="wikimessage">A Summary must be defined for this page!</h3>');		
		
############################ CODE ############################

	## define pointers to functions (Note: order IS important)
	array_push($EditFunctions,'EditMoreRemove');
	array_unshift($EditFunctions,'EditMoreRequire');
	array_unshift($EditFunctions,'EditMoreAdd');
	foreach($EMFields as $EMFieldsFall)
		array_unshift($EditFields,$EMFieldsFall);

	### EditMoreRemove ###
	## To collect information from the page
	function EditMoreRemove($pagename, &$page, &$new) {
		global $InputTags, $EMFields;
		
			# TITLE
			if(in_array('title',$EMFields)) {
				global $EMTitlePattern, $EMTitleFillEmpty, $EMTitleFillExclude, $name, $EMTitleInputDisplay;
				  
				if (preg_match($EMTitlePattern, $new['text'], $matches)) {
					//fill with old title if it already exists
					$new['title'] = htmlspecialchars($matches[1], ENT_QUOTES);
				}else{
					//fill empty if user wants it, else blank
					$EMTitleFill = '';
					$EMNameCall = array_pop(explode('.',$pagename));

					if($EMTitleFillEmpty > 0 && !in_array($EMNameCall,$EMTitleFillExclude)) {
						$EMTitleFill = $EMNameCall;
						$EMTitleFill = preg_replace("/([[:lower:]\\d])([[:upper:]])/", '$1 $2',$EMTitleFill);
						$EMTitleFill = preg_replace('/([^-\\d])(\\d[-\\d]*( |$))/','$1 $2',$EMTitleFill);
						$EMTitleFill = preg_replace("/([[:upper:]])([[:upper:]][[:lower:]\\d])/",'$1 $2',$EMTitleFill);
					}
					
					$new['title'] = htmlspecialchars($EMTitleFill, ENT_QUOTES);
				}

				$new['text'] = trim(preg_replace($EMTitlePattern,'', $new['text'] ));

				SDVA($InputTags["e_title"], 
					array(':html' => "<input type='text' name='title' ".$emtitleinputdisplay." value='".Keep($new['title'])."' />"));
			}else{
				SDVA($InputTags["e_title"], array(':html' => ''));
			}
			
			# KEYWORDS
			if(in_array('keywords',$EMFields)) {
				global $EMKeywordsPattern, $EMKeywordsInputDisplay;
				  
				if (preg_match($EMKeywordsPattern, $new['text'], $matches)) {
					//fill with old keywords if they already exist
					$new['keywords'] = htmlspecialchars($matches[1], ENT_QUOTES);
				}else{
					//fill blank
					$new['keywords'] = '';
				}

				$new['text'] = trim(preg_replace($EMKeywordsPattern,'', $new['text'] ));

				SDVA($InputTags["e_keywords"],array(':html' => 
					"<input type='text' name='keywords' size='50%' ".$emkeywordsinputdisplay." value='".Keep($new['keywords'])."' />"));
			}else{
				SDVA($InputTags["e_keywords"],array(':html' => ''));
			}
			
			# DESCRIPTION
			if(in_array('description',$EMFields)) {
				global $EMDescriptionPattern, $EMDescriptionInputDisplay;
				  
				if (preg_match($EMDescriptionPattern, $new['text'], $matches)) {
					//fill with old description if they already exist
					$new['description'] = htmlspecialchars($matches[1], ENT_QUOTES);
				}else{
					//fill blank
					$new['description'] = '';
				}

				$new['text'] = trim(preg_replace($EMDescriptionPattern,'', $new['text'] ));

				SDVA($InputTags["e_description"],array(':html' => 
					"<input type='text' name='description' ".$emdescriptioninputdisplay." value='".Keep($new['description'])."' />"));
			}else{
				SDVA($InputTags["e_description"], array(':html' => ''));
			}
			
			# TAGS
			if(in_array('tags',$EMFields)) {
				global $EMTagsPattern, $EMTagsInputDisplay;
				  
				if (preg_match($EMTagsPattern, $new['text'], $matches)) {
					//fill with old description if they already exist
					$new['tags'] = htmlspecialchars($matches[1], ENT_QUOTES);
				}else{
					//fill blank
					$new['tags'] = '';
				}

				$new['text'] = trim(preg_replace($EMTagsPattern,'', $new['text'] ));

				SDVA($InputTags["e_tags"],array(':html' => 
					"<input type='text' name='tags' ".$emtagsinputdisplay." value='".Keep($new['tags'])."' />"));
			}else{
				SDVA($InputTags["e_tags"], array(':html' => ''));
			}

			# NOTES
			if(in_array('notes',$EMFields)) {
				global $EMNotesPattern, $EMNotesInputDisplay;
				  
				if (preg_match($EMNotesPattern, $new['text'], $matches)) {
					//fill with old description if they already exist
					$new['notes'] = trim(htmlspecialchars($matches[1], ENT_QUOTES));
				}else{
					//fill blank
					$new['notes'] = '';
				}

				$new['text'] = trim(preg_replace($EMNotesPattern,'', $new['text'] ));

				SDVA($InputTags["e_notes"],array(':html' => 
					"<textarea name='notes' ".$emnotesinputdisplay." />".Keep($new['notes'])."</textarea>"));
			}else{
				SDVA($InputTags["e_notes"], array(':html' => ''));
			}
						
		return;
	}
	/// EditMoreRemove ///
	
	### EditMoreRequire ###
	## To make sure fields are filled
	function EditMoreRequire($pagename, &$page, &$new) {
		global $EMFields, $EMForcefully, $DeleteKeyPattern, $MessageFmt, $EnablePost, $ChangeSummary,
			$EMTitlePattern, $EMKeywordsPattern, $EMDescriptionPattern, $EMTagsPattern, $EMNotesPattern;
		
		if(trim($new['text']) != $DeleteKeyPattern) {
			# TITLE
			if(in_array('title',$EMForcefully) && (!preg_match($EMTitlePattern, $new['text'])) ) {
				global $EMForceTitleFmt;

				$EnablePost = 0;
				$MessagesFmt[] = $EMForceTitleFmt;
			}
			
			# KEYWORDS
			if(in_array('keywords',$EMForcefully) && (!preg_match($EMKeywordsPattern, $new['text'])) ) {
				global $EMForceKeywordsFmt;

				$EnablePost = 0;
				$MessagesFmt[] = $EMForceKeywordsFmt;
			}
			
			# DESCRIPTION
			if(in_array('description',$EMForcefully) && (!preg_match($EMDescriptionPattern, $new['text'])) ) {
				global $EMForceDescriptionFmt;

				$EnablePost = 0;
				$MessagesFmt[] = $EMForceDescriptionFmt;
			}
			
			# TAGS
			if(in_array('tags',$EMForcefully) && (!preg_match($EMTagsPattern, $new['text'])) ) {
				global $EMForceTagsFmt;

				$EnablePost = 0;
				$MessagesFmt[] = $EMForceTagsFmt;
			}
			
			# NOTES
			if(in_array('notes',$EMForcefully) && (!preg_match($EMNotesPattern, $new['text'])) ) {
				global $EMForceNotesFmt;

				$EnablePost = 0;
				$MessagesFmt[] = $EMForceNotesFmt;
			}
			
			# SUMMARY
			if(in_array('summary',$EMForcefully) && ($EnablePost && !$ChangeSummary)) {
				global $EMForceSummaryFmt;

				$EnablePost = 0;
				$MessagesFmt[] = $EMForceSummaryFmt;
			}
		}
		
		return;
	}
	/// EditMoreRequire ///

	### EditMoreAdd ###
	## To add the info back into the page
	function EditMoreAdd($pagename, &$page, &$new) {
		global $EMNotesPosition;
	
			# TITLE
			if($new['title'] > '') 
				$new['text'] = "(:title ".$new['title'].":)\n".$new['text'];
			
			# KEYWORDS
			if($new['keywords'] > '') 
				$new['text'] = "(:keywords ".$new['keywords'].":)\n".$new['text'];
				
			# DESCRIPTION
			if($new['description'] > '') 
				$new['text'] = "(:description ".$new['description'].":)\n".$new['text'];
				
			# NOTES
			if($new['notes'] > '' && $EMNotesPosition == 'top') 
				$new['text'] = "(:notes:)\n".$new['notes']."\n(:notesend:)\n".$new['text'];
			elseif($new['notes'] > '')
				$new['text'] = $new['text']."\n(:notes:)\n".$new['notes']."\n(:notesend:)";
			
			# TAGS
			if($new['tags'] > '') {
				global $CategoryGroup;
					
				$EMTCategoryGroupLower = strtolower($CategoryGroup);
					
				$EMTCleanArray = array('[',']','!',
							'Category:','category:',"$CategoryGroup:","$EMTCategoryGroupLower:",
							'Category/','category/',"$CategoryGroup/","$EMTCategoryGroupLower/",
							'Category.','category.',"$CategoryGroup.","$EMTCategoryGroupLower.");
						
				#Make into categories...
				$EMTMatches = $new['tags'];
				$EMTMatchesArray = explode(',',str_replace($EMTCleanArray,'',$EMTMatches));

				Foreach($EMTMatchesArray as $EMTM) {
					$EMTM = trim($EMTM);
							
					if($EMTM == '')
						$EMTFixed .= '';
					elseif(strstr($EMTM,'/') === FALSE && strstr($EMTM,'.') === FALSE)
						$EMTFixed .= '[[!'.$EMTM.']], ';
					else
						$EMTFixed .= '[['.$EMTM.']], ';
				}
						
				$new['tags'] = substr($EMTFixed,0,-2);

				#make the markup
				$new['text'] = "(:tags:".$new['tags'].":)\n".$new['text'];
			}
			
		return;
	}
	/// EditMoreAdd ///

}elseif($EMFields != '' && $action != 'edit') {
	# NOTES
	//Displaying Notes Box
	if($EMNotesDisplay > '') {
		Markup('EditMoreNotes','<split',
			'/\\(:notes:\\)(.*?)\\(:notesend:\\)/six',
			'(:div id=\''.$EMNotesDisplay.'\':)$1(:divend:)');
	}else{
		Markup('EditMoreNotes','<split',
			'/\\(:notes:\\)(.*?)\\(:notesend:\\)/six',
			'(:div style="display:none;":)$1(:divend:)');
	}
	
}