Issues (82)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

code/MailgunHelper.php (8 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace LeKoala\Mailgun;
4
5
use \Exception;
6
use Mailgun\Mailgun;
7
use SilverStripe\Control\Director;
8
use SilverStripe\Core\Environment;
9
use SilverStripe\Control\Email\Email;
10
use SilverStripe\Control\Email\Mailer;
11
use SilverStripe\SiteConfig\SiteConfig;
12
use SilverStripe\Core\Injector\Injector;
13
use LeKoala\Mailgun\MailgunSwiftTransport;
14
use SilverStripe\Core\Config\Configurable;
15
use SilverStripe\Control\Email\SwiftMailer;
16
17
/**
18
 * This configurable class helps decoupling the api client from SilverStripe
19
 */
20
class MailgunHelper
21
{
22
    use Configurable;
23
24
    const DEFAULT_ENDPOINT = 'https://api.mailgun.net/v3';
25
    const EU_ENDPOINT = 'https://api.eu.mailgun.net/v3';
26
27
    /**
28
     * Client instance
29
     *
30
     * @var Mailgun
31
     */
32
    protected static $client;
33
34
    /**
35
     * Get the mailer instance
36
     *
37
     * @return SilverStripe\Control\Email\SwiftMailer
38
     */
39
    public static function getMailer()
40
    {
41
        return Injector::inst()->get(Mailer::class);
42
    }
43
44
    /**
45
     * Get the api client instance
46
     * @return Mailgun
47
     * @throws Exception
48
     */
49
    public static function getClient()
50
    {
51
        if (!self::$client) {
52
            $key = self::config()->api_key;
53
            if (empty($key)) {
54
                throw new \Exception("api_key is not configured for " . __class__);
55
            }
56
            $endpoint = self::DEFAULT_ENDPOINT;
57
            if (self::config()->endpoint) {
58
                $endpoint = self::config()->endpoint;
59
            }
60
            self::$client = Mailgun::create($key, $endpoint);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Mailgun\Mailgun::create($key, $endpoint) of type object<self> is incompatible with the declared type object<Mailgun\Mailgun> of property $client.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
61
        }
62
        return self::$client;
0 ignored issues
show
Bug Compatibility introduced by
The expression self::$client; of type self|Mailgun\Mailgun adds the type self to the return on line 62 which is incompatible with the return type documented by LeKoala\Mailgun\MailgunHelper::getClient of type Mailgun\Mailgun.
Loading history...
63
    }
64
65
    /**
66
     * Get the log folder and create it if necessary
67
     *
68
     * @return string
69
     */
70
    public static function getLogFolder()
71
    {
72
        $logFolder = BASE_PATH . '/' . self::config()->log_folder;
73
        if (!is_dir($logFolder)) {
74
            mkdir($logFolder, 0755, true);
75
        }
76
        return $logFolder;
77
    }
78
79
    /**
80
     * @return string
81
     */
82
    public static function getDomain()
83
    {
84
        if ($domain = self::config()->domain) {
85
            return $domain;
86
        }
87
        if ($domain = Environment::getEnv('MAILGUN_DOMAIN')) {
88
            return $domain;
89
        }
90
        throw new Exception("MAILGUN_DOMAIN not set");
91
    }
92
93
    /**
94
     * Process environment variable to configure this module
95
     *
96
     * @return void
97
     */
98
    public static function init()
99
    {
100
        // Regular api key used for sending emails
101
        $api_key = Environment::getEnv('MAILGUN_API_KEY');
102
        if ($api_key) {
103
            self::config()->api_key = $api_key;
104
        }
105
106
        $domain = Environment::getEnv('MAILGUN_DOMAIN');
107
        if ($domain) {
108
            self::config()->domain = $domain;
109
        }
110
111
        // Set a custom endpoint
112
        $endpoint = Environment::getEnv('MAILGUN_ENDPOINT');
113
        if ($endpoint) {
114
            self::config()->endpoint = $endpoint;
115
        }
116
117
        // Disable sending
118
        $sending_disabled = Environment::getEnv('MAILGUN_SENDING_DISABLED');
119
        if ($sending_disabled) {
120
            self::config()->disable_sending = $sending_disabled;
121
        }
122
123
        // Log all outgoing emails (useful for testing)
124
        $enable_logging = Environment::getEnv('MAILGUN_ENABLE_LOGGING');
125
        if ($enable_logging) {
126
            self::config()->enable_logging = $enable_logging;
127
        }
128
129
        // We have a key, we can register the transport
130
        if (self::config()->api_key) {
131
            self::registerTransport();
132
        }
133
    }
134
135
    /**
136
     * Register the transport with the client
137
     *
138
     * @return SilverStripe\Control\Email\SwiftMailer The updated swift mailer
139
     * @throws Exception
140
     */
141
    public static function registerTransport()
142
    {
143
        $client = self::getClient();
144
        $mailer = self::getMailer();
145
        if (!$mailer instanceof SwiftMailer) {
146
            throw new Exception("Mailer must be an instance of " . SwiftMailer::class . " instead of " . get_class($mailer));
147
        }
148
        $transport = new MailgunSwiftTransport($client);
149
        $newSwiftMailer = $mailer->getSwiftMailer()->newInstance($transport);
150
        $mailer->setSwiftMailer($newSwiftMailer);
151
        return $mailer;
152
    }
153
154
155
    /**
156
     * Resolve default send from address
157
     *
158
     * Keep in mind that an email using send() without a from
159
     * will inject the admin_email. Therefore, SiteConfig
160
     * will not be used
161
     *
162
     * @param string $from
163
     * @param bool $createDefault
164
     * @return string
165
     */
166
    public static function resolveDefaultFromEmail($from = null, $createDefault = true)
167
    {
168
        $original_from = $from;
169 View Code Duplication
        if (!empty($from)) {
0 ignored issues
show
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...
170
            // If we have a sender, validate its email
171
            $from = EmailUtils::get_email_from_rfc_email($from);
172
            if (filter_var($from, FILTER_VALIDATE_EMAIL)) {
173
                return $original_from;
174
            }
175
        }
176
        // Look in siteconfig for default sender
177
        $config = SiteConfig::current_site_config();
178
        $config_field = self::config()->siteconfig_from;
179
        if ($config_field && !empty($config->$config_field)) {
180
            return $config->$config_field;
181
        }
182
        // Use admin email
183
        if ($admin = Email::config()->admin_email) {
184
            return $admin;
185
        }
186
        // If we still don't have anything, create something based on the domain
187
        if ($createDefault) {
188
            return self::createDefaultEmail();
189
        }
190
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by LeKoala\Mailgun\MailgunH...resolveDefaultFromEmail of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
191
    }
192
193
    /**
194
     * Resolve default send to address
195
     *
196
     * @param string $to
197
     * @return string
198
     */
199
    public static function resolveDefaultToEmail($to = null)
200
    {
201
        // In case of multiple recipients, do not validate anything
202
        if (is_array($to) || strpos($to, ',') !== false) {
203
            return $to;
0 ignored issues
show
Bug Compatibility introduced by
The expression return $to; of type string|null|array is incompatible with the return type documented by LeKoala\Mailgun\MailgunH...::resolveDefaultToEmail of type string as it can also be of type array which is not included in this return type.
Loading history...
204
        }
205
        $original_to = $to;
206 View Code Duplication
        if (!empty($to)) {
0 ignored issues
show
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...
207
            $to = EmailUtils::get_email_from_rfc_email($to);
208
            if (filter_var($to, FILTER_VALIDATE_EMAIL)) {
209
                return $original_to;
210
            }
211
        }
212
        $config = SiteConfig::current_site_config();
213
        $config_field = self::config()->siteconfig_to;
214
        if ($config_field && !empty($config->$config_field)) {
215
            return $config->$config_field;
216
        }
217
        if ($admin = Email::config()->admin_email) {
218
            return $admin;
219
        }
220
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by LeKoala\Mailgun\MailgunH...::resolveDefaultToEmail of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
221
    }
222
223
    /**
224
     * Create a sensible default address based on domain name
225
     *
226
     * @return string
227
     */
228
    public static function createDefaultEmail()
229
    {
230
        $fulldom = Director::absoluteBaseURL();
231
        $host = parse_url($fulldom, PHP_URL_HOST);
232
        if (!$host) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $host of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
233
            $host = 'localhost';
234
        }
235
        $dom = str_replace('www.', '', $host);
236
237
        return 'postmaster@' . $dom;
238
    }
239
}
240