Completed
Push — spip-2.1 ( b6b097 )
by cam
42:28 queued 30:44
created

parametrer.php ➔ public_parametrer_dist()   F

Complexity

Conditions 28
Paths > 20000

Size

Total Lines 132
Code Lines 74

Duplication

Lines 17
Ratio 12.88 %

Importance

Changes 0
Metric Value
cc 28
eloc 74
nc 77977
nop 4
dl 17
loc 132
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/***************************************************************************\
4
 *  SPIP, Systeme de publication pour l'internet                           *
5
 *                                                                         *
6
 *  Copyright (c) 2001-2016                                                *
7
 *  Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James  *
8
 *                                                                         *
9
 *  Ce programme est un logiciel libre distribue sous licence GNU/GPL.     *
10
 *  Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne.   *
11
\***************************************************************************/
12
13
if (!defined('_ECRIRE_INC_VERSION')) return;
14
15
include_spip('inc/lang');
16
include_spip('public/quete'); // pour quete_chapo et ses dependances
17
18
// NB: mes_fonctions peut initialiser $dossier_squelettes (old-style)
19
// donc il faut l'inclure "en globals"
20
if ($f = find_in_path('mes_fonctions.php')) {
21
	global $dossier_squelettes;
22
	include_once(_ROOT_CWD . $f);
23
}
24
25
if (@is_readable(_CACHE_PLUGINS_FCT)) {
26
	// chargement optimise precompile
27
	include_once(_CACHE_PLUGINS_FCT);
28
}
29
30
# Determine le squelette associe a une requete 
31
# et l'applique sur le contexte, le nom du cache et le serveur
32
# en ayant evacue au prealable le cas de la redirection
33
# Retourne un tableau ainsi construit
34
# 'texte' => la page calculee
35
# 'process_ins' => 'html' ou 'php' si presence d'un '< ?php'
36
# 'invalideurs' => les invalideurs de ce cache
37
# 'entetes' => headers http
38
# 'duree' => duree de vie du cache
39
# 'signal' => contexte (les id_* globales)
40
41
# En cas d'erreur process_ins est absent et texte est un tableau de 2 chaines
42
43
// http://doc.spip.org/@public_parametrer_dist
44
function public_parametrer_dist($fond, $contexte='', $cache='', $connect='')  {
45
	$page = tester_redirection($fond, $contexte, $connect);
46
	if ($page) return $page;
47
48
	if (isset($contexte['lang']))
49
		$lang = $contexte['lang'];
50
	elseif (!isset($lang))
0 ignored issues
show
Bug introduced by
The variable $lang seems only to be defined at a later point. As such the call to isset() seems to always evaluate to false.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
51
		$lang = $GLOBALS['meta']['langue_site'];
52
53
	$select = ((!isset($GLOBALS['forcer_lang']) OR !$GLOBALS['forcer_lang']) AND $lang <> $GLOBALS['spip_lang']);
54
	if ($select) $select = lang_select($lang);
55
56
	$debug = (isset($GLOBALS['var_mode']) && ($GLOBALS['var_mode'] == 'debug'));
57
58
	$styliser = charger_fonction('styliser', 'public');
59
	list($skel,$mime_type, $gram, $sourcefile) =
60
		$styliser($fond, $contexte, $GLOBALS['spip_lang'], $connect, _EXTENSION_SQUELETTES);
61
62
	if ($skel) {
63
64
		// sauver le nom de l'eventuel squelette en cours d'execution
65
		// (recursion possible a cause des modeles)
66
		if ($debug) {
67
			$courant = @$GLOBALS['debug_objets']['courant'];
68
			$GLOBALS['debug_objets']['contexte'][$sourcefile] = $contexte;
69
		}
70
71
		// charger le squelette en specifiant les langages cibles et source
72
		// au cas il faudrait le compiler (source posterieure au resultat)
73
74
		$composer = charger_fonction('composer', 'public');
75
		$code = $composer($skel, $mime_type, $gram, $sourcefile, $connect);
76
	} else $code = '';
77
78
	if (!$code) { // squelette inconnu (==='') ou faux (===false)
79
		$page = $code;
80
	} else {
81
	// Preparer l'appel de la fonction principale du squelette 
82
83
		list($fonc) = $code;
84
		spip_timer($a = 'calcul page '.rand(0,1000));
85
86
		// On cree un marqueur de notes unique lie a cette composition
87
		// et on enregistre l'etat courant des globales de notes...
88
		$notes = charger_fonction('notes', 'inc');
89
		$notes('','empiler');
90
91
		// Rajouter d'office ces deux parametres
92
		// (mais vaudrait mieux que le compilateur sache le simuler
93
		// car ca interdit l'usage de criteres conditionnels dessus).
94 View Code Duplication
		if (!isset($contexte['date'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
			$contexte['date'] = date("Y-m-d H:i:s");
96
			$contexte['date_default'] = true;
97
		} else $contexte['date'] = normaliser_date($contexte['date'], true);
98
99 View Code Duplication
		if (!isset($contexte['date_redac'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
100
			$contexte['date_redac'] = date("Y-m-d H:i:s");
101
			$contexte['date_redac_default'] = true;
102
		} else $contexte['date_redac'] = normaliser_date($contexte['date_redac'], true);
103
104
	// Passer le nom du cache pour produire sa destruction automatique
105
		$page = $fonc(array('cache' => $cache), array($contexte));
106
107
	// Restituer les globales de notes telles qu'elles etaient avant l'appel
108
	// Si l'inclus n'a pas affiche ses notes, tant pis (elles *doivent*
109
	// etre dans son resultat, autrement elles ne seraient pas prises en
110
	// compte a chaque calcul d'un texte contenant un modele, mais seulement
111
	// quand le modele serait calcule, et on aurait des resultats incoherents)
112
		$notes('','depiler');
113
114
		// reinjecter en dynamique la pile des notes
115
		// si il y a des inclure dynamiques
116
		// si la pile n'est pas vide
117
		// la generalisation de cette injection permettrait de corriger le point juste au dessus
118
		// en faisant remonter les notes a l'incluant (A tester et valider avant application)
119
		$page['notes'] = $notes('','sauver_etat');
120
121
		// spip_log: un joli contexte
122
		$infos = array();
123
		foreach (array_filter($contexte) as $var => $val) {
124
			if (is_array($val)) $val = serialize($val);
125
			if (strlen("$val") > 30)
126
				$val = substr("$val", 0,27).'..';
127
			if (strstr($val,' '))
128
				$val = "'$val'";
129
			$infos[] = $var.'='.$val;
130
		}
131
		$profile = spip_timer($a);
132
		spip_log("calcul ($profile) [$skel] "
133
			. join(', ', $infos)
134
			.' ('.strlen($page['texte']).' octets)');
135
136
		if ($debug) {
137
		// si c'est ce que demande le debusqueur, lui passer la main
138
			$t = strlen($page['texte']) ? $page['texte'] : " ";
139
			$GLOBALS['debug_objets']['resultat'][$fonc . 'tout'] = $t;
140
			$GLOBALS['debug_objets']['courant'] = $courant;
0 ignored issues
show
Bug introduced by
The variable $courant does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
141
			$GLOBALS['debug_objets']['profile'][$sourcefile] = $profile;
142 View Code Duplication
			if ($GLOBALS['debug_objets']['sourcefile']
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
143
			AND (_request('var_mode_objet') == $fonc)
144
			AND (_request('var_mode_affiche') == 'resultat')) {
145
				erreur_squelette();
146
			}
147
		}
148
		// Si #CACHE{} n'etait pas la, le mettre a $delais
149
		if (!isset($page['entetes']['X-Spip-Cache']))
150
			$page['entetes']['X-Spip-Cache'] = isset($GLOBALS['delais'])?$GLOBALS['delais']:36000;
151
152
		$page['contexte'] = $contexte;
153
		// faire remonter le fichier source
154
		//if ($GLOBALS['var_inclure'])
155
156
		static $var_inclure = false;
157
		if ($GLOBALS['var_inclure']){
158
			$page['sourcefile'] = $sourcefile;
159
			$page['texte'] =
160
				"<div class='inclure_blocs'><h6>".$page['sourcefile']."</h6>".$page['texte']."</div>"
161
				. ($var_inclure?"":"<script type='text/javascript'>jQuery(function(){jQuery('.inclure_blocs > h6:first-child').hover(function(){jQuery(this).parent().addClass('hover')},function(){jQuery(this).parent().removeClass('hover')})});</script>");
162
			$var_inclure = true;
163
		}
164
165
		// Si un modele contenait #SESSION, on note l'info dans $page
166 View Code Duplication
		if (isset($GLOBALS['cache_utilise_session'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
167
			$page['invalideurs']['session'] = $GLOBALS['cache_utilise_session'];
168
			unset($GLOBALS['cache_utilise_session']);
169
		}
170
	}
171
172
	if ($select) lang_select();
173
174
	return $page;
175
}
176
177
178
/**
179
 * si le champ chapo commence par '=' c'est une redirection.
180
 * avec un eventuel raccourci Spip
181
 * si le raccourci a un titre il sera pris comme corps du 302
182
 *
183
 * http://doc.spip.org/@tester_redirection
184
 *
185
 * @param string $fond
186
 * @param array $contexte
187
 * @param string $connect
188
 * @return array|bool
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,string>|false.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
189
 */
190
function tester_redirection($fond, $contexte, $connect)
191
{
192
	if ($fond == 'article'
193
	AND $id_article = intval($contexte['id_article'])) {
194
		$m = quete_chapo($id_article, $connect);
195
		if ($m[0]=='=') {
196
			include_spip('inc/texte');
197
			// les navigateurs pataugent si l'URL est vide
198
			if ($url = chapo_redirige(substr($m,1), true)){
199
				// passer en url absolue car cette redirection pourra
200
				// etre utilisee dans un contexte d'url qui change
201
				// y compris url arbo
202
				if (!preg_match(',^\w+:,', $url)) {
203
					include_spip('inc/filtres_mini');
204
					$url = url_absolue($url);
205
				}
206
				$url = str_replace('&amp;', '&', $url);
207
				return array('texte' => "<"
208
				. "?php header('Location: "
209
				. texte_script($url)
210
				. "'); echo '"
211
				.  addslashes($url)
212
				. "'.\"\n\"?" . ">",
213
					'process_ins' => 'php');
214
			}
215
		}
216
	}
217
	return false;
218
}
219
220
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...
221