[SPIP] ~maj 3.0.10 --> 3.0.14
[lhc/web/www.git] / www / ecrire / inc / rechercher.php
1 <?php
2
3 /***************************************************************************\
4 * SPIP, Systeme de publication pour l'internet *
5 * *
6 * Copyright (c) 2001-2014 *
7 * Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James *
8 * *
9 * Ce programme est un logiciel libre distribue sous licence GNU/GPL. *
10 * Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. *
11 \***************************************************************************/
12
13
14 if (!defined('_ECRIRE_INC_VERSION')) return;
15
16
17 // Donne la liste des champs/tables ou l'on sait chercher/remplacer
18 // avec un poids pour le score
19 // http://doc.spip.org/@liste_des_champs
20 function liste_des_champs() {
21 static $liste=null;
22 if (is_null($liste)) {
23 $liste = array();
24 // recuperer les tables_objets_sql declarees
25 include_spip('base/objets');
26 $tables_objets = lister_tables_objets_sql();
27 foreach($tables_objets as $t=>$infos){
28 if ($infos['rechercher_champs']){
29 $liste[$infos['type']] = $infos['rechercher_champs'];
30 }
31 }
32 // puis passer dans le pipeline
33 $liste = pipeline('rechercher_liste_des_champs', $liste);
34 }
35 return $liste;
36 }
37
38
39 // Recherche des auteurs et mots-cles associes
40 // en ne regardant que le titre ou le nom
41 // http://doc.spip.org/@liste_des_jointures
42 function liste_des_jointures() {
43 static $liste=null;
44 if (is_null($liste)) {
45 $liste = array();
46 // recuperer les tables_objets_sql declarees
47 include_spip('base/objets');
48 $tables_objets = lister_tables_objets_sql();
49 foreach($tables_objets as $t=>$infos){
50 if ($infos['rechercher_jointures']){
51 $liste[$infos['type']] = $infos['rechercher_jointures'];
52 }
53 }
54 // puis passer dans le pipeline
55 $liste = pipeline('rechercher_liste_des_jointures', $liste);
56 }
57 return $liste;
58 }
59
60 function expression_recherche($recherche, $options) {
61 $u = $GLOBALS['meta']['pcre_u'];
62 include_spip('inc/charsets');
63 $recherche = trim(translitteration($recherche));
64
65 $is_preg = false;
66 if (substr($recherche,0,1)=='/' AND substr($recherche,-1,1)=='/'){
67 // c'est une preg
68 $preg = $recherche.$options['preg_flags'];
69 $is_preg = true;
70 }
71 else{
72 // s'il y a plusieurs mots il faut les chercher tous : oblige REGEXP
73 // sauf ceux de moins de 4 lettres (on supprime ainsi 'le', 'les', 'un',
74 // 'une', 'des' ...)
75 if (preg_match(",\s+,".$u, $recherche)){
76 $is_preg = true;
77 $recherche_inter = '|';
78 $recherche_mots = explode(' ', $recherche);
79 $min_long = defined('_RECHERCHE_MIN_CAR') ? _RECHERCHE_MIN_CAR : 4;
80 foreach ($recherche_mots as $mot) {
81 if (strlen($mot) >= $min_long) {
82 $recherche_inter .= $mot.' ';
83 }
84 }
85 // mais on cherche quand même l'expression complète, même si elle
86 // comporte des mots de moins de quatre lettres
87 $recherche = rtrim($recherche.preg_replace(',\s+,'.$u, '|', $recherche_inter), '|');
88 }
89
90 $preg = '/'.str_replace('/', '\\/', $recherche).'/' . $options['preg_flags'];
91 }
92
93 // Si la chaine est inactive, on va utiliser LIKE pour aller plus vite
94 // ou si l'expression reguliere est invalide
95 if (!$is_preg
96 OR (@preg_match($preg,'')===FALSE) ) {
97 $methode = 'LIKE';
98 $u = $GLOBALS['meta']['pcre_u'];
99 // eviter les parentheses et autres caractères qui interferent avec pcre par la suite (dans le preg_match_all) s'il y a des reponses
100 $recherche = str_replace(
101 array('(',')','?','[', ']', '+', '*', '/'),
102 array('\(','\)','[?]', '\[', '\]', '\+', '\*', '\/'),
103 $recherche);
104 $recherche_mod = $recherche;
105
106 // echapper les % et _
107 $q = str_replace(array('%','_'), array('\%', '\_'), trim($recherche));
108 // les expressions entre " " sont un mot a chercher tel quel
109 // -> on remplace les espaces par un _ et on enleve les guillemets
110 if (preg_match(',["][^"]+["],Uims',$q,$matches)){
111 foreach($matches as $match){
112 // corriger le like dans le $q
113 $word = preg_replace(",\s+,Uims","_",$match);
114 $word = trim($word,'"');
115 $q = str_replace($match,$word,$q);
116 // corriger la regexp
117 $word = preg_replace(",\s+,Uims","[\s]",$match);
118 $word = trim($word,'"');
119 $recherche_mod = str_replace($match,$word,$recherche_mod);
120 }
121 }
122 $q = sql_quote(
123 "%"
124 . preg_replace(",\s+,".$u, "%", $q)
125 . "%"
126 );
127
128 $preg = '/'.preg_replace(",\s+,".$u, ".+", trim($recherche_mod)).'/' . $options['preg_flags'];
129
130 } else {
131 $methode = 'REGEXP';
132 $q = sql_quote(trim($recherche, '/'));
133 }
134
135 return array($methode, $q, $preg);
136 }
137
138
139 // Effectue une recherche sur toutes les tables de la base de donnees
140 // options :
141 // - toutvoir pour eviter autoriser(voir)
142 // - flags pour eviter les flags regexp par defaut (UimsS)
143 // - champs pour retourner les champs concernes
144 // - score pour retourner un score
145 // On peut passer les tables, ou une chaine listant les tables souhaitees
146 // http://doc.spip.org/@recherche_en_base
147 function recherche_en_base($recherche='', $tables=NULL, $options=array(), $serveur='') {
148 include_spip('base/abstract_sql');
149
150 if (!is_array($tables)) {
151 $liste = liste_des_champs();
152
153 if (is_string($tables)
154 AND $tables != '') {
155 $toutes = array();
156 foreach(explode(',', $tables) as $t)
157 if (isset($liste[$t]))
158 $toutes[$t] = $liste[$t];
159 $tables = $toutes;
160 unset($toutes);
161 } else
162 $tables = $liste;
163 }
164
165 if (!strlen($recherche) OR !count($tables))
166 return array();
167
168 include_spip('inc/autoriser');
169
170 // options par defaut
171 $options = array_merge(array(
172 'preg_flags' => 'UimsS',
173 'toutvoir' => false,
174 'champs' => false,
175 'score' => false,
176 'matches' => false,
177 'jointures' => false,
178 'serveur' => $serveur
179 ),
180 $options
181 );
182
183 $results = array();
184
185 // Utiliser l'iterateur (DATA:recherche)
186 // pour recuperer les couples (id_objet, score)
187 // Le resultat est au format {
188 // id1 = { 'score' => x, attrs => { } },
189 // id2 = { 'score' => x, attrs => { } },
190 // }
191 include_spip('inc/memoization');
192 foreach ($tables as $table => $champs) {
193 # lock via memoization, si dispo
194 if (function_exists('cache_lock'))
195 cache_lock($lock = 'recherche '.$table.' '.$recherche);
196
197 spip_timer('rech');
198
199 // TODO: ici plutot charger un iterateur via l'API iterateurs
200 include_spip('inc/recherche_to_array');
201 $to_array = charger_fonction('recherche_to_array', 'inc');
202 $results[$table] = $to_array($recherche,
203 array_merge($options, array('table' => $table, 'champs' => $champs))
204 );
205 ##var_dump($results[$table]);
206
207
208 spip_log("recherche $table ($recherche) : ".count($results[$table])." resultats ".spip_timer('rech'),'recherche');
209
210 if (isset($lock))
211 cache_unlock($lock);
212 }
213
214 return $results;
215 }
216
217
218 // Effectue une recherche sur toutes les tables de la base de donnees
219 // http://doc.spip.org/@remplace_en_base
220 function remplace_en_base($recherche='', $remplace=NULL, $tables=NULL, $options=array()) {
221 include_spip('inc/modifier');
222
223 // options par defaut
224 $options = array_merge(array(
225 'preg_flags' => 'UimsS',
226 'toutmodifier' => false
227 ),
228 $options
229 );
230 $options['champs'] = true;
231
232
233 if (!is_array($tables))
234 $tables = liste_des_champs();
235
236 $results = recherche_en_base($recherche, $tables, $options);
237
238 $preg = '/'.str_replace('/', '\\/', $recherche).'/' . $options['preg_flags'];
239
240 foreach ($results as $table => $r) {
241 $_id_table = id_table_objet($table);
242 foreach ($r as $id => $x) {
243 if ($options['toutmodifier']
244 OR autoriser('modifier', $table, $id)) {
245 $modifs = array();
246 foreach ($x['champs'] as $key => $val) {
247 if ($key == $_id_table) next;
248 $repl = preg_replace($preg, $remplace, $val);
249 if ($repl <> $val)
250 $modifs[$key] = $repl;
251 }
252 if ($modifs)
253 objet_modifier_champs($table, $id,
254 array(
255 'champs' => array_keys($modifs),
256 ),
257 $modifs);
258 }
259 }
260 }
261 }
262
263 ?>