Completed
Push — master ( 945d9a...e5db64 )
by Schlaefer
02:51
created
app/Lib/Saito/Posting/Decorator/UserPostingTrait.php 3 patches
Doc Comments   +7 added lines, -2 removed lines patch added patch discarded remove patch
@@ -8,10 +8,16 @@  discard block
 block discarded – undo
8 8
 
9 9
 		protected $_CU;
10 10
 
11
+		/**
12
+		 * @return \Saito\User\ForumsUserInterface
13
+		 */
11 14
 		public function getCurrentUser() {
12 15
 			return $this->_CU;
13 16
 		}
14 17
 
18
+		/**
19
+		 * @param \Saito\User\ForumsUserInterface $CU
20
+		 */
15 21
 		public function setCurrentUser($CU) {
16 22
 			$this->_CU = $CU;
17 23
 		}
@@ -19,8 +25,7 @@  discard block
 block discarded – undo
19 25
 		/**
20 26
 		 * Checks if answering an entry is allowed
21 27
 		 *
22
-		 * @param array $entry
23
-		 * @return boolean
28
+		 * @return string|false
24 29
 		 */
25 30
 		public function isAnsweringForbidden() {
26 31
 			if ($this->isLocked()) {
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -62,7 +62,7 @@  discard block
 block discarded – undo
62 62
 			$timeLimit = (\Configure::read('Saito.Settings.edit_period') * 60) + strtotime($posting->get('time'));
63 63
 			$isOverTimeLimit = time() > $timeLimit;
64 64
 
65
-			$isUsersPosting = (int)$User->getId() === (int)$posting->get('user_id');
65
+			$isUsersPosting = (int) $User->getId() === (int) $posting->get('user_id');
66 66
 
67 67
 			if ($User->isMod()) {
68 68
 				// Mods
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 		 */
124 124
 		public function hasNewAnswers() {
125 125
 			if (!$this->isRoot()) {
126
-				throw new \RuntimeException('Posting with id ' . $this->get('id') . ' is no root posting.');
126
+				throw new \RuntimeException('Posting with id '.$this->get('id').' is no root posting.');
127 127
 			}
128 128
 			if (!isset($this->_CU['last_refresh'])) {
129 129
 				return false;
Please login to merge, or discard this patch.
Indentation   +127 added lines, -127 removed lines patch added patch discarded remove patch
@@ -1,134 +1,134 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-	namespace Saito\Posting\Decorator;
4
-
5
-	trait UserPostingTrait {
6
-
7
-		protected $_cache = [];
8
-
9
-		protected $_CU;
10
-
11
-		public function getCurrentUser() {
12
-			return $this->_CU;
13
-		}
14
-
15
-		public function setCurrentUser($CU) {
16
-			$this->_CU = $CU;
17
-		}
18
-
19
-		/**
20
-		 * Checks if answering an entry is allowed
21
-		 *
22
-		 * @param array $entry
23
-		 * @return boolean
24
-		 */
25
-		public function isAnsweringForbidden() {
26
-			if ($this->isLocked()) {
27
-				$isAnsweringForbidden = 'locked';
28
-			} else {
29
-				$isAnsweringForbidden = false;
30
-			}
31
-			return $isAnsweringForbidden;
32
-		}
33
-
34
-		/**
35
-		 * checks if entry is bookmarked by current user
36
-		 */
37
-		public function isBookmarked() {
38
-			return $this->_CU->hasBookmarked($this->get('id'));
39
-		}
40
-
41
-		public function isEditingAsCurrentUserForbidden() {
42
-			return $this->_isEditingForbidden($this, $this->_CU);
43
-		}
44
-
45
-		public function isEditingWithRoleUserForbidden() {
46
-			return $this->_isEditingForbidden($this, $this->_CU->mockUserType('user'));
47
-		}
48
-
49
-		protected function _isEditingForbidden(\Saito\Posting\Posting $posting, $User) {
50
-			// Anon
51
-			if ($User->isLoggedIn() !== true) {
52
-				return true;
53
-			}
54
-
55
-			// Admins
56
-			if ($User->isAdmin()) {
57
-				return false;
58
-			}
59
-
60
-			$verboten = true;
61
-
62
-			$timeLimit = (\Configure::read('Saito.Settings.edit_period') * 60) + strtotime($posting->get('time'));
63
-			$isOverTimeLimit = time() > $timeLimit;
64
-
65
-			$isUsersPosting = (int)$User->getId() === (int)$posting->get('user_id');
66
-
67
-			if ($User->isMod()) {
68
-				// Mods
69
-				// @todo mods don't edit admin posts
70
-				if ($isUsersPosting && $isOverTimeLimit &&
71
-					/* Mods should be able to edit their own posts if they are pinned
3
+    namespace Saito\Posting\Decorator;
4
+
5
+    trait UserPostingTrait {
6
+
7
+        protected $_cache = [];
8
+
9
+        protected $_CU;
10
+
11
+        public function getCurrentUser() {
12
+            return $this->_CU;
13
+        }
14
+
15
+        public function setCurrentUser($CU) {
16
+            $this->_CU = $CU;
17
+        }
18
+
19
+        /**
20
+         * Checks if answering an entry is allowed
21
+         *
22
+         * @param array $entry
23
+         * @return boolean
24
+         */
25
+        public function isAnsweringForbidden() {
26
+            if ($this->isLocked()) {
27
+                $isAnsweringForbidden = 'locked';
28
+            } else {
29
+                $isAnsweringForbidden = false;
30
+            }
31
+            return $isAnsweringForbidden;
32
+        }
33
+
34
+        /**
35
+         * checks if entry is bookmarked by current user
36
+         */
37
+        public function isBookmarked() {
38
+            return $this->_CU->hasBookmarked($this->get('id'));
39
+        }
40
+
41
+        public function isEditingAsCurrentUserForbidden() {
42
+            return $this->_isEditingForbidden($this, $this->_CU);
43
+        }
44
+
45
+        public function isEditingWithRoleUserForbidden() {
46
+            return $this->_isEditingForbidden($this, $this->_CU->mockUserType('user'));
47
+        }
48
+
49
+        protected function _isEditingForbidden(\Saito\Posting\Posting $posting, $User) {
50
+            // Anon
51
+            if ($User->isLoggedIn() !== true) {
52
+                return true;
53
+            }
54
+
55
+            // Admins
56
+            if ($User->isAdmin()) {
57
+                return false;
58
+            }
59
+
60
+            $verboten = true;
61
+
62
+            $timeLimit = (\Configure::read('Saito.Settings.edit_period') * 60) + strtotime($posting->get('time'));
63
+            $isOverTimeLimit = time() > $timeLimit;
64
+
65
+            $isUsersPosting = (int)$User->getId() === (int)$posting->get('user_id');
66
+
67
+            if ($User->isMod()) {
68
+                // Mods
69
+                // @todo mods don't edit admin posts
70
+                if ($isUsersPosting && $isOverTimeLimit &&
71
+                    /* Mods should be able to edit their own posts if they are pinned
72 72
 					 *
73 73
 					 * @todo this opens a 'mod can pin and then edit root entries'-loophole,
74 74
 					 * as long as no one checks pinning for Configure::read('Saito.Settings.edit_period') * 60
75 75
 					 * for mods pinning root-posts.
76 76
 					 */
77
-					(!$posting->isPinned())
78
-				) {
79
-					// mods don't mod themselves
80
-					$verboten = 'time';
81
-				} else {
82
-					$verboten = false;
83
-				};
84
-
85
-			} else {
86
-				// Users
87
-				if ($isUsersPosting === false) {
88
-					$verboten = 'user';
89
-				} elseif ($isOverTimeLimit) {
90
-					$verboten = 'time';
91
-				} elseif ($this->isLocked()) {
92
-					$verboten = 'locked';
93
-				} else {
94
-					$verboten = false;
95
-				}
96
-			}
97
-
98
-			return $verboten;
99
-		}
100
-
101
-		public function isIgnored() {
102
-			return $this->_CU->ignores($this->get('user_id'));
103
-		}
104
-
105
-		public function isNew() {
106
-			if (isset($this->_cache['isNew'])) {
107
-				$this->_cache['isNew'] = $this->_cache['isNew'];
108
-			} else {
109
-				$id = $this->get('id');
110
-				$time = $this->get('time');
111
-				$this->_cache['isNew'] = !$this->_CU->ReadEntries->isRead($id, $time);
112
-			}
113
-			return $this->_cache['isNew'];
114
-		}
115
-
116
-		/**
117
-		 * Checks if posting has newer answers
118
-		 *
119
-		 * currently only supported for root postings
120
-		 *
121
-		 * @return bool
122
-		 * @throws \RuntimeException
123
-		 */
124
-		public function hasNewAnswers() {
125
-			if (!$this->isRoot()) {
126
-				throw new \RuntimeException('Posting with id ' . $this->get('id') . ' is no root posting.');
127
-			}
128
-			if (!isset($this->_CU['last_refresh'])) {
129
-				return false;
130
-			}
131
-			return $this->_CU['last_refresh_unix'] < strtotime($this->get('last_answer'));
132
-		}
133
-
134
-	}
77
+                    (!$posting->isPinned())
78
+                ) {
79
+                    // mods don't mod themselves
80
+                    $verboten = 'time';
81
+                } else {
82
+                    $verboten = false;
83
+                };
84
+
85
+            } else {
86
+                // Users
87
+                if ($isUsersPosting === false) {
88
+                    $verboten = 'user';
89
+                } elseif ($isOverTimeLimit) {
90
+                    $verboten = 'time';
91
+                } elseif ($this->isLocked()) {
92
+                    $verboten = 'locked';
93
+                } else {
94
+                    $verboten = false;
95
+                }
96
+            }
97
+
98
+            return $verboten;
99
+        }
100
+
101
+        public function isIgnored() {
102
+            return $this->_CU->ignores($this->get('user_id'));
103
+        }
104
+
105
+        public function isNew() {
106
+            if (isset($this->_cache['isNew'])) {
107
+                $this->_cache['isNew'] = $this->_cache['isNew'];
108
+            } else {
109
+                $id = $this->get('id');
110
+                $time = $this->get('time');
111
+                $this->_cache['isNew'] = !$this->_CU->ReadEntries->isRead($id, $time);
112
+            }
113
+            return $this->_cache['isNew'];
114
+        }
115
+
116
+        /**
117
+         * Checks if posting has newer answers
118
+         *
119
+         * currently only supported for root postings
120
+         *
121
+         * @return bool
122
+         * @throws \RuntimeException
123
+         */
124
+        public function hasNewAnswers() {
125
+            if (!$this->isRoot()) {
126
+                throw new \RuntimeException('Posting with id ' . $this->get('id') . ' is no root posting.');
127
+            }
128
+            if (!isset($this->_CU['last_refresh'])) {
129
+                return false;
130
+            }
131
+            return $this->_CU['last_refresh_unix'] < strtotime($this->get('last_answer'));
132
+        }
133
+
134
+    }
Please login to merge, or discard this patch.
app/Lib/Saito/Thread/Renderer/ThreadHtmlRenderer.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -76,6 +76,9 @@
 block discarded – undo
76 76
 			return $out;
77 77
 		}
78 78
 
79
+		/**
80
+		 * @param \Saito\Posting\PostingInterface $node
81
+		 */
79 82
 		protected function _renderThreadLine($node, array $posting, $level) {
80 83
 			$id = $posting['Entry']['id'];
81 84
 			$useLineCache = $level > 0 && $this->_LineCache;
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -94,7 +94,7 @@
 block discarded – undo
94 94
 				$categoryId = $posting['Category']['id'];
95 95
 				if (!isset(self::$_catL10n[$categoryId])) {
96 96
 					$accession = $posting['Category']['accession'];
97
-					$catAcs = h(__d('nondynamic', 'category_acs_' . $accession . '_exp'));
97
+					$catAcs = h(__d('nondynamic', 'category_acs_'.$accession.'_exp'));
98 98
 					$catDesc = h($posting['Category']['description']);
99 99
 					$catTitle = h($posting['Category']['category']);
100 100
 					$category = <<<EOF
Please login to merge, or discard this patch.
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -1,66 +1,66 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-	namespace Saito\Thread\Renderer;
4
-
5
-	/**
6
-	 * Class ThreadHtmlRenderer renders postings into a tree
7
-	 */
8
-	class ThreadHtmlRenderer extends HtmlRendererAbstract {
9
-
10
-		/**
11
-		 * @var array performance-cheat for category l10n
12
-		 */
13
-		protected static $_catL10n = [];
14
-
15
-		/**
16
-		 * @var ItemCache
17
-		 */
18
-		protected $_LineCache;
19
-
20
-		protected $_webroot;
21
-
22
-		public function setOptions($options) {
23
-			parent::setOptions($options);
24
-			$this->_webroot = $this->_EntryHelper->webroot;
25
-			if (isset($options['lineCache'])) {
26
-				$this->_LineCache = $options['lineCache'];
27
-			}
28
-		}
29
-
30
-		protected function _renderCore(\Saito\Posting\PostingInterface $node) {
31
-			$posting = $node->getRaw();
32
-			$level = $node->getLevel();
33
-			$id = $posting['Entry']['id'];
34
-
35
-			$threadLine = $this->_renderThreadLine($node, $posting, $level);
36
-			$css = $this->_css($node);
37
-			$badges = $this->getBadges($node);
38
-
39
-			$requestedParams = $this->_SEM->dispatch(
40
-				'Request.Saito.View.ThreadLine.beforeRender',
41
-				['node' => $node, 'View' => $this->_EntryHelper->_View]
42
-			);
43
-
44
-			$params = ['css' => '', 'style' => ''];
45
-
46
-			if (!empty($requestedParams) && !empty($requestedParams[0])) {
47
-				foreach ($requestedParams as $param) {
48
-					foreach ($param as $key => $value) {
49
-						$params[$key] .= $value;
50
-					}
51
-				}
52
-			}
53
-
54
-			//= manual json_encode() for performance
55
-			$tid = $posting['Entry']['tid'];
56
-			$isNew = $node->isNew() ? 'true' : 'false';
57
-			$jsData = <<<EOF
3
+    namespace Saito\Thread\Renderer;
4
+
5
+    /**
6
+     * Class ThreadHtmlRenderer renders postings into a tree
7
+     */
8
+    class ThreadHtmlRenderer extends HtmlRendererAbstract {
9
+
10
+        /**
11
+         * @var array performance-cheat for category l10n
12
+         */
13
+        protected static $_catL10n = [];
14
+
15
+        /**
16
+         * @var ItemCache
17
+         */
18
+        protected $_LineCache;
19
+
20
+        protected $_webroot;
21
+
22
+        public function setOptions($options) {
23
+            parent::setOptions($options);
24
+            $this->_webroot = $this->_EntryHelper->webroot;
25
+            if (isset($options['lineCache'])) {
26
+                $this->_LineCache = $options['lineCache'];
27
+            }
28
+        }
29
+
30
+        protected function _renderCore(\Saito\Posting\PostingInterface $node) {
31
+            $posting = $node->getRaw();
32
+            $level = $node->getLevel();
33
+            $id = $posting['Entry']['id'];
34
+
35
+            $threadLine = $this->_renderThreadLine($node, $posting, $level);
36
+            $css = $this->_css($node);
37
+            $badges = $this->getBadges($node);
38
+
39
+            $requestedParams = $this->_SEM->dispatch(
40
+                'Request.Saito.View.ThreadLine.beforeRender',
41
+                ['node' => $node, 'View' => $this->_EntryHelper->_View]
42
+            );
43
+
44
+            $params = ['css' => '', 'style' => ''];
45
+
46
+            if (!empty($requestedParams) && !empty($requestedParams[0])) {
47
+                foreach ($requestedParams as $param) {
48
+                    foreach ($param as $key => $value) {
49
+                        $params[$key] .= $value;
50
+                    }
51
+                }
52
+            }
53
+
54
+            //= manual json_encode() for performance
55
+            $tid = $posting['Entry']['tid'];
56
+            $isNew = $node->isNew() ? 'true' : 'false';
57
+            $jsData = <<<EOF
58 58
 {"id":{$id},"new":{$isNew},"tid":{$tid}}
59 59
 EOF;
60 60
 
61
-			// data-id still used to identify parent when inserting	an inline-answered entry
62
-			// last </span> comes from _renderThreadLine and allows appending to threadLine-post
63
-			$out = <<<EOF
61
+            // data-id still used to identify parent when inserting	an inline-answered entry
62
+            // last </span> comes from _renderThreadLine and allows appending to threadLine-post
63
+            $out = <<<EOF
64 64
 <li class="threadLeaf {$css}" data-id="{$id}" data-leaf='{$jsData}'>
65 65
 	<div class="threadLine {$params['css']}" style="{$params['style']}">
66 66
 		<button class="btnLink btn_show_thread threadLine-pre et">
@@ -73,52 +73,52 @@  discard block
 block discarded – undo
73 73
 	</div>
74 74
 </li>
75 75
 EOF;
76
-			return $out;
77
-		}
78
-
79
-		protected function _renderThreadLine($node, array $posting, $level) {
80
-			$id = $posting['Entry']['id'];
81
-			$useLineCache = $level > 0 && $this->_LineCache;
82
-
83
-			if ($useLineCache && $threadLine = $this->_LineCache->get($id)) {
84
-				return $threadLine;
85
-			}
86
-
87
-			$subject = $this->getSubject($node);
88
-			$username = h($posting['User']['username']);
89
-			$time = $this->_EntryHelper->TimeH->formatTime($posting['Entry']['time']);
90
-
91
-			//= category HTML
92
-			$category = '';
93
-			if ($level === 0) {
94
-				$categoryId = $posting['Category']['id'];
95
-				if (!isset(self::$_catL10n[$categoryId])) {
96
-					$accession = $posting['Category']['accession'];
97
-					$catAcs = h(__d('nondynamic', 'category_acs_' . $accession . '_exp'));
98
-					$catDesc = h($posting['Category']['description']);
99
-					$catTitle = h($posting['Category']['category']);
100
-					$category = <<<EOF
76
+            return $out;
77
+        }
78
+
79
+        protected function _renderThreadLine($node, array $posting, $level) {
80
+            $id = $posting['Entry']['id'];
81
+            $useLineCache = $level > 0 && $this->_LineCache;
82
+
83
+            if ($useLineCache && $threadLine = $this->_LineCache->get($id)) {
84
+                return $threadLine;
85
+            }
86
+
87
+            $subject = $this->getSubject($node);
88
+            $username = h($posting['User']['username']);
89
+            $time = $this->_EntryHelper->TimeH->formatTime($posting['Entry']['time']);
90
+
91
+            //= category HTML
92
+            $category = '';
93
+            if ($level === 0) {
94
+                $categoryId = $posting['Category']['id'];
95
+                if (!isset(self::$_catL10n[$categoryId])) {
96
+                    $accession = $posting['Category']['accession'];
97
+                    $catAcs = h(__d('nondynamic', 'category_acs_' . $accession . '_exp'));
98
+                    $catDesc = h($posting['Category']['description']);
99
+                    $catTitle = h($posting['Category']['category']);
100
+                    $category = <<<EOF
101 101
 <span class="c-category acs-$accession" title="$catDesc ($catAcs)">
102 102
 	($catTitle)
103 103
 </span>
104 104
 EOF;
105
-					self::$_catL10n[$categoryId] = $category;
106
-				}
107
-				$category = self::$_catL10n[$categoryId];
108
-			}
105
+                    self::$_catL10n[$categoryId] = $category;
106
+                }
107
+                $category = self::$_catL10n[$categoryId];
108
+            }
109 109
 
110
-			// last </span> closes in parent
111
-			$threadLine = <<<EOF
110
+            // last </span> closes in parent
111
+            $threadLine = <<<EOF
112 112
 {$subject}
113 113
 <span class="c-username"> – {$username}</span>
114 114
 {$category}
115 115
 <span class="threadLine-post"> {$time}
116 116
 EOF;
117 117
 
118
-			if ($useLineCache) {
119
-				$this->_LineCache->set($id, $threadLine, $this->_lastAnswer);
120
-			}
121
-			return $threadLine;
122
-		}
118
+            if ($useLineCache) {
119
+                $this->_LineCache->set($id, $threadLine, $this->_lastAnswer);
120
+            }
121
+            return $threadLine;
122
+        }
123 123
 
124
-	}
124
+    }
Please login to merge, or discard this patch.
app/Lib/Saito/User/Cookie/CurrentUserCookie.php 2 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -9,6 +9,9 @@
 block discarded – undo
9 9
 
10 10
 		protected $_Cookie;
11 11
 
12
+		/**
13
+		 * @param \CurrentUserComponent $CurrentUser
14
+		 */
12 15
 		public function write($CurrentUser) {
13 16
 			$cookie = [
14 17
 				'id' => $CurrentUser->getId(),
Please login to merge, or discard this patch.
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -1,38 +1,38 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-	namespace Saito\User\Cookie;
3
+    namespace Saito\User\Cookie;
4 4
 
5
-	/**
6
-	 * Handles the persistent cookie for cookie relogin
7
-	 */
8
-	class CurrentUserCookie extends Storage {
5
+    /**
6
+     * Handles the persistent cookie for cookie relogin
7
+     */
8
+    class CurrentUserCookie extends Storage {
9 9
 
10
-		protected $_Cookie;
10
+        protected $_Cookie;
11 11
 
12
-		public function write($CurrentUser) {
13
-			$cookie = [
14
-				'id' => $CurrentUser->getId(),
15
-				'username' => $CurrentUser['username'],
16
-				'password' => $CurrentUser['password']
17
-			];
18
-			parent::write($cookie);
19
-		}
12
+        public function write($CurrentUser) {
13
+            $cookie = [
14
+                'id' => $CurrentUser->getId(),
15
+                'username' => $CurrentUser['username'],
16
+                'password' => $CurrentUser['password']
17
+            ];
18
+            parent::write($cookie);
19
+        }
20 20
 
21
-		/**
22
-		 * Gets cookie values
23
-		 *
24
-		 * @return bool|array cookie values if found, `false` otherwise
25
-		 */
26
-		public function read() {
27
-			$cookie = parent::read();
28
-			if (is_null($cookie) ||
29
-				// cookie couldn't be deciphered correctly and is a meaningless string
30
-				!is_array($cookie)
31
-			) {
32
-				parent::delete();
33
-				return false;
34
-			}
35
-			return $cookie;
36
-		}
21
+        /**
22
+         * Gets cookie values
23
+         *
24
+         * @return bool|array cookie values if found, `false` otherwise
25
+         */
26
+        public function read() {
27
+            $cookie = parent::read();
28
+            if (is_null($cookie) ||
29
+                // cookie couldn't be deciphered correctly and is a meaningless string
30
+                !is_array($cookie)
31
+            ) {
32
+                parent::delete();
33
+                return false;
34
+            }
35
+            return $cookie;
36
+        }
37 37
 
38
-	}
38
+    }
Please login to merge, or discard this patch.
app/Lib/Saito/User/LastRefresh/LastRefreshAbstract.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -25,7 +25,7 @@
 block discarded – undo
25 25
 		 * is last refresh newer than $timestamp
26 26
 		 *
27 27
 		 * @param mixed $timestamp int unix-timestamp or date as string
28
-		 * @return mixed bool or null if not determinable
28
+		 * @return null|boolean bool or null if not determinable
29 29
 		 */
30 30
 		public function isNewerThan($timestamp) {
31 31
 			if (is_string($timestamp)) {
Please login to merge, or discard this patch.
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -1,72 +1,72 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-	namespace Saito\User\LastRefresh;
3
+    namespace Saito\User\LastRefresh;
4 4
 
5
-	/**
6
-	 * handles last refresh time for the current user
7
-	 */
8
-	abstract class LastRefreshAbstract {
5
+    /**
6
+     * handles last refresh time for the current user
7
+     */
8
+    abstract class LastRefreshAbstract {
9 9
 
10
-		/**
11
-		 * @var CurrentUserComponent
12
-		 */
13
-		protected $_CurrentUser;
10
+        /**
11
+         * @var CurrentUserComponent
12
+         */
13
+        protected $_CurrentUser;
14 14
 
15
-		/**
16
-		 * @var int unix timestamp
17
-		 */
18
-		protected $_timestamp = null;
15
+        /**
16
+         * @var int unix timestamp
17
+         */
18
+        protected $_timestamp = null;
19 19
 
20
-		public function __construct(\CurrentuserComponent $CurrentUser) {
21
-			$this->_CurrentUser = $CurrentUser;
22
-		}
20
+        public function __construct(\CurrentuserComponent $CurrentUser) {
21
+            $this->_CurrentUser = $CurrentUser;
22
+        }
23 23
 
24
-		/**
25
-		 * is last refresh newer than $timestamp
26
-		 *
27
-		 * @param mixed $timestamp int unix-timestamp or date as string
28
-		 * @return mixed bool or null if not determinable
29
-		 */
30
-		public function isNewerThan($timestamp) {
31
-			if (is_string($timestamp)) {
32
-				$timestamp = strtotime($timestamp);
33
-			}
34
-			$lastRefresh = $this->_get();
35
-			// timestamp is not set (or readable): everything is considered new
36
-			if ($lastRefresh === false) {
37
-				return null;
38
-			}
39
-			return $lastRefresh > $timestamp;
40
-		}
24
+        /**
25
+         * is last refresh newer than $timestamp
26
+         *
27
+         * @param mixed $timestamp int unix-timestamp or date as string
28
+         * @return mixed bool or null if not determinable
29
+         */
30
+        public function isNewerThan($timestamp) {
31
+            if (is_string($timestamp)) {
32
+                $timestamp = strtotime($timestamp);
33
+            }
34
+            $lastRefresh = $this->_get();
35
+            // timestamp is not set (or readable): everything is considered new
36
+            if ($lastRefresh === false) {
37
+                return null;
38
+            }
39
+            return $lastRefresh > $timestamp;
40
+        }
41 41
 
42
-		/**
43
-		 * returns last refresh timestamp
44
-		 *
45
-		 * @return mixed int if unix timestamp or bool false if uninitialized
46
-		 */
47
-		abstract protected function _get();
42
+        /**
43
+         * returns last refresh timestamp
44
+         *
45
+         * @return mixed int if unix timestamp or bool false if uninitialized
46
+         */
47
+        abstract protected function _get();
48 48
 
49
-		/**
50
-		 * @param mixed $timestamp
51
-		 *
52
-		 * null|'now'|<`Y-m-d H:i:s` timestamp>
53
-		 */
54
-		public function set($timestamp = null) {
55
-			// all postings individually marked as read should be removed because they
56
-			// are older than the new last-refresh timestamp
57
-			$this->_CurrentUser->ReadEntries->delete();
49
+        /**
50
+         * @param mixed $timestamp
51
+         *
52
+         * null|'now'|<`Y-m-d H:i:s` timestamp>
53
+         */
54
+        public function set($timestamp = null) {
55
+            // all postings individually marked as read should be removed because they
56
+            // are older than the new last-refresh timestamp
57
+            $this->_CurrentUser->ReadEntries->delete();
58 58
 
59
-			$this->_timestamp = $this->_parseTimestamp($timestamp);
60
-			$this->_set();
61
-		}
59
+            $this->_timestamp = $this->_parseTimestamp($timestamp);
60
+            $this->_set();
61
+        }
62 62
 
63
-		protected abstract function _set();
63
+        protected abstract function _set();
64 64
 
65
-		protected function _parseTimestamp($timestamp) {
66
-			if ($timestamp === 'now' || $timestamp === null) {
67
-				$timestamp = date('Y-m-d H:i:s');
68
-			}
69
-			return $timestamp;
70
-		}
65
+        protected function _parseTimestamp($timestamp) {
66
+            if ($timestamp === 'now' || $timestamp === null) {
67
+                $timestamp = date('Y-m-d H:i:s');
68
+            }
69
+            return $timestamp;
70
+        }
71 71
 
72
-	}
72
+    }
Please login to merge, or discard this patch.
app/Model/AppModel.php 3 patches
Doc Comments   +5 added lines, -2 removed lines patch added patch discarded remove patch
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 		 * Increments value of a field
126 126
 		 *
127 127
 		 * @param $id
128
-		 * @param $field
128
+		 * @param string $field
129 129
 		 * @param int $amount
130 130
 		 * @throws InvalidArgumentException
131 131
 		 */
@@ -197,6 +197,9 @@  discard block
 block discarded – undo
197 197
 			$this->dispatchSaitoEvent($event, $data);
198 198
 		}
199 199
 
200
+		/**
201
+		 * @param string $event
202
+		 */
200 203
 		public function dispatchSaitoEvent($event, $data) {
201 204
 			if (!$this->_SEM) {
202 205
 				$this->_SEM = SaitoEventManager::getInstance();
@@ -225,7 +228,7 @@  discard block
 block discarded – undo
225 228
 		 *
226 229
 		 * falls back to local definition if available
227 230
 		 *
228
-		 * @param $name
231
+		 * @param string $name
229 232
 		 * @return mixed
230 233
 		 * @throws UnexpectedValueException
231 234
 		 */
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 
75 75
 		public function requireFields(&$data, array $required) {
76 76
 			return $this->_mapFields($data, $required,
77
-				function (&$data, $model, $field) {
77
+				function(&$data, $model, $field) {
78 78
 					if (!isset($data[$model][$field])) {
79 79
 						return false;
80 80
 					}
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 
85 85
 		public function unsetFields(&$data, array $unset = ['id']) {
86 86
 			return $this->_mapFields($data, $unset,
87
-				function (&$data, $model, $field) {
87
+				function(&$data, $model, $field) {
88 88
 					if (isset($data[$model][$field])) {
89 89
 						unset($data[$model][$field]);
90 90
 					}
@@ -138,9 +138,9 @@  discard block
 block discarded – undo
138 138
 				$operator = '-';
139 139
 				$amount *= -1;
140 140
 			}
141
-			$field = $this->alias . '.' . $field;
141
+			$field = $this->alias.'.'.$field;
142 142
 			$this->updateAll([$field => "$field $operator $amount"],
143
-				[$this->alias . '.id' => $id]);
143
+				[$this->alias.'.id' => $id]);
144 144
 		}
145 145
 
146 146
 		public function pipeMerger(array $data) {
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
 		protected static function _anonymizeIp($ip) {
214 214
 			$strlen = strlen($ip);
215 215
 			if ($strlen > 6) :
216
-				$divider = (int)floor($strlen / 4) + 1;
216
+				$divider = (int) floor($strlen / 4) + 1;
217 217
 				$ip = substr_replace($ip, '…', $divider, $strlen - (2 * $divider));
218 218
 			endif;
219 219
 
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 		 * @throws UnexpectedValueException
231 231
 		 */
232 232
 		protected function _setting($name) {
233
-			$setting = Configure::read('Saito.Settings.' . $name);
233
+			$setting = Configure::read('Saito.Settings.'.$name);
234 234
 			if ($setting !== null) {
235 235
 				return $setting;
236 236
 			}
Please login to merge, or discard this patch.
Indentation   +261 added lines, -261 removed lines patch added patch discarded remove patch
@@ -1,291 +1,291 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-	App::uses('Model', 'Model');
4
-	App::uses('Sanitize', 'Utility');
5
-	App::uses('CakeEvent', 'Event');
6
-	App::uses('SaitoEventManager', 'Lib/Saito/Event');
3
+    App::uses('Model', 'Model');
4
+    App::uses('Sanitize', 'Utility');
5
+    App::uses('CakeEvent', 'Event');
6
+    App::uses('SaitoEventManager', 'Lib/Saito/Event');
7 7
 
8
-	// import here so that `cake schema ...` cli works
9
-	App::import('Lib', 'Stopwatch.Stopwatch');
8
+    // import here so that `cake schema ...` cli works
9
+    App::import('Lib', 'Stopwatch.Stopwatch');
10 10
 
11
-	class AppModel extends Model {
11
+    class AppModel extends Model {
12 12
 
13
-		/**
14
-		 * @var array model settings; can be overwritten by DB or config Settings
15
-		 */
16
-		protected $_settings = [];
13
+        /**
14
+         * @var array model settings; can be overwritten by DB or config Settings
15
+         */
16
+        protected $_settings = [];
17 17
 
18
-		/**
19
-		 * @var array predefined fields for filterFields()
20
-		 */
21
-		public $allowedInputFields = [];
18
+        /**
19
+         * @var array predefined fields for filterFields()
20
+         */
21
+        public $allowedInputFields = [];
22 22
 
23
-		# Entry->User->UserOnline
24
-		public $recursive = 1;
23
+        # Entry->User->UserOnline
24
+        public $recursive = 1;
25 25
 
26
-		public $SharedObjects;
26
+        public $SharedObjects;
27 27
 
28
-		/** * @var SaitoEventManager */
29
-		protected $_SEM;
28
+        /** * @var SaitoEventManager */
29
+        protected $_SEM;
30 30
 
31
-		public function __construct($id = false, $table = null, $ds = null) {
32
-			parent::__construct($id, $table, $ds);
33
-			$this->_dispatchEvent('Event.Saito.Model.initialize');
34
-		}
31
+        public function __construct($id = false, $table = null, $ds = null) {
32
+            parent::__construct($id, $table, $ds);
33
+            $this->_dispatchEvent('Event.Saito.Model.initialize');
34
+        }
35 35
 
36
-		public function __get($name) {
37
-			switch ($name) {
38
-				case 'dic':
39
-					return ClassRegistry::getObject('dic');
40
-				default:
41
-					if (isset($this->SharedObjects[$name])) {
42
-						return $this->SharedObjects[$name];
43
-					}
44
-			}
45
-			return parent::__get($name);
46
-		}
36
+        public function __get($name) {
37
+            switch ($name) {
38
+                case 'dic':
39
+                    return ClassRegistry::getObject('dic');
40
+                default:
41
+                    if (isset($this->SharedObjects[$name])) {
42
+                        return $this->SharedObjects[$name];
43
+                    }
44
+            }
45
+            return parent::__get($name);
46
+        }
47 47
 
48
-		public function toggle($key) {
49
-			$this->contain();
50
-			$value = $this->read($key);
51
-			$value = ($value[$this->alias][$key] == 0) ? 1 : 0;
52
-			$this->set($key, $value);
53
-			$this->save();
54
-			return $value;
55
-		}
48
+        public function toggle($key) {
49
+            $this->contain();
50
+            $value = $this->read($key);
51
+            $value = ($value[$this->alias][$key] == 0) ? 1 : 0;
52
+            $this->set($key, $value);
53
+            $this->save();
54
+            return $value;
55
+        }
56 56
 
57
-		/**
58
-		 * filters out all fields $fields in $data
59
-		 *
60
-		 * works only on current model, not associations
61
-		 *
62
-		 * @param $data
63
-		 * @param $fields
64
-		 */
65
-		public function filterFields(&$data, $fields) {
66
-			if (is_string($fields) && isset($this->allowedInputFields[$fields])) {
67
-				$fields = $this->allowedInputFields[$fields];
68
-			}
69
-			$fields = array_flip($fields);
70
-			$data = [
71
-				$this->alias => array_intersect_key($data[$this->alias], $fields)
72
-			];
73
-		}
57
+        /**
58
+         * filters out all fields $fields in $data
59
+         *
60
+         * works only on current model, not associations
61
+         *
62
+         * @param $data
63
+         * @param $fields
64
+         */
65
+        public function filterFields(&$data, $fields) {
66
+            if (is_string($fields) && isset($this->allowedInputFields[$fields])) {
67
+                $fields = $this->allowedInputFields[$fields];
68
+            }
69
+            $fields = array_flip($fields);
70
+            $data = [
71
+                $this->alias => array_intersect_key($data[$this->alias], $fields)
72
+            ];
73
+        }
74 74
 
75
-		public function requireFields(&$data, array $required) {
76
-			return $this->_mapFields($data, $required,
77
-				function (&$data, $model, $field) {
78
-					if (!isset($data[$model][$field])) {
79
-						return false;
80
-					}
81
-					return true;
82
-				});
83
-		}
75
+        public function requireFields(&$data, array $required) {
76
+            return $this->_mapFields($data, $required,
77
+                function (&$data, $model, $field) {
78
+                    if (!isset($data[$model][$field])) {
79
+                        return false;
80
+                    }
81
+                    return true;
82
+                });
83
+        }
84 84
 
85
-		public function unsetFields(&$data, array $unset = ['id']) {
86
-			return $this->_mapFields($data, $unset,
87
-				function (&$data, $model, $field) {
88
-					if (isset($data[$model][$field])) {
89
-						unset($data[$model][$field]);
90
-					}
91
-					return true;
92
-				});
93
-		}
85
+        public function unsetFields(&$data, array $unset = ['id']) {
86
+            return $this->_mapFields($data, $unset,
87
+                function (&$data, $model, $field) {
88
+                    if (isset($data[$model][$field])) {
89
+                        unset($data[$model][$field]);
90
+                    }
91
+                    return true;
92
+                });
93
+        }
94 94
 
95
-		protected function _mapFields(&$data, $fields, callable $func) {
96
-			if (isset(reset($data)[$this->alias])) {
97
-				foreach ($data as &$d) {
98
-					if (!$this->_mapFields($d, $fields, $func)) {
99
-						return false;
100
-					}
101
-				}
102
-				return true;
103
-			}
95
+        protected function _mapFields(&$data, $fields, callable $func) {
96
+            if (isset(reset($data)[$this->alias])) {
97
+                foreach ($data as &$d) {
98
+                    if (!$this->_mapFields($d, $fields, $func)) {
99
+                        return false;
100
+                    }
101
+                }
102
+                return true;
103
+            }
104 104
 
105
-			if (!isset($data[$this->alias])) {
106
-				$data = [$this->alias => $data];
107
-			}
108
-			foreach ($fields as $field) {
109
-				if (strpos($field, '.') !== false) {
110
-					list($model, $field) = explode('.', $field, 2);
111
-				} else {
112
-					$model = $this->alias;
113
-				}
114
-				if ($model !== $this->alias) {
115
-					continue;
116
-				}
117
-				if (!$func($data, $model, $field)) {
118
-					return false;
119
-				}
120
-			}
121
-			return true;
122
-		}
105
+            if (!isset($data[$this->alias])) {
106
+                $data = [$this->alias => $data];
107
+            }
108
+            foreach ($fields as $field) {
109
+                if (strpos($field, '.') !== false) {
110
+                    list($model, $field) = explode('.', $field, 2);
111
+                } else {
112
+                    $model = $this->alias;
113
+                }
114
+                if ($model !== $this->alias) {
115
+                    continue;
116
+                }
117
+                if (!$func($data, $model, $field)) {
118
+                    return false;
119
+                }
120
+            }
121
+            return true;
122
+        }
123 123
 
124
-		/**
125
-		 * Increments value of a field
126
-		 *
127
-		 * @param $id
128
-		 * @param $field
129
-		 * @param int $amount
130
-		 * @throws InvalidArgumentException
131
-		 */
132
-		public function increment($id, $field, $amount = 1) {
133
-			if (!is_int($amount)) {
134
-				throw new InvalidArgumentException;
135
-			}
136
-			$operator = '+';
137
-			if ($amount < 0) {
138
-				$operator = '-';
139
-				$amount *= -1;
140
-			}
141
-			$field = $this->alias . '.' . $field;
142
-			$this->updateAll([$field => "$field $operator $amount"],
143
-				[$this->alias . '.id' => $id]);
144
-		}
124
+        /**
125
+         * Increments value of a field
126
+         *
127
+         * @param $id
128
+         * @param $field
129
+         * @param int $amount
130
+         * @throws InvalidArgumentException
131
+         */
132
+        public function increment($id, $field, $amount = 1) {
133
+            if (!is_int($amount)) {
134
+                throw new InvalidArgumentException;
135
+            }
136
+            $operator = '+';
137
+            if ($amount < 0) {
138
+                $operator = '-';
139
+                $amount *= -1;
140
+            }
141
+            $field = $this->alias . '.' . $field;
142
+            $this->updateAll([$field => "$field $operator $amount"],
143
+                [$this->alias . '.id' => $id]);
144
+        }
145 145
 
146
-		public function pipeMerger(array $data) {
147
-			$out = [];
148
-			foreach ($data as $key => $value) {
149
-				$out[] = "$key=$value";
150
-			}
151
-			return implode(' | ', $out);
152
-		}
146
+        public function pipeMerger(array $data) {
147
+            $out = [];
148
+            foreach ($data as $key => $value) {
149
+                $out[] = "$key=$value";
150
+            }
151
+            return implode(' | ', $out);
152
+        }
153 153
 
154
-		/**
155
-		 * Splits String 'a=b|c=d|e=f' into an array('a'=>'b', 'c'=>'d', 'e'=>'f')
156
-		 *
157
-		 * @param string $pipeString
158
-		 * @return array
159
-		 */
160
-		protected function _pipeSplitter($pipeString) {
161
-			$unpipedArray = array();
162
-			$ranks = explode('|', $pipeString);
163
-			foreach ($ranks as $rank) :
164
-				$matches = array();
165
-				$matched = preg_match('/(\w+)\s*=\s*(.*)/', trim($rank), $matches);
166
-				if ($matched) {
167
-					$unpipedArray[$matches[1]] = $matches[2];
168
-				}
169
-			endforeach;
170
-			return $unpipedArray;
171
-		}
154
+        /**
155
+         * Splits String 'a=b|c=d|e=f' into an array('a'=>'b', 'c'=>'d', 'e'=>'f')
156
+         *
157
+         * @param string $pipeString
158
+         * @return array
159
+         */
160
+        protected function _pipeSplitter($pipeString) {
161
+            $unpipedArray = array();
162
+            $ranks = explode('|', $pipeString);
163
+            foreach ($ranks as $rank) :
164
+                $matches = array();
165
+                $matched = preg_match('/(\w+)\s*=\s*(.*)/', trim($rank), $matches);
166
+                if ($matched) {
167
+                    $unpipedArray[$matches[1]] = $matches[2];
168
+                }
169
+            endforeach;
170
+            return $unpipedArray;
171
+        }
172 172
 
173
-		protected static function _getIp() {
174
-			$ip = null;
175
-			if (Configure::read('Saito.Settings.store_ip')):
176
-				$ip = env('REMOTE_ADDR');
177
-				if (Configure::read('Saito.Settings.store_ip_anonymized')):
178
-					$ip = self::_anonymizeIp($ip);
179
-				endif;
180
-			endif;
181
-			return $ip;
182
-		}
173
+        protected static function _getIp() {
174
+            $ip = null;
175
+            if (Configure::read('Saito.Settings.store_ip')):
176
+                $ip = env('REMOTE_ADDR');
177
+                if (Configure::read('Saito.Settings.store_ip_anonymized')):
178
+                    $ip = self::_anonymizeIp($ip);
179
+                endif;
180
+            endif;
181
+            return $ip;
182
+        }
183 183
 
184
-		/**
185
-		 * Dispatches an event
186
-		 *
187
-		 * - Always passes the issuing model class as subject
188
-		 * - Wrapper for CakeEvent boilerplate code
189
-		 * - Easier to test
190
-		 *
191
-		 * @param string $event event identifier `Model.<modelname>.<event>`
192
-		 * @param array $data additional event data
193
-		 */
194
-		protected function _dispatchEvent($event, $data = []) {
195
-			$this->getEventManager()->dispatch(new CakeEvent($event, $this, $data));
196
-			// propagate event on Saito's event bus
197
-			$this->dispatchSaitoEvent($event, $data);
198
-		}
184
+        /**
185
+         * Dispatches an event
186
+         *
187
+         * - Always passes the issuing model class as subject
188
+         * - Wrapper for CakeEvent boilerplate code
189
+         * - Easier to test
190
+         *
191
+         * @param string $event event identifier `Model.<modelname>.<event>`
192
+         * @param array $data additional event data
193
+         */
194
+        protected function _dispatchEvent($event, $data = []) {
195
+            $this->getEventManager()->dispatch(new CakeEvent($event, $this, $data));
196
+            // propagate event on Saito's event bus
197
+            $this->dispatchSaitoEvent($event, $data);
198
+        }
199 199
 
200
-		public function dispatchSaitoEvent($event, $data) {
201
-			if (!$this->_SEM) {
202
-				$this->_SEM = SaitoEventManager::getInstance();
203
-			}
204
-			$this->_SEM->dispatch($event, $data + ['Model' => $this]);
205
-		}
200
+        public function dispatchSaitoEvent($event, $data) {
201
+            if (!$this->_SEM) {
202
+                $this->_SEM = SaitoEventManager::getInstance();
203
+            }
204
+            $this->_SEM->dispatch($event, $data + ['Model' => $this]);
205
+        }
206 206
 
207
-		/**
208
-		 * Rough and tough ip anonymizer
209
-		 *
210
-		 * @param string $ip
211
-		 * @return string
212
-		 */
213
-		protected static function _anonymizeIp($ip) {
214
-			$strlen = strlen($ip);
215
-			if ($strlen > 6) :
216
-				$divider = (int)floor($strlen / 4) + 1;
217
-				$ip = substr_replace($ip, '…', $divider, $strlen - (2 * $divider));
218
-			endif;
207
+        /**
208
+         * Rough and tough ip anonymizer
209
+         *
210
+         * @param string $ip
211
+         * @return string
212
+         */
213
+        protected static function _anonymizeIp($ip) {
214
+            $strlen = strlen($ip);
215
+            if ($strlen > 6) :
216
+                $divider = (int)floor($strlen / 4) + 1;
217
+                $ip = substr_replace($ip, '…', $divider, $strlen - (2 * $divider));
218
+            endif;
219 219
 
220
-			return $ip;
221
-		}
220
+            return $ip;
221
+        }
222 222
 
223
-		/**
224
-		 * gets app setting
225
-		 *
226
-		 * falls back to local definition if available
227
-		 *
228
-		 * @param $name
229
-		 * @return mixed
230
-		 * @throws UnexpectedValueException
231
-		 */
232
-		protected function _setting($name) {
233
-			$setting = Configure::read('Saito.Settings.' . $name);
234
-			if ($setting !== null) {
235
-				return $setting;
236
-			}
237
-			if (isset($this->_settings[$name])) {
238
-				return $this->_settings[$name];
239
-			}
240
-			throw new UnexpectedValueException;
241
-		}
223
+        /**
224
+         * gets app setting
225
+         *
226
+         * falls back to local definition if available
227
+         *
228
+         * @param $name
229
+         * @return mixed
230
+         * @throws UnexpectedValueException
231
+         */
232
+        protected function _setting($name) {
233
+            $setting = Configure::read('Saito.Settings.' . $name);
234
+            if ($setting !== null) {
235
+                return $setting;
236
+            }
237
+            if (isset($this->_settings[$name])) {
238
+                return $this->_settings[$name];
239
+            }
240
+            throw new UnexpectedValueException;
241
+        }
242 242
 
243
-		public function isUniqueCiString($fields) {
244
-			// lazy: only one field
245
-			if (!is_array($fields) || count($fields) > 1) {
246
-				throw InvalidArgumentException();
247
-			}
248
-			$key = key($fields);
249
-			$fields = [
250
-				"LOWER({$this->alias}.{$key})" => mb_strtolower(current($fields))
251
-			];
252
-			return $this->isUnique($fields);
253
-		}
243
+        public function isUniqueCiString($fields) {
244
+            // lazy: only one field
245
+            if (!is_array($fields) || count($fields) > 1) {
246
+                throw InvalidArgumentException();
247
+            }
248
+            $key = key($fields);
249
+            $fields = [
250
+                "LOWER({$this->alias}.{$key})" => mb_strtolower(current($fields))
251
+            ];
252
+            return $this->isUnique($fields);
253
+        }
254 254
 
255
-		/**
256
-		 * Inclusive Validation::range()
257
-		 *
258
-		 * @param array $check
259
-		 * @param float $lower
260
-		 * @param float $upper
261
-		 * @return bool
262
-		 * @see https://github.com/cakephp/cakephp/issues/3304
263
-		 */
264
-		public function inRange($check, $lower = null, $upper = null) {
265
-			$check = reset($check);
266
-			if (!is_numeric($check)) {
267
-				return false;
268
-			}
269
-			if (isset($lower) && isset($upper)) {
270
-				return ($check >= $lower && $check <= $upper);
271
-			}
272
-			// fallback to 'parent'
273
-			return Validation::range($check, $lower, $upper);
274
-		}
255
+        /**
256
+         * Inclusive Validation::range()
257
+         *
258
+         * @param array $check
259
+         * @param float $lower
260
+         * @param float $upper
261
+         * @return bool
262
+         * @see https://github.com/cakephp/cakephp/issues/3304
263
+         */
264
+        public function inRange($check, $lower = null, $upper = null) {
265
+            $check = reset($check);
266
+            if (!is_numeric($check)) {
267
+                return false;
268
+            }
269
+            if (isset($lower) && isset($upper)) {
270
+                return ($check >= $lower && $check <= $upper);
271
+            }
272
+            // fallback to 'parent'
273
+            return Validation::range($check, $lower, $upper);
274
+        }
275 275
 
276
-		/**
277
-		 * Logs current SQL log
278
-		 *
279
-		 * Set debug to 2 to enable SQL logging!
280
-		 */
281
-		public function logSql() {
282
-			if (Configure::read('debug') < 2) {
283
-				trigger_error('You must set debug level to at least 2 to enable SQL-logging',
284
-					E_USER_NOTICE);
285
-			}
286
-			$dbo = $this->getDatasource();
287
-			$logs = $dbo->getLog();
288
-			$this->log($logs['log']);
289
-		}
276
+        /**
277
+         * Logs current SQL log
278
+         *
279
+         * Set debug to 2 to enable SQL logging!
280
+         */
281
+        public function logSql() {
282
+            if (Configure::read('debug') < 2) {
283
+                trigger_error('You must set debug level to at least 2 to enable SQL-logging',
284
+                    E_USER_NOTICE);
285
+            }
286
+            $dbo = $this->getDatasource();
287
+            $logs = $dbo->getLog();
288
+            $this->log($logs['log']);
289
+        }
290 290
 
291
-	}
291
+    }
Please login to merge, or discard this patch.
app/Model/Bookmark.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -78,8 +78,8 @@
 block discarded – undo
78 78
 
79 79
 /**
80 80
  *
81
- * @param int $entry_id
82
- * @param int $user_id
81
+ * @param int $entryId
82
+ * @param int $userId
83 83
  * @return bool
84 84
  */
85 85
 		public function isBookmarked($entryId, $userId) {
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -70,8 +70,8 @@  discard block
 block discarded – undo
70 70
 
71 71
 		public function validateUniqueBookmark() {
72 72
 			$fields = array(
73
-				$this->alias . '.user_id' => $this->data['Bookmark']['user_id'],
74
-				$this->alias . '.entry_id' => $this->data['Bookmark']['entry_id'],
73
+				$this->alias.'.user_id' => $this->data['Bookmark']['user_id'],
74
+				$this->alias.'.entry_id' => $this->data['Bookmark']['entry_id'],
75 75
 			);
76 76
 			return $this->isUnique($fields, false);
77 77
 		}
@@ -88,8 +88,8 @@  discard block
 block discarded – undo
88 88
 				array(
89 89
 					'contain' => false,
90 90
 					'conditions' => array(
91
-						$this->alias . '.entry_id' => $entryId,
92
-						$this->alias . '.user_id' => $userId,
91
+						$this->alias.'.entry_id' => $entryId,
92
+						$this->alias.'.user_id' => $userId,
93 93
 					)
94 94
 				)
95 95
 			);
Please login to merge, or discard this patch.
Indentation   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-	App::uses('AppModel', 'Model');
3
+    App::uses('AppModel', 'Model');
4 4
 
5 5
 /**
6 6
  * Bookmark Model
@@ -8,73 +8,73 @@  discard block
 block discarded – undo
8 8
  * @property User  $User
9 9
  * @property Entry $Entry
10 10
  */
11
-	class Bookmark extends AppModel {
11
+    class Bookmark extends AppModel {
12 12
 
13
-		public $actsAs = array(
14
-			'Containable',
15
-		);
13
+        public $actsAs = array(
14
+            'Containable',
15
+        );
16 16
 
17 17
 /**
18 18
  * Validation rules
19 19
  *
20 20
  * @var array
21 21
  */
22
-		public $validate = array(
23
-			'user_id' => array(
24
-				'numeric' => array(
25
-					'rule' => array('validateUniqueBookmark'),
26
-					//'message' => 'Your custom message here',
27
-					//'allowEmpty' => false,
28
-					'required' => false,
29
-					//'last' => false, // Stop validation after this rule
30
-					'on' => 'create',
31
-					// Limit validation to 'create' or 'update' operations
32
-				),
33
-			),
34
-			'entry_id' => array(
35
-				'numeric' => array(
36
-					'rule' => array('validateUniqueBookmark'),
37
-					//'message' => 'Your custom message here',
38
-					//'allowEmpty' => false,
39
-					'required' => false,
40
-					//'last' => false, // Stop validation after this rule
41
-					'on' => 'create',
42
-					// Limit validation to 'create' or 'update' operations
43
-				),
44
-			),
45
-		);
22
+        public $validate = array(
23
+            'user_id' => array(
24
+                'numeric' => array(
25
+                    'rule' => array('validateUniqueBookmark'),
26
+                    //'message' => 'Your custom message here',
27
+                    //'allowEmpty' => false,
28
+                    'required' => false,
29
+                    //'last' => false, // Stop validation after this rule
30
+                    'on' => 'create',
31
+                    // Limit validation to 'create' or 'update' operations
32
+                ),
33
+            ),
34
+            'entry_id' => array(
35
+                'numeric' => array(
36
+                    'rule' => array('validateUniqueBookmark'),
37
+                    //'message' => 'Your custom message here',
38
+                    //'allowEmpty' => false,
39
+                    'required' => false,
40
+                    //'last' => false, // Stop validation after this rule
41
+                    'on' => 'create',
42
+                    // Limit validation to 'create' or 'update' operations
43
+                ),
44
+            ),
45
+        );
46 46
 
47
-		//The Associations below have been created with all possible keys, those that are not needed can be removed
47
+        //The Associations below have been created with all possible keys, those that are not needed can be removed
48 48
 
49 49
 /**
50 50
  * belongsTo associations
51 51
  *
52 52
  * @var array
53 53
  */
54
-		public $belongsTo = array(
55
-			'User' => array(
56
-				'className' => 'User',
57
-				'foreignKey' => 'user_id',
58
-				'conditions' => '',
59
-				'fields' => '',
60
-				'order' => ''
61
-			),
62
-			'Entry' => array(
63
-				'className' => 'Entry',
64
-				'foreignKey' => 'entry_id',
65
-				'conditions' => '',
66
-				'fields' => '',
67
-				'order' => ''
68
-			)
69
-		);
54
+        public $belongsTo = array(
55
+            'User' => array(
56
+                'className' => 'User',
57
+                'foreignKey' => 'user_id',
58
+                'conditions' => '',
59
+                'fields' => '',
60
+                'order' => ''
61
+            ),
62
+            'Entry' => array(
63
+                'className' => 'Entry',
64
+                'foreignKey' => 'entry_id',
65
+                'conditions' => '',
66
+                'fields' => '',
67
+                'order' => ''
68
+            )
69
+        );
70 70
 
71
-		public function validateUniqueBookmark() {
72
-			$fields = array(
73
-				$this->alias . '.user_id' => $this->data['Bookmark']['user_id'],
74
-				$this->alias . '.entry_id' => $this->data['Bookmark']['entry_id'],
75
-			);
76
-			return $this->isUnique($fields, false);
77
-		}
71
+        public function validateUniqueBookmark() {
72
+            $fields = array(
73
+                $this->alias . '.user_id' => $this->data['Bookmark']['user_id'],
74
+                $this->alias . '.entry_id' => $this->data['Bookmark']['entry_id'],
75
+            );
76
+            return $this->isUnique($fields, false);
77
+        }
78 78
 
79 79
 /**
80 80
  *
@@ -82,18 +82,18 @@  discard block
 block discarded – undo
82 82
  * @param int $user_id
83 83
  * @return bool
84 84
  */
85
-		public function isBookmarked($entryId, $userId) {
86
-			$result = $this->find(
87
-				'first',
88
-				array(
89
-					'contain' => false,
90
-					'conditions' => array(
91
-						$this->alias . '.entry_id' => $entryId,
92
-						$this->alias . '.user_id' => $userId,
93
-					)
94
-				)
95
-			);
96
-			return $result == true;
97
-		}
85
+        public function isBookmarked($entryId, $userId) {
86
+            $result = $this->find(
87
+                'first',
88
+                array(
89
+                    'contain' => false,
90
+                    'conditions' => array(
91
+                        $this->alias . '.entry_id' => $entryId,
92
+                        $this->alias . '.user_id' => $userId,
93
+                    )
94
+                )
95
+            );
96
+            return $result == true;
97
+        }
98 98
 
99
-	}
99
+    }
Please login to merge, or discard this patch.
app/Model/Entry.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -518,7 +518,7 @@
 block discarded – undo
518 518
 		/**
519 519
 		 * trees for multiple tids
520 520
 		 *
521
-		 * @param $ids
521
+		 * @param integer[] $ids
522 522
 		 * @param null $order
523 523
 		 * @param null $fieldlist
524 524
 		 * @return array|bool false if no threads or array with Posting
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
 				'category_id' => $User->Categories->getAllowed()
212 212
 			];
213 213
 
214
-			$_cacheKey = 'Entry.recentEntries-' . md5(serialize($options));
214
+			$_cacheKey = 'Entry.recentEntries-'.md5(serialize($options));
215 215
 			$_cachedEntry = Cache::read($_cacheKey, 'entries');
216 216
 			if ($_cachedEntry) {
217 217
 				Stopwatch::stop('Model->User->getRecentEntries()');
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 				]
262 262
 			);
263 263
 			if ($entry == false) {
264
-				throw new UnexpectedValueException('Posting not found. Posting-Id: ' . $id);
264
+				throw new UnexpectedValueException('Posting not found. Posting-Id: '.$id);
265 265
 			}
266 266
 			return $entry['Entry']['tid'];
267 267
 		}
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
  */
272 272
 		public function get($id) {
273 273
 			return $this->find('entry',
274
-					['conditions' => [$this->alias . '.id' => $id]]);
274
+					['conditions' => [$this->alias.'.id' => $id]]);
275 275
 		}
276 276
 
277 277
 /**
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
 				]
291 291
 			);
292 292
 			if ($entry == false) {
293
-				throw new UnexpectedValueException('Posting not found. Posting-Id: ' . $id);
293
+				throw new UnexpectedValueException('Posting not found. Posting-Id: '.$id);
294 294
 			}
295 295
 			return $entry['Entry']['pid'];
296 296
 		}
@@ -508,7 +508,7 @@  discard block
 block discarded – undo
508 508
 
509 509
 			$tree = $this->treesForThreads([$tid], null, $fields);
510 510
 
511
-			if ((int)$tid !== (int)$id) {
511
+			if ((int) $tid !== (int) $id) {
512 512
 				$tree = $this->treeGetSubtree($tree, $id);
513 513
 			}
514 514
 
@@ -551,7 +551,7 @@  discard block
 block discarded – undo
551 551
 				$threads = [];
552 552
 				$entries = $this->treeBuild($entries);
553 553
 				foreach ($entries as $thread) {
554
-					$id = (int)$thread['Entry']['tid'];
554
+					$id = (int) $thread['Entry']['tid'];
555 555
 					$threads[$id] = $thread;
556 556
 				}
557 557
 			}
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
 			}
608 608
 
609 609
 			$root = $this->get($entry['Entry']['tid']);
610
-			if ((int)$root['User']['id'] !== $this->CurrentUser->getId()) {
610
+			if ((int) $root['User']['id'] !== $this->CurrentUser->getId()) {
611 611
 				throw new ForbiddenException;
612 612
 			}
613 613
 
@@ -691,7 +691,7 @@  discard block
 block discarded – undo
691 691
 
692 692
 			$_idsToDelete = $this->getIdsForNode($id);
693 693
 			$success = $this->deleteAll(
694
-				[$this->alias . '.id' => $_idsToDelete],
694
+				[$this->alias.'.id' => $_idsToDelete],
695 695
 				true,
696 696
 				true
697 697
 			);
@@ -723,8 +723,8 @@  discard block
 block discarded – undo
723 723
  */
724 724
 		public function getIdsForNode($id) {
725 725
 			$subthread = $this->treeForNode($id);
726
-			$func = function (&$tree, &$entry) {
727
-				$tree['ids'][] = (int)$entry['Entry']['id'];
726
+			$func = function(&$tree, &$entry) {
727
+				$tree['ids'][] = (int) $entry['Entry']['id'];
728 728
 			};
729 729
 			Entry::mapTreeElements($subthread, $func);
730 730
 			sort($subthread['ids']);
@@ -841,7 +841,7 @@  discard block
 block discarded – undo
841 841
 				}
842 842
 
843 843
 				// propagate pinned property from target to source
844
-				$isTargetPinned = (bool)$targetEntry[$this->alias]['locked'];
844
+				$isTargetPinned = (bool) $targetEntry[$this->alias]['locked'];
845 845
 				if ($sourceEntry[$this->alias]['locked'] !== $isTargetPinned) {
846 846
 					$this->id = $targetEntry[$this->alias]['tid'];
847 847
 					$this->_threadLock($isTargetPinned);
@@ -1036,8 +1036,8 @@  discard block
 block discarded – undo
1036 1036
 				$oldEntry = $this->find('first',
1037 1037
 					['contain' => false, 'conditions' => ['Entry.id' => $this->id]]);
1038 1038
 
1039
-				if ($oldEntry && (int)$oldEntry[$this->alias]['pid'] === 0) {
1040
-					$categoryChanged = (int)$this->data[$this->alias]['category_id'] !== (int)$oldEntry[$this->alias]['category_id'];
1039
+				if ($oldEntry && (int) $oldEntry[$this->alias]['pid'] === 0) {
1040
+					$categoryChanged = (int) $this->data[$this->alias]['category_id'] !== (int) $oldEntry[$this->alias]['category_id'];
1041 1041
 					if ($categoryChanged) {
1042 1042
 						$success = $success && $this->_threadChangeCategory(
1043 1043
 								$oldEntry[$this->alias]['tid'],
Please login to merge, or discard this patch.
Indentation   +935 added lines, -935 removed lines patch added patch discarded remove patch
@@ -1,8 +1,8 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-	use Saito\User\ForumsUserInterface;
3
+    use Saito\User\ForumsUserInterface;
4 4
 
5
-	App::uses('AppModel', 'Model');
5
+    App::uses('AppModel', 'Model');
6 6
 
7 7
 /**
8 8
  *
@@ -23,225 +23,225 @@  discard block
 block discarded – undo
23 23
  * @td After mlf is gone `edited_by` should conatin a User.id, not the username string.
24 24
  *
25 25
  */
26
-	class Entry extends AppModel {
27
-
28
-		public $name = 'Entry';
29
-
30
-		public $primaryKey = 'id';
31
-
32
-		public $actsAs = [
33
-			'Markup',
34
-			'Containable',
35
-			'Search.Searchable',
36
-			'Tree'
37
-		];
38
-
39
-		public $findMethods = array(
40
-			'feed' => true,
41
-			'entry' => true
42
-		);
43
-
44
-		/**
45
-		 * Fields for search plugin
46
-		 *
47
-		 * @var array
48
-		 */
49
-		public $filterArgs = [
50
-				'subject' => ['type' => 'like'],
51
-				'text' => ['type' => 'like'],
52
-				'name' => ['type' => 'like'],
53
-				'category_id' => ['type' => 'value'],
54
-		];
55
-
56
-		public $belongsTo = array(
57
-			'Category' => array(
58
-				'className' => 'Category',
59
-				'foreignKey' => 'category_id',
60
-			),
61
-			'User' => array(
62
-				'className' => 'User',
63
-				'foreignKey' => 'user_id',
64
-				'counterCache' => true,
65
-			),
66
-		);
67
-
68
-		public $hasMany = array(
69
-			'Bookmark' => array(
70
-				'foreignKey' => 'entry_id',
71
-				'dependent' => true,
72
-			),
73
-			'Esevent' => array(
74
-				'foreignKey' => 'subject',
75
-				'conditions' => array('Esevent.subject' => 'Entry.id'),
76
-			),
77
-			'UserRead' => [
78
-				'foreignKey' => 'entry_id',
79
-				'dependent' => true
80
-			]
81
-		);
82
-
83
-		public $validate = [
84
-				'subject' => [
85
-						'notEmpty' => ['rule' => 'notBlank'],
86
-						'maxLength' => ['rule' => 'validateSubjectMaxLength']
87
-				],
88
-				'category_id' => [
89
-						'notEmpty' => ['rule' => 'notBlank'],
90
-						'numeric' => ['rule' => 'numeric'],
91
-						'isAllowed' => ['rule' => 'validateCategoryIsAllowed']
92
-				],
93
-				'user_id' => ['rule' => 'numeric'],
94
-				'views' => ['rule' => ['comparison', '>=', 0]],
95
-			// used in full text search
96
-				'name' => array()
97
-		];
98
-
99
-		/**
100
-		 * Fields allowed in public output
101
-		 *
102
-		 * @var array
103
-		 */
104
-		protected $_allowedPublicOutputFields = [
105
-			'Entry.id',
106
-			'Entry.pid',
107
-			'Entry.tid',
108
-			'Entry.time',
109
-			'Entry.last_answer',
110
-			'Entry.edited',
111
-			'Entry.edited_by',
112
-			'Entry.user_id',
113
-			'Entry.name',
114
-			'Entry.subject',
115
-			'Entry.category_id',
116
-			'Entry.text',
117
-			'Entry.locked',
118
-			'Entry.fixed',
119
-			'Entry.views',
120
-			'User.username'
121
-		];
122
-
123
-		/**
124
-		 * field list necessary for displaying a thread_line
125
-		 *
126
-		 * Entry.text determine if Entry is n/t
127
-		 *
128
-		 * @var string
129
-		 */
130
-		public $threadLineFieldList = [
131
-			'Entry.id',
132
-			'Entry.pid',
133
-			'Entry.tid',
134
-			'Entry.subject',
135
-			'Entry.text',
136
-			'Entry.time',
137
-			'Entry.fixed',
138
-			'Entry.last_answer',
139
-			'Entry.views',
140
-			'Entry.user_id',
141
-			'Entry.locked',
142
-			'Entry.name',
143
-			'Entry.solves',
144
-
145
-			'User.username',
146
-
147
-			'Category.accession',
148
-			'Category.category',
149
-			'Category.description'
150
-		];
151
-
152
-		/**
153
-		 * fields additional to $threadLineFieldList to show complete entry
154
-		 *
155
-		 * @var string
156
-		 */
157
-		public $showEntryFieldListAdditional = [
158
-			'Entry.edited',
159
-			'Entry.edited_by',
160
-			'Entry.ip',
161
-			'Entry.category_id',
162
-
163
-			'User.id',
164
-			'User.signature',
165
-			'User.user_place'
166
-		];
167
-
168
-		/**
169
-		 * Allowed external user input
170
-		 *
171
-		 * @var array
172
-		 */
173
-		public $allowedInputFields = [
174
-			'create' => [
175
-				'category_id',
176
-				'pid',
177
-				'subject',
178
-				'text'
179
-			],
180
-			'update' => [
181
-				'id',
182
-				'category_id',
183
-				'subject',
184
-				'text'
185
-			]
186
-		];
187
-
188
-		protected $_settings = [
189
-			'edit_period' => 20,
190
-			'subject_maxlength' => 100
191
-		];
26
+    class Entry extends AppModel {
27
+
28
+        public $name = 'Entry';
29
+
30
+        public $primaryKey = 'id';
31
+
32
+        public $actsAs = [
33
+            'Markup',
34
+            'Containable',
35
+            'Search.Searchable',
36
+            'Tree'
37
+        ];
38
+
39
+        public $findMethods = array(
40
+            'feed' => true,
41
+            'entry' => true
42
+        );
43
+
44
+        /**
45
+         * Fields for search plugin
46
+         *
47
+         * @var array
48
+         */
49
+        public $filterArgs = [
50
+                'subject' => ['type' => 'like'],
51
+                'text' => ['type' => 'like'],
52
+                'name' => ['type' => 'like'],
53
+                'category_id' => ['type' => 'value'],
54
+        ];
55
+
56
+        public $belongsTo = array(
57
+            'Category' => array(
58
+                'className' => 'Category',
59
+                'foreignKey' => 'category_id',
60
+            ),
61
+            'User' => array(
62
+                'className' => 'User',
63
+                'foreignKey' => 'user_id',
64
+                'counterCache' => true,
65
+            ),
66
+        );
67
+
68
+        public $hasMany = array(
69
+            'Bookmark' => array(
70
+                'foreignKey' => 'entry_id',
71
+                'dependent' => true,
72
+            ),
73
+            'Esevent' => array(
74
+                'foreignKey' => 'subject',
75
+                'conditions' => array('Esevent.subject' => 'Entry.id'),
76
+            ),
77
+            'UserRead' => [
78
+                'foreignKey' => 'entry_id',
79
+                'dependent' => true
80
+            ]
81
+        );
82
+
83
+        public $validate = [
84
+                'subject' => [
85
+                        'notEmpty' => ['rule' => 'notBlank'],
86
+                        'maxLength' => ['rule' => 'validateSubjectMaxLength']
87
+                ],
88
+                'category_id' => [
89
+                        'notEmpty' => ['rule' => 'notBlank'],
90
+                        'numeric' => ['rule' => 'numeric'],
91
+                        'isAllowed' => ['rule' => 'validateCategoryIsAllowed']
92
+                ],
93
+                'user_id' => ['rule' => 'numeric'],
94
+                'views' => ['rule' => ['comparison', '>=', 0]],
95
+            // used in full text search
96
+                'name' => array()
97
+        ];
98
+
99
+        /**
100
+         * Fields allowed in public output
101
+         *
102
+         * @var array
103
+         */
104
+        protected $_allowedPublicOutputFields = [
105
+            'Entry.id',
106
+            'Entry.pid',
107
+            'Entry.tid',
108
+            'Entry.time',
109
+            'Entry.last_answer',
110
+            'Entry.edited',
111
+            'Entry.edited_by',
112
+            'Entry.user_id',
113
+            'Entry.name',
114
+            'Entry.subject',
115
+            'Entry.category_id',
116
+            'Entry.text',
117
+            'Entry.locked',
118
+            'Entry.fixed',
119
+            'Entry.views',
120
+            'User.username'
121
+        ];
122
+
123
+        /**
124
+         * field list necessary for displaying a thread_line
125
+         *
126
+         * Entry.text determine if Entry is n/t
127
+         *
128
+         * @var string
129
+         */
130
+        public $threadLineFieldList = [
131
+            'Entry.id',
132
+            'Entry.pid',
133
+            'Entry.tid',
134
+            'Entry.subject',
135
+            'Entry.text',
136
+            'Entry.time',
137
+            'Entry.fixed',
138
+            'Entry.last_answer',
139
+            'Entry.views',
140
+            'Entry.user_id',
141
+            'Entry.locked',
142
+            'Entry.name',
143
+            'Entry.solves',
144
+
145
+            'User.username',
146
+
147
+            'Category.accession',
148
+            'Category.category',
149
+            'Category.description'
150
+        ];
151
+
152
+        /**
153
+         * fields additional to $threadLineFieldList to show complete entry
154
+         *
155
+         * @var string
156
+         */
157
+        public $showEntryFieldListAdditional = [
158
+            'Entry.edited',
159
+            'Entry.edited_by',
160
+            'Entry.ip',
161
+            'Entry.category_id',
162
+
163
+            'User.id',
164
+            'User.signature',
165
+            'User.user_place'
166
+        ];
167
+
168
+        /**
169
+         * Allowed external user input
170
+         *
171
+         * @var array
172
+         */
173
+        public $allowedInputFields = [
174
+            'create' => [
175
+                'category_id',
176
+                'pid',
177
+                'subject',
178
+                'text'
179
+            ],
180
+            'update' => [
181
+                'id',
182
+                'category_id',
183
+                'subject',
184
+                'text'
185
+            ]
186
+        ];
187
+
188
+        protected $_settings = [
189
+            'edit_period' => 20,
190
+            'subject_maxlength' => 100
191
+        ];
192 192
 
193 193
 /**
194 194
  * Caching for isRoot()
195 195
  *
196 196
  * @var array
197 197
  */
198
-		protected $_isRoot = [];
199
-
200
-		/**
201
-		 * @param ForumsUserInterface $User
202
-		 * @param array $options
203
-		 * @return array|mixed
204
-		 */
205
-		public function getRecentEntries(CurrentUserComponent $User, array $options = []) {
206
-			Stopwatch::start('Model->User->getRecentEntries()');
207
-
208
-			$options += [
209
-				'user_id' => null,
210
-				'limit' => 10,
211
-				'category_id' => $User->Categories->getAllowed()
212
-			];
213
-
214
-			$_cacheKey = 'Entry.recentEntries-' . md5(serialize($options));
215
-			$_cachedEntry = Cache::read($_cacheKey, 'entries');
216
-			if ($_cachedEntry) {
217
-				Stopwatch::stop('Model->User->getRecentEntries()');
218
-				return $_cachedEntry;
219
-			}
220
-
221
-			$conditions = array();
222
-			if ($options['user_id'] !== null) {
223
-				$conditions[]['Entry.user_id'] = $options['user_id'];
224
-			}
225
-			if ($options['category_id'] !== null):
226
-				$conditions[]['Entry.category_id'] = $options['category_id'];
227
-			endif;
228
-
229
-			$result = $this->find(
230
-				'all',
231
-				[
232
-					'contain' => array('User', 'Category'),
233
-					'fields' => $this->threadLineFieldList,
234
-					'conditions' => $conditions,
235
-					'limit' => $options['limit'],
236
-					'order' => 'time DESC'
237
-				]
238
-			);
239
-
240
-			Cache::write($_cacheKey, $result, 'entries');
241
-
242
-			Stopwatch::stop('Model->User->getRecentEntries()');
243
-			return $result;
244
-		}
198
+        protected $_isRoot = [];
199
+
200
+        /**
201
+         * @param ForumsUserInterface $User
202
+         * @param array $options
203
+         * @return array|mixed
204
+         */
205
+        public function getRecentEntries(CurrentUserComponent $User, array $options = []) {
206
+            Stopwatch::start('Model->User->getRecentEntries()');
207
+
208
+            $options += [
209
+                'user_id' => null,
210
+                'limit' => 10,
211
+                'category_id' => $User->Categories->getAllowed()
212
+            ];
213
+
214
+            $_cacheKey = 'Entry.recentEntries-' . md5(serialize($options));
215
+            $_cachedEntry = Cache::read($_cacheKey, 'entries');
216
+            if ($_cachedEntry) {
217
+                Stopwatch::stop('Model->User->getRecentEntries()');
218
+                return $_cachedEntry;
219
+            }
220
+
221
+            $conditions = array();
222
+            if ($options['user_id'] !== null) {
223
+                $conditions[]['Entry.user_id'] = $options['user_id'];
224
+            }
225
+            if ($options['category_id'] !== null):
226
+                $conditions[]['Entry.category_id'] = $options['category_id'];
227
+            endif;
228
+
229
+            $result = $this->find(
230
+                'all',
231
+                [
232
+                    'contain' => array('User', 'Category'),
233
+                    'fields' => $this->threadLineFieldList,
234
+                    'conditions' => $conditions,
235
+                    'limit' => $options['limit'],
236
+                    'order' => 'time DESC'
237
+                ]
238
+            );
239
+
240
+            Cache::write($_cacheKey, $result, 'entries');
241
+
242
+            Stopwatch::stop('Model->User->getRecentEntries()');
243
+            return $result;
244
+        }
245 245
 
246 246
 /**
247 247
  * Finds the thread-id for a posting
@@ -250,233 +250,233 @@  discard block
 block discarded – undo
250 250
  * @return int Thread-Id
251 251
  * @throws UnexpectedValueException
252 252
  */
253
-		public function getThreadId($id) {
254
-			$entry = $this->find(
255
-				'first',
256
-				[
257
-					'contain' => false,
258
-					'conditions' => ['Entry.id' => $id],
259
-					'fields' => 'Entry.tid'
260
-
261
-				]
262
-			);
263
-			if ($entry == false) {
264
-				throw new UnexpectedValueException('Posting not found. Posting-Id: ' . $id);
265
-			}
266
-			return $entry['Entry']['tid'];
267
-		}
253
+        public function getThreadId($id) {
254
+            $entry = $this->find(
255
+                'first',
256
+                [
257
+                    'contain' => false,
258
+                    'conditions' => ['Entry.id' => $id],
259
+                    'fields' => 'Entry.tid'
260
+
261
+                ]
262
+            );
263
+            if ($entry == false) {
264
+                throw new UnexpectedValueException('Posting not found. Posting-Id: ' . $id);
265
+            }
266
+            return $entry['Entry']['tid'];
267
+        }
268 268
 
269 269
 /**
270 270
  * Shorthand for reading an entry with full data
271 271
  */
272
-		public function get($id) {
273
-			return $this->find('entry',
274
-					['conditions' => [$this->alias . '.id' => $id]]);
275
-		}
272
+        public function get($id) {
273
+            return $this->find('entry',
274
+                    ['conditions' => [$this->alias . '.id' => $id]]);
275
+        }
276 276
 
277 277
 /**
278 278
  * @param $id
279 279
  * @return mixed
280 280
  * @throws UnexpectedValueException
281 281
  */
282
-		public function getParentId($id) {
283
-			$entry = $this->find(
284
-				'first',
285
-				[
286
-					'contain' => false,
287
-					'conditions' => ['Entry.id' => $id],
288
-					'fields' => 'Entry.pid'
289
-
290
-				]
291
-			);
292
-			if ($entry == false) {
293
-				throw new UnexpectedValueException('Posting not found. Posting-Id: ' . $id);
294
-			}
295
-			return $entry['Entry']['pid'];
296
-		}
297
-
298
-		/**
299
-		 * creates a new root or child entry for a node
300
-		 *
301
-		 * fields in $data are filtered
302
-		 *
303
-		 * @param $data
304
-		 * @return array|bool|mixed
305
-		 */
306
-		public function createPosting($data) {
307
-			if (!isset($data[$this->alias]['pid'])) {
308
-				$data[$this->alias]['pid'] = 0;
309
-			}
310
-
311
-			if (isset($data[$this->alias]['subject']) === false) {
312
-				return false;
313
-			}
314
-
315
-			try {
316
-				$this->prepare($data, ['preFilterFields' => 'create']);
317
-			} catch (Exception $e) {
318
-				return false;
319
-			}
320
-
321
-			$data[$this->alias]['user_id'] = $this->CurrentUser->getId();
322
-			$data[$this->alias]['name'] = $this->CurrentUser['username'];
323
-
324
-			$data[$this->alias]['time'] = bDate();
325
-			$data[$this->alias]['last_answer'] = bDate();
326
-			$data[$this->alias]['ip'] = self::_getIp();
327
-
328
-			$this->create();
329
-			$_newPosting = $this->save($data);
330
-
331
-			if ($_newPosting === false) {
332
-				return false;
333
-			}
334
-
335
-			$_newPostingId = $this->id;
336
-
337
-			// make sure we pass the complete ['Entry'] dataset to events
338
-			$this->contain();
339
-			$_newPosting = $this->read();
340
-
341
-			if ($this->isRoot($data)) {
342
-				// thread-id of new thread is its own id
343
-				if ($this->save(['tid' => $_newPostingId], false, ['tid']) === false) {
344
-					// @td raise error and/or roll back new entry
345
-					return false;
346
-				} else {
347
-					$_newPosting[$this->alias]['tid'] = $_newPostingId;
348
-					$this->Category->id = $data[$this->alias]['category_id'];
349
-					$this->Category->updateThreadCounter();
350
-				}
351
-				$this->_dispatchEvent(
352
-					'Model.Thread.create',
353
-					[
354
-						'subject' => $_newPosting[$this->alias]['id'],
355
-						'data' => $_newPosting
356
-					]
357
-				);
358
-			} else {
359
-				// update last answer time of root entry
360
-				$this->clear();
361
-				$this->id = $_newPosting[$this->alias]['tid'];
362
-				$this->set('last_answer', $_newPosting[$this->alias]['last_answer']);
363
-				if ($this->save() === false) {
364
-					// @td raise error and/or roll back new entry
365
-					return false;
366
-				}
367
-
368
-				$this->_dispatchEvent(
369
-					'Model.Entry.replyToEntry',
370
-					[
371
-						'subject' => $_newPosting[$this->alias]['pid'],
372
-						'data' => $_newPosting
373
-					]
374
-				);
375
-				$this->_dispatchEvent(
376
-					'Model.Entry.replyToThread',
377
-					[
378
-						'subject' => $_newPosting[$this->alias]['tid'],
379
-						'data' => $_newPosting
380
-					]
381
-				);
382
-			}
383
-
384
-			$this->id = $_newPostingId;
385
-			$_newPosting[$this->alias]['subject'] = Sanitize::html($_newPosting[$this->alias]['subject']);
386
-			$_newPosting[$this->alias]['text'] = Sanitize::html($_newPosting[$this->alias]['text']);
387
-			return $_newPosting;
388
-		}
389
-
390
-		/**
391
-		 * Updates a posting
392
-		 *
393
-		 * fields in $data are filtered except for $id!
394
-		 *
395
-		 * @param $data
396
-		 * @param null $CurrentUser
397
-		 * @return array|mixed
398
-		 * @throws NotFoundException
399
-		 * @throws InvalidArgumentException
400
-		 */
401
-		public function update($data, $CurrentUser = null) {
402
-			if ($CurrentUser !== null) {
403
-				$this->CurrentUser = $CurrentUser;
404
-			}
405
-
406
-			if (empty($data[$this->alias]['id'])) {
407
-				throw new InvalidArgumentException('Missing entry id in arguments.');
408
-			}
409
-
410
-			$id = $data[$this->alias]['id'];
411
-			if (!$this->exists($id)) {
412
-				throw new NotFoundException(sprintf('Entry with id `%s` not found.', $id));
413
-			}
414
-
415
-			$this->prepare($data, ['preFilterFields' => 'update']);
416
-
417
-			// prevents normal user of changing category of complete thread when answering
418
-			// @todo this should be refactored together with the change category handling in beforeSave()
419
-			if ($this->isRoot($data) === false) {
420
-				unset($data[$this->alias]['category_id']);
421
-			}
422
-
423
-			$data[$this->alias]['edited'] = bDate();
424
-			$data[$this->alias]['edited_by'] = $this->CurrentUser['username'];
425
-
426
-			$this->validator()->add(
427
-				'edited_by',
428
-				'isEditingAllowed',
429
-				[
430
-					'rule' => 'validateEditingAllowed'
431
-				]
432
-			);
433
-
434
-			$result = $this->save($data);
435
-
436
-			if ($result) {
437
-				$this->contain();
438
-				$result = $this->read() + $data;
439
-				$this->_dispatchEvent(
440
-					'Model.Entry.update',
441
-					[
442
-						'subject' => $result[$this->alias]['id'],
443
-						'data' => $result
444
-					]
445
-				);
446
-			}
447
-
448
-			return $result;
449
-		}
450
-
451
-		/**
452
-		 * Update view counter on all entries in a thread
453
-		 *
454
-		 * Note that this function unbinds the model associations for performance.
455
-		 * Otherwise updateAll() left joins all associated models.
456
-		 *
457
-		 * @param $tid thread-ID
458
-		 * @param $uid entries with this user-id are not updated
459
-		 */
460
-		public function threadIncrementViews($tid, $uid = null) {
461
-			Stopwatch::start('Entry::threadIncrementViews');
462
-			$_where = ['Entry.tid' => $tid];
463
-			if ($uid && is_int($uid)) {
464
-				$_where['Entry.user_id !='] = $uid;
465
-			}
466
-			// $_belongsTo = $this->belongsTo;
467
-			$this->unbindModel(['belongsTo' => array_keys($this->belongsTo)]);
468
-			$this->updateAll(['Entry.views' => 'Entry.views + 1'], $_where);
469
-			// $this->bindModel(['belongsTo' => $_belongsTo]);
470
-			Stopwatch::stop('Entry::threadIncrementViews');
471
-		}
282
+        public function getParentId($id) {
283
+            $entry = $this->find(
284
+                'first',
285
+                [
286
+                    'contain' => false,
287
+                    'conditions' => ['Entry.id' => $id],
288
+                    'fields' => 'Entry.pid'
289
+
290
+                ]
291
+            );
292
+            if ($entry == false) {
293
+                throw new UnexpectedValueException('Posting not found. Posting-Id: ' . $id);
294
+            }
295
+            return $entry['Entry']['pid'];
296
+        }
297
+
298
+        /**
299
+         * creates a new root or child entry for a node
300
+         *
301
+         * fields in $data are filtered
302
+         *
303
+         * @param $data
304
+         * @return array|bool|mixed
305
+         */
306
+        public function createPosting($data) {
307
+            if (!isset($data[$this->alias]['pid'])) {
308
+                $data[$this->alias]['pid'] = 0;
309
+            }
310
+
311
+            if (isset($data[$this->alias]['subject']) === false) {
312
+                return false;
313
+            }
314
+
315
+            try {
316
+                $this->prepare($data, ['preFilterFields' => 'create']);
317
+            } catch (Exception $e) {
318
+                return false;
319
+            }
320
+
321
+            $data[$this->alias]['user_id'] = $this->CurrentUser->getId();
322
+            $data[$this->alias]['name'] = $this->CurrentUser['username'];
323
+
324
+            $data[$this->alias]['time'] = bDate();
325
+            $data[$this->alias]['last_answer'] = bDate();
326
+            $data[$this->alias]['ip'] = self::_getIp();
327
+
328
+            $this->create();
329
+            $_newPosting = $this->save($data);
330
+
331
+            if ($_newPosting === false) {
332
+                return false;
333
+            }
334
+
335
+            $_newPostingId = $this->id;
336
+
337
+            // make sure we pass the complete ['Entry'] dataset to events
338
+            $this->contain();
339
+            $_newPosting = $this->read();
340
+
341
+            if ($this->isRoot($data)) {
342
+                // thread-id of new thread is its own id
343
+                if ($this->save(['tid' => $_newPostingId], false, ['tid']) === false) {
344
+                    // @td raise error and/or roll back new entry
345
+                    return false;
346
+                } else {
347
+                    $_newPosting[$this->alias]['tid'] = $_newPostingId;
348
+                    $this->Category->id = $data[$this->alias]['category_id'];
349
+                    $this->Category->updateThreadCounter();
350
+                }
351
+                $this->_dispatchEvent(
352
+                    'Model.Thread.create',
353
+                    [
354
+                        'subject' => $_newPosting[$this->alias]['id'],
355
+                        'data' => $_newPosting
356
+                    ]
357
+                );
358
+            } else {
359
+                // update last answer time of root entry
360
+                $this->clear();
361
+                $this->id = $_newPosting[$this->alias]['tid'];
362
+                $this->set('last_answer', $_newPosting[$this->alias]['last_answer']);
363
+                if ($this->save() === false) {
364
+                    // @td raise error and/or roll back new entry
365
+                    return false;
366
+                }
367
+
368
+                $this->_dispatchEvent(
369
+                    'Model.Entry.replyToEntry',
370
+                    [
371
+                        'subject' => $_newPosting[$this->alias]['pid'],
372
+                        'data' => $_newPosting
373
+                    ]
374
+                );
375
+                $this->_dispatchEvent(
376
+                    'Model.Entry.replyToThread',
377
+                    [
378
+                        'subject' => $_newPosting[$this->alias]['tid'],
379
+                        'data' => $_newPosting
380
+                    ]
381
+                );
382
+            }
383
+
384
+            $this->id = $_newPostingId;
385
+            $_newPosting[$this->alias]['subject'] = Sanitize::html($_newPosting[$this->alias]['subject']);
386
+            $_newPosting[$this->alias]['text'] = Sanitize::html($_newPosting[$this->alias]['text']);
387
+            return $_newPosting;
388
+        }
389
+
390
+        /**
391
+         * Updates a posting
392
+         *
393
+         * fields in $data are filtered except for $id!
394
+         *
395
+         * @param $data
396
+         * @param null $CurrentUser
397
+         * @return array|mixed
398
+         * @throws NotFoundException
399
+         * @throws InvalidArgumentException
400
+         */
401
+        public function update($data, $CurrentUser = null) {
402
+            if ($CurrentUser !== null) {
403
+                $this->CurrentUser = $CurrentUser;
404
+            }
405
+
406
+            if (empty($data[$this->alias]['id'])) {
407
+                throw new InvalidArgumentException('Missing entry id in arguments.');
408
+            }
409
+
410
+            $id = $data[$this->alias]['id'];
411
+            if (!$this->exists($id)) {
412
+                throw new NotFoundException(sprintf('Entry with id `%s` not found.', $id));
413
+            }
414
+
415
+            $this->prepare($data, ['preFilterFields' => 'update']);
416
+
417
+            // prevents normal user of changing category of complete thread when answering
418
+            // @todo this should be refactored together with the change category handling in beforeSave()
419
+            if ($this->isRoot($data) === false) {
420
+                unset($data[$this->alias]['category_id']);
421
+            }
422
+
423
+            $data[$this->alias]['edited'] = bDate();
424
+            $data[$this->alias]['edited_by'] = $this->CurrentUser['username'];
425
+
426
+            $this->validator()->add(
427
+                'edited_by',
428
+                'isEditingAllowed',
429
+                [
430
+                    'rule' => 'validateEditingAllowed'
431
+                ]
432
+            );
433
+
434
+            $result = $this->save($data);
435
+
436
+            if ($result) {
437
+                $this->contain();
438
+                $result = $this->read() + $data;
439
+                $this->_dispatchEvent(
440
+                    'Model.Entry.update',
441
+                    [
442
+                        'subject' => $result[$this->alias]['id'],
443
+                        'data' => $result
444
+                    ]
445
+                );
446
+            }
447
+
448
+            return $result;
449
+        }
450
+
451
+        /**
452
+         * Update view counter on all entries in a thread
453
+         *
454
+         * Note that this function unbinds the model associations for performance.
455
+         * Otherwise updateAll() left joins all associated models.
456
+         *
457
+         * @param $tid thread-ID
458
+         * @param $uid entries with this user-id are not updated
459
+         */
460
+        public function threadIncrementViews($tid, $uid = null) {
461
+            Stopwatch::start('Entry::threadIncrementViews');
462
+            $_where = ['Entry.tid' => $tid];
463
+            if ($uid && is_int($uid)) {
464
+                $_where['Entry.user_id !='] = $uid;
465
+            }
466
+            // $_belongsTo = $this->belongsTo;
467
+            $this->unbindModel(['belongsTo' => array_keys($this->belongsTo)]);
468
+            $this->updateAll(['Entry.views' => 'Entry.views + 1'], $_where);
469
+            // $this->bindModel(['belongsTo' => $_belongsTo]);
470
+            Stopwatch::stop('Entry::threadIncrementViews');
471
+        }
472 472
 
473 473
 /**
474 474
  *
475 475
  * @mb `views` into extra related table if performance becomes a problem
476 476
  */
477
-		public function incrementViews($id, $amount = 1) {
478
-			$this->increment($id, 'views', $amount);
479
-		}
477
+        public function incrementViews($id, $amount = 1) {
478
+            $this->increment($id, 'views', $amount);
479
+        }
480 480
 
481 481
 /**
482 482
  * tree of a single node and its subentries
@@ -489,77 +489,77 @@  discard block
 block discarded – undo
489 489
  * @param array $options
490 490
  * @return array tree
491 491
  */
492
-		public function treeForNode($id, $options = array()) {
493
-			$options += [
494
-				'root' => false,
495
-				'complete' => false
496
-			];
497
-
498
-			if ($options['root']) {
499
-				$tid = $id;
500
-			} else {
501
-				$tid = $this->getThreadId($id);
502
-			}
503
-
504
-			$fields = null;
505
-			if ($options['complete']) {
506
-				$fields = array_merge($this->threadLineFieldList, $this->showEntryFieldListAdditional);
507
-			}
508
-
509
-			$tree = $this->treesForThreads([$tid], null, $fields);
510
-
511
-			if ((int)$tid !== (int)$id) {
512
-				$tree = $this->treeGetSubtree($tree, $id);
513
-			}
514
-
515
-			return $tree;
516
-		}
517
-
518
-		/**
519
-		 * trees for multiple tids
520
-		 *
521
-		 * @param $ids
522
-		 * @param null $order
523
-		 * @param null $fieldlist
524
-		 * @return array|bool false if no threads or array with Posting
525
-		 */
526
-		public function treesForThreads($ids, $order = null, $fieldlist = null) {
527
-			if (empty($ids)) {
528
-				return [];
529
-			}
530
-
531
-			Stopwatch::start('Model->Entries->treeForThreads() DB');
532
-
533
-			if (empty($order)) {
534
-				$order = 'last_answer ASC';
535
-			}
536
-
537
-			if ($fieldlist === null) {
538
-				$fieldlist = $this->threadLineFieldList;
539
-			}
540
-
541
-			$entries = $this->_getThreadEntries(
542
-				$ids,
543
-				['order' => $order, 'fields' => $fieldlist]
544
-			);
545
-
546
-			Stopwatch::stop('Model->Entries->treeForThreads() DB');
547
-			Stopwatch::start('Model->Entries->treeForThreads() CPU');
548
-
549
-			$threads = false;
550
-			if ($entries) {
551
-				$threads = [];
552
-				$entries = $this->treeBuild($entries);
553
-				foreach ($entries as $thread) {
554
-					$id = (int)$thread['Entry']['tid'];
555
-					$threads[$id] = $thread;
556
-				}
557
-			}
558
-
559
-			Stopwatch::stop('Model->Entries->treeForThreads() CPU');
560
-
561
-			return $threads;
562
-		}
492
+        public function treeForNode($id, $options = array()) {
493
+            $options += [
494
+                'root' => false,
495
+                'complete' => false
496
+            ];
497
+
498
+            if ($options['root']) {
499
+                $tid = $id;
500
+            } else {
501
+                $tid = $this->getThreadId($id);
502
+            }
503
+
504
+            $fields = null;
505
+            if ($options['complete']) {
506
+                $fields = array_merge($this->threadLineFieldList, $this->showEntryFieldListAdditional);
507
+            }
508
+
509
+            $tree = $this->treesForThreads([$tid], null, $fields);
510
+
511
+            if ((int)$tid !== (int)$id) {
512
+                $tree = $this->treeGetSubtree($tree, $id);
513
+            }
514
+
515
+            return $tree;
516
+        }
517
+
518
+        /**
519
+         * trees for multiple tids
520
+         *
521
+         * @param $ids
522
+         * @param null $order
523
+         * @param null $fieldlist
524
+         * @return array|bool false if no threads or array with Posting
525
+         */
526
+        public function treesForThreads($ids, $order = null, $fieldlist = null) {
527
+            if (empty($ids)) {
528
+                return [];
529
+            }
530
+
531
+            Stopwatch::start('Model->Entries->treeForThreads() DB');
532
+
533
+            if (empty($order)) {
534
+                $order = 'last_answer ASC';
535
+            }
536
+
537
+            if ($fieldlist === null) {
538
+                $fieldlist = $this->threadLineFieldList;
539
+            }
540
+
541
+            $entries = $this->_getThreadEntries(
542
+                $ids,
543
+                ['order' => $order, 'fields' => $fieldlist]
544
+            );
545
+
546
+            Stopwatch::stop('Model->Entries->treeForThreads() DB');
547
+            Stopwatch::start('Model->Entries->treeForThreads() CPU');
548
+
549
+            $threads = false;
550
+            if ($entries) {
551
+                $threads = [];
552
+                $entries = $this->treeBuild($entries);
553
+                foreach ($entries as $thread) {
554
+                    $id = (int)$thread['Entry']['tid'];
555
+                    $threads[$id] = $thread;
556
+                }
557
+            }
558
+
559
+            Stopwatch::stop('Model->Entries->treeForThreads() CPU');
560
+
561
+            return $threads;
562
+        }
563 563
 
564 564
 /**
565 565
  * @param       $tid
@@ -574,82 +574,82 @@  discard block
 block discarded – undo
574 574
  *  )
575 575
  * </pre>
576 576
  */
577
-		protected function _getThreadEntries($tid, array $params = []) {
578
-			$params += [
579
-				'fields' => $this->threadLineFieldList,
580
-				'order' => 'last_answer ASC'
581
-			];
582
-			$threads = $this->find(
583
-				'all',
584
-				[
585
-					'conditions' => ['tid' => $tid],
586
-					'contain' => ['User', 'Category'],
587
-					'fields' => $params['fields'],
588
-					'order' => $params['order']
589
-				]
590
-			);
591
-
592
-			return $threads;
593
-		}
594
-
595
-		/**
596
-		 * Marks a sub-entry as solution to a root entry
597
-		 *
598
-		 * @param $id
599
-		 * @return bool
600
-		 * @throws InvalidArgumentException
601
-		 * @throws ForbiddenException
602
-		 */
603
-		public function toggleSolve($id) {
604
-			$entry = $this->get($id);
605
-			if (empty($entry) || $this->isRoot($entry)) {
606
-				throw new InvalidArgumentException;
607
-			}
608
-
609
-			$root = $this->get($entry['Entry']['tid']);
610
-			if ((int)$root['User']['id'] !== $this->CurrentUser->getId()) {
611
-				throw new ForbiddenException;
612
-			}
613
-
614
-			if ($entry[$this->alias]['solves']) {
615
-				$value = 0;
616
-			} else {
617
-				$value = $entry[$this->alias]['tid'];
618
-			}
619
-			$this->id = $id;
620
-			$success = $this->saveField('solves', $value);
621
-			if (!$success) {
622
-				return $success;
623
-			}
624
-			$this->_dispatchEvent('Model.Entry.update',
625
-					['subject' => $id, 'data' => $entry]);
626
-			$entry[$this->alias]['solves'] = $value;
627
-			return $success;
628
-		}
629
-
630
-		public function toggle($key) {
631
-			$result = parent::toggle($key);
632
-			if ($key === 'locked') {
633
-				$this->_threadLock($result);
634
-			}
635
-
636
-			$this->contain();
637
-			$entry = $this->read();
638
-
639
-			$this->_dispatchEvent(
640
-				'Model.Entry.update',
641
-				[
642
-					'subject' => $entry[$this->alias]['id'],
643
-					'data' => $entry
644
-				]
645
-			);
646
-
647
-			return $result;
648
-		}
649
-
650
-		public function beforeFind($queryData) {
651
-			parent::beforeFind($queryData);
652
-			/*
577
+        protected function _getThreadEntries($tid, array $params = []) {
578
+            $params += [
579
+                'fields' => $this->threadLineFieldList,
580
+                'order' => 'last_answer ASC'
581
+            ];
582
+            $threads = $this->find(
583
+                'all',
584
+                [
585
+                    'conditions' => ['tid' => $tid],
586
+                    'contain' => ['User', 'Category'],
587
+                    'fields' => $params['fields'],
588
+                    'order' => $params['order']
589
+                ]
590
+            );
591
+
592
+            return $threads;
593
+        }
594
+
595
+        /**
596
+         * Marks a sub-entry as solution to a root entry
597
+         *
598
+         * @param $id
599
+         * @return bool
600
+         * @throws InvalidArgumentException
601
+         * @throws ForbiddenException
602
+         */
603
+        public function toggleSolve($id) {
604
+            $entry = $this->get($id);
605
+            if (empty($entry) || $this->isRoot($entry)) {
606
+                throw new InvalidArgumentException;
607
+            }
608
+
609
+            $root = $this->get($entry['Entry']['tid']);
610
+            if ((int)$root['User']['id'] !== $this->CurrentUser->getId()) {
611
+                throw new ForbiddenException;
612
+            }
613
+
614
+            if ($entry[$this->alias]['solves']) {
615
+                $value = 0;
616
+            } else {
617
+                $value = $entry[$this->alias]['tid'];
618
+            }
619
+            $this->id = $id;
620
+            $success = $this->saveField('solves', $value);
621
+            if (!$success) {
622
+                return $success;
623
+            }
624
+            $this->_dispatchEvent('Model.Entry.update',
625
+                    ['subject' => $id, 'data' => $entry]);
626
+            $entry[$this->alias]['solves'] = $value;
627
+            return $success;
628
+        }
629
+
630
+        public function toggle($key) {
631
+            $result = parent::toggle($key);
632
+            if ($key === 'locked') {
633
+                $this->_threadLock($result);
634
+            }
635
+
636
+            $this->contain();
637
+            $entry = $this->read();
638
+
639
+            $this->_dispatchEvent(
640
+                'Model.Entry.update',
641
+                [
642
+                    'subject' => $entry[$this->alias]['id'],
643
+                    'data' => $entry
644
+                ]
645
+            );
646
+
647
+            return $result;
648
+        }
649
+
650
+        public function beforeFind($queryData) {
651
+            parent::beforeFind($queryData);
652
+            /*
653 653
 				* workarround for possible cakephp join error for associated tables
654 654
 				* and virtual fields
655 655
 				*
@@ -659,17 +659,17 @@  discard block
 block discarded – undo
659 659
 				*
660 660
 				* checkout in cakephp mailing list/bug tracker
661 661
 				*/
662
-			$this->User->virtualFields = null;
663
-		}
662
+            $this->User->virtualFields = null;
663
+        }
664 664
 
665
-		public function beforeValidate($options = array()) {
666
-			parent::beforeValidate($options);
665
+        public function beforeValidate($options = array()) {
666
+            parent::beforeValidate($options);
667 667
 
668
-			//* in n/t posting delete unnecessary body text
669
-			if (isset($this->data['Entry']['text'])) {
670
-				$this->data['Entry']['text'] = rtrim($this->data['Entry']['text']);
671
-			}
672
-		}
668
+            //* in n/t posting delete unnecessary body text
669
+            if (isset($this->data['Entry']['text'])) {
670
+                $this->data['Entry']['text'] = rtrim($this->data['Entry']['text']);
671
+            }
672
+        }
673 673
 
674 674
 /**
675 675
  * Deletes entry and all it's subentries and associated data
@@ -677,43 +677,43 @@  discard block
 block discarded – undo
677 677
  * @return bool
678 678
  * @throws Exception
679 679
  */
680
-		public function deleteNode($id = null) {
681
-			if (empty($id)) {
682
-				$id = $this->id;
683
-			}
684
-
685
-			$this->contain();
686
-			$entry = $this->findById($id);
687
-
688
-			if (empty($entry)) {
689
-				throw new Exception;
690
-			}
691
-
692
-			$_idsToDelete = $this->getIdsForNode($id);
693
-			$success = $this->deleteAll(
694
-				[$this->alias . '.id' => $_idsToDelete],
695
-				true,
696
-				true
697
-			);
698
-
699
-			if ($success):
700
-				if ($this->isRoot($entry)) {
701
-					$this->Category->id = $entry['Entry']['category_id'];
702
-					$this->Category->updateThreadCounter();
703
-					$this->Esevent->deleteSubject($id, 'thread');
704
-				}
705
-				foreach ($_idsToDelete as $_entryId) {
706
-					$this->Esevent->deleteSubject($_entryId, 'entry');
707
-				}
708
-
709
-				$this->_dispatchEvent(
710
-					'Model.Thread.change',
711
-					['subject' => $entry[$this->alias]['tid']]
712
-				);
713
-			endif;
714
-
715
-			return $success;
716
-		}
680
+        public function deleteNode($id = null) {
681
+            if (empty($id)) {
682
+                $id = $this->id;
683
+            }
684
+
685
+            $this->contain();
686
+            $entry = $this->findById($id);
687
+
688
+            if (empty($entry)) {
689
+                throw new Exception;
690
+            }
691
+
692
+            $_idsToDelete = $this->getIdsForNode($id);
693
+            $success = $this->deleteAll(
694
+                [$this->alias . '.id' => $_idsToDelete],
695
+                true,
696
+                true
697
+            );
698
+
699
+            if ($success):
700
+                if ($this->isRoot($entry)) {
701
+                    $this->Category->id = $entry['Entry']['category_id'];
702
+                    $this->Category->updateThreadCounter();
703
+                    $this->Esevent->deleteSubject($id, 'thread');
704
+                }
705
+                foreach ($_idsToDelete as $_entryId) {
706
+                    $this->Esevent->deleteSubject($_entryId, 'entry');
707
+                }
708
+
709
+                $this->_dispatchEvent(
710
+                    'Model.Thread.change',
711
+                    ['subject' => $entry[$this->alias]['tid']]
712
+                );
713
+            endif;
714
+
715
+            return $success;
716
+        }
717 717
 
718 718
 /**
719 719
  * Get the ID of all subentries of and including entry $id
@@ -721,16 +721,16 @@  discard block
 block discarded – undo
721 721
  * @param int $id
722 722
  * @return array Ids
723 723
  */
724
-		public function getIdsForNode($id) {
725
-			$subthread = $this->treeForNode($id);
726
-			$func = function (&$tree, &$entry) {
727
-				$tree['ids'][] = (int)$entry['Entry']['id'];
728
-			};
729
-			Entry::mapTreeElements($subthread, $func);
730
-			sort($subthread['ids']);
724
+        public function getIdsForNode($id) {
725
+            $subthread = $this->treeForNode($id);
726
+            $func = function (&$tree, &$entry) {
727
+                $tree['ids'][] = (int)$entry['Entry']['id'];
728
+            };
729
+            Entry::mapTreeElements($subthread, $func);
730
+            sort($subthread['ids']);
731 731
 
732
-			return $subthread['ids'];
733
-		}
732
+            return $subthread['ids'];
733
+        }
734 734
 
735 735
 /**
736 736
  * Anonymizes the entries for a user
@@ -739,24 +739,24 @@  discard block
 block discarded – undo
739 739
  *
740 740
  * @return bool success
741 741
  */
742
-		public function anonymizeEntriesFromUser($userId) {
743
-			// remove username from all entries and reassign to anonyme user
744
-			$success = $this->updateAll(
745
-				[
746
-					'Entry.name' => "NULL",
747
-					'Entry.edited_by' => "NULL",
748
-					'Entry.ip' => "NULL",
749
-					'Entry.user_id' => 0,
750
-				],
751
-				['Entry.user_id' => $userId]
752
-			);
753
-
754
-			if ($success) {
755
-				$this->_dispatchEvent('Cmd.Cache.clear', ['cache' => 'Thread']);
756
-			}
757
-
758
-			return $success;
759
-		}
742
+        public function anonymizeEntriesFromUser($userId) {
743
+            // remove username from all entries and reassign to anonyme user
744
+            $success = $this->updateAll(
745
+                [
746
+                    'Entry.name' => "NULL",
747
+                    'Entry.edited_by' => "NULL",
748
+                    'Entry.ip' => "NULL",
749
+                    'Entry.user_id' => 0,
750
+                ],
751
+                ['Entry.user_id' => $userId]
752
+            );
753
+
754
+            if ($success) {
755
+                $this->_dispatchEvent('Cmd.Cache.clear', ['cache' => 'Thread']);
756
+            }
757
+
758
+            return $success;
759
+        }
760 760
 
761 761
 /**
762 762
  * Maps all elements in $tree to function $func
@@ -768,23 +768,23 @@  discard block
 block discarded – undo
768 768
  *
769 769
  * @return string
770 770
  */
771
-		public static function mapTreeElements(&$leafs, callable $func, $context = null, &$tree = null) {
772
-			if ($tree === null) {
773
-				$tree = & $leafs;
774
-			}
775
-			foreach ($leafs as $leaf):
776
-				$result = $func($tree, $leaf, $context);
777
-				if ($result === 'break') {
778
-					return 'break';
779
-				}
780
-				if (isset($leaf['_children'])) {
781
-					$result = self::mapTreeElements($leaf['_children'], $func, $context, $tree);
782
-					if ($result === 'break') {
783
-						return 'break';
784
-					}
785
-				}
786
-			endforeach;
787
-		}
771
+        public static function mapTreeElements(&$leafs, callable $func, $context = null, &$tree = null) {
772
+            if ($tree === null) {
773
+                $tree = & $leafs;
774
+            }
775
+            foreach ($leafs as $leaf):
776
+                $result = $func($tree, $leaf, $context);
777
+                if ($result === 'break') {
778
+                    return 'break';
779
+                }
780
+                if (isset($leaf['_children'])) {
781
+                    $result = self::mapTreeElements($leaf['_children'], $func, $context, $tree);
782
+                    if ($result === 'break') {
783
+                        return 'break';
784
+                    }
785
+                }
786
+            endforeach;
787
+        }
788 788
 
789 789
 /**
790 790
  * Merge thread on to entry $targetId
@@ -792,74 +792,74 @@  discard block
 block discarded – undo
792 792
  * @param int $targetId id of the entry the thread should be appended to
793 793
  * @return bool true if merge was successfull false otherwise
794 794
  */
795
-		public function threadMerge($targetId) {
796
-			$threadIdSource = $this->id;
797
-
798
-			$this->contain();
799
-			$sourceEntry = $this->findById($threadIdSource);
800
-
801
-			// check that source is thread and not an entry
802
-			if ($sourceEntry[$this->alias]['pid'] != 0) {
803
-				return false;
804
-			}
805
-
806
-			$this->contain();
807
-			$targetEntry = $this->findById($targetId);
808
-
809
-			// check that target exists
810
-			if (!$targetEntry) {
811
-				return false;
812
-			}
813
-
814
-			// check that a thread is not merged onto itself
815
-			if ($targetEntry[$this->alias]['tid'] === $sourceEntry[$this->alias]['tid']) {
816
-				return false;
817
-			}
818
-
819
-			// set target entry as new parent entry
820
-			$this->data = [];
821
-			$this->set('pid', $targetEntry[$this->alias]['id']);
822
-			if ($this->save()) {
823
-				// associate all entries in source thread to target thread
824
-				$this->updateAll(
825
-					['tid' => $targetEntry[$this->alias]['tid']],
826
-					['tid' => $this->id]
827
-				);
828
-
829
-				// appended source entries get category of target thread
830
-				$this->_threadChangeCategory(
831
-					$targetEntry[$this->alias]['tid'],
832
-					$targetEntry[$this->alias]['category_id']
833
-				);
834
-
835
-				// update target thread last answer if source is newer
836
-				$sourceLastAnswer = $this->field('last_answer');
837
-				if (strtotime($sourceLastAnswer) > strtotime($targetEntry[$this->alias]['last_answer'])) {
838
-					$this->id = $targetEntry[$this->alias]['tid'];
839
-					$this->set('last_answer', $sourceLastAnswer);
840
-					$this->save();
841
-				}
842
-
843
-				// propagate pinned property from target to source
844
-				$isTargetPinned = (bool)$targetEntry[$this->alias]['locked'];
845
-				if ($sourceEntry[$this->alias]['locked'] !== $isTargetPinned) {
846
-					$this->id = $targetEntry[$this->alias]['tid'];
847
-					$this->_threadLock($isTargetPinned);
848
-				}
849
-
850
-				$this->Esevent->transferSubjectForEventType(
851
-					$threadIdSource,
852
-					$targetEntry[$this->alias]['tid'],
853
-					'thread'
854
-				);
855
-				$this->_dispatchEvent(
856
-					'Model.Thread.change',
857
-					['subject' => $targetEntry[$this->alias]['tid']]
858
-				);
859
-				return true;
860
-			}
861
-			return false;
862
-		}
795
+        public function threadMerge($targetId) {
796
+            $threadIdSource = $this->id;
797
+
798
+            $this->contain();
799
+            $sourceEntry = $this->findById($threadIdSource);
800
+
801
+            // check that source is thread and not an entry
802
+            if ($sourceEntry[$this->alias]['pid'] != 0) {
803
+                return false;
804
+            }
805
+
806
+            $this->contain();
807
+            $targetEntry = $this->findById($targetId);
808
+
809
+            // check that target exists
810
+            if (!$targetEntry) {
811
+                return false;
812
+            }
813
+
814
+            // check that a thread is not merged onto itself
815
+            if ($targetEntry[$this->alias]['tid'] === $sourceEntry[$this->alias]['tid']) {
816
+                return false;
817
+            }
818
+
819
+            // set target entry as new parent entry
820
+            $this->data = [];
821
+            $this->set('pid', $targetEntry[$this->alias]['id']);
822
+            if ($this->save()) {
823
+                // associate all entries in source thread to target thread
824
+                $this->updateAll(
825
+                    ['tid' => $targetEntry[$this->alias]['tid']],
826
+                    ['tid' => $this->id]
827
+                );
828
+
829
+                // appended source entries get category of target thread
830
+                $this->_threadChangeCategory(
831
+                    $targetEntry[$this->alias]['tid'],
832
+                    $targetEntry[$this->alias]['category_id']
833
+                );
834
+
835
+                // update target thread last answer if source is newer
836
+                $sourceLastAnswer = $this->field('last_answer');
837
+                if (strtotime($sourceLastAnswer) > strtotime($targetEntry[$this->alias]['last_answer'])) {
838
+                    $this->id = $targetEntry[$this->alias]['tid'];
839
+                    $this->set('last_answer', $sourceLastAnswer);
840
+                    $this->save();
841
+                }
842
+
843
+                // propagate pinned property from target to source
844
+                $isTargetPinned = (bool)$targetEntry[$this->alias]['locked'];
845
+                if ($sourceEntry[$this->alias]['locked'] !== $isTargetPinned) {
846
+                    $this->id = $targetEntry[$this->alias]['tid'];
847
+                    $this->_threadLock($isTargetPinned);
848
+                }
849
+
850
+                $this->Esevent->transferSubjectForEventType(
851
+                    $threadIdSource,
852
+                    $targetEntry[$this->alias]['tid'],
853
+                    'thread'
854
+                );
855
+                $this->_dispatchEvent(
856
+                    'Model.Thread.change',
857
+                    ['subject' => $targetEntry[$this->alias]['tid']]
858
+                );
859
+                return true;
860
+            }
861
+            return false;
862
+        }
863 863
 
864 864
 /**
865 865
  * Test if entry is thread-root
@@ -871,36 +871,36 @@  discard block
 block discarded – undo
871 871
  * @return mixed
872 872
  * @throws InvalidArgumentException
873 873
  */
874
-		public function isRoot($id = null) {
875
-			if ($id === null) {
876
-				$id = $this->id;
877
-			}
878
-
879
-			$md5 = md5(serialize($id));
880
-			if (isset($this->_isRoot[$md5]) === false) {
881
-				// $id was $entry array
882
-				if (is_array($id) && isset($id[$this->alias]['pid'])) {
883
-					$entry = $id;
884
-				} else {
885
-					if (is_array($id) && isset($id[$this->alias]['id'])) {
886
-						$id = $id[$this->alias]['id'];
887
-					} elseif (empty($id)) {
888
-						throw new InvalidArgumentException();
889
-					}
890
-					$entry = $this->find(
891
-						'first',
892
-						array(
893
-							'contain' => false,
894
-							'conditions' => array(
895
-								'id' => $id,
896
-							)
897
-						)
898
-					);
899
-				}
900
-				$this->_isRoot[$md5] = empty($entry[$this->alias]['pid']);
901
-			}
902
-			return $this->_isRoot[$md5];
903
-		}
874
+        public function isRoot($id = null) {
875
+            if ($id === null) {
876
+                $id = $this->id;
877
+            }
878
+
879
+            $md5 = md5(serialize($id));
880
+            if (isset($this->_isRoot[$md5]) === false) {
881
+                // $id was $entry array
882
+                if (is_array($id) && isset($id[$this->alias]['pid'])) {
883
+                    $entry = $id;
884
+                } else {
885
+                    if (is_array($id) && isset($id[$this->alias]['id'])) {
886
+                        $id = $id[$this->alias]['id'];
887
+                    } elseif (empty($id)) {
888
+                        throw new InvalidArgumentException();
889
+                    }
890
+                    $entry = $this->find(
891
+                        'first',
892
+                        array(
893
+                            'contain' => false,
894
+                            'conditions' => array(
895
+                                'id' => $id,
896
+                            )
897
+                        )
898
+                    );
899
+                }
900
+                $this->_isRoot[$md5] = empty($entry[$this->alias]['pid']);
901
+            }
902
+            return $this->_isRoot[$md5];
903
+        }
904 904
 
905 905
 /**
906 906
  * Preprocesses entry data before saving it
@@ -911,85 +911,85 @@  discard block
 block discarded – undo
911 911
  * @throws InvalidArgumentException
912 912
  * @throws ForbiddenException
913 913
  */
914
-		public function prepare(&$data, array $options = []) {
915
-			$options += [
916
-				'isRoot' => null
917
-			];
918
-
919
-			if (isset($options['preFilterFields'])) {
920
-				$org = $data;
921
-				$this->filterFields($data, $options['preFilterFields']);
922
-				if (isset($org['Event'])) {
923
-					$data['Event'] = $org['Event'];
924
-				}
925
-			}
926
-			unset($options['preFilterFields']);
927
-
928
-			$isRoot = $options['isRoot'];
929
-			unset($options['isRoot']);
930
-
931
-			if ($isRoot === null) {
932
-				$isRoot = $this->isRoot($data);
933
-			}
934
-			// adds info from parent entry to an answer
935
-			if ($isRoot === false) {
936
-				if (!isset($data[$this->alias]['pid'])) {
937
-					$pid = $this->getParentId($data[$this->alias]['id']);
938
-				} else {
939
-					$pid = $data[$this->alias]['pid'];
940
-				}
941
-				$parent = $this->get($pid, true);
942
-				if ($parent === false) {
943
-					throw new InvalidArgumentException;
944
-				}
945
-
946
-				// @todo highly @bogus should be a validator?
947
-				$parentPosting = $this->dic->newInstance('\Saito\Posting\Posting', ['rawData' => $parent]);
948
-				if ($parentPosting->isAnsweringForbidden()) {
949
-					throw new ForbiddenException;
950
-				}
951
-
952
-				// if new subject is empty use the parent's subject
953
-				if (empty($data[$this->alias]['subject'])) {
954
-					$data[$this->alias]['subject'] = $parent[$this->alias]['subject'];
955
-				}
956
-
957
-				$data[$this->alias]['tid'] = $parent[$this->alias]['tid'];
958
-				$data[$this->alias]['category_id'] = $parent[$this->alias]['category_id'];
959
-			}
960
-
961
-			//= markup preprocessing
962
-			if (empty($data[$this->alias]['text']) === false) {
963
-				$data[$this->alias]['text'] = $this->prepareMarkup($data[$this->alias]['text']);
964
-			}
965
-		}
966
-
967
-		protected function _findEntry($state, $query, $results = []) {
968
-			if ($state === 'before') {
969
-				$query['contain'] = ['User', 'Category'];
970
-				$query['fields'] = array_merge($this->threadLineFieldList, $this->showEntryFieldListAdditional);
971
-				return $query;
972
-			}
973
-			if ($results) {
974
-				return $results[0];
975
-			}
976
-			return $results;
977
-		}
914
+        public function prepare(&$data, array $options = []) {
915
+            $options += [
916
+                'isRoot' => null
917
+            ];
918
+
919
+            if (isset($options['preFilterFields'])) {
920
+                $org = $data;
921
+                $this->filterFields($data, $options['preFilterFields']);
922
+                if (isset($org['Event'])) {
923
+                    $data['Event'] = $org['Event'];
924
+                }
925
+            }
926
+            unset($options['preFilterFields']);
927
+
928
+            $isRoot = $options['isRoot'];
929
+            unset($options['isRoot']);
930
+
931
+            if ($isRoot === null) {
932
+                $isRoot = $this->isRoot($data);
933
+            }
934
+            // adds info from parent entry to an answer
935
+            if ($isRoot === false) {
936
+                if (!isset($data[$this->alias]['pid'])) {
937
+                    $pid = $this->getParentId($data[$this->alias]['id']);
938
+                } else {
939
+                    $pid = $data[$this->alias]['pid'];
940
+                }
941
+                $parent = $this->get($pid, true);
942
+                if ($parent === false) {
943
+                    throw new InvalidArgumentException;
944
+                }
945
+
946
+                // @todo highly @bogus should be a validator?
947
+                $parentPosting = $this->dic->newInstance('\Saito\Posting\Posting', ['rawData' => $parent]);
948
+                if ($parentPosting->isAnsweringForbidden()) {
949
+                    throw new ForbiddenException;
950
+                }
951
+
952
+                // if new subject is empty use the parent's subject
953
+                if (empty($data[$this->alias]['subject'])) {
954
+                    $data[$this->alias]['subject'] = $parent[$this->alias]['subject'];
955
+                }
956
+
957
+                $data[$this->alias]['tid'] = $parent[$this->alias]['tid'];
958
+                $data[$this->alias]['category_id'] = $parent[$this->alias]['category_id'];
959
+            }
960
+
961
+            //= markup preprocessing
962
+            if (empty($data[$this->alias]['text']) === false) {
963
+                $data[$this->alias]['text'] = $this->prepareMarkup($data[$this->alias]['text']);
964
+            }
965
+        }
966
+
967
+        protected function _findEntry($state, $query, $results = []) {
968
+            if ($state === 'before') {
969
+                $query['contain'] = ['User', 'Category'];
970
+                $query['fields'] = array_merge($this->threadLineFieldList, $this->showEntryFieldListAdditional);
971
+                return $query;
972
+            }
973
+            if ($results) {
974
+                return $results[0];
975
+            }
976
+            return $results;
977
+        }
978 978
 
979 979
 /**
980 980
  * Implements the custom find type 'feed'
981 981
  *
982 982
  * Add parameters for generating a rss/json-feed with find('feed', …)
983 983
  */
984
-		protected function _findFeed($state, $query, $results = array()) {
985
-			if ($state == 'before') {
986
-				$query['contain'] = array('User');
987
-				$query['fields'] = $this->_allowedPublicOutputFields;
988
-				$query['limit'] = 10;
989
-				return $query;
990
-			}
991
-			return $results;
992
-		}
984
+        protected function _findFeed($state, $query, $results = array()) {
985
+            if ($state == 'before') {
986
+                $query['contain'] = array('User');
987
+                $query['fields'] = $this->_allowedPublicOutputFields;
988
+                $query['limit'] = 10;
989
+                return $query;
990
+            }
991
+            return $results;
992
+        }
993 993
 
994 994
 /**
995 995
  * Locks or unlocks a whole thread
@@ -998,57 +998,57 @@  discard block
 block discarded – undo
998 998
  *
999 999
  * @param bool $value
1000 1000
  */
1001
-		protected function _threadLock($value) {
1002
-			$tid = $this->field('tid');
1003
-			$this->contain();
1004
-			// @bogus throws error on $value = false
1005
-			$value = $value ? 1 : 0;
1006
-			$this->updateAll(['locked' => $value], ['tid' => $tid]);
1007
-		}
1008
-
1009
-		public function paginateCount($conditions, $recursive, $extra) {
1010
-			if (isset($extra['getInitialThreads'])) {
1011
-				$this->Category->contain();
1012
-				$categories = $this->Category->find(
1013
-					'all',
1014
-					[
1015
-						'conditions' => array('id' => $conditions['Entry.category_id']),
1016
-						'fields' => array('thread_count')
1017
-					]
1018
-				);
1019
-				$count = array_sum(Set::extract('/Category/thread_count', $categories));
1020
-			} else {
1021
-				$parameters = array('conditions' => $conditions);
1022
-				if ($recursive != $this->recursive) {
1023
-					$parameters['recursive'] = $recursive;
1024
-				}
1025
-				$count = $this->find('count', array_merge($parameters, $extra));
1026
-			}
1027
-			return $count;
1028
-		}
1029
-
1030
-		public function beforeSave($options = array()) {
1031
-			$success = true;
1032
-
1033
-			//# change category of thread if category of root entry changed
1034
-			$modified = !empty($this->id);
1035
-			if (isset($this->data[$this->alias]['category_id']) && $modified) {
1036
-				$oldEntry = $this->find('first',
1037
-					['contain' => false, 'conditions' => ['Entry.id' => $this->id]]);
1038
-
1039
-				if ($oldEntry && (int)$oldEntry[$this->alias]['pid'] === 0) {
1040
-					$categoryChanged = (int)$this->data[$this->alias]['category_id'] !== (int)$oldEntry[$this->alias]['category_id'];
1041
-					if ($categoryChanged) {
1042
-						$success = $success && $this->_threadChangeCategory(
1043
-								$oldEntry[$this->alias]['tid'],
1044
-								$this->data[$this->alias]['category_id']
1045
-							);
1046
-					}
1047
-				}
1048
-			}
1049
-
1050
-			return $success && parent::beforeSave($options);
1051
-		}
1001
+        protected function _threadLock($value) {
1002
+            $tid = $this->field('tid');
1003
+            $this->contain();
1004
+            // @bogus throws error on $value = false
1005
+            $value = $value ? 1 : 0;
1006
+            $this->updateAll(['locked' => $value], ['tid' => $tid]);
1007
+        }
1008
+
1009
+        public function paginateCount($conditions, $recursive, $extra) {
1010
+            if (isset($extra['getInitialThreads'])) {
1011
+                $this->Category->contain();
1012
+                $categories = $this->Category->find(
1013
+                    'all',
1014
+                    [
1015
+                        'conditions' => array('id' => $conditions['Entry.category_id']),
1016
+                        'fields' => array('thread_count')
1017
+                    ]
1018
+                );
1019
+                $count = array_sum(Set::extract('/Category/thread_count', $categories));
1020
+            } else {
1021
+                $parameters = array('conditions' => $conditions);
1022
+                if ($recursive != $this->recursive) {
1023
+                    $parameters['recursive'] = $recursive;
1024
+                }
1025
+                $count = $this->find('count', array_merge($parameters, $extra));
1026
+            }
1027
+            return $count;
1028
+        }
1029
+
1030
+        public function beforeSave($options = array()) {
1031
+            $success = true;
1032
+
1033
+            //# change category of thread if category of root entry changed
1034
+            $modified = !empty($this->id);
1035
+            if (isset($this->data[$this->alias]['category_id']) && $modified) {
1036
+                $oldEntry = $this->find('first',
1037
+                    ['contain' => false, 'conditions' => ['Entry.id' => $this->id]]);
1038
+
1039
+                if ($oldEntry && (int)$oldEntry[$this->alias]['pid'] === 0) {
1040
+                    $categoryChanged = (int)$this->data[$this->alias]['category_id'] !== (int)$oldEntry[$this->alias]['category_id'];
1041
+                    if ($categoryChanged) {
1042
+                        $success = $success && $this->_threadChangeCategory(
1043
+                                $oldEntry[$this->alias]['tid'],
1044
+                                $this->data[$this->alias]['category_id']
1045
+                            );
1046
+                    }
1047
+                }
1048
+            }
1049
+
1050
+            return $success && parent::beforeSave($options);
1051
+        }
1052 1052
 
1053 1053
 /**
1054 1054
  * check that entries are only in existing and allowed categories
@@ -1056,35 +1056,35 @@  discard block
 block discarded – undo
1056 1056
  * @param $check
1057 1057
  * @return bool
1058 1058
  */
1059
-		public function validateCategoryIsAllowed($check) {
1060
-			$availableCategories = $this->CurrentUser->Categories->getAllowed();
1061
-			if (!isset($availableCategories[$check['category_id']])) {
1062
-				return false;
1063
-			}
1064
-			return true;
1065
-		}
1066
-
1067
-		/**
1068
-		 * @param $check
1069
-		 * @return bool
1070
-		 * @throws Exception
1071
-		 */
1072
-		public function validateEditingAllowed($check) {
1073
-			$id = $this->data[$this->alias]['id'];
1074
-			$entry = $this->get($id);
1075
-			if (empty($entry)) {
1076
-				throw new Exception(sprintf('Entry %s not found.', $entry));
1077
-			}
1078
-
1079
-			$posting = $this->dic->newInstance('\Saito\Posting\Posting', ['rawData' => $entry]);
1080
-			$forbidden = $posting->isEditingAsCurrentUserForbidden();
1081
-
1082
-			if (is_bool($forbidden)) {
1083
-				return !$forbidden;
1084
-			} else {
1085
-				return $forbidden;
1086
-			}
1087
-		}
1059
+        public function validateCategoryIsAllowed($check) {
1060
+            $availableCategories = $this->CurrentUser->Categories->getAllowed();
1061
+            if (!isset($availableCategories[$check['category_id']])) {
1062
+                return false;
1063
+            }
1064
+            return true;
1065
+        }
1066
+
1067
+        /**
1068
+         * @param $check
1069
+         * @return bool
1070
+         * @throws Exception
1071
+         */
1072
+        public function validateEditingAllowed($check) {
1073
+            $id = $this->data[$this->alias]['id'];
1074
+            $entry = $this->get($id);
1075
+            if (empty($entry)) {
1076
+                throw new Exception(sprintf('Entry %s not found.', $entry));
1077
+            }
1078
+
1079
+            $posting = $this->dic->newInstance('\Saito\Posting\Posting', ['rawData' => $entry]);
1080
+            $forbidden = $posting->isEditingAsCurrentUserForbidden();
1081
+
1082
+            if (is_bool($forbidden)) {
1083
+                return !$forbidden;
1084
+            } else {
1085
+                return $forbidden;
1086
+            }
1087
+        }
1088 1088
 
1089 1089
 /**
1090 1090
  *
@@ -1097,9 +1097,9 @@  discard block
 block discarded – undo
1097 1097
  * @param $check
1098 1098
  * @return bool
1099 1099
  */
1100
-		public function validateSubjectMaxLength($check) {
1101
-			return mb_strlen($check['subject']) <= $this->_setting('subject_maxlength');
1102
-		}
1100
+        public function validateSubjectMaxLength($check) {
1101
+            return mb_strlen($check['subject']) <= $this->_setting('subject_maxlength');
1102
+        }
1103 1103
 
1104 1104
 /**
1105 1105
  * Changes the category of a thread.
@@ -1113,20 +1113,20 @@  discard block
 block discarded – undo
1113 1113
  * @throws NotFoundException
1114 1114
  * @throws InvalidArgumentException
1115 1115
  */
1116
-		protected function _threadChangeCategory($tid = null, $newCategoryId = null) {
1117
-			if (empty($tid)) {
1118
-				throw new InvalidArgumentException;
1119
-			}
1120
-			$this->Category->contain();
1121
-			$categoryExists = $this->Category->findById($newCategoryId);
1122
-			if (!$categoryExists) {
1123
-				throw new NotFoundException;
1124
-			}
1125
-			$out = $this->updateAll(
1126
-				['Entry.category_id' => $newCategoryId],
1127
-				['Entry.tid' => $tid]
1128
-			);
1129
-			return $out;
1130
-		}
1131
-
1132
-	}
1133 1116
\ No newline at end of file
1117
+        protected function _threadChangeCategory($tid = null, $newCategoryId = null) {
1118
+            if (empty($tid)) {
1119
+                throw new InvalidArgumentException;
1120
+            }
1121
+            $this->Category->contain();
1122
+            $categoryExists = $this->Category->findById($newCategoryId);
1123
+            if (!$categoryExists) {
1124
+                throw new NotFoundException;
1125
+            }
1126
+            $out = $this->updateAll(
1127
+                ['Entry.category_id' => $newCategoryId],
1128
+                ['Entry.tid' => $tid]
1129
+            );
1130
+            return $out;
1131
+        }
1132
+
1133
+    }
1134 1134
\ No newline at end of file
Please login to merge, or discard this patch.
app/Model/Esevent.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
  * 		'receiver'			=> '1',
158 158
  *  );
159 159
  *
160
- * @return type
160
+ * @return boolean
161 161
  */
162 162
 		public function setNotification($params) {
163 163
 			$isSet = $this->_getEventSet($params);
@@ -355,7 +355,7 @@  discard block
 block discarded – undo
355 355
 
356 356
 /**
357 357
  *
358
- * @param type $user
358
+ * @param integer $user
359 359
  * @param array $subjects with subjet IDs
360 360
  * @return array
361 361
  *
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -295,7 +295,7 @@
 block discarded – undo
295 295
 				)
296 296
 			);
297 297
 			if ($results) {
298
-				$recipients = Hash::map($results, '{n}.Esnotification.{n}', function ($values) {
298
+				$recipients = Hash::map($results, '{n}.Esnotification.{n}', function($values) {
299 299
 					$out = $values['User'];
300 300
 					unset($values['User']);
301 301
 					$out['Esnotification'] = $values;
Please login to merge, or discard this patch.
Indentation   +263 added lines, -263 removed lines patch added patch discarded remove patch
@@ -1,58 +1,58 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-	App::uses('AppModel', 'Model');
3
+    App::uses('AppModel', 'Model');
4 4
 
5
-	/**
6
-	 * Esevent Model
7
-	 *
8
-	 * @property Essubject $Essubject
9
-	 * @property Esnotification $Esnotification
10
-	 */
11
-	class Esevent extends AppModel {
5
+    /**
6
+     * Esevent Model
7
+     *
8
+     * @property Essubject $Essubject
9
+     * @property Esnotification $Esnotification
10
+     */
11
+    class Esevent extends AppModel {
12 12
 
13
-		public $actsAs = array('Containable');
13
+        public $actsAs = array('Containable');
14 14
 
15
-		//The Associations below have been created with all possible keys, those that are not needed can be removed
15
+        //The Associations below have been created with all possible keys, those that are not needed can be removed
16 16
 
17 17
 /**
18 18
  * hasMany associations
19 19
  *
20 20
  * @var array
21 21
  */
22
-		public $hasMany = array(
23
-			'Esnotification' => array(
24
-				'className' => 'Esnotification',
25
-				'foreignKey' => 'esevent_id',
26
-				'dependent' => true,
27
-				'conditions' => '',
28
-				'fields' => '',
29
-				'order' => '',
30
-				'limit' => '',
31
-				'offset' => '',
32
-				'exclusive' => '',
33
-				'finderQuery' => '',
34
-				'counterQuery' => ''
35
-			)
36
-		);
22
+        public $hasMany = array(
23
+            'Esnotification' => array(
24
+                'className' => 'Esnotification',
25
+                'foreignKey' => 'esevent_id',
26
+                'dependent' => true,
27
+                'conditions' => '',
28
+                'fields' => '',
29
+                'order' => '',
30
+                'limit' => '',
31
+                'offset' => '',
32
+                'exclusive' => '',
33
+                'finderQuery' => '',
34
+                'counterQuery' => ''
35
+            )
36
+        );
37 37
 
38
-		protected $_eventTypes = array(
39
-			'Model.Entry.replyToEntry' => 1,
40
-			'Model.Entry.replyToThread' => 2
41
-		);
38
+        protected $_eventTypes = array(
39
+            'Model.Entry.replyToEntry' => 1,
40
+            'Model.Entry.replyToThread' => 2
41
+        );
42 42
 
43 43
 /**
44 44
  * Subject types for $eventsTypes
45 45
  *
46 46
  * @var array
47 47
  */
48
-		protected $_subjectTypes = array(
49
-			'entry' => array(1),
50
-			'thread' => array(2),
51
-		);
48
+        protected $_subjectTypes = array(
49
+            'entry' => array(1),
50
+            'thread' => array(2),
51
+        );
52 52
 
53
-		protected $_receivers = array(
54
-				'EmailNotification' => 1,
55
-		);
53
+        protected $_receivers = array(
54
+                'EmailNotification' => 1,
55
+        );
56 56
 
57 57
 /**
58 58
  *
@@ -60,57 +60,57 @@  discard block
 block discarded – undo
60 60
  * @param int $newSubject
61 61
  * @param string $subjectType one of the strings in $_subjectTypes
62 62
  */
63
-		public function transferSubjectForEventType($oldSubject, $newSubject, $subjectType) {
64
-			$old = $this->find(
65
-				'all',
66
-				array(
67
-					'contain' => array('Esnotification'),
68
-					'conditions' => array(
69
-						'subject' => $oldSubject,
70
-						'event' => $this->_subjectTypes[$subjectType],
71
-					)
72
-				)
73
-			);
63
+        public function transferSubjectForEventType($oldSubject, $newSubject, $subjectType) {
64
+            $old = $this->find(
65
+                'all',
66
+                array(
67
+                    'contain' => array('Esnotification'),
68
+                    'conditions' => array(
69
+                        'subject' => $oldSubject,
70
+                        'event' => $this->_subjectTypes[$subjectType],
71
+                    )
72
+                )
73
+            );
74 74
 
75
-			// there are no affected subjects
76
-			if (!$old) {
77
-				return;
78
-			}
75
+            // there are no affected subjects
76
+            if (!$old) {
77
+                return;
78
+            }
79 79
 
80
-			$current = $this->find(
81
-				'all',
82
-				array(
83
-					'contain' => array('Esnotification'),
84
-					'conditions' => array(
85
-						'subject' => $newSubject,
86
-						'event' => $this->_subjectTypes[$subjectType],
87
-					)
88
-				)
89
-			);
80
+            $current = $this->find(
81
+                'all',
82
+                array(
83
+                    'contain' => array('Esnotification'),
84
+                    'conditions' => array(
85
+                        'subject' => $newSubject,
86
+                        'event' => $this->_subjectTypes[$subjectType],
87
+                    )
88
+                )
89
+            );
90 90
 
91
-			$oldEvents = Hash::combine($old, '{n}.Esevent.event', '{n}');
92
-			$currentEvents = Hash::combine($current, '{n}.Esevent.event', '{n}');
91
+            $oldEvents = Hash::combine($old, '{n}.Esevent.event', '{n}');
92
+            $currentEvents = Hash::combine($current, '{n}.Esevent.event', '{n}');
93 93
 
94
-			foreach ($oldEvents as $eventType => $oldEvent) {
95
-				$newData = array();
96
-				$newData['Esnotification'] = $oldEvent['Esnotification'];
97
-				if (isset($currentEvents[$eventType])) {
98
-					$newData['Esevent']['id'] = $currentEvents[$eventType]['Esevent']['id'];
99
-				} else {
100
-					$newData['Esevent']['subject'] = $newSubject;
101
-					$newData['Esevent']['event'] = $eventType;
102
-					$this->create();
103
-				}
104
-				$this->saveAssociated($newData);
105
-			}
106
-			$this->deleteAll(
107
-				array(
108
-					'subject' => $oldSubject,
109
-					'event' => $this->_subjectTypes[$subjectType],
110
-				),
111
-				false
112
-			);
113
-		}
94
+            foreach ($oldEvents as $eventType => $oldEvent) {
95
+                $newData = array();
96
+                $newData['Esnotification'] = $oldEvent['Esnotification'];
97
+                if (isset($currentEvents[$eventType])) {
98
+                    $newData['Esevent']['id'] = $currentEvents[$eventType]['Esevent']['id'];
99
+                } else {
100
+                    $newData['Esevent']['subject'] = $newSubject;
101
+                    $newData['Esevent']['event'] = $eventType;
102
+                    $this->create();
103
+                }
104
+                $this->saveAssociated($newData);
105
+            }
106
+            $this->deleteAll(
107
+                array(
108
+                    'subject' => $oldSubject,
109
+                    'event' => $this->_subjectTypes[$subjectType],
110
+                ),
111
+                false
112
+            );
113
+        }
114 114
 
115 115
 /**
116 116
  *
@@ -129,21 +129,21 @@  discard block
 block discarded – undo
129 129
  * 	)
130 130
  * </pre>
131 131
  */
132
-		public function notifyUserOnEvents($user, $events) {
133
-			foreach ($events as $event) {
134
-				$params = array(
135
-					'user_id' => $user,
136
-					'event' => $this->_eventTypes[$event['event']],
137
-					'subject' => $event['subject'],
138
-					'receiver' => $this->_receivers[$event['receiver']],
139
-				);
140
-				if ($event['set']) {
141
-					$this->setNotification($params);
142
-				} else {
143
-					$this->deleteNotification($params);
144
-				}
145
-			}
146
-		}
132
+        public function notifyUserOnEvents($user, $events) {
133
+            foreach ($events as $event) {
134
+                $params = array(
135
+                    'user_id' => $user,
136
+                    'event' => $this->_eventTypes[$event['event']],
137
+                    'subject' => $event['subject'],
138
+                    'receiver' => $this->_receivers[$event['receiver']],
139
+                );
140
+                if ($event['set']) {
141
+                    $this->setNotification($params);
142
+                } else {
143
+                    $this->deleteNotification($params);
144
+                }
145
+            }
146
+        }
147 147
 
148 148
 /**
149 149
  *
@@ -159,54 +159,54 @@  discard block
 block discarded – undo
159 159
  *
160 160
  * @return type
161 161
  */
162
-		public function setNotification($params) {
163
-			$isSet = $this->_getEventSet($params);
164
-			$success = true;
165
-			$eventData = [];
166
-			if ($isSet['Esevent']) {
167
-				$eventData = array(
168
-					'id' => $isSet['Esevent']['id'],
169
-				);
170
-			} else {
171
-				$eventData = array(
172
-					'subject' => $params['subject'],
173
-					'event' => $params['event'],
174
-				);
175
-			}
176
-			if (!$isSet['Esnotification']) {
177
-				$data = array(
178
-					'Esevent' => $eventData,
179
-					'Esnotification' => array(
180
-						array(
181
-							'user_id' => $params['user_id'],
182
-							'esreceiver_id' => $params['receiver'],
183
-						),
184
-					),
185
-				);
186
-				$success = $success && $this->saveAssociated($data);
187
-			}
188
-			return $success;
189
-		}
162
+        public function setNotification($params) {
163
+            $isSet = $this->_getEventSet($params);
164
+            $success = true;
165
+            $eventData = [];
166
+            if ($isSet['Esevent']) {
167
+                $eventData = array(
168
+                    'id' => $isSet['Esevent']['id'],
169
+                );
170
+            } else {
171
+                $eventData = array(
172
+                    'subject' => $params['subject'],
173
+                    'event' => $params['event'],
174
+                );
175
+            }
176
+            if (!$isSet['Esnotification']) {
177
+                $data = array(
178
+                    'Esevent' => $eventData,
179
+                    'Esnotification' => array(
180
+                        array(
181
+                            'user_id' => $params['user_id'],
182
+                            'esreceiver_id' => $params['receiver'],
183
+                        ),
184
+                    ),
185
+                );
186
+                $success = $success && $this->saveAssociated($data);
187
+            }
188
+            return $success;
189
+        }
190 190
 
191 191
 /**
192 192
  * Deletes Subject and all its Notifications
193 193
  */
194
-		public function deleteSubject($subjectId, $subjectType) {
195
-			// remove all events
196
-			$this->deleteAll(array(
197
-					'subject' => $subjectId,
198
-					'event' => $this->_subjectTypes[$subjectType],
199
-			), true);
200
-		}
194
+        public function deleteSubject($subjectId, $subjectType) {
195
+            // remove all events
196
+            $this->deleteAll(array(
197
+                    'subject' => $subjectId,
198
+                    'event' => $this->_subjectTypes[$subjectType],
199
+            ), true);
200
+        }
201 201
 
202
-		public function deleteNotification($params) {
203
-			extract($params);
202
+        public function deleteNotification($params) {
203
+            extract($params);
204 204
 
205
-			$isSet = $this->_getEventSet($params);
206
-			if ($isSet['Esnotification']) {
207
-				return $this->Esnotification->deleteNotificationWithId($isSet['Esnotification'][0]['id']);
208
-			}
209
-		}
205
+            $isSet = $this->_getEventSet($params);
206
+            if ($isSet['Esnotification']) {
207
+                return $this->Esnotification->deleteNotificationWithId($isSet['Esnotification'][0]['id']);
208
+            }
209
+        }
210 210
 
211 211
 /**
212 212
  * Checks if specific notification is set
@@ -224,26 +224,26 @@  discard block
 block discarded – undo
224 224
  *
225 225
  * @return mixed array with found set or false otherwise
226 226
  */
227
-		protected function _getEventSet($params) {
228
-			$results = $this->find(
229
-				'first',
230
-				array(
231
-					'contain' => array(
232
-						'Esnotification' => array(
233
-							'conditions' => array(
234
-								'user_id' => $params['user_id'],
235
-								'esreceiver_id' => $params['receiver'],
236
-							),
237
-						),
238
-					),
239
-					'conditions' => array(
240
-						'Esevent.subject' => $params['subject'],
241
-						'Esevent.event' => $params['event'],
242
-					)
243
-				)
244
-			);
245
-			return empty($results) ? false : $results;
246
-		}
227
+        protected function _getEventSet($params) {
228
+            $results = $this->find(
229
+                'first',
230
+                array(
231
+                    'contain' => array(
232
+                        'Esnotification' => array(
233
+                            'conditions' => array(
234
+                                'user_id' => $params['user_id'],
235
+                                'esreceiver_id' => $params['receiver'],
236
+                            ),
237
+                        ),
238
+                    ),
239
+                    'conditions' => array(
240
+                        'Esevent.subject' => $params['subject'],
241
+                        'Esevent.event' => $params['event'],
242
+                    )
243
+                )
244
+            );
245
+            return empty($results) ? false : $results;
246
+        }
247 247
 
248 248
 /**
249 249
  *
@@ -269,41 +269,41 @@  discard block
 block discarded – undo
269 269
  *	)
270 270
  * </pre>
271 271
  */
272
-		public function getUsersForEventOnSubjectWithReceiver($eventName, $subject, $receiver) {
273
-			$recipients = array();
274
-			$results = $this->find(
275
-				'all',
276
-				array(
277
-					'conditions' => array(
278
-						'Esevent.event' => $this->_eventTypes[$eventName],
279
-						'Esevent.subject' => $subject,
280
-					),
281
-					'contain' => array(
282
-						'Esnotification' => array(
283
-							'fields' => array(
284
-								'Esnotification.id',
285
-								'Esnotification.deactivate'
286
-							),
287
-							'conditions' => array(
288
-								'esreceiver_id' => $this->_receivers[$receiver],
289
-							),
290
-							'User' => array(
291
-								'fields' => array('id', 'username', 'user_email'),
292
-							)
293
-						),
294
-					),
295
-				)
296
-			);
297
-			if ($results) {
298
-				$recipients = Hash::map($results, '{n}.Esnotification.{n}', function ($values) {
299
-					$out = $values['User'];
300
-					unset($values['User']);
301
-					$out['Esnotification'] = $values;
302
-					return $out;
303
-				});
304
-			}
305
-			return $recipients;
306
-		}
272
+        public function getUsersForEventOnSubjectWithReceiver($eventName, $subject, $receiver) {
273
+            $recipients = array();
274
+            $results = $this->find(
275
+                'all',
276
+                array(
277
+                    'conditions' => array(
278
+                        'Esevent.event' => $this->_eventTypes[$eventName],
279
+                        'Esevent.subject' => $subject,
280
+                    ),
281
+                    'contain' => array(
282
+                        'Esnotification' => array(
283
+                            'fields' => array(
284
+                                'Esnotification.id',
285
+                                'Esnotification.deactivate'
286
+                            ),
287
+                            'conditions' => array(
288
+                                'esreceiver_id' => $this->_receivers[$receiver],
289
+                            ),
290
+                            'User' => array(
291
+                                'fields' => array('id', 'username', 'user_email'),
292
+                            )
293
+                        ),
294
+                    ),
295
+                )
296
+            );
297
+            if ($results) {
298
+                $recipients = Hash::map($results, '{n}.Esnotification.{n}', function ($values) {
299
+                    $out = $values['User'];
300
+                    unset($values['User']);
301
+                    $out['Esnotification'] = $values;
302
+                    return $out;
303
+                });
304
+            }
305
+            return $recipients;
306
+        }
307 307
 
308 308
 /**
309 309
  *
@@ -326,32 +326,32 @@  discard block
 block discarded – undo
326 326
  * 		1 => [true|false],
327 327
  * )
328 328
  */
329
-		public function checkEventsForUser($user, $events) {
330
-			// Stopwatch::enable(); Stopwatch::start('Event->checkEventsForUser()');
329
+        public function checkEventsForUser($user, $events) {
330
+            // Stopwatch::enable(); Stopwatch::start('Event->checkEventsForUser()');
331 331
 
332
-			$subjects = array();
333
-			foreach ($events as $event) {
334
-				$subjects[] = $event['subject'];
335
-			}
332
+            $subjects = array();
333
+            foreach ($events as $event) {
334
+                $subjects[] = $event['subject'];
335
+            }
336 336
 
337
-			$notis = $this->_getEventsForUserOnSubjects($user, $subjects);
338
-			$out = array();
337
+            $notis = $this->_getEventsForUserOnSubjects($user, $subjects);
338
+            $out = array();
339 339
 
340
-			foreach ($events as $k => $event) {
341
-				foreach ($notis as $noti) {
342
-					if ($noti['subject'] == $event['subject']
343
-							&& $noti['event'] == $this->_eventTypes[$event['event']]
344
-							&& $noti['receiver'] == $this->_receivers[$event['receiver']]) {
345
-						$out[$k] = true;
346
-						break;
347
-					} else {
348
-						$out[$k] = false;
349
-					}
350
-				}
351
-			}
352
-			// Stopwatch::end('Event->checkEventsForUser()'); debug(Stopwatch::getString());
353
-			return $out;
354
-		}
340
+            foreach ($events as $k => $event) {
341
+                foreach ($notis as $noti) {
342
+                    if ($noti['subject'] == $event['subject']
343
+                            && $noti['event'] == $this->_eventTypes[$event['event']]
344
+                            && $noti['receiver'] == $this->_receivers[$event['receiver']]) {
345
+                        $out[$k] = true;
346
+                        break;
347
+                    } else {
348
+                        $out[$k] = false;
349
+                    }
350
+                }
351
+            }
352
+            // Stopwatch::end('Event->checkEventsForUser()'); debug(Stopwatch::getString());
353
+            return $out;
354
+        }
355 355
 
356 356
 /**
357 357
  *
@@ -369,49 +369,49 @@  discard block
 block discarded – undo
369 369
  *
370 370
  * )
371 371
  */
372
-		protected function _getEventsForUserOnSubjects($user, $subjects) {
373
-			$notis = $this->Esnotification->find(
374
-				'all',
375
-				array(
376
-					'joins' => array(
377
-						array(
378
-							'table' => 'esevents',
379
-							'alias' => 'Eseventa',
380
-							'type' => 'LEFT',
381
-							'conditions' => array(
382
-								'Eseventa.id = Esnotification.esevent_id'
383
-							)
384
-						)
385
-					),
386
-					'conditions' => array(
387
-						'Esnotification.user_id' => $user,
388
-						'Esevent.subject' => $subjects
389
-					),
390
-					'fields' => array(
391
-						'Esnotification.id',
392
-						'Esnotification.user_id',
393
-						'Esnotification.esevent_id',
394
-						'Esnotification.esreceiver_id',
395
-						'Esevent.event',
396
-						'Esevent.subject'
397
-					)
398
-				)
399
-			);
400
-			$out = $notis;
401
-			if ($notis) {
402
-				$out = array();
403
-				foreach ($notis as $noti) {
404
-					$out[] = array(
405
-						'user_id' => $noti['Esnotification']['user_id'],
406
-						'esevent_id' => $noti['Esnotification']['esevent_id'],
407
-						'esnotification_id' => $noti['Esnotification']['id'],
408
-						'event' => $noti['Esevent']['event'],
409
-						'subject' => $noti['Esevent']['subject'],
410
-						'receiver' => $noti['Esnotification']['esreceiver_id'],
411
-					);
412
-				}
413
-			}
414
-			return $out;
415
-		}
372
+        protected function _getEventsForUserOnSubjects($user, $subjects) {
373
+            $notis = $this->Esnotification->find(
374
+                'all',
375
+                array(
376
+                    'joins' => array(
377
+                        array(
378
+                            'table' => 'esevents',
379
+                            'alias' => 'Eseventa',
380
+                            'type' => 'LEFT',
381
+                            'conditions' => array(
382
+                                'Eseventa.id = Esnotification.esevent_id'
383
+                            )
384
+                        )
385
+                    ),
386
+                    'conditions' => array(
387
+                        'Esnotification.user_id' => $user,
388
+                        'Esevent.subject' => $subjects
389
+                    ),
390
+                    'fields' => array(
391
+                        'Esnotification.id',
392
+                        'Esnotification.user_id',
393
+                        'Esnotification.esevent_id',
394
+                        'Esnotification.esreceiver_id',
395
+                        'Esevent.event',
396
+                        'Esevent.subject'
397
+                    )
398
+                )
399
+            );
400
+            $out = $notis;
401
+            if ($notis) {
402
+                $out = array();
403
+                foreach ($notis as $noti) {
404
+                    $out[] = array(
405
+                        'user_id' => $noti['Esnotification']['user_id'],
406
+                        'esevent_id' => $noti['Esnotification']['esevent_id'],
407
+                        'esnotification_id' => $noti['Esnotification']['id'],
408
+                        'event' => $noti['Esevent']['event'],
409
+                        'subject' => $noti['Esevent']['subject'],
410
+                        'receiver' => $noti['Esnotification']['esreceiver_id'],
411
+                    );
412
+                }
413
+            }
414
+            return $out;
415
+        }
416 416
 
417
-	}
417
+    }
Please login to merge, or discard this patch.
app/Model/Setting.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -92,6 +92,9 @@
 block discarded – undo
92 92
 			return $settings;
93 93
 		}
94 94
 
95
+		/**
96
+		 * @param string $field
97
+		 */
95 98
 		protected function _normToSeconds(&$settings, $field) {
96 99
 			$settings[$field] = (int)$settings[$field] * 60;
97 100
 		}
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -93,7 +93,7 @@
 block discarded – undo
93 93
 		}
94 94
 
95 95
 		protected function _normToSeconds(&$settings, $field) {
96
-			$settings[$field] = (int)$settings[$field] * 60;
96
+			$settings[$field] = (int) $settings[$field] * 60;
97 97
 		}
98 98
 
99 99
 		/**
Please login to merge, or discard this patch.
Indentation   +110 added lines, -110 removed lines patch added patch discarded remove patch
@@ -1,112 +1,112 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-	App::uses('AppSettingModel', 'Lib/Model');
4
-
5
-	class Setting extends AppSettingModel {
6
-
7
-		public $name = 'Setting';
8
-
9
-		public $primaryKey = 'name';
10
-
11
-		public $validate = [
12
-			'name' => [
13
-				'rule' => ['between', 1, 255],
14
-				'allowEmpty' => false
15
-			],
16
-			'value' => [
17
-				'rule' => ['between', 0, 255],
18
-				'allowEmpty' => true
19
-			]
20
-		];
21
-
22
-		protected $_optionalEmailFields = [
23
-			'email_contact', 'email_register', 'email_system'
24
-		];
25
-
26
-		/* @td getSettings vs Load why to functions? */
27
-
28
-		/**
29
-		 * Reads settings from DB and returns them in a compact array
30
-		 *
31
-		 * Note that this is the stored config in the DB. It may differ from the
32
-		 * current config used by the app in Config::read('Saito.Settings'), e.g.
33
-		 * when modified with a load-preset.
34
-		 *
35
-		 * @throws UnexpectedValueException
36
-		 * @return array Settings
37
-		 */
38
-		public function getSettings() {
39
-			$settings = $this->find('all');
40
-			if (empty($settings)) {
41
-				throw new UnexpectedValueException('No settings found in settings table.');
42
-			}
43
-			$settings = $this->_compactKeyValue($settings);
44
-
45
-			// edit_delay is normed to seconds
46
-			$this->_normToSeconds($settings, 'edit_delay');
47
-			$this->_fillOptionalEmailAddresses($settings);
48
-
49
-			return $settings;
50
-		}
51
-
52
-		/**
53
-		 * Loads settings from storage into Configuration `Saito.Settings`
54
-		 *
55
-		 * @param array $preset allows to overwrite loaded values
56
-		 * @return array Settings
57
-		 */
58
-		public function load($preset = []) {
59
-			Stopwatch::start('Settings->getSettings()');
60
-
61
-			$settings = Cache::read('Saito.appSettings');
62
-			if (empty($settings)) {
63
-				$settings = $this->getSettings();
64
-				Cache::write('Saito.appSettings', $settings);
65
-			}
66
-			if ($preset) {
67
-				$settings = $preset + $settings;
68
-			}
69
-			Configure::write('Saito.Settings', $settings);
70
-
71
-			Stopwatch::end('Settings->getSettings()');
72
-		}
73
-
74
-		public function clearCache() {
75
-			parent::clearCache();
76
-			Cache::delete('Saito.appSettings');
77
-		}
78
-
79
-		/**
80
-		 * Returns a key-value array
81
-		 *
82
-		 * Fast version of Set::combine($results, '{n}.Setting.name', '{n}.Setting.value');
83
-		 *
84
-		 * @param array $results
85
-		 * @return array
86
-		 */
87
-		protected function _compactKeyValue($results) {
88
-			$settings = array();
89
-			foreach ($results as $result) {
90
-				$settings[$result[$this->alias]['name']] = $result[$this->alias]['value'];
91
-			}
92
-			return $settings;
93
-		}
94
-
95
-		protected function _normToSeconds(&$settings, $field) {
96
-			$settings[$field] = (int)$settings[$field] * 60;
97
-		}
98
-
99
-		/**
100
-		 * Defaults optional email addresses to main address
101
-		 *
102
-		 * @param $settings
103
-		 */
104
-		protected function _fillOptionalEmailAddresses(&$settings) {
105
-			foreach ($this->_optionalEmailFields as $field) {
106
-				if (empty($settings[$field])) {
107
-					$settings[$field] = $settings['forum_email'];
108
-				}
109
-			}
110
-		}
111
-
112
-	}
113 3
\ No newline at end of file
4
+    App::uses('AppSettingModel', 'Lib/Model');
5
+
6
+    class Setting extends AppSettingModel {
7
+
8
+        public $name = 'Setting';
9
+
10
+        public $primaryKey = 'name';
11
+
12
+        public $validate = [
13
+            'name' => [
14
+                'rule' => ['between', 1, 255],
15
+                'allowEmpty' => false
16
+            ],
17
+            'value' => [
18
+                'rule' => ['between', 0, 255],
19
+                'allowEmpty' => true
20
+            ]
21
+        ];
22
+
23
+        protected $_optionalEmailFields = [
24
+            'email_contact', 'email_register', 'email_system'
25
+        ];
26
+
27
+        /* @td getSettings vs Load why to functions? */
28
+
29
+        /**
30
+         * Reads settings from DB and returns them in a compact array
31
+         *
32
+         * Note that this is the stored config in the DB. It may differ from the
33
+         * current config used by the app in Config::read('Saito.Settings'), e.g.
34
+         * when modified with a load-preset.
35
+         *
36
+         * @throws UnexpectedValueException
37
+         * @return array Settings
38
+         */
39
+        public function getSettings() {
40
+            $settings = $this->find('all');
41
+            if (empty($settings)) {
42
+                throw new UnexpectedValueException('No settings found in settings table.');
43
+            }
44
+            $settings = $this->_compactKeyValue($settings);
45
+
46
+            // edit_delay is normed to seconds
47
+            $this->_normToSeconds($settings, 'edit_delay');
48
+            $this->_fillOptionalEmailAddresses($settings);
49
+
50
+            return $settings;
51
+        }
52
+
53
+        /**
54
+         * Loads settings from storage into Configuration `Saito.Settings`
55
+         *
56
+         * @param array $preset allows to overwrite loaded values
57
+         * @return array Settings
58
+         */
59
+        public function load($preset = []) {
60
+            Stopwatch::start('Settings->getSettings()');
61
+
62
+            $settings = Cache::read('Saito.appSettings');
63
+            if (empty($settings)) {
64
+                $settings = $this->getSettings();
65
+                Cache::write('Saito.appSettings', $settings);
66
+            }
67
+            if ($preset) {
68
+                $settings = $preset + $settings;
69
+            }
70
+            Configure::write('Saito.Settings', $settings);
71
+
72
+            Stopwatch::end('Settings->getSettings()');
73
+        }
74
+
75
+        public function clearCache() {
76
+            parent::clearCache();
77
+            Cache::delete('Saito.appSettings');
78
+        }
79
+
80
+        /**
81
+         * Returns a key-value array
82
+         *
83
+         * Fast version of Set::combine($results, '{n}.Setting.name', '{n}.Setting.value');
84
+         *
85
+         * @param array $results
86
+         * @return array
87
+         */
88
+        protected function _compactKeyValue($results) {
89
+            $settings = array();
90
+            foreach ($results as $result) {
91
+                $settings[$result[$this->alias]['name']] = $result[$this->alias]['value'];
92
+            }
93
+            return $settings;
94
+        }
95
+
96
+        protected function _normToSeconds(&$settings, $field) {
97
+            $settings[$field] = (int)$settings[$field] * 60;
98
+        }
99
+
100
+        /**
101
+         * Defaults optional email addresses to main address
102
+         *
103
+         * @param $settings
104
+         */
105
+        protected function _fillOptionalEmailAddresses(&$settings) {
106
+            foreach ($this->_optionalEmailFields as $field) {
107
+                if (empty($settings[$field])) {
108
+                    $settings[$field] = $settings['forum_email'];
109
+                }
110
+            }
111
+        }
112
+
113
+    }
114 114
\ No newline at end of file
Please login to merge, or discard this patch.