CHips L MINI SHELL

CHips L pro

Current Path : /opt/cpanel/ea-php54/root/usr/share/pear/RVSeagullMod/modules/newsletter/classes/
Upload File :
Current File : //opt/cpanel/ea-php54/root/usr/share/pear/RVSeagullMod/modules/newsletter/classes/NewsletterMgr.php

<?php
/* Reminder: always indent with 4 spaces (no tabs). */
// +---------------------------------------------------------------------------+
// | Copyright (c) 2005, Rares Benea                                           |
// | All rights reserved.                                                      |
// |                                                                           |
// | Redistribution and use in source and binary forms, with or without        |
// | modification, are permitted provided that the following conditions        |
// | are met:                                                                  |
// |                                                                           |
// | o Redistributions of source code must retain the above copyright          |
// |   notice, this list of conditions and the following disclaimer.           |
// | o Redistributions in binary form must reproduce the above copyright       |
// |   notice, this list of conditions and the following disclaimer in the     |
// |   documentation and/or other materials provided with the distribution.    |
// | o The names of the authors may not be used to endorse or promote          |
// |   products derived from this software without specific prior written      |
// |   permission.                                                             |
// |                                                                           |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR     |
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      |
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,     |
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT          |
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY     |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT       |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE     |
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.      |
// |                                                                           |
// +---------------------------------------------------------------------------+
// | Seagull 0.6                                                               |
// +---------------------------------------------------------------------------+
// | NewsletterMgr.php                                                         |
// +---------------------------------------------------------------------------+
// | Authors:   Benea Rares <rbenea@bluestardesign.ro>                         |
// |            Alexander J. Tarachanowicz <ajt@localhype.net>                 |
// |            Demian Turner <demian@phpkitchen.com>                          |
// +---------------------------------------------------------------------------+
// $Id: NewsletterMgr.php,v 1.24 2005/06/12 18:19:18 demian Exp $

require_once SGL_CORE_DIR . '/Emailer.php';
require_once 'Mail.php';
require_once 'Mail/mime.php';
require_once 'Validate.php';
require_once 'DB/DataObject.php';

/**
 * For distributing 'newsletter' type email to users.
 *
 * @package newsletter
 * @author  Benea Rares <rbenea@bluestardesign.ro>
 * @author  Alexander J. Tarachanowicz II <ajt@localhype.net>
 * @version $Revision: 1.24 $
 */
class NewsletterMgr extends SGL_Manager
{
    function NewsletterMgr()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        parent::SGL_Manager();

        $this->pageTitle        = 'Newsletter';
        $this->template         = 'list.html';

        $this->_aActionsMapping =  array(
            'list'        => array('list'),
            'subscribe'   => array('subscribe'),
            'unsubscribe' => array('unsubscribe'),
            'authorize'   => array('authorize'),
            'subscribeAndUnsubscribe' => array('subscribeAndUnsubscribe'),
        );
    }


    function validate($req, &$input)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);

        $this->validated    = true;
        $input->error       = array();
        $input->pageTitle   = $this->pageTitle;
        $input->masterTemplate = $this->masterTemplate;

        $input->template    = $this->template;

        $input->action      = ($req->get('action')) ? $req->get('action') : 'list';
        //strtolower all action
        $input->action 		= strtolower($input->action);
        $input->submitted   = $req->get('submitted');
        $input->listName    = $req->get('frmListName');
        $input->actionRequest = $req->get('frmRequest');

        $input->complete   = $req->get('complete');

        $input->validNewsList = $this->_getList();
        // แก้ไขให้แสดง check checkbox หน้า Newsletter list subscribe หน้า user
        //ให้แสดงว่า default user นั้น มี subscribe, unsubscribe ไหนบ้าง
        $input->checkListForUser = $this->getListForUser();
        $input->checkSubscribed = $this->checkSubscribed($input->validNewsList, $input->checkListForUser);
        $input->checkuser = $this->checkuser();
        // get email user
        $input->getEmailUser = $this->findEmailUser();

        if (class_exists('RVSGLWrapper')) {
        	$input->isResTemplate = RVSGLWrapper::isResTemplate();
        	if (RVSGLWrapper::isUikitTemplate() && @$_SESSION['rid'] != SGL_ADMIN) {
	        	$input->template = 'uikit_list.html';
        	}
        } else {
        	$input->isResTemplate = false;
        }


        //get admin real name
        $input->adminRealName = 'Admin';
        require_once SGL_MOD_DIR . '/user/classes/UserDAO.php';
        $oUserDao    = UserDAO::singleton();

        $aAdminUserIds = $oUserDao->getUsersByRoleId(SGL_ADMIN);
        if (isset($aAdminUserIds[0])) {
        	$oAdmin = $oUserDao->getUserById($aAdminUserIds[0]);
        	$input->adminRealName = $oAdmin->first_name . ' ' . $oAdmin->last_name;
        }

        $input->userID = isset($_SESSION['uid']) ? $_SESSION['uid'] : 0;
        if ($input->userID != 0) {
            //$input->userID = $req->get('frmUserID');
            $oUser = DB_DataObject::factory($this->conf['table']['user']);
            $oUser->get($input->userID);
            $input->email       = $oUser->email;
            $input->name        = $oUser->first_name . $oUser->last_name;
        } else {
           $input->email       = $req->get('frmEmail');
           $input->name        = $req->get('frmName');
        }

        $aErrors = array();
        switch ($input->action) {
        	case 'list':
        		break;
        	case 'subscribe':
        	case 'unsubscribe':
        		if (empty($input->name)) {
        			$aErrors['name'] = 'Please fill in the name field';
        		}
        		if(empty($input->listName) && empty($input->name) && empty($input->listName)){
        			$aErrors['invalid'] = 'Please enter your name and e-mail address and select the newsletters that you want to subscribe.';
        		}
        		if (!empty($input->listName) && is_array($input->listName) && count($input->listName)) {
        			foreach ($input->listName as $list) {
        				if (!array_key_exists($list,$input->validNewsList)) {
        					$aErrors['listName'] = 'Invalid input supplied to list name';
        					break;
        				}
        			}
        		} else {
        			$aErrors['listName'] = 'Please select at least one newsletter';
        		}
        		break;
        	case 'subscribeAndUnsubscribe':
        		if (empty($input->name)) {
        			$aErrors['name'] = 'Please fill in the name field';
        		}

        		if (!empty($input->email) && $input->email == 'none@none.com') {
        			$aErrors['email'] = '';
        		}

        		if(empty($input->listName) && empty($input->name) && empty($input->listName)){
        			$aErrors['invalid'] = 'Please enter your name and e-mail address and select the newsletters that you want to subscribe.';
        		}


        		if (!empty($input->listName) && is_array($input->listName) && count($input->listName)) {
        			foreach ($input->listName as $list) {
        				if (!array_key_exists($list,$input->validNewsList)) {
        					$aErrors['listName'] = 'Invalid input supplied to list name';
        					break;
        				}
        			}
        		} else {
        			$aErrors['listName'] = 'Please select at least one newsletter';
        		}
        		break;
        	case 'authorize':
        		$input->template = 'authorize.html';
        		$input->actionKey   = $req->get('frmKey');

        		if (empty($input->actionKey)) {
        			$aErrors['actionKey'] = 'Please input a valid authorization key';
        		} elseif (preg_match("([^\w])",$input->actionKey)) {
        			$aErrors['actionKey'] = 'Please input a valid authorization key';
        		}
        		break;
        	default:
        		break;
        }

        if (isset($input->email) && !empty($input->email)) {
        	$v = new Validate();
        	///fix PHP 5.3
        	$v = &$v;
        	if (!$v->email($input->email)) {
        		$aErrors['email'] = 'incorrectly formatted email';
        	}
        }

        if (isset($input->name) && !empty($input->name) && preg_match("([^\w\s])", $input->name)) {
        	$aErrors['name'] = 'Invalid input supplied to list name';
        }

        //  if errors have occured
        if (is_array($aErrors) && count($aErrors)) {
            SGL::raiseMsg('Please fill in the indicated fields');
            $input->error = $aErrors;
            $this->validated = false;
        }


    }

    /**
    * Listd the subscribe/unsubscribe form.
    *
    * @access public
    *
    */
    function _cmd_list(&$input, &$output)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
    }


    /**
    * (used no member)Sends subscribe e-mail and/or adds user data to DB.
    *
    * @access public
    *
    */
    function _cmd_subscribe(&$input, &$output)
    {

        SGL::logMessage(null, PEAR_LOG_DEBUG);
        SGL_DB::setConnection();
        $errorLists = false;

        // Process registration for every list selected
        foreach ($input->listName as $list) {
            $oList = DB_DataObject::factory($this->conf['table']['newsletter']);
            $oList->email = $input->email;

            $oList->list = $input->validNewsList[$list]['name'];
            $noRows = $oList->find(true);

            // Do not subscribe if already subscribed
            if ($noRows != 0) {

                 if ($this->conf['NewsletterMgr']['emailConfirmation']) {
                   $oList->email = $input->email;
                   $oList->action_request = 'subscribe';
                   $oList->action_key = $this->_generateKey($oList->email);
                   $oList->last_updated = SGL_Date::getTime();
                   $oList->list = $input->validNewsList[$list]['name'];
                   $success = $oList->update();
                       if ($success) {
                           if ($this->conf['NewsletterMgr']['emailConfirmation']) {
                               // Send email confirmation
                               $output->emailSiteName = ($this->conf['site']['name']) ? $this->conf['site']['name'] : $input->adminRealName;
                               $output->emailSubject = SGL_String::translate('Action confirmation for newsletter').' '.$input->validNewsList[$list]['name'];
                               $output->emailAction = SGL_String::translate('subscribe');
                               $output->emailName = $input->name ? $input->name : 'User';
                               $output->emailAddress = $input->email;
                               $output->emailList = $input->validNewsList[$list]['name'];
                               $output->emailKey = $oList->action_key;
                               $ret = $this->_send($input, $output);
                               if (!$ret) {
                                   SGL::logMessage('Unable to send subscribe message to: '.$input->email);
                               }
                           }
                       } else {
                           $errorLists = true;
                       }

                   }
               unset($oList);
            } else {
                 $oList->newsletter_id = $this->dbh->nextId($this->conf['table']['newsletter']);
                if (!empty($input->name)) {
                    $oList->name = $input->name;
                }
                // get member
                 $member = $this->findMemberByEmail($input->email);
                // If emailConfirmation not required - registration active by default
                if ($this->conf['NewsletterMgr']['emailConfirmation']) {
                    if($member != '') {
                         $oList->status = 0;
                        $oList->action_request = 'subscribe';
                        $oList->action_key = $this->_generateKey($input->email);
                    } else {
                        $oList->status = 1;
                        $oList->action_request = 'subscribe';
                        $oList->action_key = $this->_generateKey($input->email);
                    }
                } else {
                   $oList->status = 0;
                }

                $oList->date_created = $oList->last_updated = SGL_Date::getTime();
                $success = $oList->insert();
                if ($success) {
                    if ($this->conf['NewsletterMgr']['emailConfirmation']) {

                        // Send email confirmation
                        $output->emailSiteName = ($this->conf['site']['name']) ? $this->conf['site']['name'] : $input->adminRealName;
                        $output->emailSubject = SGL_String::translate('Action confirmation for newsletter').' '.$input->validNewsList[$list]['name'];
                        $output->emailAction = SGL_String::translate('subscribe');
                        $output->emailName = $input->name ? $input->name : 'User';
                        $output->emailAddress = $input->email;
                        $output->emailList = $input->validNewsList[$list]['name'];
                        $output->emailKey = $oList->action_key;
                        $output->adminRealName = $input->adminRealName;
                        $ret = $this->_send($input, $output);
                        if (!$ret) {
                           SGL::logMessage('Unable to send subscribe message to: '.$input->email);
                        }
                    }
                } else {
                    $errorLists = true;
                }
                unset($oList);
            }

            if ($errorLists) {
                SGL::raiseMsg('Unable to subscribe you to some lists');
            } else {
                if ($this->conf['NewsletterMgr']['emailConfirmation']) {
                    SGL::raiseMsg('Thank you subscribe email confirmation', true, SGL_MESSAGE_INFO);
                } else {
                    SGL::raiseMsg('Thank you subscribe', true, SGL_MESSAGE_INFO);
                }
            }
            $aParams = array(
                            'managerName' => 'newsletter'
                            ,'complete' => true
            );
            SGL_HTTP::redirect($aParams);
        }
    }

    /**
    * Send unsubscribe e-mail or remove data from DB.
    *
    * @access public
    *
    */
    function _cmd_unsubscribe(&$input, &$output)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $errorLists = false;

        // Process request for every list selected
        foreach($input->listName as $list) {
            $oList = DB_DataObject::factory($this->conf['table']['newsletter']);
            $oList->email = $input->email;

            $oList->list = $input->validNewsList[$list]['name'];
            $noRows = $oList->find(true);

            // Check if user exist
            if ($noRows != 1) {
                SGL::logMessage('Unregistered user: '.$input->email.' tried to unsubscribe to list '.$input->validNewsList[$list]['name']);
                $errorLists = true;
                continue;
            }

            if ($this->conf['NewsletterMgr']['emailConfirmation']) {
                $oList->action_request = 'unsubscribe';
                $oList->action_key = $this->_generateKey($input->email);
                $oList->last_updated = SGL_Date::getTime();
                $success = $oList->update();
                if ($success) {
                    $output->emailSiteName = ($this->conf['site']['name']) ? $this->conf['site']['name'] : $input->adminRealName;
                    $output->emailSubject = SGL_String::translate('Action confirmation for newsletter').' '.$input->validNewsList[$list]['name'];;
                    $output->emailAction = SGL_String::translate('unsubscribe');
                    $output->emailName = $input->name;
                    $output->emailAddress = $input->email;
                    $output->emailList = $input->validNewsList[$list]['name'];
                    $output->emailKey = $oList->action_key;
                    $output->adminRealName = $input->adminRealName;
                    $ret = $this->_send($input, $output);
                    if (!$ret) {
                       SGL::logMessage('Unable to send unsubscribe message to: '.$input->email);
                    }
                } else {
                    $errorLists = true;
                }
            } else {
                $success = $oList->delete();
                if (!$success) {
                    $errorLists = true;
                }
            }
            unset($oList);
        }


        if ($errorLists) {
            SGL::raiseMsg('Unable to unsubscribe you to some lists');
        } else {
            if ($this->conf['NewsletterMgr']['emailConfirmation']) {
                SGL::raiseMsg('Thank you unsubscribe email confirmation', true, SGL_MESSAGE_INFO);
            } else {
                SGL::raiseMsg('Thank you unsubscribe', true, SGL_MESSAGE_INFO);
            }
        }
        $aParams = array(
            'managerName' => 'newsletter'
            ,'complete' => true
        );
        SGL_HTTP::redirect($aParams);
    }

    /**
     * used member subscribe An dUnsubscribe
     *
     * @param unknown_type $input
     * @param unknown_type $output
     */
    function _cmd_subscribeAndUnsubscribe($input,$output)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $statuSubscribe = $this->subscribe($input,$output);
        // subscribe
        if ($statuSubscribe) {
            SGL::raiseMsg('Unable to subscribe you to from all of the selected lists');
        }

        // unsubscribe
        $statuUnSubscribe = $this->unsubscribe($input,$output);
        if ($statuUnSubscribe) {
            SGL::raiseMsg('Unable to unsubscribe you to from all of the selected lists');
        } elseif ($input->listName == '') {
            // check if no subscribe show mesage
            SGL::raiseMsg('Thank you unsubscribe', true, SGL_MESSAGE_INFO);
        } else {
            // if have subscribe and unsubscribe
            SGL::raiseMsg('Thank you subscribe', true, SGL_MESSAGE_INFO);
        }

        $aParams = array(
                'managerName' => 'newsletter'
                );
        SGL_HTTP::redirect($aParams);
    }

   function subscribe(&$input, &$output)
   {
       SGL::logMessage(null, PEAR_LOG_DEBUG);
       SGL_DB::setConnection();
       $errorLists = false;

       // Process registration for every list selected
       foreach ($input->listName as $list) {
           $oList = DB_DataObject::factory($this->conf['table']['newsletter']);
           $oList->email = $input->email;
           $oList->list = $input->validNewsList[$list]['name'];
           $noRows = $oList->find(true);
           // Do not subscribe if already subscribed
           if ($noRows != 0) {
               if ($this->conf['NewsletterMgr']['emailConfirmation']) {
                   $oList->email = $input->email;
                   $oList->action_request = 'subscribe';
                   $oList->action_key = $this->_generateKey($oList->email);
                   $oList->last_updated = SGL_Date::getTime();
                   $oList->list = $input->validNewsList[$list]['name'];
                   $success = $oList->update();
                   if (!$success) {
                       $errorLists = true;
                   }
               }
               unset($oList);
           } else {
            // get FirstName member
              $aFirstName = $this->findFirstName();
               $oList->newsletter_id = $this->dbh->nextId($this->conf['table']['newsletter']);
               $oList->name = ($aFirstName['firstname'] != '') ? $aFirstName['firstname'] : $input->name;

               // If emailConfirmation not required - registration active by default
               if ($this->conf['NewsletterMgr']['emailConfirmation']) {
                   $oList->status = 0;
                   $oList->action_request = 'subscribe';
                   $oList->action_key = $this->_generateKey($input->email);
               } else {
                   $oList->status = 0;
               }

               $oList->date_created = $oList->last_updated = SGL_Date::getTime();
               $success = $oList->insert();
               if (!$success) {
                  $errorLists = true;
               }
               unset($oList);
           }

           if ($errorLists) {
                  return $errorLists ;
           }
       }

   }


   function unsubscribe(&$input, &$output)
    {
       SGL::logMessage(null, PEAR_LOG_DEBUG);
        $errorLists = false;
           $aUnscribeList = $input->validNewsList;
        // Process request for every list selected
           foreach($input->listName as $list) {
               unset($aUnscribeList[$list]);
           }

        foreach($aUnscribeList as $key => $aUnscribe) {
            $oList = DB_DataObject::factory($this->conf['table']['newsletter']);
            $oList->email = $input->email;
            $oList->list = $aUnscribe['name'];
            $noRows = $oList->find(true);
             // ยังไม่เลือก sub หรือ unsub ก็ยังไม่บันทึก ใน newsletter เมื่อ find newsletter ก็ ไม่เจอ ค่า ก็เป็น 0
            // Check if user exist
          if ($noRows != 1) {
                SGL::logMessage('Unregistered user: '.$input->email.' tried to unsubscribe to list '.$aUnscribe['name']);
                continue;
            }

           if ($this->conf['NewsletterMgr']['emailConfirmation']) {
                $oList->action_request = 'unsubscribe';
               // $oList->email = $input->email;
                $oList->action_key = $this->_generateKey($input->email);
                $oList->last_updated = SGL_Date::getTime();
                $success = $oList->update();

               if (!$success) {
                   $errorLists = true;
               }
            } else {
                $success = $oList->delete();
                if (!$success) {
                    $errorLists = true;
                }
            }
            unset($oList);
        }

        if ($errorLists) {
           return $errorLists;
        }
    }

    /**
    * E-mail/key pair validation and perform the requested
    * action (subscribe, unsubscribe, update).
    *
    * @access public
    *
    */
    function _cmd_authorize(&$input, &$output)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $output->template = 'authorize.html';
        if (empty($input->actionKey)) {
            return;
        }

        $oList = DB_DataObject::factory($this->conf['table']['newsletter']);
        $oList->email = $input->email;
        $oList->action_key = $input->actionKey;
        $noRows = $oList->find(true);
        $aErrors = array();

        if ($noRows != 1) {

           $aErrors['actionKey'] = 'Please input a valid authorization key';
           $output->error = $aErrors;
           SGL::raiseMsg('Invalid e-mail / authorization code pair.');

           return;
        }

        // Subscribe
        if ($oList->action_request == 'subscribe') {
            $oList->action_request = 'subscribe';
            $oList->action_key = '';
            $oList->status = 0;
            $oList->last_updated = SGL_Date::getTime();
            $success = $oList->update();
            if ($success) {
                SGL::raiseMsg('Authorization accepted! Thank you for subscribing to our newsletter.',
                 true, SGL_MESSAGE_INFO);

                 //if Authorization accepted
                 $output->isAuthSuccess = true;
                return;
            }
        }

        // Unsubscribe
        if ($oList->action_request == 'unsubscribe') {
            $success = $oList->delete();
            if ($success) {
                SGL::raiseMsg('Authorization accepted! You were unsubscribed from our newsletter.',
                 true, SGL_MESSAGE_INFO);

                 //if Authorization accepted
                 $output->isAuthSuccess = true;
                return;
            }
        }

        // Update subscription
        if ($oList->action_request == 'update') {
            $oList->action_request = '';
            $oList->action_key = '';
            $oList->last_updated = SGL_Date::getTime();
            $success = $oList->update();
            if ($success) {
                SGL::raiseMsg('Authorization accepted! Thank you for updating your subscription.',
                 true, SGL_MESSAGE_INFO);

                 //if Authorization accepted
                 $output->isAuthSuccess = true;
                 return;
            }
        }

        SGL::raiseMsg('There was an error processing your request.');
    }


    /**
    * Send e-mail function.
    *
    * @access public
    *
    */
    function _send($input, $output)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $output->theme          = $_SESSION['aPrefs']['theme'];
        $path = RVS_USER_HOME . '/.rvsitebuilder/projects/' . RVS_PROJECT_ID . '/lang/user/emailtemplate/en-utf-8';
        $output->masterTemplate = 'email_confim_action.html';
        $pathEmailTemplate = $path . '/' .  $output->masterTemplate;

        include_once SGL_LIB_PEAR_DIR . '/HTML/Template/Flexy.php';
        $options = array('templateDir' => $path );
        //load subject
        $aFile = (is_file($path . '/subject.ini'))
            ? RvsLibs_Config::parse_ini_file($path . '/subject.ini', true)
            : array();

        if (is_file($pathEmailTemplate)) {
        	$this->flexyHandle = new HTML_Template_Flexy($options);
        	$bodyHtml = $this->flexyHandle->compile($output->masterTemplate);
        	$bodyHtml = $this->flexyHandle->bufferedOutputObject($output);
        } else {
        	$view     = new SGL_HtmlSimpleView($output);
        	$bodyHtml = $view->render();
        }

        $headers['From']    = $this->conf['email']['admin'];
        $headers['Subject'] = isset($aFile['Subject']) ? $aFile['Subject'] : $output->emailSubject;
        $crlf               = SGL_String::getCrlf();
        $mime               = new Mail_mime($crlf);
        ///fix PHP 5.3
        $mime = &$mime;
        $mime->setHTMLBody($bodyHtml);
        $body               = $mime->get();
        $hdrs               = $mime->headers($headers);
        $mail               = SGL_Emailer::factory();
        $success = false;
        if ($mail) {
        	$success            = $mail->send($output->emailAddress, $hdrs, $body);
        }

        if ($success) {
            //  redirect on success
            SGL::raiseMsg('Newsletter sent successfully', true, SGL_MESSAGE_INFO);
        } else {
        	SGL::raiseMsg('Problem sending email', true, SGL_MESSAGE_WARNING);
            //SGL::raiseError('Problem sending email', SGL_ERROR_EMAILFAILURE);
        }

        return $success;
    }


    /**
    * Checks if a valid newsletter list exists.
    *
    * @access   private
    * @author   Benea Rares <rbenea@bluestardesign.ro>
    * @param    string  $list   List name, if empty: return an array with all lists
    * @return   array    $ret   'id', 'name', 'descrisption'; False = list not exist
    *
    * @todo please use constants for statuses
    */
    function _getList($listName = '')
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);

        if (preg_match("(\W)",$listName) || !isset($this->conf['table']['newsletter'])) {
            SGL::logMessage('Invalid list name: '.$listName);
            return false;
        }

        if ($listName == '') {
            $query = "SELECT * FROM {$this->conf['table']['newsletter']} WHERE status=9";
        } else {
            $query = "SELECT * FROM {$this->conf['table']['newsletter']} WHERE list='$listName' AND status=9";
        }

        $result = $this->dbh->query($query);
        if (is_a($result, 'PEAR_Error')) {
            return false;
        }

        if ($result->numRows() == 0) {
            SGL::logMessage('List does not exist: '.$listName);
            return false;
        }

        if ($result->numRows() == 1) {
        	//Fix PHP5.3 (use MDB2)
            $row = $result->fetchRow(SGL_DB_FETCHMODE_ASSOC);
            $ret = array();
            $ret[] = array(
                'id' => $row['newsletter_id'],
                'name' => $row['list'],
                'description' => $row['name']);
            return $ret;
        }

        $ret = array();
        //Fix PHP5.3 (use MDB2)
        while ($row = $result->fetchRow(SGL_DB_FETCHMODE_ASSOC)) {
            $ret[$row['newsletter_id']] = array(
                'name' => $row['list'],
                'description' => $row['name']);
        }

        return $ret;
    }

    function getListForUser()
    {
        $userID =  $_SESSION['uid'];

        $oUser = DB_DataObject::factory($this->conf['table']['user']);
        $oUser->get($userID);

        $query = "SELECT * FROM ". $this->conf['table']['newsletter'] ." WHERE email='". $oUser->email ."'";
        //Fix PHP5.3 (use MDB2)
        $result = $this->dbh->getAll($query, SGL_DB_FETCHMODE_ASSOC);
        return $result;
    }


    function checkSubscribed($validNewsList, $checkListForUser)
    {
        $aCheck = array();
        foreach($checkListForUser as $keyCheck => $valueCheck) {
            if($valueCheck['action_request'] == 'subscribe') {
                foreach($validNewsList as $keyList =>$valueList) {
                    if(in_array($valueCheck['list'], $valueList)) {
                        $aCheck[$keyList] = $keyList;
                    }
                }
            }
        }
        return $aCheck;

    }


    /**
    * Generates an authorization key.
    *
    * @access   private
    * @author   Benea Rares <rbenea@bluestardesign.ro>
    * @param    string  $str   Optional noise
    * @return   string         Return the key
    *
    */
    function _generateKey($str = '')
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);

        $str = $str . (string) rand();
        return md5($str);
    }

    /**
     * Retrieves list of news lists a user is subscribed to.
     *
     * @access  public
     * @author  Alexander J. Tarachanowicz II <ajt@localhype.net>
     * @param   int     $userID
     * @return  array   $result
     *
     */
     function getSubscribedLists($userID)
     {
        SGL::logMessage(null, PEAR_LOG_DEBUG);

        //  get user details
        $oUser = DB_DataObject::factory($this->conf['table']['user']);
        $oUser->get($userID);

        $query = "SELECT * FROM ". $this->conf['table']['newsletter'] ." WHERE email='". $oUser->email ."' AND status=0";
        $result = $this->dbh->getAssoc($query);
        return $result;
     }

    /**
     * Retrieves list of news letter a user is not subsribed to.
     *
     * @access  public
     * @author  Alexander J. Tarachanowicz II <ajt@localhype.net>
     * @param   int     $userID
     * @return  array   $newsLists
     *
     */
     function getUnsubscribedLists($userID)
     {
        SGL::logMessage(null, PEAR_LOG_DEBUG);

        $newsLists = $this->_getList();
        $subscribedLists = $this->getSubscribedLists($userID);

        foreach ($newsLists as $k => $nValues) {
            foreach ($subscribedLists as $sValues) {
                if ($nValues['name'] == $sValues->list) {
                    unset($newsLists[$k]);
                }
            }
        }
        return $newsLists;
     }

    /**
     * Default redirect for all Managers.
     *
     * @param unknown_type $input
     * @param unknown_type $output
     */
    function _cmd_redirectToDefault(&$input, &$output)
    {
        //  must not logmessage here

        //  if no errors have occured, redirect
        if (!SGL_Error::count()) {
            $aParams = SGL_Manager::getDefaultPageParams();
            SGL_HTTP::redirect($aParams);

        //  else display error with blank template
        } else {
            $output->template = 'error.html';
        }
    }

    function checkuser()
    {
    	if(empty($input)) {
    		$input = new stdClass();
    	}
       $input->UserName = $_SESSION['uid'];
       if($input->UserName != 0 && $input->UserName !='' && $input->UserName !=1) {
           //user
           return true;
       }
      //nobody and admin
       return false;
    }

    function findEmailUser()
    {
        $userID =  $_SESSION['uid'];
        $aUser = array();
        $oUser = DB_DataObject::factory($this->conf['table']['user']);
        $oUser->get($userID);
        $oUser->find(true);
        $aUser[$oUser->email] = $oUser->username;
        return $aUser;
    }

    //get firstname of user
  function findFirstName()
    {
        $userID =  $_SESSION['uid'];
        $aUser = array();
        $oUser = DB_DataObject::factory($this->conf['table']['user']);
        $oUser->get($userID);
        $oUser->find(true);
        $aUser['firstname'] = $oUser->first_name;
        return $aUser;
    }

    //get member by email ไว้ check member ที่ไป send ตรง box newsletter ส่วนของ user ทั่วไป
    function findMemberByEmail($email)
    {
        $query = "SELECT email FROM ". $this->conf['table']['user'] ." WHERE email='". $email ."'";
        $result = $this->dbh->getOne($query);
        return $result;
    }
}
?>

Copyright 2K16 - 2K18 Indonesian Hacker Rulez