<?php
session_start();

foreach ($_POST as $key => $value) {
    if (get_magic_quotes_gpc() and is_string($value)) {
        $_POST[$key] = stripslashes($value);
    }
    $_POST[$key] = @mysql_real_escape_string($value);
    $_POST[$key] = str_replace('\r\n', '', $value);
}

foreach ($_GET as $key => $value) {
    if (get_magic_quotes_gpc() and is_string($value)) {
        $_GET[$key] = stripslashes($value);
    }
    $_GET[$key] = @mysql_real_escape_string($value);
    $_GET[$key] = str_replace('\r\n', '', $value);
}

if (file_exists('config.php')) {
    include("config.php");
} else {
    $ruta = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $ruta = @substr($ruta, 0, @strrpos($ruta, "/"));
    $ruta .= '/install';
    echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL=' . $ruta . '">';
    exit;
}

$errors = '';
$errores = 0;
if (!$db__server) {
    $errores++;
    $errors.= "<br><img src='images/flags/us.png' border='1'> <b>db__server</b> not specified in config.php &nbsp;&nbsp;&nbsp; <img src='images/flags/es.png' border='1'> <b>db__server</b> no especificado en config.php";
}
if (!$db__user) {
    $errores++;
    $errors.= "<br><img src='images/flags/us.png' border='1'> <b>db__user</b> not specified in config.php &nbsp;&nbsp;&nbsp; <img src='images/flags/es.png' border='1'> <b>db__user</b> no especificado en config.php";
}
if (!$db__password) {
    $errores++;
    $errors.= "<br><img src='images/flags/us.png' border='1'> <b>db__password</b> not specified in config.php &nbsp;&nbsp;&nbsp; <img src='images/flags/es.png' border='1'> <b>db__password</b> no especificado en config.php";
}
if (!$db__name) {
    $errores++;
    $errors.= "<br><img src='images/flags/us.png' border='1'> <b>db__name</b> not specified in config.php &nbsp;&nbsp;&nbsp; <img src='images/flags/es.png' border='1'> <b>db__name</b> no especificado en config.php";
}

if ($errors) {
    print errors($errors);
    $errors = '';
    if ($errores == 5) {
        $ruta = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $ruta = @substr($ruta, 0, @strrpos($ruta, "/"));
        $ruta .= '/install';
        echo '<META HTTP-EQUIV=Refresh CONTENT="5; URL=' . $ruta . '">';
    }
    exit;
}

$db_link = @mysql_connect($db__server, $db__user, $db__password);
if (!@mysql_select_db($db__name, $db_link)) {
    $errors = "<br><img src='images/flags/us.png' border='1'> Impossible to connect to the database. Verify the values in the file config.php &nbsp;&nbsp;&nbsp; <img src='images/flags/es.png' border='1'> Fallo en la conexion a la base de datos. Verifique los valores en el archivo config.php";
    print errors($errors);
    $errors = '';
    exit;
}

global $config;

$codificacion = 'utf8';
@mysql_query("SET NAMES '" . $codificacion . "'");

$query = "SELECT * FROM hd_config ORDER BY ref";
$result = mysql_query($query, $GLOBALS['db_link']);
while ($row = mysql_fetch_array($result)) {
    $config[$row["ref"]][1] = $row["valor"];
};


if ($config[1][1] == null) {
    $ruta = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $ruta = @substr($ruta, 0, @strrpos($ruta, "/"));
    $query = "UPDATE hd_config SET valor='$ruta' WHERE ref=1";
    mysql_query($query, $GLOBALS['db_link']);
    $config[1][1] = $ruta;
}

if ($config[40][1] == null) {
    $ruta = @substr($_SERVER['SCRIPT_FILENAME'], 0, @strrpos($_SERVER['SCRIPT_FILENAME'], "/"));
    $query = "UPDATE hd_config SET valor='$ruta' WHERE ref=40";
    mysql_query($query, $GLOBALS['db_link']);
    $config[40][1] = $ruta;
}

if ($config[14][1] == null) {
    $ruta = @substr($_SERVER['DOCUMENT_ROOT'], 0, @strrpos($_SERVER['DOCUMENT_ROOT'], "/")) . '/backup';
    $query = "UPDATE hd_config SET valor='$ruta' WHERE ref=14";
    mysql_query($query, $GLOBALS['db_link']);
    $config[14][1] = $ruta;
}


date_default_timezone_set($config[124][1]);
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_errors', 'Off');
ini_set('error_log', 'attachments/error.log');


if ($config[86][1] == null) {
    $newfilename = time() . '_logo_dist.png';
    copy('images/dist/logo_dist.png', 'attachments/' . $newfilename);
    mysql_query("UPDATE hd_config SET valor='$newfilename' WHERE ref='86'", $db_link);
}
if ($config[87][1] == null) {
    $newfilename = time() . '_logomail_dist.gif';
    copy('images/dist/logomail_dist.gif', 'attachments/' . $newfilename);
    mysql_query("UPDATE hd_config SET valor='$newfilename' WHERE ref='87'", $db_link);
}

if (substr($config[86][1], -4) <> '.jpg' AND substr($config[86][1], -4) <> '.gif' AND substr($config[86][1], -4) <> '.png') {
    $config[86][1] .= '_notallowedimage.gif';
}
if (substr($config[87][1], -4) <> '.jpg' AND substr($config[87][1], -4) <> '.gif' AND substr($config[87][1], -4) <> '.png') {
    $config[87][1] .= '_notallowedimage.gif';
}

global $texts;
$query = "SELECT * FROM hd_text";
$result = mysql_query($query, $GLOBALS['db_link']);
$fila = 0;
while ($row = mysql_fetch_array($result)) {
    $texts[$fila][0] = $row["variable"];
    $texts[$fila][1] = $row["valor"];
    $fila++;
};


if (!isset($_SESSION['MyIP']) OR $_SESSION['MyIP'] == '') {
    $_SESSION['MyIP'] = $_SERVER['REMOTE_ADDR'];
}

function checklevel($level, $client = '') {

    if ($client == 0) {
        $client = '';
    }

    $internal_debug = 0;

    if ($internal_debug == 1) {
        echo "<table cellspacing=5 cellpading=0><tr><td bgcolor='blue'><font color='white'>";
        echo "<b>level:</b> " . $level;
        echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>clientid:</b> " . $client;
        echo "</font></td>";
    }

    if ($_SESSION['hd_accesslvl'] < $level AND $_SESSION['hd_accesslvl'] <> '') {
        messagetop(_ERROR_403, '', 'index.php', 0);
        exit();
    }

    if ($_SESSION['MyIP'] <> $_SERVER['REMOTE_ADDR']) {
        go2('logout.php');
        exit();
    }

    $pagefrom = $_SERVER['PHP_SELF'];
    $pagefrom = explode('/', $_SERVER['PHP_SELF']);
    $pagefrom = array_pop($pagefrom);

    if (!isset($_SESSION['hd_accesslvl']) AND $pagefrom <> 'login.php') {
        go2('index.php?option=logout&pagefrom=' . $pagefrom);
        exit;
    }

    if ($_SESSION['hd_accesslvl'] == 1 AND !is_numeric($_SESSION['hd_idc'])) {
        $_SESSION['hd_clientid'] = $client;
    } elseif ($_SESSION['hd_accesslvl'] == 1) {
        $_SESSION['hd_clientid'] = $_SESSION['hd_idc'];
    } else {
        $_SESSION['hd_clientid'] = $client;
    }


    if ($_SESSION['hd_accesslvl'] == 1 AND $_SESSION['hd_clientid']) {
        $suspendido = query("SELECT suspended, active FROM hd_clients WHERE clientid='" . $_SESSION['hd_clientid'] . "'", 1);
        if ($suspendido['suspended'] == 1) {
            setcookie("hd_status", '0', time() + 86400);
            messagetop(_YOUR_ACCOUNT_HAS_BEEN_SUSPENDED, '', 'logout.php', 2);
        }
        if ($suspendido['active'] == -1) {
            setcookie("hd_status", '0', time() + 86400);
            messagetop(_YOUR_ACCOUNT_HAS_BEEN_DELETED, '', 'logout.php', 0);
        }
    }

    if ($internal_debug == 1) {
        echo "<td bgcolor='red'><font color='white'>";
        echo "<b>SESSION hd_accesslvl:</b> " . $_SESSION['hd_accesslvl'];
        echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>SESSION clientid:</b> " . $_SESSION['hd_clientid'];
        echo "</font></td></tr></table>";
    }
}

function secure($level) {
	if ($_SESSION['hd_accesslvl'] >= $level) {
        return(true);
    } else {
        return(false);
    }
}

function moduleaccess($moduleID) {
    global $config;

    if ($_SESSION['hd_accesslvl'] == 1 AND substr($config[$moduleID][1], 2, 1) == '0') {
        messagetop(_ACCESS_DENIED, '', 'index.php', 0);
    } elseif (!$_SESSION['hd_accesslvl'] AND substr($config[$moduleID][1], 0, 1) == '0') {
        messagetop(_ACCESS_DENIED, '', 'index.php', 0);
    }
}

function sel($var, $val) {
    if ($var == $val) {
        print("selected");
    }
}

function sele($var, $val) {
    if ($var == $val) {
        return " selected";
    }
}

function chec($var, $val) {
    if ($var == $val) {
        return " checked='checked'";
    }
}

function go2($url, $espera = 0) {
    global $serverurl;
    if (!strstr($url, 'http')) {
        $urlstring = "" . $serverurl . "/" . $url;
    } else {
        $urlstring = $url;
    }
    $urlstring = str_replace('index.php', '', $urlstring);
    if (!headers_sent()) {    
        header('Location: ' . $urlstring);
        exit;
    } else {                    
        echo '<meta http-equiv="refresh" content="' . $espera . ';url=' . $urlstring . '" />';
    }
}

function errors($errors) {
    if ($errors <> '') {
        $errors = substr_replace($errors, '', 0, 4);
        echo '	
		<div class="alert alert-block">
        <a class="close" data-dismiss="alert" href="#"></a>
        <h4 class="alert-heading">' . lang('_ERROR') . '</h4>
        ' . $errors . '
      	</div>
	  ';
    }
}

function bandera($codigopaisAB) {
    if (file_exists('images/flags/' . strtolower($codigopaisAB) . '.png')) {
        echo "<img src='images/flags/" . strtolower($codigopaisAB) . ".png'>";
    }
}

function bandera2($idpaisNN) {
    $codigopaisAB = query("SELECT countrycode, country FROM hd_countries WHERE id='" . $idpaisNN . "'", 1);
    if (file_exists('images/flags/' . strtolower($codigopaisAB[0]) . '.png')) {
        echo "<img src='images/flags/" . strtolower($codigopaisAB[0]) . ".png' title='" . ucwords($codigopaisAB[1]) . "' title='" . ucwords($codigopaisAB[1]) . "'>";
    }
}

function showcountry($codigopaisNN) {
    $pais_cliente = query("SELECT country FROM hd_countries WHERE id='" . $codigopaisNN . "'", 1);
    return $pais_cliente['country'];
}

function showstate($codigoestadoNN) {
    $estado_cliente = query("SELECT state FROM hd_countries_states WHERE id='" . $codigoestadoNN . "'", 1);
    return $estado_cliente['state'];
}

function showcountryISO($codigopaisNN) {
    $paisISO_cliente = query("SELECT countrycode FROM hd_countries WHERE id='" . $codigopaisNN . "'", 1);
    return $paisISO_cliente['countrycode'];
}

function showphonecode($codigopaisNN) {
    $phonecode_cliente = query("SELECT phonecode FROM hd_countries WHERE id='" . $codigopaisNN . "'", 1);
    return $phonecode_cliente['phonecode'];
}

function banderacliente($clienteID) {
    $pais_cliente = query("SELECT country FROM hd_clients WHERE clientid='" . $clienteID . "'", 1);
    $codigo_pais = query("SELECT country, countrycode FROM hd_countries WHERE id='" . $pais_cliente['country'] . "'", 1);
    if (file_exists('images/flags/' . strtolower($codigo_pais[countrycode]) . '.png')) {
        echo "<img src='images/flags/" . strtolower($codigo_pais[countrycode]) . ".png' border='0' class='btip' title='" . ucwords($codigo_pais['country']) . "'>";
    }
}


function logevent($action, $client_id, $user, $what = "") {
    global $config;
    $when = time() + $config[31][1] * 3600;
    $action = ucfirst($action);
    $user = $user . " (" . $_SERVER['REMOTE_ADDR'] . ")";
    $query = "INSERT INTO hd_history (action,clientid,user,time,what) VALUES('$action',$client_id,'$user',$when,'$what')";
    if (!mysql_query($query, $GLOBALS['db_link'])) {
        print("<br> Debug: " . $query . "<br>Error: " . mysql_error());
        exit;
    }
}



function email2queue($email, $subject, $body, $replyto, $bcc, $datetime = 0) {
    global $config;
    if ($datetime == 0) {
        $datetime = time() + $config[31][1] * 3600;
    }
    $subject = addslashes($subject);
    $body = addslashes($body);
    $query = "INSERT INTO hd_emailqueue (email,subject,body,replyto,bcc,datetime) VALUES('$email','$subject','$body','$replyto','$bcc',$datetime)";
    if (!mysql_query($query, $GLOBALS['db_link'])) {
        print("<br> Debug: " . $query . "<br>Error: " . mysql_error());
        exit;
    }
    return true;
}

function no_access() {
    session_destroy();
    $pagefrom = $_SERVER['PHP_SELF'];
    $pagefrom = explode('/', $_SERVER['PHP_SELF']);
    $pagefrom = array_pop($pagefrom);
    ?>
    <META http-equiv="refresh" content="0; url=index.php?option=logout&pagefrom=<?php echo $pagefrom ?>">
    <?php
    exit();
}

function getIp() {
    if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

function test($text, $var) {
    echo "<hr><b>" . $text . ":</b> " . $var . "<hr>";
}

function testa($text, $arreglo) {
    echo "<hr><b>" . $text . ":</b> <pre>";
    print_r($arreglo);
    echo "</pre><hr>";
}

function valorinput($valorpost, $valorrow) {
    if ($valorpost == '') {
        return $valorrow;
    } else {
        return $valorpost;
    }
}

function valorinputchecked($valorpost, $valorrow) {
    if ($valorrow == 1 OR $valorpost == 'on') {
        return "checked";
    } else {
        return '';
    }
}

function message($message1, $message2 = '', $linkURL, $linkTEXT) {
    global $serverurl;
    $clase = 'alert alert-info';
    $mensaje = '<div class="' . $clase . '">';
    $mensaje .= "<h4>" . strtoupper(nl2br($message1)) . "</h4>";
    if ($message2 <> '') {
        $mensaje .= "" . ucfirst(nl2br($message2)) . "";
    }
    $mensaje .= "<h4><a href='" . $serverurl . "/" . $linkURL . "'><b>" . strtoupper($linkTEXT) . "</b></a></h4>";
    $mensaje .= "</div>";
    echo $mensaje;
}

function messagetop($message1, $message2 = '', $URLdestino, $status) {
    if ($status == 1) {
        $clase = 'alert alert-success';
    } elseif ($status == 0) {
        $clase = 'alert alert-error';
    } elseif ($status == 2) {
        $clase = 'alert alert-info';
    }
    $mensaje = '<div class="container"><div class="row">';
    $mensaje .= '<div class="' . $clase . '">';
    $mensaje .= "<h4>" . ucfirst(nl2br($message1)) . "</h4>";
    if ($message2 <> '') {
        $mensaje .= "" . ucfirst(nl2br($message2)) . "";
    }
    $mensaje .= "</div>";
    $mensaje .= "</div>";
    $mensaje .= "</div>";
    $_SESSION['msgbox'] = $mensaje;
    go2($URLdestino);
}

function messagetopinthispage($message1, $message2 = '', $status) {
    if ($status == 1) {
        $clase = 'alert alert-success';
    } elseif ($status == 0) {
        $clase = 'alert alert-error';
    } else {
        $clase = 'alert alert-info';
    }
    $mensaje = '<div class="' . $clase . '">';
    $mensaje .= "<h4>" . ucfirst(nl2br($message1)) . "</h4>";
    if ($message2 <> '') {
        $mensaje .= "" . ucfirst(nl2br($message2)) . "";
    }
    $mensaje .= "</div>";
    return $mensaje;
}

function messagetopinthispageonetable($message1, $message2 = '', $status) {
    if ($status == 1) {
        $clase = 'alert alert-success';
    } elseif ($status == 0) {
        $clase = 'alert alert-error';
    } else {
        $clase = 'alert alert-info';
    }
    $mensaje = '<div class="' . $clase . '">';
    $mensaje .= "<h4>" . ucfirst(nl2br($message1)) . "</h4>";
    if ($message2 <> '') {
        $mensaje .= "" . ucfirst(nl2br($message2)) . "";
    }
    $mensaje .= "</div>";
    return $mensaje;
}

function msgbox($RESULT, $URLdestino, $testing = false) {
    if ($RESULT) {
        if ($status == 1) {
            $clase = 'alert alert-success';
        } elseif ($status == 0) {
            $clase = 'alert alert-error';
        } else {
            $clase = 'alert alert-info';
        }
        $mensaje = '<div class="' . $clase . '">';
        $mensaje .= "<h4>" . $RESULT['MESSAGE'] . "</h4>";

        if ($testing) {
            $mensaje .= "DEBUG:<pre>";
            $mensaje .= print_r($RESULT['DEBUG'], true);
            $mensaje .= "</pre>";
        }
        $mensaje .= "</div>";
        $_SESSION['msgbox'] = $mensaje;
        go2($URLdestino);
    }
}

function TimeAgo($timestamp, $time, $showsec = 0) {
    $current_time = $time;
    $difference = $current_time - $timestamp;
    if ($showsec == 0) {
        $periods = array(_MINUTE, _HOUR, _DAY, _MONTH, _YEAR);
        $lengths = array(60, 3600, 86400, 2630880, 31570560);
    } else {
        $periods = array(_SECOND, _MINUTE, _HOUR, _DAY, _MONTH, _YEAR);
        $lengths = array(1, 60, 3600, 86400, 2630880, 31570560);
    }
    for ($val = sizeof($lengths) - 1; ($val >= 0) && (($number = $difference / $lengths[$val]) <= 1); $val--)
        ;
    if ($val < 0)
        $val = 0;

    $new_time = $current_time - ($difference % $lengths[$val]);

    $number = floor($number);

    if ($number != 1) {
        if ($periods[$val] == _SECOND)
            $periods[$val] = _SECONDS;
        if ($periods[$val] == _MINUTE)
            $periods[$val] = _MINUTES;
        if ($periods[$val] == _HOUR)
            $periods[$val] = _HOURS;
        if ($periods[$val] == _DAY)
            $periods[$val] = _DAYS;
        if ($periods[$val] == _WEEK)
            $periods[$val] = _WEEKS;
        if ($periods[$val] == _MONTH)
            $periods[$val] = _MONTHS;
        if ($periods[$val] == _YEAR)
            $periods[$val] = _YEARS;
        if ($periods[$val] == _DECADE)
            $periods[$val] = _DECADES;
    }

    $text = sprintf("%d %s ", $number, $periods[$val]);

    if (($val >= 1) && (($current_time - $new_time) > 0)) {
        $text .= TimeAgo($new_time, $current_time, $showsec);
    }

    return trim($text);
}

function strbet($inputStr, $delimeterLeft, $delimeterRight) {
    $posLeft = strpos($inputStr, $delimeterLeft);
    $posLeft+=strlen($delimeterLeft);
    $posRight = strpos($inputStr, $delimeterRight, $posLeft);
    return substr($inputStr, $posLeft, $posRight - $posLeft);
}

function distorsiona($valor) {
    $nuevovalor = ($valor + date('d', time())) * 3;
    return $nuevovalor;
}


function query($query, $type) {
    $result = mysql_query($query);
    $error = mysql_error();
    global $query_count;
    global $queries_used;
    $query_count++;
    $queries_used .= $query . '<br>';
    if (!empty($error)) {
        ob_end_clean();
        $errno = mysql_errno();
        die("unable to successfully run a MySQL query.<br>MySQL Returned this error: <b>$error</b> Error number: <b>$errno</b><br>The query that caused this error was: <b>$query</b>");
    }
    if ($type == 0) {
        return $result;
    }
    if ($type == 1) {
        $array = mysql_fetch_array($result);
        return $array;
    }
    if ($type == 2) {
        $array = mysql_num_rows($result);
        return $array;
    }
    if ($type == 3) {
        return mysql_insert_id();
    }
    if ($type == 4) {
        return mysql_result($result, 0);
    }
    @mysql_free_result($result);
}

function checkciuy($nDocid) {
    $nDocid = str_replace('.', '', $nDocid);
    $nDocid = str_replace('-', '', $nDocid);
    $nDocid = str_replace('/', '', $nDocid);

    $cicompleta = $nDocid;

    if ($cicompleta == "") {
        return false;
        exit;
    }

    $digitoingresado = substr($nDocid, -1, 1);

    $nDocid = intval($nDocid / 10);

    $a1 = intval($nDocid / 1000000);
    $a2 = intval($nDocid / 100000) - ($a1 * 10);
    $a3 = intval($nDocid / 10000) - ($a1 * 100 + $a2 * 10);
    $a4 = intval($nDocid / 1000) - ($a1 * 1000 + $a2 * 100 + $a3 * 10);
    $a5 = intval($nDocid / 100) - ($a1 * 10000 + $a2 * 1000 + $a3 * 100 + $a4 * 10);
    $a6 = intval($nDocid / 10) - ($a1 * 100000 + $a2 * 10000 + $a3 * 1000 + $a4 * 100 + $a5 * 10);
    $a7 = intval($nDocid / 1) - ($a1 * 1000000 + $a2 * 100000 + $a3 * 10000 + $a4 * 1000 + $a5 * 100 + $a6 * 10);
    $b1 = fmod($a1 * 2, 10);
    $b2 = fmod($a2 * 9, 10);
    $b3 = fmod($a3 * 8, 10);
    $b4 = fmod($a4 * 7, 10);
    $b5 = fmod($a5 * 6, 10);
    $b6 = fmod($a6 * 3, 10);
    $b7 = fmod($a7 * 4, 10);
    $t1 = $b1 + $b2 + $b3 + $b4 + $b5 + $b6 + $b7;
    $t2 = fmod($t1, 10);
    $chd1 = abs($t2 - 10);
    $chd1 = fmod($chd1, 10);
    $digitocorrecto = $chd1;

    if ($digitoingresado == $digitocorrecto) {
        return true;
    } else {
        return false;
    }
}

function generate_password($length = 0) {
    global $config;
    if ($length == 0) {
        $length = $config[76][1];
    }
    $allowable_characters = $config[77][1];
    $ps_len = strlen($allowable_characters);
    mt_srand((double) microtime() * 1000000);
    $passw = "";
    for ($i = 0; $i < $length; $i++) {
        $passw .= $allowable_characters[mt_rand(0, $ps_len - 1)];
    } 
    return $passw;
}


function generate_id($table, $field, $length = 10) {
    global $veces;
    $allowable_characters = "123456789";
    $ps_len = strlen($allowable_characters);
    mt_srand((double) microtime() * 1000000);
    $passw = "";
    for ($i = 0; $i < $length; $i++) {
        $passw .= $allowable_characters[mt_rand(0, $ps_len - 1)];
    } 
    $dataID = query("SELECT " . $field . " FROM " . $table . " WHERE " . $field . " = " . $passw . "", 2);
    if ($dataID == 0) {
        return $passw;
    } else {
        $veces++;
        if ($veces == 5) {
            $length++;
        }
        $passw = generate_id($table, $field, $length);
    }
    return $passw;
}

function generate_user($table, $field, $start, $length = 7) {
    global $veces;
    $allowable_characters = "123456789";
    $ps_len = strlen($allowable_characters);
    mt_srand((double) microtime() * 1000000);
    $passw = "";
    for ($i = 0; $i < $length; $i++) {
        $passw .= $allowable_characters[mt_rand(0, $ps_len - 1)];
    } 
    $passw = $start . $passw;
    $dataID = query("SELECT " . $field . " FROM " . $table . " WHERE " . $field . " = '" . $passw . "'", 2);
    if ($dataID == 0) {
        return $passw;
    } else {
        $veces++;
        if ($veces == 5) {
            $length++;
        }
        $passw = generate_id($table, $field, $start, $length);
    }
    return $passw;
}

function encrypt($string, $key = 'uf4hgo7YiOld84a2cmn34dj') {
    $result = '';
    for ($i = 0; $i < strlen($string); $i++) {
        $char = substr($string, $i, 1);
        $keychar = substr($key, ($i % strlen($key)) - 1, 1);
        $char = chr(ord($char) + ord($keychar));
        $result.=$char;
    }
    return base64_encode($result);
}

function decrypt($string, $key = 'uf4hgo7YiOld84a2cmn34dj') {
    $result = '';
    $string = base64_decode($string);
    for ($i = 0; $i < strlen($string); $i++) {
        $char = substr($string, $i, 1);
        $keychar = substr($key, ($i % strlen($key)) - 1, 1);
        $char = chr(ord($char) - ord($keychar));
        $result.=$char;
    }
    return $result;
}

function removeextended($text) {
    $a = array('Á' => 'A', 'á' => 'a', 'É' => 'E', 'é' => 'e', 'Í' => 'I', 'í' => 'i', 'Ó' => 'O', 'ó' => 'o', 'Ú' => 'U', 'ú' => 'u', 'Ñ' => 'N', 'ñ' => 'n');
    return str_replace(array_keys($a), array_values($a), $text);
}


function xml2array($contents, $get_attributes = 0, $priority = 'tag') {
    if (!$contents)
        return array();

    if (!function_exists('xml_parser_create')) {
        return array();
    }

    $parser = xml_parser_create('');
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); 
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);

    if (!$xml_values)
        return;

        
    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();

    $current = &$xml_array; 
    $repeated_tag_index = array(); 
    foreach ($xml_values as $data) {
        unset($attributes, $value); 
        extract($data); 
        $result = array();
        $attributes_data = array();

        if (isset($value)) {
            if ($priority == 'tag')
                $result = $value;
            else
                $result['value'] = $value; 
        }

        if (isset($attributes) and $get_attributes) {
            foreach ($attributes as $attr => $val) {
                if ($priority == 'tag')
                    $attributes_data[$attr] = $val;
                else
                    $result['attr'][$attr] = $val; 
            }
        }

        if ($type == "open") {
            $parent[$level - 1] = &$current;
            if (!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
                $current[$tag] = $result;
                if ($attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
                $repeated_tag_index[$tag . '_' . $level] = 1;

                $current = &$current[$tag];
            } else { //There was another element with the same tag name
                if (isset($current[$tag][0])) {//If there is a 0th element it is already an array
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    $repeated_tag_index[$tag . '_' . $level]++;
                } else {//This section will make the value an array if multiple tags with the same name appear together
                    $current[$tag] = array($current[$tag], $result); //This will combine the existing item and the new item together to make an array
                    $repeated_tag_index[$tag . '_' . $level] = 2;

                    if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well
                        $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                        unset($current[$tag . '_attr']);
                    }
                }
                $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                $current = &$current[$tag][$last_item_index];
            }
        } elseif ($type == "complete") { //Tags that ends in 1 line '<tag />'
            if (!isset($current[$tag])) { //New Key
                $current[$tag] = $result;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                if ($priority == 'tag' and $attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
            } else { //If taken, put all things inside a list(array)
                if (isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array...
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;

                    if ($priority == 'tag' and $get_attributes and $attributes_data) {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag . '_' . $level]++;
                } else { //If it is not an array...
                    $current[$tag] = array($current[$tag], $result); //...Make it an array using using the existing value and the new value
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' and $get_attributes) {
                        if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset($current[$tag . '_attr']);
                        }

                        if ($attributes_data) {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
                }
            }
        } elseif ($type == 'close') { //End of tag '</tag>'
            $current = &$parent[$level - 1];
        }
    }

    return($xml_array);
}

global $serverurl;


if (isset($_SESSION['hd_accesslvl']) AND $config[84][1] == 1) {
    $serverurl = str_replace('http://', 'https://', $config[1][1]);
} else {
    $serverurl = $config[1][1];
}

$offsetdays = $config[5][1];
$df = $config[6][1];
$dfs = $config[28][1];

$thisclient = 0;
$url2co = $config[29][1] . '?sid=' . $config[30][1];

if (isset($_COOKIE['hd_langclient'])) {
    $currentlang = $_COOKIE['hd_langclient'];
} elseif ($config[3][1] == 'autodetect') {
    $langbrowser = detectarIdioma();
    $result = mysql_query("SHOW COLUMNS FROM hd_languages");
    if (mysql_num_rows($result) > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            if ($row[Field] <> 'original') {
                $langlist[] = $row[Field];
            }
        }
    }
    if (in_array($langbrowser, $langlist)) {
        $currentlang = $langbrowser;
    } else {
        $currentlang = $langlist[0];
    }
} else {
    $currentlang = $config[3][1];
}

global $theme;
$theme = $config[25][1];



if (isset($_COOKIE['hd_charts'])) {
    $charttype = $_COOKIE['hd_charts'];
} else {
    $charttype = "2D";
}

function minihelp($texto) {
    return "<mhelp name='minihelp' id='minihelp' style='BACKGROUND-COLOR: #909090; border: 1px solid #909090; color: white; display: none;'>&nbsp;$texto&nbsp;</mhelp>";
}

function btnresetpass($url) {
    global $serverurl;
    $texto = "<a href='$serverurl/$url'><img class='sprites key' src='images/transparent.gif' border='0' title='" . lang('_RESET_PASSWORD') . "' onclick=\"return confirm('" . lang('_RESET_PASSWORD') . "?')\"></a>&nbsp;";
    return $texto;
}

function btnedit($url) {
    global $serverurl;
    $texto = "<a href='$serverurl/$url'><img class='sprites edit' src='images/transparent.gif' border='0' title='" . lang('_EDIT') . "'></a>&nbsp;";
    return $texto;
}

function btndelete($url, $producto = "") {
    global $serverurl;
    $texto = "<a href='$serverurl/$url'><img class='sprites del' src='images/transparent.gif' border='0' title='" . lang('_DELETE') . "' onclick=\"return confirm('" . lang('_DELETE') . " $producto?')\"></a>&nbsp;";
    return $texto;
}

function btnsuspend($url, $producto = "") {
    global $serverurl;
    $texto = "<a href='$serverurl/$url'><img class='sprites suspend' src='images/transparent.gif' border='0' title='" . lang('_SUSPEND') . "' onclick=\"return confirm('" . lang('_SUSPEND') . " $producto?')\"></a>&nbsp;";
    return $texto;
}

function btnunsuspend($url, $producto = "") {
    global $serverurl;
    $texto = "<a href='$serverurl/$url'><img class='sprites unsuspend' src='images/transparent.gif' border='0' title='" . lang('_UNSUSPEND') . "' onclick=\"return confirm('" . lang('_UNSUSPEND') . " $producto?')\"></a>&nbsp;";
    return $texto;
}

$query = "SELECT * FROM hd_languages";
$result = mysql_query($query);
while ($idioma = mysql_fetch_array($result)) {
    if ($idioma[$currentlang]) {
        define($idioma['original'], $idioma[$currentlang]);
    } else {
        define($idioma['original'], $idioma['original']);
    }
}
$strColor[0] = '8CD5FF';
$strColor[1] = '8CFFB6';
$strColor[2] = 'FFB68C';
$strColor[3] = 'FFD1D4';
$strColor[4] = '86D9D3';

$strColor[5] = 'EAFF94';
$strColor[6] = 'BED952';
$strColor[7] = 'DBC7FF';
$strColor[8] = '59D995';
$strColor[9] = 'FF9CF3';
$strColor[10] = 'C4A9AE';
$strColor[11] = 'D9CD62';
$strColor[12] = 'F6A6FF';




require_once 'pagination.php';

function antispam($type, $text) {
    $query = "SELECT * FROM hd_spamfilters WHERE type='" . $type . "'";
    $result = mysql_query($query);
    $spam = '';
    while ($data = mysql_fetch_array($result)) {
        $spamtext = $data['text'];
        if ($type == 'Email') {
            if (strtolower($text) == strtolower($spamtext)) {
                $spam .= "<br>" . ucfirst(_EMAIL) . " <b> " . strtolower($spamtext) . "</b> " . _IS_BLACKLISTED . "";
            }
        }
        if ($type == 'Domain') {
            if (stristr($text, $spamtext)) {
                $spam .= "<br>" . ucfirst(_DOMAIN) . " <b> " . strtolower($spamtext) . "</b> " . _IS_BLACKLISTED . "";
            }
        }
        if ($type == 'Body') {
            if (stristr($text, $spamtext)) {
                $spam .= "<br><b>" . strtolower($spamtext) . "</b> " . _IS_BLACKLISTED . "";
            }
        }
        if ($type == 'Subject') {
            if (stristr($text, $spamtext)) {
                $spam .= "<br><b>" . strtolower($spamtext) . "</b> " . _IS_BLACKLISTED . "";
            }
        }
    }
    return $spam;
}

function sanitize_data($data, $noquotes = 0) {
    if ($data == "") {
        return FALSE;
    }
    if ($noquotes) {
        if (get_magic_quotes_gpc()) {
            $data = trim(htmlentities($data, ENT_COMPAT, 'UTF-8'));
        } else {
            $data = trim(htmlentities(addslashes($data), ENT_COMPAT, 'UTF-8'));
        }
    } else {
        if (get_magic_quotes_gpc()) {
            $data = trim(stripslashes(htmlentities($data, ENT_QUOTES, 'UTF-8')));
        } else {
            $data = trim(htmlentities($data, ENT_QUOTES, 'UTF-8'));
        }
    }
    $data = str_replace("(", '&#40;', $data);
    $data = str_replace(")", '&#41;', $data);
    $data = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $data);
    return $data;
}

function resto($dividendo, $divisor) {
    $cociente = floor($dividendo / $divisor);
    $resto = $dividendo - $divisor * $cociente;
    if (($divisor - $resto) < 1) {
        $resto = $divisor - $resto;
    }
    return round($resto, 2);
}

function byteConvert($bytes) {
    $s = array('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB');
    if ($bytes <= 0) {
        return "0 " . $s[0];
    }
    $e = floor(log($bytes) / log(1024));
    return sprintf('%.2f ' . $s[$e], ($bytes / pow(1024, floor($e))));
}

function collectdata($arreglo, $valor) {
    if ($arreglo == 'client') {
        if ($_SESSION['hd_accesslvl'] == 1) {
            $valor = $_SESSION['hd_clientid'];
        } elseif ($_SESSION['hd_accesslvl'] > 1) {
        } else {
            messagetop('ERROR', '479765543', 'index.php', 0);
        }
        $query = "SELECT * FROM hd_clients WHERE clientid='$valor'";
        $result = mysql_query($query, $GLOBALS['db_link']);
        $client = mysql_fetch_array($result);
        if (mysql_affected_rows() > 0) {
            $client['firstname'] = $client['first'];
            $client['lastname'] = $client['last'];
            $client['password'] = decrypt($client['password']);
            $client['state'] = showstate($client['state']);
            $client['countryISO'] = showcountryISO($client['country']);
            $client['phonecode'] = showphonecode($client['country']);
            if (substr($client['phone'], 0, 1) == '0') {
                $client['phone'] = substr($client['phone'], 1);
            }
            if ($client['zip'] == '') {
                $client['zip'] = '00000';
            }
            $client['country'] = showcountry($client['country']);
            return $client;
        } else {
            messagetop('ERROR', '', 'index.php', 0);
        }
    }
}

function mail2admin($mailsubject, $mailbody) {
    global $config, $serverurl, $theme, $fondografica25;
    $mailfrom = $config[0][1] . " <" . $config[19][1] . ">";
    $mailto = $config[0][1] . " <" . $config[19][1] . ">";
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=" . $config[72][1] . "\r\n";
    $bodymail = strtoupper($mailsubject);
    $bodymail.= $mailbody;
    $bodymail = stripslashes($bodymail);
    mail($mailto, $mailsubject, $bodymail, $headers . "From:$mailfrom");
}

function mail2client($mailsubject, $mailbody, $mailfrom = 'admin', $mailto, $logoyesno = 1) {
    global $config, $serverurl, $theme, $fondografica25;
    if ($mailfrom == 'reminder') {
        $mailfrom = $config[0][1] . " <" . $config[16][1] . ">";
        $mailreply = $config[0][1] . " <" . $config[17][1] . ">";
        $paramf = $config[16][1];
        $mailbcc = $config[18][1];
    } elseif ($mailfrom == 'admin') {
        $mailfrom = $config[0][1] . " <" . $config[19][1] . ">";
        $mailreply = $config[0][1] . " <" . $config[20][1] . ">";
        $paramf = $config[19][1];
        $mailbcc = $config[21][1];
    } elseif ($mailfrom == 'adminSINcopia') {
        $mailfrom = $config[0][1] . " <" . $config[19][1] . ">";
        $mailreply = $config[0][1] . " <" . $config[20][1] . ">";
        $paramf = $config[19][1];
        $mailbcc = '';
    } else {
        $mailfrom = $config[0][1] . " <" . $config[22][1] . ">";
        $mailreply = $config[0][1] . " <" . $config[23][1] . ">";
        $paramf = $config[22][1];
        $mailbcc = $config[24][1];
    }
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=" . $config[72][1] . "\r\n";
    $headers .= "From:" . $mailfrom;
    if ($mailreply <> '') {
        $headers .= "\nReply-To:" . $mailreply;
    }
    if ($mailbcc <> '') {
        $headers .= "\nBCC:" . $mailbcc;
    }

    $bodymail = strtoupper($mailsubject);
    if ($logoyesno) {
        $bodymail.="<img src='$serverurl/attachments/" . $config[87][1] . "'><br><br>";
    }
    $bodymail.= $mailbody;
    $bodymail = stripslashes($bodymail);

    if (mail($mailto, $mailsubject, $bodymail, $headers)) {
        return true;
    } else {
        return false;
    }
}

function mail2affiliate($mailsubject, $mailbody, $mailfrom, $mailto, $logoyesno = 0) {
    global $config, $serverurl, $theme, $fondografica25;

    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=" . $config[72][1] . "\r\n";
    $headers .= "From:" . $mailfrom;

    $bodymail = strtoupper($mailsubject);
    if ($logoyesno) {
        $bodymail.="<img src='$serverurl/attachments/" . $config[87][1] . "'><br><br>";
    }
    $bodymail.= "<div align='left'>";
    $bodymail.= stripslashes(base64_decode($mailbody));
    $bodymail.= "</div>";

    $bodymail = stripslashes($bodymail);

    if (mail($mailto, $mailsubject, $bodymail, $headers)) {
        return true;
    } else {
        return false;
    }
}


function imageintheme($imagenAmostrar) {
    if ($imagenAmostrar) {
        echo "<td align='center' valign='top' width='1'>";
        echo "<img src='images/" . $imagenAmostrar . "'>";
        echo "</td>";
    }
}



function normalbutton($url, $message, $includetable = 0) {
    global $config, $serverurl;
    if ($url <> '') {
        print("<a class='btn btn-large btn-primary' href='" . $serverurl . "/" . $url . "'><b>" . ucfirst($message) . "</b></a>&nbsp;");
    } else {
        print("<b class='btn btn-large btn-primary'>" . ucfirst($message) . "</b>&nbsp;");
    }
}

function redbutton($url, $message, $includetable = 0) {
    global $config, $serverurl;
    if ($url <> '') {
        print("<a class='btn btn-large btn-danger' href='" . $serverurl . "/" . $url . "'><b>" . ucfirst($message) . "</b></a>&nbsp;");
    } else {
        print("<b class='btn btn-large btn-danger'>" . ucfirst($message) . "</b>&nbsp;");
    }
}

function yellowbutton($url, $message, $includetable = 0) {
    global $config, $serverurl;
    if ($url <> '') {
        print("<a class='btn btn-large btn-warning' href='" . $serverurl . "/" . $url . "'><b>" . ucfirst($message) . "</b></a>&nbsp;");
    } else {
        print("<b class='btn btn-large btn-warning'>" . ucfirst($message) . "</b>&nbsp;");
    }
}

function greenbutton($url, $message, $includetable = 0) {
    global $config, $serverurl;
    if ($url <> '') {
        print("<a class='btn btn-large btn-success' href='" . $serverurl . "/" . $url . "'><b>" . ucfirst($message) . "</b></a>&nbsp;");
    } else {
        print("<b class='btn btn-large btn-success'>" . ucfirst($message) . "</b>&nbsp;");
    }
}

function graybutton($url, $message, $includetable = 0) {
    global $config, $serverurl;
    if ($url <> '') {
        print("<a class='btn btn-large' href='" . $serverurl . "/" . $url . "'><b>" . ucfirst($message) . "</b></a>&nbsp;");
    } else {
        print("<b class='btn btn-large'>" . ucfirst($message) . "</b>&nbsp;");
    }
}

function submenubutton($url, $message, $includetable = 0) {
    global $config, $serverurl;
    if ($includetable == 1) {
        print("<table border=0 cellpadding=0 cellspacing=0><tr>");
    }
    print("<td width='9' height='30' background='images/submenu_left.png' align='center' style='border-top: 0px; border-bottom: 0px; padding: 0em;'></td>");
    print("<td height='30' background='images/submenu_center.png' align='center' nowrap style='border-top: 0px; border-bottom: 0px; padding: 0em;'>");
    if ($url <> '') {
        print("<a href='" . $serverurl . "/" . $url . "'><b><font color='#ffffff' size='2'>" . ucfirst($message) . "</font></b></a></td>");
    } else {
        print("<b><font color='#ffffff'>" . ucfirst($message) . "</font></b></td>");
    }
    print("<td width='9' height='30' background='images/submenu_right.png' align='center' style='border-top: 0px; border-bottom: 0px; padding: 0em;'></td>");
    if ($includetable == 1) {
        print("</tr></table>");
    }
}

function greenbutton_blank($url, $message, $includetable = 0) {
    global $config, $serverurl;
    if ($includetable == 1) {
        print("<table border=0 cellpadding=0 cellspacing=0><tr>");
    }
    print("<td width='15' height='32' background='images/greenbutton_left.png' align='center' style='border-top: 0px; border-bottom: 0px; padding: 0em;'></td>");
    print("<td height='32' background='images/greenbutton_center.png' align='center' nowrap style='border-top: 0px; border-bottom: 0px; padding: 0em;'>");
    if ($url <> '') {
        print("<a href='" . $url . "' target='_blank'><b><font color='ffffff'>" . ucfirst($message) . "</font></b></a></td>");
    } else {
        print("<b><font color='ffffff'>" . ucfirst($message) . "</font></b></td>");
    }
    print("<td width='15' height='32' background='images/greenbutton_right.png' align='center' style='border-top: 0px; border-bottom: 0px; padding: 0em;'></td>");
    if ($includetable == 1) {
        print("</tr></table><br>");
    }
}

function printpackid($packid) {
    return "<font color=gray>[" . $packid . "]</font>";
}

function detectarIdioma() {
    $aidiomas = explode(",", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    $userlang = substr($aidiomas[0], 0, 2);
    return $userlang;
}

function langname($langcode) {
    $langname = query("SELECT name FROM hd_langcodes WHERE code='" . $langcode . "'", 1);
    return $langname['name'];
}

function translate($text, $from = 'es', $to = 'en') {
    $url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=' . urlencode($text) . '&langpair=' . $from . '|' . $to . '';
    $curl_handle = curl_init();
    curl_setopt($curl_handle, CURLOPT_URL, $url);
    curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
    $code = curl_exec($curl_handle);
    curl_close($curl_handle);
    $json = json_decode($code);
    $traduc = $json->responseData;
    $text = $traduc->translatedText;
    $traduccion = $text;
    if (!is_in_utf8($traduccion)) {
        $traduccion = utf8_encode($traduccion);
    }
    return $traduccion;
}

function is_in_utf8($string) {
    return preg_match('%^(?:
              [\x09\x0A\x0D\x20-\x7E]            # ASCII 
            | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte 
            |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs 
            | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte 
            |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates 
            |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3 
            | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15 
            |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16 
        )*$%xs', $string);
}

function stringtranslated($string) {
    global $config, $currentlang;
    if ($idioma == '') {
        $idioma = $currentlang;
    }
    if ($idioma == '') {
        $idioma = $config[107][1];
    }
    $string = strtoupper($string);
    $string = '_' . $string;
    $stringlang = query("SELECT * FROM hd_languages WHERE original = '" . $string . "' LIMIT 1", 1);
    if ($stringlang[$idioma] == '') {
        return $string;
    } else {
        return ucfirst($stringlang[$idioma]);
    }
}

function lang($original, $idioma = '') {
    global $config, $currentlang;
    if (substr($original, 0, 1) == '-') {
        $original = substr($original, 1);
        $noUC = true;
    }
    if ($idioma == '') {
        $idioma = $currentlang;
    }
    if ($idioma == '') {
        $idioma = $config[107][1];
    }
    $stringlang = query("SELECT * FROM hd_languages WHERE original = '" . $original . "' LIMIT 1", 1);
    if ($stringlang[$idioma] == '') {
        return $original;
    } else {
        if ($noUC) {
            return strtolower($stringlang[$idioma]);
        } else {
            return ucfirst($stringlang[$idioma]);
        }
    }
}

function tip($id, $idioma = '') {
    global $config, $currentlang;
    if ($idioma == '') {
        $idioma = $currentlang;
    }
    if ($idioma == '') {
        $idioma = $config[107][1];
    }
    $stringlang = query("SELECT * FROM hd_tips WHERE id = '" . $id . "' LIMIT 1", 1);
    $stringlang[$idioma] = str_replace("'", "", $stringlang[$idioma]);
    if ($stringlang[$idioma] == '') {
        return '';
    } else {
        $tip = "<img class='sprites tip btip' src='images/transparent.gif' border='0' title='" . ucfirst($stringlang[$idioma]) . "'>";
        return $tip;
    }
}

function tip4manual($id, $idioma = '') {
    global $config, $currentlang;
    if ($idioma == '') {
        $idioma = $currentlang;
    }
    if ($idioma == '') {
        $idioma = $config[107][1];
    }
    $stringlang = query("SELECT * FROM hd_tips WHERE id = '" . $id . "' LIMIT 1", 1);
    if ($stringlang[$idioma] == '') {
        return '';
    } else {
        return ucfirst($stringlang[$idioma]);
    }
}

function texto($name, $idioma = '') {
    global $currentlang;
    if ($idioma == '') {
        $idioma = $currentlang;
    }
    $query = "SELECT * FROM hd_texts WHERE name='" . $name . "' AND langs LIKE '%" . $idioma . "%' ORDER by title";
    $output = mysql_query($query, $GLOBALS['db_link']);
    $stringtext = '';
    while ($row = mysql_fetch_array($output)) {
        if ($stringtext == '') {
            $stringtext .= stripslashes(base64_decode($row['message']));
        } else {
            $stringtext .= "<br>" . stripslashes(base64_decode($row['message']));
        }
    }
    return $stringtext;
}

function clientname($clientid) {
    $output = query("SELECT first, last FROM hd_clients WHERE clientid='" . $clientid . "'", 1);
    return $output['first'] . " " . $output['last'];
}

function css3compatible() {
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $ub = '';
    $css3comp = false;
    if (preg_match('/MSIE/i', $u_agent)) {
        $ub = "ie";
        $css3comp = false;
    } elseif (preg_match('/Chrome/i', $u_agent)) {
        $ub = "chrome";
        $css3comp = true;
    } elseif (preg_match('/Firefox/i', $u_agent)) {
        $ub = "firefox";
        $css3comp = true;
    } elseif (preg_match('/Safari/i', $u_agent)) {
        $ub = "safari";
        $css3comp = true;
    } elseif (preg_match('/Opera/i', $u_agent)) {
        $ub = "opera";
        $css3comp = true;
    }
    return $css3comp;
}


function calendarform($fechaunix, $mes = 'month', $dia = 'day', $anio = 'year') {
    $fecha = getdate($fechaunix);
    $codigo = generate_password();
    $texto = '
<select name="' . $mes . '" id="fc_' . $codigo . '_m">
	<option value="01"' . sele("01", $fecha[mon]) . '>' . lang("_JAN") . '</option>
	<option value="02"' . sele("02", $fecha[mon]) . '>' . lang("_FEB") . '</option>
	<option value="03"' . sele("03", $fecha[mon]) . '>' . lang("_MAR") . '</option>
	<option value="04"' . sele("04", $fecha[mon]) . '>' . lang("_APR") . '</option>
	<option value="05"' . sele("05", $fecha[mon]) . '>' . lang("_MAY") . '</option>
	<option value="06"' . sele("06", $fecha[mon]) . '>' . lang("_JUN") . '</option>
	<option value="07"' . sele("07", $fecha[mon]) . '>' . lang("_JUL") . '</option>
	<option value="08"' . sele("08", $fecha[mon]) . '>' . lang("_AUG") . '</option>
	<option value="09"' . sele("09", $fecha[mon]) . '>' . lang("_SEP") . '</option>
	<option value="10"' . sele("10", $fecha[mon]) . '>' . lang("_OCT") . '</option>
	<option value="11"' . sele("11", $fecha[mon]) . '>' . lang("_NOV") . '</option>
	<option value="12"' . sele("12", $fecha[mon]) . '>' . lang("_DEC") . '</option>
</select>
<input size="2" maxlength="2" id="fc_' . $codigo . '_d" name="' . $dia . '" value="' . $fecha[mday] . '">
<input size="4" maxlength="4" id="fc_' . $codigo . '_y" name="' . $anio . '" value="' . $fecha[year] . '">
<a href="javascript:display3FieldCalendar(fc_getObj(\'fc_' . $codigo . '_m\'), fc_getObj(\'fc_' . $codigo . '_d\'), fc_getObj(\'fc_' . $codigo . '_y\'));">
<img src="images/calendar.png" border="0" align="top"></a>	
';
    return $texto;
}

function OutputInfo($id, $dhtml, $text = '') {
    global $textinfoot;
    $DHTMLenabled = true;
    if ($DHTMLenabled) {
        if (!is_null($dhtml)) {
            $dhtml = "<font color='" . $textinfoot . "' size='4'>" . $dhtml . "</font>";
            if ($id) {
                echo '<script type="text/javascript">if (document.getElementById("' . $id . '")) document.getElementById("' . $id . '").innerHTML="' . $dhtml . '"</script>';
            } else {
                echo $dhtml;
            }
            flush();
        }
    } else {
        if ($text) {
            $text = "<font color='" . $textinfoot . "'>" . $text . "</font>";
            echo $text;
            flush();
        }
    }
    return true;
}

function periodo($months, $lang = '') {
    global $currentlang;
    if ($lang == '') {
        $lang = $currentlang;
    }
    if ($months == 0) {
        $p = lang('_ONE_TIME_FEE', $lang);
    } elseif ($months == 1) {
        $p = ($months) . " " . mb_strtolower(lang('_MONTH', $lang), 'UTF-8');
    } elseif ($months == 12) {
        $p = ($months / 12) . " " . mb_strtolower(lang('_YEAR', $lang), 'UTF-8');
    } elseif ($months % 12 == 0) {
        $p = ($months / 12) . " " . mb_strtolower(lang('_YEARS', $lang), 'UTF-8');
    } else {
        $p = ($months) . " " . mb_strtolower(lang('_MONTHS', $lang), 'UTF-8');
    }
    return $p;
}

function make_clickable($ret) {
    $ret = ' ' . $ret . ' ';
    $ret = preg_replace("#([\s>])(https?)://([^\s<>{}()]+[^\s.,<>{}()])#i", "$1<a href='$2://$3' rel='nofollow'>$2://$3</a>", $ret);
    $ret = preg_replace("#(\s)www\.([a-z0-9\-]+)\.([a-z0-9\-.\~]+)((?:/[^ <>{}()\n\r]*[^., <>{}()\n\r]?)?)#i", "$1<a href='http://www.$2.$3$4' rel='nofollow' target='_blank'>www.$2.$3$4</a>", $ret);
    $ret = preg_replace("#(\s)([a-z0-9\-_.]+)@([^,< \n\r]+)#i", "$1<a href=\"mailto:$2@$3\">$2@$3</a>", $ret);
    $ret = trim($ret);
    return $ret;
}

function replacellaves($content) {
    global $config;
    return $content;
}

$regex4mail = '' . '^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,6})$';
?>