<?php if (!defined('PmWiki')) exit();
/*  Copyright 2006 Hans Bracker, modified from newpagebox.php
    Copyright 2005 Patrick R. Michaud (pmichaud@pobox.com) and
    newpagebox3.php thanks to code from DaveG.
    This file is newgroupbox.php; 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.

    To use this script, simply place it into the cookbook/ folder
    and add the line
        include_once('cookbook/newgroupbox.php');
    to a local customization file.

    usage: (:newgroupbox [parameter=value] [parameter=value] :)

    Possible parameters to use inside the markup:

    base=PageName -- creates new group page as NewName.PageName
              (PageName does not need to exist). Default is Group.{$DefaultName}
    template=Group.PageTemplateName -- use Group.PageTemplateName as template for new page.
    value="Create New Group" -- label or value for the inside of the field,
                            which disappears when clicking the box. Default is empty: "".
    size=number -- size of input box, default is 30.
    label="Button Label" -- label for the button, default "Create a new group called:".
    button=position -- use "left" or "right" to position button (default is "left").
    focus=true -- adds onfocus and onblur javascript which will make any initial value
                    disappear when clicking on the box. Default is "".
    autopages=Templates.Page1,Templates.Page2,Templates.HomePage,...
            specifies a list of template pages, comma separated,
            which newgroupbox will use to automatically create new group pages.
            parameters save=  and template= will be ignored.
            Specify a base= parameter a sone of the new pages,
            so the form can redirect to that page.
    autogroup=true -- enables automatic creation of pages defined in $AutoGroupPagesFmt
        Default pages: Templates.HomePage,Templates.GroupHeader,Templates.GroupFooter.
        Redefine the array in config.php before including this script
        for your own set of template pages to be used for automatic page creation
        in the new group.

    Example:
    (:newgroupbox base=Index template=Site.NewIndexPage :)
    Entering "Name" will create a new page called Name.Index,
    prefilled with content from Site.NewIndexPage
    
    2014-05-14 changes
    * updated for PHP 5.5 by using markup_e (line 71)
    * fixed Lambda problem (line 113)
    * chnage group pagename default to be Wiki page name default by using $DefaultName (line6 66, 120) 
*/
# Version date
$RecipeInfo['NewGroupBox']['Version'] = '2017-06-17';

# Set $EnableAutoSave = 1; if you want users to be able to create new group pages
# with options save=true, autogroup=true or autopages="list of template pages". 
# These options are available for users if authorised at 'edit' level though.
# Default is false, as security against page creation spamming.
SDV($EnableAutoSave, false);

# set $EnablePostRecentChangesForAutoGroupPages = false;
# in config.php to disable (All)RecentChanges from showing
# the new pages created automatically using autogroup and autopages.
SDV($EnablePostRecentChangesForAutoGroupPages, 1);

SDV($AutoGroupPagesFmt, array(
    'Templates.HomePage'    => '{$Group}.{$DefaultName}', // change from HomePage to $DefaultName
    'Templates.GroupHeader' => '{$Group}.GroupHeader',
    'Templates.GroupFooter' => '{$Group}.GroupFooter'));

# add markup (:newgroupbox:)
Markup('newgroupbox', 'directives', '/\\(:newgroupbox\\s*(.*?):\\)/i', "NewGroupBox");

# add action=new (the form sends this with the other values)
$HandleActions['newgroup'] = 'HandleNewGroup';

# add form function. The values for parameter defaults can be changed here
function NewGroupBox($m) {
  global $DefaultName;
  extract($GLOBALS['MarkupToHTML']);
  $PageUrl = PageVar($pagename, '$PageUrl');    
  $defaults = array(
		'base' => $DefaultName,
    'label' => FmtPageName(' $[Create a new group called:] ', $pagename),
    'button' => 'left',
    );
  $opt = array_merge($defaults, ParseArgs($m[1]));
  $buttonHTML = "    <input class='inputbutton newpagebutton' type='submit' value='{$opt['label']}' /> \n";
  $onfocusHTML = "
       onfocus=\"if(this.value=='{$opt['value']}') {this.value=''}\" onblur=\"if(this.value=='') {this.value='{$opt['value']}'}\" ";
  $out = "\n  <form class='newgroup' action='{$PageUrl}' method='post'>
    <input type='hidden' name='n' value='$pagename' />
    <input type='hidden' name='action' value='newgroup' /> \n".
    ($opt['value'] ? "    <input type='hidden' name='value' value='{$opt['value']}' /> \n" : "").
    ($opt['focus'] ? "    <input type='hidden' name='focus' value='{$opt['focus']}' /> \n" : "").
    ($opt['base'] ? "    <input type='hidden' name='base' value='{$opt['base']}' /> \n" : "").
    ($opt['save'] ? "    <input type='hidden' name='save' value='{$opt['save']}' /> \n" : "").
    ($opt['autogroup'] ? "    <input type='hidden' name='autogroup' value='{$opt['autogroup']}' /> \n" : "").
    ($opt['template'] ? "    <input type='hidden' name='template' value='{$opt['template']}' /> \n" : "").
    ($opt['autopages'] ? "    <input type='hidden' name='autopages' value='{$opt['autopages']}' /> \n" : "").
    ($opt['button']=="left" ? $buttonHTML : "").
    "    <input class='inputbox newpagetext' type='text' name='name' value='{$opt['value']}' size='{$opt['size']}'" .
    ($opt['focus']=="true" ? $onfocusHTML : "").
    "/> \n" .
    ($opt['button']=="right" ? $buttonHTML : "").
    "  </form>";
  return Keep($out);  
}

# handles action=new, i.e. what the form sends, sends new page to edit
function HandleNewGroup($pagename) {
  global $Author, $EnableAutoGroupPages, $AutoGroupPagesFmt,
  $EnablePostRecentChangesForAutoGroupPages, $EnableAutoSave, $MakePageNamePatterns;
  $group = PPRA($MakePageNamePatterns, @$_REQUEST['name']); // updated to fix Lambda problem
  if (!$group) Redirect($pagename);
  if (@$_REQUEST['focus'] && $group==$_REQUEST['value']) Redirect($pagename);
  if (@$_REQUEST['autogroup'] AND ($EnableAutoSave==1 OR CondAuth($pagename,'edit'))) 
      $EditFunctions[] = 'AutoGroupPages';
  $base = MakePageName($pagename, $_REQUEST['base']);
  $name = PageVar($base, '$Name');
  $newpage = MakePageName($base, "$group.$name"); // always use $name to use $DefaultPage
  $urlfmt = '$PageUrl?action=edit';
  if (@$_REQUEST['template']) {
    $urlfmt .= '&template=' . MakePageName($base, $_REQUEST['template']); }
  if (@$_REQUEST['autopages'] AND ($EnableAutoSave==1 OR CondAuth($pagename,'edit'))) {
        $pages = explode(",", $_REQUEST['autopages']);
        foreach($pages as $p) {
            $tp = explode(".", $p);
            $AutoGroupPagesFmt[$p] = MakePageName($pagename, "$group.$tp[1]");
        }
        AutoGroupPages($pagename, $page, $new);
        Redirect($newpage);
  }
  if (@$_REQUEST['save'] AND ($EnableAutoSave==1 OR CondAuth($pagename,'edit'))) {
     if(PageExists($newpage)) Redirect($newpage, $urlfmt);
     if (@$_REQUEST['template'] && PageExists($_REQUEST['template'])) {
        $p = RetrieveAuthPage($_REQUEST['template'], 'read', false, READPAGE_CURRENT);
          if ($p['text'] > '') $new['text'] = $p['text'];
          $new['author'] = $Author;}
        SaveAttributes($newpage, $new, $new);
        PostPage($newpage, $new, $new);
        PostRecentChanges($newpage, $new, $new);
        if(@$_REQUEST['autogroup']) AutoGroupPages($newpage, $new, $new);
        Redirect($newpage);
       }
   Redirect($newpage, $urlfmt);
}

function AutoGroupPages($pagename, $page, $new) {
     global $IsPagePosted, $AutoGroupPagesFmt,
     $EnablePostRecentChangesForAutoGroupPages;
     if (!$IsPagePosted && !@$_REQUEST['autopages']) return;
     foreach($AutoGroupPagesFmt as $t => $n) {
             $n = FmtPageName($n, $pagename);
             if (!PageExists($n)) {
                 $t = FmtPageName($t, $pagename);
                 WritePage($n, ReadPage($t));
                 $IsPagePosted = true;
                 if($EnablePostRecentChangesForAutoGroupPages==1)
                    PostRecentChanges($n, $new, $new);
             }
     }
}