<?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;
$email = get_parameter_value($params,'email');
$username = get_parameter_value($params,'username');

$error = 0;
$message = null;
$result = array();
$temparray = array();
$listarray = $this->GetLists(array('status'=>'public','active'=>1,'dynamic'=>0));

$template = 'nms_subscribeform';
$fielddefs = nms_fielddef::load_all();
$user = nms_utils::get_userinfo(-1);
if( is_array($fielddefs) && count($fielddefs) ) $smarty->assign('fields',$fielddefs);

try {
    if( !is_array($listarray) || count($listarray) == 0 ) throw new CmsException($this->Lang('error_nolists'));

    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',$name));
                    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 the honeypot captcha.
        if( isset($params['_data']) && $params['_data'] !== '' ) throw new Exception($this->Lang('error_invalidcaptcha'));

        // check captcha
        $captcha_mod = cms_utils::get_module('Captcha');
        if( is_object($captcha_mod) && !isset($params['nocaptcha']) ) {
            $captcha = \cge_param::get_string($params,'captcha');
            if( method_exists($captcha_mod,'NeedsInputField') && $captcha_mod->NeedsInputField() && !$captcha ) throw new Exception($this->Lang('error_invalidcaptcha'));
            if( !$captcha_mod->CheckCaptcha($captcha) ) throw new Exception($this->Lang('error_invalidcaptcha'));
        }

        // check for conflict
        $query = 'SELECT uniqueid,userid FROM '.NMS_USERS_TABLE.' WHERE email = ?';
        $tmp = $db->GetRow($query,array($user['email']));
        if( is_array($tmp) && count($tmp) ) {
            $user['userid'] = (int)$tmp['userid'];
            $user['uniqueid'] = $tmp['uniqueid'];
        }

        // insert user
        if( !$user['userid'] ) {
            $user['uniqueid'] = md5(uniqid(rand(),1));
            $query = 'INSERT INTO '.NMS_USERS_TABLE.'
                (uniqueid, email, username, disabled, confirmed, htmlemail, dateadded, dateconfirmed, error_count, bounce_count)
                VALUES (?,?,?,?,?,?,NOW(),?,?,?)';
            $dbr = $db->Execute($query,
                                array($user['uniqueid'],$user['email'],$user['username'],$user['disabled'],$user['confirmed'],
                                      $user['htmlemail'],$user['dateconfirmed'],$user['error_count'],$user['bounce_count']));
            $user['userid'] = $db->Insert_ID();
        }

        // add user fields.
        if( is_array($fielddefs) && count($fielddefs) ) {
            $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 = '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));
        }

        $smarty->assign('user',$user);

        audit($user['userid'],$this->GetName(),'Email address '.$user['email'].' subscribed to '.count($user['lists']).' lists');

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

        // send email
        $mailer = new \cms_mailer;
        $smarty->assign('lists', $listarray );
        $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 '.$user['email']);
            nms_utils::user_adderror($userinfo['userid']);
            throw new CmsException($this->Lang('error_send',$user['email'],$mailer->GetErrorInfo()));
        }
        $mailer->reset();

        // done
        echo $this->GetPreference('subscribe_posttext');
        return;
    }
}
catch( Exception $e ) {
    $smarty->assign('error',1);
    $smarty->assign('message',$e->GetMessage());
}

$inline = cge_utils::to_bool(cge_utils::get_param($params,'inline',0));
if( is_array($listarray) && count($listarray) ) $smarty->assign('lists',$listarray);
$captcha = $this->GetModuleInstance('Captcha');
if( is_object($captcha) && !isset($params['nocaptcha']) ) {
    $smarty->assign('captcha_needs_input',( method_exists($captcha, 'NeedsInputField') && $captcha->NeedsInputField()) );
    $smarty->assign('captcha',$captcha->getCaptcha());
    $smarty->assign('captcha_title',$this->Lang('captcha_title'));
}
$parms = array();
if( isset($params['select']) ) $parms['select'] = $params['select'];
if( isset($params['nocaptcha']) ) $parms['nocaptcha'] = $params['nocaptcha'];
$smarty->assign('formstart',$this->CGCreateFormStart($id,'subscribe',$returnid,$parms,$inline));
$smarty->assign('formend',$this->CreateFormEnd());

// Display the populated template
$smarty->assign('user',$user);
if( $message ) $smarty->assign('message',$message);
echo $this->ProcessTemplateFromDatabase($template);

?>
