Subversion Repositories Applications.papyrus

Rev

Go to most recent revision | Blame | Last modification | View Log | RSS feed

<?php

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.    See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA    02111-1307    USA
//------------------------------------------------------------------------------

//==============================================================================
// gs_hex2bin ($data)
//    $data : hex data (string) to be converted to binary.
//
// Convert hex value into binary value.
//==============================================================================

function gs_hex2bin ($data) {
    $len = strlen ($data);

    return pack ("H$len", $data);
}

//==============================================================================
// gs_localizeTimestamp ($ts, $locale)
//    $ts         : unix time stamp
//    $locale : locale code
//
// Convert an unix time stamp in respect with locale (en, fr, sp).
//==============================================================================

function gs_localizeTimestamp ($ts, $locale) {
    $format = 'Y/m/d H:m:s';

    if ($locale == 'fr') $format = 'd/m/Y H:m:s';
    if ($locale == 'sp') $format = 'd/m/Y H:m:s';

    return date ($format, $ts);
}

//==============================================================================
// gs_localizeDate ($date, $locale)
//    $date     : date (MySQL format: YYYY-MM-DD)
//    $locale : locale code
//
// Convert a MySQL date in respect with locale (en, fr, sp).
//==============================================================================

function gs_localizeDate ($date, $locale) {
    $dateArray = explode ('-', $date);

    $y = $dateArray[0];
    $m = $dateArray[1];
    $d = $dateArray[2];

    if ($locale == 'en') return "$y/$m/$d";
    if ($locale == 'fr') return "$d/$m/$y";
    if ($locale == 'sp') return "$d/$m/$y";

    return $date;
}

//==============================================================================
// gs_localizeDateTime ($date, $locale)
//    $datetime : datetime field (MySQL format: YYYY-MM-DD HH:MM:SS)
//    $locale     : locale code
//
// Convert a MySQL date in respect with locale (en, fr, sp).
//==============================================================================

function gs_localizeDateTime ($datetime, $locale) {
    $date = substr ($datetime, 0, 10);
    $time = substr ($datetime, 11, 8);

    return gs_localizeDate ($date, $locale).' - '.$time;
}

//==============================================================================
// gs_localizeDate2MySQL ($date, $locale)
//    $date     : date (following locale)
//    $locale : locale code
//
// Convert a date to MySQL format in respect with locale (en, fr, sp).
//==============================================================================

function gs_localizeDate2MySQL ($date, $locale) {
    $dateArray = explode ('/', $date);

    if ($locale == 'en') return "$dateArray[0]-$dateArray[1]-$dateArray[2]";
    if ($locale == 'fr') return "$dateArray[2]-$dateArray[1]-$dateArray[0]";
    if ($locale == 'sp') return "$dateArray[2]-$dateArray[1]-$dateArray[0]";

    return $date;
}

//==============================================================================
// gs_getLabel ($db, $link, $ident, $locale, $appl, $entities)
//    $db             : database name
//    $link         : database link
//    $ident        : label name
//    $locale     : locale code
//    $appl         : application name
//    $entities : htmlentities transformation ?
//
// Get localized label. If the label appears into a JavaScript string, $entities
// MUST be false.
//==============================================================================

function gs_getLabel ($dbname, $link, $ident, $locale, $appl = '', $entities = true) {
    static $labelsCache = array ();

    $tag = "$ident $locale $appl";

    if (isset ($labelsCache[$tag])) {
        return ($entities ? htmlentities ($labelsCache[$tag]) : $labelsCache[$tag]);
    }

    $query =
        "select L_TRANSLATION from $dbname.LABELS".
        " where L_IDENT='$ident' and L_LOCALE='$locale' and L_APPL='$appl'";

    $result = mysql_query ($query, $link);

    if (! $result) {
        die ("Unable to perform query ($query / " . mysql_error ($link) . ")");
    }

    if (mysql_num_rows ($result) == 0) {
        mysql_free_result ($result);
        return "($ident)";
    }

    $row = mysql_fetch_object ($result);

    mysql_free_result ($result);

    $labelsCache[$tag] = $row->L_TRANSLATION;

    return ($entities ? htmlentities ($row->L_TRANSLATION) : $row->L_TRANSLATION);
}

//==============================================================================
// gs_buildControlAndPages ($db, $link, $locale, $url, $first, $max, $numItems,
//                                                    $noResponse, $oneResponse, $responses,
//                                                    $width, $style, $imgdir)
//    $db                    : database name
//    $link                : database link
//    $locale            : locale code
//    $url                 : URL to show datas, without first and max limits
//    $first             : in the result set, the index of the first item to show
//    $max                 : max count of results by page
//    $numItems        : results count
//    $noResponse    : label (if no responses)
//    $oneResponse : label (if only one response)
//    $responses     : label (if more than one response)
//    $width             : table widh (if equal to zero, 100%)
//    $style             : style used into the images control cells
//    $imgdir            : the image set used for the control buttons
//
// Generation of control buttons (first, previous, next, last) and pages numbers
// (search result, for example).
//==============================================================================

function gs_buildControlAndPages ($db, $link, $locale,
                                                                    $url,
                                                                    $first, $max, $numItems,
                                                                    $noResponse    = null,
                                                                    $oneResponse = null,
                                                                    $responses     = null,
                                                                    $width             = null,
                                                                    $style             = null,
                                                                    $imgdir            = null,
                                                                    $appl = 'gsite') {
    //----------------------------------------------------------------------------
    // Manage default values.

    if (empty ($noResponse))    $noResponse    = 'ctrl_no_response';
    if (empty ($oneResponse)) $oneResponse = 'ctrl_one_response';
    if (empty ($responses))     $responses     = 'ctrl_responses';
    if (empty ($width))             $width             = '100%';
    if (empty ($style))             $style             = 'line';
    if (empty ($imgdir))            $imgdir            = 'dft';

    //----------------------------------------------------------------------------
    // Build style.

    global $GS_GLOBAL;

    $STYLErow = $GS_GLOBAL['style_row'];

    $fontStyle =
        "font-family:$STYLErow->S_FONT_FAMILY;".
        "font-size:$STYLErow->S_FONT_SIZE_SMALL;".
        "color:$STYLErow->S_COLOR_TEXT;".
        "font-style:normal;".
        "font-weight:bold;";

    $anchorStyle = "";
//        "text-decoration:none;".
//        "color:$STYLErow->S_COLOR_TEXT;";

    //----------------------------------------------------------------------------
    // Get labels.

    $pageLabel        = gs_getLabel ($db, $link, 'ctrl_page',    $locale, $appl);
    $numresLabel0 = gs_getLabel ($db, $link, $noResponse,    $locale, $appl);
    $numresLabel1 = gs_getLabel ($db, $link, $oneResponse, $locale, $appl);
    $numresLabel    = gs_getLabel ($db, $link, $responses,     $locale, $appl);

    //----------------------------------------------------------------------------
    // Build labels, switch number of results.

    $responses = '';
    if ($numItems == 0) {
        $responses = $numresLabel0;

    } else if ($numItems == 1) {
        $responses = $numresLabel1;

    } else {
        $responses = $numresLabel.'&nbsp;: '.$numItems;
    }

    //----------------------------------------------------------------------------
    // Build pages count.

    if ($numItems > $max) {
        //-- More than one page.
        $count     = $pageLabel.'&nbsp;:';
        $pgcount = 1;

        //-- For all sets of items.

        $current        = 0;
        $blockArray = array ();

        for ($i = 0; $i < $numItems; $i += $max) {
            if ($first == $i) {
                //-- This is the current set.
                $current = $pgcount;
                $tag         = '['.$pgcount.']';

            } else {
                //-- Another set: [$i, $i+$max]
                $href = $url.'&amp;first='.$i.'&amp;max='.$max;
                $tag    = ('<A href="'.$href.'" style="'.$anchorStyle.'">'.$pgcount.'</A>');
            }

            $blockArray[$pgcount] = $tag;

            $pgcount++;
        }

        $firstTag = ($current - 5 > 0 ? $current - 5 : 1);
        $lastTag    = $firstTag + 10;

        if ($firstTag > 1) $count .= '&nbsp;...&nbsp;';

        while (list ($k, $v) = each ($blockArray)) {
            if (($k >= $firstTag) && ($k <= $lastTag)) {
                $count .= '&nbsp;'.$v;
            }
        }

        if ($lastTag + 1 < $pgcount) $count .= '&nbsp;...&nbsp;';

    } else {
        //-- Zero or one page.
        $count = '&nbsp;';
    }

    //----------------------------------------------------------------------------
    // Build table.

    $str = '';
    $str .= "\n".'        <TABLE width="'.$width.'" border="0" cellspacing="0" cellpadding="0" summary="">';
    $str .= "\n".'            <TR>';
    $str .= "\n".'                <TD width="25%" align="left">'.gs_buildControl ($url, $first, $max, $numItems, $style, $imgdir).'</TD>';
    $str .= "\n".'                <TD width="50%" align="center"><SPAN style="'.$fontStyle.'">'.$responses.'</SPAN></TD>';
    $str .= "\n".'                <TD width="25%" style="'.$fontStyle.'" align="right"><SPAN style="'.$fontStyle.'">'.$count.'</SPAN></TD>';
    $str .= "\n".'            </TR>';
    $str .= "\n".'        </TABLE>';

    return $str;
}

//==============================================================================
// gs_buildControl ($url, $first, $max, $numItems, $style = 'line', $imgdir = 'dft')
//    $url                 : URL to show datas, without first and max limits
//    $first             : in the result set, the index of the first item to show
//    $max                 : max count of results by page
//    $numItems        : results count
//    $style             : style used into the images control cells
//    $imgdir            : the image set used for the control buttons
//
// Generation of control buttons (first, previous, next, last) for search
// result, for example.
//==============================================================================

function gs_buildControl ($url,
                                                    $first, $max, $numItems,
                                                    $style    = 'line',
                                                    $imgdir = 'dft') {
    //----------------------------------------------------------------------------
    // Compute index of last set.

    if ($numItems == 0) {
        $last = 0;

    } else {
        $last = ($numItems % $max == 0 ?
                         ((int)($numItems / $max) - 1) * $max :
                         ((int)($numItems / $max))         * $max);
    }

    //----------------------------------------------------------------------------
    // Build infos for gs_control.

    $ctrlParam = array (
        'style'    => $style,
        'imgdir' => $imgdir,
        'begin'    => $url.'&amp;first=0&amp;max='.$max,
        'last'     => $url.'&amp;first='.$last.'&amp;max='.$max
    );

    if ($first > 0) {
        $ctrlParam['prev'] = $url.'&amp;first='.($first - $max).'&amp;max='.$max;
    }

    if ($first + $max < $numItems) {
        $ctrlParam['next'] = $url.'&amp;first='.($first + $max).'&amp;max='.$max;
    }

    //----------------------------------------------------------------------------
    // Build control.

    return gs_control ($ctrlParam);
}

//==============================================================================
// gs_control ($param)
//    $param : (...)
//
// Dump a table containing images for first, prev, next, last navigation,
// according to $param parameters array.
//
// $param is an array, with the following items:
//    - style    : style used for the table cells
//    - imgdir : the directory of the control images set (Local/controls/$imgdir)
//    - begin    : URL to the first set
//    - prev     : URL to the previous set
//    - next     : URL to the next set
//    - last     : URL to the last set
//==============================================================================

function gs_control ($param) {
    $imgdir = (empty ($param['imgdir']) ? 'dft' : $param['imgdir']);

    $icon1 = "Local/controls/$imgdir/01$imgdir.gif";
    $icon2 = "Local/controls/$imgdir/02$imgdir.gif";
    $icon3 = "Local/controls/$imgdir/03$imgdir.gif";
    $icon4 = "Local/controls/$imgdir/04$imgdir.gif";
    $icon5 = "Local/controls/$imgdir/05$imgdir.gif";
    $icon6 = "Local/controls/$imgdir/06$imgdir.gif";

    $beginImg = '<IMG src="'.$icon2.'" border="0" alt="">';
    $prevImg    = '<IMG src="'.$icon3.'" border="0" alt="">';
    $nextImg    = '<IMG src="'.$icon4.'" border="0" alt="">';
    $lastImg    = '<IMG src="'.$icon5.'" border="0" alt="">';

    $style        = (empty ($param['style']) ? ''                : ' class="'.$param['style'].'"');
    $beginImg = (empty ($param['begin']) ? $beginImg : '<A href="'.$param['begin'].'">'.$beginImg.'</A>');
    $prevImg    = (empty ($param['prev'])    ? $prevImg    : '<A href="'.$param['prev'].'">'.$prevImg.'</A>');
    $nextImg    = (empty ($param['next'])    ? $nextImg    : '<A href="'.$param['next'].'">'.$nextImg.'</A>');
    $lastImg    = (empty ($param['last'])    ? $lastImg    : '<A href="'.$param['last'].'">'.$lastImg.'</A>');

    $str = '';
    $str .= "\n".'<TABLE border="0" cellspacing="0" cellpadding="0" summary="">';
    $str .= "\n".'    <TR>';
    $str .= "\n".'        <TD><IMG src="'.$icon1.'" border="0" alt=""></TD>';
    $str .= "\n".'        <TD'.$style.'>'.$beginImg.'</TD>';
    $str .= "\n".'        <TD'.$style.'>'.$prevImg.'</TD>';
    $str .= "\n".'        <TD'.$style.'>'.$nextImg.'</TD>';
    $str .= "\n".'        <TD'.$style.'>'.$lastImg.'</TD>';
    $str .= "\n".'        <TD><IMG src="'.$icon6.'" border="0" alt=""></TD>';
    $str .= "\n".'    </TR>';
    $str .= "\n".'</TABLE>';

    return $str;
}

//==============================================================================
// gs_buildOptionInVar ($db, $link, $query, $current, $valueFieldName, $labelFieldName, $locale, $appl, $isLabel)
//    $db                         : database name
//    $link                     : database link
//    $query                    : query to perform
//    $current                : current expected value of the select (option SELECTED)
//    $valueFieldName : in the query, the field name of the value
//    $labelFieldName : in the query, the field name of the text
//    $locale                 : current locale, in case of labelled text
//    $name                     : name of application, for labels
//    $isLabel                : true if $labelFieldName field is a label name.
//
// According to the result of the query $query, build SELECT options. The result
// is a string.
//==============================================================================

function gs_buildOptionInVar ($db, $query, $current, $valueFieldName, $labelFieldName, $locale = '', $appl= '', $isLabel = false) {
    //----------------------------------------------------------------------------
    // Perform query.

    $res = $db->query ($query);

    if (DB::isError($res)) {
        die ("Unable to perform query ($query / " . $res->getMessage() . ")");
    }

    //----------------------------------------------------------------------------
    // Build options.

    $str = '';

    while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
        //-- Option label. If $isLabel is true, the field named $labelFieldName is
        //-- used as a label. Otherwise, it's only a string.

        $label =  htmlentities ($row[$labelFieldName]);

        //-- The value: field $valueFieldName of the result set.
        $value = $row[$valueFieldName];

        //-- If the value if equal to $current, this option is selected.
        $selected = ($current == $value ? ' selected' : '');

        //-- Build option.

        $str .= "\n".'<OPTION value="'.$value.'"'.$selected.'>'.$label.'</OPTION>';
    }

     $res->free();

    return $str;
}

//==============================================================================
// gs_localePutLanguagesFlagsInVar ($dbname, $dblink, $project)
//    $dbname    : database name
//    $dblink    : database link
//    $project : project name
//
// Dump array of flags, one for each language supported by the project.
// Images are taken from Local/flags directory.
//==============================================================================

function gs_localePutLanguagesFlagsInVar ($dbname, $dblink, $project) {
    //----------------------------------------------------------------------------
    // List of all the languages supported by project.

    $query =
        "select * from $dbname.LOCALE, $dbname.LOCALE_PRJ".
        " where LP_PROJECT='$project' and LP_CODE=L_CODE".
        " order by LP_ORDER";

    $result = mysql_query ($query, $dblink);

    if (! $result) {
        die ("Unable to perform query (" . mysql_error ($dblink) . ")");
    }

    //----------------------------------------------------------------------------
    // Only one language ? Do nothing.

    if (mysql_num_rows ($result) <= 1) {
        mysql_free_result ($result);
        return;
    }

    //----------------------------------------------------------------------------
    // Dump array of flags.

    $outputText = '';

    $outputText .= "\n".'<TABLE summary="" cellspacing="3" cellpadding="0" border="0">';
    $outputText .= "\n".'    <TR>';

    while ($row = mysql_fetch_object ($result)) {
        //--------------------------------------------------------------------------
        // The flags images are taken from Local/flags.

        $url = "index.php?project=$project&amp;locale=$row->LP_CODE";
        $img = "Local/flags/$row->L_FLAG";
        $alt = htmlentities ($row->L_DESCRIPTION);

        $outputText .= "\n".'<TD>';
        $outputText .= '<A target="_top" href="'.$url.'">';
        $outputText .= '<IMG border="0" src="'.$img.'" alt="'.$alt.'">';
        $outputText .= '</A>';
        $outputText .= '</TD>';
    }

    $outputText .= "\n".'    </TR>';
    $outputText .= "\n".'</TABLE>';

    mysql_free_result ($result);

    return $outputText;
}

//==============================================================================
// FUNCTION gs_putAmount ($frf, $euro)
//
// Convert an amount into euro.
//
// NOTE: must be move into project module.
//==============================================================================

function gs_putAmount ($frf, $euro) {
    if ($euro == 0) {
        $euro = $frf / 6.55957;
        $euro = (round ($euro * 100)) / 100;
    }

    if ($euro == 0)            return '&nbsp;';
    if ($euro >= 150000) return 'A ( >= 150 000 &euro; )';
    if ($euro >=    45000) return 'B ( < 150 000 &euro;, >= 45 000 &euro; )';
    if ($euro >=    15000) return 'C ( < 45 000 &euro;, >= 15 000 &euro; )';

    return 'D ( < 15 000 &euro;)';
}



/**     function includeFile () Inclue des fichiers en essayant dans divers lieux
*
*   @param  mixed   Un tableau contenant les fichiers à inclure
*   @param  string  Un message d'erreur
*       return  boolean true en cas de succès
*/

function includeFile($incFiles, $msg) {
    if (! isset        ($incFiles)) die ('Bad include path');
    if (! is_array ($incFiles)) die ('Bad include path');

    $searchPath = '';

    for ($i = 0; $i < count ($incFiles); $i++) {
        $searchPath .= $incFiles[$i].'<BR>'."\n";

        if (file_exists ($incFiles[$i])) {
            include_once ($incFiles[$i]);
            return;
        }
    }

    die ("$msg<BR>\nSearch path:<BR>\n$searchPath");
}

//==============================================================================
// FUNCTION gs_getUser ($db, $link, $annu, $userid)
//
// Returns an array with user informations.
//==============================================================================

function gs_getUser ($db, $link, $annu, $userid) {
    $query =
        "select * from $db.annu_USERS".
        " where U_ID=$userid".
        " and U_ANNU_NAME='$annu'";

    $result = mysql_query ($query, $link);

    if (! $result) {
        die ("Unable to perform query ($query / " . mysql_error ($link) . ")");
    }

    $row = mysql_fetch_object ($result);
    if (! $row) return false;

    $userInfo['login']     = $row->U_LOGIN;
    $userInfo['name']        = $row->U_NAME;
    $userInfo['surname'] = $row->U_SURNAME;
    $userInfo['row']         = $row;

    mysql_free_result ($result);

    return $userInfo;
}

//==============================================================================
//==============================================================================

//==============================================================================
//==============================================================================


//==============================================================================
// FUNCTION messageTo ($project, $locale, $to)
//
// Dump an icon to send a message.
//==============================================================================

function messageTo ($project, $locale, $to) {
    $args = "'$project', '$locale', $to";
    $icon = '<IMG src="Local/icons/newmsg.gif" alt="" width="16" height="16" border="0">';

    return
        '<A href="javascript:openMessenger ('.$args.')">'.
        $icon.
        '</A>';
}

//==============================================================================
//==============================================================================

function gs_print ($item) {
    ob_start ();
    print_r ($item);
    $p = ob_get_contents ();
    ob_end_clean ();

    echo '<PRE>'.htmlentities ($p).'</PRE>';
}

//==============================================================================


?>