<?php
// File: $Id: pnadmin.php 17529 2006-01-12 13:42:10Z markwest $
// ----------------------------------------------------------------------
// PostNuke Content Management System
// Copyright (C) 2001 by the PostNuke Development Team.
// http://www.postnuke.com/
// ----------------------------------------------------------------------
// LICENSE
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// 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.
//
// To read the license please visit http://www.gnu.org/copyleft/gpl.html
// ----------------------------------------------------------------------
// Original Author of file:  Erik Slooff <erik@slooff.com> www.slooff.com
// Purpose of file:
// PHP-NUKE 5.0: Quote of the day Add-On
// Copyright (c) 2000 by Erik Slooff (erik@slooff.com)
// ----------------------------------------------------------------------
// Changes for this admin module thanks to Heinz Hombergs
// (heinz@hhombergs.de), http://www.kodewulf.za.net
// ----------------------------------------------------------------------

/**
 * @package PostNuke_ResourcePack_Modules
 * @subpackage Quotes
 * @license http://www.gnu.org/copyleft/gpl.html
*/
/**
 * Quotes main administration function
 * @author Erik Slooff
 * @return string HTML string
 */
function quotes_admin_main()
{
    // Security check - important to do this as early as possible to avoid
    // potential security holes or just too much wasted processing.  For the
    // main function we want to check that the user has at least edit privilege
    // for some item within this component, or else they won't be able to do
    // anything and so we refuse access altogether.  The lowest level of access
    // for administration depends on the particular module, but it is generally
    // either 'edit' or 'delete'
    if (!pnSecAuthAction(0, 'Quotes::', '::', ACCESS_EDIT)) {
        return pnVarPrepHTMLDisplay(_MODULENOAUTH);
    }

    // Create output object - this object will store all of our output so that
    // we can return it easily when required
	$pnRender =& new pnRender('Quotes');

	// As Admin output changes often, we do not want caching.
	$pnRender->caching = false;

    // Return the output that has been generated by this function
    return $pnRender->fetch('quotes_admin_main.htm');

}

/**
 * Display form to create a new quote
 * @author Mark West
 * @return string HTML string
 */
function quotes_admin_new()
{
    // Security check - important to do this as early as possible to avoid
    // potential security holes or just too much wasted processing
    if (!pnSecAuthAction(0, 'Quotes::', '::', ACCESS_ADD)) {
        return pnVarPrepHTMLDisplay(_MODULENOAUTH);
    }

    // Create output object - this object will store all of our output so that
    // we can return it easily when required
	$pnRender =& new pnRender('Quotes');

	// As Admin output changes often, we do not want caching.
	$pnRender->caching = false;

    // Return the output that has been generated by this function
    return $pnRender->fetch('quotes_admin_new.htm');

}

/**
 * Create a new quote
 * @author Erik Slooff
 * @param 'qquote' quote text
 * @param 'qauthor' quote author
 * @return bool true if create success, false otherwise
 */
function quotes_admin_create($args)
{
    // Get parameters from whatever input we need.  All arguments to this
    // function should be obtained from pnVarCleanFromInput(), getting them
    // from other places such as the environment is not allowed, as that makes
    // assumptions that will not hold in future versions of PostNuke
    list($qquote, $qauthor) = pnVarCleanFromInput('qquote', 'qauthor');

    // Admin functions of this type can be called by other modules.  If this
    // happens then the calling module will be able to pass in arguments to
    // this function through the $args parameter.  Hence we extract these
    // arguments *after* we have obtained any form-based input through
    // pnVarCleanFromInput().
    extract($args);

    // Confirm authorisation code.  This checks that the form had a valid
    // authorisation code attached to it.  If it did not then the function will
    // proceed no further as it is possible that this is an attempt at sending
    // in false data to the system
    if(!pnSecConfirmAuthKey()) {
	    pnSessionSetVar('errormsg', _BADAUTHKEY);
	    pnRedirect(pnModURL('Quotes', 'admin', 'main'));
	    return true;
    }
	
    // Notable by its absence there is no security check here.  This is because
    // the security check is carried out within the API function and as such we
    // do not duplicate the work here

    // The API function is called.  Note that the name of the API function and
    // the name of this function are identical, this helps a lot when
    // programming more complex modules.  The arguments to the function are
    // passed in as their own arguments array
	$qid = pnModAPIFunc('Quotes',
		                'admin',
                        'create',
		                array('qquote' => $qquote,
			                  'qauthor' => $qauthor));
    if($qid != false) {
        // Success	
	    pnSessionSetVar('statusmsg', _QUOTESADDSUCCESS);
    }
	
    // This function generated no output, and so now it is complete we redirect
    // the user to an appropriate page for them to carry on their work
    pnRedirect(pnModURL('Quotes', 'admin', 'view'));

    // Return
    return true;
}

/**
 * Display full list of quotes
 * @author Erik Slooff
 * @return string HTML string
 */
function quotes_admin_view()
{
    // Security check
    if(!(pnSecAuthAction(0, 'Quotes::', '::', ACCESS_EDIT))) {
        return pnVarPrepHTMLDisplay(_MODULENOAUTH);
    }

    // Get parameters from whatever input we need.  All arguments to this
    // function should be obtained from pnVarCleanFromInput(), getting them
    // from other places such as the environment is not allowed, as that makes
    // assumptions that will not hold in future versions of PostNuke
    $startnum = pnVarCleanFromInput('startnum');

    // Create output object - this object will store all of our output so that
    // we can return it easily when required
	$pnRender =& new pnRender('Quotes');

	// As Admin output changes often, we do not want caching.
	$pnRender->caching = false;

    // The user API function is called.  This takes the number of items
    // required and the first number in the list of all items, which we
    // obtained from the input and gets us the information on the appropriate
    // items.
    $quotes = pnModAPIFunc('Quotes',
                           'user',
                           'getall',
                           array('startnum' => $startnum,
                                 'numitems' => pnModGetVar('Quotes',
                                                           'itemsperpage')));
    $items = array();
    foreach($quotes as $quote) {
        if (pnSecAuthAction(0, 'Quotes::', "$quote[author]::$quote[qid]", ACCESS_READ)) {

            // Options for the item.  Note that each item has the appropriate
            // levels of authentication checked to ensure that it is suitable
            // for display
            $options = array();
    	    if(pnSecAuthAction(0, 'Quotes::', "$quote[author]::$quote[qid]", ACCESS_EDIT)) {
	            $options[] = array('url' => pnModURL('Quotes', 'admin', 'modify', array('qid' => $quote['qid'])),
				                   'title' => _QUOTESEDITACTION);
                if(pnSecAuthAction(0, 'Quotes::', "$quote[author]::$quote[qid]", ACCESS_DELETE)) {
	                $options[] = array('url' =>pnModURL('Quotes', 'admin', 'delete', array('qid' => $quote['qid'])),
					                   'title' => _QUOTESDELETEACTION);
                }
	        }
            $items[] = array('quotetext' => $quote['quote'],
			                  'quoteauthor' => $quote['author'],
							  'options' => $options);
        }
    }
    $pnRender->assign('quotes', $items);

    // Assign the values for the smarty plugin to produce a pager in case of there
    // being many items to display.
    //
    // Note that this function includes another user API function.  The
    // function returns a simple count of the total number of items in the item
    // table so that the pager function can do its job properly
	$pnRender->assign('pager', array('numitems' => pnModAPIFunc('Quotes', 'user', 'countitems'),
	                           'itemsperpage' => pnModGetVar('Quotes', 'itemsperpage')));

    return $pnRender->fetch('quotes_admin_view.htm');

}

/**
 * Edit quote
 * @author Erik Slooff
 * @param 'qid' Quote id to delete
 * @param 'qauther' Author of quote to delete
 * @param 'confirm' Delete confirmation
 * @return mixed HTML string if confirm is null, true otherwise
 */
function quotes_admin_modify($args)
{
    // Get parameters from whatever input we need.  All arguments to this
    // function should be obtained from pnVarCleanFromInput(), getting them
    // from other places such as the environment is not allowed, as that makes
    // assumptions that will not hold in future versions of PostNuke
    list($qid,
         $objectid)= pnVarCleanFromInput('qid',
                                         'objectid');

    // Admin functions of this type can be called by other modules.  If this
    // happens then the calling module will be able to pass in arguments to
    // this function through the $args parameter.  Hence we extract these
    // arguments *after* we have obtained any form-based input through
    // pnVarCleanFromInput().
    extract($args);

    // At this stage we check to see if we have been passed $objectid, the
    // generic item identifier.  This could have been passed in by a hook or
    // through some other function calling this as part of a larger module, but
    // if it exists it overrides $tid
    //
    // Note that this module couuld just use $objectid everywhere to avoid all
    // of this munging of variables, but then the resultant code is less
    // descriptive, especially where multiple objects are being used.  The
    // decision of which of these ways to go is up to the module developer
    if (!empty($objectid)) {
        $qid = $objectid;
    }                       

    // Create output object - this object will store all of our output so that
    // we can return it easily when required
	$pnRender =& new pnRender('Quotes');

	// As Admin output changes often, we do not want caching.
	$pnRender->caching = false;

    // The user API function is called.  This takes the item ID which we
    // obtained from the input and gets us the information on the appropriate
    // item.  If the item does not exist we post an appropriate message and
    // return
    $quote = pnModAPIFunc('Quotes',
                          'user',
                          'get',
                          array('qid' => $qid));
    if ($quote == false) {
        return pnVarPrepHTMLDisplay(_QUOTESNOSUCHITEM);
    }

    // Security check - important to do this as early as possible to avoid
    // potential security holes or just too much wasted processing.  However,
    // in this case we had to wait until we could obtain the item name to
    // complete the instance information so this is the first chance we get to
    // do the check
    if (!pnSecAuthAction(0, 'Quotes::', "$quote[author]::$qid", ACCESS_EDIT)) {
        return pnVarPrepHTMLDisplay(_MODULENOAUTH);
    }

    // Add a hidden variable for the item id.  This needs to be passed on to
    // the update function so that it knows which item for which item to carry
    // out the update
    $pnRender->assign('qid', $qid);

    // Quote Text
    $pnRender->assign('quotetext', $quote['quote']);

	// Quote Author
    $pnRender->assign('quoteauthor', $quote['author']);

    // Return the output that has been generated by this function
    return $pnRender->fetch('quotes_admin_modify.htm');
}

/**
 * Update quote
 *
 * Takes info from edit form and passes to API
 * @author Erik Slooff
 * @param 'qid' Quote id to delete
 * @param 'qauther' Author of quote to delete
 * @param 'confirm' Delete confirmation
 * @return mixed HTML string if confirm is null, true otherwise
 */
function quotes_admin_update($args)
{
    // Get parameters from whatever input we need.  All arguments to this
    // function should be obtained from pnVarCleanFromInput(), getting them
    // from other places such as the environment is not allowed, as that makes
    // assumptions that will not hold in future versions of PostNuke
    list($qid,
         $objectid,
         $qquote,
         $qauthor) = pnVarCleanFromInput('qid',
                                         'objectid',
                                         'qquote',
                                         'qauthor');

    // User functions of this type can be called by other modules.  If this
    // happens then the calling module will be able to pass in arguments to
    // this function through the $args parameter.  Hence we extract these
    // arguments *after* we have obtained any form-based input through
    // pnVarCleanFromInput().
    extract($args);

    // At this stage we check to see if we have been passed $objectid, the
    // generic item identifier.  This could have been passed in by a hook or
    // through some other function calling this as part of a larger module, but
    // if it exists it overrides $tid
    //
    // Note that this module couuld just use $objectid everywhere to avoid all
    // of this munging of variables, but then the resultant code is less
    // descriptive, especially where multiple objects are being used.  The
    // decision of which of these ways to go is up to the module developer
    if (!empty($objectid)) {
        $qid = $objectid;
    }                       

    // Confirm authorisation code.  This checks that the form had a valid
    // authorisation code attached to it.  If it did not then the function will
    // proceed no further as it is possible that this is an attempt at sending
    // in false data to the system
    if (!pnSecConfirmAuthKey()) {
        pnSessionSetVar('errormsg', _BADAUTHKEY);
        pnRedirect(pnModURL('Quotes', 'admin', 'view'));
        return true;
    }

    // Notable by its absence there is no security check here.  This is because
    // the security check is carried out within the API function and as such we
    // do not duplicate the work here

    // The API function is called.  Note that the name of the API function and
    // the name of this function are identical, this helps a lot when
    // programming more complex modules.  The arguments to the function are
    // passed in as their own arguments array.
    //
    // The return value of the function is checked here, and if the function
    // suceeded then an appropriate message is posted.  Note that if the
    // function did not succeed then the API function should have already
    // posted a failure message so no action is required
    if(pnModAPIFunc('Quotes',
                    'admin',
                    'update',
                    array('qid' => $qid,
                          'qquote' => $qquote,
                          'qauthor' => $qauthor))) {
        // Success
        pnSessionSetVar('statusmsg', _QUOTESUPDATED);
    }

    // This function generated no output, and so now it is complete we redirect
    // the user to an appropriate page for them to carry on their work
    pnRedirect(pnModURL('Quotes', 'admin', 'view'));

    // Return
    return true;

}

/**
 * Delete selected quote
 * @author Erik Slooff
 * @param 'qid' Quote id to delete
 * @param 'qauther' Author of quote to delete
 * @param 'confirm' Delete confirmation
 * @return mixed HTML string if confirm is null, true otherwise
 */
function quotes_admin_delete($args)
{
    // Get parameters from whatever input we need.  All arguments to this
    // function should be obtained from pnVarCleanFromInput(), getting them
    // from other places such as the environment is not allowed, as that makes
    // assumptions that will not hold in future versions of PostNuke
    list($qid,
         $objectid,
         $confirmation) = pnVarCleanFromInput('qid',
                                              'objectid',
                                              'confirmation');

    // User functions of this type can be called by other modules.  If this
    // happens then the calling module will be able to pass in arguments to
    // this function through the $args parameter.  Hence we extract these
    // arguments *after* we have obtained any form-based input through
    // pnVarCleanFromInput().
    extract($args);

     // At this stage we check to see if we have been passed $objectid, the
     // generic item identifier.  This could have been passed in by a hook or
     // through some other function calling this as part of a larger module, but
     // if it exists it overrides $tid
     //
     // Note that this module couuld just use $objectid everywhere to avoid all
     // of this munging of variables, but then the resultant code is less
     // descriptive, especially where multiple objects are being used.  The
     // decision of which of these ways to go is up to the module developer
     if (!empty($objectid)) {
         $qid = $objectid;
     }                     

    // The user API function is called.  This takes the item ID which we
    // obtained from the input and gets us the information on the appropriate
    // item.  If the item does not exist we post an appropriate message and
    // return
    $item = pnModAPIFunc('Quotes',
                         'user',
                         'get',
                         array('qid' => $qid));

    if ($item == false) {
        return pnVarPrepHTMLDisplay(_QUOTESNOSUCHITEM);
    }

    // Security check - important to do this as early as possible to avoid
    // potential security holes or just too much wasted processing.  However,
    // in this case we had to wait until we could obtain the item name to
    // complete the instance information so this is the first chance we get to
    // do the check
    if (!pnSecAuthAction(0, 'Quotes::', "$item[author]::$qid", ACCESS_DELETE)) {
        return pnVarPrepHTMLDisplay(_MODULENOAUTH);
    }

    // Check for confirmation. 
    if (empty($confirmation)) {
        // No confirmation yet - display a suitable form to obtain confirmation
        // of this action from the user

        // Create output object - this object will store all of our output so that
        // we can return it easily when required
    	$pnRender =& new pnRender('Quotes');

	    // As Admin output changes often, we do not want caching.
    	$pnRender->caching = false;

		// Quote id
        $pnRender->assign('qid', $qid);

        // Return the output that has been generated by this function
        return $pnRender->fetch('quotes_admin_delete.htm');
    }

    // If we get here it means that the user has confirmed the action

    // Confirm authorisation code.  This checks that the form had a valid
    // authorisation code attached to it.  If it did not then the function will
    // proceed no further as it is possible that this is an attempt at sending
    // in false data to the system
    if (!pnSecConfirmAuthKey()) {
        pnSessionSetVar('errormsg', _BADAUTHKEY);
        pnRedirect(pnModURL('Quotes', 'admin', 'qotddisplay'));
        return true;
    }

    // The API function is called.  Note that the name of the API function and
    // the name of this function are identical, this helps a lot when
    // programming more complex modules.  The arguments to the function are
    // passed in as their own arguments array.
    //
    // The return value of the function is checked here, and if the function
    // suceeded then an appropriate message is posted.  Note that if the
    // function did not succeed then the API function should have already
    // posted a failure message so no action is required
    if (pnModAPIFunc('Quotes',
                     'admin',
                     'delete', array('qid' => $qid))) {
        pnSessionSetVar('statusmsg', _QUOTESDELETED);
    }

    // This function generated no output, and so now it is complete we redirect
    // the user to an appropriate page for them to carry on their work
    pnRedirect(pnModURL('Quotes', 'admin', 'view'));

    // Return
    return true;
}

/**
 * Search quote database by keyword - unfinished obviously.
 * @author Mark West
 * @return string HTML string
 */
function Quotes_admin_modifyconfig()
{
    // Security check - important to do this as early as possible to avoid
    // potential security holes or just too much wasted processing
    if (!pnSecAuthAction(0, 'Quotes::', '::', ACCESS_ADMIN)) {
        return pnVarPrepHTMLDisplay(_MODULENOAUTH);
    }

    // Create output object - this object will store all of our output so that
    // we can return it easily when required
	$pnRender =& new pnRender('Quotes');

	// As Admin output changes often, we do not want caching.
	$pnRender->caching = false;

    // Number of items to display per page
    $pnRender->assign(pnModGetVar('Quotes'));

    // Return the output that has been generated by this function
    return $pnRender->fetch('quotes_admin_modifyconfig.htm');
}

/**
 * Update Quotes Config
 * @author Mark West
 * @return string HTML string
 */
function Quotes_admin_updateconfig()
{
    // Security check - important to do this as early as possible to avoid
    // potential security holes or just too much wasted processing
    if (!pnSecAuthAction(0, 'Quotes::', '::', ACCESS_ADMIN)) {
        return pnVarPrepHTMLDisplay(_MODULENOAUTH);
    }

    // Confirm authorisation code.  This checks that the form had a valid
    // authorisation code attached to it.  If it did not then the function will
    // proceed no further as it is possible that this is an attempt at sending
    // in false data to the system
    if (!pnSecConfirmAuthKey()) {
        pnSessionSetVar('errormsg', _BADAUTHKEY);
        pnRedirect(pnModURL('Quotes', 'admin', 'view'));
        return true;
    }

    // Get parameters from whatever input we need.  All arguments to this
    // function should be obtained from pnVarCleanFromInput(), getting them
    // from other places such as the environment is not allowed, as that makes
    // assumptions that will not hold in future versions of PostNuke
    $itemsperpage = pnVarCleanFromInput('itemsperpage');

    // Update module variables.  Note that depending on the HTML structure used
    // to obtain the information from the user it is possible that the values
    // might be unset, so it is important to check them all and assign them
    // default values if required
    if (!isset($itemsperpage)) {
        $itemsperpage = 10;
    }
    pnModSetVar('Quotes', 'itemsperpage', $itemsperpage);

    // Let any other modules know that the modules configuration has been updated
    pnModCallHooks('module','updateconfig','Quotes', array('module' => 'Quotes'));

	// the module configuration has been updated successfuly
	pnSessionSetVar('statusmsg', _CONFIGUPDATED);

    // This function generated no output, and so now it is complete we redirect
    // the user to an appropriate page for them to carry on their work
    pnRedirect(pnModURL('Quotes', 'admin', 'view'));

    // Return
    return true;
}

/**
 * Search quote database by keyword - unfinished obviously.
 * @author Erik Slooff
 * @param 'keyword' keyword to search by
 * @return string HTML string
 */
function quotes_admin_search()
{
    // Security check
    if(!(pnSecAuthAction(0, 'Quotes::', '::', ACCESS_EDIT))) {
        return pnVarPrepHTMLDisplay(_MODULENOAUTH);
    }

    // Get parameters from whatever input we need.  All arguments to this
    // function should be obtained from pnVarCleanFromInput(), getting them
    // from other places such as the environment is not allowed, as that makes
    // assumptions that will not hold in future versions of PostNuke
    $itemsperpage = pnVarCleanFromInput('itemsperpage');


    // Get parameters from whatever input we need.  All arguments to this
    // function should be obtained from pnVarCleanFromInput(), getting them
    // from other places such as the environment is not allowed, as that makes
    // assumptions that will not hold in future versions of PostNuke
    $keyword = pnVarCleanFromInput('keyword');

    // Security check - important to do this as early as possible to avoid
    // potential security holes or just too much wasted processing
    if (!pnSecConfirmAuthKey()) {
        pnSessionSetVar('errormsg', _BADAUTHKEY);
        pnRedirect(pnModURL('Quotes', 'admin', 'main'));
        return true;
    }

	// call the API function
    $quotes = pnModAPIFunc('Quotes', 'admin', 'search', array('keyword' => $keyword));

    if($quotes == false) {
    	return pnVarPrepHTMLDisplay(_QUOTESNOQUOTES);
    }

    // Create output object - this object will store all of our output so that
    // we can return it easily when required
	$pnRender =& new pnRender('Quotes');

	// As Admin output changes often, we do not want caching.
	$pnRender->caching = false;

	$quotesresults = array();
    foreach($quotes as $quote) {
     	$actions = array();
	    if(pnSecAuthAction(0, 'Quotes::', "$quote[author]::$quote[qid]", ACCESS_EDIT)) {
	        $actions[] = array('url' => pnModURL('Quotes', 'admin', 'edit', array('qid' => $quote['qid'])),
			                   'title' => _QUOTESEDITACTION);
	    }
	    if(pnSecAuthAction(0, 'Quotes::', "$quote[author]::$quote[qid]", ACCESS_DELETE)) {
	        $actions[] = array('url' => pnModURL('Quotes', 'admin', 'delete', array('qid' => $quote['qid'])),
			                   'title' => _QUOTESDELETEACTION);
	    }

        $quoteresults[] =  array('quotetext' => $quote['quote'],
	                             'quoteauthor' => $quote['author'],
				                 'options' => $actions);
    }
    $pnRender->assign('quotes', $quoteresults);
	
    return $pnRender->fetch('quotes_admin_search.htm');
}

?>