<?php
#-------------------------------------------------------------------------
# Module: Newsletter Made Simple
#        (c) to 2008 by Paul Lempkepf
#        (c) 2008 and on by Robert Campbell (calguy1000@cmsmadesimple.org)
#
#  An addon module for CMS Made Simple to provide a flexible
#  mailing list solution.
#
#-------------------------------------------------------------------------
# CMSMS - CMS Made Simple is (c) 2005 by Ted Kulp (wishy@cmsmadesimple.org)
# Visit the CMSMS Homepage at: http://www.cmsmadesimple.org
#
#-------------------------------------------------------------------------
#
# 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.
#
# However, as a special exception to the GPL, this software is distributed
# as an addon module to CMS Made Simple.  You may not use this software
# in any Non GPL version of CMS Made simple, or in any version of CMS
# Made simple that does not indicate clearly and obviously in its admin
# section that the site was built with CMS Made simple.
#
# 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.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Or read it online: http://www.gnu.org/licenses/licenses.html#GPL
#
#-------------------------------------------------------------------------
#END_LICENSE
if( !isset($gCms) ) exit;
if (!$this->CheckPermission('Manage NMS Users')) return;

$this->SetCurrentTab('users');

if( isset($params['cancel']) ) {
  $this->RedirectToTab($id);
  return;
}

$editing = (isset($params['userid']) && $params['userid'] != '' );
$userinfo = array('userid'=>'',
		  'uniqueid'=>'',
		  'email'=>'',
		  'username'=>'',
		  'disabled'=>0,
		  'confirmed'=>1,
		  'htmlemail'=>1,
		  'error_count'=>0,
		  'bounce_count'=>0,
		  'dateadded'=>null,
		  'dateconfirmed'=>null,
		  'fields'=>array());
$memberlists = array();

$fielddefs = nms_fielddef::load_all();

if( $editing ) {
  // make sure we have enough params
  if( !isset( $params['uniqueid'] ) ) {
    $this->SetError($this->Lang('error_invalidparams'));
    $this->RedirectToTab($id);
    return;
  }

  // find the user
  $query = "SELECT * FROM ".NMS_USERS_TABLE." WHERE uniqueid = ?";
  $userinfo = $db->GetRow($query,array($params['uniqueid']));
  if( !is_array($userinfo) ) {
    $this->SetError($this->Lang('error_usernotfound'));
    $this->RedirectToTab($id);
    return;
  }

  $query = 'SELECT * FROM '.NMS_USER_DATA_TABLE.' WHERE userid = ?';
  $tmp = $db->GetArray($query,array($userinfo['userid']));
  if( is_array($tmp) && count($tmp) ) {
    foreach( $tmp as $row ) {
      $userinfo['fields'][$row['fieldid']] = $row['value'];
    }
  }

  $smarty->assign('formhidden',
		  $this->CreateInputHidden( $id, 'userid', $userinfo['userid'] ).
		  $this->CreateInputHidden( $id, 'uniqueid', $params['uniqueid'] ));

  // and get his lists
  $query = "SELECT listid FROM ".NMS_LISTUSER_TABLE." WHERE userid = ?";
  $memberlists = $db->GetCol($query,array($userinfo['userid']));
}

if( isset($params['submit']) ) {
    try {
        $userinfo['email'] = trim($params['email']);
        $userinfo['username'] = trim($params['username']);
        $userinfo['htmlemail'] = (int)$params['htmlemail'];
        $userinfo['disabled'] = (int)$params['disabled'];
        $userinfo['dateadded'] = trim($db->DbTimeStamp(time()),"'");
        if( $userinfo['confirmed'] == 0 && (int)$params['confirmed'] == 1 ) $userinfo['dateconfirmed'] = trim($db->DbTimeStamp(time()),"'");
        $userinfo['confirmed'] = (int)$params['confirmed'];
        $userinfo['error_count'] = max(0,(int)$params['error_count']);
        $userinfo['bounce_count'] = max(0,(int)$params['bounce_count']);
        if( is_array($fielddefs) && count($fielddefs) ) {
            foreach( $fielddefs as $field ) {
                if( isset($params['fld_'.$field['id']]) ) $userinfo['fields'][$field['id']] = $params['fld_'.$field['id']];
            }
        }

        // now validate the userinfo
        if( $userinfo['email'] == '' || !is_email($userinfo['email']) ) throw new CmsException($this->Lang('error_invalidemail'));
        if( is_array($fielddefs) && count($fielddefs) ) {
            foreach( $fielddefs as $field ) {
                if( $field['required'] && (!isset($userinfo['fields'][$field['id']]) || empty($userinfo['fields'][$field['id']])) ) {
                    throw new CmsException($this->Lang('error_missingrequiredfield',$field['prompt']));
                }
            }
        }

        $userid = null;
        if( $editing ) {
            // existing user
            // validate that the email is not already taken (keeps the list clean).
            $query = 'SELECT userid FROM '.NMS_USERS_TABLE.' WHERE email = ? AND userid != ?';
            $tmp = $db->GetOne($query,array($userinfo['email'],$params['userid']));
            if( $tmp ) throw new CmsException($this->Lang('error_emailexists'));

            // update the record in the db.
            $query = 'UPDATE '.NMS_USERS_TABLE.' SET email = ?, username = ?, disabled = ?,
                confirmed = ?, htmlemail = ?, dateconfirmed = ?, error_count = ?,
                bounce_count = ? WHERE userid = ? AND uniqueid = ?';
            $tmp = $db->Execute($query,array($userinfo['email'],$userinfo['username'],
                                             $userinfo['disabled'],$userinfo['confirmed'],
                                             $userinfo['htmlemail'],$userinfo['dateconfirmed'],
                                             $userinfo['error_count'],$userinfo['bounce_count'],
                                             $params['userid'],$params['uniqueid']));
            if( !$tmp ) throw new CmsException($this->Lang('error_dberror'));

            $query = 'DELETE FROM '.NMS_LISTUSER_TABLE.' WHERE userid = ?';
            $dbr = $db->Execute($query,array($params['userid']));

            $query = 'DELETE FROM '.NMS_USER_DATA_TABLE.' WHERE userid = ?';
            $dbr = $db->Execute($query,array($params['userid']));

            $userid = $params['userid'];
        }
        else {
            // new user
            // validate that the email is not already taken (keeps the list clean).
            $query = 'SELECT userid FROM '.NMS_USERS_TABLE.' WHERE email = ?';
            $tmp = $db->GetOne($query,array($userinfo['email']));
            if( $tmp ) throw new CmsException($this->Lang('error_emailexists'));

            $userinfo['uniqueid'] = md5(uniqid(rand(),1));

            $query = 'INSERT INTO '.NMS_USERS_TABLE.' (uniqueid,email,username,disabled,confirmed,htmlemail,dateadded,dateconfirmed,
                 error_count,bounce_count) VALUES (?,?,?,?,?,?,?,?,?,?)';
            $tmp = $db->Execute($query,
                                array($userinfo['uniqueid'],$userinfo['email'],$userinfo['username'],
                                      $userinfo['disabled'],$userinfo['confirmed'],$userinfo['htmlemail'],
                                      $userinfo['dateadded'],$userinfo['dateconfirmed'],
                                      $userinfo['error_count'],$userinfo['bounce_count']));
            if( !$tmp ) throw new CmsException($this->Lang('error_dberror'));
            $userid = $db->Insert_ID();
        }

        // SendEvent (OnNewUser or OnEditUser)
        $parms = array('email'=>$userinfo['email'],'username'=>$userinfo['username']);
        if( isset($userinfo['lists']) ) $parms['lists'] = $userinfo['lists'];
        if( $editing ) {
            $parms['id'] = $params['userid'];
            $this->SendEvent('OnEditUser',$parms);
        }
        else {
            $this->SendEvent('OnNewUser',$parms);

            // todo: send email (depending on preference)
            if( $this->GetPreference('email_user_on_admin_subscribe') ) {
                $mailer = new \cms_mailer;
                $smarty->assign('user',$user);
                $smarty->assign('lists', $lists );
                $smarty->assign('unsubscribe', $this->_cleanLink($this->CreateLink($id,'unsubscribe',$returnid,$this->Lang('unsubscribe'))));
                $smarty->assign('unsubscribeurl', $this->_cleanLink($this->create_url($id,'unsubscribe',$returnid)));
                $smarty->assign('preferences', $this->_cleanLink($this->CreateLink($id,'preferences',$returnid,$this->Lang('preferences'))));
                $smarty->assign('preferencesurl', $this->_cleanLink($this->create_url($id,'preferences',$returnid)));
                $smarty->assign('confirm', $this->_cleanLink($this->CreateLink($id,'confirm_email',$returnid,$this->Lang('confirm'), array('uniqueid' => $user['uniqueid']) )));
                $smarty->assign('confirmurl',$this->_cleanLink($this->create_url($id,'confirm_email',$returnid,array('uniqueid' => $user['uniqueid']))));

                $mailer->reset();
                $mailer->AddAddress($user['email']);
                $mailer->SetCharSet($this->GetPreference('message_charset'));
                $mailer->SetFromName($this->GetPreference('admin_name'));
                $mailer->SetFrom($this->GetPreference('admin_email'));
                $mailer->IsHTML((int)$this->GetPreference('subscribe_email_html',1));
                $mailer->SetSubject($this->GetPreference('subscribe_subject',$this->Lang('default_subscribe_subject')));
                $mailer->SetBody($this->ProcessTemplateFromDatabase('subscribe_email_body'));
                if( !$mailer->Send() ) {
                    audit('',$this->GetName(),'Problem sending email to '.$userinfo['email']);
                    nms_utils::user_adderror($userinfo['userid']);
                    throw new CmsException($this->Lang('error_send',$userinfo['email'],$mailer->GetErrorInfo()));
                }
            }
        }

        // add him into his lists
        if( isset($params['lists']) && is_array($params['lists']) && count($params['lists']) ) {
            $query = 'INSERT INTO '.NMS_LISTUSER_TABLE." (userid,listid,active,entered) VALUES (?,?,1,NOW())";
            foreach( $params['lists'] as $one ) {
                $dbr = $db->Execute($query,array($userid,$one));
            }
        }

        // add his custom field values.
        if( isset($userinfo['fields']) && is_array($userinfo['fields']) && count($userinfo['fields']) ) {
            $query = 'INSERT INTO '.NMS_USER_DATA_TABLE.' (userid,fieldid,value) VALUES (?,?,?)';
            foreach( $userinfo['fields'] as $fldid => $value ) {
                $dbr = $db->Execute($query,array($userid,$fldid,$value));
            }
        }

        $this->SetMessage($this->Lang('operation_successful'));
        $this->RedirectToTab($id);
    }
    catch( Exception $e ) {
        echo $this->ShowErrors($e->GetMessage());
    }
}

$smarty->assign('memberlists',$memberlists);
$smarty->assign('userinfo',$userinfo);

// query all of the active
$lists = $this->GetListsAsArray(array('active'=>1,'dynamic'=>0));
$smarty->assign('lists',$lists);

if( is_array($fielddefs) && count($fielddefs) ) $smarty->assign('fielddefs',$fielddefs);
$smarty->assign('formstart',$this->CreateFormStart( $id, 'admin_addedit_user', $returnid ) );
$smarty->assign('formend',$this->CreateFormEnd());

echo $this->ProcessTemplate('admin_addedit_user.tpl');

#
# EOF
#
?>