PageRenderTime 45ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/_plugins_/ezSQL/exec/ezsql.php

https://bitbucket.org/pombredanne/spip-zone-treemap
PHP | 315 lines | 277 code | 12 blank | 26 comment | 12 complexity | 821ecd7079f3acbfea12608be5e80e6b MD5 | raw file
  1. <?php
  2. /*
  3. This file is part of ezSQL.
  4. ezSQL is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. ezSQL is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with SIOU; if not, write to the Free Software
  14. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  15. Copyright 2007, 2008 - Ghislain VLAVONOU, Yannick EDAHE, Cedric PROTIERE
  16. */
  17. include_spip('inc/presentation');
  18. include_spip('inc/config');
  19. include_spip('inc/charsets');
  20. include('inc-traitements.php');
  21. setlocale(LC_TIME, "fr_FR");
  22. define(OK,"<SPAN style='color:#3C3;font-weight:bold;'>[OK]</SPAN>");
  23. define(KO,"<SPAN style='color:#C33;font-weight:bold;'>[KO]</SPAN>");
  24. // exécuté automatiquement par le plugin au chargement de la page ?exec=ezsql
  25. function exec_ezsql() {
  26. global $connect_statut, $connect_toutes_rubriques, $debug, $txt_gauche, $txt_droite, $txt_debug, $tab_referentiel, $odb_referentiel,$odb_mapping;
  27. $annee=date("Y");
  28. $aide="Cliquez sur une des tables &agrave; gauche (vous pouvez commencer par cliquer sur \"spip\" par exemple) ou tapez une requ&ecirc;te ici puis cliquez sur le bouton [Ex&eacute;cuter]";
  29. $requeteExemple="SELECT *\\n FROM spip_articles\\n LIMIT 0,10";
  30. $aideEnregistrer=html_entity_decode_utf8("Nom de la requête");
  31. //FIXME normalement ca devrait etre dans le script d'installation automatique du plugin. Mais je comprends pas comment ca marche :(
  32. //cf http://www.spip-contrib.net/Plugin-xml
  33. $sql="CREATE TABLE IF NOT EXISTS `ez_sql` (\n"
  34. ."`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,\n"
  35. ."`nomRequete` VARCHAR( 64 ) NOT NULL ,\n"
  36. ."`requete` TEXT NOT NULL ,\n"
  37. ."`login` VARCHAR( 64 ) NOT NULL\n"
  38. .") COMMENT = 'Requetes ezSQL';"
  39. ;
  40. ez_query($sql,__FILE__,__LINE__);
  41. debut_page(_T('ezSQL - Export CSV'), "", "");
  42. // echo "<br /><br />";
  43. gros_titre(_T('ezSQL - Export CSV'));
  44. // print_r($_POST);
  45. if(isset($_REQUEST['table'])) {
  46. $isExecute=true;
  47. $sqlNormale="SELECT *\n FROM ".$_REQUEST['table']."\n LIMIT 0,30";
  48. }
  49. elseif(isset($_REQUEST['requete'])) {
  50. $isExecute=true;
  51. $sqlNormale = stripslashes($_REQUEST['requete']);
  52. } else {
  53. $isExecute=false;
  54. $sqlNormale=$aide;
  55. }
  56. $nomTable='resultat';
  57. if(isset($_REQUEST['enregistrer'])) {
  58. $nomRequete=$_REQUEST['nomRequete'];
  59. ez_query("DELETE FROM ez_sql WHERE nomRequete='$nomRequete'",__FILE__,__LINE__);
  60. if(isset($_REQUEST['public'])) $login='*';
  61. else $login=$GLOBALS['auteur_session']['login'];
  62. $sql="INSERT INTO ez_sql(nomRequete,requete,login) VALUES ('$nomRequete','$sqlNormale','$login')";
  63. ez_query($sql,__FILE__,__LINE__);
  64. }
  65. if($isExecute) {
  66. $sqlNormale=ez_propre($sqlNormale);
  67. $sqlAff=str_replace('=',"<b style='color:#e70;'>=</b>",$sqlNormale);
  68. foreach(array(')','distinct(','uncompress(','compress(','encode(','decode(') as $mot) {
  69. // mots sans espace avant/apres => ne pas mettre n'importe quoi !
  70. $sqlAff=str_ireplace("$mot",strtoupper("<b style='color:#d90;'>$mot</b>"),$sqlAff);
  71. }
  72. foreach(array('IN','*') as $mot) {
  73. $sqlAff=str_ireplace(" $mot ",strtoupper(" <b style='color:#d90;'>$mot</b> "),$sqlAff);
  74. }
  75. foreach(array('select','insert','update','delete','replace','truncate','left join',
  76. 'from','where','into','set','values','limit','and','table','order by','group by','having'
  77. ) as $mot) {
  78. $sqlAff=str_ireplace(" $mot ",strtoupper("<br/> <b style='color:#c33;'> $mot</b> "),$sqlAff);
  79. $sqlNormale=str_ireplace(" $mot ",strtoupper("\n $mot "),$sqlNormale);
  80. }
  81. $sqlNormale=trim($sqlNormale);
  82. //$sqlAff=substr($sqlAff,6);
  83. list($typeSQL,$rien)=explode(' ',trim($sqlAff),2);
  84. $sqlAff="<b style='color:#c33;'>".strtoupper($typeSQL)."</b> $rien";
  85. list($typeSQL,$rien)=explode(' ',trim($sqlNormale),2);
  86. $sqlNormale=strtoupper($typeSQL)." $rien";
  87. switch(trim(strtolower($typeSQL))) {
  88. case 'select':
  89. $isSelect=true;
  90. $tmp=trim(stristr($sqlNormale,'from'));//requete apres from
  91. list($rien,$nomTable,$reste)=explode(' ',$tmp,3);
  92. $nomTable=trim($nomTable);
  93. break;
  94. default:
  95. $isSelect=false;
  96. break;
  97. }
  98. $nomFichier="$nomTable.csv";
  99. }
  100. debut_gauche();
  101. debut_boite_info();
  102. $r = ez_query("SELECT DATABASE()",__FILE__,__LINE__);
  103. $base = mysql_result($r,0);
  104. echo "Base <b>$base</b><br/><small>".mysql_get_host_info()."<br/>\n".mysql_get_server_info()."<br/>\n</small>\n";
  105. $sql="SHOW tables";
  106. $result=ez_query($sql,__FILE__,__LINE__);
  107. while($row=mysql_fetch_row($result)) {
  108. $table=$row[0];
  109. if(substr_count($table,'_')>0)
  110. list($prefixe,$reste)=explode(strrchr($table,'_'),$table);
  111. else $prefixe=$table;
  112. if(substr_count($prefixe,'spip')>0) $prefixe='spip';
  113. if((trim(strtolower($table)))==trim(strtolower($nomTable))) {
  114. $sTableEnCours=$table;
  115. $table="<A class='table' HREF='".generer_url_ecrire('ezsql')."&table=$table' style='color:#000;'><b>$table</b></a>";
  116. $sql="SHOW columns from $nomTable";
  117. $result2=ez_query($sql,__FILE__,__LINE__);
  118. $cpt=0;
  119. while($row2=mysql_fetch_row($result2)) {
  120. $table.= "<br/><span title='".$row2[1]."'>&nbsp;&nbsp;".$row2[0]."</span>\n";
  121. switch(trim($row2[3])) {
  122. case 'PRI':
  123. $html="style='cursor:pointer;font-weight:bold;border-bottom:1px dotted #000;' title='Cl&eacute; primaire'";
  124. break;
  125. case '':
  126. $html="style='cursor:pointer;'";
  127. break;
  128. default:
  129. $html="style='cursor:pointer;border-bottom:1px dotted #000;' title='Cl&eacute; $row2[3]'";
  130. }
  131. $tBody[$cpt]="<td><span onclick=\"champ=document.forms['formRequete'].requete;champ.value+='$row2[0], ';champ.focus();\" $html>".$row2[0]."</span></td><td>".$row2[1]."</td><td>".$row2[3]."</td>";
  132. $cpt++;
  133. }
  134. } else
  135. $table="<A class='table' HREF='".generer_url_ecrire('ezsql')."&table=$table' style='color:#999;'>$table</A>";
  136. $tTable[$prefixe][]=$table;
  137. }
  138. echo "<dl id='groupes'>\n<div style='background-color:#ddd;padding:2px;'>Cliquez sur un groupe de tables ci-dessous (par exemple <b>spip</b>)</div>\n";
  139. foreach($tTable as $prefixe=>$t1) {
  140. echo "<br/>\n\t<dt style='font-weight:bold;font-size:12px;cursor:help;'>$prefixe</dt>\n";
  141. echo "\t<dd style='border:dotted 1px black;background-color:#ddd;'>".join('<br/>',$t1)."</dd>\n";
  142. }
  143. echo "</dl>\n";
  144. fin_boite_info();
  145. creer_colonne_droite();
  146. if($isSelect) {
  147. debut_boite_info();
  148. echo ez_html_table("<A href='javascript:;' title='Ajouter la table $sTableEnCours' onclick=\"champ=document.forms['formRequete'].requete;champ.value+='$sTableEnCours';champ.focus();\">$sTableEnCours</A>",$tBody,"<th>Colonne</th><th>Type</th>");
  149. $sql="SELECT count(*) from $sTableEnCours";
  150. $result=ez_query($sql,__FILE__,__LINE__);
  151. $nbRows=mysql_result($result,0,0);
  152. $s=($nbRows>1)?'s':'';
  153. echo "Contient <b>$nbRows</b> enregistrement$s<hr size=0/>\nCliquez sur un champ ci-dessus pour l'ajouter dans votre requ&ecirc;te";
  154. fin_boite_info();
  155. }
  156. debut_droite();
  157. $result=ez_query("SELECT nomRequete, requete from ez_sql WHERE login='*' OR login='".$GLOBALS['auteur_session']['login']."'",__FILE__,__LINE__);
  158. $nb=spip_num_rows($result);
  159. if($nb>0) {
  160. $selectHistorique="<SELECT NAME='historique'>\n"
  161. ."<OPTION VALUE=''>-=[Historique]=-</OPTION>\n";
  162. while($row=mysql_fetch_array($result)) {
  163. foreach(array('nomRequete','requete') as $col) $$col=addslashes($row[$col]);
  164. //if($nomRequete==$_REQUEST['nomRequete']) $selected='SELECTED';
  165. //else $selected='';
  166. $selectHistorique.="<OPTION value='".$requete."' $selected>$nomRequete</OPTION>\n";
  167. echo $requete;
  168. }
  169. $selectHistorique.="</SELECT>\n";
  170. } else $selectHistorique='';
  171. debut_cadre_relief( "", false, "", $titre = _T("Requ&ecirc;te SQL $selectHistorique"));
  172. //echo "<IMG SRC='"._DIR_PLUGIN_EZSQL."/img_pack/logo_odb.png' alt='Office du bac' ALIGN='absmiddle'><br><br>\n";
  173. echo "<form name='formRequete' method='POST' action='".generer_url_ecrire('ezsql')."'>\n";
  174. if($isExecute) echo "<small style='font-family:monospace;'>$sqlAff</small>\n";
  175. echo "<textarea name='requete' cols=100 rows=5 class='forml' style='color:#555;'>\n"
  176. .($sqlNormale)."</textarea>"
  177. ;
  178. echo "<input name='executer' type='submit' value='Ex&eacute;cuter' class='fondo'>";
  179. if($isExecute) {
  180. echo "<fieldset><legend>Enregistrer cette requ&ecirc;te (historique)</legend><small>"
  181. ."<label for='nomRequete'>$aideEnregistrer</label> <input name='nomRequete' value='$nomRequete' class='fondo'\"/>\n"
  182. ."<br/><label for='public'>Requ&ecirc;te publique (tous les auteurs peuvent la voir)</label> <input type='checkbox' name='public' checked><br/>\n"
  183. ."<input type='submit' name='enregistrer' value='Enregistrer cette requ&ecirc;te' class='fondo' onClick=\"if(document.forms['formRequete'].nomRequete.value=='') {alert('Veuillez specifier un nom pour enregistrer cette requete');return false;}\"/></small></fieldset>\n"
  184. ;
  185. }
  186. echo "</form>\n";
  187. if ($isExecute){
  188. $result = ez_query($sqlNormale,__FILE__,__LINE__);
  189. if($isSelect) {
  190. $nbLignes=mysql_num_rows($result);
  191. if($nbLignes>0) {
  192. //FIXME Preciser le repertoire du fichier csv
  193. $destination="../tmp/";
  194. $fichier = fopen($destination.$nomFichier, 'w+');
  195. $tRow=array();
  196. while($tRow[] = mysql_fetch_assoc($result));
  197. foreach($tRow[0] as $k=>$v)
  198. $tCol[$k]=ucwords(str_replace('_',' ',$k));
  199. fputcsv($fichier, (array)$tCol, "\t");
  200. $compteur=0; $min=min($nbLignes, 30);
  201. $tbody=array();
  202. foreach($tRow as $ligne) {
  203. fputcsv($fichier, (array)$ligne, "\t");
  204. if($compteur++<$min) {
  205. $cptCol=0;
  206. foreach($ligne as $col) {
  207. if($cptCol<5) $tbody[$compteur].="<td><small>".wordwrap($col,60,'<br/>',true)."</small></td>";
  208. $cptCol++;
  209. }
  210. }
  211. //$tbody[] = "<td><small>".join('</small></td><td><small>',$ligne)."</small></td>";
  212. }
  213. fclose($fichier);
  214. } else {
  215. echo "Aucun enregistrement";
  216. $isSelect=false;
  217. }
  218. }
  219. }
  220. if($isExecute) {
  221. echo "<small>".htmlentities(mysql_info())."</small><br/>";
  222. if($isSelect) {
  223. echo "<A HREF='$destination$nomFichier'>"
  224. ."<IMG SRC='"._DIR_PLUGIN_EZSQL."/img_pack/csvimport-24.png' ALIGN='absmiddle'/>"
  225. ." T&eacute;l&eacute;charger <b>$nomFichier</b> ($nbLignes lignes)</A>\n"
  226. ;
  227. }
  228. else {
  229. $nb=mysql_affected_rows();
  230. $s=$nb>1?'s':'';
  231. echo "<b>$nb</b> ligne$s affect&eacute;e$s<br/>";
  232. }
  233. }
  234. fin_cadre_relief();
  235. if($isExecute && $isSelect)
  236. echo '<br/>'.ez_html_table("Aper&ccedil;u de la requ&ecirc;te",$tbody,"<th><small>".join('</small></th><th><small>',array_slice($tCol,0,5))."</small></th>",'statistiques-24.gif');
  237. $aide=html_entity_decode_utf8($aide);
  238. $jquery= <<<FINSCRIPT
  239. $(document).ready(function() {
  240. $('#groupes').find('dd').hide().end().find('dt').click(function() {
  241. var suivant = $(this).next();
  242. suivant.slideToggle();
  243. });
  244. $("a[@class=table]").hover(function() {
  245. $(this).css("color","#222");
  246. }, function() {
  247. $(this).css("color","#999");
  248. });
  249. $("textarea[@name*=requete]").hover(function() {
  250. $(this).css("color", "#000");
  251. if(this.value=='$aide') this.value='';
  252. this.focus();
  253. //alert(this.value);
  254. }, function() {
  255. $(this).css("color", "#555");
  256. if(this.value=='') {
  257. this.value='$aide';
  258. this.blur();
  259. }
  260. });
  261. $("select[@name=historique]").change(function() {
  262. forml=document.forms['formRequete'];
  263. forml.requete.value=this.value;
  264. forml.nomRequete.value='';
  265. });
  266. $("form[@name=formRequete]").submit(function() {
  267. if(this.requete.value=='$aide') {
  268. alert('Veuillez saisir une requete valide, par exemple :\\n\\n$requeteExemple');
  269. this.requete.value='$requeteExemple';
  270. return false;
  271. }
  272. });
  273. $("dd").hover(function() {
  274. $(this).css("border-style", "solid");
  275. }, function() {
  276. $(this).css("border-style", "dotted");
  277. });
  278. });
  279. FINSCRIPT;
  280. echo "<script type='text/javascript'><!--\n$jquery\n//-->\n</script>\n";
  281. fin_page();
  282. exit;
  283. }
  284. ?>