<?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( !isset( $params['uniqueid'] ) ) {
  $this->_DisplayErrorPage( $id, $params, $returnid, $this->Lang('error_insufficientparams'));
  return;
}

$fielddefs = nms_fielddef::load_all();
$lists = $this->GetLists(array('status'=>'public','dynamic'=>0,'active'=>1));
$user = null;

try {
  $uniqueid = trim(get_parameter_value($params,'uniqueid'));
  if( !$uniqueid ) throw new CmsException($this->Lang('error_insufficientparams'));
  $user = nms_utils::get_userinfo(array('uniqueid'=>$uniqueid));
  if( $user['userid'] < 1 ) throw new CmsException($this->Lang('error_usernotfound'));

  if( isset($params['nms_submit']) ) {
    $nparams = array();
    foreach( $params as $key => $value ) {
      if( startswith($key,'nms_') ) $key = substr($key,4);
      $nparams[$key] = $value;
    }
    $params = $nparams;
    unset($nparams);

    $user['email'] = trim(get_parameter_value($params,'email'));
    $user['username'] = trim(get_parameter_value($params,'username'));
    $user['confirmed'] = ($this->GetPreference('require_confirmation',1))?0:1;
    if( $user['confirmed'] ) $user['dateconfirmed'] = trim($db->DbTimeStamp(time()),'"');
    $user['lists'] = get_parameter_value($params,'lists');
    $user['fields'] = array();
    foreach( $params as $key => $value ) {
      if( startswith($key,'field_') ) {
	$key = substr($key,strlen('field_'));
	$user['fields'][$key] = $value;
      }
    }

    // validate fields.
    if( is_array($fielddefs) && count($fielddefs) ) {
      foreach( $fielddefs as $name => $obj ) {
	$key = 'field_'.$obj['id'];
	if( !isset($params[$key]) || $params[$key] === '' ) {
	  // oops, missing required field.
	  if( !$obj['required'] )	throw new Exception($this->Lang('error_missingrequiredfield'));
	  continue;
	}
	$user['fields'][$obj['name']] = $params[$key];
      }
    }

    // validate
    if( !$this->_isValidEmail($user['email'], $this->GetPreference('check_dns_subscribe')) ) {
      throw new Exception($this->Lang('error_invalidemail'));
    }
    if( !is_array($user['lists']) || count($user['lists']) == 0) throw new Exception($this->Lang('error_selectonelist'));

    // check for conflict
    $query = 'SELECT userid FROM '.NMS_USERS_TABLE.' WHERE email = ? AND uniqueid != ?';
    $tmp = $db->GetOne($query,array($user['email'],$user['uniqueid']));
    if( $tmp ) throw new CmsException($this->Lang('error_emailexists'));

    // update user
    $query = 'UPDATE '.NMS_USERS_TABLE.' SET email = ?, username = ? WHERE userid = ? AND uniqueid = ?';
    $dbr = $db->Execute($query,array($user['email'],$user['username'],$user['userid'],$user['uniqueid']));

    if( is_array($fielddefs) && count($fielddefs) ) {
      $query = 'DELETE FROM '.NMS_USER_DATA_TABLE.' WHERE userid = ?';
      $db->Execute($query,array($user['userid']));

      $query = 'INSERT INTO '.NMS_USER_DATA_TABLE.' (userid,fieldid,value) VALUES (?,?,?)';
      foreach( $fielddefs as $name => $obj ) {
	if( !isset($user['fields'][$obj['id']]) ) continue;
	$dbr = $db->Execute($query,array( $user['userid'],$obj['id'],$user['fields'][$obj['id']] ));
      }
    }

    // add user to list(s)
    $query = 'DELETE FROM '.NMS_LISTUSER_TABLE.' WHERE userid = ?';
    $dbr = $db->Execute($query,array($user['userid']));

    $query = 'INSERT INTO '.NMS_LISTUSER_TABLE.' (userid, listid, active, entered) VALUES (?,?,1,NOW())';
    foreach( $user['lists'] as $listid ) {
      $dbr = $db->Execute($query,array($user['userid'],$listid));
    }

    audit($user['userid'],$this->GetName(),'User '.$user['uniqueid'].' edited settings.  subscribed to '.count($user['lists']).' lists');

    // send event
    $this->SendEvent('OnEditUser',array('email'=>$user['email'],'username'=>$user['username'],'lists'=>$user['lists']));

    $smarty->assign('username',$user['username'] );
    $smarty->assign('email',$user['email'] );
    echo $this->ProcessTemplateFromDatabase('usersettings_text2');
    return; // all done.
  }
}
catch( Exception $e ) {
  $smarty->assign('error',1);
  $smarty->assign('message',$e->GetMessage());
}

if( is_array($user) ) $smarty->assign('user',$user);
if( is_array($fielddefs) && count($fielddefs) ) $smarty->assign('fields',$fielddefs);
$smarty->assign('lists',$lists);
$smarty->assign('formstart', $this->CGCreateFormStart($id,'usersettings',$returnid,array('uniqueid'=>$params['uniqueid'])));;
$smarty->assign('formend',$this->CreateFormEnd());
echo $this->ProcessTemplateFromDatabase('usersettings_form2');

?>