<?php
/*
--------------------------------------------------------------------------------
PhpDig 1.6.x
This program is provided under the GNU/GPL license.
See LICENSE file for more informations
All contributors are listed in the CREDITS file provided with this package

PhpDig Website : http://phpdig.toiletoine.net/
Contact email : phpdig@toiletoine.net
Author and main maintainer : Antoine Bajolet (fr) bajolet@toiletoine.net
--------------------------------------------------------------------------------
*/

//-------------UTILS FUNCTIONS

//=================================================
// extract _POST or _GET variables from a list varname => vartype
// Useful for error_reporting E_ALL too, init variables
// usage in script : extract(phpdigHttpVars(array('foobar'=>'string')));
function phpdigHttpVars($varray=array()) {
$parse_orders = array('_POST','_GET','HTTP_POST_VARS','HTTP_GET_VARS');
$httpvars = array();
// extract the right array
if (is_array($varray)) {
    foreach($parse_orders as $globname) {
          global $$globname;
          if (!count($httpvars) && isset($$globname) && is_array($$globname)) {
              $httpvars = $$globname;
          }
    }
    // extract or create requested vars
    foreach($varray as $varname => $vartype) {
       if (in_array($vartype,array('integer','bool','double','float','string','array')) ) {
         if (!isset($httpvars[$varname])) {
            if (!isset($GLOBALS[$varname])) {
                 $httpvars[$varname] = false;
            }
            else {
                 $httpvars[$varname] = $GLOBALS[$varname];
            }
         }
         settype($httpvars[$varname],$vartype);
       }
    }
return $httpvars;
}
}

//=================================================
// timer for profiling
class phpdigTimer {
      var $time = 0;
      var $mode = '';
      var $marks = array();
      var $template = '';

      function phpdigTimer($mode='html') {
           $this->time = $this->getTime();
           if ($mode == 'cli') {
               $this->template = "%s:\t%0.9f s. \n";
           }
           else {
               $this->template = "<tr><td class=\"greyForm\">%s</td><td class=\"greyForm\">%0.9f s. </td></tr>\n";
           }
      }
      function start($name) {
           if (!isset($this->marks[$name])) {
               $this->marks[$name]['time'] = $this->getTime();
               $this->marks[$name]['stat'] = 'r';
           }
           else if ($this->marks[$name]['stat'] == 's') {
               $this->marks[$name]['time'] = $this->getTime()-$this->marks[$name]['time'];
               $this->marks[$name]['stat'] = 'r';
           }
      }
      function stop($name) {
           if (isset($this->marks[$name]) && $this->marks[$name]['stat'] == 'r') {
               $this->marks[$name]['time'] = $this->getTime()-$this->marks[$name]['time'];
           }
           else {
               $this->marks[$name]['time'] = 0;
           }
           $this->marks[$name]['stat'] = 's';
      }
      function display() {
           if ($this->mode != 'cli') {
               print "<table class=\"borderCollapse\"><tr><td class=\"blueForm\">Mark</td><td class=\"blueForm\">Value</td></tr>\n";
           }
           foreach($this->marks as $name => $value) {
                printf($this->template,ucwords($name),$value['time']);
           }
           if ($this->mode != 'cli') {
               print "</table>\n";
           }
      }
      // increase precision with deltime
      function getTime() {
          return array_sum(explode(' ',microtime()))-$this->time;
      }
}

//-------------STRING FUNCTIONS

//=================================================
//returns a localized string
function phpdigMsg($string='') {
global $phpdig_mess;
if (isset($phpdig_mess[$string])) {
    return nl2br($phpdig_mess[$string]);
}
else {
    return ucfirst($string);
}
}

//print a localized string
function phpdigPrnMsg($string='')
{
global $phpdig_mess;
if (isset($phpdig_mess[$string])) {
    print nl2br($phpdig_mess[$string]);
}
else {
    print ucfirst($string);
}
}

//=================================================
//load the common words in an array
function phpdigComWords($file='')
{
$lines = @file($file);
if (is_array($lines))
    {
    while (list($id,$word) = each($lines))
           $common[trim($word)] = 1;
    }
else
    $common['aaaa'] = 1;
return $common;
}

//=================================================
//highlight a string part
function phpdigHighlight($ereg='',$string='')
{
if ($ereg)
    return @eregi_replace($ereg,"\\1<span class=\"phpdigHighlight\">\\2</span>\\3",$string);
else
    return $result;
}

//=================================================
//replace all characters with an accent
function phpdigStripAccents($chaine) {
$chaine = str_replace('Æ','ae',str_replace('æ','ae',$chaine));
return( strtr( $chaine,
"ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ",
"AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn" ) );
}

//==========================================
//Create a ereg for highlighting
function phpdigPregQuotes($chaine)
{
$chaine = preg_quote(strtolower(phpdigStripAccents($chaine)));
$chaine = str_replace('e','[eÈÉÊËèéêë]',$chaine);
$chaine = str_replace('i','[iÌÍÎÏìíîï]',$chaine);
$chaine = str_replace('u','[uÙÚÛÜùúûü]',$chaine);
$chaine = str_replace('o','[oÒÓÔÕÖØòóôõöø]',$chaine);
$chaine = str_replace('a','[aÀÁÂÃÄÅàáâãäå]',$chaine);
$chaine = str_replace('c','[cçÇ]',$chaine);
$chaine = str_replace('n','[nÑñ]',$chaine);
return  str_replace('y','[yÿ]',$chaine);
}

//=================================================
//epure a string from all non alnum words (words can contain &__&ßðþ character)
function phpdigEpureText($text,$min_word_length=2)
{
$text = phpdigStripAccents(strtolower ($text));
//no-latin upper to lowercase - now islandic
$text = strtr( $text,
'ÐÞ',
'ðþ');
$text = ereg_replace('[[:blank:]][0-9]+[[:blank:]]',' ',ereg_replace('[^[:alnum:]ðþ._&ß%/-]+',' ',$text));
$text = ereg_replace('[[:blank:]][^ ]{1,'.$min_word_length.'}[[:blank:]]',' ',' '.$text.' ');
$text = ereg_replace('\.+[[:blank:]]|\.+$|\.{2,}',' ',$text);
return trim(ereg_replace("[[:blank:]]+"," ",$text));
}

//-------------SQL FUNCTIONS

//=================================================
//insert an entry in logs
function phpdigAddLog ($id_connect,$option='start',$includes=array(),$excludes=array(),$num_results=0,$time=0) {
    if (!is_array($excludes)) {
         $excludes = array();
    }
    sort($excludes);
    if (!is_array($includes)) {
         $includes = array();
    }
    sort($includes);
    $query = 'INSERT INTO '.PHPDIG_DB_PREFIX.'logs (l_num,l_mode,l_ts,l_includes,l_excludes,l_time) '
             .'VALUES ('.$num_results.',\''.substr($option,0,1).'\',NOW(),'
             .'\''.implode(' ',$includes).'\',\''.implode(' ',$excludes).'\','.(double)$time.')';
    mysql_query($query,$id_connect);
    return mysql_insert_id($id_connect);
}

?>