diff --git a/code/Catalog.php b/code/Catalog.php
index 0a6b4b1..277c5a6 100755
--- a/code/Catalog.php
+++ b/code/Catalog.php
@@ -4,7 +4,8 @@
* This class is only used if the CMS is installed, it ensures that the catalog
* URL is mapped via a page in the CMS
*/
-class Catalog extends Page {
+class Catalog extends Page
+{
public static $icon = "commerce/images/product.png";
private static $db = array(
@@ -15,11 +16,13 @@ class Catalog extends Page {
'Category' => 'ProductCategory'
);
- public function CommerceChildren() {
+ public function CommerceChildren()
+ {
return ProductCategory::get();
}
- public function getCMSFields() {
+ public function getCMSFields()
+ {
$fields = parent::getCMSFields();
$display_types = array(
@@ -30,7 +33,7 @@ public function getCMSFields() {
$fields->addFieldToTab('Root.Main', DropDownField::create('Display', 'What will this catalog display?', $display_types), 'Content');
- if($this->Display == 'Category') {
+ if ($this->Display == 'Category') {
$fields->addFieldToTab(
'Root.Main',
TreeDropdownField::create(
@@ -47,10 +50,11 @@ public function getCMSFields() {
return $fields;
}
- public function requireDefaultRecords() {
+ public function requireDefaultRecords()
+ {
parent::requireDefaultRecords();
- if(!Catalog::get()->first()) {
+ if (!Catalog::get()->first()) {
$catalog = new Catalog();
$catalog->Title = "Product Catalog";
$catalog->URLSegment = "catalog";
@@ -63,34 +67,40 @@ public function requireDefaultRecords() {
}
}
-class Catalog_Controller extends Page_Controller {
+class Catalog_Controller extends Page_Controller
+{
public static $url_slug = 'catalog';
public static $allowed_actions = array(
'AddItemForm'
);
- public function init() {
+ public function init()
+ {
parent::init();
- Requirements::themedCSS("Commerce","commerce");
+ Requirements::themedCSS("Commerce", "commerce");
}
- public function getRootCategories() {
+ public function getRootCategories()
+ {
return ProductCategory::get()->filter('ParentID', 0);
}
- public function getAllProducts() {
+ public function getAllProducts()
+ {
return Product::get();
}
- public function getCategoryChildren() {
+ public function getCategoryChildren()
+ {
$category = ProductCategory::get()->filter('ID', $this->CategoryID)->first();
- if($category && $category->Children()->exists())
+ if ($category && $category->Children()->exists()) {
return $category->Children();
- else
+ } else {
return $category->Products();
+ }
}
/*
public function index() {
@@ -100,18 +110,22 @@ public function index() {
return $this->renderWith(array('Categorys', 'Page'));
}*/
- public function isProduct() {
- if(Controller::curr()->request->Param('ProductID'))
+ public function isProduct()
+ {
+ if (Controller::curr()->request->Param('ProductID')) {
return true;
- else
+ } else {
return false;
+ }
}
- public function getCategory() {
+ public function getCategory()
+ {
return self::get_current_category();
}
- public function getProduct() {
+ public function getProduct()
+ {
return self::get_current_product();
}
@@ -119,16 +133,18 @@ public function getProduct() {
* Create an array list of either current category children or products
*
*/
- public function CategoriesOrProducts() {
+ public function CategoriesOrProducts()
+ {
$category = $this->getCategory();
$return = false;
- if($category->Children()->exists())
+ if ($category->Children()->exists()) {
$return = $category->Children();
- elseif($category->Products()->exists())
+ } elseif ($category->Products()->exists()) {
$return = $category->Products();
- elseif($category->ID == 0)
+ } elseif ($category->ID == 0) {
$return = Product::get();
+ }
return $return;
}
diff --git a/code/admin/CatalogueAdmin.php b/code/admin/CatalogueAdmin.php
index 73b275e..aabd159 100755
--- a/code/admin/CatalogueAdmin.php
+++ b/code/admin/CatalogueAdmin.php
@@ -6,7 +6,8 @@
* @package Commerce
*/
-class CatalogueAdmin extends ModelAdmin {
+class CatalogueAdmin extends ModelAdmin
+{
private static $url_segment = 'catalogue';
private static $menu_title = 'Catalogue';
@@ -24,7 +25,8 @@ class CatalogueAdmin extends ModelAdmin {
public $showImportForm = array('Product');
- public function init() {
+ public function init()
+ {
parent::init();
}
@@ -33,32 +35,38 @@ public function init() {
*
* @return array
*/
- public function getExportFields() {
- if($this->modelClass == 'Product')
+ public function getExportFields()
+ {
+ if ($this->modelClass == 'Product') {
return Product::config()->export_fields;
- else
+ } else {
return singleton($this->modelClass)->summaryFields();
+ }
}
- public function getList() {
+ public function getList()
+ {
$list = parent::getList();
// Filter categories
- if($this->modelClass == 'ProductCategory') {
+ if ($this->modelClass == 'ProductCategory') {
$parentID = $this->request->requestVar('ParentID');
- if(!$parentID) $parentID = 0;
+ if (!$parentID) {
+ $parentID = 0;
+ }
- $list = $list->filter('ParentID',$parentID);
+ $list = $list->filter('ParentID', $parentID);
}
return $list;
}
- public function getEditForm($id = null, $fields = null) {
+ public function getEditForm($id = null, $fields = null)
+ {
$form = parent::getEditForm($id, $fields);
$params = $this->request->requestVar('q');
- if($this->modelClass == 'Product') {
+ if ($this->modelClass == 'Product') {
$gridField = $form->Fields()->fieldByName('Product');
$field_config = $gridField->getConfig();
@@ -101,7 +109,7 @@ public function getEditForm($id = null, $fields = null) {
);
// Update list of items for subsite (if used)
- if(class_exists('Subsite')) {
+ if (class_exists('Subsite')) {
$list = $gridField
->getList()
->filter(array(
@@ -110,11 +118,10 @@ public function getEditForm($id = null, $fields = null) {
$gridField->setList($list);
}
-
}
// Alterations for Hiarachy on product cataloge
- if($this->modelClass == 'ProductCategory') {
+ if ($this->modelClass == 'ProductCategory') {
$fields = $form->Fields();
$gridField = $fields->fieldByName('ProductCategory');
@@ -147,7 +154,7 @@ public function getEditForm($id = null, $fields = null) {
// Setup hierarchy view
$parentID = $this->request->requestVar('ParentID');
- if($parentID){
+ if ($parentID) {
$field_config->addComponent(
GridFieldLevelup::create($parentID)
->setLinkSpec('?ParentID=%d')
@@ -166,7 +173,7 @@ public function getEditForm($id = null, $fields = null) {
'URLSegment' => 'URLSegement'
);
- if(!$params) {
+ if (!$params) {
$fields = array_merge(array('listChildrenLink' => ''), $fields);
}
@@ -175,7 +182,7 @@ public function getEditForm($id = null, $fields = null) {
$controller = $this;
$columns->setFieldFormatting(array(
- 'listChildrenLink' => function($value, &$item) use($controller) {
+ 'listChildrenLink' => function ($value, &$item) use ($controller) {
return sprintf(
'►',
$controller->Link(),
@@ -185,7 +192,7 @@ public function getEditForm($id = null, $fields = null) {
));
// Update list of items for subsite (if used)
- if(class_exists('Subsite')) {
+ if (class_exists('Subsite')) {
$list = $gridField
->getList()
->filter(array(
@@ -207,15 +214,18 @@ public function getEditForm($id = null, $fields = null) {
*
* @return string
*/
- function SectionTitle() {
- if($this->modelClass == 'ProductCategory')
+ public function SectionTitle()
+ {
+ if ($this->modelClass == 'ProductCategory') {
return 'Product Category';
- else
+ } else {
return 'Product';
+ }
}
}
-class ProductCategory_ItemRequest extends GridFieldDetailForm_ItemRequest {
+class ProductCategory_ItemRequest extends GridFieldDetailForm_ItemRequest
+{
private static $allowed_actions = array(
"ItemEditForm"
);
@@ -228,11 +238,13 @@ class ProductCategory_ItemRequest extends GridFieldDetailForm_ItemRequest {
* @param Controller $popupController
* @param string $popupFormName
*/
- public function __construct($gridField, $component, $record, $popupController, $popupFormName) {
+ public function __construct($gridField, $component, $record, $popupController, $popupFormName)
+ {
parent::__construct($gridField, $component, $record, $popupController, $popupFormName);
}
- public function Link($action = null) {
+ public function Link($action = null)
+ {
$parentParam = Controller::curr()->request->requestVar('ParentID');
$link = $parentParam ? parent::Link() . "?ParentID=$parentParam" : parent::Link();
@@ -247,17 +259,20 @@ public function Link($action = null) {
* @param boolean $unlinked
* @return ArrayData
*/
- function Breadcrumbs($unlinked = false) {
- if(!$this->popupController->hasMethod('Breadcrumbs')) return;
+ public function Breadcrumbs($unlinked = false)
+ {
+ if (!$this->popupController->hasMethod('Breadcrumbs')) {
+ return;
+ }
$items = $this->popupController->Breadcrumbs($unlinked);
- if($this->record && $this->record->ID) {
+ if ($this->record && $this->record->ID) {
$ancestors = $this->record->getAncestors();
$ancestors = new ArrayList(array_reverse($ancestors->toArray()));
$ancestors->push($this->record);
// Push each ancestor to breadcrumbs
- foreach($ancestors as $ancestor) {
+ foreach ($ancestors as $ancestor) {
$items->push(new ArrayData(array(
'Title' => $ancestor->Title,
'Link' => ($unlinked) ? false : $this->popupController->Link() . "?ParentID={$ancestor->ID}"
@@ -273,15 +288,16 @@ function Breadcrumbs($unlinked = false) {
return $items;
}
- public function ItemEditForm() {
+ public function ItemEditForm()
+ {
$form = parent::ItemEditForm();
- if($form) {
+ if ($form) {
// Update the default parent field
$parentParam = Controller::curr()->request->requestVar('ParentID');
$parent_field = $form->Fields()->dataFieldByName("ParentID");
- if($parentParam && $parent_field) {
+ if ($parentParam && $parent_field) {
$parent_field->setValue($parentParam);
}
diff --git a/code/admin/LocaliseAdmin.php b/code/admin/LocaliseAdmin.php
index b7d7c94..ebbc2dc 100755
--- a/code/admin/LocaliseAdmin.php
+++ b/code/admin/LocaliseAdmin.php
@@ -4,7 +4,8 @@
*
* @package Commerce
*/
-class LocaliseAdmin extends ModelAdmin {
+class LocaliseAdmin extends ModelAdmin
+{
private static $url_segment = 'localisation';
private static $menu_title = 'Localisation';
private static $menu_priority = -1;
@@ -14,7 +15,8 @@ class LocaliseAdmin extends ModelAdmin {
'ProductWeight',
);
- public function getEditForm($id = null, $fields = null) {
+ public function getEditForm($id = null, $fields = null)
+ {
$form = parent::getEditForm($id, $fields);
return $form;
diff --git a/code/admin/OrderAdmin.php b/code/admin/OrderAdmin.php
index 9977a30..4dfe694 100755
--- a/code/admin/OrderAdmin.php
+++ b/code/admin/OrderAdmin.php
@@ -4,7 +4,8 @@
*
* @package Commerce
*/
-class OrderAdmin extends ModelAdmin {
+class OrderAdmin extends ModelAdmin
+{
private static $url_segment = 'orders';
@@ -22,8 +23,9 @@ class OrderAdmin extends ModelAdmin {
* For an order, export all fields by default
*
*/
- public function getExportFields() {
- if($this->modelClass == 'Order') {
+ public function getExportFields()
+ {
+ if ($this->modelClass == 'Order') {
$return = array(
"OrderNumber" => "#",
"Status" => "Status",
@@ -60,21 +62,25 @@ public function getExportFields() {
$extend = $this->extend("updateExportFields", $return);
- if($extend && is_array($extend)) $return = $extend;
+ if ($extend && is_array($extend)) {
+ $return = $extend;
+ }
- return $return;
+ return $return;
}
- public function getList() {
+ public function getList()
+ {
$list = parent::getList();
return $list;
}
- public function getEditForm($id = null, $fields = null) {
+ public function getEditForm($id = null, $fields = null)
+ {
$form = parent::getEditForm($id, $fields);
- if($this->modelClass == 'Order') {
+ if ($this->modelClass == 'Order') {
$fields = $form->Fields();
$gridField = $fields->fieldByName('Order');
@@ -109,7 +115,7 @@ public function getEditForm($id = null, $fields = null) {
->addComponent($manager);
// Update list of items for subsite (if used)
- if(class_exists('Subsite')) {
+ if (class_exists('Subsite')) {
$list = $gridField
->getList()
->filter(array(
diff --git a/code/control/Catalogue_Controller.php b/code/control/Catalogue_Controller.php
index 83925cc..476f7cb 100755
--- a/code/control/Catalogue_Controller.php
+++ b/code/control/Catalogue_Controller.php
@@ -4,7 +4,8 @@
* Controller used to render pages in the catalogue (either categories or pages)
*
*/
-class Catalogue_Controller extends Commerce_Controller {
+class Catalogue_Controller extends Commerce_Controller
+{
private static $allowed_actions = array(
'image',
@@ -17,17 +18,20 @@ class Catalogue_Controller extends Commerce_Controller {
* @return ProductCategory
*
*/
- public static function get_current_category() {
+ public static function get_current_category()
+ {
$segment = Controller::curr()->request->param('URLSegment');
$return = null;
- if($segment) {
+ if ($segment) {
$return = ProductCategory::get()
- ->filter('URLSegment',$segment)
+ ->filter('URLSegment', $segment)
->first();
}
- if(!$return) $return = ProductCategory::create();
+ if (!$return) {
+ $return = ProductCategory::create();
+ }
return $return;
}
@@ -38,11 +42,12 @@ public static function get_current_category() {
* @return Product
*
*/
- public static function get_current_product() {
+ public static function get_current_product()
+ {
$segment = Controller::curr()->request->param('URLSegment');
$return = null;
- if($segment) {
+ if ($segment) {
$return = Product::get()
->filter(array(
'URLSegment'=> $segment,
@@ -50,7 +55,9 @@ public static function get_current_product() {
))->first();
}
- if(!$return) $return = Product::create();
+ if (!$return) {
+ $return = Product::create();
+ }
return $return;
}
@@ -60,12 +67,14 @@ public static function get_current_product() {
*
* @return PaginatedList
*/
- public function PaginatedProducts($limit = 10) {
- if($this->dataRecord instanceOf ProductCategory)
+ public function PaginatedProducts($limit = 10)
+ {
+ if ($this->dataRecord instanceof ProductCategory) {
return PaginatedList::create($this->SortedProducts(), $this->request)
->setPageLength($limit);
- else
+ } else {
return ArrayList::create();
+ }
}
@@ -74,12 +83,14 @@ public function PaginatedProducts($limit = 10) {
*
* @return PaginatedList
*/
- public function PaginatedAllProducts($limit = 10) {
- if($this->dataRecord instanceOf ProductCategory)
+ public function PaginatedAllProducts($limit = 10)
+ {
+ if ($this->dataRecord instanceof ProductCategory) {
return PaginatedList::create($this->AllProducts(), $this->request)
->setPageLength($limit);
- else
+ } else {
return ArrayList::create();
+ }
}
/**
@@ -88,7 +99,8 @@ public function PaginatedAllProducts($limit = 10) {
*
* @return string
*/
- public function Link($action = null) {
+ public function Link($action = null)
+ {
return $this->data()->Link(($action ? $action : true));
}
@@ -102,9 +114,10 @@ public function Link($action = null) {
* @param boolean $includeTitle Show default
-tag, set to false for custom templating
* @return string The XHTML metatags
*/
- public function MetaTags($includeTitle = true) {
+ public function MetaTags($includeTitle = true)
+ {
$tags = "";
- if($includeTitle === true || $includeTitle == 'true') {
+ if ($includeTitle === true || $includeTitle == 'true') {
$tags .= "" . $this->Title . "\n";
}
@@ -115,14 +128,14 @@ public function MetaTags($includeTitle = true) {
$charset = Config::inst()->get('ContentNegotiator', 'encoding');
$tags .= "\n";
- if($this->MetaDescription) {
+ if ($this->MetaDescription) {
$tags .= "MetaDescription) . "\" />\n";
}
- if($this->ExtraMeta) {
+ if ($this->ExtraMeta) {
$tags .= $this->ExtraMeta . "\n";
}
- if(Permission::check('CMS_ACCESS_CMSMain') && in_array('CMSPreviewable', class_implements($this)) && !$this instanceof ErrorPage) {
+ if (Permission::check('CMS_ACCESS_CMSMain') && in_array('CMSPreviewable', class_implements($this)) && !$this instanceof ErrorPage) {
$tags .= "ID}\" />\n";
$tags .= "CMSEditLink() . "\" />\n";
}
@@ -136,14 +149,16 @@ public function MetaTags($includeTitle = true) {
* The ContentController will take the URLSegment parameter from the URL and use that to look
* up a SiteTree record.
*/
- public function __construct($dataRecord = null) {
+ public function __construct($dataRecord = null)
+ {
$this->dataRecord = $dataRecord;
$this->failover = $this->dataRecord;
parent::__construct();
}
- public function index() {
- $first = ($this->dataRecord instanceOf Product) ? "Commerce_product" : "Commerce_category";
+ public function index()
+ {
+ $first = ($this->dataRecord instanceof Product) ? "Commerce_product" : "Commerce_category";
return $this->renderWith(array(
$first,
@@ -155,9 +170,11 @@ public function index() {
/**
* Action used to display an image for a product
*/
- public function image() {
- if(!($this->dataRecord instanceOf Product))
+ public function image()
+ {
+ if (!($this->dataRecord instanceof Product)) {
return $this->redirect(BASE_URL);
+ }
return $this->renderWith(array(
"Commerce_product",
@@ -172,24 +189,28 @@ public function image() {
*
* @return Image
*/
- public function ProductImage() {
+ public function ProductImage()
+ {
$images = $this->SortedImages();
$action = $this->request->param('Action');
$id = $this->request->param('ID');
$image = null;
- if($action && $action == "image" && $id)
- $image = $images->filter("ID",$id)->first();
+ if ($action && $action == "image" && $id) {
+ $image = $images->filter("ID", $id)->first();
+ }
- if(!$image)
+ if (!$image) {
$image = $images->first();
+ }
return $image;
}
- public function AddItemForm() {
- if(ShoppingCart::config()->enabled) {
+ public function AddItemForm()
+ {
+ if (ShoppingCart::config()->enabled) {
$form = AddItemToCartForm::create($this, $this->dataRecord, "AddItemForm")
->addExtraClass('forms')
->addExtraClass('forms-columnar');
@@ -197,9 +218,8 @@ public function AddItemForm() {
$this->extend("updateAddItemForm", $form);
return $form;
- } else
+ } else {
return false;
+ }
}
-
-
}
diff --git a/code/control/Checkout_Controller.php b/code/control/Checkout_Controller.php
index 4fd9a4d..110aea8 100755
--- a/code/control/Checkout_Controller.php
+++ b/code/control/Checkout_Controller.php
@@ -4,7 +4,8 @@
* Controller used to render the checkout process
*
*/
-class Checkout_Controller extends Commerce_Controller {
+class Checkout_Controller extends Commerce_Controller
+{
/**
* Name of the current controller. Mostly used in templates for
@@ -32,16 +33,19 @@ class Checkout_Controller extends Commerce_Controller {
"PostagePaymentForm"
);
- public function getClassName() {
+ public function getClassName()
+ {
return self::config()->class_name;
}
- public function init() {
+ public function init()
+ {
parent::init();
// If no shopping cart doesn't exist, redirect to base
- if(!ShoppingCart::create()->getItems()->exists())
+ if (!ShoppingCart::create()->getItems()->exists()) {
return $this->redirect(ShoppingCart::config()->url_segment);
+ }
}
/**
@@ -49,12 +53,14 @@ public function init() {
* or "checkout as guest" options.
*
*/
- public function index() {
- if(Member::currentUserID())
+ public function index()
+ {
+ if (Member::currentUserID()) {
return $this->redirect($this->Link('billing'));
+ }
$this->customise(array(
- 'Title' => _t('CommerceAccount.SignIn',"Sign in"),
+ 'Title' => _t('CommerceAccount.SignIn', "Sign in"),
"Login" => true,
'Content' => $this->renderWith("Commerce_Checkout_Login"),
'LoginForm' => $this->LoginForm()
@@ -75,15 +81,17 @@ public function index() {
*
* @return array
*/
- public function billing() {
+ public function billing()
+ {
$form = $this->BillingForm();
// Pre populate form with member info
- if(Member::currentUserID())
+ if (Member::currentUserID()) {
$form->loadDataFrom(Member::currentUser());
+ }
$this->customise(array(
- 'Title' => _t('Commerce.BillingDetails',"Billing Details"),
+ 'Title' => _t('Commerce.BillingDetails', "Billing Details"),
'Form' => $form
));
@@ -103,9 +111,10 @@ public function billing() {
*
* @var array
*/
- public function delivery() {
+ public function delivery()
+ {
$this->customise(array(
- 'Title' => _t('Commerce.DeliveryDetails',"Delivery Details"),
+ 'Title' => _t('Commerce.DeliveryDetails', "Delivery Details"),
'Form' => $this->DeliveryForm()
));
@@ -127,7 +136,8 @@ public function delivery() {
*
* @return redirect
*/
- public function usememberaddress() {
+ public function usememberaddress()
+ {
$allowed_otherids = array("billing","delivery");
$id = $this->request->param("ID");
$otherid = $this->request->param("OtherID");
@@ -137,7 +147,7 @@ public function usememberaddress() {
$action = "billing";
// If our required details are not set, return a server error
- if(
+ if (
!$address ||
!$member ||
($address && !$address->canView($member)) ||
@@ -151,7 +161,7 @@ public function usememberaddress() {
}
// Set the session data
- if($otherid == "billing") {
+ if ($otherid == "billing") {
$data["FirstName"] = $address->FirstName;
$data["Surname"] = $address->Surname;
$data["Address1"] = $address->Address1;
@@ -167,7 +177,7 @@ public function usememberaddress() {
$action = "delivery";
}
- if($otherid == "delivery") {
+ if ($otherid == "delivery") {
$data['DeliveryFirstnames'] = $address->FirstName;
$data['DeliverySurname'] = $address->Surname;
$data['DeliveryAddress1'] = $address->Address1;
@@ -191,18 +201,20 @@ public function usememberaddress() {
*
* @return array
*/
- public function finish() {
+ public function finish()
+ {
// Check the users details are set, if not, send them to the cart
$billing_data = Session::get("Commerce.BillingDetailsForm.data");
$delivery_data = Session::get("Commerce.DeliveryDetailsForm.data");
- if(!is_array($billing_data) && !is_array($delivery_data))
+ if (!is_array($billing_data) && !is_array($delivery_data)) {
return $this->redirect("index");
+ }
$form = $this->PostagePaymentForm();
$this->customise(array(
- 'Title' => _t('Commerce.PostagePayment',"Postage and Payment"),
+ 'Title' => _t('Commerce.PostagePayment', "Postage and Payment"),
'Form' => $form
));
@@ -220,7 +232,8 @@ public function finish() {
*
* @return MemberLoginForm
*/
- public function LoginForm() {
+ public function LoginForm()
+ {
$form = CommerceLoginForm::create($this, 'LoginForm');
$form->setAttribute("action", $this->Link("LoginForm"));
@@ -243,14 +256,17 @@ public function LoginForm() {
*
* @return BillingDetailsForm
*/
- public function BillingForm() {
+ public function BillingForm()
+ {
$form = BillingDetailsForm::create($this, 'BillingForm')
->addExtraClass('forms')
->addExtraClass('columnar')
->addExtraClass('row');
$data = Session::get("Commerce.BillingDetailsForm.data");
- if(is_array($data)) $form->loadDataFrom($data);
+ if (is_array($data)) {
+ $form->loadDataFrom($data);
+ }
$this->extend("updateBillingForm", $form);
@@ -262,14 +278,17 @@ public function BillingForm() {
*
* @return DeliveryDetailsForm
*/
- public function DeliveryForm() {
+ public function DeliveryForm()
+ {
$form = DeliveryDetailsForm::create($this, 'DeliveryForm')
->addExtraClass('forms')
->addExtraClass('columnar')
->addExtraClass('row');
$data = Session::get("Commerce.DeliveryDetailsForm.data");
- if(is_array($data)) $form->loadDataFrom($data);
+ if (is_array($data)) {
+ $form->loadDataFrom($data);
+ }
$this->extend("updateDeliveryForm", $form);
@@ -281,8 +300,9 @@ public function DeliveryForm() {
*
* @return PostagePaymentForm
*/
- public function PostagePaymentForm() {
- $form = PostagePaymentForm::create($this,"PostagePaymentForm")
+ public function PostagePaymentForm()
+ {
+ $form = PostagePaymentForm::create($this, "PostagePaymentForm")
->addExtraClass("forms");
$this->extend("updatePostagePaymentForm", $form);
diff --git a/code/control/CommerceURLController.php b/code/control/CommerceURLController.php
index 27ec7df..d6b5763 100755
--- a/code/control/CommerceURLController.php
+++ b/code/control/CommerceURLController.php
@@ -7,12 +7,15 @@
* @package commerce
* @subpackage control
*/
-class CommerceURLController extends Controller {
- public function init() {
+class CommerceURLController extends Controller
+{
+ public function init()
+ {
parent::init();
}
- public function handleRequest(SS_HTTPRequest $request, DataModel $model) {
+ public function handleRequest(SS_HTTPRequest $request, DataModel $model)
+ {
$this->pushCurrent();
$this->urlParams = $request->allParams();
$this->request = $request;
@@ -27,13 +30,15 @@ public function handleRequest(SS_HTTPRequest $request, DataModel $model) {
$this->extend('onAfterInit');
// First check products against URL segment
- if($product = Product::get()->filter(array('URLSegment'=>$urlsegment,'Disabled'=>0))->first()) {
+ if ($product = Product::get()->filter(array('URLSegment'=>$urlsegment, 'Disabled'=>0))->first()) {
$controller = Catalogue_Controller::create($product);
- } elseif($category = ProductCategory::get()->filter('URLSegment',$urlsegment)->first()) {
+ } elseif ($category = ProductCategory::get()->filter('URLSegment', $urlsegment)->first()) {
$controller = Catalogue_Controller::create($category);
} else {
// If CMS is installed
- if(class_exists('ModelAsController')) $controller = ModelAsController::create();
+ if (class_exists('ModelAsController')) {
+ $controller = ModelAsController::create();
+ }
}
$result = $controller->handleRequest($request, $model);
diff --git a/code/control/Commerce_Controller.php b/code/control/Commerce_Controller.php
index 505cd38..6f66fcb 100755
--- a/code/control/Commerce_Controller.php
+++ b/code/control/Commerce_Controller.php
@@ -7,7 +7,8 @@
*
* Currently this class acts pretty much as just a container for these classes.
*/
-abstract class Commerce_Controller extends Controller {
+abstract class Commerce_Controller extends Controller
+{
/**
* The URL segment that is matched from the routing rules. This MUST be set
@@ -23,20 +24,24 @@ abstract class Commerce_Controller extends Controller {
/**
* Returns the associated database record
*/
- public function data() {
+ public function data()
+ {
return $this->dataRecord;
}
- public function getDataRecord() {
+ public function getDataRecord()
+ {
return $this->data();
}
- public function setDataRecord($dataRecord) {
+ public function setDataRecord($dataRecord)
+ {
$this->dataRecord = $dataRecord;
return $this;
}
- public function Link($action = null) {
+ public function Link($action = null)
+ {
return Controller::join_links(
Director::BaseURL(),
$this->config()->url_segment,
@@ -49,9 +54,10 @@ public function Link($action = null) {
*
* At the moment this is used to set config where database access is required
*/
- public function init() {
+ public function init()
+ {
// Set the default currency symbol
- if($siteconfig = SiteConfig::current_site_config()) {
+ if ($siteconfig = SiteConfig::current_site_config()) {
Currency::config()->currency_symbol = $siteconfig->Currency()->HTMLNotation;
}
@@ -69,7 +75,8 @@ public function init() {
* @param $country String listing the country to search, this has to be an ISO 3166 code
* @param $zipcode String listing the zip/postage code to filter by
*/
- public function getPostageAreas($country, $zipcode) {
+ public function getPostageAreas($country, $zipcode)
+ {
$return = new ArrayList();
$countries = new ArrayList();
$cart = ShoppingCart::create();
@@ -79,25 +86,28 @@ public function getPostageAreas($country, $zipcode) {
->PostageAreas();
// First find all area's for this country directly (no wildcards)
- foreach($all_rates as $rate) {
- if(!(strpos(strtolower($rate->Country), strtolower($country)) === false))
+ foreach ($all_rates as $rate) {
+ if (!(strpos(strtolower($rate->Country), strtolower($country)) === false)) {
$countries->add($rate);
+ }
}
// If we have no countries in the list specificly, then check for wildcards
- if(!$countries->exists()) {
- foreach($all_rates as $rate) {
- if($rate->Country == "*") $countries->add($rate);
+ if (!$countries->exists()) {
+ foreach ($all_rates as $rate) {
+ if ($rate->Country == "*") {
+ $countries->add($rate);
+ }
}
}
// If we have a list of countries check them for post codes
- foreach($countries as $rate) {
- $rate_codes = explode(",",$rate->ZipCode);
+ foreach ($countries as $rate) {
+ $rate_codes = explode(",", $rate->ZipCode);
- foreach($rate_codes as $rate_to_check) {
+ foreach ($rate_codes as $rate_to_check) {
$curr_length = strlen($rate_to_check);
- if(strtolower(substr($zipcode, 0, $curr_length)) == strtolower($rate_to_check)) {
+ if (strtolower(substr($zipcode, 0, $curr_length)) == strtolower($rate_to_check)) {
$return->add($rate);
}
}
@@ -105,57 +115,68 @@ public function getPostageAreas($country, $zipcode) {
// If we still don't have anything to return, check or list of countries
// for a wildcard
- if(!$return->exists()) {
- foreach($countries as $rate) {
- if($rate->ZipCode == "*") $return->add($rate);
+ if (!$return->exists()) {
+ foreach ($countries as $rate) {
+ if ($rate->ZipCode == "*") {
+ $return->add($rate);
+ }
}
}
// Now we have a list of locations, start checking for additional
// rules an remove if not applicable.
- $total_cost = str_replace(",","",$cart->SubTotalCost());
- $total_weight = str_replace(",","",$cart->TotalWeight());
- $total_items = str_replace(",","",$cart->TotalItems());
+ $total_cost = str_replace(",", "", $cart->SubTotalCost());
+ $total_weight = str_replace(",", "", $cart->TotalWeight());
+ $total_items = str_replace(",", "", $cart->TotalItems());
$max_cost = 0;
$max_weight = 0;
$max_items = 0;
// First loop through and find items that are invalid
- foreach($return as $location) {
- if($location->Calculation == "Price" && ((float)$total_cost < $location->Unit))
+ foreach ($return as $location) {
+ if ($location->Calculation == "Price" && ((float)$total_cost < $location->Unit)) {
$return->remove($location);
+ }
- if($location->Calculation == "Weight" && ((float)$total_weight < $location->Unit))
+ if ($location->Calculation == "Weight" && ((float)$total_weight < $location->Unit)) {
$return->remove($location);
+ }
- if($location->Calculation == "Items" && ((float)$total_items < $location->Unit))
+ if ($location->Calculation == "Items" && ((float)$total_items < $location->Unit)) {
$return->remove($location);
+ }
}
// Now find max values based on units
- foreach($return as $location) {
- if($location->Calculation == "Price" && ($location->Unit > $max_cost))
+ foreach ($return as $location) {
+ if ($location->Calculation == "Price" && ($location->Unit > $max_cost)) {
$max_cost = $location->Unit;
+ }
- if($location->Calculation == "Weight" && ($location->Unit > $max_weight))
+ if ($location->Calculation == "Weight" && ($location->Unit > $max_weight)) {
$max_weight = $location->Unit;
+ }
- if($location->Calculation == "Items" && ($location->Unit > $max_items))
+ if ($location->Calculation == "Items" && ($location->Unit > $max_items)) {
$max_items = $location->Unit;
+ }
}
// Now loop through again and calculate which brackets each
// Location fits in
- foreach($return as $location) {
- if($location->Calculation == "Price" && ($location->Unit < $max_cost))
+ foreach ($return as $location) {
+ if ($location->Calculation == "Price" && ($location->Unit < $max_cost)) {
$return->remove($location);
+ }
- if($location->Calculation == "Weight" && ($location->Unit < $max_weight))
+ if ($location->Calculation == "Weight" && ($location->Unit < $max_weight)) {
$return->remove($location);
+ }
- if($location->Calculation == "Items" && ($location->Unit < $max_items))
+ if ($location->Calculation == "Items" && ($location->Unit < $max_items)) {
$return->remove($location);
+ }
}
return $return;
@@ -170,13 +191,14 @@ public function getPostageAreas($country, $zipcode) {
* @param SearchForm $form The form instance that was submitted
* @param SS_HTTPRequest $request Request generated for this action
*/
- public function results($data, $form, $request) {
+ public function results($data, $form, $request)
+ {
$results = $form->getResults();
// For the moment this will also need to be added to your
// Page_Controller::results() method (until a more elegant solution can
// be found
- if(class_exists("Product")) {
+ if (class_exists("Product")) {
$products = Product::get()->filterAny(array(
"Title:PartialMatch" => $data["Search"],
"SKU" => $data["Search"],
@@ -186,7 +208,7 @@ public function results($data, $form, $request) {
$results->merge($products);
}
- $results = $results->sort("Title","ASC");
+ $results = $results->sort("Title", "ASC");
$data = array(
'Results' => $results,
diff --git a/code/control/Payment_Controller.php b/code/control/Payment_Controller.php
index 04231bb..fc7ed6b 100755
--- a/code/control/Payment_Controller.php
+++ b/code/control/Payment_Controller.php
@@ -7,7 +7,8 @@
* @package commerce
*/
-class Payment_Controller extends Commerce_Controller {
+class Payment_Controller extends Commerce_Controller
+{
/**
* @var string
@@ -23,11 +24,13 @@ class Payment_Controller extends Commerce_Controller {
protected $payment_handler;
- public function getPaymentHandler() {
+ public function getPaymentHandler()
+ {
return $this->payment_handler;
}
- public function setPaymentHandler($handler) {
+ public function setPaymentHandler($handler)
+ {
$this->payment_handler = $handler;
return $this;
}
@@ -35,11 +38,13 @@ public function setPaymentHandler($handler) {
protected $payment_method;
- public function getPaymentMethod() {
+ public function getPaymentMethod()
+ {
return $this->payment_method;
}
- public function setPaymentMethod($method) {
+ public function setPaymentMethod($method)
+ {
$this->payment_method = $method;
return $this;
}
@@ -49,26 +54,31 @@ public function setPaymentMethod($method) {
*
* @return Order
*/
- public function getOrder() {
+ public function getOrder()
+ {
return Session::get('Commerce.Order');
}
- public function getClassName() {
- return str_replace("_Controller","",get_class($this));
+ public function getClassName()
+ {
+ return str_replace("_Controller", "", get_class($this));
}
- public function init() {
+ public function init()
+ {
parent::init();
// Check if payment slug is set and that corresponds to a payment
- if($this->request->param('ID') && $method = CommercePaymentMethod::get()->byID($this->request->param('ID')))
+ if ($this->request->param('ID') && $method = CommercePaymentMethod::get()->byID($this->request->param('ID'))) {
$this->payment_method = $method;
+ }
// Then check session
- elseif($method = CommercePaymentMethod::get()->byID(Session::get('Commerce.PaymentMethodID')))
+ elseif ($method = CommercePaymentMethod::get()->byID(Session::get('Commerce.PaymentMethodID'))) {
$this->payment_method = $method;
+ }
// Setup payment handler
- if($this->payment_method && $this->payment_method !== null) {
+ if ($this->payment_method && $this->payment_method !== null) {
$handler = $this->payment_method->ClassName;
$handler = $handler::$handler;
@@ -93,20 +103,23 @@ public function init() {
* in the "Postage and Payment" form.
*
*/
- public function index() {
+ public function index()
+ {
$cart = ShoppingCart::get();
// If shopping cart doesn't exist, redirect to base
- if(!$cart->getItems()->exists() || $this->getPaymentHandler() === null)
+ if (!$cart->getItems()->exists() || $this->getPaymentHandler() === null) {
return $this->redirect(Director::BaseURL());
+ }
// Get billing and delivery details and merge into an array
$billing_data = Session::get("Commerce.BillingDetailsForm.data");
$delivery_data = Session::get("Commerce.DeliveryDetailsForm.data");
$postage = PostageArea::get()->byID(Session::get('Commerce.PostageID'));
- if(!$postage || !$billing_data || !$delivery_data)
+ if (!$postage || !$billing_data || !$delivery_data) {
return $this->redirect(Checkout_Controller::create()->Link());
+ }
// Work out if an order prefix string has been set in siteconfig
$config = SiteConfig::current_site_config();
@@ -131,13 +144,15 @@ public function index() {
$order->update($data);
// If user logged in, track it against an order
- if(Member::currentUserID()) $order->CustomerID = Member::currentUserID();
+ if (Member::currentUserID()) {
+ $order->CustomerID = Member::currentUserID();
+ }
// Write so we can setup our foreign keys
$order->write();
// Loop through each session cart item and add that item to the order
- foreach($cart->getItems() as $cart_item) {
+ foreach ($cart->getItems() as $cart_item) {
$order_item = new OrderItem();
$order_item->Title = $cart_item->Title;
$order_item->SKU = $cart_item->SKU;
@@ -174,9 +189,10 @@ public function index() {
* either post data or get data and then sends it to the relevent payment
* method for processing.
*/
- public function callback() {
+ public function callback()
+ {
// If post data exists, process. Otherwise provide error
- if($this->payment_handler !== null) {
+ if ($this->payment_handler !== null) {
$callback = $this->payment_handler->callback();
} else {
// Redirect to error page
@@ -196,18 +212,20 @@ public function callback() {
*
* @return String
*/
- public function complete() {
+ public function complete()
+ {
$site = SiteConfig::current_site_config();
$order = $this->getOrder();
$id = $this->request->param('ID');
- if($id == "error")
+ if ($id == "error") {
$return = $this->error_data();
- else
+ } else {
$return = $this->success_data();
+ }
- if($order) {
+ if ($order) {
$return['CommerceOrderSuccess'] = true;
$return['Order'] = $order;
} else {
@@ -216,7 +234,7 @@ public function complete() {
}
// Clear our session data
- if(isset($_SESSION)) {
+ if (isset($_SESSION)) {
ShoppingCart::get()->clear();
unset($_SESSION['Commerce.Order']);
unset($_SESSION['Commerce.PostageID']);
@@ -236,11 +254,12 @@ public function complete() {
*
* @return array
*/
- public function success_data() {
+ public function success_data()
+ {
$site = SiteConfig::current_site_config();
return array(
- 'Title' => _t('Commerce.OrderComplete','Order Complete'),
+ 'Title' => _t('Commerce.OrderComplete', 'Order Complete'),
'Content' => ($site->SuccessCopy) ? nl2br(Convert::raw2xml($site->SuccessCopy), true) : false
);
}
@@ -250,11 +269,12 @@ public function success_data() {
*
* @return array
*/
- public function error_data() {
+ public function error_data()
+ {
$site = SiteConfig::current_site_config();
return array(
- 'Title' => _t('Commerce.OrderFailed','Order Failed'),
+ 'Title' => _t('Commerce.OrderFailed', 'Order Failed'),
'Content' => ($site->FailerCopy) ? nl2br(Convert::raw2xml($site->FailerCopy), true) : false
);
}
diff --git a/code/control/ShoppingCart.php b/code/control/ShoppingCart.php
index a534ff5..b02b278 100755
--- a/code/control/ShoppingCart.php
+++ b/code/control/ShoppingCart.php
@@ -8,7 +8,8 @@
* @author morven
* @package commerce
*/
-class ShoppingCart extends Commerce_Controller {
+class ShoppingCart extends Commerce_Controller
+{
/**
* URL Used to access this controller
@@ -82,31 +83,38 @@ class ShoppingCart extends Commerce_Controller {
* Getters and setters
*
*/
- public function getClassName() {
+ public function getClassName()
+ {
return self::config()->class_name;
}
- public function getTitle() {
+ public function getTitle()
+ {
return ($this->config()->title) ? $this->config()->title : _t("Commerce.CartName", "Shopping Cart");
}
- public function getMetaTitle() {
+ public function getMetaTitle()
+ {
return $this->getTitle();
}
- public function getShowDiscountForm() {
+ public function getShowDiscountForm()
+ {
return $this->config()->show_discount_form;
}
- public function getItems() {
+ public function getItems()
+ {
return $this->items;
}
- public function getDiscount() {
+ public function getDiscount()
+ {
return $this->discount;
}
- public function setDiscount(Discount $discount) {
+ public function setDiscount(Discount $discount)
+ {
$this->discount = $discount;
}
@@ -118,7 +126,8 @@ public function setDiscount(Discount $discount) {
* @param $code Zip or Postal code
* @return ShoppingCart
*/
- public function setAvailablePostage($country, $code) {
+ public function setAvailablePostage($country, $code)
+ {
// Set postage data from commerce_controller and save into a session
$postage_areas = $this->getPostageAreas($country, $code);
Session::set("Commerce.AvailablePostage", $postage_areas);
@@ -131,7 +140,8 @@ public function setAvailablePostage($country, $code) {
*
* @return Boolean
*/
- public static function isEnabled() {
+ public static function isEnabled()
+ {
return self::config()->enabled;
}
@@ -141,25 +151,29 @@ public static function isEnabled() {
*
* @return ShoppingCart
*/
- public static function get() {
+ public static function get()
+ {
return ShoppingCart::create();
}
- public function __construct() {
+ public function __construct()
+ {
// If items are stored in a session, get them now
- if(Session::get('Commerce.ShoppingCart.Items'))
+ if (Session::get('Commerce.ShoppingCart.Items')) {
$this->items = unserialize(Session::get('Commerce.ShoppingCart.Items'));
- else
+ } else {
$this->items = ArrayList::create();
+ }
// If discounts stored in a session, get them, else create new list
- if(Session::get('Commerce.ShoppingCart.Discount'))
+ if (Session::get('Commerce.ShoppingCart.Discount')) {
$this->discount = unserialize(Session::get('Commerce.ShoppingCart.Discount'));
+ }
// If we don't have any discounts, a user is logged in and he has
// access to discounts through a group, add the discount here
- if(!$this->discount && Member::currentUserID()) {
+ if (!$this->discount && Member::currentUserID()) {
$member = Member::currentUser();
$this->discount = $member->getDiscount();
Session::set('Commerce.ShoppingCart.Discount', serialize($this->discount));
@@ -175,7 +189,8 @@ public function __construct() {
/**
* Default acton for the shopping cart
*/
- public function index() {
+ public function index()
+ {
$this->extend("onBeforeIndex");
return $this->renderWith(array(
@@ -192,13 +207,15 @@ public function index() {
*
* @return Redirect
*/
- public function remove() {
+ public function remove()
+ {
$key = $this->request->param('ID');
- if(!empty($key)) {
- foreach($this->items as $item) {
- if($item->Key == $key)
+ if (!empty($key)) {
+ foreach ($this->items as $item) {
+ if ($item->Key == $key) {
$this->items->remove($item);
+ }
}
$this->save();
@@ -211,7 +228,8 @@ public function remove() {
* Action that will clear shopping cart and associated sessions
*
*/
- public function emptycart() {
+ public function emptycart()
+ {
$this->extend("onBeforeEmpty");
$this->removeAll();
$this->save();
@@ -226,29 +244,32 @@ public function emptycart() {
* forms seem to provide a less than perfect user experience
*
*/
- public function usediscount() {
+ public function usediscount()
+ {
$this->extend("onBeforeUseDiscount");
$code_to_search = $this->request->param("ID");
$code = false;
- if(!$code_to_search)
+ if (!$code_to_search) {
return $this->httpError(404, "Page not found");
+ }
// First check if the discount is already added (so we don't
// query the DB if we don't have to).
- if(!$this->discount || ($this->discount && $this->discount->Code != $code_to_search)) {
+ if (!$this->discount || ($this->discount && $this->discount->Code != $code_to_search)) {
$codes = Discount::get()
->filter("Code", $code_to_search)
->exclude("Expires:LessThan", date("Y-m-d"));
- if($codes->exists()) {
+ if ($codes->exists()) {
$code = $codes->first();
$this->discount = $code;
$this->save();
}
- } elseif($this->discount && $this->discount->Code == $code_to_search)
+ } elseif ($this->discount && $this->discount->Code == $code_to_search) {
$code = $this->discount;
+ }
return $this
->customise(array(
@@ -271,7 +292,8 @@ public function usediscount() {
* - "Value" => (str)"Item Value"
* - "ModifyPrice" => (float)"Modification to price"
*/
- public function add(Product $add_item, $quantity = 1, $customise = array()) {
+ public function add(Product $add_item, $quantity = 1, $customise = array())
+ {
$added = false;
$config = SiteConfig::current_site_config();
@@ -280,23 +302,23 @@ public function add(Product $add_item, $quantity = 1, $customise = array()) {
// Check if the add call is trying to add an item already in the cart,
// if so update the current quantity
- foreach($this->items as $item) {
+ foreach ($this->items as $item) {
// If an instance of this is already in the shopping basket, increase
- if($item->Key == $product_key) {
+ if ($item->Key == $product_key) {
$this->update($item->Key, ($item->Quantity + $quantity));
$added = true;
}
}
// If no update was sucessfull, update records
- if(!$added) {
+ if (!$added) {
$custom_data = new ArrayList();
$price = $add_item->Price;
(float)$tax_rate = $config->TaxRate;
- foreach($customise as $custom_item) {
+ foreach ($customise as $custom_item) {
$custom_data->add(new ArrayData(array(
- 'Title' => ucwords(str_replace(array('-','_'), ' ', $custom_item["Title"])),
+ 'Title' => ucwords(str_replace(array('-', '_'), ' ', $custom_item["Title"])),
'Value' => $custom_item["Value"],
'ModifyPrice' => $custom_item['ModifyPrice']
)));
@@ -306,10 +328,12 @@ public function add(Product $add_item, $quantity = 1, $customise = array()) {
}
// Now, caclulate tax based on the new modified price and tax rate
- if($tax_rate > 0)
- (float)$tax = ($price / 100) * $tax_rate; // Get our tax amount from the price
- else
+ if ($tax_rate > 0) {
+ (float)$tax = ($price / 100) * $tax_rate;
+ } // Get our tax amount from the price
+ else {
(float)$tax = 0;
+ }
$item_to_add = ArrayData::create(array(
'Key' => $product_key,
@@ -318,7 +342,7 @@ public function add(Product $add_item, $quantity = 1, $customise = array()) {
'SKU' => $add_item->SKU,
'Description' => $add_item->Description,
'Weight' => $add_item->Weight,
- 'Price' => number_format($price,2),
+ 'Price' => number_format($price, 2),
'Tax' => number_format($tax, 2),
'Customised' => $custom_data,
'Image' => $add_item->Images()->first(),
@@ -339,8 +363,9 @@ public function add(Product $add_item, $quantity = 1, $customise = array()) {
* @param Item
* @param Quantity
*/
- public function update($item_key, $quantity) {
- foreach($this->items as $item) {
+ public function update($item_key, $quantity)
+ {
+ foreach ($this->items as $item) {
if ($item->Key === $item_key) {
$this->extend("onBeforeUpdate", $item);
@@ -354,14 +379,15 @@ public function update($item_key, $quantity) {
$this->save();
return false;
- }
+ }
/**
* Empty the shopping cart object of all items.
*
*/
- public function removeAll() {
- foreach($this->items as $item) {
+ public function removeAll()
+ {
+ foreach ($this->items as $item) {
$this->items->remove($item);
}
}
@@ -370,7 +396,8 @@ public function removeAll() {
* Save the current products list and postage to a session.
*
*/
- public function save() {
+ public function save()
+ {
Session::clear("Commerce.PostageID");
// Save cart items
@@ -386,7 +413,7 @@ public function save() {
);
// Update available postage
- if($data = Session::get("Form.Form_PostageForm.data")) {
+ if ($data = Session::get("Form.Form_PostageForm.data")) {
$country = $data["Country"];
$code = $data["ZipCode"];
$this->setAvailablePostage($country, $code);
@@ -398,7 +425,8 @@ public function save() {
* empty, as that retains the session.
*
*/
- public function clear() {
+ public function clear()
+ {
Session::clear('Commerce.ShoppingCart.Items');
Session::clear('Commerce.ShoppingCart.Discount');
Session::clear("Commerce.PostageID");
@@ -409,10 +437,11 @@ public function clear() {
*
* @return Float
*/
- public function TotalWeight() {
+ public function TotalWeight()
+ {
$total = 0;
- foreach($this->items as $item) {
+ foreach ($this->items as $item) {
$total = $total + ($item->Weight * $item->Quantity);
}
@@ -424,10 +453,11 @@ public function TotalWeight() {
*
* @return Int
*/
- public function TotalItems() {
+ public function TotalItems()
+ {
$total = 0;
- foreach($this->items as $item) {
+ foreach ($this->items as $item) {
$total = $total + $item->Quantity;
}
@@ -439,27 +469,30 @@ public function TotalItems() {
*
* @return Float
*/
- public function SubTotalCost() {
+ public function SubTotalCost()
+ {
$total = 0;
- foreach($this->items as $item) {
+ foreach ($this->items as $item) {
$total = $total + ($item->Quantity * $item->Price);
}
- return number_format($total,2);
+ return number_format($total, 2);
}
/**
* Get the cost of postage
*
*/
- public function PostageCost() {
- if($postage = PostageArea::get()->byID(Session::get("Commerce.PostageID")))
+ public function PostageCost()
+ {
+ if ($postage = PostageArea::get()->byID(Session::get("Commerce.PostageID"))) {
$cost = $postage->Cost;
- else
+ } else {
$cost = 0;
+ }
- return number_format($cost,2);
+ return number_format($cost, 2);
}
/**
@@ -467,39 +500,46 @@ public function PostageCost() {
*
* @return Float
*/
- public function DiscountAmount() {
+ public function DiscountAmount()
+ {
$total = 0;
$subtotal = 0;
$discount = $this->discount;
- if($discount) {
+ if ($discount) {
// Are we using a whitelist
$whitelist = $discount->WhiteList()->exists();
// Now get the total of any allowed items
- foreach($this->items as $item) {
+ foreach ($this->items as $item) {
$allow = false;
// If item is in our whitelist, then allow discount
- if($whitelist && $discount->WhiteList()->filter("ID", $item->ProductID)->first())
+ if ($whitelist && $discount->WhiteList()->filter("ID", $item->ProductID)->first()) {
$allow = true;
+ }
// If item is NOT in our blacklist, all adding discount
- if(!$whitelist && !$discount->BlackList()->filter("ID", $item->ProductID)->first())
+ if (!$whitelist && !$discount->BlackList()->filter("ID", $item->ProductID)->first()) {
$allow = true;
+ }
- if($allow) $subtotal = $subtotal + ($item->Quantity * $item->Price);
+ if ($allow) {
+ $subtotal = $subtotal + ($item->Quantity * $item->Price);
+ }
}
// If subtotal amount it greater than discount, use discount
- if($subtotal && $discount->Type == "Fixed")
+ if ($subtotal && $discount->Type == "Fixed") {
$total = ($subtotal > $discount->Amount) ? $discount->Amount : $subtotal;
+ }
// Else, calculate a percentage
- elseif($subtotal && $discount->Type == "Percentage" && $discount->Amount)
+ elseif ($subtotal && $discount->Type == "Percentage" && $discount->Amount) {
$total = (($discount->Amount / 100) * $subtotal);
+ }
}
- return number_format($total,2);
+ return number_format($total, 2);
}
/**
@@ -508,17 +548,18 @@ public function DiscountAmount() {
*
* @return Float
*/
- public function TaxCost() {
+ public function TaxCost()
+ {
// Add any tax that is needed for postage
$config = SiteConfig::current_site_config();
$total = 0;
- if($config->TaxRate > 0) {
+ if ($config->TaxRate > 0) {
$total = ($this->SubTotalCost() + $this->PostageCost()) - $this->DiscountAmount();
$total = ($total > 0) ? ((float)$total / 100) * $config->TaxRate : 0;
}
- return number_format($total,2);
+ return number_format($total, 2);
}
/**
@@ -527,18 +568,19 @@ public function TaxCost() {
*
* @return Float
*/
- public function TotalCost() {
- $total = str_replace(",","",$this->SubTotalCost());
- $discount = str_replace(",","",$this->DiscountAmount());
- $postage = str_replace(",","",$this->PostageCost());
- $tax = str_replace(",","",$this->TaxCost());
+ public function TotalCost()
+ {
+ $total = str_replace(",", "", $this->SubTotalCost());
+ $discount = str_replace(",", "", $this->DiscountAmount());
+ $postage = str_replace(",", "", $this->PostageCost());
+ $tax = str_replace(",", "", $this->TaxCost());
// If discount is less than 0, then set to 0
$total_with_discount = (((float)$total - (float)$discount) < 0) ? 0 : ((float)$total - (float)$discount);
$total = $total_with_discount + (float)$postage + (float)$tax;
- return number_format($total,2);
+ return number_format($total, 2);
}
@@ -548,11 +590,12 @@ public function TotalCost() {
*
* @return Form
*/
- public function CartForm() {
+ public function CartForm()
+ {
$fields = new FieldList();
$actions = new FieldList(
- FormAction::create('doUpdate', _t('Commerce.CartUpdate','Update Cart'))
+ FormAction::create('doUpdate', _t('Commerce.CartUpdate', 'Update Cart'))
->addExtraClass('btn')
->addExtraClass('btn-blue')
);
@@ -572,7 +615,8 @@ public function CartForm() {
*
* @return Form
*/
- public function DiscountForm() {
+ public function DiscountForm()
+ {
$fields = new FieldList(
TextField::create(
"DiscountCode",
@@ -584,7 +628,7 @@ public function DiscountForm() {
);
$actions = new FieldList(
- FormAction::create('doAddDiscount', _t('Commerce.Add','Add'))
+ FormAction::create('doAddDiscount', _t('Commerce.Add', 'Add'))
->addExtraClass('btn')
->addExtraClass('btn-blue')
);
@@ -603,26 +647,27 @@ public function DiscountForm() {
*
* @return Form
*/
- public function PostageForm() {
+ public function PostageForm()
+ {
$available_postage = Session::get("Commerce.AvailablePostage");
// Setup default postage fields
$country_select = CompositeField::create(
- CountryDropdownField::create('Country',_t('Commerce.Country','Country'))
- ->setAttribute("class",'countrydropdown dropdown btn'),
- TextField::create("ZipCode",_t('Commerce.ZipCode',"Zip/Postal Code"))
+ CountryDropdownField::create('Country', _t('Commerce.Country', 'Country'))
+ ->setAttribute("class", 'countrydropdown dropdown btn'),
+ TextField::create("ZipCode", _t('Commerce.ZipCode', "Zip/Postal Code"))
)->addExtraClass("size1of2")
->addExtraClass("unit")
->addExtraClass("unit-50");
// If we have stipulated a search, then see if we have any results
// otherwise load empty fieldsets
- if($available_postage) {
- $search_text = _t('Commerce.Update',"Update");
+ if ($available_postage) {
+ $search_text = _t('Commerce.Update', "Update");
// Loop through all postage areas and generate a new list
$postage_array = array();
- foreach($available_postage as $area) {
+ foreach ($available_postage as $area) {
$area_currency = new Currency("Cost");
$area_currency->setValue($area->Cost);
$postage_array[$area->ID] = $area->Title . " (" . $area_currency->Nice() . ")";
@@ -631,7 +676,7 @@ public function PostageForm() {
$postage_select = CompositeField::create(
OptionsetField::create(
"PostageID",
- _t('Commerce.SelectPostage',"Select Postage"),
+ _t('Commerce.SelectPostage', "Select Postage"),
$postage_array
)
)->addExtraClass("size1of2")
@@ -639,14 +684,14 @@ public function PostageForm() {
->addExtraClass("unit-50");
$confirm_action = CompositeField::create(
- FormAction::create("doSavePostage", _t('Commerce.Confirm',"Confirm"))
+ FormAction::create("doSavePostage", _t('Commerce.Confirm', "Confirm"))
->addExtraClass('btn')
->addExtraClass('btn-green')
)->addExtraClass("size1of2")
->addExtraClass("unit")
->addExtraClass("unit-50");
} else {
- $search_text = _t('Commerce.Search',"Search");
+ $search_text = _t('Commerce.Search', "Search");
$postage_select = CompositeField::create()
->addExtraClass("size1of2")
->addExtraClass("unit")
@@ -668,13 +713,13 @@ public function PostageForm() {
// Setup fields and actions
$fields = new FieldList(
- CompositeField::create($country_select,$postage_select)
+ CompositeField::create($country_select, $postage_select)
->addExtraClass("line")
->addExtraClass("units-row-end")
);
$actions = new FieldList(
- CompositeField::create($search_action,$confirm_action)
+ CompositeField::create($search_action, $confirm_action)
->addExtraClass("line")
->addExtraClass("units-row-end")
);
@@ -690,12 +735,16 @@ public function PostageForm() {
// Check if the form has been re-posted and load data
$data = Session::get("Form.{$form->FormName()}.data");
- if(is_array($data)) $form->loadDataFrom($data);
+ if (is_array($data)) {
+ $form->loadDataFrom($data);
+ }
// Check if the postage area has been set, if so, Set Postage ID
$data = array();
$data["PostageID"] = Session::get("Commerce.PostageID");
- if(is_array($data)) $form->loadDataFrom($data);
+ if (is_array($data)) {
+ $form->loadDataFrom($data);
+ }
// Extension call
$this->extend("updatePostageForm", $form);
@@ -709,16 +758,18 @@ public function PostageForm() {
* @param type $data
* @param type $form
*/
- public function doUpdate($data, $form) {
- foreach($this->items as $cart_item) {
- foreach($data as $key => $value) {
+ public function doUpdate($data, $form)
+ {
+ foreach ($this->items as $cart_item) {
+ foreach ($data as $key => $value) {
$sliced_key = explode("_", $key);
- if($sliced_key[0] == "Quantity") {
- if(isset($cart_item) && ($cart_item->Key == $sliced_key[1])) {
- if($value > 0) {
+ if ($sliced_key[0] == "Quantity") {
+ if (isset($cart_item) && ($cart_item->Key == $sliced_key[1])) {
+ if ($value > 0) {
$this->update($cart_item->Key, $value);
- } else
+ } else {
$this->remove($cart_item->Key);
+ }
}
}
}
@@ -735,18 +786,21 @@ public function doUpdate($data, $form) {
* @param type $data
* @param type $form
*/
- public function doAddDiscount($data, $form) {
+ public function doAddDiscount($data, $form)
+ {
$code_to_search = $data['DiscountCode'];
// First check if the discount is already added (so we don't
// query the DB if we don't have to).
- if(!$this->discount || ($this->discount && $this->discount->Code != $code_to_search)) {
+ if (!$this->discount || ($this->discount && $this->discount->Code != $code_to_search)) {
$code = Discount::get()
->filter("Code", $code_to_search)
->exclude("Expires:LessThan", date("Y-m-d"))
->first();
- if($code) $this->discount = $code;
+ if ($code) {
+ $this->discount = $code;
+ }
}
$this->save();
@@ -760,7 +814,8 @@ public function doAddDiscount($data, $form) {
* @param $data
* @param $form
*/
- public function doGetPostage($data, $form) {
+ public function doGetPostage($data, $form)
+ {
$country = $data["Country"];
$code = $data["ZipCode"];
@@ -769,7 +824,7 @@ public function doGetPostage($data, $form) {
// Set the form pre-populate data before redirecting
Session::set("Form.{$form->FormName()}.data", $data);
- $url = Controller::join_links($this->Link(),"#{$form->FormName()}");
+ $url = Controller::join_links($this->Link(), "#{$form->FormName()}");
return $this->redirect($url);
}
@@ -780,10 +835,11 @@ public function doGetPostage($data, $form) {
* @param $data
* @param $form
*/
- public function doSavePostage($data, $form) {
+ public function doSavePostage($data, $form)
+ {
Session::set("Commerce.PostageID", $data["PostageID"]);
- $url = Controller::join_links($this->Link(),"#{$form->FormName()}");
+ $url = Controller::join_links($this->Link(), "#{$form->FormName()}");
return $this->redirect($url);
}
diff --git a/code/control/payment/CommercePaymentHandler.php b/code/control/payment/CommercePaymentHandler.php
index 77e52b7..ddb3bbd 100755
--- a/code/control/payment/CommercePaymentHandler.php
+++ b/code/control/payment/CommercePaymentHandler.php
@@ -5,7 +5,8 @@
* particular payment class
*
*/
-abstract class CommercePaymentHandler extends Controller {
+abstract class CommercePaymentHandler extends Controller
+{
/**
* The current payment gateway we are using
@@ -14,11 +15,13 @@ abstract class CommercePaymentHandler extends Controller {
*/
protected $payment_gateway;
- public function getPaymentGateway() {
+ public function getPaymentGateway()
+ {
return $this->payment_gateway;
}
- public function setPaymentGateway($gateway) {
+ public function setPaymentGateway($gateway)
+ {
$this->payment_gateway = $gateway;
return $this;
}
@@ -30,16 +33,19 @@ public function setPaymentGateway($gateway) {
*/
protected $order;
- public function getOrder() {
+ public function getOrder()
+ {
return $this->order;
}
- public function setOrder($order) {
+ public function setOrder($order)
+ {
$this->order = $order;
return $this;
}
- public function getPaymentInfo() {
+ public function getPaymentInfo()
+ {
return $this->payment_gateway->PaymentInfo;
}
diff --git a/code/control/payment/PayPalHandler.php b/code/control/payment/PayPalHandler.php
index f108dfc..f865db6 100644
--- a/code/control/payment/PayPalHandler.php
+++ b/code/control/payment/PayPalHandler.php
@@ -1,16 +1,19 @@
order;
// Setup the paypal gateway URL
- if(Director::isDev())
+ if (Director::isDev()) {
$gateway_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
- else
+ } else {
$gateway_url = "https://www.paypal.com/cgi-bin/webscr";
+ }
$callback_url = Controller::join_links(
Director::absoluteBaseURL(),
@@ -71,7 +74,7 @@ public function index() {
$i = 1;
- foreach($order->Items() as $item) {
+ foreach ($order->Items() as $item) {
$fields->add(HiddenField::create('item_name_' . $i, null, $item->Title));
$fields->add(HiddenField::create('amount_' . $i, null, number_format(($item->Price + $item->Tax), 2)));
$fields->add(HiddenField::create('quantity_' . $i, null, $item->Quantity));
@@ -85,22 +88,22 @@ public function index() {
$fields->add(HiddenField::create('quantity_' . $i, null, "1"));
$actions = FieldList::create(
- LiteralField::create('BackButton','' . _t('Commerce.Back','Back') . ''),
- FormAction::create('Submit', _t('Commerce.ConfirmPay','Confirm and Pay'))
+ LiteralField::create('BackButton', '' . _t('Commerce.Back', 'Back') . ''),
+ FormAction::create('Submit', _t('Commerce.ConfirmPay', 'Confirm and Pay'))
->addExtraClass('btn')
->addExtraClass('btn-green')
);
- $form = Form::create($this,'Form',$fields,$actions)
+ $form = Form::create($this, 'Form', $fields, $actions)
->addExtraClass('forms')
->setFormMethod('POST')
->setFormAction($gateway_url);
- $this->extend('updateForm',$form);
+ $this->extend('updateForm', $form);
return array(
- "Title" => _t('Commerce.CheckoutSummary',"Summary"),
- "MetaTitle" => _t('Commerce.CheckoutSummary',"Summary"),
+ "Title" => _t('Commerce.CheckoutSummary', "Summary"),
+ "MetaTitle" => _t('Commerce.CheckoutSummary', "Summary"),
"Form" => $form
);
}
@@ -108,7 +111,8 @@ public function index() {
/**
* Process the callback data from the payment provider
*/
- public function callback() {
+ public function callback()
+ {
$data = $this->request->postVars();
$success_url = Controller::join_links(
@@ -125,20 +129,21 @@ public function callback() {
);
// Check if CallBack data exists and install id matches the saved ID
- if(isset($data) && isset($data['custom']) && isset($data['payment_status'])) {
+ if (isset($data) && isset($data['custom']) && isset($data['payment_status'])) {
$order = Order::get()->filter("OrderNumber", $data['custom'])->first();
- if($order) {
+ if ($order) {
$request = 'cmd=_notify-validate';
- foreach($data as $key => $value) {
+ foreach ($data as $key => $value) {
$request .= '&' . $key . '=' . urlencode(html_entity_decode($value, ENT_QUOTES, 'UTF-8'));
}
- if(Director::isDev())
+ if (Director::isDev()) {
$paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
- else
+ } else {
$paypal_url = "https://www.paypal.com/cgi-bin/webscr";
+ }
$curl = curl_init($paypal_url);
@@ -151,12 +156,12 @@ public function callback() {
$response = curl_exec($curl);
- if (!$response)
+ if (!$response) {
return false;
+ }
- if((strcmp($response, 'VERIFIED') == 0 || strcmp($response, 'UNVERIFIED') == 0) && isset($data['payment_status'])) {
-
- switch($data['payment_status']) {
+ if ((strcmp($response, 'VERIFIED') == 0 || strcmp($response, 'UNVERIFIED') == 0) && isset($data['payment_status'])) {
+ switch ($data['payment_status']) {
case 'Canceled_Reversal':
$order->Status = "canceled";
break;
@@ -201,5 +206,4 @@ public function callback() {
return array();
}
-
}
diff --git a/code/control/payment/SagePayFormsHandler.php b/code/control/payment/SagePayFormsHandler.php
index 488bc1c..e9fd558 100755
--- a/code/control/payment/SagePayFormsHandler.php
+++ b/code/control/payment/SagePayFormsHandler.php
@@ -1,12 +1,14 @@
payment_gateway->ProtocolVersion),
+ HiddenField::create('VPSProtocol', null, $this->payment_gateway->ProtocolVersion),
HiddenField::create('TxType', null, 'PAYMENT'),
HiddenField::create('Vendor', null, $this->payment_gateway->VendorName),
HiddenField::create('Crypt', null, $this->gateway_data())
);
$actions = FieldList::create(
- LiteralField::create('BackButton','' . _t('Commerce.Back','Back') . ''),
- FormAction::create('Submit', _t('Commerce.ConfirmPay','Confirm and Pay'))
+ LiteralField::create('BackButton', '' . _t('Commerce.Back', 'Back') . ''),
+ FormAction::create('Submit', _t('Commerce.ConfirmPay', 'Confirm and Pay'))
->addExtraClass('btn')
->addExtraClass('btn-green')
);
@@ -34,11 +36,11 @@ public function index() {
->setFormMethod('POST')
->setFormAction($this->payment_gateway->GatewayURL());
- $this->extend('updateForm',$form);
+ $this->extend('updateForm', $form);
return array(
- 'Title' => _t('Commerce.CheckoutSummary',"Summary"),
- 'MetaTitle' => _t('Commerce.CheckoutSummary',"Summary"),
+ 'Title' => _t('Commerce.CheckoutSummary', "Summary"),
+ 'MetaTitle' => _t('Commerce.CheckoutSummary', "Summary"),
"Form" => $form
);
}
@@ -48,7 +50,8 @@ public function index() {
* Generate encrypted string to send to SagePay
*
*/
- private function gateway_data() {
+ private function gateway_data()
+ {
$order = $this->order;
$site = SiteConfig::current_site_config();
@@ -95,16 +98,28 @@ private function gateway_data() {
);
// Add non required elements
- if($order->Email) $post["CustomerEMail"] = $order->Email;
+ if ($order->Email) {
+ $post["CustomerEMail"] = $order->Email;
+ }
- if($this->payment_gateway->EmailRecipient) $post["VendorEMail"] = $this->payment_gateway->EmailRecipient;
+ if ($this->payment_gateway->EmailRecipient) {
+ $post["VendorEMail"] = $this->payment_gateway->EmailRecipient;
+ }
- if($order->State) $post["BillingState"] = $order->State;
- if($order->PhoneNumber) $post["BillingPhone"] = $order->PhoneNumber;
+ if ($order->State) {
+ $post["BillingState"] = $order->State;
+ }
+ if ($order->PhoneNumber) {
+ $post["BillingPhone"] = $order->PhoneNumber;
+ }
- if($order->DeliveryState) $post["DeliveryState"] = $order->DeliveryState;
- if($order->DeliveryPhone) $post["DeliveryPhone"] = $order->DeliveryPhone;
+ if ($order->DeliveryState) {
+ $post["DeliveryState"] = $order->DeliveryState;
+ }
+ if ($order->DeliveryPhone) {
+ $post["DeliveryPhone"] = $order->DeliveryPhone;
+ }
$result = "";
@@ -132,7 +147,8 @@ private function gateway_data() {
* @param thisString string to convert
* @return array of values
*/
- private function get_token($thisString) {
+ private function get_token($thisString)
+ {
// List the possible tokens
$Tokens = array(
"Status",
@@ -159,12 +175,12 @@ private function get_token($thisString) {
$resultArray = array();
// Get the next token in the sequence
- for ($i = count($Tokens)-1; $i >= 0 ; $i--){
+ for ($i = count($Tokens)-1; $i >= 0 ; $i--) {
// Find the position in the string
$start = strpos($thisString, $Tokens[$i]);
// If it's present
- if ($start !== false){
+ if ($start !== false) {
// Record position and token name
$resultArray[$i]['start'] = $start;
$resultArray[$i]['token'] = $Tokens[$i];
@@ -174,7 +190,7 @@ private function get_token($thisString) {
// Sort in order of position
sort($resultArray);
// Go through the result array, getting the token values
- for ($i = 0; $irequest->getVars();
@@ -216,10 +232,11 @@ public function callback() {
);
// Check if CallBack data exists and install id matches the saved ID
- if(isset($data) && isset($data['crypt'])) {
+ if (isset($data) && isset($data['crypt'])) {
// Clear Sagepay '@' symbol (denotes encrypted data)
- if(substr($data['crypt'],0,1) == "@")
+ if (substr($data['crypt'], 0, 1) == "@") {
$data['crypt'] = substr($data['crypt'], 1);
+ }
// Now decode the Crypt field and extract the results
$crypt_decoded = StringDecryptor::create($data['crypt'])
@@ -238,19 +255,21 @@ public function callback() {
$order_status = $values['Status'];
- if($order) {
+ if ($order) {
$order->Status = ($order_status == 'OK' || $order_status == 'AUTHENTICATED') ? 'paid' : 'failed';
$order->PaymentID = $values['VPSTxId'];
// Store all the data sent from the gateway in a json
$order->GatewayData = json_encode($values);
$order->write();
- if($order_status == 'OK' || $order_status == 'AUTHENTICATED')
+ if ($order_status == 'OK' || $order_status == 'AUTHENTICATED') {
return $controller->redirect($successs_url);
- else
+ } else {
return $controller->redirect($error_url);
- } else
+ }
+ } else {
return $controller->redirect($error_url);
+ }
}
return $controller->redirect($error_url);
diff --git a/code/control/payment/SagePayServerHandler.php b/code/control/payment/SagePayServerHandler.php
index 4227125..40c9fe2 100755
--- a/code/control/payment/SagePayServerHandler.php
+++ b/code/control/payment/SagePayServerHandler.php
@@ -1,12 +1,13 @@
order;
$site = SiteConfig::current_site_config();
@@ -76,13 +77,14 @@ public function index() {
$payload = "";
$i=0;
- foreach($payload_data as $key=>$value) {
+ foreach ($payload_data as $key=>$value) {
$payload .= $key . "=" . $value;
$i++;
- if($i < count($payload_data))
+ if ($i < count($payload_data)) {
$payload .= "&";
+ }
}
// Write our connection and check result
@@ -102,41 +104,43 @@ public function index() {
$socket = fsockopen("ssl://{$host}", $port, $errno, $errstr, 30);
- if(!$socket)
+ if (!$socket) {
return null;
+ }
- for($written = 0; $written < strlen($request); $written += $fwrite) {
+ for ($written = 0; $written < strlen($request); $written += $fwrite) {
$fwrite = fwrite($socket, substr($request, $written));
}
- while(!feof($socket))
- $response .= fgets($socket,1024);
+ while (!feof($socket)) {
+ $response .= fgets($socket, 1024);
+ }
fclose($socket);
// Ready to deal with response data
$response_data = array();
- foreach(explode("\n", $response) as $item) {
- if(!strpos($item, "=") === false) {
- $item_array = explode("=",$item, 2);
+ foreach (explode("\n", $response) as $item) {
+ if (!strpos($item, "=") === false) {
+ $item_array = explode("=", $item, 2);
$response_data[$item_array[0]] = $item_array[1];
}
}
// Check our data was recieved ok
- if(strpos($response_data['Status'],'OK') === false) {
+ if (strpos($response_data['Status'], 'OK') === false) {
$form = null;
} else {
$order->PaymentID = $response_data['VPSTxId'];
$order->write();
- Session::set('Commerce.Order',$order);
+ Session::set('Commerce.Order', $order);
// now setup our form
$actions = FieldList::create(
- LiteralField::create('BackButton','' . _t('Commerce.Back','Back') . ''),
- FormAction::create('Submit', _t('Commerce.ConfirmPay','Confirm and Pay'))
+ LiteralField::create('BackButton', '' . _t('Commerce.Back', 'Back') . ''),
+ FormAction::create('Submit', _t('Commerce.ConfirmPay', 'Confirm and Pay'))
->addExtraClass('btn')
->addExtraClass('btn-green')
);
@@ -146,12 +150,12 @@ public function index() {
->setFormMethod('POST')
->setFormAction($response_data['NextURL']);
- $this->extend('updateForm',$form);
+ $this->extend('updateForm', $form);
}
return array(
- 'Title' => _t('Commerce.CheckoutSummary',"Summary"),
- 'MetaTitle' => _t('Commerce.CheckoutSummary',"Summary"),
+ 'Title' => _t('Commerce.CheckoutSummary', "Summary"),
+ 'MetaTitle' => _t('Commerce.CheckoutSummary', "Summary"),
"Form" => $form
);
}
@@ -159,7 +163,8 @@ public function index() {
/**
* Retrieve and process order data from the request
*/
- public function callback() {
+ public function callback()
+ {
$vars = array();
$data = $this->request->postVars();
@@ -177,7 +182,7 @@ public function callback() {
);
// Check if CallBack data exists and install id matches the saved ID
- if(isset($data) && isset($data['VendorTxCode']) && isset($data['Status'])) {
+ if (isset($data) && isset($data['VendorTxCode']) && isset($data['Status'])) {
$order = Order::get()
->filter(array(
'OrderNumber' => $data['VendorTxCode'],
@@ -186,25 +191,25 @@ public function callback() {
$order_status = $data['Status'];
- if($order && trim($order->PaymentID) == trim($data['VPSTxId'])) {
+ if ($order && trim($order->PaymentID) == trim($data['VPSTxId'])) {
$order->Status = ($order_status == 'OK' || $order_status == 'AUTHENTICATED') ? 'paid' : 'failed';
// Store all the data sent from the gateway in a json
$order->GatewayData = json_encode($data);
$order->write();
- if($order_status == 'OK' || $order_status == 'AUTHENTICATED') {
+ if ($order_status == 'OK' || $order_status == 'AUTHENTICATED') {
$vars['Status'] = "OK";
- $vars['StatusDetail'] = _t('Commerce.OrderComplete',"Order Complete");
+ $vars['StatusDetail'] = _t('Commerce.OrderComplete', "Order Complete");
$vars['RedirectURL'] = $success_url;
}
} else {
$vars['Status'] = "INVALID";
- $vars['StatusDetail'] = _t('Commerce.OrderError',"An error occured, Order ID's do not match");
+ $vars['StatusDetail'] = _t('Commerce.OrderError', "An error occured, Order ID's do not match");
$vars['RedirectURL'] = $error_url;
}
} else {
$vars['Status'] = "ERROR";
- $vars['StatusDetail'] = _t('Commerce.OrderError',"An error occured, Order ID's do not match");
+ $vars['StatusDetail'] = _t('Commerce.OrderError', "An error occured, Order ID's do not match");
$vars['RedirectURL'] = $error_url;
}
diff --git a/code/control/payment/WorldPayHandler.php b/code/control/payment/WorldPayHandler.php
index 3329adf..25400d8 100755
--- a/code/control/payment/WorldPayHandler.php
+++ b/code/control/payment/WorldPayHandler.php
@@ -1,11 +1,13 @@
order;
@@ -44,33 +46,36 @@ public function index() {
HiddenField::create('email', null, $order->Email)
);
- if($this->payment_gateway->GatewayMessage)
+ if ($this->payment_gateway->GatewayMessage) {
$fields->add(HiddenField::create('desc', null, $this->payment_gateway->GatewayMessage));
+ }
- if($curr_local = str_replace("_","-",i18n::get_locale()))
+ if ($curr_local = str_replace("_", "-", i18n::get_locale())) {
$fields->add(HiddenField::create('lang', null, $curr_local));
+ }
- if(Director::isDev())
+ if (Director::isDev()) {
$fields->add(HiddenField::create('testMode', null, '100'));
+ }
$actions = FieldList::create(
- LiteralField::create('BackButton','' . _t('Commerce.Back','Back') . ''),
- FormAction::create('Submit', _t('Commerce.ConfirmPay','Confirm and Pay'))
+ LiteralField::create('BackButton', '' . _t('Commerce.Back', 'Back') . ''),
+ FormAction::create('Submit', _t('Commerce.ConfirmPay', 'Confirm and Pay'))
->addExtraClass('btn')
->addExtraClass('btn-green')
);
- $form = Form::create($this,'Form',$fields,$actions)
+ $form = Form::create($this, 'Form', $fields, $actions)
->addExtraClass('forms')
->setFormMethod('POST')
->setFormAction($this->payment_gateway->GatewayURL());
- $this->extend('updateForm',$form);
+ $this->extend('updateForm', $form);
return array(
- "Title" => _t('Commerce.CheckoutSummary',"Summary"),
- "MetaTitle" => _t('Commerce.CheckoutSummary',"Summary"),
+ "Title" => _t('Commerce.CheckoutSummary', "Summary"),
+ "MetaTitle" => _t('Commerce.CheckoutSummary', "Summary"),
"Form" => $form
);
}
@@ -78,7 +83,8 @@ public function index() {
/**
* Retrieve and process order data from the request
*/
- public function callback() {
+ public function callback()
+ {
$data = $this->request->postVars();
$success_url = Controller::join_links(
@@ -100,20 +106,20 @@ public function callback() {
);
// Check if CallBack data exists and install id matches the saved ID
- if(
+ if (
isset($data) && // Data and order are set
(isset($data['instId']) && isset($data['cartId']) && isset($data['transStatus']) && isset($data["callbackPW"])) && // check required
$this->payment_gateway->InstallID == $data['instId'] && // The current install ID matches the postback ID
$this->payment_gateway->ResponsePassword == $data["callbackPW"]
) {
$order = Order::get()
- ->filter('OrderNumber',$data['cartId'])
+ ->filter('OrderNumber', $data['cartId'])
->first();
$order_status = $data['transStatus'];
- if($order) {
- if($order_status == 'Y') {
+ if ($order) {
+ if ($order_status == 'Y') {
$order->Status = 'paid';
$vars["RedirectURL"] = $success_url;
} else {
@@ -128,5 +134,4 @@ public function callback() {
return $this->renderWith(array("Payment_WorldPay"), $vars);
}
-
}
diff --git a/code/extensions/Ext_Commerce_Controller.php b/code/extensions/Ext_Commerce_Controller.php
index 8a76e2f..304dee2 100755
--- a/code/extensions/Ext_Commerce_Controller.php
+++ b/code/extensions/Ext_Commerce_Controller.php
@@ -1,115 +1,126 @@
-Language);
-
- // Check if url is primary domain, if not, re-direct
- if($_SERVER['HTTP_HOST'] != Subsite::currentSubsite()->getPrimaryDomain())
- $this->owner->redirect(Subsite::currentSubsite()->absoluteBaseURL());
- }
-
- // Setup currency globally based on what is set in admin
- $config = SiteConfig::current_site_config();
-
- if($config->Currency()) {
- Currency::setCurrencySymbol($config->Currency()->HTMLNotation);
- }
- }
-
- /**
- * Gets a list of all ProductCategories
- *
- * @param Parent the ID of a parent cetegory
- * @return DataList
- */
- public function getCommerceCategories($ParentID = 0) {
- return ProductCategory::get()
- ->filter("ParentID",$ParentID);
- }
-
- /**
- * Get a full list of products, filtered by a category if provided.
- *
- * @param ParentCategory the ID of
- */
- public function getCommerceProducts($ParentCategory = null) {
- $products = Product::get();
-
- if(isset($ParentCategory) && is_int($ParentCategory))
- $products = $products->where("ParentID = {$ParentID}");
-
- return $products;
- }
-
- /**
- * Renders a list of all ProductCategories ready to be loaded into a template
- *
- * @return HTML
- */
- public function getCommerceCategoryNav($ParentID = 0) {
- $vars = array(
- 'ProductCategories' => $this->owner->getCommerceCategories($ParentID)
- );
-
- return $this->owner->renderWith('Commerce_CategoryNav',$vars);
- }
-
-
- /**
- * Return a URL to link to this controller
- *
- * @return string URL to cart controller
- */
- public function getCommerceCartLink(){
- return Controller::join_links(
- BASE_URL,
- ShoppingCart::config()->url_segment
- );
- }
-
-
- /**
- * Return a rendered button for the shopping cart
- *
- * @return string Rendered HTML of cart button
- */
- public function getCommerceCartButton(){
- $vars = array(
- 'Link' => $this->owner->getCommerceCartLink(),
- 'Cart' => $this->owner->getCommerceCart()
- );
-
- return $this->owner->renderWith('Commerce_CartButton',$vars);
- }
-
-
- /**
- * Return a the current shopping cart
- *
- * @return ShoppingCart
- */
- public function getCommerceCart() {
- return ShoppingCart::create();
- }
-
- /**
- * Checks to see if the shopping cart functionality is enabled
- *
- * @return Boolean
- */
- public function getCommerceCartEnabled() {
- return ShoppingCart::config()->enabled;
- }
-}
+Language);
+
+ // Check if url is primary domain, if not, re-direct
+ if ($_SERVER['HTTP_HOST'] != Subsite::currentSubsite()->getPrimaryDomain()) {
+ $this->owner->redirect(Subsite::currentSubsite()->absoluteBaseURL());
+ }
+ }
+
+ // Setup currency globally based on what is set in admin
+ $config = SiteConfig::current_site_config();
+
+ if ($config->Currency()) {
+ Currency::setCurrencySymbol($config->Currency()->HTMLNotation);
+ }
+ }
+
+ /**
+ * Gets a list of all ProductCategories
+ *
+ * @param Parent the ID of a parent cetegory
+ * @return DataList
+ */
+ public function getCommerceCategories($ParentID = 0)
+ {
+ return ProductCategory::get()
+ ->filter("ParentID", $ParentID);
+ }
+
+ /**
+ * Get a full list of products, filtered by a category if provided.
+ *
+ * @param ParentCategory the ID of
+ */
+ public function getCommerceProducts($ParentCategory = null)
+ {
+ $products = Product::get();
+
+ if (isset($ParentCategory) && is_int($ParentCategory)) {
+ $products = $products->where("ParentID = {$ParentID}");
+ }
+
+ return $products;
+ }
+
+ /**
+ * Renders a list of all ProductCategories ready to be loaded into a template
+ *
+ * @return HTML
+ */
+ public function getCommerceCategoryNav($ParentID = 0)
+ {
+ $vars = array(
+ 'ProductCategories' => $this->owner->getCommerceCategories($ParentID)
+ );
+
+ return $this->owner->renderWith('Commerce_CategoryNav', $vars);
+ }
+
+
+ /**
+ * Return a URL to link to this controller
+ *
+ * @return string URL to cart controller
+ */
+ public function getCommerceCartLink()
+ {
+ return Controller::join_links(
+ BASE_URL,
+ ShoppingCart::config()->url_segment
+ );
+ }
+
+
+ /**
+ * Return a rendered button for the shopping cart
+ *
+ * @return string Rendered HTML of cart button
+ */
+ public function getCommerceCartButton()
+ {
+ $vars = array(
+ 'Link' => $this->owner->getCommerceCartLink(),
+ 'Cart' => $this->owner->getCommerceCart()
+ );
+
+ return $this->owner->renderWith('Commerce_CartButton', $vars);
+ }
+
+
+ /**
+ * Return a the current shopping cart
+ *
+ * @return ShoppingCart
+ */
+ public function getCommerceCart()
+ {
+ return ShoppingCart::create();
+ }
+
+ /**
+ * Checks to see if the shopping cart functionality is enabled
+ *
+ * @return Boolean
+ */
+ public function getCommerceCartEnabled()
+ {
+ return ShoppingCart::config()->enabled;
+ }
+}
diff --git a/code/extensions/Ext_Commerce_Group.php b/code/extensions/Ext_Commerce_Group.php
index e8a6b61..465da2e 100755
--- a/code/extensions/Ext_Commerce_Group.php
+++ b/code/extensions/Ext_Commerce_Group.php
@@ -3,19 +3,21 @@
/**
* Overwrite group object so we can setup some more default groups
*/
-class Ext_Commerce_Group extends DataExtension {
+class Ext_Commerce_Group extends DataExtension
+{
private static $belongs_many_many = array(
"Discounts" => "Discount"
);
- public function requireDefaultRecords() {
+ public function requireDefaultRecords()
+ {
parent::requireDefaultRecords();
// Add default author group if no other group exists
- $curr_group = Group::get()->filter("Code","commerce-customers");
+ $curr_group = Group::get()->filter("Code", "commerce-customers");
- if(!$curr_group->exists()) {
+ if (!$curr_group->exists()) {
$group = new Group();
$group->Code = 'commerce-customers';
$group->Title = "Commerce Customers";
@@ -26,4 +28,3 @@ public function requireDefaultRecords() {
}
}
}
-
diff --git a/code/extensions/Ext_Commerce_Image.php b/code/extensions/Ext_Commerce_Image.php
index 9eecad7..b540072 100755
--- a/code/extensions/Ext_Commerce_Image.php
+++ b/code/extensions/Ext_Commerce_Image.php
@@ -1,5 +1,6 @@
'Product'
);
diff --git a/code/extensions/Ext_Commerce_LeftAndMain.php b/code/extensions/Ext_Commerce_LeftAndMain.php
index eed2e9e..522bce5 100755
--- a/code/extensions/Ext_Commerce_LeftAndMain.php
+++ b/code/extensions/Ext_Commerce_LeftAndMain.php
@@ -1,7 +1,9 @@
"Varchar",
"Company" => "Varchar(99)"
@@ -11,7 +12,8 @@ class Ext_Commerce_Member extends DataExtension {
"Addresses" => "MemberAddress"
);
- public function updateCMSFields(FieldList $fields) {
+ public function updateCMSFields(FieldList $fields)
+ {
$fields->remove("PhoneNumber");
$fields->addFieldToTab(
@@ -34,11 +36,12 @@ public function updateCMSFields(FieldList $fields) {
*
* @return Discount
*/
- public function getDiscount() {
+ public function getDiscount()
+ {
$discounts = ArrayList::create();
- foreach($this->owner->Groups() as $group) {
- foreach($group->Discounts() as $discount) {
+ foreach ($this->owner->Groups() as $group) {
+ foreach ($group->Discounts() as $discount) {
$discounts->add($discount);
}
}
@@ -54,12 +57,13 @@ public function getDiscount() {
*
* @return DataList
*/
- public function getOutstandingOrders() {
+ public function getOutstandingOrders()
+ {
$orders = $this
->owner
->Orders()
->filter(array(
- "Status" => array("paid","processing")
+ "Status" => array("paid", "processing")
));
return $orders;
@@ -71,12 +75,13 @@ public function getOutstandingOrders() {
*
* @return DataList
*/
- public function getHistoricOrders() {
+ public function getHistoricOrders()
+ {
$orders = $this
->owner
->Orders()
->filter(array(
- "Status" => array("dispatched","canceled")
+ "Status" => array("dispatched", "canceled")
));
return $orders;
diff --git a/code/extensions/Ext_Commerce_SiteConfig.php b/code/extensions/Ext_Commerce_SiteConfig.php
index 282402d..8fa7e56 100755
--- a/code/extensions/Ext_Commerce_SiteConfig.php
+++ b/code/extensions/Ext_Commerce_SiteConfig.php
@@ -4,7 +4,8 @@
*
* @author morven
*/
-class Ext_Commerce_SiteConfig extends DataExtension {
+class Ext_Commerce_SiteConfig extends DataExtension
+{
private static $db = array(
// Commerce Configs
'ContactEmail' => 'Varchar(100)',
@@ -51,13 +52,14 @@ class Ext_Commerce_SiteConfig extends DataExtension {
*
* @return String
*/
- public function getTaxString() {
+ public function getTaxString()
+ {
$return = "";
- if($this->owner->TaxName && $this->owner->TaxPriceInclude) {
+ if ($this->owner->TaxName && $this->owner->TaxPriceInclude) {
$return .= _t("Commerce.Including", "Including");
$return .= " " . $this->owner->TaxName;
- } elseif($this->owner->TaxName && !$this->owner->TaxPriceInclude) {
+ } elseif ($this->owner->TaxName && !$this->owner->TaxPriceInclude) {
$return .= _t("Commerce.Excluding", "Excluding");
$return .= " " . $this->owner->TaxName;
}
@@ -65,27 +67,31 @@ public function getTaxString() {
return $return;
}
- public function sendCommerceEmail($recipient, $status) {
- if($recipient == 'Customer')
- $array = array('Customer', 'Both');
- elseif($recipient == 'Vendor')
- $array = array('Vendor', 'Both');
- else
- $array = array();
+ public function sendCommerceEmail($recipient, $status)
+ {
+ if ($recipient == 'Customer') {
+ $array = array('Customer', 'Both');
+ } elseif ($recipient == 'Vendor') {
+ $array = array('Vendor', 'Both');
+ } else {
+ $array = array();
+ }
- if($status == 'paid' && in_array($this->owner->SendPaidEmail, $array))
- return true;
- elseif($status == 'failed' && in_array($this->owner->SendFailedEmail, $array))
- return true;
- elseif($status == 'processing' && in_array($this->owner->SendProcessingEmail, $array))
- return true;
- elseif($status == 'dispatched' && in_array($this->owner->SendDispatchedEmail, $array))
- return true;
- else
- return false;
+ if ($status == 'paid' && in_array($this->owner->SendPaidEmail, $array)) {
+ return true;
+ } elseif ($status == 'failed' && in_array($this->owner->SendFailedEmail, $array)) {
+ return true;
+ } elseif ($status == 'processing' && in_array($this->owner->SendProcessingEmail, $array)) {
+ return true;
+ } elseif ($status == 'dispatched' && in_array($this->owner->SendDispatchedEmail, $array)) {
+ return true;
+ } else {
+ return false;
+ }
}
- public function updateCMSFields(FieldList $fields) {
+ public function updateCMSFields(FieldList $fields)
+ {
$fields->removeByName('ContactEmail');
$fields->removeByName('ContactPhone');
@@ -109,7 +115,7 @@ public function updateCMSFields(FieldList $fields) {
TextField::create('OrderPrefix', 'Short code that can appear at the start of order numbers', null, 9),
DropdownField::create('CurrencyID', 'Currency to use', CommerceCurrency::get()->map(), $this->owner->CurrencyID)->setEmptyString('Please Select'),
DropdownField::create('WeightID', 'Weight to use', ProductWeight::get()->map(), $this->owner->WeightID)->setEmptyString('Please Select'),
- UploadField::create('NoProductImage','Overwrite default "image unavailable" image')
+ UploadField::create('NoProductImage', 'Overwrite default "image unavailable" image')
)
)->setHeadingLevel(4);
@@ -193,7 +199,7 @@ public function updateCMSFields(FieldList $fields) {
),
'Calculation' => array(
'title' => 'Base unit',
- 'callback' => function($record, $column, $grid) {
+ 'callback' => function ($record, $column, $grid) {
return DropdownField::create(
$column,
"Based on",
@@ -265,7 +271,7 @@ public function updateCMSFields(FieldList $fields) {
'Tax',
array(
NumericField::create('TaxRate'),
- TextField::create("TaxName","Name of your tax (EG 'VAT')"),
+ TextField::create("TaxName", "Name of your tax (EG 'VAT')"),
CheckboxField::create('TaxPriceInclude', 'Show price including tax?')
)
)->setHeadingLevel(4);
@@ -281,10 +287,11 @@ public function updateCMSFields(FieldList $fields) {
$fields->addFieldToTab('Root.Commerce', $tax_fields);
}
- public function requireDefaultRecords() {
+ public function requireDefaultRecords()
+ {
// If "no product image" is not in DB, add it
- if(!Image::get()->filter('Name','no-image.png')->first()) {
+ if (!Image::get()->filter('Name', 'no-image.png')->first()) {
$image = new Image();
$image->Name = 'no-image.png';
$image->Title = 'No Image';
@@ -296,16 +303,17 @@ public function requireDefaultRecords() {
}
}
- public function onBeforeWrite() {
+ public function onBeforeWrite()
+ {
parent::onBeforeWrite();
// If product image has not been set, add the default
- if(!$this->owner->NoProductImageID) {
+ if (!$this->owner->NoProductImageID) {
$image = Image::get()
- ->filter('Name','no-image.png')
+ ->filter('Name', 'no-image.png')
->first();
- if($image) {
+ if ($image) {
$this->owner->NoProductImageID = $image->ID;
}
}
diff --git a/code/extensions/Ext_Commerce_UsersController.php b/code/extensions/Ext_Commerce_UsersController.php
index 3496136..721093c 100755
--- a/code/extensions/Ext_Commerce_UsersController.php
+++ b/code/extensions/Ext_Commerce_UsersController.php
@@ -5,7 +5,8 @@
*
* @package commerce
*/
-class Ext_Commerce_UsersController extends Extension {
+class Ext_Commerce_UsersController extends Extension
+{
private static $allowed_actions = array(
"addresses",
@@ -21,7 +22,8 @@ class Ext_Commerce_UsersController extends Extension {
/**
* Display all addresses associated with the current user
*/
- public function addresses() {
+ public function addresses()
+ {
return $this
->owner
->customise(array(
@@ -33,13 +35,13 @@ public function addresses() {
"Users",
"Page"
));
-
}
/**
* Display all addresses associated with the current user
*/
- public function addaddress() {
+ public function addaddress()
+ {
$form = $this->AddressForm();
$form
->Fields()
@@ -58,18 +60,18 @@ public function addaddress() {
"Users",
"Page"
));
-
}
/**
* Display all addresses associated with the current user
*/
- public function editaddress() {
+ public function editaddress()
+ {
$member = Member::currentUser();
$id = $this->owner->request->param("ID");
$address = MemberAddress::get()->byID($id);
- if($address && $address->canEdit($member)) {
+ if ($address && $address->canEdit($member)) {
$form = $this->AddressForm();
$form->loadDataFrom($address);
$form
@@ -89,42 +91,46 @@ public function editaddress() {
"Users",
"Page"
));
- } else
+ } else {
return $this->owner->httpError(404);
+ }
}
/**
* Remove an addresses by the given ID (if allowed)
*/
- public function removeaddress() {
+ public function removeaddress()
+ {
$member = Member::currentUser();
$id = $this->owner->request->param("ID");
$address = MemberAddress::get()->byID($id);
- if($address && $address->canDelete($member)) {
+ if ($address && $address->canDelete($member)) {
$address->delete();
$this->owner->setFlashMessage(
"success",
- _t("CommerceAccount.AddressRemoved","Address Removed")
+ _t("CommerceAccount.AddressRemoved", "Address Removed")
);
return $this->owner->redirectback();
- } else
+ } else {
return $this->owner->httpError(404);
+ }
}
/**
* Display all outstanding orders for the current user
*
*/
- public function outstanding() {
+ public function outstanding()
+ {
$member = Member::currentUser();
$orders = new PaginatedList($member->getOutstandingOrders(), $this->owner->request);
- if(!$orders->exists()) {
+ if (!$orders->exists()) {
$message = '';
- $message .= _t("CommerceAccount.NoOrders","There are currently no orders");
+ $message .= _t("CommerceAccount.NoOrders", "There are currently no orders");
$message .= '
';
$content = new HTMLText();
@@ -138,7 +144,7 @@ public function outstanding() {
$this->owner->customise(array(
"ClassName" => "AccountPage",
- "Title" => _t('CommerceAccount.OutstandingOrders','Outstanding Orders'),
+ "Title" => _t('CommerceAccount.OutstandingOrders', 'Outstanding Orders'),
"Content" => $content,
"Orders" => $orders
));
@@ -154,14 +160,15 @@ public function outstanding() {
* Display all historic orders for the current user
*
*/
- public function history() {
+ public function history()
+ {
$member = Member::currentUser();
$orders = new PaginatedList($member->getHistoricOrders(), $this->owner->request);
- if(!$orders->exists()) {
+ if (!$orders->exists()) {
$message = '';
- $message .= _t("CommerceAccount.NoOrders","There are currently no orders");
+ $message .= _t("CommerceAccount.NoOrders", "There are currently no orders");
$message .= '
';
$content = new HTMLText();
@@ -175,7 +182,7 @@ public function history() {
$this->owner->customise(array(
"ClassName" => "AccountPage",
- "Title" => _t('CommerceAccount.OrderHistory','Order History'),
+ "Title" => _t('CommerceAccount.OrderHistory', 'Order History'),
"Content" => $content,
"Orders" => $orders
));
@@ -191,21 +198,22 @@ public function history() {
* Display the currently selected order from the URL
*
*/
- public function order() {
+ public function order()
+ {
$orderID = $this->owner->request->param("ID");
$order = Order::get()->byID($orderID);
$content = new HTMLText();
- if(!$order || ($order && !$order->canView())) {
+ if (!$order || ($order && !$order->canView())) {
$message = '';
- $message .= _t("CommerceAccount.NotFound","Order not found");
+ $message .= _t("CommerceAccount.NotFound", "Order not found");
$message .= '
';
- $title = _t("CommerceAccount.NotFound","Order not found");
+ $title = _t("CommerceAccount.NotFound", "Order not found");
$content->setValue($message);
$order = null;
} else {
- $title = _t('Commerce.Order','Order') . ': ' . $order->OrderNumber;
+ $title = _t('Commerce.Order', 'Order') . ': ' . $order->OrderNumber;
}
$this->owner->customise(array(
@@ -226,27 +234,27 @@ public function order() {
/**
* Form used for adding or editing addresses
*/
- public function AddressForm() {
-
+ public function AddressForm()
+ {
$personal_fields = CompositeField::create(
- HeaderField::create('PersonalHeader', _t('Commerce.PersonalDetails','Personal Details'), 2),
- TextField::create('FirstName',_t('Commerce.FirstName','First Name(s)') . '*'),
- TextField::create('Surname',_t('Commerce.Surname','Surname') . '*')
+ HeaderField::create('PersonalHeader', _t('Commerce.PersonalDetails', 'Personal Details'), 2),
+ TextField::create('FirstName', _t('Commerce.FirstName', 'First Name(s)') . '*'),
+ TextField::create('Surname', _t('Commerce.Surname', 'Surname') . '*')
)->setName("PersonalFields")
->addExtraClass('unit')
->addExtraClass('size1of2')
->addExtraClass('unit-50');
$address_fields = CompositeField::create(
- HeaderField::create('AddressHeader', _t('Commerce.Address','Address'), 2),
- TextField::create('Address1',_t('Commerce.Address1','Address Line 1') . '*'),
- TextField::create('Address2',_t('Commerce.Address2','Address Line 2')),
- TextField::create('City',_t('Commerce.City','City') . '*'),
- TextField::create('PostCode',_t('Commerce.PostCode','Post Code') . '*'),
+ HeaderField::create('AddressHeader', _t('Commerce.Address', 'Address'), 2),
+ TextField::create('Address1', _t('Commerce.Address1', 'Address Line 1') . '*'),
+ TextField::create('Address2', _t('Commerce.Address2', 'Address Line 2')),
+ TextField::create('City', _t('Commerce.City', 'City') . '*'),
+ TextField::create('PostCode', _t('Commerce.PostCode', 'Post Code') . '*'),
CountryDropdownField::create(
'Country',
- _t('Commerce.Country','Country')
- )->setAttribute("class",'countrydropdown dropdown btn')
+ _t('Commerce.Country', 'Country')
+ )->setAttribute("class", 'countrydropdown dropdown btn')
)->setName("AddressFields")
->addExtraClass('unit')
->addExtraClass('size1of2')
@@ -266,10 +274,10 @@ public function AddressForm() {
$actions = FieldList::create(
LiteralField::create(
'BackButton',
- '' . _t('Commerce.Back','Back') . ''
+ '' . _t('Commerce.Back', 'Back') . ''
),
- FormAction::create('doSaveAddress', _t('CommerceAccount.Add','Add'))
+ FormAction::create('doSaveAddress', _t('CommerceAccount.Add', 'Add'))
->addExtraClass('commerce-action-next')
->addExtraClass('btn')
->addExtraClass('btn-green')
@@ -299,25 +307,26 @@ public function AddressForm() {
* created.
*
*/
- public function doSaveAddress($data, $form) {
-
- if(!$data["ID"])
+ public function doSaveAddress($data, $form)
+ {
+ if (!$data["ID"]) {
$address = MemberAddress::create();
- else
+ } else {
$address = MemberAddress::get()->byID($data["ID"]);
+ }
- if($address) {
+ if ($address) {
$form->saveInto($address);
$address->write();
$this->owner->setFlashMessage(
"success",
- _t("CommerceAccount.AddressSaved","Address Saved")
+ _t("CommerceAccount.AddressSaved", "Address Saved")
);
} else {
$this->owner->setFlashMessage(
"error",
- _t("CommerceAccount.Error","There was an error")
+ _t("CommerceAccount.Error", "There was an error")
);
}
@@ -328,23 +337,23 @@ public function doSaveAddress($data, $form) {
* Add commerce specific links to account menu
*
*/
- public function updateAccountMenu($menu) {
-
+ public function updateAccountMenu($menu)
+ {
$menu->add(new ArrayData(array(
"ID" => 1,
- "Title" => _t('CommerceAccount.OutstandingOrders','Outstanding Orders'),
+ "Title" => _t('CommerceAccount.OutstandingOrders', 'Outstanding Orders'),
"Link" => $this->owner->Link("outstanding")
)));
$menu->add(new ArrayData(array(
"ID" => 2,
- "Title" => _t('CommerceAccount.OrderHistory',"Order history"),
+ "Title" => _t('CommerceAccount.OrderHistory', "Order history"),
"Link" => $this->owner->Link("history")
)));
$menu->add(new ArrayData(array(
"ID" => 11,
- "Title" => _t('CommerceAccount.Addresses','Addresses'),
+ "Title" => _t('CommerceAccount.Addresses', 'Addresses'),
"Link" => $this->owner->Link("addresses")
)));
}
@@ -353,15 +362,16 @@ public function updateAccountMenu($menu) {
* Add fields used by this module to the profile editing form
*
*/
- public function updateEditAccountForm($form) {
+ public function updateEditAccountForm($form)
+ {
$form->Fields()->insertBefore(TextField::create(
"Company",
- _t('CommerceAccount.Company',"Company")
- ),"FirstName");
+ _t('CommerceAccount.Company', "Company")
+ ), "FirstName");
$form->Fields()->add(TextField::create(
"PhoneNumber",
- _t("CommerceAccount.PhoneNumber","Phone Number")
+ _t("CommerceAccount.PhoneNumber", "Phone Number")
));
}
}
diff --git a/code/extensions/Ext_Subsites_Commerce.php b/code/extensions/Ext_Subsites_Commerce.php
index 772b04a..299e2b8 100755
--- a/code/extensions/Ext_Subsites_Commerce.php
+++ b/code/extensions/Ext_Subsites_Commerce.php
@@ -3,12 +3,14 @@
/**
* Adds some basic subsites options that can be added to all commerce objects
*/
-class Ext_Subsites_CommerceObject extends DataExtension {
+class Ext_Subsites_CommerceObject extends DataExtension
+{
private static $has_one=array(
'Subsite' => 'Subsite', // The subsite that this page belongs to
);
- public function updateCMSFields(FieldList $fields) {
+ public function updateCMSFields(FieldList $fields)
+ {
$fields->addFieldToTab(
"Root.Main",
HiddenField::create(
@@ -22,36 +24,48 @@ public function updateCMSFields(FieldList $fields) {
/**
* Update any requests to limit the results to the current site
*/
- function augmentSQL(SQLQuery &$query, DataQuery &$dataQuery = null) {
- if(Subsite::$disable_subsite_filter) return;
- if($dataQuery->getQueryParam('Subsite.filter') === false) return;
+ public function augmentSQL(SQLQuery &$query, DataQuery &$dataQuery = null)
+ {
+ if (Subsite::$disable_subsite_filter) {
+ return;
+ }
+ if ($dataQuery->getQueryParam('Subsite.filter') === false) {
+ return;
+ }
// Don't run on delete queries, since they are always tied to
// a specific ID.
- if ($query->getDelete()) return;
+ if ($query->getDelete()) {
+ return;
+ }
// If you're querying by ID, ignore the sub-site - this is a bit ugly...
// if(!$query->where || (strpos($query->where[0], ".\"ID\" = ") === false && strpos($query->where[0], ".`ID` = ") === false && strpos($query->where[0], ".ID = ") === false && strpos($query->where[0], "ID = ") !== 0)) {
if (!$query->where || (!preg_match('/\.(\'|"|`|)ID(\'|"|`|)( ?)=/', $query->where[0]))) {
-
- if (Subsite::$force_subsite) $subsiteID = Subsite::$force_subsite;
- else {
+ if (Subsite::$force_subsite) {
+ $subsiteID = Subsite::$force_subsite;
+ } else {
/*if($context = DataObject::context_obj()) $subsiteID = (int)$context->SubsiteID;
else */$subsiteID = (int)Subsite::currentSubsiteID();
}
// The foreach is an ugly way of getting the first key :-)
- foreach($query->getFrom() as $tableName => $info) {
+ foreach ($query->getFrom() as $tableName => $info) {
// The tableName should be SiteTree or SiteTree_Live...
- if(strpos($tableName, $this->owner->ClassName) === false) break;
+ if (strpos($tableName, $this->owner->ClassName) === false) {
+ break;
+ }
$query->addWhere("\"$tableName\".\"SubsiteID\" IN ($subsiteID)");
break;
}
}
}
- function onBeforeWrite() {
- if(!$this->owner->ID && !$this->owner->SubsiteID) $this->owner->SubsiteID = Subsite::currentSubsiteID();
+ public function onBeforeWrite()
+ {
+ if (!$this->owner->ID && !$this->owner->SubsiteID) {
+ $this->owner->SubsiteID = Subsite::currentSubsiteID();
+ }
parent::onBeforeWrite();
}
}
diff --git a/code/forms/AddItemToCartForm.php b/code/forms/AddItemToCartForm.php
index f8093f7..d731d7a 100755
--- a/code/forms/AddItemToCartForm.php
+++ b/code/forms/AddItemToCartForm.php
@@ -4,9 +4,11 @@
* The add item form is loaded into controllers to allow adding of products to
* the shopping cart
*/
-class AddItemToCartForm extends Form {
+class AddItemToCartForm extends Form
+{
- public function __construct($controller, $product, $name = "AddItemForm") {
+ public function __construct($controller, $product, $name = "AddItemForm")
+ {
$productID = ($product) ? $product->ID : 0;
$fields = FieldList::create(
@@ -14,24 +16,26 @@ public function __construct($controller, $product, $name = "AddItemForm") {
);
$actions = FieldList::create(
- FormAction::create('doAddItemToCart',_t('Commerce.AddToCart','Add to Cart'))
+ FormAction::create('doAddItemToCart', _t('Commerce.AddToCart', 'Add to Cart'))
->addExtraClass('btn')
);
$requirements = new RequiredFields(array("Quantity"));
// If product colour customisations are set, add them to the item form
- if($product && $product->Customisations()->exists()) {
- foreach($product->Customisations() as $customisation) {
+ if ($product && $product->Customisations()->exists()) {
+ foreach ($product->Customisations() as $customisation) {
$field = $customisation->Field();
$fields->add($field);
// Check if field required
- if($customisation->Required) $requirements->addRequiredField($field->getName());
+ if ($customisation->Required) {
+ $requirements->addRequiredField($field->getName());
+ }
}
}
- $quantity_fields = QuantityField::create('Quantity', _t('Commerce.CartQty','Qty'))
+ $quantity_fields = QuantityField::create('Quantity', _t('Commerce.CartQty', 'Qty'))
->setValue('1')
->addExtraClass('commerce-additem-quantity');
@@ -41,22 +45,23 @@ public function __construct($controller, $product, $name = "AddItemForm") {
parent::__construct($controller, $name, $fields, $actions, $requirements);
}
- public function doAddItemToCart($data) {
+ public function doAddItemToCart($data)
+ {
$product = Product::get()->byID($data['ProductID']);
$customisations = array();
- foreach($data as $key => $value) {
- if(!(strpos($key, 'customise') === false) && $value) {
- $custom_data = explode("_",$key);
+ foreach ($data as $key => $value) {
+ if (!(strpos($key, 'customise') === false) && $value) {
+ $custom_data = explode("_", $key);
- if($custom_item = ProductCustomisation::get()->byID($custom_data[1])) {
+ if ($custom_item = ProductCustomisation::get()->byID($custom_data[1])) {
$modify_price = 0;
// Check if the current selected option has a price modification
- if($custom_item->Options()->exists()) {
+ if ($custom_item->Options()->exists()) {
$option = $custom_item
->Options()
- ->filter("Title",$value)
+ ->filter("Title", $value)
->first();
$modify_price = ($option) ? $option->ModifyPrice : 0;
}
@@ -67,11 +72,10 @@ public function doAddItemToCart($data) {
"ModifyPrice" => $modify_price,
);
}
-
}
}
- if($product) {
+ if ($product) {
$cart = ShoppingCart::create();
$cart->add($product, $data['Quantity'], $customisations);
$cart->save();
@@ -92,5 +96,4 @@ public function doAddItemToCart($data) {
return $this->controller->redirectBack();
}
-
}
diff --git a/code/forms/BillingDetailsForm.php b/code/forms/BillingDetailsForm.php
index 5c96c66..e7bb02e 100755
--- a/code/forms/BillingDetailsForm.php
+++ b/code/forms/BillingDetailsForm.php
@@ -4,20 +4,21 @@
*
* @author morven
*/
-class BillingDetailsForm extends Form {
- public function __construct($controller, $name = "BillingDetailsForm") {
-
+class BillingDetailsForm extends Form
+{
+ public function __construct($controller, $name = "BillingDetailsForm")
+ {
$personal_fields = CompositeField::create(
HeaderField::create(
'PersonalHeader',
- _t('Commerce.PersonalDetails','Personal Details'),
+ _t('Commerce.PersonalDetails', 'Personal Details'),
3
),
- TextField::create('FirstName',_t('Commerce.FirstName','First Name(s)') . '*'),
- TextField::create('Surname',_t('Commerce.Surname','Surname') . '*'),
- TextField::create("Company",_t('Commerce.Company',"Company")),
- EmailField::create('Email',_t('Commerce.Email','Email') . '*'),
- TextField::create('PhoneNumber',_t('Commerce.Phone','Phone Number'))
+ TextField::create('FirstName', _t('Commerce.FirstName', 'First Name(s)') . '*'),
+ TextField::create('Surname', _t('Commerce.Surname', 'Surname') . '*'),
+ TextField::create("Company", _t('Commerce.Company', "Company")),
+ EmailField::create('Email', _t('Commerce.Email', 'Email') . '*'),
+ TextField::create('PhoneNumber', _t('Commerce.Phone', 'Phone Number'))
)->setName("PersonalFields")
->addExtraClass('unit')
->addExtraClass('size1of2')
@@ -26,19 +27,19 @@ public function __construct($controller, $name = "BillingDetailsForm") {
$address_fields = CompositeField::create(
HeaderField::create(
'AddressHeader',
- _t('Commerce.Address','Address'),
+ _t('Commerce.Address', 'Address'),
3
),
- TextField::create('Address1',_t('Commerce.Address1','Address Line 1') . '*'),
- TextField::create('Address2',_t('Commerce.Address2','Address Line 2')),
- TextField::create('City',_t('Commerce.City','City') . '*'),
- TextField::create('PostCode',_t('Commerce.PostCode','Post Code') . '*'),
+ TextField::create('Address1', _t('Commerce.Address1', 'Address Line 1') . '*'),
+ TextField::create('Address2', _t('Commerce.Address2', 'Address Line 2')),
+ TextField::create('City', _t('Commerce.City', 'City') . '*'),
+ TextField::create('PostCode', _t('Commerce.PostCode', 'Post Code') . '*'),
CountryDropdownField::create(
'Country',
- _t('Commerce.Country','Country') . '*',
+ _t('Commerce.Country', 'Country') . '*',
null,
'GB'
- )->setAttribute("class",'countrydropdown dropdown btn')
+ )->setAttribute("class", 'countrydropdown dropdown btn')
)->setName("AddressFields")
->addExtraClass('unit')
->addExtraClass('size1of2')
@@ -55,12 +56,12 @@ public function __construct($controller, $name = "BillingDetailsForm") {
);
// Add a save address for later checkbox if a user is logged in
- if(Member::currentUserID()) {
+ if (Member::currentUserID()) {
$fields->add(
CompositeField::create(
CheckboxField::create(
"SaveAddress",
- _t('Commerce.SaveAddress','Save this address for later')
+ _t('Commerce.SaveAddress', 'Save this address for later')
)
)->setName("SaveAddressHolder")
->addExtraClass('line')
@@ -76,14 +77,14 @@ public function __construct($controller, $name = "BillingDetailsForm") {
$actions = FieldList::create(
LiteralField::create(
'BackButton',
- '' . _t('Commerce.Back','Back') . ''
+ '' . _t('Commerce.Back', 'Back') . ''
),
- FormAction::create('doSetDelivery', _t('Commerce.SetDeliveryAddress','Deliver to another address'))
+ FormAction::create('doSetDelivery', _t('Commerce.SetDeliveryAddress', 'Deliver to another address'))
->addExtraClass('btn')
->addExtraClass('commerce-action-next'),
- FormAction::create('doContinue', _t('Commerce.DeliverThisAddress','Deliver to this address'))
+ FormAction::create('doContinue', _t('Commerce.DeliverThisAddress', 'Deliver to this address'))
->addExtraClass('btn')
->addExtraClass('commerce-action-next')
->addExtraClass('btn-green')
@@ -110,7 +111,8 @@ public function __construct($controller, $name = "BillingDetailsForm") {
*
* @return Redirect
*/
- public function doContinue($data) {
+ public function doContinue($data)
+ {
// Set delivery details based billing details
$delivery_data = array();
$delivery_data['DeliveryFirstnames'] = $data['FirstName'];
@@ -122,8 +124,8 @@ public function doContinue($data) {
$delivery_data['DeliveryCountry'] = $data['Country'];
// Save both sets of data to sessions
- Session::set("Commerce.BillingDetailsForm.data",$data);
- Session::set("Commerce.DeliveryDetailsForm.data",$delivery_data);
+ Session::set("Commerce.BillingDetailsForm.data", $data);
+ Session::set("Commerce.DeliveryDetailsForm.data", $delivery_data);
$this->save_address($data);
@@ -144,9 +146,10 @@ public function doContinue($data) {
*
* @return Redirect
*/
- public function doSetDelivery($data) {
+ public function doSetDelivery($data)
+ {
// Save billing data to sessions
- Session::set("Commerce.BillingDetailsForm.data",$data);
+ Session::set("Commerce.BillingDetailsForm.data", $data);
$this->save_address($data);
@@ -165,9 +168,10 @@ public function doSetDelivery($data) {
*
* @param $data Form data submitted
*/
- private function save_address($data) {
+ private function save_address($data)
+ {
// If the user ticked "save address" then add to their account
- if(array_key_exists('SaveAddress',$data) && $data['SaveAddress']) {
+ if (array_key_exists('SaveAddress', $data) && $data['SaveAddress']) {
$address = MemberAddress::create();
$address->FirstName = $data['FirstName'];
$address->Surname = $data['Surname'];
diff --git a/code/forms/CommerceLoginForm.php b/code/forms/CommerceLoginForm.php
index 219df12..22e22f5 100644
--- a/code/forms/CommerceLoginForm.php
+++ b/code/forms/CommerceLoginForm.php
@@ -6,7 +6,8 @@
* @package commerce
* @author i-lateral (http://www.i-lateral.com)
*/
-class CommerceLoginForm extends MemberLoginForm {
+class CommerceLoginForm extends MemberLoginForm
+{
/**
* Login form handler method
@@ -15,25 +16,32 @@ class CommerceLoginForm extends MemberLoginForm {
*
* @param array $data Submitted data
*/
- public function dologin($data) {
- if($this->performLogin($data)) {
+ public function dologin($data)
+ {
+ if ($this->performLogin($data)) {
$this->logInUserAndRedirect($data);
} else {
- if(array_key_exists('Email', $data)){
+ if (array_key_exists('Email', $data)) {
Session::set('SessionForms.MemberLoginForm.Email', $data['Email']);
Session::set('SessionForms.MemberLoginForm.Remember', isset($data['Remember']));
}
- if(isset($_REQUEST['BackURL'])) $backURL = $_REQUEST['BackURL'];
- else $backURL = null;
+ if (isset($_REQUEST['BackURL'])) {
+ $backURL = $_REQUEST['BackURL'];
+ } else {
+ $backURL = null;
+ }
- if($backURL) Session::set('BackURL', $backURL);
+ if ($backURL) {
+ Session::set('BackURL', $backURL);
+ }
// Show the right tab on failed login
$loginLink = Director::absoluteURL($this->controller->Link());
- if($backURL) $loginLink .= '?BackURL=' . urlencode($backURL);
+ if ($backURL) {
+ $loginLink .= '?BackURL=' . urlencode($backURL);
+ }
$this->controller->redirect($loginLink . '#' . $this->FormName() .'_tab');
}
}
-
}
diff --git a/code/forms/DeliveryDetailsForm.php b/code/forms/DeliveryDetailsForm.php
index a935a89..9c8145b 100755
--- a/code/forms/DeliveryDetailsForm.php
+++ b/code/forms/DeliveryDetailsForm.php
@@ -4,17 +4,18 @@
*
* @author morven
*/
-class DeliveryDetailsForm extends Form {
- public function __construct($controller, $name = "DeliveryDetailsForm") {
-
+class DeliveryDetailsForm extends Form
+{
+ public function __construct($controller, $name = "DeliveryDetailsForm")
+ {
$personal_fields = CompositeField::create(
HeaderField::create(
'PersonalHeader',
- _t('Commerce.PersonalDetails','Personal Details'),
+ _t('Commerce.PersonalDetails', 'Personal Details'),
3
),
- TextField::create('DeliveryFirstnames',_t('Commerce.FirstName','First Name(s)') . '*'),
- TextField::create('DeliverySurname',_t('Commerce.Surname','Surname') . '*')
+ TextField::create('DeliveryFirstnames', _t('Commerce.FirstName', 'First Name(s)') . '*'),
+ TextField::create('DeliverySurname', _t('Commerce.Surname', 'Surname') . '*')
)->setName("PersonalFields")
->addExtraClass('unit')
->addExtraClass('size1of2')
@@ -23,17 +24,17 @@ public function __construct($controller, $name = "DeliveryDetailsForm") {
$address_fields = CompositeField::create(
HeaderField::create(
'AddressHeader',
- _t('Commerce.Address','Address'),
+ _t('Commerce.Address', 'Address'),
3
),
- TextField::create('DeliveryAddress1',_t('Commerce.Address1','Address Line 1') . '*'),
- TextField::create('DeliveryAddress2',_t('Commerce.Address2','Address Line 2')),
- TextField::create('DeliveryCity',_t('Commerce.City','City') . '*'),
- TextField::create('DeliveryPostCode',_t('Commerce.PostCode','Post Code') . '*'),
+ TextField::create('DeliveryAddress1', _t('Commerce.Address1', 'Address Line 1') . '*'),
+ TextField::create('DeliveryAddress2', _t('Commerce.Address2', 'Address Line 2')),
+ TextField::create('DeliveryCity', _t('Commerce.City', 'City') . '*'),
+ TextField::create('DeliveryPostCode', _t('Commerce.PostCode', 'Post Code') . '*'),
CountryDropdownField::create(
'DeliveryCountry',
- _t('Commerce.Country','Country')
- )->setAttribute("class",'countrydropdown dropdown btn')
+ _t('Commerce.Country', 'Country')
+ )->setAttribute("class", 'countrydropdown dropdown btn')
)->setName("AddressFields")
->addExtraClass('unit')
->addExtraClass('size1of2')
@@ -49,14 +50,14 @@ public function __construct($controller, $name = "DeliveryDetailsForm") {
);
// Add a save address for later checkbox if a user is logged in
- if(Member::currentUserID()) {
+ if (Member::currentUserID()) {
$member = Member::currentUser();
$fields->add(
CompositeField::create(
CheckboxField::create(
"SaveAddress",
- _t('Commerce.SaveAddress','Save this address for later')
+ _t('Commerce.SaveAddress', 'Save this address for later')
)
)->setName("SaveAddressHolder")
->addExtraClass('line')
@@ -69,10 +70,10 @@ public function __construct($controller, $name = "DeliveryDetailsForm") {
$actions = FieldList::create(
LiteralField::create(
'BackButton',
- '' . _t('Commerce.Back','Back') . ''
+ '' . _t('Commerce.Back', 'Back') . ''
),
- FormAction::create('doContinue', _t('Commerce.PostageDetails','Select Postage'))
+ FormAction::create('doContinue', _t('Commerce.PostageDetails', 'Select Postage'))
->addExtraClass('btn')
->addExtraClass('commerce-action-next')
->addExtraClass('btn-green')
@@ -90,11 +91,12 @@ public function __construct($controller, $name = "DeliveryDetailsForm") {
parent::__construct($controller, $name, $fields, $actions, $validator);
}
- public function doContinue($data) {
- Session::set("Commerce.DeliveryDetailsForm.data",$data);
+ public function doContinue($data)
+ {
+ Session::set("Commerce.DeliveryDetailsForm.data", $data);
// If the user ticked "save address" then add to their account
- if(array_key_exists('SaveAddress',$data) && $data['SaveAddress']) {
+ if (array_key_exists('SaveAddress', $data) && $data['SaveAddress']) {
$address = MemberAddress::create();
$address->FirstName = $data['DeliveryFirstnames'];
$address->Surname = $data['DeliverySurname'];
diff --git a/code/forms/PostagePaymentForm.php b/code/forms/PostagePaymentForm.php
index 8c6c6af..ed04136 100755
--- a/code/forms/PostagePaymentForm.php
+++ b/code/forms/PostagePaymentForm.php
@@ -4,8 +4,10 @@
*
* @author morven
*/
-class PostagePaymentForm extends Form {
- public function __construct($controller, $name = "PostagePaymentForm") {
+class PostagePaymentForm extends Form
+{
+ public function __construct($controller, $name = "PostagePaymentForm")
+ {
// Get delivery data and postage areas from session
$delivery_data = Session::get("Commerce.DeliveryDetailsForm.data");
@@ -15,7 +17,7 @@ public function __construct($controller, $name = "PostagePaymentForm") {
// Loop through all postage areas and generate a new list
$postage_array = array();
- foreach($postage_areas as $area) {
+ foreach ($postage_areas as $area) {
$area_currency = new Currency("Cost");
$area_currency->setValue($area->Cost);
$postage_array[$area->ID] = $area->Title . " (" . $area_currency->Nice() . ")";
@@ -25,7 +27,7 @@ public function __construct($controller, $name = "PostagePaymentForm") {
// Setup postage fields
$postage_field = CompositeField::create(
- HeaderField::create("PostageHeader", _t('Commerce.Postage',"Postage")),
+ HeaderField::create("PostageHeader", _t('Commerce.Postage', "Postage")),
OptionsetField::create(
"PostageID",
_t('Commerce.PostageSelection', 'Please select your prefered postage'),
@@ -40,9 +42,9 @@ public function __construct($controller, $name = "PostagePaymentForm") {
$payment_methods = SiteConfig::current_site_config()->PaymentMethods();
// Deal with payment methods
- if($payment_methods->exists()) {
- $payment_map = $payment_methods->map('ID','Label');
- $payment_value = $payment_methods->filter('Default',1)->first()->ID;
+ if ($payment_methods->exists()) {
+ $payment_map = $payment_methods->map('ID', 'Label');
+ $payment_value = $payment_methods->filter('Default', 1)->first()->ID;
} else {
$payment_map = array();
$payment_value = 0;
@@ -75,10 +77,10 @@ public function __construct($controller, $name = "PostagePaymentForm") {
$actions = FieldList::create(
LiteralField::create(
'BackButton',
- '' . _t('Commerce.Back','Back') . ''
+ '' . _t('Commerce.Back', 'Back') . ''
),
- FormAction::create('doContinue', _t('Commerce.PaymentDetails','Enter Payment Details'))
+ FormAction::create('doContinue', _t('Commerce.PaymentDetails', 'Enter Payment Details'))
->addExtraClass('btn')
->addExtraClass('commerce-action-next')
->addExtraClass('btn-green')
@@ -92,7 +94,8 @@ public function __construct($controller, $name = "PostagePaymentForm") {
parent::__construct($controller, $name, $fields, $actions, $validator);
}
- public function doContinue($data) {
+ public function doContinue($data)
+ {
Session::set('Commerce.PaymentMethodID', $data['PaymentMethodID']);
Session::set("Commerce.PostageID", $data["PostageID"]);
diff --git a/code/forms/QuantityField.php b/code/forms/QuantityField.php
index e161904..54002b9 100755
--- a/code/forms/QuantityField.php
+++ b/code/forms/QuantityField.php
@@ -5,37 +5,41 @@
* @package forms
* @subpackage fields-formattedinput
*/
-class QuantityField extends NumericField{
+class QuantityField extends NumericField
+{
- public function Type() {
- return 'quantity numeric text';
- }
+ public function Type()
+ {
+ return 'quantity numeric text';
+ }
- /** PHP Validation **/
- public function validate($validator){
- if($this->value && !is_numeric(trim($this->value))){
- $validator->validationError(
- $this->name,
- _t(
- 'NumericField.VALIDATION', "'{value}' is not a number, only numbers can be accepted for this field",
- array('value' => $this->value)
- ),
- "validation"
- );
- return false;
- } elseif(!$this->value) {
- $validator->validationError(
- $this->name,
- sprintf(_t('Form.FIELDISREQUIRED', '%s is required'), $this->title),
- "validation"
- );
- return false;
- } else {
- return true;
- }
- }
-
- public function dataValue() {
- return (is_numeric($this->value)) ? $this->value : 0;
- }
+ /** PHP Validation **/
+ public function validate($validator)
+ {
+ if ($this->value && !is_numeric(trim($this->value))) {
+ $validator->validationError(
+ $this->name,
+ _t(
+ 'NumericField.VALIDATION', "'{value}' is not a number, only numbers can be accepted for this field",
+ array('value' => $this->value)
+ ),
+ "validation"
+ );
+ return false;
+ } elseif (!$this->value) {
+ $validator->validationError(
+ $this->name,
+ sprintf(_t('Form.FIELDISREQUIRED', '%s is required'), $this->title),
+ "validation"
+ );
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ public function dataValue()
+ {
+ return (is_numeric($this->value)) ? $this->value : 0;
+ }
}
diff --git a/code/forms/gridfield/CommerceGridFieldBulkAction_Dispatched.php b/code/forms/gridfield/CommerceGridFieldBulkAction_Dispatched.php
index 0da62df..bc474d0 100755
--- a/code/forms/gridfield/CommerceGridFieldBulkAction_Dispatched.php
+++ b/code/forms/gridfield/CommerceGridFieldBulkAction_Dispatched.php
@@ -5,7 +5,8 @@
*
* @package commerce
*/
-class CommerceGridFieldBulkAction_Dispatched extends GridFieldBulkActionHandler {
+class CommerceGridFieldBulkAction_Dispatched extends GridFieldBulkActionHandler
+{
private static $allowed_actions = array(
'dispatched'
@@ -15,10 +16,11 @@ class CommerceGridFieldBulkAction_Dispatched extends GridFieldBulkActionHandler
'dispatched' => 'dispatched'
);
- public function dispatched(SS_HTTPRequest $request) {
+ public function dispatched(SS_HTTPRequest $request)
+ {
$ids = array();
- foreach($this->getRecords() as $record) {
+ foreach ($this->getRecords() as $record) {
array_push($ids, $record->ID);
$record->Status = 'dispatched';
diff --git a/code/forms/gridfield/CommerceGridFieldBulkAction_Paid.php b/code/forms/gridfield/CommerceGridFieldBulkAction_Paid.php
index 156efa1..9553464 100755
--- a/code/forms/gridfield/CommerceGridFieldBulkAction_Paid.php
+++ b/code/forms/gridfield/CommerceGridFieldBulkAction_Paid.php
@@ -5,7 +5,8 @@
*
* @package commerce
*/
-class CommerceGridFieldBulkAction_Paid extends GridFieldBulkActionHandler {
+class CommerceGridFieldBulkAction_Paid extends GridFieldBulkActionHandler
+{
private static $allowed_actions = array(
'paid'
@@ -15,10 +16,11 @@ class CommerceGridFieldBulkAction_Paid extends GridFieldBulkActionHandler {
'paid' => 'paid'
);
- public function paid(SS_HTTPRequest $request) {
+ public function paid(SS_HTTPRequest $request)
+ {
$ids = array();
- foreach($this->getRecords() as $record) {
+ foreach ($this->getRecords() as $record) {
array_push($ids, $record->ID);
$record->Status = 'paid';
diff --git a/code/forms/gridfield/CommerceGridFieldBulkAction_Processing.php b/code/forms/gridfield/CommerceGridFieldBulkAction_Processing.php
index 8417a9e..180dc0d 100755
--- a/code/forms/gridfield/CommerceGridFieldBulkAction_Processing.php
+++ b/code/forms/gridfield/CommerceGridFieldBulkAction_Processing.php
@@ -5,7 +5,8 @@
*
* @package commerce
*/
-class CommerceGridFieldBulkAction_Processing extends GridFieldBulkActionHandler {
+class CommerceGridFieldBulkAction_Processing extends GridFieldBulkActionHandler
+{
private static $allowed_actions = array(
'processing'
@@ -15,10 +16,11 @@ class CommerceGridFieldBulkAction_Processing extends GridFieldBulkActionHandler
'processing' => 'processing'
);
- public function processing(SS_HTTPRequest $request) {
+ public function processing(SS_HTTPRequest $request)
+ {
$ids = array();
- foreach($this->getRecords() as $record) {
+ foreach ($this->getRecords() as $record) {
array_push($ids, $record->ID);
$record->Status = 'processing';
diff --git a/code/forms/gridfield/CommerceProductBulkAction.php b/code/forms/gridfield/CommerceProductBulkAction.php
index ccbf2fa..3d12391 100644
--- a/code/forms/gridfield/CommerceProductBulkAction.php
+++ b/code/forms/gridfield/CommerceProductBulkAction.php
@@ -5,7 +5,8 @@
*
* @package commerce
*/
-class CommerceProductBulkAction extends GridFieldBulkActionHandler {
+class CommerceProductBulkAction extends GridFieldBulkActionHandler
+{
private static $allowed_actions = array(
'enable',
@@ -17,10 +18,11 @@ class CommerceProductBulkAction extends GridFieldBulkActionHandler {
'disable' => 'disable'
);
- public function enable(SS_HTTPRequest $request) {
+ public function enable(SS_HTTPRequest $request)
+ {
$ids = array();
- foreach($this->getRecords() as $record) {
+ foreach ($this->getRecords() as $record) {
array_push($ids, $record->ID);
$record->Disabled = 0;
@@ -37,10 +39,11 @@ public function enable(SS_HTTPRequest $request) {
return $response;
}
- public function disable(SS_HTTPRequest $request) {
+ public function disable(SS_HTTPRequest $request)
+ {
$ids = array();
- foreach($this->getRecords() as $record) {
+ foreach ($this->getRecords() as $record) {
array_push($ids, $record->ID);
$record->Disabled = 1;
diff --git a/code/import/ProductCSVBulkLoader.php b/code/import/ProductCSVBulkLoader.php
index d1ee6aa..35b88e7 100644
--- a/code/import/ProductCSVBulkLoader.php
+++ b/code/import/ProductCSVBulkLoader.php
@@ -6,15 +6,19 @@
* @package commerce
* @author i-lateral (http://www.i-lateral.com)
*/
-class ProductCSVBulkLoader extends CsvBulkLoader {
+class ProductCSVBulkLoader extends CsvBulkLoader
+{
public $duplicateChecks = array(
'ID' => 'ID',
'SKU' => 'SKU'
);
- public function __construct($objectClass = null) {
- if(!$objectClass) $objectClass = 'Product';
+ public function __construct($objectClass = null)
+ {
+ if (!$objectClass) {
+ $objectClass = 'Product';
+ }
parent::__construct($objectClass);
}
@@ -24,7 +28,8 @@ public function __construct($objectClass = null) {
* Perform more complex imports of generic columns
*
*/
- public function processRecord($record, $columnMap, &$results, $preview = false) {
+ public function processRecord($record, $columnMap, &$results, $preview = false)
+ {
// Get Current Object
$objID = parent::processRecord($record, $columnMap, $results, $preview);
@@ -33,65 +38,71 @@ public function processRecord($record, $columnMap, &$results, $preview = false)
$this->extend("onBeforeProcess", $record, $object);
// Loop through all fields and setup associations
- foreach($record as $key => $value) {
+ foreach ($record as $key => $value) {
// Find any categories (denoted by a 'CategoryXX' column)
- if(strpos($key,'Category') !== false) {
+ if (strpos($key, 'Category') !== false) {
$category = ProductCategory::get()
->filter("Title", $value)
->first();
- if($category)
+ if ($category) {
$object->Categories()->add($category);
+ }
}
- if($key == 'Categories') {
+ if ($key == 'Categories') {
$parts = explode(',', $value);
- if(!count($parts)) return false;
+ if (!count($parts)) {
+ return false;
+ }
// First remove all categories
- foreach($object->Categories() as $category) {
+ foreach ($object->Categories() as $category) {
$object->Categories()->remove($category);
}
// Now re-add categories
- foreach($parts as $part) {
+ foreach ($parts as $part) {
$category = ProductCategory::get()
->filter("Title", trim($part))
->first();
- if($category)
+ if ($category) {
$object->Categories()->add($category);
+ }
}
}
// Find any Images (denoted by a 'ImageXX' column)
- if(strpos($key,'Image') !== false && $key != "Images") {
+ if (strpos($key, 'Image') !== false && $key != "Images") {
$image = Image::get()
->filter("Name", $value)
->first();
- if($image)
+ if ($image) {
$object->Images()->add($image);
+ }
}
// Alternativley look for the 'Images' field as a CSV
- if($key == "Images") {
+ if ($key == "Images") {
$parts = explode(',', $value);
- if(count($parts)) {
+ if (count($parts)) {
// First remove all Images
- foreach($object->Images() as $image) {
+ foreach ($object->Images() as $image) {
$object->Images()->remove($image);
}
// Now re-add categories
- foreach($parts as $part) {
+ foreach ($parts as $part) {
$image = Image::get()
->filter("Name", trim($part))
->first();
- if($image)
+ if ($image) {
$object->Images()->add($image);
+ }
}
}
}
@@ -104,5 +115,4 @@ public function processRecord($record, $columnMap, &$results, $preview = false)
return $objID;
}
-
}
diff --git a/code/model/CommerceCurrency.php b/code/model/CommerceCurrency.php
index 673e7ee..6677702 100755
--- a/code/model/CommerceCurrency.php
+++ b/code/model/CommerceCurrency.php
@@ -4,7 +4,8 @@
*
* @author morven
*/
-class CommerceCurrency extends DataObject {
+class CommerceCurrency extends DataObject
+{
private static $db = array(
'Title' => 'Varchar',
'HTMLNotation' => 'Varchar(10)',
@@ -23,10 +24,11 @@ class CommerceCurrency extends DataObject {
'GatewayCode' => 'Currency code for payment gateway'
);
- public function requireDefaultRecords() {
+ public function requireDefaultRecords()
+ {
parent::requireDefaultRecords();
- if(!CommerceCurrency::get()->exists()) {
+ if (!CommerceCurrency::get()->exists()) {
$gbp = new CommerceCurrency();
$gbp->Title = "UK Pounds";
$gbp->HTMLNotation = "£";
@@ -53,15 +55,18 @@ public function requireDefaultRecords() {
}
}
- public function canCreate($member = null) {
+ public function canCreate($member = null)
+ {
return true;
}
- public function canEdit($member = null) {
+ public function canEdit($member = null)
+ {
return true;
}
- public function canDelete($member = null) {
+ public function canDelete($member = null)
+ {
return true;
}
}
diff --git a/code/model/Discount.php b/code/model/Discount.php
index b896106..7b99e76 100644
--- a/code/model/Discount.php
+++ b/code/model/Discount.php
@@ -1,6 +1,7 @@
"Varchar",
@@ -31,7 +32,8 @@ class Discount extends DataObject {
*
* @return string
*/
- private static function generateRandomString($length = 10) {
+ private static function generateRandomString($length = 10)
+ {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = '';
@@ -45,7 +47,8 @@ private static function generateRandomString($length = 10) {
/**
* Set more complex default data
*/
- public function populateDefaults() {
+ public function populateDefaults()
+ {
$this->setField('Code', self::generateRandomString());
}
@@ -55,7 +58,8 @@ public function populateDefaults() {
*
* @return String
*/
- public function AddLink() {
+ public function AddLink()
+ {
$link = Controller::join_links(
Director::absoluteBaseURL(),
ShoppingCart::config()->url_segment,
@@ -66,10 +70,11 @@ public function AddLink() {
return $link;
}
- public function getCMSFields() {
+ public function getCMSFields()
+ {
$fields = parent::getCMSFields();
- if($this->Code) {
+ if ($this->Code) {
$fields->addFieldToTab(
"Root.Main",
LiteralField::create(
@@ -85,14 +90,14 @@ public function getCMSFields() {
}
// Remove add product button from black list
- if($blacklist = $fields->dataFieldByName("BlackList")) {
+ if ($blacklist = $fields->dataFieldByName("BlackList")) {
$blacklist
->getConfig()
->removeComponentsByType("GridFieldAddNewButton");
}
// Remove add product button from white list
- if($whitelist = $fields->dataFieldByName("WhiteList")) {
+ if ($whitelist = $fields->dataFieldByName("WhiteList")) {
$whitelist
->getConfig()
->removeComponentsByType("GridFieldAddNewButton");
@@ -101,23 +106,26 @@ public function getCMSFields() {
return $fields;
}
- public function onBeforeWrite() {
+ public function onBeforeWrite()
+ {
parent::onBeforeWrite();
// Ensure that the code is URL safe
$this->Code = Convert::raw2url($this->Code);
}
- public function canCreate($member = null) {
+ public function canCreate($member = null)
+ {
return true;
}
- public function canEdit($member = null) {
+ public function canEdit($member = null)
+ {
return true;
}
- public function canDelete($member = null) {
+ public function canDelete($member = null)
+ {
return true;
}
-
}
diff --git a/code/model/MemberAddress.php b/code/model/MemberAddress.php
index c6e211b..4517a77 100644
--- a/code/model/MemberAddress.php
+++ b/code/model/MemberAddress.php
@@ -7,7 +7,8 @@
* @package commerce
* @author i-lateral (http://www.i-lateral.com)
*/
-class MemberAddress extends DataObject {
+class MemberAddress extends DataObject
+{
public static $db = array(
'FirstName' => 'Varchar',
@@ -28,13 +29,17 @@ class MemberAddress extends DataObject {
*
* @return Boolean
*/
- public function canCreate($member = null) {
- if(!$member) $member = Member::currentUser();
+ public function canCreate($member = null)
+ {
+ if (!$member) {
+ $member = Member::currentUser();
+ }
- if($member)
+ if ($member) {
return true;
- else
+ } else {
return false;
+ }
}
/**
@@ -42,15 +47,19 @@ public function canCreate($member = null) {
*
* @return Boolean
*/
- public function canView($member = null) {
- if(!$member) $member = Member::currentUser();
+ public function canView($member = null)
+ {
+ if (!$member) {
+ $member = Member::currentUser();
+ }
- if($member && $this->OwnerID == $member->ID)
+ if ($member && $this->OwnerID == $member->ID) {
return true;
- else if($member && Permission::checkMember($member->ID, array("ADMIN")))
+ } elseif ($member && Permission::checkMember($member->ID, array("ADMIN"))) {
return true;
- else
+ } else {
return false;
+ }
}
/**
@@ -58,15 +67,19 @@ public function canView($member = null) {
*
* @return Boolean
*/
- public function canEdit($member = null) {
- if(!$member) $member = Member::currentUser();
+ public function canEdit($member = null)
+ {
+ if (!$member) {
+ $member = Member::currentUser();
+ }
- if($member && $this->OwnerID == $member->ID)
+ if ($member && $this->OwnerID == $member->ID) {
return true;
- else if($member && Permission::checkMember($member->ID, array("ADMIN")))
+ } elseif ($member && Permission::checkMember($member->ID, array("ADMIN"))) {
return true;
- else
+ } else {
return false;
+ }
}
/**
@@ -74,14 +87,18 @@ public function canEdit($member = null) {
*
* @return Boolean
*/
- public function canDelete($member = null) {
- if(!$member) $member = Member::currentUser();
+ public function canDelete($member = null)
+ {
+ if (!$member) {
+ $member = Member::currentUser();
+ }
- if($member && $this->OwnerID == $member->ID)
+ if ($member && $this->OwnerID == $member->ID) {
return true;
- else if($member && Permission::checkMember($member->ID, array("ADMIN")))
+ } elseif ($member && Permission::checkMember($member->ID, array("ADMIN"))) {
return true;
- else
+ } else {
return false;
+ }
}
}
diff --git a/code/model/Order.php b/code/model/Order.php
index 50e87a3..3d234a4 100755
--- a/code/model/Order.php
+++ b/code/model/Order.php
@@ -13,7 +13,8 @@
*
* @author morven
*/
-class Order extends DataObject implements PermissionProvider {
+class Order extends DataObject implements PermissionProvider
+{
private static $db = array(
'OrderNumber' => 'Varchar',
@@ -90,7 +91,8 @@ class Order extends DataObject implements PermissionProvider {
private static $default_sort = "Created DESC";
- public function getCMSFields() {
+ public function getCMSFields()
+ {
$fields = parent::getCMSFields();
// Remove defailt item admin
@@ -217,7 +219,7 @@ public function getCMSFields() {
$member = Member::currentUser();
- if(Permission::check('ADMIN', 'any', $member)) {
+ if (Permission::check('ADMIN', 'any', $member)) {
// Add non-editable payment ID
$paymentid_field = TextField::create('PaymentID', "Payment gateway ID number")
->setReadonly(true)
@@ -227,7 +229,7 @@ public function getCMSFields() {
$gateway_data = LiteralField::create(
"FormattedGatewayData",
"Data returned from the payment gateway:
" .
- str_replace(",",",
",$this->GatewayData)
+ str_replace(",", ",
", $this->GatewayData)
);
@@ -235,33 +237,35 @@ public function getCMSFields() {
$fields->addFieldToTab("Root.Gateway", $gateway_data);
}
- if(Permission::check(array('COMMERCE_ORDER_HISTORY','ADMIN'), 'any', $member)) {
+ if (Permission::check(array('COMMERCE_ORDER_HISTORY', 'ADMIN'), 'any', $member)) {
// Setup basic history of this order
$versions = $this->AllVersions();
$curr_version = $versions->First()->Version;
$message = "";
- foreach($versions as $version) {
+ foreach ($versions as $version) {
$i = $version->Version;
$name = "History_{$i}";
- if($i > 1) {
+ if ($i > 1) {
$frm = Versioned::get_version($this->class, $this->ID, $i - 1);
$to = Versioned::get_version($this->class, $this->ID, $i);
$diff = new DataDifferencer($frm, $to);
- if($version->Author())
+ if ($version->Author()) {
$message = "{$version->Author()->FirstName} ({$version->LastEdited})
";
- else
+ } else {
$message = "Unknown ({$version->LastEdited})
";
+ }
- if($diff->ChangedFields()->exists()) {
+ if ($diff->ChangedFields()->exists()) {
$message .= "";
// Now loop through all changed fields and track as message
- foreach($diff->ChangedFields() as $change) {
- if($change->Name != "LastEdited")
+ foreach ($diff->ChangedFields() as $change) {
+ if ($change->Name != "LastEdited") {
$message .= "- {$change->Title}: {$change->Diff}
";
+ }
}
$message .= "
";
@@ -280,7 +284,8 @@ public function getCMSFields() {
return $fields;
}
- public function getBillingAddress() {
+ public function getBillingAddress()
+ {
$address = ($this->Address1) ? $this->Address1 . ",\n" : '';
$address .= ($this->Address2) ? $this->Address2 . ",\n" : '';
$address .= ($this->City) ? $this->City . ",\n" : '';
@@ -290,7 +295,8 @@ public function getBillingAddress() {
return $address;
}
- public function getDeliveryAddress() {
+ public function getDeliveryAddress()
+ {
$address = ($this->DeliveryAddress1) ? $this->DeliveryAddress1 . ",\n" : '';
$address .= ($this->DeliveryAddress2) ? $this->DeliveryAddress2 . ",\n" : '';
$address .= ($this->DeliveryCity) ? $this->DeliveryCity . ",\n" : '';
@@ -301,8 +307,9 @@ public function getDeliveryAddress() {
}
- public function hasDiscount() {
- return (ceil($this->DiscountAmount)) ? true : false;
+ public function hasDiscount()
+ {
+ return (ceil($this->DiscountAmount)) ? true : false;
}
/**
@@ -310,11 +317,12 @@ public function hasDiscount() {
*
* @return Decimal
*/
- public function getSubTotal() {
+ public function getSubTotal()
+ {
$total = 0;
// Calculate total from items in the list
- foreach($this->Items() as $item) {
+ foreach ($this->Items() as $item) {
$total += $item->getSubTotal();
}
@@ -326,11 +334,12 @@ public function getSubTotal() {
*
* @return Decimal
*/
- public function getTaxTotal() {
+ public function getTaxTotal()
+ {
$total = 0;
// Calculate total from items in the list
- foreach($this->Items() as $item) {
+ foreach ($this->Items() as $item) {
$total += $item->getTaxTotal();
}
@@ -345,7 +354,8 @@ public function getTaxTotal() {
*
* @return Decimal
*/
- public function getPostage() {
+ public function getPostage()
+ {
return $this->PostageCost;
}
@@ -354,7 +364,8 @@ public function getPostage() {
*
* @return Decimal
*/
- public function getTotal() {
+ public function getTotal()
+ {
$sub = ($this->hasDiscount()) ? $this->SubTotal - $this->DiscountAmount : $this->SubTotal;
return number_format($sub + $this->Postage + $this->TaxTotal, 2);
@@ -365,51 +376,54 @@ public function getTotal() {
*
* @return string
*/
- public function getItemSummary() {
+ public function getItemSummary()
+ {
$return = '';
- foreach($this->Items() as $item) {
+ foreach ($this->Items() as $item) {
$return .= "{$item->Quantity} x {$item->Title};\n";
}
return $return;
}
- public function getTranslatedStatus() {
- switch($this->Status) {
+ public function getTranslatedStatus()
+ {
+ switch ($this->Status) {
case "incomplete":
- $return = _t("CommerceStatus.Incomplete","Incomplete");
+ $return = _t("CommerceStatus.Incomplete", "Incomplete");
break;
case "failed":
- $return = _t("CommerceStatus.Failed","Failed");
+ $return = _t("CommerceStatus.Failed", "Failed");
break;
case "canceled":
- $return = _t("CommerceStatus.Cancelled","Cancelled");
+ $return = _t("CommerceStatus.Cancelled", "Cancelled");
break;
case "paid":
- $return = _t("CommerceStatus.Paid","Paid");
+ $return = _t("CommerceStatus.Paid", "Paid");
break;
case "pending":
- $return = _t("CommerceStatus.Pending","Pending");
+ $return = _t("CommerceStatus.Pending", "Pending");
break;
case "processing":
- $return = _t("CommerceStatus.Processing","Processing");
+ $return = _t("CommerceStatus.Processing", "Processing");
break;
case "dispatched":
- $return = _t("CommerceStatus.Dispatched","Dispatched");
+ $return = _t("CommerceStatus.Dispatched", "Dispatched");
break;
}
return $return;
}
- protected function generate_order_number() {
+ protected function generate_order_number()
+ {
$id = str_pad($this->ID, 8, "0");
$guidText =
substr($id, 0, 4) . '-' .
substr($id, 4, 4) . '-' .
- rand(1000,9999);
+ rand(1000, 9999);
// Work out if an order prefix string has been set in siteconfig
$config = SiteConfig::current_site_config();
@@ -423,16 +437,17 @@ protected function generate_order_number() {
* API Callback before this object is written to the DB
*
*/
- public function onBeforeWrite() {
+ public function onBeforeWrite()
+ {
parent::onBeforeWrite();
// See if this order was just marked paid, if so reduce quantities for
// items.
- if($this->isChanged("Status") && $this->Status == "paid") {
- foreach($this->Items() as $item) {
+ if ($this->isChanged("Status") && $this->Status == "paid") {
+ foreach ($this->Items() as $item) {
$product = $item->MatchProduct;
- if($product->ID && $product->Quantity) {
+ if ($product->ID && $product->Quantity) {
$new_qty = $product->Quantity - $item->Quantity;
$product->Quantity = ($new_qty > 0) ? $new_qty : 0;
$product->write();
@@ -445,9 +460,10 @@ public function onBeforeWrite() {
* API Callback before this object is removed from to the DB
*
*/
- public function onBeforeDelete() {
+ public function onBeforeDelete()
+ {
// Delete all items attached to this order
- foreach($this->Items() as $item) {
+ foreach ($this->Items() as $item) {
$item->delete();
}
@@ -459,17 +475,18 @@ public function onBeforeDelete() {
* API Callback after this object is written to the DB
*
*/
- public function onAfterWrite() {
+ public function onAfterWrite()
+ {
parent::onAfterWrite();
// Check if an order number has been generated, if not, add it and save again
- if(!$this->OrderNumber) {
+ if (!$this->OrderNumber) {
$this->OrderNumber = $this->generate_order_number();
$this->write();
}
// Deal with sending the status email
- if($this->isChanged('Status') && in_array($this->Status, array('failed','paid','processing','dispatched')) ) {
+ if ($this->isChanged('Status') && in_array($this->Status, array('failed', 'paid', 'processing', 'dispatched'))) {
$siteconfig = SiteConfig::current_site_config();
$from = $siteconfig->EmailFromAddress;
@@ -480,27 +497,29 @@ public function onAfterWrite() {
);
// Deal with customer email
- if($siteconfig->sendCommerceEmail('Customer', $this->Status)) {
+ if ($siteconfig->sendCommerceEmail('Customer', $this->Status)) {
// if subsites installed, then get the native language for that site
$current_i18n = i18n::get_locale();
- if($this->SubsiteID && class_exists('Subsite') && $this->Subsite())
+ if ($this->SubsiteID && class_exists('Subsite') && $this->Subsite()) {
i18n::set_locale($this->Subsite()->Language);
+ }
$subject = _t('CommerceEmail.Order', 'Order') . " {$this->OrderNumber} {$this->getTranslatedStatus()}";
$body = $this->renderWith('OrderEmail_Customer', $vars);
- $email = new Email($from,$this->Email,$subject,$body);
+ $email = new Email($from, $this->Email, $subject, $body);
$email->sendPlain();
// If subsites enabled, set the language back
- if($this->SubsiteID && class_exists('Subsite') && $this->Subsite())
+ if ($this->SubsiteID && class_exists('Subsite') && $this->Subsite()) {
i18n::set_locale($current_i18n);
+ }
}
// Deal with vendor email
- if($siteconfig->sendCommerceEmail('Vendor', $this->Status)) {
+ if ($siteconfig->sendCommerceEmail('Vendor', $this->Status)) {
$subject = _t('CommerceEmail.Order', 'Order') . " {$this->OrderNumber} {$this->getTranslatedStatus()}";
- switch($this->Status) {
+ switch ($this->Status) {
case 'paid':
$email_to = $siteconfig->PaidEmailAddress;
case 'processing':
@@ -509,14 +528,12 @@ public function onAfterWrite() {
$email_to = $siteconfig->DispatchedEmailAddress;
}
- if(isset($email_to)) {
+ if (isset($email_to)) {
$body = $this->renderWith('OrderEmail_Vendor', $vars);
- $email = new Email($from,$email_to,$subject,$body);
+ $email = new Email($from, $email_to, $subject, $body);
$email->sendPlain();
}
}
-
-
}
}
@@ -525,7 +542,8 @@ public function onAfterWrite() {
* API Callback after this object is removed from to the DB
*
*/
- public function onAfterDelete() {
+ public function onAfterDelete()
+ {
parent::onAfterDelete();
foreach ($this->Items() as $item) {
@@ -533,7 +551,8 @@ public function onAfterDelete() {
}
}
- public function providePermissions() {
+ public function providePermissions()
+ {
return array(
"COMMERCE_VIEW_ORDERS" => array(
'name' => 'View any order',
@@ -567,21 +586,26 @@ public function providePermissions() {
*
* @return Boolean
*/
- public function canView($member = null) {
+ public function canView($member = null)
+ {
$extended = $this->extend('canView', $member);
- if($extended && $extended !== null) return $extended;
+ if ($extended && $extended !== null) {
+ return $extended;
+ }
- if($member instanceof Member)
+ if ($member instanceof Member) {
$memberID = $member->ID;
- else if(is_numeric($member))
+ } elseif (is_numeric($member)) {
$memberID = $member;
- else
+ } else {
$memberID = Member::currentUserID();
+ }
- if($memberID && Permission::checkMember($memberID, array("ADMIN", "COMMERCE_VIEW_ORDERS")))
+ if ($memberID && Permission::checkMember($memberID, array("ADMIN", "COMMERCE_VIEW_ORDERS"))) {
return true;
- else if($memberID && $memberID == $this->CustomerID)
+ } elseif ($memberID && $memberID == $this->CustomerID) {
return true;
+ }
return false;
}
@@ -591,9 +615,12 @@ public function canView($member = null) {
*
* @return Boolean
*/
- public function canCreate($member = null) {
+ public function canCreate($member = null)
+ {
$extended = $this->extend('canCreate', $member);
- if($extended && $extended !== null) return $extended;
+ if ($extended && $extended !== null) {
+ return $extended;
+ }
return true;
}
@@ -603,19 +630,24 @@ public function canCreate($member = null) {
*
* @return Boolean
*/
- public function canEdit($member = null) {
+ public function canEdit($member = null)
+ {
$extended = $this->extend('canEdit', $member);
- if($extended && $extended !== null) return $extended;
+ if ($extended && $extended !== null) {
+ return $extended;
+ }
- if($member instanceof Member)
+ if ($member instanceof Member) {
$memberID = $member->ID;
- else if(is_numeric($member))
+ } elseif (is_numeric($member)) {
$memberID = $member;
- else
+ } else {
$memberID = Member::currentUserID();
+ }
- if($memberID && Permission::checkMember($memberID, array("ADMIN", "COMMERCE_EDIT_ORDERS")))
+ if ($memberID && Permission::checkMember($memberID, array("ADMIN", "COMMERCE_EDIT_ORDERS"))) {
return true;
+ }
return false;
}
@@ -625,9 +657,12 @@ public function canEdit($member = null) {
*
* @return Boolean
*/
- public function canDelete($member = null) {
+ public function canDelete($member = null)
+ {
$extended = $this->extend('canDelete', $member);
- if($extended && $extended !== null) return $extended;
+ if ($extended && $extended !== null) {
+ return $extended;
+ }
return false;
}
diff --git a/code/model/OrderItem.php b/code/model/OrderItem.php
index 52f99cc..bf4e6a9 100755
--- a/code/model/OrderItem.php
+++ b/code/model/OrderItem.php
@@ -4,7 +4,8 @@
*
* @author morven
*/
-class OrderItem extends DataObject {
+class OrderItem extends DataObject
+{
private static $db = array(
'Title' => 'Varchar',
'SKU' => 'Varchar(100)',
@@ -44,10 +45,12 @@ class OrderItem extends DataObject {
*
* @return Product
*/
- public function Product() {
+ public function Product()
+ {
// If the SKU is set, and it matches a product, return product
- if($this->SKU && $product = Product::get()->filter("SKU", $this->SKU)->first())
+ if ($this->SKU && $product = Product::get()->filter("SKU", $this->SKU)->first()) {
return $product;
+ }
// If nothing has matched, return an empty product
return Product::create();
@@ -58,7 +61,8 @@ public function Product() {
*
* @return Product
*/
- public function getMatchProduct() {
+ public function getMatchProduct()
+ {
return $this->Product();
}
@@ -67,7 +71,8 @@ public function getMatchProduct() {
*
* @return Decimal
*/
- public function getSubTotal() {
+ public function getSubTotal()
+ {
return $this->Quantity * $this->Price;
}
@@ -76,7 +81,8 @@ public function getSubTotal() {
*
* @return Decimal
*/
- public function getTaxTotal() {
+ public function getTaxTotal()
+ {
return $this->Quantity * $this->Tax;
}
@@ -85,7 +91,8 @@ public function getTaxTotal() {
*
* @return Currency
*/
- public function getTotal() {
+ public function getTotal()
+ {
return $this->SubTotal + $this->TaxTotal;
}
@@ -94,14 +101,15 @@ public function getTotal() {
* HTML string
*
*/
- public function getCustomDetails() {
+ public function getCustomDetails()
+ {
$htmltext = HTMLText::create();
$return = "";
- if($this->Customisation) {
+ if ($this->Customisation) {
$customisations = unserialize($this->Customisation);
- foreach($customisations as $custom) {
+ foreach ($customisations as $custom) {
$return .= $custom->Title . ': ' . $custom->Value . ";
";
}
}
@@ -115,21 +123,26 @@ public function getCustomDetails() {
*
* @return Boolean
*/
- public function canView($member = null) {
+ public function canView($member = null)
+ {
$extended = $this->extend('canView', $member);
- if($extended && $extended !== null) return $extended;
+ if ($extended && $extended !== null) {
+ return $extended;
+ }
- if($member instanceof Member)
+ if ($member instanceof Member) {
$memberID = $member->ID;
- else if(is_numeric($member))
+ } elseif (is_numeric($member)) {
$memberID = $member;
- else
+ } else {
$memberID = Member::currentUserID();
+ }
- if($memberID && Permission::checkMember($memberID, array("ADMIN", "COMMERCE_VIEW_ORDERS")))
+ if ($memberID && Permission::checkMember($memberID, array("ADMIN", "COMMERCE_VIEW_ORDERS"))) {
return true;
- else if($memberID && $memberID == $this->CustomerID)
+ } elseif ($memberID && $memberID == $this->CustomerID) {
return true;
+ }
return false;
}
@@ -139,9 +152,12 @@ public function canView($member = null) {
*
* @return Boolean
*/
- public function canCreate($member = null) {
+ public function canCreate($member = null)
+ {
$extended = $this->extend('canCreate', $member);
- if($extended && $extended !== null) return $extended;
+ if ($extended && $extended !== null) {
+ return $extended;
+ }
return true;
}
@@ -151,9 +167,12 @@ public function canCreate($member = null) {
*
* @return Boolean
*/
- public function canEdit($member = null) {
+ public function canEdit($member = null)
+ {
$extended = $this->extend('canEdit', $member);
- if($extended && $extended !== null) return $extended;
+ if ($extended && $extended !== null) {
+ return $extended;
+ }
return false;
}
@@ -163,9 +182,12 @@ public function canEdit($member = null) {
*
* @return Boolean
*/
- public function canDelete($member = null) {
+ public function canDelete($member = null)
+ {
$extended = $this->extend('canDelete', $member);
- if($extended && $extended !== null) return $extended;
+ if ($extended && $extended !== null) {
+ return $extended;
+ }
return false;
}
diff --git a/code/model/PostageArea.php b/code/model/PostageArea.php
index 7ab0c87..4cfc4d3 100755
--- a/code/model/PostageArea.php
+++ b/code/model/PostageArea.php
@@ -4,7 +4,8 @@
*
* @author morven
*/
-class PostageArea extends DataObject {
+class PostageArea extends DataObject
+{
private static $db = array(
"Title" => "Varchar",
@@ -19,15 +20,18 @@ class PostageArea extends DataObject {
"Site" => "SiteConfig"
);
- public function canCreate($member = null) {
+ public function canCreate($member = null)
+ {
return true;
}
- public function canEdit($member = null) {
+ public function canEdit($member = null)
+ {
return true;
}
- public function canDelete($member = null) {
+ public function canDelete($member = null)
+ {
return true;
}
}
diff --git a/code/model/payment/CommercePaymentMethod.php b/code/model/payment/CommercePaymentMethod.php
index fd5db27..498b2ae 100755
--- a/code/model/payment/CommercePaymentMethod.php
+++ b/code/model/payment/CommercePaymentMethod.php
@@ -7,7 +7,8 @@
*
*
*/
-class CommercePaymentMethod extends DataObject {
+class CommercePaymentMethod extends DataObject
+{
/**
* Shall this class appear in the list of payment providers. Use this to
@@ -58,11 +59,13 @@ class CommercePaymentMethod extends DataObject {
*
* @return String
*/
- public function getLabel() {
+ public function getLabel()
+ {
return ($this->Icon) ? ' ' . $this->Summary . '' : "{$this->Summary}";
}
- public function getCMSFields() {
+ public function getCMSFields()
+ {
$fields = parent::getCMSFields();
$fields->removeByName('ParentConfigID');
@@ -73,22 +76,23 @@ public function getCMSFields() {
unset($payments['CommercePaymentMethod']);
// Check if any payment types have been hidden and unset
- foreach($payments as $payment_type) {
- if($payment_type::$hidden)
+ foreach ($payments as $payment_type) {
+ if ($payment_type::$hidden) {
unset($payments[$payment_type]);
+ }
}
- $classname_field = DropdownField::create('ClassName','Type of Payment',$payments)
+ $classname_field = DropdownField::create('ClassName', 'Type of Payment', $payments)
->setHasEmptyDefault(true)
->setEmptyString('Select Gateway');
$fields->addFieldToTab('Root.Main', $classname_field);
- if($this->ID) {
+ if ($this->ID) {
$fields->addFieldToTab("Root.Main", TextField::create('Summary', 'Summary message to appear on website'));
$fields->addFieldToTab("Root.Main", TextField::create('URL', 'Payment gateway URL'));
$fields->addFieldToTab("Root.Main", CheckboxField::create('Default', 'Default payment method?'));
- $fields->addFieldToTab("Root.Main", TextareaField::create('GatewayMessage','Message to appear when user user is directed to payment provider'));
+ $fields->addFieldToTab("Root.Main", TextareaField::create('GatewayMessage', 'Message to appear when user user is directed to payment provider'));
$fields->addFieldToTab("Root.Main", HTMLEditorField::create("PaymentInfo", "Message to appear on payment summary page"));
// Setup response URL field
@@ -142,7 +146,8 @@ public function getCMSFields() {
}
// Get relevent payment gateway URL to use in HTML form
- public function GatewayURL() {
+ public function GatewayURL()
+ {
return $this->URL;
}
}
diff --git a/code/model/payment/PayPal.php b/code/model/payment/PayPal.php
index 81aa5e8..3ef47b4 100644
--- a/code/model/payment/PayPal.php
+++ b/code/model/payment/PayPal.php
@@ -1,6 +1,7 @@
'Varchar(99)'
);
- public function getCMSFields() {
+ public function getCMSFields()
+ {
$fields = parent::getCMSFields();
- if($this->ID) {
+ if ($this->ID) {
$fields->removeByName("URL");
$fields->addFieldToTab(
@@ -28,7 +30,8 @@ public function getCMSFields() {
return $fields;
}
- public function onBeforeWrite() {
+ public function onBeforeWrite()
+ {
parent::onBeforeWrite();
$this->CallBackSlug = (!$this->CallBackSlug) ? 'paypal' : $this->CallBackSlug;
diff --git a/code/model/payment/SagePay.php b/code/model/payment/SagePay.php
index 3e96d26..05f9192 100755
--- a/code/model/payment/SagePay.php
+++ b/code/model/payment/SagePay.php
@@ -1,6 +1,7 @@
ID) {
+ if ($this->ID) {
// Payment Gateway Options
$email_options = array(
"Don't",
@@ -57,7 +59,7 @@ public function getCMSFields() {
$fields->addFieldToTab(
"Root.Main",
- EmailField::create('EmailRecipient','Email address of user to recieve email'),
+ EmailField::create('EmailRecipient', 'Email address of user to recieve email'),
"Summary"
);
}
@@ -66,21 +68,24 @@ public function getCMSFields() {
}
- public function onBeforeWrite() {
+ public function onBeforeWrite()
+ {
parent::onBeforeWrite();
$this->CallBackSlug = (!$this->CallBackSlug) ? 'sagepay' : Convert::raw2url($this->CallBackSlug);
- if(!$this->Summary)
+ if (!$this->Summary) {
$this->Summary = "Pay with credit/debit card securely via SagePay";
+ }
- if(!$this->GatewayMessage)
+ if (!$this->GatewayMessage) {
$this->GatewayMessage = "Thank you for your order from: " . SiteConfig::current_site_config()->Title;
+ }
}
-
}
-class SagePayForms extends SagePay {
+class SagePayForms extends SagePay
+{
public static $hidden = false;
@@ -89,7 +94,8 @@ class SagePayForms extends SagePay {
public $Title = 'SagePay Forms Integration';
}
-class SagePayServer extends SagePay {
+class SagePayServer extends SagePay
+{
public static $hidden = false;
diff --git a/code/model/payment/WorldPay.php b/code/model/payment/WorldPay.php
index 924f5e8..02eb013 100755
--- a/code/model/payment/WorldPay.php
+++ b/code/model/payment/WorldPay.php
@@ -1,6 +1,7 @@
'Varchar(10)'
);
- public function getCMSFields() {
+ public function getCMSFields()
+ {
$fields = parent::getCMSFields();
- if($this->ID) {
+ if ($this->ID) {
$fields->addFieldToTab(
"Root.Main",
TextField::create('InstallID', 'Instalation ID'),
@@ -33,12 +35,14 @@ public function getCMSFields() {
return $fields;
}
- public function onBeforeWrite() {
+ public function onBeforeWrite()
+ {
parent::onBeforeWrite();
$this->CallBackSlug = (!$this->CallBackSlug) ? 'worldpay' : $this->CallBackSlug;
- if(!$this->Summary)
+ if (!$this->Summary) {
$this->Summary = "Pay with credit/debit card securely via WorldPay";
+ }
}
}
diff --git a/code/model/product/Product.php b/code/model/product/Product.php
index b58274d..3d6d9d2 100755
--- a/code/model/product/Product.php
+++ b/code/model/product/Product.php
@@ -1,6 +1,7 @@
"Varchar(255)",
"SKU" => "Varchar(99)",
@@ -86,7 +87,8 @@ class Product extends DataObject {
*
* @return string URL to cart controller
*/
- public function Link($action = null){
+ public function Link($action = null)
+ {
return Controller::join_links(
BASE_URL,
$this->URLSegment,
@@ -97,11 +99,13 @@ public function Link($action = null){
/**
* Return the absolute link to this product
*/
- public function AbsoluteLink($action = null) {
+ public function AbsoluteLink($action = null)
+ {
return Director::absoluteURL($this->Link($action));
}
- public function getMenuTitle() {
+ public function getMenuTitle()
+ {
return $this->Title;
}
@@ -113,15 +117,18 @@ public function getMenuTitle() {
*
* @return Decimal
*/
- public function getTax() {
+ public function getTax()
+ {
$config = SiteConfig::current_site_config();
(float)$price = $this->Price;
(float)$rate = $config->TaxRate;
- if($rate > 0)
- (float)$tax = ($price / 100) * $rate; // Get our tax amount from the price
- else
+ if ($rate > 0) {
+ (float)$tax = ($price / 100) * $rate;
+ } // Get our tax amount from the price
+ else {
(float)$tax = 0;
+ }
return number_format($tax, 2);
}
@@ -135,7 +142,8 @@ public function getTax() {
*
* @return Decimal
*/
- public function getPriceWithTax() {
+ public function getPriceWithTax()
+ {
(float)$price = $this->Price;
(float)$tax = $this->Tax;
@@ -148,13 +156,15 @@ public function getPriceWithTax() {
*
* @return Decimal
*/
- public function getFrontPrice() {
+ public function getFrontPrice()
+ {
$config = SiteConfig::current_site_config();
- if($config->TaxPriceInclude)
+ if ($config->TaxPriceInclude) {
return $this->getPriceWithTax();
- else
+ } else {
return $this->Price;
+ }
}
/**
@@ -163,10 +173,11 @@ public function getFrontPrice() {
*
* @return ArrayList
*/
- public function SortedImages(){
- if($this->Images()->exists())
+ public function SortedImages()
+ {
+ if ($this->Images()->exists()) {
$images = $this->Images()->Sort('SortOrder');
- else {
+ } else {
$images = new ArrayList();
$default_image = new Image();
$default_image->ID = -1;
@@ -186,14 +197,15 @@ public function SortedImages(){
*
* @return string The breadcrumb trail.
*/
- public function Breadcrumbs($maxDepth = 20) {
+ public function Breadcrumbs($maxDepth = 20)
+ {
$items = array();
- if($this->Categories()->exists()) {
+ if ($this->Categories()->exists()) {
$items[] = $this;
$category = $this->Categories()->first();
- foreach($category->parentStack() as $item) {
+ foreach ($category->parentStack() as $item) {
$items[] = $item;
}
}
@@ -205,8 +217,9 @@ public function Breadcrumbs($maxDepth = 20) {
))));
}
- public function getCMSThumbnail() {
- return $this->SortedImages()->first()->PaddedImage(50,50);
+ public function getCMSThumbnail()
+ {
+ return $this->SortedImages()->first()->PaddedImage(50, 50);
}
/**
@@ -214,22 +227,27 @@ public function getCMSThumbnail() {
*
* return Boolean
*/
- public function HasMultipleImages() {
- if($this->Images()->exists() && $this->Images()->count() > 1)
+ public function HasMultipleImages()
+ {
+ if ($this->Images()->exists() && $this->Images()->count() > 1) {
return true;
- else
+ } else {
return false;
+ }
}
- public function getCategoriesList() {
+ public function getCategoriesList()
+ {
$list = '';
$categories = $this->Categories();
$i = 1;
- if($categories->exists()){
- foreach($categories as $category) {
+ if ($categories->exists()) {
+ foreach ($categories as $category) {
$list .= $category->Title;
- if($i < $categories->count()) $list .= ',';
+ if ($i < $categories->count()) {
+ $list .= ',';
+ }
$i++;
}
}
@@ -237,15 +255,18 @@ public function getCategoriesList() {
return $list;
}
- public function getImagesList() {
+ public function getImagesList()
+ {
$list = '';
$images = $this->SortedImages();
$i = 1;
- if($images->exists()){
- foreach($images as $image) {
+ if ($images->exists()) {
+ foreach ($images as $image) {
$list .= $image->Name;
- if($i < $images->count()) $list .= ',';
+ if ($i < $images->count()) {
+ $list .= ',';
+ }
$i++;
}
}
@@ -253,7 +274,8 @@ public function getImagesList() {
return $list;
}
- public function getCMSFields() {
+ public function getCMSFields()
+ {
$fields = new FieldList(
$rootTab = new TabSet("Root",
// Main Tab Fields
@@ -275,10 +297,10 @@ public function getCMSFields() {
ToggleCompositeField::create('Metadata', _t('CommerceAdmin.MetadataToggle', 'Metadata'),
array(
$metaFieldDesc = TextareaField::create("MetaDescription", $this->fieldLabel('MetaDescription')),
- $metaFieldExtra = TextareaField::create("ExtraMeta",$this->fieldLabel('ExtraMeta'))
+ $metaFieldExtra = TextareaField::create("ExtraMeta", $this->fieldLabel('ExtraMeta'))
)
)->setHeadingLevel(4),
- CheckboxField::create("Disabled",$this->fieldLabel('Disabled'))
+ CheckboxField::create("Disabled", $this->fieldLabel('Disabled'))
),
$tabImages = new Tab('Images',
SortableUploadField::create('Images', $this->fieldLabel('Images'), $this->Images())
@@ -306,7 +328,7 @@ public function getCMSFields() {
// Once product is saved, deal with more complex associations
- if($this->ID) {
+ if ($this->ID) {
// Deal with product features
$add_button = new GridFieldAddNewInlineButton('toolbar-header-left');
$add_button->setTitle('Add Attribute');
@@ -360,8 +382,9 @@ public function getCMSFields() {
return $fields;
}
- public function getCMSValidator() {
- return new RequiredFields(array("Title","Price"));
+ public function getCMSValidator()
+ {
+ return new RequiredFields(array("Title", "Price"));
}
/**
@@ -373,19 +396,22 @@ public function getCMSValidator() {
*
* @return bool
*/
- public function validURLSegment() {
+ public function validURLSegment()
+ {
$objects_to_check = array("SiteTree", "Product", "ProductCategory");
$segment = Convert::raw2sql($this->URLSegment);
- foreach($objects_to_check as $classname) {
+ foreach ($objects_to_check as $classname) {
$return = $classname::get()
->filter(array(
"URLSegment"=> $segment,
"ID:not" => $this->ID
));
- if($return->exists()) return false;
+ if ($return->exists()) {
+ return false;
+ }
}
return true;
@@ -402,12 +428,15 @@ public function validURLSegment() {
* @param string $title Page title.
* @return string Generated url segment
*/
- public function generateURLSegment($title){
+ public function generateURLSegment($title)
+ {
$filter = URLSegmentFilter::create();
$t = $filter->filter($title);
// Fallback to generic page name if path is empty (= no valid, convertable characters)
- if(!$t || $t == '-' || $t == '-1') $t = "page-$this->ID";
+ if (!$t || $t == '-' || $t == '-1') {
+ $t = "page-$this->ID";
+ }
// Hook for extensions
$this->extend('updateURLSegment', $t, $title);
@@ -415,72 +444,80 @@ public function generateURLSegment($title){
return $t;
}
- public function onBeforeWrite() {
+ public function onBeforeWrite()
+ {
parent::onBeforeWrite();
// If there is no URLSegment set, generate one from Title
- if((!$this->URLSegment || $this->URLSegment == 'new-page') && $this->Title) {
+ if ((!$this->URLSegment || $this->URLSegment == 'new-page') && $this->Title) {
$this->URLSegment = $this->generateURLSegment($this->Title);
- } else if($this->isChanged('URLSegment', 2)) {
+ } elseif ($this->isChanged('URLSegment', 2)) {
// Do a strict check on change level, to avoid double encoding caused by
// bogus changes through forceChange()
$filter = URLSegmentFilter::create();
$this->URLSegment = $filter->filter($this->URLSegment);
// If after sanitising there is no URLSegment, give it a reasonable default
- if(!$this->URLSegment) $this->URLSegment = "page-$this->ID";
+ if (!$this->URLSegment) {
+ $this->URLSegment = "page-$this->ID";
+ }
}
// Ensure that this object has a non-conflicting URLSegment value.
$count = 2;
- while(!$this->validURLSegment()) {
+ while (!$this->validURLSegment()) {
$this->URLSegment = preg_replace('/-[0-9]+$/', null, $this->URLSegment) . '-' . $count;
$count++;
}
// If no images are set, add our default image (if it exists)
- if(!$this->Images()->exists()) {
+ if (!$this->Images()->exists()) {
$config = SiteConfig::current_site_config();
- if ($config->NoProductImageID){
+ if ($config->NoProductImageID) {
$image = $config->NoProductImage();
} else {
$image = Image::get()
- ->filter('Name','no-image.png')
+ ->filter('Name', 'no-image.png')
->first();
}
- if($image) {
+ if ($image) {
$this->Images()->add($image->ID);
}
}
}
- public function onBeforeDelete() {
+ public function onBeforeDelete()
+ {
// Delete all attributes when this opbect is deleted
- foreach($this->Attributes() as $attribute) {
+ foreach ($this->Attributes() as $attribute) {
$attribute->delete();
}
// Delete all customisations when this opbect is deleted
- foreach($this->Customisations() as $cusomisation) {
+ foreach ($this->Customisations() as $cusomisation) {
$cusomisation->delete();
}
parent::onBeforeDelete();
}
- public function canView($member = false) {
+ public function canView($member = false)
+ {
return true;
}
- public function canCreate($member = null) {
+ public function canCreate($member = null)
+ {
return true;
}
- public function canEdit($member = null) {
+ public function canEdit($member = null)
+ {
return true;
}
- public function canDelete($member = null) {
+ public function canDelete($member = null)
+ {
return true;
}
}
diff --git a/code/model/product/ProductAttribute.php b/code/model/product/ProductAttribute.php
index aaa2c70..560ebf0 100755
--- a/code/model/product/ProductAttribute.php
+++ b/code/model/product/ProductAttribute.php
@@ -1,6 +1,7 @@
'Varchar',
'Content' => 'Varchar',
diff --git a/code/model/product/ProductCategory.php b/code/model/product/ProductCategory.php
index d353d9b..434021d 100755
--- a/code/model/product/ProductCategory.php
+++ b/code/model/product/ProductCategory.php
@@ -1,6 +1,7 @@
'Varchar',
'URLSegment' => 'Varchar',
@@ -40,7 +41,8 @@ class ProductCategory extends DataObject {
*
* @return string URL to cart controller
*/
- public function Link($action = null) {
+ public function Link($action = null)
+ {
return Controller::join_links(
BASE_URL,
$this->URLSegment,
@@ -51,11 +53,13 @@ public function Link($action = null) {
/**
* Return the absolute link to this category
*/
- public function AbsoluteLink($action = null) {
+ public function AbsoluteLink($action = null)
+ {
return Director::absoluteURL($this->Link($action));
}
- public function getMenuTitle() {
+ public function getMenuTitle()
+ {
return $this->Title;
}
@@ -65,11 +69,13 @@ public function getMenuTitle() {
*
* @return bool
*/
- public function isCurrent() {
- if($this->ID)
+ public function isCurrent()
+ {
+ if ($this->ID) {
return $this->ID == Catalogue_Controller::get_current_category()->ID;
- else
+ } else {
return $this === Catalogue_Controller::get_current_category();
+ }
}
/**
@@ -79,21 +85,24 @@ public function isCurrent() {
*
* @return bool
*/
- public function isSection() {
+ public function isSection()
+ {
// First check if we are currently viewing a product
$product = Catalogue_Controller::get_current_product();
- if($product->ID && $product->Categories()->exists()) {
+ if ($product->ID && $product->Categories()->exists()) {
$ancestors = $product->Categories()->first()->getAncestors()->column();
$ancestors[] = $product->Categories()->first()->ID;
} else {
// Get a map of ancestors
$ancestors = Catalogue_Controller::get_current_category()->getAncestors()->column();
- if($this->isCurrent()) $ancestors[] = $this->ID;
+ if ($this->isCurrent()) {
+ $ancestors[] = $this->ID;
+ }
}
- return in_array($this->ID,$ancestors) ? true : false;
+ return in_array($this->ID, $ancestors) ? true : false;
}
/**
@@ -102,10 +111,11 @@ public function isSection() {
*
* @return string
*/
- public function LinkingMode() {
- if($this->isCurrent()) {
+ public function LinkingMode()
+ {
+ if ($this->isCurrent()) {
return 'current';
- } elseif($this->isSection()) {
+ } elseif ($this->isSection()) {
return 'section';
} else {
return 'link';
@@ -117,7 +127,8 @@ public function LinkingMode() {
*
* @return string
*/
- public function LinkOrSection() {
+ public function LinkOrSection()
+ {
return $this->isSection() ? 'section' : 'link';
}
@@ -129,7 +140,8 @@ public function LinkOrSection() {
*
* @return string The breadcrumb trail.
*/
- public function Breadcrumbs($maxDepth = 20) {
+ public function Breadcrumbs($maxDepth = 20)
+ {
$template = new SSViewer('BreadcrumbsTemplate');
return $template->process($this->customise(new ArrayData(array(
@@ -141,10 +153,11 @@ public function Breadcrumbs($maxDepth = 20) {
* Returns the category in the current stack of the given level.
* Level(1) will return the category item that we're currently inside, etc.
*/
- public function Level($level) {
+ public function Level($level)
+ {
$parent = $this;
$stack = array($parent);
- while($parent = $parent->Parent) {
+ while ($parent = $parent->Parent) {
array_unshift($stack, $parent);
}
@@ -157,7 +170,8 @@ public function Level($level) {
*
* @return ArrayList
*/
- public function SortedProducts() {
+ public function SortedProducts()
+ {
return $this->Products()->Sort("SortOrder ASC, \"Product\".\"Title\" ASC");
}
@@ -167,26 +181,32 @@ public function SortedProducts() {
*
* @return ArrayList
*/
- public function AllProducts() {
+ public function AllProducts()
+ {
$products = new ArrayList();
// First add all products from this category
- foreach($this->Products() as $product) {
- if(!$product->Disabled) $products->add($product);
+ foreach ($this->Products() as $product) {
+ if (!$product->Disabled) {
+ $products->add($product);
+ }
}
// Now loop each child product
- foreach($this->Children() as $child) {
+ foreach ($this->Children() as $child) {
// First add all products from this category
- foreach($child->Products() as $product) {
- if(!$product->Disabled) $products->add($product);
+ foreach ($child->Products() as $product) {
+ if (!$product->Disabled) {
+ $products->add($product);
+ }
}
}
return $products;
}
- public function getCMSFields() {
+ public function getCMSFields()
+ {
$fields = parent::getCMSFields();
$fields->removeByName('Sort');
@@ -221,22 +241,25 @@ public function getCMSFields() {
return $fields;
}
- public function onBeforeWrite() {
+ public function onBeforeWrite()
+ {
parent::onBeforeWrite();
// Only call on first creation, ir if title is changed
- if(($this->ID == 0) || $this->isChanged('Title') || !($this->URLSegment)) {
+ if (($this->ID == 0) || $this->isChanged('Title') || !($this->URLSegment)) {
// Set the URL Segment, so it can be accessed via the controller
$filter = URLSegmentFilter::create();
$t = $filter->filter($this->Title);
// Fallback to generic name if path is empty (= no valid, convertable characters)
- if(!$t || $t == '-' || $t == '-1') $t = "category-{$this->ID}";
+ if (!$t || $t == '-' || $t == '-1') {
+ $t = "category-{$this->ID}";
+ }
// Ensure that this object has a non-conflicting URLSegment value.
- $existing_cats = ProductCategory::get()->filter('URLSegment',$t)->count();
- $existing_products = Product::get()->filter('URLSegment',$t)->count();
- $existing_pages = (class_exists('SiteTree')) ? SiteTree::get()->filter('URLSegment',$t)->count() : 0;
+ $existing_cats = ProductCategory::get()->filter('URLSegment', $t)->count();
+ $existing_products = Product::get()->filter('URLSegment', $t)->count();
+ $existing_pages = (class_exists('SiteTree')) ? SiteTree::get()->filter('URLSegment', $t)->count() : 0;
$count = (int)$existing_cats + (int)$existing_products + (int)$existing_pages;
@@ -244,29 +267,34 @@ public function onBeforeWrite() {
}
}
- public function onBeforeDelete() {
+ public function onBeforeDelete()
+ {
parent::onBeforeDelete();
- if($this->Children()) {
- foreach($this->Children() as $child) {
+ if ($this->Children()) {
+ foreach ($this->Children() as $child) {
$child->delete();
}
}
}
- public function canView($member = false) {
+ public function canView($member = false)
+ {
return true;
}
- public function canCreate($member = false) {
+ public function canCreate($member = false)
+ {
return true;
}
- public function canEdit($member = false) {
+ public function canEdit($member = false)
+ {
return true;
}
- public function canDelete($member = false) {
+ public function canDelete($member = false)
+ {
return true;
}
}
diff --git a/code/model/product/ProductColour.php b/code/model/product/ProductColour.php
index 8d12ccd..626855e 100755
--- a/code/model/product/ProductColour.php
+++ b/code/model/product/ProductColour.php
@@ -1,6 +1,7 @@
'Varchar',
'ColourCode' => 'Varchar',
diff --git a/code/model/product/ProductCustomisation.php b/code/model/product/ProductCustomisation.php
index b8217e7..ecb8c22 100755
--- a/code/model/product/ProductCustomisation.php
+++ b/code/model/product/ProductCustomisation.php
@@ -1,6 +1,7 @@
'Varchar',
'Required' => 'Boolean',
@@ -24,7 +25,8 @@ class ProductCustomisation extends DataObject {
private static $default_sort = "\"Sort\" ASC";
- public function getCMSFields() {
+ public function getCMSFields()
+ {
$fields = parent::getCMSFields();
$fields->removeByName('Options');
@@ -32,7 +34,7 @@ public function getCMSFields() {
$fields->removeByName('Sort');
$fields->removeByName('MaxLength');
- if($this->ID && $this->DisplayAs != "TextEntry") {
+ if ($this->ID && $this->DisplayAs != "TextEntry") {
$field_types = singleton('ProductCustomisationOption')->getFieldTypes();
// Deal with product features
@@ -56,12 +58,12 @@ public function getCMSFields() {
$fields->addFieldToTab('Root.Main', $options_field);
}
- if($this->ID && $this->DisplayAs == "TextEntry") {
- $fields->addFieldToTab("Root.Main",TextField::create("MaxLength"));
+ if ($this->ID && $this->DisplayAs == "TextEntry") {
+ $fields->addFieldToTab("Root.Main", TextField::create("MaxLength"));
}
- if(!$this->ID) {
- $fields->addFieldToTab('Root.Main',LiteralField::create('CreateWarning','You need to create this before you can add options
'));
+ if (!$this->ID) {
+ $fields->addFieldToTab('Root.Main', LiteralField::create('CreateWarning', 'You need to create this before you can add options
'));
}
$this->extend('updateCMSFields', $fields);
@@ -70,7 +72,8 @@ public function getCMSFields() {
}
// Get the default options for this customisation
- public function DefaultOptions() {
+ public function DefaultOptions()
+ {
$options = $this->Options()->filter('Default', 1);
$this->extend('updateDefaultOptions', $options);
@@ -83,18 +86,19 @@ public function DefaultOptions() {
*
* @return FormField
*/
- public function Field() {
- if($this->Title && $this->DisplayAs) {
+ public function Field()
+ {
+ if ($this->Title && $this->DisplayAs) {
$name = "customise_{$this->ID}_" . Convert::raw2url($this->Title);
$title = ($this->Required) ? $this->Title . ' *' : $this->Title;
- $options = $this->Options()->map('Title','ItemSummary');
+ $options = $this->Options()->map('Title', 'ItemSummary');
$defaults = $this->DefaultOptions();
$default = ($defaults->exists()) ? $defaults->first()->Title : null;
- switch($this->DisplayAs) {
+ switch ($this->DisplayAs) {
case 'Dropdown':
$field = DropdownField::create($name, $title, $options, $default)
- ->setEmptyString(_t('Commerce.PleaseSelect','Please Select'))
+ ->setEmptyString(_t('Commerce.PleaseSelect', 'Please Select'))
->setAttribute("class", "dropdown btn");
break;
case 'Radio':
@@ -105,44 +109,53 @@ public function Field() {
break;
case 'TextEntry':
$field = TextField::create($name, $title);
- if($this->MaxLength) $field->setMaxLength($this->MaxLength);
+ if ($this->MaxLength) {
+ $field->setMaxLength($this->MaxLength);
+ }
break;
}
$this->extend('updateField', $field);
return $field;
- } else
+ } else {
return false;
+ }
}
- public function onBeforeDelete() {
+ public function onBeforeDelete()
+ {
// Delete all options when this opbect is deleted
- foreach($this->Options() as $option) {
+ foreach ($this->Options() as $option) {
$option->delete();
}
parent::onBeforeDelete();
}
- public function canView($member = false) {
+ public function canView($member = false)
+ {
return $this->Parent()->canView($member);
}
- public function canCreate($member = null) {
+ public function canCreate($member = null)
+ {
return $this->Parent()->canCreate($member);
}
- public function canEdit($member = null) {
+ public function canEdit($member = null)
+ {
return $this->Parent()->canEdit($member);
}
- public function canDelete($member = null) {
+ public function canDelete($member = null)
+ {
return $this->Parent()->canDelete($member);
}
}
-class ProductCustomisationOption extends DataObject {
+class ProductCustomisationOption extends DataObject
+{
private static $db = array(
'Title' => 'Varchar',
'ModifyPrice' => 'Decimal',
@@ -179,7 +192,8 @@ class ProductCustomisationOption extends DataObject {
*
* @return Array of field names and types
*/
- public function getFieldTypes() {
+ public function getFieldTypes()
+ {
$fields = self::$field_types;
$this->extend('updateFieldTypes', $fields);
@@ -187,7 +201,8 @@ public function getFieldTypes() {
return $fields;
}
- public function getItemSummary() {
+ public function getItemSummary()
+ {
$config = SiteConfig::current_site_config();
$summary = $this->Title;
@@ -198,19 +213,23 @@ public function getItemSummary() {
return $summary;
}
- public function canView($member = false) {
+ public function canView($member = false)
+ {
return $this->Parent()->canView($member);
}
- public function canCreate($member = null) {
+ public function canCreate($member = null)
+ {
return $this->Parent()->canCreate($member);
}
- public function canEdit($member = null) {
+ public function canEdit($member = null)
+ {
return $this->Parent()->canEdit($member);
}
- public function canDelete($member = null) {
+ public function canDelete($member = null)
+ {
return $this->Parent()->canDelete($member);
}
}
diff --git a/code/model/product/ProductWeight.php b/code/model/product/ProductWeight.php
index e5b2dba..00d25d6 100755
--- a/code/model/product/ProductWeight.php
+++ b/code/model/product/ProductWeight.php
@@ -4,61 +4,65 @@
* Class that represents the weight of a product and how that weight is rendered
*
*/
- class ProductWeight extends DataObject {
- private static $db = array(
+ class ProductWeight extends DataObject
+ {
+ private static $db = array(
'Title' => 'Varchar',
'Unit' => 'Varchar(3)'
);
- private static $summary_fields = array(
+ private static $summary_fields = array(
'Title',
'Unit'
);
- public function requireDefaultRecords() {
- parent::requireDefaultRecords();
+ public function requireDefaultRecords()
+ {
+ parent::requireDefaultRecords();
- if(!ProductWeight::get()->exists()) {
- $weight = new ProductWeight();
- $weight->Title = "Kilograms";
- $weight->Unit = "kg";
- $weight->write();
- $weight->flushCache();
- DB::alteration_message('Kilograms weight created', 'created');
+ if (!ProductWeight::get()->exists()) {
+ $weight = new ProductWeight();
+ $weight->Title = "Kilograms";
+ $weight->Unit = "kg";
+ $weight->write();
+ $weight->flushCache();
+ DB::alteration_message('Kilograms weight created', 'created');
- $weight = new ProductWeight();
- $weight->Title = "Grams";
- $weight->Unit = "g";
- $weight->write();
- $weight->flushCache();
- DB::alteration_message('Grams weight created', 'created');
+ $weight = new ProductWeight();
+ $weight->Title = "Grams";
+ $weight->Unit = "g";
+ $weight->write();
+ $weight->flushCache();
+ DB::alteration_message('Grams weight created', 'created');
- $weight = new ProductWeight();
- $weight->Title = "Pound";
- $weight->Unit = "lb";
- $weight->write();
- $weight->flushCache();
- DB::alteration_message('Pounds weight created', 'created');
+ $weight = new ProductWeight();
+ $weight->Title = "Pound";
+ $weight->Unit = "lb";
+ $weight->write();
+ $weight->flushCache();
+ DB::alteration_message('Pounds weight created', 'created');
- $weight = new ProductWeight();
- $weight->Title = "Ounce";
- $weight->Unit = "oz";
- $weight->write();
- $weight->flushCache();
- DB::alteration_message('Ounces weight created', 'created');
- }
- }
+ $weight = new ProductWeight();
+ $weight->Title = "Ounce";
+ $weight->Unit = "oz";
+ $weight->write();
+ $weight->flushCache();
+ DB::alteration_message('Ounces weight created', 'created');
+ }
+ }
- public function canCreate($member = null) {
- return true;
- }
+ public function canCreate($member = null)
+ {
+ return true;
+ }
- public function canEdit($member = null) {
- return true;
- }
-
- public function canDelete($member = null) {
- return true;
- }
+ public function canEdit($member = null)
+ {
+ return true;
+ }
+ public function canDelete($member = null)
+ {
+ return true;
+ }
}
diff --git a/code/reports/OrderItemReport.php b/code/reports/OrderItemReport.php
index d5c12b6..68236cc 100644
--- a/code/reports/OrderItemReport.php
+++ b/code/reports/OrderItemReport.php
@@ -1,16 +1,20 @@
"SKU",
"Details" => "Details",
@@ -19,22 +23,25 @@ public function columns() {
);
}
- public function exportColumns() {
+ public function exportColumns()
+ {
// Loop through all colls and replace BR's with spaces
$cols = array();
- foreach($this->columns() as $key => $value) {
+ foreach ($this->columns() as $key => $value) {
$cols[$key] = str_replace('
', ' ', $value);
}
return $cols;
}
- public function sortColumns() {
+ public function sortColumns()
+ {
return array();
}
- public function getReportField() {
+ public function getReportField()
+ {
$gridField = parent::getReportField();
// Edit CSV export button
@@ -44,38 +51,49 @@ public function getReportField() {
return $gridField;
}
- public function sourceRecords($params, $sort, $limit) {
+ public function sourceRecords($params, $sort, $limit)
+ {
$return = ArrayList::create();
// Check filters
$where_filter = array();
$where_filter[] = (isset($params['Filter_Year'])) ? "YEAR(\"Created\") = '{$params['Filter_Year']}'" : "YEAR(\"Created\") = '".date('Y')."'";
- if(!empty($params['Filter_Month'])) $where_filter[] = "Month(\"Created\") = '{$params['Filter_Month']}'";
- if(!empty($params['Filter_Status'])) $where_filter[] = "Status = '{$params['Filter_Status']}'";
- if(!empty($params['Filter_FirstName'])) $where_filter[] = "FirstName = '{$params['Filter_FirstName']}'";
- if(!empty($params['Filter_Surname'])) $where_filter[] = "Surname = '{$params['Filter_Surname']}'";
+ if (!empty($params['Filter_Month'])) {
+ $where_filter[] = "Month(\"Created\") = '{$params['Filter_Month']}'";
+ }
+ if (!empty($params['Filter_Status'])) {
+ $where_filter[] = "Status = '{$params['Filter_Status']}'";
+ }
+ if (!empty($params['Filter_FirstName'])) {
+ $where_filter[] = "FirstName = '{$params['Filter_FirstName']}'";
+ }
+ if (!empty($params['Filter_Surname'])) {
+ $where_filter[] = "Surname = '{$params['Filter_Surname']}'";
+ }
$orders = Order::get()
->where(implode(' AND ', $where_filter));
- foreach($orders as $order) {
+ foreach ($orders as $order) {
// Setup a filter for our order items
$filter = array();
- if(!empty($params['Filter_ProductName']))
+ if (!empty($params['Filter_ProductName'])) {
$filter["Title:PartialMatch"] = $params['Filter_ProductName'];
+ }
- if(!empty($params['Filter_ProductSKU']))
+ if (!empty($params['Filter_ProductSKU'])) {
$filter["SKU"] = $params['Filter_ProductSKU'];
+ }
$list = (count($filter)) ? $order->Items()->filter($filter) : $order->Items();
- foreach($list as $order_item) {
- if($order_item->SKU) {
- if($list_item = $return->find("SKU", $order_item->SKU))
+ foreach ($list as $order_item) {
+ if ($order_item->SKU) {
+ if ($list_item = $return->find("SKU", $order_item->SKU)) {
$list_item->Quantity = $list_item->Quantity + $order_item->Quantity;
- else {
+ } else {
$report_item = OrderItemReportItem::create();
$report_item->ID = $order_item->SKU;
$report_item->SKU = $order_item->SKU;
@@ -92,30 +110,35 @@ public function sourceRecords($params, $sort, $limit) {
return $return;
}
- public function parameterFields() {
+ public function parameterFields()
+ {
$fields = new FieldList();
- if(class_exists("Subsite")) {
+ if (class_exists("Subsite")) {
$first_order = Subsite::get_from_all_subsites("Order")
- ->sort('Created','ASC')
+ ->sort('Created', 'ASC')
->first();
} else {
$first_order = Order::get()
- ->sort('Created','ASC')
+ ->sort('Created', 'ASC')
->first();
}
// Check if any order exist
- if($first_order) {
+ if ($first_order) {
// List all months
$months = array('All');
- for ($i = 1; $i <= 12; $i++) { $months[] = date("F", mktime(0, 0, 0, $i + 1, 0, 0)); }
+ for ($i = 1; $i <= 12; $i++) {
+ $months[] = date("F", mktime(0, 0, 0, $i + 1, 0, 0));
+ }
// Get the first order, then count down from current year to that
$firstyear = new SS_Datetime('FirstDate');
$firstyear->setValue($first_order->Created);
$years = array();
- for ($i = date('Y'); $i >= $firstyear->Year(); $i--) { $years[$i] = $i; }
+ for ($i = date('Y'); $i >= $firstyear->Year(); $i--) {
+ $years[$i] = $i;
+ }
// Order Status
$status = singleton('Order')->dbObject('Status')->enumValues();
diff --git a/code/reports/OrderItemReportItem.php b/code/reports/OrderItemReportItem.php
index 8c900a8..0758d12 100644
--- a/code/reports/OrderItemReportItem.php
+++ b/code/reports/OrderItemReportItem.php
@@ -4,7 +4,8 @@
* Item that can be loaded into an OrderItem report
*
*/
-class OrderItemReportItem extends Object {
+class OrderItemReportItem extends Object
+{
public $ClassName = "OrderItemReportItem";
@@ -14,7 +15,8 @@ class OrderItemReportItem extends Object {
public $Price;
public $Quantity;
- public function canView($member = null) {
+ public function canView($member = null)
+ {
return true;
}
}
diff --git a/code/reports/OrderReport.php b/code/reports/OrderReport.php
index 15f1ed3..8dc4dc8 100755
--- a/code/reports/OrderReport.php
+++ b/code/reports/OrderReport.php
@@ -1,16 +1,20 @@
'Order
Number',
'Created' => 'Order
Date',
@@ -27,22 +31,25 @@ public function columns() {
);
}
- public function exportColumns() {
+ public function exportColumns()
+ {
// Loop through all colls and replace BR's with spaces
$cols = array();
- foreach($this->columns() as $key => $value) {
+ foreach ($this->columns() as $key => $value) {
$cols[$key] = str_replace('
', ' ', $value);
}
return $cols;
}
- public function sortColumns() {
+ public function sortColumns()
+ {
return array();
}
- public function getReportField() {
+ public function getReportField()
+ {
$gridField = parent::getReportField();
// Edit CSV export button
@@ -52,18 +59,24 @@ public function getReportField() {
return $gridField;
}
- public function sourceRecords($params, $sort, $limit) {
+ public function sourceRecords($params, $sort, $limit)
+ {
// Check filters
$where_filter = array();
$where_filter[] = (isset($params['Filter_Year'])) ? "YEAR(\"Created\") = '{$params['Filter_Year']}'" : "YEAR(\"Created\") = '".date('Y')."'";
- if(!empty($params['Filter_Month'])) $where_filter[] = "Month(\"Created\") = '{$params['Filter_Month']}'";
- if(!empty($params['Filter_Status'])) $where_filter[] = "Status = '{$params['Filter_Status']}'";
+ if (!empty($params['Filter_Month'])) {
+ $where_filter[] = "Month(\"Created\") = '{$params['Filter_Month']}'";
+ }
+ if (!empty($params['Filter_Status'])) {
+ $where_filter[] = "Status = '{$params['Filter_Status']}'";
+ }
$limit = (isset($params['ResultsLimit']) && $params['ResultsLimit'] != 0) ? $params['ResultsLimit'] : '';
- if(!isset($sort))
+ if (!isset($sort)) {
$sort = (isset($params['Sort'])) ? Convert::raw2sql($params['Sort']) : 'Created DESC';
+ }
$orders = Order::get()
->where(implode(' AND ', $where_filter))
@@ -73,30 +86,35 @@ public function sourceRecords($params, $sort, $limit) {
return $orders;
}
- public function parameterFields() {
+ public function parameterFields()
+ {
$fields = new FieldList();
- if(class_exists("Subsite")) {
+ if (class_exists("Subsite")) {
$first_order = Subsite::get_from_all_subsites("Order")
- ->sort('Created','ASC')
+ ->sort('Created', 'ASC')
->first();
} else {
$first_order = Order::get()
- ->sort('Created','ASC')
+ ->sort('Created', 'ASC')
->first();
}
// Check if any order exist
- if($first_order) {
+ if ($first_order) {
// List all months
$months = array('All');
- for ($i = 1; $i <= 12; $i++) { $months[] = date("F", mktime(0, 0, 0, $i + 1, 0, 0)); }
+ for ($i = 1; $i <= 12; $i++) {
+ $months[] = date("F", mktime(0, 0, 0, $i + 1, 0, 0));
+ }
// Get the first order, then count down from current year to that
$firstyear = new SS_Datetime('FirstDate');
$firstyear->setValue($first_order->Created);
$years = array();
- for ($i = date('Y'); $i >= $firstyear->Year(); $i--) { $years[$i] = $i; }
+ for ($i = date('Y'); $i >= $firstyear->Year(); $i--) {
+ $years[$i] = $i;
+ }
// Order Status
$status = singleton('Order')->dbObject('Status')->enumValues();
diff --git a/code/tools/StringDecryptor.php b/code/tools/StringDecryptor.php
index 0961c23..061ddda 100755
--- a/code/tools/StringDecryptor.php
+++ b/code/tools/StringDecryptor.php
@@ -36,7 +36,8 @@
* ->get();
*/
-class StringDecryptor {
+class StringDecryptor
+{
/**
* String that we are going to decrypt
@@ -63,7 +64,8 @@ class StringDecryptor {
*/
private $hash;
- private function __construct($string) {
+ private function __construct($string)
+ {
$this->data = $string;
}
@@ -73,7 +75,8 @@ private function __construct($string) {
* @para, $string string to encrypt
* @return StringEncryptor
*/
- public static function create($string) {
+ public static function create($string)
+ {
return new StringDecryptor($string);
}
@@ -83,7 +86,8 @@ public static function create($string) {
* @param $type Type of encryption
* @return self
*/
- public function setEncryption($type) {
+ public function setEncryption($type)
+ {
$this->encryption = $type;
return $this;
}
@@ -94,7 +98,8 @@ public function setEncryption($type) {
* @param $hash
* @return self
*/
- public function setHash($hash) {
+ public function setHash($hash)
+ {
$this->hash = $hash;
return $this;
}
@@ -104,7 +109,8 @@ public function setHash($hash) {
*
* @return String
*/
- public function get() {
+ public function get()
+ {
return $this->encrypted_data;
}
@@ -113,9 +119,10 @@ public function get() {
*
* @return self
*/
- public function decode() {
+ public function decode()
+ {
// Fix plus to space conversion issue
- $this->data = str_replace(' ','+',$this->data);
+ $this->data = str_replace(' ', '+', $this->data);
// Do decoding
$this->data = base64_decode($this->data);
@@ -128,11 +135,13 @@ public function decode() {
*
* @return self
*/
- public function decrypt() {
- if($this->encryption == 'XOR')
+ public function decrypt()
+ {
+ if ($this->encryption == 'XOR') {
$this->encrypted_data = $this->simplexor();
- elseif($this->encryption == 'MCRYPT')
+ } elseif ($this->encryption == 'MCRYPT') {
$this->encrypted_data = $this->mcrypt();
+ }
return $this;
}
@@ -143,17 +152,18 @@ public function decrypt() {
*
* return self
*/
- private function simplexor() {
+ private function simplexor()
+ {
$KeyList = array();
$output = "";
// Convert $Key into array of ASCII values
- for($i = 0; $i < strlen($this->hash); $i++) {
+ for ($i = 0; $i < strlen($this->hash); $i++) {
$KeyList[$i] = ord(substr($this->hash, $i, 1));
}
// Step through string a character at a time
- for($i = 0; $i < strlen($this->data); $i++) {
+ for ($i = 0; $i < strlen($this->data); $i++) {
$output.= chr(ord(substr($this->data, $i, 1)) ^ ($KeyList[$i % strlen($this->hash)]));
}
@@ -166,7 +176,8 @@ private function simplexor() {
*
* @return string
*/
- private function mcrypt() {
+ private function mcrypt()
+ {
// HEX decoding
$data = pack('H*', $this->data);
@@ -184,7 +195,8 @@ private function mcrypt() {
*
* @return string
*/
- private function removePKCS5Padding($decrypt) {
+ private function removePKCS5Padding($decrypt)
+ {
$padChar = ord($decrypt[strlen($decrypt) - 1]);
return substr($decrypt, 0, -$padChar);
}
diff --git a/code/tools/StringEncryptor.php b/code/tools/StringEncryptor.php
index df7d73b..2ad8e37 100755
--- a/code/tools/StringEncryptor.php
+++ b/code/tools/StringEncryptor.php
@@ -35,7 +35,8 @@
*
*/
-class StringEncryptor {
+class StringEncryptor
+{
/**
* String that we are going to encrypt
@@ -62,7 +63,8 @@ class StringEncryptor {
*/
private $hash;
- private function __construct($string) {
+ private function __construct($string)
+ {
$this->data = $string;
}
@@ -72,7 +74,8 @@ private function __construct($string) {
* @para, $string string to encrypt
* @return StringEncryptor
*/
- public static function create($string) {
+ public static function create($string)
+ {
return new StringEncryptor($string);
}
@@ -82,7 +85,8 @@ public static function create($string) {
* @param $type Type of encryption
* @return self
*/
- public function setEncryption($type) {
+ public function setEncryption($type)
+ {
$this->encryption = $type;
return $this;
}
@@ -93,7 +97,8 @@ public function setEncryption($type) {
* @param $hash
* @return self
*/
- public function setHash($hash) {
+ public function setHash($hash)
+ {
$this->hash = $hash;
return $this;
}
@@ -103,7 +108,8 @@ public function setHash($hash) {
*
* @return String
*/
- public function get() {
+ public function get()
+ {
return $this->encrypted_data;
}
@@ -112,11 +118,13 @@ public function get() {
*
* @return self
*/
- public function encrypt() {
- if($this->encryption == 'XOR')
+ public function encrypt()
+ {
+ if ($this->encryption == 'XOR') {
$this->encrypted_data = $this->simplexor();
- elseif($this->encryption == 'MCRYPT')
+ } elseif ($this->encryption == 'MCRYPT') {
$this->encrypted_data = $this->mcrypt();
+ }
return $this;
}
@@ -126,7 +134,8 @@ public function encrypt() {
*
* @return self
*/
- public function encode() {
+ public function encode()
+ {
// Encode data string
$this->encrypted_data = base64_encode($this->encrypted_data);
@@ -139,17 +148,18 @@ public function encode() {
*
* return self
*/
- private function simplexor() {
+ private function simplexor()
+ {
$KeyList = array();
$output = "";
// Convert $Key into array of ASCII values
- for($i = 0; $i < strlen($this->hash); $i++) {
+ for ($i = 0; $i < strlen($this->hash); $i++) {
$KeyList[$i] = ord(substr($this->hash, $i, 1));
}
// Step through string a character at a time
- for($i = 0; $i < strlen($this->data); $i++) {
+ for ($i = 0; $i < strlen($this->data); $i++) {
$output.= chr(ord(substr($this->data, $i, 1)) ^ ($KeyList[$i % strlen($this->hash)]));
}
@@ -162,7 +172,8 @@ private function simplexor() {
*
* @return self
*/
- private function mcrypt() {
+ private function mcrypt()
+ {
$strIV = $this->hash;
// add PKCS5 padding to the text to be encypted
@@ -178,16 +189,17 @@ private function mcrypt() {
/**
* PHP's mcrypt does not have built in PKCS5 Padding, so we use this
*/
- private function addPKCS5Padding() {
- $blocksize = 16;
- $padding = "";
+ private function addPKCS5Padding()
+ {
+ $blocksize = 16;
+ $padding = "";
// Pad input to an even block size boundary
$padlength = $blocksize - (strlen($this->data) % $blocksize);
- for($i = 1; $i <= $padlength; $i++) {
- $padding .= chr($padlength);
- }
+ for ($i = 1; $i <= $padlength; $i++) {
+ $padding .= chr($padlength);
+ }
- return $this->data . $padding;
+ return $this->data . $padding;
}
}