<?php
/*
Plugin Name: Irontec - Notifier
Plugin URI: http://www.irontec.com
Description: Notificaciones en pantalla de comentarios en el blog y activity updates
Version: 1.0
Author: Irontec
Author URI: http://www.irontec.com
*/

// Define plugin version and plugin url
define( 'IRON_NOTIFIER_VERSION', '1.0' );
define( 'IRON_NOTIFIER_URL', WP_PLUGIN_URL . '/irontec-notifier' );

// Define notifications slug
define("BP_IRON_NOTIFIER_SLUG","iron_notifier");

// Add the plugin Administration Menu
add_action('admin_menu', 'iron_notifier_create_menu');

// Notifier globals
function iron_notifier_setup_globals() {
    global $bp, $current_blog;
    $bp->iron_notifier = new stdClass();
    $bp->iron_notifier->id = 'iron_notifier';
    $bp->iron_notifier->slug = BP_IRON_NOTIFIER_SLUG;
    $bp->iron_notifier->format_notification_function = 'iron_notifier_format_notifications';
    $bp->active_components[$bp->iron_notifier->slug] = $bp->iron_notifier->id;

    do_action( 'iron_notifier_setup_globals' );
}
add_action( 'bp_setup_globals', 'iron_notifier_setup_globals' );

// Notify format function
function iron_notifier_format_notifications( $action, $item_id, $secondary_item_id, $total_items ) {
    global $bp;

	$post = get_post ($item_id);
	$activity = new BP_Activity_Activity( $item_id);
    $link=iron_notifier_post_get_permalink( $item_id );
    $iron_action='new_blog_comment_'.$item_id;
    $link2 = site_url() . '/activity/p/'. $item_id;
    $iron_action2='new_favorite_'.$item_id;

    if ($action==$iron_action) {
    	if ( $total_items > 1 )
    		return '<a class="iron-notify" href="'. $link .'">'. __ ('There are','buddypress') .' '. $total_items .' '. __ ('new comments in the post:','buddypress') .' '. $post->post_title .'</a>';
    	else
    		return '<a class="iron-notify" href="'. $link .'">'. __ ('There is a','buddypress') .' '. __ ('new comment in the post:','buddypress') .' '. $post->post_title .'</a>';
    }
    elseif ($action==$iron_action2) {
    	$res_items = $total_items - 1;
    	if ( $total_items > 1 )
    		return '<a class="iron-notify" href="'. $link2 .'">'. ucfirst( bp_core_get_username($secondary_item_id) ) .' '. __ ('favorited an activity update you\'ve posted', 'buddypress') .'</a>';
    	else
    		return '<a class="iron-notify" href="'. $link2 .'">'. ucfirst( bp_core_get_username($secondary_item_id) ) . __ (' and ','buddypress') . $res_total . ' '. __ ('users favorited an activity update you\'ve posted', 'buddypress') .'</a>';
    }
}

// Activity Update Email Notifications to involved users
function iron_activity_update_email_notifications ( $activity_id ) {
	$activity = new BP_Activity_Activity( $activity_id );

	$persons = ac_notifier_find_involved_persons ($activity->item_id);
	foreach ( $persons as $pers) {
		$user_email = bp_core_get_user_email($pers[0]);
		$message = __ ('Hay un nuevo comentario','buddypress') . ': ';
		$message .= '<a class="iron-notify" href="'.site_url() . '/p/' . $activity->id .'/">'. site_url() . '/p/' . $activity->id .'</a>';
		$message .= '<br />';
		$message .= __ ('Author','buddypress') . ': ' . bp_core_get_user_displayname( $activity->user_id );
		$message .= '<br />';
		$message .= __ ('Comment','buddypress') . ': ' . $activity->content;
		// Email the involved users
		// Only if user has selected to receive notifications
		$activated = get_user_meta($pers[0], 'notification_activity_new_reply');
		if ($activated[0] == 'yes')
			wp_mail($user_email,'[Kronikoen Sarea] Nuevo comentario',$message);
	}
}
add_action ('bp_activity_comment_posted','iron_activity_update_email_notifications',1);

// Blog Comment Post Notifications
function iron_comment_notification ( $comment_ID ) {
	global $wpdb;
	$comment = get_comment($comment_ID);
	$post    = get_post($comment->comment_post_ID);

	// Notify POST author and all users that have commented
	if ( get_option ('iron_notifier_mode') == 'all') {

		// Obtain involved users
		$involved_users = $wpdb->get_col ($wpdb->prepare('
		SELECT DISTINCT user_id FROM '. $wpdb->comments .' WHERE comment_post_ID= '. $post->ID
		));

		// Add the Notification to every user involved in the thread, except the comment author
		foreach ($involved_users as $involved_user_id) {
			if ( $involved_user_id != $comment->user_id ) {
				// Add the notification to involved users
				bp_core_add_notification( $post->ID, $involved_user_id, 'iron_notifier', 'new_blog_comment_'.$post->ID, bp_loggedin_user_id() );
				// Send the email to involved users
				if ( get_option ('iron_notifier_activate_blog_comments_email') == 1) {
					$userdata = get_userdata($involved_user_id);
					$message = __ ('There is a new comment in the post','buddypress') . ': ';
					$message .= site_url() . '/' . $post->post_name;
					$message .= '<br />';
					$message .= __ ('Author','buddypress') . ': ' . $comment->comment_author;
					$message .= '<br />';
					$message .= __ ('Comment','buddypress') . ': ' . $comment->comment_content;
					
					/**
            	     * dani - irontec
            	     * se comprueba si los usuarios que han comentado en el post (pregunta/testimonio)
            	     * han seleccionado no resivir notificaciones de estos comentarios.
            	     * @var get_user_meta($involved_user_id, 'notification_blog_comments');
            	     */
					$userAuthorNot = get_user_meta($involved_user_id, 'notification_blog_comments');
					if ($post->post_author != $involved_user_id and $userAuthorNot[0] != 'no')
						wp_mail($userdata->user_email, '[Kronikoen Sarea] Notificacion', $message);
				}
			}
		}

		// Add the notification to post author
		bp_core_add_notification( $post->ID, $post->post_author, 'iron_notifier', 'new_blog_comment_'.$post->ID, bp_loggedin_user_id() );
		// Send email to post author only if WP comment notifications are not active
		if ( get_option ('iron_notifier_activate_blog_comments_email') == 1) {
			$authordata = get_userdata($post->post_author);
			if ( !get_option ('comments_notify') ) {
				$message = __ ('There is a new comment in the post','buddypress') . ': ';
				$message .= site_url() . '/' . $post->post_name;
				$message .= '<br />';
				$message .= __ ('Author','buddypress') . ': ' . $comment->comment_author;
				$message .= '<br />';
				$message .= __ ('Comment','buddypress') . ': ' . $comment->comment_content;
				wp_mail($authordata->user_email, '[Kronikoen Sarea] Notificacion', $message);
			}
		}
	}
	// Notify only the POST author
	else {
		// Add the notification
		bp_core_add_notification( $post->ID, $post->post_author, 'iron_notifier', 'new_blog_comment_'.$post->ID, bp_loggedin_user_id() );
		// Send email to post author only if WP comment notifications are not active
		if ( get_option ('iron_notifier_activate_blog_comments_email') == 1) {
			$authordata = get_userdata($post->post_author);
			if ( !get_option ('comments_notify') ) {
				$message = __ ('There is a new comment in the post','buddypress') . ': ';
				$message .= site_url() . '/' . $post->post_name;
				$message .= '<br />';
				$message .= __ ('Author','buddypress') . ': ' . $comment->comment_author;
				$message .= '<br />';
				$message .= __ ('Comment','buddypress') . ': ' . $comment->comment_content;
				wp_mail($authordata->user_email, '[Kronikoen Sarea] Notificacion', $message);
			}
		}
	}
}
if ( get_option ('iron_notifier_activate_blog_comments_screen') == 1)
	add_filter('comment_post', 'iron_comment_notification', 10, 1);

// Activity Favorite Notifications
function iron_favorite_notification ( $activity_id ) {
	$activity = new BP_Activity_Activity( $activity_id );
	// Add the notification to the activity author
	bp_core_add_notification( $activity_id, $activity->user_id, 'iron_notifier', 'new_favorite_'.$activity_id, bp_loggedin_user_id() );
}
if ( get_option ('iron_notifier_activate_favorite_notifications_screen') == 1)
	add_filter ('bp_activity_add_user_favorite', 'iron_favorite_notification');

// Activity UnFavorite Clear notifications
function iron_unfavorite_notification ( $activity_id ) {
	$activity = new BP_Activity_Activity( $activity_id );
	// Clear notification for the activity author
	bp_core_delete_notifications_for_user_by_item_id ( $activity->user_id, $activity->id, 'iron_notifier', 'new_favorite_'.$activity->id, bp_loggedin_user_id() );
}
if ( get_option ('iron_notifier_activate_favorite_notifications_screen') == 1)
	add_filter ('bp_activity_remove_user_favorite', 'iron_unfavorite_notification');

// Clear notifications when viewed
function iron_clear_notifications() {
	global $bp;

	// Only executed when in single page (for blog comment notifications)
    if ( is_single() ) {
    	$post=wp_get_single_post();
		bp_core_delete_notifications_for_user_by_item_id ( bp_loggedin_user_id(), $post->ID, 'iron_notifier', 'new_blog_comment_'.$post->ID );
    }

	// Only executed when in activity permalink (for activity notifications)
    elseif ( $bp->current_component == 'activity' && is_numeric($bp->current_action) ) {
    	bp_core_delete_notifications_for_user_by_item_id ( bp_loggedin_user_id(), $bp->current_action, 'iron_notifier', 'new_favorite_'.$bp->current_action);
    }
}
add_filter('wp_head','iron_clear_notifications');

// Basic functions

// Get the post permalink
function iron_notifier_post_get_permalink( $post_ID ) {
	global $bp;

	$post = get_post ($post_ID);
	$link = site_url() . '/' . $post->post_name .'/#respond' ;

	return apply_filters( 'iron_notifier_post_get_permalink', $link );
}

/* Avisos email custom */
function bp_custom_screen_notification_settings() {
    global $bp; ?>
    <table class="notification-settings zebra" id="iron-notification-settings">
    <thead>
        <tr>
            <th class="icon"></th>
            <th class="title"><?php _e( 'Testimonios y Preguntas', 'buddypress' ) ?></th>
            <th class="yes"><?php _e( 'S&iacute;', 'buddypress' ) ?></th>
            <th class="no"><?php _e( 'No', 'buddypress' )?></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td><?php _e( 'Publican un comentario en un testimonio o pregunta de la que eres el autor.', 'buddypress' ) ?></td>
            <td class="yes"><input type="radio" name="notifications[notification_blog_comments_author]" value="yes" <?php if ( !get_usermeta( $bp->loggedin_user->id,'notification_blog_comments_author') || 'yes' == get_usermeta( $bp->loggedin_user->id,'notification_blog_comments_author') ) { ?>checked="checked" <?php } ?>/></td>
            <td class="no"><input type="radio" name="notifications[notification_blog_comments_author]" value="no" <?php if ( get_usermeta( $bp->loggedin_user->id,'notification_blog_comments_author') == 'no' ) { ?>checked="checked" <?php } ?>/></td>
        </tr>
        <tr>
            <td></td>
            <td><?php _e( 'Publican un comentario en un testimonio o pregunta en la que t&uacute; tambi&eacute;n has comentado.', 'buddypress' ) ?></td>
            <td class="yes"><input type="radio" name="notifications[notification_blog_comments]" value="yes" <?php if ( !get_usermeta( $bp->loggedin_user->id,'notification_blog_comments') || 'yes' == get_usermeta( $bp->loggedin_user->id,'notification_blog_comments') ) { ?>checked="checked" <?php } ?>/></td>
            <td class="no"><input type="radio" name="notifications[notification_blog_comments]" value="no" <?php if ( get_usermeta( $bp->loggedin_user->id,'notification_blog_comments') == 'no' ) { ?>checked="checked" <?php } ?>/></td>
        </tr>
	</tbody>
        <?php do_action( 'bp_custom_screen_notification_settings' ); ?>
    </table>
<?php
}
add_action( 'bp_notification_settings', 'bp_custom_screen_notification_settings' );

// Administration Menu
function iron_notifier_create_menu() {

	//create new top-level menu
	add_menu_page('Iron Notifier', 'Iron Notifier', 'manage_options', 'iron-notifier-handle', 'iron_notifier_settings_page', plugins_url('/css/images/irontec.gif', __FILE__));

	//call register settings function
	add_action( 'admin_init', 'iron_notifier_settings' );
}

// Administration Settings page options
function iron_notifier_settings() {
	register_setting( 'iron-notifier-settings-group', 'iron_notifier_activate_blog_comments_screen' );
	register_setting( 'iron-notifier-settings-group', 'iron_notifier_activate_blog_comments_email' );
	register_setting( 'iron-notifier-settings-group', 'iron_notifier_activate_favorite_notifications_screen' );
	register_setting( 'iron-notifier-settings-group', 'iron_notifier_activate_favorite_notifications_email' );
	register_setting( 'iron-notifier-settings-group', 'iron_notifier_mode' );
}

// Administration Settings page
function iron_notifier_settings_page() { ?>

<div class="notifier-admin-div wrap">
	<img style="float: left; margin: 13px;" src="<?php echo IRON_NOTIFIER_URL; ?>/css/images/logo_irontec_2.0.png" />
	<h2>Notifier: Settings Page</h2>
	<div class="clear"></div>

	<form id="iron-notifier-form" method="post" action="options.php">
		<fieldset>
		<legend><b>&nbsp;Blog Comments Notifications&nbsp;</b></legend>
		<?php settings_fields( 'iron-notifier-settings-group' ); ?>

		<table id="iron-notifier-table" class="form-table">

        <tr valign="top">
        <td align="left">
        <p>Notify when users comment in a blog post.</p>
        <input type="checkbox" value="1" name="iron_notifier_activate_blog_comments_screen" <?php if (get_option ('iron_notifier_activate_blog_comments_screen') == 1) echo ' checked'; ?>>&nbsp;Activate screen notifications<br />
        <input type="checkbox" value="1" name="iron_notifier_activate_blog_comments_email" <?php if (get_option ('iron_notifier_activate_blog_comments_email') == 1) echo ' checked'; ?>>&nbsp;Activate email notifications<br />
        </td>
        </tr>

		<tr valign="top">
        <td align="left">
        <p>Send notifications to:</p>
        <select name="iron_notifier_mode">
        <option value="author" <?php if (get_option ('iron_notifier_mode') == 'author' ) echo ' selected'; ?>>Post author only</option>
        <option value="all" <?php if (get_option ('iron_notifier_mode') == 'all' ) echo ' selected'; ?>>Author and all users in the thread</option>
        </select>
        </td>
        </tr>

        <tr valign="top">
        <td align="left">
        <p>Notify when users mark an item as favorite.</p>
        <input type="checkbox" value="1" name="iron_notifier_activate_favorite_notifications_screen" <?php if (get_option ('iron_notifier_activate_favorite_notifications_screen') == 1) echo ' checked'; ?>>&nbsp;Activate screen notifications<br />
        <input type="checkbox" value="1" name="iron_notifier_activate_favorite_notifications_email" <?php if (get_option ('iron_notifier_activate_favorite_notifications_email') == 1) echo ' checked'; ?>>&nbsp;Activate email notifications<br />
        </td>
        </tr>

        </table>

        <p class="submit">
    	<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
    	</p>
		</fieldset>
	</form>
</div> <!-- .notifier-admin-div -->

<?php }
?>
