PageRenderTime 47ms CodeModel.GetById 2ms app.highlight 33ms RepoModel.GetById 1ms app.codeStats 1ms

/contact.php

https://github.com/swatCap/banan
PHP | 1205 lines | 402 code | 86 blank | 717 comment | 28 complexity | 92874635d7218bd5323f222f81ce33b2 MD5 | raw file
   1<?php
   2
   3/**
   4 * Class file to handle user requests for contact form
   5 * 
   6 * LICENSE:
   7 *
   8 * This source file is subject to the licensing terms that
   9 * is available through the world-wide-web at the following URI:
  10 * http://codecanyon.net/wiki/support/legal-terms/licensing-terms/.
  11 * The buyers have extended license are hence certified to use or
  12 * extend the functionality of this file or re-sell after modification.
  13 * 
  14 * This file is licensed to be used with Eventify theme and the
  15 * same can be resold/redistributed with the terms subject to those
  16 * are specified for extended license at Envato marketplace in the above link
  17 * 
  18 * PHP version >= 5.3
  19 *
  20 * @category  ContactForm
  21 * @package   ContactForm
  22 * @author    Kirti Kumar Nayak, India <thebestfreelancer.in@gmail.com>
  23 * @copyright 2013 TheBestFreelancer,
  24 * @license   http://codecanyon.net/wiki/support/legal-terms/licensing-terms/ CodeCanyon
  25 * @version   Release 1.9
  26 * @link      http://demos.thebestfreelancer.in/phpcontact/
  27 * @tutorial  http://demos.thebestfreelancer.in/phpcontact/documentation/
  28 */
  29
  30/**
  31 * Check if Contact class exists or not and define if not
  32 */
  33if (!class_exists('Contact')) {
  34    
  35    /**
  36     * Class to handle contact form requests handled via url
  37     * 
  38     * This is a singleton pattern class and can be called via static methods
  39     * 
  40     * @category  ContactForm
  41     * @package   ContactForm
  42     * @author    Kirti Kumar Nayak, India <thebestfreelancer.in@gmail.com>
  43     * @copyright 2013 TheBestFreelancer,
  44     * @license   http://codecanyon.net/wiki/support/legal-terms/licensing-terms/ CodeCanyon
  45     * @version   Release 1.9
  46     * @link      http://demos.thebestfreelancer.in/phpcontact/
  47     * @tutorial  http://demos.thebestfreelancer.in/phpcontact/documentation/
  48     */
  49    class Contact
  50    {
  51        // {{{ properties
  52        
  53        /**
  54         * private variable to store any string
  55         * mainly used to store user submitted data
  56         * 
  57         * @access private
  58         * @var string  The string submitted by user/visitor
  59         */
  60        private $_str;
  61        
  62        /**
  63         * private variable to store a string of allowable HTML tags
  64         * to be used against code / CSFR / XSS attacks by visitors/hackers
  65         * 
  66         * @access private
  67         * @var string  The allowable html tags for user
  68         */
  69        private $_allowedHTML;
  70        /**
  71         * private variable to store
  72         * an array of restricted HTML/special characters
  73         * to be used against code / CSFR / XSS attacks by visitors/hackers
  74         * 
  75         * @access private
  76         * @var string  The restricted special characters/strings for user
  77         */
  78        private $_restrictedChars;
  79        /**
  80         * private property to store mail receivers/admin
  81         * 
  82         * @access private
  83         * @var string The e-mail id(s) who will receive the mail
  84         */
  85        private $_receiver;
  86        /**
  87         * private property to hold the lowercase letter set
  88         * to be used to generate random string
  89         * 
  90         * @access private
  91         * @var string  The lowercase character set string
  92         */
  93        private $_lowerCaseChars;
  94        
  95        /**
  96         * private property to hold the uppercase letter set
  97         * to be used to generate random string
  98         * 
  99         * @access private
 100         * @var string  The uppercase character set string
 101         */
 102        private $_upperCaseChars;
 103        
 104        /**
 105         * private property to hold the numeric character set
 106         * to be used to generate random string
 107         * 
 108         * @access private
 109         * @var string  The numeric character set string
 110         */
 111        private $_numericChars;
 112        
 113        /**
 114         * private property to hold the special character set
 115         * to be used to generate random string
 116         * 
 117         * @access private
 118         * @var string  The special character set string
 119         */
 120        private $_specialChars;
 121        
 122        /**
 123         * private variable for random characters used by captcha method
 124         * 
 125         * @access private
 126         * @var string  The character set from which captcha should be generated
 127         */
 128        private $_charSet;
 129        
 130        /**
 131         * Private variable to store captcha type
 132         * if you have no GD library installed you may switch over to
 133         * Javascript captcha
 134         * 
 135         * @access private
 136         * @var string  The type of the captcha wanted
 137         */
 138        private $_captchaType;
 139        
 140        /**
 141         * Private variable to store captcha width
 142         * 
 143         * @access private
 144         * @var int  The height of the captcha image
 145         */
 146        private $_captchaWidth;
 147        
 148        /**
 149         * Private variable to store the captcha height
 150         * 
 151         * @access private
 152         * @var int  The height of the captcha image
 153         */
 154        private $_captchaHeight;
 155        
 156        /**
 157         * Private variable to store the location of the font to be used in captcha image
 158         * 
 159         * @access private
 160         * @var string  The path string of the ttf font file
 161         */
 162        private $_captchaFontLocation;
 163        
 164        /**
 165         * Private variable to store the captcha image font size
 166         * 
 167         * @access private
 168         * @var float  The font size for the captcha image
 169         */
 170        private $_captchaFontSize;
 171        
 172        /**
 173         * Private variable to store the captcha string angle
 174         * 
 175         * @access private
 176         * @var float  The angle of the captcha string
 177         */
 178        private $_captchaCharAngle;
 179        
 180        /**
 181         * private variable to hold mail type
 182         * expected values 'plain' / 'html'
 183         * 
 184         * @access private
 185         * @var string  The string describing mail type
 186         */
 187        private $_mailType;
 188        
 189        /**
 190         * private variable to store plain template
 191         * 
 192         * @access private
 193         * @var string  The plain mail template string
 194         */
 195        private $_plainMailTemplate;
 196        
 197        /**
 198         * private variable to store html template
 199         * 
 200         * @access private
 201         * @var string  The html mail template string
 202         */
 203        private $_htmlMailTemplate;
 204
 205        /**
 206         * private variable to store html reply template
 207         * 
 208         * @access private
 209         * @var string  The html reply mail template string
 210         */
 211        private $_replyHtmlMailTemplate;
 212        
 213        /**
 214         * private variable to contain response and to be converted into json
 215         * 
 216         * @access private
 217         * @var mixed  Json data object for page responses
 218         */
 219        private $_response;
 220        
 221        /**
 222         * private variable to store system auto response mail id
 223         * 
 224         * @access private
 225         * @var string  The name and e-mail string of the system
 226         */
 227        private $_autoResponder;
 228        
 229        /**
 230         * private static variable to hold class object
 231         * 
 232         * @access private
 233         * @staticvar
 234         * @var object  The current class object
 235         */
 236        private static $_classObject;
 237        
 238        // }}}
 239        // {{{ __construct()
 240        
 241        /**
 242         * Default constructor class to initialize variables and page data.
 243         * Accoring to singleton class costructor must be private
 244         * 
 245         * @return void
 246         * @access  private
 247         */
 248        private function __construct()
 249        {
 250            
 251            /*
 252             * set Error Reporting to all
 253             */
 254            error_reporting(E_ALL | E_STRICT);
 255            /*
 256             * Initialize a session if not started yet
 257             * YOU MUST ENABLE THIS IF WANT TO USE CAPTCHA !!!!!!!!!!!!
 258             */
 259            /*if (session_id() === '') {
 260                session_start();
 261            }
 262            /*
 263             * Set the receiver e-mail of the mail
 264             * CHANGE IT ACCORDING TO NEEDS
 265             */
 266            $this->_receiver        = 'yourname@yourdomain.com';
 267            /*
 268             * initialize the allowed html tags which user/visitor can
 269             * use to send a html formatted message
 270             * define more if you want
 271             */
 272            $this->_allowedHTML     =   '<a><br><div><p><span><strong>';
 273            $this->_allowedHTML     .=  '<h1><h2><h3><h4><h5><h6><hr>';
 274            $this->_allowedHTML     .=  '<table><tr><td><th><thead><tfoot>';
 275            
 276            /*
 277             * initialize the allowed html tags which user/visitor can
 278             * use to send a html formatted message
 279             * define more if you want
 280             */
 281            $this->_restrictedChars  =   array('"', 'javascript', '()', '\\');
 282            /*
 283             * Main user configurations start
 284             * You may edit as per your need from here
 285             * Please refer to documentation if you face problems
 286             * Or you may ask me in the support section
 287             */
 288            
 289            // captcha configurations
 290            
 291            /*
 292             * define captcha type as php
 293             * you may use javascript captcha too
 294             * possible values: php, js
 295             */
 296            
 297            $this->_captchaType     =   'php';
 298            
 299            /*
 300             * initialize captcha image width
 301             * it is defined as per the html design
 302             */
 303            $this->_captchaWidth     =   70;            
 304            /*
 305             * initialize the captcha image height
 306             * defined optimum for the design
 307             */
 308            $this->_captchaHeight    =   30;            
 309            /*
 310             * initialize the font file location to be used for captcha characters
 311             * it must be a valid ttf font file at the specified location
 312             */
 313            $this->_captchaFontLocation =   './MONOFONT.TTF';
 314            /*
 315             * initialize the font size of the captcha string
 316             * by default the maximum defined i.e. 80% of the image height
 317             */
 318            $this->_captchaFontSize  = $this->_captchaHeight * 0.8;
 319            /*
 320             * initialize the characters angle for the captcha
 321             * it is randomly set between -2 and 2
 322             * as the image height and font size are set
 323             */
 324            $this->_captchaCharAngle = rand(-2, 2);
 325            /*
 326             * initialize the lowercase character set from a-z
 327             */
 328            $this->_lowerCaseChars  =    'abcdefghijklmopqrstuvwxyz';
 329            /*
 330             * initialize the uppercase character set from A-Z
 331             */
 332            $this->_upperCaseChars  =    'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 333            /*
 334             * initalize the numeric character set from 0-9
 335             */
 336            $this->_numericChars    =    '0123456789';
 337            /*
 338             * initialize the special character set (add more or delete if you like)
 339             */
 340            $this->_specialChars    =    '!$%^&*+#~/|';
 341            /*
 342             * initialize the captcha characters as null
 343             */
 344            $this->_charSet		    =	 '';
 345            
 346            // mail configurations
 347            
 348            /*
 349             * Initialize mail type to catch user preferences
 350             * change it if you want plain mail witout any formatting
 351             */
 352            $this->_mailType        =    'html';
 353            
 354            /*
 355             * initiate auto reply system name and e-mail
 356             * Change it accodting to your needs
 357             */
 358            $this->_autoResponder   =   'noreply@yourdomain.com';
 359            
 360            /*
 361             * Initialize plain mail content template
 362             */
 363            $this->_plainMailTemplate = '{userMessage}';
 364            $this->_plainMailTemplate .= "\r\n\r\n\r\n" . 'From';
 365            $this->_plainMailTemplate .= "\r\n" . 'Name : {userFullName}';
 366            $this->_plainMailTemplate .= "\r\n" . 'E-Mail : {userEmail}';
 367            // check for optional fields and add them if they are set
 368            /*if (isset($_POST['phone']) and (trim($_POST['phone']) !== '')) {
 369                $this->_plainMailTemplate .= "\r\n" . 'Phone : {userPhone}';
 370            }
 371            if (isset($_POST['url']) and (trim($_POST['url']) !== '')) {
 372                $this->_plainMailTemplate .= "\r\n" . 'URL : {userUrl}';
 373            }
 374            /*
 375             * define html mail content template
 376             */
 377            $this->_htmlMailTemplate = '<html><body>';
 378            $this->_htmlMailTemplate .= '<table style="margin:0 auto;padding:20px;width:90%;display:block;color:#000;background-color:#dddfea;font-family:Tahoma;border-radius:10px"><tr>';
 379            $this->_htmlMailTemplate .= '<td style="padding:5px;width:100%;display:block">';
 380            $this->_htmlMailTemplate .= '<p>{userMessage}</p>';
 381            $this->_htmlMailTemplate .= '</td></tr>';
 382            $this->_htmlMailTemplate .= '<tr><td style="margin-top:10px;padding-left:10px;font-weight:700;font-family:seriff;font-style:italic">';
 383            $this->_htmlMailTemplate .= '<h4>From</h4></td></tr>';
 384            $this->_htmlMailTemplate .= '<tr><td><hr />Name : {userFullName}</td></tr>';
 385            $this->_htmlMailTemplate .= '<tr><td>E-Mail : {userEmail}</td></tr>';
 386            // check for optional fields and add them if they are set
 387            /*if (isset($_POST['phone']) and (trim($_POST['phone']) !== '')) {
 388                $this->_htmlMailTemplate .= '<tr><td>Phone : {userPhone}</td></tr>';
 389            }
 390            if (isset($_POST['url']) and (trim($_POST['url']) !== '')) {
 391                $this->_htmlMailTemplate .= '<tr><td>URL : {userUrl}</td></tr>';
 392            }*/
 393            $this->_htmlMailTemplate .= '</table></body></html>';
 394            /*
 395             * define reply html mail content template
 396             */
 397            $this->_replyHtmlMailTemplate = '<html><body>';
 398            $this->_replyHtmlMailTemplate .= '<table style="margin:0 auto;padding:20px;width:100%;display:block;color:#000;font-family:Tahoma">';
 399            $this->_replyHtmlMailTemplate .= '<tr><td style="padding:10px;width:90%;display:block">';
 400            $this->_replyHtmlMailTemplate .= 'Dear&nbsp;{userName}</td></tr>';
 401            $this->_replyHtmlMailTemplate .= '<tr><td><p>We just received your following mail.<br />We\'ll reach you as soon as possible.</p><br /></td></tr>'; 
 402            $this->_replyHtmlMailTemplate .= '<tr><td><i style="font-size:10px">This is an auto generated reply. Please <strong>do not reply to this e-mail</strong></i></td></tr>';
 403            $this->_replyHtmlMailTemplate .= '<tr><td style="padding:15px;font-weight:normal;font-size:11px;border:#ccc 1px solid;border-radius:8px">';
 404            $this->_replyHtmlMailTemplate .= '<p>{userMessage}</p></td></tr>';
 405            $this->_replyHtmlMailTemplate .= '<tr><td style="margin-top:10px;padding-left:10px;font-weight:700;font-family:seriff;font-style:italic">';
 406            $this->_replyHtmlMailTemplate .= '<h4>From</h4></td></tr><tr><td>';
 407            $this->_replyHtmlMailTemplate .= $this->_autoResponder;
 408            $this->_replyHtmlMailTemplate .= '</td></tr>';
 409            $this->_replyHtmlMailTemplate .= '</body></html>';
 410            
 411            // output configurations
 412            
 413            /*
 414             * initialize page contents as null
 415             */
 416            $this->_pageContents	= 	 '';
 417            /*
 418             * set page compression to true
 419             * you may set this false
 420             * if you don't like to compress the page contents
 421             */
 422            $this->_pageCompression =    true;
 423            /*
 424             * Initialize the response variable as null
 425             */
 426            $this->_response = array(
 427                'status'            =>   '',
 428                'message'           =>   '',
 429                'control'           =>   ''
 430            );
 431            
 432        }
 433        
 434        // }}}
 435        // {{{ getObject()
 436        
 437        /**
 438         * Method to return singleton class object.
 439         * returns current class object if already present
 440         * else creates one
 441         * 
 442         * @return object  The current class object
 443         * @access public
 444         * @static
 445         * 
 446         */
 447        public static function getObject()
 448        {
 449            /*
 450             *  check if class not instantiated
 451             */
 452            if (self::$_classObject === null) {
 453                /*
 454                 *  then create a new instance
 455                 */
 456                self::$_classObject = new self();
 457            }
 458            /*
 459             *  return the class object to be used
 460             */
 461            return self::$_classObject;
 462        }
 463        
 464        // }}}
 465        // {{{ _getRandomChars
 466        
 467        /**
 468         * Generate string of random characters
 469         *
 470         * @param int  $length         Length of the string to generate
 471         * @param bool $lowerCaseChars Include lower case characters
 472         * @param bool $upperCaseChars Include uppercase characters
 473         * @param bool $numericChars   Include numbers
 474         * @param bool $specialChars   Include special characters
 475         * 
 476         * @access private
 477         * @return string  The random character string
 478         */
 479        private function _getRandomChars (
 480            $length = 5,
 481            $lowerCaseChars = true,
 482            $upperCaseChars = true,
 483            $numericChars = true,
 484            $specialChars = false
 485        ) {
 486           
 487            /**
 488             * variable to store a random character index every time
 489             * @access private
 490             * @var int  The random character index out of character set
 491             */
 492            $charIndex               =    '';
 493           
 494            /**
 495             * variable to store a random character every time
 496             * @access private
 497             * @var char  The random character out of character set
 498             */
 499            $char                    =    '';
 500           
 501            /**
 502             * variable to store a random character set every time
 503             * @access private
 504             * @var int  The random character setof length 5 out of character set
 505             */
 506            $resultChars             =    '';
 507           
 508            /*
 509             * check if user has opted for lowercase characters
 510             * if true, then add it to the character set
 511             */
 512            if ($lowerCaseChars === true) {
 513                $this->_charSet      .=   $this->_lowerCaseChars;
 514            }
 515            /*
 516             * Check if user has opted for uppercase characters
 517             * If true, add it to the character set
 518             */
 519            if ($upperCaseChars === true) {
 520                $this->_charSet      .=   $this->_upperCaseChars;
 521            }
 522            /*
 523             * Check if user has opted for numeric characters
 524             * If true, add it to the character set
 525             */
 526            if ($numericChars === true) {
 527                $this->_charSet      .=   $this->_numericChars;
 528            }
 529            /*
 530             * Check if user has opted for uppercase characters
 531             * If true, add it to the character set
 532             */
 533            if ($specialChars === true) {
 534                $this->_charSet      .=   $this->_specialChars;
 535            }
 536
 537            /*
 538             * Check if length has given greater than 0 else return null
 539             */
 540            if (($length < 0) || ($length == 0)) {
 541                return $resultChars;
 542            }
 543
 544            /*
 545             * create a loop to get random 5 characters from the character set
 546             * 
 547             */
 548            for ($i = 0; $i < $length; $i++) {
 549                /*
 550                 * get the character randomly
 551                 * by selecting between 0 to length of the charSet
 552                 */
 553                $charIndex           =    rand(0, strlen($this->_charSet));
 554                $char                =    substr($this->_charSet, $charIndex, 1);
 555                $resultChars         .=   $char;
 556            }
 557
 558            return $resultChars;
 559        }
 560        
 561        // }}}
 562        // {{{ respondRequest()
 563                
 564        /**
 565         * Method to respond to the requests via url
 566         * 
 567         * @param bool   $pageCompression Option for the output data to be compressed or not
 568         * @param mixed  $mapOptions      The option to show/hide, logitude, latitude for Google Map
 569         * @param string $companyName     The name of your company
 570         * @param string $address         The address of your company
 571         * @param string $captchaType     The type of captcha wanted, possible values: php, js
 572         * @param string $mailType        The type of mail to be sent, possible values: html, text
 573         * @param string $emails          The address of mail to send, possible values: as specified
 574         * @param string $autoResponder   The address of reply mail to be sent back to the visitor
 575         * 
 576         * @return mixed  May output page HTML string or JSON validation data
 577         * @access public
 578         */
 579        public function respondRequest(
 580            $captchaType,
 581            $mailType,
 582            $emails,
 583            $autoResponder
 584        ) {
 585            
 586            /*
 587             * assign captcha type as user has defined
 588             * you may use javascript captcha too
 589             * possible values: php, js
 590             */
 591            $this->_captchaType     =   $captchaType;
 592            
 593            /*
 594             * assign mail type to catch user preferences
 595             * change it if you want plain mail witout any formatting
 596             */
 597            $this->_mailType        =    $mailType;
 598            
 599            /*
 600             * set page compression to user defined
 601             * you may set this false
 602             * if you don't like to compress the page contents
 603             */
 604            $this->_receiver          =    $emails;
 605            
 606            /*
 607             * set page compression to user defined
 608             * you may set this false
 609             * if you don't like to compress the page contents
 610             */
 611            $this->_autoResponder   =    $autoResponder;
 612            
 613            /*
 614             * catch the get variable
 615             * if set then act accordingly
 616             */
 617            if (isset($_GET['req'])) {
 618                /*
 619                 * switch over the request and respond accordingly
 620                 */
 621                switch ($_GET['req']) {
 622                case 'captcha':
 623                    /*
 624                     * call the method to create the captcha image
 625                     */
 626                    $this->createCaptcha();
 627                    break;
 628                case 'captchaimg':
 629                    /*
 630                     * check if user has opted php captcha and GD library present
 631                     * if user has them both then
 632                     * call the method to create the captcha image
 633                     * else just return the captcha characters
 634                     */
 635                    
 636                    if (extension_loaded('gd') and ($this->_captchaType==='php')) {
 637                        /*
 638                         * return an image tag
 639                         */
 640                        echo '<img src="' . $_SERVER['PHP_SELF'] . '?req=captcha&tm='.time().'" alt="Captcha Image" title="Click to get new challenge" />';
 641                    } else {
 642                        /*
 643                         * take two variables with random integer values,
 644                         * then add them and save in session to verify
 645                         * @var int  Integers to work as captcha
 646                         */
 647                        $a          =   rand(1, 9);
 648                        $b          =   rand(1, 9);
 649                        /*
 650                         * Assign the characters to a session variable
 651                         */
 652                        $_SESSION['CaptchaChars']	=	$a+$b;
 653                        /*
 654                         * Close the session write buffer to avoid overwriting
 655                         */
 656                        session_write_close();
 657                        /*
 658                         * simply output the characters only
 659                         */
 660                        echo '<h5>'.$a.' + '.$b.' =</h5>';
 661                    }
 662                    break;
 663                
 664                default:
 665                     /*
 666                     * call the method to validate and send the message
 667                     */
 668                    $this->sendMail();
 669                    break;
 670                }
 671                /*
 672                 * validate the name must not be empty
 673                 * and send json data
 674                 */
 675            } else {
 676                /*
 677                 * call the method to validate and send the message
 678                 */
 679                $this->sendMail();
 680            }
 681        }
 682        
 683        // }}}
 684        // {{{ createCaptcha()
 685        
 686        /**
 687         * Method to create captcha image for bot verification
 688         *
 689         * @return mixed  Image for captcha
 690         * @throws Exception  GD or general exceptions
 691         * @access public
 692         */
 693        public function createCaptcha()
 694        {
 695            try {
 696                /*
 697                 * Assign the characters to a session variable
 698                 */
 699                $_SESSION['CaptchaChars']	=	$this->_getRandomChars(5, false, true, true, false);
 700                /*
 701                 * Close the session write buffer to avoid overwriting
 702                 */
 703                session_write_close();
 704                
 705                /*
 706                 * Create a 100 X 30 image and assign it to a var
 707                 */
 708                $img				=	 imagecreatetruecolor($this->_captchaWidth, $this->_captchaHeight);
 709                /*
 710                 * create a white color
 711                 */
 712                $white              =    imagecolorallocate($img, 255, 255, 255);
 713                
 714                /*
 715                 * Create a black color to write the characters prominently
 716                 */
 717                $black              =    imagecolorallocate($img, 0, 0, 0);
 718                /*
 719                 * fill the rectangular image with white background
 720                 */
 721                imagefilledrectangle($img, 0, 0, 399, 30, $white);
 722                
 723                /*
 724                 * Write the string inside the image
 725                 * with black color
 726                 */
 727                imagettftext(
 728                    $img,
 729                    $this->_captchaFontSize,
 730                    $this->_captchaCharAngle,
 731                    2,
 732                    25,
 733                    $black,
 734                    $this->_captchaFontLocation,
 735                    $_SESSION['CaptchaChars']
 736                );
 737                /*
 738                 * generating dots randomly in background
 739                 * to make an image noise
 740                 * if you want more noise replace the argument 5
 741                 * as per your requirement
 742                 */ 
 743                for ( $i=0; $i<5; $i++ ) {
 744                    imagefilledellipse(
 745                        $img,
 746                        mt_rand(0,  $this->_captchaWidth),
 747                        mt_rand(0,  $this->_captchaHeight),
 748                        2,
 749                        3,
 750                        0
 751                    );
 752                }
 753                
 754                /*
 755                 * generating lines randomly in background of image
 756                 * for more noise
 757                 * if you want more noise replace the argument 10
 758                 * as per your requirement
 759                 */ 
 760                for ( $i=0; $i<10; $i++ ) {
 761                    imageline(
 762                        $img,
 763                        mt_rand(0, $this->_captchaWidth),
 764                        mt_rand(0, $this->_captchaHeight),
 765                        mt_rand(0, $this->_captchaWidth),
 766                        mt_rand(0, $this->_captchaHeight),
 767                        0
 768                    );
 769                }
 770                /*
 771                 * Output the image
 772                 */
 773                header('Content-Type: image/gif');
 774                /*
 775                 * output a gif image
 776                 */
 777                imagegif($img);
 778                /*
 779                 * destroy the image to save server space
 780                 */
 781                imagedestroy($img);
 782            }
 783            catch(Exception $ex) {
 784                die('Oh no.. Something gone wrong... Details: ' . $ex->getMessage());
 785            }
 786        }
 787        
 788        // }}}
 789        // {{{ _cleanSubmittedData()
 790        
 791        /**
 792         * The following method makes a variable safe
 793         * as that may contain unacceptable formats or data
 794         * to prevent security holes those may be a threat
 795         * 
 796         * @param mixed $submittedData The data submitted by the user to be filtered
 797         * 
 798         * @return mixed  Cleaned data submitted by the user
 799         * @access protected
 800         */
 801
 802        protected function _cleanSubmittedData($submittedData)
 803        {
 804            try {
 805                /*
 806                 * check if the data is an array or not
 807                 */
 808                if (!is_array($submittedData)) {
 809                    /*
 810                     * if that is not an array, treat that as a string
 811                     */
 812                    $this->_str       =   $submittedData;
 813                     /*
 814                      * trim the spaces if any
 815                      */
 816                    $this->_str       =   trim($this->_str);
 817
 818                    /*
 819                     * check if magic quotes are on or not
 820                     * if on then it must have inserted slashes before quotes and slashes
 821                     */
 822                    if (get_magic_quotes_gpc()) {
 823                        /*
 824                         * if magic quotes are on, it inserts a slash before any quotes, hence remove them
 825                         */
 826                        $this->_str   =   stripslashes($this->_str);
 827                    }
 828                    
 829                    /*
 830                     * escape the data and insert null where restricted characters found
 831                     */
 832                    $this->_str       =   str_ireplace($this->_restrictedChars, "", $this->_str);
 833
 834                    /*
 835                     * allow the tags for user and strip off rest of them
 836                     */
 837                    $this->_str     =   strip_tags($this->_str, $this->_allowedHTML);
 838                    /*
 839                     * now return the cleaned data
 840                     */
 841                    return $this->_str;
 842
 843                } else {
 844                    /**
 845                     * var to keep cleaned data array for a temporary period
 846                     * so that they can be returned in cleaned state
 847                     * and acceptable format
 848                     * 
 849                     * @var mixed  The injection cleaned data array
 850                     * @access private
 851                     */
 852                    $cleanArr       =   array();
 853                    /*
 854                     * if the data is an array
 855                     * fetch the array values one by one by the loop
 856                     */
 857                    foreach ($submittedData as $pointer=>$str) {
 858                        /*
 859                         * Recursively call clean function if the data is array
 860                         */
 861                        $cleanArr[$pointer]=$this->_cleanSubmittedData($str);
 862                    }
 863                    /*
 864                     * return the cleaned data array
 865                     */
 866                    return $cleanArr;
 867                }
 868            }
 869            catch(Exception $ex) {
 870                /*
 871                 * Catch any Exceptions occured
 872                 */
 873                die('There seems an error while cleaning user submitted data. Description: '. $ex->getMessage());
 874            }
 875        }
 876        
 877        public function saveToFile($submittedData)
 878        {
 879            $file = 'participants.txt';
 880            // Open the file to get existing content
 881            $current = file_get_contents($file);
 882            // Append a new person to the file
 883            $current .= print_r($submittedData,true);
 884            $current .= "\n";
 885            // Write the contents back to the file
 886            file_put_contents($file, $current);
 887        }
 888        
 889        
 890        
 891        // }}}
 892        // {{{ sendMail()
 893        
 894        /**
 895         * Method to send normal mail
 896         * 
 897         * @return string  JSON data object for success or failure
 898         * @access public
 899         */
 900        public function sendMail()
 901        {
 902            /*
 903             * clean up the user submitted data with the defined method
 904             */
 905            $submittedData          =   $this->_cleanSubmittedData($_POST);
 906            /*
 907             * validate the form data
 908             */
 909            if (!isset($submittedData['contact_name']) or ($submittedData['contact_name'] === '')) {
 910                /*
 911                 * fill out the response array variable
 912                 * with alert/error message having bootstrap styles
 913                 */
 914                $this->_response['status']	=	'error';
 915                $this->_response['message']	=	'<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
 916                $this->_response['message']	.=	'Please Enter your Name'.$submittedData['contact_name'];
 917                $this->_response['message']	.=	'</div>';
 918                
 919                /*
 920                 * output the json data by converting the response array into a json format
 921                 */
 922                echo json_encode($this->_response);
 923                /*
 924                 * exit the script
 925                 */
 926                exit(0);
 927            }
 928            
 929            /*
 930             * validate email via php predefined (inbuilt) function
 931             */
 932            if (!isset($submittedData['contact_email']) or (strlen(filter_var($submittedData['contact_email'], FILTER_VALIDATE_EMAIL)) < 1)) {
 933                $this->_response['status']	=	'error';
 934                $this->_response['message']	=	'<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
 935                $this->_response['message']	.=	'Please Enter your Valid E-Mail';
 936                $this->_response['message']	.=	'</div>';
 937                echo json_encode($this->_response);
 938                exit(0);
 939            }
 940            
 941            /*
 942             * validate the phone number correct or not if entered
 943             * enable if you want to validate phone number
 944             */
 945            /*if (isset($submittedData['phone']) and !empty($submittedData['phone']) and (!preg_match('/^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$/', $submittedData['phone']))) {
 946                $this->_response['status']	=	'error';
 947                $this->_response['message']	=	'<div class="alert alert-danger alert-dismissable">';
 948                $this->_response['message']	.=	'Please Enter a correct phone number';
 949                $this->_response['message']	.=	'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button></div>';
 950                $this->_response['control']	=	'phone';
 951                echo json_encode($this->_response);
 952                exit(0);
 953            }
 954            /*
 955             * validate the url correct or not if entered
 956             * enable this if you want to validate url
 957             */
 958            /*if (isset($submittedData['url']) and !empty($submittedData['url']) and (!preg_match('/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/', $submittedData['url']))) {
 959                $this->_response['status']	=	'error';
 960                $this->_response['message']	=	'<div class="alert alert-danger alert-dismissable">';
 961                $this->_response['message']	.=	'Please Enter a correct URL';
 962                $this->_response['message']	.=	'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button></div>';
 963                $this->_response['control']	=	'url';
 964                header("Content-Type: application/json");
 965                echo json_encode($this->_response);
 966                exit(0);
 967            }
 968            /*
 969             * validate subject for empty value
 970             */
 971            if (!isset($submittedData['contact_subject']) or ($submittedData['contact_subject']==='')) {
 972                $this->_response['status']	=	'error';
 973                $this->_response['message']	=	'<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
 974                $this->_response['message']	.=	'Please Enter a Subject';
 975                $this->_response['message']	.=	'</div>';
 976                echo json_encode($this->_response);
 977                exit(0);
 978            }
 979            /*
 980             * validate the message empty or blank
 981             */
 982            if (!isset($submittedData['contact_message']) or ($submittedData['contact_message'] === '')) {
 983                $this->_response['status']	=	'error';
 984                $this->_response['message']	=	'<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
 985                $this->_response['message']	.=	'Please Enter your Message';
 986                $this->_response['message']	.=	'</div>';
 987                echo json_encode($this->_response);
 988                exit(0);
 989            }
 990            /*
 991             * Enable this if you want to validate captcha
 992             */
 993            /*if (!isset($submittedData['captcha']) or !isset($_SESSION['CaptchaChars']) or ($submittedData['captcha'] !== (string)$_SESSION['CaptchaChars'])) {
 994                $this->_response['status']	=	'error';
 995                $this->_response['message']	=	'<div class="alert alert-danger alert-dismissable">';
 996                $this->_response['message']	.=	'Please Enter The Captcha Correctly';
 997                $this->_response['message']	.=	'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button></div>';
 998                $this->_response['control']	=	'captcha';
 999                echo json_encode($this->_response);
1000                exit(0);
1001            }
1002            
1003            /*
1004             * Build up the mail and
1005             * Set headers first, else the mail may be caught as spam
1006             */
1007            $headers			=	array();
1008            $headers[]			=	"MIME-Version: 1.0";
1009            // set content type according to the option supplied
1010            if ($this->_mailType === 'html') {
1011                $headers[]			=	"Content-type: text/html; charset=iso-8859-1";
1012            } else {
1013                $headers[]			=	"Content-type: text/plain; charset=iso-8859-1";
1014            }
1015            $headers[]			=	"From: {$submittedData['contact_name']} <{$submittedData['contact_email']}>";
1016            $headers[]			=	"Reply-To: {$submittedData['contact_name']} <{$submittedData['contact_email']}>";
1017            $headers[]			=	"Subject: {$submittedData['contact_subject']}";
1018            /*
1019             * Set final headers by separating them by newlines into a single string
1020             */
1021            $finalHeaderString		=	implode("\r\n", $headers);
1022            /*
1023             * Set up the message according to the template
1024             */
1025            if ($this->_mailType === 'html') {
1026                // set up the html template and add contents
1027                $message			= str_replace(
1028                    array(
1029                        '{userMessage}',
1030                        '{userFullName}',
1031                        '{userEmail}',
1032                        //'{userPhone}',
1033                        //'{userUrl}'
1034                        ),
1035                    array(
1036                        nl2br($submittedData['contact_message']),
1037                        $submittedData['contact_name'],
1038                        $submittedData['contact_email'],
1039                        //$submittedData['phone'],
1040                        //$submittedData['url']
1041                        ),
1042                    "{$this->_htmlMailTemplate}"
1043                );
1044                
1045            } else {
1046                // set up the plain mail template
1047                $message			= str_replace(
1048                    array(
1049                        '{userMessage}',
1050                        '{userFullName}',
1051                        '{userEmail}',
1052                        //'{userPhone}',
1053                        //'{userUrl}'
1054                        ),
1055                    array(
1056                        $submittedData['contact_message'],
1057                        $submittedData['contact_name'],
1058                        $submittedData['contact_email'],
1059                        //$submittedData['phone'],
1060                        //$submittedData['url']
1061                        ),
1062                    "{$this->_plainMailTemplate}"
1063                );
1064            }
1065            
1066            
1067            $this->saveToFile($submittedData);
1068            
1069            /*
1070             * Mail it and catch the result to further check if mail has sent or not
1071             */
1072            $mailed			=	mail($this->_receiver, $submittedData['contact_subject'], $message, $finalHeaderString);
1073            /*
1074             * Now check if the mailing was successful
1075             */
1076//            if ($mailed) {            
1077                /*
1078                 * if sender has checked the checkbox to get acknowledgement,
1079                 * then send a confirmation mail
1080                 * You dont have any checkbox hence commented the if condition
1081                 */
1082                //if (isset($submittedData['acknowledge']) and ($submittedData['acknowledge']==='1')) {
1083                    
1084                    // Build up the mail and
1085                    $headers			=	array();
1086                    $headers[]		=	"MIME-Version: 1.0";
1087                    $headers[]		=	"Content-type: text/html; charset=iso-8859-1";
1088                    $headers[]		=	"From: ".$this->_autoResponder;
1089                    $headers[]		=	"Reply-To: {$this->_receiver}";
1090                    $headers[]		=	"Subject: reply: {$submittedData['contact_subject']}";
1091                    $finalHeaderString	=	implode("\r\n", $headers);
1092                    // set up the html reply mail template
1093                    $message		= str_replace(
1094                        array(
1095                            '{userName}',
1096                            '{userMessage}'
1097                            ),
1098                        array(
1099                            $submittedData['contact_name'],
1100                            nl2br($submittedData['contact_message'])
1101                            ),
1102                        $this->_replyHtmlMailTemplate
1103                    );
1104                    /*
1105                     * Mail it and catch the result to further check if mail has sent or not
1106                     */
1107                    $mail			=	mail($submittedData['contact_email'], 'reply: ' . $submittedData['contact_subject'], $message, $finalHeaderString);
1108                //}
1109                
1110                $this->_response['status']	=	'success';
1111                $this->_response['message']	=	'<div class="alert alert-success alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
1112                $this->_response['message']	.=	'Дякуємо за участь! Кожна людина для нас важлива! Чекайте на дзвінок.';
1113                // if acknowledgement opted, then output a message to view inbox  ## Commented as you need not
1114                //if (isset($submittedData['acknowledge']) and ($submittedData['acknowledge']==='1')) {
1115                //$this->_response['message']	.=	' Please check your acknowledgement in your email (inbox/spam folder).';
1116                //}
1117                $this->_response['message']	.=	'</div>';
1118                echo json_encode($this->_response);
1119                exit(0);
1120//            } else {
1121//                /*
1122//                 * Else give Out an error message and reset
1123//                 */
1124//                $this->_response['status']	=	'success';
1125//                $this->_response['message']	=	'<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
1126//                $this->_response['message']	.=	'Some Error Occured!';
1127//                $this->_response['message']	.=	'</div>';
1128//                echo json_encode($this->_response);
1129//                exit(0);
1130//            }
1131        }
1132        
1133        // }}}
1134        // {{{ __clone()
1135        
1136        /**
1137         * According to singleton pattern instance, cloning is prihibited
1138         *
1139         * @return string  A message that states, cloning is prohibited
1140         * @access public
1141         */
1142        private function __clone()
1143        {
1144            /*
1145             * only set an error message
1146             */
1147            die('Cloning is prohibited for singleton instance.');
1148        }
1149        
1150        // }}}
1151        
1152    }
1153}
1154//echo 'error:'.implode(', '$_POST);exit();
1155/*
1156 * Call Setup for the class
1157 * you must set these options
1158 * before using the class
1159 * This configuration should be present
1160 * when you call the class object
1161 * Otherwise you may not get your desired results
1162 * 
1163 * please contact the author in case
1164 * any difficulties
1165 */
1166/**
1167 * Set the type of the captcha needed
1168 * @var string The type of captcha needed
1169 */
1170$captchaType                        = null;
1171/**
1172 * Set the reciever email(s) to receive the mail(s)
1173 * 
1174 * @var string The e-mails of contact mail receiver
1175 */
1176$emails                             = 'yourname@yourdomain.com';
1177/**
1178 * Set auto reply system name and e-mail
1179 * from where the acknowledgement to be sent.
1180 * Generally it is set to be the id where no reply to be sent
1181 * Change it according to your needs
1182 * 
1183 * @var string  The e-mail for auto reply system
1184 */
1185$autoResponder                      =   'noreply@yourdomain.com';
1186
1187/**
1188 * Set desired type of mail to send
1189 * Possible values: html/text
1190 * Change according to need
1191 * 
1192 * @var string  The type of mail to be sent
1193 */
1194$mailType                           =   'html';
1195
1196/*
1197 * Now call the class method  to implement all the options
1198 * and get the response as per need
1199 */
1200Contact::getObject()->respondRequest(
1201    $captchaType,
1202    $mailType,
1203    $emails,
1204    $autoResponder
1205);