Location: PHPKode > projects > Bradabra > bradabra/include/functions.php
<?php
//****************************************************************************
//
// Copyright (C) 2001 Eric SEIGNE <hide@address.com>
//
// 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.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
//****************************************************************************
//
// For more informations, get to the project's main source file.
//
// Description  Main header for some useful functions
//              Global constants and variables definitions.
//
//****************************************************************************

if(!defined("__functions_php__")):
define("__functions_php__", "1");


$chrono_starttime = 0;


//----------------------------------------------------------------------------
// ChronoStart
//----------------------------------------------------------------------------
function ChronoStart ()
{
  global $chrono_starttime;

  $timeparts = explode(" ", microtime());
  $chrono_starttime = $timeparts[1].substr($timeparts[0], 1);
}

//----------------------------------------------------------------------------
// ChronoStop - Return the time difference between a call of ChronoStart() and
//              this call to ChronoStop() in seconds.
//----------------------------------------------------------------------------
function ChronoStop ()
{
  global $chrono_starttime;

  $timeparts = explode(" ", microtime());
  $endtime   = $timeparts[1].substr($timeparts[0], 1);

  return sprintf("%.3f", (float)$endtime - (float)$chrono_starttime);
  // return bcsub($endtime, $chrono_starttime, 3);
}

//----------------------------------------------------------------------------
// GetBrowserLanguage
//----------------------------------------------------------------------------
function GetBrowserLanguage ()
{
  global $HTTP_ACCEPT_LANGUAGE;
  global $browser_languages;

  $ret = "";

  if(strlen($HTTP_ACCEPT_LANGUAGE) == 0)
    return "none";

  $langs = explode(",", $HTTP_ACCEPT_LANGUAGE);

  for($i=0 ; $i<count($langs) ; $i++)
  {
    $l = strtolower(trim($langs[$i]));
    $ret .= "\"$l\" ";

    if(isset($browser_languages[$l]))
      return $browser_languages[$l];
  }

//  if(strlen($GLOBALS["HTTP_ACCEPT_LANGUAGE"]))
//    return "none ($HTTP_ACCEPT_LANGUAGE not supported)";
//  else
//    return "none";
}

//----------------------------------------------------------------------------
// GetInternalModuleArray - Returns FALSE if current interal module was not
//                          found.
//----------------------------------------------------------------------------
function GetInternalModuleArray ()
{
  global $InternalModules;

  if(!defined("__this_is_an_internal_module__"))
    return FALSE;

  $n = count($InternalModules);
  for($i=0 ; $i<$n ; $i++)
    if($InternalModules[$i]["name"] == __this_is_an_internal_module__)
      return $InternalModules[$i];

  return FALSE;
}

//----------------------------------------------------------------------------
// GetEnterpriseHeader
//----------------------------------------------------------------------------
function GetEnterpriseHeader ($bInputCtrlAllowed, $txt_enterprise_email)
{
  global $lang;

  // initializing
  $logopath = MakeRelativePath($GLOBALS["PHP_SELF"], $GLOBALS["enterprise_logopath"]);

  // header
  $header = "            <h4 align=\"left\">\n";

  if($GLOBALS["enterprise_logopath"] != "")
  {
    if($bInputCtrlAllowed == FALSE)
      $header .= "              <img src=\"".substr($logopath, 3)."\">\n";  // remove the first "../" from logo path
    else
      $header .= "              <img src=\"".$logopath."\">\n";
  }
  else
    $header .= "              ".$GLOBALS["enterprise_name"]."\n";

  $header .=
    "              <br>\n".
    "              ".$GLOBALS["enterprise_description"]."\n".
    "            </h4>\n".
    "            <p>\n".
    "              ".my_nl2br($GLOBALS["enterprise_address"])."<br>\n".
    "              ".$GLOBALS["enterprise_postalcode"]." ".$GLOBALS["enterprise_city"]."<br>\n".
    "              ".$lang["phone"]." ".$GLOBALS["enterprise_phone"]."<br>\n";

  if($GLOBALS["enterprise_fax"] != "")
    $header .=
      "              ".$lang["phone"]." ".$GLOBALS["enterprise_fax"]."<br>\n";

  if($bInputCtrlAllowed == FALSE)
  {
    $header .= "              ".$txt_enterprise_email."<br>\n";
  }
  else
  {
    $txt_enterprise_email = trim($txt_enterprise_email);

    $header .=
      "              <input type=\"text\" name=\"txt_enterprise_email\" size=\"20\" value=\"".($txt_enterprise_email=="" ? stripslashes($GLOBALS["enterprise_emails"][0]["email"]) : stripslashes($txt_enterprise_email))."\">\n".
      "              <select name=\"sel_enterprise_email\" onchange=\"ChangeEnterpriseEMail(sel_enterprise_email, txt_enterprise_email);\">\n";

    $n = count($GLOBALS["enterprise_emails"]);
    for($i=0 ; $i<$n ; $i++)
    {
      if($txt_enterprise_email == "")
        $sel = ($i == 0) ? " selected" : "";
      else
        $sel = ($txt_enterprise_email == $GLOBALS["enterprise_emails"][$i]["email"]) ? " selected" : "";

      $header .=
        "                ".
        "<option value=\"".$GLOBALS["enterprise_emails"][$i]["email"]."\"".$sel.">".$GLOBALS["enterprise_emails"][$i]["caption"]."\n";
    }

    $header .=
      "              </select>\n".
      "              <br>\n";
  }

  $header .=
    "              ".$GLOBALS["enterprise_legalstatus"]."<br>\n";

  $GLOBALS["enterprise_capital"] = trim($GLOBALS["enterprise_capital"]);
  if(!empty($GLOBALS["enterprise_capital"]))
    $header .= "              ".$lang["Capital"]." ".$GLOBALS["enterprise_capital"]."<br>\n";

  $header .=
    "              ".$GLOBALS["enterprise_trade_register"]."<br>\n".
    "              ".$GLOBALS["enterprise_ape"]."<br>\n".
    "            </p>\n";

  return $header;
}

//----------------------------------------------------------------------------
// IncludeDHTMLPopup
//----------------------------------------------------------------------------
function IncludeDHTMLPopup ($id, $content, $imagesdir, $width=200)
{
  $text = "";

  $text .=
    "<div id=\"".$id."\" class=\"popup\">".
      "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" bgcolor=\"".COL_BACK."\">".
        "<tr>".
          "<td>".
            "<img src=\"".$imagesdir.IMG_TABLE_CORNER_1."\" width=\"".TABLE_BORDERSIZE."\" height=\"".TABLE_BORDERSIZE."\" alt=\"\">".
          "</td>".
          "<td background=\"".$imagesdir.IMG_TABLE_BORDER_HORZ."\">".
            "<img src=\"".$imagesdir.IMG_TABLE_BORDER_HORZ."\"  width=\"1\" height=\"".TABLE_BORDERSIZE."\" alt=\"\">".
          "</td>".
          "<td>".
            "<img src=\"".$imagesdir.IMG_TABLE_CORNER_2."\" width=\"".TABLE_BORDERSIZE."\" height=\"".TABLE_BORDERSIZE."\" alt=\"\">".
          "</td>".
        "</tr>".
        "<tr>".
          "<td background=\"".$imagesdir.IMG_TABLE_BORDER_VERT."\">".
            "<img src=\"".$imagesdir.IMG_TABLE_BORDER_VERT."\" width=\"".TABLE_BORDERSIZE."\" height=\"1\" alt=\"\">".
          "</td>".
          "<td width=\"100%\">".
            $content.
          "</td>".
          "<td background=\"".$imagesdir.IMG_TABLE_BORDER_VERT."\">".
            "<img src=\"".$imagesdir.IMG_TABLE_BORDER_VERT."\" width=\"".TABLE_BORDERSIZE."\" height=\"1\" alt=\"\">".
          "</td>".
        "</tr>".
        "<tr>".
          "<td>".
            "<img src=\"".$imagesdir.IMG_TABLE_CORNER_4."\" width=\"".TABLE_BORDERSIZE."\" height=\"".TABLE_BORDERSIZE."\" alt=\"\">".
          "</td>".
          "<td background=\"".$imagesdir.IMG_TABLE_BORDER_HORZ."\">".
            "<img src=\"".$imagesdir.IMG_TABLE_BORDER_HORZ."\" width=\"1\" height=\"".TABLE_BORDERSIZE."\" alt=\"\">".
          "</td>".
          "<td>".
            "<img src=\"".$imagesdir.IMG_TABLE_CORNER_3."\" width=\"".TABLE_BORDERSIZE."\" height=\"".TABLE_BORDERSIZE."\" alt=\"\">".
          "</td>".
        "</tr>".
      "</table>".
    "</div>".
    "\n";

  print($text);
}

//----------------------------------------------------------------------------
// IncludeJS - Insert JavaScript function(s)
//----------------------------------------------------------------------------
function IncludeJS ($javascript_functions)
{
  print(
    "\n".
    "<script language=\"JavaScript\">\n".
    $javascript_functions.
    "</script>\n");
}

//----------------------------------------------------------------------------
// InvertListRowColor
//----------------------------------------------------------------------------
function InvertListRowColor ($col_row)
{
  if($col_row == COL_LISTROW1)
    $col_row = COL_LISTROW2;
  else
    $col_row = COL_LISTROW1;

  return $col_row;
}

//----------------------------------------------------------------------------
// MagicQuotes_Decode
//----------------------------------------------------------------------------
function MagicQuotes_Decode ($text)
{
  return (($GLOBALS["mq_flag"]=="1") ? $text : stripslashes($text));
}

//----------------------------------------------------------------------------
// MagicQuotes_Encode
//----------------------------------------------------------------------------
function MagicQuotes_Encode ($text)
{
  return (($GLOBALS["mq_flag"]=="1") ? $text : addslashes($text));
}

//----------------------------------------------------------------------------
// MakeRelativePath
//----------------------------------------------------------------------------
function MakeRelativePath ($from_path, $to_path)
{
  $relpath = "";
  $wildcard = "/";

  // remove beginning matching sub-strings
  $i = 0;
  while(($from_path[$i] == $to_path[$i]) && $from_path[$i] && $to_path[$i])
    $i++;

  if(!$from_path[$i] || !$to_path[$i]) // strings exactly match ?
  {
    $relpath = substr($from_path, strrpos($from_path, $wildcard) + 1);
    return $relpath;
  }
  else
  {
    while($from_path[$i] != $wildcard)
      $i--;

    $from_path = substr($from_path, $i);
    $to_path = substr($to_path, $i);

    // remove first-character wildcard if there's one
    if($from_path[0] == $wildcard)
      $from_path = substr($from_path, 1);
    if($to_path[0] == $wildcard)
      $to_path = substr($to_path, 1);
  }

  // count $from_path levels
  $i = 0;
  $from_path_levels = 0;
  while($from_path[$i])
  {
    if($from_path[$i] == $wildcard)
      $from_path_levels++;

    $i++;
  }

  // prepare relative path
  for($i=0 ; $i<$from_path_levels ; $i++)
    $relpath .= "../";
  $relpath .= $to_path;

  return $relpath;
}

//----------------------------------------------------------------------------
// my_nl2br
//----------------------------------------------------------------------------
function my_nl2br ($text)
{
  return ereg_replace("(".REGEXP_NEWLINE.")", "<br>", $text);
}

//---------------------------------------------------------------------------
// Redirect
//---------------------------------------------------------------------------
function Redirect ($url)
{
  // PHP method
  //------------
  // Must be called from the very top of an HTML page, before the <HTML> tag.
//header("Location: $url");
//print("\n<html><head><title>Redirect</title></head><body>Please go <a href=\"".$url."\">here</a></body></html>\n");

  // JavaScript method
  //-------------------
  // Can be called from everywhere in an HTML page.
  print("<script language=\"javascript\">window.location='".$url."';</script>\n");

  // Exit
  //------
  // Be sure to exit
  exit;
}

//----------------------------------------------------------------------------
// RedirRobot - Redirection Robot.
//              Only for local using, not external links.
//
//              PARAMETERS
//              bRedirect - Boolean value. When it's FALSE, this function will
//                          just return the wanted destination link, but not
//                          redirecting. This is useful for <a href> tags.
//              dst       - Destination label (one of the "Dest" member in
//                          RedirArray declared in the include/config.php
//              args      - Arguments. Must be formated like this :
//                          "arg1=value1&arg2=value2&arg3=value3".
//                          Can be NULL.
//----------------------------------------------------------------------------
function RedirRobot ($bRedirect, $dst, $args)
{
  global $RedirArray;

  //$dst = strtolower($dst);
  $args = trim($args);

  // - REMARK -
  // I could use the parse_str() function to parse URL string.


  // Special dst caption : "this"
  //------------------------------
  // - Important -
  // Handling of arguments with "this" destination is a little black magic.
  // If you have an argument and its value in the original QUERY_STRING named
  // "myarg=myvalue1", and if you send an argument who have the same name like
  // this "myarg=value2", the string "myarg=myvalue1" will be removed from the
  // originale QUERY_STRING and replaced by the same argument but the new
  // value, so the final string will be "myarg=value2".
  if($dst == "this")
  {
    $redirstr = $GLOBALS["PHP_SELF"];
    $querystr = trim(getenv("QUERY_STRING"));

    if(empty($querystr) && empty($args))
    {
      $querystr = NULL;
    }
    else if(empty($querystr))
    {
      $querystr = $args;
    }
    else if(empty($args))
    {
      // do nothing here, just let $querystr to be added to the $redirstr by
      // the next step
    }
    else
    {
      // parse original and new arguments strings into two arrays
      $args_orig = split("[&=]", $querystr);
      $args_new  = split("[&=]", $args);

      // construct the new query string
      $querystr = NULL;
      $n_orig = count($args_orig);
      $n_new  = count($args_new);
      for($i=0 ; $i<$n_orig ; $i+=2)
      {
        // reset "new value"
        $newvalue = NULL;

        // search for a new value for the same argument
        for($j=0 ; $j<$n_new ; $j+=2)
        {
          if($args_orig[$i] == $args_new[$j])
          {
            $newvalue = $args_new[$j+1];

            // reset this argument to tell we will not need it anymore for next steps
            $args_new[$j] = NULL;
            $args_new[$j+1] = NULL;
          }
        }

        // append a "&" to prevent incomming argument
        if($querystr)
          $querystr .= "&";

        // old value of this argument is not replaced
        if(!$newvalue)
          $querystr .= $args_orig[$i]."=".$args_orig[$i+1];
        // old value of this argument is replaced by a new value
        else
          $querystr .= $args_orig[$i]."=".$newvalue;
      }

      // now we can append the very new arguments to the new query string
      for($j=0 ; $j<$n_new ; $j+=2)
        if($args_new[$j] && $args_new[$j+1])
          $querystr .= "&".$args_new[$j]."=".$args_new[$j+1];
    }

    // add arguments to redirection string (if there's one)
    if($querystr)
      $redirstr .= "?".$querystr;

    // redirecting or just return the link string
    if(!$bRedirect)
      return $redirstr;
    else
      Redirect($redirstr);
  }

  // Others destinations
  //---------------------
  // find an occurence of the wanted destination label in the redirection array
  $n = count($RedirArray);
  for($i=0 ; $i<$n ; $i+=2)
  {
    if($dst == $RedirArray[$i])  //if($dst == strtolower($RedirArray[$i]))
    {
      if(!eregi("^javascript", $RedirArray[$i+1]))
      {
        $redirstr = DIR_ROOT."/".$RedirArray[$i+1];
        if($GLOBALS["sid"])
          $redirstr .= "?sid=".$GLOBALS["sid"];

        if($args)
        {
          if(!$GLOBALS["sid"])
            $redirstr .= "?";
          else
            $redirstr .= "&";

          $redirstr .= $args;
        }

        // redirecting or just return the link string
        if(!$bRedirect)
          return $redirstr;
        else
          Redirect($redirstr);
      }
      else
      {
        if(!$bRedirect)
          return $RedirArray[$i+1];
        //else
        //  Redirect($redirstr);
      }
    }
  }

  die("ERROR : Unknown redirection address \"".$dst."\".");
}

//----------------------------------------------------------------------------
// RedirRobotReversed - Get the destination caption from the URL.
//                      Returns FALSE when caption was not found.
//
//                      WARNING
//                      Not tested !!!!
//----------------------------------------------------------------------------
function RedirRobotReversed ($url)
{
  global $RedirArray;

  $url = strtolower($url);

  // find an occurence of the wanted destination label from the redirection array
  $n = count($RedirArray);
  for($i=0 ; $i<$n ; $i+=2)
  {
    if(strstr($url, DIR_ROOT."/".strtolower($RedirArray[$i+1])))
      return $RedirArray[$i];
  }

  return FALSE;
}

//----------------------------------------------------------------------------
// SendEMail - code stolen from http://phpinfo.net/
//----------------------------------------------------------------------------
function SendEMail ($to, $subject, $msg)
{
  /*
  // -------------------------------------------------------------------------
  // Envoyer un mail en spécifiant le serveur.
  // -------------------------------------------------------------------------
  // Auteur: Shino
  // Email:  hide@address.com
  // Web:
  // -------------------------------------------------------------------------
  // Commentaires : le 'hashinutile' etait necessaire chez moi car le serveur
  // SMTP ne prenait en compte le premier mot et le premier espace. je ne sais
  // pas si c'est valable partout. Ce code est specialement utile pour un
  // intranet ou le mail ne doit pas aller se balader sur internet (si celui
  // est accessible, ce qui n'est pas mon cas pour l'application courante).
  // -------------------------------------------------------------------------

  $message = "";

  $message .= "HELO ".$server_name."\n"; // salut
  $message .= "EHLO ".$server_name."\n"; // reponse au salut
  $message .= "MAIL FROM: <".$exp.">\n"; // expediteur
  $message .= "RCPT TO: <".$to.">\n";    // destinataire
  $message .= "DATA\n";                  // debut des donnees
  $message .= "SUBJECT: ".$subject."\n"; // sujet
  $message .= "hashinutile ";            // necessaire au traitement
  $message .= $msg;                      // message
  $message .= "\n.\n";                   // fin du message
  $message .= "QUIT\n";                  // deconnexion

  $hSocket = fsockopen($server_ip, 25);
  fputs($hSocket, $message);
  fclose($hSocket);
  */

  mail($to, $subject, $msg);
}




//****************************************************************************
//****************************************************************************
//
// Header and Footer
//
//****************************************************************************
//****************************************************************************
//----------------------------------------------------------------------------
// MenuBar
//----------------------------------------------------------------------------
function MenuBar ()
{
  global $lang;
  global $InternalModules;

  $text = "";

  IncludeJS($GLOBALS["js_PopupConverter"]);

  // basic menu
  $text .=
    "\n".
    "<!-- Menu Bar TOP -->\n".
    "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n".
    "  <tr bgcolor=\"".COL_LISTROW1."\">\n".
    "    <td class=\"statusbox\">\n".
    "      [\n".
    "      ".$lang["Logged as"]." <b>".$GLOBALS["user_login"]."</b>\n". // ICI, faire du login un lien vers un pad affichant les infos spécifiques à cet utilisateur.
    "      ]\n".
    "      [\n".
    "      <a href=\"".DIR_ROOT."/\">".$lang["Logout"]."</a>\n".
    "      <a href=\"".RedirRobot(FALSE, "main_home", NULL)."\">".$lang["Home"]."</a>\n".
    "      <a href=\"".RedirRobot(FALSE, "config", NULL)."\">".$lang["Config"]."</a>\n".
    "      ]\n";

  // internal modules
  $n = count($InternalModules);
  if($n > 0)
  {
    $text .= "      [\n";
    for($i=0 ; $i<$n ; $i++)
    {
      if($InternalModules[$i]["id"] == 0)
        $text .= "      &middot;\n";
      else if(($GLOBALS["user_access_intmods"] == INTMODS_FULLACCESS) || ($GLOBALS["user_access_intmods"] & $InternalModules[$i]["id"]))
        $text .= "      <a href=\"".RedirRobot(FALSE, $InternalModules[$i]["name"], NULL)."\">".$InternalModules[$i]["caption"]."</a>\n";
    }
    $text = eregi_replace("(      &middot;\n)$", "", $text);
    $text .= "      ]\n";
  }

  // external modules
  $n = count($GLOBALS["config_external_modules"]);
  if($n > 0)
  {
    $text .= "      [\n";
    for($i=0 ; $i<$n ; $i++)
    {
      $text .= "      <a href=\"".$GLOBALS["config_external_modules"][$i]["path"]."\" target=\"_blank\">".$GLOBALS["config_external_modules"][$i]["name"]."</a>\n";
      if($i < $n-1)
        $text .= "      &middot;\n";
    }
    $text .= "      ]\n";
  }

  $text .=
    "    </td>\n".
    "  </tr>\n".
    "</table>\n".
    "<!-- Menu Bar BOTTOM -->\n\n";

  print($text);
}

//----------------------------------------------------------------------------
// FooterBar
//----------------------------------------------------------------------------
function FooterBar ()
{
  print(
    "<br>\n".
    "\n".
    "<!-- Footer Bar TOP -->\n".
    "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n".
    "  <tr>\n". //"  <tr bgcolor=\"".COL_LISTROW1."\">\n".
    "    <td class=\"statusbox\" align=\"center\">\n".
    "      <a href=\"".PROG_WEB."\" target=\"_blank\">".PROG_NAME."</a> v".PROG_VER."&nbsp;&nbsp;-&nbsp;&nbsp;Copyright ".chr(169)." 2001 Eric SEIGNE [<a href=\"mailto:".CREATOR_EMAIL."\">e-mail</a> - <a href=\"".CREATOR_WEB."\" target=\"_blank\">www</a>]\n".
    "    </td>\n".
    "  </tr>\n".
    "</table>\n".
    "<!-- Footer Bar BOTTOM -->\n\n");
}


endif;
?>
Return current item: Bradabra