<?php
// $Id: pnadmin.php,v 1.33.2.1 2006/01/12 12:20:17 markwest Exp $
// ----------------------------------------------------------------------
// PostNuke Content Management System
// Copyright (C) 2002 by the PostNuke Development Team.
// http://www.postnuke.com/
// ----------------------------------------------------------------------
// Based on:
// PHP-NUKE Web Portal System - http://phpnuke.org/
// Thatware - http://thatware.org/
// ----------------------------------------------------------------------
// 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: Mark West
// Purpose of file:  Admin Messages administration display functions
// ----------------------------------------------------------------------

/**
 * @package PostNuke_System_Modules
 * @subpackage Admin_Messages
 * @license http://www.gnu.org/copyleft/gpl.html
*/
/**
 * the main administration function
 * This function is the default function, and is called whenever the
 * module is initiated without defining arguments.  As such it can
 * be used for a number of things, but most commonly it either just
 * shows the module menu and returns or calls whatever the module
 * designer feels should be the default function (often this is the
 * view() function)
 * @author Mark West
 * @return string HTML output string
 */
function Admin_Messages_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, 'Admin_Messages::', '::', 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('Admin_Messages');

	// 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('admin_messages_admin_main.htm');
}

/**
 * add a new admin message
 * This is a standard function that is called whenever an administrator
 * wishes to create a new module item
 * @author Mark West
 * @return string HTML output string
 */
function Admin_Messages_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, 'Admin_Messages::', '::', 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('Admin_Messages');

	// 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('admin_messages_admin_new.htm');
}

/**
 * This is a standard function that is called with the results of the
 * form supplied by Admin_Messages_admin_new() to create a new item
 * @author Mark West
 * @see Admin_Messages_admin_new()
 * @param string $args['title'] the title of the admin message
 * @param string $args['content'] the text of the admin message
 * @param string $args['language'] the language of the admin message
 * @param int $args['active'] active status of the admin message
 * @param int $args['expire'] the expiry date of the message
 * @param int $args['whocanview'] who can view the message
 * @return bool true if creation successful, false otherwiise
 */
function Admin_Messages_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($title,
         $content,
         $language,
         $active,
         $expire,
         $whocanview) = pnVarCleanFromInput('title',
                                            'content',
			                                'language',
                                            'active',
                                            'expire',
                                            'whocanview');

    // 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('Admin_Messages', '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
    $mid = pnModAPIFunc('Admin_Messages',
                        'admin',
                        'create',
                        array('title' => $title,
                              'content' => $content,
			                  'language' => $language,
			                  'active' => $active,
			                  'expire' => $expire,
			                  'whocanview' => $whocanview));

    // 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 ($mid != false) {
        // Success
        pnSessionSetVar('statusmsg', _ADMINMESSAGESCREATED);
    }

    // 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('Admin_Messages', 'admin', 'view'));

    // Return
    return true;
}

/**
 * modify an Admin Message
 * This is a standard function that is called whenever an administrator
 * wishes to modify a current module item
 * @author Mark West
 * @param int $args['mid'] the id of the admin message to modify
 * @param int $args['objectid'] generic object id maps to mid if present
 * @return string HTML output string
 */
function Admin_Messages_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($mid,
         $objectid)= pnVarCleanFromInput('mid',
                                         '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 $objecmid, 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 $mid
    //
    // Note that this module couuld just use $objecmid 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($objecmid)) {
        $mid = $objecmid;
    }                       

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

	// 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
    $item = pnModAPIFunc('Admin_Messages',
                         'user',
                         'get',
                         array('mid' => $mid));

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

    // 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, 'Admin_Messages::item', "$item[title]::$mid", ACCESS_EDIT)) {
        return pnVarPrepHTMLDisplay(_MODULENOAUTH);
    }

	// Assign the item
	$pnRender->assign($item);

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


/**
 * This is a standard function that is called with the results of the
 * form supplied by Admin_Messages_admin_modify() to update a current item
 * @author Mark West
 * @see Admin_Messages_admin_modify()
 * @param int $args['mid'] the id of the admin message to update
 * @param int $args['objectid'] generic object id maps to mid if present
 * @param string $args['title'] the title of the admin message
 * @param string $args['content'] the text of the admin message
 * @param string $args['language'] the language of the admin message
 * @param int $args['active'] active status of the admin message
 * @param int $args['expire'] the expiry date of the message
 * @param int $args['whocanview'] who can view the message
 * @return bool true if successful, false otherwise
 */
function Admin_Messages_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($mid,
	     $objectid,
         $title,
         $content,
         $language,
         $active,
         $expire,
         $oldtime,
         $changestartday,
         $whocanview) = pnVarCleanFromInput('mid',
		                                    'objectid',
                                            'title',
                                            'content',
                                            'language',
                                            'active',
                                            'expire',
                                            'oldtime',
                                            'changestartday',
                                            'whocanview');

    // 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 $mid
    //
    // 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)) {
        $mid = $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('Admin_Messages', '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('Admin_Messages',
                    'admin',
                    'update',
                    array('mid' => $mid,
                          'title' => $title,
                          'content' => $content,
                          'language' => $language,
                          'active' => $active,
                          'expire' => $expire,
                          'oldtime' => $oldtime,
                          'changestartday' => $changestartday,
                          'whocanview' => $whocanview))) {
        // Success
        pnSessionSetVar('statusmsg', _ADMINMESSAGESUPDATED);
    }

    // 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('Admin_Messages', 'admin', 'view'));

    // Return
    return true;
}

/**
 * delete item
 * This is a standard function that is called whenever an administrator
 * wishes to delete a current module item.  Note that this function is
 * the equivalent of both of the modify() and update() functions above as
 * it both creates a form and processes its output.  This is fine for
 * simpler functions, but for more complex operations such as creation and
 * modification it is generally easier to separate them into separate
 * functions.  There is no requirement in the PostNuke MDG to do one or the
 * other, so either or both can be used as seen appropriate by the module
 * developer
 * @author Mark West
 * @param int $args['mid'] the id of the admin message to delete
 * @param int $args['objectid'] generic object id maps to mid if present
 * @param bool $args['confirmation'] confirmation of the deletion
 * @return mixed HTML output string if no confirmation, true if succesful, false otherwise
 */
function Admin_Messages_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($mid,
         $objectid,
         $confirmation) = pnVarCleanFromInput('mid',
                                              '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 $objecmid, 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 $mid
     //
     // Note that this module couuld just use $objecmid 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)) {
         $mid = $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('Admin_Messages',
                         'user',
                         'get',
                         array('mid' => $mid));

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

    // 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, 'Admin_Messages::', "$item[title]::$mid", 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('Admin_Messages');

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

        // Add the message id
		$pnRender->assign('mid', $mid);

        // Return the output that has been generated by this function
        return $pnRender->fetch('admin_messages_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('Admin_Messages', 'admin', 'view'));
        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('Admin_Messages',
                     'admin',
                     'delete',
                     array('mid' => $mid))) {
        // Success
        pnSessionSetVar('statusmsg', _ADMINMESSAGESDELETED);
    }

    // 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('Admin_Messages', 'admin', 'view'));
    
    // Return
    return true;
}

/**
 * view items
 * @author Mark West
 * @param int $startnum the start item id for the pager
 * @return string HTML output string
 */
function Admin_Messages_admin_view()
{
    // Security check - important to do this as early as possible to avoid
    // potential security holes or just too much wasted processing
    if (!pnSecAuthAction(0, 'Admin_Messages::', '::', 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('Admin_Messages');

	// 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.
    $items = pnModAPIFunc('Admin_Messages',
                          'user',
                          'getall',
                          array('startnum' => $startnum,
                                'numitems' => pnModGetVar('Admin_Messages',
                                                          'itemsperpage')));

    $rows = array();
    foreach ($items as $item) {

        if (pnSecAuthAction(0, 'Admin_Messages::', "$item[title]::$item[mid]", ACCESS_READ)) {

            $fullitem = pnModAPIFunc('Admin_Messages',
                                     'user',
                                     'get',
                                      array('mid' => $item['mid']));
    
            if ($fullitem['language'] == '') {
                $fullitem['language'] = _ALL;
            }

            $row[] = $fullitem['language'];

            switch ($fullitem['whocanview']) {
                case '1':
                    $fullitem['whocanview'] = _ADMINMESSAGESALL;
                    break;
                case '2':
                    $fullitem['whocanview'] = _ADMINMESSAGESUSERS;
                    break;
                case '3':
                    $fullitem['whocanview'] = _ADMINMESSAGESANON;
                    break;
                case '4':
                    $fullitem['whocanview'] = _ADMINMESSAGESADMIN;
                    break;
            }
            $row[] = $fullitem['whocanview'];
			
			if ($fullitem['active'] == 1) {
                $active = _YES;
			} else {
			    $active = _NO;
			}

            if ($fullitem['expire'] == 0) {
			    $expire = _ADMINMESSAGESUNLIMITED;
			} else if ($fullitem['expire']/86400 == 1) {
                $expire = $fullitem['expire']/86400 . ' ' . _ADMINMESSAGESDAY;
			} else {
                $expire = $fullitem['expire']/86400 . ' ' . _ADMINMESSAGESDAYS;
            }

            if ($fullitem['expire'] == 0) {
			    $expiredate = _ADMINMESSAGESNOEXPIRE;
			} else {
                $expiredate = ml_ftime(_DATETIMEBRIEF, $fullitem['date'] + $fullitem['expire']);
			}

            // 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, 'Admin_Messages::', "$item[title]::$item[mid]", ACCESS_EDIT)) {
                $options[] = array('url' => pnModURL('Admin_Messages', 'admin', 'modify', array('mid' => $item['mid'])),
                                   'text' => _EDIT);
                if (pnSecAuthAction(0, 'Admin_Messages::', "$item[title]::$item[mid]", ACCESS_DELETE)) {
                    $options[] = array('url' => pnModURL('Admin_Messages', 'admin', 'delete', array('mid' => $item['mid'])),
                                       'text' => _DELETE);
                }
            }
			$rows[] = array( 'mid' => $item['mid'],
			                 'title' => $item['title'],
							 'language' => $fullitem['language'],
							 'whocanview' => $fullitem['whocanview'],
							 'active' => $active,
							 'expire' => $expire,
							 'expiredate' => $expiredate,
							 'options' => $options);

        }
    }
    $pnRender->assign('items', $rows);

    // 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('Admin_Messages', 'user', 'countitems'),
	                                 'itemsperpage' => pnModGetVar('Admin_Messages', 'itemsperpage')));

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


/**
 * This is a standard function to modify the configuration parameters of the
 * module
 * @author Mark West
 * @return string HTML output string
 */
function Admin_Messages_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, 'Admin_Messages::', '::', 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('Admin_Messages');

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

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

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

/**
 * This is a standard function to update the configuration parameters of the
 * module given the information passed back by the modification form
 * @author Mark West
 * @see Admin_Messages_admin_modifyconfig()
 * @param int $itemsperpage the number messages per page in the admin panel
 * @return bool true if successful, false otherwise
 */
function Admin_Messages_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, 'Admin_Messages::', '::', ACCESS_ADMIN)) {
        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');

    // 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('Admin_Messages', 'admin', 'view'));
        return true;
    }

    // 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 (empty($itemsperpage)) {
        $itemsperpage = 10;
    }
    pnModSetVar('Admin_Messages', 'itemsperpage', $itemsperpage);

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

	// 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('Admin_Messages', 'admin', 'view'));

    // Return
    return true;
}

?>