<?php if (!defined('PmWiki')) exit();
/*
  EditTitle (v 1.1)
  
  Copyright 2005 - Waylan Limberg (waylan@gmail.com)
  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 input field to the edit form of PmWiki.
  For more info and instructions go to http://www.pmwiki.org/wiki/Cookbook/EditTitle
*/

## define default variables 
if (!isset($EditTitleInputFmt))
  $EditTitleInputFmt = "<label>\$[Title]: <input type='text' \$InputFormArgs /></label>";
if (!isset($ForceTitleMessageFmt))
  $ForceTitleMessageFmt = '<h3 class="wikimessage">A Title must be defined for this page</h3>';
# pattern should be same as defined in markup
if (!isset($EditTitlePattern))
  $EditTitlePattern = '/\\(:title\\s(.*?):\\)/i';

## define pointers to functions (Note: order IS important)
array_push($EditFunctions, 'RemoveTitle');
array_unshift($EditFunctions, 'RequireTitle');
array_unshift($EditFunctions, 'AddTitle');
array_unshift($EditFields, 'title');

## RemoveTitle removes title from markup and  sets it to display in text input field
function RemoveTitle($pagename, &$page, &$new){
  global $InputTags, $EditTitle, $EditTitleInputFmt, $EditTitlePattern;
  if (isEnabled($EditTitle, 1)) {
    if (!isset($new['title'])){
      if (preg_match($EditTitlePattern, $new['text'], $matches)){
        $new['title'] = $matches[1];
      }else{
        $new['title'] = '';
      }
    }
    $new['text'] = trim(preg_replace($EditTitlePattern,'', $new['text'] ));    
    SDVA($InputTags["e_title"], array(
      ':html' => $EditTitleInputFmt, 'name' => 'title', 
      'size' => '60' ,'value' => $new['title']));
  } else {
    SDVA($InputTags["e_title"], array(':html' => ''));
  }
  return;
}

## AddTitle adds title back into markup before saving
function AddTitle($pagename, &$page, &$new){
  global $EditTitle;
  if ($new['title'] > '' && isEnabled($EditTitle, 1)) 
    $new['text'] = "(:title ".$new['title'].":)\n".$new['text'];
  return;
}

## Require that a title be defined on each page
function RequireTitle($pagename, &$page, &$new){
  global $EnablePost, $MessagesFmt, $ForceTitle, $DeleteKeyPattern,
    $EditTitlePattern, $ForceTitleMessageFmt;
  if (isEnabled($ForceTitle, 0) && (trim($new['text']) != $DeleteKeyPattern) &&
     (!preg_match($EditTitlePattern, $new['text']))) {
      $EnablePost = 0;
      $MessagesFmt[] = $ForceTitleMessageFmt;
  }
  return;
}