Completed
Push — master ( d21053...c59b30 )
by
unknown
08:11
created

start.php ➔ phpmailer_send()   F

Complexity

Conditions 25
Paths 1348

Size

Total Lines 141

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 25
nc 1348
nop 9
dl 0
loc 141
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/**
3
 * PHPMailer Plugin
4
 * 
5
 * @package PHPMailer
6
 * @license Lesser General Public License (LGPL)
7
 * @author Cash Costello
8
 * @copyright Cash Costello 2008-2011
9
 */
10
11
12
elgg_register_event_handler('init', 'system', 'phpmailer_init');
13
14
/**
15
 * initialize the phpmailer plugin
16
 */
17
function phpmailer_init() {
18
	/*if (elgg_get_plugin_setting('phpmailer_override', 'phpmailer') != 'disabled') {
19
		register_notification_handler('email', 'phpmailer_notify_handler');
20
		elgg_register_plugin_hook_handler('email', 'system', 'phpmailer_mail_override');
21
	}*/
22
}
23
24
/**
25
 * Send a notification via email using phpmailer
26
 *
27
 * @param ElggEntity $from The from user/site/object
28
 * @param ElggUser $to To which user?
29
 * @param string $subject The subject of the message.
30
 * @param string $message The message body
31
 * @param array $params Optional parameters (not used)
32
 * @return bool
33
 */
34
function phpmailer_notify_handler(ElggEntity $from, ElggUser $to, $subject, $message, array $params = NULL) {
35
36
	if (!$from) {
37
		throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'from'));
38
	}
39
40
	if (!$to) {
41
		throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'to'));
42
	}
43
44
	if ($to->email == "") {
45
		throw new NotificationException(sprintf(elgg_echo('NotificationException:NoEmailAddress'), $to->guid));
46
	}
47
48
	$from_email = phpmailer_extract_from_email($from);
49
	$site = elgg_get_site_entity();
50
	$from_name = $site->name;
51
52
	return phpmailer_send($from_email, $from_name, $to->email, '', $subject, $message);
0 ignored issues
show
Documentation introduced by
$subject is of type string, but the function expects a null|array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$message is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
53
}
54
55
/**
56
 * Overrides the default email send method of Elgg
57
 * @note Will need to add code to handle from and to if using: name <email>
58
 */
59
function phpmailer_mail_override($hook, $entity_type, $returnvalue, $params) {
60
	return phpmailer_send(
61
			$params["from"],
62
			$params["from"],
63
			$params["to"],
64
			'',
65
			$params["subject"],
66
			$params["body"]);
67
}
68
69
/**
70
 * Determine the best 'from' email address
71
 *
72
 * This is a stupid function pulled from original Elgg code
73
 *
74
 * @param  ElggEntity The entity sending the message
75
 * @return string with email address
76
 */
77
function phpmailer_extract_from_email($from) {
78
	$from_email = '';
79
	$site = elgg_get_site_entity();
80
	// If there's an email address, use it - but only if its not from a user.
81
	if ($from->email && !($from instanceof ElggUser)) {
82
		$from_email = $from->email;
83
	// Has the current site got a from email address?
84
	} else if ($site && $site->email) {
85
		$from_email = $site->email;
86
	// If we have a url then try and use that.
87
	} else if (isset($from->url)) {
88
		$breakdown = parse_url($from->url);
89
		$from_email = 'noreply@' . $breakdown['host'];
90
	// If all else fails, use the domain of the site.
91
	} else {
92
		$from_email = 'noreply@' . get_site_domain($site->guid);
93
	}
94
	
95
	return $from_email;
96
}
97
98
/**
99
 * Send an email using phpmailer
100
 *
101
 * @param string $from       From address
0 ignored issues
show
Bug introduced by
There is no parameter named $from. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
102
 * @param string $from_name  From name
0 ignored issues
show
Bug introduced by
There is no parameter named $from_name. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
103
 * @param string $to         To address
104
 * @param string $to_name    To name
105
 * @param string $subject    The subject of the message.
106
 * @param string $body       The message body
107
 * @param array  $bcc        Array of address strings
108
 * @param bool   $html       Set true for html email, also consider setting
109
 *                           altbody in $params array
110
 * @param array  $files      Array of file descriptor arrays, each file array
111
 *                           consists of full path and name
112
 * @param array  $params     Additional parameters
113
 * @return bool
114
 */
115
function phpmailer_send($to, $to_name, $subject, $body, array $bcc = NULL, $html = true, array $files = NULL, array $params = NULL, $image = NULL) {
116
117
	require_once elgg_get_plugins_path() . '/phpmailer/vendors/class.phpmailer.php';
118
	$phpmailer = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
0 ignored issues
show
Unused Code introduced by
The call to PHPMailer::__construct() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
119
120
	// CONFIGURE SERVER INFORMATION defaults
121
	$phpmailer->IsSMTP(); // telling the class to use SMTP
122
	$phpmailer->Host       = elgg_get_plugin_setting('phpmailer_host', 'phpmailer'); // SMTP server
123
	$phpmailer->Port       = elgg_get_plugin_setting('ep_phpmailer_port', 'phpmailer'); // SMTP server port
124
	$phpmailer->SMTPAuth   = elgg_get_plugin_setting('phpmailer_smtp_auth', 'phpmailer');
125
	$phpmailer->SMTPSecure = "";	// set below
126
	$phpmailer->Username = elgg_get_plugin_setting('phpmailer_username', 'phpmailer');
127
	$phpmailer->Password = elgg_get_plugin_setting('phpmailer_password', 'phpmailer');
128
	$phpmailer->SetFrom( elgg_get_plugin_setting('phpmailer_from_email', 'phpmailer'), elgg_get_plugin_setting('phpmailer_from_name', 'phpmailer') );
0 ignored issues
show
Bug introduced by
The method SetFrom() does not seem to exist on object<PHPMailer>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
129
130
	/*if (!$from) {
131
		throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'from'));
132
	}*/
133
134
	if (!$to && !$bcc) {
135
		throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'to'));
136
	}
137
138
	if (!$subject) {
139
		throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'subject'));
140
	}
141
142
	// set line ending if admin selected \n (if admin did not change setting, null is returned)
143
	if (elgg_get_plugin_setting('nonstd_mta', 'phpmailer'))
144
		$phpmailer->LE = "\n";
145
	else
146
		$phpmailer->LE = "\r\n";
147
	
148
	////////////////////////////////////
149
	// Format message
150
	$phpmailer->SMTPDebug = 0; // Set to 1 for debugging information
0 ignored issues
show
Documentation Bug introduced by
The property $SMTPDebug was declared of type boolean, but 0 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
151
152
	$phpmailer->ClearAllRecipients();
153
	$phpmailer->ClearAttachments();
154
155
	// Set the from name and email
156
	//$phpmailer->From = $from;
157
	//$phpmailer->FromName = $from_name;
158
159
	if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
160
		return;
161
	}
162
163
	// Set destination address
164
	if (isset($to)) {
165
		$phpmailer->AddAddress($to, $to_name);
166
	}
167
168
	// set bccs if exists
169
	if ($bcc && is_array($bcc)) {
170
		foreach ($bcc as $address)
171
			$phpmailer->AddBCC($address);
172
	}
173
174
	$phpmailer->Subject = $subject;
175
	
176
	if ($image)
177
		$phpmailer->AddEmbeddedImage($image, 'wire_image');
178
179
	if (!$html) {
180
		$phpmailer->CharSet = 'utf-8';
181
		$phpmailer->IsHTML(false);
182
		if ($params && array_key_exists('altbody', $params)) {
183
			$phpmailer->AltBody = $params['altbody'];
184
		}
185
186
		$trans_tbl = get_html_translation_table(HTML_ENTITIES);
187
		$trans_tbl[chr(146)] = '&rsquo;';
188
		foreach ($trans_tbl as $k => $v) {
189
			$ttr[$v] = utf8_encode($k);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$ttr was never initialized. Although not strictly required by PHP, it is generally a good practice to add $ttr = 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...
190
		}
191
		$source = strtr($body, $ttr);
0 ignored issues
show
Bug introduced by
The variable $ttr 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...
192
		$body = strip_tags($source);
193
194
		$phpmailer->Body = $body;
195
	
196
	} else {
197
	
198
		//$phpmailer->IsHTML(true);
199
		$phpmailer->CharSet = 'utf-8';
200
		$phpmailer->MsgHTML($body);
201
	}
202
203
204
	if ($files && is_array($files)) {
205
		foreach ($files as $file) {
206
			if (isset($file['path']))
207
				$phpmailer->AddAttachment($file['path'], $file['name']);
208
		}
209
	}
210
211
	$is_smtp   = elgg_get_plugin_setting('phpmailer_smtp', 'phpmailer');
212
	$smtp_host = elgg_get_plugin_setting('phpmailer_host', 'phpmailer');
213
	$smtp_auth = elgg_get_plugin_setting('phpmailer_smtp_auth', 'phpmailer');
214
215
	$is_ssl    = elgg_get_plugin_setting('ep_phpmailer_ssl', 'phpmailer');
216
	$smtp_port  = elgg_get_plugin_setting('ep_phpmailer_port', 'phpmailer');
217
218
	try {
219
220
		if ($is_smtp && isset($smtp_host)) {
221
222
			if ($smtp_auth && $is_ssl) {
223
224
				$phpmailer->SMTPSecure = "tls";
225
				
226
			}
227
		} else {
228
			// use php's mail
229
			$phpmailer->IsMail();
230
		}
231
232
		$phpmailer->Port = $smtp_port;
233
	
234
		$return = $phpmailer->Send();
235
236
	} catch (phpmailerException $e) {
0 ignored issues
show
Bug introduced by
The class phpmailerException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
237
		
238
		$errMess = $e->getMessage();
239
		$errStack = $e->getTraceAsString();
240
		$errType = $e->getCode();
241
		phpmailer_logging($errMess, $errStack, 'PHPMailer', $errType);
242
	}
243
244
245
246
	if (!$return) {
0 ignored issues
show
Bug introduced by
The variable $return 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...
247
		
248
		$errMess = $phpmailer->ErrorInfo;
249
		$errStack = "";
250
		$errType = "custom";
251
		phpmailer_logging($errMess, $errStack, 'PHPMailer', $errType);
252
	}
253
254
	return $return;
255
}
256
257
258
259
function phpmailer_logging($errMess, $errStack, $type, $errType) {
260
	// logging mechanism
261
	if (elgg_is_active_plugin('wet4')) {
262
		elgg_load_library('GCconnex_logging');
263
		gc_err_logging($errMess, $errStack, $type, $errType);
264
	}
265
}