<?php
require_once "PHPMailerAutoload.php";

//the following class is the main class for any and all database interaction for the wdd admin panel
//this class also contains the email functions for sending emails to administrators
//all admin panel classes will etend from this one.

class MasterClass
{

    //establish db connection info
    private $db_LOC = DBLOC_; //default is localhost and usually will stay
    private $db_USER = DBUSER_; //user name for logging into database
    private $db_PASS = DBPASS_; // password for the login
    private $db_NAME = DBNAME_; // the actual database base name. Usually preceeded by the site login and an _

    //establish protected variables that will be used in all the database interaction classes
    protected $query;
    private $data = array();
    public $info;
    protected $db;
    protected $isConnected;

    //establish regular expression strings for data validation
    protected $charList = "/[^0-9]/";

    //variables used for file upload handling
    public $path;
    private $domain;
    private $ref;
    private $ipCheck;


    ####################################################################################################################################################
    ####################################################################################################################################################

    //function for connecting to the database and performing the necessary query
    protected function dbConn()
    {

        //make the connection to the actual database if the connection is not made, then there is a problem with the mysql database
        if ($this->db = new mysqli($this->db_LOC, $this->db_USER, $this->db_PASS, $this->db_NAME)) {

            $this->isConnected = 'yes';
            return true;

        } else {

            return false;

        }

    }

    ####################################################################################################################################################
    ####################################################################################################################################################

    //function to close a database connection
    protected function dbClose()
    {

        //first make sure that the database is actually connected before trying to close it
        if ($this->isConnected == 'yes') {

            $this->isConnected = '';
            $this->db->close();

        }

    }

    ####################################################################################################################################################
    ####################################################################################################################################################

    //function to clean the post data coming in from the user submission
    protected function cleanData()
    {

        foreach ($_POST as $key => $value) {

            if (is_array($value)) {

                //multiple select menu
                $i = 0;
                foreach ($value as $fieldKey => $fieldValue) {

                    $this->data[$key][$i] = addslashes($fieldValue);
                    $i++;

                }

            } else {

                if ($key != 'sendBtn' && $key != 'emailC' && $key != 'passC') {

                    $this->data[$key] = addslashes($value);

                }

            }

        }

        return $this->data;

    }

    ####################################################################################################################################################
    ####################################################################################################################################################

    //function to check the referrer agains the array of allowed referrers
    protected function checkRef()
    {

        if (REFER_IP_ADDRESS == IP_ADDRESS) {

            //ip addresses match
            return true;

        } else {

            //ip addresses don't match
            return false;

        }

    }

    ####################################################################################################################################################
    ####################################################################################################################################################

    //function to get the list of states
    public function getStates()
    {

        $this->dbConn();

        $this->query = "SELECT * FROM States ORDER BY state_name ASC";

        $getStates = $this->db->query($this->query);

        $data = array();
        $i = 0;

        while ($row = $getStates->fetch_assoc()) {

            $data[$i]['Nbr'] = stripslashes($row['state_nbr']);
            $data[$i]['Name'] = stripslashes($row['state_name']);
            $data[$i]['Abbr'] = stripslashes($row['state_abbr']);
            $i++;

        }

        $this->dbClose();

        return $data;

    }

    ####################################################################################################################################################
    ####################################################################################################################################################

    //function to get the list of countries
    public function getCountries()
    {

        $this->dbConn();

        $this->query = "SELECT * FROM Countries ORDER BY country_name ASC";

        $getCountries = $this->db->query($this->query);

        $data = array();
        $i = 0;

        while ($row = $getCountries->fetch_assoc()) {

            $data[$i]['Nbr'] = stripslashes($row['country_nbr']);
            $data[$i]['Name'] = stripslashes($row['country_name']);
            $data[$i]['Abbr_1'] = stripslashes($row['country_abbr_1']);
            $data[$i]['Abbr_2'] = stripslashes($row['country_abbr_2']);
            $data[$i]['Abbr_3'] = stripslashes($row['country_abbr_3']);
            $i++;

        }

        $this->dbClose();

        return $data;

    }

    ######################################################################################################################
    ######################################################################################################################

    //function for sending email
    public function sendEmail($msgHTML, $msgTXT, $subject, $to = '', $toName = '',$cc='',$ccName='')
    {

        $result = array();

        //send the email using the phpMailer
        date_default_timezone_set('Etc/UTC');

        $mail = new PHPMailer;

        $mail->SMTPDebug = 0; // Enable verbose debug output ( 3 for debugging info )

        $mail->isSMTP(); // Set mailer to use SMTP
        $mail->Host = SERVER_HOST; // Specify main and backup SMTP servers
        $mail->SMTPAuth = true; // Enable SMTP authentication
        $mail->Username = EMAIL_LOGIN; // SMTP username
        $mail->Password = EMAIL_PASSWORD; // SMTP password
        $mail->Port = EMAIL_PORT; // TCP port to connect to

        $mail->From = SERVER_FROM;
        $mail->FromName = SERVER_FROM_NAME;
        if ($to == '') {

            $mail->addAddress(EMAIL_TO, EMAIL_TO_NAME); // Add a recipient

        } else {

            $mail->addAddress($to, $toName);

        }
        $mail->addReplyTo(SERVER_FROM, SERVER_FROM_NAME);
        if($cc != '' && $ccName != ''){

            $mail->addCC($cc,$ccName);

        }
        //$mail->addCC(CC_EMAIL_TO);
        //$mail->addBCC('bcc@example.com');

        //$mail->addAttachment('/var/tmp/file.tar.gz');          // Add attachments
        //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');     // Optional name
        $mail->isHTML(true); // Set email format to HTML
        $mail->SMTPSecure = "tls"; 

        $mail->Subject = $subject;
        $mail->Body = $msgHTML; // HTML Msg
        $mail->AltBody = $msgTXT; // Plain Text Msg

        if (!$mail->send()) {

            $result['Msg'] = 'Message could not be sent.';
            //$result['Msg'] .= 'Mailer Error: ' . $mail->ErrorInfo;
            $result['Status'] = false;

        } else {

            $result['Msg'] = 'Your message has been sent. Thank you for contacting ' . COMPANY_NAME . '.';
            $result['Status'] = true;

        }

        return $result;

    }

    ####################################################################################################################################################
    ####################################################################################################################################################

    //function to determine the file type that was uploaded
    //can only use .gif, .png, and .jpg files
    public function dType($name = '')
    {

        //make sure the file name is not empty
        if ($name != '') {

            $fileArray = explode('.', $name);

            $ext = strtolower($fileArray['1']);

            //use the extension to determine the right file type
            switch (strtolower($ext)) {

                case "png":
                    $ftype = 'png';
                    break;

                case "gif":
                    $ftype = 'gif';
                    break;

                case "jpg":
                    $ftype = 'jpeg';
                    break;

                case "jpeg":
                    $ftype = 'jpeg';
                    break;
                    case "pdf":
                        $ftype = 'pdf';
                    break; 
                default:
                    $ftype = 'none';
                    break;

            }

        } else {

            $ftype = 'none';

        }

        return $ftype;

    }

    ###################################################################################################################################################
    ###################################################################################################################################################

    //function to determine the new size cropped thumb canvas
    //thumb dimensions are pre determined by cropped dimensions
    public function determineDimensions($canvas, $th_width, $th_height)
    {

        $info = array();

        //get the size of the canvas image
        $area = @getimagesize($canvas);

        $width = $area[0];
        $height = $area[1];

        //have to make sure that the thumb image is actually smaller than the real image
        //can't crop an image smaller than the original image
        if ($width > $th_width && $height > $th_height) {

            if ($th_width != $th_height) {

                $wRatio = floor($area[0] / $th_width);
                $hRatio = floor($area[1] / $th_height);

                if ($wRatio < $hRatio) {

                    $ratio = $wRatio;

                } else if ($hRatio < $wRatio) {

                    $ratio = $hRatio;

                } else {

                    $ratio = $hRatio;

                }

                $info['cropWidth'] = $th_width * $ratio;
                $info['cropHeight'] = $th_height * $ratio;

            } else {

                //perfect square thumb

                if ($area[0] > $area[1]) {

                    $info['cropWidth'] = $area[1];
                    $info['cropHeight'] = $area[1];

                } else {

                    $info['cropWidth'] = $area[0];
                    $info['cropHeight'] = $area[0];

                }

            }

            //determine the x and y coordinates

            $xAreaDif = $area[0] - $info['cropWidth'];
            $yAreaDif = $area[1] - $info['cropHeight'];

            if ($xAreaDif > 0) {

                $info['x'] = $xAreaDif / 2;

            } else {

                $info['x'] = 0;

            }

            if ($yAreaDif > 0) {

                $info['y'] = $yAreaDif / 2;

            } else {

                $info['y'] = 0;

            }

            $info['Status'] = true;

        } else {

            $info['Status'] = false;

        }

        return $info;

    }

    ####################################################################################################################################################
    ####################################################################################################################################################

    //create thumbnail image
    public function createThumbImage($canvas, $mWidth, $mHeight, $thDir, $imgName)
    {

        $result = array();

        if (is_file($canvas)) {

            $type = $this->dType($imgName);

            if ($type != 'none') {

                //we have a legitimate file type, time to create the thumbnail image
                switch ($type) {
                    case "jpeg":
                        $srcImg = @imagecreatefromjpeg($canvas);
                        break;
                    case "gif":
                        $srcImg = @imagecreatefromgif($canvas);
                        break;
                    case "png":
                        $srcImg = @imagecreatefrompng($canvas);
                        break;
                }

                if ($srcImg) {

                    //determine the new width and height of the thumbnail image
                    $dimensions = $this->determineDimensions($canvas, $mWidth, $mHeight);

                    if ($dimensions['Status'] === true) {

                        //create the thumbnail image
                        $thumb = imagecreatetruecolor($mWidth, $mHeight);

                        if ($thumb) {

                            if (imagecopyresampled($thumb, $srcImg, 0, 0, $dimensions['x'], $dimensions['y'], $mWidth, $mHeight, $dimensions['cropWidth'], $dimensions['cropHeight'])) {

                                $thumbPath = THIS_DOMAIN . '/' . $thDir . '/' . $imgName;

                                //create the finished file and save it based on the file type
                                switch ($type) {

                                    case "jpeg":
                                        $final = imagejpeg($thumb, $thumbPath, 75);
                                        break;

                                    case "gif":
                                        $final = imagegif($thumb, $thumbPath, 75);
                                        break;

                                    case "png":
                                        $final = imagepng($thumb, $thumbPath);
                                        break;

                                }

                                if ($final) {

                                    //image was successfully created and saved.
                                    //delete the src image
                                    @imagedestroy($srcImg);
                                    @imagedestroy($thumb);

                                    $result['imgName'] = $imgName;
                                    $result['Msg'] = 'Image upload was successful';
                                    $result['Status'] = true;

                                } else {

                                    $result['Msg'] = 'Could not save thumbnail to the specified directory';
                                    $result['Msg'] .= '<br/>' . $thumbPath;
                                    $result['Msg'] .= '<br/><br/>File upload unsuccessful';
                                    $result['Status'] = false;

                                }

                            } else {

                                $result['Msg'] = 'Could not resize the canvas to the new parameters';
                                $result['Msg'] .= '<br/><br/>File upload unsuccessful';
                                $result['Status'] = false;

                            }

                        } else {

                            $result['Msg'] = 'Could not create the thumbnail image from canvas';
                            $result['Msg'] .= '<br/><br/>File upload unsuccessful';
                            $result['Status'] = false;

                        }

                    } else {

                        $result['Msg'] = 'Could not create the thumbnail image because the image your provided is smaller than ' . $mWidth . ' by ' . $mHeight . '.';
                        $result['Msg'] .= '<br/><br/>File upload unsuccessful';
                        $result['Status'] = false;

                    }

                } else {

                    $result['Msg'] = 'Could not create image';
                    $result['Msg'] .= '<br/><br/>File upload unsuccessful';
                    $result['Status'] = false;

                }

            } else {

                $result['Msg'] = 'Either no file was present, could not determine the file type, or the type of file you uploaded was the wrong kind';
                $result['Msg'] .= '<br/><br/>File upload unsuccessful';
                $result['Status'] = false;

            }

        } else {

            $result['Msg'] = 'There is no file to use as a canvas for alteration';
            $result['Msg'] .= '<br/><br/>File upload unsuccessful';
            $result['Status'] = false;

        }

        return $result;

    }

    ####################################################################################################################################################
    ####################################################################################################################################################

    //function to check at file type against an accepted file type
    public function checkType($ftype, $typeReq)
    {

        //first create an array based on the string
        $typeArray = explode("|", $typeReq);
        $flag = '';
        foreach ($typeArray as $value) {

            if ($ftype == trim($value)) {

                $flag = 'yes';
                break;

            }

        }

        if ($flag == 'yes') {

            return true;

        } else {

            return false;

        }

    }

    ####################################################################################################################################################
    ####################################################################################################################################################

    //function to handle Trumbowyg embed image file upload
    public function handleImageUpload()
    {

        $result = array();
        $dir = '';
        $imgName = '';
        $imgFieldName = '';

        if ($this->checkRef()) {

            if (isset($_FILES)) {

                if (isset($_FILES['CMSImage']) && $_FILES['CMSImage']['tmp_name'] != '') {

                    $dir = CMS_CONTENT_IMAGES;
                    $imgFieldName = 'CMSImage';

                }

                if ($dir != '' && $imgFieldName != '') {

                    if ($this->checkType($_FILES[$imgFieldName]['type'], ALLOWED_FILES_IMAGES)) {

                        $chars = array('!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '=', '{', '}', '[', ']', '<', '>', '?', '/', '\\', ' ', '\'');
                        $canvas = $_FILES[$imgFieldName]['tmp_name'];
                        $imgName = str_replace($chars, '_', $_FILES[$imgFieldName]['name']);

                        if (is_file(THIS_DOMAIN.'/' . $dir . '/' . $imgName)) {

                            $now = time();
                            $imgName .= '_' . $now;

                        }

                        if ($img = move_uploaded_file($canvas, THIS_DOMAIN.'/' . $dir . '/' . $imgName)) {

                            $result['success'] = true;
                            $result['url'] = WEBSITE_ADDY . '/' . $dir . '/' . $imgName;

                        } else {

                            $result['success'] = false;
                            $result['errorMsg'] = 'Could not move the file';

                        }

                    }

                } else {

                    $result['success'] = false;
                    $result['errorMsg'] = 'Could not see uploaded file';

                }

            } else {

                $result['success'] = false;
                $result['errorMsg'] = 'Could not see uploaded file';

            }

        } else {

            $result['success'] = false;
            $result['errorMsg'] = 'IP Address Fail';

        }

        return $result;

    }

    ####################################################################################################################################################
    ####################################################################################################################################################

    //function to clean a string to be url friendly
    public function urlSafeString($string,$file=false,$append=false)
    {

        if ($string != '') {

            if ($file === true) {

                $stringArray = explode('.', $string);
                $ext = $stringArray[(count($stringArray) - 1)];
                if (count($stringArray) == 2) {

                    $string = trim($stringArray[0]);

                } else {

                    $string = '';
                    for ($i = 0; $i < (count($stringArray) - 1); $i++) {

                        $string .= $stringArray[$i];
                        if (($i + 1) < count($stringArray)) {

                            $string .= ' ';

                        }

                    }

                }

            }

            $chars = array('!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '/', '|',
                ',', ';', '.', ':', '?', '<', '>', '\\', '\'', '"',
                '™', '°', '©', '®', 'ü', 'µ', 'Ü', '×', '¯', 'Ø', '£', '¢',
                '€', '§', '¼', '«', '«', '~', 'Ã', 'Å', 'Ä', 'À', 'Á', 'Â',
                'Ç', 'É', 'È', '╩', '╦', 'Ï', 'Î', 'Í', 'Ì', 'Ñ', 'Ö', '╘',
                'Ò', 'Ó', 'Û', 'Ù', 'Æ', 'ß', 'Œ', ' ');

            $stringArray = explode(' ',trim($string));
            $finalString = '';

            for($i=0;$i<count($stringArray);$i++){

                $cleanString = str_replace($chars,'', strtolower(trim($stringArray[$i])));
                if($cleanString != '' && $cleanString != ' '){

                    $finalString .= $cleanString;
                    if($i+1 < count($stringArray)){

                        $finalString .= '-';
    
                    }

                }                

            }

            if($append === true){

                $finalString .= '_'.time();

            }            

            if ($file === false) {

                return $finalString;

            } else {

                $finalString .= '.' . $ext;
                return $finalString;

            }

        } else {

            return false;

        }

    }
    
    ####################################################################################################################################################	    
    ####################################################################################################################################################	

    //function to generate a random password.
    public function genPass(){

        $digitArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');

        //establish the password variable
        $pword = '';

        //loop through the array and create the new password
        for($i=0; $i<7; $i++){

            shuffle($digitArray);			
            $key = array_rand($digitArray);
            $pword .= $digitArray[$key];

        }

        //return the actual new password for sending via email
        return $pword;
    }

    ####################################################################################################################################################	
    ####################################################################################################################################################	

    //function to convert number string to money
    public function toMoney($val,$symbol='')
    {    
    
        $n = $val; 
        $c = is_float($n) ? 1 : number_format($n,2);
        $d = '.';
        $t = ',';
        $sign = ($n < 0) ? '-' : '';
        $i = $n = number_format(abs($n),2); 
        $j = (($j = strlen($i)) > 3) ? $j % 3 : 0; 
    
        return  $symbol.$sign .($j ? substr($i,0, $j) + $t : '').preg_replace('/(\d{3})(?=\d)/',"$1" + $t,substr($i,$j)) ;
    
    }  


}

?>
