<?php

// Stop the theme from killing WordPress if BuddyPress is not enabled.
if ( !class_exists( 'BP_Core_User' ) )
	return false;

// Register the widget columns
register_sidebars( 1,
	array(
		'name'          => 'Sidebar',
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget'  => '</div>',
		'before_title'  => '<h3 class="widgettitle">',
		'after_title'   => '</h3>'
	)
);

// Load the AJAX functions for the theme
require_once( TEMPLATEPATH . '/_inc/ajax.php' );

// Load the javascript for the theme
wp_enqueue_script( 'dtheme-ajax-js', get_template_directory_uri() . '/_inc/global.js', array( 'jquery' ) );

// Add words that we need to use in JS to the end of the page so they can be translated and still used.
$params = array(
	'my_favs'           => __( 'My Favorites', 'buddypress' ),
	'accepted'          => __( 'Accepted', 'buddypress' ),
	'rejected'          => __( 'Rejected', 'buddypress' ),
	'show_all_comments' => __( 'Show all comments for this thread', 'buddypress' ),
	'show_all'          => __( 'Show all', 'buddypress' ),
	'comments'          => __( 'comments', 'buddypress' ),
	'close'             => __( 'Close', 'buddypress' ),
	'mention_explain'   => sprintf( __( "%s is a unique identifier for %s that you can type into any message on this site. %s will be sent a notification and a link to your message any time you use it.", 'buddypress' ), '@' . bp_get_displayed_user_username(), bp_get_user_firstname( bp_get_displayed_user_fullname() ), bp_get_user_firstname( bp_get_displayed_user_fullname() ) )
);
wp_localize_script( 'dtheme-ajax-js', 'BP_DTheme', $params );

/**
 * Add the JS needed for blog comment replies
 *
 * @package BuddyPress Theme
 * @since 1.2
 */
function bp_dtheme_add_blog_comments_js() {
	if ( is_singular() ) wp_enqueue_script( 'comment-reply' );
}
add_action( 'template_redirect', 'bp_dtheme_add_blog_comments_js' );

/**
 * HTML for outputting blog comments as defined by the WP comment API
 *
 * @param mixed $comment Comment record from database
 * @param array $args Arguments from wp_list_comments() call
 * @param int $depth Comment nesting level
 * @see wp_list_comments()
 * @package BuddyPress Theme
 * @since 1.2
 */
function bp_dtheme_blog_comments( $comment, $args, $depth ) {
	$GLOBALS['comment'] = $comment;
	?>

	<?php if ( 'pingback' == $comment->comment_type ) return false; ?>
	
	<?php	
	// Obtener estadoanimo de cada comentario
	$user_mood = get_comment_meta($comment->comment_ID, 'ironestado', true);	
	
	if ($user_mood == 'familiares') $ua = "av01";
	elseif ($user_mood == 'reflexivos') $ua = "av02";
	elseif ($user_mood == 'sintomaticos') $ua = "av03";
	elseif ($user_mood == 'transgresores') $ua = "av04"; 
	?>

	<li id="comment-<?php comment_ID(); ?>">
		<div class="comment-avatar-box <?php echo $ua; ?>">
			<div class="author-box <?php echo $ua; ?>">
				<a href="<?php echo get_comment_author_url() ?>" rel="nofollow">
					<?php if ( $comment->user_id ) : ?>
						<?php echo bp_core_fetch_avatar( array( 'item_id' => $comment->user_id, 'width' => 50, 'height' => 50, 'email' => $comment->comment_author_email ) ); ?>
					<?php else : ?>
						<?php echo get_avatar( $comment, 50 ) ?>
					<?php endif; ?>
				</a>
			</div>
		</div>

		<div class="comment-content">

			<div class="comment-meta">
				<a href="<?php echo get_comment_author_url() ?>" rel="nofollow"><?php echo get_comment_author(); ?></a> <?php _e( 'said:', 'buddypress' ) ?>
				<em><?php _e( 'On', 'buddypress' ) ?> <a href="#comment-<?php comment_ID() ?>" title="<?php comment_date() ?>" ><?php comment_date() ?></a></em>
			</div>

			<?php if ( $comment->comment_approved == '0' ) : ?>
			 	<em class="moderate"><?php _e('Your comment is awaiting moderation.'); ?></em><br />
			<?php endif; ?>

			<?php comment_text() ?>

			<div class="comment-options">
				<?php //echo comment_reply_link( array('depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ?>
				<?php //edit_comment_link( __( 'Edit' ),'','' ); ?>
				<?php $comment_url = explode ('/', get_comment_guid()); ?>
				<?php $comment_url = $comment_url[sizeof($comment_url)-2]; ?>
				<?php
				$comm = get_comment($id);
                if ($comm->user_id == bp_loggedin_user_id()) {
                    echo '<a href="'. site_url() .'/'. $comment_url . '/?action=deletecomment&id='.get_comment_ID().'" onClick="if(!confirm(\'Eliminar Comentario ?\')) {return false;}">Borrar</a>';
                }
                ?>
			</div>

		</div>
<?php
}

/**
 * Filter the dropdown for selecting the page to show on front to include "Activity Stream"
 *
 * @param string $page_html A list of pages as a dropdown (select list)
 * @see wp_dropdown_pages()
 * @return string
 * @package BuddyPress Theme
 * @since 1.2
 */
function bp_dtheme_wp_pages_filter( $page_html ) {
	if ( !bp_is_active( 'activity' ) )
		return $page_html;

	if ( 'page_on_front' != substr( $page_html, 14, 13 ) )
		return $page_html;

	$selected = false;
	$page_html = str_replace( '</select>', '', $page_html );

	if ( bp_dtheme_page_on_front() == 'activity' )
		$selected = ' selected="selected"';

	$page_html .= '<option class="level-0" value="activity"' . $selected . '>' . __( 'Activity Stream', 'buddypress' ) . '</option></select>';
	return $page_html;
}
add_filter( 'wp_dropdown_pages', 'bp_dtheme_wp_pages_filter' );

/**
 * Hijack the saving of page on front setting to save the activity stream setting
 *
 * @param $string $oldvalue Previous value of get_option( 'page_on_front' )
 * @param $string $oldvalue New value of get_option( 'page_on_front' )
 * @return string
 * @package BuddyPress Theme
 * @since 1.2
 */
function bp_dtheme_page_on_front_update( $oldvalue, $newvalue ) {
	if ( !is_admin() || !is_super_admin() )
		return false;

	if ( 'activity' == $_POST['page_on_front'] )
		return 'activity';
	else
		return $oldvalue;
}
add_action( 'pre_update_option_page_on_front', 'bp_dtheme_page_on_front_update', 10, 2 );

/**
 * Load the activity stream template if settings allow
 *
 * @param string $template Absolute path to the page template
 * @return string
 * @global WP_Query $wp_query WordPress query object
 * @package BuddyPress Theme
 * @since 1.2
 */
function bp_dtheme_page_on_front_template( $template ) {
	global $wp_query;

	if ( empty( $wp_query->post->ID ) )
		return locate_template( array( 'activity/index.php' ), false );
	else
		return $template;
}
add_filter( 'page_template', 'bp_dtheme_page_on_front_template' );

/**
 * Return the ID of a page set as the home page.
 *
 * @return false|int ID of page set as the home page
 * @package BuddyPress Theme
 * @since 1.2
 */
function bp_dtheme_page_on_front() {
	if ( 'page' != get_option( 'show_on_front' ) )
		return false;

	return apply_filters( 'bp_dtheme_page_on_front', get_option( 'page_on_front' ) );
}

/**
 * Force the page ID as a string to stop the get_posts query from kicking up a fuss.
 *
 * @global WP_Query $wp_query WordPress query object
 * @package BuddyPress Theme
 * @since 1.2
 */
function bp_dtheme_fix_get_posts_on_activity_front() {
	global $wp_query;

	if ( !empty($wp_query->query_vars['page_id']) && 'activity' == $wp_query->query_vars['page_id'] )
		$wp_query->query_vars['page_id'] = '"activity"';
}
add_action( 'pre_get_posts', 'bp_dtheme_fix_get_posts_on_activity_front' );

/**
 * WP 3.0 requires there to be a non-null post in the posts array
 *
 * @param array $posts Posts as retrieved by WP_Query
 * @global WP_Query $wp_query WordPress query object
 * @return array
 * @package BuddyPress Theme
 * @since 1.2.5
 */
function bp_dtheme_fix_the_posts_on_activity_front( $posts ) {
	global $wp_query;

	// NOTE: the double quotes around '"activity"' are thanks to our previous function bp_dtheme_fix_get_posts_on_activity_front()
	if ( empty( $posts ) && !empty( $wp_query->query_vars['page_id'] ) && '"activity"' == $wp_query->query_vars['page_id'] )
		$posts = array( (object) array( 'ID' => 'activity' ) );

	return $posts;
}
add_filter( 'the_posts', 'bp_dtheme_fix_the_posts_on_activity_front' );

/**
 * bp_dtheme_activity_secondary_avatars()
 *
 * Add secondary avatar image to this activity stream's record, if supported
 *
 * @param string $action The text of this activity
 * @param BP_Activity_Activity $activity Activity object
 * @return string
 * @package BuddyPress Theme
 * @since 1.2.6
 */
function bp_dtheme_activity_secondary_avatars( $action, $activity ) {
	switch ( $activity->component ) {
		case 'groups' :
		case 'friends' :
			// Only insert avatar if one exists
			if ( $secondary_avatar = bp_get_activity_secondary_avatar() ) {
				$reverse_content = strrev( $action );
				$position        = strpos( $reverse_content, 'a<' );
				$action          = substr_replace( $action, $secondary_avatar, -$position - 2, 0 );
			}
			break;
	}

	return $action;
}
add_filter( 'bp_get_activity_action_pre_meta', 'bp_dtheme_activity_secondary_avatars', 10, 2 );

/**
 * Custom header image support. You can remove this entirely in a child theme by adding this line
 * to your functions.php: define( 'BP_DTHEME_DISABLE_CUSTOM_HEADER', true );
 *
 * @package BuddyPress Theme
 * @since 1.2
 */
function bp_dtheme_add_custom_header_support() {
	// Set the defaults for the custom header image (http://ryan.boren.me/2007/01/07/custom-image-header-api/)
	define( 'HEADER_TEXTCOLOR', 'FFFFFF' );
	define( 'HEADER_IMAGE', '%s/_inc/images/default_header.jpg' ); // %s is theme dir uri
	define( 'HEADER_IMAGE_WIDTH', 1250 );
	define( 'HEADER_IMAGE_HEIGHT', 125 );

	function bp_dtheme_header_style() { ?>
		<style type="text/css">
			#header { background-image: url(<?php header_image() ?>); }
			<?php if ( 'blank' == get_header_textcolor() ) { ?>
			#header h1, #header #desc { display: none; }
			<?php } else { ?>
			#header h1 a, #desc { color:#<?php header_textcolor() ?>; }
			<?php } ?>
		</style>
	<?php
	}

	function bp_dtheme_admin_header_style() { ?>
		<style type="text/css">
			#headimg {
				position: relative;
				color: #fff;
				background: url(<?php header_image() ?>);
				-moz-border-radius-bottomleft: 6px;
				-webkit-border-bottom-left-radius: 6px;
				-moz-border-radius-bottomright: 6px;
				-webkit-border-bottom-right-radius: 6px;
				margin-bottom: 20px;
				height: 100px;
				padding-top: 25px;
			}

			#headimg h1{
				position: absolute;
				bottom: 15px;
				left: 15px;
				width: 44%;
				margin: 0;
				font-family: Arial, Tahoma, sans-serif;
			}
			#headimg h1 a{
				color:#<?php header_textcolor() ?>;
				text-decoration: none;
				border-bottom: none;
			}
			#headimg #desc{
				color:#<?php header_textcolor() ?>;
				font-size:1em;
				margin-top:-0.5em;
			}

			#desc {
				display: none;
			}

			<?php if ( 'blank' == get_header_textcolor() ) { ?>
			#headimg h1, #headimg #desc {
				display: none;
			}
			#headimg h1 a, #headimg #desc {
				color:#<?php echo HEADER_TEXTCOLOR ?>;
			}
			<?php } ?>
		</style>
	<?php
	}
	add_custom_image_header( 'bp_dtheme_header_style', 'bp_dtheme_admin_header_style' );
}
if ( !defined( 'BP_DTHEME_DISABLE_CUSTOM_HEADER' ) )
	add_action( 'init', 'bp_dtheme_add_custom_header_support' );

/**
 * Show a notice when the theme is activated - workaround by Ozh (http://old.nabble.com/Activation-hook-exist-for-themes--td25211004.html)
 *
 * @package BuddyPress Theme
 * @since 1.2
 */
function bp_dtheme_show_notice() { ?>
	<div id="message" class="updated fade">
		<p><?php printf( __( 'Theme activated! This theme contains <a href="%s">custom header image</a> support and <a href="%s">sidebar widgets</a>.', 'buddypress' ), admin_url( 'themes.php?page=custom-header' ), admin_url( 'widgets.php' ) ) ?></p>
	</div>

	<style type="text/css">#message2, #message0 { display: none; }</style>
	<?php
}
if ( is_admin() && isset($_GET['activated'] ) && $pagenow == "themes.php" )
	add_action( 'admin_notices', 'bp_dtheme_show_notice' );


// Member Buttons
if ( bp_is_active( 'friends' ) )
	add_action( 'bp_member_header_actions',    'bp_add_friend_button' );

if ( bp_is_active( 'activity' ) )
	add_action( 'bp_member_header_actions',    'bp_send_public_message_button' );

if ( bp_is_active( 'messages' ) )
	add_action( 'bp_member_header_actions',    'bp_send_private_message_button' );

// Group Buttons
if ( bp_is_active( 'groups' ) ) {
	add_action( 'bp_group_header_actions',     'bp_group_join_button' );
	add_action( 'bp_group_header_actions',     'bp_group_new_topic_button' );
	add_action( 'bp_directory_groups_actions', 'bp_group_join_button' );
}

// Blog Buttons
if ( bp_is_active( 'blogs' ) )
	add_action( 'bp_directory_blogs_actions',  'bp_blogs_visit_blog_button' );

// REGISTER LEFT SIDEBAR
register_sidebars( 1,
	array(
		'name' => 'left sidebar',
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget' => '</div>',
		'before_title' => '<h3 class="widgettitle">',
		'after_title' => '</h3>'
	)
);

// REGISTER CATEGORY WIDGETS
$cats=get_categories(array('hide_empty' => 0, 'parent' => 1));
if (sizeof($cats)>0) {
	foreach ($cats as $cat) {
		if ($cat->id == $user_mood) {
			register_sidebars ( 1,
				array(
					'name' => $cat->name,
					'before_widget' => '<div id="%1$s" class="widget %2$s">',
					'after_widget' => '</div>',
					'before_title' => '<h3 class="widgettitle">',
					'after_title' => '</h3>'
				)
			);
		}
	}
}

// REMOVE GRAVATAR
function bp_remove_gravatar ($image, $params, $item_id, $avatar_dir, $css_id, $html_width, $html_height, $avatar_folder_url, $avatar_folder_dir) {

    $default = get_stylesheet_directory_uri() .'/_inc/images/bp_default_avatar.jpg';

    if( $image && strpos( $image, "gravatar.com" ) ){

        return '<img src="' . $default . '" alt="avatar" class="avatar" ' . $html_width . $html_height . ' />';
    } else {
        return $image;

    }

}
add_filter('bp_core_fetch_avatar', 'bp_remove_gravatar', 1, 9 );

function fetchMyAvatar ($data1) {

    global $current_user;

    if (isset($current_user->ID)) {

        $avatar = base64_decode($current_user->data->avatar);

        if ($avatar) {

            $classDir = dirname(__FILE__)."/../cvp-irontec/members/single/profile/fetchAvatar.php";

            require_once($classDir);

            $newAvatar = new fetchAvatar();
            $newAvatar->setUserId($current_user->ID);
            $newAvatar->setAvatarSrc($avatar);

            if ($newAvatar->fetch()) {

                delete_user_meta($current_user->ID, "avatar" );
            }
        }
    }
}

add_action('wp_head', 'fetchMyAvatar', 10, 2);

/*
function remove_gravatar ($avatar, $id_or_email, $size, $default, $alt) {

    $default = get_stylesheet_directory_uri() .'/_inc/images/bp_default_avatar.jpg';
    return "<img alt='{$alt}' src='{$default}' class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' />";
}

add_filter('get_avatar', 'remove_gravatar', 1, 5);
*/

function bp_remove_signup_gravatar ($image) {

    $default = get_stylesheet_directory_uri() .'/_inc/images/bp_default_avatar.jpg';

    if( $image && strpos( $image, "gravatar.com" ) ){

        return '<img src="' . $default . '" alt="avatar" class="avatar" width="150" height="150" />';
    } else {
        return $image;
    }

}
add_filter('bp_get_signup_avatar', 'bp_remove_signup_gravatar', 1, 1 );
// END REMOVE GRAVATAR

// DESHABILITAR ADMINBAR
define ("BP_DISABLE_ADMIN_BAR", true);

// CALCULAR COLOR ESTADO DE ANIMO
function calculate_moodbar ($user_id) {
    $class = '';
	$origmood = xprofile_get_field_data( 'EstadoAnimo', $user_id);

	if ($origmood == 'familiares')
		$class="av01";
	elseif ($origmood == 'reflexivos')
		$class="av02";
	elseif ($origmood == 'sintomaticos')
		$class="av03";
	elseif ($origmood == 'transgresores')
		$class="av04";

	return $class;
}

// HTML emails
add_filter('wp_mail_content_type',create_function('', 'return "text/html"; '), 10, 0);
add_filter('bp_core_signup_send_activation_key',create_function('', 'return; '));
// Disable normal activation email
add_filter('bp_core_activation_signup_user_notification_to',create_function('', 'return; '), 1, 1);

function iron_signup_mail_message ($user_id, $asunto = '', $mensaje = '', $userNameAndPasswd = array()) {

    $user_obj = get_userdata($user_id);
    $activate_url = bp_get_activation_page() ."?key=".$user_obj->activation_key;
    $activate_url = esc_url( $activate_url );

    // Email subject
    if ($mensaje == "") {

        $asunto = 'Bienvenido a kronet.net';
    }

    // Email data
    if ($mensaje == "") {

        $mensaje = '
        <p>Hola !</p>
        <p>Gracias por registrate en la red <b>kronet.net</b>.</p>
        <p>Para acceder, pincha en el siguiente enlace:</p>
        <p><a href="%s">%s</a></p>
        <p>Una vez activada, podr&aacute;s acceder a tu cuenta con los datos facilitados en el registro.</p>';

        $mensaje = sprintf(__($mensaje, "buddypress"), $activate_url, $activate_url);

        if (count($userNameAndPasswd) > 0 and isset($userNameAndPasswd["username"]) and isset($userNameAndPasswd["passwd"])) {

            $messageFooter = __('<p>Nombre de usuario: %s</p><p>Contraseña: %s</p>', 'buddypress');
            $messageFooter = sprintf($messageFooter, $userNameAndPasswd["username"], $userNameAndPasswd["passwd"]);

            $mensaje .= $messageFooter;
        }

        /*$mensaje = '
        <p>Hola !</p>
        <p>Gracias por registrate en la red <b>kronet.net</b>.</p>
        <p>Para acceder, pincha en el siguiente enlace:</p>
        <p><a href="'. $activate_url .'">'. $activate_url .'</a></p>
        <p>Una vez activada, podr&aacute;s acceder a tu cuenta con los datos facilitados en el registro.</p>';*/
    }

    // Send email with activation key
    wp_mail ($user_obj->user_email, $asunto, $mensaje);
}

// QUITAR "VIEW" PERMALINK DE ACTIVITIES
//add_filter('bp_activity_permalink','new_bp_activity_permalink');
function new_bp_activity_permalink () {
	return;
}

// QUITAR "TIME-SINCE" DE ACTIVITIES
//add_filter('bp_activity_time_since','new_bp_activity_time_since');

function new_bp_activity_time_since () {
	//$content = '<span class="time-since">' . sprintf( __( '&nbsp;%s', 'buddypress' ), bp_get_activity_date_recorded() ) . '</span></div>';
	//return $content;
	return;
}

// MESSAGES: OPTIONS
function iron_messages_options() {
	global $bp;
?>
	<?php _e( 'Select:', 'buddypress' ) ?>
	<select name="message-type-select" id="message-type-select">
		<option value=""></option>
		<option value="read"><?php _e('Le&iacute;dos', 'buddypress') ?></option>
		<option value="unread"><?php _e('No le&iacute;dos', 'buddypress') ?></option>
		<option value="all"><?php _e('Todos', 'buddypress') ?></option>
	</select>&nbsp;
	<?php if ( $bp->current_action != 'sentbox' && $bp->current_action != 'notices' ) : ?>
		<span id="mark_as_read"><?php _e('Mark as Read', 'buddypress') ?></span> &nbsp;
		<span id="mark_as_unread"><?php _e('Mark as Unread', 'buddypress') ?></span> &nbsp;
	<?php endif; ?>
	<a href="#" id="delete_<?php echo $bp->current_action ?>_messages"><?php _e('Eliminar', 'buddypress') ?></a> &nbsp;
<?php
}

// ACTIVITY COMMENTS
// Esta funcion permite mostrar el puntito con el estado de animo
// En entry.php, llamar a new_bp_activity_comments()
function new_bp_activity_comments( $args = '' ) {
	echo new_bp_activity_get_comments( $args );
}
	function new_bp_activity_get_comments( $args = '' ) {
		global $activities_template, $bp;

		if ( !$activities_template->activity->children )
			return false;

		$comments_html = new_bp_activity_recurse_comments( $activities_template->activity );

		return apply_filters( 'new_bp_activity_get_comments', $comments_html );
	}
		/* TODO: The HTML in this function is temporary and will be moved to the template in a future version. */
		function new_bp_activity_recurse_comments( $comment ) {
			global $activities_template, $bp, $wpdb;

			if ( !$comment->children )
				return false;

			$content .= '<ul>';
			foreach ( (array)$comment->children as $comment ) {
				$classmeta="";
				$classbackground="";

				if ( !$comment->user_fullname )
					$comment->user_fullname = $comment->display_name;

				// Para los colores de estado
				$table_name = $wpdb->prefix . "bp_activity_meta";
				$results = $wpdb->get_results(
				"SELECT * FROM ".$table_name." WHERE activity_id = ". $comment->id);
				foreach ($results as $activity_meta) {
					if ($activity_meta->meta_key == "current_mood") $postmood=$activity_meta->meta_value;
				}

				$currentusermood = xprofile_get_field_data( 'EstadoAnimo', $comment->user_id);

				if ($currentusermood == "familiares") $classmeta="am01";
				elseif ($currentusermood == "sintomaticos") $classmeta="am03";
				elseif ($currentusermood == "reflexivos") $classmeta="am02";
				elseif ($currentusermood == "transgresores") $classmeta="am04";

				if ($postmood == "familiares") $classbackground="ac01";
				elseif ($postmood == "sintomaticos") $classbackground="ac03";
				elseif ($postmood == "reflexivos") $classbackground="ac02";
				elseif ($postmood == "transgresores") $classbackground="ac04";
				// Fin colores de estado

				$content .= '<li id="acomment-' . $comment->id . '" class="'. $classbackground .'">';
				//$content .= 'post_mood: '. $postmood .' | user_id: '. $comment->user_id;
				//$content .= '<div class="acomment-avatar">';
				//$content .= '<a href="' . bp_core_get_user_domain( $comment->user_id, $comment->user_nicename, $comment->user_login ) . '">';
				//$content .= bp_core_fetch_avatar( array( 'item_id' => $comment->user_id, 'type' => 'full', 'width' => 24, 'height' => 24 ) );
				//$content .= '</a>';
				//$content .= '</div>';
				//$content .= bp_get_loggedin_user_avatar( 'width=' . BP_AVATAR_THUMB_WIDTH . '&height=' . BP_AVATAR_THUMB_HEIGHT );
				$content .= '<div class="acomment-avatar">';
				$content .= bp_core_fetch_avatar( array( 'item_id' => $comment->user_id, 'type' => 'full', 'width' => 24, 'height' => 24 ) );
				$content .= '</div>';
				$content .= '<div class="acomment-meta '.$classmeta.'">';
				$content .= '<a href="' . bp_core_get_user_domain( $comment->user_id, $comment->user_nicename, $comment->user_login ) . '">' . apply_filters( 'bp_acomment_name', $comment->user_fullname, $comment ) . '</a>';
				$content .= '&middot; ' . sprintf( __( '%s ago', 'buddypress' ), bp_core_time_since( $comment->date_recorded ) );

				/* Reply link - the span is so that threaded reply links can be hidden when JS is off. */
				if ( is_user_logged_in() )
					$content .= '<span class="acomment-replylink"> &middot; <a href="#acomment-' . $comment->id . '" class="acomment-reply" id="acomment-reply-' . $activities_template->activity->id . '">' . __( 'Reply', 'buddypress' ) . '</a></span>';

				/* Delete link */
				if ( $bp->loggedin_user->is_super_admin || $bp->loggedin_user->id == $comment->user_id )
					$content .= ' &middot; <a href="' . wp_nonce_url( $bp->root_domain . '/' . $bp->activity->slug . '/delete/?cid=' . $comment->id, 'bp_activity_delete_link' ) . '" class="delete acomment-delete">' . __( 'Delete', 'buddypress' ) . '</a>';

				$content .= '</div>';

                // Si no estamos en el Hilo en concreto limitamos el texto mostrado
                if (!$bp->current_action || $bp->current_action=='just-me' || $bp->current_action=='home') {
                    $act_content = '';
                    $act_excerpt = '';
                    $act_excerpt = explode(' ',$comment->content);
                    if (sizeof($act_excerpt)>60) {

                        // Limitamos a 50 palabras
                        //$act_excerpt=substr($act_excerpt,0,100);
                        for ($i=0; $i<60; $i++) {
                            $act_content .= $act_excerpt[$i]." ";
                        }

                        $act_content .= '... <a href="'. bp_activity_get_permalink( bp_get_activity_id() ) .'" title="' . __('Leer m&aacute;s', 'buddypress' ) . '">' . __('Leer m&aacute;s', 'buddypress' ) . '</a></p>';

                    }
                    else $act_content=$comment->content;
                }
                else $act_content=$comment->content;

				$content .= '<div class="acomment-content">' . apply_filters( 'bp_get_activity_content', $act_content ) . '</div>';

				/* Favorite comments */
				if (xprofile_get_field_data('Privacidad', bp_loggedin_user_id()) != 'Privado') {
				
				$my_fav_count = bp_activity_get_meta( $comment->id, 'favorite_count' );
				$content .= '<div id="activity-' . $comment->id . '" class="activity-meta '. $classbackground .'">';

				if ( is_user_logged_in() ) :
					if ( !bp_get_activity_comment_is_favorite( $comment->id ) ) {
					    $content .= '<a rel="'. get_stylesheet_directory_uri() .'/_inc/tips.php?id='. $comment->id .'&act=fav" href="'. bp_get_activity_comment_favorite_link( $comment->id ) .'" class="fav">' . __( 'Me gusta', 'buddypress' ) .'</a>';
					    if ($my_fav_count>0) {
                            $content .= '<span rel="'. get_stylesheet_directory_uri() .'/_inc/tips.php?id='. $comment->id .'&act=fav" class="cluetip fav-count">('. $my_fav_count .')</span>';
                        }
                        else {
                            $content .= '<span rel="'. get_stylesheet_directory_uri() .'/_inc/tips.php?id='. $comment->id .'&act=fav" class="cluetip fav-count">(0)</span>';
                        }
                    }
					else {
					    $content .= '<a rel="'. get_stylesheet_directory_uri() .'/_inc/tips.php?id='. $comment->id .'&act=fav" href="'. bp_get_activity_comment_unfavorite_link( $comment->id ) .'" class="unfav">' . __( 'Ya no me gusta', 'buddypress' ) .'</a>';
					    if ($my_fav_count>0) {
                           $content .= '<span rel="'. get_stylesheet_directory_uri() .'/_inc/tips.php?id='. $comment->id .'&act=fav" class="cluetip fav-count" style="margin-left: 4px;">('. $my_fav_count .')</span>';
                        }
					}
				endif;

				$content .= '</div>';
				}
				/* End Favorite comments */

				$content .= new_bp_activity_recurse_comments( $comment );
				$content .= '</li>';
			}
			$content .= '</ul>';

			return apply_filters( 'new_bp_activity_recurse_comments', $content );
		}

// Custom Favorite Links to activity comments
function bp_activity_comment_is_favorite( $id ) {
	echo bp_get_activity_comment_is_favorite( $id );
}
	function bp_get_activity_comment_is_favorite( $id ) {
		global $bp, $activities_template;

 		return apply_filters( 'bp_get_activity_comment_is_favorite', in_array( $id, (array)$activities_template->my_favs ) );
	}

function bp_activity_comment_favorite_link( $id ) {
	echo bp_get_activity_comment_favorite_link( $id );
}
	function bp_get_activity_comment_favorite_link( $id ) {

		return apply_filters( 'bp_get_activity_comment_favorite_link', wp_nonce_url( site_url( BP_ACTIVITY_SLUG . '/favorite/' . $id . '/' ), 'mark_favorite' ) );
	}

function bp_activity_comment_unfavorite_link( $id ) {
	echo bp_get_activity_comment_unfavorite_link( $id );
}
	function bp_get_activity_comment_unfavorite_link( $id ) {
		global $activities_template;
		return apply_filters( 'bp_get_activity_unfavorite_link', wp_nonce_url( site_url( BP_ACTIVITY_SLUG . '/unfavorite/' . $id . '/' ), 'unmark_favorite' ) );
	}

// End Custom Favorite Links to activity comments

// Generate Random Password
function IronGenPassword($length=6,$level=2){

   list($usec, $sec) = explode(' ', microtime());
   srand((float) $sec + ((float) $usec * 100000));

   $validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
   $validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
   $validchars[3] = "0123456789_!@#$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%&*()-=+/";

   $password  = "";
   $counter   = 0;

   while ($counter < $length) {
     $actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);

     // All character must be different
     if (!strstr($password, $actChar)) {
        $password .= $actChar;
        $counter++;
     }
   }

   return $password;
}

// DISABLE WORDPRESS UPDATE
add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );

# 2.8 to 3.0:
remove_action( 'wp_version_check', 'wp_version_check' );
remove_action( 'admin_init', '_maybe_update_core' );
add_filter( 'pre_transient_update_core', create_function( '$a', "return null;" ) );

# 3.0:
add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) );
// END DISABLE WORDPRESS UPDATE

// DISPLAY WHOS ONLINE

function imath_bp_display_friends(){

	global $bp;
	// Si ponemos un user id, solo muestra los amigos de ese usuario conectados
	$user_id = 0;
	$user_all_friends_url = $bp->displayed_user->domain . BP_FRIENDS_SLUG;
	?>
	<div id="friends-list" class="widget friends-list">
		<h3 class="widgettitle online"><?php _e( 'Qui&eacute;n est&aacute; en l&iacute;nea', 'buddypress' ) ?></h3>
		<div id="friends-container">
		<?php if ( bp_has_members( 'user_id='.$user_id.'&type=online&per_page=10&max=10&populate_extras=0' ) ) : ?>
			<?php while ( bp_members() ) : bp_the_member(); ?>
				<div class="item-avatar">
					<a href="<?php bp_member_permalink() ?>"><?php bp_member_avatar() ?></a>
				</div>
			<?php endwhile; ?>
		<?php else:?>
			<p>No hay nadie en l&iacute;nea !</p>
		<?php endif;?>
		</div>
		<br style="clear:both"/>
	
	<?php	
}

remove_filter('authenticate','bp_core_signup_disable_inactive', 11, 2);

function bp_core_signup_disable_inactive_with_error( $auth_obj, $username ) {
    global $bp, $wpdb;

    if ( !$user_id = bp_core_get_userid( $username ) )
        return $auth_obj;

    $user_status = (int) $wpdb->get_var( $wpdb->prepare( "SELECT user_status FROM $wpdb->users WHERE ID = %d", $user_id ) );

    if ( 2 == $user_status ) {

        define('CUSTOM_LOGIN_ERROR_MESSAGE', __('Cuenta no activada','login-with-ajax'));
        return null;

    } else {
        return $auth_obj;
    }
}
add_filter( 'authenticate', 'bp_core_signup_disable_inactive_with_error', 20, 2);

function custom_retrieve_password_message( $message, $key ) {
    $message = str_replace(array("<",">"),"", $message);
    //$message = str_replace(array("wp-login.php","kronet-login.php"),"", $message);
    return $message;
}
add_filter( 'retrieve_password_message', 'custom_retrieve_password_message', 10, 2);

// Favorite Count
function my_show_favorite_count() {
    $my_fav_count = bp_activity_get_meta( bp_get_activity_id(), 'favorite_count' );
    //if ($my_fav_count>0)
        //echo '<span style="width: 20px; height: 20px; cursor: pointer;" class="cluetip" rel="'. get_stylesheet_directory_uri () . '/_inc/tips.php" title="Test">('.$my_fav_count.')</span>';
}
add_action( 'bp_activity_entry_meta', 'my_show_favorite_count' );

// Favorite post
function my_bp_activity_is_favorite($activity_id) {
    global $bp, $activities_template;
    return apply_filters( 'bp_get_activity_is_favorite', in_array( $activity_id, (array)$activities_template->my_favs ) );
}
 
function my_bp_activity_favorite_link($activity_id) {
    global $activities_template;
    echo apply_filters( 'bp_get_activity_favorite_link', wp_nonce_url( site_url( BP_ACTIVITY_SLUG . '/favorite/' . $activity_id . '/' ), 'mark_favorite' ) );
}
 
function my_bp_activity_unfavorite_link($activity_id) {
    global $activities_template;
    echo apply_filters( 'bp_get_activity_unfavorite_link', wp_nonce_url( site_url( BP_ACTIVITY_SLUG . '/unfavorite/' . $activity_id . '/' ), 'unmark_favorite' ) );
}

function custom_mail_htmlyzer($vars) {

    if ( strpos($vars['message'], "</a>") === false) {

        // Convert string urls into links               
        preg_match('/(http:\/\/[^\s]+)/', $vars['message'], $text);
        $link = "<a title=\". $text[0] .\" href=\"". $text[0] . "\">" . $text[0] . "</a>";
        $vars['message'] = preg_replace('/(http:\/\/[^\s]+)/', $link, $vars['message']);
        }
        
    // Replace \n and \r with <br>
    $vars['message'] = str_replace(array("\r\n"), '<br />', $vars['message']);
    $vars['message'] = str_replace(array("\n"), '<br />', $vars['message']);
    $vars['message'] = str_replace(array("\r"), '<br />', $vars['message']);
        
    $cabecera = '<a title="Kronet" href="'.home_url().'/">
    <img border="0" alt="Logo" src="'.home_url().'/wp-content/themes/cvp-irontec/_inc/images/logo0.png">
    </a><br /><br />';
    
    $vars['message'] = $cabecera.$vars['message'];    

    return $vars;
}
add_filter('wp_mail', 'custom_mail_htmlyzer');

/* Redireccionar pagina de login/change password */

function iron_redirect_login () {
    wp_redirect (site_url());
}
add_action( 'login_head', 'iron_redirect_login' );

/* Agregar meta de estado de animo al marcar favoritos */
function iron_favorite_estado($activity_id, $user_id) {
    // Recogemos el estado de animo del usuario en cuestión
    // $estado_user = xprofile_get_field_data('EstadoAnimo', $user_id);

    // INSTRUCCIONES: Para recoger el estado de un favorito
    /*
    $test = get_user_meta(8, 'bp_favorite_activities_estado', true);
    var_dump($test);
    echo $test[id_activity];
    // Para borrar
    primero: get_user_meta($user_id,'bp_favorite_activities_estado', true);
    despues: unset ($test[id_activity]);
    por ultimo: update_user_meta($user_id, 'bp_favorite_activities_estado', $test);
    */

    $test=get_user_meta($user_id,'bp_favorite_activities_estado', true);
    $test[$activity_id] = xprofile_get_field_data('EstadoAnimo', $user_id);
    update_user_meta($user_id, 'bp_favorite_activities_estado', $test);
}
add_action( 'bp_activity_add_user_favorite', 'iron_favorite_estado', 10, 2 );

function modify_logout_url ($logout_url, $redirect) {

    return str_replace("wp-login.php","kronet-login.php",$logout_url);
}
//add_filter('logout_url', 'modify_logout_url', 10, 2);

// Filtro para el texto quitar datos sensibles (whois, etc.) de las notificaciones de nuevos comentarios
function iron_notification_text ($text, $comment_id) {

    $comment = get_comment($comment_id);
    $post    = get_post($comment->comment_post_ID);
    $userdata = get_userdata($comment->user_id);
    
    $text = '<a title="Kronet" href="'.home_url().'/"><img border="0" alt="Logo" src="'.home_url().'/wp-content/themes/cvp-irontec/_inc/images/logo0.png"></a><br /><br />';
    
    $text .= __ ('Han respondido a una de tus publicaciones:', 'buddypress');
    $text .= __ ('<p><b><a href="'. $post->guid .'">'. $post->post_title .'</a></b></p>', 'buddypress');
    $text .= __ ('<p><b>Autor</b>: ' . $userdata->nickname .'<br />', 'buddypress');
    $text .= __ ('<b>Comentario</b>: <em>' . $comment->comment_content .'</em></p>', 'buddypress');
    $text .= __ ('<p>Para ver el comentario pincha sobre el siguiente enlace: <a href="'. $post->guid .'">'. $post->guid .'</a></p>', 'buddypress');
    
    return $text;
}
add_filter('comment_notification_text', 'iron_notification_text', 10, 2);

// Filtro para el post de comentarios
// Otorgamos los hitos correspondientes
function iron_comment_hitos ( $comment ) {
    global $wpdb;
    $table2= $wpdb->prefix . 'achievements';
    $table3= $wpdb->prefix . 'achievements_unlocked';
    $achievement_slug_bronce = 'gua-bronce';
    $achievement_slug_plata = 'gua-plata';
    $achievement_slug_oro = 'gua-oro';

    // Contamos el nº de respuestas a preguntas que tiene publicados
    $res=$wpdb->get_results("SELECT COUNT(DISTINCT ".$wpdb->comments.".comment_ID) as counter FROM ". $wpdb->comments .", ". $wpdb->postmeta .", ". $wpdb->posts ."
    WHERE ".$wpdb->comments.".comment_approved=1 AND ".$wpdb->postmeta.".meta_value='pregunta' AND ".$wpdb->comments.".comment_post_ID=".$wpdb->posts.".ID AND
    ".$wpdb->posts.".ID=".$wpdb->postmeta.".post_id AND ".$wpdb->posts.".post_author=".bp_loggedin_user_id());
    
    // Obtener los id de los hitos
    $hito_bronce_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_bronce."'");
    $hito_plata_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_plata."'");
    $hito_oro_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_oro."'");
    
    // Bronce
    if ($res[0]->counter >=14 && $res[0]->counter <17) {
        // Otorgar hito
        $res=dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_bronce );
    }
    // Plata
    elseif ($res[0]->counter >=17 && $res[0]->counter <34) {
        // Eliminar hito bronce
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_bronce_id[0]->id);
        // Otorgar hito
        $res=dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_plata );
    }
    // Oro
    elseif ($res[0]->counter >=34) {
        // Eliminar hito bronce
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_bronce_id[0]->id);
        // Eliminar hito plata
        $wpdb->query("DELETE FROM ".$table." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_plata_id[0]->id);
        // Otorgar hito
        $res=dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_oro );
    }
    
    return $comment;
}
add_filter ('preprocess_comment', 'iron_comment_hitos', 10, 1);

// Filtro para join event
// Otorgamos los hitos correspondientes
function iron_join_event_hitos ($event_id, $user_id) {
    global $wpdb;
    $table='wp_jet_events_members';
    $table2= $wpdb->prefix . 'achievements';
    $table3= $wpdb->prefix . 'achievements_unlocked';
    $achievement_slug_bronce = 'social-bronce';
    $achievement_slug_plata = 'social-plata';
    $achievement_slug_oro = 'social-oro';
    
    // Contar el nº de items
    $res=$wpdb->get_results("SELECT COUNT(DISTINCT id) as counter FROM ".$table." WHERE user_id=".bp_loggedin_user_id());
    
    // Obtener los id de los hitos
    $hito_bronce_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_bronce."'");
    $hito_plata_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_plata."'");
    $hito_oro_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_oro."'");
    
    // Bronce
    if ($res[0]->counter >=3 && $res[0]->counter <5) {
        // Otorgar hito
        $res=dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_bronce );
    }
    // Plata
    elseif ($res[0]->counter >=5 && $res[0]->counter <10) {
        // Eliminar hito bronce
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_bronce_id[0]->id);
        // Otorgar hito
        $res=dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_plata );
    }
    // Oro
    elseif ($res[0]->counter >=10) {
        // Eliminar hito bronce
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_bronce_id[0]->id);
        // Eliminar hito plata
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_plata_id[0]->id);
        // Otorgar hito
        $res=dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_oro );
    }
}
add_filter ('events_join_event', 'iron_join_event_hitos', 10, 2);

// Filtro para create group
// Otorgamos los hitos correspondientes
function iron_create_group_hitos ($group_id, $creator_id) {
    global $wpdb;
    $table= $wpdb->prefix . 'bp_groups';
    $table2= $wpdb->prefix . 'achievements';
    $table3= $wpdb->prefix . 'achievements_unlocked';
    $achievement_slug_bronce = 'animador-bronce';
    $achievement_slug_plata = 'animador-plata';
    $achievement_slug_oro = 'animador-oro';
    
    // Contar el nº de items
    $res=$wpdb->get_results("SELECT COUNT(DISTINCT id) as counter FROM ".$table." WHERE creator_id=".bp_loggedin_user_id());
    
    // Obtener los id de los hitos
    $hito_bronce_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_bronce."'");
    $hito_plata_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_plata."'");
    $hito_oro_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_oro."'");
    
    // Bronce
    if ($res[0]->counter >=5 && $res[0]->counter <10) {
        // Otorgar hito
        $res=dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_bronce );
    }
    // Plata
    elseif ($res[0]->counter >=10 && $res[0]->counter <15) {
        // Eliminar hito bronce
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_bronce_id[0]->id);
        // Otorgar hito
        $res=dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_plata );
    }
    // Oro
    elseif ($res[0]->counter >=15) {
        // Eliminar hito bronce
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_bronce_id[0]->id);
        // Eliminar hito plata
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_plata_id[0]->id);
        
        // Otorgar hito
        $res=dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_oro );
    }
}
add_filter ('groups_create_group', 'iron_create_group_hitos', 10, 2);

// Filtro para add_user_favorite
// Otorgamos los hitos correspondientes
function iron_activity_add_user_favorite_hitos ($activity_id, $user_id) {
    global $wpdb;
    $table= '';
    $table2= $wpdb->prefix . 'achievements';
    $table3= $wpdb->prefix . 'achievements_unlocked';
    $achievement_slug_bronce = 'opinion-bronce';
    $achievement_slug_plata = 'opinion-plata';
    $achievement_slug_oro = 'opinion-oro';
    
    // Contar el nº de items
    $usermeta=get_user_meta(bp_loggedin_user_id(), 'bp_favorite_activities');
    $num=sizeof($usermeta[0]);
    
    // Obtener los id de los hitos
    $hito_bronce_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_bronce."'");
    $hito_plata_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_plata."'");
    $hito_oro_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_oro."'");
    
    // Bronce
    if ($num >=15 && $num <25) {
        // Otorgar hito
        dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_bronce );
    }
    // Plata
    elseif ($num >=25 && $num <35) {
        // Eliminar hito bronce
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_bronce_id[0]->id);
        // Otorgar hito
        dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_plata );
    }
    // Oro
    elseif ($num >=35) {
        // Eliminar hito bronce
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_bronce_id[0]->id);
        // Eliminar hito plata
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_plata_id[0]->id);
        // Otorgar hito
        dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_oro );
    }
}
add_filter ('bp_activity_add_user_favorite', 'iron_activity_add_user_favorite_hitos', 10, 2);

// Filtro para activity_posted_update
// Otorgamos los hitos correspondientes
function iron_activity_posted_update_hitos ($content, $user_id) {
    global $wpdb;
    $table= $wpdb->prefix . 'bp_activity';
    $table2= $wpdb->prefix . 'achievements';
    $table3= $wpdb->prefix . 'achievements_unlocked';
    $achievement_slug_bronce = 'generosidad-bronce';
    $achievement_slug_plata = 'generosidad-plata';
    $achievement_slug_oro = 'generosidad-oro';
    
    // Contar el nº de items
    $res=$wpdb->get_results("SELECT COUNT(DISTINCT id) as counter FROM ".$table." WHERE user_id=".bp_loggedin_user_id());
    
    // Obtener los id de los hitos
    $hito_bronce_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_bronce."'");
    $hito_plata_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_plata."'");
    $hito_oro_id=$wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_oro."'");
    
    // Bronce
    if ($res[0]->counter >=15 && $res[0]->counter < 25) {
        // Otorgar hito
        dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_bronce );
    }
    // Plata
    elseif ($res[0]->counter >=25 && $res[0]->counter < 35) {
        // Eliminar hito bronce
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_bronce_id[0]->id);
        // Otorgar hito
        dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_plata );
    }
    // Oro
    elseif ($res[0]->counter >=35) {
        // Eliminar hito bronce
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_bronce_id[0]->id);
        // Eliminar hito plata
        $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_plata_id[0]->id);
        // Otorgar hito
        dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_oro );
    }
}
add_filter ('bp_activity_posted_update', 'iron_activity_posted_update_hitos', 10, 2);

// NOTIFICACIONES AL POSTEAR ACTIVITY COMMENTS
/*
function ac_notifier_notify($comment_id, $params){
    global $bp;
    extract( $params );
               
    // Agregar la notificacion
    $activity=new BP_Activity_Activity($activity_id);
    bp_core_add_notification($params['activity_id'], $activity->user_id, 'activity', 'new_activity_comment');
        
    //var_dump($params);
    //echo "act: ".$params[activity_id];
    //echo "<br />user: ".$params[user_id];
    
    $comment = get_comment($comment_id);
    $post    = get_post($comment->comment_post_ID);
    $userdata = get_userdata($activity->user_id);
    $posterdata = get_userdata($params[user_id]);
    
    //var_dump($userdata);
    //var_dump ($activity);
    
    echo '<br />autor: '.$posterdata->nickname;
    echo '<br />content: '.$params[content];
    echo '<br />email: '.$userdata->user_email;
    echo '<br />perma: <a href="'. site_url() .'/activity/p/'. $activity_id .'">link</a>';
    exit ();
    
    $text = __ ('Han respondido a una de tus publicaciones del muro:', 'buddypress');
    $text .= __ ('<p><b><a href="'. site_url() .'/activity/p/'. $activity_id .'">link</a></b></p>', 'buddypress');
    $text .= __ ('<p><b>Autor</b>: ' . $posterdata->nickname .'<br />', 'buddypress');
    $text .= __ ('<b>Comentario</b>: <em>' . $params[content] .'</em></p>', 'buddypress');
    $text .= __ ('<p>Para ver el comentario pincha sobre el siguiente enlace: <a href="'. site_url() .'/activity/p/'. $activity_id .'">ver comentario</a></p>', 'buddypress');
    
    // Solo mandamos esto al admin porque a los usuarios se los manda el sistema
    if ( user_can ( $activity->user_id, 'manage_options' ) ) {
    	wp_mail ($userdata->user_email, 'Kronet: nuevo comentario', $text);
    }
}
add_action("bp_activity_comment_posted","ac_notifier_notify",10,2);///hook to comment_posted for adding notification
*/

// Esta funcion quita el HTML de los profile fields
// para evitar comportamientos raros como spameo
function custom_sanitize ($field_value, $field_id) {    
    $processed_value = strip_tags ($field_value);
    return $processed_value;
}
add_action ('xprofile_data_value_before_save','custom_sanitize', 10, 2);

// Guardar el estado de animo del creador de cada grupo
function group_save_estado ( $group ) {    
    $user_mood = xprofile_get_field_data( 'EstadoAnimo', $group->creator_id);
    groups_update_groupmeta($group->id, 'ironestado', $user_mood);
}
add_action ('groups_group_after_save', 'group_save_estado', 10, 1);

// Guardar el estado de animo de los comentarios
function comments_save_estado ( $comment_ID ) {
    $commentdata = get_comment ( $comment_ID );
    $user_mood = xprofile_get_field_data( 'EstadoAnimo', $commentdata->user_id);        
    update_comment_meta($comment_ID, 'ironestado', $user_mood);
}
add_action ('comment_post', 'comments_save_estado', 10, 1);
?>
