FGContactForm::ValidateFileUploads()   B
last analyzed

Complexity

Conditions 9
Paths 14

Size

Total Lines 37

Duplication

Lines 37
Ratio 100 %

Importance

Changes 0
Metric Value
cc 9
nc 14
nop 0
dl 37
loc 37
rs 7.7724
c 0
b 0
f 0
1
<?PHP
2
/*
3
    Contact Form from HTML Form Guide
4
5
    This program is free software published under the
6
    terms of the GNU Lesser General Public License.
7
8
This program is distributed in the hope that it will
9
be useful - WITHOUT ANY WARRANTY; without even the
10
implied warranty of MERCHANTABILITY or FITNESS FOR A
11
PARTICULAR PURPOSE.
12
13
@copyright html-form-guide.com 2010
14
*/
15
require_once( elgg_get_plugins_path() ."phpmailer/vendors/class.phpmailer.php");
16
17
/*
18
Interface to Captcha handler
19
*/
20
class FG_CaptchaHandler
21
{
22
    function Validate() { return false;}
23
    function GetError(){ return '';}
24
}
25
/*
26
FGContactForm is a general purpose contact form class
27
It supports Captcha, HTML Emails, sending emails
28
conditionally, File atachments and more.
29
*/
30 View Code Duplication
class FGContactForm
0 ignored issues
show
Duplication introduced by
This class 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...
31
{
32
    var $receipients;
33
    var $errors;
34
    var $error_message;
35
    var $name;
36
    var $email;
37
    var $message;
38
    var $from_address;
39
    var $form_random_key;
40
    var $conditional_field;
41
    var $arr_conditional_receipients;
42
    var $fileupload_fields;
43
    var $captcha_handler;
44
    var $mailer;
45
46
    function FGContactForm()
47
    {
48
        $this->receipients = array();
49
        $this->errors = array();
50
        $this->form_random_key = 'HTgsjhartag';
51
        $this->conditional_field='';
52
        $this->arr_conditional_receipients=array();
53
        $this->fileupload_fields=array();
54
        $this->mailer = new PHPMailer();
55
        $this->mailer->CharSet = 'utf-8';
56
        $this->mailer->IsSMTP();
57
        $this->mailer->Host = elgg_get_plugin_setting('phpmailer_host', 'phpmailer'); // SMTP server
58
        $this->mailer->Port = elgg_get_plugin_setting('ep_phpmailer_port', 'phpmailer'); // SMTP server port
59
        $this->mailer->SMTPSecure = 'tls';
60
        $this->mailer->SMTPAuth = 'true';
0 ignored issues
show
Documentation Bug introduced by
The property $SMTPAuth was declared of type boolean, but 'true' is of type string. 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...
61
        $this->mailer->Username = elgg_get_plugin_setting('phpmailer_username', 'phpmailer');
62
        $this->mailer->Password = elgg_get_plugin_setting('phpmailer_password', 'phpmailer');
63
    }
64
65
    function EnableCaptcha($captcha_handler)
66
    {
67
        $this->captcha_handler = $captcha_handler;
68
        session_start();
69
    }
70
71
    function AddRecipient($email,$name="")
72
    {
73
        $this->mailer->AddAddress($email,$name);
74
    }
75
76
    function SetFromAddress($from)
77
    {
78
        $this->from_address = $from;
79
    }
80
    function SetFormRandomKey($key)
81
    {
82
        $this->form_random_key = $key;
83
    }
84
    function GetSpamTrapInputName()
85
    {
86
        return 'sp'.md5('KHGdnbvsgst'.$this->GetKey());
87
    }
88
    function SafeDisplay($value_name)
89
    {
90
        if(empty($_POST[$value_name]))
91
        {
92
            return'';
93
        }
94
        return htmlentities($_POST[$value_name]);
95
    }
96
    function GetFormIDInputName()
97
    {
98
        $rand = md5('TygshRt'.$this->GetKey());
99
100
        $rand = substr($rand,0,20);
101
        return 'id'.$rand;
102
    }
103
104
105
    function GetFormIDInputValue()
106
    {
107
        return md5('jhgahTsajhg'.$this->GetKey());
108
    }
109
110
    function SetConditionalField($field)
111
    {
112
        $this->conditional_field = $field;
113
    }
114
    function AddConditionalReceipent($value,$email)
115
    {
116
        $this->arr_conditional_receipients[$value] =  $email;
117
    }
118
119
    function AddFileUploadField($file_field_name,$accepted_types,$max_size)
120
    {
121
122
        $this->fileupload_fields[] =
123
            array("name"=>$file_field_name,
124
            "file_types"=>$accepted_types,
125
            "maxsize"=>$max_size);
126
    }
127
128
    function ProcessForm()
129
    {
130
        if(!isset($_POST['submitted']))
131
        {
132
           return false;
133
        }
134
        if(!$this->Validate())
135
        {
136
           // $this->error_message = implode('<br/><br/><br/>',$this->errors);
137
            return false;
138
        }
139
        $this->CollectData();
140
141
        $ret = $this->SendFormSubmission();
142
143
        return $ret;
144
    }
145
146
    function RedirectToURL($url)
147
    {
148
        header("Location: $url");
149
        exit;
150
    }
151
152
    function GetErrorMessage()
153
    {
154
        return $this->error_message;
155
    }
156
    function GetSelfScript()
157
    {
158
        return htmlentities($_SERVER['PHP_SELF']);
159
    }
160
161
    function GetName()
162
    {
163
        return $this->name;
164
    }
165
    function GetEmail()
166
    {
167
        return $this->email;
168
    }
169
    function GetMessage()
170
    {
171
        return htmlentities($this->message,ENT_QUOTES,"UTF-8");
172
    }
173
174
/*--------  Private (Internal) Functions -------- */
175
176
177
    function SendFormSubmission()
178
    {
179
              $reason = $_POST['reason'];
180
                $option = explode("$", $_POST['reason']);
181
                    $categoryfr = $option[0];
182
                    $categoryen = $option[1]; 
183
184
        $depart = $_POST['depart'];
185
        $reason = $_POST['reason'];
186
                $option = explode("$", $_POST['reason']);
187
                    $french = $option[0];
188
                    $english = $option[1]; 
189
         if(empty($_POST['subject']))
190
           {
191
           $subject = $categoryen." - ".$depart. " - $this->name  / ".$categoryfr." - ".$depart. " - $this->name";
192
           }else{
193
            $subject = "GCconnex - ".$depart. " - $this->name  / GCconnex - ".$depart. " - $this->name";
194
           }
195
        
196
        $this->CollectConditionalReceipients();
197
        $this->mailer->CharSet = 'utf-8';
198
        $this->mailer->Subject = $subject;
199
        $this->mailer->From = elgg_get_plugin_setting('phpmailer_from_email', 'phpmailer');
200
        $this->mailer->FromName = elgg_get_plugin_setting('phpmailer_from_name', 'phpmailer');
201
        $this->mailer->AddCC($this->email);
202
        $message = $this->ComposeFormtoEmail();
203
        $this->mailer->ConfirmReadingTo = $this->email;
204
        $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
205
        $this->mailer->AltBody = @html_entity_decode($textMsg,ENT_QUOTES,"UTF-8");
206
        $this->mailer->MsgHTML($message);
207
        $this->AttachFiles();
208
209
        if(!$this->mailer->Send())
210
        {
211
            $this->add_error("Failed sending email!");
212
            return false;
213
        }
214
215
        return true;
216
    }
217
218
    function CollectConditionalReceipients()
219
    {
220
        if(count($this->arr_conditional_receipients)>0 &&
221
          !empty($this->conditional_field) &&
222
          !empty($_POST[$this->conditional_field]))
223
        {
224
            foreach($this->arr_conditional_receipients as $condn => $rec)
225
            {
226
                if(strcasecmp($condn,$_POST[$this->conditional_field])==0 &&
227
                !empty($rec))
228
                {
229
                    $this->AddRecipient($rec);
230
                }
231
            }
232
        }
233
    }
234
235
    /*
236
    Internal variables, that you donot want to appear in the email
237
    Add those variables in this array.
238
    */
239
    function IsInternalVariable($varname)
240
    {
241
        $arr_interanl_vars = array('scaptcha',
242
                            'submitted',
243
                            $this->GetSpamTrapInputName(),
244
                            $this->GetFormIDInputName()
245
                            );
246
        if(in_array($varname,$arr_interanl_vars))
247
        {
248
            return true;
249
        }
250
        return false;
251
    }
252
253
    function FormSubmissionToMail()
254
    {
255
        $ret_str='';
256
        
257
                $name = $_POST['name'];
258
                $email = $_POST['email'];
259
                $reason = $_POST['reason'];
260
                $option = explode("$", $_POST['reason']);
261
                    $french = $option[0];
262
                    $english = $option[1]; 
263
                if(empty($_POST['subject']))
264
                {
265
                    $subject = "$this->name has contacted you about ". $english." / $this->name vous a envoyé un message à propos de ".$french;
266
                }else{
267
                    $subject = $_POST['subject'];
268
                }
269
        
270
                $message = $_POST['message'];
271
        
272
        $name=htmlentities($name, ENT_QUOTES, "UTF-8");
273
        $email=htmlentities($email, ENT_QUOTES, "UTF-8");
274
        $reason=htmlentities($reason, ENT_QUOTES, "UTF-8");
275
        $subject=htmlentities($subject, ENT_QUOTES, "UTF-8");
276
        $message=htmlentities($message, ENT_QUOTES, "UTF-8");
277
      
278
                $value = htmlentities($value,ENT_QUOTES,"UTF-8");
0 ignored issues
show
Bug introduced by
The variable $value seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
279
                $value = nl2br($value);
280
                $key = ucfirst($key);
0 ignored issues
show
Bug introduced by
The variable $key seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
281
                $ret_str .= '
282
283
<!-- beginning of email template -->
284
  <div width="100%" bgcolor="#fcfcfc">
285
    <div>
286
      <div>
287
288
        <!-- email header -->
289
            <div align="center" width="100%" style="background-color:#f5f5f5; padding:20px 30px 15px 30px; font-family: sans-serif; font-size: 12px; color: #055959">
290
              Thank you for contacting the GCconnex Help desk. This is a copy of your request.<br/><br/> Merci d\'avoir communiqué avec le bureau de soutien de GCconnex. Ceci est une copie de votre requête.
291
            </div>
292
        
293
294
            <!-- GCconnex banner -->
295
            <div width="100%" style="padding: 0 0 0 10px; color:#ffffff; font-family: sans-serif; font-size: 35px; line-height:38px; font-weight: bold; background-color:#047177;">
296
            <span style="padding: 0 0 0 3px; font-size: 20px; color: #ffffff; font-family: sans-serif;">GCconnex</span>
297
            </div>
298
299
            <!-- email divider -->
300
            <div style="height:1px; background:#bdbdbd; border-bottom:1px solid #ffffff"></div>
301
302
<!-- english -->
303
304
            <!-- main content of the notification (ENGLISH) -->
305
            <!-- *optional* email message (DO NOT REPLY) -->
306
            <div width="100%" style="padding:30px 30px 10px 30px; font-size:12px; line-height:22px; font-family:sans-serif;">
307
308
            <!-- The French Follows... -->
309
            <span style="font-size:12px; font-weight: normal;"><i>(Le fran&ccedil;ais suit)</i></span><br/>  
310
            </div>
311
312
            <div width="100%" style="padding:30px 30px 30px 30px; color:#153643; font-family:sans-serif; font-size:16px; line-height:22px; ">
313
            <!-- TITLE OF CONTENT -->
314
            <h2 style="padding: 0px 0px 15px 0px">
315
            <strong> GCconnex Contact Us Form </strong>
316
            </h2>
317
318
            <!-- BODY OF CONTENT -->
319
            <b>Name:</b> '.$name.'<br/>
320
            <b>Email:</b> '.$email.'<br/>
321
            <b>Reason:</b> '.$english.' <br/>
322
            <b>Subject:</b> '.$subject.'<br/>
323
            <b>Message:</b>'.$message .'<br/>
324
            </div>
325
                
326
            <div style="margin-top:15px; padding: 5px; color: #6d6d6d; border-bottom: 1px solid #ddd;"></div>
327
                
328
<!-- french -->
329
330
            <!-- main content of the notification (FRENCH) -->
331
            <!-- *optional* email message (DO NOT REPLY) -->
332
            <div id="gcc_fr_suit" name="gcc_fr_suit" width="100%" style="padding:30px 30px 10px 30px; font-size:12px; line-height:22px; font-family:sans-serif;"></div>
333
334
            <div width="100%" style="padding:30px 30px 30px 30px; color:#153643; font-family:sans-serif; font-size:16px; line-height:22px;">
335
            <!-- TITLE OF CONTENT -->
336
            <h2 style="padding: 0px 0px 15px 0px">
337
            <strong> Formulaire contactez-nous de GCconnex</strong>
338
            </h2>
339
340
            <!-- BODY OF CONTENT -->
341
            <b>Nom :</b> '.$name.'<br/> 
342
            <b>Courriel :</b> '.$email.'<br/>
343
            <b>Raison :</b> '.$french.'<br/>
344
            <b>Sujet :</b> '.$subject.'<br/>
345
            <b>Message :</b>'.$message.'<br/>
346
            </div>
347
            <div style="margin-top:15px; padding: 5px; color: #6d6d6d;"></div>
348
349
            <!-- email divider -->
350
            <div style="height:1px; background:#bdbdbd; border-bottom:1px solid #ffffff"></div>
351
352
            <!-- email footer -->
353
            <div align="center" width="100%" style="background-color:#f5f5f5; padding:20px 30px 15px 30px; font-family: sans-serif; font-size: 16px; color: #055959">
354
            Please do not reply to this message | Veuillez ne pas répondre à ce message
355
            </div>
356
357
      </div>
358
    </div>
359
  </div>';
360
361
        foreach($this->fileupload_fields as $upload_field)
362
        {
363
            $field_name = $upload_field["name"];
364
            if(!$this->IsFileUploaded($field_name))
365
            {
366
                continue;
367
            }        
368
            
369
            $filename = basename($_FILES[$field_name]['name']);
370
            $ret_str .= "<div class='label'>File upload '$field_name' :</div><div class='value'>$filename </div>\n";
371
        }
372
        return $ret_str;
373
    }
374
375
    function ExtraInfoToMail()
376
    {
377
        $ret_str='';
378
379
        $ip = $_SERVER['REMOTE_ADDR'];
380
        $ret_str = "<div class='label'>IP address of the submitter:</div><div class='value'>$ip</div>\n";
381
382
        return $ret_str;
383
    }
384
385
    function GetHTMLHeaderPart()
386
    {
387
         $retstr = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">'."\n".
388
                   '<html><head><title></title><style type="text/css">
389
  body {margin: 0; padding: 0; min-width: 100%!important;}
390
  img {height: auto;}
391
  .content {width: 100%; max-width: 600px;}
392
  .header {padding: 40px 30px 20px 30px;}
393
  .innerpadding {padding: 30px 30px 30px 30px;}
394
  .borderbottom {border-bottom: 1px solid #f2eeed;}
395
  .subhead {font-size: 15px; color: #ffffff; font-family: sans-serif; }
396
  .h1, .h2, .bodycopy {color: #153643; font-family: sans-serif;}
397
  .h1 {font-size: 33px; line-height: 38px; font-weight: bold;}
398
  .h2 {padding: 0 0 15px 0; font-size: 24px; line-height: 28px; font-weight: bold;}
399
  .bodycopy {font-size: 16px; line-height: 22px;}
400
  .button {text-align: center; font-size: 18px; font-family: sans-serif; font-weight: bold; padding: 0 30px 0 30px;}
401
  .button a {color: #ffffff; text-decoration: none;}
402
  .footer {padding: 20px 30px 15px 30px;}
403
  .footercopy {font-family: sans-serif; font-size: 14px; color: #ffffff;}
404
  .footercopy a {color: #ffffff; text-decoration: underline;}
405
  @media only screen and (max-width: 550px), screen and (max-device-width: 550px) {
406
  body[yahoo] .hide {display: none!important;}
407
  body[yahoo] .buttonwrapper {background-color: transparent!important;}
408
  body[yahoo] .button {padding: 0px!important;}
409
  body[yahoo] .button a {background-color: #e05443; padding: 15px 15px 13px!important;}
410
  body[yahoo] .unsubscribe {display: block; margin-top: 20px; padding: 10px 50px; background: #2f3942; border-radius: 5px; text-decoration: none!important; font-weight: bold;}
411
  }
412
  /*@media only screen and (min-device-width: 601px) {
413
    .content {width: 600px !important;}
414
    .col425 {width: 425px!important;}
415
    .col380 {width: 380px!important;}
416
    }*/
417
  </style>'.
418
  '<meta http-equiv=Content-Type content="text/html; charset=utf-8">';
419
       
420
         $retstr .= '</head><body yahoo bgcolor="#fcfcfc" style="margin: 0; padding: 0; min-width: 100%!important;">';
421
         return $retstr;
422
    }
423
424
    function GetHTMLFooterPart()
425
    {
426
        $retstr ='</body></html>';
427
        return $retstr ;
428
    }
429
430
    function ComposeFormtoEmail()
431
    {
432
        $header = $this->GetHTMLHeaderPart();
433
        $formsubmission = $this->FormSubmissionToMail();
434
        $footer = $this->GetHTMLFooterPart();
435
        $message = $header."<p>$formsubmission</p><hr/>$extra_info".$footer;
0 ignored issues
show
Bug introduced by
The variable $extra_info does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
436
437
        return $message;
438
    }
439
440
    function AttachFiles()
441
    {
442
        foreach($this->fileupload_fields as $upld_field)
443
        {
444
            $field_name = $upld_field["name"];
445
            if(!$this->IsFileUploaded($field_name))
446
            {
447
                continue;
448
            }
449
            
450
            $filename =basename($_FILES[$field_name]['name']);
451
            $this->mailer->AddAttachment($_FILES[$field_name]["tmp_name"],$filename);
452
        }
453
    }
454
455
    function GetFromAddress()
456
    {
457
        if(!empty($this->from_address))
458
        {
459
            return $this->from_address;
460
        }
461
462
        $host = $_SERVER['SERVER_NAME'];
463
        $from ="nobody@$host";
464
        return $from;
465
    }
466
467
    function Validate()
468
    {
469
        $ret = true;
470
        $numErr=0;
471
        //security validations
472
        if(empty($_POST[$this->GetFormIDInputName()]) ||
473
          $_POST[$this->GetFormIDInputName()] != $this->GetFormIDInputValue() )
474
        {
475
            $numErr=$numErr+1;
476
            //The proper error is not given intentionally
477
            $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
478
            register_error("Automated submission prevention: case 1 failed");
479
            $ret = false;
480
        }
481
482
        //This is a hidden input field. Humans won't fill this field.
483
        if(!empty($_POST[$this->GetSpamTrapInputName()]) )
484
        {
485
            $numErr=$numErr+1;
486
            //The proper error is not given intentionally
487
            $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
488
            register_error("Automated submission prevention: case 2 failed");
489
            $ret = false;
490
        }
491
492
        //select validations
493
        if((($_POST['reason']) =='Select...') || (($_POST['reason']) == "Choisir..."))
494
        {
495
            $numErr=$numErr+1;
496
            $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
497
            register_error(str_replace('[#]',$numErr,elgg_echo('contactform:Errreason')));
498
            $ret = false;
499
        }
500
501
        if ($_POST['reason'] == 'Autres$Other')
502
        {
503
            if (empty($_POST['subject']))
504
            {
505
                $numErr=$numErr+1;
506
                $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
507
                register_error(str_replace('[#]',$numErr,elgg_echo('contactform:Errsubject')));
508
                $ret = false;
509
            }
510
        }
511
512
        //name validations
513
        if(empty($_POST['name']))
514
        {
515
            $numErr=$numErr+1;
516
            $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
517
            //'contactform:Errname'
518
            register_error(str_replace('[#]',$numErr,elgg_echo('contactform:Errname')));
519
            $ret = false;
520
        }
521
        else
522
            if(strlen($_POST['name'])>75)
523
            {
524
                $numErr=$numErr+1;
525
                $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
526
                //'contactform:Errnamebig'
527
                register_error(str_replace('[#]',$numErr,elgg_echo('contactform:Errnamebig')));
528
                $ret = false;
529
            }
530
531
        //email validations
532
        if(empty($_POST['email']))
533
        {
534
            $numErr=$numErr+1;
535
            $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
536
            register_error(str_replace('[#]',$numErr,elgg_echo('contactform:Erremail')));
537
            $ret = false;
538
        }
539
        else
540
            if(strlen($_POST['email'])>100)
541
            {
542
                $numErr=$numErr+1;
543
                $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
544
                register_error(str_replace('[#]',$numErr,elgg_echo('contactform:Erremailbig')));
545
                $ret = false;
546
            }
547
            else
548
                if(!$this->validate_email($_POST['email']))
549
                {
550
                    $numErr=$numErr+1;
551
                    $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
552
                    //'contactform:Erremailvalid'
553
                    register_error(str_replace('[#]',$numErr,elgg_echo('contactform:Erremailvalid')));
554
                    $ret = false;
555
                }
556
557
        //department validaions
558
        if (elgg_is_active_plugin('gcconnex_theme')) {
559
            if(empty($_POST['depart']))
560
            {
561
                $numErr=$numErr+1;
562
                $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
563
                register_error(str_replace('[#]',$numErr,elgg_echo('contactform:Errdepart')));
564
                $ret = false;
565
            }
566
            else
567
                if(strlen($_POST['depart'])>255)
568
                {
569
                    $numErr=$numErr+1;
570
                    $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
571
                    register_error(str_replace('[#]',$numErr,elgg_echo('contactform:Errdepartbig')));
572
                    $ret = false;
573
                }
574
        }
575
576
        //message validaions
577
        if(empty($_POST['message']))
578
        {
579
            $numErr=$numErr+1;
580
            $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
581
            register_error(str_replace('[#]',$numErr,elgg_echo('contactform:Errmess')));
582
            $ret = false;
583
        }
584
        else
585
            if(strlen($_POST['message'])>2048)
586
            {
587
                $numErr=$numErr+1;
588
                $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
589
                register_error(str_replace('[#]',$numErr,elgg_echo('contactform:Errmessbig')));
590
                $ret = false;
591
            }
592
593
        //file upload validations
594
        if(!empty($this->fileupload_fields))
595
        {
596
            $numErr=$numErr+1;
597
            if(!$this->ValidateFileUploads($numErr))
0 ignored issues
show
Unused Code introduced by
The call to FGContactForm::ValidateFileUploads() has too many arguments starting with $numErr.

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...
598
            {
599
                $ret = false;
600
            }
601
        }
602
        return $ret;
603
    }
604
605
    function ValidateFileType($field_name,$valid_filetypes)
606
    {
607
        $ret=true;
608
        $info = pathinfo($_FILES[$field_name]['name']);
609
        $extn = $info['extension'];
610
        $extn = strtolower($extn);
611
612
        $arr_valid_filetypes= explode(',',$valid_filetypes);
613
        if(!in_array($extn,$arr_valid_filetypes))
614
        {
615
            $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
616
            register_error("Valid file types are: $valid_filetypes");
617
            $ret=false;
618
        }
619
        return $ret;
620
    }
621
622
    function ValidateFileSize($field_name,$max_size)
623
    {
624
        $size_of_uploaded_file = $_FILES[$field_name]["size"]/1024;//size in KBs
625
        if($size_of_uploaded_file > $max_size)
626
        {
627
            $this->add_error();
0 ignored issues
show
Bug introduced by
The call to add_error() misses a required argument $error.

This check looks for function calls that miss required arguments.

Loading history...
628
            register_error("The file is too big. File size should be less than $max_size KB");
629
            return false;
630
        }
631
        return true;
632
    }
633
634
    function IsFileUploaded($field_name)
635
    {
636
        if(empty($_FILES[$field_name]['name']))
637
        {
638
            return false;
639
        }
640
        if(!is_uploaded_file($_FILES[$field_name]['tmp_name']))
641
        {
642
            return false;
643
        }
644
        return true;
645
    }
646
    function ValidateFileUploads()
647
    {
648
        $ret=true;
649
        foreach($this->fileupload_fields as $upld_field)
650
        {
651
            $field_name = $upld_field["name"];
652
653
            $valid_filetypes = $upld_field["file_types"];
654
            
655
            if(!$this->IsFileUploaded($field_name))
656
            {
657
                continue;
658
            }
659
660
            if($_FILES[$field_name]["error"] != 0)
661
            {
662
                $this->add_error("Error in file upload; Error code:".$_FILES[$field_name]["error"]);
663
                $ret=false;
664
            }
665
666
            if(!empty($valid_filetypes) &&
667
             !$this->ValidateFileType($field_name,$valid_filetypes))
668
            {
669
                $ret=false;
670
            }
671
672
            if(!empty($upld_field["maxsize"]) &&
673
            $upld_field["maxsize"]>0)
674
            {
675
                if(!$this->ValidateFileSize($field_name,$upld_field["maxsize"]))
676
                {
677
                    $ret=false;
678
                }
679
            }
680
        }
681
        return $ret;
682
    }
683
684
    function StripSlashes($str)
685
    {
686
        if(get_magic_quotes_gpc())
687
        {
688
            $str = stripslashes($str);
689
        }
690
        return $str;
691
    }
692
    /*
693
    Sanitize() function removes any potential threat from the
694
    data submitted. Prevents email injections or any other hacker attempts.
695
    if $remove_nl is true, newline chracters are removed from the input.
696
    */
697
    function Sanitize($str,$remove_nl=true)
698
    {
699
        $str = $this->StripSlashes($str);
700
701
        if($remove_nl)
702
        {
703
            $injections = array('/(\n+)/i',
704
                '/(\r+)/i',
705
                '/(\t+)/i',
706
                '/(%0A+)/i',
707
                '/(%0D+)/i',
708
                '/(%08+)/i',
709
                '/(%09+)/i'
710
                );
711
            $str = preg_replace($injections,'',$str);
712
        }
713
714
        return $str;
715
    }
716
717
    /*Collects clean data from the $_POST array and keeps in internal variables.*/
718
    function CollectData()
719
    {
720
        $this->name = $this->Sanitize($_POST['name']);
721
        $this->email = $this->Sanitize($_POST['email']);
722
723
        /*newline is OK in the message.*/
724
        $this->message = $this->StripSlashes($_POST['message']);
725
    }
726
727
    function add_error($error)
728
    {
729
        array_push($this->errors,$error);
730
    }
731
    function validate_email($email)
732
    {
733
        return eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email);
734
    }
735
736
    function GetKey()
737
    {
738
        return $this->form_random_key.$_SERVER['SERVER_NAME'].$_SERVER['REMOTE_ADDR'];
739
    }
740
741
}
742
743
?>
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...