Location: PHPKode > projects > Quick Guestbook > quicktalk/bin/qtg_fn_base.php
<?php

/**
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license.  If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to hide@address.com so we can mail you a copy immediately.
*
* @package    QuickTalk Guestbook
* @author     Philippe Vandenberghe <hide@address.com>
* @copyright  2009-2012 The PHP Group
* @version    2.5 build:20100731
*/

function AsEmails($strEmails,$strId,$strRender='txt',$bFirst=false,$strSkin='skin/default',$strNojava='Java protected email',$strEmpty='&nbsp;')
{
  if ( !is_string($strEmails) ) return $strEmpty;
  if ( empty($strEmails) ) return $strEmpty;
  // get list of Emails
  if ( strstr($strEmails,' ; ') ) { $arrEmails = explode(' ; ',$strEmails); } else { $arrEmails = array($strEmails);  }
  // get first Email
  $strFirst = $arrEmails[0];
  // only one email
  if ( $bFirst ) $arrEmails = array($strFirst);
  // build expression
  $strReturn = '';
  switch ($strRender)
  {
  case 'txt':
    $strReturn .= '<a id="href'.$strId.'" class="small" href="mailto:'.implode(';',$arrEmails).'">';
    $strReturn .= implode(' ; ',$arrEmails);
    $strReturn .= '</a>';
    break;
  case 'img':
    $strReturn .= '<a id="href'.$strId.'" class="small" href="mailto:'.implode(';',$arrEmails).'">';
    $strReturn .= '<img class="email" id="img'.$strId.'" src="'.$strSkin.'/ico_mail.gif" alt="email" title="'.$strFirst.'"/>';
    $strReturn .= '</a>';
    break;
  case 'txtjava':
    $strReturn .= '<script type="text/javascript">';
    foreach ($arrEmails as $strEmail)
    {
    $arr = explode('@',$strEmail);
    $strReturn .= 'writemailto("'.$arr[0].'","'.$arr[1].'"," ");';
    }
    $strReturn .= '</script><noscript class="small">'.$strNojava.'</noscript>';
    break;
  case 'imgjava':
    $str = implode(';',$arrEmails);
    $str = str_replace('@','-at-',$str);
    $str = str_replace('.','-dot-',$str);
    $strFirst = str_replace('@','-at-',$strFirst);
    $strFirst = str_replace('.','-dot-',$strFirst);
    $strReturn .= '<a id="href'.$strId.'" onmouseover="vmail(\''.$strId.'\');" onmouseout="hmail(\''.$strId.'\');" class="small" href="javamail:'.$str.'">';
    $strReturn .= '<img class="email" id="img'.$strId.'" src="'.$strSkin.'/ico_mail.gif" alt="email" title="'.$strFirst.'"/>';
    $strReturn .= '</a>';
    break;
  }
  return $strReturn;
}

// --------

function DateAdd($d='0',$i=-1,$str='year')
{
   if ( $d=='0' ) die('DateAdd: Argument #1 must be a string');
   QTargs( 'DateAdd',array($d,$i,$str),array('str','int','str') );

   $intY = intval(substr($d,0,4));
   $intM = intval(substr($d,4,2));
   $intD = intval(substr($d,6,2));
   switch($str)
   {
   case 'year': $intY += $i; break;
   case 'month': $intM += $i; break;
   case 'day': $intD += $i; break;
   }
   if ( $intD>30 ) { $intM++; $intD -= 30; }
   if ( $intD<1 ) { $intM--; $intD += 30; }
   if ( $intM>12 ) { $intY++; $intM -= 12; }
   if ( $intM<1 ) { $intY--; $intM += 12; }
   if ( $intM==2 && $intD>28 ) { $intM++; $intD -= 28; }
   return strval($intY*10000+$intM*100+$intD).(strlen($d)>8 ? substr($d,8) : '');
}

// --------

function GetIso($str='')
{
  if ( empty($str) ) { $str=$_SESSION[QT]['language']; }
  switch(strtolower($str))
  {
  case 'english': return 'en'; break;
  case 'francais': return 'fr'; break;
  case 'nederlands': return 'nl'; break;
  case 'italiano': return 'it'; break;
  case 'espanol': return 'es'; break;
  default: include('bin/qtg_lang.php'); $arr=array_flip(QTarrget($arrLang,2)); if ( isset($arr[$str]) ) return $arr[$str]; break;
  }
  return 'en';
}

// --------

function GetLang($str='')
{
  if ( empty($str) ) { return 'language/'.$_SESSION[QT]['language'].'/'; }
  return 'language/'.$str.'/';
}

// --------

function Href($str='qtg_index.php')
{
  // When urlrewriting is active, the url can be displayed in html format (they will be converted by the server's rewrite rule).
  // This function transforms a php url into a html like url (the url can have arguments): 'qtg_login.php' is displayed as 'login.html'.
  // Note: Don't worry, server's rewriting has NO effect when the url is in php format (i.e. when this function is not used or when QTG_URLREWRITE is FALSE)
  if ( empty($str) ) die('Href: Missing url');
  if ( QTG_URLREWRITE ) {
  if ( substr($str,0,4)=='qtg_' && strstr($str,'.php') ) {
    $str = substr($str,4);
    $str = str_replace('.php','.html',$str);
  }}
  return $str;
}

// --------

function HtmlRedirect($u='qtg_index.php',$s='Continue')
{

if ( headers_sent() )
{
echo '<a href="'.$u.'">',$s,'</a><meta http-equiv="REFRESH" content="0;url='.$u.'">';
}
else
{
header('Location: '.str_replace('&amp;','&',$u));
}
exit;

}

// --------

//  Returns the plural (if $intVal>1 and if the plural word exists)
//  The variable $strVar can be composed of 2 strings (comma separated): LangS['userrole,A',25] returns $L['Userroles']['A']
//  $bInclude=true will returns number + space + the word

function LangS($strVar,$intVar,$bInclude=true)
{  
  global $L;
  if ( !strstr($strVar,',') )
  {
    if ( !isset($L[$strVar]) ) return ($bInclude ? $intVar.' ' : '').$strVar;
    if ( $intVar>1 && isset($L[$strVar.'s']) ) return ($bInclude ? $intVar.' ' : '').$L[$strVar.'s'];
    return ($bInclude ? $intVar.' ' : '').$L[$strVar];
  }
  else
  {
    $arr = explode(',',$strVar);
    if ( !isset($L[$arr[0]][$arr[1]]) ) return ($bInclude ? $intVar.' ' : '').$strVar;
    if ( $intVar>1 && isset($L[$arr[0].'s'][$arr[1]]) ) return ($bInclude ? $intVar.' ' : '').$L[$arr[0].'s'][$arr[1]];
    return ($bInclude ? $intVar.' ' : '').$L[$arr[0]][$arr[1]];    
  }
}

// --------

function LimitSQL($dbtype,$strState,$strOrder,$intStart=0,$intLength=50,$intCount=50)
{
  $strOrder = trim($strOrder); if ( substr($strOrder,-3,3)!='ASC' && substr($strOrder,-4,4)!='DESC' ) $strOrder .= ' ASC';
  switch ($dbtype)
  {
  case 'mysql4':
    return "SELECT $strState ORDER BY $strOrder LIMIT $intStart,$intLength";
    break;
  case 'mysql':
    return "SELECT $strState ORDER BY $strOrder LIMIT $intStart,$intLength";
    break;
  case 'mssql':
    if ($intStart==0)
    {
      $query = "SELECT TOP $intLength $strState ORDER BY $strOrder";
    }
    elseif ( ($intLength+$intStart)>$intCount )
    {
      $strInvor = $strOrder;
      if ( substr($strOrder,-4,4)==' ASC' ) $strInvor=str_replace(' ASC',' DESC',$strOrder);
      if ( substr($strOrder,-4,4)=='DESC' ) $strInvor=str_replace(' DESC',' ASC',$strOrder);
      $intLast = $intCount-$intStart;
      $query = "SELECT TOP $intLast $strState ORDER BY $strInvor";
      $strOrder = str_replace('t.','',$strOrder); // to support t1,t2
      $strInvor = str_replace('t.','',$strInvor); // to support t1,t2
      $query = "SELECT * FROM ($query) As t1 ORDER BY $strOrder";
    }
    else
    {
      $strInvor = $strOrder;
      if ( substr($strOrder,-4,4)==' ASC' ) $strInvor=str_replace(' ASC',' DESC',$strOrder);
      if ( substr($strOrder,-4,4)=='DESC' ) $strInvor=str_replace(' DESC',' ASC',$strOrder);
      $invlength = $intLength+$intStart;
      $query = "SELECT TOP $invlength $strState ORDER BY $strOrder";
      $strOrder = str_replace('t.','',$strOrder); // to support t1,t2
      $strInvor = str_replace('t.','',$strInvor); // to support t1,t2
      $query = "SELECT * FROM (SELECT TOP $intLength * FROM ($query) As t1 ORDER BY $strInvor) As t2 ORDER BY $strOrder";
    }
    return $query;
    break;
  case 'pg':
    return "SELECT $strState ORDER BY $strOrder LIMIT $intLength OFFSET $intStart";
    break;
  case 'ibase':
    return "SELECT FIRST $intLength SKIP $intStart $strState ORDER BY $strOrder";
    break;
  case 'sqlite':
    return "SELECT $strState ORDER BY $strOrder LIMIT $intLength OFFSET $intStart";
    break;
  case 'db2':
    if ($intStart==0)
    {
      return "SELECT $strState ORDER BY $strOrder FETCH FIRST $intLength ROWS ONLY";
    }
    else
    {
      return "SELECT * FROM (SELECT ROW_NUMBER() OVER() AS RN, $strState) AS cols WHERE RN BETWEEN ($intStart+1) AND ($intStart+1+$intLength)";
    }
    break;
  case 'oci':
    if ($intStart==0)
    {
      return "SELECT * FROM (SELECT $strState ORDER BY $strOrder) WHERE ROWNUM<=$intLength";
    }
    else
    {
      return "SELECT * FROM (SELECT a.*, rownum RN FROM (SELECT $strState ORDER BY $strOrder) a WHERE rownum<$intStart+1+$intLength) WHERE rn>$intStart";
    }
    break;
  default: die('Unknown db type '.$dbtype);
  }
}

// --------

function MakePager($strUri,$intRows,$intSize=50,$intPage=1)
{
  // $strUri full url (with arguments)
  // $intRows total number of rows
  // $intSize number of rows per page
  // $intPage current page

  global $L;
  $arrUri = parse_url($strUri);
  $strUri = $arrUri['path'];
  $strArg = '';
  if ( isset($arrUri['query']) ) $strArg = QTargimplode( QTarradd(QTargexplode($arrUri['query']),'page',null) ); // remove the 'page' argument
  $strPager='';
  if ( $intRows>($intSize*5) )
  {
    // firstpage
    if ( $intPage==1 )
    {
      $strFirstpage = ' &laquo;';
    }
    else
    {
      $strFirstpage = ' <a class="pager" href="'.$strUri.'?'.(empty($strArg) ? '' : $strArg.'&amp;').'page=1" title="'.$L['First'].'">&laquo;</a>';
    }
    // lastpage
    $intLastpage = ceil($intRows/$intSize);
    if ( $intPage==$intLastpage )
    {
      $strLastpage = ' &raquo;';
    }
    else
    {
      $strLastpage = ' <a class="pager" href="'.$strUri.'?'.(empty($strArg) ? '' : $strArg.'&amp;').'page='.$intLastpage.'" title="'.$L['Last'].': '.$intLastpage.'">&raquo;</a>';
    }
    // 3 pages
    if ( $intPage==1 )
    {
       $strThesepages = ' <span class="pager">'.$intPage.'</span> <a class="pager" href="'.$strUri.'?'.(empty($strArg) ? '' : $strArg.'&amp;').'page='.($intPage+1).'" title="'.$L['Next'].'">'.($intPage+1).'</a> <a class="pager" href="'.$strUri.'?'.(empty($strArg) ? '' : $strArg.'&amp;').'page='.($intPage+2).'" title="'.$L['Next'].'">'.($intPage+2).'</a>';
    }
    elseif ( $intPage==$intLastpage )
    {
       $strThesepages = ' <a class="pager" href="'.$strUri.'?'.(empty($strArg) ? '' : $strArg.'&amp;').'page='.($intPage-2).'" title="'.$L['Previous'].'">'.($intPage-2).'</a> <a class="pager" href="'.$strUri.'?'.(empty($strArg) ? '' : $strArg.'&amp;').'page='.($intPage-1).'" title="'.$L['Previous'].'">'.($intPage-1).'</a> <span class="pager">'.$intPage.'</span> ';
    }
    else
    {
       $strThesepages = ' <a class="pager" href="'.$strUri.'?'.(empty($strArg) ? '' : $strArg.'&amp;').'page='.($intPage-1).'" title="'.$L['Previous'].'">'.($intPage-1).'</a> <span class="pager">'.$intPage.'</span> <a class="pager" href="'.$strUri.'?'.(empty($strArg) ? '' : $strArg.'&amp;').'page='.($intPage+1).'" title="'.$L['Next'].'">'.($intPage+1).'</a>';
    }
    // finish
    $strPager .= $strFirstpage.$strThesepages.$strLastpage;
  }
  elseif ($intRows>$intSize)
  {
    for($i=0;$i<$intRows;$i+=$intSize)
    {
      $p = $i/$intSize+1;
      if ( $intPage==$p )
      {
        $strPager .= ' <span class="pager">'.$p.'</span>';
      }
      else
      {
        $strPager .= ' <a class="pager" href="'.$strUri.'?'.(empty($strArg) ? '' : $strArg.'&amp;').'page='.$p.'">'.$p.'</a>';
      }
    }
  }
  return $strPager;
}

// --------

function LastPostDelayAcceptable($qtg_max_sec=5)
{
  if ( isset($_SESSION['qtg_beginedit']) ) {
  if ( !empty($_SESSION['qtg_beginedit']) ) {
    if ( $_SESSION['qtg_beginedit']+$qtg_max_sec >= time() ) return FALSE;
  }}
  return TRUE;
}

// --------

function TooMuch($qtg_max_day=5)
{
  global $oDB;
  $now = date('Ymd'); // to avoid having different date() inside this function (if response-time is long), we lock the date argument 

  if ( is_a($oDB,'cDT') )
  {
    // search this ip only in the directory of this month
    $arr = $oDB->GetFiles($_SERVER['REMOTE_ADDR'],$qtg_max_day+1,substr($now,0,6),substr($now,0,6));
    if (count($arr)<=$qtg_max_day) return FALSE;
    // search further for this date only
    $i=0;
    foreach($arr as $str)
    {
    if ( substr($str,0,8)==$now ) $i++;
    if ( $i>=$qtg_max_day ) return TRUE;
    }
  }
  else
  {
    switch(substr($oDB->type,0,5))
    {
    case 'mysql':$oDB->Query( 'SELECT count(id) as countid FROM '.TABMESSAGE.' WHERE ip="'.$_SERVER['REMOTE_ADDR'].'" AND SUBSTRING(issuedate,1,8)="'.$now.'"' ); break;
    case 'mssql':$oDB->Query( 'SELECT count(id) as countid FROM '.TABMESSAGE.' WHERE ip="'.$_SERVER['REMOTE_ADDR'].'" AND SUBSTRING(issuedate,1,8)="'.$now.'"' ); break;
    case 'pg':   $oDB->Query( 'SELECT count(id) as countid FROM '.TABMESSAGE.' WHERE ip="'.$_SERVER['REMOTE_ADDR'].'" AND SUBSTRING(issuedate,1,8)="'.$now.'"' ); break;
    case 'ibase':$oDB->Query( 'SELECT count(id) as countid FROM '.TABMESSAGE.' WHERE ip="'.$_SERVER['REMOTE_ADDR'].'" AND SUBSTRING(issuedate,1,8)="'.$now.'"' ); break;
    case 'sqlit':$oDB->Query( 'SELECT count(id) as countid FROM '.TABMESSAGE.' WHERE ip="'.$_SERVER['REMOTE_ADDR'].'" AND SUBSTR(issuedate,1,8)="'.$now.'"' ); break;
    case 'db2':  $oDB->Query( 'SELECT count(id) as countid FROM '.TABMESSAGE.' WHERE ip="'.$_SERVER['REMOTE_ADDR'].'" AND SUBSTR(issuedate,1,8)="'.$now.'"' ); break;
    case 'oci':  $oDB->Query( 'SELECT count(id) as countid FROM '.TABMESSAGE.' WHERE ip="'.$_SERVER['REMOTE_ADDR'].'" AND SUBSTR(issuedate,1,8)="'.$now.'"' ); break;
    default: die('Unknown db type '.$oDB->type);
    }
    $row = $oDB->Getrow();
    if ($row['countid']>=$qtg_max_day) Return TRUE;
  }
  return FALSE;
}

// --------

function IQTbbc($oPost,$nl='<br/>',$maxlen=0, $beforediv='', $afterdiv='',$skin='skin/default',$page=0,$bTruncatelink=true)
{  
  $strMsg = $oPost->message;
  $intMsg = strlen($strMsg);
  $bTruncated=false; 

  global $qtg_bbctags,$L;
  
  // STRIP TAGS (if '<' exists)
  
  if ( strpos($strMsg,'<')!==FALSE ) $strMsg=strip_tags($strMsg);
  
  // DROP UNALLOWED BBC TAGS (if '[' exists)

  if ( strpos($strMsg,'[')!==FALSE )
  {
    if ( !$qtg_bbctags['B'] ) $strMsg = preg_replace("/\[b\](.*?)\[\/b\]/","\$1", $strMsg);
    if ( !$qtg_bbctags['I'] ) $strMsg = preg_replace("/\[i\](.*?)\[\/i\]/","\$1", $strMsg);
    if ( !$qtg_bbctags['U'] ) $strMsg = preg_replace("/\[u\](.*?)\[\/u\]/","\$1", $strMsg);
    if ( !$qtg_bbctags['A'] ) $strMsg = preg_replace("/\[url\](.*?)\[\/url\]/","\$1", $strMsg);
    if ( !$qtg_bbctags['S'] ) $strMsg = preg_replace("/\[:(.*?)\]/","", $strMsg);
    // Some more unallowed tags
    if ( strpos($strMsg,'[')!==FALSE ) $strMsg = preg_replace( array ("/\[color\=(.*?)\](.*?)\[\/color\]/",  "/\[size=(.*?)\](.*?)\[\/size\]/", "/\[quote\]/", "/\[quote\=(.*?)\]/", "/\[\/quote\]/", "/\[code\]/", "/\[\/code\]/"), array('','','','','','',''), $strMsg );
  }

  // TRUNCATE (if long message)

  if ( is_numeric($maxlen) ) {
  if ( $maxlen>0 ) {
  if ( $intMsg>$maxlen ) {
    // smart-cutting
    if ( QT_SMARTCUT>0 )
    {
      // don't cut if within smartcut tolerance
      if ( $intMsg>$maxlen+QT_SMARTCUT )
      {
        // if some caracters are at the cut-position, cut after
        switch (substr($strMsg,$maxlen,1))
        {
        case ']': $maxlen++; break;
        case '.': $maxlen++; break;
        case ',': $maxlen++; break;
        case ':': $maxlen++; break;
        case '!': $maxlen++; break;
        case '?': $maxlen++; break;
        case ')': $maxlen++; break;
        case ';': $maxlen++; break;
        case '}': $maxlen++; break;
        }
        // cut
        $strMsg=substr($strMsg,0,$maxlen);
        $bTruncated=true;
      }
    }
    else
    {
      // strict-cutting (smartcut==0)
      $strMsg=substr($strMsg,0,$maxlen);
      $bTruncated=true;
    }
  }}}
  
  
  // FORMAT THE MESSAGE
  
  $strMsg = QTbbc($strMsg,$nl);

  // FORMAT THE SMILEY (if exists and allowed)

  if ( strpos($strMsg,'[')!==FALSE ) {
  if ( $qtg_bbctags['S'] ) {
    $strMsg = str_replace(
    array
    (
    '[:)]','[:(]','[:|]','[;)]','[:t]','[:o]','[:?]','[:!]','[:*]'
    ),
    array
    (
    '<img class="smile" src="'.$skin.'/ico_smile_01.gif" alt="[:)]" title="'.$L['Ico_smile01'].'"/>',
    '<img class="smile" src="'.$skin.'/ico_smile_02.gif" alt="[:(]" title="'.$L['Ico_smile02'].'"/>',
    '<img class="smile" src="'.$skin.'/ico_smile_03.gif" alt="[:|]" title="'.$L['Ico_smile03'].'"/>',
    '<img class="smile" src="'.$skin.'/ico_smile_04.gif" alt="[;)]" title="'.$L['Ico_smile04'].'"/>',
    '<img class="smile" src="'.$skin.'/ico_smile_05.gif" alt="[:t]" title="'.$L['Ico_smile05'].'"/>',
    '<img class="smile" src="'.$skin.'/ico_smile_06.gif" alt="[:o]" title="'.$L['Ico_smile06'].'"/>',
    '<img class="smile" src="'.$skin.'/ico_smile_07.gif" alt="[:?]" title="'.$L['Ico_smile07'].'"/>',
    '<img class="smile" src="'.$skin.'/ico_smile_08.gif" alt="[:!]" title="'.$L['Ico_smile08'].'"/>',
    '<img class="smile" src="'.$skin.'/ico_smile_09.gif" alt="[:*]" title="'.$L['Ico_smile09'].'"/>',
    ),
    $strMsg);
  }}
  
  // ADD '[More]' TO THE TEXT (if truncation has occurs)
  
  if ( $bTruncated ) $strMsg .= ($bTruncatelink ? ' <a href="'.Href('qtg_msg_view.php').'?id='.$oPost->id.'&amp;page='.$page.'">'.$L['More'].'</a>' : ' [...]');
  
  return $strMsg;
}

// ---------

function PrevMonth($str)
{
  if ( is_int($str) ) $str=strval($str);
  if ( !is_string($str) ) die('PrevMonth: arg #1 must be a string');
  
  $y = intval(substr($str,0,4));
  $m = intval(substr($str,4,2));
  $m--; if ( $m<1 ) { $m=12; $y--; }
  return strval($y*100+$m);
}

?>
Return current item: Quick Guestbook