Completed
Push — master ( 44fd31...388bf1 )
by cam
01:38
created
config/ecran_securite.php 1 patch
Indentation   +427 added lines, -427 removed lines patch added patch discarded remove patch
@@ -15,11 +15,11 @@  discard block
 block discarded – undo
15 15
  * Test utilisateur
16 16
  */
17 17
 if (isset($_GET['test_ecran_securite'])) {
18
-	$ecran_securite_raison = 'test ' . _ECRAN_SECURITE;
18
+    $ecran_securite_raison = 'test ' . _ECRAN_SECURITE;
19 19
 }
20 20
 
21 21
 if (file_exists($f = __DIR__ . DIRECTORY_SEPARATOR  . 'ecran_securite_options.php')) {
22
-	include ($f);
22
+    include ($f);
23 23
 }
24 24
 
25 25
 /*
@@ -29,222 +29,222 @@  discard block
 block discarded – undo
29 29
  * le load depasse ECRAN_SECURITE_LOAD)
30 30
  */
31 31
 if (!defined('_IS_BOT') and isset($_GET['var_isbot'])) {
32
-	define('_IS_BOT', $_GET['var_isbot'] ? true : false);
32
+    define('_IS_BOT', $_GET['var_isbot'] ? true : false);
33 33
 }
34 34
 
35 35
 /*
36 36
  * Détecteur de robot d'indexation
37 37
  */
38 38
 if (!defined('_IS_BOT')) {
39
-	define(
40
-		'_IS_BOT',
41
-		isset($_SERVER['HTTP_USER_AGENT'])
42
-			and preg_match(
43
-				','
44
-					. implode('|', array(
45
-						// mots generiques
46
-						'bot',
47
-						'slurp',
48
-						'crawler',
49
-						'crwlr',
50
-						'java',
51
-						'monitoring',
52
-						'spider',
53
-						'webvac',
54
-						'yandex',
55
-						'MSIE 6\.0', // botnet 99,9% du temps
56
-						// UA plus cibles
57
-						'200please',
58
-						'80legs',
59
-						'a6-indexer',
60
-						'aboundex',
61
-						'accoona',
62
-						'acrylicapps',
63
-						'addthis',
64
-						'adressendeutschland',
65
-						'alexa',
66
-						'altavista',
67
-						'analyticsseo',
68
-						'antennapod',
69
-						'arachnys',
70
-						'archive',
71
-						'argclrint',
72
-						'aspseek',
73
-						'baidu',
74
-						'begunadvertising',
75
-						'bing',
76
-						'bloglines',
77
-						'buck',
78
-						'browsershots',
79
-						'bubing',
80
-						'butterfly',
81
-						'changedetection',
82
-						'charlotte',
83
-						'chilkat',
84
-						'china',
85
-						'coccoc',
86
-						'crowsnest',
87
-						'dataminr',
88
-						'daumoa',
89
-						'dlvr\.it',
90
-						'dlweb',
91
-						'drupal',
92
-						'ec2linkfinder',
93
-						'eset\.com',
94
-						'estyle',
95
-						'exalead',
96
-						'ezooms',
97
-						'facebookexternalhit',
98
-						'facebookplatform',
99
-						'fairshare',
100
-						'feedfetcher',
101
-						'feedfetcher-google',
102
-						'feedly',
103
-						'fetch',
104
-						'flipboardproxy',
105
-						'genieo',
106
-						'google',
107
-						'go-http-client',
108
-						'grapeshot',
109
-						'hatena-useragent',
110
-						'head',
111
-						'hosttracker',
112
-						'hubspot',
113
-						'ia_archiver',
114
-						'ichiro',
115
-						'iltrovatore-setaccio',
116
-						'immediatenet',
117
-						'ina',
118
-						'inoreader',
119
-						'infegyatlas',
120
-						'infohelfer',
121
-						'instapaper',
122
-						'jabse',
123
-						'james',
124
-						'jersey',
125
-						'kumkie',
126
-						'linkdex',
127
-						'linkfluence',
128
-						'linkwalker',
129
-						'litefinder',
130
-						'loadimpactpageanalyzer',
131
-						'ltx71',
132
-						'luminate',
133
-						'lycos',
134
-						'lycosa',
135
-						'mediapartners-google',
136
-						'msai',
137
-						'myapp',
138
-						'nativehost',
139
-						'najdi',
140
-						'netcraftsurveyagent',
141
-						'netestate',
142
-						'netseer',
143
-						'netnewswire',
144
-						'newspaper',
145
-						'newsblur',
146
-						'nuhk',
147
-						'nuzzel',
148
-						'okhttp',
149
-						'otmedia',
150
-						'owlin',
151
-						'owncloud',
152
-						'panscient',
153
-						'paper\.li',
154
-						'parsijoo',
155
-						'protopage',
156
-						'plukkie',
157
-						'proximic',
158
-						'pubsub',
159
-						'python',
160
-						'qirina',
161
-						'qoshe',
162
-						'qualidator',
163
-						'qwantify',
164
-						'rambler',
165
-						'readability',
166
-						'ruby',
167
-						'sbsearch',
168
-						'scoop\.it',
169
-						'scooter',
170
-						'scoutjet',
171
-						'scrapy',
172
-						'scrubby',
173
-						'scrubbybloglines',
174
-						'shareaholic',
175
-						'shopwiki',
176
-						'simplepie',
177
-						'sistrix',
178
-						'sitechecker',
179
-						'siteexplorer',
180
-						'snapshot',
181
-						'sogou',
182
-						'special_archiver',
183
-						'speedy',
184
-						'spinn3r',
185
-						'spreadtrum',
186
-						'steeler',
187
-						'subscriber',
188
-						'suma',
189
-						'superdownloads',
190
-						'svenska-webbsido',
191
-						'teoma',
192
-						'the knowledge AI',
193
-						'thumbshots',
194
-						'tineye',
195
-						'traackr',
196
-						'trendiction',
197
-						'trendsmap',
198
-						'tweetedtimes',
199
-						'tweetmeme',
200
-						'universalfeedparser',
201
-						'uaslinkchecker',
202
-						'undrip',
203
-						'unwindfetchor',
204
-						'upday',
205
-						'vedma',
206
-						'vkshare',
207
-						'vm',
208
-						'wch',
209
-						'webalta',
210
-						'webcookies',
211
-						'webparser',
212
-						'webthumbnail',
213
-						'wesee',
214
-						'wise-guys',
215
-						'woko',
216
-						'wordpress',
217
-						'wotbox',
218
-						'y!j-bri',
219
-						'y!j-bro',
220
-						'y!j-brw',
221
-						'y!j-bsc',
222
-						'yahoo',
223
-						'yahoo!',
224
-						'yahooysmcm',
225
-						'ymobactus',
226
-						'yats',
227
-						'yeti',
228
-						'zeerch'
229
-					)) . ',i',
230
-				(string)$_SERVER['HTTP_USER_AGENT']
231
-			)
232
-	);
39
+    define(
40
+        '_IS_BOT',
41
+        isset($_SERVER['HTTP_USER_AGENT'])
42
+            and preg_match(
43
+                ','
44
+                    . implode('|', array(
45
+                        // mots generiques
46
+                        'bot',
47
+                        'slurp',
48
+                        'crawler',
49
+                        'crwlr',
50
+                        'java',
51
+                        'monitoring',
52
+                        'spider',
53
+                        'webvac',
54
+                        'yandex',
55
+                        'MSIE 6\.0', // botnet 99,9% du temps
56
+                        // UA plus cibles
57
+                        '200please',
58
+                        '80legs',
59
+                        'a6-indexer',
60
+                        'aboundex',
61
+                        'accoona',
62
+                        'acrylicapps',
63
+                        'addthis',
64
+                        'adressendeutschland',
65
+                        'alexa',
66
+                        'altavista',
67
+                        'analyticsseo',
68
+                        'antennapod',
69
+                        'arachnys',
70
+                        'archive',
71
+                        'argclrint',
72
+                        'aspseek',
73
+                        'baidu',
74
+                        'begunadvertising',
75
+                        'bing',
76
+                        'bloglines',
77
+                        'buck',
78
+                        'browsershots',
79
+                        'bubing',
80
+                        'butterfly',
81
+                        'changedetection',
82
+                        'charlotte',
83
+                        'chilkat',
84
+                        'china',
85
+                        'coccoc',
86
+                        'crowsnest',
87
+                        'dataminr',
88
+                        'daumoa',
89
+                        'dlvr\.it',
90
+                        'dlweb',
91
+                        'drupal',
92
+                        'ec2linkfinder',
93
+                        'eset\.com',
94
+                        'estyle',
95
+                        'exalead',
96
+                        'ezooms',
97
+                        'facebookexternalhit',
98
+                        'facebookplatform',
99
+                        'fairshare',
100
+                        'feedfetcher',
101
+                        'feedfetcher-google',
102
+                        'feedly',
103
+                        'fetch',
104
+                        'flipboardproxy',
105
+                        'genieo',
106
+                        'google',
107
+                        'go-http-client',
108
+                        'grapeshot',
109
+                        'hatena-useragent',
110
+                        'head',
111
+                        'hosttracker',
112
+                        'hubspot',
113
+                        'ia_archiver',
114
+                        'ichiro',
115
+                        'iltrovatore-setaccio',
116
+                        'immediatenet',
117
+                        'ina',
118
+                        'inoreader',
119
+                        'infegyatlas',
120
+                        'infohelfer',
121
+                        'instapaper',
122
+                        'jabse',
123
+                        'james',
124
+                        'jersey',
125
+                        'kumkie',
126
+                        'linkdex',
127
+                        'linkfluence',
128
+                        'linkwalker',
129
+                        'litefinder',
130
+                        'loadimpactpageanalyzer',
131
+                        'ltx71',
132
+                        'luminate',
133
+                        'lycos',
134
+                        'lycosa',
135
+                        'mediapartners-google',
136
+                        'msai',
137
+                        'myapp',
138
+                        'nativehost',
139
+                        'najdi',
140
+                        'netcraftsurveyagent',
141
+                        'netestate',
142
+                        'netseer',
143
+                        'netnewswire',
144
+                        'newspaper',
145
+                        'newsblur',
146
+                        'nuhk',
147
+                        'nuzzel',
148
+                        'okhttp',
149
+                        'otmedia',
150
+                        'owlin',
151
+                        'owncloud',
152
+                        'panscient',
153
+                        'paper\.li',
154
+                        'parsijoo',
155
+                        'protopage',
156
+                        'plukkie',
157
+                        'proximic',
158
+                        'pubsub',
159
+                        'python',
160
+                        'qirina',
161
+                        'qoshe',
162
+                        'qualidator',
163
+                        'qwantify',
164
+                        'rambler',
165
+                        'readability',
166
+                        'ruby',
167
+                        'sbsearch',
168
+                        'scoop\.it',
169
+                        'scooter',
170
+                        'scoutjet',
171
+                        'scrapy',
172
+                        'scrubby',
173
+                        'scrubbybloglines',
174
+                        'shareaholic',
175
+                        'shopwiki',
176
+                        'simplepie',
177
+                        'sistrix',
178
+                        'sitechecker',
179
+                        'siteexplorer',
180
+                        'snapshot',
181
+                        'sogou',
182
+                        'special_archiver',
183
+                        'speedy',
184
+                        'spinn3r',
185
+                        'spreadtrum',
186
+                        'steeler',
187
+                        'subscriber',
188
+                        'suma',
189
+                        'superdownloads',
190
+                        'svenska-webbsido',
191
+                        'teoma',
192
+                        'the knowledge AI',
193
+                        'thumbshots',
194
+                        'tineye',
195
+                        'traackr',
196
+                        'trendiction',
197
+                        'trendsmap',
198
+                        'tweetedtimes',
199
+                        'tweetmeme',
200
+                        'universalfeedparser',
201
+                        'uaslinkchecker',
202
+                        'undrip',
203
+                        'unwindfetchor',
204
+                        'upday',
205
+                        'vedma',
206
+                        'vkshare',
207
+                        'vm',
208
+                        'wch',
209
+                        'webalta',
210
+                        'webcookies',
211
+                        'webparser',
212
+                        'webthumbnail',
213
+                        'wesee',
214
+                        'wise-guys',
215
+                        'woko',
216
+                        'wordpress',
217
+                        'wotbox',
218
+                        'y!j-bri',
219
+                        'y!j-bro',
220
+                        'y!j-brw',
221
+                        'y!j-bsc',
222
+                        'yahoo',
223
+                        'yahoo!',
224
+                        'yahooysmcm',
225
+                        'ymobactus',
226
+                        'yats',
227
+                        'yeti',
228
+                        'zeerch'
229
+                    )) . ',i',
230
+                (string)$_SERVER['HTTP_USER_AGENT']
231
+            )
232
+    );
233 233
 }
234 234
 if (!defined('_IS_BOT_FRIEND')) {
235
-	define(
236
-		'_IS_BOT_FRIEND',
237
-		isset($_SERVER['HTTP_USER_AGENT'])
238
-			and preg_match(
239
-				',' . implode('|', array(
240
-					'facebookexternalhit',
241
-					'twitterbot',
242
-					'flipboardproxy',
243
-					'wordpress'
244
-				)) . ',i',
245
-				(string)$_SERVER['HTTP_USER_AGENT']
246
-			)
247
-	);
235
+    define(
236
+        '_IS_BOT_FRIEND',
237
+        isset($_SERVER['HTTP_USER_AGENT'])
238
+            and preg_match(
239
+                ',' . implode('|', array(
240
+                    'facebookexternalhit',
241
+                    'twitterbot',
242
+                    'flipboardproxy',
243
+                    'wordpress'
244
+                )) . ',i',
245
+                (string)$_SERVER['HTTP_USER_AGENT']
246
+            )
247
+    );
248 248
 }
249 249
 
250 250
 /*
@@ -256,28 +256,28 @@  discard block
 block discarded – undo
256 256
  */
257 257
 $_exceptions = array('id_table', 'id_base', 'id_parent', 'id_article_pdf');
258 258
 foreach ($_GET as $var => $val) {
259
-	if (
260
-		$_GET[$var] and strncmp($var, "id_", 3) == 0
261
-		and !in_array($var, $_exceptions)
262
-	) {
263
-		$_GET[$var] = is_array($_GET[$var]) ? @array_map('intval', $_GET[$var]) : intval($_GET[$var]);
264
-	}
259
+    if (
260
+        $_GET[$var] and strncmp($var, "id_", 3) == 0
261
+        and !in_array($var, $_exceptions)
262
+    ) {
263
+        $_GET[$var] = is_array($_GET[$var]) ? @array_map('intval', $_GET[$var]) : intval($_GET[$var]);
264
+    }
265 265
 }
266 266
 foreach ($_POST as $var => $val) {
267
-	if (
268
-		$_POST[$var] and strncmp($var, "id_", 3) == 0
269
-		and !in_array($var, $_exceptions)
270
-	) {
271
-		$_POST[$var] = is_array($_POST[$var]) ? @array_map('intval', $_POST[$var]) : intval($_POST[$var]);
272
-	}
267
+    if (
268
+        $_POST[$var] and strncmp($var, "id_", 3) == 0
269
+        and !in_array($var, $_exceptions)
270
+    ) {
271
+        $_POST[$var] = is_array($_POST[$var]) ? @array_map('intval', $_POST[$var]) : intval($_POST[$var]);
272
+    }
273 273
 }
274 274
 foreach ($GLOBALS as $var => $val) {
275
-	if (
276
-		$GLOBALS[$var] and strncmp($var, "id_", 3) == 0
277
-		and !in_array($var, $_exceptions)
278
-	) {
279
-		$GLOBALS[$var] = is_array($GLOBALS[$var]) ? @array_map('intval', $GLOBALS[$var]) : intval($GLOBALS[$var]);
280
-	}
275
+    if (
276
+        $GLOBALS[$var] and strncmp($var, "id_", 3) == 0
277
+        and !in_array($var, $_exceptions)
278
+    ) {
279
+        $GLOBALS[$var] = is_array($GLOBALS[$var]) ? @array_map('intval', $GLOBALS[$var]) : intval($GLOBALS[$var]);
280
+    }
281 281
 }
282 282
 
283 283
 /*
@@ -290,116 +290,116 @@  discard block
 block discarded – undo
290 290
  * Contrôle de quelques variables (XSS)
291 291
  */
292 292
 foreach (array('lang', 'var_recherche', 'aide', 'var_lang_r', 'lang_r', 'var_ajax_ancre', 'nom_fichier') as $var) {
293
-	if (isset($_GET[$var])) {
294
-		$_REQUEST[$var] = $GLOBALS[$var] = $_GET[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_GET[$var]);
295
-	}
296
-	if (isset($_POST[$var])) {
297
-		$_REQUEST[$var] = $GLOBALS[$var] = $_POST[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_POST[$var]);
298
-	}
293
+    if (isset($_GET[$var])) {
294
+        $_REQUEST[$var] = $GLOBALS[$var] = $_GET[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_GET[$var]);
295
+    }
296
+    if (isset($_POST[$var])) {
297
+        $_REQUEST[$var] = $GLOBALS[$var] = $_POST[$var] = preg_replace(',[^\w\,/#&;-]+,', ' ', (string)$_POST[$var]);
298
+    }
299 299
 }
300 300
 
301 301
 /*
302 302
  * Filtre l'accès à spip_acces_doc (injection SQL en 1.8.2x)
303 303
  */
304 304
 if (isset($_SERVER['REQUEST_URI'])) {
305
-	if (preg_match(',^(.*/)?spip_acces_doc\.,', (string)$_SERVER['REQUEST_URI'])) {
306
-		$file = addslashes((string)$_GET['file']);
307
-	}
305
+    if (preg_match(',^(.*/)?spip_acces_doc\.,', (string)$_SERVER['REQUEST_URI'])) {
306
+        $file = addslashes((string)$_GET['file']);
307
+    }
308 308
 }
309 309
 
310 310
 /*
311 311
  * Pas d'inscription abusive
312 312
  */
313 313
 if (
314
-	isset($_REQUEST['mode']) and isset($_REQUEST['page'])
315
-	and !in_array($_REQUEST['mode'], array("6forum", "1comite"))
316
-	and $_REQUEST['page'] == "identifiants"
314
+    isset($_REQUEST['mode']) and isset($_REQUEST['page'])
315
+    and !in_array($_REQUEST['mode'], array("6forum", "1comite"))
316
+    and $_REQUEST['page'] == "identifiants"
317 317
 ) {
318
-	$ecran_securite_raison = "identifiants";
318
+    $ecran_securite_raison = "identifiants";
319 319
 }
320 320
 
321 321
 /*
322 322
  * Agenda joue à l'injection php
323 323
  */
324 324
 if (
325
-	isset($_REQUEST['partie_cal'])
326
-	and $_REQUEST['partie_cal'] !== htmlentities((string)$_REQUEST['partie_cal'])
325
+    isset($_REQUEST['partie_cal'])
326
+    and $_REQUEST['partie_cal'] !== htmlentities((string)$_REQUEST['partie_cal'])
327 327
 ) {
328
-	$ecran_securite_raison = "partie_cal";
328
+    $ecran_securite_raison = "partie_cal";
329 329
 }
330 330
 if (
331
-	isset($_REQUEST['echelle'])
332
-	and $_REQUEST['echelle'] !== htmlentities((string)$_REQUEST['echelle'])
331
+    isset($_REQUEST['echelle'])
332
+    and $_REQUEST['echelle'] !== htmlentities((string)$_REQUEST['echelle'])
333 333
 ) {
334
-	$ecran_securite_raison = "echelle";
334
+    $ecran_securite_raison = "echelle";
335 335
 }
336 336
 
337 337
 /*
338 338
  * Espace privé
339 339
  */
340 340
 if (
341
-	isset($_REQUEST['exec'])
342
-	and !preg_match(',^[\w-]+$,', (string)$_REQUEST['exec'])
341
+    isset($_REQUEST['exec'])
342
+    and !preg_match(',^[\w-]+$,', (string)$_REQUEST['exec'])
343 343
 ) {
344
-	$ecran_securite_raison = "exec";
344
+    $ecran_securite_raison = "exec";
345 345
 }
346 346
 if (
347
-	isset($_REQUEST['cherche_auteur'])
348
-	and preg_match(',[<],', (string)$_REQUEST['cherche_auteur'])
347
+    isset($_REQUEST['cherche_auteur'])
348
+    and preg_match(',[<],', (string)$_REQUEST['cherche_auteur'])
349 349
 ) {
350
-	$ecran_securite_raison = "cherche_auteur";
350
+    $ecran_securite_raison = "cherche_auteur";
351 351
 }
352 352
 if (
353
-	isset($_REQUEST['exec'])
354
-	and $_REQUEST['exec'] == 'auteurs'
355
-	and isset($_REQUEST['recherche'])
356
-	and preg_match(',[<],', (string)$_REQUEST['recherche'])
353
+    isset($_REQUEST['exec'])
354
+    and $_REQUEST['exec'] == 'auteurs'
355
+    and isset($_REQUEST['recherche'])
356
+    and preg_match(',[<],', (string)$_REQUEST['recherche'])
357 357
 ) {
358
-	$ecran_securite_raison = "recherche";
358
+    $ecran_securite_raison = "recherche";
359 359
 }
360 360
 if (
361
-	isset($_REQUEST['exec'])
362
-	and $_REQUEST['exec'] == 'info_plugin'
363
-	and isset($_REQUEST['plugin'])
364
-	and preg_match(',[<],', (string)$_REQUEST['plugin'])
361
+    isset($_REQUEST['exec'])
362
+    and $_REQUEST['exec'] == 'info_plugin'
363
+    and isset($_REQUEST['plugin'])
364
+    and preg_match(',[<],', (string)$_REQUEST['plugin'])
365 365
 ) {
366
-	$ecran_securite_raison = "plugin";
366
+    $ecran_securite_raison = "plugin";
367 367
 }
368 368
 if (
369
-	isset($_REQUEST['exec'])
370
-	and $_REQUEST['exec'] == 'puce_statut'
371
-	and isset($_REQUEST['id'])
372
-	and !intval($_REQUEST['id'])
369
+    isset($_REQUEST['exec'])
370
+    and $_REQUEST['exec'] == 'puce_statut'
371
+    and isset($_REQUEST['id'])
372
+    and !intval($_REQUEST['id'])
373 373
 ) {
374
-	$ecran_securite_raison = "puce_statut";
374
+    $ecran_securite_raison = "puce_statut";
375 375
 }
376 376
 if (
377
-	isset($_REQUEST['action'])
378
-	and $_REQUEST['action'] == 'configurer'
377
+    isset($_REQUEST['action'])
378
+    and $_REQUEST['action'] == 'configurer'
379 379
 ) {
380
-	if (
381
-		@file_exists('inc_version.php')
382
-		or @file_exists('ecrire/inc_version.php')
383
-	) {
384
-		function action_configurer() {
385
-			include_spip('inc/autoriser');
386
-			if (!autoriser('configurer', _request('configuration'))) {
387
-				include_spip('inc/minipres');
388
-				echo minipres(_T('info_acces_interdit'));
389
-				exit;
390
-			}
391
-			require _DIR_RESTREINT . 'action/configurer.php';
392
-			action_configurer_dist();
393
-		}
394
-	}
380
+    if (
381
+        @file_exists('inc_version.php')
382
+        or @file_exists('ecrire/inc_version.php')
383
+    ) {
384
+        function action_configurer() {
385
+            include_spip('inc/autoriser');
386
+            if (!autoriser('configurer', _request('configuration'))) {
387
+                include_spip('inc/minipres');
388
+                echo minipres(_T('info_acces_interdit'));
389
+                exit;
390
+            }
391
+            require _DIR_RESTREINT . 'action/configurer.php';
392
+            action_configurer_dist();
393
+        }
394
+    }
395 395
 }
396 396
 if (
397
-	isset($_REQUEST['action'])
398
-	and $_REQUEST['action'] == 'ordonner_liens_documents'
399
-	and isset($_REQUEST['ordre'])
400
-	and is_string($_REQUEST['ordre'])
397
+    isset($_REQUEST['action'])
398
+    and $_REQUEST['action'] == 'ordonner_liens_documents'
399
+    and isset($_REQUEST['ordre'])
400
+    and is_string($_REQUEST['ordre'])
401 401
 ) {
402
-	$ecran_securite_raison = "ordre a la chaine";
402
+    $ecran_securite_raison = "ordre a la chaine";
403 403
 }
404 404
 
405 405
 
@@ -407,29 +407,29 @@  discard block
 block discarded – undo
407 407
  * Bloque les requêtes contenant %00 (manipulation d'include)
408 408
  */
409 409
 if (strpos(
410
-	(function_exists('get_magic_quotes_gpc') and @get_magic_quotes_gpc())
411
-		? stripslashes(serialize($_REQUEST))
412
-		: serialize($_REQUEST),
413
-	chr(0)
410
+    (function_exists('get_magic_quotes_gpc') and @get_magic_quotes_gpc())
411
+        ? stripslashes(serialize($_REQUEST))
412
+        : serialize($_REQUEST),
413
+    chr(0)
414 414
 ) !== false) {
415
-	$ecran_securite_raison = "%00";
415
+    $ecran_securite_raison = "%00";
416 416
 }
417 417
 
418 418
 /*
419 419
  * Bloque les requêtes fond=formulaire_
420 420
  */
421 421
 if (
422
-	isset($_REQUEST['fond'])
423
-	and preg_match(',^formulaire_,i', $_REQUEST['fond'])
422
+    isset($_REQUEST['fond'])
423
+    and preg_match(',^formulaire_,i', $_REQUEST['fond'])
424 424
 ) {
425
-	$ecran_securite_raison = "fond=formulaire_";
425
+    $ecran_securite_raison = "fond=formulaire_";
426 426
 }
427 427
 
428 428
 /*
429 429
  * Bloque les requêtes du type ?GLOBALS[type_urls]=toto (bug vieux php)
430 430
  */
431 431
 if (isset($_REQUEST['GLOBALS'])) {
432
-	$ecran_securite_raison = "GLOBALS[GLOBALS]";
432
+    $ecran_securite_raison = "GLOBALS[GLOBALS]";
433 433
 }
434 434
 
435 435
 /*
@@ -438,14 +438,14 @@  discard block
 block discarded – undo
438 438
  * les paginations entremélées
439 439
  */
440 440
 if (_IS_BOT) {
441
-	if (
442
-		(isset($_REQUEST['echelle']) and isset($_REQUEST['partie_cal']) and isset($_REQUEST['type']))
443
-		or (strpos((string)$_SERVER['REQUEST_URI'], 'debut_') and preg_match(',[?&]debut_.*&debut_,', (string)$_SERVER['REQUEST_URI']))
444
-		or (isset($_REQUEST['calendrier_annee']) and strpos((string)$_SERVER['REQUEST_URI'], 'debut_'))
445
-		or (isset($_REQUEST['calendrier_annee']) and preg_match(',[?&]calendrier_annee=.*&calendrier_annee=,', (string)$_SERVER['REQUEST_URI']))
446
-	) {
447
-		$ecran_securite_raison = "robot agenda/double pagination";
448
-	}
441
+    if (
442
+        (isset($_REQUEST['echelle']) and isset($_REQUEST['partie_cal']) and isset($_REQUEST['type']))
443
+        or (strpos((string)$_SERVER['REQUEST_URI'], 'debut_') and preg_match(',[?&]debut_.*&debut_,', (string)$_SERVER['REQUEST_URI']))
444
+        or (isset($_REQUEST['calendrier_annee']) and strpos((string)$_SERVER['REQUEST_URI'], 'debut_'))
445
+        or (isset($_REQUEST['calendrier_annee']) and preg_match(',[?&]calendrier_annee=.*&calendrier_annee=,', (string)$_SERVER['REQUEST_URI']))
446
+    ) {
447
+        $ecran_securite_raison = "robot agenda/double pagination";
448
+    }
449 449
 }
450 450
 
451 451
 /*
@@ -453,82 +453,82 @@  discard block
 block discarded – undo
453 453
  * Bloque un XSS sur une page inexistante
454 454
  */
455 455
 if (isset($_REQUEST['page'])) {
456
-	if ($_REQUEST['page'] == 'test_cfg') {
457
-		$ecran_securite_raison = "test_cfg";
458
-	}
459
-	if ($_REQUEST['page'] !== htmlspecialchars((string)$_REQUEST['page'])) {
460
-		$ecran_securite_raison = "xsspage";
461
-	}
462
-	if (
463
-		$_REQUEST['page'] == '404'
464
-		and isset($_REQUEST['erreur'])
465
-	) {
466
-		$ecran_securite_raison = "xss404";
467
-	}
456
+    if ($_REQUEST['page'] == 'test_cfg') {
457
+        $ecran_securite_raison = "test_cfg";
458
+    }
459
+    if ($_REQUEST['page'] !== htmlspecialchars((string)$_REQUEST['page'])) {
460
+        $ecran_securite_raison = "xsspage";
461
+    }
462
+    if (
463
+        $_REQUEST['page'] == '404'
464
+        and isset($_REQUEST['erreur'])
465
+    ) {
466
+        $ecran_securite_raison = "xss404";
467
+    }
468 468
 }
469 469
 
470 470
 /*
471 471
  * XSS par array
472 472
  */
473 473
 foreach (array('var_login') as $var) {
474
-	if (isset($_REQUEST[$var]) and is_array($_REQUEST[$var])) {
475
-		$ecran_securite_raison = "xss " . $var;
476
-	}
474
+    if (isset($_REQUEST[$var]) and is_array($_REQUEST[$var])) {
475
+        $ecran_securite_raison = "xss " . $var;
476
+    }
477 477
 }
478 478
 
479 479
 /*
480 480
  * Parade antivirale contre un cheval de troie
481 481
  */
482 482
 if (!function_exists('tmp_lkojfghx')) {
483
-	function tmp_lkojfghx() {}
484
-	function tmp_lkojfghx2($a = 0, $b = 0, $c = 0, $d = 0) {
485
-		// si jamais on est arrivé ici sur une erreur php
486
-		// et qu'un autre gestionnaire d'erreur est défini, l'appeller
487
-		if ($b && $GLOBALS['tmp_xhgfjokl']) {
488
-			call_user_func($GLOBALS['tmp_xhgfjokl'], $a, $b, $c, $d);
489
-		}
490
-	}
483
+    function tmp_lkojfghx() {}
484
+    function tmp_lkojfghx2($a = 0, $b = 0, $c = 0, $d = 0) {
485
+        // si jamais on est arrivé ici sur une erreur php
486
+        // et qu'un autre gestionnaire d'erreur est défini, l'appeller
487
+        if ($b && $GLOBALS['tmp_xhgfjokl']) {
488
+            call_user_func($GLOBALS['tmp_xhgfjokl'], $a, $b, $c, $d);
489
+        }
490
+    }
491 491
 }
492 492
 if (isset($_POST['tmp_lkojfghx3'])) {
493
-	$ecran_securite_raison = "gumblar";
493
+    $ecran_securite_raison = "gumblar";
494 494
 }
495 495
 
496 496
 /*
497 497
  * Outils XML mal sécurisés < 2.0.9
498 498
  */
499 499
 if (isset($_REQUEST['transformer_xml'])) {
500
-	$ecran_securite_raison = "transformer_xml";
500
+    $ecran_securite_raison = "transformer_xml";
501 501
 }
502 502
 
503 503
 /*
504 504
  * Outils XML mal sécurisés again
505 505
  */
506 506
 if (isset($_REQUEST['var_url']) and $_REQUEST['var_url'] and isset($_REQUEST['exec']) and $_REQUEST['exec'] == 'valider_xml') {
507
-	$url = trim($_REQUEST['var_url']);
508
-	if (
509
-		strncmp($url, '/', 1) == 0
510
-		or (($p = strpos($url, '..')) !== false and strpos($url, '..', $p + 3) !== false)
511
-		or (($p = strpos($url, '..')) !== false and strpos($url, 'IMG', $p + 3) !== false)
512
-		or (strpos($url, '://') !== false or strpos($url, ':\\') !== false)
513
-	) {
514
-		$ecran_securite_raison = 'URL interdite pour var_url';
515
-	}
507
+    $url = trim($_REQUEST['var_url']);
508
+    if (
509
+        strncmp($url, '/', 1) == 0
510
+        or (($p = strpos($url, '..')) !== false and strpos($url, '..', $p + 3) !== false)
511
+        or (($p = strpos($url, '..')) !== false and strpos($url, 'IMG', $p + 3) !== false)
512
+        or (strpos($url, '://') !== false or strpos($url, ':\\') !== false)
513
+    ) {
514
+        $ecran_securite_raison = 'URL interdite pour var_url';
515
+    }
516 516
 }
517 517
 
518 518
 /*
519 519
  * Sauvegarde mal securisée < 2.0.9
520 520
  */
521 521
 if (
522
-	isset($_REQUEST['nom_sauvegarde'])
523
-	and strstr((string)$_REQUEST['nom_sauvegarde'], '/')
522
+    isset($_REQUEST['nom_sauvegarde'])
523
+    and strstr((string)$_REQUEST['nom_sauvegarde'], '/')
524 524
 ) {
525
-	$ecran_securite_raison = 'nom_sauvegarde manipulee';
525
+    $ecran_securite_raison = 'nom_sauvegarde manipulee';
526 526
 }
527 527
 if (
528
-	isset($_REQUEST['znom_sauvegarde'])
529
-	and strstr((string)$_REQUEST['znom_sauvegarde'], '/')
528
+    isset($_REQUEST['znom_sauvegarde'])
529
+    and strstr((string)$_REQUEST['znom_sauvegarde'], '/')
530 530
 ) {
531
-	$ecran_securite_raison = 'znom_sauvegarde manipulee';
531
+    $ecran_securite_raison = 'znom_sauvegarde manipulee';
532 532
 }
533 533
 
534 534
 
@@ -537,57 +537,57 @@  discard block
 block discarded – undo
537 537
  * on vérifie 'page' pour ne pas bloquer ... drupal
538 538
  */
539 539
 if (
540
-	isset($_REQUEST['op']) and isset($_REQUEST['page'])
541
-	and $_REQUEST['op'] !== preg_replace('/[^\\-\w]/', '', $_REQUEST['op'])
540
+    isset($_REQUEST['op']) and isset($_REQUEST['page'])
541
+    and $_REQUEST['op'] !== preg_replace('/[^\\-\w]/', '', $_REQUEST['op'])
542 542
 ) {
543
-	$ecran_securite_raison = 'op';
543
+    $ecran_securite_raison = 'op';
544 544
 }
545 545
 
546 546
 /*
547 547
  * Forms & Table ne se méfiait pas assez des uploads de fichiers
548 548
  */
549 549
 if (count($_FILES)) {
550
-	foreach ($_FILES as $k => $v) {
551
-		if (
552
-			preg_match(',^fichier_\d+$,', $k)
553
-			and preg_match(',\.php,i', $v['name'])
554
-		) {
555
-			unset($_FILES[$k]);
556
-		}
557
-	}
550
+    foreach ($_FILES as $k => $v) {
551
+        if (
552
+            preg_match(',^fichier_\d+$,', $k)
553
+            and preg_match(',\.php,i', $v['name'])
554
+        ) {
555
+            unset($_FILES[$k]);
556
+        }
557
+    }
558 558
 }
559 559
 /*
560 560
  * et Contact trop laxiste avec une variable externe
561 561
  * on bloque pas le post pour eviter de perdre des donnees mais on unset la variable et c'est tout
562 562
  */
563 563
 if (isset($_REQUEST['pj_enregistrees_nom']) and $_REQUEST['pj_enregistrees_nom']) {
564
-	unset($_REQUEST['pj_enregistrees_nom']);
565
-	unset($_GET['pj_enregistrees_nom']);
566
-	unset($_POST['pj_enregistrees_nom']);
564
+    unset($_REQUEST['pj_enregistrees_nom']);
565
+    unset($_GET['pj_enregistrees_nom']);
566
+    unset($_POST['pj_enregistrees_nom']);
567 567
 }
568 568
 
569 569
 /*
570 570
  * reinstall=oui un peu trop permissif
571 571
  */
572 572
 if (
573
-	isset($_REQUEST['reinstall'])
574
-	and $_REQUEST['reinstall'] == 'oui'
573
+    isset($_REQUEST['reinstall'])
574
+    and $_REQUEST['reinstall'] == 'oui'
575 575
 ) {
576
-	$ecran_securite_raison = 'reinstall=oui';
576
+    $ecran_securite_raison = 'reinstall=oui';
577 577
 }
578 578
 
579 579
 /*
580 580
  * Pas d'action pendant l'install
581 581
  */
582 582
 if (isset($_REQUEST['exec']) and $_REQUEST['exec'] === 'install' and isset($_REQUEST['action'])) {
583
-	$ecran_securite_raison = 'install&action impossibles';
583
+    $ecran_securite_raison = 'install&action impossibles';
584 584
 }
585 585
 
586 586
 /*
587 587
  * Échappement xss referer
588 588
  */
589 589
 if (isset($_SERVER['HTTP_REFERER'])) {
590
-	$_SERVER['HTTP_REFERER'] = strtr($_SERVER['HTTP_REFERER'], '<>"\'', '[]##');
590
+    $_SERVER['HTTP_REFERER'] = strtr($_SERVER['HTTP_REFERER'], '<>"\'', '[]##');
591 591
 }
592 592
 
593 593
 
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
  * Echappement HTTP_X_FORWARDED_HOST
596 596
  */
597 597
 if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
598
-	$_SERVER['HTTP_X_FORWARDED_HOST'] = strtr($_SERVER['HTTP_X_FORWARDED_HOST'], "<>?\"\{\}\$'` \r\n", '____________');
598
+    $_SERVER['HTTP_X_FORWARDED_HOST'] = strtr($_SERVER['HTTP_X_FORWARDED_HOST'], "<>?\"\{\}\$'` \r\n", '____________');
599 599
 }
600 600
 
601 601
 
@@ -603,9 +603,9 @@  discard block
 block discarded – undo
603 603
  * Pas d'erreur dans l'erreur
604 604
  */
605 605
 if (isset($_REQUEST['var_erreur']) and isset($_REQUEST['page']) and $_REQUEST['page'] === 'login') {
606
-	if (strlen($_REQUEST['var_erreur']) !== strcspn($_REQUEST['var_erreur'], '<>')) {
607
-		$ecran_securite_raison = 'var_erreur incorrecte';
608
-	}
606
+    if (strlen($_REQUEST['var_erreur']) !== strcspn($_REQUEST['var_erreur'], '<>')) {
607
+        $ecran_securite_raison = 'var_erreur incorrecte';
608
+    }
609 609
 }
610 610
 
611 611
 
@@ -613,30 +613,30 @@  discard block
 block discarded – undo
613 613
  * Réinjection des clés en html dans l'admin r19561
614 614
  */
615 615
 if (
616
-	(isset($_SERVER['REQUEST_URI']) and strpos($_SERVER['REQUEST_URI'], "ecrire/") !== false)
617
-	or isset($_REQUEST['var_memotri'])
616
+    (isset($_SERVER['REQUEST_URI']) and strpos($_SERVER['REQUEST_URI'], "ecrire/") !== false)
617
+    or isset($_REQUEST['var_memotri'])
618 618
 ) {
619
-	$zzzz = implode("", array_keys($_REQUEST));
620
-	if (strlen($zzzz) != strcspn($zzzz, '<>"\'')) {
621
-		$ecran_securite_raison = 'Cle incorrecte en $_REQUEST';
622
-	}
619
+    $zzzz = implode("", array_keys($_REQUEST));
620
+    if (strlen($zzzz) != strcspn($zzzz, '<>"\'')) {
621
+        $ecran_securite_raison = 'Cle incorrecte en $_REQUEST';
622
+    }
623 623
 }
624 624
 
625 625
 /*
626 626
  * Injection par connect
627 627
  */
628 628
 if (
629
-	isset($_REQUEST['connect'])
630
-	// cas qui permettent de sortir d'un commentaire PHP
631
-	and (
632
-		strpos($_REQUEST['connect'], "?") !== false
633
-		or strpos($_REQUEST['connect'], "<") !== false
634
-		or strpos($_REQUEST['connect'], ">") !== false
635
-		or strpos($_REQUEST['connect'], "\n") !== false
636
-		or strpos($_REQUEST['connect'], "\r") !== false
637
-	)
629
+    isset($_REQUEST['connect'])
630
+    // cas qui permettent de sortir d'un commentaire PHP
631
+    and (
632
+        strpos($_REQUEST['connect'], "?") !== false
633
+        or strpos($_REQUEST['connect'], "<") !== false
634
+        or strpos($_REQUEST['connect'], ">") !== false
635
+        or strpos($_REQUEST['connect'], "\n") !== false
636
+        or strpos($_REQUEST['connect'], "\r") !== false
637
+    )
638 638
 ) {
639
-	$ecran_securite_raison = "malformed connect argument";
639
+    $ecran_securite_raison = "malformed connect argument";
640 640
 }
641 641
 
642 642
 
@@ -644,9 +644,9 @@  discard block
 block discarded – undo
644 644
  * _oups donc
645 645
  */
646 646
 if (
647
-	isset($_REQUEST['_oups'])
648
-	and base64_decode($_REQUEST['_oups'], true) === false) {
649
-	$ecran_securite_raison = "malformed _oups argument";
647
+    isset($_REQUEST['_oups'])
648
+    and base64_decode($_REQUEST['_oups'], true) === false) {
649
+    $ecran_securite_raison = "malformed _oups argument";
650 650
 }
651 651
 
652 652
 
@@ -654,23 +654,23 @@  discard block
 block discarded – undo
654 654
  * S'il y a une raison de mourir, mourons
655 655
  */
656 656
 if (isset($ecran_securite_raison)) {
657
-	header("HTTP/1.0 403 Forbidden");
658
-	header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");
659
-	header("Cache-Control: no-cache, must-revalidate");
660
-	header("Pragma: no-cache");
661
-	header("Content-Type: text/html");
662
-	header("Connection: close");
663
-	die("<html><title>Error 403: Forbidden</title><body><h1>Error 403</h1><p>You are not authorized to view this page ($ecran_securite_raison)</p></body></html>");
657
+    header("HTTP/1.0 403 Forbidden");
658
+    header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");
659
+    header("Cache-Control: no-cache, must-revalidate");
660
+    header("Pragma: no-cache");
661
+    header("Content-Type: text/html");
662
+    header("Connection: close");
663
+    die("<html><title>Error 403: Forbidden</title><body><h1>Error 403</h1><p>You are not authorized to view this page ($ecran_securite_raison)</p></body></html>");
664 664
 }
665 665
 
666 666
 /*
667 667
  * Un filtre filtrer_entites securise
668 668
  */
669 669
 if (!function_exists('filtre_filtrer_entites_dist')) {
670
-	function filtre_filtrer_entites_dist($t) {
671
-		include_spip('inc/texte');
672
-		return interdire_scripts(filtrer_entites($t));
673
-	}
670
+    function filtre_filtrer_entites_dist($t) {
671
+        include_spip('inc/texte');
672
+        return interdire_scripts(filtrer_entites($t));
673
+    }
674 674
 }
675 675
 
676 676
 
@@ -684,35 +684,35 @@  discard block
 block discarded – undo
684 684
  * Bloque les bots quand le load déborde
685 685
  */
686 686
 if (!defined('_ECRAN_SECURITE_LOAD')) {
687
-	define('_ECRAN_SECURITE_LOAD', 4);
687
+    define('_ECRAN_SECURITE_LOAD', 4);
688 688
 }
689 689
 
690 690
 if (
691
-	defined('_ECRAN_SECURITE_LOAD')
692
-	and _ECRAN_SECURITE_LOAD > 0
693
-	and _IS_BOT
694
-	and !_IS_BOT_FRIEND
695
-	and $_SERVER['REQUEST_METHOD'] === 'GET'
696
-	and (
697
-		(function_exists('sys_getloadavg')
698
-			and $load = sys_getloadavg()
699
-			and is_array($load)
700
-			and $load = array_shift($load))
701
-		or
702
-		(@is_readable('/proc/loadavg')
703
-			and $load = file_get_contents('/proc/loadavg')
704
-			and $load = floatval($load))
705
-	)
706
-	and $load > _ECRAN_SECURITE_LOAD // eviter l'evaluation suivante si de toute facon le load est inferieur a la limite
707
-	and rand(0, $load * $load) > _ECRAN_SECURITE_LOAD * _ECRAN_SECURITE_LOAD
691
+    defined('_ECRAN_SECURITE_LOAD')
692
+    and _ECRAN_SECURITE_LOAD > 0
693
+    and _IS_BOT
694
+    and !_IS_BOT_FRIEND
695
+    and $_SERVER['REQUEST_METHOD'] === 'GET'
696
+    and (
697
+        (function_exists('sys_getloadavg')
698
+            and $load = sys_getloadavg()
699
+            and is_array($load)
700
+            and $load = array_shift($load))
701
+        or
702
+        (@is_readable('/proc/loadavg')
703
+            and $load = file_get_contents('/proc/loadavg')
704
+            and $load = floatval($load))
705
+    )
706
+    and $load > _ECRAN_SECURITE_LOAD // eviter l'evaluation suivante si de toute facon le load est inferieur a la limite
707
+    and rand(0, $load * $load) > _ECRAN_SECURITE_LOAD * _ECRAN_SECURITE_LOAD
708 708
 ) {
709
-	//https://webmasters.stackexchange.com/questions/65674/should-i-return-a-429-or-503-status-code-to-a-bot
710
-	header("HTTP/1.0 429 Too Many Requests");
711
-	header("Retry-After: 300");
712
-	header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");
713
-	header("Cache-Control: no-cache, must-revalidate");
714
-	header("Pragma: no-cache");
715
-	header("Content-Type: text/html");
716
-	header("Connection: close");
717
-	die("<html><title>Status 429: Too Many Requests</title><body><h1>Status 429</h1><p>Too Many Requests (try again soon)</p></body></html>");
709
+    //https://webmasters.stackexchange.com/questions/65674/should-i-return-a-429-or-503-status-code-to-a-bot
710
+    header("HTTP/1.0 429 Too Many Requests");
711
+    header("Retry-After: 300");
712
+    header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");
713
+    header("Cache-Control: no-cache, must-revalidate");
714
+    header("Pragma: no-cache");
715
+    header("Content-Type: text/html");
716
+    header("Connection: close");
717
+    die("<html><title>Status 429: Too Many Requests</title><body><h1>Status 429</h1><p>Too Many Requests (try again soon)</p></body></html>");
718 718
 }
Please login to merge, or discard this patch.
ecrire/src/Chiffrer/SpipCles.php 1 patch
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -14,171 +14,171 @@
 block discarded – undo
14 14
 
15 15
 /** Gestion des clés d’authentification / chiffrement de SPIP */
16 16
 final class SpipCles {
17
-	private static array $instances = [];
18
-
19
-	private string $file = _DIR_ETC . 'cles.php';
20
-	private Cles $cles;
21
-
22
-	public static function instance(string $file = ''): self {
23
-		if (empty(self::$instances[$file])) {
24
-			self::$instances[$file] = new self($file);
25
-		}
26
-		return self::$instances[$file];
27
-	}
28
-
29
-	/**
30
-	 * Retourne le secret du site (shorthand)
31
-	 * @uses self::getSecretSite()
32
-	 */
33
-	public static function secret_du_site(): ?string {
34
-		return (self::instance())->getSecretSite();
35
-	}
36
-
37
-	private function __construct(string $file = '') {
38
-		if ($file) {
39
-			$this->file = $file;
40
-		}
41
-		$this->cles = new Cles($this->read());
42
-	}
43
-
44
-	/**
45
-	 * Renvoyer le secret du site
46
-	 *
47
-	 * Le secret du site doit rester aussi secret que possible, et est eternel
48
-	 * On ne doit pas l'exporter
49
-	 *
50
-	 * Le secret est partagé entre une clé disque et une clé bdd
51
-	 *
52
-	 * @return string
53
-	 */
54
-	public function getSecretSite(bool $autoInit = true): ?string {
55
-		$key = $this->getKey('secret_du_site', $autoInit);
56
-		$meta = $this->getMetaKey('secret_du_site', $autoInit);
57
-		// conserve la même longeur.
58
-		return $key ^ $meta;
59
-	}
60
-
61
-	/** Renvoyer le secret des authentifications */
62
-	public function getSecretAuth(bool $autoInit = false): ?string {
63
-		return $this->getKey('secret_des_auth', $autoInit);
64
-	}
65
-	public function save(): bool {
66
-		return ecrire_fichier_securise($this->file, $this->cles->toJson());
67
-	}
68
-
69
-	/**
70
-	 * Fournir une sauvegarde chiffree des cles (a l'aide d'une autre clé, comme le pass d'un auteur)
71
-	 *
72
-	 * @param string $withKey Clé de chiffrage de la sauvegarde
73
-	 * @return string Contenu de la sauvegarde chiffrée générée
74
-	 */
75
-	public function backup(
76
-		#[\SensitiveParameter]
77
-		string $withKey
78
-	): string {
79
-		if (count($this->cles)) {
80
-			return Chiffrement::chiffrer($this->cles->toJson(), $withKey);
81
-		}
82
-		return '';
83
-	}
84
-
85
-	/**
86
-	 * Restaurer les cles manquantes depuis une sauvegarde chiffree des cles
87
-	 * (si la sauvegarde est bien valide)
88
-	 *
89
-	 * @param string $backup Sauvegarde chiffrée (générée par backup())
90
-	 * @param int $id_auteur
91
-	 * @param string $pass
92
-	 * @return void
93
-	 */
94
-	public function restore(
95
-		string $backup,
96
-		#[\SensitiveParameter]
97
-		string $password_clair,
98
-		#[\SensitiveParameter]
99
-		string $password_hash,
100
-		int $id_auteur
101
-	): bool {
102
-		if (empty($backup)) {
103
-			return false;
104
-		}
105
-
106
-		$sauvegarde = Chiffrement::dechiffrer($backup, $password_clair);
107
-		$json = json_decode($sauvegarde, true);
108
-		if (!$json) {
109
-			return false;
110
-		}
111
-
112
-		// cela semble une sauvegarde valide
113
-		$cles_potentielles = array_map('base64_decode', $json);
114
-
115
-		// il faut faire une double verif sur secret_des_auth
116
-		// pour s'assurer qu'elle permet bien de decrypter le pass de l'auteur qui fournit la sauvegarde
117
-		// et par extension tous les passwords
118
-		if (!empty($cles_potentielles['secret_des_auth'])) {
119
-			if (!Password::verifier($password_clair, $password_hash, $cles_potentielles['secret_des_auth'])) {
120
-				spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer' . _LOG_INFO_IMPORTANTE);
121
-				unset($cles_potentielles['secret_des_auth']);
122
-			}
123
-		}
124
-
125
-		// on merge les cles pour recuperer les cles manquantes
126
-		$restauration = false;
127
-		foreach ($cles_potentielles as $name => $key) {
128
-			if (!$this->cles->has($name)) {
129
-				$this->cles->set($name, $key);
130
-				spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer' . _LOG_INFO_IMPORTANTE);
131
-				$restauration = true;
132
-			}
133
-		}
134
-		return $restauration;
135
-	}
136
-
137
-	private function getKey(string $name, bool $autoInit): ?string {
138
-		if ($this->cles->has($name)) {
139
-			return $this->cles->get($name);
140
-		}
141
-		if ($autoInit) {
142
-			$this->cles->generate($name);
143
-			// si l'ecriture de fichier a bien marche on peut utiliser la cle
144
-			if ($this->save()) {
145
-				return $this->cles->get($name);
146
-			}
147
-			// sinon loger et annule la cle generee car il ne faut pas l'utiliser
148
-			spip_log('Echec ecriture du fichier cle ' . $this->file . " ; impossible de generer une cle $name", 'chiffrer' . _LOG_ERREUR);
149
-			$this->cles->delete($name);
150
-		}
151
-		return null;
152
-	}
153
-
154
-	private function getMetaKey(string $name, bool $autoInit = true): ?string {
155
-		if (!isset($GLOBALS['meta'][$name])) {
156
-			include_spip('base/abstract_sql');
157
-			$GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = ' . sql_quote($name, '', 'string'));
158
-		}
159
-		$key = base64_decode($GLOBALS['meta'][$name] ?? '');
160
-		if (strlen($key) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
161
-			return $key;
162
-		}
163
-		if (!$autoInit) {
164
-			return null;
165
-		}
166
-		$key = Chiffrement::keygen();
167
-		ecrire_meta($name, base64_encode($key), 'non');
168
-		lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
169
-
170
-		return $key;
171
-	}
172
-
173
-	private function read(): array {
174
-		lire_fichier_securise($this->file, $json);
175
-		if (
176
-			$json
177
-			and $json = \json_decode($json, true)
178
-			and is_array($json)
179
-		) {
180
-			return array_map('base64_decode', $json);
181
-		}
182
-		return [];
183
-	}
17
+    private static array $instances = [];
18
+
19
+    private string $file = _DIR_ETC . 'cles.php';
20
+    private Cles $cles;
21
+
22
+    public static function instance(string $file = ''): self {
23
+        if (empty(self::$instances[$file])) {
24
+            self::$instances[$file] = new self($file);
25
+        }
26
+        return self::$instances[$file];
27
+    }
28
+
29
+    /**
30
+     * Retourne le secret du site (shorthand)
31
+     * @uses self::getSecretSite()
32
+     */
33
+    public static function secret_du_site(): ?string {
34
+        return (self::instance())->getSecretSite();
35
+    }
36
+
37
+    private function __construct(string $file = '') {
38
+        if ($file) {
39
+            $this->file = $file;
40
+        }
41
+        $this->cles = new Cles($this->read());
42
+    }
43
+
44
+    /**
45
+     * Renvoyer le secret du site
46
+     *
47
+     * Le secret du site doit rester aussi secret que possible, et est eternel
48
+     * On ne doit pas l'exporter
49
+     *
50
+     * Le secret est partagé entre une clé disque et une clé bdd
51
+     *
52
+     * @return string
53
+     */
54
+    public function getSecretSite(bool $autoInit = true): ?string {
55
+        $key = $this->getKey('secret_du_site', $autoInit);
56
+        $meta = $this->getMetaKey('secret_du_site', $autoInit);
57
+        // conserve la même longeur.
58
+        return $key ^ $meta;
59
+    }
60
+
61
+    /** Renvoyer le secret des authentifications */
62
+    public function getSecretAuth(bool $autoInit = false): ?string {
63
+        return $this->getKey('secret_des_auth', $autoInit);
64
+    }
65
+    public function save(): bool {
66
+        return ecrire_fichier_securise($this->file, $this->cles->toJson());
67
+    }
68
+
69
+    /**
70
+     * Fournir une sauvegarde chiffree des cles (a l'aide d'une autre clé, comme le pass d'un auteur)
71
+     *
72
+     * @param string $withKey Clé de chiffrage de la sauvegarde
73
+     * @return string Contenu de la sauvegarde chiffrée générée
74
+     */
75
+    public function backup(
76
+        #[\SensitiveParameter]
77
+        string $withKey
78
+    ): string {
79
+        if (count($this->cles)) {
80
+            return Chiffrement::chiffrer($this->cles->toJson(), $withKey);
81
+        }
82
+        return '';
83
+    }
84
+
85
+    /**
86
+     * Restaurer les cles manquantes depuis une sauvegarde chiffree des cles
87
+     * (si la sauvegarde est bien valide)
88
+     *
89
+     * @param string $backup Sauvegarde chiffrée (générée par backup())
90
+     * @param int $id_auteur
91
+     * @param string $pass
92
+     * @return void
93
+     */
94
+    public function restore(
95
+        string $backup,
96
+        #[\SensitiveParameter]
97
+        string $password_clair,
98
+        #[\SensitiveParameter]
99
+        string $password_hash,
100
+        int $id_auteur
101
+    ): bool {
102
+        if (empty($backup)) {
103
+            return false;
104
+        }
105
+
106
+        $sauvegarde = Chiffrement::dechiffrer($backup, $password_clair);
107
+        $json = json_decode($sauvegarde, true);
108
+        if (!$json) {
109
+            return false;
110
+        }
111
+
112
+        // cela semble une sauvegarde valide
113
+        $cles_potentielles = array_map('base64_decode', $json);
114
+
115
+        // il faut faire une double verif sur secret_des_auth
116
+        // pour s'assurer qu'elle permet bien de decrypter le pass de l'auteur qui fournit la sauvegarde
117
+        // et par extension tous les passwords
118
+        if (!empty($cles_potentielles['secret_des_auth'])) {
119
+            if (!Password::verifier($password_clair, $password_hash, $cles_potentielles['secret_des_auth'])) {
120
+                spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer' . _LOG_INFO_IMPORTANTE);
121
+                unset($cles_potentielles['secret_des_auth']);
122
+            }
123
+        }
124
+
125
+        // on merge les cles pour recuperer les cles manquantes
126
+        $restauration = false;
127
+        foreach ($cles_potentielles as $name => $key) {
128
+            if (!$this->cles->has($name)) {
129
+                $this->cles->set($name, $key);
130
+                spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer' . _LOG_INFO_IMPORTANTE);
131
+                $restauration = true;
132
+            }
133
+        }
134
+        return $restauration;
135
+    }
136
+
137
+    private function getKey(string $name, bool $autoInit): ?string {
138
+        if ($this->cles->has($name)) {
139
+            return $this->cles->get($name);
140
+        }
141
+        if ($autoInit) {
142
+            $this->cles->generate($name);
143
+            // si l'ecriture de fichier a bien marche on peut utiliser la cle
144
+            if ($this->save()) {
145
+                return $this->cles->get($name);
146
+            }
147
+            // sinon loger et annule la cle generee car il ne faut pas l'utiliser
148
+            spip_log('Echec ecriture du fichier cle ' . $this->file . " ; impossible de generer une cle $name", 'chiffrer' . _LOG_ERREUR);
149
+            $this->cles->delete($name);
150
+        }
151
+        return null;
152
+    }
153
+
154
+    private function getMetaKey(string $name, bool $autoInit = true): ?string {
155
+        if (!isset($GLOBALS['meta'][$name])) {
156
+            include_spip('base/abstract_sql');
157
+            $GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = ' . sql_quote($name, '', 'string'));
158
+        }
159
+        $key = base64_decode($GLOBALS['meta'][$name] ?? '');
160
+        if (strlen($key) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
161
+            return $key;
162
+        }
163
+        if (!$autoInit) {
164
+            return null;
165
+        }
166
+        $key = Chiffrement::keygen();
167
+        ecrire_meta($name, base64_encode($key), 'non');
168
+        lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
169
+
170
+        return $key;
171
+    }
172
+
173
+    private function read(): array {
174
+        lire_fichier_securise($this->file, $json);
175
+        if (
176
+            $json
177
+            and $json = \json_decode($json, true)
178
+            and is_array($json)
179
+        ) {
180
+            return array_map('base64_decode', $json);
181
+        }
182
+        return [];
183
+    }
184 184
 }
Please login to merge, or discard this patch.
prive/formulaires/configurer_preferences.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
  **/
22 22
 
23 23
 if (!defined('_ECRIRE_INC_VERSION')) {
24
-	return;
24
+    return;
25 25
 }
26 26
 
27 27
 /**
@@ -31,27 +31,27 @@  discard block
 block discarded – undo
31 31
  *     Environnement du formulaire
32 32
  **/
33 33
 function formulaires_configurer_preferences_charger_dist() {
34
-	// travailler sur des meta fraiches
35
-	include_spip('inc/meta');
36
-	lire_metas();
34
+    // travailler sur des meta fraiches
35
+    include_spip('inc/meta');
36
+    lire_metas();
37 37
 
38
-	$valeurs = [];
39
-	$valeurs['display_navigation'] = $GLOBALS['visiteur_session']['prefs']['display_navigation'] ?? 'navigation_avec_icones';
40
-	$valeurs['display'] = (isset($GLOBALS['visiteur_session']['prefs']['display']) and $GLOBALS['visiteur_session']['prefs']['display'] > 0) ? $GLOBALS['visiteur_session']['prefs']['display'] : 2;
41
-	$valeurs['couleur'] = (isset($GLOBALS['visiteur_session']['prefs']['couleur']) and $GLOBALS['visiteur_session']['prefs']['couleur'] > 0) ? $GLOBALS['visiteur_session']['prefs']['couleur'] : 1;
38
+    $valeurs = [];
39
+    $valeurs['display_navigation'] = $GLOBALS['visiteur_session']['prefs']['display_navigation'] ?? 'navigation_avec_icones';
40
+    $valeurs['display'] = (isset($GLOBALS['visiteur_session']['prefs']['display']) and $GLOBALS['visiteur_session']['prefs']['display'] > 0) ? $GLOBALS['visiteur_session']['prefs']['display'] : 2;
41
+    $valeurs['couleur'] = (isset($GLOBALS['visiteur_session']['prefs']['couleur']) and $GLOBALS['visiteur_session']['prefs']['couleur'] > 0) ? $GLOBALS['visiteur_session']['prefs']['couleur'] : 1;
42 42
 
43
-	$couleurs = charger_fonction('couleurs', 'inc');
44
-	$les_couleurs = $couleurs();
45
-	foreach ($les_couleurs as $k => $c) {
46
-		$valeurs['_couleurs_url'][$k] = generer_url_public('style_prive.css', 'ltr='
47
-			. $GLOBALS['spip_lang_left'] . '&'
48
-			. $couleurs($k));
49
-		$valeurs['couleurs'][$k] = $c;
50
-	}
43
+    $couleurs = charger_fonction('couleurs', 'inc');
44
+    $les_couleurs = $couleurs();
45
+    foreach ($les_couleurs as $k => $c) {
46
+        $valeurs['_couleurs_url'][$k] = generer_url_public('style_prive.css', 'ltr='
47
+            . $GLOBALS['spip_lang_left'] . '&'
48
+            . $couleurs($k));
49
+        $valeurs['couleurs'][$k] = $c;
50
+    }
51 51
 
52
-	$valeurs['imessage'] = $GLOBALS['visiteur_session']['imessage'];
52
+    $valeurs['imessage'] = $GLOBALS['visiteur_session']['imessage'];
53 53
 
54
-	return $valeurs;
54
+    return $valeurs;
55 55
 }
56 56
 
57 57
 /**
@@ -62,33 +62,33 @@  discard block
 block discarded – undo
62 62
  **/
63 63
 function formulaires_configurer_preferences_traiter_dist() {
64 64
 
65
-	if ($couleur = _request('couleur')) {
66
-		$couleurs = charger_fonction('couleurs', 'inc');
67
-		$les_couleurs = $couleurs([], true);
68
-		if (isset($les_couleurs[$couleur])) {
69
-			$GLOBALS['visiteur_session']['prefs']['couleur'] = $couleur;
70
-		}
71
-	}
72
-	if ($display = intval(_request('display'))) {
73
-		$GLOBALS['visiteur_session']['prefs']['display'] = $display;
74
-	}
75
-	if (
76
-		$display_navigation = _request('display_navigation')
77
-		and in_array($display_navigation, ['navigation_sans_icone', 'navigation_avec_icones'])
78
-	) {
79
-		$GLOBALS['visiteur_session']['prefs']['display_navigation'] = $display_navigation;
80
-	}
65
+    if ($couleur = _request('couleur')) {
66
+        $couleurs = charger_fonction('couleurs', 'inc');
67
+        $les_couleurs = $couleurs([], true);
68
+        if (isset($les_couleurs[$couleur])) {
69
+            $GLOBALS['visiteur_session']['prefs']['couleur'] = $couleur;
70
+        }
71
+    }
72
+    if ($display = intval(_request('display'))) {
73
+        $GLOBALS['visiteur_session']['prefs']['display'] = $display;
74
+    }
75
+    if (
76
+        $display_navigation = _request('display_navigation')
77
+        and in_array($display_navigation, ['navigation_sans_icone', 'navigation_avec_icones'])
78
+    ) {
79
+        $GLOBALS['visiteur_session']['prefs']['display_navigation'] = $display_navigation;
80
+    }
81 81
 
82
-	if (intval($GLOBALS['visiteur_session']['id_auteur'])) {
83
-		include_spip('action/editer_auteur');
84
-		$c = ['prefs' => serialize($GLOBALS['visiteur_session']['prefs'])];
82
+    if (intval($GLOBALS['visiteur_session']['id_auteur'])) {
83
+        include_spip('action/editer_auteur');
84
+        $c = ['prefs' => serialize($GLOBALS['visiteur_session']['prefs'])];
85 85
 
86
-		if ($imessage = _request('imessage') and in_array($imessage, ['oui', 'non'])) {
87
-			$c['imessage'] = $imessage;
88
-		}
86
+        if ($imessage = _request('imessage') and in_array($imessage, ['oui', 'non'])) {
87
+            $c['imessage'] = $imessage;
88
+        }
89 89
 
90
-		auteur_modifier($GLOBALS['visiteur_session']['id_auteur'], $c);
91
-	}
90
+        auteur_modifier($GLOBALS['visiteur_session']['id_auteur'], $c);
91
+    }
92 92
 
93
-	return ['message_ok' => _T('config_info_enregistree'), 'editable' => true];
93
+    return ['message_ok' => _T('config_info_enregistree'), 'editable' => true];
94 94
 }
Please login to merge, or discard this patch.
ecrire/inc/informer.php 1 patch
Indentation   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -11,77 +11,77 @@
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 # Les information d'une rubrique selectionnee dans le mini navigateur
18 18
 
19 19
 function inc_informer_dist($id, $col, $exclus, $rac, $type, $do = 'aff') {
20
-	include_spip('inc/texte');
21
-	$titre = $descriptif = '';
22
-	if ($type === 'rubrique') {
23
-		$row = sql_fetsel('titre, descriptif', 'spip_rubriques', 'id_rubrique = ' . intval($id));
24
-		if ($row) {
25
-			$titre = typo($row['titre']);
26
-			$descriptif = propre($row['descriptif']);
27
-		} else {
28
-			$titre = _T('info_racine_site');
29
-		}
30
-	}
20
+    include_spip('inc/texte');
21
+    $titre = $descriptif = '';
22
+    if ($type === 'rubrique') {
23
+        $row = sql_fetsel('titre, descriptif', 'spip_rubriques', 'id_rubrique = ' . intval($id));
24
+        if ($row) {
25
+            $titre = typo($row['titre']);
26
+            $descriptif = propre($row['descriptif']);
27
+        } else {
28
+            $titre = _T('info_racine_site');
29
+        }
30
+    }
31 31
 
32
-	$res = '';
33
-	if (
34
-		$type === 'rubrique'
35
-		and intval($GLOBALS['visiteur_session']['prefs']['display'] ?? 0) !== 1
36
-		and isset($GLOBALS['meta']['image_process'])
37
-	) {
38
-		if ($GLOBALS['meta']['image_process'] !== 'non') {
39
-			$chercher_logo = charger_fonction('chercher_logo', 'inc');
40
-			if ($res = $chercher_logo($id, 'id_rubrique', 'on')) {
41
-				[$fid, $dir, $nom, $format] = $res;
42
-				include_spip('inc/filtres_images_mini');
43
-				$res = image_reduire("<img src='$fid' alt='' />", 100, 48);
44
-				if ($res) {
45
-					$res = "<div class='informer__media' style='float: " . $GLOBALS['spip_lang_right'] . '; margin-' . $GLOBALS['spip_lang_right'] . ": -5px; margin-top: -5px;'>$res</div>";
46
-				}
47
-			}
48
-		}
49
-	}
32
+    $res = '';
33
+    if (
34
+        $type === 'rubrique'
35
+        and intval($GLOBALS['visiteur_session']['prefs']['display'] ?? 0) !== 1
36
+        and isset($GLOBALS['meta']['image_process'])
37
+    ) {
38
+        if ($GLOBALS['meta']['image_process'] !== 'non') {
39
+            $chercher_logo = charger_fonction('chercher_logo', 'inc');
40
+            if ($res = $chercher_logo($id, 'id_rubrique', 'on')) {
41
+                [$fid, $dir, $nom, $format] = $res;
42
+                include_spip('inc/filtres_images_mini');
43
+                $res = image_reduire("<img src='$fid' alt='' />", 100, 48);
44
+                if ($res) {
45
+                    $res = "<div class='informer__media' style='float: " . $GLOBALS['spip_lang_right'] . '; margin-' . $GLOBALS['spip_lang_right'] . ": -5px; margin-top: -5px;'>$res</div>";
46
+                }
47
+            }
48
+        }
49
+    }
50 50
 
51
-	$rac = spip_htmlentities($rac, ENT_QUOTES);
52
-	$do = spip_htmlentities($do, ENT_QUOTES);
53
-	$id = intval($id);
51
+    $rac = spip_htmlentities($rac, ENT_QUOTES);
52
+    $do = spip_htmlentities($do, ENT_QUOTES);
53
+    $id = intval($id);
54 54
 
55 55
 # ce lien provoque la selection (directe) de la rubrique cliquee
56 56
 # et l'affichage de son titre dans le bandeau
57
-	$titre = strtr(
58
-		str_replace(
59
-			"'",
60
-			'&#8217;',
61
-			str_replace('"', '&#34;', textebrut($titre))
62
-		),
63
-		"\n\r",
64
-		'  '
65
-	);
57
+    $titre = strtr(
58
+        str_replace(
59
+            "'",
60
+            '&#8217;',
61
+            str_replace('"', '&#34;', textebrut($titre))
62
+        ),
63
+        "\n\r",
64
+        '  '
65
+    );
66 66
 
67
-	$js_func = $do . '_selection_titre';
67
+    $js_func = $do . '_selection_titre';
68 68
 
69
-	return "<div style='display: none;'>"
70
-	. "<input type='text' id='" . $rac . "_sel' value='$id' />"
71
-	. "<input type='text' id='" . $rac . "_sel2' value=\""
72
-	. entites_html($titre)
73
-	. '" />'
74
-	. '</div>'
75
-	. "<div class='informer' style='padding: 5px; border-top: 0px;'>"
76
-	. '<div class="informer__item">'
77
-	. (!$res ? '' : $res)
78
-	. "<p class='informer__titre'><b>" . safehtml($titre) . '</b></p>'
79
-	. (!$descriptif ? '' : "<div class='informer__descriptif'>" . safehtml($descriptif) . '</div>')
80
-	. '</div>'
81
-	. "<div class='informer__action' style='clear:both; text-align: " . $GLOBALS['spip_lang_right'] . ";'>"
82
-	. "<input type='submit' class='fondo btn submit' value='"
83
-	. _T('bouton_choisir')
84
-	. "'\nonclick=\"$js_func('$titre',$id,'selection_rubrique','id_parent'); return false;\" />"
85
-	. '</div>'
86
-	. '</div>';
69
+    return "<div style='display: none;'>"
70
+    . "<input type='text' id='" . $rac . "_sel' value='$id' />"
71
+    . "<input type='text' id='" . $rac . "_sel2' value=\""
72
+    . entites_html($titre)
73
+    . '" />'
74
+    . '</div>'
75
+    . "<div class='informer' style='padding: 5px; border-top: 0px;'>"
76
+    . '<div class="informer__item">'
77
+    . (!$res ? '' : $res)
78
+    . "<p class='informer__titre'><b>" . safehtml($titre) . '</b></p>'
79
+    . (!$descriptif ? '' : "<div class='informer__descriptif'>" . safehtml($descriptif) . '</div>')
80
+    . '</div>'
81
+    . "<div class='informer__action' style='clear:both; text-align: " . $GLOBALS['spip_lang_right'] . ";'>"
82
+    . "<input type='submit' class='fondo btn submit' value='"
83
+    . _T('bouton_choisir')
84
+    . "'\nonclick=\"$js_func('$titre',$id,'selection_rubrique','id_parent'); return false;\" />"
85
+    . '</div>'
86
+    . '</div>';
87 87
 }
Please login to merge, or discard this patch.
ecrire/inc/commencer_page.php 1 patch
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 /**
@@ -43,25 +43,25 @@  discard block
 block discarded – undo
43 43
  * @return string Code HTML
44 44
  **/
45 45
 function inc_commencer_page_dist(
46
-	$titre = '',
47
-	$rubrique = 'accueil',
48
-	$sous_rubrique = 'accueil',
49
-	$id_rubrique = '',
50
-	$menu = true,
51
-	$minipres = false,
52
-	$alertes = true
46
+    $titre = '',
47
+    $rubrique = 'accueil',
48
+    $sous_rubrique = 'accueil',
49
+    $id_rubrique = '',
50
+    $menu = true,
51
+    $minipres = false,
52
+    $alertes = true
53 53
 ) {
54 54
 
55
-	include_spip('inc/headers');
55
+    include_spip('inc/headers');
56 56
 
57
-	http_no_cache();
57
+    http_no_cache();
58 58
 
59
-	return init_entete($titre, $id_rubrique, $minipres)
60
-	. init_body($rubrique, $sous_rubrique, $id_rubrique, $menu)
61
-	. "<div id='page'>"
62
-	. auteurs_recemment_connectes($GLOBALS['connect_id_auteur'])
63
-	. ($alertes ? alertes_auteur($GLOBALS['connect_id_auteur']) : '')
64
-	. '<div class="largeur">';
59
+    return init_entete($titre, $id_rubrique, $minipres)
60
+    . init_body($rubrique, $sous_rubrique, $id_rubrique, $menu)
61
+    . "<div id='page'>"
62
+    . auteurs_recemment_connectes($GLOBALS['connect_id_auteur'])
63
+    . ($alertes ? alertes_auteur($GLOBALS['connect_id_auteur']) : '')
64
+    . '<div class="largeur">';
65 65
 }
66 66
 
67 67
 /**
@@ -82,21 +82,21 @@  discard block
 block discarded – undo
82 82
  *     Entête du fichier HTML avec le DOCTYPE
83 83
  */
84 84
 function init_entete($titre = '', $dummy = 0, $minipres = false) {
85
-	include_spip('inc/texte');
86
-	if (!$nom_site_spip = textebrut(typo($GLOBALS['meta']['nom_site']))) {
87
-		$nom_site_spip = _T('info_mon_site_spip');
88
-	}
89
-
90
-	$titre = '['
91
-		. $nom_site_spip
92
-		. ']'
93
-		. ($titre ? ' ' . textebrut(typo($titre)) : '');
94
-
95
-	return _DOCTYPE_ECRIRE
96
-	. html_lang_attributes()
97
-	. "<head>\n"
98
-	. init_head($titre, $dummy, $minipres)
99
-	. "</head>\n";
85
+    include_spip('inc/texte');
86
+    if (!$nom_site_spip = textebrut(typo($GLOBALS['meta']['nom_site']))) {
87
+        $nom_site_spip = _T('info_mon_site_spip');
88
+    }
89
+
90
+    $titre = '['
91
+        . $nom_site_spip
92
+        . ']'
93
+        . ($titre ? ' ' . textebrut(typo($titre)) : '');
94
+
95
+    return _DOCTYPE_ECRIRE
96
+    . html_lang_attributes()
97
+    . "<head>\n"
98
+    . init_head($titre, $dummy, $minipres)
99
+    . "</head>\n";
100 100
 }
101 101
 
102 102
 /**
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
  * @return string
111 111
  */
112 112
 function init_head($titre = '', $dummy = 0, $minipres = false) {
113
-	return recuperer_fond('prive/squelettes/head/dist', ['titre' => $titre, 'minipres' => $minipres ? ' ' : '']);
113
+    return recuperer_fond('prive/squelettes/head/dist', ['titre' => $titre, 'minipres' => $minipres ? ' ' : '']);
114 114
 }
115 115
 
116 116
 /**
@@ -132,20 +132,20 @@  discard block
 block discarded – undo
132 132
  */
133 133
 function init_body($rubrique = 'accueil', $sous_rubrique = 'accueil', $id_rubrique = '', $menu = true) {
134 134
 
135
-	$res = pipeline('body_prive', "<body class='"
136
-		. init_body_class() . ' ' . _request('exec') . "'"
137
-		. ($GLOBALS['spip_lang_rtl'] ? " dir='rtl'" : '')
138
-		. '>');
135
+    $res = pipeline('body_prive', "<body class='"
136
+        . init_body_class() . ' ' . _request('exec') . "'"
137
+        . ($GLOBALS['spip_lang_rtl'] ? " dir='rtl'" : '')
138
+        . '>');
139 139
 
140
-	if (!$menu) {
141
-		return $res;
142
-	}
140
+    if (!$menu) {
141
+        return $res;
142
+    }
143 143
 
144 144
 
145
-	$bandeau = charger_fonction('bandeau', 'inc');
145
+    $bandeau = charger_fonction('bandeau', 'inc');
146 146
 
147
-	return $res
148
-	. $bandeau();
147
+    return $res
148
+    . $bandeau();
149 149
 }
150 150
 
151 151
 /**
@@ -157,23 +157,23 @@  discard block
 block discarded – undo
157 157
  * @return string Classes CSS (séparées par des espaces)
158 158
  */
159 159
 function init_body_class() {
160
-	$display_modes = [
161
-		0 => 'icones_img_texte' // défaut.
162
-		/*init*/,
163
-		1 => 'icones_texte',
164
-		2 => 'icones_img_texte',
165
-		3 => 'icones_img'
166
-	];
160
+    $display_modes = [
161
+        0 => 'icones_img_texte' // défaut.
162
+        /*init*/,
163
+        1 => 'icones_texte',
164
+        2 => 'icones_img_texte',
165
+        3 => 'icones_img'
166
+    ];
167 167
 
168
-	$prefs = $GLOBALS['visiteur_session']['prefs'] ?? [];
168
+    $prefs = $GLOBALS['visiteur_session']['prefs'] ?? [];
169 169
 
170
-	$display_mode = $display_modes[intval($prefs['display'] ?? 0)] ?? $display_modes[0];
171
-	$spip_display_navigation = isset($prefs['display_navigation']) ? spip_sanitize_classname($prefs['display_navigation']) : 'navigation_avec_icones';
170
+    $display_mode = $display_modes[intval($prefs['display'] ?? 0)] ?? $display_modes[0];
171
+    $spip_display_navigation = isset($prefs['display_navigation']) ? spip_sanitize_classname($prefs['display_navigation']) : 'navigation_avec_icones';
172 172
 
173
-	$couleur = intval($prefs['couleur'] ?? 2);
173
+    $couleur = intval($prefs['couleur'] ?? 2);
174 174
 
175
-	$classes = "spip-theme-colors-$couleur $spip_display_navigation $display_mode";
176
-	return spip_sanitize_classname($classes);
175
+    $classes = "spip-theme-colors-$couleur $spip_display_navigation $display_mode";
176
+    return spip_sanitize_classname($classes);
177 177
 }
178 178
 
179 179
 
@@ -184,5 +184,5 @@  discard block
 block discarded – undo
184 184
  * @return string
185 185
  */
186 186
 function auteurs_recemment_connectes($id_auteur) {
187
-	return recuperer_fond('prive/objets/liste/auteurs_enligne');
187
+    return recuperer_fond('prive/objets/liste/auteurs_enligne');
188 188
 }
Please login to merge, or discard this patch.
ecrire/index.php 1 patch
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
 /** Drapeau indiquant que l'on est dans l'espace privé */
20 20
 define('_ESPACE_PRIVE', true);
21 21
 if (!defined('_ECRIRE_INC_VERSION')) {
22
-	include 'inc_version.php';
22
+    include 'inc_version.php';
23 23
 }
24 24
 
25 25
 include_spip('inc/cookie');
@@ -35,18 +35,18 @@  discard block
 block discarded – undo
35 35
 // alors il faut blinder les variables d'URL
36 36
 //
37 37
 if (autoriser_sans_cookie($exec, false)) {
38
-	if (!isset($reinstall)) {
39
-		$reinstall = 'non';
40
-	}
41
-	$var_auth = true;
38
+    if (!isset($reinstall)) {
39
+        $reinstall = 'non';
40
+    }
41
+    $var_auth = true;
42 42
 } else {
43
-	// Authentification, redefinissable
44
-	$auth = charger_fonction('auth', 'inc');
45
-	$var_auth = $auth();
46
-	if ($var_auth) {
47
-		echo auth_echec($var_auth);
48
-		exit;
49
-	}
43
+    // Authentification, redefinissable
44
+    $auth = charger_fonction('auth', 'inc');
45
+    $var_auth = $auth();
46
+    if ($var_auth) {
47
+        echo auth_echec($var_auth);
48
+        exit;
49
+    }
50 50
 }
51 51
 
52 52
 // initialiser a la langue par defaut
@@ -57,29 +57,29 @@  discard block
 block discarded – undo
57 57
 
58 58
 
59 59
 if (_request('action') or _request('var_ajax') or _request('formulaire_action')) {
60
-	if (!autoriser_sans_cookie($exec)) {
61
-		// Charger l'aiguilleur qui va mettre sur la bonne voie les traitements derogatoires
62
-		include_spip('public/aiguiller');
63
-		if (
64
-			// cas des appels actions ?action=xxx
65
-			traiter_appels_actions()
66
-			or
67
-			// cas des hits ajax sur les inclusions ajax
68
-			traiter_appels_inclusions_ajax()
69
-			or
70
-			// cas des formulaires charger/verifier/traiter
71
-			traiter_formulaires_dynamiques()
72
-		) {
73
-			exit;
74
-		} // le hit est fini !
75
-	}
60
+    if (!autoriser_sans_cookie($exec)) {
61
+        // Charger l'aiguilleur qui va mettre sur la bonne voie les traitements derogatoires
62
+        include_spip('public/aiguiller');
63
+        if (
64
+            // cas des appels actions ?action=xxx
65
+            traiter_appels_actions()
66
+            or
67
+            // cas des hits ajax sur les inclusions ajax
68
+            traiter_appels_inclusions_ajax()
69
+            or
70
+            // cas des formulaires charger/verifier/traiter
71
+            traiter_formulaires_dynamiques()
72
+        ) {
73
+            exit;
74
+        } // le hit est fini !
75
+    }
76 76
 }
77 77
 // securiser les redirect du back-office
78 78
 if (_request('redirect')) {
79
-	if (!function_exists('securiser_redirect_action')) {
80
-		include_spip('public/aiguiller');
81
-	}
82
-	set_request('redirect', securiser_redirect_action(_request('redirect')));
79
+    if (!function_exists('securiser_redirect_action')) {
80
+        include_spip('public/aiguiller');
81
+    }
82
+    set_request('redirect', securiser_redirect_action(_request('redirect')));
83 83
 }
84 84
 
85 85
 
@@ -89,12 +89,12 @@  discard block
 block discarded – undo
89 89
 
90 90
 // Controle de la version, sauf si on est deja en train de s'en occuper
91 91
 if (
92
-	!$reinstall == 'oui'
93
-	and !_AJAX
94
-	and isset($GLOBALS['meta']['version_installee'])
95
-	and ($GLOBALS['spip_version_base'] != (str_replace(',', '.', $GLOBALS['meta']['version_installee'])))
92
+    !$reinstall == 'oui'
93
+    and !_AJAX
94
+    and isset($GLOBALS['meta']['version_installee'])
95
+    and ($GLOBALS['spip_version_base'] != (str_replace(',', '.', $GLOBALS['meta']['version_installee'])))
96 96
 ) {
97
-	$exec = 'demande_mise_a_jour';
97
+    $exec = 'demande_mise_a_jour';
98 98
 }
99 99
 
100 100
 // Quand une action d'administration est en cours (meta "admin"),
@@ -104,39 +104,39 @@  discard block
 block discarded – undo
104 104
 // sinon c'est qu'elle a ete interrompue et il faut la reprendre
105 105
 
106 106
 elseif (isset($GLOBALS['meta']['admin'])) {
107
-	if (preg_match('/^(.*)_(\d+)_/', $GLOBALS['meta']['admin'], $l)) {
108
-		[, $var_f, $n] = $l;
109
-	}
110
-	if (
111
-		_AJAX
112
-		or !(
113
-			isset($_COOKIE['spip_admin'])
114
-			or (isset($GLOBALS['visiteur_session']) and $GLOBALS['visiteur_session']['statut'] == '0minirezo')
115
-		)
116
-	) {
117
-		spip_log('Quand la meta admin vaut ' .
118
-			$GLOBALS['meta']['admin'] .
119
-			' seul un admin peut se connecter et sans AJAX.' .
120
-			' En cas de probleme, detruire cette meta.');
121
-		die(_T('info_travaux_texte'));
122
-	}
123
-	if ($n) {
124
-		[, $var_f, $n] = $l;
125
-		if (tester_url_ecrire("base_$var_f")) {
126
-			$var_f = "base_$var_f";
127
-		}
128
-		if ($var_f != $exec) {
129
-			spip_log("Le script $var_f lance par auteur$n se substitue a l'exec $exec");
130
-			$exec = $var_f;
131
-			set_request('exec', $exec);
132
-		}
133
-	}
107
+    if (preg_match('/^(.*)_(\d+)_/', $GLOBALS['meta']['admin'], $l)) {
108
+        [, $var_f, $n] = $l;
109
+    }
110
+    if (
111
+        _AJAX
112
+        or !(
113
+            isset($_COOKIE['spip_admin'])
114
+            or (isset($GLOBALS['visiteur_session']) and $GLOBALS['visiteur_session']['statut'] == '0minirezo')
115
+        )
116
+    ) {
117
+        spip_log('Quand la meta admin vaut ' .
118
+            $GLOBALS['meta']['admin'] .
119
+            ' seul un admin peut se connecter et sans AJAX.' .
120
+            ' En cas de probleme, detruire cette meta.');
121
+        die(_T('info_travaux_texte'));
122
+    }
123
+    if ($n) {
124
+        [, $var_f, $n] = $l;
125
+        if (tester_url_ecrire("base_$var_f")) {
126
+            $var_f = "base_$var_f";
127
+        }
128
+        if ($var_f != $exec) {
129
+            spip_log("Le script $var_f lance par auteur$n se substitue a l'exec $exec");
130
+            $exec = $var_f;
131
+            set_request('exec', $exec);
132
+        }
133
+    }
134 134
 }
135 135
 // si nom pas plausible, prendre le script par defaut
136 136
 // attention aux deux cas 404/403 qui commencent par un 4 !
137 137
 elseif (!preg_match(',^[a-z4_][0-9a-z_-]*$,i', $exec)) {
138
-	$exec = 'accueil';
139
-	set_request('exec', $exec);
138
+    $exec = 'accueil';
139
+    set_request('exec', $exec);
140 140
 }
141 141
 
142 142
 //  si la langue est specifiee par cookie et ne correspond pas
@@ -144,19 +144,19 @@  discard block
 block discarded – undo
144 144
 // on appelle directement la fonction, car un appel d'action peut conduire a une boucle infinie
145 145
 // si le cookie n'est pas pose correctement dans l'action
146 146
 if (
147
-	!$var_auth and isset($_COOKIE['spip_lang_ecrire'])
148
-	and $_COOKIE['spip_lang_ecrire'] <> $GLOBALS['visiteur_session']['lang']
147
+    !$var_auth and isset($_COOKIE['spip_lang_ecrire'])
148
+    and $_COOKIE['spip_lang_ecrire'] <> $GLOBALS['visiteur_session']['lang']
149 149
 ) {
150
-	include_spip('action/converser');
151
-	action_converser_post($GLOBALS['visiteur_session']['lang'], true);
150
+    include_spip('action/converser');
151
+    action_converser_post($GLOBALS['visiteur_session']['lang'], true);
152 152
 }
153 153
 
154 154
 if ($var_f = tester_url_ecrire($exec)) {
155
-	$var_f = charger_fonction($var_f);
156
-	$var_f(); // at last
155
+    $var_f = charger_fonction($var_f);
156
+    $var_f(); // at last
157 157
 } else {
158
-	// Rien de connu: rerouter vers exec=404 au lieu d'echouer
159
-	// ce qui permet de laisser la main a un plugin
160
-	$var_f = charger_fonction('404');
161
-	$var_f($exec);
158
+    // Rien de connu: rerouter vers exec=404 au lieu d'echouer
159
+    // ce qui permet de laisser la main a un plugin
160
+    $var_f = charger_fonction('404');
161
+    $var_f($exec);
162 162
 }
Please login to merge, or discard this patch.
ecrire/inc/flock.php 1 patch
Indentation   +407 added lines, -407 removed lines patch added patch discarded remove patch
@@ -17,12 +17,12 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 if (!defined('_TEST_FILE_EXISTS')) {
24
-	/** Permettre d'éviter des tests file_exists sur certains hébergeurs */
25
-	define('_TEST_FILE_EXISTS', preg_match(',(online|free)[.]fr$,', $_ENV['HTTP_HOST'] ?? ''));
24
+    /** Permettre d'éviter des tests file_exists sur certains hébergeurs */
25
+    define('_TEST_FILE_EXISTS', preg_match(',(online|free)[.]fr$,', $_ENV['HTTP_HOST'] ?? ''));
26 26
 }
27 27
 
28 28
 #define('_SPIP_LOCK_MODE',0); // ne pas utiliser de lock (deconseille)
@@ -30,7 +30,7 @@  discard block
 block discarded – undo
30 30
 #define('_SPIP_LOCK_MODE',2); // utiliser le nfslock de spip
31 31
 
32 32
 if (_SPIP_LOCK_MODE == 2) {
33
-	include_spip('inc/nfslock');
33
+    include_spip('inc/nfslock');
34 34
 }
35 35
 
36 36
 $GLOBALS['liste_verrous'] = [];
@@ -53,24 +53,24 @@  discard block
 block discarded – undo
53 53
  *     Ressource sur le fichier ouvert, sinon false.
54 54
  **/
55 55
 function spip_fopen_lock($fichier, $mode, $verrou) {
56
-	if (_SPIP_LOCK_MODE == 1) {
57
-		if ($fl = @fopen($fichier, $mode)) {
58
-			// verrou
59
-			@flock($fl, $verrou);
60
-		}
61
-
62
-		return $fl;
63
-	} elseif (_SPIP_LOCK_MODE == 2) {
64
-		if (($verrou = spip_nfslock($fichier)) && ($fl = @fopen($fichier, $mode))) {
65
-			$GLOBALS['liste_verrous'][$fl] = [$fichier, $verrou];
66
-
67
-			return $fl;
68
-		} else {
69
-			return false;
70
-		}
71
-	}
72
-
73
-	return @fopen($fichier, $mode);
56
+    if (_SPIP_LOCK_MODE == 1) {
57
+        if ($fl = @fopen($fichier, $mode)) {
58
+            // verrou
59
+            @flock($fl, $verrou);
60
+        }
61
+
62
+        return $fl;
63
+    } elseif (_SPIP_LOCK_MODE == 2) {
64
+        if (($verrou = spip_nfslock($fichier)) && ($fl = @fopen($fichier, $mode))) {
65
+            $GLOBALS['liste_verrous'][$fl] = [$fichier, $verrou];
66
+
67
+            return $fl;
68
+        } else {
69
+            return false;
70
+        }
71
+    }
72
+
73
+    return @fopen($fichier, $mode);
74 74
 }
75 75
 
76 76
 /**
@@ -85,14 +85,14 @@  discard block
 block discarded – undo
85 85
  *     true si succès, false sinon.
86 86
  **/
87 87
 function spip_fclose_unlock($handle) {
88
-	if (_SPIP_LOCK_MODE == 1) {
89
-		@flock($handle, LOCK_UN);
90
-	} elseif (_SPIP_LOCK_MODE == 2) {
91
-		spip_nfsunlock(reset($GLOBALS['liste_verrous'][$handle]), end($GLOBALS['liste_verrous'][$handle]));
92
-		unset($GLOBALS['liste_verrous'][$handle]);
93
-	}
94
-
95
-	return @fclose($handle);
88
+    if (_SPIP_LOCK_MODE == 1) {
89
+        @flock($handle, LOCK_UN);
90
+    } elseif (_SPIP_LOCK_MODE == 2) {
91
+        spip_nfsunlock(reset($GLOBALS['liste_verrous'][$handle]), end($GLOBALS['liste_verrous'][$handle]));
92
+        unset($GLOBALS['liste_verrous'][$handle]);
93
+    }
94
+
95
+    return @fclose($handle);
96 96
 }
97 97
 
98 98
 
@@ -106,23 +106,23 @@  discard block
 block discarded – undo
106 106
  *     Contenu du fichier
107 107
  **/
108 108
 function spip_file_get_contents($fichier) {
109
-	if (substr($fichier, -3) != '.gz') {
110
-		if (function_exists('file_get_contents')) {
111
-			// quand on est sous windows on ne sait pas si file_get_contents marche
112
-			// on essaye : si ca retourne du contenu alors c'est bon
113
-			// sinon on fait un file() pour avoir le coeur net
114
-			$contenu = @file_get_contents($fichier);
115
-			if (!$contenu and _OS_SERVEUR == 'windows') {
116
-				$contenu = @file($fichier);
117
-			}
118
-		} else {
119
-			$contenu = @file($fichier);
120
-		}
121
-	} else {
122
-		$contenu = @gzfile($fichier);
123
-	}
124
-
125
-	return is_array($contenu) ? join('', $contenu) : (string)$contenu;
109
+    if (substr($fichier, -3) != '.gz') {
110
+        if (function_exists('file_get_contents')) {
111
+            // quand on est sous windows on ne sait pas si file_get_contents marche
112
+            // on essaye : si ca retourne du contenu alors c'est bon
113
+            // sinon on fait un file() pour avoir le coeur net
114
+            $contenu = @file_get_contents($fichier);
115
+            if (!$contenu and _OS_SERVEUR == 'windows') {
116
+                $contenu = @file($fichier);
117
+            }
118
+        } else {
119
+            $contenu = @file($fichier);
120
+        }
121
+    } else {
122
+        $contenu = @gzfile($fichier);
123
+    }
124
+
125
+    return is_array($contenu) ? join('', $contenu) : (string)$contenu;
126 126
 }
127 127
 
128 128
 
@@ -147,48 +147,48 @@  discard block
 block discarded – undo
147 147
  *     true si l'opération a réussie, false sinon.
148 148
  **/
149 149
 function lire_fichier($fichier, &$contenu, $options = []) {
150
-	$contenu = '';
151
-	// inutile car si le fichier n'existe pas, le lock va renvoyer false juste apres
152
-	// economisons donc les acces disque, sauf chez free qui rale pour un rien
153
-	if (_TEST_FILE_EXISTS and !@file_exists($fichier)) {
154
-		return false;
155
-	}
156
-
157
-	#spip_timer('lire_fichier');
158
-
159
-	// pas de @ sur spip_fopen_lock qui est silencieux de toute facon
160
-	if ($fl = spip_fopen_lock($fichier, 'r', LOCK_SH)) {
161
-		// lire le fichier avant tout
162
-		$contenu = spip_file_get_contents($fichier);
163
-
164
-		// le fichier a-t-il ete supprime par le locker ?
165
-		// on ne verifie que si la tentative de lecture a echoue
166
-		// pour discriminer un contenu vide d'un fichier absent
167
-		// et eviter un acces disque
168
-		if (!$contenu and !@file_exists($fichier)) {
169
-			spip_fclose_unlock($fl);
170
-
171
-			return false;
172
-		}
173
-
174
-		// liberer le verrou
175
-		spip_fclose_unlock($fl);
176
-
177
-		// Verifications
178
-		$ok = true;
179
-		if (isset($options['phpcheck']) and $options['phpcheck'] == 'oui') {
180
-			$ok &= (preg_match(",[?]>\n?$,", $contenu));
181
-		}
182
-
183
-		#spip_log("$fread $fichier ".spip_timer('lire_fichier'));
184
-		if (!$ok) {
185
-			spip_log("echec lecture $fichier");
186
-		}
187
-
188
-		return $ok;
189
-	}
190
-
191
-	return false;
150
+    $contenu = '';
151
+    // inutile car si le fichier n'existe pas, le lock va renvoyer false juste apres
152
+    // economisons donc les acces disque, sauf chez free qui rale pour un rien
153
+    if (_TEST_FILE_EXISTS and !@file_exists($fichier)) {
154
+        return false;
155
+    }
156
+
157
+    #spip_timer('lire_fichier');
158
+
159
+    // pas de @ sur spip_fopen_lock qui est silencieux de toute facon
160
+    if ($fl = spip_fopen_lock($fichier, 'r', LOCK_SH)) {
161
+        // lire le fichier avant tout
162
+        $contenu = spip_file_get_contents($fichier);
163
+
164
+        // le fichier a-t-il ete supprime par le locker ?
165
+        // on ne verifie que si la tentative de lecture a echoue
166
+        // pour discriminer un contenu vide d'un fichier absent
167
+        // et eviter un acces disque
168
+        if (!$contenu and !@file_exists($fichier)) {
169
+            spip_fclose_unlock($fl);
170
+
171
+            return false;
172
+        }
173
+
174
+        // liberer le verrou
175
+        spip_fclose_unlock($fl);
176
+
177
+        // Verifications
178
+        $ok = true;
179
+        if (isset($options['phpcheck']) and $options['phpcheck'] == 'oui') {
180
+            $ok &= (preg_match(",[?]>\n?$,", $contenu));
181
+        }
182
+
183
+        #spip_log("$fread $fichier ".spip_timer('lire_fichier'));
184
+        if (!$ok) {
185
+            spip_log("echec lecture $fichier");
186
+        }
187
+
188
+        return $ok;
189
+    }
190
+
191
+    return false;
192 192
 }
193 193
 
194 194
 
@@ -216,85 +216,85 @@  discard block
 block discarded – undo
216 216
  **/
217 217
 function ecrire_fichier($fichier, $contenu, $ignorer_echec = false, $truncate = true) {
218 218
 
219
-	#spip_timer('ecrire_fichier');
220
-
221
-	// verrouiller le fichier destination
222
-	if ($fp = spip_fopen_lock($fichier, 'a', LOCK_EX)) {
223
-		// ecrire les donnees, compressees le cas echeant
224
-		// (on ouvre un nouveau pointeur sur le fichier, ce qui a l'avantage
225
-		// de le recreer si le locker qui nous precede l'avait supprime...)
226
-		if (substr($fichier, -3) == '.gz') {
227
-			$contenu = gzencode($contenu);
228
-		}
229
-		// si c'est une ecriture avec troncation , on fait plutot une ecriture complete a cote suivie unlink+rename
230
-		// pour etre sur d'avoir une operation atomique
231
-		// y compris en NFS : http://www.ietf.org/rfc/rfc1094.txt
232
-		// sauf sous wintruc ou ca ne marche pas
233
-		$ok = false;
234
-		if ($truncate and _OS_SERVEUR != 'windows') {
235
-			if (!function_exists('creer_uniqid')) {
236
-				include_spip('inc/acces');
237
-			}
238
-			$id = creer_uniqid();
239
-			// on ouvre un pointeur sur un fichier temporaire en ecriture +raz
240
-			if ($fp2 = spip_fopen_lock("$fichier.$id", 'w', LOCK_EX)) {
241
-				$s = @fputs($fp2, $contenu, $a = strlen($contenu));
242
-				$ok = ($s == $a);
243
-				spip_fclose_unlock($fp2);
244
-				spip_fclose_unlock($fp);
245
-				// unlink direct et pas spip_unlink car on avait deja le verrou
246
-				// a priori pas besoin car rename ecrase la cible
247
-				// @unlink($fichier);
248
-				// le rename aussitot, atomique quand on est pas sous windows
249
-				// au pire on arrive en second en cas de concourance, et le rename echoue
250
-				// --> on a la version de l'autre process qui doit etre identique
251
-				@rename("$fichier.$id", $fichier);
252
-				// precaution en cas d'echec du rename
253
-				if (!_TEST_FILE_EXISTS or @file_exists("$fichier.$id")) {
254
-					@unlink("$fichier.$id");
255
-				}
256
-				if ($ok) {
257
-					$ok = file_exists($fichier);
258
-				}
259
-			} else // echec mais penser a fermer ..
260
-			{
261
-				spip_fclose_unlock($fp);
262
-			}
263
-		}
264
-		// sinon ou si methode precedente a echoueee
265
-		// on se rabat sur la methode ancienne
266
-		if (!$ok) {
267
-			// ici on est en ajout ou sous windows, cas desespere
268
-			if ($truncate) {
269
-				@ftruncate($fp, 0);
270
-			}
271
-			$s = @fputs($fp, $contenu, $a = strlen($contenu));
272
-
273
-			$ok = ($s == $a);
274
-			spip_fclose_unlock($fp);
275
-		}
276
-
277
-		// liberer le verrou et fermer le fichier
278
-		@chmod($fichier, _SPIP_CHMOD & 0666);
279
-		if ($ok) {
280
-			if (strpos($fichier, '.php') !== false) {
281
-				spip_clear_opcode_cache(realpath($fichier));
282
-			}
283
-
284
-			return $ok;
285
-		}
286
-	}
287
-
288
-	if (!$ignorer_echec) {
289
-		include_spip('inc/autoriser');
290
-		if (autoriser('chargerftp')) {
291
-			raler_fichier($fichier);
292
-		}
293
-		spip_unlink($fichier);
294
-	}
295
-	spip_log("Ecriture fichier $fichier impossible", _LOG_INFO_IMPORTANTE);
296
-
297
-	return false;
219
+    #spip_timer('ecrire_fichier');
220
+
221
+    // verrouiller le fichier destination
222
+    if ($fp = spip_fopen_lock($fichier, 'a', LOCK_EX)) {
223
+        // ecrire les donnees, compressees le cas echeant
224
+        // (on ouvre un nouveau pointeur sur le fichier, ce qui a l'avantage
225
+        // de le recreer si le locker qui nous precede l'avait supprime...)
226
+        if (substr($fichier, -3) == '.gz') {
227
+            $contenu = gzencode($contenu);
228
+        }
229
+        // si c'est une ecriture avec troncation , on fait plutot une ecriture complete a cote suivie unlink+rename
230
+        // pour etre sur d'avoir une operation atomique
231
+        // y compris en NFS : http://www.ietf.org/rfc/rfc1094.txt
232
+        // sauf sous wintruc ou ca ne marche pas
233
+        $ok = false;
234
+        if ($truncate and _OS_SERVEUR != 'windows') {
235
+            if (!function_exists('creer_uniqid')) {
236
+                include_spip('inc/acces');
237
+            }
238
+            $id = creer_uniqid();
239
+            // on ouvre un pointeur sur un fichier temporaire en ecriture +raz
240
+            if ($fp2 = spip_fopen_lock("$fichier.$id", 'w', LOCK_EX)) {
241
+                $s = @fputs($fp2, $contenu, $a = strlen($contenu));
242
+                $ok = ($s == $a);
243
+                spip_fclose_unlock($fp2);
244
+                spip_fclose_unlock($fp);
245
+                // unlink direct et pas spip_unlink car on avait deja le verrou
246
+                // a priori pas besoin car rename ecrase la cible
247
+                // @unlink($fichier);
248
+                // le rename aussitot, atomique quand on est pas sous windows
249
+                // au pire on arrive en second en cas de concourance, et le rename echoue
250
+                // --> on a la version de l'autre process qui doit etre identique
251
+                @rename("$fichier.$id", $fichier);
252
+                // precaution en cas d'echec du rename
253
+                if (!_TEST_FILE_EXISTS or @file_exists("$fichier.$id")) {
254
+                    @unlink("$fichier.$id");
255
+                }
256
+                if ($ok) {
257
+                    $ok = file_exists($fichier);
258
+                }
259
+            } else // echec mais penser a fermer ..
260
+            {
261
+                spip_fclose_unlock($fp);
262
+            }
263
+        }
264
+        // sinon ou si methode precedente a echoueee
265
+        // on se rabat sur la methode ancienne
266
+        if (!$ok) {
267
+            // ici on est en ajout ou sous windows, cas desespere
268
+            if ($truncate) {
269
+                @ftruncate($fp, 0);
270
+            }
271
+            $s = @fputs($fp, $contenu, $a = strlen($contenu));
272
+
273
+            $ok = ($s == $a);
274
+            spip_fclose_unlock($fp);
275
+        }
276
+
277
+        // liberer le verrou et fermer le fichier
278
+        @chmod($fichier, _SPIP_CHMOD & 0666);
279
+        if ($ok) {
280
+            if (strpos($fichier, '.php') !== false) {
281
+                spip_clear_opcode_cache(realpath($fichier));
282
+            }
283
+
284
+            return $ok;
285
+        }
286
+    }
287
+
288
+    if (!$ignorer_echec) {
289
+        include_spip('inc/autoriser');
290
+        if (autoriser('chargerftp')) {
291
+            raler_fichier($fichier);
292
+        }
293
+        spip_unlink($fichier);
294
+    }
295
+    spip_log("Ecriture fichier $fichier impossible", _LOG_INFO_IMPORTANTE);
296
+
297
+    return false;
298 298
 }
299 299
 
300 300
 /**
@@ -314,12 +314,12 @@  discard block
 block discarded – undo
314 314
  *     Écriture avec troncation ?
315 315
  */
316 316
 function ecrire_fichier_securise($fichier, $contenu, $ecrire_quand_meme = false, $truncate = true) {
317
-	if (substr($fichier, -4) !== '.php') {
318
-		spip_log('Erreur de programmation: ' . $fichier . ' doit finir par .php');
319
-	}
320
-	$contenu = '<' . "?php die ('Acces interdit'); ?" . ">\n" . $contenu;
317
+    if (substr($fichier, -4) !== '.php') {
318
+        spip_log('Erreur de programmation: ' . $fichier . ' doit finir par .php');
319
+    }
320
+    $contenu = '<' . "?php die ('Acces interdit'); ?" . ">\n" . $contenu;
321 321
 
322
-	return ecrire_fichier($fichier, $contenu, $ecrire_quand_meme, $truncate);
322
+    return ecrire_fichier($fichier, $contenu, $ecrire_quand_meme, $truncate);
323 323
 }
324 324
 
325 325
 
@@ -330,25 +330,25 @@  discard block
 block discarded – undo
330 330
  * @return bool
331 331
  */
332 332
 function ecrire_fichier_calcule_si_modifie($fichier, $contenu, $force = false, $use_copy = false) {
333
-	$fichier_tmp = $fichier . '.last';
334
-	if (!ecrire_fichier($fichier_tmp, $contenu, true)) {
335
-		return false;
336
-	}
337
-	if (
338
-		$force
339
-		or !file_exists($fichier)
340
-		or md5_file($fichier) != md5_file($fichier_tmp)
341
-	) {
342
-		if ($use_copy) {
343
-			@copy($fichier_tmp, $fichier);
344
-		}
345
-		else {
346
-			@rename($fichier_tmp, $fichier);
347
-		}
348
-		// eviter que PHP ne reserve le vieux timestamp
349
-		clearstatcache(true, $fichier);
350
-	}
351
-	return true;
333
+    $fichier_tmp = $fichier . '.last';
334
+    if (!ecrire_fichier($fichier_tmp, $contenu, true)) {
335
+        return false;
336
+    }
337
+    if (
338
+        $force
339
+        or !file_exists($fichier)
340
+        or md5_file($fichier) != md5_file($fichier_tmp)
341
+    ) {
342
+        if ($use_copy) {
343
+            @copy($fichier_tmp, $fichier);
344
+        }
345
+        else {
346
+            @rename($fichier_tmp, $fichier);
347
+        }
348
+        // eviter que PHP ne reserve le vieux timestamp
349
+        clearstatcache(true, $fichier);
350
+    }
351
+    return true;
352 352
 }
353 353
 
354 354
 
@@ -369,11 +369,11 @@  discard block
 block discarded – undo
369 369
  *     true si l'opération a réussie, false sinon.
370 370
  */
371 371
 function lire_fichier_securise($fichier, &$contenu, $options = []) {
372
-	if ($res = lire_fichier($fichier, $contenu, $options)) {
373
-		$contenu = substr($contenu, strlen('<' . "?php die ('Acces interdit'); ?" . ">\n"));
374
-	}
372
+    if ($res = lire_fichier($fichier, $contenu, $options)) {
373
+        $contenu = substr($contenu, strlen('<' . "?php die ('Acces interdit'); ?" . ">\n"));
374
+    }
375 375
 
376
-	return $res;
376
+    return $res;
377 377
 }
378 378
 
379 379
 /**
@@ -388,25 +388,25 @@  discard block
 block discarded – undo
388 388
  *     Chemin du fichier
389 389
  **/
390 390
 function raler_fichier($fichier) {
391
-	if (!defined('_SPIP_ECRIRE_SCRIPT')) {
392
-		spip_initialisation_suite();
393
-	}
394
-	include_spip('inc/minipres');
395
-	$dir = dirname($fichier);
396
-	http_response_code(401);
397
-	echo minipres(_T('texte_inc_meta_2'), "<h4 style='color: red'>"
398
-		. _T('texte_inc_meta_1', ['fichier' => $fichier])
399
-		. " <a href='"
400
-		. generer_url_ecrire('install', "etape=chmod&test_dir=$dir")
401
-		. "'>"
402
-		. _T('texte_inc_meta_2')
403
-		. '</a> '
404
-		. _T(
405
-			'texte_inc_meta_3',
406
-			['repertoire' => joli_repertoire($dir)]
407
-		)
408
-		. "</h4>\n");
409
-	exit;
391
+    if (!defined('_SPIP_ECRIRE_SCRIPT')) {
392
+        spip_initialisation_suite();
393
+    }
394
+    include_spip('inc/minipres');
395
+    $dir = dirname($fichier);
396
+    http_response_code(401);
397
+    echo minipres(_T('texte_inc_meta_2'), "<h4 style='color: red'>"
398
+        . _T('texte_inc_meta_1', ['fichier' => $fichier])
399
+        . " <a href='"
400
+        . generer_url_ecrire('install', "etape=chmod&test_dir=$dir")
401
+        . "'>"
402
+        . _T('texte_inc_meta_2')
403
+        . '</a> '
404
+        . _T(
405
+            'texte_inc_meta_3',
406
+            ['repertoire' => joli_repertoire($dir)]
407
+        )
408
+        . "</h4>\n");
409
+    exit;
410 410
 }
411 411
 
412 412
 
@@ -421,14 +421,14 @@  discard block
 block discarded – undo
421 421
  *     - true si récent, false sinon
422 422
  */
423 423
 function jeune_fichier($fichier, $n) {
424
-	if (!file_exists($fichier)) {
425
-		return false;
426
-	}
427
-	if (!$c = @filemtime($fichier)) {
428
-		return false;
429
-	}
430
-
431
-	return (time() - $n <= $c);
424
+    if (!file_exists($fichier)) {
425
+        return false;
426
+    }
427
+    if (!$c = @filemtime($fichier)) {
428
+        return false;
429
+    }
430
+
431
+    return (time() - $n <= $c);
432 432
 }
433 433
 
434 434
 /**
@@ -443,22 +443,22 @@  discard block
 block discarded – undo
443 443
  *     - false si on n'arrive pas poser le verrou ou si la suppression échoue
444 444
  */
445 445
 function supprimer_fichier($fichier, $lock = true) {
446
-	if (!@file_exists($fichier)) {
447
-		return true;
448
-	}
449
-
450
-	if ($lock) {
451
-		// verrouiller le fichier destination
452
-		if (!$fp = spip_fopen_lock($fichier, 'a', LOCK_EX)) {
453
-			return false;
454
-		}
455
-
456
-		// liberer le verrou
457
-		spip_fclose_unlock($fp);
458
-	}
459
-
460
-	// supprimer
461
-	return @unlink($fichier);
446
+    if (!@file_exists($fichier)) {
447
+        return true;
448
+    }
449
+
450
+    if ($lock) {
451
+        // verrouiller le fichier destination
452
+        if (!$fp = spip_fopen_lock($fichier, 'a', LOCK_EX)) {
453
+            return false;
454
+        }
455
+
456
+        // liberer le verrou
457
+        spip_fclose_unlock($fp);
458
+    }
459
+
460
+    // supprimer
461
+    return @unlink($fichier);
462 462
 }
463 463
 
464 464
 /**
@@ -468,12 +468,12 @@  discard block
 block discarded – undo
468 468
  *     Chemin du fichier
469 469
  */
470 470
 function spip_unlink($f) {
471
-	if (!is_dir($f)) {
472
-		supprimer_fichier($f, false);
473
-	} else {
474
-		@unlink("$f/.ok");
475
-		@rmdir($f);
476
-	}
471
+    if (!is_dir($f)) {
472
+        supprimer_fichier($f, false);
473
+    } else {
474
+        @unlink("$f/.ok");
475
+        @rmdir($f);
476
+    }
477 477
 }
478 478
 
479 479
 /**
@@ -487,26 +487,26 @@  discard block
 block discarded – undo
487 487
  *   The absolute path of the PHP file to invalidate.
488 488
  */
489 489
 function spip_clear_opcode_cache($filepath) {
490
-	clearstatcache(true, $filepath);
491
-
492
-	// Zend OPcache
493
-	if (function_exists('opcache_invalidate')) {
494
-		$invalidate = @opcache_invalidate($filepath, true);
495
-		// si l'invalidation a echoue lever un flag
496
-		if (!$invalidate and !defined('_spip_attend_invalidation_opcode_cache')) {
497
-			define('_spip_attend_invalidation_opcode_cache', true);
498
-		}
499
-	} elseif (!defined('_spip_attend_invalidation_opcode_cache')) {
500
-		// n'agira que si opcache est effectivement actif (il semble qu'on a pas toujours la fonction opcache_invalidate)
501
-		define('_spip_attend_invalidation_opcode_cache', true);
502
-	}
503
-	// APC.
504
-	if (function_exists('apc_delete_file')) {
505
-		// apc_delete_file() throws a PHP warning in case the specified file was
506
-		// not compiled yet.
507
-		// @see http://php.net/apc-delete-file
508
-		@apc_delete_file($filepath);
509
-	}
490
+    clearstatcache(true, $filepath);
491
+
492
+    // Zend OPcache
493
+    if (function_exists('opcache_invalidate')) {
494
+        $invalidate = @opcache_invalidate($filepath, true);
495
+        // si l'invalidation a echoue lever un flag
496
+        if (!$invalidate and !defined('_spip_attend_invalidation_opcode_cache')) {
497
+            define('_spip_attend_invalidation_opcode_cache', true);
498
+        }
499
+    } elseif (!defined('_spip_attend_invalidation_opcode_cache')) {
500
+        // n'agira que si opcache est effectivement actif (il semble qu'on a pas toujours la fonction opcache_invalidate)
501
+        define('_spip_attend_invalidation_opcode_cache', true);
502
+    }
503
+    // APC.
504
+    if (function_exists('apc_delete_file')) {
505
+        // apc_delete_file() throws a PHP warning in case the specified file was
506
+        // not compiled yet.
507
+        // @see http://php.net/apc-delete-file
508
+        @apc_delete_file($filepath);
509
+    }
510 510
 }
511 511
 
512 512
 /**
@@ -529,25 +529,25 @@  discard block
 block discarded – undo
529 529
  *
530 530
  */
531 531
 function spip_attend_invalidation_opcode_cache($timestamp = null) {
532
-	if (
533
-		function_exists('opcache_get_configuration')
534
-		and @ini_get('opcache.enable')
535
-		and @ini_get('opcache.validate_timestamps')
536
-		and ($duree = intval(@ini_get('opcache.revalidate_freq')) or $duree = 2)
537
-		and defined('_spip_attend_invalidation_opcode_cache') // des invalidations ont echouees
538
-	) {
539
-		$wait = $duree + 1;
540
-		if ($timestamp) {
541
-			$wait -= (time() - $timestamp);
542
-			if ($wait < 0) {
543
-				$wait = 0;
544
-			}
545
-		}
546
-		spip_log('Probleme de configuration opcache.revalidate_freq ' . $duree . 's : on attend ' . $wait . 's', _LOG_INFO_IMPORTANTE);
547
-		if ($wait) {
548
-			sleep($duree + 1);
549
-		}
550
-	}
532
+    if (
533
+        function_exists('opcache_get_configuration')
534
+        and @ini_get('opcache.enable')
535
+        and @ini_get('opcache.validate_timestamps')
536
+        and ($duree = intval(@ini_get('opcache.revalidate_freq')) or $duree = 2)
537
+        and defined('_spip_attend_invalidation_opcode_cache') // des invalidations ont echouees
538
+    ) {
539
+        $wait = $duree + 1;
540
+        if ($timestamp) {
541
+            $wait -= (time() - $timestamp);
542
+            if ($wait < 0) {
543
+                $wait = 0;
544
+            }
545
+        }
546
+        spip_log('Probleme de configuration opcache.revalidate_freq ' . $duree . 's : on attend ' . $wait . 's', _LOG_INFO_IMPORTANTE);
547
+        if ($wait) {
548
+            sleep($duree + 1);
549
+        }
550
+    }
551 551
 }
552 552
 
553 553
 
@@ -560,26 +560,26 @@  discard block
 block discarded – undo
560 560
  * @return bool Suppression reussie.
561 561
  */
562 562
 function supprimer_repertoire($dir) {
563
-	if (!file_exists($dir)) {
564
-		return true;
565
-	}
566
-	if (!is_dir($dir) || is_link($dir)) {
567
-		return @unlink($dir);
568
-	}
569
-
570
-	foreach (scandir($dir) as $item) {
571
-		if ($item == '.' || $item == '..') {
572
-			continue;
573
-		}
574
-		if (!supprimer_repertoire($dir . '/' . $item)) {
575
-			@chmod($dir . '/' . $item, 0777);
576
-			if (!supprimer_repertoire($dir . '/' . $item)) {
577
-				return false;
578
-			}
579
-		};
580
-	}
581
-
582
-	return @rmdir($dir);
563
+    if (!file_exists($dir)) {
564
+        return true;
565
+    }
566
+    if (!is_dir($dir) || is_link($dir)) {
567
+        return @unlink($dir);
568
+    }
569
+
570
+    foreach (scandir($dir) as $item) {
571
+        if ($item == '.' || $item == '..') {
572
+            continue;
573
+        }
574
+        if (!supprimer_repertoire($dir . '/' . $item)) {
575
+            @chmod($dir . '/' . $item, 0777);
576
+            if (!supprimer_repertoire($dir . '/' . $item)) {
577
+                return false;
578
+            }
579
+        };
580
+    }
581
+
582
+    return @rmdir($dir);
583 583
 }
584 584
 
585 585
 
@@ -608,57 +608,57 @@  discard block
 block discarded – undo
608 608
  *     Chemin du répertoire créé.
609 609
  **/
610 610
 function sous_repertoire($base, $subdir = '', $nobase = false, $tantpis = false) {
611
-	static $dirs = [];
612
-
613
-	$base = str_replace('//', '/', $base);
614
-
615
-	# suppr le dernier caractere si c'est un /
616
-	$base = rtrim($base, '/');
617
-
618
-	if (!strlen($subdir)) {
619
-		$n = strrpos($base, '/');
620
-		if ($n === false) {
621
-			return $nobase ? '' : ($base . '/');
622
-		}
623
-		$subdir = substr($base, $n + 1);
624
-		$base = substr($base, 0, $n + 1);
625
-	} else {
626
-		$base .= '/';
627
-		$subdir = str_replace('/', '', $subdir);
628
-	}
629
-
630
-	$baseaff = $nobase ? '' : $base;
631
-	if (isset($dirs[$base . $subdir])) {
632
-		return $baseaff . $dirs[$base . $subdir];
633
-	}
634
-
635
-	$path = $base . $subdir; # $path = 'IMG/distant/pdf' ou 'IMG/distant_pdf'
636
-
637
-	if (file_exists("$path/.ok")) {
638
-		return $baseaff . ($dirs[$base . $subdir] = "$subdir/");
639
-	}
640
-
641
-	@mkdir($path, _SPIP_CHMOD);
642
-	@chmod($path, _SPIP_CHMOD);
643
-
644
-	if (is_dir($path) && is_writable($path)) {
645
-		@touch("$path/.ok");
646
-		spip_log("creation $base$subdir/");
647
-
648
-		return $baseaff . ($dirs[$base . $subdir] = "$subdir/");
649
-	}
650
-
651
-	// en cas d'echec c'est peut etre tout simplement que le disque est plein :
652
-	// l'inode du fichier dir_test existe, mais impossible d'y mettre du contenu
653
-	spip_log("echec creation $base{$subdir}");
654
-	if ($tantpis) {
655
-		return '';
656
-	}
657
-	if (!_DIR_RESTREINT) {
658
-		$base = preg_replace(',^' . _DIR_RACINE . ',', '', $base);
659
-	}
660
-	$base .= $subdir;
661
-	raler_fichier($base . '/.ok');
611
+    static $dirs = [];
612
+
613
+    $base = str_replace('//', '/', $base);
614
+
615
+    # suppr le dernier caractere si c'est un /
616
+    $base = rtrim($base, '/');
617
+
618
+    if (!strlen($subdir)) {
619
+        $n = strrpos($base, '/');
620
+        if ($n === false) {
621
+            return $nobase ? '' : ($base . '/');
622
+        }
623
+        $subdir = substr($base, $n + 1);
624
+        $base = substr($base, 0, $n + 1);
625
+    } else {
626
+        $base .= '/';
627
+        $subdir = str_replace('/', '', $subdir);
628
+    }
629
+
630
+    $baseaff = $nobase ? '' : $base;
631
+    if (isset($dirs[$base . $subdir])) {
632
+        return $baseaff . $dirs[$base . $subdir];
633
+    }
634
+
635
+    $path = $base . $subdir; # $path = 'IMG/distant/pdf' ou 'IMG/distant_pdf'
636
+
637
+    if (file_exists("$path/.ok")) {
638
+        return $baseaff . ($dirs[$base . $subdir] = "$subdir/");
639
+    }
640
+
641
+    @mkdir($path, _SPIP_CHMOD);
642
+    @chmod($path, _SPIP_CHMOD);
643
+
644
+    if (is_dir($path) && is_writable($path)) {
645
+        @touch("$path/.ok");
646
+        spip_log("creation $base$subdir/");
647
+
648
+        return $baseaff . ($dirs[$base . $subdir] = "$subdir/");
649
+    }
650
+
651
+    // en cas d'echec c'est peut etre tout simplement que le disque est plein :
652
+    // l'inode du fichier dir_test existe, mais impossible d'y mettre du contenu
653
+    spip_log("echec creation $base{$subdir}");
654
+    if ($tantpis) {
655
+        return '';
656
+    }
657
+    if (!_DIR_RESTREINT) {
658
+        $base = preg_replace(',^' . _DIR_RACINE . ',', '', $base);
659
+    }
660
+    $base .= $subdir;
661
+    raler_fichier($base . '/.ok');
662 662
 }
663 663
 
664 664
 
@@ -691,56 +691,56 @@  discard block
 block discarded – undo
691 691
  *     Chemins des fichiers trouvés.
692 692
  **/
693 693
 function preg_files($dir, $pattern = -1 /* AUTO */, $maxfiles = 10000, $recurs = []) {
694
-	$nbfiles = 0;
695
-	if ($pattern == -1) {
696
-		$pattern = '';
697
-	}
698
-	$fichiers = [];
699
-	// revenir au repertoire racine si on a recu dossier/truc
700
-	// pour regarder dossier/truc/ ne pas oublier le / final
701
-	$dir = preg_replace(',/[^/]*$,', '', $dir);
702
-	if ($dir == '') {
703
-		$dir = '.';
704
-	}
705
-
706
-	if (@is_dir($dir) and is_readable($dir) and $d = opendir($dir)) {
707
-		while (($f = readdir($d)) !== false && ($nbfiles < $maxfiles)) {
708
-			if (
709
-				$f[0] != '.' # ignorer . .. .svn etc
710
-				and $f != 'CVS'
711
-				and $f != 'remove.txt'
712
-				and is_readable($f = "$dir/$f")
713
-			) {
714
-				if (is_file($f)) {
715
-					if (!$pattern or preg_match(";$pattern;iS", $f)) {
716
-						$fichiers[] = $f;
717
-						$nbfiles++;
718
-					}
719
-				} else {
720
-					if (is_dir($f) and is_array($recurs)) {
721
-						$rp = @realpath($f);
722
-						if (!is_string($rp) or !strlen($rp)) {
723
-							$rp = $f;
724
-						} # realpath n'est peut etre pas autorise
725
-						if (!isset($recurs[$rp])) {
726
-							$recurs[$rp] = true;
727
-							$beginning = $fichiers;
728
-							$end = preg_files(
729
-								"$f/",
730
-								$pattern,
731
-								$maxfiles - $nbfiles,
732
-								$recurs
733
-							);
734
-							$fichiers = array_merge((array)$beginning, (array)$end);
735
-							$nbfiles = count($fichiers);
736
-						}
737
-					}
738
-				}
739
-			}
740
-		}
741
-		closedir($d);
742
-	}
743
-	sort($fichiers);
744
-
745
-	return $fichiers;
694
+    $nbfiles = 0;
695
+    if ($pattern == -1) {
696
+        $pattern = '';
697
+    }
698
+    $fichiers = [];
699
+    // revenir au repertoire racine si on a recu dossier/truc
700
+    // pour regarder dossier/truc/ ne pas oublier le / final
701
+    $dir = preg_replace(',/[^/]*$,', '', $dir);
702
+    if ($dir == '') {
703
+        $dir = '.';
704
+    }
705
+
706
+    if (@is_dir($dir) and is_readable($dir) and $d = opendir($dir)) {
707
+        while (($f = readdir($d)) !== false && ($nbfiles < $maxfiles)) {
708
+            if (
709
+                $f[0] != '.' # ignorer . .. .svn etc
710
+                and $f != 'CVS'
711
+                and $f != 'remove.txt'
712
+                and is_readable($f = "$dir/$f")
713
+            ) {
714
+                if (is_file($f)) {
715
+                    if (!$pattern or preg_match(";$pattern;iS", $f)) {
716
+                        $fichiers[] = $f;
717
+                        $nbfiles++;
718
+                    }
719
+                } else {
720
+                    if (is_dir($f) and is_array($recurs)) {
721
+                        $rp = @realpath($f);
722
+                        if (!is_string($rp) or !strlen($rp)) {
723
+                            $rp = $f;
724
+                        } # realpath n'est peut etre pas autorise
725
+                        if (!isset($recurs[$rp])) {
726
+                            $recurs[$rp] = true;
727
+                            $beginning = $fichiers;
728
+                            $end = preg_files(
729
+                                "$f/",
730
+                                $pattern,
731
+                                $maxfiles - $nbfiles,
732
+                                $recurs
733
+                            );
734
+                            $fichiers = array_merge((array)$beginning, (array)$end);
735
+                            $nbfiles = count($fichiers);
736
+                        }
737
+                    }
738
+                }
739
+            }
740
+        }
741
+        closedir($d);
742
+    }
743
+    sort($fichiers);
744
+
745
+    return $fichiers;
746 746
 }
Please login to merge, or discard this patch.
ecrire/inc/filtres_alertes.php 1 patch
Indentation   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
  **/
19 19
 
20 20
 if (!defined('_ECRIRE_INC_VERSION')) {
21
-	return;
21
+    return;
22 22
 }
23 23
 
24 24
 /**
@@ -43,22 +43,22 @@  discard block
 block discarded – undo
43 43
  *     Pile complétée par le code à générer
44 44
  */
45 45
 function balise_ALERTE_MESSAGE_dist($p) {
46
-	$_texte = interprete_argument_balise(1, $p);
47
-	$_titre = interprete_argument_balise(2, $p);
48
-	$_class = interprete_argument_balise(3, $p);
49
-	$_role  = interprete_argument_balise(4, $p);
50
-	$_id    = interprete_argument_balise(5, $p);
51
-	$_texte = ($_texte ?: "''");
52
-	$_titre = ($_titre ? ", $_titre" : ', null');
53
-	$_class = ($_class ? ", $_class" : ', null');
54
-	$_role  = ($_role  ? ", $_role"  : ', null');
55
-	$_id    = ($_id    ? ", $_id"    : ', null');
46
+    $_texte = interprete_argument_balise(1, $p);
47
+    $_titre = interprete_argument_balise(2, $p);
48
+    $_class = interprete_argument_balise(3, $p);
49
+    $_role  = interprete_argument_balise(4, $p);
50
+    $_id    = interprete_argument_balise(5, $p);
51
+    $_texte = ($_texte ?: "''");
52
+    $_titre = ($_titre ? ", $_titre" : ', null');
53
+    $_class = ($_class ? ", $_class" : ', null');
54
+    $_role  = ($_role  ? ", $_role"  : ', null');
55
+    $_id    = ($_id    ? ", $_id"    : ', null');
56 56
 
57
-	$f = chercher_filtre('message_alerte');
58
-	$p->code = "$f($_texte$_titre$_class$_role$_id)";
59
-	$p->interdire_scripts = false;
57
+    $f = chercher_filtre('message_alerte');
58
+    $p->code = "$f($_texte$_titre$_class$_role$_id)";
59
+    $p->interdire_scripts = false;
60 60
 
61
-	return $p;
61
+    return $p;
62 62
 }
63 63
 
64 64
 /**
@@ -86,20 +86,20 @@  discard block
 block discarded – undo
86 86
  *     Pile complétée par le code à générer
87 87
  */
88 88
 function balise_ALERTE_OUVRIR_dist($p) {
89
-	$_titre = interprete_argument_balise(1, $p);
90
-	$_class = interprete_argument_balise(2, $p);
91
-	$_role  = interprete_argument_balise(3, $p);
92
-	$_id    = interprete_argument_balise(4, $p);
93
-	$_titre = ($_titre ? "$_titre"   : 'null');
94
-	$_class = ($_class ? ", $_class" : ', null');
95
-	$_role  = ($_role  ? ", $_role"  : ', null');
96
-	$_id    = ($_id    ? ", $_id"    : ', null');
89
+    $_titre = interprete_argument_balise(1, $p);
90
+    $_class = interprete_argument_balise(2, $p);
91
+    $_role  = interprete_argument_balise(3, $p);
92
+    $_id    = interprete_argument_balise(4, $p);
93
+    $_titre = ($_titre ? "$_titre"   : 'null');
94
+    $_class = ($_class ? ", $_class" : ', null');
95
+    $_role  = ($_role  ? ", $_role"  : ', null');
96
+    $_id    = ($_id    ? ", $_id"    : ', null');
97 97
 
98
-	$f = chercher_filtre('message_alerte_ouvrir');
99
-	$p->code = "$f($_titre$_class$_role$_id)";
100
-	$p->interdire_scripts = false;
98
+    $f = chercher_filtre('message_alerte_ouvrir');
99
+    $p->code = "$f($_titre$_class$_role$_id)";
100
+    $p->interdire_scripts = false;
101 101
 
102
-	return $p;
102
+    return $p;
103 103
 }
104 104
 
105 105
 /**
@@ -121,11 +121,11 @@  discard block
 block discarded – undo
121 121
  *     Pile complétée par le code à générer
122 122
  */
123 123
 function balise_ALERTE_FERMER_dist($p) {
124
-	$f = chercher_filtre('message_alerte_fermer');
125
-	$p->code = "$f()";
126
-	$p->interdire_scripts = false;
124
+    $f = chercher_filtre('message_alerte_fermer');
125
+    $p->code = "$f()";
126
+    $p->interdire_scripts = false;
127 127
 
128
-	return $p;
128
+    return $p;
129 129
 }
130 130
 
131 131
 /**
@@ -160,14 +160,14 @@  discard block
 block discarded – undo
160 160
  */
161 161
 function message_alerte(string $texte, ?string $titre = null, ?string $class = null, ?string $role = null, ?string $id = null): string {
162 162
 
163
-	$message_alerte_ouvrir = chercher_filtre('message_alerte_ouvrir');
164
-	$message_alerte_fermer = chercher_filtre('message_alerte_fermer');
165
-	$message =
166
-		$message_alerte_ouvrir($titre, $class, $role, $id) .
167
-		$texte .
168
-		$message_alerte_fermer();
163
+    $message_alerte_ouvrir = chercher_filtre('message_alerte_ouvrir');
164
+    $message_alerte_fermer = chercher_filtre('message_alerte_fermer');
165
+    $message =
166
+        $message_alerte_ouvrir($titre, $class, $role, $id) .
167
+        $texte .
168
+        $message_alerte_fermer();
169 169
 
170
-	return $message;
170
+    return $message;
171 171
 }
172 172
 
173 173
 /**
@@ -198,56 +198,56 @@  discard block
 block discarded – undo
198 198
  */
199 199
 function message_alerte_ouvrir(?string $titre = null, ?string $class = null, ?string $role = null, ?string $id = null): string {
200 200
 
201
-	$prive = test_espace_prive();
201
+    $prive = test_espace_prive();
202 202
 
203
-	// Valeurs par défaut
204
-	$titre = trim($titre ?? '');
205
-	$role ??= 'alert'; // fallback uniquement si null
206
-	$class ??= 'notice'; // fallback uniquement si null
203
+    // Valeurs par défaut
204
+    $titre = trim($titre ?? '');
205
+    $role ??= 'alert'; // fallback uniquement si null
206
+    $class ??= 'notice'; // fallback uniquement si null
207 207
 
208
-	// Type d'alerte : le chercher dans les classes, nettoyer celles-ci, puis le réinjecter
209
-	$types = [
210
-		'notice',
211
-		'error',
212
-		'success',
213
-		'info',
214
-	];
215
-	$type  = array_intersect(explode(' ', $class), $types);
216
-	$type  = reset($type);
217
-	$class = trim(str_replace($types, '', $class) . " $type");
208
+    // Type d'alerte : le chercher dans les classes, nettoyer celles-ci, puis le réinjecter
209
+    $types = [
210
+        'notice',
211
+        'error',
212
+        'success',
213
+        'info',
214
+    ];
215
+    $type  = array_intersect(explode(' ', $class), $types);
216
+    $type  = reset($type);
217
+    $class = trim(str_replace($types, '', $class) . " $type");
218 218
 
219
-	// Classes
220
-	$class_racine = 'msg-alert';
221
-	$clearfix     = ($prive ? 'clearfix' : '');
222
-	$class_alerte = "$class_racine $class";
223
-	$class_texte  = "{$class_racine}__text $clearfix";
224
-	$class_titre  = "{$class_racine}__heading";
219
+    // Classes
220
+    $class_racine = 'msg-alert';
221
+    $clearfix     = ($prive ? 'clearfix' : '');
222
+    $class_alerte = "$class_racine $class";
223
+    $class_texte  = "{$class_racine}__text $clearfix";
224
+    $class_titre  = "{$class_racine}__heading";
225 225
 
226
-	// Titre : markup
227
-	$titre = trim($titre);
228
-	if (strlen($titre)) {
229
-		include_spip('inc/filtres');
230
-		// Si besoin on encapsule le titre : un h3 dans le privé, un simple div sinon.
231
-		$cherche_tag = ($prive ? '<h' : '<');
232
-		$wrap_tag    = ($prive ? '<h3>' : '<div>');
233
-		if (strpos($titre, $cherche_tag) !== 0) {
234
-			$titre = wrap($titre, $wrap_tag);
235
-		}
236
-		// puis on ajoute la classe
237
-		$titre = ajouter_class($titre, $class_titre);
238
-	}
226
+    // Titre : markup
227
+    $titre = trim($titre);
228
+    if (strlen($titre)) {
229
+        include_spip('inc/filtres');
230
+        // Si besoin on encapsule le titre : un h3 dans le privé, un simple div sinon.
231
+        $cherche_tag = ($prive ? '<h' : '<');
232
+        $wrap_tag    = ($prive ? '<h3>' : '<div>');
233
+        if (strpos($titre, $cherche_tag) !== 0) {
234
+            $titre = wrap($titre, $wrap_tag);
235
+        }
236
+        // puis on ajoute la classe
237
+        $titre = ajouter_class($titre, $class_titre);
238
+    }
239 239
 
240
-	// Attributs
241
-	$attr_role = ($role ? "role=\"$role\"" : '');
242
-	$attr_id   = ($id   ? "id=\"$id\"" : '');
243
-	$attr_data = ($type ? "data-alert=\"$type\"" : '');
240
+    // Attributs
241
+    $attr_role = ($role ? "role=\"$role\"" : '');
242
+    $attr_id   = ($id   ? "id=\"$id\"" : '');
243
+    $attr_data = ($type ? "data-alert=\"$type\"" : '');
244 244
 
245
-	$message =
246
-		"<div class=\"$class_alerte\" $attr_role $attr_id $attr_data>"
247
-			. $titre
248
-			. "<div class=\"$class_texte\">";
245
+    $message =
246
+        "<div class=\"$class_alerte\" $attr_role $attr_id $attr_data>"
247
+            . $titre
248
+            . "<div class=\"$class_texte\">";
249 249
 
250
-	return $message;
250
+    return $message;
251 251
 }
252 252
 
253 253
 /**
@@ -261,5 +261,5 @@  discard block
 block discarded – undo
261 261
  *     HTML de fin de l'alerte
262 262
  */
263 263
 function message_alerte_fermer(): string {
264
-	return '</div></div>';
264
+    return '</div></div>';
265 265
 }
Please login to merge, or discard this patch.
ecrire/inc/recherche_to_array.php 1 patch
Indentation   +267 added lines, -267 removed lines patch added patch discarded remove patch
@@ -11,298 +11,298 @@
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 
18 18
 // methodes sql
19 19
 function inc_recherche_to_array_dist($recherche, $options = []) {
20 20
 
21
-	// options par defaut
22
-	$options = array_merge(
23
-		[
24
-			'score' => true,
25
-			'champs' => false,
26
-			'toutvoir' => false,
27
-			'matches' => false,
28
-			'jointures' => false
29
-		],
30
-		$options
31
-	);
21
+    // options par defaut
22
+    $options = array_merge(
23
+        [
24
+            'score' => true,
25
+            'champs' => false,
26
+            'toutvoir' => false,
27
+            'matches' => false,
28
+            'jointures' => false
29
+        ],
30
+        $options
31
+    );
32 32
 
33
-	include_spip('inc/rechercher');
34
-	include_spip('inc/autoriser');
33
+    include_spip('inc/rechercher');
34
+    include_spip('inc/autoriser');
35 35
 
36
-	$requete = [
37
-		'SELECT' => [],
38
-		'FROM' => [],
39
-		'WHERE' => [],
40
-		'GROUPBY' => [],
41
-		'ORDERBY' => [],
42
-		'LIMIT' => '',
43
-		'HAVING' => []
44
-	];
36
+    $requete = [
37
+        'SELECT' => [],
38
+        'FROM' => [],
39
+        'WHERE' => [],
40
+        'GROUPBY' => [],
41
+        'ORDERBY' => [],
42
+        'LIMIT' => '',
43
+        'HAVING' => []
44
+    ];
45 45
 
46
-	$table = sinon($options['table'], 'article');
47
-	if ($options['champs']) {
48
-		$champs = $options['champs'];
49
-	} else {
50
-		$l = liste_des_champs();
51
-		$champs = $l['article'];
52
-	}
53
-	$serveur = $options['serveur'];
46
+    $table = sinon($options['table'], 'article');
47
+    if ($options['champs']) {
48
+        $champs = $options['champs'];
49
+    } else {
50
+        $l = liste_des_champs();
51
+        $champs = $l['article'];
52
+    }
53
+    $serveur = $options['serveur'];
54 54
 
55
-	[$methode, $q, $preg] = expression_recherche($recherche, $options);
55
+    [$methode, $q, $preg] = expression_recherche($recherche, $options);
56 56
 
57
-	$jointures = $options['jointures']
58
-		? liste_des_jointures()
59
-		: [];
57
+    $jointures = $options['jointures']
58
+        ? liste_des_jointures()
59
+        : [];
60 60
 
61
-	$_id_table = id_table_objet($table);
61
+    $_id_table = id_table_objet($table);
62 62
 
63
-	// c'est un pis-aller : ca a peu de chance de marcher, mais mieux quand meme que en conservant la ','
64
-	// (aka ca marche au moins dans certains cas comme avec spip_formulaires_reponses_champs)
65
-	if (strpos($_id_table, ',') !== false) {
66
-		$_id_table = explode(',', $_id_table);
67
-		$_id_table = reset($_id_table);
68
-	}
63
+    // c'est un pis-aller : ca a peu de chance de marcher, mais mieux quand meme que en conservant la ','
64
+    // (aka ca marche au moins dans certains cas comme avec spip_formulaires_reponses_champs)
65
+    if (strpos($_id_table, ',') !== false) {
66
+        $_id_table = explode(',', $_id_table);
67
+        $_id_table = reset($_id_table);
68
+    }
69 69
 
70
-	$requete['SELECT'][] = 't.' . $_id_table;
71
-	$a = [];
72
-	// Recherche fulltext
73
-	foreach ($champs as $champ => $poids) {
74
-		if (is_array($champ)) {
75
-			spip_log('requetes imbriquees interdites');
76
-		} else {
77
-			if (strpos($champ, '.') === false) {
78
-				$champ = "t.$champ";
79
-			}
80
-			$requete['SELECT'][] = $champ;
81
-			$a[] = $champ . ' ' . $methode . ' ' . $q;
82
-		}
83
-	}
84
-	if ($a) {
85
-		$requete['WHERE'][] = join(' OR ', $a);
86
-	}
87
-	$requete['FROM'][] = table_objet_sql($table) . ' AS t';
70
+    $requete['SELECT'][] = 't.' . $_id_table;
71
+    $a = [];
72
+    // Recherche fulltext
73
+    foreach ($champs as $champ => $poids) {
74
+        if (is_array($champ)) {
75
+            spip_log('requetes imbriquees interdites');
76
+        } else {
77
+            if (strpos($champ, '.') === false) {
78
+                $champ = "t.$champ";
79
+            }
80
+            $requete['SELECT'][] = $champ;
81
+            $a[] = $champ . ' ' . $methode . ' ' . $q;
82
+        }
83
+    }
84
+    if ($a) {
85
+        $requete['WHERE'][] = join(' OR ', $a);
86
+    }
87
+    $requete['FROM'][] = table_objet_sql($table) . ' AS t';
88 88
 
89
-	$results = [];
89
+    $results = [];
90 90
 
91
-	$s = sql_select(
92
-		$requete['SELECT'],
93
-		$requete['FROM'],
94
-		$requete['WHERE'],
95
-		implode(' ', $requete['GROUPBY']),
96
-		$requete['ORDERBY'],
97
-		$requete['LIMIT'],
98
-		$requete['HAVING'],
99
-		$serveur
100
-	);
91
+    $s = sql_select(
92
+        $requete['SELECT'],
93
+        $requete['FROM'],
94
+        $requete['WHERE'],
95
+        implode(' ', $requete['GROUPBY']),
96
+        $requete['ORDERBY'],
97
+        $requete['LIMIT'],
98
+        $requete['HAVING'],
99
+        $serveur
100
+    );
101 101
 
102
-	while (
103
-		$t = sql_fetch($s, $serveur)
104
-		and (!isset($t['score']) or $t['score'] > 0)
105
-	) {
106
-		$id = intval($t[$_id_table]);
102
+    while (
103
+        $t = sql_fetch($s, $serveur)
104
+        and (!isset($t['score']) or $t['score'] > 0)
105
+    ) {
106
+        $id = intval($t[$_id_table]);
107 107
 
108
-		if (
109
-			$options['toutvoir']
110
-			or autoriser('voir', $table, $id)
111
-		) {
112
-			// indiquer les champs concernes
113
-			$champs_vus = [];
114
-			$score = 0;
115
-			$matches = [];
108
+        if (
109
+            $options['toutvoir']
110
+            or autoriser('voir', $table, $id)
111
+        ) {
112
+            // indiquer les champs concernes
113
+            $champs_vus = [];
114
+            $score = 0;
115
+            $matches = [];
116 116
 
117
-			$vu = false;
118
-			foreach ($champs as $champ => $poids) {
119
-				$champ = explode('.', $champ);
120
-				$champ = end($champ);
121
-				// translitteration_rapide uniquement si on est deja en utf-8
122
-				$value = ($GLOBALS['meta']['charset'] == 'utf-8' ? translitteration_rapide($t[$champ]) : translitteration($t[$champ]));
123
-				if (
124
-					$n =
125
-					($options['score'] || $options['matches'])
126
-						? preg_match_all($preg, $value, $regs, PREG_SET_ORDER)
127
-						: preg_match($preg, $value)
128
-				) {
129
-					$vu = true;
117
+            $vu = false;
118
+            foreach ($champs as $champ => $poids) {
119
+                $champ = explode('.', $champ);
120
+                $champ = end($champ);
121
+                // translitteration_rapide uniquement si on est deja en utf-8
122
+                $value = ($GLOBALS['meta']['charset'] == 'utf-8' ? translitteration_rapide($t[$champ]) : translitteration($t[$champ]));
123
+                if (
124
+                    $n =
125
+                    ($options['score'] || $options['matches'])
126
+                        ? preg_match_all($preg, $value, $regs, PREG_SET_ORDER)
127
+                        : preg_match($preg, $value)
128
+                ) {
129
+                    $vu = true;
130 130
 
131
-					if ($options['champs']) {
132
-						$champs_vus[$champ] = $t[$champ];
133
-					}
134
-					if ($options['score']) {
135
-						// compter les points avec un peu de discernement : on pondere par la longueur du match compte en chars
136
-						$score += $poids * strlen(implode('', array_column($regs, 0)));
137
-					}
131
+                    if ($options['champs']) {
132
+                        $champs_vus[$champ] = $t[$champ];
133
+                    }
134
+                    if ($options['score']) {
135
+                        // compter les points avec un peu de discernement : on pondere par la longueur du match compte en chars
136
+                        $score += $poids * strlen(implode('', array_column($regs, 0)));
137
+                    }
138 138
 
139
-					if ($options['matches']) {
140
-						$matches[$champ] = $regs;
141
-					}
139
+                    if ($options['matches']) {
140
+                        $matches[$champ] = $regs;
141
+                    }
142 142
 
143
-					if (
144
-						!$options['champs']
145
-						and !$options['score']
146
-						and !$options['matches']
147
-					) {
148
-						break;
149
-					}
150
-				}
151
-			}
143
+                    if (
144
+                        !$options['champs']
145
+                        and !$options['score']
146
+                        and !$options['matches']
147
+                    ) {
148
+                        break;
149
+                    }
150
+                }
151
+            }
152 152
 
153
-			if ($vu) {
154
-				if (!isset($results)) {
155
-					$results = [];
156
-				}
157
-				$results[$id] = [];
158
-				if ($champs_vus) {
159
-					$results[$id]['champs'] = $champs_vus;
160
-				}
161
-				if ($score) {
162
-					$results[$id]['score'] = $score;
163
-				}
164
-				if ($matches) {
165
-					$results[$id]['matches'] = $matches;
166
-				}
167
-			}
168
-		}
169
-	}
153
+            if ($vu) {
154
+                if (!isset($results)) {
155
+                    $results = [];
156
+                }
157
+                $results[$id] = [];
158
+                if ($champs_vus) {
159
+                    $results[$id]['champs'] = $champs_vus;
160
+                }
161
+                if ($score) {
162
+                    $results[$id]['score'] = $score;
163
+                }
164
+                if ($matches) {
165
+                    $results[$id]['matches'] = $matches;
166
+                }
167
+            }
168
+        }
169
+    }
170 170
 
171 171
 
172
-	// Gerer les donnees associees
173
-	// ici on est un peu naze : pas capables de reconstruire une jointure complexe
174
-	// on ne sait passer que par table de laison en 1 coup
175
-	if (
176
-		isset($jointures[$table])
177
-		and $joints = recherche_en_base(
178
-			$recherche,
179
-			$jointures[$table],
180
-			array_merge($options, ['jointures' => false])
181
-		)
182
-	) {
183
-		include_spip('action/editer_liens');
184
-		$trouver_table = charger_fonction('trouver_table', 'base');
185
-		$cle_depart = id_table_objet($table);
186
-		$table_depart = table_objet($table, $serveur);
187
-		$desc_depart = $trouver_table($table_depart, $serveur);
188
-		$depart_associable = objet_associable($table);
189
-		foreach ($joints as $table_liee => $ids_trouves) {
190
-			// on peut definir une fonction de recherche jointe pour regler les cas particuliers
191
-			if (
192
-				!(
193
-				$rechercher_joints = charger_fonction("rechercher_joints_{$table}_{$table_liee}", 'inc', true)
194
-				or $rechercher_joints = charger_fonction("rechercher_joints_objet_{$table_liee}", 'inc', true)
195
-				or $rechercher_joints = charger_fonction("rechercher_joints_{$table}_objet_lie", 'inc', true)
196
-				)
197
-			) {
198
-				$cle_arrivee = id_table_objet($table_liee);
199
-				$table_arrivee = table_objet($table_liee, $serveur);
200
-				$desc_arrivee = $trouver_table($table_arrivee, $serveur);
201
-				// cas simple : $cle_depart dans la table_liee
202
-				if (isset($desc_arrivee['field'][$cle_depart])) {
203
-					$s = sql_select(
204
-						"$cle_depart, $cle_arrivee",
205
-						$desc_arrivee['table_sql'],
206
-						sql_in($cle_arrivee, array_keys($ids_trouves)),
207
-						'',
208
-						'',
209
-						'',
210
-						'',
211
-						$serveur
212
-					);
213
-				} // cas simple : $cle_arrivee dans la table
214
-				elseif (isset($desc_depart['field'][$cle_arrivee])) {
215
-					$s = sql_select(
216
-						"$cle_depart, $cle_arrivee",
217
-						$desc_depart['table_sql'],
218
-						sql_in($cle_arrivee, array_keys($ids_trouves)),
219
-						'',
220
-						'',
221
-						'',
222
-						'',
223
-						$serveur
224
-					);
225
-				}
226
-				// sinon cherchons une table de liaison
227
-				// cas recherche principale article, objet lie document : passer par spip_documents_liens
228
-				elseif ($l = objet_associable($table_liee)) {
229
-					[$primary, $table_liens] = $l;
230
-					$s = sql_select(
231
-						"id_objet as $cle_depart, $primary as $cle_arrivee",
232
-						$table_liens,
233
-						["objet='$table'", sql_in($primary, array_keys($ids_trouves))],
234
-						'',
235
-						'',
236
-						'',
237
-						'',
238
-						$serveur
239
-					);
240
-				} // cas recherche principale auteur, objet lie article: passer par spip_auteurs_liens
241
-				elseif ($l = $depart_associable) {
242
-					[$primary, $table_liens] = $l;
243
-					$s = sql_select(
244
-						"$primary as $cle_depart, id_objet as $cle_arrivee",
245
-						$table_liens,
246
-						["objet='$table_liee'", sql_in('id_objet', array_keys($ids_trouves))],
247
-						'',
248
-						'',
249
-						'',
250
-						'',
251
-						$serveur
252
-					);
253
-				} // cas table de liaison generique spip_xxx_yyy
254
-				elseif (
255
-					$t = $trouver_table($table_arrivee . '_' . $table_depart, $serveur)
256
-					or $t = $trouver_table($table_depart . '_' . $table_arrivee, $serveur)
257
-				) {
258
-					$s = sql_select(
259
-						"$cle_depart,$cle_arrivee",
260
-						$t['table_sql'],
261
-						sql_in($cle_arrivee, array_keys($ids_trouves)),
262
-						'',
263
-						'',
264
-						'',
265
-						'',
266
-						$serveur
267
-					);
268
-				}
269
-			} else {
270
-				[$cle_depart, $cle_arrivee, $s] = $rechercher_joints(
271
-					$table,
272
-					$table_liee,
273
-					array_keys($ids_trouves),
274
-					$serveur
275
-				);
276
-			}
172
+    // Gerer les donnees associees
173
+    // ici on est un peu naze : pas capables de reconstruire une jointure complexe
174
+    // on ne sait passer que par table de laison en 1 coup
175
+    if (
176
+        isset($jointures[$table])
177
+        and $joints = recherche_en_base(
178
+            $recherche,
179
+            $jointures[$table],
180
+            array_merge($options, ['jointures' => false])
181
+        )
182
+    ) {
183
+        include_spip('action/editer_liens');
184
+        $trouver_table = charger_fonction('trouver_table', 'base');
185
+        $cle_depart = id_table_objet($table);
186
+        $table_depart = table_objet($table, $serveur);
187
+        $desc_depart = $trouver_table($table_depart, $serveur);
188
+        $depart_associable = objet_associable($table);
189
+        foreach ($joints as $table_liee => $ids_trouves) {
190
+            // on peut definir une fonction de recherche jointe pour regler les cas particuliers
191
+            if (
192
+                !(
193
+                $rechercher_joints = charger_fonction("rechercher_joints_{$table}_{$table_liee}", 'inc', true)
194
+                or $rechercher_joints = charger_fonction("rechercher_joints_objet_{$table_liee}", 'inc', true)
195
+                or $rechercher_joints = charger_fonction("rechercher_joints_{$table}_objet_lie", 'inc', true)
196
+                )
197
+            ) {
198
+                $cle_arrivee = id_table_objet($table_liee);
199
+                $table_arrivee = table_objet($table_liee, $serveur);
200
+                $desc_arrivee = $trouver_table($table_arrivee, $serveur);
201
+                // cas simple : $cle_depart dans la table_liee
202
+                if (isset($desc_arrivee['field'][$cle_depart])) {
203
+                    $s = sql_select(
204
+                        "$cle_depart, $cle_arrivee",
205
+                        $desc_arrivee['table_sql'],
206
+                        sql_in($cle_arrivee, array_keys($ids_trouves)),
207
+                        '',
208
+                        '',
209
+                        '',
210
+                        '',
211
+                        $serveur
212
+                    );
213
+                } // cas simple : $cle_arrivee dans la table
214
+                elseif (isset($desc_depart['field'][$cle_arrivee])) {
215
+                    $s = sql_select(
216
+                        "$cle_depart, $cle_arrivee",
217
+                        $desc_depart['table_sql'],
218
+                        sql_in($cle_arrivee, array_keys($ids_trouves)),
219
+                        '',
220
+                        '',
221
+                        '',
222
+                        '',
223
+                        $serveur
224
+                    );
225
+                }
226
+                // sinon cherchons une table de liaison
227
+                // cas recherche principale article, objet lie document : passer par spip_documents_liens
228
+                elseif ($l = objet_associable($table_liee)) {
229
+                    [$primary, $table_liens] = $l;
230
+                    $s = sql_select(
231
+                        "id_objet as $cle_depart, $primary as $cle_arrivee",
232
+                        $table_liens,
233
+                        ["objet='$table'", sql_in($primary, array_keys($ids_trouves))],
234
+                        '',
235
+                        '',
236
+                        '',
237
+                        '',
238
+                        $serveur
239
+                    );
240
+                } // cas recherche principale auteur, objet lie article: passer par spip_auteurs_liens
241
+                elseif ($l = $depart_associable) {
242
+                    [$primary, $table_liens] = $l;
243
+                    $s = sql_select(
244
+                        "$primary as $cle_depart, id_objet as $cle_arrivee",
245
+                        $table_liens,
246
+                        ["objet='$table_liee'", sql_in('id_objet', array_keys($ids_trouves))],
247
+                        '',
248
+                        '',
249
+                        '',
250
+                        '',
251
+                        $serveur
252
+                    );
253
+                } // cas table de liaison generique spip_xxx_yyy
254
+                elseif (
255
+                    $t = $trouver_table($table_arrivee . '_' . $table_depart, $serveur)
256
+                    or $t = $trouver_table($table_depart . '_' . $table_arrivee, $serveur)
257
+                ) {
258
+                    $s = sql_select(
259
+                        "$cle_depart,$cle_arrivee",
260
+                        $t['table_sql'],
261
+                        sql_in($cle_arrivee, array_keys($ids_trouves)),
262
+                        '',
263
+                        '',
264
+                        '',
265
+                        '',
266
+                        $serveur
267
+                    );
268
+                }
269
+            } else {
270
+                [$cle_depart, $cle_arrivee, $s] = $rechercher_joints(
271
+                    $table,
272
+                    $table_liee,
273
+                    array_keys($ids_trouves),
274
+                    $serveur
275
+                );
276
+            }
277 277
 
278
-			while ($t = is_array($s) ? array_shift($s) : sql_fetch($s)) {
279
-				$id = $t[$cle_depart];
280
-				$joint = $ids_trouves[$t[$cle_arrivee]];
281
-				if (!isset($results)) {
282
-					$results = [];
283
-				}
284
-				if (!isset($results[$id])) {
285
-					$results[$id] = [];
286
-				}
287
-				if (isset($joint['score']) and $joint['score']) {
288
-					if (!isset($results[$id]['score'])) {
289
-						$results[$id]['score'] = 0;
290
-					}
291
-					$results[$id]['score'] += $joint['score'];
292
-				}
293
-				if (isset($joint['champs']) and $joint['champs']) {
294
-					foreach ($joint['champs'] as $c => $val) {
295
-						$results[$id]['champs'][$table_liee . '.' . $c] = $val;
296
-					}
297
-				}
298
-				if (isset($joint['matches']) and $joint['matches']) {
299
-					foreach ($joint['matches'] as $c => $val) {
300
-						$results[$id]['matches'][$table_liee . '.' . $c] = $val;
301
-					}
302
-				}
303
-			}
304
-		}
305
-	}
278
+            while ($t = is_array($s) ? array_shift($s) : sql_fetch($s)) {
279
+                $id = $t[$cle_depart];
280
+                $joint = $ids_trouves[$t[$cle_arrivee]];
281
+                if (!isset($results)) {
282
+                    $results = [];
283
+                }
284
+                if (!isset($results[$id])) {
285
+                    $results[$id] = [];
286
+                }
287
+                if (isset($joint['score']) and $joint['score']) {
288
+                    if (!isset($results[$id]['score'])) {
289
+                        $results[$id]['score'] = 0;
290
+                    }
291
+                    $results[$id]['score'] += $joint['score'];
292
+                }
293
+                if (isset($joint['champs']) and $joint['champs']) {
294
+                    foreach ($joint['champs'] as $c => $val) {
295
+                        $results[$id]['champs'][$table_liee . '.' . $c] = $val;
296
+                    }
297
+                }
298
+                if (isset($joint['matches']) and $joint['matches']) {
299
+                    foreach ($joint['matches'] as $c => $val) {
300
+                        $results[$id]['matches'][$table_liee . '.' . $c] = $val;
301
+                    }
302
+                }
303
+            }
304
+        }
305
+    }
306 306
 
307
-	return $results;
307
+    return $results;
308 308
 }
Please login to merge, or discard this patch.