From 7385bfe7b175ec908e51992a7260b0dbf9e1ed9f Mon Sep 17 00:00:00 2001
From: helpfulrobot <chris@silverstripe.com>
Date: Sat, 26 Dec 2015 11:19:54 +1300
Subject: [PATCH] Converted to PSR-2

---
 code/controllers/UniadsAdmin.php      | 104 ++++----
 code/controllers/UniadsController.php |  75 +++---
 code/dataobjects/UniadsCampaign.php   |  99 +++----
 code/dataobjects/UniadsClick.php      |   4 +-
 code/dataobjects/UniadsClient.php     |  20 +-
 code/dataobjects/UniadsImpression.php | 231 ++++++++--------
 code/dataobjects/UniadsObject.php     | 368 +++++++++++++-------------
 code/dataobjects/UniadsZone.php       | 162 ++++++------
 code/extensions/UniadsExtension.php   | 259 +++++++++---------
 9 files changed, 665 insertions(+), 657 deletions(-)

diff --git a/code/controllers/UniadsAdmin.php b/code/controllers/UniadsAdmin.php
index 183d559..d1305c9 100644
--- a/code/controllers/UniadsAdmin.php
+++ b/code/controllers/UniadsAdmin.php
@@ -7,55 +7,57 @@
  * @author Marcus Nyeholt <marcus@silverstripe.com.au>
  * @license BSD http://silverstripe.org/BSD-license
  */
-class UniadsAdmin extends ModelAdmin {
-
-	private static $managed_models = array(
-		'UniadsObject',
-		'UniadsCampaign',
-		'UniadsClient',
-		'UniadsZone',
-	);
-
-	private static $allowed_actions = array(
-		'preview'
-	);
-
-	private static $url_rule = '/$ModelClass/$Action/$ID/$OtherID';
-
-	private static $url_segment = 'advrt';
-	private static $menu_title = 'Ads';
-	private static $menu_icon = '';
-
-
-	public function __construct() {
-		$this->config()->menu_icon = ADS_MODULE_DIR . '/images/icon-advrt.png';
-		parent::__construct();
-	}
-
-	/** Preview an advertisement.
-	 */
-	public function preview(SS_HTTPRequest $request) {
-		$request->shift();
-		$adID = (int) $request->param('ID');
-		$ad = UniadsObject::get()->byID($adID);
-
-		if (!$ad) {
-			Controller::curr()->httpError(404);
-			return;
-		}
-
-		// No impression and click tracking for previews
-		$conf = UniadsObject::config();
-		$conf->use_js_tracking = false;
-		$conf->record_impressions = false;
-		$conf->record_impressions_stats = false;
-
-		// Block stylesheets and JS that are not required (using our own template)
-		Requirements::clear();
-
-		$template = new SSViewer('UniadsPreview');
-
-		return $template->Process($ad);
-	}
-
+class UniadsAdmin extends ModelAdmin
+{
+
+    private static $managed_models = array(
+        'UniadsObject',
+        'UniadsCampaign',
+        'UniadsClient',
+        'UniadsZone',
+    );
+
+    private static $allowed_actions = array(
+        'preview'
+    );
+
+    private static $url_rule = '/$ModelClass/$Action/$ID/$OtherID';
+
+    private static $url_segment = 'advrt';
+    private static $menu_title = 'Ads';
+    private static $menu_icon = '';
+
+
+    public function __construct()
+    {
+        $this->config()->menu_icon = ADS_MODULE_DIR . '/images/icon-advrt.png';
+        parent::__construct();
+    }
+
+    /** Preview an advertisement.
+     */
+    public function preview(SS_HTTPRequest $request)
+    {
+        $request->shift();
+        $adID = (int) $request->param('ID');
+        $ad = UniadsObject::get()->byID($adID);
+
+        if (!$ad) {
+            Controller::curr()->httpError(404);
+            return;
+        }
+
+        // No impression and click tracking for previews
+        $conf = UniadsObject::config();
+        $conf->use_js_tracking = false;
+        $conf->record_impressions = false;
+        $conf->record_impressions_stats = false;
+
+        // Block stylesheets and JS that are not required (using our own template)
+        Requirements::clear();
+
+        $template = new SSViewer('UniadsPreview');
+
+        return $template->Process($ad);
+    }
 }
diff --git a/code/controllers/UniadsController.php b/code/controllers/UniadsController.php
index b81bda3..137c3e3 100644
--- a/code/controllers/UniadsController.php
+++ b/code/controllers/UniadsController.php
@@ -7,44 +7,47 @@
  * @author Marcus Nyeholt <marcus@silverstripe.com.au>
  * @license BSD http://silverstripe.org/BSD-license
  */
-class UniadsController extends Controller {
+class UniadsController extends Controller
+{
 
-	private static $allowed_actions = array(
-		'clk',
-		'go',
-	);
+    private static $allowed_actions = array(
+        'clk',
+        'go',
+    );
 
-	public function clk() {
-		$this->GetAdAndLogClick($this->request->requestVar('id'));
-	}
+    public function clk()
+    {
+        $this->GetAdAndLogClick($this->request->requestVar('id'));
+    }
 
-	public function go() {
-		$ad = $this->GetAdAndLogClick($this->request->param('ID'));
-		if ($ad) {
-			$target = $ad->getTarget();
-			$this->redirect($target ? $target : Director::baseURL());
-		}
-	}
-
-	private function GetAdAndLogClick($id) {
-		$id = (int) $id;
-		if ($id) {
-			$ad = UniadsObject::get()->byID($id);
-			if ($ad && $ad->exists()) {
-				$conf = UniadsObject::config();
-				if ($conf->record_clicks) {
-					$ad->Clicks++;
-					$ad->write();
-				}
-				if ($conf->record_clicks_stats) {
-					$clk = new UniadsClick;
-					$clk->AdID = $ad->ID;
-					$clk->write();
-				}
-				return $ad;
-			}
-		}
-		return null;
-	}
+    public function go()
+    {
+        $ad = $this->GetAdAndLogClick($this->request->param('ID'));
+        if ($ad) {
+            $target = $ad->getTarget();
+            $this->redirect($target ? $target : Director::baseURL());
+        }
+    }
 
+    private function GetAdAndLogClick($id)
+    {
+        $id = (int) $id;
+        if ($id) {
+            $ad = UniadsObject::get()->byID($id);
+            if ($ad && $ad->exists()) {
+                $conf = UniadsObject::config();
+                if ($conf->record_clicks) {
+                    $ad->Clicks++;
+                    $ad->write();
+                }
+                if ($conf->record_clicks_stats) {
+                    $clk = new UniadsClick;
+                    $clk->AdID = $ad->ID;
+                    $clk->write();
+                }
+                return $ad;
+            }
+        }
+        return null;
+    }
 }
diff --git a/code/dataobjects/UniadsCampaign.php b/code/dataobjects/UniadsCampaign.php
index 878daf5..6c18181 100644
--- a/code/dataobjects/UniadsCampaign.php
+++ b/code/dataobjects/UniadsCampaign.php
@@ -7,53 +7,54 @@
  * @author Marcus Nyeholt <marcus@silverstripe.com.au>
  * @license BSD http://silverstripe.org/BSD-license
  */
-class UniadsCampaign extends DataObject {
-
-	private static $db = array(
-		'Title' => 'Varchar',
-		'Starts' => 'Date',
-		'Expires' => 'Date',
-		'Active' => 'Boolean',
-	);
-
-	private static $summary_fields = array(
-		'Title' => 'Title',
-		'Starts' => 'Starts',
-		'Expires' => 'Expires',
-		'Active' => 'Active',
-	);
-
-	private static $has_many = array(
-		'Ads' => 'UniadsObject',
-	);
-
-	private static $has_one = array(
-		'Client' => 'UniadsClient',
-	);
-
-	public function getCMSFields() {
-		$fields = parent::getCMSFields();
-
-		$Starts = $fields->fieldByName('Root.Main.Starts');
-		$Starts->setConfig('showcalendar', true);
-		$Starts->setConfig('dateformat', i18n::get_date_format());
-		$Starts->setConfig('datavalueformat', 'yyyy-MM-dd');
-
-		$Expires = $fields->fieldByName('Root.Main.Expires');
-		$Expires->setConfig('showcalendar', true);
-		$Expires->setConfig('dateformat', i18n::get_date_format());
-		$Expires->setConfig('datavalueformat', 'yyyy-MM-dd');
-		$Expires->setConfig('min', date('Y-m-d', strtotime($this->Starts ? $this->Starts : '+1 days')));
-
-		$fields->changeFieldOrder(array(
-			'Title',
-			'ClientID',
-			'Starts',
-			'Expires',
-			'Active',
-		));
-
-		return $fields;
-	}
-
+class UniadsCampaign extends DataObject
+{
+
+    private static $db = array(
+        'Title' => 'Varchar',
+        'Starts' => 'Date',
+        'Expires' => 'Date',
+        'Active' => 'Boolean',
+    );
+
+    private static $summary_fields = array(
+        'Title' => 'Title',
+        'Starts' => 'Starts',
+        'Expires' => 'Expires',
+        'Active' => 'Active',
+    );
+
+    private static $has_many = array(
+        'Ads' => 'UniadsObject',
+    );
+
+    private static $has_one = array(
+        'Client' => 'UniadsClient',
+    );
+
+    public function getCMSFields()
+    {
+        $fields = parent::getCMSFields();
+
+        $Starts = $fields->fieldByName('Root.Main.Starts');
+        $Starts->setConfig('showcalendar', true);
+        $Starts->setConfig('dateformat', i18n::get_date_format());
+        $Starts->setConfig('datavalueformat', 'yyyy-MM-dd');
+
+        $Expires = $fields->fieldByName('Root.Main.Expires');
+        $Expires->setConfig('showcalendar', true);
+        $Expires->setConfig('dateformat', i18n::get_date_format());
+        $Expires->setConfig('datavalueformat', 'yyyy-MM-dd');
+        $Expires->setConfig('min', date('Y-m-d', strtotime($this->Starts ? $this->Starts : '+1 days')));
+
+        $fields->changeFieldOrder(array(
+            'Title',
+            'ClientID',
+            'Starts',
+            'Expires',
+            'Active',
+        ));
+
+        return $fields;
+    }
 }
diff --git a/code/dataobjects/UniadsClick.php b/code/dataobjects/UniadsClick.php
index 75ed141..f3402c1 100644
--- a/code/dataobjects/UniadsClick.php
+++ b/code/dataobjects/UniadsClick.php
@@ -6,6 +6,6 @@
  * @author Marcus Nyeholt <marcus@silverstripe.com.au>
  * @license BSD http://silverstripe.org/BSD-license
  */
-class UniadsClick extends UniadsImpression {
-
+class UniadsClick extends UniadsImpression
+{
 }
diff --git a/code/dataobjects/UniadsClient.php b/code/dataobjects/UniadsClient.php
index a4b3a74..3b4d602 100644
--- a/code/dataobjects/UniadsClient.php
+++ b/code/dataobjects/UniadsClient.php
@@ -7,16 +7,16 @@
  * @author Marcus Nyeholt <marcus@silverstripe.com.au>
  * @license BSD http://silverstripe.org/BSD-license
  */
-class UniadsClient extends DataObject {
+class UniadsClient extends DataObject
+{
 
-	private static $db = array(
-		'Title' => 'Varchar(128)',
-		'ContactEmail' => 'Text',
-	);
-
-	private static $summary_fields = array(
-		'Title',
-		'ContactEmail',
-	);
+    private static $db = array(
+        'Title' => 'Varchar(128)',
+        'ContactEmail' => 'Text',
+    );
 
+    private static $summary_fields = array(
+        'Title',
+        'ContactEmail',
+    );
 }
diff --git a/code/dataobjects/UniadsImpression.php b/code/dataobjects/UniadsImpression.php
index 74c58c1..0281cd8 100644
--- a/code/dataobjects/UniadsImpression.php
+++ b/code/dataobjects/UniadsImpression.php
@@ -7,49 +7,51 @@
  * @author Marcus Nyeholt <marcus@silverstripe.com.au>
  * @license BSD http://silverstripe.org/BSD-license
  */
-class UniadsImpression extends DataObject {
-
-	private static $db = array(
-		'UserAgent' => 'Varchar(128)',
-		'BrowserVersion' => 'Varchar',
-		'Browser' => 'Varchar',
-		'Platform' => 'Varchar',
-		'ViewDayName' => 'Varchar',
-		'ViewMonth' => 'Varchar',
-		'ViewDay' => 'Int',
-		'ViewYear' => 'Int',
-		'Referer' => 'Varchar',
-		'RemoteIP' => 'Varchar',
-	);
-
-	private static $has_one = array(
-		'User' => 'Member',
-		'Ad' => 'UniadsObject',
-	);
-
-	public function onBeforeWrite() {
-		parent::onBeforeWrite();
-		$browser = get_browser_info();
-		$this->UserAgent = $browser['user_agent'];
-		$this->Browser = $browser['name'];
-		$this->BrowserVersion = $browser['version'];
-		$this->Platform = $browser['platform'];
-
-		$this->Referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
-		$this->RemoteIP = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
-		$this->UserID = Member::currentUserID();
-
-		$this->ViewDay = date('d');
-		$this->ViewDayName = date('l');
-		$this->ViewMonth = date('F');
-		$this->ViewYear = date('Y');
-	}
+class UniadsImpression extends DataObject
+{
+
+    private static $db = array(
+        'UserAgent' => 'Varchar(128)',
+        'BrowserVersion' => 'Varchar',
+        'Browser' => 'Varchar',
+        'Platform' => 'Varchar',
+        'ViewDayName' => 'Varchar',
+        'ViewMonth' => 'Varchar',
+        'ViewDay' => 'Int',
+        'ViewYear' => 'Int',
+        'Referer' => 'Varchar',
+        'RemoteIP' => 'Varchar',
+    );
+
+    private static $has_one = array(
+        'User' => 'Member',
+        'Ad' => 'UniadsObject',
+    );
+
+    public function onBeforeWrite()
+    {
+        parent::onBeforeWrite();
+        $browser = get_browser_info();
+        $this->UserAgent = $browser['user_agent'];
+        $this->Browser = $browser['name'];
+        $this->BrowserVersion = $browser['version'];
+        $this->Platform = $browser['platform'];
+
+        $this->Referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
+        $this->RemoteIP = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
+        $this->UserID = Member::currentUserID();
+
+        $this->ViewDay = date('d');
+        $this->ViewDayName = date('l');
+        $this->ViewMonth = date('F');
+        $this->ViewYear = date('Y');
+    }
 }
 
 
 function get_browser_info()
 {
-	$u_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
+    $u_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
 // $u_agent = 'MSIE win32';
 // $u_agent = 'mac os x Safari 2';
 
@@ -57,86 +59,73 @@ function get_browser_info()
 
 // $u_agent = 'linux Chrome 8';
 
-	$bname = 'Unknown';
-	$platform = 'Unknown';
-	$version= "";
-	$ub = "";
-
-	//First get the platform?
-	if (preg_match('/linux/i', $u_agent)) {
-		$platform = 'linux';
-	}
-	elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
-		$platform = 'mac';
-	}
-	elseif (preg_match('/windows|win32/i', $u_agent)) {
-		$platform = 'windows';
-	}
-
-	// Next get the name of the useragent yes seperately and for good reason
-	if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
-	{
-		$bname = 'Internet Explorer';
-		$ub = "MSIE";
-	}
-	elseif(preg_match('/Firefox/i',$u_agent))
-	{
-		$bname = 'Mozilla Firefox';
-		$ub = "Firefox";
-	}
-	elseif(preg_match('/Chrome/i',$u_agent))
-	{
-		$bname = 'Google Chrome';
-		$ub = "Chrome";
-	}
-	elseif(preg_match('/Safari/i',$u_agent))
-	{
-		$bname = 'Apple Safari';
-		$ub = "Safari";
-	}
-	elseif(preg_match('/Opera/i',$u_agent))
-	{
-		$bname = 'Opera';
-		$ub = "Opera";
-	}
-	elseif(preg_match('/Netscape/i',$u_agent))
-	{
-		$bname = 'Netscape';
-		$ub = "Netscape";
-	}
-
-	// finally get the correct version number
-	$known = array('Version', $ub, 'other');
-	$pattern = '#(?P<browser>' . join('|', $known) .
-	')[/ ]+(?P<version>[0-9.|a-zA-Z.]*)#';
-	if (!preg_match_all($pattern, $u_agent, $matches)) {
-		// we have no matching number just continue
-	}
-
-	// see how many we have
-	$i = count($matches['browser']);
-	if ($i != 1) {
-		//we will have two since we are not using 'other' argument yet
-		//see if version is before or after the name
-		if (strripos($u_agent,"Version") < strripos($u_agent, $ub)){
-			$version = isset($matches['version'][0]) ? $matches['version'][0] : '';
-		}
-		else {
-			$version = isset($matches['version'][1]) ? $matches['version'][1] : '';
-		}
-	}
-	else {
-		$version = isset($matches['version'][0]) ? $matches['version'][0] : '';
-	}
-
-	// check if we have a number
-	if ($version==null || $version=="") {$version="?";}
-
-	return array(
-		'user_agent' => $u_agent,
-		'name' => $bname,
-		'version' => $version,
-		'platform' => $platform,
-		'pattern' => $pattern
-	);
-}
\ No newline at end of file
+    $bname = 'Unknown';
+    $platform = 'Unknown';
+    $version= "";
+    $ub = "";
+
+    //First get the platform?
+    if (preg_match('/linux/i', $u_agent)) {
+        $platform = 'linux';
+    } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
+        $platform = 'mac';
+    } elseif (preg_match('/windows|win32/i', $u_agent)) {
+        $platform = 'windows';
+    }
+
+    // Next get the name of the useragent yes seperately and for good reason
+    if (preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent)) {
+        $bname = 'Internet Explorer';
+        $ub = "MSIE";
+    } elseif (preg_match('/Firefox/i', $u_agent)) {
+        $bname = 'Mozilla Firefox';
+        $ub = "Firefox";
+    } elseif (preg_match('/Chrome/i', $u_agent)) {
+        $bname = 'Google Chrome';
+        $ub = "Chrome";
+    } elseif (preg_match('/Safari/i', $u_agent)) {
+        $bname = 'Apple Safari';
+        $ub = "Safari";
+    } elseif (preg_match('/Opera/i', $u_agent)) {
+        $bname = 'Opera';
+        $ub = "Opera";
+    } elseif (preg_match('/Netscape/i', $u_agent)) {
+        $bname = 'Netscape';
+        $ub = "Netscape";
+    }
+
+    // finally get the correct version number
+    $known = array('Version', $ub, 'other');
+    $pattern = '#(?P<browser>' . join('|', $known) .
+    ')[/ ]+(?P<version>[0-9.|a-zA-Z.]*)#';
+    if (!preg_match_all($pattern, $u_agent, $matches)) {
+        // we have no matching number just continue
+    }
+
+    // see how many we have
+    $i = count($matches['browser']);
+    if ($i != 1) {
+        //we will have two since we are not using 'other' argument yet
+        //see if version is before or after the name
+        if (strripos($u_agent, "Version") < strripos($u_agent, $ub)) {
+            $version = isset($matches['version'][0]) ? $matches['version'][0] : '';
+        } else {
+            $version = isset($matches['version'][1]) ? $matches['version'][1] : '';
+        }
+    } else {
+        $version = isset($matches['version'][0]) ? $matches['version'][0] : '';
+    }
+
+    // check if we have a number
+    if ($version==null || $version=="") {
+        $version="?";
+    }
+
+    return array(
+        'user_agent' => $u_agent,
+        'name' => $bname,
+        'version' => $version,
+        'platform' => $platform,
+        'pattern' => $pattern
+    );
+}
diff --git a/code/dataobjects/UniadsObject.php b/code/dataobjects/UniadsObject.php
index b5ec498..b00ca5f 100644
--- a/code/dataobjects/UniadsObject.php
+++ b/code/dataobjects/UniadsObject.php
@@ -8,179 +8,188 @@
  * @author Marcus Nyeholt <marcus@silverstripe.com.au>
  * @license BSD http://silverstripe.org/BSD-license
  */
-class UniadsObject extends DataObject {
-
-	private static $use_js_tracking = true;
-	private static $record_impressions = true;
-	private static $record_impressions_stats = false;
-	private static $record_clicks = true;
-	private static $record_clicks_stats = true;
-
-	private static $files_dir = 'UploadedAds';
-	private static $max_file_size = 2097152;
-
-	private static $db = array(
-		'Title' => 'Varchar',
-		'Starts' => 'Date',
-		'Expires' => 'Date',
-		'Active' => 'Boolean',
-		'TargetURL' => 'Varchar(255)',
-		'NewWindow' => 'Boolean',
-		'AdContent' => 'HTMLText',
-		'ImpressionLimit' => 'Int',
-		'Weight' => 'Double',
-		'Impressions' => 'Int',
-		'Clicks' => 'Int',
-	);
-
-	private static $has_one = array(
-		'File' => 'File',
-		'Zone' => 'UniadsZone',
-		'Campaign' => 'UniadsCampaign',
-		'InternalPage' => 'Page',
-	);
-
-	private static $belongs_many_many = array(
-		'AdInPages' => 'Page',
-	);
-
-
-	private static $defaults = array(
-		'Active' => 0,
-		'NewWindow' => 1,
-		'ImpressionLimit' => 0,
-		'Weight' => 1.0,
-	);
-	private static $searchable_fields = array(
-		'Title',
-	);
-	private static $summary_fields = array(
-		'Title',
-		'Campaign.Title',
-		'Zone.Title',
-		'Impressions',
-		'Clicks',
-	);
-
-
-	public function fieldLabels($includerelations = true) {
-		$labels = parent::fieldLabels($includerelations);
-
-		$labels['Campaign.Title'] = _t('UniadsObject.has_one_Campaign', 'Campaign');
-		$labels['Zone.Title'] = _t('UniadsObject.has_one_Zone', 'Zone');
-		$labels['Impressions'] = _t('UniadsObject.db_Impressions', 'Impressions');
-		$labels['Clicks'] = _t('UniadsObject.db_Clicks', 'Clicks');
-
-		return $labels;
-	}
-
-
-	public function getCMSFields() {
-		$fields = new FieldList();
-		$fields->push(new TabSet('Root', new Tab('Main', _t('SiteTree.TABMAIN', 'Main')
-			, new TextField('Title', _t('UniadsObject.db_Title', 'Title'))
-		)));
-
-		if ($this->ID) {
-			$previewLink = Director::absoluteBaseURL() . 'admin/' . UniadsAdmin::config()->url_segment . '/UniadsObject/preview/' . $this->ID;
-
-			$fields->addFieldToTab('Root.Main', new ReadonlyField('Impressions', _t('UniadsObject.db_Impressions', 'Impressions')), 'Title');
-			$fields->addFieldToTab('Root.Main', new ReadonlyField('Clicks', _t('UniadsObject.db_Clicks', 'Clicks')), 'Title');
-
-			$fields->addFieldsToTab('Root.Main', array(
-				DropdownField::create('CampaignID', _t('UniadsObject.has_one_Campaign', 'Campaign'), DataList::create('UniadsCampaign')->map())->setEmptyString(_t('UniadsObject.Campaign_none', 'none')),
-				DropdownField::create('ZoneID', _t('UniadsObject.has_one_Zone', 'Zone'), DataList::create('UniadsZone')->map())->setEmptyString(_t('UniadsObject.Zone_select', 'select one')),
-				new NumericField('Weight', _t('UniadsObject.db_Weight', 'Weight (controls how often it will be shown relative to others)')),
-				new TextField('TargetURL', _t('UniadsObject.db_TargetURL', 'Target URL')),
-				new Treedropdownfield('InternalPageID', _t('UniadsObject.has_one_InternalPage', 'Internal Page Link'), 'Page'),
-				new CheckboxField('NewWindow', _t('UniadsObject.db_NewWindow', 'Open in a new Window')),
-				$file = new UploadField('File', _t('UniadsObject.has_one_File', 'Advertisement File')),
-				$AdContent = new TextareaField('AdContent', _t('UniadsObject.db_AdContent', 'Advertisement Content')),
-				$Starts = new DateField('Starts', _t('UniadsObject.db_Starts', 'Starts')),
-				$Expires = new DateField('Expires', _t('UniadsObject.db_Expires', 'Expires')),
-				new NumericField('ImpressionLimit', _t('UniadsObject.db_ImpressionLimit', 'Impression Limit')),
-				new CheckboxField('Active', _t('UniadsObject.db_Active', 'Active')),
-				new LiteralField('Preview', '<a href="'.$previewLink.'" target="_blank">' . _t('UniadsObject.Preview', 'Preview this advertisement') . "</a>"),
-			));
-
-			$app_categories = File::config()->app_categories;
-			$file->setFolderName($this->config()->files_dir);
-			$file->getValidator()->setAllowedMaxFileSize(array('*' => $this->config()->max_file_size));
-			$file->getValidator()->setAllowedExtensions(array_merge($app_categories['image'], $app_categories['flash']));
-
-			$AdContent->setRows(10);
-			$AdContent->setColumns(20);
-
-			$Starts->setConfig('showcalendar', true);
-			$Starts->setConfig('dateformat', i18n::get_date_format());
-			$Starts->setConfig('datavalueformat', 'yyyy-MM-dd');
-
-			$Expires->setConfig('showcalendar', true);
-			$Expires->setConfig('dateformat', i18n::get_date_format());
-			$Expires->setConfig('datavalueformat', 'yyyy-MM-dd');
-			$Expires->setConfig('min', date('Y-m-d', strtotime($this->Starts ? $this->Starts : '+1 days')));
-		}
-
-		$this->extend('updateCMSFields', $fields);
-		return $fields;
-	}
-
-
-	/** Returns true if this is an "external" advertisment (e.g., one from Google AdSense).
-	 * "External" advertisements have no target URL or page.
-	 */
-	public function ExternalAd() {
-		if (!$this->InternalPageID && empty($this->TargetURL)) {
-			return true;
-		}
-
-		$file = $this->getComponent('File');
-		if ($file && $file->appCategory() == 'flash') {
-			return true;
-		}
-
-		return false;
-	}
-
-	public function forTemplate() {
-		$template = new SSViewer('UniadsObject');
-		return $template->process($this);
-	}
-
-	public function UseJsTracking() {
-		return $this->config()->use_js_tracking;
-	}
-
-	public function TrackingLink($absolute = false) {
-		return Controller::join_links($absolute ? Director::absoluteBaseURL() : Director::baseURL(), 'uniads-click/go/'.$this->ID);
-	}
-
-	public function Link() {
-		if ($this->UseJsTracking()) {
-			Requirements::javascript(THIRDPARTY_DIR.'/jquery/jquery.js'); // TODO: How about jquery.min.js?
-			Requirements::javascript(ADS_MODULE_DIR.'/javascript/uniads.js');
-
-			$link = Convert::raw2att($this->getTarget());
-		} else {
-			$link = $this->TrackingLink();
-		}
-		return $link;
-	}
-
-	public function getTarget() {
-		return $this->InternalPageID
-			? $this->InternalPage()->AbsoluteLink()
-			: ($this->TargetURL ? (strpos($this->TargetURL, 'http') !== 0 ? 'http://' : '') . $this->TargetURL : false)
-		;
-	}
-
-	public function getContent() {
-		$file = $this->getComponent('File');
-		$zone = $this->getComponent('Zone');
-		if ($file) {
-			if ($file->appCategory() == 'flash') {
-				$src = $this->getTarget() ? HTTP::setGetVar('clickTAG', $this->TrackingLink(true), $file->Filename) : $file->Filename;
-				return '
+class UniadsObject extends DataObject
+{
+
+    private static $use_js_tracking = true;
+    private static $record_impressions = true;
+    private static $record_impressions_stats = false;
+    private static $record_clicks = true;
+    private static $record_clicks_stats = true;
+
+    private static $files_dir = 'UploadedAds';
+    private static $max_file_size = 2097152;
+
+    private static $db = array(
+        'Title' => 'Varchar',
+        'Starts' => 'Date',
+        'Expires' => 'Date',
+        'Active' => 'Boolean',
+        'TargetURL' => 'Varchar(255)',
+        'NewWindow' => 'Boolean',
+        'AdContent' => 'HTMLText',
+        'ImpressionLimit' => 'Int',
+        'Weight' => 'Double',
+        'Impressions' => 'Int',
+        'Clicks' => 'Int',
+    );
+
+    private static $has_one = array(
+        'File' => 'File',
+        'Zone' => 'UniadsZone',
+        'Campaign' => 'UniadsCampaign',
+        'InternalPage' => 'Page',
+    );
+
+    private static $belongs_many_many = array(
+        'AdInPages' => 'Page',
+    );
+
+
+    private static $defaults = array(
+        'Active' => 0,
+        'NewWindow' => 1,
+        'ImpressionLimit' => 0,
+        'Weight' => 1.0,
+    );
+    private static $searchable_fields = array(
+        'Title',
+    );
+    private static $summary_fields = array(
+        'Title',
+        'Campaign.Title',
+        'Zone.Title',
+        'Impressions',
+        'Clicks',
+    );
+
+
+    public function fieldLabels($includerelations = true)
+    {
+        $labels = parent::fieldLabels($includerelations);
+
+        $labels['Campaign.Title'] = _t('UniadsObject.has_one_Campaign', 'Campaign');
+        $labels['Zone.Title'] = _t('UniadsObject.has_one_Zone', 'Zone');
+        $labels['Impressions'] = _t('UniadsObject.db_Impressions', 'Impressions');
+        $labels['Clicks'] = _t('UniadsObject.db_Clicks', 'Clicks');
+
+        return $labels;
+    }
+
+
+    public function getCMSFields()
+    {
+        $fields = new FieldList();
+        $fields->push(new TabSet('Root', new Tab('Main', _t('SiteTree.TABMAIN', 'Main'), new TextField('Title', _t('UniadsObject.db_Title', 'Title'))
+        )));
+
+        if ($this->ID) {
+            $previewLink = Director::absoluteBaseURL() . 'admin/' . UniadsAdmin::config()->url_segment . '/UniadsObject/preview/' . $this->ID;
+
+            $fields->addFieldToTab('Root.Main', new ReadonlyField('Impressions', _t('UniadsObject.db_Impressions', 'Impressions')), 'Title');
+            $fields->addFieldToTab('Root.Main', new ReadonlyField('Clicks', _t('UniadsObject.db_Clicks', 'Clicks')), 'Title');
+
+            $fields->addFieldsToTab('Root.Main', array(
+                DropdownField::create('CampaignID', _t('UniadsObject.has_one_Campaign', 'Campaign'), DataList::create('UniadsCampaign')->map())->setEmptyString(_t('UniadsObject.Campaign_none', 'none')),
+                DropdownField::create('ZoneID', _t('UniadsObject.has_one_Zone', 'Zone'), DataList::create('UniadsZone')->map())->setEmptyString(_t('UniadsObject.Zone_select', 'select one')),
+                new NumericField('Weight', _t('UniadsObject.db_Weight', 'Weight (controls how often it will be shown relative to others)')),
+                new TextField('TargetURL', _t('UniadsObject.db_TargetURL', 'Target URL')),
+                new Treedropdownfield('InternalPageID', _t('UniadsObject.has_one_InternalPage', 'Internal Page Link'), 'Page'),
+                new CheckboxField('NewWindow', _t('UniadsObject.db_NewWindow', 'Open in a new Window')),
+                $file = new UploadField('File', _t('UniadsObject.has_one_File', 'Advertisement File')),
+                $AdContent = new TextareaField('AdContent', _t('UniadsObject.db_AdContent', 'Advertisement Content')),
+                $Starts = new DateField('Starts', _t('UniadsObject.db_Starts', 'Starts')),
+                $Expires = new DateField('Expires', _t('UniadsObject.db_Expires', 'Expires')),
+                new NumericField('ImpressionLimit', _t('UniadsObject.db_ImpressionLimit', 'Impression Limit')),
+                new CheckboxField('Active', _t('UniadsObject.db_Active', 'Active')),
+                new LiteralField('Preview', '<a href="'.$previewLink.'" target="_blank">' . _t('UniadsObject.Preview', 'Preview this advertisement') . "</a>"),
+            ));
+
+            $app_categories = File::config()->app_categories;
+            $file->setFolderName($this->config()->files_dir);
+            $file->getValidator()->setAllowedMaxFileSize(array('*' => $this->config()->max_file_size));
+            $file->getValidator()->setAllowedExtensions(array_merge($app_categories['image'], $app_categories['flash']));
+
+            $AdContent->setRows(10);
+            $AdContent->setColumns(20);
+
+            $Starts->setConfig('showcalendar', true);
+            $Starts->setConfig('dateformat', i18n::get_date_format());
+            $Starts->setConfig('datavalueformat', 'yyyy-MM-dd');
+
+            $Expires->setConfig('showcalendar', true);
+            $Expires->setConfig('dateformat', i18n::get_date_format());
+            $Expires->setConfig('datavalueformat', 'yyyy-MM-dd');
+            $Expires->setConfig('min', date('Y-m-d', strtotime($this->Starts ? $this->Starts : '+1 days')));
+        }
+
+        $this->extend('updateCMSFields', $fields);
+        return $fields;
+    }
+
+
+    /** Returns true if this is an "external" advertisment (e.g., one from Google AdSense).
+     * "External" advertisements have no target URL or page.
+     */
+    public function ExternalAd()
+    {
+        if (!$this->InternalPageID && empty($this->TargetURL)) {
+            return true;
+        }
+
+        $file = $this->getComponent('File');
+        if ($file && $file->appCategory() == 'flash') {
+            return true;
+        }
+
+        return false;
+    }
+
+    public function forTemplate()
+    {
+        $template = new SSViewer('UniadsObject');
+        return $template->process($this);
+    }
+
+    public function UseJsTracking()
+    {
+        return $this->config()->use_js_tracking;
+    }
+
+    public function TrackingLink($absolute = false)
+    {
+        return Controller::join_links($absolute ? Director::absoluteBaseURL() : Director::baseURL(), 'uniads-click/go/'.$this->ID);
+    }
+
+    public function Link()
+    {
+        if ($this->UseJsTracking()) {
+            Requirements::javascript(THIRDPARTY_DIR.'/jquery/jquery.js'); // TODO: How about jquery.min.js?
+            Requirements::javascript(ADS_MODULE_DIR.'/javascript/uniads.js');
+
+            $link = Convert::raw2att($this->getTarget());
+        } else {
+            $link = $this->TrackingLink();
+        }
+        return $link;
+    }
+
+    public function getTarget()
+    {
+        return $this->InternalPageID
+            ? $this->InternalPage()->AbsoluteLink()
+            : ($this->TargetURL ? (strpos($this->TargetURL, 'http') !== 0 ? 'http://' : '') . $this->TargetURL : false)
+        ;
+    }
+
+    public function getContent()
+    {
+        $file = $this->getComponent('File');
+        $zone = $this->getComponent('Zone');
+        if ($file) {
+            if ($file->appCategory() == 'flash') {
+                $src = $this->getTarget() ? HTTP::setGetVar('clickTAG', $this->TrackingLink(true), $file->Filename) : $file->Filename;
+                return '
 					<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="'.$zone->Width.'" height="'.$zone->Height.'" style="display:block;">
 						<param name="movie" value="'.$src.'" />
 						<param name="quality" value="high" />
@@ -196,11 +205,10 @@ public function getContent() {
 						</embed>
 					</object>
 				';
-			} else if ($file->appCategory() == 'image') {
-				return '<img src="'.$file->URL.'" style="width:100%;display:block;" alt="'.$file->Title.'" />';
-			}
-		}
-		return $this->AdContent;
-	}
-
+            } elseif ($file->appCategory() == 'image') {
+                return '<img src="'.$file->URL.'" style="width:100%;display:block;" alt="'.$file->Title.'" />';
+            }
+        }
+        return $this->AdContent;
+    }
 }
diff --git a/code/dataobjects/UniadsZone.php b/code/dataobjects/UniadsZone.php
index 7acd4da..4da3717 100644
--- a/code/dataobjects/UniadsZone.php
+++ b/code/dataobjects/UniadsZone.php
@@ -7,83 +7,87 @@
  * @license BSD http://silverstripe.org/BSD-license
  */
 
-class UniadsZone extends DataObject {
-
-	private static $db = array(
-		'Title' => 'Varchar',
-		'ZoneWidth' => 'Varchar(6)',
-		'ZoneHeight' => 'Varchar(6)',
-		'Order' => 'Int',
-		'Active' => 'Boolean',
-	);
-
-	private static $summary_fields = array(
-		'Title',
-		'ParentZone.Title',
-		'Order',
-		'Active',
-	);
-
-	private static $has_one = array(
-		'ParentZone' => 'UniadsZone',
-	);
-
-	private static $has_many = array(
-		'Ads' => 'UniadsObject',
-		'ChildZones' => 'UniadsZone',
-	);
-
-	private static $indexes = array(
-		'Title' => true,
-	);
-
-	private static $defaults = array(
-		'Active' => 1,
-	);
-
-	private static $default_records = array(
-		array('Title' => 'Top', 'ZoneWidth' => '500', 'ZoneHeight' => '90'),
-		array('Title' => 'Right', 'ZoneWidth' => '160', 'ZoneHeight' => '600'),
-	);
-
-	private static $default_sort = 'ParentZoneID asc, Order asc, ID asc';
-
-	public function getWidth(){
-		return $this->ZoneWidth . (ctype_digit($this->ZoneWidth) ? 'px' : '');
-	}
-
-	public function getHeight(){
-		return $this->ZoneHeight . (ctype_digit($this->ZoneHeight) ? 'px' : '');
-	}
-
-	public function fieldLabels($includerelations = true) {
-		$labels = parent::fieldLabels($includerelations);
-
-		$labels['ParentZone.Title'] = _t('UniadsZone.has_one_ParentZone', 'Parent Zone');
-
-		return $labels;
-	}
-
-	public function getCMSFields() {
-		$fields = parent::getCMSFields();
-
-		if (!$this->ParentZoneID) {
-			$fields->removeByName('Order');
-		}
-
-		if ($this->ChildZones()->Count() > 0) {
-			$fields->removeByName('ParentZoneID');
-		}
-
-		if (($field = $fields->dataFieldByName('ParentZoneID'))) {
-			$field->setSource(
-				DataList::create('UniadsZone')
-				->where("ID != " . $this->ID . " and (ParentZoneID is null or ParentZoneID = 0)")
-				->map()
-			);
-		}
-
-		return $fields;
-	}
-
+class UniadsZone extends DataObject
+{
+
+    private static $db = array(
+        'Title' => 'Varchar',
+        'ZoneWidth' => 'Varchar(6)',
+        'ZoneHeight' => 'Varchar(6)',
+        'Order' => 'Int',
+        'Active' => 'Boolean',
+    );
+
+    private static $summary_fields = array(
+        'Title',
+        'ParentZone.Title',
+        'Order',
+        'Active',
+    );
+
+    private static $has_one = array(
+        'ParentZone' => 'UniadsZone',
+    );
+
+    private static $has_many = array(
+        'Ads' => 'UniadsObject',
+        'ChildZones' => 'UniadsZone',
+    );
+
+    private static $indexes = array(
+        'Title' => true,
+    );
+
+    private static $defaults = array(
+        'Active' => 1,
+    );
+
+    private static $default_records = array(
+        array('Title' => 'Top', 'ZoneWidth' => '500', 'ZoneHeight' => '90'),
+        array('Title' => 'Right', 'ZoneWidth' => '160', 'ZoneHeight' => '600'),
+    );
+
+    private static $default_sort = 'ParentZoneID asc, Order asc, ID asc';
+
+    public function getWidth()
+    {
+        return $this->ZoneWidth . (ctype_digit($this->ZoneWidth) ? 'px' : '');
+    }
+
+    public function getHeight()
+    {
+        return $this->ZoneHeight . (ctype_digit($this->ZoneHeight) ? 'px' : '');
+    }
+
+    public function fieldLabels($includerelations = true)
+    {
+        $labels = parent::fieldLabels($includerelations);
+
+        $labels['ParentZone.Title'] = _t('UniadsZone.has_one_ParentZone', 'Parent Zone');
+
+        return $labels;
+    }
+
+    public function getCMSFields()
+    {
+        $fields = parent::getCMSFields();
+
+        if (!$this->ParentZoneID) {
+            $fields->removeByName('Order');
+        }
+
+        if ($this->ChildZones()->Count() > 0) {
+            $fields->removeByName('ParentZoneID');
+        }
+
+        if (($field = $fields->dataFieldByName('ParentZoneID'))) {
+            $field->setSource(
+                DataList::create('UniadsZone')
+                ->where("ID != " . $this->ID . " and (ParentZoneID is null or ParentZoneID = 0)")
+                ->map()
+            );
+        }
+
+        return $fields;
+    }
 }
diff --git a/code/extensions/UniadsExtension.php b/code/extensions/UniadsExtension.php
index e2ccc70..4c80250 100644
--- a/code/extensions/UniadsExtension.php
+++ b/code/extensions/UniadsExtension.php
@@ -8,88 +8,92 @@
  * @author Marcus Nyeholt <marcus@silverstripe.com.au>
  * @license BSD http://silverstripe.org/BSD-license
  */
-class UniadsExtension extends DataExtension {
-
-	private static $db = array(
-		'InheritSettings' => 'Boolean',
-	);
-	private static $defaults = array(
-		'InheritSettings' => true
-	);
-	private static $many_many = array(
-		'Ads' => 'UniadsObject',
-	);
-	private static $has_one = array(
-		'UseCampaign' => 'UniadsCampaign',
-	);
-
-	private function getListboxOptions($o) {
-		$list = new DataList($o);
-		return array('' => '') + $list->map()->toArray();
-	}
-
-	public function updateCMSFields(FieldList $fields) {
-		parent::updateCMSFields($fields);
-
-		$fields->findOrMakeTab('Root.Advertisements', _t('UniadsObject.PLURALNAME', 'Advertisements'));
-		$fields->addFieldToTab('Root.Advertisements', new CheckboxField('InheritSettings', _t('UniadsObject.InheritSettings', 'Inherit parent settings')));
-
-		if (!$this->owner->InheritSettings) {
-			$conf = GridFieldConfig_RelationEditor::create();
-			$conf->getComponentByType('GridFieldAddExistingAutocompleter')->setSearchFields(array('Title'));
-			$grid = new GridField("Advertisements", _t('UniadsObject.PLURALNAME', 'Advertisements'), $this->owner->Ads(), $conf);
-			$fields->addFieldToTab("Root.Advertisements", $grid);
-			$fields->addFieldToTab('Root.Advertisements', new DropdownField('UseCampaignID', _t('UniadsObject.UseCampaign', 'Use Campaign'), $this->getListboxOptions('UniadsCampaign')));
-		}
-	}
-
-	/** Displays a randomly chosen advertisement of the specified dimensions.
-	 *
-	 * @param zone of the advertisement
-	 */
-	public function DisplayAd($zone) {
-		$ad = null;
-
-		if ($zone) {
-			if (!is_object($zone)) {
-				$zone = UniadsZone::get()
-					->filter(array(
-						'Title' => $zone,
-						'Active' => 1
-					))
-					->first();
-			}
-			if ($zone) {
-				$toUse = $this->owner;
-				if ($toUse->InheritSettings) {
-					while ($toUse->ParentID) {
-						if (!$toUse->InheritSettings) {
-							break;
-						}
-						$toUse = $toUse->Parent();
-					}
-					if(!$toUse->ParentID && $toUse->InheritSettings) {
-						$toUse = null;
-					}
-				}
-
-				$page_related = "and not exists (select * from Page_Ads pa where pa.UniadsObjectID = UniadsObject.ID)";
-				$campaign = '';
-				if ($toUse) {
-					$page_related = "and (
+class UniadsExtension extends DataExtension
+{
+
+    private static $db = array(
+        'InheritSettings' => 'Boolean',
+    );
+    private static $defaults = array(
+        'InheritSettings' => true
+    );
+    private static $many_many = array(
+        'Ads' => 'UniadsObject',
+    );
+    private static $has_one = array(
+        'UseCampaign' => 'UniadsCampaign',
+    );
+
+    private function getListboxOptions($o)
+    {
+        $list = new DataList($o);
+        return array('' => '') + $list->map()->toArray();
+    }
+
+    public function updateCMSFields(FieldList $fields)
+    {
+        parent::updateCMSFields($fields);
+
+        $fields->findOrMakeTab('Root.Advertisements', _t('UniadsObject.PLURALNAME', 'Advertisements'));
+        $fields->addFieldToTab('Root.Advertisements', new CheckboxField('InheritSettings', _t('UniadsObject.InheritSettings', 'Inherit parent settings')));
+
+        if (!$this->owner->InheritSettings) {
+            $conf = GridFieldConfig_RelationEditor::create();
+            $conf->getComponentByType('GridFieldAddExistingAutocompleter')->setSearchFields(array('Title'));
+            $grid = new GridField("Advertisements", _t('UniadsObject.PLURALNAME', 'Advertisements'), $this->owner->Ads(), $conf);
+            $fields->addFieldToTab("Root.Advertisements", $grid);
+            $fields->addFieldToTab('Root.Advertisements', new DropdownField('UseCampaignID', _t('UniadsObject.UseCampaign', 'Use Campaign'), $this->getListboxOptions('UniadsCampaign')));
+        }
+    }
+
+    /** Displays a randomly chosen advertisement of the specified dimensions.
+     *
+     * @param zone of the advertisement
+     */
+    public function DisplayAd($zone)
+    {
+        $ad = null;
+
+        if ($zone) {
+            if (!is_object($zone)) {
+                $zone = UniadsZone::get()
+                    ->filter(array(
+                        'Title' => $zone,
+                        'Active' => 1
+                    ))
+                    ->first();
+            }
+            if ($zone) {
+                $toUse = $this->owner;
+                if ($toUse->InheritSettings) {
+                    while ($toUse->ParentID) {
+                        if (!$toUse->InheritSettings) {
+                            break;
+                        }
+                        $toUse = $toUse->Parent();
+                    }
+                    if (!$toUse->ParentID && $toUse->InheritSettings) {
+                        $toUse = null;
+                    }
+                }
+
+                $page_related = "and not exists (select * from Page_Ads pa where pa.UniadsObjectID = UniadsObject.ID)";
+                $campaign = '';
+                if ($toUse) {
+                    $page_related = "and (
 						exists (select * from Page_Ads pa where pa.UniadsObjectID = UniadsObject.ID and pa.PageID = ".$toUse->ID.")
 						or not exists (select * from Page_Ads pa where pa.UniadsObjectID = UniadsObject.ID)
 					)";
-					if ($toUse->UseCampaignID) {
-						$campaign = "and c.ID = '" . $toUse->UseCampaignID . "'";
-					}
-				}
+                    if ($toUse->UseCampaignID) {
+                        $campaign = "and c.ID = '" . $toUse->UseCampaignID . "'";
+                    }
+                }
 
-				$base_from = "
+                $base_from = "
 					UniadsObject
 						left join UniadsCampaign c on c.ID = UniadsObject.CampaignID
 				";
-				$base_where = "
+                $base_where = "
 					UniadsObject.ZoneID = '" . $zone->ID . "'
 					".$page_related."
 					and (c.ID is null or (
@@ -102,16 +106,14 @@ public function DisplayAd($zone) {
 					and (UniadsObject.Expires >= '" . date('Y-m-d') . "' or UniadsObject.Expires = '' or UniadsObject.Expires is null)
 					and UniadsObject.Active = '1'
 				";
-				$subbase_where = preg_replace_callback(
-					'/(?<!\w)(UniadsObject|c)\./'
-					, function ($m) { return str_repeat($m[1], 2).'.'; }
-					, $base_where
-				);
-
-				$sqlQuery = new SQLQuery(
-					$select = 'UniadsObject.ID',
-					$from = array($base_from),
-					$where = $base_where . "
+                $subbase_where = preg_replace_callback(
+                    '/(?<!\w)(UniadsObject|c)\./', function ($m) { return str_repeat($m[1], 2).'.'; }, $base_where
+                );
+
+                $sqlQuery = new SQLQuery(
+                    $select = 'UniadsObject.ID',
+                    $from = array($base_from),
+                    $where = $base_where . "
 						and (UniadsObject.ImpressionLimit = 0 or UniadsObject.ImpressionLimit > UniadsObject.Impressions)
 						and UniadsObject.Weight >= (rand() * (
 							select max(UniadsObjectUniadsObject.Weight)
@@ -119,48 +121,47 @@ public function DisplayAd($zone) {
 								left join UniadsCampaign cc on cc.ID = UniadsObjectUniadsObject.CampaignID
 							where " . $subbase_where . "
 						))",
-					$order = "rand()",
-					$limit = 1
-				);
-				singleton('UniadsObject')->extend('augmentSQL', $sqlQuery);
-				//echo $sqlQuery->sql();
-				$result = $sqlQuery->execute();
-				if($result && count($result) > 0) {
-					$row = $result->First();
-					if (isset($row['ID']) && $row['ID'] !== '') {
-						$ad = UniadsObject::get()->byID($row['ID']);
-						// now we can log impression
-						$conf = UniadsObject::config();
-						if ($conf->record_impressions) {
-							$ad->Impressions++;
-							$ad->write();
-						}
-						if ($conf->record_impressions_stats) {
-							$imp = new UniadsImpression;
-							$imp->AdID = $ad->ID;
-							$imp->write();
-						}
-					}
-				}
-			}
-		}
-
-		if (!$ad) {
-			// Show an empty advert
-			$ad = new UniadsObject();
-		}
-
-		$output = $ad->forTemplate();
-
-		if ($zone) {
-			foreach ($zone->ChildZones()->sort('Order') as $child) {
-				if ($child->Active) {
-					$output .= $this->DisplayAd($child);
-				}
-			}
-		}
-
-		return $output;
-	}
-
+                    $order = "rand()",
+                    $limit = 1
+                );
+                singleton('UniadsObject')->extend('augmentSQL', $sqlQuery);
+                //echo $sqlQuery->sql();
+                $result = $sqlQuery->execute();
+                if ($result && count($result) > 0) {
+                    $row = $result->First();
+                    if (isset($row['ID']) && $row['ID'] !== '') {
+                        $ad = UniadsObject::get()->byID($row['ID']);
+                        // now we can log impression
+                        $conf = UniadsObject::config();
+                        if ($conf->record_impressions) {
+                            $ad->Impressions++;
+                            $ad->write();
+                        }
+                        if ($conf->record_impressions_stats) {
+                            $imp = new UniadsImpression;
+                            $imp->AdID = $ad->ID;
+                            $imp->write();
+                        }
+                    }
+                }
+            }
+        }
+
+        if (!$ad) {
+            // Show an empty advert
+            $ad = new UniadsObject();
+        }
+
+        $output = $ad->forTemplate();
+
+        if ($zone) {
+            foreach ($zone->ChildZones()->sort('Order') as $child) {
+                if ($child->Active) {
+                    $output .= $this->DisplayAd($child);
+                }
+            }
+        }
+
+        return $output;
+    }
 }