From 35128ef2c95d8f76afd3edea594623cc265da673 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tobias=20H=C3=B6=C3=9Fl?= <tobias@hoessl.eu>
Date: Mon, 27 Feb 2012 22:01:17 +0000
Subject: [PATCH 01/10] Avoid a Notice

---
 include/event.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/include/event.php b/include/event.php
index 4a9a9a004..29202badd 100755
--- a/include/event.php
+++ b/include/event.php
@@ -163,7 +163,7 @@ function bbtoevent($s) {
 	if(preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is",$s,$match))
 		$ev['adjust'] = $match[1];
 	$match = '';
-	$ev['nofinish'] = (($ev['start'] && (!x($ev, 'finish') || !$ev['finish'])) ? 1 : 0);
+	$ev['nofinish'] = (((x($ev, 'start') && $ev['start']) && (!x($ev, 'finish') || !$ev['finish'])) ? 1 : 0);
 	return $ev;
 
 }

From e33c2b8f89d0174b6b2bcbd31d8d89c2ee664340 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tobias=20H=C3=B6=C3=9Fl?= <tobias@hoessl.eu>
Date: Mon, 27 Feb 2012 22:08:00 +0000
Subject: [PATCH 02/10] Avoid a Notice

---
 include/items.php | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/include/items.php b/include/items.php
index 7d52571c2..5452dfbda 100755
--- a/include/items.php
+++ b/include/items.php
@@ -682,7 +682,7 @@ function item_store($arr,$force_parent = false) {
 		unset($arr['dsprsig']);
 	}
 
-	if($arr['gravity'])
+	if(x($arr, 'gravity'))
 		$arr['gravity'] = intval($arr['gravity']);
 	elseif($arr['parent-uri'] === $arr['uri'])
 		$arr['gravity'] = 0;
@@ -800,6 +800,8 @@ function item_store($arr,$force_parent = false) {
 				logger('item_store: item parent was not found - ignoring item');
 				return 0;
 			}
+			
+			$parent_deleted = 0;
 		}
 	}
 

From 7c30fca98186538eff731519bdd0c76527237192 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tobias=20H=C3=B6=C3=9Fl?= <tobias@hoessl.eu>
Date: Mon, 27 Feb 2012 22:17:57 +0000
Subject: [PATCH 03/10] Avoid a Notice

---
 boot.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/boot.php b/boot.php
index 54f318e5e..c89dae27c 100755
--- a/boot.php
+++ b/boot.php
@@ -1335,7 +1335,7 @@ function profile_tabs($a, $is_owner=False, $nickname=Null){
 		array(
 			'label' => t('Profile'),
 			'url' 	=> $url.'/?tab=profile',
-			'sel'	=> (($tab=='profile')?'active':''),
+			'sel'	=> ((isset($tab) && $tab=='profile')?'active':''),
 		),
 		array(
 			'label' => t('Photos'),

From e55d13c2b4425183dde64da8ca27c794f4c04900 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tobias=20H=C3=B6=C3=9Fl?= <tobias@hoessl.eu>
Date: Tue, 28 Feb 2012 12:56:16 +0000
Subject: [PATCH 04/10] Avoid a notice

---
 include/items.php | 1 +
 1 file changed, 1 insertion(+)

diff --git a/include/items.php b/include/items.php
index 5452dfbda..5268dfc1d 100755
--- a/include/items.php
+++ b/include/items.php
@@ -742,6 +742,7 @@ function item_store($arr,$force_parent = false) {
 
 	if($arr['parent-uri'] === $arr['uri']) {
 		$parent_id = 0;
+		$parent_deleted = 0;
 		$allow_cid = $arr['allow_cid'];
 		$allow_gid = $arr['allow_gid'];
 		$deny_cid  = $arr['deny_cid'];

From 1204210c69eade767bb19af5a5a18cee4a9db215 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tobias=20H=C3=B6=C3=9Fl?= <tobias@hoessl.eu>
Date: Tue, 28 Feb 2012 13:01:58 +0000
Subject: [PATCH 05/10]  wasn't actually changed before

---
 include/conversation.php | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/include/conversation.php b/include/conversation.php
index 53369cf20..6f0dc3687 100755
--- a/include/conversation.php
+++ b/include/conversation.php
@@ -976,8 +976,8 @@ function conv_sort($arr,$order) {
 		usort($parents,'sort_thr_commented');
 
 	if(count($parents))
-		foreach($parents as $x) 
-			$x['children'] = array();
+		foreach($parents as $i=>$_x) 
+			$parents[$i]['children'] = array();
 
 	foreach($arr as $x) {
 		if($x['id'] != $x['parent']) {

From f48556cbc08c0600e256f5964a553c666ee66372 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tobias=20H=C3=B6=C3=9Fl?= <tobias@hoessl.eu>
Date: Tue, 28 Feb 2012 13:40:41 +0000
Subject: [PATCH 06/10] contact.network is used later to check if a direct link
 or a redirect by /redir/contactid should be used

---
 mod/message.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/mod/message.php b/mod/message.php
index 4b494e906..e293d62d9 100755
--- a/mod/message.php
+++ b/mod/message.php
@@ -176,7 +176,7 @@ function message_content(&$a) {
 			$a->set_pager_total($r[0]['total']);
 	
 		$r = q("SELECT max(`mail`.`created`) AS `mailcreated`, min(`mail`.`seen`) AS `mailseen`, 
-			`mail`.* , `contact`.`name`, `contact`.`url`, `contact`.`thumb` 
+			`mail`.* , `contact`.`name`, `contact`.`url`, `contact`.`thumb` , `contact`.`network`  
 			FROM `mail` LEFT JOIN `contact` ON `mail`.`contact-id` = `contact`.`id` 
 			WHERE `mail`.`uid` = %d AND `from-url` $eq '%s' GROUP BY `parent-uri` ORDER BY `created` DESC  LIMIT %d , %d ",
 			intval(local_user()),

From 36a1a43f06dc2a0d55463c83154cce55fa3948ad Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tobias=20H=C3=B6=C3=9Fl?= <tobias@hoessl.eu>
Date: Tue, 28 Feb 2012 13:42:12 +0000
Subject: [PATCH 07/10] Avoid notices

---
 boot.php             | 2 +-
 mod/dfrn_request.php | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/boot.php b/boot.php
index c89dae27c..e39504e11 100755
--- a/boot.php
+++ b/boot.php
@@ -1209,7 +1209,7 @@ function current_theme(){
 	$a = get_app();
 	
 	$system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
-	$theme_name = ((is_array($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
+	$theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
 	
 	if($theme_name && file_exists('view/theme/' . $theme_name . '/style.css'))
 		return($theme_name);
diff --git a/mod/dfrn_request.php b/mod/dfrn_request.php
index bc159137d..452fec166 100755
--- a/mod/dfrn_request.php
+++ b/mod/dfrn_request.php
@@ -43,7 +43,7 @@ function dfrn_request_post(&$a) {
 		return;
 
 
-	if($_POST['cancel']) {
+	if(x($_POST, 'cancel')) {
 		goaway(z_root());
 	} 
 

From 5bb8ed4b8b5310acc8556ef2fba7b3958284b2a6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tobias=20H=C3=B6=C3=9Fl?= <tobias@hoessl.eu>
Date: Tue, 28 Feb 2012 21:56:42 +0000
Subject: [PATCH 08/10] Mostly some checks in order to avoid Notices; 1 real
 bugfix in /mod/network.php

---
 include/conversation.php       |  5 +++--
 include/oembed.php             |  2 +-
 include/template_processor.php |  9 +++++++--
 mod/network.php                | 14 ++++++++------
 4 files changed, 19 insertions(+), 11 deletions(-)

diff --git a/include/conversation.php b/include/conversation.php
index 9f564843e..bd9b11bee 100755
--- a/include/conversation.php
+++ b/include/conversation.php
@@ -373,7 +373,8 @@ function conversation(&$a, $items, $mode, $update, $preview = false) {
 						$comments[$item['parent']] = 1;
 					else
 						$comments[$item['parent']] += 1;
-				}
+				} elseif(! x($comments,$item['parent'])) 
+					$comments[$item['parent']] = 0; // avoid notices later on
 			}
 
 			// map all the like/dislike activities for each parent item 
@@ -921,7 +922,7 @@ function status_editor($a,$x, $notes_cid = 0, $popup=false) {
 	$o .= replace_macros($tpl,array(
 		'$return_path' => $a->cmd,
 		'$action' =>  $a->get_baseurl().'/item',
-		'$share' => (($x['button']) ? $x['button'] : t('Share')),
+		'$share' => (x($x,'button') ? $x['button'] : t('Share')),
 		'$upload' => t('Upload photo'),
 		'$shortupload' => t('upload photo'),
 		'$attach' => t('Attach file'),
diff --git a/include/oembed.php b/include/oembed.php
index 5c3c595f5..52068efc7 100755
--- a/include/oembed.php
+++ b/include/oembed.php
@@ -62,7 +62,7 @@ function oembed_fetch_url($embedurl){
 	
 function oembed_format_object($j){
 	$embedurl = $j->embedurl;
-	$jhtml = oembed_iframe($j->embedurl,$j->width,$j->height );
+	$jhtml = oembed_iframe($j->embedurl,(isset($j->width) ? $j->width : null), (isset($j->height) ? $j->height : null) );
 	$ret="<span class='oembed ".$j->type."'>";
 	switch ($j->type) {
 		case "video": {
diff --git a/include/template_processor.php b/include/template_processor.php
index 28c3f07dd..7a4cba64e 100755
--- a/include/template_processor.php
+++ b/include/template_processor.php
@@ -92,8 +92,13 @@
 		 */
 		private function _replcb_for($args){
 			$m = array_map('trim', explode(" as ", $args[2]));
-			list($keyname, $varname) = explode("=>",$m[1]);
-			if (is_null($varname)) { $varname=$keyname; $keyname=""; }
+			$x = explode("=>",$m[1]);
+			if (count($x) == 1) {
+				$varname = $x[0];
+				$keyname = "";
+			} else {
+				list($keyname, $varname) = $x;
+			}
 			if ($m[0]=="" || $varname=="" || is_null($varname)) die("template error: 'for ".$m[0]." as ".$varname."'") ;
 			//$vals = $this->r[$m[0]];
 			$vals = $this->_get_var($m[0]);
diff --git a/mod/network.php b/mod/network.php
index 03a671b61..26265f5a0 100755
--- a/mod/network.php
+++ b/mod/network.php
@@ -44,7 +44,7 @@ function network_init(&$a) {
 	}
 	
 	$a->page['aside'] .= group_side('network','network',true,$group_id);
-	$a->page['aside'] .= networks_widget($a->get_baseurl() . '/network',(($_GET['nets']) ? $_GET['nets'] : ''));
+	$a->page['aside'] .= networks_widget($a->get_baseurl() . '/network',(x($_GET, 'nets') ? $_GET['nets'] : ''));
 	$a->page['aside'] .= saved_searches($search);
 
 }
@@ -130,15 +130,15 @@ function network_content(&$a, $update = 0) {
 		$starred_active = 'active';
 	}
 	
-	if($_GET['bmark']) {
+	if(x($_GET,'bmark')) {
 		$bookmarked_active = 'active';
 	}
 
-	if($_GET['conv']) {
+	if(x($_GET,'conv')) {
 		$conv_active = 'active';
 	}
 
-	if($_GET['spam']) {
+	if(x($_GET,'spam')) {
 		$spam_active = 'active';
 	}
 
@@ -245,7 +245,7 @@ function network_content(&$a, $update = 0) {
 		$def_acl = array('allow_cid' => '<' . intval($cid) . '>');
 
 	if(! $update) {
-		if(group) {
+		if($group) {
 			if(($t = group_public_members($group)) && (! get_pconfig(local_user(),'system','nowarn_insecure'))) {
 				notice( sprintf( tt('Warning: This group contains %s member from an insecure network.',
 									'Warning: This group contains %s members from an insecure network.',
@@ -492,7 +492,9 @@ function network_content(&$a, $update = 0) {
 
 			$items = conv_sort($items,$ordering);
 
-		}	
+		} else {
+			$items = array();
+		}
 	}
 
 

From 02a9fd5dc1d1d9e848e2f406f2e13c4cf0ce228b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tobias=20H=C3=B6=C3=9Fl?= <tobias@hoessl.eu>
Date: Sat, 3 Mar 2012 10:44:34 +0000
Subject: [PATCH 09/10] A 'PHP Fatal error:  Call to a member function
 getElementsByTagName() on a non-object in mod/parse_url.php on line 191'
 occurred when the linked HTML-File doesn't have a HEAD. The HTML-file couln't
 be link to in the editor therefore.

---
 mod/parse_url.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/mod/parse_url.php b/mod/parse_url.php
index e0b378f68..27dac4d5d 100755
--- a/mod/parse_url.php
+++ b/mod/parse_url.php
@@ -188,7 +188,7 @@ function parse_url_content(&$a) {
 
 	if(! $text) {
 		logger('parsing meta');
-		$items = $domhead->getElementsByTagName('meta');
+		$items = (isset($domhead) && is_object($domhead) ? $domhead->getElementsByTagName('meta') : null);
 		if($items) {
 			foreach($items as $item) {
 				$property = $item->getAttribute('property');

From 59766b944c9ea3a45b1d7e8593f7bb5d4a0b8445 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tobias=20H=C3=B6=C3=9Fl?= <tobias@hoessl.eu>
Date: Mon, 12 Mar 2012 20:17:37 +0000
Subject: [PATCH 10/10] Some security against XSRF-attacks

---
 include/security.php            | 46 +++++++++++++++++++++++++
 mod/profile_photo.php           | 18 ++++++----
 mod/profiles.php                | 26 ++++++++++++---
 mod/settings.php                | 59 +++++++++++++++++++++------------
 view/cropbody.tpl               |  1 +
 view/profile_edit.tpl           |  5 +--
 view/profile_listing_header.tpl |  2 +-
 view/profile_photo.tpl          |  1 +
 view/settings.tpl               |  2 +-
 view/settings_addons.tpl        |  1 +
 view/settings_connectors.tpl    |  1 +
 view/settings_oauth.tpl         |  5 +--
 view/settings_oauth_edit.tpl    |  2 ++
 13 files changed, 131 insertions(+), 38 deletions(-)

diff --git a/include/security.php b/include/security.php
index 8c536b656..6ea515bff 100755
--- a/include/security.php
+++ b/include/security.php
@@ -288,3 +288,49 @@ function item_permissions_sql($owner_id,$remote_verified = false,$groups = null)
 }
 
 
+/*
+ * Functions used to protect against Cross-Site Request Forgery
+ * The security token has to base on at least one value that an attacker can't know - here it's the session ID and the private key.
+ * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
+ * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
+ * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
+ *    A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
+ *    If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
+ *    Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
+ *    so this mechanism brings in some damage control (the attacker would be able to forge a request to a form of this type, but not to forms of other types).
+ */ 
+function get_form_security_token($typename = "") {
+	$a = get_app();
+	
+	$timestamp = time();
+	$sec_hash = hash('whirlpool', $a->user["guid"] . $a->user["prvkey"] . session_id() . $timestamp . $typename);
+	
+	return $timestamp . "." . $sec_hash;
+}
+
+function check_form_security_token($typename = "", $formname = 'form_security_token') {
+	if (!x($_REQUEST, $formname)) return false;
+	$hash = $_REQUEST[$formname];
+	
+	$max_livetime = 10800; // 3 hours
+	
+	$a = get_app();
+	
+	$x = explode(".", $hash);
+	if (time() > (IntVal($x[0]) + $max_livetime)) return false;
+	
+	$sec_hash = hash('whirlpool', $a->user["guid"] . $a->user["prvkey"] . session_id() . $x[0] . $typename);
+	
+	return ($sec_hash == $x[1]);
+}
+
+function check_form_security_std_err_msg() {
+	return t('The form security token was not correct. This probably happened because the form has been opened for too long (>3 hours) before subitting it.') . EOL;
+}
+function check_form_security_token_redirectOnErr($err_redirect, $typename = "", $formname = 'form_security_token') {
+	if (!check_form_security_token($typename, $formname)) {
+		$a = get_app();
+		notice( check_form_security_std_err_msg() );
+		goaway($a->get_baseurl() . $err_redirect );
+	}
+}
diff --git a/mod/profile_photo.php b/mod/profile_photo.php
index e3dbdaf39..d1fd08eba 100755
--- a/mod/profile_photo.php
+++ b/mod/profile_photo.php
@@ -15,11 +15,13 @@ function profile_photo_init(&$a) {
 
 function profile_photo_post(&$a) {
 
-        if(! local_user()) {
-                notice ( t('Permission denied.') . EOL );
-                return;
-        }
-
+	if(! local_user()) {
+		notice ( t('Permission denied.') . EOL );
+		return;
+	}
+	
+	check_form_security_token_redirectOnErr('/profile_photo', 'profile_photo');
+        
 	if((x($_POST,'cropfinal')) && ($_POST['cropfinal'] == 1)) {
 
 		// phase 2 - we have finished cropping
@@ -148,7 +150,9 @@ function profile_photo_content(&$a) {
 			notice( t('Permission denied.') . EOL );
 			return;
 		};
-			
+		
+		check_form_security_token_redirectOnErr('/profile_photo', 'profile_photo');
+        
 		$resource_id = $a->argv[2];
 		//die(":".local_user());
 		$r=q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' ORDER BY `scale` ASC",
@@ -203,6 +207,7 @@ function profile_photo_content(&$a) {
 			'$lbl_upfile' => t('Upload File:'),
 			'$title' => t('Upload Profile Photo'),
 			'$submit' => t('Upload'),
+			'$form_security_token' => get_form_security_token("profile_photo"),
 			'$select' => sprintf('%s %s', t('or'), ($newuser) ? '<a href="' . $a->get_baseurl() . '">' . t('skip this step') . '</a>' : '<a href="'. $a->get_baseurl() . '/photos/' . $a->user['nickname'] . '">' . t('select a photo from your photo albums') . '</a>')
 		));
 
@@ -218,6 +223,7 @@ function profile_photo_content(&$a) {
 			'$image_url' => $a->get_baseurl() . '/photo/' . $filename,
 			'$title' => t('Crop Image'),
 			'$desc' => t('Please adjust the image cropping for optimum viewing.'),
+			'$form_security_token' => get_form_security_token("profile_photo"),
 			'$done' => t('Done Editing')
 		));
 		return $o;
diff --git a/mod/profiles.php b/mod/profiles.php
index ccd7d5474..b307a2d43 100755
--- a/mod/profiles.php
+++ b/mod/profiles.php
@@ -21,6 +21,9 @@ function profiles_post(&$a) {
 			notice( t('Profile not found.') . EOL);
 			return;
 		}
+		
+		check_form_security_token_redirectOnErr('/profiles', 'profile_edit');
+		
 		$is_default = (($orig[0]['is-default']) ? 1 : 0);
 
 		$profile_name = notags(trim($_POST['profile_name']));
@@ -240,6 +243,8 @@ function profiles_content(&$a) {
 			goaway($a->get_baseurl() . '/profiles');
 			return; // NOTREACHED
 		}
+		
+		check_form_security_token_redirectOnErr('/profiles', 'profile_drop', 't');
 
 		// move every contact using this profile as their default to the user default
 
@@ -264,6 +269,8 @@ function profiles_content(&$a) {
 
 
 	if(($a->argc > 1) && ($a->argv[1] === 'new')) {
+		
+		check_form_security_token_redirectOnErr('/profiles', 'profile_new', 't');
 
 		$r0 = q("SELECT `id` FROM `profile` WHERE `uid` = %d",
 			intval(local_user()));
@@ -291,10 +298,13 @@ function profiles_content(&$a) {
 		info( t('New profile created.') . EOL);
 		if(count($r3) == 1)
 			goaway($a->get_baseurl() . '/profiles/' . $r3[0]['id']);
+		
 		goaway($a->get_baseurl() . '/profiles');
-	}		 
+	} 
 
 	if(($a->argc > 2) && ($a->argv[1] === 'clone')) {
+		
+		check_form_security_token_redirectOnErr('/profiles', 'profile_clone', 't');
 
 		$r0 = q("SELECT `id` FROM `profile` WHERE `uid` = %d",
 			intval(local_user()));
@@ -330,9 +340,11 @@ function profiles_content(&$a) {
 		info( t('New profile created.') . EOL);
 		if(count($r3) == 1)
 			goaway($a->get_baseurl() . '/profiles/' . $r3[0]['id']);
-	goaway($a->get_baseurl() . '/profiles');
-	return; // NOTREACHED
-	}		 
+		
+		goaway($a->get_baseurl() . '/profiles');
+		
+		return; // NOTREACHED
+	}
 
 
 	if(($a->argc > 1) && (intval($a->argv[1]))) {
@@ -371,6 +383,9 @@ function profiles_content(&$a) {
 		$is_default = (($r[0]['is-default']) ? 1 : 0);
 		$tpl = get_markup_template("profile_edit.tpl");
 		$o .= replace_macros($tpl,array(
+			'$form_security_token' => get_form_security_token("profile_edit"),
+			'$profile_clone_link' => 'profiles/clone/' . $r[0]['id'] . '?t=' . get_form_security_token("profile_clone"),
+			'$profile_drop_link' => 'profiles/drop/' . $r[0]['id'] . '?t=' . get_form_security_token("profile_drop"),
 			'$banner' => t('Edit Profile Details'),
 			'$submit' => t('Submit'),
 			'$viewprof' => t('View this profile'),
@@ -460,7 +475,8 @@ function profiles_content(&$a) {
 			$o .= replace_macros($tpl_header,array(
 				'$header' => t('Edit/Manage Profiles'),
 				'$chg_photo' => t('Change profile photo'),
-				'$cr_new' => t('Create New Profile')
+				'$cr_new' => t('Create New Profile'),
+				'$cr_new_link' => 'profiles/new?t=' . get_form_security_token("profile_new")
 			));
 
 
diff --git a/mod/settings.php b/mod/settings.php
index 2ef582fdf..f42fdb397 100755
--- a/mod/settings.php
+++ b/mod/settings.php
@@ -53,6 +53,8 @@ function settings_post(&$a) {
 	$old_page_flags = $a->user['page-flags'];
 
 	if(($a->argc > 1) && ($a->argv[1] === 'oauth') && x($_POST,'remove')){
+		check_form_security_token_redirectOnErr('/settings/oauth', 'settings_oauth');
+		
 		$key = $_POST['remove'];
 		q("DELETE FROM tokens WHERE id='%s' AND uid=%d",
 			dbesc($key),
@@ -63,6 +65,8 @@ function settings_post(&$a) {
 
 	if(($a->argc > 2) && ($a->argv[1] === 'oauth')  && ($a->argv[2] === 'edit'||($a->argv[2] === 'add')) && x($_POST,'submit')) {
 		
+		check_form_security_token_redirectOnErr('/settings/oauth', 'settings_oauth');
+		
 		$name   	= ((x($_POST,'name')) ? $_POST['name'] : '');
 		$key		= ((x($_POST,'key')) ? $_POST['key'] : '');
 		$secret		= ((x($_POST,'secret')) ? $_POST['secret'] : '');
@@ -105,13 +109,18 @@ function settings_post(&$a) {
 	}
 
 	if(($a->argc > 1) && ($a->argv[1] == 'addon')) {
+		check_form_security_token_redirectOnErr('/settings/addon', 'settings_addon');
+		
 		call_hooks('plugin_settings_post', $_POST);
 		return;
 	}
 
 	if(($a->argc > 1) && ($a->argv[1] == 'connectors')) {
-
-		if(x($_POST['imap-submit'])) {
+		
+		check_form_security_token_redirectOnErr('/settings/connectors', 'settings_connectors');
+		
+		if(x($_POST, 'imap-submit')) {
+			
 			$mail_server       = ((x($_POST,'mail_server')) ? $_POST['mail_server'] : '');
 			$mail_port         = ((x($_POST,'mail_port')) ? $_POST['mail_port'] : '');
 			$mail_ssl          = ((x($_POST,'mail_ssl')) ? strtolower(trim($_POST['mail_ssl'])) : '');
@@ -185,7 +194,8 @@ function settings_post(&$a) {
 		return;
 	}
 
-
+	check_form_security_token_redirectOnErr('/settings', 'settings');
+	
 	call_hooks('settings_post', $_POST);
 
 	if((x($_POST,'npassword')) || (x($_POST,'confirm'))) {
@@ -460,6 +470,7 @@ function settings_content(&$a) {
 		if(($a->argc > 2) && ($a->argv[2] === 'add')) {
 			$tpl = get_markup_template("settings_oauth_edit.tpl");
 			$o .= replace_macros($tpl, array(
+				'$form_security_token' => get_form_security_token("settings_oauth"),
 				'$tabs'		=> $tabs,
 				'$title'	=> t('Add application'),
 				'$submit'	=> t('Submit'),
@@ -486,6 +497,7 @@ function settings_content(&$a) {
 			
 			$tpl = get_markup_template("settings_oauth_edit.tpl");
 			$o .= replace_macros($tpl, array(
+				'$form_security_token' => get_form_security_token("settings_oauth"),
 				'$tabs'		=> $tabs,
 				'$title'	=> t('Add application'),
 				'$submit'	=> t('Update'),
@@ -500,6 +512,8 @@ function settings_content(&$a) {
 		}
 		
 		if(($a->argc > 3) && ($a->argv[2] === 'delete')) {
+			check_form_security_token_redirectOnErr('/settings/oauth', 'settings_oauth', 't');
+		
 			$r = q("DELETE FROM clients WHERE client_id='%s' AND uid=%d",
 					dbesc($a->argv[3]),
 					local_user());
@@ -518,6 +532,7 @@ function settings_content(&$a) {
 		
 		$tpl = get_markup_template("settings_oauth.tpl");
 		$o .= replace_macros($tpl, array(
+			'$form_security_token' => get_form_security_token("settings_oauth"),
 			'$baseurl'	=> $a->get_baseurl(),
 			'$title'	=> t('Connected Apps'),
 			'$add'		=> t('Add application'),
@@ -544,6 +559,7 @@ function settings_content(&$a) {
 		
 		$tpl = get_markup_template("settings_addons.tpl");
 		$o .= replace_macros($tpl, array(
+			'$form_security_token' => get_form_security_token("settings_addons"),
 			'$title'	=> t('Plugin Settings'),
 			'$tabs'		=> $tabs,
 			'$settings_addons' => $settings_addons
@@ -586,28 +602,28 @@ function settings_content(&$a) {
 
 	$tpl = get_markup_template("settings_connectors.tpl");
 		$o .= replace_macros($tpl, array(
+			'$form_security_token' => get_form_security_token("settings_connectors"),
+			
 			'$title'	=> t('Connector Settings'),
 			'$tabs'		=> $tabs,
 
-		'$diasp_enabled' => $diasp_enabled,
-		'$ostat_enabled' => $ostat_enabled,
-
-		'$h_imap' => t('Email/Mailbox Setup'),
-		'$imap_desc' => t("If you wish to communicate with email contacts using this service \x28optional\x29, please specify how to connect to your mailbox."),
-		'$imap_lastcheck' => array('imap_lastcheck', t('Last successful email check:'), $mail_chk,''),
-		'$mail_disabled' => (($mail_disabled) ? t('Email access is disabled on this site.') : ''),
-		'$mail_server'	=> array('mail_server',  t('IMAP server name:'), $mail_server, ''),
-		'$mail_port'	=> array('mail_port', 	 t('IMAP port:'), $mail_port, ''),
-		'$mail_ssl'		=> array('mail_ssl', 	 t('Security:'), strtoupper($mail_ssl), '', array( ''=>t('None'), 'TLS'=>'TLS', 'SSL'=>'SSL')),
-		'$mail_user'	=> array('mail_user',    t('Email login name:'), $mail_user, ''),
-		'$mail_pass'	=> array('mail_pass', 	 t('Email password:'), '', ''),
-		'$mail_replyto'	=> array('mail_replyto', t('Reply-to address:'), '', 'Optional'),
-		'$mail_pubmail'	=> array('mail_pubmail', t('Send public posts to all email contacts:'), $mail_pubmail, ''),
-		'$mail_action'	=> array('mail_action',	 t('Action after import:'), $mail_action, '', array(0=>t('None'), 1=>t('Delete'), 2=>t('Mark as seen'), 3=>t('Move to folder'))),
-		'$mail_movetofolder'	=> array('mail_movetofolder',	 t('Move to folder:'), $mail_movetofolder, ''),
-		'$submit' => t('Submit'),
-
+			'$diasp_enabled' => $diasp_enabled,
+			'$ostat_enabled' => $ostat_enabled,
 
+			'$h_imap' => t('Email/Mailbox Setup'),
+			'$imap_desc' => t("If you wish to communicate with email contacts using this service \x28optional\x29, please specify how to connect to your mailbox."),
+			'$imap_lastcheck' => array('imap_lastcheck', t('Last successful email check:'), $mail_chk,''),
+			'$mail_disabled' => (($mail_disabled) ? t('Email access is disabled on this site.') : ''),
+			'$mail_server'	=> array('mail_server',  t('IMAP server name:'), $mail_server, ''),
+			'$mail_port'	=> array('mail_port', 	 t('IMAP port:'), $mail_port, ''),
+			'$mail_ssl'		=> array('mail_ssl', 	 t('Security:'), strtoupper($mail_ssl), '', array( ''=>t('None'), 'TLS'=>'TLS', 'SSL'=>'SSL')),
+			'$mail_user'	=> array('mail_user',    t('Email login name:'), $mail_user, ''),
+			'$mail_pass'	=> array('mail_pass', 	 t('Email password:'), '', ''),
+			'$mail_replyto'	=> array('mail_replyto', t('Reply-to address:'), '', 'Optional'),
+			'$mail_pubmail'	=> array('mail_pubmail', t('Send public posts to all email contacts:'), $mail_pubmail, ''),
+			'$mail_action'	=> array('mail_action',	 t('Action after import:'), $mail_action, '', array(0=>t('None'), 1=>t('Delete'), 2=>t('Mark as seen'), 3=>t('Move to folder'))),
+			'$mail_movetofolder'	=> array('mail_movetofolder',	 t('Move to folder:'), $mail_movetofolder, ''),
+			'$submit' => t('Submit'),
 
 			'$settings_connectors' => $settings_connectors
 		));
@@ -805,6 +821,7 @@ function settings_content(&$a) {
 		'$submit' 	=> t('Submit'),
 		'$baseurl' => $a->get_baseurl(),
 		'$uid' => local_user(),
+		'$form_security_token' => get_form_security_token("settings"),
 		
 		'$nickname_block' => $prof_addr,
 		
diff --git a/view/cropbody.tpl b/view/cropbody.tpl
index c9c0f84de..b484d15bf 100755
--- a/view/cropbody.tpl
+++ b/view/cropbody.tpl
@@ -40,6 +40,7 @@ $desc
 </script>
 
 <form action="profile_photo/$resource" id="crop-image-form" method="post" />
+<input type='hidden' name='form_security_token' value='$form_security_token'>
 
 <input type="hidden" name="cropfinal" value="1" />
 <input type="hidden" name="xstart" id="x1" />
diff --git a/view/profile_edit.tpl b/view/profile_edit.tpl
index 8dab72649..e5c7162d0 100755
--- a/view/profile_edit.tpl
+++ b/view/profile_edit.tpl
@@ -5,9 +5,9 @@ $default
 <div id="profile-edit-links">
 <ul>
 <li><a href="profile/$profile_id/view?tab=profile" id="profile-edit-view-link" title="$viewprof">$viewprof</a></li>
-<li><a href="profiles/clone/$profile_id" id="profile-edit-clone-link" title="$cr_prof">$cl_prof</a></li>
+<li><a href="$profile_clone_link" id="profile-edit-clone-link" title="$cr_prof">$cl_prof</a></li>
 <li></li>
-<li><a href="profiles/drop/$profile_id" id="profile-edit-drop-link" title="$del_prof" $disabled >$del_prof</a></li>
+<li><a href="$profile_drop_link" id="profile-edit-drop-link" title="$del_prof" $disabled >$del_prof</a></li>
 
 </ul>
 </div>
@@ -17,6 +17,7 @@ $default
 
 <div id="profile-edit-wrapper" >
 <form id="profile-edit-form" name="form1" action="profiles/$profile_id" method="post" >
+<input type='hidden' name='form_security_token' value='$form_security_token'>
 
 <div id="profile-edit-profile-name-wrapper" >
 <label id="profile-edit-profile-name-label" for="profile-edit-profile-name" >$lbl_profname </label>
diff --git a/view/profile_listing_header.tpl b/view/profile_listing_header.tpl
index 09e4fc9b2..61a273792 100755
--- a/view/profile_listing_header.tpl
+++ b/view/profile_listing_header.tpl
@@ -3,6 +3,6 @@
 <a href="profile_photo" >$chg_photo</a>
 </p>
 <div id="profile-listing-new-link-wrapper" class="button" >
-<a href="profiles/new" id="profile-listing-new-link" title="$cr_new" >$cr_new</a>
+<a href="$cr_new_link" id="profile-listing-new-link" title="$cr_new" >$cr_new</a>
 </div>
 
diff --git a/view/profile_photo.tpl b/view/profile_photo.tpl
index f258b5b86..0b3a1cac1 100755
--- a/view/profile_photo.tpl
+++ b/view/profile_photo.tpl
@@ -1,6 +1,7 @@
 <h1>$title</h1>
 
 <form enctype="multipart/form-data" action="profile_photo" method="post">
+<input type='hidden' name='form_security_token' value='$form_security_token'>
 
 <div id="profile-photo-upload-wrapper">
 <label id="profile-photo-upload-label" for="profile-photo-upload">$lbl_upfile </label>
diff --git a/view/settings.tpl b/view/settings.tpl
index 46c737b23..25479b5bf 100755
--- a/view/settings.tpl
+++ b/view/settings.tpl
@@ -5,7 +5,7 @@ $tabs
 $nickname_block
 
 <form action="settings" id="settings-form" method="post" autocomplete="off" >
-
+<input type='hidden' name='form_security_token' value='$form_security_token'>
 
 <h3 class="settings-heading">$h_pass</h3>
 
diff --git a/view/settings_addons.tpl b/view/settings_addons.tpl
index 2cbfd17e9..28fca5362 100755
--- a/view/settings_addons.tpl
+++ b/view/settings_addons.tpl
@@ -4,6 +4,7 @@ $tabs
 
 
 <form action="settings/addon" method="post" autocomplete="off">
+<input type='hidden' name='form_security_token' value='$form_security_token'>
 
 $settings_addons
 
diff --git a/view/settings_connectors.tpl b/view/settings_connectors.tpl
index 9493c8bf7..43c0346bb 100755
--- a/view/settings_connectors.tpl
+++ b/view/settings_connectors.tpl
@@ -6,6 +6,7 @@ $tabs
 <div class="connector_statusmsg">$ostat_enabled</div>
 
 <form action="settings/connectors" method="post" autocomplete="off">
+<input type='hidden' name='form_security_token' value='$form_security_token'>
 
 $settings_connectors
 
diff --git a/view/settings_oauth.tpl b/view/settings_oauth.tpl
index 0de0dbe98..da1398ab9 100755
--- a/view/settings_oauth.tpl
+++ b/view/settings_oauth.tpl
@@ -4,7 +4,8 @@ $tabs
 
 
 <form action="settings/oauth" method="post" autocomplete="off">
-	
+<input type='hidden' name='form_security_token' value='$form_security_token'>
+
 	<div id="profile-edit-links">
 		<ul>
 			<li>
@@ -24,7 +25,7 @@ $tabs
 		{{ endif }}
 		{{ if $app.my }}
 		<a href="$baseurl/settings/oauth/edit/$app.client_id" class="icon s22 edit" title="$edit">&nbsp;</a>
-		<a href="$baseurl/settings/oauth/delete/$app.client_id" class="icon s22 delete" title="$delete">&nbsp;</a>
+		<a href="$baseurl/settings/oauth/delete/$app.client_id?t=$form_security_token" class="icon s22 delete" title="$delete">&nbsp;</a>
 		{{ endif }}		
 	</div>
 	{{ endfor }}
diff --git a/view/settings_oauth_edit.tpl b/view/settings_oauth_edit.tpl
index 98b7457aa..d29341386 100755
--- a/view/settings_oauth_edit.tpl
+++ b/view/settings_oauth_edit.tpl
@@ -3,6 +3,8 @@ $tabs
 <h1>$title</h1>
 
 <form method="POST">
+<input type='hidden' name='form_security_token' value='$form_security_token'>
+
 {{ inc field_input.tpl with $field=$name }}{{ endinc }}
 {{ inc field_input.tpl with $field=$key }}{{ endinc }}
 {{ inc field_input.tpl with $field=$secret }}{{ endinc }}