Completed
Push — master ( 945d9a...e5db64 )
by Schlaefer
02:51
created
app/Controller/EntriesController.php 2 patches
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -43,8 +43,8 @@  discard block
 block discarded – undo
43 43
 
44 44
 			$currentPage = 1;
45 45
 			if (isset($this->request->named['page']) && $this->request->named['page'] != 1) {
46
-				$currentPage = (int)$this->request->named['page'];
47
-				$this->set('title_for_layout', __('page') . ' ' . $currentPage);
46
+				$currentPage = (int) $this->request->named['page'];
47
+				$this->set('title_for_layout', __('page').' '.$currentPage);
48 48
 			}
49 49
 			if ($currentPage === 1 && $this->CurrentUser->isLoggedIn()
50 50
 				&& $this->CurrentUser['user_automaticaly_mark_as_read']
@@ -146,11 +146,11 @@  discard block
 block discarded – undo
146 146
 		public function source($id = null) {
147 147
 			$this->autoRender = false;
148 148
 
149
-			$data = $this->requestAction('/entries/view/' . $id);
149
+			$data = $this->requestAction('/entries/view/'.$id);
150 150
 
151 151
 			$out = array();
152 152
 			$out[] = '<pre style="white-space: pre-wrap;">';
153
-			$out[] = $data['Entry']['subject'] . "\n";
153
+			$out[] = $data['Entry']['subject']."\n";
154 154
 			$out[] = $data['Entry']['text'];
155 155
 			$out[] = '</pre>';
156 156
 			return implode("\n", $out);
@@ -233,9 +233,9 @@  discard block
 block discarded – undo
233 233
 
234 234
 							return json_encode(
235 235
 								[
236
-									'id' => (int)$newPosting['Entry']['id'],
237
-									'pid' => (int)$newPosting['Entry']['pid'],
238
-									'tid' => (int)$newPosting['Entry']['tid']
236
+									'id' => (int) $newPosting['Entry']['id'],
237
+									'pid' => (int) $newPosting['Entry']['pid'],
238
+									'tid' => (int) $newPosting['Entry']['tid']
239 239
 								]
240 240
 							);
241 241
 						} else {
@@ -336,8 +336,8 @@  discard block
 block discarded – undo
336 336
 				}
337 337
 			}
338 338
 
339
-			$this->set('is_answer', (int)$this->request->data['Entry']['pid'] !== 0);
340
-			$this->set('is_inline', (int)$this->request->data['Entry']['pid'] !== 0);
339
+			$this->set('is_answer', (int) $this->request->data['Entry']['pid'] !== 0);
340
+			$this->set('is_inline', (int) $this->request->data['Entry']['pid'] !== 0);
341 341
 			$this->set('form_id', $this->request->data['Entry']['pid']);
342 342
 			$this->_setAddViewVars();
343 343
 		}
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
 			);
440 440
 			$this->set('notis', $notis);
441 441
 
442
-			$this->set('is_answer', (int)$this->request->data['Entry']['pid'] !== 0);
442
+			$this->set('is_answer', (int) $this->request->data['Entry']['pid'] !== 0);
443 443
 			$this->set('is_inline', false);
444 444
 			$this->set('form_id', $this->request->data['Entry']['pid']);
445 445
 
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
 				$this->redirect('/');
488 488
 			} else {
489 489
 				$this->Session->setFlash(__('delete_subtree_success'), 'flash/success');
490
-				$this->redirect('/entries/view/' . $entry['Entry']['pid']);
490
+				$this->redirect('/entries/view/'.$entry['Entry']['pid']);
491 491
 			}
492 492
 		} else {
493 493
 			$this->Session->setFlash(__('delete_tree_error'), 'flash/error');
@@ -587,16 +587,16 @@  discard block
 block discarded – undo
587 587
 			else :
588 588
 				// validation errors
589 589
 				foreach ($errors as $field => $error) {
590
-					$message = __d('nondynamic', $field) . ": " . __d( 'nondynamic', $error[0]);
590
+					$message = __d('nondynamic', $field).": ".__d('nondynamic', $error[0]);
591 591
 					$this->JsData->addAppJsMessage(
592 592
 						$message,
593 593
 						[
594 594
 							'type' => 'error',
595 595
 							'channel' => 'form',
596
-							'element' => '#Entry' . array_reduce(
596
+							'element' => '#Entry'.array_reduce(
597 597
 									explode('_', $field),
598
-									function ($carry, $item) {
599
-										return $carry . ucfirst($item);
598
+									function($carry, $item) {
599
+										return $carry.ucfirst($item);
600 600
 									},
601 601
 									''
602 602
 								)
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
 			$this->Entry->contain();
627 627
 			$data = $this->Entry->findById($id);
628 628
 
629
-			if (!$data || (int)$data['Entry']['pid'] !== 0) {
629
+			if (!$data || (int) $data['Entry']['pid'] !== 0) {
630 630
 				throw new NotFoundException();
631 631
 			}
632 632
 
@@ -635,7 +635,7 @@  discard block
 block discarded – undo
635 635
 				$targetId = $this->request->data['Entry']['targetId'];
636 636
 				$this->Entry->id = $id;
637 637
 				if ($this->Entry->threadMerge($targetId)) {
638
-					$this->redirect('/entries/view/' . $id);
638
+					$this->redirect('/entries/view/'.$id);
639 639
 					return;
640 640
 				} else {
641 641
 					$this->Session->setFlash(__("Error"), 'flash/error');
@@ -676,10 +676,10 @@  discard block
 block discarded – undo
676 676
 				//* let's toggle
677 677
 				$this->Entry->id = $id;
678 678
 				$this->request->data = $this->Entry->toggle($toggle);
679
-				return ($this->request->data == 0) ? __d('nondynamic', $toggle . '_set_entry_link') : __d('nondynamic', $toggle . '_unset_entry_link');
679
+				return ($this->request->data == 0) ? __d('nondynamic', $toggle.'_set_entry_link') : __d('nondynamic', $toggle.'_unset_entry_link');
680 680
 			}
681 681
 
682
-			$this->set('json_data', (string)$this->request->data);
682
+			$this->set('json_data', (string) $this->request->data);
683 683
 			$this->render('/Elements/json/json_data');
684 684
 		}
685 685
 
@@ -925,7 +925,7 @@  discard block
 block discarded – undo
925 925
 						// … directly in entries/mix
926 926
 						|| $this->request->action === 'mix'
927 927
 						// … inline viewing … on entries/index.
928
-						|| ( $this->localReferer('controller') === 'entries' && $this->localReferer('action') === 'index')
928
+						|| ($this->localReferer('controller') === 'entries' && $this->localReferer('action') === 'index')
929 929
 				):
930 930
 					$showAnsweringPanel = true;
931 931
 				endif;
@@ -934,7 +934,7 @@  discard block
 block discarded – undo
934 934
 		}
935 935
 
936 936
 		protected function _setRootEntry($entry) {
937
-			if ((int)$entry['Entry']['pid'] !== 0) {
937
+			if ((int) $entry['Entry']['pid'] !== 0) {
938 938
 				$_rootEntry = $this->Entry->find('first',
939 939
 					[
940 940
 						'contain' => false,
@@ -949,9 +949,9 @@  discard block
 block discarded – undo
949 949
 
950 950
 		protected function _setTitleFromEntry($entry, $type = null) {
951 951
 			if ($type === null) {
952
-				$template =	__(':subject | :category');
952
+				$template = __(':subject | :category');
953 953
 			} else {
954
-				$template =	__(':subject (:type) | :category');
954
+				$template = __(':subject (:type) | :category');
955 955
 			}
956 956
 			$this->set('title_for_layout',
957 957
 					CakeText::insert($template,
Please login to merge, or discard this patch.
Indentation   +883 added lines, -883 removed lines patch added patch discarded remove patch
@@ -1,140 +1,140 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-	use Saito\User\Categories;
4
-
5
-	App::uses('AppController', 'Controller');
6
-
7
-	class EntriesController extends AppController {
8
-
9
-		public $name = 'Entries';
10
-
11
-		public $helpers = [
12
-			'EntryH',
13
-			'MarkitupEditor',
14
-			'Shouts',
15
-			'Text',
16
-		];
17
-
18
-		public $components = [
19
-			'Shouts'
20
-		];
21
-
22
-		public function index() {
23
-			Stopwatch::start('Entries->index()');
24
-
25
-			$this->_prepareSlidetabData();
26
-
27
-			//= determine user sort order
28
-			$sortKey = 'Entry.';
29
-			if (!$this->CurrentUser->isLoggedIn() || $this->CurrentUser['user_sort_last_answer']) {
30
-				$sortKey .= 'last_answer';
31
-			} else {
32
-				$sortKey .= 'time';
33
-			}
34
-			$order = ['Entry.fixed' => 'DESC', $sortKey => 'DESC'];
35
-
36
-			//= get threads
37
-			$initials = $this->_getInitialThreads($this->CurrentUser, $order);
38
-			$threads = $this->Entry->treesForThreads($initials, $order);
39
-			foreach ($threads as $tid => $thread) {
40
-				$threads[$tid] = $this->dic->newInstance('\Saito\Posting\Posting', ['rawData' => $thread]);
41
-			}
42
-			$this->set('entries', $threads);
43
-
44
-			$currentPage = 1;
45
-			if (isset($this->request->named['page']) && $this->request->named['page'] != 1) {
46
-				$currentPage = (int)$this->request->named['page'];
47
-				$this->set('title_for_layout', __('page') . ' ' . $currentPage);
48
-			}
49
-			if ($currentPage === 1 && $this->CurrentUser->isLoggedIn()
50
-				&& $this->CurrentUser['user_automaticaly_mark_as_read']
51
-			) {
52
-				$this->set('markAsRead', true);
53
-			}
54
-			// @bogus
55
-			$this->Session->write('paginator.lastPage', $currentPage);
56
-			$this->showDisclaimer = true;
57
-			$this->set('allowThreadCollapse', true);
58
-
59
-			Stopwatch::stop('Entries->index()');
60
-		}
61
-
62
-		public function feed() {
63
-			Configure::write('debug', 0);
64
-
65
-			if (isset($this->request->params['named']['depth']) &&
66
-					$this->request->params['named']['depth'] === 'start'
67
-			) {
68
-				$title = __('Last started threads');
69
-				$order = 'time DESC';
70
-				$conditions['pid'] = 0;
71
-			} else {
72
-				$title = __('Last entries');
73
-				$order = 'last_answer DESC';
74
-			}
75
-
76
-			$conditions['category_id'] = $this->CurrentUser->Categories->getAllowed();
77
-
78
-			$entries = $this->Entry->find(
79
-				'feed',
80
-				[
81
-					'conditions' => $conditions,
82
-					'order' => $order
83
-				]
84
-			);
85
-			$this->set('entries', $entries);
86
-
87
-			// serialize for JSON
88
-			$this->set('_serialize', 'entries');
89
-			$this->set('title', $title);
90
-		}
91
-
92
-		/**
93
-		 * Mix view
94
-		 *
95
-		 * @param $tid
96
-		 * @throws NotFoundException
97
-		 */
98
-		public function mix($tid) {
99
-			if (!$tid) {
100
-				$this->redirect('/');
101
-			}
102
-			$entries = $this->Entry->treeForNode($tid,
103
-					['root' => true, 'complete' => true]);
104
-
105
-			if (empty($entries)) {
106
-				throw new NotFoundException();
107
-			}
108
-
109
-			// check if anonymous tries to access internal categories
110
-			$root = reset($entries);
111
-			$accession = $root['Category']['accession'];
112
-			if (!$this->CurrentUser->Categories->isAccessionAuthorized($accession)) {
113
-				$this->_requireAuth();
114
-				return;
115
-			}
116
-
117
-			$this->_setRootEntry($root);
118
-			$this->_setTitleFromEntry($root, __('view.type.mix'));
119
-
120
-			$entries = $this->dic->newInstance('\Saito\Posting\Posting', ['rawData' => $root]);
121
-			$this->set('entries', $entries);
122
-
123
-			$this->_showAnsweringPanel();
124
-
125
-			$this->_incrementViews($root, 'thread');
126
-
127
-			$this->_marMixThread = $tid;
128
-		}
3
+    use Saito\User\Categories;
4
+
5
+    App::uses('AppController', 'Controller');
6
+
7
+    class EntriesController extends AppController {
8
+
9
+        public $name = 'Entries';
10
+
11
+        public $helpers = [
12
+            'EntryH',
13
+            'MarkitupEditor',
14
+            'Shouts',
15
+            'Text',
16
+        ];
17
+
18
+        public $components = [
19
+            'Shouts'
20
+        ];
21
+
22
+        public function index() {
23
+            Stopwatch::start('Entries->index()');
24
+
25
+            $this->_prepareSlidetabData();
26
+
27
+            //= determine user sort order
28
+            $sortKey = 'Entry.';
29
+            if (!$this->CurrentUser->isLoggedIn() || $this->CurrentUser['user_sort_last_answer']) {
30
+                $sortKey .= 'last_answer';
31
+            } else {
32
+                $sortKey .= 'time';
33
+            }
34
+            $order = ['Entry.fixed' => 'DESC', $sortKey => 'DESC'];
35
+
36
+            //= get threads
37
+            $initials = $this->_getInitialThreads($this->CurrentUser, $order);
38
+            $threads = $this->Entry->treesForThreads($initials, $order);
39
+            foreach ($threads as $tid => $thread) {
40
+                $threads[$tid] = $this->dic->newInstance('\Saito\Posting\Posting', ['rawData' => $thread]);
41
+            }
42
+            $this->set('entries', $threads);
43
+
44
+            $currentPage = 1;
45
+            if (isset($this->request->named['page']) && $this->request->named['page'] != 1) {
46
+                $currentPage = (int)$this->request->named['page'];
47
+                $this->set('title_for_layout', __('page') . ' ' . $currentPage);
48
+            }
49
+            if ($currentPage === 1 && $this->CurrentUser->isLoggedIn()
50
+                && $this->CurrentUser['user_automaticaly_mark_as_read']
51
+            ) {
52
+                $this->set('markAsRead', true);
53
+            }
54
+            // @bogus
55
+            $this->Session->write('paginator.lastPage', $currentPage);
56
+            $this->showDisclaimer = true;
57
+            $this->set('allowThreadCollapse', true);
58
+
59
+            Stopwatch::stop('Entries->index()');
60
+        }
61
+
62
+        public function feed() {
63
+            Configure::write('debug', 0);
64
+
65
+            if (isset($this->request->params['named']['depth']) &&
66
+                    $this->request->params['named']['depth'] === 'start'
67
+            ) {
68
+                $title = __('Last started threads');
69
+                $order = 'time DESC';
70
+                $conditions['pid'] = 0;
71
+            } else {
72
+                $title = __('Last entries');
73
+                $order = 'last_answer DESC';
74
+            }
75
+
76
+            $conditions['category_id'] = $this->CurrentUser->Categories->getAllowed();
77
+
78
+            $entries = $this->Entry->find(
79
+                'feed',
80
+                [
81
+                    'conditions' => $conditions,
82
+                    'order' => $order
83
+                ]
84
+            );
85
+            $this->set('entries', $entries);
86
+
87
+            // serialize for JSON
88
+            $this->set('_serialize', 'entries');
89
+            $this->set('title', $title);
90
+        }
91
+
92
+        /**
93
+         * Mix view
94
+         *
95
+         * @param $tid
96
+         * @throws NotFoundException
97
+         */
98
+        public function mix($tid) {
99
+            if (!$tid) {
100
+                $this->redirect('/');
101
+            }
102
+            $entries = $this->Entry->treeForNode($tid,
103
+                    ['root' => true, 'complete' => true]);
104
+
105
+            if (empty($entries)) {
106
+                throw new NotFoundException();
107
+            }
108
+
109
+            // check if anonymous tries to access internal categories
110
+            $root = reset($entries);
111
+            $accession = $root['Category']['accession'];
112
+            if (!$this->CurrentUser->Categories->isAccessionAuthorized($accession)) {
113
+                $this->_requireAuth();
114
+                return;
115
+            }
116
+
117
+            $this->_setRootEntry($root);
118
+            $this->_setTitleFromEntry($root, __('view.type.mix'));
119
+
120
+            $entries = $this->dic->newInstance('\Saito\Posting\Posting', ['rawData' => $root]);
121
+            $this->set('entries', $entries);
122
+
123
+            $this->_showAnsweringPanel();
124
+
125
+            $this->_incrementViews($root, 'thread');
126
+
127
+            $this->_marMixThread = $tid;
128
+        }
129 129
 
130 130
 /**
131 131
  * load front page force all entries mark-as-read
132 132
  */
133
-		public function update() {
134
-			$this->autoRender = false;
135
-			$this->CurrentUser->LastRefresh->set('now');
136
-			$this->redirect('/entries/index');
137
-		}
133
+        public function update() {
134
+            $this->autoRender = false;
135
+            $this->CurrentUser->LastRefresh->set('now');
136
+            $this->redirect('/entries/index');
137
+        }
138 138
 
139 139
 /**
140 140
  * Outputs raw markup of an posting $id
@@ -143,72 +143,72 @@  discard block
 block discarded – undo
143 143
  *
144 144
  * @return string
145 145
  */
146
-		public function source($id = null) {
147
-			$this->autoRender = false;
146
+        public function source($id = null) {
147
+            $this->autoRender = false;
148 148
 
149
-			$data = $this->requestAction('/entries/view/' . $id);
149
+            $data = $this->requestAction('/entries/view/' . $id);
150 150
 
151
-			$out = array();
152
-			$out[] = '<pre style="white-space: pre-wrap;">';
153
-			$out[] = $data['Entry']['subject'] . "\n";
154
-			$out[] = $data['Entry']['text'];
155
-			$out[] = '</pre>';
156
-			return implode("\n", $out);
157
-		}
151
+            $out = array();
152
+            $out[] = '<pre style="white-space: pre-wrap;">';
153
+            $out[] = $data['Entry']['subject'] . "\n";
154
+            $out[] = $data['Entry']['text'];
155
+            $out[] = '</pre>';
156
+            return implode("\n", $out);
157
+        }
158 158
 
159
-		public function view($id = null) {
160
-			Stopwatch::start('Entries->view()');
159
+        public function view($id = null) {
160
+            Stopwatch::start('Entries->view()');
161 161
 
162
-			// redirect if no id is given
163
-			if (!$id) {
164
-				$this->Session->setFlash(__('Invalid post'));
165
-				return $this->redirect(['action' => 'index']);
166
-			}
162
+            // redirect if no id is given
163
+            if (!$id) {
164
+                $this->Session->setFlash(__('Invalid post'));
165
+                return $this->redirect(['action' => 'index']);
166
+            }
167 167
 
168
-			$this->Entry->id = $id;
169
-			$entry = $this->Entry->get($id);
168
+            $this->Entry->id = $id;
169
+            $entry = $this->Entry->get($id);
170 170
 
171
-			// redirect if posting doesn't exists
172
-			if ($entry == false) {
173
-				$this->Session->setFlash(__('Invalid post'));
174
-				$this->redirect('/');
175
-				return;
176
-			}
171
+            // redirect if posting doesn't exists
172
+            if ($entry == false) {
173
+                $this->Session->setFlash(__('Invalid post'));
174
+                $this->redirect('/');
175
+                return;
176
+            }
177 177
 
178
-			// check if anonymous tries to access internal categories
179
-			$accession = $entry['Category']['accession'];
180
-			if (!$this->CurrentUser->Categories->isAccessionAuthorized($accession)) {
181
-				$this->_requireAuth();
182
-				return;
183
-			}
178
+            // check if anonymous tries to access internal categories
179
+            $accession = $entry['Category']['accession'];
180
+            if (!$this->CurrentUser->Categories->isAccessionAuthorized($accession)) {
181
+                $this->_requireAuth();
182
+                return;
183
+            }
184 184
 
185
-			$this->_incrementViews($entry);
185
+            $this->_incrementViews($entry);
186 186
 
187
-			// for /source/<id> view
188
-			if (!empty($this->request->params['requested'])) {
189
-				return $entry;
190
-			}
187
+            // for /source/<id> view
188
+            if (!empty($this->request->params['requested'])) {
189
+                return $entry;
190
+            }
191 191
 
192
-			$this->set('entry', $entry);
192
+            $this->set('entry', $entry);
193 193
 
194
-			$this->_setRootEntry($entry);
195
-			$this->_showAnsweringPanel();
194
+            $this->_setRootEntry($entry);
195
+            $this->_showAnsweringPanel();
196 196
 
197
-			$this->CurrentUser->ReadEntries->set($entry);
197
+            $this->CurrentUser->ReadEntries->set($entry);
198 198
 
199
-			// inline open
200
-			if ($this->request->is('ajax')) {
201
-				$this->render('/Elements/entry/view_posting');
202
-				return;
203
-			}
199
+            // inline open
200
+            if ($this->request->is('ajax')) {
201
+                $this->render('/Elements/entry/view_posting');
202
+                return;
203
+            }
204 204
 
205
-			// full page request
206
-			$this->set('tree',
207
-					$this->Entry->treeForNode($entry['Entry']['tid'], ['root' => true]));
208
-			$this->_setTitleFromEntry($entry);
205
+            // full page request
206
+            $this->set('tree',
207
+                    $this->Entry->treeForNode($entry['Entry']['tid'], ['root' => true]));
208
+            $this->_setTitleFromEntry($entry);
209 209
 
210
-			Stopwatch::stop('Entries->view()');
211
-		}
210
+            Stopwatch::stop('Entries->view()');
211
+        }
212 212
 
213 213
 /**
214 214
  * @param null $id
@@ -216,143 +216,143 @@  discard block
 block discarded – undo
216 216
  * @return string
217 217
  * @throws ForbiddenException
218 218
  */
219
-		public function add($id = null) {
220
-			$this->set('title_for_layout', __('Write a New Entry'));
221
-
222
-			//# insert new entry
223
-			if (!empty($this->request->data)) {
224
-				$newPosting = $this->Entry->createPosting($this->request->data);
225
-
226
-				// inserting new posting was successful
227
-				if ($newPosting !== false) :
228
-					$this->_setNotifications($newPosting + $this->request->data);
229
-					if ($this->request->is('ajax')) :
230
-						// Ajax request came from front answer on front page /entries/index
231
-						if ($this->localReferer('action') === 'index') {
232
-							$this->autoRender = false;
233
-
234
-							return json_encode(
235
-								[
236
-									'id' => (int)$newPosting['Entry']['id'],
237
-									'pid' => (int)$newPosting['Entry']['pid'],
238
-									'tid' => (int)$newPosting['Entry']['tid']
239
-								]
240
-							);
241
-						} else {
242
-							$this->_stop();
243
-						}
244
-					// answering through POST request
245
-					else :
246
-						if ($this->localReferer('action') === 'mix') {
247
-							// answer request came from mix ansicht
248
-							$this->redirect(
249
-								[
250
-									'controller' => 'entries',
251
-									'action' => 'mix',
252
-									$newPosting['Entry']['tid'],
253
-									'#' => $this->Entry->id
254
-								]
255
-							);
256
-
257
-						} else {
258
-							// normal posting from entries/add or entries/view
259
-							$this->redirect(
260
-								[
261
-									'controller' => 'entries',
262
-									'action' => 'view',
263
-									$this->Entry->id
264
-								]
265
-							);
266
-
267
-						}
268
-						return;
269
-					endif;
270
-				else :
271
-					// Error while trying to save a post
272
-					if (count($this->Entry->validationErrors) === 0) {
273
-						$this->Session->setFlash(
274
-							__(
275
-								'Something clogged the tubes. Could not save entry. Try again.'
276
-							),
277
-							'flash/error'
278
-						);
279
-					}
280
-				endif;
281
-
282
-			// show add form
283
-			} else {
284
-				$isAnswer = $id !== null;
285
-				$this->request->data = null;
286
-
287
-				if ($isAnswer) {
288
-					if ($this->request->is('ajax') === false) {
289
-						$this->redirect($this->referer());
290
-						return;
291
-					}
292
-
293
-					$this->request->data = $this->Entry->get($id);
294
-					$posting = $this->dic->newInstance('\Saito\Posting\Posting',
295
-						['rawData' => $this->request->data]);
296
-
297
-					if ($posting->isAnsweringForbidden()) {
298
-						throw new ForbiddenException;
299
-					}
300
-
301
-					// create new subentry
302
-					unset($this->request->data['Entry']['id']);
303
-					$this->request->data['Entry']['pid'] = $id;
304
-					$this->set('citeSubject', $this->request->data['Entry']['subject']);
305
-					// subject is empty in answer-form
306
-					unset($this->request->data['Entry']['subject']);
307
-					$this->set('citeText', $this->request->data['Entry']['text']);
308
-					// text field is empty in answer
309
-					unset($this->request->data['Entry']['text']);
310
-
311
-					// get notifications
312
-					$notis = $this->Entry->Esevent->checkEventsForUser(
313
-						$this->CurrentUser->getId(),
314
-						array(
315
-							1 => array(
316
-								'subject' => $this->request->data['Entry']['tid'],
317
-								'event' => 'Model.Entry.replyToThread',
318
-								'receiver' => 'EmailNotification',
319
-							),
320
-						)
321
-					);
322
-					$this->set('notis', $notis);
323
-
324
-					// set Subnav
325
-					$headerSubnavLeftTitle = __(
326
-						'back_to_posting_from_linkname',
327
-						$this->request->data['User']['username']
328
-					);
329
-					$this->set('headerSubnavLeftTitle', $headerSubnavLeftTitle);
330
-
331
-					$this->set('title_for_layout', __('Write a Reply'));
332
-				} else {
333
-					// new posting which creates new thread
334
-					$this->request->data['Entry']['pid'] = 0;
335
-					$this->request->data['Entry']['tid'] = 0;
336
-				}
337
-			}
338
-
339
-			$this->set('is_answer', (int)$this->request->data['Entry']['pid'] !== 0);
340
-			$this->set('is_inline', (int)$this->request->data['Entry']['pid'] !== 0);
341
-			$this->set('form_id', $this->request->data['Entry']['pid']);
342
-			$this->_setAddViewVars();
343
-		}
344
-
345
-		public function threadLine($id) {
346
-			$entry = $this->Entry->get($id);
347
-			$accession = $entry['Category']['accession'];
348
-			if (!$this->CurrentUser->Categories->isAccessionAuthorized($accession)) {
349
-				$this->_requireAuth();
350
-				return;
351
-			}
352
-			$this->set('entry_sub', $entry);
353
-			// ajax requests so far are always answers
354
-			$this->set('level', '1');
355
-		}
219
+        public function add($id = null) {
220
+            $this->set('title_for_layout', __('Write a New Entry'));
221
+
222
+            //# insert new entry
223
+            if (!empty($this->request->data)) {
224
+                $newPosting = $this->Entry->createPosting($this->request->data);
225
+
226
+                // inserting new posting was successful
227
+                if ($newPosting !== false) :
228
+                    $this->_setNotifications($newPosting + $this->request->data);
229
+                    if ($this->request->is('ajax')) :
230
+                        // Ajax request came from front answer on front page /entries/index
231
+                        if ($this->localReferer('action') === 'index') {
232
+                            $this->autoRender = false;
233
+
234
+                            return json_encode(
235
+                                [
236
+                                    'id' => (int)$newPosting['Entry']['id'],
237
+                                    'pid' => (int)$newPosting['Entry']['pid'],
238
+                                    'tid' => (int)$newPosting['Entry']['tid']
239
+                                ]
240
+                            );
241
+                        } else {
242
+                            $this->_stop();
243
+                        }
244
+                    // answering through POST request
245
+                    else :
246
+                        if ($this->localReferer('action') === 'mix') {
247
+                            // answer request came from mix ansicht
248
+                            $this->redirect(
249
+                                [
250
+                                    'controller' => 'entries',
251
+                                    'action' => 'mix',
252
+                                    $newPosting['Entry']['tid'],
253
+                                    '#' => $this->Entry->id
254
+                                ]
255
+                            );
256
+
257
+                        } else {
258
+                            // normal posting from entries/add or entries/view
259
+                            $this->redirect(
260
+                                [
261
+                                    'controller' => 'entries',
262
+                                    'action' => 'view',
263
+                                    $this->Entry->id
264
+                                ]
265
+                            );
266
+
267
+                        }
268
+                        return;
269
+                    endif;
270
+                else :
271
+                    // Error while trying to save a post
272
+                    if (count($this->Entry->validationErrors) === 0) {
273
+                        $this->Session->setFlash(
274
+                            __(
275
+                                'Something clogged the tubes. Could not save entry. Try again.'
276
+                            ),
277
+                            'flash/error'
278
+                        );
279
+                    }
280
+                endif;
281
+
282
+            // show add form
283
+            } else {
284
+                $isAnswer = $id !== null;
285
+                $this->request->data = null;
286
+
287
+                if ($isAnswer) {
288
+                    if ($this->request->is('ajax') === false) {
289
+                        $this->redirect($this->referer());
290
+                        return;
291
+                    }
292
+
293
+                    $this->request->data = $this->Entry->get($id);
294
+                    $posting = $this->dic->newInstance('\Saito\Posting\Posting',
295
+                        ['rawData' => $this->request->data]);
296
+
297
+                    if ($posting->isAnsweringForbidden()) {
298
+                        throw new ForbiddenException;
299
+                    }
300
+
301
+                    // create new subentry
302
+                    unset($this->request->data['Entry']['id']);
303
+                    $this->request->data['Entry']['pid'] = $id;
304
+                    $this->set('citeSubject', $this->request->data['Entry']['subject']);
305
+                    // subject is empty in answer-form
306
+                    unset($this->request->data['Entry']['subject']);
307
+                    $this->set('citeText', $this->request->data['Entry']['text']);
308
+                    // text field is empty in answer
309
+                    unset($this->request->data['Entry']['text']);
310
+
311
+                    // get notifications
312
+                    $notis = $this->Entry->Esevent->checkEventsForUser(
313
+                        $this->CurrentUser->getId(),
314
+                        array(
315
+                            1 => array(
316
+                                'subject' => $this->request->data['Entry']['tid'],
317
+                                'event' => 'Model.Entry.replyToThread',
318
+                                'receiver' => 'EmailNotification',
319
+                            ),
320
+                        )
321
+                    );
322
+                    $this->set('notis', $notis);
323
+
324
+                    // set Subnav
325
+                    $headerSubnavLeftTitle = __(
326
+                        'back_to_posting_from_linkname',
327
+                        $this->request->data['User']['username']
328
+                    );
329
+                    $this->set('headerSubnavLeftTitle', $headerSubnavLeftTitle);
330
+
331
+                    $this->set('title_for_layout', __('Write a Reply'));
332
+                } else {
333
+                    // new posting which creates new thread
334
+                    $this->request->data['Entry']['pid'] = 0;
335
+                    $this->request->data['Entry']['tid'] = 0;
336
+                }
337
+            }
338
+
339
+            $this->set('is_answer', (int)$this->request->data['Entry']['pid'] !== 0);
340
+            $this->set('is_inline', (int)$this->request->data['Entry']['pid'] !== 0);
341
+            $this->set('form_id', $this->request->data['Entry']['pid']);
342
+            $this->_setAddViewVars();
343
+        }
344
+
345
+        public function threadLine($id) {
346
+            $entry = $this->Entry->get($id);
347
+            $accession = $entry['Category']['accession'];
348
+            if (!$this->CurrentUser->Categories->isAccessionAuthorized($accession)) {
349
+                $this->_requireAuth();
350
+                return;
351
+            }
352
+            $this->set('entry_sub', $entry);
353
+            // ajax requests so far are always answers
354
+            $this->set('level', '1');
355
+        }
356 356
 
357 357
 /**
358 358
  * @param null $id
@@ -360,99 +360,99 @@  discard block
 block discarded – undo
360 360
  * @throws NotFoundException
361 361
  * @throws BadRequestException
362 362
  */
363
-		public function edit($id = null) {
364
-			if (empty($id)) {
365
-				throw new BadRequestException();
366
-			}
367
-
368
-			$oldEntry = $this->Entry->get($id);
369
-			if (!$oldEntry) {
370
-				throw new NotFoundException();
371
-			}
372
-
373
-			/** * @var \Saito\Posting\Posting */
374
-			$posting = $this->dic->newInstance('\Saito\Posting\Posting', ['rawData' => $oldEntry]);
375
-
376
-			switch ($posting->isEditingAsCurrentUserForbidden()) {
377
-				case 'time':
378
-					$this->Session->setFlash(
379
-						'Stand by your word bro\', it\'s too late. @lo',
380
-						'flash/error'
381
-					);
382
-					$this->redirect(['action' => 'view', $id]);
383
-					return;
384
-				case 'user':
385
-					$this->Session->setFlash('Not your horse, Hoss! @lo', 'flash/error');
386
-					$this->redirect(['action' => 'view', $id]);
387
-					return;
388
-				case true :
389
-					$this->Session->setFlash(
390
-						'Something went terribly wrong. Alert the authorities now! @lo',
391
-						'flash/error'
392
-					);
393
-					return;
394
-			}
395
-
396
-			// try to save edit
397
-			if (!empty($this->request->data)) {
398
-				$data = $this->request->data;
399
-				$data['Entry']['id'] = $id;
400
-				$newEntry = $this->Entry->update($data);
401
-				if ($newEntry) {
402
-					$this->_setNotifications(am($this->request['data'], $oldEntry));
403
-					$this->redirect(['action' => 'view', $id]);
404
-					return;
405
-				} else {
406
-					$this->Session->setFlash(__('Something clogged the tubes. Could not save entry. Try again.'));
407
-				}
408
-			}
409
-
410
-			// show editing form
411
-			if ($posting->isEditingWithRoleUserForbidden()) {
412
-				$this->Session->setFlash(__('notice_you_are_editing_as_mod'), 'flash/warning');
413
-			}
414
-
415
-			$this->request->data = Hash::merge($oldEntry, $this->request->data);
416
-
417
-			// get text of parent entry for citation
418
-			$parentEntryId = $oldEntry['Entry']['pid'];
419
-			if ($parentEntryId > 0) {
420
-				$parentEntry = $this->Entry->get($parentEntryId);
421
-				$this->set('citeText', $parentEntry['Entry']['text']);
422
-			}
423
-
424
-			// get notifications
425
-			$notis = $this->Entry->Esevent->checkEventsForUser(
426
-				$oldEntry['Entry']['user_id'],
427
-				array(
428
-					array(
429
-						'subject' => $oldEntry['Entry']['id'],
430
-						'event' => 'Model.Entry.replyToEntry',
431
-						'receiver' => 'EmailNotification',
432
-					),
433
-					array(
434
-						'subject' => $oldEntry['Entry']['tid'],
435
-						'event' => 'Model.Entry.replyToThread',
436
-						'receiver' => 'EmailNotification',
437
-					),
438
-				)
439
-			);
440
-			$this->set('notis', $notis);
441
-
442
-			$this->set('is_answer', (int)$this->request->data['Entry']['pid'] !== 0);
443
-			$this->set('is_inline', false);
444
-			$this->set('form_id', $this->request->data['Entry']['pid']);
445
-
446
-			// set headers
447
-			$this->set(
448
-				'headerSubnavLeftTitle',
449
-				__('back_to_posting_from_linkname', $this->request->data['User']['username'])
450
-			);
451
-			$this->set('headerSubnavLeftUrl', ['action' => 'view', $id]);
452
-			$this->set('form_title', __('edit_linkname'));
453
-			$this->_setAddViewVars();
454
-			$this->render('/Entries/add');
455
-		}
363
+        public function edit($id = null) {
364
+            if (empty($id)) {
365
+                throw new BadRequestException();
366
+            }
367
+
368
+            $oldEntry = $this->Entry->get($id);
369
+            if (!$oldEntry) {
370
+                throw new NotFoundException();
371
+            }
372
+
373
+            /** * @var \Saito\Posting\Posting */
374
+            $posting = $this->dic->newInstance('\Saito\Posting\Posting', ['rawData' => $oldEntry]);
375
+
376
+            switch ($posting->isEditingAsCurrentUserForbidden()) {
377
+                case 'time':
378
+                    $this->Session->setFlash(
379
+                        'Stand by your word bro\', it\'s too late. @lo',
380
+                        'flash/error'
381
+                    );
382
+                    $this->redirect(['action' => 'view', $id]);
383
+                    return;
384
+                case 'user':
385
+                    $this->Session->setFlash('Not your horse, Hoss! @lo', 'flash/error');
386
+                    $this->redirect(['action' => 'view', $id]);
387
+                    return;
388
+                case true :
389
+                    $this->Session->setFlash(
390
+                        'Something went terribly wrong. Alert the authorities now! @lo',
391
+                        'flash/error'
392
+                    );
393
+                    return;
394
+            }
395
+
396
+            // try to save edit
397
+            if (!empty($this->request->data)) {
398
+                $data = $this->request->data;
399
+                $data['Entry']['id'] = $id;
400
+                $newEntry = $this->Entry->update($data);
401
+                if ($newEntry) {
402
+                    $this->_setNotifications(am($this->request['data'], $oldEntry));
403
+                    $this->redirect(['action' => 'view', $id]);
404
+                    return;
405
+                } else {
406
+                    $this->Session->setFlash(__('Something clogged the tubes. Could not save entry. Try again.'));
407
+                }
408
+            }
409
+
410
+            // show editing form
411
+            if ($posting->isEditingWithRoleUserForbidden()) {
412
+                $this->Session->setFlash(__('notice_you_are_editing_as_mod'), 'flash/warning');
413
+            }
414
+
415
+            $this->request->data = Hash::merge($oldEntry, $this->request->data);
416
+
417
+            // get text of parent entry for citation
418
+            $parentEntryId = $oldEntry['Entry']['pid'];
419
+            if ($parentEntryId > 0) {
420
+                $parentEntry = $this->Entry->get($parentEntryId);
421
+                $this->set('citeText', $parentEntry['Entry']['text']);
422
+            }
423
+
424
+            // get notifications
425
+            $notis = $this->Entry->Esevent->checkEventsForUser(
426
+                $oldEntry['Entry']['user_id'],
427
+                array(
428
+                    array(
429
+                        'subject' => $oldEntry['Entry']['id'],
430
+                        'event' => 'Model.Entry.replyToEntry',
431
+                        'receiver' => 'EmailNotification',
432
+                    ),
433
+                    array(
434
+                        'subject' => $oldEntry['Entry']['tid'],
435
+                        'event' => 'Model.Entry.replyToThread',
436
+                        'receiver' => 'EmailNotification',
437
+                    ),
438
+                )
439
+            );
440
+            $this->set('notis', $notis);
441
+
442
+            $this->set('is_answer', (int)$this->request->data['Entry']['pid'] !== 0);
443
+            $this->set('is_inline', false);
444
+            $this->set('form_id', $this->request->data['Entry']['pid']);
445
+
446
+            // set headers
447
+            $this->set(
448
+                'headerSubnavLeftTitle',
449
+                __('back_to_posting_from_linkname', $this->request->data['User']['username'])
450
+            );
451
+            $this->set('headerSubnavLeftUrl', ['action' => 'view', $id]);
452
+            $this->set('form_title', __('edit_linkname'));
453
+            $this->_setAddViewVars();
454
+            $this->render('/Entries/add');
455
+        }
456 456
 
457 457
 /**
458 458
  * @param null $id
@@ -460,72 +460,72 @@  discard block
 block discarded – undo
460 460
  * @throws NotFoundException
461 461
  * @throws MethodNotAllowedException
462 462
  */
463
-	public function delete($id = null) {
464
-		if (!$id) {
465
-			throw new NotFoundException;
466
-		}
467
-
468
-		if (!$this->CurrentUser->isMod()) {
469
-			throw new MethodNotAllowedException;
470
-		}
471
-
472
-		$this->Entry->id = $id;
473
-		$this->Entry->contain();
474
-		$entry = $this->Entry->findById($id);
475
-
476
-		if (!$entry) {
477
-			throw new NotFoundException;
478
-		}
479
-
480
-		// Delete Entry
481
-		$success = $this->Entry->deleteNode($id);
482
-
483
-		// Redirect
484
-		if ($success) {
485
-			if ($this->Entry->isRoot($entry)) {
486
-				$this->Session->setFlash(__('delete_tree_success'), 'flash/success');
487
-				$this->redirect('/');
488
-			} else {
489
-				$this->Session->setFlash(__('delete_subtree_success'), 'flash/success');
490
-				$this->redirect('/entries/view/' . $entry['Entry']['pid']);
491
-			}
492
-		} else {
493
-			$this->Session->setFlash(__('delete_tree_error'), 'flash/error');
494
-			$this->redirect($this->referer());
495
-		}
496
-		$this->redirect('/');
497
-	}
463
+    public function delete($id = null) {
464
+        if (!$id) {
465
+            throw new NotFoundException;
466
+        }
467
+
468
+        if (!$this->CurrentUser->isMod()) {
469
+            throw new MethodNotAllowedException;
470
+        }
471
+
472
+        $this->Entry->id = $id;
473
+        $this->Entry->contain();
474
+        $entry = $this->Entry->findById($id);
475
+
476
+        if (!$entry) {
477
+            throw new NotFoundException;
478
+        }
479
+
480
+        // Delete Entry
481
+        $success = $this->Entry->deleteNode($id);
482
+
483
+        // Redirect
484
+        if ($success) {
485
+            if ($this->Entry->isRoot($entry)) {
486
+                $this->Session->setFlash(__('delete_tree_success'), 'flash/success');
487
+                $this->redirect('/');
488
+            } else {
489
+                $this->Session->setFlash(__('delete_subtree_success'), 'flash/success');
490
+                $this->redirect('/entries/view/' . $entry['Entry']['pid']);
491
+            }
492
+        } else {
493
+            $this->Session->setFlash(__('delete_tree_error'), 'flash/error');
494
+            $this->redirect($this->referer());
495
+        }
496
+        $this->redirect('/');
497
+    }
498 498
 
499 499
 /**
500 500
  * Empty function for benchmarking
501 501
  */
502
-		public function e() {
503
-			Stopwatch::start('Entries->e()');
504
-			Stopwatch::stop('Entries->e()');
505
-		}
506
-
507
-		/**
508
-		 * Marks sub-entry $id as solution to its current root-entry
509
-		 *
510
-		 * @param $id
511
-		 * @throws BadRequestException
512
-		 * @throws ForbiddenException
513
-		 * @throws Exception
514
-		 */
515
-		public function solve($id) {
516
-			if (!$this->CurrentUser->isLoggedIn()) {
517
-				throw new ForbiddenException;
518
-			}
519
-			$this->autoRender = false;
520
-			try {
521
-				$success = $this->Entry->toggleSolve($id);
522
-				if (!$success) {
523
-					throw new Exception;
524
-				}
525
-			} catch (Exception $e) {
526
-				throw new BadRequestException;
527
-			}
528
-		}
502
+        public function e() {
503
+            Stopwatch::start('Entries->e()');
504
+            Stopwatch::stop('Entries->e()');
505
+        }
506
+
507
+        /**
508
+         * Marks sub-entry $id as solution to its current root-entry
509
+         *
510
+         * @param $id
511
+         * @throws BadRequestException
512
+         * @throws ForbiddenException
513
+         * @throws Exception
514
+         */
515
+        public function solve($id) {
516
+            if (!$this->CurrentUser->isLoggedIn()) {
517
+                throw new ForbiddenException;
518
+            }
519
+            $this->autoRender = false;
520
+            try {
521
+                $success = $this->Entry->toggleSolve($id);
522
+                if (!$success) {
523
+                    throw new Exception;
524
+                }
525
+            } catch (Exception $e) {
526
+                throw new BadRequestException;
527
+            }
528
+        }
529 529
 
530 530
 /**
531 531
  * @return string
@@ -533,80 +533,80 @@  discard block
 block discarded – undo
533 533
  * @throws BadRequestException
534 534
  * @throws ForbiddenException
535 535
  */
536
-		public function preview() {
537
-			if ($this->CurrentUser->isLoggedIn() === false) {
538
-				throw new ForbiddenException();
539
-			}
540
-			if ($this->request->is('ajax') === false) {
541
-				throw new BadRequestException();
542
-			}
543
-			if ($this->request->is('get')) {
544
-				throw new MethodNotAllowedException();
545
-			}
546
-
547
-			$data = $this->request->data;
548
-			$data = $data['Entry'];
549
-			$newEntry = array(
550
-				'Entry' => array(
551
-					'id' => 'preview',
552
-					'pid' => $data['pid'],
553
-					'subject' => $data['subject'],
554
-					'text' => $data['text'],
555
-					'category_id' => $data['category_id'],
556
-					'edited_by' => null,
557
-					'fixed' => false,
558
-					'solves' => 0,
559
-					'views' => 0,
560
-					'ip' => '',
561
-					'time' => date("Y-m-d H:i:s")
562
-				)
563
-			);
564
-			$this->Entry->prepare($newEntry);
565
-			$this->Entry->set($newEntry);
566
-
567
-			$this->Entry->validates(['fieldList' => ['subject', 'text', 'category_id']]);
568
-			$errors = $this->Entry->validationErrors;
569
-
570
-			if (count($errors) === 0) :
571
-				// no validation errors
572
-				$newEntry['User'] = $this->CurrentUser->getSettings();
573
-				$newEntry = array_merge(
574
-					$newEntry,
575
-					$this->Entry->Category->find(
576
-						'first',
577
-						array(
578
-							'conditions' => array(
579
-								'id' => $newEntry['Entry']['category_id']
580
-							),
581
-							'contain' => false,
582
-						)
583
-					)
584
-				);
585
-				$entry = $this->dic->newInstance('\Saito\Posting\Posting', ['rawData' => $newEntry]);
586
-				$this->set('entry', $entry);
587
-			else :
588
-				// validation errors
589
-				foreach ($errors as $field => $error) {
590
-					$message = __d('nondynamic', $field) . ": " . __d( 'nondynamic', $error[0]);
591
-					$this->JsData->addAppJsMessage(
592
-						$message,
593
-						[
594
-							'type' => 'error',
595
-							'channel' => 'form',
596
-							'element' => '#Entry' . array_reduce(
597
-									explode('_', $field),
598
-									function ($carry, $item) {
599
-										return $carry . ucfirst($item);
600
-									},
601
-									''
602
-								)
603
-						]
604
-					);
605
-				}
606
-				$this->autoRender = false;
607
-				return json_encode($this->JsData->getAppJsMessages());
608
-			endif;
609
-		}
536
+        public function preview() {
537
+            if ($this->CurrentUser->isLoggedIn() === false) {
538
+                throw new ForbiddenException();
539
+            }
540
+            if ($this->request->is('ajax') === false) {
541
+                throw new BadRequestException();
542
+            }
543
+            if ($this->request->is('get')) {
544
+                throw new MethodNotAllowedException();
545
+            }
546
+
547
+            $data = $this->request->data;
548
+            $data = $data['Entry'];
549
+            $newEntry = array(
550
+                'Entry' => array(
551
+                    'id' => 'preview',
552
+                    'pid' => $data['pid'],
553
+                    'subject' => $data['subject'],
554
+                    'text' => $data['text'],
555
+                    'category_id' => $data['category_id'],
556
+                    'edited_by' => null,
557
+                    'fixed' => false,
558
+                    'solves' => 0,
559
+                    'views' => 0,
560
+                    'ip' => '',
561
+                    'time' => date("Y-m-d H:i:s")
562
+                )
563
+            );
564
+            $this->Entry->prepare($newEntry);
565
+            $this->Entry->set($newEntry);
566
+
567
+            $this->Entry->validates(['fieldList' => ['subject', 'text', 'category_id']]);
568
+            $errors = $this->Entry->validationErrors;
569
+
570
+            if (count($errors) === 0) :
571
+                // no validation errors
572
+                $newEntry['User'] = $this->CurrentUser->getSettings();
573
+                $newEntry = array_merge(
574
+                    $newEntry,
575
+                    $this->Entry->Category->find(
576
+                        'first',
577
+                        array(
578
+                            'conditions' => array(
579
+                                'id' => $newEntry['Entry']['category_id']
580
+                            ),
581
+                            'contain' => false,
582
+                        )
583
+                    )
584
+                );
585
+                $entry = $this->dic->newInstance('\Saito\Posting\Posting', ['rawData' => $newEntry]);
586
+                $this->set('entry', $entry);
587
+            else :
588
+                // validation errors
589
+                foreach ($errors as $field => $error) {
590
+                    $message = __d('nondynamic', $field) . ": " . __d( 'nondynamic', $error[0]);
591
+                    $this->JsData->addAppJsMessage(
592
+                        $message,
593
+                        [
594
+                            'type' => 'error',
595
+                            'channel' => 'form',
596
+                            'element' => '#Entry' . array_reduce(
597
+                                    explode('_', $field),
598
+                                    function ($carry, $item) {
599
+                                        return $carry . ucfirst($item);
600
+                                    },
601
+                                    ''
602
+                                )
603
+                        ]
604
+                    );
605
+                }
606
+                $this->autoRender = false;
607
+                return json_encode($this->JsData->getAppJsMessages());
608
+            endif;
609
+        }
610 610
 
611 611
 /**
612 612
  * @param null $id
@@ -614,37 +614,37 @@  discard block
 block discarded – undo
614 614
  * @throws NotFoundException
615 615
  * @throws MethodNotAllowedException
616 616
  */
617
-		public function merge($id = null) {
618
-			if (!$id) {
619
-				throw new NotFoundException();
620
-			}
621
-
622
-			if (!$this->CurrentUser->isMod() && !$this->CurrentUser->isAdmin()) {
623
-				throw new MethodNotAllowedException;
624
-			}
625
-
626
-			$this->Entry->contain();
627
-			$data = $this->Entry->findById($id);
628
-
629
-			if (!$data || (int)$data['Entry']['pid'] !== 0) {
630
-				throw new NotFoundException();
631
-			}
632
-
633
-			// perform move operation
634
-			if (isset($this->request->data['Entry']['targetId'])) {
635
-				$targetId = $this->request->data['Entry']['targetId'];
636
-				$this->Entry->id = $id;
637
-				if ($this->Entry->threadMerge($targetId)) {
638
-					$this->redirect('/entries/view/' . $id);
639
-					return;
640
-				} else {
641
-					$this->Session->setFlash(__("Error"), 'flash/error');
642
-				}
643
-			}
644
-
645
-			$this->layout = 'admin';
646
-			$this->request->data = $data;
647
-		}
617
+        public function merge($id = null) {
618
+            if (!$id) {
619
+                throw new NotFoundException();
620
+            }
621
+
622
+            if (!$this->CurrentUser->isMod() && !$this->CurrentUser->isAdmin()) {
623
+                throw new MethodNotAllowedException;
624
+            }
625
+
626
+            $this->Entry->contain();
627
+            $data = $this->Entry->findById($id);
628
+
629
+            if (!$data || (int)$data['Entry']['pid'] !== 0) {
630
+                throw new NotFoundException();
631
+            }
632
+
633
+            // perform move operation
634
+            if (isset($this->request->data['Entry']['targetId'])) {
635
+                $targetId = $this->request->data['Entry']['targetId'];
636
+                $this->Entry->id = $id;
637
+                if ($this->Entry->threadMerge($targetId)) {
638
+                    $this->redirect('/entries/view/' . $id);
639
+                    return;
640
+                } else {
641
+                    $this->Session->setFlash(__("Error"), 'flash/error');
642
+                }
643
+            }
644
+
645
+            $this->layout = 'admin';
646
+            $this->request->data = $data;
647
+        }
648 648
 
649 649
 /**
650 650
  * @param null $id
@@ -652,316 +652,316 @@  discard block
 block discarded – undo
652 652
  *
653 653
  * @return translated
654 654
  */
655
-		public function ajax_toggle($id = null, $toggle = null) {
656
-			$this->autoLayout = false;
657
-			$this->autoRender = false;
658
-
659
-			if (!$id || !$toggle || !$this->request->is('ajax')) {
660
-				return;
661
-			}
662
-
663
-			// check if the requested toggle is allowed to be changed via this function
664
-			$allowedToggles = array(
665
-					'fixed',
666
-					'locked',
667
-			);
668
-			if (!in_array($toggle, $allowedToggles)) {
669
-				$this->request->data = false;
670
-
671
-				// check is user is allowed to perform operation
672
-				// luckily we only mod options in the allowed toggles
673
-			} elseif ($this->CurrentUser->isMod() === false) {
674
-				$this->request->data = false;
675
-			} else {
676
-				//* let's toggle
677
-				$this->Entry->id = $id;
678
-				$this->request->data = $this->Entry->toggle($toggle);
679
-				return ($this->request->data == 0) ? __d('nondynamic', $toggle . '_set_entry_link') : __d('nondynamic', $toggle . '_unset_entry_link');
680
-			}
681
-
682
-			$this->set('json_data', (string)$this->request->data);
683
-			$this->render('/Elements/json/json_data');
684
-		}
685
-
686
-		public function beforeFilter() {
687
-			parent::beforeFilter();
688
-			Stopwatch::start('Entries->beforeFilter()');
689
-
690
-			$this->_automaticalyMarkAsRead();
691
-
692
-			$this->Security->unlockedActions = ['preview', 'solve', 'view'];
693
-			$this->Auth->allow('feed', 'index', 'view', 'mix', 'update');
694
-
695
-			switch ($this->request->action) {
696
-				case 'index':
697
-					$this->_setAutoRefreshTime();
698
-					break;
699
-				case 'add':
700
-				case 'edit':
701
-					if ($this->Components->enabled('Security')) {
702
-						$this->Components->disable('Security');
703
-					}
704
-			}
705
-
706
-			Stopwatch::stop('Entries->beforeFilter()');
707
-		}
708
-
709
-		public function afterFilter() {
710
-			if (isset($this->_marMixThread)) {
711
-				$entries = $this->Entry->find('all',
712
-						[
713
-								'contain' => false,
714
-								'conditions' => ['Entry.tid' => $this->_marMixThread],
715
-								'fields' => ['Entry.id', 'Entry.time']
716
-						]);
717
-				$this->CurrentUser->ReadEntries->set($entries);
718
-			}
719
-		}
720
-
721
-		protected function _automaticalyMarkAsRead() {
722
-			if (!$this->CurrentUser->isLoggedIn() ||
723
-					!$this->CurrentUser['user_automaticaly_mark_as_read']
724
-			) {
725
-				return;
726
-			}
727
-
728
-			if ($this->request->action === "index" &&
729
-					!$this->Session->read('User.last_refresh_tmp')
730
-			) {
731
-				// initiate sessions last_refresh_tmp for new sessions
732
-				$this->Session->write('User.last_refresh_tmp', time());
733
-			}
734
-
735
-			/* // old
655
+        public function ajax_toggle($id = null, $toggle = null) {
656
+            $this->autoLayout = false;
657
+            $this->autoRender = false;
658
+
659
+            if (!$id || !$toggle || !$this->request->is('ajax')) {
660
+                return;
661
+            }
662
+
663
+            // check if the requested toggle is allowed to be changed via this function
664
+            $allowedToggles = array(
665
+                    'fixed',
666
+                    'locked',
667
+            );
668
+            if (!in_array($toggle, $allowedToggles)) {
669
+                $this->request->data = false;
670
+
671
+                // check is user is allowed to perform operation
672
+                // luckily we only mod options in the allowed toggles
673
+            } elseif ($this->CurrentUser->isMod() === false) {
674
+                $this->request->data = false;
675
+            } else {
676
+                //* let's toggle
677
+                $this->Entry->id = $id;
678
+                $this->request->data = $this->Entry->toggle($toggle);
679
+                return ($this->request->data == 0) ? __d('nondynamic', $toggle . '_set_entry_link') : __d('nondynamic', $toggle . '_unset_entry_link');
680
+            }
681
+
682
+            $this->set('json_data', (string)$this->request->data);
683
+            $this->render('/Elements/json/json_data');
684
+        }
685
+
686
+        public function beforeFilter() {
687
+            parent::beforeFilter();
688
+            Stopwatch::start('Entries->beforeFilter()');
689
+
690
+            $this->_automaticalyMarkAsRead();
691
+
692
+            $this->Security->unlockedActions = ['preview', 'solve', 'view'];
693
+            $this->Auth->allow('feed', 'index', 'view', 'mix', 'update');
694
+
695
+            switch ($this->request->action) {
696
+                case 'index':
697
+                    $this->_setAutoRefreshTime();
698
+                    break;
699
+                case 'add':
700
+                case 'edit':
701
+                    if ($this->Components->enabled('Security')) {
702
+                        $this->Components->disable('Security');
703
+                    }
704
+            }
705
+
706
+            Stopwatch::stop('Entries->beforeFilter()');
707
+        }
708
+
709
+        public function afterFilter() {
710
+            if (isset($this->_marMixThread)) {
711
+                $entries = $this->Entry->find('all',
712
+                        [
713
+                                'contain' => false,
714
+                                'conditions' => ['Entry.tid' => $this->_marMixThread],
715
+                                'fields' => ['Entry.id', 'Entry.time']
716
+                        ]);
717
+                $this->CurrentUser->ReadEntries->set($entries);
718
+            }
719
+        }
720
+
721
+        protected function _automaticalyMarkAsRead() {
722
+            if (!$this->CurrentUser->isLoggedIn() ||
723
+                    !$this->CurrentUser['user_automaticaly_mark_as_read']
724
+            ) {
725
+                return;
726
+            }
727
+
728
+            if ($this->request->action === "index" &&
729
+                    !$this->Session->read('User.last_refresh_tmp')
730
+            ) {
731
+                // initiate sessions last_refresh_tmp for new sessions
732
+                $this->Session->write('User.last_refresh_tmp', time());
733
+            }
734
+
735
+            /* // old
736 736
 			$isMarkAsReadRequest = $this->localReferer('controller') === 'entries' &&
737 737
 					$this->localReferer('action') === 'index' &&
738 738
 					$this->request->action === "index";
739 739
 			*/
740 740
 
741
-			$isMarkAsReadRequest = isset($this->request->query['mar']) &&
742
-					$this->request->query['mar'] === '';
743
-
744
-			if ($isMarkAsReadRequest &&
745
-					$this->request->isPreview() === false
746
-			) {
747
-				// a second session A shall not accidentally mark something as read that isn't read on session B
748
-				if ($this->Session->read('User.last_refresh_tmp') > $this->CurrentUser['last_refresh_unix']) {
749
-					$this->CurrentUser->LastRefresh->set();
750
-				}
751
-				$this->Session->write('User.last_refresh_tmp', time());
752
-				$this->redirect('/');
753
-				return;
754
-			} elseif ($this->request->action === "index") {
755
-				$this->CurrentUser->LastRefresh->setMarker();
756
-			}
757
-		}
758
-
759
-		protected function _prepareSlidetabData() {
760
-			if ($this->CurrentUser->isLoggedIn()) {
761
-				// get current user's recent entries for slidetab
762
-				$this->set(
763
-					'recentPosts',
764
-					$this->Entry->getRecentEntries(
765
-						$this->CurrentUser,
766
-						[
767
-							'user_id' => $this->CurrentUser->getId(),
768
-							'limit' => 5
769
-						]
770
-					)
771
-				);
772
-				// get last 10 recent entries for slidetab
773
-				$this->set(
774
-					'recentEntries',
775
-					$this->Entry->getRecentEntries($this->CurrentUser)
776
-				);
777
-				// get shouts
778
-				if (in_array('slidetab_shoutbox', $this->viewVars['slidetabs'])) {
779
-					$this->Shouts->setShoutsForView();
780
-				}
781
-			}
782
-		}
783
-
784
-		protected function _incrementViews($entry, $type = null) {
785
-			if ($this->CurrentUser->isBot()) {
786
-				return;
787
-			}
788
-			$cUserId = $this->CurrentUser->getId();
789
-
790
-			if ($type === 'thread') {
791
-				$this->Entry->threadIncrementViews($entry['Entry']['tid'], $cUserId);
792
-			} elseif ($entry['Entry']['user_id'] != $cUserId) {
793
-				$this->Entry->incrementViews($entry['Entry']['id']);
794
-			}
795
-		}
796
-
797
-		protected function _setNotifications($newEntry) {
798
-			if (isset($newEntry['Event'])) {
799
-				$notis = [
800
-					[
801
-						'subject' => $newEntry['Entry']['id'],
802
-						'event' => 'Model.Entry.replyToEntry',
803
-						'receiver' => 'EmailNotification',
804
-						'set' => $newEntry['Event'][1]['event_type_id'],
805
-					],
806
-					[
807
-						'subject' => $newEntry['Entry']['tid'],
808
-						'event' => 'Model.Entry.replyToThread',
809
-						'receiver' => 'EmailNotification',
810
-						'set' => $newEntry['Event'][2]['event_type_id'],
811
-					]
812
-				];
813
-				$this->Entry->Esevent->notifyUserOnEvents(
814
-					$newEntry['Entry']['user_id'],
815
-					$notis
816
-				);
817
-			}
818
-		}
819
-
820
-		protected function _setAutoRefreshTime() {
821
-			if (!$this->CurrentUser->isLoggedIn()) {
822
-				return;
823
-			}
824
-			if ($this->CurrentUser['user_forum_refresh_time'] > 0) {
825
-				$this->set(
826
-					'autoPageReload',
827
-					$this->CurrentUser['user_forum_refresh_time'] * 60
828
-				);
829
-			}
830
-		}
831
-
832
-		/**
833
-		 * Gets thread ids for paginated entries/index.
834
-		 *
835
-		 * @param CurrentUserComponent $User
836
-		 * @param array $order sort order
837
-		 * @return array thread ids
838
-		 */
839
-		protected function _getInitialThreads(CurrentUserComponent $User, $order) {
840
-			Stopwatch::start('Entries->_getInitialThreads() Paginate');
841
-
842
-			$categories = $this->_setupCategoryChooser($User);
843
-
844
-			//! Check DB performance after changing conditions/sorting!
845
-			$this->paginate = [
846
-				'conditions' => [
847
-					'pid' => 0,
848
-					'Entry.category_id' => $categories
849
-				],
850
-				'contain' => false,
851
-				'fields' => 'id, pid, tid, time, last_answer, fixed',
852
-				'limit' => Configure::read('Saito.Settings.topics_per_page'),
853
-				'order' => $order,
854
-				'getInitialThreads' => 1,
855
-			];
856
-
857
-			// disallows overwriting pagination params from request
858
-			unset(
859
-				$this->request->params['named']['direction'],
860
-				$this->request->params['named']['sort']
861
-			);
862
-			$initialThreads = $this->paginate(null, null, array_keys($order));
863
-
864
-			$initialThreadsNew = [];
865
-			foreach ($initialThreads as $k => $v) {
866
-				$initialThreadsNew[$k] = $v['Entry']['id'];
867
-			}
868
-			Stopwatch::stop('Entries->_getInitialThreads() Paginate');
869
-
870
-			return $initialThreadsNew;
871
-		}
872
-
873
-		protected function _setupCategoryChooser(\Saito\User\ForumsUserInterface $User) {
874
-			$categories = $User->Categories->getAllowed();
875
-
876
-			$isUsed = $User->isLoggedIn() &&
877
-					(
878
-							Configure::read('Saito.Settings.category_chooser_global') ||
879
-							(
880
-									Configure::read(
881
-										'Saito.Settings.category_chooser_user_override'
882
-									) && $User['user_category_override']
883
-							)
884
-					);
885
-
886
-			if ($isUsed) {
887
-				// @todo find right place for this; also: User::getCategories();
888
-				$UserCategories = new Categories($User->getSettings(), $categories);
889
-				list($categories, $type, $custom) = $UserCategories->get();
890
-
891
-				$this->set('categoryChooserChecked', $custom);
892
-
893
-				switch ($type) {
894
-					case 'single':
895
-						$title = $User['user_category_active'];
896
-						break;
897
-					case 'custom':
898
-						$title = __('Custom');
899
-						break;
900
-					default:
901
-						$title = __('All Categories');
902
-				}
903
-				$this->set('categoryChooserTitleId', $title);
904
-				$this->set('categoryChooser', $User->Categories->getAllowed('list'));
905
-			}
906
-			return $categories;
907
-		}
908
-
909
-		protected function _setAddViewVars() {
910
-			//= categories for dropdown
911
-			$categories = $this->CurrentUser->Categories->getAllowed('list');
912
-			$this->set('categories', $categories);
913
-		}
741
+            $isMarkAsReadRequest = isset($this->request->query['mar']) &&
742
+                    $this->request->query['mar'] === '';
743
+
744
+            if ($isMarkAsReadRequest &&
745
+                    $this->request->isPreview() === false
746
+            ) {
747
+                // a second session A shall not accidentally mark something as read that isn't read on session B
748
+                if ($this->Session->read('User.last_refresh_tmp') > $this->CurrentUser['last_refresh_unix']) {
749
+                    $this->CurrentUser->LastRefresh->set();
750
+                }
751
+                $this->Session->write('User.last_refresh_tmp', time());
752
+                $this->redirect('/');
753
+                return;
754
+            } elseif ($this->request->action === "index") {
755
+                $this->CurrentUser->LastRefresh->setMarker();
756
+            }
757
+        }
758
+
759
+        protected function _prepareSlidetabData() {
760
+            if ($this->CurrentUser->isLoggedIn()) {
761
+                // get current user's recent entries for slidetab
762
+                $this->set(
763
+                    'recentPosts',
764
+                    $this->Entry->getRecentEntries(
765
+                        $this->CurrentUser,
766
+                        [
767
+                            'user_id' => $this->CurrentUser->getId(),
768
+                            'limit' => 5
769
+                        ]
770
+                    )
771
+                );
772
+                // get last 10 recent entries for slidetab
773
+                $this->set(
774
+                    'recentEntries',
775
+                    $this->Entry->getRecentEntries($this->CurrentUser)
776
+                );
777
+                // get shouts
778
+                if (in_array('slidetab_shoutbox', $this->viewVars['slidetabs'])) {
779
+                    $this->Shouts->setShoutsForView();
780
+                }
781
+            }
782
+        }
783
+
784
+        protected function _incrementViews($entry, $type = null) {
785
+            if ($this->CurrentUser->isBot()) {
786
+                return;
787
+            }
788
+            $cUserId = $this->CurrentUser->getId();
789
+
790
+            if ($type === 'thread') {
791
+                $this->Entry->threadIncrementViews($entry['Entry']['tid'], $cUserId);
792
+            } elseif ($entry['Entry']['user_id'] != $cUserId) {
793
+                $this->Entry->incrementViews($entry['Entry']['id']);
794
+            }
795
+        }
796
+
797
+        protected function _setNotifications($newEntry) {
798
+            if (isset($newEntry['Event'])) {
799
+                $notis = [
800
+                    [
801
+                        'subject' => $newEntry['Entry']['id'],
802
+                        'event' => 'Model.Entry.replyToEntry',
803
+                        'receiver' => 'EmailNotification',
804
+                        'set' => $newEntry['Event'][1]['event_type_id'],
805
+                    ],
806
+                    [
807
+                        'subject' => $newEntry['Entry']['tid'],
808
+                        'event' => 'Model.Entry.replyToThread',
809
+                        'receiver' => 'EmailNotification',
810
+                        'set' => $newEntry['Event'][2]['event_type_id'],
811
+                    ]
812
+                ];
813
+                $this->Entry->Esevent->notifyUserOnEvents(
814
+                    $newEntry['Entry']['user_id'],
815
+                    $notis
816
+                );
817
+            }
818
+        }
819
+
820
+        protected function _setAutoRefreshTime() {
821
+            if (!$this->CurrentUser->isLoggedIn()) {
822
+                return;
823
+            }
824
+            if ($this->CurrentUser['user_forum_refresh_time'] > 0) {
825
+                $this->set(
826
+                    'autoPageReload',
827
+                    $this->CurrentUser['user_forum_refresh_time'] * 60
828
+                );
829
+            }
830
+        }
831
+
832
+        /**
833
+         * Gets thread ids for paginated entries/index.
834
+         *
835
+         * @param CurrentUserComponent $User
836
+         * @param array $order sort order
837
+         * @return array thread ids
838
+         */
839
+        protected function _getInitialThreads(CurrentUserComponent $User, $order) {
840
+            Stopwatch::start('Entries->_getInitialThreads() Paginate');
841
+
842
+            $categories = $this->_setupCategoryChooser($User);
843
+
844
+            //! Check DB performance after changing conditions/sorting!
845
+            $this->paginate = [
846
+                'conditions' => [
847
+                    'pid' => 0,
848
+                    'Entry.category_id' => $categories
849
+                ],
850
+                'contain' => false,
851
+                'fields' => 'id, pid, tid, time, last_answer, fixed',
852
+                'limit' => Configure::read('Saito.Settings.topics_per_page'),
853
+                'order' => $order,
854
+                'getInitialThreads' => 1,
855
+            ];
856
+
857
+            // disallows overwriting pagination params from request
858
+            unset(
859
+                $this->request->params['named']['direction'],
860
+                $this->request->params['named']['sort']
861
+            );
862
+            $initialThreads = $this->paginate(null, null, array_keys($order));
863
+
864
+            $initialThreadsNew = [];
865
+            foreach ($initialThreads as $k => $v) {
866
+                $initialThreadsNew[$k] = $v['Entry']['id'];
867
+            }
868
+            Stopwatch::stop('Entries->_getInitialThreads() Paginate');
869
+
870
+            return $initialThreadsNew;
871
+        }
872
+
873
+        protected function _setupCategoryChooser(\Saito\User\ForumsUserInterface $User) {
874
+            $categories = $User->Categories->getAllowed();
875
+
876
+            $isUsed = $User->isLoggedIn() &&
877
+                    (
878
+                            Configure::read('Saito.Settings.category_chooser_global') ||
879
+                            (
880
+                                    Configure::read(
881
+                                        'Saito.Settings.category_chooser_user_override'
882
+                                    ) && $User['user_category_override']
883
+                            )
884
+                    );
885
+
886
+            if ($isUsed) {
887
+                // @todo find right place for this; also: User::getCategories();
888
+                $UserCategories = new Categories($User->getSettings(), $categories);
889
+                list($categories, $type, $custom) = $UserCategories->get();
890
+
891
+                $this->set('categoryChooserChecked', $custom);
892
+
893
+                switch ($type) {
894
+                    case 'single':
895
+                        $title = $User['user_category_active'];
896
+                        break;
897
+                    case 'custom':
898
+                        $title = __('Custom');
899
+                        break;
900
+                    default:
901
+                        $title = __('All Categories');
902
+                }
903
+                $this->set('categoryChooserTitleId', $title);
904
+                $this->set('categoryChooser', $User->Categories->getAllowed('list'));
905
+            }
906
+            return $categories;
907
+        }
908
+
909
+        protected function _setAddViewVars() {
910
+            //= categories for dropdown
911
+            $categories = $this->CurrentUser->Categories->getAllowed('list');
912
+            $this->set('categories', $categories);
913
+        }
914 914
 
915 915
 /**
916 916
  * Decide if an answering panel is show when rendering a posting
917 917
  */
918
-		protected function _showAnsweringPanel() {
919
-			$showAnsweringPanel = false;
920
-
921
-			if ($this->CurrentUser->isLoggedIn()) {
922
-				// Only logged in users see the answering buttons if they …
923
-				if (// … directly on entries/view but not inline
924
-						($this->request->action === 'view' && !$this->request->is('ajax'))
925
-						// … directly in entries/mix
926
-						|| $this->request->action === 'mix'
927
-						// … inline viewing … on entries/index.
928
-						|| ( $this->localReferer('controller') === 'entries' && $this->localReferer('action') === 'index')
929
-				):
930
-					$showAnsweringPanel = true;
931
-				endif;
932
-			}
933
-			$this->set('showAnsweringPanel', $showAnsweringPanel);
934
-		}
935
-
936
-		protected function _setRootEntry($entry) {
937
-			if ((int)$entry['Entry']['pid'] !== 0) {
938
-				$_rootEntry = $this->Entry->find('first',
939
-					[
940
-						'contain' => false,
941
-						'conditions' => ['Entry.id' => $entry['Entry']['tid']],
942
-						'fields' => ['Entry.user_id']
943
-					]);
944
-			} else {
945
-				$_rootEntry = $entry;
946
-			}
947
-			$this->set('rootEntry', $_rootEntry);
948
-		}
949
-
950
-		protected function _setTitleFromEntry($entry, $type = null) {
951
-			if ($type === null) {
952
-				$template =	__(':subject | :category');
953
-			} else {
954
-				$template =	__(':subject (:type) | :category');
955
-			}
956
-			$this->set('title_for_layout',
957
-					CakeText::insert($template,
958
-							[
959
-									'category' => $entry['Category']['category'],
960
-									'subject' => $entry['Entry']['subject'],
961
-									'type' => $type
962
-							]
963
-					)
964
-			);
965
-		}
966
-
967
-	}
918
+        protected function _showAnsweringPanel() {
919
+            $showAnsweringPanel = false;
920
+
921
+            if ($this->CurrentUser->isLoggedIn()) {
922
+                // Only logged in users see the answering buttons if they …
923
+                if (// … directly on entries/view but not inline
924
+                        ($this->request->action === 'view' && !$this->request->is('ajax'))
925
+                        // … directly in entries/mix
926
+                        || $this->request->action === 'mix'
927
+                        // … inline viewing … on entries/index.
928
+                        || ( $this->localReferer('controller') === 'entries' && $this->localReferer('action') === 'index')
929
+                ):
930
+                    $showAnsweringPanel = true;
931
+                endif;
932
+            }
933
+            $this->set('showAnsweringPanel', $showAnsweringPanel);
934
+        }
935
+
936
+        protected function _setRootEntry($entry) {
937
+            if ((int)$entry['Entry']['pid'] !== 0) {
938
+                $_rootEntry = $this->Entry->find('first',
939
+                    [
940
+                        'contain' => false,
941
+                        'conditions' => ['Entry.id' => $entry['Entry']['tid']],
942
+                        'fields' => ['Entry.user_id']
943
+                    ]);
944
+            } else {
945
+                $_rootEntry = $entry;
946
+            }
947
+            $this->set('rootEntry', $_rootEntry);
948
+        }
949
+
950
+        protected function _setTitleFromEntry($entry, $type = null) {
951
+            if ($type === null) {
952
+                $template =	__(':subject | :category');
953
+            } else {
954
+                $template =	__(':subject (:type) | :category');
955
+            }
956
+            $this->set('title_for_layout',
957
+                    CakeText::insert($template,
958
+                            [
959
+                                    'category' => $entry['Category']['category'],
960
+                                    'subject' => $entry['Entry']['subject'],
961
+                                    'type' => $type
962
+                            ]
963
+                    )
964
+            );
965
+        }
966
+
967
+    }
Please login to merge, or discard this patch.
app/Controller/ContactsController.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -128,7 +128,7 @@
 block discarded – undo
128 128
 				$Logger->write('Contact email failed', ['e' => $e]);
129 129
 
130 130
 				$this->Session->setFlash(
131
-					__('Message couldn\'t be send! ' . $e->getMessage()),
131
+					__('Message couldn\'t be send! '.$e->getMessage()),
132 132
 					'flash/error'
133 133
 				);
134 134
 			}
Please login to merge, or discard this patch.
Indentation   +135 added lines, -135 removed lines patch added patch discarded remove patch
@@ -1,137 +1,137 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-	App::uses('AppController', 'Controller');
4
-
5
-	class ContactsController extends AppController {
6
-
7
-		public $uses = [];
8
-
9
-		public function beforeFilter() {
10
-			parent::beforeFilter();
11
-			$this->showDisclaimer = true;
12
-			$this->Auth->allow('owner');
13
-		}
14
-
15
-		/**
16
-		 * Contacts forum's owner via contact address
17
-		 */
18
-		public function owner() {
19
-			//* show form
20
-			if (empty($this->request->data)) {
21
-				return;
22
-			}
23
-
24
-			$recipient = $this->SaitoEmail->getPredefinedSender('contact');
25
-
26
-			if ($this->CurrentUser->isLoggedIn()) {
27
-				$sender = $this->CurrentUser->getId();
28
-			} else {
29
-				$senderContact = $this->request->data['Message']['sender_contact'];
30
-
31
-				App::uses('Validation', 'Utility');
32
-				if (!Validation::email($senderContact)) {
33
-					$this->JsData->addAppJsMessage(__('error_email_not-valid'), [
34
-						'type' => 'error',
35
-						'channel' => 'form',
36
-						'element' => '#MessageSenderContact'
37
-					]);
38
-					return;
39
-				}
40
-
41
-				$sender['User'] = [
42
-					'username' => '',
43
-					'user_email' => $senderContact
44
-				];
45
-			}
46
-
47
-			$this->_contact($recipient, $sender);
48
-		}
49
-
50
-		/**
51
-		 * Contacts individual user
52
-		 *
53
-		 * @param null $id
54
-		 * @throws InvalidArgumentException
55
-		 * @throws BadRequestException
56
-		 */
57
-		public function user($id = null) {
58
-			if (empty($id) || !$this->CurrentUser->isLoggedIn()) {
59
-				throw new BadRequestException();
60
-			}
61
-
62
-			$this->User->id = $id;
63
-			$this->User->contain();
64
-			$recipient = $this->User->read();
65
-
66
-			if (empty($recipient) || !$recipient['User']['personal_messages']) {
67
-				throw new InvalidArgumentException();
68
-			}
69
-
70
-			$this->set('title_for_page',
71
-				__('user_contact_title', $recipient['User']['username'])
72
-			);
73
-
74
-			//* show form
75
-			if (empty($this->request->data)) {
76
-				$this->request->data = $recipient;
77
-				return;
78
-			}
79
-
80
-			$sender = $this->CurrentUser->getId();
81
-
82
-			$this->_contact($recipient, $sender);
83
-		}
84
-
85
-		protected function _contact($recipient, $sender) {
86
-			$validationError = false;
87
-
88
-			// validate and set subject
89
-			$subject = rtrim($this->request->data['Message']['subject']);
90
-			if (empty($subject)) {
91
-				$this->JsData->addAppJsMessage(
92
-					__('error_subject_empty'),
93
-					[
94
-						'type' => 'error',
95
-						'channel' => 'form',
96
-						'element' => '#MessageSubject'
97
-					]
98
-				);
99
-				$validationError = true;
100
-			}
101
-
102
-			$this->request->data = $this->request->data + $recipient;
103
-
104
-			if ($validationError) {
105
-				return;
106
-			}
107
-
108
-			try {
109
-				$email = [
110
-					'recipient' => $recipient,
111
-					'sender' => $sender,
112
-					'subject' => $subject,
113
-					'message' => $this->request->data['Message']['text'],
114
-					'template' => 'user_contact'
115
-				];
116
-
117
-				if (isset($this->request->data['Message']['carbon_copy']) && $this->request->data['Message']['carbon_copy']) {
118
-					$email['ccsender'] = true;
119
-				}
120
-
121
-				$mail = $this->SaitoEmail->email($email);
122
-				$this->set('email', $mail); // for evaluating send mail in test cases
123
-				$this->Session->setFlash(__('Message was send.'), 'flash/success');
124
-				$this->redirect('/');
125
-				return;
126
-			} catch (Exception $e) {
127
-				$Logger = new Saito\Logger\ExceptionLogger();
128
-				$Logger->write('Contact email failed', ['e' => $e]);
129
-
130
-				$this->Session->setFlash(
131
-					__('Message couldn\'t be send! ' . $e->getMessage()),
132
-					'flash/error'
133
-				);
134
-			}
135
-		}
136
-
137
-	}
3
+    App::uses('AppController', 'Controller');
4
+
5
+    class ContactsController extends AppController {
6
+
7
+        public $uses = [];
8
+
9
+        public function beforeFilter() {
10
+            parent::beforeFilter();
11
+            $this->showDisclaimer = true;
12
+            $this->Auth->allow('owner');
13
+        }
14
+
15
+        /**
16
+         * Contacts forum's owner via contact address
17
+         */
18
+        public function owner() {
19
+            //* show form
20
+            if (empty($this->request->data)) {
21
+                return;
22
+            }
23
+
24
+            $recipient = $this->SaitoEmail->getPredefinedSender('contact');
25
+
26
+            if ($this->CurrentUser->isLoggedIn()) {
27
+                $sender = $this->CurrentUser->getId();
28
+            } else {
29
+                $senderContact = $this->request->data['Message']['sender_contact'];
30
+
31
+                App::uses('Validation', 'Utility');
32
+                if (!Validation::email($senderContact)) {
33
+                    $this->JsData->addAppJsMessage(__('error_email_not-valid'), [
34
+                        'type' => 'error',
35
+                        'channel' => 'form',
36
+                        'element' => '#MessageSenderContact'
37
+                    ]);
38
+                    return;
39
+                }
40
+
41
+                $sender['User'] = [
42
+                    'username' => '',
43
+                    'user_email' => $senderContact
44
+                ];
45
+            }
46
+
47
+            $this->_contact($recipient, $sender);
48
+        }
49
+
50
+        /**
51
+         * Contacts individual user
52
+         *
53
+         * @param null $id
54
+         * @throws InvalidArgumentException
55
+         * @throws BadRequestException
56
+         */
57
+        public function user($id = null) {
58
+            if (empty($id) || !$this->CurrentUser->isLoggedIn()) {
59
+                throw new BadRequestException();
60
+            }
61
+
62
+            $this->User->id = $id;
63
+            $this->User->contain();
64
+            $recipient = $this->User->read();
65
+
66
+            if (empty($recipient) || !$recipient['User']['personal_messages']) {
67
+                throw new InvalidArgumentException();
68
+            }
69
+
70
+            $this->set('title_for_page',
71
+                __('user_contact_title', $recipient['User']['username'])
72
+            );
73
+
74
+            //* show form
75
+            if (empty($this->request->data)) {
76
+                $this->request->data = $recipient;
77
+                return;
78
+            }
79
+
80
+            $sender = $this->CurrentUser->getId();
81
+
82
+            $this->_contact($recipient, $sender);
83
+        }
84
+
85
+        protected function _contact($recipient, $sender) {
86
+            $validationError = false;
87
+
88
+            // validate and set subject
89
+            $subject = rtrim($this->request->data['Message']['subject']);
90
+            if (empty($subject)) {
91
+                $this->JsData->addAppJsMessage(
92
+                    __('error_subject_empty'),
93
+                    [
94
+                        'type' => 'error',
95
+                        'channel' => 'form',
96
+                        'element' => '#MessageSubject'
97
+                    ]
98
+                );
99
+                $validationError = true;
100
+            }
101
+
102
+            $this->request->data = $this->request->data + $recipient;
103
+
104
+            if ($validationError) {
105
+                return;
106
+            }
107
+
108
+            try {
109
+                $email = [
110
+                    'recipient' => $recipient,
111
+                    'sender' => $sender,
112
+                    'subject' => $subject,
113
+                    'message' => $this->request->data['Message']['text'],
114
+                    'template' => 'user_contact'
115
+                ];
116
+
117
+                if (isset($this->request->data['Message']['carbon_copy']) && $this->request->data['Message']['carbon_copy']) {
118
+                    $email['ccsender'] = true;
119
+                }
120
+
121
+                $mail = $this->SaitoEmail->email($email);
122
+                $this->set('email', $mail); // for evaluating send mail in test cases
123
+                $this->Session->setFlash(__('Message was send.'), 'flash/success');
124
+                $this->redirect('/');
125
+                return;
126
+            } catch (Exception $e) {
127
+                $Logger = new Saito\Logger\ExceptionLogger();
128
+                $Logger->write('Contact email failed', ['e' => $e]);
129
+
130
+                $this->Session->setFlash(
131
+                    __('Message couldn\'t be send! ' . $e->getMessage()),
132
+                    'flash/error'
133
+                );
134
+            }
135
+        }
136
+
137
+    }
Please login to merge, or discard this patch.
app/Controller/UsersController.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 			$code = $this->request->query('c');
158 158
 
159 159
 			try {
160
-				$activated = $this->User->activate((int)$id, $code);
160
+				$activated = $this->User->activate((int) $id, $code);
161 161
 			} catch (Exception $e) {
162 162
 				$activated = false;
163 163
 			}
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
 				return;
422 422
 			}
423 423
 
424
-			$id = (int)$this->request->data('User.lockUserId');
424
+			$id = (int) $this->request->data('User.lockUserId');
425 425
 			if (!$id) {
426 426
 				throw new BadRequestException;
427 427
 			}
@@ -445,7 +445,7 @@  discard block
 block discarded – undo
445 445
 				);
446 446
 			} else {
447 447
 				try {
448
-					$duration = (int)$this->request->data('User.lockPeriod');
448
+					$duration = (int) $this->request->data('User.lockPeriod');
449 449
 					$status = $this->User->UserBlock->block(
450 450
 						new \Saito\User\Blocker\ManualBlocker,
451 451
 						$id,
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
 			}
609 609
 
610 610
 			$allowed = $this->viewVars['slidetabs'];
611
-			$order = array_filter( $order, function ($item) use ($allowed) {
611
+			$order = array_filter($order, function($item) use ($allowed) {
612 612
 				return in_array($item, $allowed);
613 613
 			});
614 614
 			$order = serialize($order);
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
 			if ($CurrentUser->isAdmin()) {
668 668
 				return true;
669 669
 			}
670
-			return $CurrentUser->getId() === (int)$userId;
670
+			return $CurrentUser->getId() === (int) $userId;
671 671
 		}
672 672
 
673 673
 		protected function _passwordAuthSwitch($data) {
Please login to merge, or discard this patch.
Indentation   +677 added lines, -677 removed lines patch added patch discarded remove patch
@@ -1,679 +1,679 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-	use Saito\Exception\Logger\ExceptionLogger;
4
-	use Saito\Exception\Logger\ForbiddenLogger;
5
-	use Saito\Exception\SaitoForbiddenException;
6
-	use Saito\User\SaitoUser;
7
-
8
-	App::uses('AppController', 'Controller');
9
-
10
-	class UsersController extends AppController {
11
-
12
-		public $name = 'Users';
13
-
14
-		public $helpers = [
15
-			'Farbtastic',
16
-			'SimpleCaptcha.SimpleCaptcha',
17
-			'EntryH',
18
-			'Map',
19
-			'Text'
20
-		];
21
-
22
-		public function login() {
23
-			$this->CurrentUser->logOut();
24
-
25
-			//# just show form
26
-			if (empty($this->request->data['User']['username'])) {
27
-				return;
28
-			}
29
-
30
-			//# successful login with request data
31
-			if ($this->CurrentUser->login()) {
32
-				if ($this->localReferer('action') === 'login') {
33
-					$this->redirect($this->Auth->redirectUrl());
34
-				} else {
35
-					$this->redirect($this->referer());
36
-				}
37
-				return;
38
-			}
39
-
40
-			//# error on login
41
-			$this->User->contain();
42
-			$username = $this->request->data['User']['username'];
43
-			$readUser = $this->User->findByUsername($username);
44
-
45
-			$status = null;
46
-
47
-			if (!empty($readUser)) {
48
-				$User = new SaitoUser($readUser['User']);
49
-				$status = $User->isForbidden();
50
-			}
51
-
52
-			switch ($status) {
53
-				case 'locked':
54
-					$ends = $this->User->UserBlock
55
-						->getBlockEndsForUser($readUser['User']['id']);
56
-					if ($ends) {
57
-						$message = __('user.block.pubExpEnds', [$username,
58
-							CakeTime::timeAgoInWords($ends, ['accuracy' => 'hour'])]);
59
-					} else {
60
-						$message = __('user.block.pubExp', $username);
61
-					}
62
-					break;
63
-				case 'unactivated':
64
-					$message = __('User %s is not activated yet.', $readUser['User']['username']);
65
-					break;
66
-				default:
67
-					$message = __('auth_loginerror');
68
-			}
69
-
70
-			// don't autofill password
71
-			unset($this->request->data['User']['password']);
72
-
73
-			$Logger = new ForbiddenLogger;
74
-			$Logger->write("Unsuccessful login for user: $username",
75
-				['msgs' => [$message]]);
76
-
77
-			$this->Session->setFlash($message, 'default', [], 'auth');
78
-		}
79
-
80
-		public function logout() {
81
-			$this->CurrentUser->logout();
82
-		}
83
-
84
-		public function register() {
85
-			$this->set('status', 'view');
86
-
87
-			$this->CurrentUser->logout();
88
-
89
-			$tosRequired = Configure::read('Saito.Settings.tos_enabled');
90
-			$this->set(compact('tosRequired'));
91
-
92
-			// display empty form
93
-			if (empty($this->request->data)) {
94
-				return;
95
-			}
96
-
97
-			$data = $this->request->data;
98
-
99
-			if (!$tosRequired) {
100
-				$data['User']['tos_confirm'] = true;
101
-			}
102
-
103
-			$tosConfirmed = $data['User']['tos_confirm'];
104
-			if (!$tosConfirmed) {
105
-				return;
106
-			}
107
-
108
-			$data = $this->_passwordAuthSwitch($data);
109
-			$this->User->Behaviors->attach('SimpleCaptcha.SimpleCaptcha');
110
-			$user = $this->User->register($data);
111
-
112
-			// registering failed, show form again
113
-			if (!$user) {
114
-				// undo the passwordAuthSwitch() to display error message for the field
115
-				if (isset($this->User->validationErrors['password'])) {
116
-					$this->User->validationErrors['user_password'] = $this->User->validationErrors['password'];
117
-				}
118
-				$data['User']['tos_confirm'] = false;
119
-				$this->request->data = $data;
120
-				return;
121
-			}
122
-
123
-			// registered successfully
124
-			try {
125
-				$forumName = Configure::read('Saito.Settings.forum_name');
126
-				$subject = __('register_email_subject', $forumName);
127
-				$email = $this->SaitoEmail->email([
128
-					'recipient' => $data,
129
-					'subject' => $subject,
130
-					'sender' => 'register',
131
-					'template' => 'user_register',
132
-					'viewVars' => ['user' => $user]
133
-				]);
134
-				// only used in test cases
135
-				$this->set('email', $email);
136
-			} catch (Exception $e) {
137
-				$Logger = new ExceptionLogger();
138
-				$Logger->write('Registering email confirmation failed', ['e' => $e]);
139
-				$this->set('status', 'fail: email');
140
-				return;
141
-			}
142
-
143
-			$this->set('status', 'success');
144
-		}
145
-
146
-		/**
147
-		 * register success (user clicked link in confirm mail)
148
-		 *
149
-		 * @param $id
150
-		 * @throws BadRequestException
151
-		 */
152
-		public function rs($id = null) {
153
-			if (!$id) {
154
-				throw new BadRequestException();
155
-			}
156
-
157
-			$code = $this->request->query('c');
158
-
159
-			try {
160
-				$activated = $this->User->activate((int)$id, $code);
161
-			} catch (Exception $e) {
162
-				$activated = false;
163
-			}
164
-
165
-			if (!$activated) {
166
-				$activated = ['status' => 'fail'];
167
-			}
168
-			$this->set('status', $activated['status']);
169
-		}
170
-
171
-		public function admin_index() {
172
-			$data = $this->User->find(
173
-					'all',
174
-					[
175
-							'contain' => false,
176
-							'fields' => [
177
-									'id',
178
-									'username',
179
-									'user_type',
180
-									'user_email',
181
-									'registered',
182
-									'user_lock'
183
-							],
184
-							'order' => ['User.username' => 'asc']
185
-					]
186
-			);
187
-			$this->set('users', $data);
188
-		}
189
-
190
-		public function index() {
191
-			$menuItems = [
192
-				'username' => [__('username_marking'), []],
193
-				'user_type' => [__('user_type'), []],
194
-				'UserOnline.logged_in' => [__('userlist_online'), ['direction' => 'desc']],
195
-				'registered' => [__('registered'), ['direction' => 'desc']]
196
-			];
197
-			$showBlocked = Configure::read('Saito.Settings.block_user_ui');
198
-			if ($showBlocked) {
199
-				$menuItems['user_lock'] = [__('user.set.lock.t'), ['direction' => 'desc']];
200
-			}
201
-
202
-			$this->paginate = [
203
-				'contain' => 'UserOnline',
204
-				'limit' => 400,
205
-				'order' => ['UserOnline.logged_in' => 'desc', 'User.username' => 'asc']
206
-			];
207
-			$users = $this->paginate('User', null, array_keys($menuItems));
208
-
209
-			$this->set(compact('menuItems', 'users'));
210
-		}
211
-
212
-		public function ignore() {
213
-			$this->request->allowMethod('POST');
214
-			$blockedId = $this->request->data('id');
215
-			$this->_ignore($blockedId, true);
216
-		}
217
-
218
-		public function unignore() {
219
-			$this->request->allowMethod('POST');
220
-			$blockedId = $this->request->data('id');
221
-			$this->_ignore($blockedId, false);
222
-		}
223
-
224
-		protected function _ignore($blockedId, $set) {
225
-			if (!$this->CurrentUser->isLoggedIn() || !is_numeric($blockedId)) {
226
-				throw new BadRequestException();
227
-			}
228
-			$userId = $this->CurrentUser->getId();
229
-			$this->User->id = $userId;
230
-			if (!$this->User->exists($userId) || $userId == $blockedId) {
231
-				throw new BadRequestException();
232
-			}
233
-			if ($set) {
234
-				$this->User->Ignore->ignore($userId, $blockedId);
235
-			} else {
236
-				$this->User->Ignore->unignore($userId, $blockedId);
237
-			}
238
-			$this->redirect($this->referer());
239
-		}
240
-
241
-		public function admin_add() {
242
-			if (!empty($this->request->data)) :
243
-				$this->request->data = $this->_passwordAuthSwitch($this->request->data);
244
-				if ($this->User->register($this->request->data, true)) {
245
-					$this->Session->setFlash(__('user.admin.add.success'),
246
-							'flash/success');
247
-					$this->redirect(['action' => 'view', $this->User->id, 'admin' => false]);
248
-				}
249
-			endif;
250
-		}
251
-
252
-		public function map() {
253
-			if (!Configure::read('Saito.Settings.map_enabled')) {
254
-				$this->Session->setFlash(__('admin.setting.disabled', __('admin.feat.map')), 'flash/error');
255
-				$this->redirect('/');
256
-				return;
257
-			}
258
-			$users = $this->User->find('all',
259
-					[
260
-							'contain' => false,
261
-							'conditions' => ['user_place_lat !=' => null],
262
-							'fields' => [
263
-									'User.id',
264
-									'User.username',
265
-									'User.user_place_lat',
266
-									'User.user_place_lng'
267
-							]
268
-					]
269
-			);
270
-			$this->set(compact('users'));
271
-		}
272
-
273
-		public function name($id = null) {
274
-			if (!empty($id)) {
275
-				$this->User->contain();
276
-				$viewedUser = $this->User->findByUsername($id);
277
-				if (!empty($viewedUser)) {
278
-					$this->redirect(
279
-						[
280
-							'controller' => 'users',
281
-							'action' => 'view',
282
-							$viewedUser['User']['id']
283
-						]
284
-					);
285
-					return;
286
-				}
287
-			}
288
-			$this->Session->setFlash(__('Invalid user'), 'flash/error');
289
-			$this->redirect('/');
290
-		}
291
-
292
-		public function view($id = null) {
293
-			// redirect view/<username> to name/<username>
294
-			if (!empty($id) && !is_numeric($id)) {
295
-				$this->redirect(
296
-					[
297
-						'controller' => 'users',
298
-						'action' => 'name',
299
-						$id
300
-					]
301
-				);
302
-				return; // test case return
303
-			}
304
-
305
-			$this->User->id = $id;
306
-			$this->User->contain(['UserBlock' => ['By'], 'UserOnline']);
307
-			$viewedUser = $this->User->read();
308
-
309
-			if ($id === null || empty($viewedUser)) {
310
-				$this->Session->setFlash(__('Invalid user'), 'flash/error');
311
-				$this->redirect('/');
312
-				return;
313
-			}
314
-
315
-			$viewedUser['User']['number_of_entries'] = $this->User->numberOfEntries();
316
-
317
-			$entriesShownOnPage = 20;
318
-			$this->set(
319
-				'lastEntries',
320
-				$this->User->Entry->getRecentEntries(
321
-					$this->CurrentUser,
322
-					[
323
-						'user_id' => $this->User->id,
324
-						'limit' => $entriesShownOnPage
325
-					]
326
-				)
327
-			);
328
-
329
-			$this->set(
330
-				'hasMoreEntriesThanShownOnPage',
331
-					($viewedUser['User']['number_of_entries'] - $entriesShownOnPage) > 0
332
-			);
333
-
334
-			if ($this->CurrentUser->getId() == $id) {
335
-				$viewedUser['User']['ignores'] = $this->User->Ignore->ignoredBy($id);
336
-			}
337
-			$viewedUser['User']['solves_count'] = $this->User->countSolved($id);
338
-			$this->set('user', $viewedUser);
339
-			$this->set(
340
-					'title_for_layout',
341
-					$viewedUser['User']['username']
342
-			);
343
-		}
344
-
345
-		/**
346
-		 * @param null $id
347
-		 * @throws Saito\Exception\SaitoForbiddenException
348
-		 * @throws BadRequestException
349
-		 */
350
-	public function edit($id = null) {
351
-		if (!$id) {
352
-			throw new BadRequestException;
353
-		}
354
-		if (!$this->_isEditingAllowed($this->CurrentUser, $id)) {
355
-			throw new \Saito\Exception\SaitoForbiddenException("Attempt to edit user $id.", [
356
-				'CurrentUser' => $this->CurrentUser
357
-			]);
358
-		}
359
-
360
-		$this->set('userId', $id);
361
-
362
-		// try to save entry
363
-		if (!empty($this->request->data)) {
364
-			$data = $this->request->data['User'];
365
-
366
-			unset($data['id']);
367
-			//# make sure only admin can edit these fields
368
-			if ($this->CurrentUser['user_type'] !== 'admin') {
369
-				// @todo DRY: refactor this admin fields together with view
370
-				unset($data['username'], $data['user_email'], $data['user_type']);
371
-			}
372
-
373
-			$this->User->id = $id;
374
-			$success = $this->User->save($data);
375
-			if ($success) {
376
-				$this->redirect(['action' => 'view', $id]);
377
-				return;
378
-			} else {
379
-				// if empty fields are missing from send form read user again
380
-				$this->User->contain();
381
-				$user = $this->User->read();
382
-				$this->request->data['User'] = array_merge($user['User'],
383
-					$this->request->data['User']);
384
-
385
-				$this->User->set($this->request->data);
386
-				$this->User->validates();
387
-
388
-				$this->JsData->addAppJsMessage(
389
-					__('The user could not be saved. Please, try again.'),
390
-					['type' => 'error']);
391
-			}
392
-		}
393
-
394
-		if (empty($this->request->data)) {
395
-			//* View Entry by id
396
-			$this->User->id = $id;
397
-			$this->User->contain('UserOnline');
398
-			$this->request->data = $this->User->read();
399
-		}
400
-
401
-		$themes = $this->Themes->getAvailable();
402
-		$this->set('availableThemes', array_combine($themes, $themes));
403
-		$this->set('user', $this->request->data);
404
-		$this->set(
405
-				'title_for_layout',
406
-				__('Edit %s Profil',
407
-						Saito\String\Properize::prop($this->request->data['User']['username']))
408
-		);
409
-	}
410
-
411
-		public function admin_block() {
412
-			$this->set('UserBlock', $this->User->UserBlock->getAll());
413
-		}
414
-
415
-		/**
416
-		 * @throws BadRequestException
417
-		 */
418
-		public function lock() {
419
-			if (!($this->CurrentUser->isAdmin() || $this->viewVars['modLocking'])) {
420
-				$this->redirect('/');
421
-				return;
422
-			}
423
-
424
-			$id = (int)$this->request->data('User.lockUserId');
425
-			if (!$id) {
426
-				throw new BadRequestException;
427
-			}
428
-
429
-			$this->User->contain();
430
-			$readUser = $this->User->findById($id);
431
-			if (!$readUser) {
432
-				$this->Session->setFlash(__('User not found.'), 'flash/error');
433
-				$this->redirect('/');
434
-				return;
435
-			}
436
-
437
-			$editedUser = new SaitoUser($readUser['User']);
438
-
439
-			if ($id == $this->CurrentUser->getId()) {
440
-				$this->Session->setFlash(__("You can't lock yourself."), 'flash/error');
441
-			} elseif ($editedUser->isAdmin()) {
442
-				$this->Session->setFlash(
443
-					__("You can't lock administrators.", 'flash/error'),
444
-					'flash/error'
445
-				);
446
-			} else {
447
-				try {
448
-					$duration = (int)$this->request->data('User.lockPeriod');
449
-					$status = $this->User->UserBlock->block(
450
-						new \Saito\User\Blocker\ManualBlocker,
451
-						$id,
452
-						[
453
-							'adminId' => $this->CurrentUser->getId(),
454
-							'duration' => $duration
455
-						]
456
-					);
457
-					$username = $readUser['User']['username'];
458
-					if ($status === true) {
459
-						$message = __('User %s is locked.', $username);
460
-					} else {
461
-						$message = __('User %s is unlocked.', $username);
462
-					}
463
-					$this->Session->setFlash($message, 'flash/success');
464
-				} catch (Exception $e) {
465
-					$this->Session->setFlash(__('Error while un/locking.'), 'flash/error');
466
-				}
467
-			}
468
-			$this->redirect($this->referer());
469
-		}
470
-
471
-		public function unlock($id) {
472
-			if (!$id || !($this->CurrentUser->isAdmin() || $this->viewVars['modLocking'])) {
473
-				throw new BadRequestException;
474
-			}
475
-			if (!$this->User->UserBlock->unblock($id)) {
476
-				$this->Session->setFlash(__('Error while unlocking.'), 'flash/error');
477
-			}
478
-			$this->redirect($this->referer());
479
-		}
480
-
481
-		public function admin_delete($id = null) {
482
-			$this->User->contain();
483
-			$readUser = $this->User->findById($id);
484
-			if (!$readUser) {
485
-				$this->Session->setFlash(__('User not found.'), 'flash/error');
486
-				$this->redirect('/');
487
-				return;
488
-			}
489
-
490
-			if (isset($this->request->data['User']['modeDelete'])) {
491
-				if ($id == $this->CurrentUser->getId()) {
492
-					$this->Session->setFlash(__("You can't delete yourself."), 'flash/error');
493
-				} elseif ($id == 1) {
494
-					$this->Session->setFlash(__("You can't delete the installation account."), 'flash/error');
495
-				} elseif ($this->User->deleteAllExceptEntries($id)) {
496
-					$this->Session->setFlash(__('User %s deleted.', $readUser['User']['username']), 'flash/success');
497
-					$this->redirect('/');
498
-					return;
499
-				} else {
500
-					$this->Session->setFlash(__("Couldn't delete user."), 'flash/error');
501
-				}
502
-				$this->redirect(['controller' => 'users', 'action' => 'view', $id]);
503
-				return;
504
-			}
505
-			$this->set('user', $readUser);
506
-		}
507
-
508
-		/**
509
-		 * changes user password
510
-		 *
511
-		 * @param null $id
512
-		 * @throws \Saito\Exception\SaitoForbiddenException
513
-		 * @throws BadRequestException
514
-		 */
515
-		public function changepassword($id = null) {
516
-			if (!$id) {
517
-				throw new BadRequestException();
518
-			}
519
-
520
-			$user = $this->User->getProfile($id);
521
-			$allowed = $this->_isEditingAllowed($this->CurrentUser, $id);
522
-			if (empty($user) || !$allowed) {
523
-				throw new SaitoForbiddenException("Attempt to change password for user $id.",
524
-					['CurrentUser' => $this->CurrentUser]);
525
-			}
526
-			$this->set('userId', $id);
527
-			$this->set('username', $user['username']);
528
-
529
-			//# just show empty form
530
-			if (empty($this->request->data)) {
531
-				return;
532
-			}
533
-
534
-			//# process submitted form
535
-			$this->request->data = $this->_passwordAuthSwitch($this->request->data);
536
-			$data = [
537
-				'id' => $id,
538
-				'password_old' => $this->request->data['User']['password_old'],
539
-				'password' => $this->request->data['User']['password'],
540
-				'password_confirm' => $this->request->data['User']['password_confirm']
541
-			];
542
-			$success = $this->User->save($data);
543
-
544
-			if ($success) {
545
-				$this->Session->setFlash(__('change_password_success'),
546
-					'flash/success');
547
-				$this->redirect(['controller' => 'users', 'action' => 'edit', $id]);
548
-				return;
549
-			}
550
-
551
-			$this->Session->setFlash(
552
-				__d('nondynamic', current(array_pop($this->User->validationErrors))),
553
-				'flash/error'
554
-			);
555
-
556
-			// unset all autofill form data
557
-			$this->request->data = [];
558
-		}
559
-
560
-		/**
561
-		 * @throws BadRequestException
562
-		 */
563
-		private function __ajaxBeforeFilter() {
564
-			if (!$this->request->is('ajax')) {
565
-				throw new BadRequestException;
566
-			}
567
-			$this->autoRender = false;
568
-		}
569
-
570
-		/**
571
-		 * toggles slidetabs open/close
572
-		 *
573
-		 * @return $this|mixed
574
-		 * @throws BadRequestException
575
-		 */
576
-		public function slidetab_toggle() {
577
-			$this->__ajaxBeforeFilter();
578
-
579
-			$toggle = $this->request->data('slidetabKey');
580
-			$allowed = [
581
-				'show_userlist',
582
-				'show_recentposts',
583
-				'show_recententries',
584
-				'show_shoutbox'
585
-			];
586
-			if (!$toggle || !in_array($toggle, $allowed)) {
587
-				throw new BadRequestException(null, 1412949882);
588
-			}
589
-
590
-			$this->User->id = $this->CurrentUser->getId();
591
-			$newValue = $this->User->toggle($toggle);
592
-			$this->CurrentUser[$toggle] = $newValue;
593
-			return $toggle;
594
-		}
595
-
596
-		/**
597
-		 * sets slidetab-order
598
-		 *
599
-		 * @return bool
600
-		 * @throws BadRequestException
601
-		 */
602
-		public function slidetab_order() {
603
-			$this->__ajaxBeforeFilter();
604
-
605
-			$order = $this->request->data('slidetabOrder');
606
-			if (!$order) {
607
-				throw new BadRequestException;
608
-			}
609
-
610
-			$allowed = $this->viewVars['slidetabs'];
611
-			$order = array_filter( $order, function ($item) use ($allowed) {
612
-				return in_array($item, $allowed);
613
-			});
614
-			$order = serialize($order);
615
-
616
-			$this->User->id = $this->CurrentUser->getId();
617
-			$this->User->saveField('slidetab_order', $order);
618
-			$this->CurrentUser['slidetab_order'] = $order;
619
-
620
-			return true;
621
-		}
622
-
623
-		/**
624
-		 * @param null $id
625
-		 *
626
-		 * @throws ForbiddenException
627
-		 */
628
-		public function setcategory($id = null) {
629
-			if (!$this->CurrentUser->isLoggedIn()) {
630
-				throw new ForbiddenException();
631
-			}
632
-			$this->User->id = $this->CurrentUser->getId();
633
-			if ($id === 'all') {
634
-				$this->User->setCategory('all');
635
-			} elseif (!$id && $this->request->data) {
636
-				$this->User->setCategory($this->request->data['CatChooser']);
637
-			} else {
638
-				$this->User->setCategory($id);
639
-			}
640
-			$this->redirect($this->referer());
641
-		}
642
-
643
-		public function beforeFilter() {
644
-			Stopwatch::start('Users->beforeFilter()');
645
-			parent::beforeFilter();
646
-
647
-			// @todo CSRF protection
648
-			$this->Security->unlockedActions[] = 'slidetab_toggle';
649
-			$this->Security->unlockedActions[] = 'slidetab_order';
650
-
651
-			$this->Auth->allow('login', 'register', 'rs');
652
-			$this->set('modLocking',
653
-					$this->CurrentUser->isMod() && Configure::read('Saito.Settings.block_user_ui')
654
-			);
655
-
656
-			Stopwatch::stop('Users->beforeFilter()');
657
-		}
658
-
659
-		/**
660
-		 * Checks if the current user is allowed to edit user $userId
661
-		 *
662
-		 * @param SaitoUser $CurrentUser
663
-		 * @param int $userId
664
-		 * @return type
665
-		 */
666
-		protected function _isEditingAllowed(\Saito\User\ForumsUserInterface $CurrentUser, $userId) {
667
-			if ($CurrentUser->isAdmin()) {
668
-				return true;
669
-			}
670
-			return $CurrentUser->getId() === (int)$userId;
671
-		}
672
-
673
-		protected function _passwordAuthSwitch($data) {
674
-			$data['User']['password'] = $data['User']['user_password'];
675
-			unset($data['User']['user_password']);
676
-			return $data;
677
-		}
678
-
679
-	}
3
+    use Saito\Exception\Logger\ExceptionLogger;
4
+    use Saito\Exception\Logger\ForbiddenLogger;
5
+    use Saito\Exception\SaitoForbiddenException;
6
+    use Saito\User\SaitoUser;
7
+
8
+    App::uses('AppController', 'Controller');
9
+
10
+    class UsersController extends AppController {
11
+
12
+        public $name = 'Users';
13
+
14
+        public $helpers = [
15
+            'Farbtastic',
16
+            'SimpleCaptcha.SimpleCaptcha',
17
+            'EntryH',
18
+            'Map',
19
+            'Text'
20
+        ];
21
+
22
+        public function login() {
23
+            $this->CurrentUser->logOut();
24
+
25
+            //# just show form
26
+            if (empty($this->request->data['User']['username'])) {
27
+                return;
28
+            }
29
+
30
+            //# successful login with request data
31
+            if ($this->CurrentUser->login()) {
32
+                if ($this->localReferer('action') === 'login') {
33
+                    $this->redirect($this->Auth->redirectUrl());
34
+                } else {
35
+                    $this->redirect($this->referer());
36
+                }
37
+                return;
38
+            }
39
+
40
+            //# error on login
41
+            $this->User->contain();
42
+            $username = $this->request->data['User']['username'];
43
+            $readUser = $this->User->findByUsername($username);
44
+
45
+            $status = null;
46
+
47
+            if (!empty($readUser)) {
48
+                $User = new SaitoUser($readUser['User']);
49
+                $status = $User->isForbidden();
50
+            }
51
+
52
+            switch ($status) {
53
+                case 'locked':
54
+                    $ends = $this->User->UserBlock
55
+                        ->getBlockEndsForUser($readUser['User']['id']);
56
+                    if ($ends) {
57
+                        $message = __('user.block.pubExpEnds', [$username,
58
+                            CakeTime::timeAgoInWords($ends, ['accuracy' => 'hour'])]);
59
+                    } else {
60
+                        $message = __('user.block.pubExp', $username);
61
+                    }
62
+                    break;
63
+                case 'unactivated':
64
+                    $message = __('User %s is not activated yet.', $readUser['User']['username']);
65
+                    break;
66
+                default:
67
+                    $message = __('auth_loginerror');
68
+            }
69
+
70
+            // don't autofill password
71
+            unset($this->request->data['User']['password']);
72
+
73
+            $Logger = new ForbiddenLogger;
74
+            $Logger->write("Unsuccessful login for user: $username",
75
+                ['msgs' => [$message]]);
76
+
77
+            $this->Session->setFlash($message, 'default', [], 'auth');
78
+        }
79
+
80
+        public function logout() {
81
+            $this->CurrentUser->logout();
82
+        }
83
+
84
+        public function register() {
85
+            $this->set('status', 'view');
86
+
87
+            $this->CurrentUser->logout();
88
+
89
+            $tosRequired = Configure::read('Saito.Settings.tos_enabled');
90
+            $this->set(compact('tosRequired'));
91
+
92
+            // display empty form
93
+            if (empty($this->request->data)) {
94
+                return;
95
+            }
96
+
97
+            $data = $this->request->data;
98
+
99
+            if (!$tosRequired) {
100
+                $data['User']['tos_confirm'] = true;
101
+            }
102
+
103
+            $tosConfirmed = $data['User']['tos_confirm'];
104
+            if (!$tosConfirmed) {
105
+                return;
106
+            }
107
+
108
+            $data = $this->_passwordAuthSwitch($data);
109
+            $this->User->Behaviors->attach('SimpleCaptcha.SimpleCaptcha');
110
+            $user = $this->User->register($data);
111
+
112
+            // registering failed, show form again
113
+            if (!$user) {
114
+                // undo the passwordAuthSwitch() to display error message for the field
115
+                if (isset($this->User->validationErrors['password'])) {
116
+                    $this->User->validationErrors['user_password'] = $this->User->validationErrors['password'];
117
+                }
118
+                $data['User']['tos_confirm'] = false;
119
+                $this->request->data = $data;
120
+                return;
121
+            }
122
+
123
+            // registered successfully
124
+            try {
125
+                $forumName = Configure::read('Saito.Settings.forum_name');
126
+                $subject = __('register_email_subject', $forumName);
127
+                $email = $this->SaitoEmail->email([
128
+                    'recipient' => $data,
129
+                    'subject' => $subject,
130
+                    'sender' => 'register',
131
+                    'template' => 'user_register',
132
+                    'viewVars' => ['user' => $user]
133
+                ]);
134
+                // only used in test cases
135
+                $this->set('email', $email);
136
+            } catch (Exception $e) {
137
+                $Logger = new ExceptionLogger();
138
+                $Logger->write('Registering email confirmation failed', ['e' => $e]);
139
+                $this->set('status', 'fail: email');
140
+                return;
141
+            }
142
+
143
+            $this->set('status', 'success');
144
+        }
145
+
146
+        /**
147
+         * register success (user clicked link in confirm mail)
148
+         *
149
+         * @param $id
150
+         * @throws BadRequestException
151
+         */
152
+        public function rs($id = null) {
153
+            if (!$id) {
154
+                throw new BadRequestException();
155
+            }
156
+
157
+            $code = $this->request->query('c');
158
+
159
+            try {
160
+                $activated = $this->User->activate((int)$id, $code);
161
+            } catch (Exception $e) {
162
+                $activated = false;
163
+            }
164
+
165
+            if (!$activated) {
166
+                $activated = ['status' => 'fail'];
167
+            }
168
+            $this->set('status', $activated['status']);
169
+        }
170
+
171
+        public function admin_index() {
172
+            $data = $this->User->find(
173
+                    'all',
174
+                    [
175
+                            'contain' => false,
176
+                            'fields' => [
177
+                                    'id',
178
+                                    'username',
179
+                                    'user_type',
180
+                                    'user_email',
181
+                                    'registered',
182
+                                    'user_lock'
183
+                            ],
184
+                            'order' => ['User.username' => 'asc']
185
+                    ]
186
+            );
187
+            $this->set('users', $data);
188
+        }
189
+
190
+        public function index() {
191
+            $menuItems = [
192
+                'username' => [__('username_marking'), []],
193
+                'user_type' => [__('user_type'), []],
194
+                'UserOnline.logged_in' => [__('userlist_online'), ['direction' => 'desc']],
195
+                'registered' => [__('registered'), ['direction' => 'desc']]
196
+            ];
197
+            $showBlocked = Configure::read('Saito.Settings.block_user_ui');
198
+            if ($showBlocked) {
199
+                $menuItems['user_lock'] = [__('user.set.lock.t'), ['direction' => 'desc']];
200
+            }
201
+
202
+            $this->paginate = [
203
+                'contain' => 'UserOnline',
204
+                'limit' => 400,
205
+                'order' => ['UserOnline.logged_in' => 'desc', 'User.username' => 'asc']
206
+            ];
207
+            $users = $this->paginate('User', null, array_keys($menuItems));
208
+
209
+            $this->set(compact('menuItems', 'users'));
210
+        }
211
+
212
+        public function ignore() {
213
+            $this->request->allowMethod('POST');
214
+            $blockedId = $this->request->data('id');
215
+            $this->_ignore($blockedId, true);
216
+        }
217
+
218
+        public function unignore() {
219
+            $this->request->allowMethod('POST');
220
+            $blockedId = $this->request->data('id');
221
+            $this->_ignore($blockedId, false);
222
+        }
223
+
224
+        protected function _ignore($blockedId, $set) {
225
+            if (!$this->CurrentUser->isLoggedIn() || !is_numeric($blockedId)) {
226
+                throw new BadRequestException();
227
+            }
228
+            $userId = $this->CurrentUser->getId();
229
+            $this->User->id = $userId;
230
+            if (!$this->User->exists($userId) || $userId == $blockedId) {
231
+                throw new BadRequestException();
232
+            }
233
+            if ($set) {
234
+                $this->User->Ignore->ignore($userId, $blockedId);
235
+            } else {
236
+                $this->User->Ignore->unignore($userId, $blockedId);
237
+            }
238
+            $this->redirect($this->referer());
239
+        }
240
+
241
+        public function admin_add() {
242
+            if (!empty($this->request->data)) :
243
+                $this->request->data = $this->_passwordAuthSwitch($this->request->data);
244
+                if ($this->User->register($this->request->data, true)) {
245
+                    $this->Session->setFlash(__('user.admin.add.success'),
246
+                            'flash/success');
247
+                    $this->redirect(['action' => 'view', $this->User->id, 'admin' => false]);
248
+                }
249
+            endif;
250
+        }
251
+
252
+        public function map() {
253
+            if (!Configure::read('Saito.Settings.map_enabled')) {
254
+                $this->Session->setFlash(__('admin.setting.disabled', __('admin.feat.map')), 'flash/error');
255
+                $this->redirect('/');
256
+                return;
257
+            }
258
+            $users = $this->User->find('all',
259
+                    [
260
+                            'contain' => false,
261
+                            'conditions' => ['user_place_lat !=' => null],
262
+                            'fields' => [
263
+                                    'User.id',
264
+                                    'User.username',
265
+                                    'User.user_place_lat',
266
+                                    'User.user_place_lng'
267
+                            ]
268
+                    ]
269
+            );
270
+            $this->set(compact('users'));
271
+        }
272
+
273
+        public function name($id = null) {
274
+            if (!empty($id)) {
275
+                $this->User->contain();
276
+                $viewedUser = $this->User->findByUsername($id);
277
+                if (!empty($viewedUser)) {
278
+                    $this->redirect(
279
+                        [
280
+                            'controller' => 'users',
281
+                            'action' => 'view',
282
+                            $viewedUser['User']['id']
283
+                        ]
284
+                    );
285
+                    return;
286
+                }
287
+            }
288
+            $this->Session->setFlash(__('Invalid user'), 'flash/error');
289
+            $this->redirect('/');
290
+        }
291
+
292
+        public function view($id = null) {
293
+            // redirect view/<username> to name/<username>
294
+            if (!empty($id) && !is_numeric($id)) {
295
+                $this->redirect(
296
+                    [
297
+                        'controller' => 'users',
298
+                        'action' => 'name',
299
+                        $id
300
+                    ]
301
+                );
302
+                return; // test case return
303
+            }
304
+
305
+            $this->User->id = $id;
306
+            $this->User->contain(['UserBlock' => ['By'], 'UserOnline']);
307
+            $viewedUser = $this->User->read();
308
+
309
+            if ($id === null || empty($viewedUser)) {
310
+                $this->Session->setFlash(__('Invalid user'), 'flash/error');
311
+                $this->redirect('/');
312
+                return;
313
+            }
314
+
315
+            $viewedUser['User']['number_of_entries'] = $this->User->numberOfEntries();
316
+
317
+            $entriesShownOnPage = 20;
318
+            $this->set(
319
+                'lastEntries',
320
+                $this->User->Entry->getRecentEntries(
321
+                    $this->CurrentUser,
322
+                    [
323
+                        'user_id' => $this->User->id,
324
+                        'limit' => $entriesShownOnPage
325
+                    ]
326
+                )
327
+            );
328
+
329
+            $this->set(
330
+                'hasMoreEntriesThanShownOnPage',
331
+                    ($viewedUser['User']['number_of_entries'] - $entriesShownOnPage) > 0
332
+            );
333
+
334
+            if ($this->CurrentUser->getId() == $id) {
335
+                $viewedUser['User']['ignores'] = $this->User->Ignore->ignoredBy($id);
336
+            }
337
+            $viewedUser['User']['solves_count'] = $this->User->countSolved($id);
338
+            $this->set('user', $viewedUser);
339
+            $this->set(
340
+                    'title_for_layout',
341
+                    $viewedUser['User']['username']
342
+            );
343
+        }
344
+
345
+        /**
346
+         * @param null $id
347
+         * @throws Saito\Exception\SaitoForbiddenException
348
+         * @throws BadRequestException
349
+         */
350
+    public function edit($id = null) {
351
+        if (!$id) {
352
+            throw new BadRequestException;
353
+        }
354
+        if (!$this->_isEditingAllowed($this->CurrentUser, $id)) {
355
+            throw new \Saito\Exception\SaitoForbiddenException("Attempt to edit user $id.", [
356
+                'CurrentUser' => $this->CurrentUser
357
+            ]);
358
+        }
359
+
360
+        $this->set('userId', $id);
361
+
362
+        // try to save entry
363
+        if (!empty($this->request->data)) {
364
+            $data = $this->request->data['User'];
365
+
366
+            unset($data['id']);
367
+            //# make sure only admin can edit these fields
368
+            if ($this->CurrentUser['user_type'] !== 'admin') {
369
+                // @todo DRY: refactor this admin fields together with view
370
+                unset($data['username'], $data['user_email'], $data['user_type']);
371
+            }
372
+
373
+            $this->User->id = $id;
374
+            $success = $this->User->save($data);
375
+            if ($success) {
376
+                $this->redirect(['action' => 'view', $id]);
377
+                return;
378
+            } else {
379
+                // if empty fields are missing from send form read user again
380
+                $this->User->contain();
381
+                $user = $this->User->read();
382
+                $this->request->data['User'] = array_merge($user['User'],
383
+                    $this->request->data['User']);
384
+
385
+                $this->User->set($this->request->data);
386
+                $this->User->validates();
387
+
388
+                $this->JsData->addAppJsMessage(
389
+                    __('The user could not be saved. Please, try again.'),
390
+                    ['type' => 'error']);
391
+            }
392
+        }
393
+
394
+        if (empty($this->request->data)) {
395
+            //* View Entry by id
396
+            $this->User->id = $id;
397
+            $this->User->contain('UserOnline');
398
+            $this->request->data = $this->User->read();
399
+        }
400
+
401
+        $themes = $this->Themes->getAvailable();
402
+        $this->set('availableThemes', array_combine($themes, $themes));
403
+        $this->set('user', $this->request->data);
404
+        $this->set(
405
+                'title_for_layout',
406
+                __('Edit %s Profil',
407
+                        Saito\String\Properize::prop($this->request->data['User']['username']))
408
+        );
409
+    }
410
+
411
+        public function admin_block() {
412
+            $this->set('UserBlock', $this->User->UserBlock->getAll());
413
+        }
414
+
415
+        /**
416
+         * @throws BadRequestException
417
+         */
418
+        public function lock() {
419
+            if (!($this->CurrentUser->isAdmin() || $this->viewVars['modLocking'])) {
420
+                $this->redirect('/');
421
+                return;
422
+            }
423
+
424
+            $id = (int)$this->request->data('User.lockUserId');
425
+            if (!$id) {
426
+                throw new BadRequestException;
427
+            }
428
+
429
+            $this->User->contain();
430
+            $readUser = $this->User->findById($id);
431
+            if (!$readUser) {
432
+                $this->Session->setFlash(__('User not found.'), 'flash/error');
433
+                $this->redirect('/');
434
+                return;
435
+            }
436
+
437
+            $editedUser = new SaitoUser($readUser['User']);
438
+
439
+            if ($id == $this->CurrentUser->getId()) {
440
+                $this->Session->setFlash(__("You can't lock yourself."), 'flash/error');
441
+            } elseif ($editedUser->isAdmin()) {
442
+                $this->Session->setFlash(
443
+                    __("You can't lock administrators.", 'flash/error'),
444
+                    'flash/error'
445
+                );
446
+            } else {
447
+                try {
448
+                    $duration = (int)$this->request->data('User.lockPeriod');
449
+                    $status = $this->User->UserBlock->block(
450
+                        new \Saito\User\Blocker\ManualBlocker,
451
+                        $id,
452
+                        [
453
+                            'adminId' => $this->CurrentUser->getId(),
454
+                            'duration' => $duration
455
+                        ]
456
+                    );
457
+                    $username = $readUser['User']['username'];
458
+                    if ($status === true) {
459
+                        $message = __('User %s is locked.', $username);
460
+                    } else {
461
+                        $message = __('User %s is unlocked.', $username);
462
+                    }
463
+                    $this->Session->setFlash($message, 'flash/success');
464
+                } catch (Exception $e) {
465
+                    $this->Session->setFlash(__('Error while un/locking.'), 'flash/error');
466
+                }
467
+            }
468
+            $this->redirect($this->referer());
469
+        }
470
+
471
+        public function unlock($id) {
472
+            if (!$id || !($this->CurrentUser->isAdmin() || $this->viewVars['modLocking'])) {
473
+                throw new BadRequestException;
474
+            }
475
+            if (!$this->User->UserBlock->unblock($id)) {
476
+                $this->Session->setFlash(__('Error while unlocking.'), 'flash/error');
477
+            }
478
+            $this->redirect($this->referer());
479
+        }
480
+
481
+        public function admin_delete($id = null) {
482
+            $this->User->contain();
483
+            $readUser = $this->User->findById($id);
484
+            if (!$readUser) {
485
+                $this->Session->setFlash(__('User not found.'), 'flash/error');
486
+                $this->redirect('/');
487
+                return;
488
+            }
489
+
490
+            if (isset($this->request->data['User']['modeDelete'])) {
491
+                if ($id == $this->CurrentUser->getId()) {
492
+                    $this->Session->setFlash(__("You can't delete yourself."), 'flash/error');
493
+                } elseif ($id == 1) {
494
+                    $this->Session->setFlash(__("You can't delete the installation account."), 'flash/error');
495
+                } elseif ($this->User->deleteAllExceptEntries($id)) {
496
+                    $this->Session->setFlash(__('User %s deleted.', $readUser['User']['username']), 'flash/success');
497
+                    $this->redirect('/');
498
+                    return;
499
+                } else {
500
+                    $this->Session->setFlash(__("Couldn't delete user."), 'flash/error');
501
+                }
502
+                $this->redirect(['controller' => 'users', 'action' => 'view', $id]);
503
+                return;
504
+            }
505
+            $this->set('user', $readUser);
506
+        }
507
+
508
+        /**
509
+         * changes user password
510
+         *
511
+         * @param null $id
512
+         * @throws \Saito\Exception\SaitoForbiddenException
513
+         * @throws BadRequestException
514
+         */
515
+        public function changepassword($id = null) {
516
+            if (!$id) {
517
+                throw new BadRequestException();
518
+            }
519
+
520
+            $user = $this->User->getProfile($id);
521
+            $allowed = $this->_isEditingAllowed($this->CurrentUser, $id);
522
+            if (empty($user) || !$allowed) {
523
+                throw new SaitoForbiddenException("Attempt to change password for user $id.",
524
+                    ['CurrentUser' => $this->CurrentUser]);
525
+            }
526
+            $this->set('userId', $id);
527
+            $this->set('username', $user['username']);
528
+
529
+            //# just show empty form
530
+            if (empty($this->request->data)) {
531
+                return;
532
+            }
533
+
534
+            //# process submitted form
535
+            $this->request->data = $this->_passwordAuthSwitch($this->request->data);
536
+            $data = [
537
+                'id' => $id,
538
+                'password_old' => $this->request->data['User']['password_old'],
539
+                'password' => $this->request->data['User']['password'],
540
+                'password_confirm' => $this->request->data['User']['password_confirm']
541
+            ];
542
+            $success = $this->User->save($data);
543
+
544
+            if ($success) {
545
+                $this->Session->setFlash(__('change_password_success'),
546
+                    'flash/success');
547
+                $this->redirect(['controller' => 'users', 'action' => 'edit', $id]);
548
+                return;
549
+            }
550
+
551
+            $this->Session->setFlash(
552
+                __d('nondynamic', current(array_pop($this->User->validationErrors))),
553
+                'flash/error'
554
+            );
555
+
556
+            // unset all autofill form data
557
+            $this->request->data = [];
558
+        }
559
+
560
+        /**
561
+         * @throws BadRequestException
562
+         */
563
+        private function __ajaxBeforeFilter() {
564
+            if (!$this->request->is('ajax')) {
565
+                throw new BadRequestException;
566
+            }
567
+            $this->autoRender = false;
568
+        }
569
+
570
+        /**
571
+         * toggles slidetabs open/close
572
+         *
573
+         * @return $this|mixed
574
+         * @throws BadRequestException
575
+         */
576
+        public function slidetab_toggle() {
577
+            $this->__ajaxBeforeFilter();
578
+
579
+            $toggle = $this->request->data('slidetabKey');
580
+            $allowed = [
581
+                'show_userlist',
582
+                'show_recentposts',
583
+                'show_recententries',
584
+                'show_shoutbox'
585
+            ];
586
+            if (!$toggle || !in_array($toggle, $allowed)) {
587
+                throw new BadRequestException(null, 1412949882);
588
+            }
589
+
590
+            $this->User->id = $this->CurrentUser->getId();
591
+            $newValue = $this->User->toggle($toggle);
592
+            $this->CurrentUser[$toggle] = $newValue;
593
+            return $toggle;
594
+        }
595
+
596
+        /**
597
+         * sets slidetab-order
598
+         *
599
+         * @return bool
600
+         * @throws BadRequestException
601
+         */
602
+        public function slidetab_order() {
603
+            $this->__ajaxBeforeFilter();
604
+
605
+            $order = $this->request->data('slidetabOrder');
606
+            if (!$order) {
607
+                throw new BadRequestException;
608
+            }
609
+
610
+            $allowed = $this->viewVars['slidetabs'];
611
+            $order = array_filter( $order, function ($item) use ($allowed) {
612
+                return in_array($item, $allowed);
613
+            });
614
+            $order = serialize($order);
615
+
616
+            $this->User->id = $this->CurrentUser->getId();
617
+            $this->User->saveField('slidetab_order', $order);
618
+            $this->CurrentUser['slidetab_order'] = $order;
619
+
620
+            return true;
621
+        }
622
+
623
+        /**
624
+         * @param null $id
625
+         *
626
+         * @throws ForbiddenException
627
+         */
628
+        public function setcategory($id = null) {
629
+            if (!$this->CurrentUser->isLoggedIn()) {
630
+                throw new ForbiddenException();
631
+            }
632
+            $this->User->id = $this->CurrentUser->getId();
633
+            if ($id === 'all') {
634
+                $this->User->setCategory('all');
635
+            } elseif (!$id && $this->request->data) {
636
+                $this->User->setCategory($this->request->data['CatChooser']);
637
+            } else {
638
+                $this->User->setCategory($id);
639
+            }
640
+            $this->redirect($this->referer());
641
+        }
642
+
643
+        public function beforeFilter() {
644
+            Stopwatch::start('Users->beforeFilter()');
645
+            parent::beforeFilter();
646
+
647
+            // @todo CSRF protection
648
+            $this->Security->unlockedActions[] = 'slidetab_toggle';
649
+            $this->Security->unlockedActions[] = 'slidetab_order';
650
+
651
+            $this->Auth->allow('login', 'register', 'rs');
652
+            $this->set('modLocking',
653
+                    $this->CurrentUser->isMod() && Configure::read('Saito.Settings.block_user_ui')
654
+            );
655
+
656
+            Stopwatch::stop('Users->beforeFilter()');
657
+        }
658
+
659
+        /**
660
+         * Checks if the current user is allowed to edit user $userId
661
+         *
662
+         * @param SaitoUser $CurrentUser
663
+         * @param int $userId
664
+         * @return type
665
+         */
666
+        protected function _isEditingAllowed(\Saito\User\ForumsUserInterface $CurrentUser, $userId) {
667
+            if ($CurrentUser->isAdmin()) {
668
+                return true;
669
+            }
670
+            return $CurrentUser->getId() === (int)$userId;
671
+        }
672
+
673
+        protected function _passwordAuthSwitch($data) {
674
+            $data['User']['password'] = $data['User']['user_password'];
675
+            unset($data['User']['user_password']);
676
+            return $data;
677
+        }
678
+
679
+    }
Please login to merge, or discard this patch.
app/Controller/EsnotificationsController.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -25,7 +25,7 @@
 block discarded – undo
25 25
 
26 26
 			$deactivate = $this->Esnotification->read('deactivate');
27 27
 			if (!isset($this->request->params['named']['token'])
28
-					|| (int)$this->request->params['named']['token'] !== (int)$deactivate['Esnotification']['deactivate']
28
+					|| (int) $this->request->params['named']['token'] !== (int) $deactivate['Esnotification']['deactivate']
29 29
 			) {
30 30
 				throw new MethodNotAllowedException();
31 31
 			}
Please login to merge, or discard this patch.
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -1,13 +1,13 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-	App::uses('AppController', 'Controller');
3
+    App::uses('AppController', 'Controller');
4 4
 
5 5
 /**
6 6
  * Esnotifications Controller
7 7
  *
8 8
  * @property Esnotification $Esnotification
9 9
  */
10
-	class EsnotificationsController extends AppController {
10
+    class EsnotificationsController extends AppController {
11 11
 
12 12
 /**
13 13
  * delete method
@@ -17,30 +17,30 @@  discard block
 block discarded – undo
17 17
  * @param string $id
18 18
  * @return void
19 19
  */
20
-		public function unsubscribe($id = null) {
21
-			$this->Esnotification->id = $id;
22
-			if (!$this->Esnotification->exists()) {
23
-				throw new NotFoundException(__('Invalid esnotification'));
24
-			}
20
+        public function unsubscribe($id = null) {
21
+            $this->Esnotification->id = $id;
22
+            if (!$this->Esnotification->exists()) {
23
+                throw new NotFoundException(__('Invalid esnotification'));
24
+            }
25 25
 
26
-			$deactivate = $this->Esnotification->read('deactivate');
27
-			if (!isset($this->request->params['named']['token'])
28
-					|| (int)$this->request->params['named']['token'] !== (int)$deactivate['Esnotification']['deactivate']
29
-			) {
30
-				throw new MethodNotAllowedException();
31
-			}
32
-			if ($this->Esnotification->deleteNotificationWithId($id)) {
33
-				$this->Session->setFlash(__('Succesfully unsubscribed.'), 'flash/success');
34
-				$this->redirect('/');
35
-			}
36
-			$this->Session->setFlash(__('Error. Could not unsubscribe.'));
37
-			$this->redirect('/');
38
-		}
26
+            $deactivate = $this->Esnotification->read('deactivate');
27
+            if (!isset($this->request->params['named']['token'])
28
+                    || (int)$this->request->params['named']['token'] !== (int)$deactivate['Esnotification']['deactivate']
29
+            ) {
30
+                throw new MethodNotAllowedException();
31
+            }
32
+            if ($this->Esnotification->deleteNotificationWithId($id)) {
33
+                $this->Session->setFlash(__('Succesfully unsubscribed.'), 'flash/success');
34
+                $this->redirect('/');
35
+            }
36
+            $this->Session->setFlash(__('Error. Could not unsubscribe.'));
37
+            $this->redirect('/');
38
+        }
39 39
 
40
-		public function beforeFilter() {
41
-			parent::beforeFilter();
42
-			$this->Auth->allow('unsubscribe');
43
-		}
40
+        public function beforeFilter() {
41
+            parent::beforeFilter();
42
+            $this->Auth->allow('unsubscribe');
43
+        }
44 44
 
45
-	}
45
+    }
46 46
 
Please login to merge, or discard this patch.
app/Controller/BookmarksController.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
 			'entry_id' => $this->request->data['id'],
49 49
 		];
50 50
 		$this->Bookmark->create();
51
-		return (bool)$this->Bookmark->save($data);
51
+		return (bool) $this->Bookmark->save($data);
52 52
 	}
53 53
 
54 54
 	/**
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 		$this->_getBookmark($id, $this->CurrentUser->getId());
99 99
 		$this->autoRender = false;
100 100
 		$this->Bookmark->id = $id;
101
-		return (bool)$this->Bookmark->delete();
101
+		return (bool) $this->Bookmark->delete();
102 102
 	}
103 103
 
104 104
 	public function beforeFilter() {
Please login to merge, or discard this patch.
Indentation   +107 added lines, -107 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('AppController', 'Controller');
3
+    App::uses('AppController', 'Controller');
4 4
 
5 5
 /**
6 6
  * Bookmarks Controller
@@ -9,127 +9,127 @@  discard block
 block discarded – undo
9 9
  */
10 10
 class BookmarksController extends AppController {
11 11
 
12
-	public $helpers = ['EntryH'];
12
+    public $helpers = ['EntryH'];
13 13
 
14 14
 /**
15 15
  * @throws MethodNotAllowedException
16 16
  */
17
-	public function index() {
18
-		if (!$this->CurrentUser->isLoggedIn()) {
19
-			throw new MethodNotAllowedException;
20
-		}
21
-		$bookmarks = $this->Bookmark->find('all', [
22
-			'contain' => ['Entry' => ['Category', 'User']],
23
-			'conditions' => ['Bookmark.user_id' => $this->CurrentUser->getId()],
24
-			'order' => 'Bookmark.id DESC',
25
-		]);
26
-		$this->set('bookmarks', $bookmarks);
27
-	}
17
+    public function index() {
18
+        if (!$this->CurrentUser->isLoggedIn()) {
19
+            throw new MethodNotAllowedException;
20
+        }
21
+        $bookmarks = $this->Bookmark->find('all', [
22
+            'contain' => ['Entry' => ['Category', 'User']],
23
+            'conditions' => ['Bookmark.user_id' => $this->CurrentUser->getId()],
24
+            'order' => 'Bookmark.id DESC',
25
+        ]);
26
+        $this->set('bookmarks', $bookmarks);
27
+    }
28 28
 
29 29
 /**
30 30
  * @return bool
31 31
  * @throws MethodNotAllowedException
32 32
  * @throws BadRequestException
33 33
  */
34
-	public function add() {
35
-		if (!$this->request->is('ajax')) {
36
-			throw new BadRequestException;
37
-		}
38
-		if (!$this->CurrentUser->isLoggedIn()) {
39
-			throw new MethodNotAllowedException;
40
-		}
41
-		$this->autoRender = false;
42
-		if (!$this->request->is('post')) {
43
-			return false;
44
-		}
45
-
46
-		$data = [
47
-			'user_id' => $this->CurrentUser->getId(),
48
-			'entry_id' => $this->request->data['id'],
49
-		];
50
-		$this->Bookmark->create();
51
-		return (bool)$this->Bookmark->save($data);
52
-	}
53
-
54
-	/**
55
-	 * @param null $id
56
-	 * @throws NotFoundException
57
-	 * @throws MethodNotAllowedException
58
-	 */
59
-	public function edit($id = null) {
60
-		$bookmark = $this->_getBookmark($id);
61
-
62
-		if (!$this->request->is('post') && !$this->request->is('put')) {
63
-			$posting = array(
64
-				'Entry' => $bookmark['Entry'],
65
-				'Category' => $bookmark['Entry']['Category'],
66
-				'User' => $bookmark['Entry']['User'],
67
-			);
68
-			$this->set('entry', $this->dic->newInstance('\Saito\Posting\Posting',
69
-				['rawData' => $posting]));
70
-			$this->request->data = $bookmark;
71
-			return;
72
-		}
73
-
74
-		$data['Bookmark'] = [
75
-			'id' => $id,
76
-			'comment' => $this->request->data['Bookmark']['comment']
77
-		];
78
-		$success = $this->Bookmark->save($data);
79
-		if (!$success) {
80
-			$this->Session->setFlash(
81
-				__('The bookmark could not be saved. Please, try again.'));
82
-			return;
83
-		}
84
-		$this->redirect(['action' => 'index',
85
-			'#' => $bookmark['Bookmark']['entry_id']]);
86
-	}
34
+    public function add() {
35
+        if (!$this->request->is('ajax')) {
36
+            throw new BadRequestException;
37
+        }
38
+        if (!$this->CurrentUser->isLoggedIn()) {
39
+            throw new MethodNotAllowedException;
40
+        }
41
+        $this->autoRender = false;
42
+        if (!$this->request->is('post')) {
43
+            return false;
44
+        }
45
+
46
+        $data = [
47
+            'user_id' => $this->CurrentUser->getId(),
48
+            'entry_id' => $this->request->data['id'],
49
+        ];
50
+        $this->Bookmark->create();
51
+        return (bool)$this->Bookmark->save($data);
52
+    }
53
+
54
+    /**
55
+     * @param null $id
56
+     * @throws NotFoundException
57
+     * @throws MethodNotAllowedException
58
+     */
59
+    public function edit($id = null) {
60
+        $bookmark = $this->_getBookmark($id);
61
+
62
+        if (!$this->request->is('post') && !$this->request->is('put')) {
63
+            $posting = array(
64
+                'Entry' => $bookmark['Entry'],
65
+                'Category' => $bookmark['Entry']['Category'],
66
+                'User' => $bookmark['Entry']['User'],
67
+            );
68
+            $this->set('entry', $this->dic->newInstance('\Saito\Posting\Posting',
69
+                ['rawData' => $posting]));
70
+            $this->request->data = $bookmark;
71
+            return;
72
+        }
73
+
74
+        $data['Bookmark'] = [
75
+            'id' => $id,
76
+            'comment' => $this->request->data['Bookmark']['comment']
77
+        ];
78
+        $success = $this->Bookmark->save($data);
79
+        if (!$success) {
80
+            $this->Session->setFlash(
81
+                __('The bookmark could not be saved. Please, try again.'));
82
+            return;
83
+        }
84
+        $this->redirect(['action' => 'index',
85
+            '#' => $bookmark['Bookmark']['entry_id']]);
86
+    }
87 87
 
88 88
 /**
89 89
  * @param null $id
90 90
  * @return bool
91 91
  * @throws BadRequestException
92 92
  */
93
-	public function delete($id = null) {
94
-		if (!$this->request->is('ajax')) {
95
-			throw new BadRequestException;
96
-		}
97
-
98
-		$this->_getBookmark($id, $this->CurrentUser->getId());
99
-		$this->autoRender = false;
100
-		$this->Bookmark->id = $id;
101
-		return (bool)$this->Bookmark->delete();
102
-	}
103
-
104
-	public function beforeFilter() {
105
-		parent::beforeFilter();
106
-
107
-		$this->Security->unlockedActions = ['add'];
108
-	}
109
-
110
-	/**
111
-	 * @param $id
112
-	 * @throws NotFoundException
113
-	 * @throws MethodNotAllowedException
114
-	 * @throws Saito\Exception\SaitoForbiddenException
115
-	 * @return mixed
116
-	 */
117
-	protected function _getBookmark($id) {
118
-		if (!$this->CurrentUser->isLoggedIn()) {
119
-			throw new MethodNotAllowedException;
120
-		}
121
-
122
-		if (!$this->Bookmark->exists($id)) {
123
-			throw new NotFoundException(__('Invalid bookmark.'));
124
-		}
125
-
126
-		$this->Bookmark->contain(['Entry' => ['Category', 'User']]);
127
-		$bookmark = $this->Bookmark->findById($id);
128
-
129
-		if ($bookmark['Bookmark']['user_id'] != $this->CurrentUser->getId()) {
130
-			throw new Saito\Exception\SaitoForbiddenException("Attempt to edit bookmark $id.");
131
-		}
132
-		return $bookmark;
133
-	}
93
+    public function delete($id = null) {
94
+        if (!$this->request->is('ajax')) {
95
+            throw new BadRequestException;
96
+        }
97
+
98
+        $this->_getBookmark($id, $this->CurrentUser->getId());
99
+        $this->autoRender = false;
100
+        $this->Bookmark->id = $id;
101
+        return (bool)$this->Bookmark->delete();
102
+    }
103
+
104
+    public function beforeFilter() {
105
+        parent::beforeFilter();
106
+
107
+        $this->Security->unlockedActions = ['add'];
108
+    }
109
+
110
+    /**
111
+     * @param $id
112
+     * @throws NotFoundException
113
+     * @throws MethodNotAllowedException
114
+     * @throws Saito\Exception\SaitoForbiddenException
115
+     * @return mixed
116
+     */
117
+    protected function _getBookmark($id) {
118
+        if (!$this->CurrentUser->isLoggedIn()) {
119
+            throw new MethodNotAllowedException;
120
+        }
121
+
122
+        if (!$this->Bookmark->exists($id)) {
123
+            throw new NotFoundException(__('Invalid bookmark.'));
124
+        }
125
+
126
+        $this->Bookmark->contain(['Entry' => ['Category', 'User']]);
127
+        $bookmark = $this->Bookmark->findById($id);
128
+
129
+        if ($bookmark['Bookmark']['user_id'] != $this->CurrentUser->getId()) {
130
+            throw new Saito\Exception\SaitoForbiddenException("Attempt to edit bookmark $id.");
131
+        }
132
+        return $bookmark;
133
+    }
134 134
 
135 135
 }
136 136
\ No newline at end of file
Please login to merge, or discard this patch.
app/Controller/CategoriesController.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -72,7 +72,7 @@
 block discarded – undo
72 72
 				if (isset($this->request->data['Category']['modeMove']) && isset($this->request->data['Category']['targetCategory'])):
73 73
 					/* move category items before deleting the cateogry */
74 74
 
75
-					$targetId = (int)$this->request->data['Category']['targetCategory'];
75
+					$targetId = (int) $this->request->data['Category']['targetCategory'];
76 76
 
77 77
 					/* make sure that target category exists */
78 78
 					$this->Category->contain();
Please login to merge, or discard this patch.
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -1,123 +1,123 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-	App::uses('AppController', 'Controller');
4
-
5
-	class CategoriesController extends AppController {
6
-
7
-		public $name = 'Categories';
8
-
9
-		public $paginate = [
10
-			/**
11
-			 * sets limit unrealisticly high so we should never reach the upper limit
12
-			 * i.e. always show all entries on one page
13
-			 */
14
-				'limit' => 1000,
15
-		];
16
-
17
-		public function admin_index() {
18
-			$this->Category->recursive = 0;
19
-			$this->set('categories', $this->paginate());
20
-		}
21
-
22
-		public function admin_add() {
23
-			if (!empty($this->request->data)) {
24
-				$this->Category->create();
25
-				if ($this->Category->save($this->request->data)) {
26
-					$this->Session->setFlash(__('The category has been saved'));
27
-					$this->redirect(array('action' => 'index'));
28
-				} else {
29
-					$this->Session->setFlash(__('The category could not be saved. Please, try again.'));
30
-				}
31
-			}
32
-		}
33
-
34
-		public function admin_edit($id = null) {
35
-			if (!$id && empty($this->request->data)) {
36
-				$this->Session->setFlash(__('Invalid category'));
37
-				$this->redirect(array('action' => 'index'));
38
-			}
39
-			if (!empty($this->request->data)) {
40
-				if ($this->Category->save($this->request->data)) {
41
-					$this->Session->setFlash(__('The category has been saved'));
42
-					$this->redirect(array('action' => 'index'));
43
-				} else {
44
-					$this->Session->setFlash(__('The category could not be saved. Please, try again.'));
45
-				}
46
-			}
47
-			if (empty($this->request->data)) {
48
-				$this->Category->contain();
49
-				$this->request->data = $this->Category->read(null, $id);
50
-			}
51
-		}
52
-
53
-		public function admin_delete($id = null) {
54
-			if (!$id) {
55
-				$this->Session->setFlash(__('Invalid id for category'), 'flash/error');
56
-				$this->redirect($this->referer(array('action' => 'index')));
57
-				exit();
58
-			}
59
-
60
-			/* check if category to exists */
61
-			$this->Category->contain();
62
-			$categoryToDelete = $this->Category->findById($id);
63
-			if (empty($categoryToDelete)) :
64
-				$this->Session->setFlash(__('Category not found.'), 'flash/error');
65
-				$this->redirect($this->referer(array('action' => 'index')));
66
-				exit();
67
-			endif;
68
-
69
-			if (isset($this->request->data['Category']['modeDelete'])):
70
-				$failure = false;
71
-
72
-				if (isset($this->request->data['Category']['modeMove']) && isset($this->request->data['Category']['targetCategory'])):
73
-					/* move category items before deleting the cateogry */
74
-
75
-					$targetId = (int)$this->request->data['Category']['targetCategory'];
76
-
77
-					/* make sure that target category exists */
78
-					$this->Category->contain();
79
-					$categoryToDelete = $this->Category->findById($targetId);
80
-					if (empty($categoryToDelete)) :
81
-						$this->Session->setFlash(__('Target category not found.'),
82
-								'flash/error');
83
-						$this->redirect($this->referer());
84
-						exit();
85
-					endif;
86
-
87
-					$this->Category->id = $id;
88
-					if ($this->Category->mergeIntoCategory($targetId) == false) :
89
-						$this->Session->setFlash(__('Error moving category.'),
90
-								'flash/error');
91
-						$failure = $failure || true;
92
-					else:
93
-						$this->Session->setFlash(__('Category moved.'), 'flash/notice');
94
-					endif;
95
-				endif;
96
-
97
-				$this->Category->id = $id;
98
-				if ($this->Category->deleteWithAllEntries() == false) :
99
-					$this->Session->setFlash(__("Error deleting category."),
100
-							'flash/error');
101
-					$failure = $failure || true;
102
-				else:
103
-					$this->Session->setFlash(__('Category deleted.'), 'flash/notice');
104
-				endif;
105
-
106
-				if ($failure == false) :
107
-					$this->redirect(array('action' => 'index', 'admin' => true));
108
-					exit();
109
-				endif;
110
-
111
-			endif; // move or delete category
112
-
113
-			/* get categories for target <select> */
114
-			$categories = $this->CurrentUser->Categories->getAllowed('list');
115
-			unset($categories[$id]);
116
-			$this->set('targetCategory', $categories);
117
-
118
-			$this->Category->contain();
119
-			$this->request->data = $this->Category->read(null, $id);
120
-		}
121
-
122
-	}
3
+    App::uses('AppController', 'Controller');
4
+
5
+    class CategoriesController extends AppController {
6
+
7
+        public $name = 'Categories';
8
+
9
+        public $paginate = [
10
+            /**
11
+             * sets limit unrealisticly high so we should never reach the upper limit
12
+             * i.e. always show all entries on one page
13
+             */
14
+                'limit' => 1000,
15
+        ];
16
+
17
+        public function admin_index() {
18
+            $this->Category->recursive = 0;
19
+            $this->set('categories', $this->paginate());
20
+        }
21
+
22
+        public function admin_add() {
23
+            if (!empty($this->request->data)) {
24
+                $this->Category->create();
25
+                if ($this->Category->save($this->request->data)) {
26
+                    $this->Session->setFlash(__('The category has been saved'));
27
+                    $this->redirect(array('action' => 'index'));
28
+                } else {
29
+                    $this->Session->setFlash(__('The category could not be saved. Please, try again.'));
30
+                }
31
+            }
32
+        }
33
+
34
+        public function admin_edit($id = null) {
35
+            if (!$id && empty($this->request->data)) {
36
+                $this->Session->setFlash(__('Invalid category'));
37
+                $this->redirect(array('action' => 'index'));
38
+            }
39
+            if (!empty($this->request->data)) {
40
+                if ($this->Category->save($this->request->data)) {
41
+                    $this->Session->setFlash(__('The category has been saved'));
42
+                    $this->redirect(array('action' => 'index'));
43
+                } else {
44
+                    $this->Session->setFlash(__('The category could not be saved. Please, try again.'));
45
+                }
46
+            }
47
+            if (empty($this->request->data)) {
48
+                $this->Category->contain();
49
+                $this->request->data = $this->Category->read(null, $id);
50
+            }
51
+        }
52
+
53
+        public function admin_delete($id = null) {
54
+            if (!$id) {
55
+                $this->Session->setFlash(__('Invalid id for category'), 'flash/error');
56
+                $this->redirect($this->referer(array('action' => 'index')));
57
+                exit();
58
+            }
59
+
60
+            /* check if category to exists */
61
+            $this->Category->contain();
62
+            $categoryToDelete = $this->Category->findById($id);
63
+            if (empty($categoryToDelete)) :
64
+                $this->Session->setFlash(__('Category not found.'), 'flash/error');
65
+                $this->redirect($this->referer(array('action' => 'index')));
66
+                exit();
67
+            endif;
68
+
69
+            if (isset($this->request->data['Category']['modeDelete'])):
70
+                $failure = false;
71
+
72
+                if (isset($this->request->data['Category']['modeMove']) && isset($this->request->data['Category']['targetCategory'])):
73
+                    /* move category items before deleting the cateogry */
74
+
75
+                    $targetId = (int)$this->request->data['Category']['targetCategory'];
76
+
77
+                    /* make sure that target category exists */
78
+                    $this->Category->contain();
79
+                    $categoryToDelete = $this->Category->findById($targetId);
80
+                    if (empty($categoryToDelete)) :
81
+                        $this->Session->setFlash(__('Target category not found.'),
82
+                                'flash/error');
83
+                        $this->redirect($this->referer());
84
+                        exit();
85
+                    endif;
86
+
87
+                    $this->Category->id = $id;
88
+                    if ($this->Category->mergeIntoCategory($targetId) == false) :
89
+                        $this->Session->setFlash(__('Error moving category.'),
90
+                                'flash/error');
91
+                        $failure = $failure || true;
92
+                    else:
93
+                        $this->Session->setFlash(__('Category moved.'), 'flash/notice');
94
+                    endif;
95
+                endif;
96
+
97
+                $this->Category->id = $id;
98
+                if ($this->Category->deleteWithAllEntries() == false) :
99
+                    $this->Session->setFlash(__("Error deleting category."),
100
+                            'flash/error');
101
+                    $failure = $failure || true;
102
+                else:
103
+                    $this->Session->setFlash(__('Category deleted.'), 'flash/notice');
104
+                endif;
105
+
106
+                if ($failure == false) :
107
+                    $this->redirect(array('action' => 'index', 'admin' => true));
108
+                    exit();
109
+                endif;
110
+
111
+            endif; // move or delete category
112
+
113
+            /* get categories for target <select> */
114
+            $categories = $this->CurrentUser->Categories->getAllowed('list');
115
+            unset($categories[$id]);
116
+            $this->set('targetCategory', $categories);
117
+
118
+            $this->Category->contain();
119
+            $this->request->data = $this->Category->read(null, $id);
120
+        }
121
+
122
+    }
123 123
 
Please login to merge, or discard this patch.
app/Controller/SettingsController.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -63,7 +63,7 @@
 block discarded – undo
63 63
 
64 64
 		public function admin_edit($id = null) {
65 65
 			if (!$id) {
66
-				$this->redirect(array( 'action ' => 'index' ));
66
+				$this->redirect(array('action ' => 'index'));
67 67
 			}
68 68
 
69 69
 			$this->Setting->id = $id;
Please login to merge, or discard this patch.
Indentation   +83 added lines, -83 removed lines patch added patch discarded remove patch
@@ -1,94 +1,94 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-	App::uses('AppController', 'Controller');
3
+    App::uses('AppController', 'Controller');
4 4
 
5
-	class SettingsController extends AppController {
5
+    class SettingsController extends AppController {
6 6
 
7
-		public $name = 'Settings';
7
+        public $name = 'Settings';
8 8
 
9
-		public $helpers = [
10
-			'Setting',
11
-			'TimeH'
12
-		];
9
+        public $helpers = [
10
+            'Setting',
11
+            'TimeH'
12
+        ];
13 13
 
14
-		protected $_settingsShownInAdminIndex = [
15
-				'api_crossdomain' => 1,
16
-				'api_enabled' => 1,
17
-				'autolink' => 1,
18
-				'bbcode_img' => 1,
19
-				'block_user_ui' => 1,
20
-			// Activates and deactivates the category-chooser on entries/index
21
-				'category_chooser_global' => 1,
22
-			// Allows users to show the category-chooser even if the default
23
-			// setting `category_chooser_global` is off
24
-				'category_chooser_user_override' => 1,
25
-				'edit_delay' => 1,
26
-				'edit_period' => 1,
27
-				'embedly_enabled' => 1,
28
-				'embedly_key' => 1,
29
-				'email_contact' => 1,
30
-				'email_register' => 1,
31
-				'email_system' => 1,
32
-				'forum_disabled' => 1,
33
-				'forum_disabled_text' => 1,
34
-				'forum_email' => 1,
35
-				'forum_name' => 1,
36
-				'map_enabled' => 1,
37
-				'map_api_key' => 1,
38
-				'quote_symbol' => 1,
39
-				'shoutbox_enabled' => 1,
40
-				'shoutbox_max_shouts' => 1,
41
-				'smilies' => 1,
42
-				'signature_separator' => 1,
43
-				'stopwatch_get' => 1,
44
-				'store_ip' => 1,
45
-				'store_ip_anonymized' => 1,
46
-				'subject_maxlength' => 1,
47
-				'text_word_maxlength' => 1,
48
-				'thread_depth_indent' => 1,
49
-				'timezone' => 1,
50
-				'topics_per_page' => 1,
51
-				'tos_enabled' => 1,
52
-				'tos_url' => 1,
53
-				'upload_max_img_size' => 1,
54
-				'upload_max_number_of_uploads' => 1,
55
-				'video_domains_allowed' => 1,
56
-		];
14
+        protected $_settingsShownInAdminIndex = [
15
+                'api_crossdomain' => 1,
16
+                'api_enabled' => 1,
17
+                'autolink' => 1,
18
+                'bbcode_img' => 1,
19
+                'block_user_ui' => 1,
20
+            // Activates and deactivates the category-chooser on entries/index
21
+                'category_chooser_global' => 1,
22
+            // Allows users to show the category-chooser even if the default
23
+            // setting `category_chooser_global` is off
24
+                'category_chooser_user_override' => 1,
25
+                'edit_delay' => 1,
26
+                'edit_period' => 1,
27
+                'embedly_enabled' => 1,
28
+                'embedly_key' => 1,
29
+                'email_contact' => 1,
30
+                'email_register' => 1,
31
+                'email_system' => 1,
32
+                'forum_disabled' => 1,
33
+                'forum_disabled_text' => 1,
34
+                'forum_email' => 1,
35
+                'forum_name' => 1,
36
+                'map_enabled' => 1,
37
+                'map_api_key' => 1,
38
+                'quote_symbol' => 1,
39
+                'shoutbox_enabled' => 1,
40
+                'shoutbox_max_shouts' => 1,
41
+                'smilies' => 1,
42
+                'signature_separator' => 1,
43
+                'stopwatch_get' => 1,
44
+                'store_ip' => 1,
45
+                'store_ip_anonymized' => 1,
46
+                'subject_maxlength' => 1,
47
+                'text_word_maxlength' => 1,
48
+                'thread_depth_indent' => 1,
49
+                'timezone' => 1,
50
+                'topics_per_page' => 1,
51
+                'tos_enabled' => 1,
52
+                'tos_url' => 1,
53
+                'upload_max_img_size' => 1,
54
+                'upload_max_number_of_uploads' => 1,
55
+                'video_domains_allowed' => 1,
56
+        ];
57 57
 
58
-		public function admin_index() {
59
-			$settings = $this->request->data = $this->Setting->getSettings();
60
-			$settings = array_intersect_key($settings, $this->_settingsShownInAdminIndex);
61
-			$this->set('Settings', $settings);
62
-		}
58
+        public function admin_index() {
59
+            $settings = $this->request->data = $this->Setting->getSettings();
60
+            $settings = array_intersect_key($settings, $this->_settingsShownInAdminIndex);
61
+            $this->set('Settings', $settings);
62
+        }
63 63
 
64
-		public function admin_edit($id = null) {
65
-			if (!$id) {
66
-				$this->redirect(array( 'action ' => 'index' ));
67
-			}
64
+        public function admin_edit($id = null) {
65
+            if (!$id) {
66
+                $this->redirect(array( 'action ' => 'index' ));
67
+            }
68 68
 
69
-			$this->Setting->id = $id;
69
+            $this->Setting->id = $id;
70 70
 
71
-			if (empty($this->request->data)) {
72
-				$this->request->data = $this->Setting->read();
73
-				if (empty($this->request->data)) {
74
-					$this->Session->setFlash("Couldn't find parameter: {$id}", 'flash/error');
75
-					$this->redirect(array(
76
-							'controller' => 'settings', 'action' => 'index', 'admin' => true )
77
-					);
78
-				}
79
-				if ($id === 'timezone') :
80
-					$this->render('admin_timezone');
81
-				endif;
82
-			} else {
83
-				$this->Setting->id = $id;
84
-				if ($this->Setting->save($this->request->data)) {
85
-					$this->Session->setFlash('Saved. @lo', 'flash/notice');
86
-					$this->redirect(['action' => 'index', '#' => $id]);
87
-					return;
88
-				} else {
89
-					$this->Session->setFlash('Something went wrong @lo', 'flash/error');
90
-				}
91
-			}
92
-		}
71
+            if (empty($this->request->data)) {
72
+                $this->request->data = $this->Setting->read();
73
+                if (empty($this->request->data)) {
74
+                    $this->Session->setFlash("Couldn't find parameter: {$id}", 'flash/error');
75
+                    $this->redirect(array(
76
+                            'controller' => 'settings', 'action' => 'index', 'admin' => true )
77
+                    );
78
+                }
79
+                if ($id === 'timezone') :
80
+                    $this->render('admin_timezone');
81
+                endif;
82
+            } else {
83
+                $this->Setting->id = $id;
84
+                if ($this->Setting->save($this->request->data)) {
85
+                    $this->Session->setFlash('Saved. @lo', 'flash/notice');
86
+                    $this->redirect(['action' => 'index', '#' => $id]);
87
+                    return;
88
+                } else {
89
+                    $this->Session->setFlash('Something went wrong @lo', 'flash/error');
90
+                }
91
+            }
92
+        }
93 93
 
94
-	}
94
+    }
Please login to merge, or discard this patch.
app/Controller/SearchesController.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -79,8 +79,8 @@  discard block
 block discarded – undo
79 79
 			$order = '`Entry`.`time` DESC';
80 80
 			$fields = '*';
81 81
 			if ($query['order'] === 'rank') {
82
-				$order = 'rating DESC, ' . $order;
83
-				$fields = $fields . ", (MATCH (Entry.subject) AGAINST ('$q' IN BOOLEAN MODE)*2) + (MATCH (Entry.text) AGAINST ('$q' IN BOOLEAN MODE)) + (MATCH (Entry.name) AGAINST ('$q' IN BOOLEAN MODE)*4) AS rating";
82
+				$order = 'rating DESC, '.$order;
83
+				$fields = $fields.", (MATCH (Entry.subject) AGAINST ('$q' IN BOOLEAN MODE)*2) + (MATCH (Entry.text) AGAINST ('$q' IN BOOLEAN MODE)) + (MATCH (Entry.name) AGAINST ('$q' IN BOOLEAN MODE)*4) AS rating";
84 84
 			}
85 85
 
86 86
 			// query
@@ -152,8 +152,8 @@  discard block
 block discarded – undo
152 152
 						'Y-m-d H:i:s',
153 153
 						mktime(0, 0, 0, $month, 1, $year));
154 154
 
155
-				if (isset($query['category_id']) && (int)$query['category_id'] !== 0) {
156
-					if (!isset($categories[(int)$query['category_id']])) {
155
+				if (isset($query['category_id']) && (int) $query['category_id'] !== 0) {
156
+					if (!isset($categories[(int) $query['category_id']])) {
157 157
 						throw new NotFoundException;
158 158
 					}
159 159
 				} else {
Please login to merge, or discard this patch.
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -1,188 +1,188 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-	use Saito\SimpleSearchString;
4
-
5
-	App::uses('AppController', 'Controller');
6
-
7
-	class SearchesController extends AppController {
8
-
9
-		public $components = [
10
-				'Paginator',
11
-				'Search.Prg' => [
12
-					'commonProcess' => [
13
-						'allowedParams' => ['nstrict'],
14
-						'keepPassed' => true,
15
-						'filterEmpty' => true,
16
-						'paramType' => 'querystring'
17
-					]
18
-				]
19
-		];
20
-
21
-		public $helpers = ['Form', 'Html', 'EntryH'];
22
-
23
-		public $uses = [
24
-				'Entry'
25
-		];
26
-
27
-		protected $_paginateConfig = [
28
-				'limit' => 25
29
-		];
30
-
31
-		public function beforeFilter() {
32
-			parent::beforeFilter();
33
-			$this->Auth->allow('simple');
34
-		}
35
-
36
-		public function simple() {
37
-			$defaults = [
38
-					'order' => 'time'
39
-			];
40
-			$this->set('order', $defaults['order']);
41
-
42
-			// @todo pgsql
43
-			$db = $this->Entry->getDataSource();
44
-			// @codingStandardsIgnoreStart
45
-			// on 5.5 phpcs assumes this is the deprecated PHP MySQL extension
46
-			if (!($db instanceof Mysql)) {
47
-				// @codingStandardsIgnoreEnd
48
-				$this->redirect(['action' => 'advanced']);
49
-				return;
50
-			}
51
-
52
-			$minWordLength = $this->Entry->query("SHOW VARIABLES LIKE 'ft_min_word_len'")[0];
53
-			$minWordLength = array_shift($minWordLength)['Value'];
54
-			$this->set(compact('minWordLength'));
55
-
56
-			if (!isset($this->request->query['q'])) {
57
-				// request for empty search form
58
-				return;
59
-			}
60
-
61
-			$this->_filterQuery(['q', 'page', 'order']);
62
-			$qRaw = $this->request->query['q'];
63
-			$query = $this->request->query += $defaults;
64
-			$this->set(['q' => $qRaw, 'order' => $query['order']]);
65
-
66
-			// test query is valid
67
-			$SearchString = new SimpleSearchString($qRaw, $minWordLength);
68
-			$this->set('minChars', $minWordLength);
69
-
70
-			$query['q'] = $SearchString->replaceOperators();
71
-			$omitted = $SearchString->getOmittedWords();
72
-			$this->set('omittedWords', $omitted);
73
-
74
-			// sanitize search-term for manual SQL-query
75
-			$query['q'] = $this->_sanitize($query['q']);
76
-
77
-			// build query
78
-			$q = $query['q'];
79
-			$order = '`Entry`.`time` DESC';
80
-			$fields = '*';
81
-			if ($query['order'] === 'rank') {
82
-				$order = 'rating DESC, ' . $order;
83
-				$fields = $fields . ", (MATCH (Entry.subject) AGAINST ('$q' IN BOOLEAN MODE)*2) + (MATCH (Entry.text) AGAINST ('$q' IN BOOLEAN MODE)) + (MATCH (Entry.name) AGAINST ('$q' IN BOOLEAN MODE)*4) AS rating";
84
-			}
85
-
86
-			// query
87
-			$this->Paginator->settings = [
88
-					'fields' => $fields,
89
-					'conditions' => [
90
-							"MATCH (Entry.subject, Entry.text, Entry.name) AGAINST ('$q' IN BOOLEAN MODE)",
91
-							'Entry.category_id' => $this->CurrentUser->Categories->getAllowed()
92
-					],
93
-					'order' => $order,
94
-					'paramType' => 'querystring'
95
-			];
96
-			$this->Paginator->settings += $this->_paginateConfig;
97
-			$results = $this->Paginator->paginate('Entry');
98
-			$this->set('results', $results);
99
-		}
100
-
101
-		/**
102
-		 * @throws NotFoundException
103
-		 * @throws BadRequestException
104
-		 */
105
-		public function advanced() {
106
-			// year for date drop-down
107
-			$first = $this->Entry->find('first',
108
-					['contain' => false, 'order' => 'Entry.id ASC']);
109
-			if ($first !== false) {
110
-				$startDate = strtotime($first['Entry']['time']);
111
-			} else {
112
-				$startDate = time();
113
-			}
114
-			$this->set('start_year', date('Y', $startDate));
115
-
116
-			// category drop-down
117
-			$categories = $this->CurrentUser->Categories->getAllowed('list');
118
-			$this->set('categories', $categories);
119
-
120
-			// calculate current month and year
121
-			if (isset($this->request->query['month'])) {
122
-				$month = $this->request->query['month'];
123
-				$year = $this->request->query['year'];
124
-			} else {
125
-				$month = date('n', $startDate);
126
-				$year = date('Y', $startDate);
127
-			}
128
-
129
-			$this->Prg->commonProcess();
130
-			$query = $this->Prg->parsedParams();
131
-
132
-			if (!empty($query['subject']) || !empty($query['text']) ||
133
-					!empty($query['name'])
134
-			) {
135
-				// strict username search: set before parseCriteria
136
-				if (!empty($this->request->query['nstrict'])) {
137
-					// presetVars controller var isn't working in Search v2.3
138
-					$this->Entry->filterArgs['name']['type'] = 'value';
139
-				}
140
-
141
-				$settings = [
142
-								'conditions' => $this->Entry->parseCriteria($query),
143
-								'order' => ['Entry.time' => 'DESC'],
144
-								'paramType' => 'querystring'
145
-						] + $this->_paginateConfig;
146
-
147
-				$time = mktime(0, 0, 0, $month, 1, $year);
148
-				if (!$time) {
149
-					throw new BadRequestException;
150
-				}
151
-				$settings['conditions']['time >'] = date(
152
-						'Y-m-d H:i:s',
153
-						mktime(0, 0, 0, $month, 1, $year));
154
-
155
-				if (isset($query['category_id']) && (int)$query['category_id'] !== 0) {
156
-					if (!isset($categories[(int)$query['category_id']])) {
157
-						throw new NotFoundException;
158
-					}
159
-				} else {
160
-					$settings['conditions']['Entry.category_id'] = $this->CurrentUser
161
-						->Categories->getAllowed();
162
-				}
163
-				$this->Paginator->settings = $settings;
164
-				unset(
165
-					$this->request->query['direction'],
166
-					$this->request->query['sort']
167
-				);
168
-				$this->set('results',
169
-					$this->Paginator->paginate(null, null, ['Entry.time']));
170
-			}
171
-
172
-			if (!isset($query['category_id'])) {
173
-				$this->request->data['Entry']['category_id'] = 0;
174
-			}
175
-
176
-			$this->set(compact('month', 'year'));
177
-		}
178
-
179
-		protected function _sanitize($string) {
180
-			return Sanitize::escape($string, $this->Entry->useDbConfig);
181
-		}
182
-
183
-		protected function _filterQuery($params) {
184
-			$this->request->query = array_intersect_key($this->request->query,
185
-					array_fill_keys($params, 1));
186
-		}
187
-
188
-	}
3
+    use Saito\SimpleSearchString;
4
+
5
+    App::uses('AppController', 'Controller');
6
+
7
+    class SearchesController extends AppController {
8
+
9
+        public $components = [
10
+                'Paginator',
11
+                'Search.Prg' => [
12
+                    'commonProcess' => [
13
+                        'allowedParams' => ['nstrict'],
14
+                        'keepPassed' => true,
15
+                        'filterEmpty' => true,
16
+                        'paramType' => 'querystring'
17
+                    ]
18
+                ]
19
+        ];
20
+
21
+        public $helpers = ['Form', 'Html', 'EntryH'];
22
+
23
+        public $uses = [
24
+                'Entry'
25
+        ];
26
+
27
+        protected $_paginateConfig = [
28
+                'limit' => 25
29
+        ];
30
+
31
+        public function beforeFilter() {
32
+            parent::beforeFilter();
33
+            $this->Auth->allow('simple');
34
+        }
35
+
36
+        public function simple() {
37
+            $defaults = [
38
+                    'order' => 'time'
39
+            ];
40
+            $this->set('order', $defaults['order']);
41
+
42
+            // @todo pgsql
43
+            $db = $this->Entry->getDataSource();
44
+            // @codingStandardsIgnoreStart
45
+            // on 5.5 phpcs assumes this is the deprecated PHP MySQL extension
46
+            if (!($db instanceof Mysql)) {
47
+                // @codingStandardsIgnoreEnd
48
+                $this->redirect(['action' => 'advanced']);
49
+                return;
50
+            }
51
+
52
+            $minWordLength = $this->Entry->query("SHOW VARIABLES LIKE 'ft_min_word_len'")[0];
53
+            $minWordLength = array_shift($minWordLength)['Value'];
54
+            $this->set(compact('minWordLength'));
55
+
56
+            if (!isset($this->request->query['q'])) {
57
+                // request for empty search form
58
+                return;
59
+            }
60
+
61
+            $this->_filterQuery(['q', 'page', 'order']);
62
+            $qRaw = $this->request->query['q'];
63
+            $query = $this->request->query += $defaults;
64
+            $this->set(['q' => $qRaw, 'order' => $query['order']]);
65
+
66
+            // test query is valid
67
+            $SearchString = new SimpleSearchString($qRaw, $minWordLength);
68
+            $this->set('minChars', $minWordLength);
69
+
70
+            $query['q'] = $SearchString->replaceOperators();
71
+            $omitted = $SearchString->getOmittedWords();
72
+            $this->set('omittedWords', $omitted);
73
+
74
+            // sanitize search-term for manual SQL-query
75
+            $query['q'] = $this->_sanitize($query['q']);
76
+
77
+            // build query
78
+            $q = $query['q'];
79
+            $order = '`Entry`.`time` DESC';
80
+            $fields = '*';
81
+            if ($query['order'] === 'rank') {
82
+                $order = 'rating DESC, ' . $order;
83
+                $fields = $fields . ", (MATCH (Entry.subject) AGAINST ('$q' IN BOOLEAN MODE)*2) + (MATCH (Entry.text) AGAINST ('$q' IN BOOLEAN MODE)) + (MATCH (Entry.name) AGAINST ('$q' IN BOOLEAN MODE)*4) AS rating";
84
+            }
85
+
86
+            // query
87
+            $this->Paginator->settings = [
88
+                    'fields' => $fields,
89
+                    'conditions' => [
90
+                            "MATCH (Entry.subject, Entry.text, Entry.name) AGAINST ('$q' IN BOOLEAN MODE)",
91
+                            'Entry.category_id' => $this->CurrentUser->Categories->getAllowed()
92
+                    ],
93
+                    'order' => $order,
94
+                    'paramType' => 'querystring'
95
+            ];
96
+            $this->Paginator->settings += $this->_paginateConfig;
97
+            $results = $this->Paginator->paginate('Entry');
98
+            $this->set('results', $results);
99
+        }
100
+
101
+        /**
102
+         * @throws NotFoundException
103
+         * @throws BadRequestException
104
+         */
105
+        public function advanced() {
106
+            // year for date drop-down
107
+            $first = $this->Entry->find('first',
108
+                    ['contain' => false, 'order' => 'Entry.id ASC']);
109
+            if ($first !== false) {
110
+                $startDate = strtotime($first['Entry']['time']);
111
+            } else {
112
+                $startDate = time();
113
+            }
114
+            $this->set('start_year', date('Y', $startDate));
115
+
116
+            // category drop-down
117
+            $categories = $this->CurrentUser->Categories->getAllowed('list');
118
+            $this->set('categories', $categories);
119
+
120
+            // calculate current month and year
121
+            if (isset($this->request->query['month'])) {
122
+                $month = $this->request->query['month'];
123
+                $year = $this->request->query['year'];
124
+            } else {
125
+                $month = date('n', $startDate);
126
+                $year = date('Y', $startDate);
127
+            }
128
+
129
+            $this->Prg->commonProcess();
130
+            $query = $this->Prg->parsedParams();
131
+
132
+            if (!empty($query['subject']) || !empty($query['text']) ||
133
+                    !empty($query['name'])
134
+            ) {
135
+                // strict username search: set before parseCriteria
136
+                if (!empty($this->request->query['nstrict'])) {
137
+                    // presetVars controller var isn't working in Search v2.3
138
+                    $this->Entry->filterArgs['name']['type'] = 'value';
139
+                }
140
+
141
+                $settings = [
142
+                                'conditions' => $this->Entry->parseCriteria($query),
143
+                                'order' => ['Entry.time' => 'DESC'],
144
+                                'paramType' => 'querystring'
145
+                        ] + $this->_paginateConfig;
146
+
147
+                $time = mktime(0, 0, 0, $month, 1, $year);
148
+                if (!$time) {
149
+                    throw new BadRequestException;
150
+                }
151
+                $settings['conditions']['time >'] = date(
152
+                        'Y-m-d H:i:s',
153
+                        mktime(0, 0, 0, $month, 1, $year));
154
+
155
+                if (isset($query['category_id']) && (int)$query['category_id'] !== 0) {
156
+                    if (!isset($categories[(int)$query['category_id']])) {
157
+                        throw new NotFoundException;
158
+                    }
159
+                } else {
160
+                    $settings['conditions']['Entry.category_id'] = $this->CurrentUser
161
+                        ->Categories->getAllowed();
162
+                }
163
+                $this->Paginator->settings = $settings;
164
+                unset(
165
+                    $this->request->query['direction'],
166
+                    $this->request->query['sort']
167
+                );
168
+                $this->set('results',
169
+                    $this->Paginator->paginate(null, null, ['Entry.time']));
170
+            }
171
+
172
+            if (!isset($query['category_id'])) {
173
+                $this->request->data['Entry']['category_id'] = 0;
174
+            }
175
+
176
+            $this->set(compact('month', 'year'));
177
+        }
178
+
179
+        protected function _sanitize($string) {
180
+            return Sanitize::escape($string, $this->Entry->useDbConfig);
181
+        }
182
+
183
+        protected function _filterQuery($params) {
184
+            $this->request->query = array_intersect_key($this->request->query,
185
+                    array_fill_keys($params, 1));
186
+        }
187
+
188
+    }
Please login to merge, or discard this patch.
app/Controller/StatusController.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@
 block discarded – undo
36 36
 			$this->response->disableCache();
37 37
 			$_out = '';
38 38
 			$_out .= "retry: $_retry\n";
39
-			$_out .= 'data: ' . $data . "\n\n";
39
+			$_out .= 'data: '.$data."\n\n";
40 40
 			return $_out;
41 41
 		}
42 42
 
Please login to merge, or discard this patch.
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -1,57 +1,57 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-	App::uses('AppController', 'Controller');
4
-
5
-	class StatusController extends AppController {
6
-
7
-		public $uses = [
8
-			'Shout'
9
-		];
10
-
11
-		public $autoRender = false;
12
-
13
-		/**
14
-		 * Current app status ping
15
-		 *
16
-		 * @return string
17
-		 * @throws BadRequestException
18
-		 */
19
-		public function status() {
20
-			$data = [
21
-				'lastShoutId' => $this->Shout->findLastId()
22
-			];
23
-			$data = json_encode($data);
24
-			if ($this->request->accepts('text/event-streams')) {
25
-				return $this->_statusAsEventStream($data);
26
-			} else {
27
-				return $this->_statusAsJson($data);
28
-			}
29
-		}
30
-
31
-		protected function _statusAsEventStream($data) {
32
-			// time in ms to next request
33
-			$_retry = '10000';
34
-			$this->response->type(['eventstream' => 'text/event-stream']);
35
-			$this->response->type('eventstream');
36
-			$this->response->disableCache();
37
-			$_out = '';
38
-			$_out .= "retry: $_retry\n";
39
-			$_out .= 'data: ' . $data . "\n\n";
40
-			return $_out;
41
-		}
42
-
43
-		protected function _statusAsJson($data) {
44
-			if ($this->request->is('ajax') === false) {
45
-				throw new BadRequestException();
46
-			}
47
-			return $data;
48
-		}
49
-
50
-		public function beforeFilter() {
51
-			parent::beforeFilter();
52
-			if ($this->Components->enabled('Auth')) {
53
-				$this->Components->disable('Auth');
54
-			}
55
-		}
56
-
57
-	}
3
+    App::uses('AppController', 'Controller');
4
+
5
+    class StatusController extends AppController {
6
+
7
+        public $uses = [
8
+            'Shout'
9
+        ];
10
+
11
+        public $autoRender = false;
12
+
13
+        /**
14
+         * Current app status ping
15
+         *
16
+         * @return string
17
+         * @throws BadRequestException
18
+         */
19
+        public function status() {
20
+            $data = [
21
+                'lastShoutId' => $this->Shout->findLastId()
22
+            ];
23
+            $data = json_encode($data);
24
+            if ($this->request->accepts('text/event-streams')) {
25
+                return $this->_statusAsEventStream($data);
26
+            } else {
27
+                return $this->_statusAsJson($data);
28
+            }
29
+        }
30
+
31
+        protected function _statusAsEventStream($data) {
32
+            // time in ms to next request
33
+            $_retry = '10000';
34
+            $this->response->type(['eventstream' => 'text/event-stream']);
35
+            $this->response->type('eventstream');
36
+            $this->response->disableCache();
37
+            $_out = '';
38
+            $_out .= "retry: $_retry\n";
39
+            $_out .= 'data: ' . $data . "\n\n";
40
+            return $_out;
41
+        }
42
+
43
+        protected function _statusAsJson($data) {
44
+            if ($this->request->is('ajax') === false) {
45
+                throw new BadRequestException();
46
+            }
47
+            return $data;
48
+        }
49
+
50
+        public function beforeFilter() {
51
+            parent::beforeFilter();
52
+            if ($this->Components->enabled('Auth')) {
53
+                $this->Components->disable('Auth');
54
+            }
55
+        }
56
+
57
+    }
Please login to merge, or discard this patch.