<?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>'
    )
);

$wpdb->query( $wpdb->prepare( "DELETE FROM wp_bp_notifications WHERE user_id = %d AND component_name = %s AND component_action = %s", get_current_user_id(),'achievements','new_achievement' ) );

/**
 * 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;
    
    if ( 'pingback' == $comment->comment_type ) return false;
    
    
    /**
     * 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>
                <span id="mentions">@<?php echo get_userdata( $comment->user_id )->user_login; ?></span>
                <?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(\''. __ ('Delete Comment?','buddypress') .'\')) {return false;}">' . __('Delete','buddypress') . '</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);
    
    /**
     * Email confirmación de registro
     */
    
    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 );
        
        $username = $user_obj->user_login;
        
        /**
         * Email subject
         */
        if ($mensaje == "") {
            $asunto = __('Pulsa el enlace y disfruta de Kronikoen Sarea', "buddypress");
        }
        
        /**
         * Email data
         */
        if ($mensaje == "") {
            
            $mensaje = sprintf(
            __('<p>Hola, %s </p>
            
            <p>Solo te falta pulsar este enlace para finalizar el registro en <b>kronikoensarea.net</b></p>
            <p><a href="%s">%s</a></p>
            
            <p>Una vez confirmado, podrás acceder a la comunidad con los datos que introdujiste al principio del mismo (usuario y contraseña).</p>
            
            <p>Muchísimas gracias. Nos vemos muy pronto.</p>
            
            <p>El equipo de <b>kronikoensarea.net</b></p>
            <a href="mailto:kronikoensarea@oberri.org">kronikoensarea@oberri.org</a>', "buddypress"), $username, $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;
            }
        }
        
        /**
         * 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 );
    }
    
    function br2nl($str) {
       $str = preg_replace("/(\r\n|\n|\r)/", "", $str);
       return preg_replace("=<br */?>=i", "\n", $str);
    }
    
    /**
     * 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 );
                
                $classmeta       = classMetaEstadoAnimo($currentusermood);
                $classbackground = classBackgroundEstadoAnimo($postmood);
                
                /**
                 * Fin colores de estado
                 */
                
                $content .= '<li id="acomment-' . $comment->id . '" class="'. $classbackground .'">';
                $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> <span id="mentions">@'. $comment->user_login .'</span>';
                $content .= '&middot; ' . 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
                 */
                
                $conte = $conte2 = $act_content =  $ContectClear = "";
                
                if (!$bp->current_action || $bp->current_action=='just-me' || $bp->current_action=='home') {
                    
                    $act_content = contenidoMuroCorto($comment->content);
                    
                } else {
                    
                    $act_content = contenidoMuroCompleto($comment->content);
                    
                }
             
/*		if ($_POST['action'] == 'activity_get_older_updates' && $_POST['page'] == 4) {
			

//var_dump($comment); exit;

			//$act_content = "**" . utf8_encode($act_content) . "<!-- ".print_r($comment, true)." -->" ; //utf8_encode($act_content);	
			//$act_content = "**" . utf8_encode($act_content) . "<!-- ".print_r($comment, true)." -->" ; //utf8_encode($act_content);	

				$foo = array(
					'a' => $act_content
				);

				$x = json_encode($foo);
			
//			$act_content =  utf8_encode($act_content);
		} 
  */ 
                $content .= '<div class="acomment-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" id="'.$comment->id.'">' . __( 'Me gusta', 'buddypress' ) .'</a>';
                            if ($my_fav_count > 0) {
                                
                                $content .= '<span id="me-gusta-count-'.$comment->id.'" rel="'. get_stylesheet_directory_uri() .'/_inc/tips.php?id='. $comment->id .'&act=fav" class="cluetip fav-count">('. $my_fav_count .')</span>';
                            } else {
                                
                                $content .= '<span id="me-gusta-count-'.$comment->id.'" 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" id="'.$comment->id.'">' . __( 'Ya no me gusta', 'buddypress' ) .'</a>';
                            if ($my_fav_count > 0) {
                                
                               $content .= '<span id="me-gusta-count-'.$comment->id.'" 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>';
                            }
                        }
                    }
                    
                    $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><?php _e('No hay nadie en línea!', 'buddypress')?></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="kronikoensarea" 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="kronikoensarea" 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;
    }
    /**
     * dani - irontec - quitar hitos
     * 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 );
        }
    }
    /**
     * dani - irontec - quitar hitos
     * 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 );
        }
    }
    /**
     * dani - irontec - quitar hitos
     * 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 );
        }
    }
    /**
     * dani - irontec - quitar hitos
     * 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 );
        }
    }
    /**
     * dani - irontec - quitar hitos
     * 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);

    /**
     * Genera los links de la nueva home en base al $_COOKIE['LANG']
     * Paginas: *Activate *Passreset
     * @param string $lang
     */
    
    function header_home_links_registration ( $lang ) {
        
        switch ( $lang ) {
            case 'es':
                $lang = 'es_ES';
                $urlProyecto = get_option('home') . '/el_proyecto_es/';
                $urlRecomienda = 'http://recomienda.kronikoensarea.net/?lang=es';
                $urlPrensa = get_option('home') . '/prensa_es/';
                $urlAyuda = get_option('home') . '/ayuda_es/';
                $urlContact = get_option('home') . '/contacto_es/';
                break;
            case 'en':
                $lang = 'en_US';
                $urlProyecto = get_option('home') . '/el_proyecto_en/';
                $urlRecomienda = 'http://recomienda.kronikoensarea.net/?lang=en';
                $urlPrensa = get_option('home') . '/prensa_en/';
                $urlAyuda = get_option('home') . '/ayuda_en/';
                $urlContact = get_option('home') . '/contacto_en/';
                break;
                
            case 'eu':
                $lang = 'eu_ES';
                $urlProyecto = get_option('home') . '/el_proyecto_eu/';
                $urlRecomienda = 'http://recomienda.kronikoensarea.net/?lang=eu';
                $urlPrensa = get_option('home') . '/prensa_eu/';
                $urlAyuda = get_option('home') . '/ayuda_eu/';
                $urlContact = get_option('home') . '/contacto_eu/';
                break;
                
            default:
                $lang = 'es_ES';
                $urlProyecto = get_option('home') . '/el_proyecto_es/';
                $urlRecomienda = 'http://recomienda.kronikoensarea.net/?lang=es';
                $urlPrensa = get_option('home') . '/prensa_es/';
                $urlAyuda = get_option('home') . '/ayuda_es/';
                $urlContact = get_option('home') . '/contacto_es/';
                break;
        }
        ?>
            <h1 id="logo">
                <a href="<?php echo site_url()?>" title="<?php _e( 'Home', 'buddypress' ) ?>">
                    <img src="<?php echo get_stylesheet_directory_uri() ?>/_inc/images/Home/logo_KronikoenSarea.png" alt="Logo" />
                </a>
            </h1>
            <div class="iron-slogan">
                <a href="<?php echo $urlProyecto ?>"><?php _e('El proyecto','buddypress'); ?></a>
                <a href="<?php echo $urlRecomienda ?>"><?php _e('Recomienda','buddypress'); ?></a>
                <a href="<?php echo $urlPrensa ?>"><?php _e('Prensa','buddypress'); ?></a>
                <a href="<?php echo $urlAyuda ?>"><?php _e('Ayuda','buddypress'); ?></a>
                <a href="<?php echo $urlContact ?>"><?php _e('Contacto','buddypress'); ?></a>
                <hr />
            </div>
        <?php
    }

    /**
     * Genera los links de la nueva home en base al $_COOKIE['LANG']
     * Paginas: *index *page-view *page-view2
     * @param string $lang
     */
    
    function iron_slogan_home( $lang ) {
    
        switch ( $lang ) {
            case 'es':
                $lang           = 'es_ES';
                
                $inicioTitle    = 'Inicio';
                $proyectoTitle  = 'Conoce Kronikoen Sarea';
                $ayudaTitle     = 'Primeros pasos';
                $contactoTitle  = 'Contacto';
                
                $urlInicio      = get_option('home');
                $urlProyecto    = get_option('home') . '/el_proyecto_es/';
                $urlAyuda       = get_option('home') . '/ayuda_es/';
                $urlContact     = get_option('home') . '/contacto_es/';
            break;
            
            case 'en':
                $lang           = 'en_US';
                
                $inicioTitle    = 'Home';
                $proyectoTitle  = 'About Kronikoen Sarea';
                $ayudaTitle     = 'First Steps';
                $contactoTitle  = 'Contact';
                
                $urlInicio      = get_option('home');
                $urlProyecto    = get_option('home') . '/el_proyecto_en/';
                $urlAyuda       = get_option('home') . '/ayuda_en/';
                $urlContact     = get_option('home') . '/contacto_en/';
            break;
            
            case 'eu':
                $lang           = 'eu_ES';
                
                $inicioTitle    = 'Hasiera';
                $proyectoTitle  = 'Ezagutu Kronikoen Sarea';
                $ayudaTitle     = 'Lehenengo hurratsak';
                $contactoTitle  = 'Harremana';
                
                $urlInicio      = get_option('home');
                $urlProyecto    = get_option('home') . '/el_proyecto_eu/';
                $urlAyuda       = get_option('home') . '/ayuda_eu/';
                $urlContact     = get_option('home') . '/contacto_eu/';
            break;
            
            default:
                $lang           = 'es_ES';
                
                $inicioTitle    = "Inicio";
                $proyectoTitle  = "Conoce Kronikoen Sarea";
                $ayudaTitle     = 'Primeros pasos';
                $contactoTitle  ='Contacto';
                
                $urlInicio      = get_option('home');
                $urlProyecto    = get_option('home') . '/el_proyecto_es/';
                $urlAyuda       = get_option('home') . '/ayuda_es/';
                $urlContact     = get_option('home') . '/contacto_es/';
            break;
        }
        ?>
            <a href="<?php echo $urlInicio ?>" ><?php echo $inicioTitle ?></a>
            <a href="<?php echo $urlProyecto ?>" <?php echo (get_query_var('pagename') == 'el_proyecto_' . $_COOKIE['LANG'])? 'style="background: #F3F3F4;"' : '' ?>><?php echo $proyectoTitle ?></a>
            <a href="<?php echo $urlAyuda ?>" <?php echo (get_query_var('pagename') == 'ayuda_' . $_COOKIE['LANG'])? 'style="background: #F3F3F4;"' : '' ?>><?php echo $ayudaTitle ?></a>
            <a href="<?php echo $urlContact ?>" <?php echo (get_query_var('pagename') == 'contacto_' . $_COOKIE['LANG'])? 'style="background: #F3F3F4;"' : '' ?>><?php echo $contactoTitle ?></a>
        <?php
    }
    
    /**
     * Video de Kronikoen Sarea segun el $_COOKIE['LANG']
     * Paginas: *index
     * @param string $lang
     */
    
    function youtube_home( $lang ) {
    
         if ($lang == 'eu') {
             $url = 'https://www.youtube.com/embed/8cF9fRrXO5Q';
         } else {
             $url = 'https://www.youtube.com/embed/JQybrVvxF5Y';
         }
         ?>
         <iframe width="317" height="215" src="<?php echo $url ?>" frameborder="0" allowfullscreen></iframe>
         <?php
    }
    
    /**
     * Genera los links del footer en base al $_COOKIE['LANG']
     * @param string $lang
     */
    
    function footer_home_links ( $lang ) {
        
        echo '<a title="' . __( 'Inicio', 'buddypress' ) . '" href="'. site_url() .'">'. __( 'Inicio', 'buddypress' ) .'</a>';
        echo '&nbsp;|&nbsp;<a title="FAQ" href="'. site_url() .'/faq_'.$lang.'/" >'. __('FAQ','buddypress') .'</a>';
        echo '&nbsp;|&nbsp;<a title="'. __('Pol&iacute;tica de Privacidad','buddypress') .'" href="'. site_url() .'/politica-de-privacidad_'.$lang.'/">'. __('Pol&iacute;tica de privacidad','buddypress') .'</a>';
        echo '&nbsp;|&nbsp;<a title="'. __('Condiciones de uso','buddypress') .'" href="'. site_url() .'/condiciones-de-uso_'.$lang.'/">'. __('Condiciones de uso','buddypress') .'</a>';
        echo '&nbsp;|&nbsp;<a title="'. __ ('Denunciar contenido','buddypress') .'" class="fancybox-denuncias" href="'. site_url() .'/denuncias-modal/">'. __('Denunciar','buddypress') .'</a>';
        
    }
    
    /**
     * Genera el contenido del nav de las paginas *footer y *footer-home
     * @param string $lang
     */
    
    function footer_nav_home ( $lang ) {
    
        switch ( $lang ) {
            case 'es':
                $urlProyecto = 'http://recomienda.kronikoensarea.net/';
                $urlPrensa = get_option('home') . '/prensa_es/';
                $urlAyuda = get_option('home') . '/ayuda_es/';
                $urlContact = get_option('home') . '/contacto_es/';
                $urlCondiciones = get_option('home') . '/condiciones-de-uso_es/';
                $urlTerminos = get_option('home') . '/politica-de-privacidad_es/';
                
                $proyectoTitle = "Recomienda Kronikoen Sarea";
                $recomiendaTitle = "Recomienda";
                $prensaTitle = 'Prensa';
                $ayudaTitle = 'Ayuda';
                $contactoTitle='Contacto';
                
                $condicionesTitle = 'Condiciones';
                $privacidadTitle = 'Privacidad';
                $yTitle = 'y';
                break;
            case 'en':
                $urlProyecto = get_option('home') . '/el_proyecto_en/';
                
                $urlProyecto = 'http://recomienda.kronikoensarea.net/';
                
                $urlPrensa = get_option('home') . '/prensa_en/';
                $urlAyuda = get_option('home') . '/ayuda_en/';
                $urlContact = get_option('home') . '/contacto_en/';
                $urlCondiciones = get_option('home') . '/condiciones-de-uso_en/';
                $urlTerminos = get_option('home') . '/politica-de-privacidad_en/';
                
                $proyectoTitle = "Recommend Kronikoen Sarea";
                $recomiendaTitle = "Recommend";
                $prensaTitle = 'Press';
                $ayudaTitle = 'Help';
                $contactoTitle='Contact';
                
                $condicionesTitle = 'Conditions';
                $privacidadTitle = 'Terms';
                $yTitle = 'and';
                break;
                
            case 'eu':
                $urlProyecto = get_option('home') . '/el_proyecto_eu/';
                
                $urlProyecto = 'http://recomienda.kronikoensarea.net/';
                
                $urlPrensa = get_option('home') . '/prensa_eu/';
                $urlAyuda = get_option('home') . '/ayuda_eu/';
                $urlContact = get_option('home') . '/contacto_eu/';
                $urlCondiciones = get_option('home') . '/condiciones-de-uso_eu/';
                $urlTerminos = get_option('home') . '/politica-de-privacidad_eu/';
                
                $proyectoTitle = "Gomendatu Kronikoen Sarea";
                $recomiendaTitle = "Gomendatu";
                $prensaTitle = 'Prentsa';
                $ayudaTitle = 'Laguntza';
                $contactoTitle='Harremana';
                
                $condicionesTitle = 'Baldintzak';
                $privacidadTitle = 'Pribatasuna';
                $yTitle = 'eta';
                
                break;
                
            default:
                $urlProyecto = get_option('home') . '/el_proyecto_es/';
                
                $urlProyecto = 'http://recomienda.kronikoensarea.net/';
                
                $urlPrensa = get_option('home') . '/prensa_es/';
                $urlAyuda = get_option('home') . '/ayuda_es/';
                $urlContact = get_option('home') . '/contacto_es/';
                $urlCondiciones = get_option('home') . '/condiciones-de-uso_es/';
                $urlTerminos = get_option('home') . '/politica-de-privacidad_es/';
                
                $proyectoTitle = "Recomienda Kronikoen Sarea";
                $recomiendaTitle = "Recomienda";
                $prensaTitle = 'Prensa';
                $ayudaTitle = 'Ayuda';
                $contactoTitle='Contacto';
                
                $condicionesTitle = 'Condiciones';
                $privacidadTitle = 'Privacidad';
                $yTitle = 'y';
                break;
        }
        
        ?>
        <div class="menu-sec-container">
            <ul id="menu-sec" class="menu">
            <li id="menu-item-100" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-100">
                <a href="<?php echo $urlProyecto ?>"><?php echo $proyectoTitle; ?></a>
            </li>
            <li id="menu-item-101" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-101">
                <a href="<?php echo $urlPrensa ?>"><?php echo $prensaTitle ?></a>
            </li>
            <li id="menu-item-102" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-102">
                <a href="<?php echo $urlAyuda ?>"><?php echo $ayudaTitle;?></a>
            </li>
            <li id="menu-item-103" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-103">
                <a href="<?php echo $urlCondiciones ?>">
                <?php  echo $condicionesTitle;?> 
                </a> 
                <?php  echo $yTitle;?>
                <a href="<?php echo $urlTerminos ?>"> 
                <?php  echo $privacidadTitle;?>
                </a> 
            </li>
            <li id="menu-item-99" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-99">
                <a href="<?php echo $urlContact ?>"><?php echo $contactoTitle; ?></a>
            </li>
            </ul>
        </div>
        <?php
    }
    
    /**
     * Anula la admin bar de wordpress
     */
    function my_function_admin_bar(){
        return false;
    }
    add_filter( 'show_admin_bar' , 'my_function_admin_bar');
    
    /**
     * 
     * Enter description here ...
     * @author dani
     * @param String $links links de videos detectados 395x320
     */
    
    function LinksYoutube( $links = null ) {
        
        $links = str_replace('&amp;','&',(str_replace('&#038;','&',$links)));
        $links = explode('?', $links);
        
        $parameters = array();
        parse_str($links[1], $parameters);
        
        if ($parameters['v']) {
            
            $testa = $parameters['v'];
            list($parameters['v']) = $testa;
            
            $parUrl = explode(' ', $testa, 2);
            
            $video = '<iframe src="https://www.youtube.com/embed/' . $parUrl[0] . '/?feature=oembed" allowfullscreen="true" width="395" height="320"></iframe>';
            
        } else {
            
            $link = explode('/',$links[0]);
            
            if ($link['2'] == 'youtu.be') {
                $video = '<iframe src="https://www.youtube.com/embed/' . $link['3'] . '/?feature=oembed" allowfullscreen="true" width="395" height="320"></iframe>';
            } else {
                $video = $link;
            }
        }
        
        return $video;
    }
    
    /**
     * 
     * Enter description here ...
     * @author dani
     * @param String $links links de videos detectados 350x250
     */
    
    function LinksYoutubeSmall( $links = null ) {
        
        $links = str_replace('&amp;','&',(str_replace('&#038;','&',$links)));
        $links = explode('?', $links);
        
        $parameters = array();
        parse_str($links[1], $parameters);
        
        if ($parameters['v']) {
            
            $testa = $parameters['v'];
            list($parameters['v']) = $testa;
            
            $parUrl = explode(' ', $testa, 2);
            
            $video  = '<iframe src="https://www.youtube.com/embed/' . $parUrl[0] . '/?feature=oembed" allowfullscreen="true" width="350" height="250"></iframe>';
            
        } else {
            
            $link = explode('/',$links[0]);
            
            if ($link['2'] == 'youtu.be') {
                $video = '<iframe src="https://www.youtube.com/embed/' . $link['3'] . '/?feature=oembed" allowfullscreen="true" width="350" height="250"></iframe>';
            } elseif($links[0]) {
                $video = '<iframe src="https://' . $links[0] . '/?feature=oembed" allowfullscreen="true" width="350" height="250"></iframe>';
            } else {
                $video = $link;
            }
        }
        
        return $video;
    }
    
    /**
     * comprueba si el link que se le pasa es de youtube o de vimeo
     * @param string $url
     */
    function parse_yturl($url) {
        
        $pattern  = '#^(?:https?://)?';    # Optional URL scheme. Either http or https.
        $pattern .= '(?:www\.)?';         #  Optional www subdomain.
        $pattern .= '(?:';                #  Group host alternatives:
        $pattern .=   'youtu\.be/';       #    Either youtu.be,
        $pattern .=   '|youtube\.com';    #    or youtube.com
        $pattern .=   '(?:';              #    Group path alternatives:
        $pattern .=     '/embed/';        #      Either /embed/,
        $pattern .=     '|/v/';           #      or /v/,
        $pattern .=     '|/watch\?v=';    #      or /watch?v=,    
        $pattern .=     '|/watch\?.+&v='; #      or /watch?other_param&v=
        $pattern .=   ')';                #    End path alternatives.
        $pattern .= ')';                  #  End host alternatives.
        $pattern .= '([\w-]{11})';        # 11 characters (Length of Youtube video ids).
        $pattern .= '(?:.+)?$#x';         # Optional other ending URL parameters.
        
        preg_match($pattern, $url, $matches);
        
        if (isset($matches[1])) {
            
            return $matches[1];
        } else {
            $url2 = str_replace('#038;', '', str_replace('amp;', '', str_replace('&', '', $url)));
            preg_match($pattern, $url2, $matches2);
            
            if (isset($matches2[1])) {
                return $matches2[1];
            } else {
                
                $patternVimeo  = '#^(?:https?://)?';
                $patternVimeo .= '(?:www\.)?';
                $patternVimeo .= '(';
                $patternVimeo .=   'player\.vimeo\.com/';
                $patternVimeo .=   '|vimeo\.com/)';
                $patternVimeo .=     '(';
                $patternVimeo .=       'video/';
                $patternVimeo .=       '|m/';
                $patternVimeo .=       '|';
                $patternVimeo .=       '|(album)/([0-9]+)/video/';
                $patternVimeo .=     ')';
                $patternVimeo .= '([0-9]+)#i';
                
                preg_match_all($patternVimeo, $url2, $vimeo);
                
                if (sizeof($vimeo) == 6) {
                    $album = $vimeo[3][0] == 'album';
                    
                    if ($album) {
                        $albumNumber = $vimeo[4][0];
                    } else {
                        $albumNumber = false;
                    }
                    
                    $video = $vimeo[5][0];
                    
                }
                
                $match = array($video, $album, $albumNumber);
                
                if ( $vimeo[0] != NULL ) {
                    return $match;
                } else {
                    return false;
                }
            }
        }
    }
    
    /**
     * crea un iframe de youtube con el hash del video
     * @param string $code
     */
    function direcYoutube($code) {
        
        return '<br /><iframe src="https://www.youtube.com/embed/' . $code . '/?feature=oembed" allowfullscreen="true" width="350" height="250"></iframe><br />';
    }
    
    /**
     * crea un iframe de Vimeo
     * @param String $url
     */
    function direcVimeo( $code ) {
        
        return '<br /><iframe src="https://player.vimeo.com/video/' . $code[0] . '/?badge=0" width="350" height="250" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe><br />';
        
    }
    
    /**
     * comprueba que es un videos de vimeo
     * @param string $url
     */
    
    function is_vimeo($url) {
    
        if ( is_array($url) and sizeof($url) == 3 ) {
            return $url;
        } else {
            return false;
        }
        
    }
    
    /**
     * se comprueba si es un enlace url y lo mete en su etiqueta <a .... ></a>
     * @param string $contect
     */
    function is_enlaceUrl( $contect ) {
        
        if(filter_var(trim($contect), FILTER_VALIDATE_URL) === FALSE) {
            return false;
        }else{
            
            return '<a href="' . trim($contect) .'" title="' . trim($contect) .'" >' . trim($contect) .'</a>';
        }
        
    }
    
    /**
     * Cambia las menciones @mencios por su nombe
     * usuarios / grupos
     * @author dani
     * @param String $contenido
     */
    
    function filter_mentions($contenido) {
        global $wpdb;
        preg_match_all("|<[^>]+>@(.*)</[^>]+>|U", $contenido, $menciones, PREG_PATTERN_ORDER);
        
        if (count($menciones[1]) == 0) {
            $tweet = preg_replace('/(^|[^a-z0-9_])@([a-z0-9_]+)/i', '@$2', $contenido);
            
                if (strstr($tweet,'@')) {
                    
                    if (substr_count(strstr($tweet,'@'),'@') > 1) {
                        
                        foreach (explode('@', strstr($tweet,'@')) as $value) {
                            if ($value != '') {
                                $value     = ereg_replace("[^A-Za-z0-9]", "", $value);
                                $idUser    = get_user_by('login', $value)->ID;
                                $UserName  = xprofile_get_field_data( 'Nombre', $idUser);
                                $content  .= ' <a href="'.home_url('/miembros/' . $value .'/') . '" title="' . $UserName . '">' . $UserName . '</a> ';
                            }
                            
                        }
                        
                    } else {
                        
                        //$tweetN    = ereg_replace("[^A-Za-z0-9]", "", $tweet);
                        $idMention = get_user_by('login', str_replace('@', '', $tweet))->ID;
                        
                        if ($idMention) {
                            
                            $NameUser  = xprofile_get_field_data( 'Nombre', $idMention);
                            $content   = ' <a href="'.home_url('/miembros/'.str_replace('@', '', $tweet).'/').'" title="' . $NameUser . '">' . $NameUser . '</a> ';
                        } else {
                            
                            $gropuQuery = 'select * from wp_bp_groups where slug = "' . str_replace('@', '', $tweet) . '"';
                            $group      = $wpdb->get_row($wpdb->prepare($gropuQuery));
                            
                            if ($group) {
                                
                                $content = '<a href ="' . get_option('home') . '/grupos/' . $group->slug . '" title="' . $group->name . '">' . $group->name . '</a>';
                                
                            } else {
                                $content = $tweet;
                            }
                            
                        }
                    } 
                    
                } else {
                    $content  = $tweet;
                }
                
            } else {
                
                foreach ($menciones[1] as $mencion) {
                    if ($mencion == 'admin') {
                        $idMention = '1';
                    } else {
                        $idMention = get_user_by('login', $mencion)->ID;
                    }
                    
                        $NameUser[] = xprofile_get_field_data( 'Nombre', $idMention);
                        
                    if ($idMention != null) {
                        $twet[] = '/\@'.$mencion . '/'; 
                    } else {
                        // es una mencion erronea, asi se deja igual.
                        $twet[] = '/\@-'.$mencion . '/';
                    }
                    
                }
                
                if (!isset($twet)) {
                    $content = $contenido;
                } else {
                    $content = preg_replace($twet, $NameUser, $contenido);
                }
            }
            
        return $content;
    }
    
    /**
     * Comprobamos si el usuario tiene su privacidad en "Privado"
     * @author dani
     * @param String $user_id
     */
    function check_private_profile($user_id) {
        
        return xprofile_get_field_data( 'Privacidad', $user_id) == 'Privado';
    }
    
    /**
     * Comprobamos que sc se esta usando actualmente para filtrar en el muro
     * @author dani
     * @param String $sc valor del litrado solo yo/mis amigos y yo/grupos/todos
     */
    function check_scFilterMuro($sc) {
        
        $sc = trim( strip_tags($sc) );
        
        if ($sc == '') {
            
            $server_referer = $_SERVER['HTTP_REFERER'];
            
            if (isset($server_referer)) {
                
                $referalURL = parse_url($server_referer);
                if (isset($referalURL['query'])) {
                    
                    $parameters = array();
                    parse_str($referalURL['query'], $parameters);
                    
                   if (isset($parameters['sc'])) {
                       
                       $result = $parameters['sc'];
                   }
                } else {
                    $result = 'all';
                }
                
            } elseif ($sc != 'all' && !$sc) {
                
                $result = 'all';
                
            }
            
        } else {
            $result = $sc;
        }
        
        return $result;
    }
    
    /**
     * Comprobamos el estado por el cual se quiere filtrar el muro
     * (se saca por $_POST y $_GET para enviar el filtrado de ajax.php/global.js )
     * @author dani
     * @param String $ironEstadoP filtrado por $_POST del estado de amino
     * @param String $ironEstadoG filtrado por $_GET  del estado de amino
     */
    
    function check_ironEstadoFilterMuro($ironEstadoP = null, $ironEstadoG = null){
        
        if ($ironEstadoG != '') {
            $result = $ironEstadoG;
        } elseif ($ironEstadoP  != '') {
            $result = $ironEstadoP;
        }
        
        return $result;
    }
    
    /**
     * Comprobamos el tipo de actividad que es y devuelve el estado de animo con el que se guardo (clase para el style del estado de animo)
     * * Cuando son blog posts, el estado se guarda en post_meta
     * * Cuando son grupos, cogemos el meta de group_meta
     * * Cuando son eventos, cogemos el meta de events_meta
     * @author dani
     * @param String $type       bp_get_activity_type()
     * @param String $post_mood  si en la comprobacion anterior es igual "current_mood" el meta_key existe
     */
    
    function check_activity_estado( $type, $post_mood = null ) {
        
        if ($type == 'new_blog_post') {
            $result = get_post_meta($postd->ID, 'iron-estado', true);
        } elseif ($type == 'created_group') {
            $result = groups_get_groupmeta(bp_get_activity_item_id(), 'ironestado');
        } elseif ($type == 'created_event') {
            $result = events_get_eventmeta(bp_get_activity_item_id(), 'ironestado');
        }
        
        $classbackground = "";
        
        if ($post_mood == "familiares" || $postm1[0] == "familiares" || $result == "familiares") {
            $result="ac01";
        } elseif ($post_mood == "sintomaticos" || $postm1[0] == "sintomaticos" || $result == "sintomaticos") {
            $result="ac03";
        } elseif ($post_mood == "reflexivos" || $postm1[0] == "reflexivos" || $result == "reflexivos") {
            $result="ac02";
        } elseif ($post_mood == "transgresores" || $postm1[0] == "transgresores" || $result == "transgresores") {
            $result="ac04";
        } else { 
            $result = '';
        }
        
        return $result;
    }
    
    /**
     * 
     * Sacamos la clase dependiendo del estado de animo
     * @author dani
     * @param String $animo
     */
    
    function classMetaEstadoAnimo( $animo ) {
        
        if ($animo == "familiares") {
            $result = "am01";
        } elseif ($animo == "sintomaticos") {
            $result = "am03";
        } elseif ($animo == "reflexivos") {
            $result = "am02";
        } elseif ($animo == "transgresores") {
            $result = "am04";
        }
        return $result;
    
    }
    
    /**
     * 
     Sacamos el backgorund dependiendo del estado de animo
     * @author dani
     * @param String $animos
     */
    
    function classBackgroundEstadoAnimo( $animos ) {
        
        if ($animos == "familiares") {
            
            $result = "ac01";
        } elseif ($animos == "sintomaticos") {
            
            $result = "ac03";
        } elseif ($animos == "reflexivos") {
            
            $result = "ac02";
        } elseif ($animos == "transgresores") {
            
            $result = "ac04";
        }
        
        return $result;
    }
    
    /**
     * 
     * Calcular el estado que le corresponde a un poste dependiendo del estado de animo actual del post, el estado de
     * animo del autor, el número de "Me gustas" y el estado de los comentarios que tenga.
     * ac01 => familiares
     * ac02 => reflexivos
     * ac03 => sintomaticos
     * ac04 => transgresores
     * @author dani
     * @param number $idActivity
     * @param string $estadoAutor
     */
    
    function calculateStatePostNew($idActivity, $estadoAutor) {
        
        global $wpdb, $bp;
        
        $familiares    = '0';//ac01
        $reflexivos    = '0';//ac02
        $sintomaticos  = '0';//ac03
        $transgresores = '0';//ac04
        
        $component       = 'select * from wp_bp_activity where id ="' . $idActivity . '"';
        $componentResult = $wpdb->get_row($wpdb->prepare($component));
        
        $stateCreatre    = bp_activity_get_meta($idActivity, 'orig_mood');
        
        //echo ' * estadon con el que se creo: ' . $stateCreatre . ' <br />';
        
        /**
         * se comprieba si es un post de grupo y si es asi, se le da +1 al estado del grupo
         */
        if ($componentResult->component == 'groups') {
            
            $stateGroup  = 'select * from wp_bp_groups_groupmeta where group_id = "' . $componentResult->item_id . '" and meta_key = "ironestado"';
            $reultGrouop = $wpdb->get_row($wpdb->prepare($stateGroup));
            
            switch ($reultGrouop->meta_value) {
                case 'familiares';
                    $familiares    = $familiares    + 1;
                break;
                case 'reflexivos':
                    $reflexivos    = $reflexivos    + 1;
                break;
                case 'sintomaticos':
                    $sintomaticos  = $sintomaticos  + 1;
                break;
                case 'transgresores':
                    $transgresores = $transgresores + 1;
                break;
            }
            
            //echo '<br /> * es un grupo con estado:    ' . $reultGrouop->meta_value . ' +1 <br />';
        }
        
        /**
         * estado actual del author se le suma +1
         */
        switch ($estadoAutor) {
            case 'familiares';
                $familiares    = $familiares    + 1;
            break;
            case 'reflexivos':
                $reflexivos    = $reflexivos    + 1;
            break;
            case 'sintomaticos':
                $sintomaticos  = $sintomaticos  + 1;
            break;
            case 'transgresores':
                $transgresores = $transgresores + 1;
            break;
        }
        
        //echo '<br /> * el estado actual del author es:    ' .$estadoAutor . ' +1 <br />';
        
        
        /**
         * se le suma +2 al estado de animo con mas "Me Gusta"
         */
        $metaStateLikes   = bp_activity_get_meta($idActivity, 'favorite_state');
        
        if ( $metaStateLikes ) {
            
            $mayorPuntaje = max($metaStateLikes);
            
            foreach ($metaStateLikes as $val => $key) {
                if ($key == $mayorPuntaje) {
                    $commentMoreLikes = $val;
                }
            }
            
            if (count($metaStateLikes[$commentMoreLikes]) > 0) {
                switch ($commentMoreLikes) {
                    case 'familiares';
                        $familiares    = $familiares    + 2;
                    break;
                    case 'reflexivos':
                        $reflexivos    = $reflexivos    + 2;
                    break;
                    case 'sintomaticos':
                        $sintomaticos  = $sintomaticos  + 2;
                    break;
                    case 'transgresores':
                        $transgresores = $transgresores + 2;
                    break;
                }
                
            //echo '<br /> * la mayoria de "Me Gusta" es de usuarios con el estado de animo:   ' . $commentMoreLikes .' +2 <br />';
            }
            
        }
        
        /**
         * con el $idActivity sacamos los meta_key = 'current_mood' de los comentarios que se le han echo, que son los
         * estados de animo que tienen.
         */
        $queryActivities = "select * from wp_bp_activity_meta where activity_id in (select id from wp_bp_activity where item_id = '" . $idActivity . "') and meta_key = 'current_mood'";
        $activities = $wpdb->get_results($queryActivities);
        
        if ( count($activities) > 0) {
            
            $Commentsfamiliares     = 0; 
            $Commentsreflexivos     = 0;
            $Commentssintomaticos   = 0;
            $Commentstransgresores  = 0;
            
            foreach ($activities as $value) {
                
                switch ($value->meta_value) {
                    case 'familiares';
                        $Commentsfamiliares++;
                    break;
                    case 'reflexivos':
                        $Commentsreflexivos++;
                    break;
                    case 'sintomaticos':
                        $Commentssintomaticos++;
                    break;
                    case 'transgresores':
                        $Commentstransgresores++;
                    break;
                }
            }
            
            $sumaComments = array(
                                'familiares'    => $Commentsfamiliares,
                                'reflexivos'    => $Commentsreflexivos,
                                'sintomaticos'  => $Commentssintomaticos,
                                'transgresores' => $Commentstransgresores
                                );
                                
            $mayorComments = max($sumaComments);
            
            foreach ($sumaComments as $commentsValue => $commentsKey) {
                if($commentsKey == $mayorComments) {
                    $statetmp[$commentsValue] = $commentsValue;
                }
            }
            
            if (count($statetmp) >= 2) {
                
                if (gettype($stateCreatre) != string) {
                    $stateCreatre = "";
                }
                
                if ( array_key_exists($stateCreatre,$statetmp) ) {
                    $stateWinner = $stateCreatre;
                } else {
                    $stateWinner = end($statetmp);
                }
                
            } else {
                $stateWinner = current($statetmp);
            }
            
            switch ($stateWinner) {
                case 'familiares';
                    $familiares    = $familiares    + 3;
                break;
                case 'reflexivos':
                    $reflexivos    = $reflexivos    + 3;
                break;
                case 'sintomaticos':
                    $sintomaticos  = $sintomaticos  + 3;
                break;
                case 'transgresores':
                    $transgresores = $transgresores + 3;
                break;
            }
            
            //echo '<br /> * la mayoria de los comentarios se escribieron con el estado de animo:    ' . $stateWinner . ' +3 <br />';
        }
        
        /**
         * cojemos todos los resultamos y sacamos el mayor
         */
        $sumasFinal = array(
                        'familiares'    => $familiares,
                        'reflexivos'    => $reflexivos,
                        'sintomaticos'  => $sintomaticos,
                        'transgresores' => $transgresores
                       );
        $mayor = max($sumasFinal);
        
        foreach ($sumasFinal as $val => $key) {
            if ($key == $mayor) {
                $AnimoPreb[$val] = $val;
            }
        }
        
        //echo '<br /><br /><br />se suman los datos y queda <br />';
        
                //echo '<br /> **** familiares:     ' . $sumasFinal['familiares'];
                //echo '<br /> **** reflexivos:     ' . $sumasFinal['reflexivos'];
                //echo '<br /> **** sintomaticos:   ' . $sumasFinal['sintomaticos'];
                //echo '<br /> **** transgresores:  ' . $sumasFinal['transgresores'];
                //echo '<br />';
                
            
        //echo '<br />';
        
        
        //echo '<br />si hay un empate en los puntos se queda el del estado de animo con el que se creo<br />';
        /**
         * si hay mas de un estado con el mayor puntaje
         */
        if (count($AnimoPreb) >= 2) {
            
            /**
             * si entre los estados de mayor puntaje esta con el que se creo el post, automaticamente se pone ese.
             * sino se pone uno de los estamos empatados con un array_rand
             */
            if ($stateCreatre) {
                if (array_key_exists($stateCreatre,$AnimoPreb)) {
                    $AnimoFinal = $stateCreatre;
                } else {
                    $AnimoFinal = end($AnimoPreb);
                    $wpdb->update($table = 'wp_bp_activity_meta', $data = array('meta_value' => $AnimoFinal), $where = array('activity_id' => $idActivity, 'meta_key' => 'current_mood'));
                }
            } else {
                $AnimoFinal = end($AnimoPreb);
                $wpdb->update($table = 'wp_bp_activity_meta', $data = array('meta_value' => $AnimoFinal), $where = array('activity_id' => $idActivity, 'meta_key' => 'current_mood'));
            }
            
        } else {
            $AnimoFinal = current($AnimoPreb);
            $wpdb->update($table = 'wp_bp_activity_meta', $data = array('meta_value' => $AnimoFinal), $where = array('activity_id' => $idActivity, 'meta_key' => 'current_mood'));
        }
        
        /**
         * sacamos el id del style que usa el estado de animo que llevara.
         */
        switch ($AnimoFinal) {
            case 'familiares':
                $result = 'id="state_orange"';
            break;
            case 'reflexivos':
                $result = 'id="state_green"';
            break;
            case 'sintomaticos':
                $result = 'id="state_blue"';
            break;
            case 'transgresores':
                $result = 'id="state_purple"';
            break;
        }
        
        //echo '<br />----------------------------------------------------------------------------<br />';
        //echo 'quedaria asi con el estas => ' . $AnimoFinal;
        //echo '<br />----------------------------------------------------------------------------<br />';
        return $result;
    }
    
    function calculateStatePost($idActivity, $estadoCreado, $estadoAutor, $nLikes) {
        global $wpdb;
        
        $familiares    = '0';//ac01
        $reflexivos    = '0';//ac02
        $sintomaticos  = '0';//ac03
        $transgresores = '0';//ac04
        
        /**
         * si no hay "Me gusta" es false, asi que lo definimos como '0' para poder sumar.
         */
        if (!$nLikes) {
            $nLikes = '0';
        }
        
        /**
         * estado actual del post
         */
        $estadoOriginal = 'select * from wp_bp_activity_meta where activity_id = "' . $idActivity . '" and meta_key = "orig_mood"';
        $estadoResult   = $wpdb->get_row($estadoOriginal);
        
        switch ($estadoResult->meta_value) {
            case 'familiares';
                $familiares    = $nLikes;
                $familiares++;
                $stateCreatre  = 'familiares';
            break;
            case 'reflexivos':
                $reflexivos    = $nLikes;
                $reflexivos++;
                $stateCreatre  = 'reflexivos';
            break;
            case 'sintomaticos':
                $sintomaticos  = $nLikes;
                $sintomaticos++;
                $stateCreatre  = 'sintomaticos';
            break;
            case 'transgresores':
                $transgresores = $nLikes;
                $transgresores++;
                $stateCreatre  = 'transgresores';
            break;
        }
        
        /**
         * estado actual del author
         */
        switch ($estadoAutor) {
            case 'familiares';
                $familiares++;
            break;
            case 'reflexivos':
                $reflexivos++;
            break;
            case 'sintomaticos':
                $sintomaticos++;
            break;
            case 'transgresores':
                $transgresores++;
            break;
        }
        
        /**
         * con el $idActivity sacamos los meta_key = 'current_mood' de los comentarios que se le han echo, que son los
         * estados de animo que tienen.
         */
        $queryActivities = "select * from wp_bp_activity_meta where activity_id in (select id from wp_bp_activity where item_id = '" . $idActivity . "') and meta_key = 'current_mood'";
        $activities = $wpdb->get_results($queryActivities);
        
        foreach ($activities as $value) {
            
            switch ($value->meta_value) {
                case 'familiares';
                    $familiares++;
                break;
                case 'reflexivos':
                    $reflexivos++;
                break;
                case 'sintomaticos':
                    $sintomaticos++;
                break;
                case 'transgresores':
                    $transgresores++;
                break;
            }
        }
        
        /**
         * cojemos todos los resultamos y sacamos el mayor
         */
        $sumas = array(
                        'familiares'    => $familiares,
                        'reflexivos'    => $reflexivos,
                        'sintomaticos'  => $sintomaticos,
                        'transgresores' => $transgresores
                       );
        
        $mayorPuntaje = max($sumas);
        
        foreach ($sumas as $val => $key) {
            if ($key == $mayorPuntaje) {
                $AnimoPreb[$val] = $val;
            }
        }
        
        /**
         * si hay mas de un estado con el mayor puntaje
         */
        if (count($AnimoPreb) >= 2) {
            
            /**
             * si entre los estados de mayor puntaje esta con el que se creo el post, automaticamente se pone ese.
             * sino se pone uno de los estamos empatados con un array_rand
             */
            if (array_key_exists($stateCreatre,$AnimoPreb)) {
                $AnimoFinal = $stateCreatre;
            } else {
                $AnimoFinal = array_rand($AnimoPreb, '1');
                $wpdb->update($table = 'wp_bp_activity_meta', $data = array('meta_value' => $AnimoFinal), $where = array('activity_id' => $idActivity, 'meta_key' => 'current_mood'));
            }
            
        } else {
            $AnimoFinal = current($AnimoPreb);
            $wpdb->update($table = 'wp_bp_activity_meta', $data = array('meta_value' => $AnimoFinal), $where = array('activity_id' => $idActivity, 'meta_key' => 'current_mood'));
        }
        
        /**
         * sacamos el id del style que usa el estado de animo que llevara.
         */
        switch ($AnimoFinal) {
            case 'familiares':
                $reult = 'id="state_orange"';
            break;
            case 'reflexivos':
                $reult = 'id="state_green"';
            break;
            case 'sintomaticos':
                $reult = 'id="state_blue"';
            break;
            case 'transgresores':
                $reult = 'id="state_purple"';
            break;
        }
        
        return $reult;
    }
    
    function calculateStatePostBackground($idActivity, $estadoAutor) {
        
        $state = calculateStatePostNew($idActivity, $estadoAutor);
        
        $classbackground = "";
        
        if ( $state == 'id="state_orange"' ) {
            $result="ac01";
        } elseif ( $state == 'id="state_green"' ) {
            $result="ac02";
        } elseif ( $state == 'id="state_blue"' ) {
            $result="ac03";
        } elseif ( $state == 'id="state_purple"' ) {
            $result="ac04";
        } else { 
            $result = '';
        }
        
        return $result;
    }
    
    /**
     * comprueba si es un elemento sin background para listar en el entry.php
     * relacion de amistad, pregunta/testimonio, crear evento/grupo, achievement
     * @author dani
     * @param string $activityType
     */
    function checkTypeActivityClear($activityType) {
        if (
            $activityType == 'friendship_created' ||
            $activityType == 'new_blog_post'      ||
            $activityType == 'created_group'      ||
            $activityType == 'created_event'      ||
            $activityType == 'new_achievement'
        ) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * comprueba si es un elemento con un contenedor completo entry.php
     * que no sea => relacion de amistad, pregunta/testimonio, crear evento/grupo, achievement
     * @author dani
     * @param string $activityType
     */
    function checkTypeActivityFull($activityType) {
        
        if (
            bp_get_activity_type() != 'friendship_created'  &&
            bp_get_activity_type() != 'new_blog_post'       &&
            bp_get_activity_type() != 'created_group'        &&
            bp_get_activity_type() != 'created_event'        &&
            bp_get_activity_type() != 'new_achievement'
        ) {
            return true;
        } else {
            return false;
        }
        
    }
    
    /**
     * el contenido los post que se muestran en el muro con un limite de 60 palabras, se compreba y se imprime en
     * pantalla
     * @author dani
     * @param string $contenido
     */
        function contenidoMuroCorto( $contenido ) {
        
        global $wpsmiliestrans;
        
        $resultContect = $contentTmp = $texto = $conte = $conte2 = $act_content =  $ContectClear = '';
        
        $contenido = preg_replace('#.+?src=[\'"]([^\'"]+)[\'"].+#i', "$1", $contenido);
        
        $act_content = explode(' ',strip_tags(str_replace('<br />', ' -- ', str_replace('<br>', ' -- ', nl2br($contenido)))));
        
        /**
         * limite de palabras a 50
         */
        if (sizeof($act_content)>50) {
            
            foreach ($act_content as $value) {
                
                $texto = str_replace('feature=player_embedded', '', $value);
                
                if ( parse_yturl(trim($texto)) ) {
                    $video[] = $texto;
                } elseif ( is_enlaceUrl($texto) ) {
                    $conte[] = is_enlaceUrl($texto);
                } else {
                    if ($wpsmiliestrans[$texto]) {
                        $conte[] = translate_smiley(array($texto));
                    } else {
                        $conte[] = $texto;
                    }
                }
            }
            
            for ($i=0; $i<50; $i++) {
                $contentTmp .= filter_mentions($conte[$i]) ." ";
            }
            
            $resultContect .= str_replace('--', ' <br /> ', $contentTmp);
            
            $resultContect .= '... <a href="'. bp_activity_get_permalink( bp_get_activity_id() ) .'" title="' . __( 'Leer m&aacute;s','buddypress') . '">' . __( 'Leer m&aacute;s','buddypress') . '</a> </p>';
            
            if ($video) {
                foreach ($video as $urlYou) {
                    $url = '';
                    $url = parse_yturl(trim($urlYou));
                    if (is_vimeo($url)) {
                        $resultContect .= direcVimeo(is_vimeo($url));
                    } else {
                        $resultContect .= direcYoutube($url);
                    }
                }
            }
            
        } else {
            
            $act_content = explode(' ',strip_tags(str_replace('<br />', ' -- ', nl2br($contenido))));
            
            foreach ($act_content as $value) {
                
                $texto = str_replace('feature=player_embedded', '', $value);
                
                if ( parse_yturl(trim($texto)) ) {
                    $video[] = $texto;
                } elseif ( is_enlaceUrl($texto) ) {
                    $conte[] = is_enlaceUrl($texto);
                } else {
                    if ($wpsmiliestrans[$texto]) {
                        $conte[] = translate_smiley(array($texto));
                    } else {
                        $conte[] = $texto;
                    }
                }
            }
            
            
            for ($i=0; $i<sizeof($act_content); $i++) {
                $contentTmp .= filter_mentions($conte[$i]) ." ";
            }
            
            $resultContect .= str_replace('--', ' <br /> ', $contentTmp);
            
            if ($video) {
                foreach ($video as $urlYou) {
                    $url = '';
                    $url = parse_yturl(trim($urlYou));
                    if (is_vimeo($url)) {
                        $resultContect .= direcVimeo(is_vimeo($url));
                    } else {
                        $resultContect .= direcYoutube($url);
                    }
                }
            }
        }
        
        return str_replace('\\', '', $resultContect);
    }
    
    /**
     * el contenido los post que se muestran en el muro.
     * @author dani
     * @param string $contenido
     */
    function contenidoMuroCompleto( $contenido ) {
        
        global $wpsmiliestrans;
        
        $resultContect = $contentTmp = $texto = $conte = $conte2 = $act_content =  $ContectClear = "";
        
        $contenido = preg_replace('#.+?src=[\'"]([^\'"]+)[\'"].+#i', "$1", $contenido);
        
        if ($_GET['search']) {
            
            $act_content = explode(' ',strip_tags(str_replace('<br />', ' -- ', nl2br($contenido))));
            
            foreach ($act_content as $value) {
                
                $texto = str_replace('feature=player_embedded', '', $value);
                
                if ( parse_yturl(trim($texto)) ) {
                    $video[] = $texto;
                } elseif ( is_enlaceUrl($texto) ) {
                    $conte[] = is_enlaceUrl($texto);
                } else {
                    if ($wpsmiliestrans[$texto]) {
                        $conte[] = translate_smiley(array($texto));
                    } else {
                        $conte[] = $texto;
                    }
                }
            }
            
            for ($i=0; $i<sizeof($act_content); $i++) {
                $contentTmp .= filter_mentions($conte[$i]) ." ";
            }
            
            $contenitoFull = str_replace('--', ' <br /> ', $contentTmp);
            $resultContect .= str_ireplace($_GET['search'],'<span style="color:#E4611D;">'.$_GET['search'].'</span>',$contenitoFull);
            
            if ($video) {
                foreach ($video as $urlYou) {
                    $url = '';
                    $url = parse_yturl(trim($urlYou));
                    if (is_vimeo($url)) {
                        $resultContect .= direcVimeo(is_vimeo($url));
                    } else {
                        $resultContect .= direcYoutube($url);
                    }
                }
            }
            
        } else {
            
            $act_content = explode(' ',strip_tags(str_replace('<br />', ' -- ', str_replace('<br>', ' -- ', nl2br($contenido)))));
            
            foreach ($act_content as $value) {
                $texto = str_replace('feature=player_embedded', '', $value);
                
                if ( parse_yturl(trim($texto)) ) {
                    $video[] = $texto;
                } elseif ( is_enlaceUrl($texto) ) {
                    $conte[] = is_enlaceUrl($texto);
                } else {
                    
                    if ($wpsmiliestrans[$texto]) {
                        $conte[] = translate_smiley(array($texto));
                    } else {
                        $conte[] = $texto;
                    }
                    
                }
            }
            
            for ($i=0; $i<sizeof($act_content); $i++) {
                $contentTmp .= filter_mentions($conte[$i]) ." ";
            }
            
            $resultContect .= str_replace('--', ' <br /> ', $contentTmp);
            
            if ($video) {
                
                foreach ($video as $urlYou) {
                    $url = '';
                    $url = parse_yturl(trim($urlYou));
                    if (is_vimeo($url)) {
                        $resultContect .= direcVimeo(is_vimeo($url));
                    } else {
                        $resultContect .= direcYoutube($url);
                    }
                    
                }
            }
            
        }
        
        return str_replace('\\', '', $resultContect);
    }
    
    /**
     * comprobamos que tipo de link se a puesto en el apartado enlace del muro.
     * @author dani
     * @param string $enlace
     */
    function check_enlaceActivity( $enlace ) {
        
        if (parse_yturl($enlace)) {
            
            if (is_vimeo(parse_yturl($enlace))) {
                $resultEnlace = direcVimeo(is_vimeo(parse_yturl($enlace)));
            } else {
                $resultEnlace = direcYoutube(parse_yturl($enlace));
            }
            
        } elseif (eregi('dailymotion.com', $enlace)) {
            
            /**
             * DailyMotion
             */
            
            $slices      = explode('/', $enlace);
            $slices2     = explode('_', $slices[sizeof($slices)-1]);
            $videohash   = $slices2[0];
            
            $resultEnlace = '
                    <object width="395" height="320">
                    <param name="movie" value="http://www.dailymotion.com/swf/video/' . $videohash . '?theme=none"></param>
                    <param name="allowFullScreen" value="true"></param>
                    <param name="allowScriptAccess" value="always"></param>
                    <param name="wmode" value="transparent"></param>
                    <embed type="application/x-shockwave-flash" src="http://www.dailymotion.com/swf/video/xe5q25?theme=none" width="395" height="320" wmode="opaque" allowfullscreen="true" allowscriptaccess="always"></embed>
                    </object>';
            
        } else {
            $resultEnlace = '<a href="' . $enlace . '" title="' . $enlace . '" >'.$enlace.'</a>';
        }
        
        return $resultEnlace;
    }
    
    
    
    function checkLang($cookie) {
        
        switch ($cookie) {
            
            case 'es':
                $lang = 'es-ES';
            break;
            case 'en':
                $lang = 'en-US';
            break;
            case 'eu':
                $lang = 'eu';
            break;
            default:
                $lang = 'es-ES';
            break;
            
        }
        
        return $lang;
        
    }
    
    function urlAmigables( $url ) {
    
        /**
         * Tranformamos todo a minusculas
         */
        $url = strtolower($url);
        
        /**
         * Rememplazamos caracteres especiales latinos
         */
        $find = array('á', 'é', 'í', 'ó', 'ú', 'ñ');
        $repl = array('a', 'e', 'i', 'o', 'u', 'n');
        $url  = str_replace ($find, $repl, $url);
        
        /**
         * Añadimos los guiones
         */
        $find = array(' ', '&', '\r\n', '\n', '+'); 
        $url  = str_replace ($find, '-', $url);
        
        /**
         * Eliminamos y Reemplazamos demás caracteres especiales
         */
        $find = array('/[^a-z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/');
        $repl = array('', '-', '');
        $url = preg_replace ($find, $repl, $url);
        
        return checkSlugEventExist($url);
    
    }
    
    function checkSlugEventExist( $url ) {
        
        global $wpdb;
        
        $slugExist = "select slug from " . $wpdb->prefix . "jet_events where slug = '" . $url ."'";
         
        if (count($wpdb->get_results($wpdb->prepare($slugExist))) >= '1') {
            
            $newUrl = $url . '-' . date('mdy-his');
            
        } else {
            $newUrl = $url;
        }
        
        return $newUrl;
        
    }
    
    function validCodeCountry($code) {
        global $wpdb;
        
        $query   = 'select * from iron_paises where valor = "' . $code . '"';
        $country = $wpdb->get_row($wpdb->prepare($query));
        
        return $country->pais;
    }
    
    /**
     * compilar en un nuevo fichero de traduccion todos los nuevos literales,
     * para evitar los problemas de compilacion con los antiguos.
     * __('literal a traducir', 'kronikoensarea') ... _e('literal a traducir', 'kronikoensarea')
     */
    
    function load_custom_textdomain() {
        $locale        = apply_filters( 'kronikoensarea_locale', get_locale() );
        $mofile        = sprintf( 'kronikoensarea-%s.mo', $locale );
        $mofile_global = WP_LANG_DIR . '/' . $mofile;
        
        if ( file_exists( $mofile_global ) )
            return load_textdomain( 'kronikoensarea', $mofile_global );
        elseif ( file_exists( $mofile_local ) )
        return load_textdomain( 'kronikoensarea', $mofile_local );
        else
            return false;
    }
    
    load_custom_textdomain();
    
?>
