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

editer_site.php ➔ revisions_sites()   F

Complexity

Conditions 20
Paths 560

Size

Total Lines 93
Code Lines 56

Duplication

Lines 22
Ratio 23.66 %

Importance

Changes 0
Metric Value
cc 20
eloc 56
nc 560
nop 2
dl 22
loc 93
rs 2.5519
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
// http://doc.spip.org/@action_editer_site_dist
16
function action_editer_site_dist($arg=null) {
17
18
	if (is_null($arg)){
19
		$securiser_action = charger_fonction('securiser_action', 'inc');
20
		$arg = $securiser_action();
21
	}
22
	$resyndiquer = false;
23
24
	include_spip('inc/filtres'); // pour vider_url()
25
26
	if (preg_match(',options/(\d+),',$arg, $r)) {
27
		$id_syndic = $r[1];
28
		$resyndiquer = editer_site_options($id_syndic);
29
	// Envoi depuis le formulaire d'edition d'un site existant
30
	} else if ($id_syndic = intval($arg)) {
31
		// reload si on change une des valeurs de syndication
32
		if (
33
		(_request('url_syndic') OR _request('resume') OR _request('syndication'))
34
		AND $t = sql_fetsel('url_syndic,syndication,resume', 'spip_syndic', "id_syndic=".sql_quote($id_syndic))
35
		AND (
36
			(_request('url_syndic') AND _request('url_syndic') != $t['url_syndic'])
37
			OR
38
			(_request('syndication') AND _request('syndication') != $t['syndication'])
39
			OR
40
			(_request('resume') AND _request('resume') != $t['resume'])
41
			)
42
		)
43
			set_request('reload', 'oui');
44
		revisions_sites($id_syndic);
45
46
	// Envoi normal depuis le formulaire de creation d'un site
47
	}
48
	elseif (strlen(vider_url(_request('url_site')))
49
		AND strlen(_request('nom_site'))) {
50
			set_request('reload', 'oui');
51
			$id_syndic = insert_syndic(_request('id_parent'));
52
			revisions_sites($id_syndic);
53
			if ($logo = _request('logo')
54
			 AND $format_logo = _request('format_logo')){
55
			 	include_spip('inc/distant');
56
				@rename(copie_locale($logo),
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
57
				_DIR_IMG . 'siteon'.$id_syndic.'.'.$format_logo);
58
			 }
59
	}
60
	// Erreur
61
	else {
62
		include_spip('inc/headers');
63
		redirige_url_ecrire();
64
	}
65
66
	// Re-syndiquer le site
67
	if (_request('reload') == 'oui') {
68
		// Effacer les messages si on supprime la syndication
69
		if (_request('syndication') == 'non')
70
			sql_delete("spip_syndic_articles", "id_syndic=".sql_quote($id_syndic));
71
72
		$t = sql_getfetsel('descriptif', 'spip_syndic', "id_syndic=$id_syndic AND syndication IN ('oui', 'sus', 'off')", '','', 1);
73
		if ($t !== NULL) {
74
75
			// Si descriptif vide, chercher le logo si pas deja la
76
			$chercher_logo = charger_fonction('chercher_logo', 'inc');
77
			if (!$logo = $chercher_logo($id_syndic, 'id_syndic', 'on')
78
			OR !$t) {
79
				if ($auto = vider_url(_request('url_auto'))) {
80
					$auto = analyser_site($auto);
81
					if (!strlen($t) AND strlen($auto['descriptif']))
82
						revisions_sites($id_syndic, array('descriptif' => $auto['descriptif']));
83
				}
84
				if (!$logo
85
				AND $auto['logo'] AND $auto['format_logo'])
86
					@rename($auto['logo'],
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
87
					_DIR_IMG . 'siteon'.$id_syndic.'.'.$auto['format_logo']);
88
			}
89
			$resyndiquer = true;
90
		}
91
	}
92
93
	if ($resyndiquer) {
94
	  // ah si PHP connaisait les fermetures...
95
	  // A la place, une constante utilisee exclusivement
96
	  // dans la fct suivante.
97
		define('_GENIE_SYNDIC_NOW', $id_syndic);
98
		// forcer l'execution immediate de cette tache
99
		// (i.e. appeler la fct suivante avec gestion du verrou)
100
		cron(0, array('syndic' => -91));
101
	}
102 View Code Duplication
	if (_request('redirect')) {
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...
103
	$redirect = parametre_url(urldecode(_request('redirect')),
104
		'id_syndic', $id_syndic, '&');
105
		include_spip('inc/headers');
106
		redirige_par_entete($redirect);
107
	}
108
	else
109
		return array($id_syndic,'');
110
}
111
112
// Cette fonction redefinit la tache standard de syndication
113
// pour la forcer a syndiquer le site dans la globale genie_syndic_now
114
115
// http://doc.spip.org/@genie_syndic
116
function genie_syndic($t) {
0 ignored issues
show
Unused Code introduced by
The parameter $t is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
117
	include_spip('genie/syndic');
118
	define('_GENIE_SYNDIC', 2); // Pas de faux message d'erreur
119
	$t = syndic_a_jour(_GENIE_SYNDIC_NOW);
120
	return $t ? 0 : _GENIE_SYNDIC_NOW;
121
}
122
123
// http://doc.spip.org/@insert_syndic
124
function insert_syndic($id_rubrique) {
125
126
	include_spip('inc/rubriques');
127
128
	// Si id_rubrique vaut 0 ou n'est pas definie, creer le site
129
	// dans la premiere rubrique racine
130 View Code Duplication
	if (!$id_rubrique = intval($id_rubrique)) {
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...
131
		$id_rubrique = sql_getfetsel("id_rubrique", "spip_rubriques", "id_parent=0",'', '0+titre,titre', "1");
132
	}
133
134
	// Le secteur a la creation : c'est le secteur de la rubrique
135
136
	$id_secteur = sql_getfetsel("id_secteur", "spip_rubriques", "id_rubrique=$id_rubrique");
137
138
	$champs = array(
139
		'id_rubrique' => $id_rubrique,
140
		'id_secteur' => $id_secteur,
141
		'statut' => 'prop',
142
		'date' => date('Y-m-d H:i:s'));
143
144
	// Envoyer aux plugins
145
	$champs = pipeline('pre_insertion',
146
		array(
147
			'args' => array(
148
				'table' => 'spip_syndic',
149
			),
150
			'data' => $champs
151
		)
152
	);
153
154
	$id_syndic = sql_insertq("spip_syndic", $champs);
155
	pipeline('post_insertion',
156
		array(
157
			'args' => array(
158
				'table' => 'spip_syndic',
159
				'id_objet' => $id_syndic
160
			),
161
			'data' => $champs
162
		)
163
	);
164
165
	return $id_syndic;
166
}
167
168
169
// Enregistre une revision de syndic
170
// $c est un contenu (par defaut on prend le contenu via _request())
171
// http://doc.spip.org/@revisions_sites
172
function revisions_sites ($id_syndic, $c=false) {
173
174
	include_spip('inc/rubriques');
175
	include_spip('inc/autoriser');
176
177
	// champs normaux
178 View Code Duplication
	if ($c === false) {
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...
179
		$c = array();
180
		foreach (array(
181
			'nom_site', 'url_site', 'descriptif', 'url_syndic', 'syndication', 'statut', 'id_parent'
182
		) as $champ)
183
			if (($a = _request($champ)) !== null)
184
				$c[$champ] = $a;
185
	}
186
187
	// Si le site est publie, invalider les caches et demander sa reindexation
188
	$t = sql_getfetsel("statut", "spip_syndic", "id_syndic=$id_syndic");
189
	if ($t == 'publie') {
190
		$invalideur = "id='id_syndic/$id_syndic'";
191
		$indexation = true;
192
	}
193
	include_spip('inc/modifier');
194
195
	modifier_contenu('syndic', $id_syndic,
196
		array(
197
			'nonvide' => array('nom_site' => _T('info_sans_titre')),
198
			'invalideur' => $invalideur,
0 ignored issues
show
Bug introduced by
The variable $invalideur 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...
199
			'indexation' => $indexation
0 ignored issues
show
Bug introduced by
The variable $indexation 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...
200
		),
201
		$c);
0 ignored issues
show
Bug introduced by
It seems like $c defined by array() on line 179 can also be of type array; however, modifier_contenu() does only seem to accept boolean, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
202
203
204
	$row = sql_fetsel("statut, id_rubrique, id_secteur", "spip_syndic", "id_syndic=$id_syndic");
205
	$id_rubrique = $row['id_rubrique'];
206
	$statut_ancien = $row['statut'];
207
	$id_secteur_old = $row['id_secteur'];
208
209
	$statut = $c['statut'];
210
211
	if ($statut
212
	AND $statut != $statut_ancien
213
	AND autoriser('publierdans','rubrique',$id_rubrique)) {
214
		$champs['statut'] = $statut;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$champs was never initialized. Although not strictly required by PHP, it is generally a good practice to add $champs = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
215
		if ($statut == 'publie') {
216
			if ($d = _request('date', $c)) {
0 ignored issues
show
Bug introduced by
It seems like $c defined by array() on line 179 can also be of type array; however, _request() does only seem to accept boolean, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
217
				$champs['date'] = $d;
218
			} else {
219
				$champs['date'] = date('Y-m-d H:i:s');
220
			}
221
		}
222
	} else
223
		$statut = $statut_ancien;
224
225
	// Changer de rubrique ?
226
	// Verifier que la rubrique demandee est differente de l'actuelle,
227
	// et qu'elle existe. Recuperer son secteur
228
229 View Code Duplication
	if ($id_parent = intval(_request('id_parent', $c))
0 ignored issues
show
Bug introduced by
It seems like $c defined by array() on line 179 can also be of type array; however, _request() does only seem to accept boolean, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
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...
230
	AND $id_parent != $id_rubrique
231
	AND ($id_secteur = sql_getfetsel('id_secteur', 'spip_rubriques', "id_rubrique=$id_parent"))) {
232
		$champs['id_rubrique'] = $id_parent;
0 ignored issues
show
Bug introduced by
The variable $champs 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...
233
		if ($id_secteur_old != $id_secteur)
234
			$champs['id_secteur'] = $id_secteur;
235
		// si le site est publie
236
		// et que le demandeur n'est pas admin de la rubrique
237
		// repasser le site en statut 'prop'.
238
		if ($statut == 'publie') {
239
			if (!autoriser('publierdans','rubrique',$id_parent))
240
				$champs['statut'] = $statut = 'prop';
241
		}
242
	}
243
244
	if (!$champs) return;
0 ignored issues
show
Bug Best Practice introduced by
The expression $champs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
245
246
	// Enregistrer les modifications
247
	sql_updateq('spip_syndic', $champs, "id_syndic=$id_syndic");
248
249
	// Invalider les caches
250
	if ($statut == 'publie') {
251
		include_spip('inc/invalideur');
252
		suivre_invalideur("id='id_syndic/$id_syndic'");
253
	}
254
255
	// Notifications
256
	if ($notifications = charger_fonction('notifications', 'inc')) {
257
		$notifications('instituersite', $id_syndic,
258
			array('statut' => $statut, 'statut_ancien' => $statut_ancien, 'date'=>($champs['date']?$champs['date']:$row['date']))
259
		);
260
	}
261
262
	include_spip('inc/rubriques');
263
	calculer_rubriques_if($id_rubrique, $champs, $statut_ancien);
264
}
265
266
267
// Enregistrre les options et retourne True s'il faut syndiquer.
268
269
// http://doc.spip.org/@editer_site_options
270
function editer_site_options($id_syndic)
271
{
272
	$moderation = _request('moderation');
273
	$miroir = _request('miroir');
274
	$oubli = _request('oubli');
275
	$resume = _request('resume');
276
277
	if ($moderation == 'oui' OR $moderation == 'non')
278
		sql_updateq("spip_syndic", array("moderation" => $moderation), "id_syndic=$id_syndic");
279
	if ($miroir == 'oui' OR $miroir == 'non')
280
		sql_updateq("spip_syndic", array("miroir" => $miroir	), "id_syndic=$id_syndic");
281
	if ($oubli == 'oui' OR $oubli == 'non')
282
		sql_updateq("spip_syndic", array("oubli" => $oubli), "id_syndic=$id_syndic");
283
284
	if (!($resume == 'oui' OR $resume == 'non')) return false;
285
286
	sql_updateq("spip_syndic", array("resume" => $resume	), "id_syndic=$id_syndic");
287
	return true;
288
}
289
290
?>
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...
291