ContactPage_Controller::SendContactForm()   B
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 34
Code Lines 22

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 34
rs 8.8571
cc 2
eloc 22
nc 2
nop 2
1
<?php
2
/******************
3
 *
4
 * ContactPage
5
 *
6
 * Tutorial on www.ssbits.com/creating-a-simple-contact-form/
7
 *
8
 * Author: Aram Balakjian of aabweb.co.uk
9
 *
10
 ******************/
11
12
//Model
13
class ContactPage extends Page
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
14
{
15
	static $db = array(
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $db.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
16
17
		'ContactAddress' => 'Text',
18
		'ContactTelephoneNumber' => 'Varchar(255)',
19
		'ContactFaxNumber' => 'Varchar(255)',
20
		'ContactEmailAddress' => 'Varchar(255)',
21
		'Mailto' => 'Varchar(100)', //Email address to send submissions to
22
		'SubmitText' => 'HTMLText', //Text presented after submitting message,
23
		'Twitter' => 'Varchar(255)',
24
		'Facebook' => 'Varchar(255)'
25
	);
26
27
28
	private static $icon = 'contactage/icons/phone.png';
0 ignored issues
show
Unused Code introduced by
The property $icon is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
29
30
31
	public function SingularMap() {
32
		return !$this::has_extension('ContactPageMultipleAddressExtension');
33
	}
34
35
36
	public function Map() {
37
		if ($this::has_extension('ContactPageMultipleAddress')) {
38
			return '';
39
		} else {
40
			$map = $this->owner->RenderMap();
41
			// $map->setDelayLoadMapFunction( true );
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
42
			$map->setZoom( 10 );
43
			$map->setAdditionalCSSClasses( 'fullWidthMap' );
44
			$map->setShowInlineMapDivStyle( true );
45
			$map->setClusterer(false);
46
			//$map->addKML('http://assets.tripodtravel.co.nz/cycling/meuang-nont-to-bang-sue-loop.kml');
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
47
			return $map;
48
		}
49
	  }
50
51
52
	//CMS fields
53
	function getCMSFields() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
54
		$fields = parent::getCMSFields();
55
56
		$addresstabname = 'Root.'._t('ContactPage.ADDRESS', 'Address');
57
		$socialmediatabname = 'Root.'._t('ContactPage.SOCIAL_MEDIA', 'Social Media');
58
59
		$fields->addFieldToTab('Root.Main', new CheckboxField('ShowOnMap', 'Tick this box to show a map'));
60
61
		$fields->addFieldToTab( "Root.OnSubmission",
62
			new TextField( 'Mailto', _t( 'ContactPage.EMAIL_SUBMISSIONS_TO', 'Email submissions to' )
63
			) );
64
65
		$fields->addFieldToTab( "Root.OnSubmission",
66
			new HTMLEditorField( 'SubmitText', _t( 'ContactPage.TEXT_SHOWN_AFTER_SUBMISSION', 'Text on Submission' ) ) );
67
68
		$fields->addFieldToTab( $addresstabname, new TextAreaField( 'ContactAddress', _t( 'ContactPage.ADDRESS', 'Address' ) ) );
69
		$fields->addFieldToTab( $addresstabname, new TextField( 'ContactTelephoneNumber',
70
				_t( 'ContactPage.CONTACT_TELEPHONE_NUMBER', 'Contact Tel. Number' ) ) );
71
		$fields->addFieldToTab( $addresstabname, new TextField( 'ContactFaxNumber',
72
				_t( 'ContactPage.CONTACT_FAX_NUMBER', 'Contact Fax Number' ) ) );
73
		$fields->addFieldToTab( $addresstabname, new TextField( 'ContactEmailAddress',
74
				_t( 'ContactPage.CONTACT_EMAIL_ADDRESS_ADMIN', '(TH) Contact Email Address' ) ) );
75
76
		$fields->addFieldToTab( $socialmediatabname, new TextField( 'Facebook',
77
				_t( 'ContactPage.FACEBOOK_URL', 'Facebook URL' ) ) );
78
		$fields->addFieldToTab( $socialmediatabname, new TextField( 'Twitter',
79
				_t( 'ContactPage.TWITTER_USERNAME', 'Twitter Username' ) ) );
80
81
		$this->extend('updateContactPageForm', $fields);
82
83
		return $fields;
84
	}
85
86
87
	public function ShortenedFacebook() {
88
		$result = str_replace('https:', 'http:', $this->Facebook);
89
		$result = str_replace('http://facebook.com/', '', $result);
90
		$result = str_replace('http://www.facebook.com/', '', $result);
91
		$result = str_replace('http://facebook.com/', '', $result);
92
		return $result;
93
	}
94
95
}
96
97
98
// Controller
99
class ContactPage_Controller extends Page_Controller
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
100
{
101
	//Define our form function as allowed
102
	static $allowed_actions = array(
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $allowed_actions.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
103
		'ContactForm',
104
		'SendContactForm'
105
	);
106
107
108
	function init() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
109
		//add a javascript library for easy interaction with the server
110
		Requirements::javascript( 'mysite/javascript/jQuery.js' );
111
		if ( Director::is_ajax() ) {
112
			$this->isAjax = true;
113
		}
114
		else {
115
			$this->isAjax = false;
116
		}
117
		parent::init();
118
	}
119
120
121
	function index() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
122
		error_log( "Contact page index" );
123
		error_log( "AJAX? ".$this->isAjax );
124
125
		if ( $this->isAjax ) {
126
			return $this->renderWith( "ContactPageModal" );
127
		}
128
		else {
129
			return array();
130
		}
131
132
	}
133
134
135
	//The function which generates our form
136
	function ContactForm() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
137
		error_log( "Render form" );
138
		$name = _t( 'ContactPage.NAME', 'Name' );
139
		$email = _t( 'ContactPage.EMAIL', 'Email' );
140
		$comments = _t( 'ContactPage.COMMENTS', 'Comments' );
141
		$send = _t( 'ContactPage.SEND', 'Send' );
142
143
		// Create fields
144
		$tf = new TextField( 'Name', $name );
145
		$tf->addExtraClass( 'span11' );
146
147
		$ef = new EmailField( 'Email', $email );
148
		$ef->addExtraClass( 'span11' );
149
150
		$taf = new TextareaField( 'Comments', $comments );
151
		$taf->addExtraClass( 'span11' );
152
153
		$fields = new FieldList(
154
			$tf,
155
			$ef,
156
			$taf
157
		);
158
159
		// Create action
160
		$fa = new FormAction( 'SendContactForm', $send );
161
162
		// for bootstrap
163
		$fa->useButtonTag = true;
164
		$fa->addExtraClass( 'btn btn-primary buttonright' );
165
166
		$actions = new FieldList(
167
			$fa
168
		);
169
170
		// Create action
171
		$validator = new RequiredFields( 'Name', 'Email', 'Comments' );
172
173
		$form = new Form( $this, 'ContactForm', $fields, $actions, $validator );
174
		$form->setTemplate( 'VerticalForm' );
175
		$form->addExtraClass( 'well' );
176
177
		if(class_exists('SpamProtectorManager')) {
178
			$form->enableSpamProtection();
179
		}
180
181
		return $form;
182
	}
183
184
185
	//The function that handles our form submission
186
	function SendContactForm( $data, $form ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
187
		// saving data before sending contact form
188
		$cpm = new ContactPageMessage();
189
		$cpm->Email = $data['Email'];
0 ignored issues
show
Documentation introduced by
The property Email does not exist on object<ContactPageMessage>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
190
		$cpm->Name = $data['Name'];
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<ContactPageMessage>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
191
		$cpm->Comments = $data['Comments'];
0 ignored issues
show
Documentation introduced by
The property Comments does not exist on object<ContactPageMessage>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
192
		$cpm->write();
193
194
		//Set data
195
		$From = $data['Email'];
196
		//$From = Email::getAdminEmail();
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
197
198
		$To = $this->Mailto;
199
		$Subject = $this->SiteConfig()->Title.' - ';
200
		$Subject .= "Website Contact message";
201
		$email = new Email( $From, $To, $Subject );
202
		//set template
203
		$email->setTemplate( 'ContactEmail' );
204
		//populate template
205
		$email->populateTemplate( $data );
206
		//send mail
207
		$email->send();
208
209
		if ( $this->isAjax ) {
210
			$result = array();
211
			$result['message'] = $this->SubmitText;
212
			$result['success'] = 1;
213
			echo json_encode( $result );
214
			die;
0 ignored issues
show
Coding Style Compatibility introduced by
The method SendContactForm() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
215
		}
216
		else {
217
			Controller::redirect( Director::baseURL(). $this->URLSegment . "/?success=1" );
218
		}
219
	}
220
221
222
	//The function to test whether to display the Submit Text or not
223
	public function Success() {
0 ignored issues
show
Coding Style introduced by
Success uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
224
		return isset( $_REQUEST['success'] ) && $_REQUEST['success'] == "1";
225
	}
226
227
228
	public function HasGeo() {
229
		return (($this->Latitude !=0) && ($this->Longitude != 0));
230
	}
231
232
233
	public function HasSocialMedia() {
234
		return $this->Twitter || $this->Facebook;
235
	}
236
237
238
	public function HasTelecomAddress() {
239
		return $this->ContactEmailAddress || $this->ContactFaxNumber || $this->ContactTelephoneNumber;
240
	}
241
242
243
	public function ColumnLayout() {
244
		return 'layout2col';
245
	}
246
}
247