Location: PHPKode > scripts > Comments script with pagination > comm/class.SetComm.php
<?php
/* SetComm Class (adds, modify, delete comments) - www.coursesweb.net/php-mysql/ */
class SetComm extends BaseCM {
  public $table = 'comments';           // HERE add the mysql table name
  protected $back = '';             // used to go to previous page

  public function __construct($conn_data) {
    parent::__construct($conn_data);        // include the parent __construct() instructions

    // if form fields are received, checks form data. If GET for Unsubscribe, calls unsubscribe()
    if(isset($_POST['namec']) && isset($_POST['emailc']) && isset($_POST['coment']) && isset($_POST['codevc'])) {
      // checks form data, if no error, calls addComments(), else, returns error
      $this->checkForm($_POST);
      if($this->eror === false) $this->addComments($_POST);
      else echo $this->eror;
    }
    else if(isset($_GET['unsub'])) echo $this->unsubscribe($_GET['unsub']);
    else if(isset($_SESSION['adminlog'])) {      // if admin logged
      // if form fields to modify content, calls method that modify comment
      // else, if POST 'id_dcm', sets in $delform a form to delete that require admin password, and calls delComm()
      if(isset($_POST['idc']) && isset($_POST['namec']) && isset($_POST['emailc']) && isset($_POST['coment']) && isset($_POST['nrp'])) $this->modifyComm($_POST);
      if(isset($_POST['id_dcm'])) {
        $this->delform = '<br/><form action="" method="post">
          <b>'.$this->clsite['comments']['delcomm'].'<b><br />
          <input type="hidden" name="id_dcm" id="id_dcm" value="'.$_POST['id_dcm'].'" />
          <input type="hidden" name="img_dcm" id="img_dcm" value="'.$_POST['img_dcm'].'" />
          <input type="hidden" name="sbmt" value="delcmm" />
          <input type="password" name="pass"> &nbsp; <input type="submit" value="'.$this->clsite['delete'].'" />
          </form>';
        $this->delComm($_POST);
      }
    }
    else echo $this->setEror($this->clsite['comments']['eror_form']);
  }

  // checks form data
  protected function checkForm($frm) {
    $re = '';             // will store the errors to return

    // checks the name, email, comments, and verification code
    if (!preg_match('/^[_a-zA-Z0-9-]{3,32}$/', $frm['namec'])) $re .= $this->clsite['comments']['eror_name'].'<br/>';
    if($frm['emailc']!='optional' && $frm['emailc']!='' && !preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $frm['emailc'])) $re .= $this->clsite['eror_email'].'<br/>';
    if(strlen($frm['coment'])<5 || strlen($frm['coment'])>600) $re .= $this->clsite['comments']['eror_coment'].'<br/>';
    // checks verification code
    if(isset($_POST['codevc'])) if($_POST['codevc'] !== $_SESSION['codevc'])  $re .= $this->clsite['eror_codev'].'<br/>';

    // if $re is empty, returns true; else, returns error
    if($re == '') return true;
    else return $this->setEror($re);
  }

  // the method to add the comment
  protected function addComments($frm) {
    $dt = time();              // store current time
    $reout = "<script type=\"text/javascript\"> 
      window.parent.resetFrm('%s');                    // sets output that will be returned (a call to JS function)
    </script>";

    // if session, or cookie "addcomm" exists, and their value is higher then time()+300
    // sets to return error message, else, add the comments
    if((isset($_SESSION['addcomm']) && ($_SESSION['addcomm']+300)>$dt) || (isset($_COOKIE['addcomm']) && ($_COOKIE['addcomm']+300)>$dt)) {
      echo sprintf($reout, $this->clsite['comments']['eror_sesadd']);
    }
    else {
      // sets data to be added in database
      $frm['sitec'] = (isset($frm['sitec']) && $frm['sitec']!='optional') ? 'http://'.str_replace('http://', '', $frm['sitec']) : '';
      if($frm['emailc']=='optional') $frm['email'] = '';

      // sets the value for 'amail' column (1=show the email, 2=notify when comments are added, 3= 1 and 2)
      $amail = 0;
      // if notiffy-email, sets $amail 2, if show-email, increment $amail (this way can be 1 or 3)
      if(isset($_POST['amail']) && $_POST['amail']==2) $amail = 2;
      if(isset($_POST['showmail']) && $_POST['showmail']==1) $amail++;

      // if image is added (a string with atleast 4 characters [minimum extension])
      // sets data for uploading, and calls uploadFile() to upload it
      $eror_upimg = '';           // in case of errors, store them to be aded in JS alert()
      if(isset($_FILES['upimg']) && strlen($_FILES['upimg']['name'])>4) {
        GLOBAL $imguprule;          // array with permissions for image
        $fileup = $imguprule['dir'].$frm['codevc'].$_FILES['upimg']['name'];

        // if upload without errors, sets a BBCODE to include the image
        if($this->uploadFile($_FILES['upimg'], $imguprule, $fileup)) {
          $frm['coment'] = '[imup='.$fileup.']'.$_FILES['upimg']['name'].'[/imup]'.$frm['coment'].'[brc]';
        }
        else $eror_upimg = $this->eror;
      }

      // gets all e-mails to which to send mail notifications, adds them into array with key=['id_dt']
      // "id_dt" is ussed in link for unsubscribe
      $tosend = array();
      $sql = "SELECT `id`, `dt`, `email` FROM `$this->table` WHERE `page`='".$frm['pg']."' AND LENGTH(`email`)>4 AND `amail`>1 LIMIT 10";
      $resql = $this->sqlExecute($sql);
      if($this->affected_rows > 0) {
        for($i=0; $i<$this->affected_rows; $i++) { $tosend[$resql[$i]['id'].'_'.$resql[$i]['dt']] = $resql[$i]['email']; }
      }

      // add comments data in database
      $sql = "INSERT INTO `$this->table` (page, name, email, coment, site, dt, ip, amail) VALUES ('".$frm['pg']."', '".$frm['namec']."', '".$frm['emailc']."', '".$frm['coment']."', '".$frm['sitec']."', $dt, '".$this->ip."', ".$amail.")";

      if($this->sqlExecute($sql)) {
        // set session and cookie with the time when added comment,
        // that is checked to not let adding another comment in 5 minutes
        $_SESSION['addcomm'] = $dt;
        setcookie("addcomm", $_SESSION['addcomm'], $dt+60*5, "/");

        echo sprintf($reout, sprintf($this->clsite['comments']['jsadd'], $frm['namec'])."\\n $eror_upimg");      // confirm comment added
        flush();       // transmit the output to browser, than execute the rest of instructions

        // define the URL of the pages with comment, and calls resetFrm() JS function
        $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on') ? 'https' : 'http';    // site protocol
        $pgcomm = $protocol.'://'.$this->site.urldecode($frm['pg']).'#cm';

        if(count($tosend) > 0) {
          $tosend = array_unique($tosend);           // remove duplicate e-mails
          $this->notifyMail($tosend, $pgcomm);     // sends mail notifications
        }
      }
      else echo sprintf($reout, $this->eror."\\n $eror_upimg");
    }
  }

  // receive array with [id_dt]=>e-mails for notification, and comment page URL. Calls the method to send emails
  protected function notifyMail($tosend, $pgcomm) {
    // sets subject, parse $tosend, to create the link for unsubscribe, and calls method to send e-mail
    $subject = sprintf($this->clsite['comments']['notifysub'], $this->site);
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on') ? 'https' : 'http';    // site protocol
    $to = array();          // store e-mail address
    $msgs = array();        // to store message to be send, associated by $i to each e-mail
    $i = 0;

    foreach($tosend AS $unsub=>$e) {
      $to[$i] = $e;
      $pguns = $protocol.'://'.$this->site.$_SERVER['PHP_SELF'].'?unsub='.$unsub;
      $msgs[$i] = sprintf($this->clsite['comments']['notifymsg'], $this->site, $this->site, '<a href="'.$pgcomm.'" title="Comment">'.$pgcomm.'</a>', '<a href="'.$pguns.'" title="Unsubscribe">'.$pguns.'</a>');
      $i++;
    }
    $this->sendMail($to, CMAMAIL, $this->site, $subject, $msgs);
  }

  // unsubscribe the notification, receive the "ID_DT", select the page where that ID and DT
  // then decrease 'amail' with 2 where that page, e-mail, and 'amail'>1
  protected function unsubscribe($unsub) {
    // sets variable to return an JS alert, and redirect to homepage
    $reout = "%s <script type=\"text/javascript\">
      alert('%s');
      window.location = '/';
    </script>";
    $iddt = explode('_', $unsub);          // separe 'id' and 'dt'

    $sql = "SELECT `page`, `email` FROM `$this->table` WHERE `id`=".$iddt[0]." AND `dt`=".$iddt[1]." LIMIT 1";
    if($resql = $this->sqlExecute($sql)) {
      if($this->affected_rows > 0) {
        // if session that unsubscribed from the page with "id", return message, else perform subscription
        if(isset($_SESSION['unsub']) && $_SESSION['unsub'] == $resql[0]['page']) {
          return sprintf($reout, $this->clsite['comments']['eror_sesunsub'], $this->clsite['comments']['eror_sesunsub']);
        }
        else {
          $sql = "UPDATE `$this->table` SET `amail`=`amail`-2 WHERE `page`='".$resql[0]['page']."' AND `email`='".$resql[0]['email']."' AND `amail`>1";
          if($this->sqlExecute($sql)) {
            $_SESSION['unsub'] = $resql[0]['page'];      // set session to know that unsubscribed from the page with $id/2
            return sprintf($reout, $this->clsite['comments']['unsubscribe'], $this->clsite['comments']['unsubscribe']);
          }
          else return $this->clsite['comments']['eror_unsub'];
        }
      }
      else return $this->clsite['comments']['eror_unsubscribe'];
    }
    else return $this->clsite['comments']['eror_unsubscribe'].$this->eror;
  }

  // modify comment
  protected function modifyComm($frm) {
    // checks form data, if no error, modify comment, else, output error
    $this->checkForm($frm);
    if($this->eror === false) {
      // sets form fields to be used in UPDATE query
      $frm['idc'] = intval($frm['idc']);
      $frm['sitec'] = 'http://'.str_replace('http://', '', $frm['sitec']);    // Add 'http://' in URL

      // sets UPDATE and calls the method to perform the query
      $sql = "UPDATE `comments` SET `name`='".$frm['namec']."', `email`='".$frm['emailc']."', `coment`='".$frm['coment']."', `site`='".$frm['sitec']."' WHERE `id`=".$frm['idc']." LIMIT 1";

      // if the comment is modified, display a JS confirmation-alert, and refresh
      if($this->sqlExecute($sql)) {
        echo '<script type="text/javascript">
          window.alert("'.$this->clsite['comments']['jsmodify'].'");
          window.parent.getcoms = new Array();
          window.parent.toAjaxCM('.$frm['nrp'].');
          window.parent.remBoxCM();
        </script>';
      }
      else echo $this->clsite['comments']['eror_modify']. $this->eror;
    }
    else echo $this->eror;
  }

  // delete comment
  protected function delComm($frm) {
    // if form data with fields with admin pass, IDs, and img of the comments to delete
    if(isset($frm['pass']) && isset($frm['id_dcm']) && isset($frm['img_dcm'])) {
      // if correct admin password, delete comments in database
      if($frm['pass'] == CMAPASS) {
        $sql = "DELETE FROM `$this->table` WHERE `id` IN(".$frm['id_dcm'].")";
        if($this->sqlExecute($sql)) {
          $delfile = $this->clsite['comments']['jsdelete'];            // messages for detetting files

          // if "img_dcm" not empty, gets each img adress (separatted by comma), and delete it
          if($frm['img_dcm'] != '') {
            $imgs = explode(',', $frm['img_dcm']);
            $nr_imgs = count($imgs);
            if($nr_imgs > 0) {
              for($i=0; $i<$nr_imgs; $i++) {
                if(unlink($imgs[$i])) $delfile .= '\n'.$imgs[$i]. $this->clsite['delfile'];
                else $delfile .= '\n'. $this->clsite['eror_delfile']. $imgs[$i];
              }
            }
          }

          echo '<script type="text/javascript">
            window.alert("'.$delfile.'");
            window.parent.location.reload();
          </script>';
        }
        else echo $this->clsite['comments']['eror_delete']. $this->eror;
      }
      else echo '<center><h3 style="margin:0px auto;color:red;">'.$this->clsite['eror_pass'].'</h3>'.$this->delform.'</center>';
    }
    else if(isset($frm['id_dcm']) && isset($frm['img_dcm'])) {
      // if form fields only with IDs, and img of the comments to delete, stores in another form to confirm admin
      echo '<br /><center>'.$this->delform.'</center>';
    }
  }
}
Return current item: Comments script with pagination