function fecha($fecha)
{
    $intervalo = fecha_intervalo($fecha);
    $segundos = fecha_a_segundos($intervalo);
    $buffer = "";
    if ($segundos < 60) {
        $buffer .= "hace unos segundos";
    } elseif ($segundos < 3600) {
        $buffer .= "hace {$intervalo->format('%i')} minuto";
        if ($intervalo->format('%i') != 1) {
            $buffer .= "s";
        }
    } elseif ($segundos < 86400) {
        $buffer .= "hace {$intervalo->format('%h')} hora";
        if ($intervalo->format('%h') != 1) {
            $buffer .= "s";
        }
    } elseif ($segundos < 604800) {
        $buffer .= "hace {$intervalo->format('%d')} dia";
        if ($intervalo->format('%d') != 1) {
            $buffer .= "s";
        }
    } elseif ($segundos < 2592000) {
        $semanas = floor($intervalo->format('%d') / 7);
        $buffer .= "hace {$semanas} semana";
        if ($semanas != 1) {
            $buffer .= "s";
        }
    } elseif ($segundos < 31104000) {
        $buffer .= "hace " . ltrim($intervalo->format('%M'), '0') . " mes";
        if (ltrim($intervalo->format('%M'), '0') != 1) {
            $buffer .= "es";
        }
    } else {
        $buffer .= "hace {$intervalo->format('%d')} dias ELSE";
    }
    //Debug
    //echo "Intervalo: " . $intervalo -> format('%Y-%m-%d %H:%i:%s') . "<br>";
    //echo "Segundos: " . $segundos . "<br>";
    return $buffer;
}
    mysqli_query($link, "UPDATE chat SET leido='1' WHERE receptor='" . $global_idusuarios . "'");
    error_mysql();
    die;
}
if ($_POST['chat_leer_prev']) {
    //Sacamos los msg antiguos en orden inverso a proposito
    $sql = "SELECT *, DATE_FORMAT(fecha, '%H:%i') AS fecha_corta, DATE_FORMAT(fecha, '%d/%m %H:%i') AS fecha_larga\n\t\t\tFROM chat\n\t\t\tWHERE ((emisor = '{$_POST['iduser']}' AND receptor='" . $global_idusuarios . "') OR (receptor = '{$_POST['iduser']}' AND emisor='" . $global_idusuarios . "'))";
    if ($_POST['idchat']) {
        $sql .= " AND idchat < '{$_POST['idchat']}'";
    }
    $sql .= "  ORDER BY idchat DESC LIMIT 30";
    $result = mysqli_query($link, $sql);
    if (mysqli_num_rows($result) > 0) {
        $mensajes = array();
        while ($row = mysqli_fetch_assoc($result)) {
            $intervalo = fecha_intervalo($row['fecha']);
            $segundos = fecha_a_segundos($intervalo);
            if ($segundos > 86400) {
                $fecha = $row['fecha_larga'];
            } else {
                $fecha = $row['fecha_corta'];
            }
            if ($row['emisor'] != $global_idusuarios) {
                $class = "mensaje_ajeno";
            } else {
                $class = "mensaje_propio";
            }
            $msg = "<div idchat='{$row['idchat']}' class='{$class}'><div class='texto'>{$row['mensaje']}<div class='fecha'>{$fecha}</div></div></div>";
            array_unshift($mensajes, $msg);
            //con esto el orden se corrige
        }