phpDocumentor lodel
[ class tree: lodel ] [ index: lodel ] [ all elements ]

Source for file func.php

Documentation is available at func.php

  1. <?php
  2. /**
  3.  * Fichier utilitaire proposant des fonctions souvent utilisées dans Lodel
  4.  *
  5.  * PHP versions 4 et 5
  6.  *
  7.  * LODEL - Logiciel d'Edition ELectronique.
  8.  *
  9.  * Copyright (c) 2001-2002, Ghislain Picard, Marin Dacos
  10.  * Copyright (c) 2003, Ghislain Picard, Marin Dacos, Luc Santeramo, Nicolas Nutten, Anne Gentil-Beccot
  11.  * Copyright (c) 2004, Ghislain Picard, Marin Dacos, Luc Santeramo, Anne Gentil-Beccot, Bruno Cénou
  12.  * Copyright (c) 2005, Ghislain Picard, Marin Dacos, Luc Santeramo, Gautier Poupeau, Jean Lamy, Bruno Cénou
  13.  * Copyright (c) 2006, Marin Dacos, Luc Santeramo, Bruno Cénou, Jean Lamy, Mikaël Cixous, Sophie Malafosse
  14.  * Copyright (c) 2007, Marin Dacos, Bruno Cénou, Sophie Malafosse, Pierre-Alain Mignot
  15.  *
  16.  * Home page: http://www.lodel.org
  17.  *
  18.  * E-Mail: lodel@lodel.org
  19.  *
  20.  * All Rights Reserved
  21.  *
  22.  * This program is free software; you can redistribute it and/or modify
  23.  * it under the terms of the GNU General Public License as published by
  24.  * the Free Software Foundation; either version 2 of the License, or
  25.  * (at your option) any later version.
  26.  *
  27.  * This program is distributed in the hope that it will be useful,
  28.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  29.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  30.  * GNU General Public License for more details.
  31.  *
  32.  * You should have received a copy of the GNU General Public License
  33.  * along with this program; if not, write to the Free Software
  34.  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  35.  *
  36.  * @author Ghislain Picard
  37.  * @author Jean Lamy
  38.  * @author Sophie Malafosse
  39.  * @author Pierre-Alain Mignot
  40.  * @copyright 2005, Ghislain Picard, Marin Dacos, Luc Santeramo, Gautier Poupeau, Jean Lamy, Bruno Cénou
  41.  * @copyright 2006, Marin Dacos, Luc Santeramo, Bruno Cénou, Jean Lamy, Mikaël Cixous, Sophie Malafosse
  42.  * @copyright 2007, Marin Dacos, Bruno Cénou, Sophie Malafosse, Pierre-Alain Mignot
  43.  * @licence http://www.gnu.org/copyleft/gpl.html
  44.  * @version CVS:$Id:
  45.  * @package lodel
  46.  */
  47.  
  48.  
  49. function writefile ($filename,$text)
  50. {
  51. # echo "name de fichier : $filename";
  52.    if (file_exists($filename)) 
  53.      if ((unlink($filename)) ) die ("Ne peut pas supprimer $filenameprobleme de right contacter Luc ou Ghislain");
  54.    }
  55.   $ret=($f=fopen($filename,"w")) && (fputs($f,$text)!==false&& fclose($f);
  56.    
  57.   @chmod ($filename,0666 octdec($GLOBALS['filemask']));
  58.   return  $ret;
  59. }
  60.  
  61.  
  62. function postprocessing(&$context)
  63.  
  64. {
  65.   if ($context{
  66.     foreach($context as $key=>$val{
  67.       if (is_array($val)) {
  68.     postprocessing($context[$key]);
  69.       else {
  70.     $context[$key]=str_replace(array("\n","Â\240"),array(" ","&nbsp;"),$val);
  71.       }
  72.     }
  73.   }
  74. }
  75.  
  76.  
  77.  
  78. /**
  79.  *   Extrait toutes les variables passées par la méthode post puis les stocke dans
  80.  *   le tableau $context
  81.  */
  82. function extract_post($arr=-1)
  83. {
  84.   if (!is_array($arr)) $arr=&$_POST;
  85.   foreach ($arr as $key=>$val{
  86.  
  87.     if (!isset($GLOBALS['context'][$key])) // protege
  88.       $GLOBALS['context'][$key$val;
  89.   }
  90.   array_walk($GLOBALS['context'],"clean_request_variable");
  91.  
  92. }
  93.  
  94.  
  95. function clean_request_variable(&$var)
  96. {
  97.     static $filter;
  98.     if (!$filter{
  99.         require_once 'class.inputfilter.php';
  100.         $filter new InputFilter(array()array()11);
  101.       }
  102.  
  103.     if (is_array($var)) {
  104.         #print_r($var);
  105.         foreach(array_keys($varas $k{
  106.             clean_request_variable($var[$k]);
  107.         }
  108.     else {
  109.         $var magic_stripslashes($var);
  110.         //ici on regle un bug : lors qu'on insere un espace insécable, l'appel à la fonction PHP 'chr' plante sur le &#160; dans la fonction $filter->decode
  111.         if(preg_match("`&#160;`me"$var))
  112.             $var str_replace("&#160;""&nbsp;"$var);
  113.         $var $filter->process(trim($var));
  114.         // le process nettoie un peu trop : remplace les br fermés par des br ouverts : document plus valide..
  115.         $var str_replace("<br>""<br />"$var);
  116.         $var str_replace(array("\n""&nbsp;")array("""Â\240")$var);
  117.       }
  118. }
  119.  
  120. function magic_addslashes($var
  121. {
  122.     /*if (!get_magic_quotes_gpc()) {
  123.         $var = addslashes($var);
  124.     }*/
  125.     $var stripslashes($var);
  126.     $var addslashes($var);
  127.     return $var;
  128. }
  129.  
  130. function magic_stripslashes($var
  131. {
  132.     if (get_magic_quotes_gpc()) {
  133.         $var stripslashes($var);
  134.     }
  135.     return $var;
  136. }
  137.  
  138.  
  139. function get_max_rank ($table,$where=""
  140. {
  141.   if ($where$where="WHERE ".$where;
  142.  
  143.   #require_once ($GLOBALS[home]."connect.php");
  144.   $rank=$db->getone("SELECT MAX(rankFROM #_TP_$table $where");
  145.   if ($db->errorno()) dberror();
  146.  
  147.   return $rank+1;
  148. }
  149.  
  150. function chrank($table,$id,$critere,$dir,$inverse="",$jointables="")
  151. {
  152.   global $db;
  153.  
  154.   $table="#_TP_$table";
  155.   $dir=$dir=="up" ? -1;  if ($inverse$dir=-$dir;
  156.   $desc=$dir>"" "DESC";
  157.   if ($jointables{
  158.     $jointables=",#_TP_".
  159.       trim(join(",#_TP_",preg_split("/,\s*/",$jointables)));
  160.   }
  161.   $result=$db->execute(lq("SELECT $table.id,$table.rank FROM $table $jointables WHERE $critere ORDER BY $table.rank $desc")) or dberror();
  162.  
  163.   $rank=$dir>mysql_num_rows($result);
  164.  
  165.   while ($row=$result->fetchrow($result)) {
  166.     if ($row['id']==$id{
  167.       # intervertit avec le suivant s il existe
  168.       if (!($row2=$result->fetchrow($result))) break;
  169.       $db->execute(lq("UPDATE $table SET rank='$rankWHERE id='$row2[id]'")) or dberror();
  170.       $rank+=$dir;
  171.     }
  172.     if ($row['rank']!=$rank{
  173.       $db->execute(lq("UPDATE $table SET rank='$rankWHERE id='$row[id]'")) or dberror();
  174.     }
  175.     $rank+=$dir;
  176.   }
  177.  
  178.  
  179. /**
  180.  * function returning the closing tag corresponding to the opening tag in the sequence
  181.  * this function could be smarter.
  182.  */
  183. function closetags($text)
  184. {
  185.     preg_match_all("/<(\w+)\b[^>]*>/",$text,$results,PREG_PATTERN_ORDER);
  186.     $n=count($results[1]);
  187.     for($i=$n-1$i>=0$i--$ret.="</".$results[1][$i].">";
  188.     return $ret;
  189. }
  190.  
  191.  
  192. function myaddslashes (&$var)
  193. {
  194.   if (is_array($var)) {
  195.     array_walk($var,"myaddslashes");
  196.     return $var;
  197.   else {
  198.     return $var=addslashes($var);
  199.   }
  200. }
  201.  
  202.  
  203.  
  204. /**
  205.  * Fonction permettant de vérifier l'existence d'un fichier correctement !
  206.  *
  207.  * @param string $file fichier à tester
  208. */
  209. function myfileexists($file{
  210.     // plus important : on supprime  le cache généré par les fonctions de stat de fichier !
  211.     clearstatcache();
  212.     return file_exists($file)// on retourne le test du fichier
  213. }
  214.  
  215. /**
  216.  * Retourne la dernière date de modif de $filename
  217.  *
  218.  * @param string $filename fichier à tester
  219. */
  220. function myfilemtime($filename)
  221. {
  222.   return myfileexists($filename@filemtime($filename0;
  223. }
  224.  
  225.  
  226. function update()
  227. {
  228.     require_once 'cachefunc.php';
  229.     clearcache(false);
  230. }
  231.  
  232. function addmeta(&$arr,$meta="")
  233. {
  234.     foreach ($arr as $k=>$v{
  235.         if (strpos($k,"meta_")===0{
  236.             if (!isset($metaarr)) // cree le hash des meta
  237.         $metaarr=$meta unserialize($metaarray();
  238.             }
  239.             if ($v{
  240.     $metaarr[$k]=$v;
  241.             else {
  242.     unset($metaarr[$k]);
  243.             }
  244.         }
  245.     }
  246.     return $metaarr serialize($metaarr$meta;
  247. }
  248.  
  249.  
  250.  
  251. function translate_xmldata($data
  252. {
  253.     return strtr($data,array("&"=>"&amp;","<" => "&lt;"">" => "&gt;"));
  254. }
  255.  
  256.  
  257. ### use the transaction now.
  258. function unlock()
  259. {
  260.     global $db;
  261.     // Déverrouille toutes les tables verrouillées
  262.     // fonction lock_write()
  263.     if (!defined("DONTUSELOCKTABLES"|| !DONTUSELOCKTABLES{
  264.         $db->execute(lq("UNLOCK TABLES")) or dberror();
  265.     }
  266. }
  267.  
  268.  
  269. function lock_write()
  270. {
  271.     global $db;
  272.   // Verrouille toutes les tables MySQL en écriture
  273.   $list func_get_args();
  274.     if (!defined("DONTUSELOCKTABLES"|| !DONTUSELOCKTABLES)
  275.         $db->execute(lq("LOCK TABLES #_MTP_"join (" WRITE ,"."#_MTP_"$list)." WRITE")) or dberror();
  276. }
  277.  
  278. function prefix_keys($prefix,$arr)
  279. {
  280.     if (!$arr{
  281.         return $arr;
  282.     }
  283.     foreach ($arr as $k=>$v{
  284.         $outarr[$prefix.$k]=$v;
  285.     }
  286.     return $outarr;
  287. }
  288.  
  289. function array_merge_withprefix($arr1,$prefix,$arr2)
  290. {
  291.     if (!$arr2{
  292.         return $arr1;
  293.     }
  294.     foreach ($arr2 as $k=>$v{
  295.         $arr1[$prefix.$k]=$v;
  296.     }
  297.     return $arr1;
  298. }
  299.  
  300. function getoption($name)
  301. {
  302.     global $db;
  303.     static $options_cache;
  304.     if (!$namereturn;
  305.     if (!isset($options_cache)) {
  306.         $optionsfile=SITEROOT."CACHE/options_cache.php";
  307.     
  308.         if (file_exists($optionsfile)) {
  309.             require($optionsfile);
  310.         else {
  311.             require_once('optionfunc.php');
  312.             $options_cache cacheOptionsInFile($optionsfile);
  313.         }
  314.     }
  315.     if (is_array($name)) {
  316.         foreach ($name as $n{
  317.             if ($options_cache[$n]$ret[$n]=stripslashes($options_cache[$n]);
  318.         }    
  319.         return  ($ret);
  320.     else {
  321.         if ($options_cache[$name]// cached ?
  322.             return  stripslashes ($options_cache[$name]);
  323.         $critere="name='$name'";
  324.     }
  325. }
  326.  
  327. function getlodeltext($name,$group,&$id,&$contents,&$status,$lang=-1)
  328. {
  329.     
  330.     if ($group==""{
  331.         if ($name[0]!='[' && $name[1]!='@'return array(0,$name);
  332.         $dotpos=strpos($name,".");
  333.         if ($dotpos{
  334.             $group=substr($name,1,$dotpos)
  335.             $name=substr($name,$dotpos+1,-1);
  336.         else {
  337.             die("ERROR: unknow group for getlodeltext");
  338.         }
  339.     }
  340.     if ($lang==-1$lang=$GLOBALS['lang'$GLOBALS['lang'$GLOBALS['lodeluser']['lang'];
  341.     if (!$lang$lang $GLOBALS['installlang']// if no lang is specified choose the default installation language
  342.     require_once("connect.php");
  343.     global $db;
  344.     
  345.     if ($group!="site"{
  346.         usemaindb();
  347.         $prefix="#_MTP_";
  348.     else {
  349.         $prefix="#_TP_";
  350.     }
  351.     
  352.     $critere=$GLOBALS['lodeluser']['visitor'"" "AND status>0";
  353.     $logic=false;
  354.     do {
  355.         $arr=$db->getRow("SELECT id,contents,status FROM ".lq($prefix)."texts WHERE name='".$name."' AND textgroup='".$group."AND (lang='$langOR lang='') $critere ORDER BY lang DESC");
  356.         if ($arr===falsedberror();
  357.         if (!$GLOBALS['lodeluser']['admin'|| $logicbreak;
  358.         
  359.         if (!$arr{
  360.             
  361.             // create the textfield
  362.             require_once("logic.php");
  363.             $logic=getLogic("texts");
  364.             $logic->createTexts($name,$group);
  365.         }
  366.     while(!$arr);
  367.     
  368.     if ($group!="site"usecurrentdb();
  369.     
  370.     $id=$arr['id'];
  371.     $contents=$arr['contents'];
  372.     $status=$arr['status'];
  373.     if (!$contents && $GLOBALS['lodeluser']['visitor']$contents="@".$name;
  374. }
  375.  
  376. function getlodeltextcontents($name,$group="",$lang=-1)
  377. {
  378.     if ($lang==-1$lang=$GLOBALS['lang'$GLOBALS['lang'$GLOBALS['lodeluser']['lang'];
  379.     if ($GLOBALS['langcache'][$lang][$group.".".$name]{
  380.         return $GLOBALS['langcache'][$lang][$group.".".$name];
  381.     else {
  382.         #echo "name=$name,group=$group,id=$id,contents=$contents,status=$status,lang=$lang<br />";
  383.         getlodeltext($name,$group,$id,$contents,$status,$lang);
  384.         return $contents;
  385.     }
  386. }
  387.  
  388. function makeurlwithid ($id$base 'index')
  389. {
  390.     
  391.     if (is_numeric($base)) {
  392.         $t    $id;
  393.         $id   $base;
  394.         $base $t;
  395.     // exchange
  396.     if (defined('URI')) {
  397.         $uri URI;
  398.     else {
  399.         // compat 0.7
  400.         if ($GLOBALS['idagauche']{
  401.             $uri 'leftid';
  402.         }
  403.     }
  404.     
  405.     /*$class = $GLOBALS['db']->getOne(lq("SELECT class FROM #_TP_objects WHERE id='$id'"));
  406.         if ($GLOBALS['db']->errorno()) {
  407.             dberror();
  408.         }
  409.     if($class != 'entities')
  410.         $uri = '';*/
  411.     switch($uri{
  412.     case 'leftid':
  413.         return $base$id'.'$GLOBALS['extensionscripts'];
  414.     //fabrique des urls type index.php?/rubrique/mon-titre
  415.     case 'path':
  416.         $id intval($id);
  417.         $path getPath($id,'path');
  418.         return $path;
  419.     case 'querystring':
  420.         $id intval($id);
  421.         $path getPath($id,'querystring');
  422.         return $path;
  423.     default:
  424.         return $base'.'$GLOBALS['extensionscripts']'?id='$id;
  425.     }
  426. }
  427.  
  428. function makeurlwithfile($id{
  429.     $url makeurlwithid($id);
  430.     $url .= (false === strpos($url'?')) '?file=1' '&file=1';
  431.     return $url;
  432. }
  433.  
  434. if (!function_exists("file_get_contents")) {
  435.   function file_get_contents($file
  436.   {
  437.     $fp=fopen($file,"r"or die("Impossible to read the file $file");
  438.     while(!feof($fp)) $res.=fread($fp,2048);
  439.     fclose($fp);
  440.     return $res;
  441.   }
  442. }
  443. /**
  444.  * retourne le chemin complet vers une entitée *
  445.  * @param integer $id identifiant numérique de l'entitée *
  446.  * @param string $urltype le type d'url utilisée(path,querystring)
  447.  * @return string le chemin
  448.  * @since fonction ajoutée en 0.8
  449.  */
  450. function getPath($id$urltype,$base='index')
  451. {
  452.     $urltype 'querystring'//la version actuelle de lodel ne gère que le type path
  453.     if($urltype!='path' && $urltype!='querystring'{
  454.         return;
  455.     }
  456.     $id intval($id);
  457.         $result $GLOBALS['db']->execute(lq("SELECT identifier FROM #_TP_entities INNER JOIN #_TP_relations ON id1=id WHERE id2='$idORDER BY degree DESC")) or dberror();
  458.         while(!$result->EOF{
  459.             $path.= '/'$result->fields['identifier'];
  460.             $result->MoveNext();
  461.         }
  462.         $row $GLOBALS['db']->getRow(lq("SELECT identifier FROM #_TP_entities WHERE id='$id'"));
  463.         if ($GLOBALS['db']->errorno()) {
  464.             dberror();
  465.         }
  466.         $path.= "/$id-"$row['identifier'];
  467.         if($urltype == 'path'{
  468.             return $base'.'$GLOBALS['extensionscripts']$path;
  469.         }
  470.         return "$base."$GLOBALS['extensionscripts']"?$path";
  471. }
  472.  
  473.  
  474. /**
  475.  * sent the header and the file for downloading
  476.  * 
  477.  * @param     string   name of the real file.
  478.  * @param     string   name to send to the browser.
  479.  * 
  480.  */
  481. function download($filename,$originalname="",$contents="")
  482. {
  483.   $mimetype array(
  484.             'doc'=>'application/msword',
  485.             'htm'=>'text/html',
  486.             'html'=>'text/html',
  487.             'jpg'=>'image/jpeg',
  488.             'gif'=>'image/gif',
  489.             'png'=>'image/png',
  490.             'pdf'=>'application/pdf',
  491.             'txt'=>'text/plain',
  492.             'xls'=>'application/vnd.ms-excel'
  493.             );
  494.  
  495.   if (!$originalname$originalname=$filename;
  496.   $originalname=preg_replace("/.*\//","",$originalname);
  497.   $ext=substr($originalname,strrpos($originalname,".")+1);
  498.   $size $filename filesize($filenamestrlen($contents);
  499.   if($mimetype[$ext&& !(PMA_USR_BROWSER_AGENT == 'IE' && $ext == "pdf" && PMA_USR_OS != "Mac")){
  500.     $mime $mimetype[$ext];
  501.     $disposition "inline";
  502.   else {
  503.     $mime