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

notifications.php ➔ email_notification_forum()   F

Complexity

Conditions 18
Paths 2080

Size

Total Lines 86
Code Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 18
eloc 54
nc 2080
nop 2
dl 0
loc 86
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
16
// La fonction de notification de base, qui dispatche le travail
17
// http://doc.spip.org/@inc_notifications_dist
18
function inc_notifications_dist($quoi, $id=0, $options=array()) {
19
20
	// charger les fichiers qui veulent ajouter des definitions
21
	// ou faire des trucs aussi dans le pipeline, ca fait deux api pour le prix d'une ...
22
	pipeline('notifications',array('args'=>array('quoi'=>$quoi,'id'=>$id,'options'=>$options)));
23
24
	if ($notification = charger_fonction($quoi,'notifications',true)) {
25
		spip_log("$notification($quoi,$id"
26
			.($options?",".serialize($options):"")
27
			.")",'notifications');
28
		$notification($quoi, $id, $options);
29
	}
30
}
31
32
/**
33
 * Nettoyage des emails avant un envoi
34
 * on passe par reference pour la perf
35
 *
36
 * les emails liste par $eclure seront exclus de la liste
37
 *
38
 * @param array $emails
39
 * @param array $exclure
40
 */
41
function notifications_nettoyer_emails(&$emails, $exclure = array()){
42
	// filtrer et unifier
43
	$emails = array_unique(array_filter(array_map('email_valide',array_map('trim', $emails))));
44
	if ($exclure AND count($exclure)){
45
		// nettoyer les exclusions d'abord
46
		notifications_nettoyer_emails($exclure);
47
		// faire un diff
48
		$emails = array_diff($emails,$exclure);
49
	}
50
}
51
52
/**
53
 * Envoyer un email de notification
54
 * Le sujet peut etre vide, dans ce cas il reprendra la premiere ligne non vide du texte
55
 *
56
 * @param array/string $emails
0 ignored issues
show
Documentation introduced by
The doc-type array/string could not be parsed: Unknown type name "array/string" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
57
 * @param string $texte
58
 * @param string $sujet
59
 */
60
function notifications_envoyer_mails($emails,$texte,$sujet=""){
61
	// rien a faire si pas de texte !
62
	if (!strlen($texte))
63
		return;
64
65
	// si on ne specifie qu'un email, le mettre dans un tableau
66
	if (!is_array($emails))
67
		$emails = explode(',',$emails);
68
69
	notifications_nettoyer_emails($emails);
70
71
	// si le sujet est vide, extraire la premiere ligne du corps
72
	if (!strlen($sujet)){
73
		// nettoyer un peu les retours chariots
74
		$texte = str_replace("\r\n", "\r", $texte);
75
		$texte = str_replace("\r", "\n", $texte);
76
		// decouper
77
		$texte = explode("\n",trim($texte));
78
		// extraire la premiere ligne
79
		$sujet = array_shift($texte);
80
		$texte = trim(implode("\n",$texte));
81
	}
82
83
	$envoyer_mail = charger_fonction('envoyer_mail','inc');
84
	foreach($emails as $email){
85
		// passer dans un pipeline qui permet un ajout eventuel
86
		// (url de suivi des notifications par exemple)
87
		$envoi = pipeline('notifications_envoyer_mails',array('email'=>$email,'sujet'=>$sujet,'texte'=>$texte));
88
		$email = $envoi['email'];
89
		$sujet = $envoi['sujet'];
90
		$texte = $envoi['texte'];
91
		if (function_exists('job_queue_add'))
92
			job_queue_add('envoyer_mail', ">$email : $sujet", array($email, $sujet, $texte), 'inc/');
93
		else
94
			$envoyer_mail($email, $sujet, $texte);
95
	}
96
97
}
98
99
/**
100
 * Notifier un evenement sur un article
101
 * recupere le fond designe dans $modele,
102
 * prend la premiere ligne comme sujet
103
 * et l'interprete pour envoyer l'email
104
 *
105
 * @param int $id_article
106
 * @param string $modele
107
 */
108
function email_notification_article($id_article, $modele) {
109
	$envoyer_mail = charger_fonction('envoyer_mail','inc'); // pour nettoyer_titre_email
0 ignored issues
show
Unused Code introduced by
$envoyer_mail is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
110
111
	return recuperer_fond($modele,array('id_article'=>$id_article));
112
}
113
114
// Compatibilite, ne plus utiliser
115
// http://doc.spip.org/@notifier_publication_article
116 View Code Duplication
function notifier_publication_article($id_article) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in 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...
117
	if ($GLOBALS['meta']["suivi_edito"] == "oui") {
118
		$adresse_suivi = $GLOBALS['meta']["adresse_suivi"];
119
		$texte = email_notification_article($id_article, "notifications/article_publie");
120
		notifications_envoyer_mails($adresse_suivi, $texte);
121
	}
122
}
123
124
// Compatibilite, ne plus utiliser
125
// http://doc.spip.org/@notifier_proposition_article
126 View Code Duplication
function notifier_proposition_article($id_article) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in 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...
127
	if ($GLOBALS['meta']["suivi_edito"] == "oui") {
128
		$adresse_suivi = $GLOBALS['meta']["adresse_suivi"];
129
		$texte = email_notification_article($id_article, "notifications/article_propose");
130
		notifications_envoyer_mails($adresse_suivi, $texte);
131
	}
132
}
133
134
/**
135
 * Construitre l'email personalise de notification d'un forum
136
 *
137
 * @param array $t
138
 * @param string $email
139
 * @return string
140
 */
141
function email_notification_forum ($t, $email) {
142
	static $contexte = array();
143
144
	if(!isset($contexte[$t['id_forum']])){
145
		$url = '';
146
		$id_forum = $t['id_forum'];
147
148
		if ($t['statut'] == 'prive') # forum prive
149
		{
150
			if ($t['id_article'])
151
				$url = generer_url_ecrire('articles', 'id_article='.$t['id_article']).'#id'.$id_forum;
152
			else if ($t['id_breve'])
153
				$url = generer_url_ecrire('breves_voir', 'id_breve='.$t['id_breve']).'#id'.$id_forum;
154
			else if ($t['id_syndic'])
155
				$url = generer_url_ecrire('sites', 'id_syndic='.$t['id_syndic']).'#id'.$id_forum;
156
		}
157
		else if ($t['statut'] == 'privrac') # forum general
158
		{
159
			$url = generer_url_ecrire('forum').'#id'.$id_forum;
160
		}
161
		else if ($t['statut'] == 'privadm') # forum des admins
162
		{
163
			$url = generer_url_ecrire('forum_admin').'#id'.$id_forum;
164
		}
165
		else if ($t['statut'] == 'publie') # forum publie
166
		{
167
			$url = generer_url_entite($id_forum, 'forum');
168
		}
169
		else #  forum modere, spam, poubelle direct ....
170
		{
171
			$url = generer_url_ecrire('controle_forum', "debut_id_forum=".$id_forum);
172
		}
173
174
		if (!$url) {
175
			spip_log("forum $id_forum sans referent",'notifications');
176
			$url = './';
177
		}
178
		if ($t['id_article']) {
179
			$titre = sql_getfetsel("titre", "spip_articles", "id_article=".sql_quote($t['id_article']));
180
		}
181
		if ($t['id_message']) {
182
			$titre = sql_getfetsel("titre", "spip_messages", "id_message=".sql_quote($t['id_message']));
183
		}
184
185
		$t['titre_source'] = $titre;
0 ignored issues
show
Bug introduced by
The variable $titre 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...
186
		$t['url'] = $url;
187
188
		// detecter les url des liens du forum
189
		// pour la moderation (permet de reperer les SPAMS avec des liens caches)
190
		$links = array();
191
		foreach ($t as $champ)
192
			$links = $links + extraire_balises($champ,'a');
193
		$links = extraire_attribut($links,'href');
194
		$links = implode("\n",$links);
195
		$t['liens'] = $links;
196
197
		$contexte[$t['id_forum']] = $t;
198
	}
199
200
	$t = $contexte[$t['id_forum']];
201
		// Rechercher eventuellement la langue du destinataire
202
	if (NULL !== ($l = sql_getfetsel('lang', 'spip_auteurs', "email=" . sql_quote($email))))
203
		$l = lang_select($l);
204
205
	$parauteur = (strlen($t['auteur']) <= 2) ? '' :
206
		(" " ._T('forum_par_auteur', array(
207
			'auteur' => $t['auteur'])
208
		) .
209
		 ($t['email_auteur'] ? ' <' . $t['email_auteur'] . '>' : ''));
210
211
	$titre = textebrut(typo($t['titre_source']));
212
	$forum_poste_par = ($t['id_article']
213
		? _T('forum_poste_par', array(
214
			'parauteur' => $parauteur, 'titre' => $titre))
215
		: $parauteur . ' (' . $titre . ')');
216
217
	$t['par_auteur'] = $forum_poste_par;
218
219
	$envoyer_mail = charger_fonction('envoyer_mail','inc'); // pour nettoyer_titre_email
0 ignored issues
show
Unused Code introduced by
$envoyer_mail is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
220
	$corps = recuperer_fond("notifications/forum_poste",$t);
221
222
	if ($l)
223
		lang_select();
224
225
	return $corps;
226
}
227
228
229
230
?>
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...
231