<?php
/**************************************************
  Coppermine 1.5.x Plugin - email_comments
**************************************************/

// Make sure that this file can't be accessed directly, but only from within the Coppermine user interface
if (!defined('IN_COPPERMINE')) {
    die('Not in Coppermine...');
}

require "./plugins/email_comments/lang/english.php";
if ($CONFIG['lang'] != 'english' && file_exists("./plugins/email_comments/lang/{$CONFIG['lang']}.php")) {
    require ("./plugins/email_comments/lang/{$CONFIG['lang']}.php");
}

// Define plugin actions here
$thisplugin->add_action('plugin_install','email_comments_install');             // install script
$thisplugin->add_action('plugin_cleanup','email_comments_cleanup');             // pre-uninstall script
$thisplugin->add_action('plugin_uninstall','email_comments_uninstall');         // uninstall script
$thisplugin->add_action('comment_add','email_comments_added');                  // comments added action
$thisplugin->add_action('comment_approve','email_comments_approved');           // comments approved action

// Define the plugin's functions here
function email_comments_install() {
    global $CONFIG;
    // Add the config options for the plugin                                max length:   xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    cpg_db_query("INSERT IGNORE INTO {$CONFIG['TABLE_CONFIG']} (`name`, `value`) VALUES ('plugin_email_comments_version', '1.1')");
    cpg_db_query("UPDATE {$CONFIG['TABLE_CONFIG']} SET `value` = '1.1' WHERE `name` = 'plugin_email_comments_version'");  // update version if re-install
    cpg_db_query("INSERT IGNORE INTO {$CONFIG['TABLE_CONFIG']} (`name`, `value`) VALUES ('plugin_email_comments_send_owner', '1')");
    cpg_db_query("INSERT IGNORE INTO {$CONFIG['TABLE_CONFIG']} (`name`, `value`) VALUES ('plugin_email_comments_send_commenters', '0')");
    cpg_db_query("INSERT IGNORE INTO {$CONFIG['TABLE_CONFIG']} (`name`, `value`) VALUES ('plugin_email_comments_send_thumbnail', '1')");
    cpg_db_query("INSERT IGNORE INTO {$CONFIG['TABLE_CONFIG']} (`name`, `value`) VALUES ('plugin_email_comments_subject', 'Comment posted on Coppermine Photo Gallery')");
    cpg_db_query("INSERT IGNORE INTO {$CONFIG['TABLE_CONFIG']} (`name`, `value`) VALUES ('plugin_email_comments_owner', '{username},<br />Your photo has received a new comment')");
    cpg_db_query("INSERT IGNORE INTO {$CONFIG['TABLE_CONFIG']} (`name`, `value`) VALUES ('plugin_email_comments_author', '{username},<br />A photo you previously commented on has received a new comment')");
    cpg_db_query("INSERT IGNORE INTO {$CONFIG['TABLE_CONFIG']} (`name`, `value`) VALUES ('plugin_email_comments_text1', 'Comment from {author}: {comment}')");
    cpg_db_query("INSERT IGNORE INTO {$CONFIG['TABLE_CONFIG']} (`name`, `value`) VALUES ('plugin_email_comments_text2', 'You can view the picture and all comments at: {link}')");
    cpg_db_query("INSERT IGNORE INTO {$CONFIG['TABLE_CONFIG']} (`name`, `value`) VALUES ('plugin_email_comments_text3', '')");
    cpg_db_query("INSERT IGNORE INTO {$CONFIG['TABLE_CONFIG']} (`name`, `value`) VALUES ('plugin_email_comments_text4', '')");
    cpg_db_query("INSERT IGNORE INTO {$CONFIG['TABLE_CONFIG']} (`name`, `value`) VALUES ('plugin_email_comments_loginreq', 'You must be logged on for this link to take you to the picture/comments - otherwise you will be redirected to the login page.')");
    return true;
}


function email_comments_cleanup($action) {
    global $CONFIG, $lang_plugin_email_comments, $email_comments_icon_array;
    // Initialize language and icons
    // get language files
    require "./plugins/email_comments/lang/english.php";
    if ($CONFIG['lang'] != 'english' && file_exists("./plugins/email_comments/lang/{$CONFIG['lang']}.php")) {
      require "./plugins/email_comments/lang/{$CONFIG['lang']}.php";
    }
    $superCage = Inspekt::makeSuperCage();
    $cleanup = $superCage->server->getEscaped('REQUEST_URI');
    if ($action===1) {
      // prompt to see what we should retain during uninstall...
      $remove_settings = 'checked="checked"';                                   // set options to remove settings
      echo <<< EOT
        <form action="{$cleanup}" method="post">
EOT;
      starttable('100%', '', 2);
      echo <<< EOT
        <tr>
          <td class="tableb">
            {$lang_plugin_email_comments['uninstall_remove_settings']}
          </td>
          <td class="tableb">
            <input type="checkbox" name="remove_settings" id="remove_settings" class="checkbox" value="1" $remove_settings />
            <label for="drop_yes" class="clickable_option">{$lang_plugin_email_comments['remove_settings']}</label>
          </td>
        </tr>
EOT;
      echo <<< EOT
        <tr>
          <td class="tablef">
          </td>
          <td class="tablef">
            <button type="submit" class="button" name="submit" value="{$lang_plugin_email_comments['submit_uninstall']}">{$email_comments_icon_array['ok']}{$lang_plugin_email_comments['submit_uninstall']}</button>
          </td>
        </tr>
EOT;
      endtable();
      echo <<< EOT
        </form>
EOT;
    }
}


function email_comments_uninstall() {
    global $CONFIG, $lang_errors;
    $superCage = Inspekt::makeSuperCage();
    if (!checkFormToken()) {
        cpg_die(ERROR, $lang_errors['invalid_form_token'], __FILE__, __LINE__);
    }
    if (!$superCage->post->keyExists('submit')) {
      return 1;
    }
    // Remove plugin config records
    if ($superCage->post->keyExists('remove_settings') && $superCage->post->getInt('remove_settings') == 1) {
      // Delete the plugin config records
      cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name = 'plugin_email_comments_version'");
      cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name = 'plugin_email_comments_send_owner'");
      cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name = 'plugin_email_comments_send_commenters'");
      cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name = 'plugin_email_comments_send_thumbnail'");
      cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name = 'plugin_email_comments_subject'");
      cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name = 'plugin_email_comments_owner'");
      cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name = 'plugin_email_comments_author'");
      cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name = 'plugin_email_comments_text1'");
      cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name = 'plugin_email_comments_text2'");
      cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name = 'plugin_email_comments_text3'");
      cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name = 'plugin_email_comments_text4'");
      cpg_db_query("DELETE FROM {$CONFIG['TABLE_CONFIG']} WHERE name = 'plugin_email_comments_loginreq'");
    }
    return true;
}


function email_comments_added($parm) {
  // most of the work - determine who needs to be notified about comment just left (or just approved)
  // Invoked via Plugin API for each new comment not needing approval:
  //   CPGPluginAPI::action('comment_add', array('msg_id' => cpg_db_last_insert_id(), 'pid' => $pid, 'msg_author' => $msg_author, 'author_id' => USER_ID, 'msg_body' => $msg_body, 'approval' => $app));
  // Invoked via email_comments_approved function below when processing list of approved comments
  //   email_comments_added(array('msg_id' => $row['msg_id'], 'pid' => $row['pid'], 'msg_author' => $row['msg_author'], 'author_id' => $row['author_id'], 'msg_body' => $row['msg_body'], 'approval' => 'YES'));
  global $CONFIG;
  // only email owner/other authors if this was an approved comment...
  if ($parm['approval'] == 'YES' && $CONFIG['plugin_email_comments_send_owner']) {
    // include language and functions needed...
    require "./plugins/email_comments/lang/english.php";
    if ($CONFIG['lang'] != 'english' && file_exists("./plugins/email_comments/lang/{$CONFIG['lang']}.php")) {
      require ("./plugins/email_comments/lang/{$CONFIG['lang']}.php");
    }
    if (!function_exists('cpg_mail')) {
      // if we are invoked via reviewcom.php (drives comment_approve action) - the function hasn't been included
      require_once('include/mailer.inc.php');
    }
    $user_id_array = array();
    // get picture information...
    $result = cpg_db_query("SELECT url_prefix, filepath, filename, owner_id, title, caption, pwidth, pheight FROM {$CONFIG['TABLE_PICTURES']} WHERE pid = '{$parm['pid']}' LIMIT 1");
    $picture = cpg_db_fetch_row($result);
    mysql_free_result($result);
    // see if owner is one leaving comment - no email to them if so..
    if ($picture['owner_id'] != $parm['author_id']) {
      $user_id_array[] = $picture['owner_id'];
    }
    // see who else left comments (registered users only)... if requested
    if ($CONFIG['plugin_email_comments_send_commenters']) {
      // get list of registered authors that have commented (exclude guest comments - we won't have an email address)
      $result = cpg_db_query("SELECT DISTINCT author_id FROM {$CONFIG['TABLE_COMMENTS']} WHERE pid = '{$parm['pid']}' AND author_id != 0");
      while ($row = cpg_db_fetch_row($result)) {
        if ($row['author_id'] != $parm['author_id']) {
          // no email to the one leaving comment - but add the rest
          $user_id_array[] = $row['author_id'];
        }
      }
      mysql_free_result($result);
    }
    // if we have users to send to...
    if (count($user_id_array)) {
      global $cpg_udb;
      // extract title, link to picture, comment text, pic_markup (thumbnail)
      $title = $picture['title'] ? $picture['title'] : $picture['filename'];
      $link = $CONFIG['ecards_more_pic_target'] . (substr($CONFIG["ecards_more_pic_target"], -1) == '/' ? '' : '/') . 'displayimage.php?pid='.$parm['pid'];
      $author = $parm['msg_author'];
      $comment = '"' . bb_decode(process_smilies($parm['msg_body'], $CONFIG['ecards_more_pic_target'])) . '"';
      if ($CONFIG['plugin_email_comments_send_thumbnail']) {
        // get url for thumbnail to include if requested
        $thumb_pic_url = get_pic_url($picture, 'thumb');
        $gallery_url_prefix = $CONFIG['ecards_more_pic_target']. (substr($CONFIG['ecards_more_pic_target'], -1) == '/' ? '' : '/');
        if (!stristr($thumb_pic_url, 'http:')) {
          $thumb_pic_url = $gallery_url_prefix . $thumb_pic_url;
        }
        $pic_markup = '<img src="'.$thumb_pic_url.'" alt="CPG Thumbnail" vspace="8" border="0" class="image" /><br />';
      } else {
        // no thumbnail requested
        $pic_markup = '';
      }
      // build email message from CONFIG settings and variables
      $mail_owner = $CONFIG['plugin_email_comments_owner'].': <br />';          // prefix for owner email
      $mail_author = $CONFIG['plugin_email_comments_author'].': <br />';        // prefix for comment author emails
      $mail_message = email_comments_build_email($title, $pic_markup, $author, $comment, $link);
      // get email addresses and usernames for desired ids
      $result = cpg_db_query("SELECT ".$cpg_udb->field['email']." AS user_email, ".$cpg_udb->field['user_id']." AS user_id, ".$cpg_udb->field['username']." AS username  FROM ".$cpg_udb->usertable." WHERE ".$cpg_udb->field['user_id']." IN (".implode(', ', $user_id_array).")");
      while ($row = cpg_db_fetch_row($result)) {
        // set appropriate text for owner or author and send
        $mail_body = ($row['user_id'] == $picture['owner_id']) ? $mail_owner . $mail_message : $mail_author . $mail_message;
        $search  = array('{username}');
        $replace = array($row['username']);
        $mail_body = str_replace($search, $replace, $mail_body);
        cpg_mail($row['user_email'], "{$CONFIG['gallery_name']}: {$CONFIG['plugin_email_comments_subject']}", make_clickable($mail_body));
      }
      mysql_free_result($result);
    }
  }
  return;
}

function email_comments_approved($parm) {
  // When comments are approved - function called with list of approved (and rejected - which we ignore) comments
  // Parse list and call email_comments_added for each comment to send emails
  // Invoked via Plugin API when comments are approved:
  //   CPGPluginAPI::action('comment_approve', array('approved_yes_set' => $approved_yes_set, 'approved_no_set' => $approved_no_set));
  global $CONFIG;
  if ($parm['approved_yes_set'] == '') {
    // no approved comments - we're done
    return;
  }
  // get approved message info
  $result = cpg_db_query("SELECT pid, msg_id, msg_author, msg_body, author_id FROM {$CONFIG['TABLE_COMMENTS']} WHERE msg_id IN ({$parm['approved_yes_set']})");
  while ($row = mysql_fetch_assoc($result)) {
    // go send email for each message...
    email_comments_added(array('msg_id' => $row['msg_id'], 'pid' => $row['pid'], 'msg_author' => $row['msg_author'], 'author_id' => $row['author_id'], 'msg_body' => $row['msg_body'], 'approval' => 'YES'));
  }
  mysql_free_result($result);
  return;
}

function email_comments_build_email($title, $pic_markup, $author, $comment, $link) {
  // construct email text from passed data and CONFIG variables.
  // called by email_comments_added function and admin.php script
  global $CONFIG;
  $mail_message = $title . '<br />' . $pic_markup . $LINEBREAK;
  $mail_message .= ($CONFIG['plugin_email_comments_text1'] != '') ? '<p>' . $CONFIG['plugin_email_comments_text1'] . '</p>' . $LINEBREAK : '';
  $mail_message .= ($CONFIG['plugin_email_comments_text2'] != '') ? '<p>' . $CONFIG['plugin_email_comments_text2'] . '</p>' . $LINEBREAK : '';
  $mail_message .= ($CONFIG['plugin_email_comments_text3'] != '') ? '<p>' . $CONFIG['plugin_email_comments_text3'] . '</p>' . $LINEBREAK : '';
  $mail_message .= ($CONFIG['plugin_email_comments_text4'] != '') ? '<p>' . $CONFIG['plugin_email_comments_text4'] . '</p>' . $LINEBREAK : '';
  // if no 'unlogged access' - add a message (if set in CONFIG)
  if (!$CONFIG['allow_unlogged_access']) {
    // gallery doesn't allow unlogged access - link requires you be logged on to bring you there...
    $mail_message .= ($CONFIG['plugin_email_comments_loginreq'] != '') ? '<p>' . $CONFIG['plugin_email_comments_loginreq'] . '</p>' . $LINEBREAK : '';
  }
  // replace tokens in message
  $search  = array('{author}', '{comment}', '{link}');
  $replace = array($author, $comment, $link);
  $mail_message = str_replace($search, $replace, $mail_message);
  return $mail_message;
}
?>