<?php
// $Id: pnuser.php,v 1.33.2.1 2005/09/08 19:09:19 landseer 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
// ----------------------------------------------------------------------
/**
 * Messages Module
 *
 * Purpose of file:  user display functions --
 *                   This file contains all user GUI functions for the module
 *
 * @package      PostNuke_Miscellaneous_Modules
 * @subpackage   Messages
 * @version      $Id: pnuser.php,v 1.33.2.1 2005/09/08 19:09:19 landseer Exp $
 * @author       Mark West
 * @author       Richard Tirtadji
 * @link         http://www.postnuke.com  The PostNuke Home Page
 * @copyright    Copyright (C) 2002 by the PostNuke Development Team
 * @license      http://www.gnu.org/copyleft/gpl.html GNU General Public License
 */

/**
 * the main user 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       The PostNuke Development Team
 * @return       output       The main module page
 */
function Messages_user_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 overview
    // privilege for some item within this component, or else they won't be
    // able to see anything and so we refuse access altogether.  The lowest
    // level of access for administration depends on the particular module, but
    // it is generally either 'overview' or 'read'
    if (!pnSecAuthAction(0, 'Messages::', '::', ACCESS_OVERVIEW) || !pnUserLoggedIn()) {
        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();

    // assign the output of the main function
    $pnRender->assign('main', Messages_user_view());

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

/**
 * view items
 *
 * This is a standard function to provide an overview of all of the items
 * available from the module.
 *
 * @author       The PostNuke Development Team
 * @param        integer      $startnum    (optional) The number of the start item
 * @return       output       The overview page
 */
function Messages_user_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, 'Messages::', '::', ACCESS_OVERVIEW) || !pnUserLoggedIn()) {
        return pnVarPrepHTMLDisplay(_MODULENOAUTH);
    }

    $uid = pnUserGetVar('uid');

    // The API function is called.  The arguments to the function are passed in
    // as their own arguments array
    $items = pnModAPIFunc('Messages', 'user', 'getall', array('uid' => $uid));

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

    $pnRender->assign('messagecount', pnModAPIFunc('Messages', 'user', 'countitems', array('uid' => pnUserGetVar('uid'))));

    $messages = array();
    if (is_array($items)) {
        foreach($items as $item) {
            // get a Unix timestamp for this date/time  -- Alarion :: 08/21/2001
            $item['msg_time'] = mktime( substr($item['msg_time'], 11, 2),     // hour
                                        substr($item['msg_time'], 14, 2),     // minute
                                        '0',                                   // second
                                        substr($item['msg_time'], 5, 2),      // month
                                        substr($item['msg_time'], 8, 2),      // day
                                        substr($item['msg_time'], 0, 4));     // year
            $item['posterdata'] = pnUserGetVars($item['from_userid']);
            if($item['from_userid']==1) {
                // anonymous user
                $item['posterdata']['pn_name'] = $item['posterdata']['pn_uname'];
            }
            $item['messagetime'] = ml_ftime(_DATETIMEBRIEF, GetUserTime($item['msg_time']));
            $messages[] = $item;
        }
    }
    $pnRender->assign('messages', $messages);

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

/**
 * display item
 *
 * This is a standard function to provide detailed informtion on a single item
 * available from the module.
 *
 * @author       The PostNuke Development Team
 * @param        integer      $tid     the ID of the item to display
 * @return       output       The item detail page
 */
function Messages_user_display($args)
{
    $msgid = pnVarCleanFromInput('msgid');

    $uid = pnUserGetVar('uid');

    // The API function is called.  The arguments to the function are passed in
    // as their own arguments array
    $item = pnModAPIFunc('Messages', 'user', 'get', array('uid' => $uid, 'msgid' => $msgid));

    // 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 (!$item) {
        return pnVarPrepHTMLDisplay(_MESSAGESNOSUCHMESSAGE);
    }

    // Turn this time string into a UNIX timestamp for use with GetUserTime
    $item['msg_time'] = mktime( substr($item['msg_time'], 11, 2),     // hour
                                substr($item['msg_time'], 14, 2),     // minute
                                '0',                                   // second
                                substr($item['msg_time'], 5, 2),      // month
                                substr($item['msg_time'], 8, 2),      // day
                                substr($item['msg_time'], 0, 4));     // year

    // update the read count
    if ($item['read_msg'] == 0) {
        pnModAPIFunc('Messages', 'user', 'setreadstatus', array('msgid' => $item['msg_id']));
    }

    $pnRender =& new pnRender();
    $pnRender->cache_id = $uid . $msgid;

    if (!is_array($item)) {
        $pnRender->assign('errormsg', _MESSAGESDONTHAVEMESSAGES);
    } else {
        $message = array();
        $item['posterdata'] = pnUserGetVars($item['from_userid']);
        if(substr($item['posterdata']['pn_url'], 0, 4) != 'http')  {
			$item['posterdata']['pn_url'] = "http://" . $item['posterdata']['pn_url'];
        }
        $item['messagetime'] = ml_ftime(_DATETIMEBRIEF, GetUserTime($item['msg_time']));
        // bit of a cheat here .. greg.
        $item['message'] = pnModAPIFunc('Messages', 'user', 'replacesignature',
                                        array('signature' => $item['posterdata']['user_sig'],
                                              'message'   => $item['msg_text']));

    }
    $pnRender->assign('message', $item);
    $pnRender->assign('messagecount', pnModAPIFunc('Messages', 'user', 'countitems', array('uid' => $uid)));
    $pnRender->assign('previous', $msgid-1);
    $pnRender->assign('next', $msgid+1);
    $pnRender->assign('authkey', pnSecGenAuthKey());

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

}

/**
 * delete item
 *
 * @author       The PostNuke Development Team
 * @param        integer      $tid     the ID of the item to display
 * @return       output       The item detail page
 */
function Messages_user_delete($args)
{
    if (!pnSecAuthAction(0, 'Messages::', ".*", ACCESS_COMMENT)) {
        return pnVarPrepHTMLDisplay(_MODULENOAUTH);
    }

    list($msg_id, $total_messages) = pnVarCleanFromInput('msg_id', 'total_messages');

    if (empty($msg_id)) {
        pnSessionSetVar('errormsg', _MESSAGESNOSELECTED);
        pnRedirect(pnModURL('Messages', 'user', 'view'));
        return true;
    }

    $status = false;
    $uid = pnUserGetVar('uid');

    if (is_array($msg_id)) {
        // delete multiple messages for a list
        for ($i = 0; $i < $total_messages; $i++) {
            if (isset($msg_id[$i])) {
                $status = pnModAPIFunc('Messages', 'user', 'delete', array('msgid' => $msg_id[$i], 'uid' => $uid));
                if (!$status) {
                    pnRedirect(pnModURL('Messages', 'user', 'view'));
                    return true;
                }
            }
        }
    } else {
        $status = pnModAPIFunc('Messages', 'user', 'delete', array('msgid' => $msg_id, 'uid' => $uid));
        if (!$status) {
            pnRedirect(pnModURL('Messages', 'user', 'view'));
            return true;
        }
    }
    if ($status) {
        $pnRender =& new pnRender('Messages');
        $pnRender->clear_cache(null, $uid);
        pnSessionSetVar('statusmsg', _MESSAGESDELETED);
        pnRedirect(pnModURL('Messages', 'user', 'view'));
        return true;
    }

}

/**
 * compose a message
 *
 * @author       The PostNuke Development Team
 * @param        integer      $tid     the ID of the item to display
 * @return       output       The item detail page
 */
function Messages_user_compose($args)
{
    list ($reply, $send, $msg_id, $uname) = pnVarCleanFromInput('reply', 'send', 'msg_id', 'uname');

    if (!pnSecAuthAction(0, 'Messages::', $uname . '::', ACCESS_COMMENT)) {
        return pnVarPrepHTMLDisplay(_MODULENOAUTH);
    }

    $pnRender =& new pnRender();
    $pnRender->caching = false;

    if (!empty($reply)) {
        // The API function is called.  The arguments to the function are passed in
        // as their own arguments array
        $item = pnModAPIFunc('Messages', 'user', 'get', array('uid' => pnUserGetVar('uid'), 'msgid' => $msg_id));

        $fromuserdata = pnUserGetVars($item['from_userid']);
        $touserdata = pnUserGetVars($item['to_userid']);
        $user_id = pnUserGetVar('uid');
        if (pnUserLoggedIn() && ($user_id != $touserdata['pn_uid']) ) {
            pnSessionSetVar('errormsg', _MESSAGESNOTSENTTOYOU);
            pnRedirect(pnModURL('Messages', 'user', 'view'));
            return true;
        }
        $pnRender->assign('reply', $reply);
        $pnRender->assign('fromuser', $fromuserdata['pn_uname']);
        $pnRender->assign('subject', $item['subject']);
        if (!empty($uname)) {
            $pnRender->assign('touser', $uname);
        }

        $text = preg_replace('/(<br[ \/]*?>)/i', '', $item['msg_text']);
        $text = pnVarPrepHTMLDisplay($text);
        $text = eregi_replace('\[addsig]', '', $text);

        $row['msg_time'] = mktime( substr($item['msg_time'], 11, 2),     // hour
                                   substr($item['msg_time'], 14, 2),    // minute
                                   '0',                                // second
                                   substr($item['msg_time'], 5, 2),     // month
                                   substr($item['msg_time'], 8, 2),     // day
                                   substr($item['msg_time'], 0, 4));    // year
        $reply = "[quote=$fromuserdata[uname] "._MESSAGESWROTE.' '._ON.' '. ml_ftime(_DATETIMEBRIEF, GetUserTime($row['msg_time'])) .":]\n$text\n[/quote]";


    } else {
    	$reply = false;
    }
	$pnRender->assign('reply', $reply);
    if (pnModAvailable('pn_bbsmile') && pnModIsHooked('pn_bbsmile', 'Messages')){
        $icons = pnModAPIFunc('pn_bbsmile', 'user', 'getall');
        $pnRender->assign('icons', $icons);
    } else {
    $pnRender->assign('icons', false);
    }

    if (pnModAvailable('pn_bbcode') && pnModIsHooked('pn_bbcode', 'Messages')){
    	$pnRender->assign('bbcode', true);
  	} else {
  		$pnRender->assign('bbcode', false);
  	}
    // assign the username if both present and valid
    if (!empty($uname)) {
        // we call the API to check if the uname is valid
        $uid = pnUserGetIDFromName($uname);
        if (isset($uid)) {
            $pnRender->assign('touser', $uname);
        }
    }

    if(empty($msg_id)) {
        $msg_id = '';
    }
    $pnRender->assign('msgid', $msg_id);

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

}

/**
 * submit a message
 *
 * @author       The PostNuke Development Team
 * @param        integer      $tid     the ID of the item to display
 * @return       output       The item detail page
 */
function Messages_user_submit($args)
{
    if (!pnSecConfirmAuthKey()) {
        return pnVarPrepHTMLDisplay(_BADAUTHKEY);
    }

    list($image,
         $subject,
         $to_user,
         $message) = pnVarCleanFromInput('image',
                                         'subject',
                                         'to_user',
                                         'message');
    if (!pnSecAuthAction(0, 'Messages::', $to_user . '::', ACCESS_COMMENT)) {
        return pnVarPrepHTMLDisplay(_MODULENOAUTH);
    }

    if(empty($message)) {
        pnSessionSetVar('errormsg', _MODARGSERROR);
        pnRedirect(pnModURL('Messages', 'user', 'view'));
        return true;
    }

    if(empty($subject)) {
        $subject = _MESSAGESNOSUBJECT;
    }

    $message = nl2br($message);
    if(pnUserLoggedin()) {
        $message .= "[addsig]";
    }

    // get the user id
    $to_userid = pnUserGetIDFromName($to_user);

    if (!$to_userid) {
        pnSessionSetVar('errormsg', _MESSAGESUSERNOTINDB . ', ' . _MESSAGESCHECKNAMEANDTRY);
    } else {
        if (pnModAPIFunc('Messages', 'user', 'create',
                         array('image' => $image, 'subject' => $subject, 'to_userid' => $to_userid, 'message' => $message))) {
            $pnRender =& new pnRender('Messages');
            $pnRender->clear_cache(null, $to_userid);
            pnSessionSetVar('statusmsg', _MESSAGESPOSTED);
        } else {
            pnSessionSetVar('errormsg', _CREATEFAILED);
        }
    }
    pnRedirect((pnUserLoggedIn()) ? pnModURL('Messages', 'user', 'view') : 'index.php');
    return true;

}

?>