1.44 build 178


Please rate DAlbum at HotScripts.com
Please rate DAlbum at @ PHP-Resource.de
Rate DAlbum @ The PHP Resource Index
Script Rating:
Allow users to add comments   

The purpose of this sample is to demonstrate how to add simple image commenting system to your album. Number of image comments is displayed on the index page.

Administrator can see IP addresses of comment senders and delete unwanted messages. As comments are stored in a simple text files one line per comment, administration can also be done with a text editor over FTP.

Depending on configuration anonymous users may not be allowed to post comments or even view comments at all. Administrator may be notified by e-mail when a new comment is posted.

Please check demo for an example.

Comments are stored in .cmt files next to original album images. For example, comments for /photo/album1/picture1.jpg are stored in /photo/album1/picture1.cmt.

Instructions

If you don't feel like patching configuration files yourself, download and install already patched set of templates from comments.zip.

1. Edit your t_showimg.php page template and insert the following code snippet at the beginning of the file (after the title comments:)
 
<?php
    ////////////// Image Comments customization 1 of 2 begins ///////////////
    include(DALBUM_ROOT . "/config/comments.php");

    $nCommentsAuth=1; /*   0=all users can view and post messages,
                           1=all users can view, but only authenticated can post
                           2=anonymous users do not see any comments */

    $sAdminEmail="";  /* Put admin e-mail here. Ex. john@hotmail.com */
    $sFromEmail="DAlbum <dalbum@mysite.com>";

     if (DAlbum_Comments_Plugin_Send(    $nCommentsAuth,
                                        $sAdminEmail,
                                        $sFromEmail ))
    {
        header("Location: " . base64_decode(encodeCurrentLocation()));
        return;
    }
    ////////////// Image Comments customization 1 of 2 ends ///////////////
?>

Modify configuration variables appropriately.

Then insert the following piece of code just before '<!-- Row 3: copyright -->' line:

 
<?php
////////////// Image Comments customization 2 of 2 begins ///////////////
DAlbum_Comments_Plugin_Display($nCommentsAuth);
////////////// Image Comments customization 2 of 2 ends ///////////////
?>

2. Edit your custom.php and find and uncomment customTitle function. Replace its body with the following code snippet:

 

3. Edit your custom.css and append the following lines to the file:

 
.imagecommentsRow
{
    /* Uncomment the next line for main_blue.css */
    /* background-color: #444444; */

    /* Uncomment the next line for main_cyan.css */
    /* background-color: #CCDDFF; */
}
table.imagecomments
{
    margin-top: 20px;
    font-size: 80%;
    border-top: 2px solid black;

    /* Uncomment the next line for main_cyan.css */
    /* color: black; */
}

table.imagecomments th
{
    padding: 10px;
}

table.imagecomments td.imagecomment
{
    border-top: 1px dashed black;
}

table.imagecomments td.imagecommentform
{
    border-top: 1px dashed black;
}

table.imagecomments td.imagecommentform table
{
    font-size: 100%;
}

You may need to adjust colors in this snippet to match your color scheme.

4. Create comments.php file in ./config directory and paste the following text:
 
<?php

if (!defined('DALBUM_ROOT')) die("Security violation!");

// localization strings have been added to distribution already
/*
$lang['cCommentsImageComments']="Image comments";
$lang['cCommentsLoginToAddComments']='Please #loginbutton# to add your comments.<BR>&nbsp;';
$lang['cCommentsYourName']='Your name:';
$lang['cCommentsComment']='Comment:';
$lang['cCommentsSendButtonText']='Send';
$lang['cCommentsDeleteButtonText']='Delete';
$lang['cCommentsMailSubject']="New comment about image #image# ( Album: #album# )";
$lang['cCommentsMailBody']   ="New comment posted by #user#, IP: #ip#,".
                              "DNS: #dns#\n\n#body#\n\nPage URL: #url#\n";
$lang['cCommentsDateFormat'] ="F j, Y, g:i a";
*/

function DAlbum_Comments_Plugin_Send(   $nCommentsAuth,
                                        $sAdminMail,
                                        $sFromLine )
{
    global $lang,$sUserName,$image,$bAdminMode,$album;
    //
    $bShowComments=($nCommentsAuth<2 || !empty($sUserName));
    $bShowForm=($nCommentsAuth==0 || !empty($sUserName));
    $bShowLogin=($nCommentsAuth==1 && empty($sUserName));

    if (!$bShowComments || !$bShowForm)
        return false;

    // $image variable is set to displayed image
    $imagefname=absfname($image->m_sFullFilename);
    $textfname=dirname_ex($imagefname) . "/" . getfname($imagefname) . ".cmt";

    // Add new comments
    if (!isset($_POST['comment']))
        return false;

    $arr=array();
    $arr[]=$_POST['realname'];

    // Add IP address
    $ip=$_SERVER['REMOTE_ADDR'];
    if (@$_SERVER["HTTP_X_FORWARDED_FOR"])
        $ip=$_SERVER["HTTP_X_FORWARDED_FOR"];

    $arr[]=$ip;

    // Change to your preferred date format here
    $arr[]=date($lang['cCommentsDateFormat']);

    $body=trim($_POST['comment']);
    if (empty($body))
        return false;
    $arr[]=$body;

    // Notify admin by mail
    if (!empty($sAdminMail))
    {
        $dns=@gethostbyaddr($ip);

        $subject = strtr( $lang['cCommentsMailSubject'], array(
                            "#image#"=>$image->m_sBaseFilename,
                            "#album#"=>$album->GetTitle() ));

        $url="http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']
                         . "?" . @$_SERVER['QUERY_STRING'];

        global $g_sCharset;

        if (preg_match('/[^a-zA-Z0-9!@#$%&*()-{}]/',$subject))
            $subject="=?$g_sCharset?B?".base64_encode($subject)."?=";
        else
            $subject=$subject;


        $headers="";
        if (!empty($sFromLine))
            $headers="From: " . $sFromLine."\n";

        $headers.="Content-type: text/plain; charset=$g_sCharset\n";
        $headers.="MIME-Version: 1.0\nX-Priority: 3 (Normal)\n";
        $headers.="X-MSMail-Priority: Normal\n";
        $headers.="X-Mailer: DAlbum\n";

        $message = strtr( $lang['cCommentsMailBody'], array(
                            '#user#'=>$arr[0],
                            '#ip#'=>$arr[1],
                            '#dns#'=>$dns,
                            '#body#'=>$body,
                            '#url#'=>$url));

        mail($sAdminMail, $subject, $message, $headers);
    }

    // Cut very long strings and quote HTML
    for ($i=0;$i<count($arr);++$i)
    {
        if (strlen($arr[$i])>2000)
            $arr[$i]=substr($arr[$i],0,2000)+"...";

        $arr[$i]=str_replace("\n",'',nl2br(quotehtml($arr[$i])));
        $arr[$i]=str_replace("",'',$arr[$i]);
    }

    $handle=fopen($textfname,"at");
    if ($handle)
    {
        $line=join(":|:",$arr)."\n";
        @fwrite($handle,$line);
        @fclose($handle);

        global $g_newDirRights;
        @chmod($textfname,$g_newDirRights);
    }
    return true;
}

function DAlbum_Comments_Plugin_Display($nCommentsAuth)
{
    global $lang,$sUserName,$image,$bAdminMode,$album;

    //
    $bShowComments=($nCommentsAuth<2 || !empty($sUserName));
    $bShowForm=($nCommentsAuth==0 || !empty($sUserName));
    $bShowLogin=($nCommentsAuth==1 && empty($sUserName));

    if ($bShowComments)
    {
        // $image variable is set to displayed image
        $imagefname=absfname($image->m_sFullFilename);
        $textfname= dirname_ex($imagefname) . "/" .
                    getfname($imagefname) . ".cmt";

        //////////// Image comments header begins  ////////////
        ?>
            <!-- Image comments code begin -->
            <tr>
            <td align="center" class="imagecommentsRow">
            <table class="imagecomments">
            <tr><th><?php print $lang['cCommentsImageComments']; ?></th></tr>
<?php   //////////// Image comments header ends  ////////////

        // Display existing comments

        if (file_exists($textfname))
        {
            $file=safe_read_file($textfname);

            $bChanged=false;
            $hashDelete="";
            if ($bAdminMode && isset($_POST['deleteComment']))
                $hashDelete=$_POST['hashComment'];

            for ($i=0;$i<count($file);++$i)
            {
                $line=trim($file[$i]);
                if (empty($line))
                    continue;

                $linehash=md5($line);

                // If this line was marked to delete - make it empty
                if (!empty($hashDelete) && $hashDelete==$linehash)
                {
                    $file[$i]="";
                    $hashDelete="";
                    $bChanged=true;
                    continue;
                }

                // Display found line
                $arr=explode(":|:",$line);
                $name=$arr[0];
                $ip  =$arr[1];
                $date=$arr[2];
                $body=$arr[3];

                // Comment line begin
                print '<tr><td class="imagecomment">';
                print "<B>$name</B>&nbsp;&nbsp;";
                if ($bAdminMode)
                    print " ( IP: {$ip} ) &nbsp;";
                print "- $date ";

                if ($bAdminMode)
                {
                    print '<form action="" method="post" style="display:inline;">';
                    print '<input type="submit" name="deleteComment" value="';
                    print  $lang['cCommentsDeleteButtonText'] . '">';
                    print '<input type="hidden" name="hashComment"   value="'
                            . $linehash .'">';
                    print '</form>';
                }
                print "<BR>". $body;

                print '</td></tr>';
            }

            // Delete empty lines
            if ($bAdminMode && isset($_POST['deleteComment']))
            {
                $bPrev=@ignore_user_abort(true);
                for ($i=0;$i<count($file);++$i)
                {
                    $handle=fopen($textfname,"wt");
                    if ($handle)
                    {
                        foreach ($file as $line)
                        {
                            if (!empty($line))
                                fwrite($handle,trim($line)."\n");
                        }
                        fclose($handle);

                        global $g_newDirRights;
                        @chmod($textfname,$g_newDirRights);
                    }
                }
                @ignore_user_abort($bPrev);
            }
        }
    }

    if ($bShowLogin)
    {
        global $lang;
        $loginCode=getButton('login',translateRef("login.php?url=" . encodeCurrentLocation()),
                            $lang['loginBtn'],$lang['loginBtnTitle'],0);
        // Let the user know that he needs to login to post comments
?>
        <tr><td class="imagecomment">
        <?php print strtr($lang['cCommentsLoginToAddComments'],
                            array("#loginbutton#"=>$loginCode)); ?>
        </td></tr>
<?php  /////////////////////////////////////////////////////////
    }

    if ($bShowComments && $bShowForm)
    {
        $sDefaultUserName="Anonymous";
        if (!empty($sUserName))
            $sDefaultUserName=$sUserName;

        ////////////// "New comment" form begins //////////////
?>
<tr><td class="imagecommentform">
<form action="#commentsform" method="post">
<table cellpadding=2 cellspacing=2 border=0>
    <tr><td valign=top><a name="commentsform"></a>
        <?php print $lang['cCommentsYourName']; ?></td>
        <td valign=top>
            <input type="text" name="realname"
                   size=80 value="<?php print $sDefaultUserName; ?>">
        </td>
    </tr>
    <tr>
        <td valign=top><?php print $lang['cCommentsComment']; ?></td>
        <td valign=top>
            <textarea name="comment" rows=4 cols=60></textarea>
        </td>
    </tr>
    <tr>
        <td colspan=2 align=right>
            <input type="submit" value="<?php print $lang['cCommentsSendButtonText']; ?>">
        </td>
    </tr>
</table>
</form>
</td></tr>
<?php //////////// "new comment" form ends  ////////////
    }


    if ($nCommentsAuth<2 || !empty($sUserName))
    {
        //////////// Display footer  ////////////
?>
</table>
</td>
</tr>
<!-- Image comments end -->
<?php } //////////// Footer ends ////////////
}?>

5. Secure your installation so it is not possible to download image comments file by using a URL like www.mysite.com/photo/pictures/pic1.cmt

If you're running Apache, edit .htaccess file located in DAlbum directory and append the following lines:

<Files ~ ".cmt$">
order allow,deny
deny from all
</Files>

Most likely you do not need to do anything for Microsoft IIS as no registered MIME type correspond to .cmt extension by default.

6. That's all. Modify the code above as needed.