<?php
/**
 * pragmaMx  Content Management System
 * Copyright (c) 2007 pragmaMx Dev Team - http://pragmaMx.org
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * $Source: /home/www/dps3311/home/cvsroot/pragmamx/pragmamx_01/modules/Web_Links/includes/functions.php,v $
 * $Revision: 1.11 $
 * $Author: tora60 $
 * $Date: 2007/06/16 11:50:02 $
 * 
 * this file based on:
 * php-nuke Web Portal System - http://phpnuke.org/
 * Thatware - http://thatware.org/
 * Based on Journey Links Hack
 * Copyright (c) 2000 by James Knickelbein
 * Journey Milwaukee (http://www.journeymilwaukee.com)
 */

if (!defined("mxMainFileLoaded")) die ("You can't access this file directly...");

function modViewData($row = array(), $mode = 'single', $full = '')
{
    global $module_name, $showdetails, $usevoting, $bgcolor1, $bgcolor2, $bgcolor3; 
    // zuerst die Daten des Links fuer die Anzeige aufbereiten
    // die wechselnde Hintergrundfarbe
    if ($mode == 'single') {
        $bgcolor = 'transparent';
    } else {
        static $x = 1;
        $c = fmod($x++, 2);
        $bgcolor = ($c) ? $bgcolor1 : $bgcolor3;
    } 
    // User ist als Admin unterwegs...
    static $isadmin;
    if (!isset($isadmin)) {
        $isadmin = mxGetAdminPref("radminlink");
    } 
    // versch. benoetigte Bildchen
    static $imgs;
    if (!isset($imgs)) {
        $imgs['download'] = mxCreateImage('modules/' . $module_name . '/images/download.gif', _LINKNOW, 0, 'hspace="5" style="vertical-align: middle;"'); #
        $imgs['details'] = mxCreateImage('modules/' . $module_name . '/images/info.gif', _ADDITIONALDET, 0, 'align="right"'); #, 0, 'hspace="5"'
        $imgs['check'] = mxCreateImage('modules/' . $module_name . '/images/check.gif', _LINKVALIDATION, 0, 'align="right"'); #, 0, 'hspace="5"'
        $imgs['edit'] = mxCreateImage('modules/' . $module_name . '/images/edit.gif', _EDIT, 0, 'align="right"'); 
        // $imgs['chart'] = mxCreateImage('modules/' . $module_name . '/images/chart.gif', _LINKRATINGDET); #, 0, 'hspace="5"'
        $imgs['pop'] = mxCreateImage('modules/' . $module_name . '/images/popular.gif', _WLPOPULAR . ' (' . $row['hits'] . ' ' . _HITSTOITEM . ')', 0, 'hspace="5" style="vertical-align: middle;"');
        $imgs['default'] = mxCreateImage('modules/' . $module_name . '/images/lwin.gif', ''); 
        // $imgs['homepage'] = mxCreateImage('modules/' . $module_name . '/images/homepage.gif', _WLHOMEPAGE, 0, 'style="vertical-align: middle;"');
    } 
    // formatiertes Veroeffentlichungsdatum
    $row['datetime'] = ucfirst(mx_strftime(_DATESTRING, mxSqlDate2UnixTime($row['updated']))); 
    // wenn Neuer Link, dann ein Bildchen generieren
    if ($mode != 'single' || $full == 'full') {
        if (!isset($_REQUEST['op']) || $_REQUEST['op'] != 'NewLinks') {
            $newimage = modNewMakeGrafic($row['date'], 'hspace="5" style="vertical-align: middle;"');
        } else {
            $newimage = '';
        } 
        // wenn populaerer Link, dann ein Bildchen generieren
        if ($row['hits'] >= $GLOBALS['popular'] && (!isset($GLOBALS['op']) || $GLOBALS['op'] != 'MostPopular')) {
            $popimage = '&nbsp;' . $imgs['pop'];
        } else {
            $popimage = '';
        } 
    } 
    // wenn Detailansicht des Links, auch wirklich die Details anzeigen...
    if ((isset($_REQUEST['op']) && $_REQUEST['op'] == 'view') || $full == 'full') {
        $showdetails = true;
    } 
    // Zeilenumbrueche vor und hinter der Beschreibung entfernen
    // $row wird u.U. nicht als Array erkannt und php macht dann Probleme beim ergaenzen von Strings
    // mit ".", deswegen hier bei $description als normale Variable weiterarbeiten.
    // Info dazu: http://www.pragmamx.org/Forum-topic-21006.html
    $description = preg_replace('#<br\s*/?>+$#si', '', trim($row['description']));
    $description = preg_replace('#^<br\s*/?>+#si', '', $description); 
    // Suchergebnisse hervorheben, falls vorhanden
    if (isset($_GET['query'])) {
        $words = explode(' ', $_GET['query']);
        foreach($words as $word) {
            if ($word) {
                // $row['title'] = modHighlightString($title, $word);
                $description = modHighlightString($description, $word);
            } 
        } 
    } 
    // TODO: nur bei Listenansicht!!!
    // wenn Editorial vorhanden, einen zusaetzlichen Link dazu in der Beschreibung anzeigen
    if (!empty($row['editorialid'])) {
        $description .= '<div align="right"><a href="modules.php?name=' . $module_name . '&amp;op=view&amp;lid=' . $row['lid'] . '#editorial" title="' . _EDITORREVIEW . '">' . _HREADMORE . '</a></div>';
    } 
    // die Kategorie, komplett mit Links
    if (isset($row['cparentid'])) {
        $row['categorie'] = modGetParentTitlesAsLink($row['cparentid'], $row['ctitle'], $row['cid']);
    } 
    // wenn Admin, dann Link zum Aendern
    $edit = '';
    if ($isadmin) {
        $edit = '<a href="admin.php?op=LinksModData&amp;lid=' . $row['lid'] . '">' . $imgs['edit'] . '</a>';
        $edit .= '<a href="modules.php?name=' . $module_name . '&amp;op=check&amp;url=' . urlencode($row['url']) . '"' . modCheckPopupLink($row['url']) . '>' . $imgs['check'] . '</a>';
    } 
    if ($mode != 'single') {
        $view = '<a href="modules.php?name=' . $module_name . '&amp;op=view&amp;lid=' . $row['lid'] . '" title="' . _ADDITIONALDET . '">' . $imgs['details'] . '</a>';
    } else {
        $view = '';
    } 

    if ($row['totalvotes']) {
        // Die Dezimalstellen der Bewertung formatieren
        $row['linkratingsummary'] = number_format($row['linkratingsummary'], $GLOBALS['mainvotedecimal']); 
        // das Bewertungsbildchen (die Sterne)
        $ratepic = '<a href="modules.php?name=' . $module_name . '&amp;op=viewratingdetails&amp;lid=' . $row['lid'] . '" title="' . _LINKRATINGDET . '">' . modRateMakeStar($row['linkratingsummary'], $row['totalvotes']) . '</a>';
        $more1 = '';
        $more2 = $view . '' . $edit; 
        // $more2 .= '<a href="modules.php?name=' . $module_name . '&amp;op=viewratingdetails&amp;lid=' . $row['lid'] . '" title="' . _LINKRATINGDET . '">' . $imgs['chart'] . '</a>';
    } else {
        $more1 = $view . '' . $edit;
        $more2 = '';
    } 
    // / Und jetzt endlich die eigentliche Anzeige
    if ($mode != 'single' || $full == 'full') {

        ?>
<div style="border: 1px solid <?php echo $bgcolor2 ?>;">
<table width="100%" border="0" cellspacing="0" cellpadding="5" style="background-color:<?php echo $bgcolor ?>;">
  <tr valign="top">
    <td width="2%"><?php echo $imgs['default'] ?></td>
    <td><h3 style="margin: 0;"><?php echo '<a href="modules.php?name=' . $module_name . '&amp;op=view&amp;lid=' . $row['lid'] . '" title="' . _ADDITIONALDET . '">' . $row['title'] . '</a>' , $popimage, $newimage ?></h3></td>
    <td width="20%" align="right"><div style="white-space: nowrap;"><?php echo '<a href="modules.php?name=' . $module_name . '&amp;op=visit&amp;lid=' . $row['lid'] . '" target="_blank" title="' . _LINKNOW . '">' . _LINKNOW . $imgs['download'] . '</a>' ?></div></td>
  </tr>
</table>
<?php } 

    ?>
<table width="100%" border="0" cellspacing="0" cellpadding="3" style="background-color:<?php echo $bgcolor ?>;">

<?php if ($showdetails) {
        if (isset($row['categorie'])) {

            ?>
  <tr valign="top">
    <td align="right"><strong><?php echo _WLCATEGORY ?>:</strong></td>
    <td colspan="4"><?php echo $row['categorie'] ?></td>
  </tr>
  <?php } 

        ?>
  <tr valign="top">
    <td width="10%"><div align="right"><strong><?php echo _WLDESCRIPTION ?>:</strong></div></td>
    <td width="90%" colspan="4"><?php echo $description ?></td>
  </tr>
  <tr valign="top">
    <td align="right"><strong><?php echo _LASTUPDATED ?>:</strong></td>
    <td colspan="4"><?php echo $row['datetime'] ?></td>
  </tr>
  <?php if ($row['auth_name']) {

            ?>
  <tr valign="top">
    <td align="right"><strong><?php echo _WLAUTHOR ?>:</strong></td>
    <td colspan="4"><?php echo $row['auth_name'] ?></td>
  </tr>
  <?php } 

        ?>
  <tr valign="top">
    <td align="right"><strong><?php echo _HITSTOITEM ?>:</strong></td>
    <td colspan="4"><?php echo $more1, $row['hits'] ?></td>
  </tr>
  <?php if ($usevoting && $row['totalvotes']) {

            ?>
  <tr valign="top">
    <td width="10%" align="right"><strong><?php echo _RATING ?>:</strong></td>
    <td width="20%" align="left"><?php echo $ratepic ?>&nbsp;</td>
    <td width="25%" align="right"><strong><?php echo _TOTALVOTES ?>:</strong></td>
    <td width="10%" align="left"><span style="white-space: nowrap;"><?php echo $row['totalvotes'] ?></span></td>
    <td align="left"><?php echo $more2 ?></td>
  </tr>
  <?php } 
    } 
    // END if ($showdetails)
    else {
        if (isset($row['categorie'])) {

            ?>
  <tr valign="top">
    <td colspan="5"><?php echo _WLCATEGORY ?>: <?php echo $row['categorie'] ?></td>
  </tr>
  <?php } 

        ?>
  <tr valign="top">
    <td colspan="5"><?php echo $description ?></td>
  </tr>
  <tr valign="top">
    <td colspan="5"><?php echo $more1, $more2, _HITSTOITEM, ':&nbsp;', $row['hits'] ?></td>
  </tr>
    <?php
    } 

    ?>
</table>
<?php
    if ($mode != 'single' || $full == 'full') {

        ?>
</div>
<?php
    } 

    ?>
<br>
<?php
} 

function modDataForm($thisdata = array(), $op = '')
{
    global $module_name;
    $thisdata['lid'] = (isset($thisdata['lid'])) ? intval($thisdata['lid']) : 0;
    if (mxGetAdminPref('radmindownload')) {
        $iseradmin = 1;
        $thisdata['url'] = (isset($thisdata['url'])) ? htmlspecialchars($thisdata['url']) : 'http://';
        $checkurl = mxCutHTTP($thisdata['url']);
        if ($checkurl) {
            $checkurl = ' [&nbsp;<a target="_blank" href="' . $thisdata['url'] . '"' . modCheckPopupLink($thisdata['url']) . '>' . _CHECKTHIS . '</a>&nbsp;]';
        } 
    } else {
        $iseradmin = 0; 
        // url vor nicht-admins verstecken
        $thisdata['url'] = (isset($thisdata['url'])) ? '' : 'http://';
        $checkurl = '';
    } 
    // Linkbeschreibung
    $thisdata['description'] = (isset($thisdata['description'])) ? trim($thisdata['description']) : '';
    if ($thisdata['description']) {
        // Zeilenumbrueche vor und hinter der Beschreibung entfernen
        $thisdata['description'] = preg_replace('#<br\s*/?>+$#si', '', $thisdata['description']);
        $thisdata['description'] = preg_replace('#^<br\s*/?>+#si', '', $thisdata['description']);
    } 
    // Hauptkategorie anzeigen, um Link zu verstecken
    $showmaincat = $iseradmin; 
    // das Aenderungsdateum als Timestamp
    if (!empty($thisdata['date'])) {
        $thisdata['timestamp'] = mxSqlDate2UnixTime($thisdata['date']);
    } else if (isset($thisdata['upday'], $thisdata['upmonth'], $thisdata['upyear'])) {
        $thisdata['timestamp'] = mktime(date('H'), date('i'), date('s'), $thisdata['upmonth'], $thisdata['upday'], $thisdata['upyear']);
    } else {
        $thisdata['timestamp'] = time();
    } 

    $upbutton = ''; //'&nbsp;<input type="button" value="Upload" onClick="newWindow('modules.php?name=' . $module_name . '&amp;file=upload_file&amp;type=file','window2')">';
    /**
     * $js = '
     * <script language="JavaScript" type="text/javascript">
     * function newWindow(file,window) {
     * msgWindow=open(file,window,'resizable=no,width=450,height=250,top=25,left=200');
     * if (msgWindow.opener == null) msgWindow.opener = self;
     * }
     * </script>';
     */
    $js = '';

    $out = '
    <tr valign="top"><td width="15%">' . $js . '<input type="hidden" name="lid" value="' . $thisdata['lid'] . '">' . _LINKNAME . ': </td>
    <td><input type="text" name="title" value="' . ((isset($thisdata['title'])) ? htmlspecialchars($thisdata['title']):'') . '" size="60" maxlength="100"></td></tr>
    <tr valign="top"><td>' . _WLFILEURL . ': </td>
    <td><input type="text" name="url" value="' . $thisdata['url'] . '" size="60" maxlength="255">' . $upbutton . '&nbsp;' . $checkurl . '</td></tr>
    <tr valign="top"><td>' . _WLCATEGORY . ': </td>
    <td><select name="cid">' . modGetCategoriesSelect(((isset($thisdata['cid'])) ? intval($thisdata['cid']):'0'), $showmaincat) . '</select></td></tr>
    <tr valign="top">';
    if ($GLOBALS['wysiwyg'] && $GLOBALS['wysiwyg_linx']) {
        $sw = new SPAW_Wysiwyg('downdescription_' . $thisdata['lid'], ((isset($thisdata['description'])) ? $thisdata['description']:''), _DOC_LANGUAGE, $GLOBALS['wysiwyg_toolbar'], $GLOBALS['wysiwyg_btnset'], '100%', '250');
        $out .= '<td colspan="2">' . _LDESCRIPTION . ':<br>';
        $out .= $sw->getHtml();
    } else {
        $out .= '<td>' . _LDESCRIPTION . ': </td><td>';
        $out .= '<textarea name="downdescription_' . $thisdata['lid'] . '" cols="70" rows="12">' . ((isset($thisdata['description'])) ? htmlspecialchars($thisdata['description']):'') . '</textarea>';
    } 
    $out .= '</td></tr>
    <tr valign="top"><td>' . _LASTUPDATED . ': </td>
    <td>' . mxDateSelect($thisdata['timestamp'], "upyear", "upmonth", "upday") . ' <input type="hidden" name="orgtimestamp" value="' . $thisdata['timestamp'] . '"></td></tr>
    <tr valign="top"><td>' . _WLAUTHORNAME . ': </td>
    <td><input type="text" name="auth_name" value="' . ((isset($thisdata['auth_name'])) ? htmlspecialchars($thisdata['auth_name']):'') . '" size="30" maxlength="100"></td></tr>
    <tr valign="top"><td>' . _WLAUTHOREMAIL . ': </td>
    <td><input type="text" name="email" value="' . ((isset($thisdata['email'])) ? htmlspecialchars($thisdata['email']):'') . '" size="30" maxlength="100"></td></tr>
    ';
    if ($iseradmin) {
        $out .= '<tr valign="top"><td>' . _WLSUBMITTER . ':  </td>
        <td><input type="text" name="submitter" value="' . ((isset($thisdata['submitter'])) ? htmlspecialchars($thisdata['submitter']):'') . '" size="30" maxlength="25"></td></tr>';
        $out .= '<tr valign="top"><td>' . _WLHITS . ': </td>
        <td><input type="text" name="hits" value="' . ((isset($thisdata['hits'])) ? intval($thisdata['hits']):'0') . '" size="15" maxlength="15"></td></tr>';
        if (!empty($thisdata['lid'])) {
            $out .= '<tr valign="top"><td>' . _LINKID . ':  </td><td><b>' . $thisdata['lid'] . '</b></td></tr>';
        } 
    } else {
        if (isset($thisdata['submitter'])) {
            $out .= '<tr valign="top"><td>' . _WLSUBMITTER . ':  </td>
            <td><b>' . mxPrepareToDisplay($thisdata['submitter']) . '</b></td></tr>';
        } 
        if ($GLOBALS['weblinkson']) {
            $out .= '<tr><td colspan="2" align="center">';
            include('includes/captcha/captcha_java.php');
            $out .= '<img id="captchaimage" src="includes/captcha/captchaimg.php?' . md5(crypt(uniqid(rand()))) . '" alt="' . _CAPTCHAINSERT . '">'
             . '<p>' . _CAPTCHAINSERT . ' <input type="text" name="captcha" value="" size="20" maxlength="20">'
             . '&nbsp;&nbsp;<input type="button" value="' . _CAPTCHARELOAD . '" onclick="do_reload(); return false;">'
             . '</p></td></tr>';
        } 
    } 
    return $out;
} 

function modPageTopMenu($op = '')
{
    global $module_name, $usevoting; 
    // die aktuelle Kategorie-id aus request ermitteln, wenn leer, dann ist es die Hauptseite ohne spezielle Kategorie
    $cid = (empty($_REQUEST['cid']) || $_REQUEST['cid'] < 0) ? 0 : intval($_REQUEST['cid']); 
    // guggen was gerade laeuft
    if (!$op) {
        $op = (empty($_REQUEST['op'])) ? '' : $_REQUEST['op'];
    } 
    // mxDebugFuncVars($op);
    if ($cid || $op) {
        $menu[] = '<a href="modules.php?name=' . $module_name . '" title="' . _LINKSMAINCAT . '">' . _LINKSMAIN . '</a>';
    } else {
        $menu[] = _LINKSMAIN;
    } 

    if ($op === 'RandomLink') {
        $menu[] = _RANDOM;
    } else {
        $menu[] = '<a href="modules.php?name=' . $module_name . '&amp;op=RandomLink' . (($cid) ? '&amp;cid=' . $cid : '') . '" title="' . _RANDOM . '">' . _RANDOM . '</a>';
    } 

    if ($op === 'NewLinks') {
        $menu[] = _NEW;
    } else {
        $menu[] = '<a href="modules.php?name=' . $module_name . '&amp;op=NewLinks" title="' . _TOTALNEWLINKS . '">' . _NEW . '</a>';
    } 

    if ($op === 'MostPopular') {
        $menu[] = _WLPOPULAR;
    } else {
        $menu[] = '<a href="modules.php?name=' . $module_name . '&amp;op=MostPopular" title="' . _MOSTPOPULAR . ' ' . _MODITEMS . '">' . _WLPOPULAR . '</a>';
    } 

    if ($usevoting) {
        if ($op === 'TopRated') {
            $menu[] = _TOPRATED;
        } else {
            $menu[] = '<a href="modules.php?name=' . $module_name . '&amp;op=TopRated" title="' . _DBESTRATED . '">' . _TOPRATED . '</a>';
        } 
    } 

    if (mxGetAdminPref('radminlink')) {
        $menu[] = '<a href="admin.php?op=Links&amp;cid=' . $cid . '#addnew" title="' . _ADDNEWLINK . '">' . _WEBLINKSADMIN . '</a>';
    } else if ($GLOBALS['user_addlink'] == 1) {
        if (MX_IS_USER || $GLOBALS['link_anonaddlinklock'] != 1) {
            if ($op === 'AddLink' || $op == 'Add') {
                $menu[] = _WLADDLINK;
            } else {
                $menu[] = '<a rel="nofollow" href="modules.php?name=' . $module_name . '&amp;op=AddLink&amp;cid=' . $cid . '" title="' . _ADDNEWLINK . '">' . _WLADDLINK . '</a>';
            } 
        } 
    } 
    return '[&nbsp;' . implode(' <small class="tiny">|</small> ', $menu) . '&nbsp;]';
} 

function modDetailsTopMenu($lid, $op = '')
{
    global $prefix, $module_name, $blockunregmodify, $usevoting, $usecomments; 
    // guggen was gerade laeuft
    if (!$op) {
        $op = (empty($_REQUEST['op'])) ? '' : $_REQUEST['op'];
    } 
    // mxDebugFuncVars($op);
    $result = sql_query("SELECT lid, cid, title, totalvotes, totalcomments FROM " . $prefix . "_links_links WHERE lid = " . intval($lid));
    list($lid, $cid, $title, $totalvotes, $totalcomments) = sql_fetch_row($result);
    if (empty($lid)) {
        return '<b>' . _WLFNOTFOUND . '</b>';
    } 

    if ($op === 'visit') {
        $link[] = _LINKNOW;
    } else {
        $link[] = '<a href="modules.php?name=' . $module_name . '&amp;op=visit&amp;lid=' . $lid . '" target="_blank" title="' . _LINKNOW . '">' . _LINKNOW . '</a>';
    } 
    if ($op === 'view') {
        $link[] = _DETAILS;
    } else {
        $link[] = '<a href="modules.php?name=' . $module_name . '&amp;op=view&amp;lid=' . $lid . '" title="' . _LINKPROFILE . '">' . _DETAILS . '</a>';
    } 

    if ($usevoting) {
        if ($op === 'rating' || $op === 'addrating') {
            $link[] = _LINKVOTE;
        } else {
            $link[] = '<a rel="nofollow" href="modules.php?name=' . $module_name . '&amp;op=rating&amp;lid=' . $lid . '" title="' . _RATEIT . '">' . _LINKVOTE . '</a>';
        } 
        if ($totalvotes) {
            // TODO: diesen Link verstecken, wenn der User bereits abgestimmt hat
            if ($op === 'viewratingdetails') {
                $link[] = _RATING;
            } else {
                $link[] = '<a href="modules.php?name=' . $module_name . '&amp;op=viewratingdetails&amp;lid=' . $lid . '" title="' . _LINKRATING . '">' . _RATING . '</a>';
            } 
        } 
        if ($usecomments) {
            if ($totalcomments) {
                if ($op === 'comments') {
                    $link[] = _SCOMMENTS;
                } else {
                    $link[] = '<a href="modules.php?name=' . $module_name . '&amp;op=comments&amp;lid=' . $lid . '" title="' . _LINKCOMMENTS . '">' . _SCOMMENTS . ' <span class="tiny">(' . $totalcomments . ')</span></a>';
                } 
            } 
        } 
    } 

    $links = '[&nbsp;' . implode(' <small class="tiny">|</small> ', $link) . '&nbsp;]';

    return $links;
} 

function modDetailsFootMenu($lid)
{
    global $prefix, $module_name, $blockunregmodify;
    $result = sql_query("SELECT lid, cid, title, totalvotes, totalcomments FROM " . $prefix . "_links_links WHERE lid = " . intval($lid));
    list($lid, $cid, $title, $totalvotes, $totalcomments) = sql_fetch_row($result);
    if (empty($lid)) {
        return ''; 
        // return '<b>' . _WLFNOTFOUND . '</b>';
    } 
    if (mxGetAdminPref('radminlink')) {
        $link[] = '<a href="admin.php?op=LinksModData&amp;lid=' . $lid . '">' . _WLMODIFY . '&nbsp;(admin)</a>';
    } else {
        if (!$blockunregmodify || MX_IS_USER) {
            $link[] = '<a rel="nofollow" href="modules.php?name=' . $module_name . '&amp;op=modifyrequest&amp;lid=' . $lid . '" title="' . _WLMODIFY . '">' . _REQUESTLINKMOD . '</a>';
        } 
        $link[] = '<a rel="nofollow" href="modules.php?name=' . $module_name . '&amp;op=reportbroken&amp;lid=' . $lid . '" title="' . _REPORTBROKEN . '">' . _REPORTBROKEN . '</a>';
    } 

    if (isset($link)) {
        $links = '[&nbsp;' . implode(' <small class="tiny">|</small> ', $link) . '&nbsp;]';
        return $links;
    } 
} 

/**
 * einheitliche Liste fuer alle Linkseiten...
 */
function modSortMenu($orderby = '', $link = '')
{
    global $module_name, $usevoting, $bgcolor1, $bgcolor2, $bgcolor3; 
    // Sortierung der Ergebnisse, nur wenn $orderby uebergeben
    $sorts = '';
    if ($orderby) {
        $imgs['up_d'] = mxCreateImage('modules/' . $module_name . '/images/up.gif', '', 0, ' style="vertical-align: middle;"');
        $imgs['up_a'] = mxCreateImage('modules/' . $module_name . '/images/up_a.gif', '', 0, ' style="vertical-align: middle;"');
        $imgs['down_d'] = mxCreateImage('modules/' . $module_name . '/images/down.gif', '', 0, ' style="vertical-align: middle;"');
        $imgs['down_a'] = mxCreateImage('modules/' . $module_name . '/images/down_a.gif', '', 0, ' style="vertical-align: middle;"');
        if ($link) {
            $link = sprintf($link, ((isset($_GET['min']) && intval($_GET['min']) > 0) ? $_GET['min'] : 0));
        } else {
            $link = 'modules.php?name=' . $module_name;
        } 
        if ($usevoting) {
            $sorts = array('date' => _DATE, 'rating' => _RATING, 'hits' => _WLPOPULARITY, 'title' => _WLTITLE);
        } else {
            $sorts = array('title' => _WLTITLE, 'date' => _DATE, 'hits' => _WLPOPULARITY);
        } 
        foreach($sorts as $sort => $bezeichnung) {
            if ($orderby == $sort . 'A') {
                // die aktuelle Sortierung ist aktuell aufsteigend
                $titles[$sort] = '<a rel="nofollow" href="' . $link . '&amp;orderby=' . $sort . 'D" title="' . modConvertOrderTranslated($sort . 'D') . '">' . $imgs['down_d'] . '</a>'; // Standard, Text Aufsteigend
                $titles[$sort] .= '&nbsp;&nbsp;<a rel="nofollow" href="' . $link . '&amp;orderby=' . $sort . 'D" title="' . modConvertOrderTranslated($sort . 'D') . '"><b>' . $bezeichnung . '</b></a>&nbsp;'; // text Aufsteigend
                $titles[$sort] .= '<a rel="nofollow" href="' . $link . '&amp;orderby=' . $sort . 'A" title="' . modConvertOrderTranslated($sort . 'A') . '">' . $imgs['up_a'] . '</a>'; // hervorgehoben, text Absteigend
            } else if ($orderby == $sort . 'D') {
                // die aktuelle Sortierung ist aktuell absteigend
                $titles[$sort] = '<a rel="nofollow" href="' . $link . '&amp;orderby=' . $sort . 'D" title="' . modConvertOrderTranslated($sort . 'D') . '">' . $imgs['down_a'] . '</a>';
                $titles[$sort] .= '&nbsp;<a rel="nofollow" href="' . $link . '&amp;orderby=' . $sort . 'A" title="' . modConvertOrderTranslated($sort . 'A') . '"><b>' . $bezeichnung . '</b></a>&nbsp;';
                $titles[$sort] .= '<a rel="nofollow" href="' . $link . '&amp;orderby=' . $sort . 'A" title="' . modConvertOrderTranslated($sort . 'A') . '">' . $imgs['up_d'] . '</a>';
            } else {
                $titles[$sort] = '<a rel="nofollow" href="' . $link . '&amp;orderby=' . $sort . 'D" title="' . modConvertOrderTranslated($sort . 'D') . '">' . $imgs['down_d'] . '</a>';
                $titles[$sort] .= '&nbsp;<a rel="nofollow" href="' . $link . '&amp;orderby=' . $sort . 'D" title="' . modConvertOrderTranslated($sort . 'D') . '">' . $bezeichnung . '</a>&nbsp;';
                $titles[$sort] .= '<a rel="nofollow" href="' . $link . '&amp;orderby=' . $sort . 'A" title="' . modConvertOrderTranslated($sort . 'A') . '">' . $imgs['up_d'] . '</a>';
            } 
        } 
        $sorts = implode(' <small class="tiny">|</small> ', $titles); 
        // das ist die gleiche Tabelle wie in modViewData() !!!
        ?>
<table width="100%" cellspacing="0" cellpadding="5" style="border: 1px solid <?php echo $bgcolor2 ?>;"><tr>
    <td align="right" style="background-color:<?php echo $bgcolor3 ?>;">
        <em><?php echo _SORTLINKSBY ?>:</em>&nbsp;&nbsp;<?php echo $sorts ?>
    </td>
</tr></table>
        <br>
        <?php
    } 
} 

/**
 * Start New & Top Links
 */
function modSpecialTopLists($cid = 0)
{
    global $prefix, $module_name, $perpage;
    $cidwhere = ($cid) ? ' cid = ' . intval($cid) . ' ' : ' cid > 0 ';
    $viewlimit = (empty($cid)) ? 10 : $perpage; 
    // New Links
    $news = '';
    $i = 0; 
    // einen Datensatz mehr abfragen ;)
    $result = sql_query("select lid, title, date as updated from " . $prefix . "_links_links WHERE " . $cidwhere . " ORDER BY date DESC limit 0,11");
    $totalrows = sql_num_rows($result); 
    // nur was anzeigen, wenn mehr als 10 oder {perpage} Datensaetze vorhanden
    if ($totalrows <= $viewlimit) {
        return;
    } while (list($lid, $title, $date) = sql_fetch_row($result)) {
        $i++;
        if ($i == $viewlimit + 1) {
            break;
        } 
        $shortdate = mx_strftime(_SHORTDATESTRING, mxSqlDate2UnixTime($date));
        $title2 = str_replace("_", " ", $title);
        $news .= "<tr><td align=\"right\" valign=\"top\" nowrap>" . $shortdate . "&nbsp;</td><td><a href=\"modules.php?name=" . $module_name . "&amp;op=view&amp;lid=" . $lid . "\">" . $title2 . "</a></td></tr>";
    } 
    // nur was anzeigen, wenn mehr als 10 Datensaetze vorhanden
    if ($i <= $viewlimit) {
        return;
    } 
    // Top Links
    $tops = '';
    $result = sql_query("select lid, title, hits from " . $prefix . "_links_links where hits > 1 AND " . $cidwhere . " ORDER BY hits DESC limit 0,10");
    while (list($lid, $title, $hits) = sql_fetch_row($result)) {
        $title2 = str_replace("_", " ", $title);
        $tops .= "<tr><td align=\"right\" valign=\"top\" nowrap>" . $hits . " x&nbsp;</td><td><a href=\"modules.php?name=" . $module_name . "&amp;op=view&amp;lid=" . $lid . "\">" . $title2 . "</a></td></tr>\n";
    } 

    OpenTable();
    echo '
    <table width="100%" border="0" cellspacing="0" cellpadding="3" align="center">
    <tr>
    <th width="49%" align="left" nowrap class="title"><b>' . _NEWLINKS . '</b></th>
    <th width="2%">&nbsp;</th>
    <th width="49%" align="left" nowrap class="title"><b>' . _MOSTPOPULAR . ' ' . _MODITEMS . '</b></th>
    </tr>
    <tr valign="top">
    <td><table border="0" cellspacing="0" cellpadding="2">' . $news . '</table></td>
    <td>&nbsp;</td>
    <td><table border="0" cellspacing="0" cellpadding="2">' . $tops . '</table></td>
    </tr></table>
    ';
    CloseTable();
    echo "<br>";
} 
/**
 * Linkstatistik
 */
function modShowStats($cid = 0)
{
    global $prefix, $module_name;
    $cidwhere = ($cid) ? ' cid = ' . intval($cid) . ' ' : ' cid > 0 ';
    $result = sql_query("select count(lid) from " . $prefix . "_links_links WHERE " . $cidwhere);
    list($numrows) = sql_fetch_row($result);
    if ($numrows) {
        $result = sql_query("select count(cid) from " . $prefix . "_links_categories WHERE " . $cidwhere);
        list($catnum) = sql_fetch_row($result);
        OpenTable();
        echo "<center><span class=\"content\">" . _WLTHEREARE . " <b>" . $numrows . "</b> " . _MODITEMS . " " . _AND . " <b>" . $catnum . "</b> " . _WLCATEGORIES . " " . _WLATTACHEDTOCAT . "</span></center>";
        CloseTable();
    } 
} 

/**
 * Page Numbering
 */
function modShowPageView($totalselectedrows, $min, $show, $link)
{
    $pages = ceil($totalselectedrows / $show); 
    // wenn weniger als 2 Seiten, nix anzeigen
    if ($pages <= 1) {
        return;
    } 

    $max = intval($min + $show);
    $prev = intval($min - $show);
    $currentpage = ceil($max / $show);
    $start = '';
    $ende = '';
    $counter = 1;
    if ($currentpage > 3 && $pages > 6) {
        $start = '<a href="' . sprintf($link, 0) . '" title="' . _GOTOPAGEFIRST . '">1&nbsp;<span style="font-size: 120%;">&laquo;</span></a>&nbsp;..&nbsp;';
        if ($currentpage >= $pages - 3) {
            $counter = $currentpage - ($currentpage - $pages + 4);
        } else {
            $counter = $currentpage - 1;
        } 
    } while ($counter <= $pages) {
        $mintemp = ($show * $counter) - $show;
        if (($counter > 5) && ($counter > $currentpage + 2) && ($counter < $pages) && $pages > 6) {
            $ende = '&nbsp;..&nbsp;<a href="' . sprintf($link, ($pages-1) * $show) . '" title="' . _GOTOPAGELAST . '"><span style="font-size: 120%;">&raquo;</span>&nbsp;' . $pages . ' </a>';
            break;
        } else if ($counter == $currentpage) {
            $part[] = '<a href="' . sprintf($link, $mintemp) . '" title="' . _PAGE . '&nbsp;' . $currentpage . ' ' . _OF . ' ' . $pages . '"><b>' . $counter . '</b></a>';
        } else {
            $part[] = '<a href="' . sprintf($link, $mintemp) . '" title="' . _GOTOPAGE . ' ' . $counter . '">' . $counter . '</a>';
        } 
        $counter++;
    } 
    if (isset($part)) {
        return '
        <span class="tiny">' . _PAGE . '&nbsp;' . $currentpage . '&nbsp;' . _OF . '&nbsp;' . $pages . '</span>&nbsp;&nbsp;
        ' . $start . implode(' <small class="tiny">|</small> ', $part) . $ende . '
        ';
    } 
} 

function modCategoriesQuickJump($cid = 0)
{
    global $module_name, $showemptycategories;
    $orderby = (empty($_REQUEST['orderby'])) ? DLDEFAULTORDER : $_REQUEST['orderby']; 
    // die aktuelle Kategorie-id ermitteln
    $cid = (empty($cid) || $cid < 0) ? 0 : intval($cid);
    return '<form action="modules.php" method="get" name="jump">
    <input type="hidden" name="name" value="' . $module_name . '">
    <input type="hidden" name="min" value="0">
    <input type="hidden" name="orderby" value="' . $orderby . '">
    <select name="cid" onChange="location.href=\'modules.php?name=' . $module_name . '&amp;min=0&amp;orderby=' . $orderby . '&amp;cid=\' + document.jump.cid.options[document.jump.cid.options.selectedIndex].value">' . modGetCategoriesSelect($cid, 'showmain', (($showemptycategories) ? '' : 'hideemptycats')) . '</select>
    <input type="submit" name="jumpswitch" id="jumpswitch" value="' . _SWITCHIT . '" style="visibility: visible;">
    <script type="text/javascript">
        <!--
        document.getElementById("jumpswitch").style.display = \'none\';
        //-->
    </script>
    </form>';
} 

function modViewCategories($cid = 0)
{
    global $prefix, $module_name, $showcounters, $showemptycategories, $catcols, $catsort, $bgcolor1, $bgcolor2, $bgcolor3;

    $cid = intval($cid);
    $count = 0;
    $catimage = mxCreateImage('modules/' . $module_name . '/images/folder.gif', '');

    $mainout = array();
    $allarray = modGetCountArray();
    if (isset($allarray[$cid]['subcat'])) {
        // das Theme includen, um an die Farben ranzukommen...
        includetheme();
        $maincat = $allarray[$cid]['subcat'];
        foreach ($maincat as $mainarry) {
            $out = "";
            $maindls = modCountAll($mainarry['cid']);
            if (!$showemptycategories && empty($maindls) && empty($mainarry['anzd'])) {
                continue;
            } 
            $subout = array();
            if (isset($allarray[$mainarry['cid']]['subcat'])) {
                $subcat = $allarray[$mainarry['cid']]['subcat'];
                foreach ($subcat as $subarry) {
                    $subdls = modCountAll($subarry['cid']);
                    if ($subdls) {
                        if ($showcounters) {
                            $viewsubdls = '<td>(' . $subdls . ')</td>';
                        } else {
                            $viewsubdls = '';
                        } 
                        $subout[$subarry['title']] = '<tr valign="top" style="background-color: ' . $bgcolor1 . ';">
                            <td>&nbsp;</td><td width="2%" align="center">' . $catimage . '</td>
                            <td><span class="content">' . modNewMakeGrafic($subarry['newest'], 'align="right"') . '<a href="modules.php?name=' . $module_name . '&amp;cid=' . $subarry['cid'] . '">' . $subarry['title'] . '</a></span></td>
                            ' . $viewsubdls . '
                            </tr>';
                    } 
                } 
            } 
            if ($showcounters) {
                $viewanz = '<td width="20%" class="tiny">(' . $mainarry['anzd'] . '&nbsp;/&nbsp;' . $maindls . ')</td>';
            } else {
                $viewanz = '';
            } 

            $desc = '';
            if ($mainarry['cdescription']) {
                $desc = '<div align="left">' . $mainarry['cdescription'] . '</div>';
            } 
            $out = '<tr valign="top" style="background-color: ' . $bgcolor1 . ';">
            <td width="2%" align="center">' . $catimage . '</td>
            <td width="75%" colspan="2"><div class="content">' . modNewMakeGrafic($mainarry['newest'], 'align="right"') . '<a href="modules.php?name=' . $module_name . '&amp;cid=' . $mainarry['cid'] . '"><b>' . $mainarry['title'] . '</b></a></div>' . $desc . '</td>
            ' . $viewanz . '
            </tr>';
            $sublen = 0;
            if (count($subout)) {
                $subout = array_change_key_case($subout, CASE_UPPER);
                ksort($subout, SORT_STRING);
                $subout = implode("\n", $subout);
                $sublen = strlen(strip_tags($subout));
                $out .= $subout;
            } 

            if ($catcols > 1) {
                $out = '<table border="0" width="100%" cellpadding="1" cellspacing="0">' . $out . '</table>';
            } 
            $count++;
            if ($catsort) {
                // die laenge des Ausgabestrings als Index fuer das array verwenden
                $mainout[(strlen(strip_tags($out)) + ($count / 100)) * 100] = $out;
            } else {
                // oder dann einfach alphabetisch sortieren
                $mainout[$mainarry['title'] . '_' . strval($count)] = $out;
            } 
        } 
    } 
    if (empty($mainout)) {
        return '';
    } 

    if ($catsort) {
        krsort($mainout, SORT_NUMERIC);
    } else {
        ksort($mainout);
    } 

    if ($catcols > 1) {
        $width = ceil(100 / $catcols);
        $mainout = array_chunk($mainout, $catcols);
        foreach ($mainout as $c => $line) {
            if ($c && ($catcols > 1) && (count($line) < $catcols)) {
                $diff = $catcols - count($line); 
                // Leerzellen fuellen
                for ($i = 0; $i < $diff; $i++) {
                    $line[] = '&nbsp;';
                } 
            } 
            $lines[] = '<tr style="background-color: ' . $bgcolor1 . ';" valign="top"><td width="' . $width . '%">' . implode('</td><td width="' . $width . '%">', $line) . '</td></tr>';
            $padding = 5;
        } 
    } else {
        $padding = 2;
        $lines[] = implode("\n", $mainout);
    } 

    $allout = '<table border="0" align="center" style="background-color: ' . $bgcolor2 . ';" cellpadding="' . $padding . '" cellspacing="1">' . implode("\n", $lines) . '</table>';
    return $allout;
} 

/**
 * einheitlicher Check fuer alle Links...
 */
function modCheckData($pvs)
{
    global $prefix; 
    // die Rueckmeldungen initialisieren
    $pvs['msg'] = array(); 
    // ID initialisieren, falls neuer Datensatz
    $pvs['lid'] = (empty($pvs['lid'])) ? 0 : intval($pvs['lid']);

    if (isset($pvs['downdescription_' . $pvs['lid']])) {
        // die Beschreibung aus Textfeldname und lid zusammensetzen
        $pvs['description'] = trim($pvs['downdescription_' . $pvs['lid']]); 
        // Zeilenumbrueche vor und hinter der Beschreibung entfernen
        $pvs['description'] = preg_replace('#<br\s*/?>+$#si', '', $pvs['description']);
        $pvs['description'] = preg_replace('#^<br\s*/?>+#si', '', $pvs['description']);
        $pvs['downdescription_' . $pvs['lid']] = $pvs['description'];
    } else {
        $pvs['description'] = (empty($pvs['description'])) ? '' : $pvs['description'];
    } 
    // captcha pruefen, nicht in admin.php
    if (isset($GLOBALS['weblinkson']) && $GLOBALS['weblinkson']) {
        if (empty($pvs['captcha'])) {
            $pvs['msg'][] = _CAPTCHAWRONG;
        } else {
            require_once("includes/captcha/__captcha/PhraseFactory.php");
            $storedCaptcha = PhraseFactory::get('', $GLOBALS['passphraselenght'], $pvs['captcha'], $GLOBALS['storagetype']);
            if ($pvs['captcha'] !== $storedCaptcha) {
                $pvs['msg'][] = _CAPTCHAWRONG;
            } 
        } 
    } 
    // Check if URL is empty
    if (empty($pvs['url'])) {
        $pvs['msg'][] = _LINKNOURL;
    } else {
        $pvs['url'] = substr(strip_tags($pvs['url']), 0, 255);
        if (strlen($pvs['url']) < 10) {
            $pvs['msg'][] = _LINKNOURL;
        } else {
            // / check if URL already exist (in Schleife wegen sql_injection)
            if ($pvs['op'] == 'LinksAddData' || $pvs['op'] == 'Add') {
                $result = sql_query("select url from " . $prefix . "_links_links");
                while (list($url) = sql_fetch_row($result)) {
                    if ($url == $pvs['url']) {
                        $pvs['msg'][] = _LINKALREADYEXT . '<br><i>' . $pvs['url'] . '</i>';
                        $dblfound = true;
                        break;
                    } 
                } 
            } 
            if (!isset($dblfound) && $pvs['op'] == 'Add') {
                $result = sql_query("select url from " . $prefix . "_links_newlink");
                while (list($url) = sql_fetch_row($result)) {
                    if ($url == $pvs['url']) {
                        $pvs['msg'][] = _LINKALREADYEXT . '<br><i>' . $pvs['url'] . '</i>';
                        break;
                    } 
                } 
            } 
        } 
    } 
    // Check if Title exist
    if (empty($pvs['title'])) {
        $pvs['msg'][] = _LINKNOTITLE;
    } else {
        $pvs['title'] = substr(strip_tags($pvs['title']), 0, 100);
        if (empty($pvs['title'])) {
            $pvs['msg'][] = _LINKNOTITLE;
        } 
    } 
    // Check if Description exist
    if (empty($pvs['description'])) {
        $pvs['msg'][] = _LINKNODESC;
    } 
    // feed submitter var
    // $pvs['submitter'] = (isset($udata['uname'])) ? $udata['uname'] : $GLOBALS['anonymous'] ;
    // das Aktualisierungsdateum
    $newdate = $pvs['orgtimestamp'];
    if (isset($pvs['upday'], $pvs['upmonth'], $pvs['upyear'])) {
        if (checkdate($pvs['upmonth'], $pvs['upday'], $pvs['upyear'])) {
            // mktime ( [int Stunde [, int Minute [, int Sekunde [, int Monat [, int Tag [, int Jahr [, int is_dst]]]]]]] )
            $newdate = mktime(date('H'), date('i'), date('s'), $pvs['upmonth'], $pvs['upday'], $pvs['upyear']);
            if ($newdate > time()) {
                $pvs['msg'][] = _ERRFALSEUPDATED;
                $newdate = $pvs['orgtimestamp'];
            } 
        } else {
            $pvs['msg'][] = _ERRFALSEUPDATED;
        } 
    } 
    if ($newdate > time()) {
        $newdate = time();
    } 
    $pvs['updated'] = sprintf("%04d-%02d-%02d %02d.%02d.00", date('Y', $newdate), date('m', $newdate), date('j', $newdate), date('H', $newdate), date('i', $newdate)); 
    // ENDE das Aktualisierungsdateum
    // mxDebugFuncVars($pvs);exit;
    return $pvs;
} 

function modFetchForm($lid, $title, $url, $target = '_self')
{
    global $module_name;
    include('includes/captcha/captcha_java.php');
    $pass = md5(crypt(uniqid(rand())));
    echo '<p>' . _WLFDIRECTION1 . '&quot;' . $title . '&quot;' . _WLFDIRECTION2 . '</p>
    <form action="modules.php?name=' . $module_name . '&amp;op=visit&amp;lid=' . $lid . '" method="post" name="modFetchForm" id="modFetchForm" target="' . $target . '">
    <input type="hidden" name="name" value="' . $module_name . '">
    <input type="hidden" name="op" value="visit">
    <input type="hidden" name="noJpC" value="">
    <input type="hidden" name="lid" value="' . $lid . '">
    <input type="hidden" name="pass" value="' . $pass . '">
    <div align="center">
    <p><img id="captchaimage" src="includes/captcha/captchaimg.php?' . $pass . '" alt="' . _CAPTCHAINSERT . '"></p>
    <p><input type="text" name="captcha" id="captcha" size="20" maxlength="20"></p>
    <p>
    <input type="submit" value="' . _LINKNOW . '">&nbsp;&nbsp;<input type="button" value="' . _CAPTCHARELOAD . '" onclick="do_reload(); document.modFetchForm.captcha.focus(); return false;">
    </p>
    </div>
    </form>
    <script language="JavaScript" type="text/javascript">
        <!--
        document.modFetchForm.captcha.focus();
        //-->
    </script>';
} 

function modGetCountArray($cat = null)
{
    global $prefix, $module_name;
    static $arr;
    if (!isset($arr)) {
        $arr = array();
        $qry = "
            SELECT dc.parentid, dc.cid, dc.title, dc.cdescription, Count( dd.lid )  AS anzd, Max( dd.date )  AS newest
            FROM ${prefix}_links_categories AS dc
            LEFT  JOIN ${prefix}_links_links AS dd ON dc.cid = dd.cid
            GROUP  BY dc.parentid, dc.cid, dc.title, dc.cdescription
            ";
        $result = sql_query($qry);
        while ($row = sql_fetch_assoc($result)) {
            if (empty($row['parentid'])) {
                $arr[$row['parentid']]['anzd'] = 0;
                $arr[$row['parentid']]['title'] = ''; #_LINKSMAINCAT;
                $arr[$row['parentid']]['cdescription'] = '';
                $arr[$row['parentid']]['parentid'] = 0;
            } 
            $arr[$row['parentid']]['subcat'][$row['cid']] = $row;
            $arr[$row['cid']]['anzd'] = $row['anzd'];
            $arr[$row['cid']]['title'] = $row['title'];
            $arr[$row['cid']]['cdescription'] = $row['cdescription'];
            $arr[$row['cid']]['parentid'] = $row['parentid'];
        } 
    } 
    if ($cat === null) {
        return $arr;
    } else {
        return $arr[intval($cat)];
    } 
} 

/**
 * this function will count all links of a categorie and up to ALL more subcategories
 */
function modCountAll($cid) // [$cid]
{
    $arr = modGetCountArray();
    if (!isset($arr[$cid])) {
        return 0;
    } 
    $out['countdl'] = (isset($arr[$cid]['anzd'])) ? $arr[$cid]['anzd'] : 0;
    if (isset($arr[$cid]['subcat'])) {
        foreach($arr[$cid]['subcat'] as $key => $scid) {
            $out['countdl'] += modCountAll($scid['cid']);
        } 
    } 
    return $out['countdl'];
} 

function modGetParentTitles($parentid, $title)
{
    global $prefix, $module_name;
    static $arr;

    if (!isset($arr[$parentid])) {
        $allarray = modGetCountArray();
        $arr[$parentid]['cid'] = $parentid;
        $arr[$parentid]['ptitle'] = $allarray[$parentid]['title'];
        $arr[$parentid]['pparentid'] = $allarray[$parentid]['parentid'];
    } 

    if (!empty($arr[$parentid]['ptitle'])) {
        $title = $arr[$parentid]['ptitle'] . " &raquo; " . $title;
    } 
    if (!empty($arr[$parentid]['pparentid'])) {
        $title = modGetParentTitles($arr[$parentid]['pparentid'], $title);
    } 
    return $title;
} 

function modGetParentTitlesAsLink($parentid, $title, $curcid)
{
    global $prefix, $module_name;
    static $arr;
    if (!isset($arr[$parentid])) {
        $allarray = modGetCountArray();
        $arr[$parentid]['cid'] = $parentid;
        $arr[$parentid]['ptitle'] = $allarray[$parentid]['title'];
        $arr[$parentid]['pparentid'] = $allarray[$parentid]['parentid'];
    } 
    if (!empty($arr[$parentid]['ptitle'])) {
        $des = ($arr[$parentid]['pparentid']) ? _SUBCATEGORY : _WLCATEGORY;
        $title = '<a href="modules.php?name=' . $module_name . '&amp;cid=' . $arr[$parentid]['cid'] . '" title="' . $des . ': ' . strip_tags($arr[$parentid]['ptitle']) . '">' . $arr[$parentid]['ptitle'] . '</a> &raquo; <a href="modules.php?name=' . $module_name . '&amp;cid=' . $curcid . '" title="' . _SUBCATEGORY . ': ' . strip_tags($title) . '">' . $title . '</a>';
    } 
    if (!empty($arr[$parentid]['pparentid'])) {
        $title = modGetParentTitlesAsLink($arr[$parentid]['pparentid'], $title, $arr[$parentid]['cid']);
    } 
    if (!$parentid && $curcid) {
        $title = '<a href="modules.php?name=' . $module_name . '&amp;cid=' . $curcid . '" title="' . _WLCATEGORY . ': ' . strip_tags($title) . '">' . $title . '</a>';
    } 
    return $title;
} 

function modGetCategoriesSelect($cid = array(), $showmain = '', $hideemptycats = '')
{
    global $prefix;
    static $out, $lastcid, $lastshowmain, $lasthideemptycats;

    if ($lastcid == $cid && $lastshowmain == $showmain && $lasthideemptycats == $hideemptycats && isset($out)) {
        return $out;
    } else {
        $lastcid = $cid;
        if (is_array($cid)) {
            $array_cid = $cid;
        } else {
            $array_cid = array($cid);
        } 
        $lastshowmain = $showmain;
        $lasthideemptycats = $hideemptycats;
        $result2 = sql_query("select cid, title, parentid from " . $prefix . "_links_categories");
        while (list($cid2, $ctitle2, $parentid2) = sql_fetch_row($result2)) {
            // wenn leere Kategorien nicht angezeigt werden sollen
            if ($hideemptycats && !modCountAll($cid2)) {
                continue;
            } 
            if (!empty($parentid2)) $ctitle2 = modGetParentTitles($parentid2, $ctitle2);
            $options[strtolower($ctitle2)] = '<option value="' . $cid2 . '"' . ((in_array($cid2, $array_cid)) ? ' selected="selected"' : '') . '>' . $ctitle2 . '</option>';
        } 
        if (isset($options)) {
            ksort($options);
        } else {
            $options[] = '<option value="0">' . _NOCATAVAILABLE . '</option>';
        } 
        $out = implode("\n", $options);
        if ($showmain) {
            $out = '<option value="0"' . ((in_array(0, $array_cid)) ? ' selected="selected"' : '') . '>&raquo; ' . _LINKSMAIN . '</option>' . $out;
        } 
        return $out;
    } 
} 

function modRateMakeStar($score, $votes)
{
    global $module_name, $usevoting;
    if (!$usevoting) {
        return '';
    } 
    if (!$score || !$votes || $votes < $GLOBALS['linkvotemin']) {
        return '';
    } 
    static $rateImgFull, $rateImgHalf;
    if (!isset($rateImgFull)) {
        $rateImgFull = mxCreateImage('modules/' . $module_name . '/images/ratingstar.gif', '');
    } 
    $title = _RATING . ': ' . $score . ' (' . $votes . ' ' . _LVOTES . ')';
    $score /= 2;
    $stars = str_repeat($rateImgFull, ceil($score));
    return '<span style="white-space: nowrap" title="' . $title . '">' . $stars . '</span>';
} 

function modNewMakeGrafic($time, $format = '')
{
    global $module_name;
    static $images;
    $time = time() - mxSqlDate2UnixTime($time);

    if (empty($format)) {
        $format = 'style="vertical-align: middle;"';
    } 

    switch (true) {
        // 24 hours
        case ($time < 86400):
            if (!isset($images[1])) {
                $images[1] = mxCreateImage('modules/' . $module_name . '/images/new_1.gif', _NEWTODAY, 0, '%s');
            } 
            return sprintf($images[1], $format); 
            // 3 days
        case ($time < 259200):
            if (!isset($images[3])) {
                $images[3] = mxCreateImage('modules/' . $module_name . '/images/new_3.gif', _NEWLAST3DAYS, 0, '%s');
            } 
            return sprintf($images[3], $format); 
            // 7 days
        case ($time < 604800):
            if (!isset($images[7])) {
                $images[7] = mxCreateImage('modules/' . $module_name . '/images/new_7.gif', _NEWTHISWEEK, 0, '%s');
            } 
            return sprintf($images[7], $format);
    } 
} 

function modFormatFilesize($size)
{
    $mb = 1024 * 1024;
    if ($size > $mb) {
        return sprintf ("%01.2f", $size / $mb) . " MB";
    } elseif ($size >= 1024) {
        return sprintf ("%01.2f", $size / 1024) . " Kb";
    } else {
        return $size . " bytes";
    } 
} 

function modCheckAndCleanSubdata($lid)
{
    global $prefix;
    $qry = "SELECT lid FROM `{$prefix}_links_links` WHERE lid=" . intval($lid) . " LIMIT 1";
    $result = sql_query($qry);
    if (sql_num_rows($result)) {
        return true;
    } 
    sql_query("DELETE FROM `{$prefix}_links_votedata`   WHERE ratinglid=" . intval($lid));
    sql_query("DELETE FROM `{$prefix}_links_modrequest` WHERE lid=" . intval($lid));
    sql_query("DELETE FROM `{$prefix}_links_editorials` WHERE linkid=" . intval($lid));
    return false;
} 

function modHighlightString($source, $high)
{
    $source = preg_replace_callback('#<[^>]*>#', 'modHighlightString_hidetags', $source);
    $source = str_replace($high, "<b><span class=\"highlight\">$high</span></b>", $source);
    $source = preg_replace_callback('#{~{~([0-9]+)~}~}#', 'modHighlightString_hidetags', $source);
    return $source;
} 

function modHighlightString_hidetags($source)
{
    static $strings;
    if (isset($source[1], $strings[$source[1]])) {
        return $strings[$source[1]];
    } 
    $i = count($strings)-1;
    $strings[] = $source[0];
    return '{~{~' . ($i + 1) . '~}~}';
} 

function modConvertOrderForSql($orderby)
{
    global $usevoting;
    if ($orderby == "hitsA") return "hits ASC";
    if ($orderby == "hitsD") return "hits DESC";
    if ($orderby == "titleA") return "title ASC";
    if ($orderby == "titleD") return "title DESC";
    if ($orderby == "dateA") return "date ASC";
    if ($orderby == "dateD") return "date DESC";
    if ($usevoting) {
        if ($orderby == "ratingA") return "linkratingsummary ASC";
        if ($orderby == "ratingD") return "linkratingsummary DESC";
    } 
    return modConvertOrderForSql(DLDEFAULTORDER);
} 

function modConvertOrderTranslated($orderby)
{
    global $usevoting;
    if ($orderby == "hitsA") return _WLPOPULARITY1;
    if ($orderby == "hitsD") return _WLPOPULARITY2;
    if ($orderby == "titleA") return _WLTITLEAZ;
    if ($orderby == "titleD") return _WLTITLEZA;
    if ($orderby == "dateA") return _DDATE1;
    if ($orderby == "dateD") return _DDATE2;
    if ($usevoting) {
        if ($orderby == "ratingA") return _RATING1;
        if ($orderby == "ratingD") return _RATING2;
    } 
    return modConvertOrderTranslated(DLDEFAULTORDER);
} 

function get_response_header($url, $reporting = false, $reverse = 0)
{
    $url = str_replace('&amp;', '&', $url);
    if ($reporting) {
        echo '<p><b>URL:</b> <a href="' . $url . '" target="_blank">' . $url . '</a></p>';
    } 
    static $runs = 0;
    static $lastheader = array();
    if ($reverse) {
        $runs++;
    } else {
        $runs = 0;
    } 
    // wenn mehr als 6x rekursiv aufgerufen, abbrechen um Endlosschleife zu vermeiden
    if ($runs > 6) {
        if ($reporting) {
            echo '<p><b>Error</b>: more than ' . ($runs-1) . ' redirects</p>';
        } 
        return $lastheader;
    } 
    // return initialisieren
    $header['status'] = false;
    $header['type'] = false; 
    // die url aufsplitten
    $url_parsed = parse_url($url); 
    // Falls direkter Link auf eigene Homepage
    if (empty($url_parsed["scheme"]) || empty($url_parsed["host"])) {
        $ttemmp = parse_url(MX_HOME_URL);
        $url_parsed["scheme"] = $ttemmp["scheme"];
        $url_parsed["host"] = $ttemmp["host"];
        $url = MX_BASE_URL . ltrim($url, ' /:;.');
        if (empty($url_parsed["scheme"])) {
            $url_parsed["scheme"] = $ttemmp["scheme"];
        } 
        if (empty($url_parsed["host"])) {
            $url_parsed["scheme"] = $ttemmp["scheme"];
        } 
    } 
    $scheme = $url_parsed["scheme"];
    $host = $url_parsed["host"]; 
    // immer die aktuelle URL zwischenspeichern, falls die beim rekursiven Aufruf geaendert wird
    $header['url'] = $url;

    if (empty($url_parsed["port"])) {
        $port = 80;
    } else {
        $port = $url_parsed["port"];
    } 

    if (empty($url_parsed["path"])) {
        $path = "/";
        $url .= "/";
    } else {
        $path = $url_parsed["path"];
        if ($reporting && preg_match('#\s#', $path)) {
            echo '<p><b>Error</b>: unescaped spaces in path (' . $path . ')</p>';
        } 
    } 

    if (!empty($url_parsed["query"])) {
        $path .= "?" . $url_parsed["query"];
    } 
    // Kompatibilitaet mit macintosh, etc...
    @ini_set('auto_detect_line_endings', 'On'); 
    // $php_errormsg fuellen...
    @ini_set('track_errors', 'On');
    $fp = @fsockopen($host, $port, $errno, $errstr, 15);
    if (!$fp) {
        $header['status'] = 0;
        $header['errno'] = $errno;
        if (!empty($php_errormsg)) {
            $header['errstr'] = $php_errormsg;
        } else if (!empty($errstr)) {
            $header['errstr'] = $errstr;
        } else {
            $header['errstr'] = 'undefined';
        } 
        if ($reporting) {
            echo '<p>Error! ' . $header['errstr'] . '</p>';
        } 
        // mxDebugFuncVars($header, $php_errormsg);
    } else {
        // var_dump(socket_get_status($fp));
        // einen referer zusammenbasteln, damit der von der Linkseite selbst kommt
        $refer = $scheme . '://' . $host . str_replace('%2F', '/', urlencode(dirname($path))) . '/'; 
        // timeout setzen
        $initime = intval(mxIniGet('max_execution_time')) / 2; // falls unbeschraenktes Zeitlimit...
        $initime = ($initime) ? $initime : 15;
        socket_set_timeout($fp, $initime); 
        // den http-header der url abfragen, spaces muessen durch den Hex-Wert ersetzt werden!!
        // dazu: http://www.zend.com/zend/spotlight/mimocsumissions.php
        fputs($fp, "GET " . preg_replace('#\s#', '%20', $path) . " HTTP/1.1\r\nHost: " . $host . "\r\nReferer: " . $refer . "\r\nUser-Agent: pragmaMx-Linkmodule\r\n\r\n"); 
        // var_dump(socket_get_status($fp));exit;
        // while (!feof($fp)) {
        $i = 0;

        if ($reporting) {
            echo '<ul>';
        } while ($line = trim(fgetss($fp, 256))) {
            // print $line;
            // $line = trim(fgetss($fp, 256));
            // wenn mehr Eintraege vorhanden, abbrechen um Endlosschleife zu vermeiden
            if (!$line || $i > 20) {
                break;
            } else {
                if ($reporting) {
                    // $report[] =  trim(str_replace('&amp;', '&', $line));
                    echo '<li>' . trim(strip_tags($line)) . '</li>';
                } 
                if (preg_match('#^(?:Location:\s*|Refresh:.*url=)(([^:]{3,4}://).+)#i', $line, $matches)) {
                    // check auf Weiterleitung
                    $redirect = trim(str_replace('&amp;', '&', $matches[1])); 
                    // bei manchen buggy nuke-Linkscripten wird die redirect-url nicht korrekt uebergeben (doppelt etc.)
                    preg_match('#^([^:]{3,4})://[^:]{3,}(://.*$)#i', $redirect, $matches);
                    if (!empty($matches[1]) && !empty($matches[2])) {
                        if ($reporting) {
                            echo '<ul><li><b>Error</b>: bad redirect <i>' . $redirect . '</i></li></ul>';
                        } 
                        $redirect = $matches[1] . $matches[2];
                    } 
                } else if (preg_match('#^HTTP[^ ]+\s([0-9]{3})\s(.+)$#i', $line, $matches)) {
                    // den Antwortcode (http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html)
                    $header['status'] = intval($matches[1]);
                } else if (preg_match('#^Content-Type:\s([^; ]+)#i', $line, $matches)) {
                    // der Inhaltstyp (mime)
                    $header['type'] = $matches[1];
                } 
            } 
            $type = $i++;
        } 
        if ($reporting) {
            echo '</ul>';
        } 

        fclose($fp); 
        // den aktuellen Header zwischenspeichern um beim naechsten rekursiven Aufruf da zu sein...
        $lastheader = $header; 
        // falls Umleitung, rekursiv aufrufen, mit der Umleitung als URL
        if (isset($redirect)) {
            if ($reporting) {
                echo '<p><b><i>redirect to:</i></b></p>';
            } 
            return get_response_header($redirect, $reporting, 'reverse');
        } 
    } 
    return $header;
} 

function modCheckPopupLink($url)
{
    global $module_name;
    return " onClick=\"window.open('modules.php?name=" . $module_name . "&amp;op=check&amp;url=" . urlencode($url) . "', 'urldetail','left=100,top=100,width=600,height=500,toolbar=no,location=no,menubar=no,scrollbars=yes,resizable=yes,status=no'); return false;\"" ;
} 

?>