Completed
Push — master ( 945d9a...e5db64 )
by Schlaefer
02:51
created
app/Model/UserIgnore.php 2 patches
Doc Comments   +12 added lines, -2 removed lines patch added patch discarded remove patch
@@ -29,6 +29,10 @@  discard block
 block discarded – undo
29 29
 		 */
30 30
 		public $duration = 8035200;
31 31
 
32
+		/**
33
+		 * @param integer $userId
34
+		 * @param integer $blockedUserId
35
+		 */
32 36
 		public function ignore($userId, $blockedUserId) {
33 37
 			$exists = $this->_get($userId, $blockedUserId);
34 38
 			if ($exists) {
@@ -62,6 +66,9 @@  discard block
 block discarded – undo
62 66
 			]);
63 67
 		}
64 68
 
69
+		/**
70
+		 * @param integer $id
71
+		 */
65 72
 		public function ignoredBy($id) {
66 73
 			return $this->find(
67 74
 				'all',
@@ -72,6 +79,9 @@  discard block
 block discarded – undo
72 79
 			);
73 80
 		}
74 81
 
82
+		/**
83
+		 * @param integer $userId
84
+		 */
75 85
 		public function deleteUser($userId) {
76 86
 			$success = $this->deleteAll(['user_id' => $userId], false);
77 87
 			$success = $success && $this->deleteAll(['blocked_user_id' => $userId], false);
@@ -81,8 +91,8 @@  discard block
 block discarded – undo
81 91
 		/**
82 92
 		 * counts how many users ignore the user with ID $id
83 93
 		 *
84
-		 * @param $id
85
-		 * @return array
94
+		 * @param integer $id
95
+		 * @return integer
86 96
 		 */
87 97
 		public function countIgnored($id) {
88 98
 			return count($this->getIgnored($id));
Please login to merge, or discard this patch.
Indentation   +92 added lines, -92 removed lines patch added patch discarded remove patch
@@ -1,108 +1,108 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-	App::uses('AppModel', 'Model');
3
+    App::uses('AppModel', 'Model');
4 4
 
5
-	class UserIgnore extends AppModel {
5
+    class UserIgnore extends AppModel {
6 6
 
7
-		public $actsAs = [
8
-			'Containable',
9
-			'Cron.Cron' => [
10
-					'removeOld' => [
11
-							'id' => 'UserIgnore.removeOld',
12
-							'due' => 'daily',
13
-					]
14
-			]
15
-		];
7
+        public $actsAs = [
8
+            'Containable',
9
+            'Cron.Cron' => [
10
+                    'removeOld' => [
11
+                            'id' => 'UserIgnore.removeOld',
12
+                            'due' => 'daily',
13
+                    ]
14
+            ]
15
+        ];
16 16
 
17
-		public $belongsTo = [
18
-			'User' => [
19
-				'className' => 'User',
20
-				'counterCache' => true,
21
-				'fields' => ['id', 'username'],
22
-				'foreignKey' => 'blocked_user_id',
23
-				'order' => ['User.username' => 'asc']
24
-			]
25
-		];
17
+        public $belongsTo = [
18
+            'User' => [
19
+                'className' => 'User',
20
+                'counterCache' => true,
21
+                'fields' => ['id', 'username'],
22
+                'foreignKey' => 'blocked_user_id',
23
+                'order' => ['User.username' => 'asc']
24
+            ]
25
+        ];
26 26
 
27
-		/**
28
-		 * @var int 3 months
29
-		 */
30
-		public $duration = 8035200;
27
+        /**
28
+         * @var int 3 months
29
+         */
30
+        public $duration = 8035200;
31 31
 
32
-		public function ignore($userId, $blockedUserId) {
33
-			$exists = $this->_get($userId, $blockedUserId);
34
-			if ($exists) {
35
-				return;
36
-			}
37
-			$this->create();
38
-			$this->save([
39
-				'user_id' => $userId,
40
-				'blocked_user_id' => $blockedUserId,
41
-				'timestamp' => bDate()
42
-			]);
32
+        public function ignore($userId, $blockedUserId) {
33
+            $exists = $this->_get($userId, $blockedUserId);
34
+            if ($exists) {
35
+                return;
36
+            }
37
+            $this->create();
38
+            $this->save([
39
+                'user_id' => $userId,
40
+                'blocked_user_id' => $blockedUserId,
41
+                'timestamp' => bDate()
42
+            ]);
43 43
 
44
-			$this->_dispatchEvent('Event.Saito.User.afterIgnore', [
45
-				'blockedUserId' => $blockedUserId,
46
-				'userId' => $userId
47
-			]);
48
-		}
44
+            $this->_dispatchEvent('Event.Saito.User.afterIgnore', [
45
+                'blockedUserId' => $blockedUserId,
46
+                'userId' => $userId
47
+            ]);
48
+        }
49 49
 
50
-		public function unignore($userId, $blockedId) {
51
-			$entry = $this->_get($userId, $blockedId);
52
-			if (empty($entry)) {
53
-				return;
54
-			}
55
-			$this->delete($entry['Ignore']['id']);
56
-		}
50
+        public function unignore($userId, $blockedId) {
51
+            $entry = $this->_get($userId, $blockedId);
52
+            if (empty($entry)) {
53
+                return;
54
+            }
55
+            $this->delete($entry['Ignore']['id']);
56
+        }
57 57
 
58
-		protected function _get($userId, $blockedId) {
59
-			return $this->find('first', [
60
-				'contain' => false,
61
-				'conditions' => ['user_id' => $userId, 'blocked_user_id' => $blockedId]
62
-			]);
63
-		}
58
+        protected function _get($userId, $blockedId) {
59
+            return $this->find('first', [
60
+                'contain' => false,
61
+                'conditions' => ['user_id' => $userId, 'blocked_user_id' => $blockedId]
62
+            ]);
63
+        }
64 64
 
65
-		public function ignoredBy($id) {
66
-			return $this->find(
67
-				'all',
68
-				[
69
-					'contain' => ['User'],
70
-					'conditions' => ['user_id' => $id]
71
-				]
72
-			);
73
-		}
65
+        public function ignoredBy($id) {
66
+            return $this->find(
67
+                'all',
68
+                [
69
+                    'contain' => ['User'],
70
+                    'conditions' => ['user_id' => $id]
71
+                ]
72
+            );
73
+        }
74 74
 
75
-		public function deleteUser($userId) {
76
-			$success = $this->deleteAll(['user_id' => $userId], false);
77
-			$success = $success && $this->deleteAll(['blocked_user_id' => $userId], false);
78
-			return $success;
79
-		}
75
+        public function deleteUser($userId) {
76
+            $success = $this->deleteAll(['user_id' => $userId], false);
77
+            $success = $success && $this->deleteAll(['blocked_user_id' => $userId], false);
78
+            return $success;
79
+        }
80 80
 
81
-		/**
82
-		 * counts how many users ignore the user with ID $id
83
-		 *
84
-		 * @param $id
85
-		 * @return array
86
-		 */
87
-		public function countIgnored($id) {
88
-			return count($this->getIgnored($id));
89
-		}
81
+        /**
82
+         * counts how many users ignore the user with ID $id
83
+         *
84
+         * @param $id
85
+         * @return array
86
+         */
87
+        public function countIgnored($id) {
88
+            return count($this->getIgnored($id));
89
+        }
90 90
 
91
-		public function getIgnored($id) {
92
-			return $this->find(
93
-				'all',
94
-				[
95
-					'contain' => false,
96
-					'conditions' => ['blocked_user_id' => $id]
97
-				]
98
-			);
99
-		}
91
+        public function getIgnored($id) {
92
+            return $this->find(
93
+                'all',
94
+                [
95
+                    'contain' => false,
96
+                    'conditions' => ['blocked_user_id' => $id]
97
+                ]
98
+            );
99
+        }
100 100
 
101
-		public function removeOld() {
102
-			$this->deleteAll([
103
-					'timestamp <' => bDate(time() - $this->duration)
104
-				],
105
-				false);
106
-		}
101
+        public function removeOld() {
102
+            $this->deleteAll([
103
+                    'timestamp <' => bDate(time() - $this->duration)
104
+                ],
105
+                false);
106
+        }
107 107
 
108
-	}
108
+    }
Please login to merge, or discard this patch.
app/Plugin/Embedly/Vendor/Embedly.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
     /**
170 170
      *
171 171
      * @param string $version
172
-     * @param array $action
172
+     * @param string $action
173 173
      * @param array $params
174 174
      * @return object
175 175
      */
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
     /**
292 292
      *
293 293
      * @param resource $ch
294
-     * @param array $headers
294
+     * @param string[] $headers
295 295
      * @return void
296 296
      */
297 297
     protected function setCurlOptions(&$ch, $headers = array())
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 
334 334
     /**
335 335
      *
336
-     * @param stdClass $o
336
+     * @param \stdClass $o
337 337
      * @return string
338 338
      */
339 339
     public static function reg_imploder(\stdClass $o)
Please login to merge, or discard this patch.
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -274,10 +274,10 @@
 block discarded – undo
274 274
      * @return string
275 275
      */
276 276
     public function services_regex() {
277
-    	$services = $this->services();
278
-    	$regexes = array_map(array(__CLASS__, 'reg_imploder'), $services);
279
-    	return '#'.implode('|', $regexes).'#i';
280
-	}
277
+        $services = $this->services();
278
+        $regexes = array_map(array(__CLASS__, 'reg_imploder'), $services);
279
+        return '#'.implode('|', $regexes).'#i';
280
+    }
281 281
 
282 282
     /**
283 283
      *
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
                 if (!$match) {
203 203
                     //print("rejecting $url");
204 204
                     unset($params['urls'][$i]);
205
-                    $rejects[$i] = (object)array(
205
+                    $rejects[$i] = (object) array(
206 206
                         'error_code' => '401',
207 207
                         'error_message' => 'This service requires an Embedly key',
208 208
                         'type' => 'error'
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
             array_push($merged_result, $obj);
244 244
         }
245 245
 
246
-        if($justone) {
246
+        if ($justone) {
247 247
             return array_shift($merged_result);
248 248
         }
249 249
 
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
      */
366 366
     public static function paramify($input)
367 367
     {
368
-        if(is_string($input)) {
368
+        if (is_string($input)) {
369 369
             return array('urls' => $input);
370 370
         }
371 371
 
Please login to merge, or discard this patch.
app/Plugin/FileUpload/Vendor/uploader.php 4 patches
Doc Comments   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -94,6 +94,7 @@  discard block
 block discarded – undo
94 94
     * Preform requested target patch checks depending on the unique setting
95 95
     *
96 96
     * @var string chosen filename target_path
97
+    * @param string $target_path
97 98
     * @return string of resulting target_path
98 99
     * @access private
99 100
     */
@@ -217,7 +218,7 @@  discard block
 block discarded – undo
217 218
   /**
218 219
     * Checks if there is a file uploaded
219 220
     *
220
-    * @return void
221
+    * @return boolean
221 222
     * @access public
222 223
     * @param file array of uploaded file (optional)
223 224
     */
@@ -293,7 +294,7 @@  discard block
 block discarded – undo
293 294
   }
294 295
 
295 296
   /**
296
-    * @return boolean true if errors were detected.
297
+    * @return integer true if errors were detected.
297 298
     */
298 299
   function hasErrors(){
299 300
     return count($this->errors);
Please login to merge, or discard this patch.
Indentation   +218 added lines, -218 removed lines patch added patch discarded remove patch
@@ -1,40 +1,40 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 /**
3
-  * Uploader class handles a single file to be uploaded to the file system
4
-  *
5
-  * @author: Nick Baker
6
-  * @version: since 6.0.0
7
-  * @link: http://www.webtechnick.com
8
-  */
3
+ * Uploader class handles a single file to be uploaded to the file system
4
+ *
5
+ * @author: Nick Baker
6
+ * @version: since 6.0.0
7
+ * @link: http://www.webtechnick.com
8
+ */
9 9
 class Uploader {
10 10
 
11
-  /**
12
-    * File to upload.
13
-    */
14
-  var $file = array();
11
+    /**
12
+     * File to upload.
13
+     */
14
+    var $file = array();
15 15
 
16
-  /**
17
-    * Global options
18
-    * fileTypes to allow to upload
19
-    */
20
-  var $options = array();
16
+    /**
17
+     * Global options
18
+     * fileTypes to allow to upload
19
+     */
20
+    var $options = array();
21 21
 
22
-  /**
23
-    * errors holds any errors that occur as string values.
24
-    * this can be access to debug the FileUploadComponent
25
-    *
26
-    * @var array
27
-    * @access public
28
-    */
29
-  var $errors = array();
22
+    /**
23
+     * errors holds any errors that occur as string values.
24
+     * this can be access to debug the FileUploadComponent
25
+     *
26
+     * @var array
27
+     * @access public
28
+     */
29
+    var $errors = array();
30 30
 
31
-  /**
32
-    * Definitions of errors that could occur during upload
33
-    *
34
-    * @author Jon Langevin
35
-    * @var array
36
-    */
37
-  var $uploadErrors = array(
31
+    /**
32
+     * Definitions of errors that could occur during upload
33
+     *
34
+     * @author Jon Langevin
35
+     * @var array
36
+     */
37
+    var $uploadErrors = array(
38 38
     UPLOAD_ERR_OK => 'There is no error, the file uploaded with success.',
39 39
     UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
40 40
     UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
@@ -43,87 +43,87 @@  discard block
 block discarded – undo
43 43
     UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.', //Introduced in PHP 4.3.10 and PHP 5.0.3.
44 44
     UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.', //Introduced in PHP 5.1.0.
45 45
     UPLOAD_ERR_EXTENSION => 'File upload stopped by extension.' //Introduced in PHP 5.2.0.
46
-  );
46
+    );
47 47
 
48
-  /**
49
-    * Final file is set on move_uploaded_file success.
50
-    * This is the file name of the final file that was uploaded
51
-    * to the uploadDir directory
52
-    *
53
-    * @var string of final file name uploaded
54
-    * @access public
55
-    */
56
-  var $finalFile = null;
48
+    /**
49
+     * Final file is set on move_uploaded_file success.
50
+     * This is the file name of the final file that was uploaded
51
+     * to the uploadDir directory
52
+     *
53
+     * @var string of final file name uploaded
54
+     * @access public
55
+     */
56
+    var $finalFile = null;
57 57
 
58
-  function __construct($options = array()){
58
+    function __construct($options = array()){
59 59
     $this->options = array_merge($this->options, $options);
60
-  }
60
+    }
61 61
 
62
-  /**
63
-    * Preform requested callbacks on the filename.
64
-    *
65
-    * @var string chosen filename
66
-    * @return string of resulting filename
67
-    * @access private
68
-    */
69
-  function __handleFileNameCallback($fileName){
62
+    /**
63
+     * Preform requested callbacks on the filename.
64
+     *
65
+     * @var string chosen filename
66
+     * @return string of resulting filename
67
+     * @access private
68
+     */
69
+    function __handleFileNameCallback($fileName){
70 70
     if($this->options['fileNameFunction']){
71
-      if($this->options['fileModel']){
71
+        if($this->options['fileModel']){
72 72
         $Model = ClassRegistry::init($this->options['fileModel']);
73 73
         if(method_exists($Model, $this->options['fileNameFunction'])){
74
-          $fileName = $Model->{$this->options['fileNameFunction']}($fileName);
74
+            $fileName = $Model->{$this->options['fileNameFunction']}($fileName);
75 75
         }
76 76
         elseif(function_exists($this->options['fileNameFunction'])){
77
-          $fileName = call_user_func($this->options['fileNameFunction'], $fileName);
77
+            $fileName = call_user_func($this->options['fileNameFunction'], $fileName);
78
+        }
78 79
         }
79
-      }
80
-      else {
80
+        else {
81 81
         if(function_exists($this->options['fileNameFunction'])){
82
-          $fileName = call_user_func($this->options['fileNameFunction'], $fileName);
82
+            $fileName = call_user_func($this->options['fileNameFunction'], $fileName);
83
+        }
83 84
         }
84
-      }
85 85
 
86
-      if(!$fileName){
86
+        if(!$fileName){
87 87
         $this->_error('No filename resulting after parsing. Function: ' . $this->options['fileNameFunction']);
88
-      }
88
+        }
89 89
     }
90 90
     return $fileName;
91
-  }
91
+    }
92 92
 
93
-  /**
94
-    * Preform requested target patch checks depending on the unique setting
95
-    *
96
-    * @var string chosen filename target_path
97
-    * @return string of resulting target_path
98
-    * @access private
99
-    */
100
-  function __handleUnique($target_path){
93
+    /**
94
+     * Preform requested target patch checks depending on the unique setting
95
+     *
96
+     * @var string chosen filename target_path
97
+     * @return string of resulting target_path
98
+     * @access private
99
+     */
100
+    function __handleUnique($target_path){
101 101
     if($this->options['unique']){
102
-      $temp_path = substr($target_path, 0, strlen($target_path) - strlen($this->_ext())); //temp path without the ext
103
-      $i=1;
104
-      while(file_exists($target_path)){
102
+        $temp_path = substr($target_path, 0, strlen($target_path) - strlen($this->_ext())); //temp path without the ext
103
+        $i=1;
104
+        while(file_exists($target_path)){
105 105
         $target_path = $temp_path . "-" . $i . $this->_ext();
106 106
         $i++;
107
-      }
108
-		}
107
+        }
108
+        }
109 109
     return $target_path;
110
-  }
110
+    }
111 111
 
112
-  /**
113
-    * processFile will take a file, or use the current file given to it
114
-    * and attempt to save the file to the file system.
115
-    * processFile will check to make sure the file is there, and its type is allowed to be saved.
116
-    *
117
-    * @param file array of uploaded file (optional)
118
-    * @return String | false String of finalFile name saved to the file system or false if unable to save to file system.
119
-    * @access public
120
-    */
121
-  function processFile($file = null){
112
+    /**
113
+     * processFile will take a file, or use the current file given to it
114
+     * and attempt to save the file to the file system.
115
+     * processFile will check to make sure the file is there, and its type is allowed to be saved.
116
+     *
117
+     * @param file array of uploaded file (optional)
118
+     * @return String | false String of finalFile name saved to the file system or false if unable to save to file system.
119
+     * @access public
120
+     */
121
+    function processFile($file = null){
122 122
     $this->setFile($file);
123 123
 
124 124
     //check if we have a file and if we allow the type, return false otherwise.
125 125
     if(!$this->checkFile() || !$this->checkType() || !$this->checkSize()){
126
-      return false;
126
+        return false;
127 127
     }
128 128
 
129 129
     //make sure the file doesn't already exist, if it does, add an itteration to it
@@ -131,143 +131,143 @@  discard block
 block discarded – undo
131 131
     $fileName = $this->__handleFileNameCallback($this->file['name']);
132 132
     //if callback returns false hault the upload
133 133
     if(!$fileName){
134
-      return false;
134
+        return false;
135 135
     }
136 136
     $target_path = $up_dir . DS . $fileName;
137 137
     $target_path = $this->__handleUnique($target_path);
138 138
 
139 139
     //now move the file.
140 140
     if(move_uploaded_file($this->file['tmp_name'], $target_path)){
141
-      $this->finalFile = basename($target_path);
142
-      return $this->finalFile;
141
+        $this->finalFile = basename($target_path);
142
+        return $this->finalFile;
143 143
     }
144 144
     else{
145
-      $this->_error('Unable to save temp file to file system.');
146
-      return false;
145
+        $this->_error('Unable to save temp file to file system.');
146
+        return false;
147
+    }
147 148
     }
148
-  }
149 149
 
150
-  /**
151
-    * setFile will set a this->file if given one.
152
-    *
153
-    * @param file array of uploaded file. (optional)
154
-    * @return void
155
-    */
156
-  function setFile($file = null){
150
+    /**
151
+     * setFile will set a this->file if given one.
152
+     *
153
+     * @param file array of uploaded file. (optional)
154
+     * @return void
155
+     */
156
+    function setFile($file = null){
157 157
     if($file) $this->file = $file;
158
-  }
158
+    }
159 159
 
160
-  /**
161
-    * Returns the extension of the uploaded filename.
162
-    *
163
-    * @return string $extension A filename extension
164
-    * @param file array of uploaded file (optional)
165
-    * @access protected
166
-    */
167
-  function _ext($file = null){
160
+    /**
161
+     * Returns the extension of the uploaded filename.
162
+     *
163
+     * @return string $extension A filename extension
164
+     * @param file array of uploaded file (optional)
165
+     * @access protected
166
+     */
167
+    function _ext($file = null){
168 168
     $this->setFile($file);
169 169
     return strrchr($this->file['name'],".");
170
-  }
170
+    }
171 171
 
172
-  /**
173
-  * Adds error messages to the component
174
-  *
175
-  * @param string $text String of error message to save
176
-  * @return void
177
-  * @access protected
178
-  */
179
-  function _error($text){
172
+    /**
173
+     * Adds error messages to the component
174
+     *
175
+     * @param string $text String of error message to save
176
+     * @return void
177
+     * @access protected
178
+     */
179
+    function _error($text){
180 180
     $this->errors[] = __($text);
181
-  }
181
+    }
182 182
 
183
-  /**
184
-  * Checks if the uploaded type is allowed defined in the allowedTypes
185
-  *
186
-  * @return boolean if type is accepted
187
-  * @param file array of uploaded file (optional)
188
-  * @access public
189
-  */
190
-  function checkType($file = null){
183
+    /**
184
+     * Checks if the uploaded type is allowed defined in the allowedTypes
185
+     *
186
+     * @return boolean if type is accepted
187
+     * @param file array of uploaded file (optional)
188
+     * @access public
189
+     */
190
+    function checkType($file = null){
191 191
     $this->setFile($file);
192 192
     foreach($this->options['allowedTypes'] as $ext => $types){
193
-      if(!is_string($ext)){
193
+        if(!is_string($ext)){
194 194
         $ext = $types;
195
-      }
196
-      if($ext == '*'){
195
+        }
196
+        if($ext == '*'){
197 197
         return true;
198
-      }
198
+        }
199 199
 
200
-      $ext = strtolower('.' . str_replace('.','', $ext));
201
-      $file_ext = strtolower($this->_ext());
202
-      if($file_ext == $ext){
200
+        $ext = strtolower('.' . str_replace('.','', $ext));
201
+        $file_ext = strtolower($this->_ext());
202
+        if($file_ext == $ext){
203 203
         if(is_array($types) && !in_array($this->file['type'], $types)){
204
-          $this->_error("{$this->file['type']} is not an allowed type.");
205
-          return false;
204
+            $this->_error("{$this->file['type']} is not an allowed type.");
205
+            return false;
206 206
         }
207 207
         else {
208
-          return true;
208
+            return true;
209
+        }
209 210
         }
210
-      }
211 211
     }
212 212
 
213 213
     $this->_error("Extension is not allowed.");
214 214
     return false;
215
-  }
215
+    }
216 216
 
217
-  /**
218
-    * Checks if there is a file uploaded
219
-    *
220
-    * @return void
221
-    * @access public
222
-    * @param file array of uploaded file (optional)
223
-    */
224
-  function checkFile($file = null){
217
+    /**
218
+     * Checks if there is a file uploaded
219
+     *
220
+     * @return void
221
+     * @access public
222
+     * @param file array of uploaded file (optional)
223
+     */
224
+    function checkFile($file = null){
225 225
     $this->setFile($file);
226 226
     if($this->hasUpload() && $this->file){
227
-      if(isset($this->file['error']) && $this->file['error'] == UPLOAD_ERR_OK ) {
227
+        if(isset($this->file['error']) && $this->file['error'] == UPLOAD_ERR_OK ) {
228 228
         return true;
229
-      }
230
-      else {
229
+        }
230
+        else {
231 231
         $this->_error($this->uploadErrors[$this->file['error']]);
232
-      }
232
+        }
233 233
     }
234 234
     return false;
235
-  }
235
+    }
236 236
 
237
-  /**
238
-    * Checks if the file uploaded exceeds the maxFileSize setting (if there is onw)
239
-    *
240
-    * @return boolean
241
-    * @access public
242
-    * @param file array of uploaded file (optional)
243
-    */
244
-  function checkSize($file = null){
237
+    /**
238
+     * Checks if the file uploaded exceeds the maxFileSize setting (if there is onw)
239
+     *
240
+     * @return boolean
241
+     * @access public
242
+     * @param file array of uploaded file (optional)
243
+     */
244
+    function checkSize($file = null){
245 245
     $this->setFile($file);
246 246
     if($this->hasUpload() && $this->file){
247
-      if(!$this->options['maxFileSize']){ //We don't want to test maxFileSize
247
+        if(!$this->options['maxFileSize']){ //We don't want to test maxFileSize
248 248
         return true;
249
-      }
250
-      elseif($this->options['maxFileSize'] && $this->file['size'] < $this->options['maxFileSize']){
249
+        }
250
+        elseif($this->options['maxFileSize'] && $this->file['size'] < $this->options['maxFileSize']){
251 251
         return true;
252
-      }
253
-      else {
252
+        }
253
+        else {
254 254
         // $this->_error("File exceeds {$this->options['maxFileSize']} byte limit.");
255
-				$this->_error("File exceeds size limit.");
256
-      }
255
+                $this->_error("File exceeds size limit.");
256
+        }
257 257
     }
258 258
     return false;
259
-  }
259
+    }
260 260
 
261
-  /**
262
-    * removeFile removes a specific file from the uploaded directory
263
-    *
264
-    * @param string $name A reference to the filename to delete from the uploadDirectory
265
-    * @return boolean
266
-    * @access public
267
-    */
268
-  function removeFile($name = null){
261
+    /**
262
+     * removeFile removes a specific file from the uploaded directory
263
+     *
264
+     * @param string $name A reference to the filename to delete from the uploadDirectory
265
+     * @return boolean
266
+     * @access public
267
+     */
268
+    function removeFile($name = null){
269 269
     if(!$name || strpos($name, '://')){
270
-      return false;
270
+        return false;
271 271
     }
272 272
 
273 273
     $up_dir = $this->options['uploadDir'];
@@ -275,70 +275,70 @@  discard block
 block discarded – undo
275 275
 
276 276
     //delete main image -- $name
277 277
     if(@unlink($target_path)){
278
-      return true;
278
+        return true;
279 279
     } else {
280
-      return false;
280
+        return false;
281
+    }
281 282
     }
282
-  }
283 283
 
284
-  /**
285
-    * hasUpload
286
-    *
287
-    * @return boolean true | false depending if a file was actually uploaded.
288
-    * @param file array of uploaded file (optional)
289
-    */
290
-  function hasUpload($file = null){
284
+    /**
285
+     * hasUpload
286
+     *
287
+     * @return boolean true | false depending if a file was actually uploaded.
288
+     * @param file array of uploaded file (optional)
289
+     */
290
+    function hasUpload($file = null){
291 291
     $this->setFile($file);
292 292
     return ($this->_multiArrayKeyExists("tmp_name", $this->file));
293
-  }
293
+    }
294 294
 
295
-  /**
296
-    * @return boolean true if errors were detected.
297
-    */
298
-  function hasErrors(){
295
+    /**
296
+     * @return boolean true if errors were detected.
297
+     */
298
+    function hasErrors(){
299 299
     return count($this->errors);
300
-  }
300
+    }
301 301
 
302
-  /**
303
-    * showErrors itterates through the errors array
304
-    * and returns a concatinated string of errors sepearated by
305
-    * the $sep
306
-    *
307
-    * @param string $sep A seperated defaults to <br />
308
-    * @return string
309
-    * @access public
310
-    */
311
-  function showErrors($sep = " "){
302
+    /**
303
+     * showErrors itterates through the errors array
304
+     * and returns a concatinated string of errors sepearated by
305
+     * the $sep
306
+     *
307
+     * @param string $sep A seperated defaults to <br />
308
+     * @return string
309
+     * @access public
310
+     */
311
+    function showErrors($sep = " "){
312 312
     $retval = "";
313 313
     foreach($this->errors as $error){
314
-      $retval .= "$error $sep";
314
+        $retval .= "$error $sep";
315 315
     }
316 316
     return $retval;
317
-  }
317
+    }
318 318
 
319
-  /**
320
-    * Searches through the $haystack for a $key.
321
-    *
322
-    * @param string $needle String of key to search for in $haystack
323
-    * @param array $haystack Array of which to search for $needle
324
-    * @return boolean true if given key is in an array
325
-    * @access protected
326
-    */
327
-  function _multiArrayKeyExists($needle, $haystack) {
319
+    /**
320
+     * Searches through the $haystack for a $key.
321
+     *
322
+     * @param string $needle String of key to search for in $haystack
323
+     * @param array $haystack Array of which to search for $needle
324
+     * @return boolean true if given key is in an array
325
+     * @access protected
326
+     */
327
+    function _multiArrayKeyExists($needle, $haystack) {
328 328
     if(is_array($haystack)){
329
-      foreach ($haystack as $key=>$value) {
329
+        foreach ($haystack as $key=>$value) {
330 330
         if ($needle===$key && $value) {
331
-          return true;
331
+            return true;
332 332
         }
333 333
         if (is_array($value)) {
334
-          if($this->_multiArrayKeyExists($needle, $value)){
334
+            if($this->_multiArrayKeyExists($needle, $value)){
335 335
             return true;
336
-          }
336
+            }
337
+        }
337 338
         }
338
-      }
339 339
     }
340 340
     return false;
341
-  }
341
+    }
342 342
 
343 343
 }
344 344
 ?>
345 345
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
     */
56 56
   var $finalFile = null;
57 57
 
58
-  function __construct($options = array()){
58
+  function __construct($options = array()) {
59 59
     $this->options = array_merge($this->options, $options);
60 60
   }
61 61
 
@@ -66,25 +66,25 @@  discard block
 block discarded – undo
66 66
     * @return string of resulting filename
67 67
     * @access private
68 68
     */
69
-  function __handleFileNameCallback($fileName){
70
-    if($this->options['fileNameFunction']){
71
-      if($this->options['fileModel']){
69
+  function __handleFileNameCallback($fileName) {
70
+    if ($this->options['fileNameFunction']) {
71
+      if ($this->options['fileModel']) {
72 72
         $Model = ClassRegistry::init($this->options['fileModel']);
73
-        if(method_exists($Model, $this->options['fileNameFunction'])){
73
+        if (method_exists($Model, $this->options['fileNameFunction'])) {
74 74
           $fileName = $Model->{$this->options['fileNameFunction']}($fileName);
75 75
         }
76
-        elseif(function_exists($this->options['fileNameFunction'])){
76
+        elseif (function_exists($this->options['fileNameFunction'])) {
77 77
           $fileName = call_user_func($this->options['fileNameFunction'], $fileName);
78 78
         }
79 79
       }
80 80
       else {
81
-        if(function_exists($this->options['fileNameFunction'])){
81
+        if (function_exists($this->options['fileNameFunction'])) {
82 82
           $fileName = call_user_func($this->options['fileNameFunction'], $fileName);
83 83
         }
84 84
       }
85 85
 
86
-      if(!$fileName){
87
-        $this->_error('No filename resulting after parsing. Function: ' . $this->options['fileNameFunction']);
86
+      if (!$fileName) {
87
+        $this->_error('No filename resulting after parsing. Function: '.$this->options['fileNameFunction']);
88 88
       }
89 89
     }
90 90
     return $fileName;
@@ -97,12 +97,12 @@  discard block
 block discarded – undo
97 97
     * @return string of resulting target_path
98 98
     * @access private
99 99
     */
100
-  function __handleUnique($target_path){
101
-    if($this->options['unique']){
100
+  function __handleUnique($target_path) {
101
+    if ($this->options['unique']) {
102 102
       $temp_path = substr($target_path, 0, strlen($target_path) - strlen($this->_ext())); //temp path without the ext
103
-      $i=1;
104
-      while(file_exists($target_path)){
105
-        $target_path = $temp_path . "-" . $i . $this->_ext();
103
+      $i = 1;
104
+      while (file_exists($target_path)) {
105
+        $target_path = $temp_path."-".$i.$this->_ext();
106 106
         $i++;
107 107
       }
108 108
 		}
@@ -118,11 +118,11 @@  discard block
 block discarded – undo
118 118
     * @return String | false String of finalFile name saved to the file system or false if unable to save to file system.
119 119
     * @access public
120 120
     */
121
-  function processFile($file = null){
121
+  function processFile($file = null) {
122 122
     $this->setFile($file);
123 123
 
124 124
     //check if we have a file and if we allow the type, return false otherwise.
125
-    if(!$this->checkFile() || !$this->checkType() || !$this->checkSize()){
125
+    if (!$this->checkFile() || !$this->checkType() || !$this->checkSize()) {
126 126
       return false;
127 127
     }
128 128
 
@@ -130,18 +130,18 @@  discard block
 block discarded – undo
130 130
     $up_dir = $this->options['uploadDir'];
131 131
     $fileName = $this->__handleFileNameCallback($this->file['name']);
132 132
     //if callback returns false hault the upload
133
-    if(!$fileName){
133
+    if (!$fileName) {
134 134
       return false;
135 135
     }
136
-    $target_path = $up_dir . DS . $fileName;
136
+    $target_path = $up_dir.DS.$fileName;
137 137
     $target_path = $this->__handleUnique($target_path);
138 138
 
139 139
     //now move the file.
140
-    if(move_uploaded_file($this->file['tmp_name'], $target_path)){
140
+    if (move_uploaded_file($this->file['tmp_name'], $target_path)) {
141 141
       $this->finalFile = basename($target_path);
142 142
       return $this->finalFile;
143 143
     }
144
-    else{
144
+    else {
145 145
       $this->_error('Unable to save temp file to file system.');
146 146
       return false;
147 147
     }
@@ -153,8 +153,8 @@  discard block
 block discarded – undo
153 153
     * @param file array of uploaded file. (optional)
154 154
     * @return void
155 155
     */
156
-  function setFile($file = null){
157
-    if($file) $this->file = $file;
156
+  function setFile($file = null) {
157
+    if ($file) $this->file = $file;
158 158
   }
159 159
 
160 160
   /**
@@ -164,9 +164,9 @@  discard block
 block discarded – undo
164 164
     * @param file array of uploaded file (optional)
165 165
     * @access protected
166 166
     */
167
-  function _ext($file = null){
167
+  function _ext($file = null) {
168 168
     $this->setFile($file);
169
-    return strrchr($this->file['name'],".");
169
+    return strrchr($this->file['name'], ".");
170 170
   }
171 171
 
172 172
   /**
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
   * @return void
177 177
   * @access protected
178 178
   */
179
-  function _error($text){
179
+  function _error($text) {
180 180
     $this->errors[] = __($text);
181 181
   }
182 182
 
@@ -187,20 +187,20 @@  discard block
 block discarded – undo
187 187
   * @param file array of uploaded file (optional)
188 188
   * @access public
189 189
   */
190
-  function checkType($file = null){
190
+  function checkType($file = null) {
191 191
     $this->setFile($file);
192
-    foreach($this->options['allowedTypes'] as $ext => $types){
193
-      if(!is_string($ext)){
192
+    foreach ($this->options['allowedTypes'] as $ext => $types) {
193
+      if (!is_string($ext)) {
194 194
         $ext = $types;
195 195
       }
196
-      if($ext == '*'){
196
+      if ($ext == '*') {
197 197
         return true;
198 198
       }
199 199
 
200
-      $ext = strtolower('.' . str_replace('.','', $ext));
200
+      $ext = strtolower('.'.str_replace('.', '', $ext));
201 201
       $file_ext = strtolower($this->_ext());
202
-      if($file_ext == $ext){
203
-        if(is_array($types) && !in_array($this->file['type'], $types)){
202
+      if ($file_ext == $ext) {
203
+        if (is_array($types) && !in_array($this->file['type'], $types)) {
204 204
           $this->_error("{$this->file['type']} is not an allowed type.");
205 205
           return false;
206 206
         }
@@ -221,10 +221,10 @@  discard block
 block discarded – undo
221 221
     * @access public
222 222
     * @param file array of uploaded file (optional)
223 223
     */
224
-  function checkFile($file = null){
224
+  function checkFile($file = null) {
225 225
     $this->setFile($file);
226
-    if($this->hasUpload() && $this->file){
227
-      if(isset($this->file['error']) && $this->file['error'] == UPLOAD_ERR_OK ) {
226
+    if ($this->hasUpload() && $this->file) {
227
+      if (isset($this->file['error']) && $this->file['error'] == UPLOAD_ERR_OK) {
228 228
         return true;
229 229
       }
230 230
       else {
@@ -241,13 +241,13 @@  discard block
 block discarded – undo
241 241
     * @access public
242 242
     * @param file array of uploaded file (optional)
243 243
     */
244
-  function checkSize($file = null){
244
+  function checkSize($file = null) {
245 245
     $this->setFile($file);
246
-    if($this->hasUpload() && $this->file){
247
-      if(!$this->options['maxFileSize']){ //We don't want to test maxFileSize
246
+    if ($this->hasUpload() && $this->file) {
247
+      if (!$this->options['maxFileSize']) { //We don't want to test maxFileSize
248 248
         return true;
249 249
       }
250
-      elseif($this->options['maxFileSize'] && $this->file['size'] < $this->options['maxFileSize']){
250
+      elseif ($this->options['maxFileSize'] && $this->file['size'] < $this->options['maxFileSize']) {
251 251
         return true;
252 252
       }
253 253
       else {
@@ -265,16 +265,16 @@  discard block
 block discarded – undo
265 265
     * @return boolean
266 266
     * @access public
267 267
     */
268
-  function removeFile($name = null){
269
-    if(!$name || strpos($name, '://')){
268
+  function removeFile($name = null) {
269
+    if (!$name || strpos($name, '://')) {
270 270
       return false;
271 271
     }
272 272
 
273 273
     $up_dir = $this->options['uploadDir'];
274
-    $target_path = $up_dir . DS . $name;
274
+    $target_path = $up_dir.DS.$name;
275 275
 
276 276
     //delete main image -- $name
277
-    if(@unlink($target_path)){
277
+    if (@unlink($target_path)) {
278 278
       return true;
279 279
     } else {
280 280
       return false;
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
     * @return boolean true | false depending if a file was actually uploaded.
288 288
     * @param file array of uploaded file (optional)
289 289
     */
290
-  function hasUpload($file = null){
290
+  function hasUpload($file = null) {
291 291
     $this->setFile($file);
292 292
     return ($this->_multiArrayKeyExists("tmp_name", $this->file));
293 293
   }
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
   /**
296 296
     * @return boolean true if errors were detected.
297 297
     */
298
-  function hasErrors(){
298
+  function hasErrors() {
299 299
     return count($this->errors);
300 300
   }
301 301
 
@@ -308,9 +308,9 @@  discard block
 block discarded – undo
308 308
     * @return string
309 309
     * @access public
310 310
     */
311
-  function showErrors($sep = " "){
311
+  function showErrors($sep = " ") {
312 312
     $retval = "";
313
-    foreach($this->errors as $error){
313
+    foreach ($this->errors as $error) {
314 314
       $retval .= "$error $sep";
315 315
     }
316 316
     return $retval;
@@ -325,13 +325,13 @@  discard block
 block discarded – undo
325 325
     * @access protected
326 326
     */
327 327
   function _multiArrayKeyExists($needle, $haystack) {
328
-    if(is_array($haystack)){
328
+    if (is_array($haystack)) {
329 329
       foreach ($haystack as $key=>$value) {
330
-        if ($needle===$key && $value) {
330
+        if ($needle === $key && $value) {
331 331
           return true;
332 332
         }
333 333
         if (is_array($value)) {
334
-          if($this->_multiArrayKeyExists($needle, $value)){
334
+          if ($this->_multiArrayKeyExists($needle, $value)) {
335 335
             return true;
336 336
           }
337 337
         }
Please login to merge, or discard this patch.
Braces   +10 added lines, -15 removed lines patch added patch discarded remove patch
@@ -72,12 +72,10 @@  discard block
 block discarded – undo
72 72
         $Model = ClassRegistry::init($this->options['fileModel']);
73 73
         if(method_exists($Model, $this->options['fileNameFunction'])){
74 74
           $fileName = $Model->{$this->options['fileNameFunction']}($fileName);
75
-        }
76
-        elseif(function_exists($this->options['fileNameFunction'])){
75
+        } elseif(function_exists($this->options['fileNameFunction'])){
77 76
           $fileName = call_user_func($this->options['fileNameFunction'], $fileName);
78 77
         }
79
-      }
80
-      else {
78
+      } else {
81 79
         if(function_exists($this->options['fileNameFunction'])){
82 80
           $fileName = call_user_func($this->options['fileNameFunction'], $fileName);
83 81
         }
@@ -140,8 +138,7 @@  discard block
 block discarded – undo
140 138
     if(move_uploaded_file($this->file['tmp_name'], $target_path)){
141 139
       $this->finalFile = basename($target_path);
142 140
       return $this->finalFile;
143
-    }
144
-    else{
141
+    } else{
145 142
       $this->_error('Unable to save temp file to file system.');
146 143
       return false;
147 144
     }
@@ -154,7 +151,9 @@  discard block
 block discarded – undo
154 151
     * @return void
155 152
     */
156 153
   function setFile($file = null){
157
-    if($file) $this->file = $file;
154
+    if($file) {
155
+        $this->file = $file;
156
+    }
158 157
   }
159 158
 
160 159
   /**
@@ -203,8 +202,7 @@  discard block
 block discarded – undo
203 202
         if(is_array($types) && !in_array($this->file['type'], $types)){
204 203
           $this->_error("{$this->file['type']} is not an allowed type.");
205 204
           return false;
206
-        }
207
-        else {
205
+        } else {
208 206
           return true;
209 207
         }
210 208
       }
@@ -226,8 +224,7 @@  discard block
 block discarded – undo
226 224
     if($this->hasUpload() && $this->file){
227 225
       if(isset($this->file['error']) && $this->file['error'] == UPLOAD_ERR_OK ) {
228 226
         return true;
229
-      }
230
-      else {
227
+      } else {
231 228
         $this->_error($this->uploadErrors[$this->file['error']]);
232 229
       }
233 230
     }
@@ -246,11 +243,9 @@  discard block
 block discarded – undo
246 243
     if($this->hasUpload() && $this->file){
247 244
       if(!$this->options['maxFileSize']){ //We don't want to test maxFileSize
248 245
         return true;
249
-      }
250
-      elseif($this->options['maxFileSize'] && $this->file['size'] < $this->options['maxFileSize']){
246
+      } elseif($this->options['maxFileSize'] && $this->file['size'] < $this->options['maxFileSize']){
251 247
         return true;
252
-      }
253
-      else {
248
+      } else {
254 249
         // $this->_error("File exceeds {$this->options['maxFileSize']} byte limit.");
255 250
 				$this->_error("File exceeds size limit.");
256 251
       }
Please login to merge, or discard this patch.
app/Plugin/FileUpload/View/Helper/FileUploadHelper.php 4 patches
Doc Comments   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
     * @param Array|Int $options takes an array of options passed to the image helper, or an integer representing the width of the image to display
100 100
     *         options: width = 100 (default), if width is set along with autoResize the uploaded image will be resized.
101 101
     * @access public
102
-    * @return mixed html tag, url string, or false if unable to find image.
102
+    * @return string|false html tag, url string, or false if unable to find image.
103 103
     */
104 104
   function image($name, $options = array()){
105 105
     $this->fileName = $name;
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
 		 * Constructor
330 330
 		 *
331 331
 		 * @param [String $imgFile] Image File Name
332
-		 * @return RESIZEIMAGE (Class Object)
332
+		 * @return false|null (Class Object)
333 333
 		 */
334 334
 		function __construct($imgFile=""){
335 335
 			if (!function_exists("imagecreate")){
@@ -356,7 +356,7 @@  discard block
 block discarded – undo
356 356
 		 * Set image file name
357 357
 		 *
358 358
 		 * @param String $imgFile
359
-		 * @return void
359
+		 * @return boolean
360 360
 		 */
361 361
 		function setImage($imgFile){
362 362
 			$this->imgFile=$imgFile;
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
 		 * Resize a image to given width and height and keep it's current width and height ratio
375 375
 		 *
376 376
 		 * @param Number $imgwidth
377
-		 * @param Numnber $imgheight
377
+		 * @param integer $imgheight
378 378
 		 * @param String $newfile
379 379
 		 */
380 380
 		function resize_limitwh($imgwidth,$imgheight,$newfile=NULL){
@@ -394,9 +394,9 @@  discard block
 block discarded – undo
394 394
     /**
395 395
 		 * Resize an image to given percentage.
396 396
 		 *
397
-		 * @param Number $percent
397
+		 * @param integer $percent
398 398
 		 * @param String $newfile
399
-		 * @return Boolean
399
+		 * @return false|null
400 400
 		 */
401 401
 		function resize_percentage($percent=100,$newfile=NULL)	{
402 402
 			$newWidth=($this->imgWidth*$percent)/100;
@@ -407,10 +407,10 @@  discard block
 block discarded – undo
407 407
     /**
408 408
 		 * Resize an image to given X and Y percentage.
409 409
 		 *
410
-		 * @param Number $xpercent
411
-		 * @param Number $ypercent
410
+		 * @param integer $xpercent
411
+		 * @param integer $ypercent
412 412
 		 * @param String $newfile
413
-		 * @return Boolean
413
+		 * @return false|null
414 414
 		 */
415 415
 		function resize_xypercentage($xpercent=100,$ypercent=100,$newfile=NULL)		{
416 416
 			$newWidth=($this->imgWidth*$xpercent)/100;
@@ -421,10 +421,10 @@  discard block
 block discarded – undo
421 421
 		/**
422 422
 		 * Resize an image to given width and height
423 423
 		 *
424
-		 * @param Number $width
425
-		 * @param Number $height
424
+		 * @param integer $width
425
+		 * @param integer $height
426 426
 		 * @param String $newfile
427
-		 * @return Boolean
427
+		 * @return false|null
428 428
 		 */
429 429
 		function resize($width,$height,$newfile=NULL){
430 430
 			if(empty($this->imgFile)){
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
 		 * @param Number $width
484 484
 		 * @param Number $height
485 485
 		 * @param String $newfile
486
-		 * @return Boolean
486
+		 * @return false|null
487 487
 		 */
488 488
 		function _resize($width,$height,$newfile=NULL){
489 489
 			if (!function_exists("imagecreate")){
Please login to merge, or discard this patch.
Indentation   +426 added lines, -426 removed lines patch added patch discarded remove patch
@@ -1,160 +1,160 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 /**
3
-  * FileUPloadHelper is the helper to the component FileUploadComponent.
4
-  * This helper REQUIRES the FileUploadComponent.
5
-  *
6
-  * @author: Nick Baker
7
-  * @version: 6.1.1
8
-  * @email: [email protected]
9
-  * @link: http://www.webtechnick.com/blogs/view/221/CakePHP_File_Upload_Plugin
10
-  *
11
-  * @example
12
-  *      Show an already uploaded image
13
-  *      $fileUpload->image('filename.jpg', array('width' => 250)); //resizes a thumbnail of 'filename.jpg' to 250
14
-  *      $fileUpload->image('filename.jpg', array('width' => 250, 'uploadDir' => 'custom/dir')); //resizes a thumbnail of 'webroot/custom/dir/filename.jpg' to 250
15
-  *
16
-  *      Show the upload field form
17
-  *      $fileUpload->input(); //builds the input form based on your FileUploadComponent defaults
18
-  *           -or-
19
-  *      $fileUpload->input(array('var' => 'fileVar', 'model' => 'Picture')); //customized input form.
20
-  *
21
-  */
3
+ * FileUPloadHelper is the helper to the component FileUploadComponent.
4
+ * This helper REQUIRES the FileUploadComponent.
5
+ *
6
+ * @author: Nick Baker
7
+ * @version: 6.1.1
8
+ * @email: [email protected]
9
+ * @link: http://www.webtechnick.com/blogs/view/221/CakePHP_File_Upload_Plugin
10
+ *
11
+ * @example
12
+ *      Show an already uploaded image
13
+ *      $fileUpload->image('filename.jpg', array('width' => 250)); //resizes a thumbnail of 'filename.jpg' to 250
14
+ *      $fileUpload->image('filename.jpg', array('width' => 250, 'uploadDir' => 'custom/dir')); //resizes a thumbnail of 'webroot/custom/dir/filename.jpg' to 250
15
+ *
16
+ *      Show the upload field form
17
+ *      $fileUpload->input(); //builds the input form based on your FileUploadComponent defaults
18
+ *           -or-
19
+ *      $fileUpload->input(array('var' => 'fileVar', 'model' => 'Picture')); //customized input form.
20
+ *
21
+ */
22 22
 App::import('Config', 'FileUpload.file_upload_settings');
23 23
 class FileUploadHelper extends AppHelper{
24
-  var $helpers = array('Html', 'Form');
25
-
26
-  /**
27
-    * the name of the file passed in.
28
-    */
29
-  var $fileName = NULL;
30
-
31
-  /**
32
-    * Holds the FileUpload component
33
-    */
34
-  var $FileUpload = NULL;
35
-
36
-  /**
37
-    * Counts the number of inputs, for multiple fileUpload inputing.
38
-    */
39
-  var $inputCount = 0;
40
-
41
-  /**
42
-    * Default options for showImage
43
-    *
44
-    * - width: the width of the image to display (0 means no resizing (default))
45
-    * - resizedDir: is the directory in which to save the resized files into (resized by default)
46
-    * - imagePathOnly: will only return the requested image_path (false by default)
47
-    * - autoResize: will resize the file automatically if given a valid width. (true by default)
48
-    * - resizeThumbOnly: will only resize the image down -- not up past the original's size (true by default)
49
-    */
50
-  var $options = array(
24
+    var $helpers = array('Html', 'Form');
25
+
26
+    /**
27
+     * the name of the file passed in.
28
+     */
29
+    var $fileName = NULL;
30
+
31
+    /**
32
+     * Holds the FileUpload component
33
+     */
34
+    var $FileUpload = NULL;
35
+
36
+    /**
37
+     * Counts the number of inputs, for multiple fileUpload inputing.
38
+     */
39
+    var $inputCount = 0;
40
+
41
+    /**
42
+     * Default options for showImage
43
+     *
44
+     * - width: the width of the image to display (0 means no resizing (default))
45
+     * - resizedDir: is the directory in which to save the resized files into (resized by default)
46
+     * - imagePathOnly: will only return the requested image_path (false by default)
47
+     * - autoResize: will resize the file automatically if given a valid width. (true by default)
48
+     * - resizeThumbOnly: will only resize the image down -- not up past the original's size (true by default)
49
+     */
50
+    var $options = array(
51 51
     'width' => 0, //0 means no resizing
52 52
     'resizedDir' => 'resized', // make sure webroot/files/resized is chmod 777
53 53
     'imagePathOnly' => false, //if true, will only return the requested image_path
54 54
     'autoResize' => true, //if true, will resize the file automatically if given a valid width.
55 55
     'resizeThumbOnly' => true //if true, will only resize the image down -- not up past the original's size
56
-  );
57
-
58
-  /**
59
-    * FileUpload Settings set in config/file_upload_settings.php
60
-    */
61
-  var $settings = array();
62
-
63
-  /**
64
-    * Constructor, initiallizes the FileUpload Component
65
-    * and sets the default options.
66
-    */
67
-  function __construct(View $View, $settings = array()){
68
-		parent::__construct($View, $settings);
56
+    );
57
+
58
+    /**
59
+     * FileUpload Settings set in config/file_upload_settings.php
60
+     */
61
+    var $settings = array();
62
+
63
+    /**
64
+     * Constructor, initiallizes the FileUpload Component
65
+     * and sets the default options.
66
+     */
67
+    function __construct(View $View, $settings = array()){
68
+        parent::__construct($View, $settings);
69 69
     $this->FileUploadSettings = new FileUploadSettings;
70 70
 
71 71
     //setup settings
72 72
     $this->settings = array_merge($this->FileUploadSettings->defaults, $this->options);
73
-  }
74
-
75
-  /**
76
-    * Reset the helper to its initial state
77
-    * @access public
78
-    * @return void
79
-    */
80
-  function reset(){
73
+    }
74
+
75
+    /**
76
+     * Reset the helper to its initial state
77
+     * @access public
78
+     * @return void
79
+     */
80
+    function reset(){
81 81
     $this->fileName = null;
82 82
     $this->options = array(
83
-      'width' => 0,
84
-      'resizedDir' => 'resized',
85
-      'imagePathOnly' => false,
86
-      'autoResize' => true,
87
-      'resizeThumbOnly' => true
83
+        'width' => 0,
84
+        'resizedDir' => 'resized',
85
+        'imagePathOnly' => false,
86
+        'autoResize' => true,
87
+        'resizeThumbOnly' => true
88 88
     );
89 89
 
90 90
     //setup settings
91 91
     $this->settings = array_merge($this->FileUploadSettings->defaults, $this->options);
92 92
     unset($this->newImage);
93
-  }
94
-
95
-  /**
96
-    * image takes a file_name or Upload.id and returns the HTML image
97
-    *
98
-    * @param String|Int $name takes a file_name or ID of uploaded file.
99
-    * @param Array|Int $options takes an array of options passed to the image helper, or an integer representing the width of the image to display
100
-    *         options: width = 100 (default), if width is set along with autoResize the uploaded image will be resized.
101
-    * @access public
102
-    * @return mixed html tag, url string, or false if unable to find image.
103
-    */
104
-  function image($name, $options = array()){
93
+    }
94
+
95
+    /**
96
+     * image takes a file_name or Upload.id and returns the HTML image
97
+     *
98
+     * @param String|Int $name takes a file_name or ID of uploaded file.
99
+     * @param Array|Int $options takes an array of options passed to the image helper, or an integer representing the width of the image to display
100
+     *         options: width = 100 (default), if width is set along with autoResize the uploaded image will be resized.
101
+     * @access public
102
+     * @return mixed html tag, url string, or false if unable to find image.
103
+     */
104
+    function image($name, $options = array()){
105 105
     $this->fileName = $name;
106 106
     //options takes in a width as well
107 107
     if(is_int($options)){
108
-      $width = $options;
109
-      $options = array();
110
-      $options['width'] = $width;
108
+        $width = $options;
109
+        $options = array();
110
+        $options['width'] = $width;
111 111
     }
112 112
     $this->options = array_merge($this->options, $options);
113 113
     $this->settings = array_merge($this->settings, $options);
114 114
 
115 115
     $img = false;
116 116
     if(is_string($name)){
117
-      $img = $this->_getImageByName();
117
+        $img = $this->_getImageByName();
118 118
     }
119 119
     elseif(is_int($name)){
120
-      $img = $this->_getImageById();
120
+        $img = $this->_getImageById();
121 121
     }
122 122
 
123 123
     if($img){
124
-      return $img;
124
+        return $img;
125 125
     }
126 126
 
127 127
     // $this->log("Unable to find $img");
128 128
     return false;
129
-  }
130
-
131
-  /**
132
-    * input takes an array of options and display the file browser html input
133
-    * options.
134
-    * @param Array $options of model and file options.  Defaults to default FileUpload component configuration
135
-    * @return String HTML form input element configured for the FileUploadComponent
136
-    * @access public
137
-    */
138
-  function input($options = array()){
129
+    }
130
+
131
+    /**
132
+     * input takes an array of options and display the file browser html input
133
+     * options.
134
+     * @param Array $options of model and file options.  Defaults to default FileUpload component configuration
135
+     * @return String HTML form input element configured for the FileUploadComponent
136
+     * @access public
137
+     */
138
+    function input($options = array()){
139 139
     $options = array_merge(
140
-      array('var' => $this->settings['fileVar'],'model' => $this->settings['fileModel']),
141
-      $options
140
+        array('var' => $this->settings['fileVar'],'model' => $this->settings['fileModel']),
141
+        $options
142 142
     );
143 143
     $configs = $options;
144 144
     if($configs['model']){
145
-      unset($options['model'], $options['var']);
145
+        unset($options['model'], $options['var']);
146 146
 
147
-      return $this->Form->input("{$configs['model']}.".$this->inputCount++.".{$configs['var']}", array_merge(array('type'=>'file'), $options));
147
+        return $this->Form->input("{$configs['model']}.".$this->inputCount++.".{$configs['var']}", array_merge(array('type'=>'file'), $options));
148 148
     }
149 149
     else {
150
-      return "<input type='file' name='data[{$configs['var']}][".$this->inputCount++."]' />";
150
+        return "<input type='file' name='data[{$configs['var']}][".$this->inputCount++."]' />";
151
+    }
151 152
     }
152
-  }
153 153
 
154
-  /**
155
-    * @access protected
156
-    */
157
-  function _getImageById(){
154
+    /**
155
+     * @access protected
156
+     */
157
+    function _getImageById(){
158 158
     App::import('Component', 'FileUpload.FileUpload');
159 159
     $this->FileUpload = new FileUploadComponent;
160 160
 
@@ -164,121 +164,121 @@  discard block
 block discarded – undo
164 164
     $Model->recursive = -1;
165 165
     $upload = $Model->findById($id);
166 166
     if(!empty($upload)){
167
-      $this->fileName = $upload[$this->settings['fileModel']][$this->settings['fields']['name']];
168
-      return $this->_getImageByName();
167
+        $this->fileName = $upload[$this->settings['fileModel']][$this->settings['fields']['name']];
168
+        return $this->_getImageByName();
169 169
     }
170 170
     else{
171
-      return false;
171
+        return false;
172
+    }
172 173
     }
173
-  }
174 174
 
175
-  /**
176
-    * _getFullPath returns the full path of the file name
177
-    * @access protected
178
-    * @return String full path of the file name
179
-    */
180
-  function _getFullPath(){
175
+    /**
176
+     * _getFullPath returns the full path of the file name
177
+     * @access protected
178
+     * @return String full path of the file name
179
+     */
180
+    function _getFullPath(){
181 181
     if($this->_isOutsideSource()){
182
-      return $this->fileName;
182
+        return $this->fileName;
183 183
     }
184 184
     else {
185
-      return WWW_ROOT . $this->_getUploadPath();
185
+        return WWW_ROOT . $this->_getUploadPath();
186
+    }
186 187
     }
187
-  }
188 188
 
189
-  /**
190
-    * _getImagePath returns the image path of the file name
191
-    * @access protected
192
-    * @return String full path of the file name
193
-    */
194
-  function _getImagePath(){
189
+    /**
190
+     * _getImagePath returns the image path of the file name
191
+     * @access protected
192
+     * @return String full path of the file name
193
+     */
194
+    function _getImagePath(){
195 195
     if($this->_isOutsideSource()){
196
-      return $this->fileName;
196
+        return $this->fileName;
197 197
     }
198 198
     else {
199
-      return '/' . $this->_getUploadPath();
199
+        return '/' . $this->_getUploadPath();
200
+    }
200 201
     }
201
-  }
202 202
 
203
-  /**
204
-    * _getUploadPath returns the upload path of all files
205
-    * @access protected
206
-    * @return String upload path of all files
207
-    */
208
-  function _getUploadPath(){
203
+    /**
204
+     * _getUploadPath returns the upload path of all files
205
+     * @access protected
206
+     * @return String upload path of all files
207
+     */
208
+    function _getUploadPath(){
209 209
     return $this->settings['uploadDir'] . '/' . $this->fileName;
210
-  }
211
-
212
-  /**
213
-    * _getExt returns the extension of the filename.
214
-    * @access protected
215
-    * @return String extension of filename
216
-    */
217
-  function _getExt(){
210
+    }
211
+
212
+    /**
213
+     * _getExt returns the extension of the filename.
214
+     * @access protected
215
+     * @return String extension of filename
216
+     */
217
+    function _getExt(){
218 218
     return strrchr($this->fileName,".");
219
-  }
220
-
221
-  /**
222
-    * Get the image by name and width.
223
-    * if width is not specified return full image
224
-    * if width is specified, see if width of image exists
225
-    * if not, make it, save it, and return it.
226
-    * @return String HTML of resized or full image.
227
-    */
228
-  function _getImageByName(){
219
+    }
220
+
221
+    /**
222
+     * Get the image by name and width.
223
+     * if width is not specified return full image
224
+     * if width is specified, see if width of image exists
225
+     * if not, make it, save it, and return it.
226
+     * @return String HTML of resized or full image.
227
+     */
228
+    function _getImageByName(){
229 229
     //only proceed if we actually have the file in question
230 230
     if(!$this->_isOutsideSource() && !file_exists($this->_getFullPath())) return false;
231 231
 
232 232
     //resize if we have resize on, a width, and if it doesn't already exist.
233 233
     if($this->options['autoResize'] && $this->options['width'] > 0 && !file_exists($this->_getResizeNameOrPath($this->_getFullPath()))){
234
-      $this->_resizeImage();
234
+        $this->_resizeImage();
235 235
     }
236 236
     return $this->_htmlImage();
237
-  }
237
+    }
238 238
 
239
-  /**
240
-    * @return String of the resizedpath of a filename or path.
241
-    * @access protected
242
-    */
243
-  function _getResizeNameOrPath($file_name_or_path){
239
+    /**
240
+     * @return String of the resizedpath of a filename or path.
241
+     * @access protected
242
+     */
243
+    function _getResizeNameOrPath($file_name_or_path){
244 244
     $file_name = basename($file_name_or_path);
245 245
     $path = substr($file_name_or_path, 0, strlen($file_name_or_path) - strlen($file_name));
246 246
     $temp_path = substr($file_name,0,strlen($file_name) - strlen($this->_getExt())) . "x" . $this->options['width'] . $this->_getExt();
247 247
     $full_path = (strlen($this->options['resizedDir']) > 0) ? $path . $this->options['resizedDir'] . '/' . $temp_path : $path . $temp_path;
248 248
     return $full_path;
249
-  }
250
-
251
-  /**
252
-    * _resizeImage actually resizes the passed in image.
253
-    * @access protected
254
-    * @return null
255
-    */
256
-  function _resizeImage(){
249
+    }
250
+
251
+    /**
252
+     * _resizeImage actually resizes the passed in image.
253
+     * @access protected
254
+     * @return null
255
+     */
256
+    function _resizeImage(){
257 257
     $this->newImage = new RResizeImage($this->_getFullPath());
258 258
     if($this->newImage->imgWidth > $this->options['width']){
259
-      $this->newImage->resize_limitwh($this->options['width'], 0, $this->_getResizeNameOrPath($this->_getFullPath()));
259
+        $this->newImage->resize_limitwh($this->options['width'], 0, $this->_getResizeNameOrPath($this->_getFullPath()));
260 260
     }
261 261
     else {
262
-      //$this->autoResize = false;
262
+        //$this->autoResize = false;
263
+    }
263 264
     }
264
-  }
265 265
 
266
-  /**
267
-    * _htmlImage returns the atual HTML of the resized/full image asked for
268
-    * @access protected
269
-    * @return String HTML image asked for
270
-    */
271
-  function _htmlImage(){
266
+    /**
267
+     * _htmlImage returns the atual HTML of the resized/full image asked for
268
+     * @access protected
269
+     * @return String HTML image asked for
270
+     */
271
+    function _htmlImage(){
272 272
     if(!$this->_isOutsideSource() && $this->options['autoResize'] && $this->options['width'] > 0){
273
-      if(isset($this->newImage) && $this->newImage->imgWidth && $this->newImage->imgWidth <= $this->options['width']){
273
+        if(isset($this->newImage) && $this->newImage->imgWidth && $this->newImage->imgWidth <= $this->options['width']){
274 274
         $image = $this->_getImagePath();
275
-      }
276
-      else {
275
+        }
276
+        else {
277 277
         $image = $this->_getResizeNameOrPath($this->_getImagePath());
278
-      }
278
+        }
279 279
     }
280 280
     else {
281
-      $image = $this->_getImagePath();
281
+        $image = $this->_getImagePath();
282 282
     }
283 283
 
284 284
     $options = $this->options; //copy
@@ -289,265 +289,265 @@  discard block
 block discarded – undo
289 289
 
290 290
     //return the impage path or image html
291 291
     if($this->options['imagePathOnly']){
292
-      return $image;
292
+        return $image;
293 293
     }
294 294
     else {
295
-      return $this->Html->image($image, $options);
295
+        return $this->Html->image($image, $options);
296
+    }
296 297
     }
297
-  }
298 298
 
299
-  /**
300
-    * _isOutsideSource searches the fileName string for :// to determine if the image source is inside or outside our server
301
-    */
302
-  function _isOutsideSource(){
299
+    /**
300
+     * _isOutsideSource searches the fileName string for :// to determine if the image source is inside or outside our server
301
+     */
302
+    function _isOutsideSource(){
303 303
     return !!strpos($this->fileName, '://');
304
-  }
304
+    }
305 305
 }
306 306
 
307 307
 
308 308
 
309 309
 
310
-	/**
311
-	 * Image Resizer.
312
-	 * @author : Harish Chauhan
313
-	 * @copyright : Freeware
314
-	 * About :This PHP script will resize the given image and can show on the fly or save as image file.
315
-	 *
316
-	 */
317
-	//define("HAR_AUTO_NAME",1);
318
-	Class RResizeImage	{
319
-		var $imgFile="";
320
-		var $imgWidth=0;
321
-		var $imgHeight=0;
322
-		var $imgType="";
323
-		var $imgAttr="";
324
-		var $type=NULL;
325
-		var $_img=NULL;
326
-		var $_error="";
327
-
328
-		/**
329
-		 * Constructor
330
-		 *
331
-		 * @param [String $imgFile] Image File Name
332
-		 * @return RESIZEIMAGE (Class Object)
333
-		 */
334
-		function __construct($imgFile=""){
335
-			if (!function_exists("imagecreate")){
336
-				$this->_error="Error: GD Library is not available.";
337
-				return false;
338
-			}
339
-
340
-			$this->type=Array(1 => 'GIF', 2 => 'JPG', 3 => 'PNG', 4 => 'SWF', 5 => 'PSD', 6 => 'BMP', 7 => 'TIFF', 8 => 'TIFF', 9 => 'JPC', 10 => 'JP2', 11 => 'JPX', 12 => 'JB2', 13 => 'SWC', 14 => 'IFF', 15 => 'WBMP', 16 => 'XBM');
341
-			if(!empty($imgFile)){
342
-				$this->setImage($imgFile);
343
-      }
344
-		}
345
-
346
-		/**
347
-		 * Error occured while resizing the image.
348
-		 *
349
-		 * @return String
350
-		 */
351
-		function error(){
352
-			return $this->_error;
353
-		}
354
-
355
-		/**
356
-		 * Set image file name
357
-		 *
358
-		 * @param String $imgFile
359
-		 * @return void
360
-		 */
361
-		function setImage($imgFile){
362
-			$this->imgFile=$imgFile;
363
-			return $this->_createImage();
364
-		}
310
+    /**
311
+     * Image Resizer.
312
+     * @author : Harish Chauhan
313
+     * @copyright : Freeware
314
+     * About :This PHP script will resize the given image and can show on the fly or save as image file.
315
+     *
316
+     */
317
+    //define("HAR_AUTO_NAME",1);
318
+    Class RResizeImage	{
319
+        var $imgFile="";
320
+        var $imgWidth=0;
321
+        var $imgHeight=0;
322
+        var $imgType="";
323
+        var $imgAttr="";
324
+        var $type=NULL;
325
+        var $_img=NULL;
326
+        var $_error="";
327
+
328
+        /**
329
+         * Constructor
330
+         *
331
+         * @param [String $imgFile] Image File Name
332
+         * @return RESIZEIMAGE (Class Object)
333
+         */
334
+        function __construct($imgFile=""){
335
+            if (!function_exists("imagecreate")){
336
+                $this->_error="Error: GD Library is not available.";
337
+                return false;
338
+            }
339
+
340
+            $this->type=Array(1 => 'GIF', 2 => 'JPG', 3 => 'PNG', 4 => 'SWF', 5 => 'PSD', 6 => 'BMP', 7 => 'TIFF', 8 => 'TIFF', 9 => 'JPC', 10 => 'JP2', 11 => 'JPX', 12 => 'JB2', 13 => 'SWC', 14 => 'IFF', 15 => 'WBMP', 16 => 'XBM');
341
+            if(!empty($imgFile)){
342
+                $this->setImage($imgFile);
343
+        }
344
+        }
345
+
346
+        /**
347
+         * Error occured while resizing the image.
348
+         *
349
+         * @return String
350
+         */
351
+        function error(){
352
+            return $this->_error;
353
+        }
354
+
355
+        /**
356
+         * Set image file name
357
+         *
358
+         * @param String $imgFile
359
+         * @return void
360
+         */
361
+        function setImage($imgFile){
362
+            $this->imgFile=$imgFile;
363
+            return $this->_createImage();
364
+        }
365 365
 
366 366
     /**
367
-		 * @return void
368
-		 */
369
-		function close(){
370
-			return @imagedestroy($this->_img);
371
-		}
372
-
373
-		/**
374
-		 * Resize a image to given width and height and keep it's current width and height ratio
375
-		 *
376
-		 * @param Number $imgwidth
377
-		 * @param Numnber $imgheight
378
-		 * @param String $newfile
379
-		 */
380
-		function resize_limitwh($imgwidth,$imgheight,$newfile=NULL){
381
-			$image_per = 100;
382
-			list($width, $height, $type, $attr) = @getimagesize($this->imgFile);
383
-			if($width > $imgwidth && $imgwidth > 0){
384
-				$image_per = (double)(($imgwidth * 100) / $width);
385
-      }
386
-
387
-			if(floor(($height * $image_per)/100)>$imgheight && $imgheight > 0){
388
-				$image_per = (double)(($imgheight * 100) / $height);
389
-      }
390
-
391
-			$this->resize_percentage($image_per,$newfile);
392
-		}
367
+     * @return void
368
+     */
369
+        function close(){
370
+            return @imagedestroy($this->_img);
371
+        }
372
+
373
+        /**
374
+         * Resize a image to given width and height and keep it's current width and height ratio
375
+         *
376
+         * @param Number $imgwidth
377
+         * @param Numnber $imgheight
378
+         * @param String $newfile
379
+         */
380
+        function resize_limitwh($imgwidth,$imgheight,$newfile=NULL){
381
+            $image_per = 100;
382
+            list($width, $height, $type, $attr) = @getimagesize($this->imgFile);
383
+            if($width > $imgwidth && $imgwidth > 0){
384
+                $image_per = (double)(($imgwidth * 100) / $width);
385
+        }
386
+
387
+            if(floor(($height * $image_per)/100)>$imgheight && $imgheight > 0){
388
+                $image_per = (double)(($imgheight * 100) / $height);
389
+        }
390
+
391
+            $this->resize_percentage($image_per,$newfile);
392
+        }
393 393
 
394 394
     /**
395
-		 * Resize an image to given percentage.
396
-		 *
397
-		 * @param Number $percent
398
-		 * @param String $newfile
399
-		 * @return Boolean
400
-		 */
401
-		function resize_percentage($percent=100,$newfile=NULL)	{
402
-			$newWidth=($this->imgWidth*$percent)/100;
403
-			$newHeight=($this->imgHeight*$percent)/100;
404
-			return $this->resize($newWidth,$newHeight,$newfile);
405
-		}
395
+     * Resize an image to given percentage.
396
+     *
397
+     * @param Number $percent
398
+     * @param String $newfile
399
+     * @return Boolean
400
+     */
401
+        function resize_percentage($percent=100,$newfile=NULL)	{
402
+            $newWidth=($this->imgWidth*$percent)/100;
403
+            $newHeight=($this->imgHeight*$percent)/100;
404
+            return $this->resize($newWidth,$newHeight,$newfile);
405
+        }
406 406
 
407 407
     /**
408
-		 * Resize an image to given X and Y percentage.
409
-		 *
410
-		 * @param Number $xpercent
411
-		 * @param Number $ypercent
412
-		 * @param String $newfile
413
-		 * @return Boolean
414
-		 */
415
-		function resize_xypercentage($xpercent=100,$ypercent=100,$newfile=NULL)		{
416
-			$newWidth=($this->imgWidth*$xpercent)/100;
417
-			$newHeight=($this->imgHeight*$ypercent)/100;
418
-			return $this->resize($newWidth,$newHeight,$newfile);
419
-		}
420
-
421
-		/**
422
-		 * Resize an image to given width and height
423
-		 *
424
-		 * @param Number $width
425
-		 * @param Number $height
426
-		 * @param String $newfile
427
-		 * @return Boolean
428
-		 */
429
-		function resize($width,$height,$newfile=NULL){
430
-			if(empty($this->imgFile)){
431
-				$this->_error="File name is not initialised.";
432
-				return false;
433
-			}
434
-			if($this->imgWidth<=0 || $this->imgHeight<=0){
435
-				$this->_error="Could not resize given image";
436
-				return false;
437
-			}
438
-			if($width<=0)	$width=$this->imgWidth;
439
-			if($height<=0) $height=$this->imgHeight;
440
-
441
-			return $this->_resize($width,$height,$newfile);
442
-		}
443
-
444
-		/**
445
-		 * Get the image attributes
446
-		 * @access Private
447
-		 *
448
-		 */
449
-		function _getImageInfo()
450
-		{
451
-			@list($this->imgWidth,$this->imgHeight,$type,$this->imgAttr)=@getimagesize($this->imgFile);
452
-			$this->imgType=$this->type[$type];
453
-		}
454
-
455
-		/**
456
-		 * Create the image resource
457
-		 * @access Private
458
-		 * @return Boolean
459
-		 */
460
-		function _createImage(){
461
-			$this->_getImageInfo();
462
-			if($this->imgType=='GIF'){
463
-				$this->_img=@imagecreatefromgif($this->imgFile);
464
-			}
465
-			elseif($this->imgType=='JPG'){
466
-				$this->_img=@imagecreatefromjpeg($this->imgFile);
467
-			}
468
-			elseif($this->imgType=='PNG'){
469
-				$this->_img=@imagecreatefrompng($this->imgFile);
470
-			}
471
-
472
-			if(!$this->_img || !@is_resource($this->_img)){
473
-				$this->_error="Error loading ".$this->imgFile;
474
-				return false;
475
-			}
476
-			return true;
477
-		}
478
-
479
-		/**
480
-		 * Function is used to resize the image
481
-		 *
482
-		 * @access Private
483
-		 * @param Number $width
484
-		 * @param Number $height
485
-		 * @param String $newfile
486
-		 * @return Boolean
487
-		 */
488
-		function _resize($width,$height,$newfile=NULL){
489
-			if (!function_exists("imagecreate")){
490
-				$this->_error="Error: GD Library is not available.";
491
-				return false;
492
-			}
493
-
494
-			$newimg=@imagecreatetruecolor($width,$height);
495
-			//imagecolortransparent( $newimg, imagecolorat( $newimg, 0, 0 ) );
496
-
497
-			if($this->imgType=='GIF' || $this->imgType=='PNG')	{
498
-				/** Code to keep transparency of image **/
499
-				$colorcount = imagecolorstotal($this->_img);
500
-				if ($colorcount == 0) $colorcount = 256;
501
-				imagetruecolortopalette($newimg,true,$colorcount);
502
-				imagepalettecopy($newimg,$this->_img);
503
-				$transparentcolor = imagecolortransparent($this->_img);
504
-				imagefill($newimg,0,0,$transparentcolor);
505
-				imagecolortransparent($newimg,$transparentcolor);
506
-			}
507
-
508
-			@imagecopyresampled ( $newimg, $this->_img, 0,0,0,0, $width, $height, $this->imgWidth,$this->imgHeight);
509
-
510
-			if($newfile===1)	{
511
-				if(@preg_match("/\..*+$/",@basename($this->imgFile),$matches)){
512
-			   		$newfile=@substr_replace($this->imgFile,"_har",-@strlen($matches[0]),0);
408
+     * Resize an image to given X and Y percentage.
409
+     *
410
+     * @param Number $xpercent
411
+     * @param Number $ypercent
412
+     * @param String $newfile
413
+     * @return Boolean
414
+     */
415
+        function resize_xypercentage($xpercent=100,$ypercent=100,$newfile=NULL)		{
416
+            $newWidth=($this->imgWidth*$xpercent)/100;
417
+            $newHeight=($this->imgHeight*$ypercent)/100;
418
+            return $this->resize($newWidth,$newHeight,$newfile);
419
+        }
420
+
421
+        /**
422
+         * Resize an image to given width and height
423
+         *
424
+         * @param Number $width
425
+         * @param Number $height
426
+         * @param String $newfile
427
+         * @return Boolean
428
+         */
429
+        function resize($width,$height,$newfile=NULL){
430
+            if(empty($this->imgFile)){
431
+                $this->_error="File name is not initialised.";
432
+                return false;
433
+            }
434
+            if($this->imgWidth<=0 || $this->imgHeight<=0){
435
+                $this->_error="Could not resize given image";
436
+                return false;
437
+            }
438
+            if($width<=0)	$width=$this->imgWidth;
439
+            if($height<=0) $height=$this->imgHeight;
440
+
441
+            return $this->_resize($width,$height,$newfile);
513 442
         }
514
-			}
515
-			elseif(!empty($newfile)){
516
-				if(!@preg_match("/\..*+$/",@basename($newfile))){
517
-					if(@preg_match("/\..*+$/",@basename($this->imgFile),$matches)){
518
-					   $newfile=$newfile.$matches[0];
519
-          }
520
-				}
521
-			}
522
-
523
-			if($this->imgType=='GIF'){
524
-				if(!empty($newfile)){
525
-          @imagegif($newimg,$newfile);
443
+
444
+        /**
445
+         * Get the image attributes
446
+         * @access Private
447
+         *
448
+         */
449
+        function _getImageInfo()
450
+        {
451
+            @list($this->imgWidth,$this->imgHeight,$type,$this->imgAttr)=@getimagesize($this->imgFile);
452
+            $this->imgType=$this->type[$type];
526 453
         }
527
-				else {
528
-					@header("Content-type: image/gif");
529
-					@imagegif($newimg);
530
-				}
531
-			}
532
-			elseif($this->imgType=='JPG'){
533
-				if(!empty($newfile)){
534
-					@imagejpeg($newimg,$newfile);
454
+
455
+        /**
456
+         * Create the image resource
457
+         * @access Private
458
+         * @return Boolean
459
+         */
460
+        function _createImage(){
461
+            $this->_getImageInfo();
462
+            if($this->imgType=='GIF'){
463
+                $this->_img=@imagecreatefromgif($this->imgFile);
464
+            }
465
+            elseif($this->imgType=='JPG'){
466
+                $this->_img=@imagecreatefromjpeg($this->imgFile);
467
+            }
468
+            elseif($this->imgType=='PNG'){
469
+                $this->_img=@imagecreatefrompng($this->imgFile);
470
+            }
471
+
472
+            if(!$this->_img || !@is_resource($this->_img)){
473
+                $this->_error="Error loading ".$this->imgFile;
474
+                return false;
475
+            }
476
+            return true;
477
+        }
478
+
479
+        /**
480
+         * Function is used to resize the image
481
+         *
482
+         * @access Private
483
+         * @param Number $width
484
+         * @param Number $height
485
+         * @param String $newfile
486
+         * @return Boolean
487
+         */
488
+        function _resize($width,$height,$newfile=NULL){
489
+            if (!function_exists("imagecreate")){
490
+                $this->_error="Error: GD Library is not available.";
491
+                return false;
492
+            }
493
+
494
+            $newimg=@imagecreatetruecolor($width,$height);
495
+            //imagecolortransparent( $newimg, imagecolorat( $newimg, 0, 0 ) );
496
+
497
+            if($this->imgType=='GIF' || $this->imgType=='PNG')	{
498
+                /** Code to keep transparency of image **/
499
+                $colorcount = imagecolorstotal($this->_img);
500
+                if ($colorcount == 0) $colorcount = 256;
501
+                imagetruecolortopalette($newimg,true,$colorcount);
502
+                imagepalettecopy($newimg,$this->_img);
503
+                $transparentcolor = imagecolortransparent($this->_img);
504
+                imagefill($newimg,0,0,$transparentcolor);
505
+                imagecolortransparent($newimg,$transparentcolor);
506
+            }
507
+
508
+            @imagecopyresampled ( $newimg, $this->_img, 0,0,0,0, $width, $height, $this->imgWidth,$this->imgHeight);
509
+
510
+            if($newfile===1)	{
511
+                if(@preg_match("/\..*+$/",@basename($this->imgFile),$matches)){
512
+                        $newfile=@substr_replace($this->imgFile,"_har",-@strlen($matches[0]),0);
535 513
         }
536
-				else	{
537
-					@header("Content-type: image/jpeg");
538
-					@imagejpeg($newimg);
539
-				}
540
-			}
541
-			elseif($this->imgType=='PNG'){
542
-				if(!empty($newfile)){
543
-					@imagepng($newimg,$newfile);
514
+            }
515
+            elseif(!empty($newfile)){
516
+                if(!@preg_match("/\..*+$/",@basename($newfile))){
517
+                    if(@preg_match("/\..*+$/",@basename($this->imgFile),$matches)){
518
+                        $newfile=$newfile.$matches[0];
519
+            }
520
+                }
521
+            }
522
+
523
+            if($this->imgType=='GIF'){
524
+                if(!empty($newfile)){
525
+            @imagegif($newimg,$newfile);
544 526
         }
545
-				else{
546
-					@header("Content-type: image/png");
547
-					@imagepng($newimg);
548
-				}
549
-			}
550
-			@imagedestroy($newimg);
551
-		}
552
-	}
527
+                else {
528
+                    @header("Content-type: image/gif");
529
+                    @imagegif($newimg);
530
+                }
531
+            }
532
+            elseif($this->imgType=='JPG'){
533
+                if(!empty($newfile)){
534
+                    @imagejpeg($newimg,$newfile);
535
+        }
536
+                else	{
537
+                    @header("Content-type: image/jpeg");
538
+                    @imagejpeg($newimg);
539
+                }
540
+            }
541
+            elseif($this->imgType=='PNG'){
542
+                if(!empty($newfile)){
543
+                    @imagepng($newimg,$newfile);
544
+        }
545
+                else{
546
+                    @header("Content-type: image/png");
547
+                    @imagepng($newimg);
548
+                }
549
+            }
550
+            @imagedestroy($newimg);
551
+        }
552
+    }
553 553
 ?>
554 554
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +118 added lines, -118 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
   *
21 21
   */
22 22
 App::import('Config', 'FileUpload.file_upload_settings');
23
-class FileUploadHelper extends AppHelper{
23
+class FileUploadHelper extends AppHelper {
24 24
   var $helpers = array('Html', 'Form');
25 25
 
26 26
   /**
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
     * Constructor, initiallizes the FileUpload Component
65 65
     * and sets the default options.
66 66
     */
67
-  function __construct(View $View, $settings = array()){
67
+  function __construct(View $View, $settings = array()) {
68 68
 		parent::__construct($View, $settings);
69 69
     $this->FileUploadSettings = new FileUploadSettings;
70 70
 
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
     * @access public
78 78
     * @return void
79 79
     */
80
-  function reset(){
80
+  function reset() {
81 81
     $this->fileName = null;
82 82
     $this->options = array(
83 83
       'width' => 0,
@@ -101,10 +101,10 @@  discard block
 block discarded – undo
101 101
     * @access public
102 102
     * @return mixed html tag, url string, or false if unable to find image.
103 103
     */
104
-  function image($name, $options = array()){
104
+  function image($name, $options = array()) {
105 105
     $this->fileName = $name;
106 106
     //options takes in a width as well
107
-    if(is_int($options)){
107
+    if (is_int($options)) {
108 108
       $width = $options;
109 109
       $options = array();
110 110
       $options['width'] = $width;
@@ -113,14 +113,14 @@  discard block
 block discarded – undo
113 113
     $this->settings = array_merge($this->settings, $options);
114 114
 
115 115
     $img = false;
116
-    if(is_string($name)){
116
+    if (is_string($name)) {
117 117
       $img = $this->_getImageByName();
118 118
     }
119
-    elseif(is_int($name)){
119
+    elseif (is_int($name)) {
120 120
       $img = $this->_getImageById();
121 121
     }
122 122
 
123
-    if($img){
123
+    if ($img) {
124 124
       return $img;
125 125
     }
126 126
 
@@ -135,13 +135,13 @@  discard block
 block discarded – undo
135 135
     * @return String HTML form input element configured for the FileUploadComponent
136 136
     * @access public
137 137
     */
138
-  function input($options = array()){
138
+  function input($options = array()) {
139 139
     $options = array_merge(
140
-      array('var' => $this->settings['fileVar'],'model' => $this->settings['fileModel']),
140
+      array('var' => $this->settings['fileVar'], 'model' => $this->settings['fileModel']),
141 141
       $options
142 142
     );
143 143
     $configs = $options;
144
-    if($configs['model']){
144
+    if ($configs['model']) {
145 145
       unset($options['model'], $options['var']);
146 146
 
147 147
       return $this->Form->input("{$configs['model']}.".$this->inputCount++.".{$configs['var']}", array_merge(array('type'=>'file'), $options));
@@ -154,20 +154,20 @@  discard block
 block discarded – undo
154 154
   /**
155 155
     * @access protected
156 156
     */
157
-  function _getImageById(){
157
+  function _getImageById() {
158 158
     App::import('Component', 'FileUpload.FileUpload');
159 159
     $this->FileUpload = new FileUploadComponent;
160 160
 
161 161
     $id = $this->fileName;
162 162
     $this->FileUpload->options['fileModel'] = $this->settings['fileModel'];
163
-    $Model =& $this->FileUpload->getModel();
163
+    $Model = & $this->FileUpload->getModel();
164 164
     $Model->recursive = -1;
165 165
     $upload = $Model->findById($id);
166
-    if(!empty($upload)){
166
+    if (!empty($upload)) {
167 167
       $this->fileName = $upload[$this->settings['fileModel']][$this->settings['fields']['name']];
168 168
       return $this->_getImageByName();
169 169
     }
170
-    else{
170
+    else {
171 171
       return false;
172 172
     }
173 173
   }
@@ -177,12 +177,12 @@  discard block
 block discarded – undo
177 177
     * @access protected
178 178
     * @return String full path of the file name
179 179
     */
180
-  function _getFullPath(){
181
-    if($this->_isOutsideSource()){
180
+  function _getFullPath() {
181
+    if ($this->_isOutsideSource()) {
182 182
       return $this->fileName;
183 183
     }
184 184
     else {
185
-      return WWW_ROOT . $this->_getUploadPath();
185
+      return WWW_ROOT.$this->_getUploadPath();
186 186
     }
187 187
   }
188 188
 
@@ -191,12 +191,12 @@  discard block
 block discarded – undo
191 191
     * @access protected
192 192
     * @return String full path of the file name
193 193
     */
194
-  function _getImagePath(){
195
-    if($this->_isOutsideSource()){
194
+  function _getImagePath() {
195
+    if ($this->_isOutsideSource()) {
196 196
       return $this->fileName;
197 197
     }
198 198
     else {
199
-      return '/' . $this->_getUploadPath();
199
+      return '/'.$this->_getUploadPath();
200 200
     }
201 201
   }
202 202
 
@@ -205,8 +205,8 @@  discard block
 block discarded – undo
205 205
     * @access protected
206 206
     * @return String upload path of all files
207 207
     */
208
-  function _getUploadPath(){
209
-    return $this->settings['uploadDir'] . '/' . $this->fileName;
208
+  function _getUploadPath() {
209
+    return $this->settings['uploadDir'].'/'.$this->fileName;
210 210
   }
211 211
 
212 212
   /**
@@ -214,8 +214,8 @@  discard block
 block discarded – undo
214 214
     * @access protected
215 215
     * @return String extension of filename
216 216
     */
217
-  function _getExt(){
218
-    return strrchr($this->fileName,".");
217
+  function _getExt() {
218
+    return strrchr($this->fileName, ".");
219 219
   }
220 220
 
221 221
   /**
@@ -225,12 +225,12 @@  discard block
 block discarded – undo
225 225
     * if not, make it, save it, and return it.
226 226
     * @return String HTML of resized or full image.
227 227
     */
228
-  function _getImageByName(){
228
+  function _getImageByName() {
229 229
     //only proceed if we actually have the file in question
230
-    if(!$this->_isOutsideSource() && !file_exists($this->_getFullPath())) return false;
230
+    if (!$this->_isOutsideSource() && !file_exists($this->_getFullPath())) return false;
231 231
 
232 232
     //resize if we have resize on, a width, and if it doesn't already exist.
233
-    if($this->options['autoResize'] && $this->options['width'] > 0 && !file_exists($this->_getResizeNameOrPath($this->_getFullPath()))){
233
+    if ($this->options['autoResize'] && $this->options['width'] > 0 && !file_exists($this->_getResizeNameOrPath($this->_getFullPath()))) {
234 234
       $this->_resizeImage();
235 235
     }
236 236
     return $this->_htmlImage();
@@ -240,11 +240,11 @@  discard block
 block discarded – undo
240 240
     * @return String of the resizedpath of a filename or path.
241 241
     * @access protected
242 242
     */
243
-  function _getResizeNameOrPath($file_name_or_path){
243
+  function _getResizeNameOrPath($file_name_or_path) {
244 244
     $file_name = basename($file_name_or_path);
245 245
     $path = substr($file_name_or_path, 0, strlen($file_name_or_path) - strlen($file_name));
246
-    $temp_path = substr($file_name,0,strlen($file_name) - strlen($this->_getExt())) . "x" . $this->options['width'] . $this->_getExt();
247
-    $full_path = (strlen($this->options['resizedDir']) > 0) ? $path . $this->options['resizedDir'] . '/' . $temp_path : $path . $temp_path;
246
+    $temp_path = substr($file_name, 0, strlen($file_name) - strlen($this->_getExt()))."x".$this->options['width'].$this->_getExt();
247
+    $full_path = (strlen($this->options['resizedDir']) > 0) ? $path.$this->options['resizedDir'].'/'.$temp_path : $path.$temp_path;
248 248
     return $full_path;
249 249
   }
250 250
 
@@ -253,9 +253,9 @@  discard block
 block discarded – undo
253 253
     * @access protected
254 254
     * @return null
255 255
     */
256
-  function _resizeImage(){
256
+  function _resizeImage() {
257 257
     $this->newImage = new RResizeImage($this->_getFullPath());
258
-    if($this->newImage->imgWidth > $this->options['width']){
258
+    if ($this->newImage->imgWidth > $this->options['width']) {
259 259
       $this->newImage->resize_limitwh($this->options['width'], 0, $this->_getResizeNameOrPath($this->_getFullPath()));
260 260
     }
261 261
     else {
@@ -268,9 +268,9 @@  discard block
 block discarded – undo
268 268
     * @access protected
269 269
     * @return String HTML image asked for
270 270
     */
271
-  function _htmlImage(){
272
-    if(!$this->_isOutsideSource() && $this->options['autoResize'] && $this->options['width'] > 0){
273
-      if(isset($this->newImage) && $this->newImage->imgWidth && $this->newImage->imgWidth <= $this->options['width']){
271
+  function _htmlImage() {
272
+    if (!$this->_isOutsideSource() && $this->options['autoResize'] && $this->options['width'] > 0) {
273
+      if (isset($this->newImage) && $this->newImage->imgWidth && $this->newImage->imgWidth <= $this->options['width']) {
274 274
         $image = $this->_getImagePath();
275 275
       }
276 276
       else {
@@ -285,10 +285,10 @@  discard block
 block discarded – undo
285 285
     //unset the default options
286 286
     unset($options['resizedDir'], $options['uploadDir'], $options['imagePathOnly'], $options['autoResize'], $options['resizeThumbOnly']);
287 287
     //unset width only if we're not an outsourced image, we have resize turned on, or we don't have a width to begin with.
288
-    if(!$this->_isOutsideSource() && ($this->options['resizeThumbOnly'] || !$options['width'])) unset($options['width']);
288
+    if (!$this->_isOutsideSource() && ($this->options['resizeThumbOnly'] || !$options['width'])) unset($options['width']);
289 289
 
290 290
     //return the impage path or image html
291
-    if($this->options['imagePathOnly']){
291
+    if ($this->options['imagePathOnly']) {
292 292
       return $image;
293 293
     }
294 294
     else {
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
   /**
300 300
     * _isOutsideSource searches the fileName string for :// to determine if the image source is inside or outside our server
301 301
     */
302
-  function _isOutsideSource(){
302
+  function _isOutsideSource() {
303 303
     return !!strpos($this->fileName, '://');
304 304
   }
305 305
 }
@@ -315,15 +315,15 @@  discard block
 block discarded – undo
315 315
 	 *
316 316
 	 */
317 317
 	//define("HAR_AUTO_NAME",1);
318
-	Class RResizeImage	{
319
-		var $imgFile="";
320
-		var $imgWidth=0;
321
-		var $imgHeight=0;
322
-		var $imgType="";
323
-		var $imgAttr="";
324
-		var $type=NULL;
325
-		var $_img=NULL;
326
-		var $_error="";
318
+	Class RResizeImage {
319
+		var $imgFile = "";
320
+		var $imgWidth = 0;
321
+		var $imgHeight = 0;
322
+		var $imgType = "";
323
+		var $imgAttr = "";
324
+		var $type = NULL;
325
+		var $_img = NULL;
326
+		var $_error = "";
327 327
 
328 328
 		/**
329 329
 		 * Constructor
@@ -331,14 +331,14 @@  discard block
 block discarded – undo
331 331
 		 * @param [String $imgFile] Image File Name
332 332
 		 * @return RESIZEIMAGE (Class Object)
333 333
 		 */
334
-		function __construct($imgFile=""){
335
-			if (!function_exists("imagecreate")){
336
-				$this->_error="Error: GD Library is not available.";
334
+		function __construct($imgFile = "") {
335
+			if (!function_exists("imagecreate")) {
336
+				$this->_error = "Error: GD Library is not available.";
337 337
 				return false;
338 338
 			}
339 339
 
340
-			$this->type=Array(1 => 'GIF', 2 => 'JPG', 3 => 'PNG', 4 => 'SWF', 5 => 'PSD', 6 => 'BMP', 7 => 'TIFF', 8 => 'TIFF', 9 => 'JPC', 10 => 'JP2', 11 => 'JPX', 12 => 'JB2', 13 => 'SWC', 14 => 'IFF', 15 => 'WBMP', 16 => 'XBM');
341
-			if(!empty($imgFile)){
340
+			$this->type = Array(1 => 'GIF', 2 => 'JPG', 3 => 'PNG', 4 => 'SWF', 5 => 'PSD', 6 => 'BMP', 7 => 'TIFF', 8 => 'TIFF', 9 => 'JPC', 10 => 'JP2', 11 => 'JPX', 12 => 'JB2', 13 => 'SWC', 14 => 'IFF', 15 => 'WBMP', 16 => 'XBM');
341
+			if (!empty($imgFile)) {
342 342
 				$this->setImage($imgFile);
343 343
       }
344 344
 		}
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
 		 *
349 349
 		 * @return String
350 350
 		 */
351
-		function error(){
351
+		function error() {
352 352
 			return $this->_error;
353 353
 		}
354 354
 
@@ -358,15 +358,15 @@  discard block
 block discarded – undo
358 358
 		 * @param String $imgFile
359 359
 		 * @return void
360 360
 		 */
361
-		function setImage($imgFile){
362
-			$this->imgFile=$imgFile;
361
+		function setImage($imgFile) {
362
+			$this->imgFile = $imgFile;
363 363
 			return $this->_createImage();
364 364
 		}
365 365
 
366 366
     /**
367 367
 		 * @return void
368 368
 		 */
369
-		function close(){
369
+		function close() {
370 370
 			return @imagedestroy($this->_img);
371 371
 		}
372 372
 
@@ -377,18 +377,18 @@  discard block
 block discarded – undo
377 377
 		 * @param Numnber $imgheight
378 378
 		 * @param String $newfile
379 379
 		 */
380
-		function resize_limitwh($imgwidth,$imgheight,$newfile=NULL){
380
+		function resize_limitwh($imgwidth, $imgheight, $newfile = NULL) {
381 381
 			$image_per = 100;
382 382
 			list($width, $height, $type, $attr) = @getimagesize($this->imgFile);
383
-			if($width > $imgwidth && $imgwidth > 0){
384
-				$image_per = (double)(($imgwidth * 100) / $width);
383
+			if ($width > $imgwidth && $imgwidth > 0) {
384
+				$image_per = (double) (($imgwidth * 100) / $width);
385 385
       }
386 386
 
387
-			if(floor(($height * $image_per)/100)>$imgheight && $imgheight > 0){
388
-				$image_per = (double)(($imgheight * 100) / $height);
387
+			if (floor(($height * $image_per) / 100) > $imgheight && $imgheight > 0) {
388
+				$image_per = (double) (($imgheight * 100) / $height);
389 389
       }
390 390
 
391
-			$this->resize_percentage($image_per,$newfile);
391
+			$this->resize_percentage($image_per, $newfile);
392 392
 		}
393 393
 
394 394
     /**
@@ -398,10 +398,10 @@  discard block
 block discarded – undo
398 398
 		 * @param String $newfile
399 399
 		 * @return Boolean
400 400
 		 */
401
-		function resize_percentage($percent=100,$newfile=NULL)	{
402
-			$newWidth=($this->imgWidth*$percent)/100;
403
-			$newHeight=($this->imgHeight*$percent)/100;
404
-			return $this->resize($newWidth,$newHeight,$newfile);
401
+		function resize_percentage($percent = 100, $newfile = NULL) {
402
+			$newWidth = ($this->imgWidth * $percent) / 100;
403
+			$newHeight = ($this->imgHeight * $percent) / 100;
404
+			return $this->resize($newWidth, $newHeight, $newfile);
405 405
 		}
406 406
 
407 407
     /**
@@ -412,10 +412,10 @@  discard block
 block discarded – undo
412 412
 		 * @param String $newfile
413 413
 		 * @return Boolean
414 414
 		 */
415
-		function resize_xypercentage($xpercent=100,$ypercent=100,$newfile=NULL)		{
416
-			$newWidth=($this->imgWidth*$xpercent)/100;
417
-			$newHeight=($this->imgHeight*$ypercent)/100;
418
-			return $this->resize($newWidth,$newHeight,$newfile);
415
+		function resize_xypercentage($xpercent = 100, $ypercent = 100, $newfile = NULL) {
416
+			$newWidth = ($this->imgWidth * $xpercent) / 100;
417
+			$newHeight = ($this->imgHeight * $ypercent) / 100;
418
+			return $this->resize($newWidth, $newHeight, $newfile);
419 419
 		}
420 420
 
421 421
 		/**
@@ -426,19 +426,19 @@  discard block
 block discarded – undo
426 426
 		 * @param String $newfile
427 427
 		 * @return Boolean
428 428
 		 */
429
-		function resize($width,$height,$newfile=NULL){
430
-			if(empty($this->imgFile)){
431
-				$this->_error="File name is not initialised.";
429
+		function resize($width, $height, $newfile = NULL) {
430
+			if (empty($this->imgFile)) {
431
+				$this->_error = "File name is not initialised.";
432 432
 				return false;
433 433
 			}
434
-			if($this->imgWidth<=0 || $this->imgHeight<=0){
435
-				$this->_error="Could not resize given image";
434
+			if ($this->imgWidth <= 0 || $this->imgHeight <= 0) {
435
+				$this->_error = "Could not resize given image";
436 436
 				return false;
437 437
 			}
438
-			if($width<=0)	$width=$this->imgWidth;
439
-			if($height<=0) $height=$this->imgHeight;
438
+			if ($width <= 0)	$width = $this->imgWidth;
439
+			if ($height <= 0) $height = $this->imgHeight;
440 440
 
441
-			return $this->_resize($width,$height,$newfile);
441
+			return $this->_resize($width, $height, $newfile);
442 442
 		}
443 443
 
444 444
 		/**
@@ -448,8 +448,8 @@  discard block
 block discarded – undo
448 448
 		 */
449 449
 		function _getImageInfo()
450 450
 		{
451
-			@list($this->imgWidth,$this->imgHeight,$type,$this->imgAttr)=@getimagesize($this->imgFile);
452
-			$this->imgType=$this->type[$type];
451
+			@list($this->imgWidth, $this->imgHeight, $type, $this->imgAttr) = @getimagesize($this->imgFile);
452
+			$this->imgType = $this->type[$type];
453 453
 		}
454 454
 
455 455
 		/**
@@ -457,20 +457,20 @@  discard block
 block discarded – undo
457 457
 		 * @access Private
458 458
 		 * @return Boolean
459 459
 		 */
460
-		function _createImage(){
460
+		function _createImage() {
461 461
 			$this->_getImageInfo();
462
-			if($this->imgType=='GIF'){
463
-				$this->_img=@imagecreatefromgif($this->imgFile);
462
+			if ($this->imgType == 'GIF') {
463
+				$this->_img = @imagecreatefromgif($this->imgFile);
464 464
 			}
465
-			elseif($this->imgType=='JPG'){
466
-				$this->_img=@imagecreatefromjpeg($this->imgFile);
465
+			elseif ($this->imgType == 'JPG') {
466
+				$this->_img = @imagecreatefromjpeg($this->imgFile);
467 467
 			}
468
-			elseif($this->imgType=='PNG'){
469
-				$this->_img=@imagecreatefrompng($this->imgFile);
468
+			elseif ($this->imgType == 'PNG') {
469
+				$this->_img = @imagecreatefrompng($this->imgFile);
470 470
 			}
471 471
 
472
-			if(!$this->_img || !@is_resource($this->_img)){
473
-				$this->_error="Error loading ".$this->imgFile;
472
+			if (!$this->_img || !@is_resource($this->_img)) {
473
+				$this->_error = "Error loading ".$this->imgFile;
474 474
 				return false;
475 475
 			}
476 476
 			return true;
@@ -485,64 +485,64 @@  discard block
 block discarded – undo
485 485
 		 * @param String $newfile
486 486
 		 * @return Boolean
487 487
 		 */
488
-		function _resize($width,$height,$newfile=NULL){
489
-			if (!function_exists("imagecreate")){
490
-				$this->_error="Error: GD Library is not available.";
488
+		function _resize($width, $height, $newfile = NULL) {
489
+			if (!function_exists("imagecreate")) {
490
+				$this->_error = "Error: GD Library is not available.";
491 491
 				return false;
492 492
 			}
493 493
 
494
-			$newimg=@imagecreatetruecolor($width,$height);
494
+			$newimg = @imagecreatetruecolor($width, $height);
495 495
 			//imagecolortransparent( $newimg, imagecolorat( $newimg, 0, 0 ) );
496 496
 
497
-			if($this->imgType=='GIF' || $this->imgType=='PNG')	{
497
+			if ($this->imgType == 'GIF' || $this->imgType == 'PNG') {
498 498
 				/** Code to keep transparency of image **/
499 499
 				$colorcount = imagecolorstotal($this->_img);
500 500
 				if ($colorcount == 0) $colorcount = 256;
501
-				imagetruecolortopalette($newimg,true,$colorcount);
502
-				imagepalettecopy($newimg,$this->_img);
501
+				imagetruecolortopalette($newimg, true, $colorcount);
502
+				imagepalettecopy($newimg, $this->_img);
503 503
 				$transparentcolor = imagecolortransparent($this->_img);
504
-				imagefill($newimg,0,0,$transparentcolor);
505
-				imagecolortransparent($newimg,$transparentcolor);
504
+				imagefill($newimg, 0, 0, $transparentcolor);
505
+				imagecolortransparent($newimg, $transparentcolor);
506 506
 			}
507 507
 
508
-			@imagecopyresampled ( $newimg, $this->_img, 0,0,0,0, $width, $height, $this->imgWidth,$this->imgHeight);
508
+			@imagecopyresampled($newimg, $this->_img, 0, 0, 0, 0, $width, $height, $this->imgWidth, $this->imgHeight);
509 509
 
510
-			if($newfile===1)	{
511
-				if(@preg_match("/\..*+$/",@basename($this->imgFile),$matches)){
512
-			   		$newfile=@substr_replace($this->imgFile,"_har",-@strlen($matches[0]),0);
510
+			if ($newfile === 1) {
511
+				if (@preg_match("/\..*+$/", @basename($this->imgFile), $matches)) {
512
+			   		$newfile = @substr_replace($this->imgFile, "_har", -@strlen($matches[0]), 0);
513 513
         }
514 514
 			}
515
-			elseif(!empty($newfile)){
516
-				if(!@preg_match("/\..*+$/",@basename($newfile))){
517
-					if(@preg_match("/\..*+$/",@basename($this->imgFile),$matches)){
518
-					   $newfile=$newfile.$matches[0];
515
+			elseif (!empty($newfile)) {
516
+				if (!@preg_match("/\..*+$/", @basename($newfile))) {
517
+					if (@preg_match("/\..*+$/", @basename($this->imgFile), $matches)) {
518
+					   $newfile = $newfile.$matches[0];
519 519
           }
520 520
 				}
521 521
 			}
522 522
 
523
-			if($this->imgType=='GIF'){
524
-				if(!empty($newfile)){
525
-          @imagegif($newimg,$newfile);
523
+			if ($this->imgType == 'GIF') {
524
+				if (!empty($newfile)) {
525
+          @imagegif($newimg, $newfile);
526 526
         }
527 527
 				else {
528 528
 					@header("Content-type: image/gif");
529 529
 					@imagegif($newimg);
530 530
 				}
531 531
 			}
532
-			elseif($this->imgType=='JPG'){
533
-				if(!empty($newfile)){
534
-					@imagejpeg($newimg,$newfile);
532
+			elseif ($this->imgType == 'JPG') {
533
+				if (!empty($newfile)) {
534
+					@imagejpeg($newimg, $newfile);
535 535
         }
536
-				else	{
536
+				else {
537 537
 					@header("Content-type: image/jpeg");
538 538
 					@imagejpeg($newimg);
539 539
 				}
540 540
 			}
541
-			elseif($this->imgType=='PNG'){
542
-				if(!empty($newfile)){
543
-					@imagepng($newimg,$newfile);
541
+			elseif ($this->imgType == 'PNG') {
542
+				if (!empty($newfile)) {
543
+					@imagepng($newimg, $newfile);
544 544
         }
545
-				else{
545
+				else {
546 546
 					@header("Content-type: image/png");
547 547
 					@imagepng($newimg);
548 548
 				}
Please login to merge, or discard this patch.
Braces   +32 added lines, -39 removed lines patch added patch discarded remove patch
@@ -115,8 +115,7 @@  discard block
 block discarded – undo
115 115
     $img = false;
116 116
     if(is_string($name)){
117 117
       $img = $this->_getImageByName();
118
-    }
119
-    elseif(is_int($name)){
118
+    } elseif(is_int($name)){
120 119
       $img = $this->_getImageById();
121 120
     }
122 121
 
@@ -145,8 +144,7 @@  discard block
 block discarded – undo
145 144
       unset($options['model'], $options['var']);
146 145
 
147 146
       return $this->Form->input("{$configs['model']}.".$this->inputCount++.".{$configs['var']}", array_merge(array('type'=>'file'), $options));
148
-    }
149
-    else {
147
+    } else {
150 148
       return "<input type='file' name='data[{$configs['var']}][".$this->inputCount++."]' />";
151 149
     }
152 150
   }
@@ -166,8 +164,7 @@  discard block
 block discarded – undo
166 164
     if(!empty($upload)){
167 165
       $this->fileName = $upload[$this->settings['fileModel']][$this->settings['fields']['name']];
168 166
       return $this->_getImageByName();
169
-    }
170
-    else{
167
+    } else{
171 168
       return false;
172 169
     }
173 170
   }
@@ -180,8 +177,7 @@  discard block
 block discarded – undo
180 177
   function _getFullPath(){
181 178
     if($this->_isOutsideSource()){
182 179
       return $this->fileName;
183
-    }
184
-    else {
180
+    } else {
185 181
       return WWW_ROOT . $this->_getUploadPath();
186 182
     }
187 183
   }
@@ -194,8 +190,7 @@  discard block
 block discarded – undo
194 190
   function _getImagePath(){
195 191
     if($this->_isOutsideSource()){
196 192
       return $this->fileName;
197
-    }
198
-    else {
193
+    } else {
199 194
       return '/' . $this->_getUploadPath();
200 195
     }
201 196
   }
@@ -227,7 +222,9 @@  discard block
 block discarded – undo
227 222
     */
228 223
   function _getImageByName(){
229 224
     //only proceed if we actually have the file in question
230
-    if(!$this->_isOutsideSource() && !file_exists($this->_getFullPath())) return false;
225
+    if(!$this->_isOutsideSource() && !file_exists($this->_getFullPath())) {
226
+        return false;
227
+    }
231 228
 
232 229
     //resize if we have resize on, a width, and if it doesn't already exist.
233 230
     if($this->options['autoResize'] && $this->options['width'] > 0 && !file_exists($this->_getResizeNameOrPath($this->_getFullPath()))){
@@ -257,8 +254,7 @@  discard block
 block discarded – undo
257 254
     $this->newImage = new RResizeImage($this->_getFullPath());
258 255
     if($this->newImage->imgWidth > $this->options['width']){
259 256
       $this->newImage->resize_limitwh($this->options['width'], 0, $this->_getResizeNameOrPath($this->_getFullPath()));
260
-    }
261
-    else {
257
+    } else {
262 258
       //$this->autoResize = false;
263 259
     }
264 260
   }
@@ -272,12 +268,10 @@  discard block
 block discarded – undo
272 268
     if(!$this->_isOutsideSource() && $this->options['autoResize'] && $this->options['width'] > 0){
273 269
       if(isset($this->newImage) && $this->newImage->imgWidth && $this->newImage->imgWidth <= $this->options['width']){
274 270
         $image = $this->_getImagePath();
275
-      }
276
-      else {
271
+      } else {
277 272
         $image = $this->_getResizeNameOrPath($this->_getImagePath());
278 273
       }
279
-    }
280
-    else {
274
+    } else {
281 275
       $image = $this->_getImagePath();
282 276
     }
283 277
 
@@ -285,13 +279,14 @@  discard block
 block discarded – undo
285 279
     //unset the default options
286 280
     unset($options['resizedDir'], $options['uploadDir'], $options['imagePathOnly'], $options['autoResize'], $options['resizeThumbOnly']);
287 281
     //unset width only if we're not an outsourced image, we have resize turned on, or we don't have a width to begin with.
288
-    if(!$this->_isOutsideSource() && ($this->options['resizeThumbOnly'] || !$options['width'])) unset($options['width']);
282
+    if(!$this->_isOutsideSource() && ($this->options['resizeThumbOnly'] || !$options['width'])) {
283
+        unset($options['width']);
284
+    }
289 285
 
290 286
     //return the impage path or image html
291 287
     if($this->options['imagePathOnly']){
292 288
       return $image;
293
-    }
294
-    else {
289
+    } else {
295 290
       return $this->Html->image($image, $options);
296 291
     }
297 292
   }
@@ -435,8 +430,12 @@  discard block
 block discarded – undo
435 430
 				$this->_error="Could not resize given image";
436 431
 				return false;
437 432
 			}
438
-			if($width<=0)	$width=$this->imgWidth;
439
-			if($height<=0) $height=$this->imgHeight;
433
+			if($width<=0) {
434
+			    $width=$this->imgWidth;
435
+			}
436
+			if($height<=0) {
437
+			    $height=$this->imgHeight;
438
+			}
440 439
 
441 440
 			return $this->_resize($width,$height,$newfile);
442 441
 		}
@@ -461,11 +460,9 @@  discard block
 block discarded – undo
461 460
 			$this->_getImageInfo();
462 461
 			if($this->imgType=='GIF'){
463 462
 				$this->_img=@imagecreatefromgif($this->imgFile);
464
-			}
465
-			elseif($this->imgType=='JPG'){
463
+			} elseif($this->imgType=='JPG'){
466 464
 				$this->_img=@imagecreatefromjpeg($this->imgFile);
467
-			}
468
-			elseif($this->imgType=='PNG'){
465
+			} elseif($this->imgType=='PNG'){
469 466
 				$this->_img=@imagecreatefrompng($this->imgFile);
470 467
 			}
471 468
 
@@ -497,7 +494,9 @@  discard block
 block discarded – undo
497 494
 			if($this->imgType=='GIF' || $this->imgType=='PNG')	{
498 495
 				/** Code to keep transparency of image **/
499 496
 				$colorcount = imagecolorstotal($this->_img);
500
-				if ($colorcount == 0) $colorcount = 256;
497
+				if ($colorcount == 0) {
498
+				    $colorcount = 256;
499
+				}
501 500
 				imagetruecolortopalette($newimg,true,$colorcount);
502 501
 				imagepalettecopy($newimg,$this->_img);
503 502
 				$transparentcolor = imagecolortransparent($this->_img);
@@ -511,8 +510,7 @@  discard block
 block discarded – undo
511 510
 				if(@preg_match("/\..*+$/",@basename($this->imgFile),$matches)){
512 511
 			   		$newfile=@substr_replace($this->imgFile,"_har",-@strlen($matches[0]),0);
513 512
         }
514
-			}
515
-			elseif(!empty($newfile)){
513
+			} elseif(!empty($newfile)){
516 514
 				if(!@preg_match("/\..*+$/",@basename($newfile))){
517 515
 					if(@preg_match("/\..*+$/",@basename($this->imgFile),$matches)){
518 516
 					   $newfile=$newfile.$matches[0];
@@ -523,26 +521,21 @@  discard block
 block discarded – undo
523 521
 			if($this->imgType=='GIF'){
524 522
 				if(!empty($newfile)){
525 523
           @imagegif($newimg,$newfile);
526
-        }
527
-				else {
524
+        } else {
528 525
 					@header("Content-type: image/gif");
529 526
 					@imagegif($newimg);
530 527
 				}
531
-			}
532
-			elseif($this->imgType=='JPG'){
528
+			} elseif($this->imgType=='JPG'){
533 529
 				if(!empty($newfile)){
534 530
 					@imagejpeg($newimg,$newfile);
535
-        }
536
-				else	{
531
+        } else	{
537 532
 					@header("Content-type: image/jpeg");
538 533
 					@imagejpeg($newimg);
539 534
 				}
540
-			}
541
-			elseif($this->imgType=='PNG'){
535
+			} elseif($this->imgType=='PNG'){
542 536
 				if(!empty($newfile)){
543 537
 					@imagepng($newimg,$newfile);
544
-        }
545
-				else{
538
+        } else{
546 539
 					@header("Content-type: image/png");
547 540
 					@imagepng($newimg);
548 541
 				}
Please login to merge, or discard this patch.
app/Plugin/Install/Controller/InstallController.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@
 block discarded – undo
110 110
  * credentials or create the missing database
111 111
  * Create the database file and insert the submitted details
112 112
  *
113
- * @return void
113
+ * @return null|CakeResponse
114 114
  * @access public
115 115
  */
116 116
 	public function database() {
Please login to merge, or discard this patch.
Indentation   +176 added lines, -176 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
  * @var string
22 22
  * @access public
23 23
  */
24
-	public $name = 'Install';
24
+    public $name = 'Install';
25 25
 
26 26
 /**
27 27
  * No models required
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
  * @var array
30 30
  * @access public
31 31
  */
32
-	public $uses = null;
32
+    public $uses = null;
33 33
 
34 34
 /**
35 35
  * No components required
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
  * @var array
38 38
  * @access public
39 39
  */
40
-	public $components = null;
40
+    public $components = null;
41 41
 
42 42
 /**
43 43
  * Default configuration
@@ -45,19 +45,19 @@  discard block
 block discarded – undo
45 45
  * @var array
46 46
  * @access public
47 47
  */
48
-	public $defaultConfig = array(
49
-		'name' => 'default',
50
-		'datasource'=> 'Database/Mysql',
51
-		'persistent'=> false,
52
-		'host'=> 'localhost',
53
-		'login'=> 'root',
54
-		'password'=> '',
55
-		'database'=> 'croogo',
56
-		'schema'=> null,
57
-		'prefix'=> null,
58
-		'encoding' => 'utf8',
59
-		'port' => null,
60
-	);
48
+    public $defaultConfig = array(
49
+        'name' => 'default',
50
+        'datasource'=> 'Database/Mysql',
51
+        'persistent'=> false,
52
+        'host'=> 'localhost',
53
+        'login'=> 'root',
54
+        'password'=> '',
55
+        'database'=> 'croogo',
56
+        'schema'=> null,
57
+        'prefix'=> null,
58
+        'encoding' => 'utf8',
59
+        'port' => null,
60
+    );
61 61
 
62 62
 /**
63 63
  * beforeFilter
@@ -65,30 +65,30 @@  discard block
 block discarded – undo
65 65
  * @return void
66 66
  * @access public
67 67
  */
68
-	public function beforeFilter() {
69
-		parent::beforeFilter();
70
-		$this->_check();
68
+    public function beforeFilter() {
69
+        parent::beforeFilter();
70
+        $this->_check();
71 71
 
72
-		$this->layout = 'install';
73
-		App::import('Component', 'Session');
74
-		$this->Session = new SessionComponent($this->Components);
72
+        $this->layout = 'install';
73
+        App::import('Component', 'Session');
74
+        $this->Session = new SessionComponent($this->Components);
75 75
 
76
-		Cache::clear(false, '_cake_core_');
77
-		Cache::clear(false, '_cake_model_');
78
-	}
76
+        Cache::clear(false, '_cake_core_');
77
+        Cache::clear(false, '_cake_model_');
78
+    }
79 79
 
80 80
 /**
81 81
  * If settings.yml exists, app is already installed
82 82
  *
83 83
  * @return void
84 84
  */
85
-	protected function _check() {
86
-		if (file_exists(APP . 'Config' . DS . 'installed.txt')) {
85
+    protected function _check() {
86
+        if (file_exists(APP . 'Config' . DS . 'installed.txt')) {
87 87
 //		if (Configure::read('Install.installed') && Configure::read('Install.secured')) {
88
-			$this->Session->setFlash('Already Installed');
89
-			$this->redirect('/');
90
-		}
91
-	}
88
+            $this->Session->setFlash('Already Installed');
89
+            $this->redirect('/');
90
+        }
91
+    }
92 92
 
93 93
 /**
94 94
  * Step 0: welcome
@@ -98,10 +98,10 @@  discard block
 block discarded – undo
98 98
  * @return void
99 99
  * @access public
100 100
  */
101
-	public function index() {
102
-		$this->_check();
103
-		$this->set('title_for_layout', __('Installation: Welcome'));
104
-	}
101
+    public function index() {
102
+        $this->_check();
103
+        $this->set('title_for_layout', __('Installation: Welcome'));
104
+    }
105 105
 
106 106
 /**
107 107
  * Step 1: database
@@ -113,63 +113,63 @@  discard block
 block discarded – undo
113 113
  * @return void
114 114
  * @access public
115 115
  */
116
-	public function database() {
117
-		$this->_check();
118
-		$this->set('title_for_layout', __('Step 1: Database'));
116
+    public function database() {
117
+        $this->_check();
118
+        $this->set('title_for_layout', __('Step 1: Database'));
119 119
 
120 120
 
121
-		if (empty($this->request->data)) {
122
-			return;
123
-		}
121
+        if (empty($this->request->data)) {
122
+            return;
123
+        }
124 124
 
125
-		@App::import('Model', 'ConnectionManager');
126
-		$config = $this->defaultConfig;
127
-		foreach ($this->request->data['Install'] AS $key => $value) {
128
-			if (isset($this->request->data['Install'][$key])) {
129
-				$config[$key] = $value;
130
-			}
131
-		}
132
-		try {
133
-			@ConnectionManager::create('default', $config);
134
-			$db = ConnectionManager::getDataSource('default');
135
-		}
136
-		catch (MissingConnectionException $e) {
137
-			$this->Session->setFlash(__('Could not connect to database: %s', $e->getMessage()), 'default', array('class' => 'error'));
138
-			$this->redirect(array('action' => 'database'));
139
-		}
140
-		if (!$db->isConnected()) {
141
-			$this->Session->setFlash(__('Could not connect to database.'), 'default', array('class' => 'error'));
142
-			return;
143
-		}
125
+        @App::import('Model', 'ConnectionManager');
126
+        $config = $this->defaultConfig;
127
+        foreach ($this->request->data['Install'] AS $key => $value) {
128
+            if (isset($this->request->data['Install'][$key])) {
129
+                $config[$key] = $value;
130
+            }
131
+        }
132
+        try {
133
+            @ConnectionManager::create('default', $config);
134
+            $db = ConnectionManager::getDataSource('default');
135
+        }
136
+        catch (MissingConnectionException $e) {
137
+            $this->Session->setFlash(__('Could not connect to database: %s', $e->getMessage()), 'default', array('class' => 'error'));
138
+            $this->redirect(array('action' => 'database'));
139
+        }
140
+        if (!$db->isConnected()) {
141
+            $this->Session->setFlash(__('Could not connect to database.'), 'default', array('class' => 'error'));
142
+            return;
143
+        }
144 144
 
145
-		copy(APP . 'Config' . DS.'database.php.install', APP . 'Config' . DS.'database.php');
146
-		App::uses('File', 'Utility');
147
-		$file = new File(APP . 'Config' . DS.'database.php', true);
148
-		$content = $file->read();
145
+        copy(APP . 'Config' . DS.'database.php.install', APP . 'Config' . DS.'database.php');
146
+        App::uses('File', 'Utility');
147
+        $file = new File(APP . 'Config' . DS.'database.php', true);
148
+        $content = $file->read();
149 149
 
150
-		foreach ($config AS $configKey => $configValue) {
151
-			$content = str_replace('{default_' . $configKey . '}', $configValue, $content);
152
-		}
150
+        foreach ($config AS $configKey => $configValue) {
151
+            $content = str_replace('{default_' . $configKey . '}', $configValue, $content);
152
+        }
153 153
 
154
-		if($file->write($content) ) {
155
-			return $this->redirect(array('action' => 'data'));
156
-		} else {
157
-			$this->Session->setFlash(__('Could not write database.php file.'), 'default', array('class' => 'error'));
158
-		}
159
-	}
154
+        if($file->write($content) ) {
155
+            return $this->redirect(array('action' => 'data'));
156
+        } else {
157
+            $this->Session->setFlash(__('Could not write database.php file.'), 'default', array('class' => 'error'));
158
+        }
159
+    }
160 160
 
161
-	/**
162
-	 * Fixes Postgres sequence
163
-	 */
164
-	protected function _fixSequence($model) {
165
-		$db = $model->getDataSource();
166
-		$nextValue = $model->find('first', array(
167
-			'fields' => sprintf('MAX(%s.%s) as max', $model->alias, $model->primaryKey),
168
-			));
169
-		$nextValue = empty($nextValue[0]['max']) ? 1 :  $nextValue[0]['max'] + 1;
170
-		$sql = sprintf('alter sequence %s restart with %d', $db->getSequence($model), $nextValue);
171
-		$db->execute($sql);
172
-	}
161
+    /**
162
+     * Fixes Postgres sequence
163
+     */
164
+    protected function _fixSequence($model) {
165
+        $db = $model->getDataSource();
166
+        $nextValue = $model->find('first', array(
167
+            'fields' => sprintf('MAX(%s.%s) as max', $model->alias, $model->primaryKey),
168
+            ));
169
+        $nextValue = empty($nextValue[0]['max']) ? 1 :  $nextValue[0]['max'] + 1;
170
+        $sql = sprintf('alter sequence %s restart with %d', $db->getSequence($model), $nextValue);
171
+        $db->execute($sql);
172
+    }
173 173
 
174 174
 /**
175 175
  * Step 2: Run the initial sql scripts to create the db and seed it with data
@@ -177,83 +177,83 @@  discard block
 block discarded – undo
177 177
  * @return void
178 178
  * @access public
179 179
  */
180
-	public function data() {
181
-		$this->_check();
182
-		$this->set('title_for_layout', __('Step 2: Build database'));
183
-		if (isset($this->params['named']['run'])) {
184
-			App::uses('File', 'Utility');
185
-			App::import('Model', 'CakeSchema', false);
186
-			App::import('Model', 'ConnectionManager');
180
+    public function data() {
181
+        $this->_check();
182
+        $this->set('title_for_layout', __('Step 2: Build database'));
183
+        if (isset($this->params['named']['run'])) {
184
+            App::uses('File', 'Utility');
185
+            App::import('Model', 'CakeSchema', false);
186
+            App::import('Model', 'ConnectionManager');
187 187
 
188
-			$db = ConnectionManager::getDataSource('default');
189
-			$brokenSequence = $db instanceof Postgres;
190
-			if(!$db->isConnected()) {
191
-				$this->Session->setFlash(__('Could not connect to database.'), 'default', array('class' => 'error'));
192
-			} else {
193
-				$schema = new CakeSchema(array('name'=>'app'));
194
-				$schema = $schema->load();
195
-				foreach($schema->tables as $table => $fields) {
196
-					$create = $db->createSchema($schema, $table);
197
-					try {
198
-						$db->execute($create);
199
-					}
200
-					catch (PDOException $e) {
201
-						$this->Session->setFlash(__('Could not create table: %s', $e->getMessage()), 'default', array('class' => 'error'));
202
-						$this->redirect(array('action' => 'database'));
203
-					}
204
-				}
188
+            $db = ConnectionManager::getDataSource('default');
189
+            $brokenSequence = $db instanceof Postgres;
190
+            if(!$db->isConnected()) {
191
+                $this->Session->setFlash(__('Could not connect to database.'), 'default', array('class' => 'error'));
192
+            } else {
193
+                $schema = new CakeSchema(array('name'=>'app'));
194
+                $schema = $schema->load();
195
+                foreach($schema->tables as $table => $fields) {
196
+                    $create = $db->createSchema($schema, $table);
197
+                    try {
198
+                        $db->execute($create);
199
+                    }
200
+                    catch (PDOException $e) {
201
+                        $this->Session->setFlash(__('Could not create table: %s', $e->getMessage()), 'default', array('class' => 'error'));
202
+                        $this->redirect(array('action' => 'database'));
203
+                    }
204
+                }
205 205
 
206
-				$path = CakePlugin::path('Install') .DS. 'Config' .DS. 'Data' .DS;
207
-				$dataObjects = App::objects('class', $path);
208
-				foreach ($dataObjects as $data) {
209
-					include($path . $data . '.php');
210
-					$classVars = get_class_vars($data);
211
-					$modelAlias = substr($data, 0, -4);
212
-					$table = $classVars['table'];
213
-					$records = $classVars['records'];
214
-					App::import('Model', 'Model', false);
215
-					$modelObject = new Model(array(
216
-						'name' => $modelAlias,
217
-						'table' => $table,
218
-						'ds' => 'default',
219
-					));
220
-					if (is_array($records) && count($records) > 0) {
221
-						$i = 1;
222
-						foreach($records as $record) {
223
-							if (!isset($record['id'])) {
224
-								$record['id'] = $i++;
225
-							}
226
-							$modelObject->create($record);
227
-							$modelObject->save();
228
-						}
229
-					}
230
-					if ($brokenSequence) {
231
-						// $this->_fixSequence($modelObject);
232
-					}
233
-				}
206
+                $path = CakePlugin::path('Install') .DS. 'Config' .DS. 'Data' .DS;
207
+                $dataObjects = App::objects('class', $path);
208
+                foreach ($dataObjects as $data) {
209
+                    include($path . $data . '.php');
210
+                    $classVars = get_class_vars($data);
211
+                    $modelAlias = substr($data, 0, -4);
212
+                    $table = $classVars['table'];
213
+                    $records = $classVars['records'];
214
+                    App::import('Model', 'Model', false);
215
+                    $modelObject = new Model(array(
216
+                        'name' => $modelAlias,
217
+                        'table' => $table,
218
+                        'ds' => 'default',
219
+                    ));
220
+                    if (is_array($records) && count($records) > 0) {
221
+                        $i = 1;
222
+                        foreach($records as $record) {
223
+                            if (!isset($record['id'])) {
224
+                                $record['id'] = $i++;
225
+                            }
226
+                            $modelObject->create($record);
227
+                            $modelObject->save();
228
+                        }
229
+                    }
230
+                    if ($brokenSequence) {
231
+                        // $this->_fixSequence($modelObject);
232
+                    }
233
+                }
234 234
 
235
-				$this->redirect(array('action' => 'adminuser'));
236
-			}
237
-		}
238
-	}
235
+                $this->redirect(array('action' => 'adminuser'));
236
+            }
237
+        }
238
+    }
239 239
 
240 240
 /**
241 241
  * Step 3: get username and passwords for administrative user
242 242
  */
243
-	public function adminuser() {
243
+    public function adminuser() {
244 244
 //		if ($this->request->is('post')) {
245
-			$this->loadModel('User');
245
+            $this->loadModel('User');
246 246
 //			$this->User->set($this->request->data);
247 247
 //			if ($this->User->validates()) {
248
-				$token = uniqid();
249
-				$this->Session->write('Install', array(
250
-					'token' => $token,
248
+                $token = uniqid();
249
+                $this->Session->write('Install', array(
250
+                    'token' => $token,
251 251
 //					'User' => $this->request->data['User'],
252
-					));
253
-				$this->redirect(array('action' => 'finish', $token));
252
+                    ));
253
+                $this->redirect(array('action' => 'finish', $token));
254 254
 //			}
255 255
 //		}
256
-	}
256
+    }
257 257
 
258 258
 /**
259 259
  * Step 4: finish
@@ -263,33 +263,33 @@  discard block
 block discarded – undo
263 263
  * @return void
264 264
  * @access public
265 265
  */
266
-	public function finish($token = null) {
267
-		$this->set('title_for_layout', __('Installation completed successfully'));
268
-		$this->_check();
269
-		$this->loadModel('Install.Install');
270
-		$install = $this->Session->read('Install');
271
-		if ($install['token'] == $token) {
272
-			unset($install['token']);
273
-			if ($this->Install->finalize($install)) {
274
-				$urlBlogAdd = Router::url(array(
275
-					'plugin' => false, 'admin' => true,
276
-					'controller' => 'nodes', 'action' => 'add', 'blog',
277
-					));
278
-				$urlSettings = Router::url(array(
279
-					'plugin' => false, 'admin' => true,
280
-					'controller' => 'settings', 'action' => 'prefix', 'Site',
281
-					));
282
-				$this->set('user', $install);
283
-				$this->set(compact('urlBlogAdd', 'urlSettings'));
284
-			} else {
285
-				$this->Session->setFlash('Something went wrong during installation. Please check your server logs.');
286
-				$this->redirect(array('action' => 'adminuser'));
287
-			}
288
-			$this->Session->delete('Install');
289
-		} else {
290
-			$this->redirect('/');
291
-		}
292
-	}
266
+    public function finish($token = null) {
267
+        $this->set('title_for_layout', __('Installation completed successfully'));
268
+        $this->_check();
269
+        $this->loadModel('Install.Install');
270
+        $install = $this->Session->read('Install');
271
+        if ($install['token'] == $token) {
272
+            unset($install['token']);
273
+            if ($this->Install->finalize($install)) {
274
+                $urlBlogAdd = Router::url(array(
275
+                    'plugin' => false, 'admin' => true,
276
+                    'controller' => 'nodes', 'action' => 'add', 'blog',
277
+                    ));
278
+                $urlSettings = Router::url(array(
279
+                    'plugin' => false, 'admin' => true,
280
+                    'controller' => 'settings', 'action' => 'prefix', 'Site',
281
+                    ));
282
+                $this->set('user', $install);
283
+                $this->set(compact('urlBlogAdd', 'urlSettings'));
284
+            } else {
285
+                $this->Session->setFlash('Something went wrong during installation. Please check your server logs.');
286
+                $this->redirect(array('action' => 'adminuser'));
287
+            }
288
+            $this->Session->delete('Install');
289
+        } else {
290
+            $this->redirect('/');
291
+        }
292
+    }
293 293
 
294 294
 }
295 295
 ?>
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
  * @return void
84 84
  */
85 85
 	protected function _check() {
86
-		if (file_exists(APP . 'Config' . DS . 'installed.txt')) {
86
+		if (file_exists(APP.'Config'.DS.'installed.txt')) {
87 87
 //		if (Configure::read('Install.installed') && Configure::read('Install.secured')) {
88 88
 			$this->Session->setFlash('Already Installed');
89 89
 			$this->redirect('/');
@@ -142,16 +142,16 @@  discard block
 block discarded – undo
142 142
 			return;
143 143
 		}
144 144
 
145
-		copy(APP . 'Config' . DS.'database.php.install', APP . 'Config' . DS.'database.php');
145
+		copy(APP.'Config'.DS.'database.php.install', APP.'Config'.DS.'database.php');
146 146
 		App::uses('File', 'Utility');
147
-		$file = new File(APP . 'Config' . DS.'database.php', true);
147
+		$file = new File(APP.'Config'.DS.'database.php', true);
148 148
 		$content = $file->read();
149 149
 
150 150
 		foreach ($config AS $configKey => $configValue) {
151
-			$content = str_replace('{default_' . $configKey . '}', $configValue, $content);
151
+			$content = str_replace('{default_'.$configKey.'}', $configValue, $content);
152 152
 		}
153 153
 
154
-		if($file->write($content) ) {
154
+		if ($file->write($content)) {
155 155
 			return $this->redirect(array('action' => 'data'));
156 156
 		} else {
157 157
 			$this->Session->setFlash(__('Could not write database.php file.'), 'default', array('class' => 'error'));
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
 		$nextValue = $model->find('first', array(
167 167
 			'fields' => sprintf('MAX(%s.%s) as max', $model->alias, $model->primaryKey),
168 168
 			));
169
-		$nextValue = empty($nextValue[0]['max']) ? 1 :  $nextValue[0]['max'] + 1;
169
+		$nextValue = empty($nextValue[0]['max']) ? 1 : $nextValue[0]['max'] + 1;
170 170
 		$sql = sprintf('alter sequence %s restart with %d', $db->getSequence($model), $nextValue);
171 171
 		$db->execute($sql);
172 172
 	}
@@ -187,12 +187,12 @@  discard block
 block discarded – undo
187 187
 
188 188
 			$db = ConnectionManager::getDataSource('default');
189 189
 			$brokenSequence = $db instanceof Postgres;
190
-			if(!$db->isConnected()) {
190
+			if (!$db->isConnected()) {
191 191
 				$this->Session->setFlash(__('Could not connect to database.'), 'default', array('class' => 'error'));
192 192
 			} else {
193 193
 				$schema = new CakeSchema(array('name'=>'app'));
194 194
 				$schema = $schema->load();
195
-				foreach($schema->tables as $table => $fields) {
195
+				foreach ($schema->tables as $table => $fields) {
196 196
 					$create = $db->createSchema($schema, $table);
197 197
 					try {
198 198
 						$db->execute($create);
@@ -203,10 +203,10 @@  discard block
 block discarded – undo
203 203
 					}
204 204
 				}
205 205
 
206
-				$path = CakePlugin::path('Install') .DS. 'Config' .DS. 'Data' .DS;
206
+				$path = CakePlugin::path('Install').DS.'Config'.DS.'Data'.DS;
207 207
 				$dataObjects = App::objects('class', $path);
208 208
 				foreach ($dataObjects as $data) {
209
-					include($path . $data . '.php');
209
+					include($path.$data.'.php');
210 210
 					$classVars = get_class_vars($data);
211 211
 					$modelAlias = substr($data, 0, -4);
212 212
 					$table = $classVars['table'];
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 					));
220 220
 					if (is_array($records) && count($records) > 0) {
221 221
 						$i = 1;
222
-						foreach($records as $record) {
222
+						foreach ($records as $record) {
223 223
 							if (!isset($record['id'])) {
224 224
 								$record['id'] = $i++;
225 225
 							}
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -132,8 +132,7 @@  discard block
 block discarded – undo
132 132
 		try {
133 133
 			@ConnectionManager::create('default', $config);
134 134
 			$db = ConnectionManager::getDataSource('default');
135
-		}
136
-		catch (MissingConnectionException $e) {
135
+		} catch (MissingConnectionException $e) {
137 136
 			$this->Session->setFlash(__('Could not connect to database: %s', $e->getMessage()), 'default', array('class' => 'error'));
138 137
 			$this->redirect(array('action' => 'database'));
139 138
 		}
@@ -196,8 +195,7 @@  discard block
 block discarded – undo
196 195
 					$create = $db->createSchema($schema, $table);
197 196
 					try {
198 197
 						$db->execute($create);
199
-					}
200
-					catch (PDOException $e) {
198
+					} catch (PDOException $e) {
201 199
 						$this->Session->setFlash(__('Could not create table: %s', $e->getMessage()), 'default', array('class' => 'error'));
202 200
 						$this->redirect(array('action' => 'database'));
203 201
 					}
Please login to merge, or discard this patch.
app/Plugin/Install/Model/Install.php 3 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
 		 * Finalize installation
16 16
 		 *
17 17
 		 * @param $user
18
-		 * @return mixed if false, indicates processing failure
18
+		 * @return boolean if false, indicates processing failure
19 19
 		 */
20 20
 		public function finalize($user) {
21 21
 			if (Configure::read('Install.installed') && Configure::read('Install.secured')) {
@@ -58,6 +58,9 @@  discard block
 block discarded – undo
58 58
 			Configure::write('Security.cipherSeed', $seed);
59 59
 		}
60 60
 
61
+		/**
62
+		 * @param false|null $salt
63
+		 */
61 64
 		protected function _createAdmin($salt) {
62 65
 			$User = ClassRegistry::init('User');
63 66
 			$User->id = $User->field('id', ['username' => 'admin']);
Please login to merge, or discard this patch.
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -1,77 +1,77 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-	App::uses('InstallAppModel', 'Install.Model');
4
-	App::uses('CakeTime', 'Utility');
5
-	App::uses('Security', 'Utility');
6
-	App::uses('File', 'Utility');
7
-
8
-	class Install extends InstallAppModel {
9
-
10
-		public $name = 'Install';
11
-
12
-		public $useTable = false;
13
-
14
-		/**
15
-		 * Finalize installation
16
-		 *
17
-		 * @param $user
18
-		 * @return mixed if false, indicates processing failure
19
-		 */
20
-		public function finalize($user) {
21
-			if (Configure::read('Install.installed') && Configure::read('Install.secured')) {
22
-				return false;
23
-			}
24
-
25
-			$this->_markInstalled();
26
-			$salt = $this->_createSecurity();
27
-			$saved = $this->_createAdmin($salt);
28
-
29
-			return $saved;
30
-		}
31
-
32
-		protected function _markInstalled() {
33
-			touch(APP . 'Config' . DS . 'installed.txt');
34
-		}
35
-
36
-		protected function _createSecurity() {
37
-			$File = new File(APP . 'Config' . DS . 'core.php');
38
-
39
-			// save previous core file
40
-			// copy(APP . 'Config' . DS.'settings.yml.install', APP . 'Config' . DS.'settings.yml');
41
-			$File->copy(APP . 'Config' . DS . 'core.' . date('YmdHis',
42
-					time()) . '.php');
43
-
44
-			// set new salt and seed value
45
-			$salt = Security::generateAuthKey();
46
-			$seed = mt_rand() . mt_rand();
47
-			$contents = $File->read();
48
-			$contents = preg_replace('/(?<=Configure::write\(\'Security.salt\', \')([^\' ]+)(?=\'\))/',
49
-					$salt,
50
-					$contents);
51
-			$contents = preg_replace('/(?<=Configure::write\(\'Security.cipherSeed\', \')(\d+)(?=\'\))/',
52
-					$seed,
53
-					$contents);
54
-			if (!$File->write($contents)) {
55
-				return false;
56
-			}
57
-			Configure::write('Security.salt', $salt);
58
-			Configure::write('Security.cipherSeed', $seed);
59
-		}
60
-
61
-		protected function _createAdmin($salt) {
62
-			$User = ClassRegistry::init('User');
63
-			$User->id = $User->field('id', ['username' => 'admin']);
64
-			Security::setHash('md5');
65
-			Configure::write('Security.salt', $salt);
66
-			$saved = $User->save([
67
-					'User' => [
68
-							'password' => 'password',
69
-							'password_confirm' => 'password',
70
-							'registered' => date('Y-m-d H:i:s')
71
-					]
72
-			]);
73
-
74
-			/*
3
+    App::uses('InstallAppModel', 'Install.Model');
4
+    App::uses('CakeTime', 'Utility');
5
+    App::uses('Security', 'Utility');
6
+    App::uses('File', 'Utility');
7
+
8
+    class Install extends InstallAppModel {
9
+
10
+        public $name = 'Install';
11
+
12
+        public $useTable = false;
13
+
14
+        /**
15
+         * Finalize installation
16
+         *
17
+         * @param $user
18
+         * @return mixed if false, indicates processing failure
19
+         */
20
+        public function finalize($user) {
21
+            if (Configure::read('Install.installed') && Configure::read('Install.secured')) {
22
+                return false;
23
+            }
24
+
25
+            $this->_markInstalled();
26
+            $salt = $this->_createSecurity();
27
+            $saved = $this->_createAdmin($salt);
28
+
29
+            return $saved;
30
+        }
31
+
32
+        protected function _markInstalled() {
33
+            touch(APP . 'Config' . DS . 'installed.txt');
34
+        }
35
+
36
+        protected function _createSecurity() {
37
+            $File = new File(APP . 'Config' . DS . 'core.php');
38
+
39
+            // save previous core file
40
+            // copy(APP . 'Config' . DS.'settings.yml.install', APP . 'Config' . DS.'settings.yml');
41
+            $File->copy(APP . 'Config' . DS . 'core.' . date('YmdHis',
42
+                    time()) . '.php');
43
+
44
+            // set new salt and seed value
45
+            $salt = Security::generateAuthKey();
46
+            $seed = mt_rand() . mt_rand();
47
+            $contents = $File->read();
48
+            $contents = preg_replace('/(?<=Configure::write\(\'Security.salt\', \')([^\' ]+)(?=\'\))/',
49
+                    $salt,
50
+                    $contents);
51
+            $contents = preg_replace('/(?<=Configure::write\(\'Security.cipherSeed\', \')(\d+)(?=\'\))/',
52
+                    $seed,
53
+                    $contents);
54
+            if (!$File->write($contents)) {
55
+                return false;
56
+            }
57
+            Configure::write('Security.salt', $salt);
58
+            Configure::write('Security.cipherSeed', $seed);
59
+        }
60
+
61
+        protected function _createAdmin($salt) {
62
+            $User = ClassRegistry::init('User');
63
+            $User->id = $User->field('id', ['username' => 'admin']);
64
+            Security::setHash('md5');
65
+            Configure::write('Security.salt', $salt);
66
+            $saved = $User->save([
67
+                    'User' => [
68
+                            'password' => 'password',
69
+                            'password_confirm' => 'password',
70
+                            'registered' => date('Y-m-d H:i:s')
71
+                    ]
72
+            ]);
73
+
74
+            /*
75 75
 			// create administrative user
76 76
 			$User = ClassRegistry::init('User');
77 77
 			$User->Role->Behaviors->attach('Aliasable');
@@ -87,12 +87,12 @@  discard block
 block discarded – undo
87 87
 			 *
88 88
 			 */
89 89
 
90
-			if (!$saved) {
91
-				$this->log('Unable to create administrative user. Validation errors:');
92
-				$this->log($User->validationErrors);
93
-			}
90
+            if (!$saved) {
91
+                $this->log('Unable to create administrative user. Validation errors:');
92
+                $this->log($User->validationErrors);
93
+            }
94 94
 
95
-			return (bool)$saved;
96
-		}
95
+            return (bool)$saved;
96
+        }
97 97
 
98
-	}
98
+    }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -30,20 +30,20 @@  discard block
 block discarded – undo
30 30
 		}
31 31
 
32 32
 		protected function _markInstalled() {
33
-			touch(APP . 'Config' . DS . 'installed.txt');
33
+			touch(APP.'Config'.DS.'installed.txt');
34 34
 		}
35 35
 
36 36
 		protected function _createSecurity() {
37
-			$File = new File(APP . 'Config' . DS . 'core.php');
37
+			$File = new File(APP.'Config'.DS.'core.php');
38 38
 
39 39
 			// save previous core file
40 40
 			// copy(APP . 'Config' . DS.'settings.yml.install', APP . 'Config' . DS.'settings.yml');
41
-			$File->copy(APP . 'Config' . DS . 'core.' . date('YmdHis',
42
-					time()) . '.php');
41
+			$File->copy(APP.'Config'.DS.'core.'.date('YmdHis',
42
+					time()).'.php');
43 43
 
44 44
 			// set new salt and seed value
45 45
 			$salt = Security::generateAuthKey();
46
-			$seed = mt_rand() . mt_rand();
46
+			$seed = mt_rand().mt_rand();
47 47
 			$contents = $File->read();
48 48
 			$contents = preg_replace('/(?<=Configure::write\(\'Security.salt\', \')([^\' ]+)(?=\'\))/',
49 49
 					$salt,
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
 				$this->log($User->validationErrors);
93 93
 			}
94 94
 
95
-			return (bool)$saved;
95
+			return (bool) $saved;
96 96
 		}
97 97
 
98 98
 	}
Please login to merge, or discard this patch.
app/Plugin/Markitup/Vendor/parser/markdown/markdown.php 4 patches
Doc Comments   +19 added lines patch added patch discarded remove patch
@@ -1028,6 +1028,10 @@  discard block
 block discarded – undo
1028 1028
 
1029 1029
 	var $list_level = 0;
1030 1030
 
1031
+	/**
1032
+	 * @param string $list_str
1033
+	 * @param string $marker_any_re
1034
+	 */
1031 1035
 	function processListItems($list_str, $marker_any_re) {
1032 1036
 	#
1033 1037
 	#	Process the contents of a single ordered or unordered list, splitting it
@@ -1131,6 +1135,9 @@  discard block
 block discarded – undo
1131 1135
 	}
1132 1136
 
1133 1137
 
1138
+	/**
1139
+	 * @param string $code
1140
+	 */
1134 1141
 	function makeCodeSpan($code) {
1135 1142
 	#
1136 1143
 	# Create a code span markup for $code. Called from handleSpanToken.
@@ -1612,6 +1619,9 @@  discard block
 block discarded – undo
1612 1619
 	# hanlde UTF-8 if the default function does not exist.
1613 1620
 	var $utf8_strlen = 'mb_strlen';
1614 1621
 
1622
+	/**
1623
+	 * @param string $text
1624
+	 */
1615 1625
 	function detab($text) {
1616 1626
 	#
1617 1627
 	# Replace tabs with the appropriate amount of space.
@@ -2035,6 +2045,12 @@  discard block
 block discarded – undo
2035 2045
 
2036 2046
 		return array($parsed, $text);
2037 2047
 	}
2048
+
2049
+	/**
2050
+	 * @param string $text
2051
+	 * @param string $hash_method
2052
+	 * @param boolean $md_attr
2053
+	 */
2038 2054
 	function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
2039 2055
 	#
2040 2056
 	# Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
@@ -2464,6 +2480,9 @@  discard block
 block discarded – undo
2464 2480
 	}
2465 2481
 
2466 2482
 
2483
+	/**
2484
+	 * @return string
2485
+	 */
2467 2486
 	function processDefListItems($list_str) {
2468 2487
 	#
2469 2488
 	#	Process the contents of a single definition list, splitting it
Please login to merge, or discard this patch.
Indentation   +2139 added lines, -2139 removed lines patch added patch discarded remove patch
@@ -53,15 +53,15 @@  discard block
 block discarded – undo
53 53
 #
54 54
 # Initialize the parser and return the result of its transform method.
55 55
 #
56
-	# Setup static parser variable.
57
-	static $parser;
58
-	if (!isset($parser)) {
59
-		$parser_class = MARKDOWN_PARSER_CLASS;
60
-		$parser = new $parser_class;
61
-	}
62
-
63
-	# Transform text using parser.
64
-	return $parser->transform($text);
56
+    # Setup static parser variable.
57
+    static $parser;
58
+    if (!isset($parser)) {
59
+        $parser_class = MARKDOWN_PARSER_CLASS;
60
+        $parser = new $parser_class;
61
+    }
62
+
63
+    # Transform text using parser.
64
+    return $parser->transform($text);
65 65
 }
66 66
 
67 67
 
@@ -77,109 +77,109 @@  discard block
 block discarded – undo
77 77
 */
78 78
 
79 79
 if (isset($wp_version)) {
80
-	# More details about how it works here:
81
-	# <http://michelf.com/weblog/2005/wordpress-text-flow-vs-markdown/>
82
-
83
-	# Post content and excerpts
84
-	# - Remove WordPress paragraph generator.
85
-	# - Run Markdown on excerpt, then remove all tags.
86
-	# - Add paragraph tag around the excerpt, but remove it for the excerpt rss.
87
-	if (MARKDOWN_WP_POSTS) {
88
-		remove_filter('the_content',     'wpautop');
80
+    # More details about how it works here:
81
+    # <http://michelf.com/weblog/2005/wordpress-text-flow-vs-markdown/>
82
+
83
+    # Post content and excerpts
84
+    # - Remove WordPress paragraph generator.
85
+    # - Run Markdown on excerpt, then remove all tags.
86
+    # - Add paragraph tag around the excerpt, but remove it for the excerpt rss.
87
+    if (MARKDOWN_WP_POSTS) {
88
+        remove_filter('the_content',     'wpautop');
89 89
         remove_filter('the_content_rss', 'wpautop');
90
-		remove_filter('the_excerpt',     'wpautop');
91
-		add_filter('the_content',     'mdwp_MarkdownPost', 6);
90
+        remove_filter('the_excerpt',     'wpautop');
91
+        add_filter('the_content',     'mdwp_MarkdownPost', 6);
92 92
         add_filter('the_content_rss', 'mdwp_MarkdownPost', 6);
93
-		add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6);
94
-		add_filter('get_the_excerpt', 'trim', 7);
95
-		add_filter('the_excerpt',     'mdwp_add_p');
96
-		add_filter('the_excerpt_rss', 'mdwp_strip_p');
97
-
98
-		remove_filter('content_save_pre',  'balanceTags', 50);
99
-		remove_filter('excerpt_save_pre',  'balanceTags', 50);
100
-		add_filter('the_content',  	  'balanceTags', 50);
101
-		add_filter('get_the_excerpt', 'balanceTags', 9);
102
-	}
103
-
104
-	# Add a footnote id prefix to posts when inside a loop.
105
-	function mdwp_MarkdownPost($text) {
106
-		static $parser;
107
-		if (!$parser) {
108
-			$parser_class = MARKDOWN_PARSER_CLASS;
109
-			$parser = new $parser_class;
110
-		}
111
-		if (is_single() || is_page() || is_feed()) {
112
-			$parser->fn_id_prefix = "";
113
-		} else {
114
-			$parser->fn_id_prefix = get_the_ID() . ".";
115
-		}
116
-		return $parser->transform($text);
117
-	}
118
-
119
-	# Comments
120
-	# - Remove WordPress paragraph generator.
121
-	# - Remove WordPress auto-link generator.
122
-	# - Scramble important tags before passing them to the kses filter.
123
-	# - Run Markdown on excerpt then remove paragraph tags.
124
-	if (MARKDOWN_WP_COMMENTS) {
125
-		remove_filter('comment_text', 'wpautop', 30);
126
-		remove_filter('comment_text', 'make_clickable');
127
-		add_filter('pre_comment_content', 'Markdown', 6);
128
-		add_filter('pre_comment_content', 'mdwp_hide_tags', 8);
129
-		add_filter('pre_comment_content', 'mdwp_show_tags', 12);
130
-		add_filter('get_comment_text',    'Markdown', 6);
131
-		add_filter('get_comment_excerpt', 'Markdown', 6);
132
-		add_filter('get_comment_excerpt', 'mdwp_strip_p', 7);
133
-
134
-		global $mdwp_hidden_tags, $mdwp_placeholders;
135
-		$mdwp_hidden_tags = explode(' ',
136
-			'<p> </p> <pre> </pre> <ol> </ol> <ul> </ul> <li> </li>');
137
-		$mdwp_placeholders = explode(' ', str_rot13(
138
-			'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '.
139
-			'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli'));
140
-	}
141
-
142
-	function mdwp_add_p($text) {
143
-		if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) {
144
-			$text = '<p>'.$text.'</p>';
145
-			$text = preg_replace('{\n{2,}}', "</p>\n\n<p>", $text);
146
-		}
147
-		return $text;
148
-	}
149
-
150
-	function mdwp_strip_p($t) { return preg_replace('{</?p>}i', '', $t); }
151
-
152
-	function mdwp_hide_tags($text) {
153
-		global $mdwp_hidden_tags, $mdwp_placeholders;
154
-		return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text);
155
-	}
156
-	function mdwp_show_tags($text) {
157
-		global $mdwp_hidden_tags, $mdwp_placeholders;
158
-		return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text);
159
-	}
93
+        add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6);
94
+        add_filter('get_the_excerpt', 'trim', 7);
95
+        add_filter('the_excerpt',     'mdwp_add_p');
96
+        add_filter('the_excerpt_rss', 'mdwp_strip_p');
97
+
98
+        remove_filter('content_save_pre',  'balanceTags', 50);
99
+        remove_filter('excerpt_save_pre',  'balanceTags', 50);
100
+        add_filter('the_content',  	  'balanceTags', 50);
101
+        add_filter('get_the_excerpt', 'balanceTags', 9);
102
+    }
103
+
104
+    # Add a footnote id prefix to posts when inside a loop.
105
+    function mdwp_MarkdownPost($text) {
106
+        static $parser;
107
+        if (!$parser) {
108
+            $parser_class = MARKDOWN_PARSER_CLASS;
109
+            $parser = new $parser_class;
110
+        }
111
+        if (is_single() || is_page() || is_feed()) {
112
+            $parser->fn_id_prefix = "";
113
+        } else {
114
+            $parser->fn_id_prefix = get_the_ID() . ".";
115
+        }
116
+        return $parser->transform($text);
117
+    }
118
+
119
+    # Comments
120
+    # - Remove WordPress paragraph generator.
121
+    # - Remove WordPress auto-link generator.
122
+    # - Scramble important tags before passing them to the kses filter.
123
+    # - Run Markdown on excerpt then remove paragraph tags.
124
+    if (MARKDOWN_WP_COMMENTS) {
125
+        remove_filter('comment_text', 'wpautop', 30);
126
+        remove_filter('comment_text', 'make_clickable');
127
+        add_filter('pre_comment_content', 'Markdown', 6);
128
+        add_filter('pre_comment_content', 'mdwp_hide_tags', 8);
129
+        add_filter('pre_comment_content', 'mdwp_show_tags', 12);
130
+        add_filter('get_comment_text',    'Markdown', 6);
131
+        add_filter('get_comment_excerpt', 'Markdown', 6);
132
+        add_filter('get_comment_excerpt', 'mdwp_strip_p', 7);
133
+
134
+        global $mdwp_hidden_tags, $mdwp_placeholders;
135
+        $mdwp_hidden_tags = explode(' ',
136
+            '<p> </p> <pre> </pre> <ol> </ol> <ul> </ul> <li> </li>');
137
+        $mdwp_placeholders = explode(' ', str_rot13(
138
+            'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '.
139
+            'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli'));
140
+    }
141
+
142
+    function mdwp_add_p($text) {
143
+        if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) {
144
+            $text = '<p>'.$text.'</p>';
145
+            $text = preg_replace('{\n{2,}}', "</p>\n\n<p>", $text);
146
+        }
147
+        return $text;
148
+    }
149
+
150
+    function mdwp_strip_p($t) { return preg_replace('{</?p>}i', '', $t); }
151
+
152
+    function mdwp_hide_tags($text) {
153
+        global $mdwp_hidden_tags, $mdwp_placeholders;
154
+        return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text);
155
+    }
156
+    function mdwp_show_tags($text) {
157
+        global $mdwp_hidden_tags, $mdwp_placeholders;
158
+        return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text);
159
+    }
160 160
 }
161 161
 
162 162
 
163 163
 ### bBlog Plugin Info ###
164 164
 
165 165
 function identify_modifier_markdown() {
166
-	return array(
167
-		'name' => 'markdown',
168
-		'type' => 'modifier',
169
-		'nicename' => 'PHP Markdown Extra',
170
-		'description' => 'A text-to-HTML conversion tool for web writers',
171
-		'authors' => 'Michel Fortin and John Gruber',
172
-		'licence' => 'GPL',
173
-		'version' => MARKDOWNEXTRA_VERSION,
174
-		'help' => '<a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://michelf.com/projects/php-markdown/">More...</a>',
175
-		);
166
+    return array(
167
+        'name' => 'markdown',
168
+        'type' => 'modifier',
169
+        'nicename' => 'PHP Markdown Extra',
170
+        'description' => 'A text-to-HTML conversion tool for web writers',
171
+        'authors' => 'Michel Fortin and John Gruber',
172
+        'licence' => 'GPL',
173
+        'version' => MARKDOWNEXTRA_VERSION,
174
+        'help' => '<a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://michelf.com/projects/php-markdown/">More...</a>',
175
+        );
176 176
 }
177 177
 
178 178
 
179 179
 ### Smarty Modifier Interface ###
180 180
 
181 181
 function smarty_modifier_markdown($text) {
182
-	return Markdown($text);
182
+    return Markdown($text);
183 183
 }
184 184
 
185 185
 
@@ -188,22 +188,22 @@  discard block
 block discarded – undo
188 188
 # Rename this file to "classTextile.php" and it can replace Textile everywhere.
189 189
 
190 190
 if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) {
191
-	# Try to include PHP SmartyPants. Should be in the same directory.
192
-	@include_once 'smartypants.php';
193
-	# Fake Textile class. It calls Markdown instead.
194
-	class Textile {
195
-		function TextileThis($text, $lite='', $encode='') {
196
-			if ($lite == '' && $encode == '')    $text = Markdown($text);
197
-			if (function_exists('SmartyPants'))  $text = SmartyPants($text);
198
-			return $text;
199
-		}
200
-		# Fake restricted version: restrictions are not supported for now.
201
-		function TextileRestricted($text, $lite='', $noimage='') {
202
-			return $this->TextileThis($text, $lite);
203
-		}
204
-		# Workaround to ensure compatibility with TextPattern 4.0.3.
205
-		function blockLite($text) { return $text; }
206
-	}
191
+    # Try to include PHP SmartyPants. Should be in the same directory.
192
+    @include_once 'smartypants.php';
193
+    # Fake Textile class. It calls Markdown instead.
194
+    class Textile {
195
+        function TextileThis($text, $lite='', $encode='') {
196
+            if ($lite == '' && $encode == '')    $text = Markdown($text);
197
+            if (function_exists('SmartyPants'))  $text = SmartyPants($text);
198
+            return $text;
199
+        }
200
+        # Fake restricted version: restrictions are not supported for now.
201
+        function TextileRestricted($text, $lite='', $noimage='') {
202
+            return $this->TextileThis($text, $lite);
203
+        }
204
+        # Workaround to ensure compatibility with TextPattern 4.0.3.
205
+        function blockLite($text) { return $text; }
206
+    }
207 207
 }
208 208
 
209 209
 
@@ -214,144 +214,144 @@  discard block
 block discarded – undo
214 214
 
215 215
 class Markdown_Parser {
216 216
 
217
-	# Regex to match balanced [brackets].
218
-	# Needed to insert a maximum bracked depth while converting to PHP.
219
-	var $nested_brackets_depth = 6;
220
-	var $nested_brackets_re;
217
+    # Regex to match balanced [brackets].
218
+    # Needed to insert a maximum bracked depth while converting to PHP.
219
+    var $nested_brackets_depth = 6;
220
+    var $nested_brackets_re;
221 221
 
222
-	var $nested_url_parenthesis_depth = 4;
223
-	var $nested_url_parenthesis_re;
222
+    var $nested_url_parenthesis_depth = 4;
223
+    var $nested_url_parenthesis_re;
224 224
 
225
-	# Table of hash values for escaped characters:
226
-	var $escape_chars = '\`*_{}[]()>#+-.!';
227
-	var $escape_chars_re;
225
+    # Table of hash values for escaped characters:
226
+    var $escape_chars = '\`*_{}[]()>#+-.!';
227
+    var $escape_chars_re;
228 228
 
229
-	# Change to ">" for HTML output.
230
-	var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;
231
-	var $tab_width = MARKDOWN_TAB_WIDTH;
229
+    # Change to ">" for HTML output.
230
+    var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;
231
+    var $tab_width = MARKDOWN_TAB_WIDTH;
232 232
 
233
-	# Change to `true` to disallow markup or entities.
234
-	var $no_markup = false;
235
-	var $no_entities = false;
233
+    # Change to `true` to disallow markup or entities.
234
+    var $no_markup = false;
235
+    var $no_entities = false;
236 236
 
237
-	# Predefined urls and titles for reference links and images.
238
-	var $predef_urls = array();
239
-	var $predef_titles = array();
237
+    # Predefined urls and titles for reference links and images.
238
+    var $predef_urls = array();
239
+    var $predef_titles = array();
240 240
 
241 241
 
242
-	function Markdown_Parser() {
243
-	#
244
-	# Constructor function. Initialize appropriate member variables.
245
-	#
246
-		$this->_initDetab();
247
-		$this->prepareItalicsAndBold();
242
+    function Markdown_Parser() {
243
+    #
244
+    # Constructor function. Initialize appropriate member variables.
245
+    #
246
+        $this->_initDetab();
247
+        $this->prepareItalicsAndBold();
248 248
 
249
-		$this->nested_brackets_re =
250
-			str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
251
-			str_repeat('\])*', $this->nested_brackets_depth);
249
+        $this->nested_brackets_re =
250
+            str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
251
+            str_repeat('\])*', $this->nested_brackets_depth);
252 252
 
253
-		$this->nested_url_parenthesis_re =
254
-			str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
255
-			str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
253
+        $this->nested_url_parenthesis_re =
254
+            str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
255
+            str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
256 256
 
257
-		$this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
257
+        $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
258 258
 
259
-		# Sort document, block, and span gamut in ascendent priority order.
260
-		asort($this->document_gamut);
261
-		asort($this->block_gamut);
262
-		asort($this->span_gamut);
263
-	}
259
+        # Sort document, block, and span gamut in ascendent priority order.
260
+        asort($this->document_gamut);
261
+        asort($this->block_gamut);
262
+        asort($this->span_gamut);
263
+    }
264 264
 
265 265
 
266
-	# Internal hashes used during transformation.
267
-	var $urls = array();
268
-	var $titles = array();
269
-	var $html_hashes = array();
266
+    # Internal hashes used during transformation.
267
+    var $urls = array();
268
+    var $titles = array();
269
+    var $html_hashes = array();
270 270
 
271
-	# Status flag to avoid invalid nesting.
272
-	var $in_anchor = false;
271
+    # Status flag to avoid invalid nesting.
272
+    var $in_anchor = false;
273 273
 
274 274
 
275
-	function setup() {
276
-	#
277
-	# Called before the transformation process starts to setup parser
278
-	# states.
279
-	#
280
-		# Clear global hashes.
281
-		$this->urls = $this->predef_urls;
282
-		$this->titles = $this->predef_titles;
283
-		$this->html_hashes = array();
275
+    function setup() {
276
+    #
277
+    # Called before the transformation process starts to setup parser
278
+    # states.
279
+    #
280
+        # Clear global hashes.
281
+        $this->urls = $this->predef_urls;
282
+        $this->titles = $this->predef_titles;
283
+        $this->html_hashes = array();
284 284
 
285
-		$in_anchor = false;
286
-	}
285
+        $in_anchor = false;
286
+    }
287 287
 
288
-	function teardown() {
289
-	#
290
-	# Called after the transformation process to clear any variable
291
-	# which may be taking up memory unnecessarly.
292
-	#
293
-		$this->urls = array();
294
-		$this->titles = array();
295
-		$this->html_hashes = array();
296
-	}
288
+    function teardown() {
289
+    #
290
+    # Called after the transformation process to clear any variable
291
+    # which may be taking up memory unnecessarly.
292
+    #
293
+        $this->urls = array();
294
+        $this->titles = array();
295
+        $this->html_hashes = array();
296
+    }
297 297
 
298 298
 
299
-	function transform($text) {
300
-	#
301
-	# Main function. Performs some preprocessing on the input text
302
-	# and pass it through the document gamut.
303
-	#
304
-		$this->setup();
299
+    function transform($text) {
300
+    #
301
+    # Main function. Performs some preprocessing on the input text
302
+    # and pass it through the document gamut.
303
+    #
304
+        $this->setup();
305 305
 
306
-		# Remove UTF-8 BOM and marker character in input, if present.
307
-		$text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
306
+        # Remove UTF-8 BOM and marker character in input, if present.
307
+        $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
308 308
 
309
-		# Standardize line endings:
310
-		#   DOS to Unix and Mac to Unix
311
-		$text = preg_replace('{\r\n?}', "\n", $text);
309
+        # Standardize line endings:
310
+        #   DOS to Unix and Mac to Unix
311
+        $text = preg_replace('{\r\n?}', "\n", $text);
312 312
 
313
-		# Make sure $text ends with a couple of newlines:
314
-		$text .= "\n\n";
313
+        # Make sure $text ends with a couple of newlines:
314
+        $text .= "\n\n";
315 315
 
316
-		# Convert all tabs to spaces.
317
-		$text = $this->detab($text);
316
+        # Convert all tabs to spaces.
317
+        $text = $this->detab($text);
318 318
 
319
-		# Turn block-level HTML blocks into hash entries
320
-		$text = $this->hashHTMLBlocks($text);
319
+        # Turn block-level HTML blocks into hash entries
320
+        $text = $this->hashHTMLBlocks($text);
321 321
 
322
-		# Strip any lines consisting only of spaces and tabs.
323
-		# This makes subsequent regexen easier to write, because we can
324
-		# match consecutive blank lines with /\n+/ instead of something
325
-		# contorted like /[ ]*\n+/ .
326
-		$text = preg_replace('/^[ ]+$/m', '', $text);
322
+        # Strip any lines consisting only of spaces and tabs.
323
+        # This makes subsequent regexen easier to write, because we can
324
+        # match consecutive blank lines with /\n+/ instead of something
325
+        # contorted like /[ ]*\n+/ .
326
+        $text = preg_replace('/^[ ]+$/m', '', $text);
327 327
 
328
-		# Run document gamut methods.
329
-		foreach ($this->document_gamut as $method => $priority) {
330
-			$text = $this->$method($text);
331
-		}
328
+        # Run document gamut methods.
329
+        foreach ($this->document_gamut as $method => $priority) {
330
+            $text = $this->$method($text);
331
+        }
332 332
 
333
-		$this->teardown();
333
+        $this->teardown();
334 334
 
335
-		return $text . "\n";
336
-	}
335
+        return $text . "\n";
336
+    }
337 337
 
338
-	var $document_gamut = array(
339
-		# Strip link definitions, store in hashes.
340
-		"stripLinkDefinitions" => 20,
338
+    var $document_gamut = array(
339
+        # Strip link definitions, store in hashes.
340
+        "stripLinkDefinitions" => 20,
341 341
 
342
-		"runBasicBlockGamut"   => 30,
343
-		);
342
+        "runBasicBlockGamut"   => 30,
343
+        );
344 344
 
345 345
 
346
-	function stripLinkDefinitions($text) {
347
-	#
348
-	# Strips link definitions from text, stores the URLs and titles in
349
-	# hash references.
350
-	#
351
-		$less_than_tab = $this->tab_width - 1;
346
+    function stripLinkDefinitions($text) {
347
+    #
348
+    # Strips link definitions from text, stores the URLs and titles in
349
+    # hash references.
350
+    #
351
+        $less_than_tab = $this->tab_width - 1;
352 352
 
353
-		# Link defs are in the form: ^[id]: url "optional title"
354
-		$text = preg_replace_callback('{
353
+        # Link defs are in the form: ^[id]: url "optional title"
354
+        $text = preg_replace_callback('{
355 355
 							^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?:	# id = $1
356 356
 							  [ ]*
357 357
 							  \n?				# maybe *one* newline
@@ -373,44 +373,44 @@  discard block
 block discarded – undo
373 373
 							)?	# title is optional
374 374
 							(?:\n+|\Z)
375 375
 			}xm',
376
-			array(&$this, '_stripLinkDefinitions_callback'),
377
-			$text);
378
-		return $text;
379
-	}
380
-	function _stripLinkDefinitions_callback($matches) {
381
-		$link_id = strtolower($matches[1]);
382
-		$url = $matches[2] == '' ? $matches[3] : $matches[2];
383
-		$this->urls[$link_id] = $url;
384
-		$this->titles[$link_id] =& $matches[4];
385
-		return ''; # String that will replace the block
386
-	}
387
-
388
-
389
-	function hashHTMLBlocks($text) {
390
-		if ($this->no_markup)  return $text;
391
-
392
-		$less_than_tab = $this->tab_width - 1;
393
-
394
-		# Hashify HTML blocks:
395
-		# We only want to do this for block-level HTML tags, such as headers,
396
-		# lists, and tables. That's because we still want to wrap <p>s around
397
-		# "paragraphs" that are wrapped in non-block-level tags, such as anchors,
398
-		# phrase emphasis, and spans. The list of tags we're looking for is
399
-		# hard-coded:
400
-		#
401
-		# *  List "a" is made of tags which can be both inline or block-level.
402
-		#    These will be treated block-level when the start tag is alone on
403
-		#    its line, otherwise they're not matched here and will be taken as
404
-		#    inline later.
405
-		# *  List "b" is made of tags which are always block-level;
406
-		#
407
-		$block_tags_a_re = 'ins|del';
408
-		$block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.
409
-						   'script|noscript|form|fieldset|iframe|math';
410
-
411
-		# Regular expression for the content of a block tag.
412
-		$nested_tags_level = 4;
413
-		$attr = '
376
+            array(&$this, '_stripLinkDefinitions_callback'),
377
+            $text);
378
+        return $text;
379
+    }
380
+    function _stripLinkDefinitions_callback($matches) {
381
+        $link_id = strtolower($matches[1]);
382
+        $url = $matches[2] == '' ? $matches[3] : $matches[2];
383
+        $this->urls[$link_id] = $url;
384
+        $this->titles[$link_id] =& $matches[4];
385
+        return ''; # String that will replace the block
386
+    }
387
+
388
+
389
+    function hashHTMLBlocks($text) {
390
+        if ($this->no_markup)  return $text;
391
+
392
+        $less_than_tab = $this->tab_width - 1;
393
+
394
+        # Hashify HTML blocks:
395
+        # We only want to do this for block-level HTML tags, such as headers,
396
+        # lists, and tables. That's because we still want to wrap <p>s around
397
+        # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
398
+        # phrase emphasis, and spans. The list of tags we're looking for is
399
+        # hard-coded:
400
+        #
401
+        # *  List "a" is made of tags which can be both inline or block-level.
402
+        #    These will be treated block-level when the start tag is alone on
403
+        #    its line, otherwise they're not matched here and will be taken as
404
+        #    inline later.
405
+        # *  List "b" is made of tags which are always block-level;
406
+        #
407
+        $block_tags_a_re = 'ins|del';
408
+        $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.
409
+                            'script|noscript|form|fieldset|iframe|math';
410
+
411
+        # Regular expression for the content of a block tag.
412
+        $nested_tags_level = 4;
413
+        $attr = '
414 414
 			(?>				# optional tag attributes
415 415
 			  \s			# starts with whitespace
416 416
 			  (?>
@@ -424,8 +424,8 @@  discard block
 block discarded – undo
424 424
 			  )*
425 425
 			)?
426 426
 			';
427
-		$content =
428
-			str_repeat('
427
+        $content =
428
+            str_repeat('
429 429
 				(?>
430 430
 				  [^<]+			# content without tag
431 431
 				|
@@ -435,29 +435,29 @@  discard block
 block discarded – undo
435 435
 					  />
436 436
 					|
437 437
 					  >', $nested_tags_level).	# end of opening tag
438
-					  '.*?'.					# last level nested tag content
439
-			str_repeat('
438
+                        '.*?'.					# last level nested tag content
439
+            str_repeat('
440 440
 					  </\2\s*>	# closing nested tag
441 441
 					)
442 442
 				  |
443 443
 					<(?!/\2\s*>	# other tags with a different name
444 444
 				  )
445 445
 				)*',
446
-				$nested_tags_level);
447
-		$content2 = str_replace('\2', '\3', $content);
448
-
449
-		# First, look for nested blocks, e.g.:
450
-		# 	<div>
451
-		# 		<div>
452
-		# 		tags for inner block must be indented.
453
-		# 		</div>
454
-		# 	</div>
455
-		#
456
-		# The outermost tags must start at the left margin for this to match, and
457
-		# the inner nested divs must be indented.
458
-		# We need to do this before the next, more liberal match, because the next
459
-		# match will start at the first `<div>` and stop at the first `</div>`.
460
-		$text = preg_replace_callback('{(?>
446
+                $nested_tags_level);
447
+        $content2 = str_replace('\2', '\3', $content);
448
+
449
+        # First, look for nested blocks, e.g.:
450
+        # 	<div>
451
+        # 		<div>
452
+        # 		tags for inner block must be indented.
453
+        # 		</div>
454
+        # 	</div>
455
+        #
456
+        # The outermost tags must start at the left margin for this to match, and
457
+        # the inner nested divs must be indented.
458
+        # We need to do this before the next, more liberal match, because the next
459
+        # match will start at the first `<div>` and stop at the first `</div>`.
460
+        $text = preg_replace_callback('{(?>
461 461
 			(?>
462 462
 				(?<=\n\n)		# Starting after a blank line
463 463
 				|				# or
@@ -518,97 +518,97 @@  discard block
 block discarded – undo
518 518
 
519 519
 			)
520 520
 			)}Sxmi',
521
-			array(&$this, '_hashHTMLBlocks_callback'),
522
-			$text);
523
-
524
-		return $text;
525
-	}
526
-	function _hashHTMLBlocks_callback($matches) {
527
-		$text = $matches[1];
528
-		$key  = $this->hashBlock($text);
529
-		return "\n\n$key\n\n";
530
-	}
531
-
532
-
533
-	function hashPart($text, $boundary = 'X') {
534
-	#
535
-	# Called whenever a tag must be hashed when a function insert an atomic
536
-	# element in the text stream. Passing $text to through this function gives
537
-	# a unique text-token which will be reverted back when calling unhash.
538
-	#
539
-	# The $boundary argument specify what character should be used to surround
540
-	# the token. By convension, "B" is used for block elements that needs not
541
-	# to be wrapped into paragraph tags at the end, ":" is used for elements
542
-	# that are word separators and "X" is used in the general case.
543
-	#
544
-		# Swap back any tag hash found in $text so we do not have to `unhash`
545
-		# multiple times at the end.
546
-		$text = $this->unhash($text);
547
-
548
-		# Then hash the block.
549
-		static $i = 0;
550
-		$key = "$boundary\x1A" . ++$i . $boundary;
551
-		$this->html_hashes[$key] = $text;
552
-		return $key; # String that will replace the tag.
553
-	}
554
-
555
-
556
-	function hashBlock($text) {
557
-	#
558
-	# Shortcut function for hashPart with block-level boundaries.
559
-	#
560
-		return $this->hashPart($text, 'B');
561
-	}
562
-
563
-
564
-	var $block_gamut = array(
565
-	#
566
-	# These are all the transformations that form block-level
567
-	# tags like paragraphs, headers, and list items.
568
-	#
569
-		"doHeaders"         => 10,
570
-		"doHorizontalRules" => 20,
571
-
572
-		"doLists"           => 40,
573
-		"doCodeBlocks"      => 50,
574
-		"doBlockQuotes"     => 60,
575
-		);
576
-
577
-	function runBlockGamut($text) {
578
-	#
579
-	# Run block gamut tranformations.
580
-	#
581
-		# We need to escape raw HTML in Markdown source before doing anything
582
-		# else. This need to be done for each block, and not only at the
583
-		# begining in the Markdown function since hashed blocks can be part of
584
-		# list items and could have been indented. Indented blocks would have
585
-		# been seen as a code block in a previous pass of hashHTMLBlocks.
586
-		$text = $this->hashHTMLBlocks($text);
587
-
588
-		return $this->runBasicBlockGamut($text);
589
-	}
590
-
591
-	function runBasicBlockGamut($text) {
592
-	#
593
-	# Run block gamut tranformations, without hashing HTML blocks. This is
594
-	# useful when HTML blocks are known to be already hashed, like in the first
595
-	# whole-document pass.
596
-	#
597
-		foreach ($this->block_gamut as $method => $priority) {
598
-			$text = $this->$method($text);
599
-		}
600
-
601
-		# Finally form paragraph and restore hashed blocks.
602
-		$text = $this->formParagraphs($text);
603
-
604
-		return $text;
605
-	}
606
-
607
-
608
-	function doHorizontalRules($text) {
609
-		# Do Horizontal Rules:
610
-		return preg_replace(
611
-			'{
521
+            array(&$this, '_hashHTMLBlocks_callback'),
522
+            $text);
523
+
524
+        return $text;
525
+    }
526
+    function _hashHTMLBlocks_callback($matches) {
527
+        $text = $matches[1];
528
+        $key  = $this->hashBlock($text);
529
+        return "\n\n$key\n\n";
530
+    }
531
+
532
+
533
+    function hashPart($text, $boundary = 'X') {
534
+    #
535
+    # Called whenever a tag must be hashed when a function insert an atomic
536
+    # element in the text stream. Passing $text to through this function gives
537
+    # a unique text-token which will be reverted back when calling unhash.
538
+    #
539
+    # The $boundary argument specify what character should be used to surround
540
+    # the token. By convension, "B" is used for block elements that needs not
541
+    # to be wrapped into paragraph tags at the end, ":" is used for elements
542
+    # that are word separators and "X" is used in the general case.
543
+    #
544
+        # Swap back any tag hash found in $text so we do not have to `unhash`
545
+        # multiple times at the end.
546
+        $text = $this->unhash($text);
547
+
548
+        # Then hash the block.
549
+        static $i = 0;
550
+        $key = "$boundary\x1A" . ++$i . $boundary;
551
+        $this->html_hashes[$key] = $text;
552
+        return $key; # String that will replace the tag.
553
+    }
554
+
555
+
556
+    function hashBlock($text) {
557
+    #
558
+    # Shortcut function for hashPart with block-level boundaries.
559
+    #
560
+        return $this->hashPart($text, 'B');
561
+    }
562
+
563
+
564
+    var $block_gamut = array(
565
+    #
566
+    # These are all the transformations that form block-level
567
+    # tags like paragraphs, headers, and list items.
568
+    #
569
+        "doHeaders"         => 10,
570
+        "doHorizontalRules" => 20,
571
+
572
+        "doLists"           => 40,
573
+        "doCodeBlocks"      => 50,
574
+        "doBlockQuotes"     => 60,
575
+        );
576
+
577
+    function runBlockGamut($text) {
578
+    #
579
+    # Run block gamut tranformations.
580
+    #
581
+        # We need to escape raw HTML in Markdown source before doing anything
582
+        # else. This need to be done for each block, and not only at the
583
+        # begining in the Markdown function since hashed blocks can be part of
584
+        # list items and could have been indented. Indented blocks would have
585
+        # been seen as a code block in a previous pass of hashHTMLBlocks.
586
+        $text = $this->hashHTMLBlocks($text);
587
+
588
+        return $this->runBasicBlockGamut($text);
589
+    }
590
+
591
+    function runBasicBlockGamut($text) {
592
+    #
593
+    # Run block gamut tranformations, without hashing HTML blocks. This is
594
+    # useful when HTML blocks are known to be already hashed, like in the first
595
+    # whole-document pass.
596
+    #
597
+        foreach ($this->block_gamut as $method => $priority) {
598
+            $text = $this->$method($text);
599
+        }
600
+
601
+        # Finally form paragraph and restore hashed blocks.
602
+        $text = $this->formParagraphs($text);
603
+
604
+        return $text;
605
+    }
606
+
607
+
608
+    function doHorizontalRules($text) {
609
+        # Do Horizontal Rules:
610
+        return preg_replace(
611
+            '{
612 612
 				^[ ]{0,3}	# Leading space
613 613
 				([-*_])		# $1: First marker
614 614
 				(?>			# Repeated marker group
@@ -618,68 +618,68 @@  discard block
 block discarded – undo
618 618
 				[ ]*		# Tailing spaces
619 619
 				$			# End of line.
620 620
 			}mx',
621
-			"\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
622
-			$text);
623
-	}
624
-
625
-
626
-	var $span_gamut = array(
627
-	#
628
-	# These are all the transformations that occur *within* block-level
629
-	# tags like paragraphs, headers, and list items.
630
-	#
631
-		# Process character escapes, code spans, and inline HTML
632
-		# in one shot.
633
-		"parseSpan"           => -30,
634
-
635
-		# Process anchor and image tags. Images must come first,
636
-		# because ![foo][f] looks like an anchor.
637
-		"doImages"            =>  10,
638
-		"doAnchors"           =>  20,
639
-
640
-		# Make links out of things like `<http://example.com/>`
641
-		# Must come after doAnchors, because you can use < and >
642
-		# delimiters in inline links like [this](<url>).
643
-		"doAutoLinks"         =>  30,
644
-		"encodeAmpsAndAngles" =>  40,
645
-
646
-		"doItalicsAndBold"    =>  50,
647
-		"doHardBreaks"        =>  60,
648
-		);
649
-
650
-	function runSpanGamut($text) {
651
-	#
652
-	# Run span gamut tranformations.
653
-	#
654
-		foreach ($this->span_gamut as $method => $priority) {
655
-			$text = $this->$method($text);
656
-		}
657
-
658
-		return $text;
659
-	}
660
-
661
-
662
-	function doHardBreaks($text) {
663
-		# Do hard breaks:
664
-		return preg_replace_callback('/ {2,}\n/',
665
-			array(&$this, '_doHardBreaks_callback'), $text);
666
-	}
667
-	function _doHardBreaks_callback($matches) {
668
-		return $this->hashPart("<br$this->empty_element_suffix\n");
669
-	}
670
-
671
-
672
-	function doAnchors($text) {
673
-	#
674
-	# Turn Markdown link shortcuts into XHTML <a> tags.
675
-	#
676
-		if ($this->in_anchor) return $text;
677
-		$this->in_anchor = true;
678
-
679
-		#
680
-		# First, handle reference-style links: [link text] [id]
681
-		#
682
-		$text = preg_replace_callback('{
621
+            "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
622
+            $text);
623
+    }
624
+
625
+
626
+    var $span_gamut = array(
627
+    #
628
+    # These are all the transformations that occur *within* block-level
629
+    # tags like paragraphs, headers, and list items.
630
+    #
631
+        # Process character escapes, code spans, and inline HTML
632
+        # in one shot.
633
+        "parseSpan"           => -30,
634
+
635
+        # Process anchor and image tags. Images must come first,
636
+        # because ![foo][f] looks like an anchor.
637
+        "doImages"            =>  10,
638
+        "doAnchors"           =>  20,
639
+
640
+        # Make links out of things like `<http://example.com/>`
641
+        # Must come after doAnchors, because you can use < and >
642
+        # delimiters in inline links like [this](<url>).
643
+        "doAutoLinks"         =>  30,
644
+        "encodeAmpsAndAngles" =>  40,
645
+
646
+        "doItalicsAndBold"    =>  50,
647
+        "doHardBreaks"        =>  60,
648
+        );
649
+
650
+    function runSpanGamut($text) {
651
+    #
652
+    # Run span gamut tranformations.
653
+    #
654
+        foreach ($this->span_gamut as $method => $priority) {
655
+            $text = $this->$method($text);
656
+        }
657
+
658
+        return $text;
659
+    }
660
+
661
+
662
+    function doHardBreaks($text) {
663
+        # Do hard breaks:
664
+        return preg_replace_callback('/ {2,}\n/',
665
+            array(&$this, '_doHardBreaks_callback'), $text);
666
+    }
667
+    function _doHardBreaks_callback($matches) {
668
+        return $this->hashPart("<br$this->empty_element_suffix\n");
669
+    }
670
+
671
+
672
+    function doAnchors($text) {
673
+    #
674
+    # Turn Markdown link shortcuts into XHTML <a> tags.
675
+    #
676
+        if ($this->in_anchor) return $text;
677
+        $this->in_anchor = true;
678
+
679
+        #
680
+        # First, handle reference-style links: [link text] [id]
681
+        #
682
+        $text = preg_replace_callback('{
683 683
 			(					# wrap whole match in $1
684 684
 			  \[
685 685
 				('.$this->nested_brackets_re.')	# link text = $2
@@ -693,12 +693,12 @@  discard block
 block discarded – undo
693 693
 			  \]
694 694
 			)
695 695
 			}xs',
696
-			array(&$this, '_doAnchors_reference_callback'), $text);
696
+            array(&$this, '_doAnchors_reference_callback'), $text);
697 697
 
698
-		#
699
-		# Next, inline-style links: [link text](url "optional title")
700
-		#
701
-		$text = preg_replace_callback('{
698
+        #
699
+        # Next, inline-style links: [link text](url "optional title")
700
+        #
701
+        $text = preg_replace_callback('{
702 702
 			(				# wrap whole match in $1
703 703
 			  \[
704 704
 				('.$this->nested_brackets_re.')	# link text = $2
@@ -720,88 +720,88 @@  discard block
 block discarded – undo
720 720
 			  \)
721 721
 			)
722 722
 			}xs',
723
-			array(&$this, '_doAnchors_inline_callback'), $text);
724
-
725
-		#
726
-		# Last, handle reference-style shortcuts: [link text]
727
-		# These must come last in case you've also got [link text][1]
728
-		# or [link text](/foo)
729
-		#
730
-		$text = preg_replace_callback('{
723
+            array(&$this, '_doAnchors_inline_callback'), $text);
724
+
725
+        #
726
+        # Last, handle reference-style shortcuts: [link text]
727
+        # These must come last in case you've also got [link text][1]
728
+        # or [link text](/foo)
729
+        #
730
+        $text = preg_replace_callback('{
731 731
 			(					# wrap whole match in $1
732 732
 			  \[
733 733
 				([^\[\]]+)		# link text = $2; can\'t contain [ or ]
734 734
 			  \]
735 735
 			)
736 736
 			}xs',
737
-			array(&$this, '_doAnchors_reference_callback'), $text);
738
-
739
-		$this->in_anchor = false;
740
-		return $text;
741
-	}
742
-	function _doAnchors_reference_callback($matches) {
743
-		$whole_match =  $matches[1];
744
-		$link_text   =  $matches[2];
745
-		$link_id     =& $matches[3];
746
-
747
-		if ($link_id == "") {
748
-			# for shortcut links like [this][] or [this].
749
-			$link_id = $link_text;
750
-		}
751
-
752
-		# lower-case and turn embedded newlines into spaces
753
-		$link_id = strtolower($link_id);
754
-		$link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
755
-
756
-		if (isset($this->urls[$link_id])) {
757
-			$url = $this->urls[$link_id];
758
-			$url = $this->encodeAttribute($url);
759
-
760
-			$result = "<a href=\"$url\"";
761
-			if ( isset( $this->titles[$link_id] ) ) {
762
-				$title = $this->titles[$link_id];
763
-				$title = $this->encodeAttribute($title);
764
-				$result .=  " title=\"$title\"";
765
-			}
766
-
767
-			$link_text = $this->runSpanGamut($link_text);
768
-			$result .= ">$link_text</a>";
769
-			$result = $this->hashPart($result);
770
-		}
771
-		else {
772
-			$result = $whole_match;
773
-		}
774
-		return $result;
775
-	}
776
-	function _doAnchors_inline_callback($matches) {
777
-		$whole_match	=  $matches[1];
778
-		$link_text		=  $this->runSpanGamut($matches[2]);
779
-		$url			=  $matches[3] == '' ? $matches[4] : $matches[3];
780
-		$title			=& $matches[7];
781
-
782
-		$url = $this->encodeAttribute($url);
783
-
784
-		$result = "<a href=\"$url\"";
785
-		if (isset($title)) {
786
-			$title = $this->encodeAttribute($title);
787
-			$result .=  " title=\"$title\"";
788
-		}
789
-
790
-		$link_text = $this->runSpanGamut($link_text);
791
-		$result .= ">$link_text</a>";
792
-
793
-		return $this->hashPart($result);
794
-	}
795
-
796
-
797
-	function doImages($text) {
798
-	#
799
-	# Turn Markdown image shortcuts into <img> tags.
800
-	#
801
-		#
802
-		# First, handle reference-style labeled images: ![alt text][id]
803
-		#
804
-		$text = preg_replace_callback('{
737
+            array(&$this, '_doAnchors_reference_callback'), $text);
738
+
739
+        $this->in_anchor = false;
740
+        return $text;
741
+    }
742
+    function _doAnchors_reference_callback($matches) {
743
+        $whole_match =  $matches[1];
744
+        $link_text   =  $matches[2];
745
+        $link_id     =& $matches[3];
746
+
747
+        if ($link_id == "") {
748
+            # for shortcut links like [this][] or [this].
749
+            $link_id = $link_text;
750
+        }
751
+
752
+        # lower-case and turn embedded newlines into spaces
753
+        $link_id = strtolower($link_id);
754
+        $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
755
+
756
+        if (isset($this->urls[$link_id])) {
757
+            $url = $this->urls[$link_id];
758
+            $url = $this->encodeAttribute($url);
759
+
760
+            $result = "<a href=\"$url\"";
761
+            if ( isset( $this->titles[$link_id] ) ) {
762
+                $title = $this->titles[$link_id];
763
+                $title = $this->encodeAttribute($title);
764
+                $result .=  " title=\"$title\"";
765
+            }
766
+
767
+            $link_text = $this->runSpanGamut($link_text);
768
+            $result .= ">$link_text</a>";
769
+            $result = $this->hashPart($result);
770
+        }
771
+        else {
772
+            $result = $whole_match;
773
+        }
774
+        return $result;
775
+    }
776
+    function _doAnchors_inline_callback($matches) {
777
+        $whole_match	=  $matches[1];
778
+        $link_text		=  $this->runSpanGamut($matches[2]);
779
+        $url			=  $matches[3] == '' ? $matches[4] : $matches[3];
780
+        $title			=& $matches[7];
781
+
782
+        $url = $this->encodeAttribute($url);
783
+
784
+        $result = "<a href=\"$url\"";
785
+        if (isset($title)) {
786
+            $title = $this->encodeAttribute($title);
787
+            $result .=  " title=\"$title\"";
788
+        }
789
+
790
+        $link_text = $this->runSpanGamut($link_text);
791
+        $result .= ">$link_text</a>";
792
+
793
+        return $this->hashPart($result);
794
+    }
795
+
796
+
797
+    function doImages($text) {
798
+    #
799
+    # Turn Markdown image shortcuts into <img> tags.
800
+    #
801
+        #
802
+        # First, handle reference-style labeled images: ![alt text][id]
803
+        #
804
+        $text = preg_replace_callback('{
805 805
 			(				# wrap whole match in $1
806 806
 			  !\[
807 807
 				('.$this->nested_brackets_re.')		# alt text = $2
@@ -816,13 +816,13 @@  discard block
 block discarded – undo
816 816
 
817 817
 			)
818 818
 			}xs',
819
-			array(&$this, '_doImages_reference_callback'), $text);
819
+            array(&$this, '_doImages_reference_callback'), $text);
820 820
 
821
-		#
822
-		# Next, handle inline images:  ![alt text](url "optional title")
823
-		# Don't forget: encode * and _
824
-		#
825
-		$text = preg_replace_callback('{
821
+        #
822
+        # Next, handle inline images:  ![alt text](url "optional title")
823
+        # Don't forget: encode * and _
824
+        #
825
+        $text = preg_replace_callback('{
826 826
 			(				# wrap whole match in $1
827 827
 			  !\[
828 828
 				('.$this->nested_brackets_re.')		# alt text = $2
@@ -845,76 +845,76 @@  discard block
 block discarded – undo
845 845
 			  \)
846 846
 			)
847 847
 			}xs',
848
-			array(&$this, '_doImages_inline_callback'), $text);
849
-
850
-		return $text;
851
-	}
852
-	function _doImages_reference_callback($matches) {
853
-		$whole_match = $matches[1];
854
-		$alt_text    = $matches[2];
855
-		$link_id     = strtolower($matches[3]);
856
-
857
-		if ($link_id == "") {
858
-			$link_id = strtolower($alt_text); # for shortcut links like ![this][].
859
-		}
860
-
861
-		$alt_text = $this->encodeAttribute($alt_text);
862
-		if (isset($this->urls[$link_id])) {
863
-			$url = $this->encodeAttribute($this->urls[$link_id]);
864
-			$result = "<img src=\"$url\" alt=\"$alt_text\"";
865
-			if (isset($this->titles[$link_id])) {
866
-				$title = $this->titles[$link_id];
867
-				$title = $this->encodeAttribute($title);
868
-				$result .=  " title=\"$title\"";
869
-			}
870
-			$result .= $this->empty_element_suffix;
871
-			$result = $this->hashPart($result);
872
-		}
873
-		else {
874
-			# If there's no such link ID, leave intact:
875
-			$result = $whole_match;
876
-		}
877
-
878
-		return $result;
879
-	}
880
-	function _doImages_inline_callback($matches) {
881
-		$whole_match	= $matches[1];
882
-		$alt_text		= $matches[2];
883
-		$url			= $matches[3] == '' ? $matches[4] : $matches[3];
884
-		$title			=& $matches[7];
885
-
886
-		$alt_text = $this->encodeAttribute($alt_text);
887
-		$url = $this->encodeAttribute($url);
888
-		$result = "<img src=\"$url\" alt=\"$alt_text\"";
889
-		if (isset($title)) {
890
-			$title = $this->encodeAttribute($title);
891
-			$result .=  " title=\"$title\""; # $title already quoted
892
-		}
893
-		$result .= $this->empty_element_suffix;
894
-
895
-		return $this->hashPart($result);
896
-	}
897
-
898
-
899
-	function doHeaders($text) {
900
-		# Setext-style headers:
901
-		#	  Header 1
902
-		#	  ========
903
-		#
904
-		#	  Header 2
905
-		#	  --------
906
-		#
907
-		$text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
908
-			array(&$this, '_doHeaders_callback_setext'), $text);
909
-
910
-		# atx-style headers:
911
-		#	# Header 1
912
-		#	## Header 2
913
-		#	## Header 2 with closing hashes ##
914
-		#	...
915
-		#	###### Header 6
916
-		#
917
-		$text = preg_replace_callback('{
848
+            array(&$this, '_doImages_inline_callback'), $text);
849
+
850
+        return $text;
851
+    }
852
+    function _doImages_reference_callback($matches) {
853
+        $whole_match = $matches[1];
854
+        $alt_text    = $matches[2];
855
+        $link_id     = strtolower($matches[3]);
856
+
857
+        if ($link_id == "") {
858
+            $link_id = strtolower($alt_text); # for shortcut links like ![this][].
859
+        }
860
+
861
+        $alt_text = $this->encodeAttribute($alt_text);
862
+        if (isset($this->urls[$link_id])) {
863
+            $url = $this->encodeAttribute($this->urls[$link_id]);
864
+            $result = "<img src=\"$url\" alt=\"$alt_text\"";
865
+            if (isset($this->titles[$link_id])) {
866
+                $title = $this->titles[$link_id];
867
+                $title = $this->encodeAttribute($title);
868
+                $result .=  " title=\"$title\"";
869
+            }
870
+            $result .= $this->empty_element_suffix;
871
+            $result = $this->hashPart($result);
872
+        }
873
+        else {
874
+            # If there's no such link ID, leave intact:
875
+            $result = $whole_match;
876
+        }
877
+
878
+        return $result;
879
+    }
880
+    function _doImages_inline_callback($matches) {
881
+        $whole_match	= $matches[1];
882
+        $alt_text		= $matches[2];
883
+        $url			= $matches[3] == '' ? $matches[4] : $matches[3];
884
+        $title			=& $matches[7];
885
+
886
+        $alt_text = $this->encodeAttribute($alt_text);
887
+        $url = $this->encodeAttribute($url);
888
+        $result = "<img src=\"$url\" alt=\"$alt_text\"";
889
+        if (isset($title)) {
890
+            $title = $this->encodeAttribute($title);
891
+            $result .=  " title=\"$title\""; # $title already quoted
892
+        }
893
+        $result .= $this->empty_element_suffix;
894
+
895
+        return $this->hashPart($result);
896
+    }
897
+
898
+
899
+    function doHeaders($text) {
900
+        # Setext-style headers:
901
+        #	  Header 1
902
+        #	  ========
903
+        #
904
+        #	  Header 2
905
+        #	  --------
906
+        #
907
+        $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
908
+            array(&$this, '_doHeaders_callback_setext'), $text);
909
+
910
+        # atx-style headers:
911
+        #	# Header 1
912
+        #	## Header 2
913
+        #	## Header 2 with closing hashes ##
914
+        #	...
915
+        #	###### Header 6
916
+        #
917
+        $text = preg_replace_callback('{
918 918
 				^(\#{1,6})	# $1 = string of #\'s
919 919
 				[ ]*
920 920
 				(.+?)		# $2 = Header text
@@ -922,45 +922,45 @@  discard block
 block discarded – undo
922 922
 				\#*			# optional closing #\'s (not counted)
923 923
 				\n+
924 924
 			}xm',
925
-			array(&$this, '_doHeaders_callback_atx'), $text);
926
-
927
-		return $text;
928
-	}
929
-	function _doHeaders_callback_setext($matches) {
930
-		# Terrible hack to check we haven't found an empty list item.
931
-		if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
932
-			return $matches[0];
933
-
934
-		$level = $matches[2]{0} == '=' ? 1 : 2;
935
-		$block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
936
-		return "\n" . $this->hashBlock($block) . "\n\n";
937
-	}
938
-	function _doHeaders_callback_atx($matches) {
939
-		$level = strlen($matches[1]);
940
-		$block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
941
-		return "\n" . $this->hashBlock($block) . "\n\n";
942
-	}
943
-
944
-
945
-	function doLists($text) {
946
-	#
947
-	# Form HTML ordered (numbered) and unordered (bulleted) lists.
948
-	#
949
-		$less_than_tab = $this->tab_width - 1;
950
-
951
-		# Re-usable patterns to match list item bullets and number markers:
952
-		$marker_ul_re  = '[*+-]';
953
-		$marker_ol_re  = '\d+[.]';
954
-		$marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
955
-
956
-		$markers_relist = array(
957
-			$marker_ul_re => $marker_ol_re,
958
-			$marker_ol_re => $marker_ul_re,
959
-			);
960
-
961
-		foreach ($markers_relist as $marker_re => $other_marker_re) {
962
-			# Re-usable pattern to match any entirel ul or ol list:
963
-			$whole_list_re = '
925
+            array(&$this, '_doHeaders_callback_atx'), $text);
926
+
927
+        return $text;
928
+    }
929
+    function _doHeaders_callback_setext($matches) {
930
+        # Terrible hack to check we haven't found an empty list item.
931
+        if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
932
+            return $matches[0];
933
+
934
+        $level = $matches[2]{0} == '=' ? 1 : 2;
935
+        $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
936
+        return "\n" . $this->hashBlock($block) . "\n\n";
937
+    }
938
+    function _doHeaders_callback_atx($matches) {
939
+        $level = strlen($matches[1]);
940
+        $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
941
+        return "\n" . $this->hashBlock($block) . "\n\n";
942
+    }
943
+
944
+
945
+    function doLists($text) {
946
+    #
947
+    # Form HTML ordered (numbered) and unordered (bulleted) lists.
948
+    #
949
+        $less_than_tab = $this->tab_width - 1;
950
+
951
+        # Re-usable patterns to match list item bullets and number markers:
952
+        $marker_ul_re  = '[*+-]';
953
+        $marker_ol_re  = '\d+[.]';
954
+        $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
955
+
956
+        $markers_relist = array(
957
+            $marker_ul_re => $marker_ol_re,
958
+            $marker_ol_re => $marker_ul_re,
959
+            );
960
+
961
+        foreach ($markers_relist as $marker_re => $other_marker_re) {
962
+            # Re-usable pattern to match any entirel ul or ol list:
963
+            $whole_list_re = '
964 964
 				(								# $1 = whole list
965 965
 				  (								# $2
966 966
 					([ ]{0,'.$less_than_tab.'})	# $3 = number of spaces
@@ -987,79 +987,79 @@  discard block
 block discarded – undo
987 987
 				)
988 988
 			'; // mx
989 989
 
990
-			# We use a different prefix before nested lists than top-level lists.
991
-			# See extended comment in _ProcessListItems().
990
+            # We use a different prefix before nested lists than top-level lists.
991
+            # See extended comment in _ProcessListItems().
992 992
 
993
-			if ($this->list_level) {
994
-				$text = preg_replace_callback('{
993
+            if ($this->list_level) {
994
+                $text = preg_replace_callback('{
995 995
 						^
996 996
 						'.$whole_list_re.'
997 997
 					}mx',
998
-					array(&$this, '_doLists_callback'), $text);
999
-			}
1000
-			else {
1001
-				$text = preg_replace_callback('{
998
+                    array(&$this, '_doLists_callback'), $text);
999
+            }
1000
+            else {
1001
+                $text = preg_replace_callback('{
1002 1002
 						(?:(?<=\n)\n|\A\n?) # Must eat the newline
1003 1003
 						'.$whole_list_re.'
1004 1004
 					}mx',
1005
-					array(&$this, '_doLists_callback'), $text);
1006
-			}
1007
-		}
1008
-
1009
-		return $text;
1010
-	}
1011
-	function _doLists_callback($matches) {
1012
-		# Re-usable patterns to match list item bullets and number markers:
1013
-		$marker_ul_re  = '[*+-]';
1014
-		$marker_ol_re  = '\d+[.]';
1015
-		$marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
1016
-
1017
-		$list = $matches[1];
1018
-		$list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
1019
-
1020
-		$marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
1021
-
1022
-		$list .= "\n";
1023
-		$result = $this->processListItems($list, $marker_any_re);
1024
-
1025
-		$result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
1026
-		return "\n". $result ."\n\n";
1027
-	}
1028
-
1029
-	var $list_level = 0;
1030
-
1031
-	function processListItems($list_str, $marker_any_re) {
1032
-	#
1033
-	#	Process the contents of a single ordered or unordered list, splitting it
1034
-	#	into individual list items.
1035
-	#
1036
-		# The $this->list_level global keeps track of when we're inside a list.
1037
-		# Each time we enter a list, we increment it; when we leave a list,
1038
-		# we decrement. If it's zero, we're not in a list anymore.
1039
-		#
1040
-		# We do this because when we're not inside a list, we want to treat
1041
-		# something like this:
1042
-		#
1043
-		#		I recommend upgrading to version
1044
-		#		8. Oops, now this line is treated
1045
-		#		as a sub-list.
1046
-		#
1047
-		# As a single paragraph, despite the fact that the second line starts
1048
-		# with a digit-period-space sequence.
1049
-		#
1050
-		# Whereas when we're inside a list (or sub-list), that line will be
1051
-		# treated as the start of a sub-list. What a kludge, huh? This is
1052
-		# an aspect of Markdown's syntax that's hard to parse perfectly
1053
-		# without resorting to mind-reading. Perhaps the solution is to
1054
-		# change the syntax rules such that sub-lists must start with a
1055
-		# starting cardinal number; e.g. "1." or "a.".
1056
-
1057
-		$this->list_level++;
1058
-
1059
-		# trim trailing blank lines:
1060
-		$list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
1061
-
1062
-		$list_str = preg_replace_callback('{
1005
+                    array(&$this, '_doLists_callback'), $text);
1006
+            }
1007
+        }
1008
+
1009
+        return $text;
1010
+    }
1011
+    function _doLists_callback($matches) {
1012
+        # Re-usable patterns to match list item bullets and number markers:
1013
+        $marker_ul_re  = '[*+-]';
1014
+        $marker_ol_re  = '\d+[.]';
1015
+        $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
1016
+
1017
+        $list = $matches[1];
1018
+        $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
1019
+
1020
+        $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
1021
+
1022
+        $list .= "\n";
1023
+        $result = $this->processListItems($list, $marker_any_re);
1024
+
1025
+        $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
1026
+        return "\n". $result ."\n\n";
1027
+    }
1028
+
1029
+    var $list_level = 0;
1030
+
1031
+    function processListItems($list_str, $marker_any_re) {
1032
+    #
1033
+    #	Process the contents of a single ordered or unordered list, splitting it
1034
+    #	into individual list items.
1035
+    #
1036
+        # The $this->list_level global keeps track of when we're inside a list.
1037
+        # Each time we enter a list, we increment it; when we leave a list,
1038
+        # we decrement. If it's zero, we're not in a list anymore.
1039
+        #
1040
+        # We do this because when we're not inside a list, we want to treat
1041
+        # something like this:
1042
+        #
1043
+        #		I recommend upgrading to version
1044
+        #		8. Oops, now this line is treated
1045
+        #		as a sub-list.
1046
+        #
1047
+        # As a single paragraph, despite the fact that the second line starts
1048
+        # with a digit-period-space sequence.
1049
+        #
1050
+        # Whereas when we're inside a list (or sub-list), that line will be
1051
+        # treated as the start of a sub-list. What a kludge, huh? This is
1052
+        # an aspect of Markdown's syntax that's hard to parse perfectly
1053
+        # without resorting to mind-reading. Perhaps the solution is to
1054
+        # change the syntax rules such that sub-lists must start with a
1055
+        # starting cardinal number; e.g. "1." or "a.".
1056
+
1057
+        $this->list_level++;
1058
+
1059
+        # trim trailing blank lines:
1060
+        $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
1061
+
1062
+        $list_str = preg_replace_callback('{
1063 1063
 			(\n)?							# leading line = $1
1064 1064
 			(^[ ]*)							# leading whitespace = $2
1065 1065
 			('.$marker_any_re.'				# list marker and space = $3
@@ -1069,41 +1069,41 @@  discard block
 block discarded – undo
1069 1069
 			(?:(\n+(?=\n))|\n)				# tailing blank line = $5
1070 1070
 			(?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
1071 1071
 			}xm',
1072
-			array(&$this, '_processListItems_callback'), $list_str);
1073
-
1074
-		$this->list_level--;
1075
-		return $list_str;
1076
-	}
1077
-	function _processListItems_callback($matches) {
1078
-		$item = $matches[4];
1079
-		$leading_line =& $matches[1];
1080
-		$leading_space =& $matches[2];
1081
-		$marker_space = $matches[3];
1082
-		$tailing_blank_line =& $matches[5];
1083
-
1084
-		if ($leading_line || $tailing_blank_line ||
1085
-			preg_match('/\n{2,}/', $item))
1086
-		{
1087
-			# Replace marker with the appropriate whitespace indentation
1088
-			$item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
1089
-			$item = $this->runBlockGamut($this->outdent($item)."\n");
1090
-		}
1091
-		else {
1092
-			# Recursion for sub-lists:
1093
-			$item = $this->doLists($this->outdent($item));
1094
-			$item = preg_replace('/\n+$/', '', $item);
1095
-			$item = $this->runSpanGamut($item);
1096
-		}
1097
-
1098
-		return "<li>" . $item . "</li>\n";
1099
-	}
1100
-
1101
-
1102
-	function doCodeBlocks($text) {
1103
-	#
1104
-	#	Process Markdown `<pre><code>` blocks.
1105
-	#
1106
-		$text = preg_replace_callback('{
1072
+            array(&$this, '_processListItems_callback'), $list_str);
1073
+
1074
+        $this->list_level--;
1075
+        return $list_str;
1076
+    }
1077
+    function _processListItems_callback($matches) {
1078
+        $item = $matches[4];
1079
+        $leading_line =& $matches[1];
1080
+        $leading_space =& $matches[2];
1081
+        $marker_space = $matches[3];
1082
+        $tailing_blank_line =& $matches[5];
1083
+
1084
+        if ($leading_line || $tailing_blank_line ||
1085
+            preg_match('/\n{2,}/', $item))
1086
+        {
1087
+            # Replace marker with the appropriate whitespace indentation
1088
+            $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
1089
+            $item = $this->runBlockGamut($this->outdent($item)."\n");
1090
+        }
1091
+        else {
1092
+            # Recursion for sub-lists:
1093
+            $item = $this->doLists($this->outdent($item));
1094
+            $item = preg_replace('/\n+$/', '', $item);
1095
+            $item = $this->runSpanGamut($item);
1096
+        }
1097
+
1098
+        return "<li>" . $item . "</li>\n";
1099
+    }
1100
+
1101
+
1102
+    function doCodeBlocks($text) {
1103
+    #
1104
+    #	Process Markdown `<pre><code>` blocks.
1105
+    #
1106
+        $text = preg_replace_callback('{
1107 1107
 				(?:\n\n|\A\n?)
1108 1108
 				(	            # $1 = the code block -- one or more lines, starting with a space/tab
1109 1109
 				  (?>
@@ -1113,197 +1113,197 @@  discard block
 block discarded – undo
1113 1113
 				)
1114 1114
 				((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z)	# Lookahead for non-space at line-start, or end of doc
1115 1115
 			}xm',
1116
-			array(&$this, '_doCodeBlocks_callback'), $text);
1117
-
1118
-		return $text;
1119
-	}
1120
-	function _doCodeBlocks_callback($matches) {
1121
-		$codeblock = $matches[1];
1122
-
1123
-		$codeblock = $this->outdent($codeblock);
1124
-		$codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
1125
-
1126
-		# trim leading newlines and trailing newlines
1127
-		$codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
1128
-
1129
-		$codeblock = "<pre><code>$codeblock\n</code></pre>";
1130
-		return "\n\n".$this->hashBlock($codeblock)."\n\n";
1131
-	}
1132
-
1133
-
1134
-	function makeCodeSpan($code) {
1135
-	#
1136
-	# Create a code span markup for $code. Called from handleSpanToken.
1137
-	#
1138
-		$code = htmlspecialchars(trim($code), ENT_NOQUOTES);
1139
-		return $this->hashPart("<code>$code</code>");
1140
-	}
1141
-
1142
-
1143
-	var $em_relist = array(
1144
-		''  => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![.,:;]\s)',
1145
-		'*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
1146
-		'_' => '(?<=\S|^)(?<!_)_(?!_)',
1147
-		);
1148
-	var $strong_relist = array(
1149
-		''   => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![.,:;]\s)',
1150
-		'**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
1151
-		'__' => '(?<=\S|^)(?<!_)__(?!_)',
1152
-		);
1153
-	var $em_strong_relist = array(
1154
-		''    => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![.,:;]\s)',
1155
-		'***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
1156
-		'___' => '(?<=\S|^)(?<!_)___(?!_)',
1157
-		);
1158
-	var $em_strong_prepared_relist;
1159
-
1160
-	function prepareItalicsAndBold() {
1161
-	#
1162
-	# Prepare regular expressions for searching emphasis tokens in any
1163
-	# context.
1164
-	#
1165
-		foreach ($this->em_relist as $em => $em_re) {
1166
-			foreach ($this->strong_relist as $strong => $strong_re) {
1167
-				# Construct list of allowed token expressions.
1168
-				$token_relist = array();
1169
-				if (isset($this->em_strong_relist["$em$strong"])) {
1170
-					$token_relist[] = $this->em_strong_relist["$em$strong"];
1171
-				}
1172
-				$token_relist[] = $em_re;
1173
-				$token_relist[] = $strong_re;
1174
-
1175
-				# Construct master expression from list.
1176
-				$token_re = '{('. implode('|', $token_relist) .')}';
1177
-				$this->em_strong_prepared_relist["$em$strong"] = $token_re;
1178
-			}
1179
-		}
1180
-	}
1181
-
1182
-	function doItalicsAndBold($text) {
1183
-		$token_stack = array('');
1184
-		$text_stack = array('');
1185
-		$em = '';
1186
-		$strong = '';
1187
-		$tree_char_em = false;
1188
-
1189
-		while (1) {
1190
-			#
1191
-			# Get prepared regular expression for seraching emphasis tokens
1192
-			# in current context.
1193
-			#
1194
-			$token_re = $this->em_strong_prepared_relist["$em$strong"];
1195
-
1196
-			#
1197
-			# Each loop iteration search for the next emphasis token.
1198
-			# Each token is then passed to handleSpanToken.
1199
-			#
1200
-			$parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
1201
-			$text_stack[0] .= $parts[0];
1202
-			$token =& $parts[1];
1203
-			$text =& $parts[2];
1204
-
1205
-			if (empty($token)) {
1206
-				# Reached end of text span: empty stack without emitting.
1207
-				# any more emphasis.
1208
-				while ($token_stack[0]) {
1209
-					$text_stack[1] .= array_shift($token_stack);
1210
-					$text_stack[0] .= array_shift($text_stack);
1211
-				}
1212
-				break;
1213
-			}
1214
-
1215
-			$token_len = strlen($token);
1216
-			if ($tree_char_em) {
1217
-				# Reached closing marker while inside a three-char emphasis.
1218
-				if ($token_len == 3) {
1219
-					# Three-char closing marker, close em and strong.
1220
-					array_shift($token_stack);
1221
-					$span = array_shift($text_stack);
1222
-					$span = $this->runSpanGamut($span);
1223
-					$span = "<strong><em>$span</em></strong>";
1224
-					$text_stack[0] .= $this->hashPart($span);
1225
-					$em = '';
1226
-					$strong = '';
1227
-				} else {
1228
-					# Other closing marker: close one em or strong and
1229
-					# change current token state to match the other
1230
-					$token_stack[0] = str_repeat($token{0}, 3-$token_len);
1231
-					$tag = $token_len == 2 ? "strong" : "em";
1232
-					$span = $text_stack[0];
1233
-					$span = $this->runSpanGamut($span);
1234
-					$span = "<$tag>$span</$tag>";
1235
-					$text_stack[0] = $this->hashPart($span);
1236
-					$$tag = ''; # $$tag stands for $em or $strong
1237
-				}
1238
-				$tree_char_em = false;
1239
-			} else if ($token_len == 3) {
1240
-				if ($em) {
1241
-					# Reached closing marker for both em and strong.
1242
-					# Closing strong marker:
1243
-					for ($i = 0; $i < 2; ++$i) {
1244
-						$shifted_token = array_shift($token_stack);
1245
-						$tag = strlen($shifted_token) == 2 ? "strong" : "em";
1246
-						$span = array_shift($text_stack);
1247
-						$span = $this->runSpanGamut($span);
1248
-						$span = "<$tag>$span</$tag>";
1249
-						$text_stack[0] .= $this->hashPart($span);
1250
-						$$tag = ''; # $$tag stands for $em or $strong
1251
-					}
1252
-				} else {
1253
-					# Reached opening three-char emphasis marker. Push on token
1254
-					# stack; will be handled by the special condition above.
1255
-					$em = $token{0};
1256
-					$strong = "$em$em";
1257
-					array_unshift($token_stack, $token);
1258
-					array_unshift($text_stack, '');
1259
-					$tree_char_em = true;
1260
-				}
1261
-			} else if ($token_len == 2) {
1262
-				if ($strong) {
1263
-					# Unwind any dangling emphasis marker:
1264
-					if (strlen($token_stack[0]) == 1) {
1265
-						$text_stack[1] .= array_shift($token_stack);
1266
-						$text_stack[0] .= array_shift($text_stack);
1267
-					}
1268
-					# Closing strong marker:
1269
-					array_shift($token_stack);
1270
-					$span = array_shift($text_stack);
1271
-					$span = $this->runSpanGamut($span);
1272
-					$span = "<strong>$span</strong>";
1273
-					$text_stack[0] .= $this->hashPart($span);
1274
-					$strong = '';
1275
-				} else {
1276
-					array_unshift($token_stack, $token);
1277
-					array_unshift($text_stack, '');
1278
-					$strong = $token;
1279
-				}
1280
-			} else {
1281
-				# Here $token_len == 1
1282
-				if ($em) {
1283
-					if (strlen($token_stack[0]) == 1) {
1284
-						# Closing emphasis marker:
1285
-						array_shift($token_stack);
1286
-						$span = array_shift($text_stack);
1287
-						$span = $this->runSpanGamut($span);
1288
-						$span = "<em>$span</em>";
1289
-						$text_stack[0] .= $this->hashPart($span);
1290
-						$em = '';
1291
-					} else {
1292
-						$text_stack[0] .= $token;
1293
-					}
1294
-				} else {
1295
-					array_unshift($token_stack, $token);
1296
-					array_unshift($text_stack, '');
1297
-					$em = $token;
1298
-				}
1299
-			}
1300
-		}
1301
-		return $text_stack[0];
1302
-	}
1303
-
1304
-
1305
-	function doBlockQuotes($text) {
1306
-		$text = preg_replace_callback('/
1116
+            array(&$this, '_doCodeBlocks_callback'), $text);
1117
+
1118
+        return $text;
1119
+    }
1120
+    function _doCodeBlocks_callback($matches) {
1121
+        $codeblock = $matches[1];
1122
+
1123
+        $codeblock = $this->outdent($codeblock);
1124
+        $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
1125
+
1126
+        # trim leading newlines and trailing newlines
1127
+        $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
1128
+
1129
+        $codeblock = "<pre><code>$codeblock\n</code></pre>";
1130
+        return "\n\n".$this->hashBlock($codeblock)."\n\n";
1131
+    }
1132
+
1133
+
1134
+    function makeCodeSpan($code) {
1135
+    #
1136
+    # Create a code span markup for $code. Called from handleSpanToken.
1137
+    #
1138
+        $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
1139
+        return $this->hashPart("<code>$code</code>");
1140
+    }
1141
+
1142
+
1143
+    var $em_relist = array(
1144
+        ''  => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![.,:;]\s)',
1145
+        '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
1146
+        '_' => '(?<=\S|^)(?<!_)_(?!_)',
1147
+        );
1148
+    var $strong_relist = array(
1149
+        ''   => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![.,:;]\s)',
1150
+        '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
1151
+        '__' => '(?<=\S|^)(?<!_)__(?!_)',
1152
+        );
1153
+    var $em_strong_relist = array(
1154
+        ''    => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![.,:;]\s)',
1155
+        '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
1156
+        '___' => '(?<=\S|^)(?<!_)___(?!_)',
1157
+        );
1158
+    var $em_strong_prepared_relist;
1159
+
1160
+    function prepareItalicsAndBold() {
1161
+    #
1162
+    # Prepare regular expressions for searching emphasis tokens in any
1163
+    # context.
1164
+    #
1165
+        foreach ($this->em_relist as $em => $em_re) {
1166
+            foreach ($this->strong_relist as $strong => $strong_re) {
1167
+                # Construct list of allowed token expressions.
1168
+                $token_relist = array();
1169
+                if (isset($this->em_strong_relist["$em$strong"])) {
1170
+                    $token_relist[] = $this->em_strong_relist["$em$strong"];
1171
+                }
1172
+                $token_relist[] = $em_re;
1173
+                $token_relist[] = $strong_re;
1174
+
1175
+                # Construct master expression from list.
1176
+                $token_re = '{('. implode('|', $token_relist) .')}';
1177
+                $this->em_strong_prepared_relist["$em$strong"] = $token_re;
1178
+            }
1179
+        }
1180
+    }
1181
+
1182
+    function doItalicsAndBold($text) {
1183
+        $token_stack = array('');
1184
+        $text_stack = array('');
1185
+        $em = '';
1186
+        $strong = '';
1187
+        $tree_char_em = false;
1188
+
1189
+        while (1) {
1190
+            #
1191
+            # Get prepared regular expression for seraching emphasis tokens
1192
+            # in current context.
1193
+            #
1194
+            $token_re = $this->em_strong_prepared_relist["$em$strong"];
1195
+
1196
+            #
1197
+            # Each loop iteration search for the next emphasis token.
1198
+            # Each token is then passed to handleSpanToken.
1199
+            #
1200
+            $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
1201
+            $text_stack[0] .= $parts[0];
1202
+            $token =& $parts[1];
1203
+            $text =& $parts[2];
1204
+
1205
+            if (empty($token)) {
1206
+                # Reached end of text span: empty stack without emitting.
1207
+                # any more emphasis.
1208
+                while ($token_stack[0]) {
1209
+                    $text_stack[1] .= array_shift($token_stack);
1210
+                    $text_stack[0] .= array_shift($text_stack);
1211
+                }
1212
+                break;
1213
+            }
1214
+
1215
+            $token_len = strlen($token);
1216
+            if ($tree_char_em) {
1217
+                # Reached closing marker while inside a three-char emphasis.
1218
+                if ($token_len == 3) {
1219
+                    # Three-char closing marker, close em and strong.
1220
+                    array_shift($token_stack);
1221
+                    $span = array_shift($text_stack);
1222
+                    $span = $this->runSpanGamut($span);
1223
+                    $span = "<strong><em>$span</em></strong>";
1224
+                    $text_stack[0] .= $this->hashPart($span);
1225
+                    $em = '';
1226
+                    $strong = '';
1227
+                } else {
1228
+                    # Other closing marker: close one em or strong and
1229
+                    # change current token state to match the other
1230
+                    $token_stack[0] = str_repeat($token{0}, 3-$token_len);
1231
+                    $tag = $token_len == 2 ? "strong" : "em";
1232
+                    $span = $text_stack[0];
1233
+                    $span = $this->runSpanGamut($span);
1234
+                    $span = "<$tag>$span</$tag>";
1235
+                    $text_stack[0] = $this->hashPart($span);
1236
+                    $$tag = ''; # $$tag stands for $em or $strong
1237
+                }
1238
+                $tree_char_em = false;
1239
+            } else if ($token_len == 3) {
1240
+                if ($em) {
1241
+                    # Reached closing marker for both em and strong.
1242
+                    # Closing strong marker:
1243
+                    for ($i = 0; $i < 2; ++$i) {
1244
+                        $shifted_token = array_shift($token_stack);
1245
+                        $tag = strlen($shifted_token) == 2 ? "strong" : "em";
1246
+                        $span = array_shift($text_stack);
1247
+                        $span = $this->runSpanGamut($span);
1248
+                        $span = "<$tag>$span</$tag>";
1249
+                        $text_stack[0] .= $this->hashPart($span);
1250
+                        $$tag = ''; # $$tag stands for $em or $strong
1251
+                    }
1252
+                } else {
1253
+                    # Reached opening three-char emphasis marker. Push on token
1254
+                    # stack; will be handled by the special condition above.
1255
+                    $em = $token{0};
1256
+                    $strong = "$em$em";
1257
+                    array_unshift($token_stack, $token);
1258
+                    array_unshift($text_stack, '');
1259
+                    $tree_char_em = true;
1260
+                }
1261
+            } else if ($token_len == 2) {
1262
+                if ($strong) {
1263
+                    # Unwind any dangling emphasis marker:
1264
+                    if (strlen($token_stack[0]) == 1) {
1265
+                        $text_stack[1] .= array_shift($token_stack);
1266
+                        $text_stack[0] .= array_shift($text_stack);
1267
+                    }
1268
+                    # Closing strong marker:
1269
+                    array_shift($token_stack);
1270
+                    $span = array_shift($text_stack);
1271
+                    $span = $this->runSpanGamut($span);
1272
+                    $span = "<strong>$span</strong>";
1273
+                    $text_stack[0] .= $this->hashPart($span);
1274
+                    $strong = '';
1275
+                } else {
1276
+                    array_unshift($token_stack, $token);
1277
+                    array_unshift($text_stack, '');
1278
+                    $strong = $token;
1279
+                }
1280
+            } else {
1281
+                # Here $token_len == 1
1282
+                if ($em) {
1283
+                    if (strlen($token_stack[0]) == 1) {
1284
+                        # Closing emphasis marker:
1285
+                        array_shift($token_stack);
1286
+                        $span = array_shift($text_stack);
1287
+                        $span = $this->runSpanGamut($span);
1288
+                        $span = "<em>$span</em>";
1289
+                        $text_stack[0] .= $this->hashPart($span);
1290
+                        $em = '';
1291
+                    } else {
1292
+                        $text_stack[0] .= $token;
1293
+                    }
1294
+                } else {
1295
+                    array_unshift($token_stack, $token);
1296
+                    array_unshift($text_stack, '');
1297
+                    $em = $token;
1298
+                }
1299
+            }
1300
+        }
1301
+        return $text_stack[0];
1302
+    }
1303
+
1304
+
1305
+    function doBlockQuotes($text) {
1306
+        $text = preg_replace_callback('/
1307 1307
 			  (								# Wrap whole match in $1
1308 1308
 				(?>
1309 1309
 				  ^[ ]*>[ ]?			# ">" at the start of a line
@@ -1313,58 +1313,58 @@  discard block
 block discarded – undo
1313 1313
 				)+
1314 1314
 			  )
1315 1315
 			/xm',
1316
-			array(&$this, '_doBlockQuotes_callback'), $text);
1317
-
1318
-		return $text;
1319
-	}
1320
-	function _doBlockQuotes_callback($matches) {
1321
-		$bq = $matches[1];
1322
-		# trim one level of quoting - trim whitespace-only lines
1323
-		$bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
1324
-		$bq = $this->runBlockGamut($bq);		# recurse
1325
-
1326
-		$bq = preg_replace('/^/m', "  ", $bq);
1327
-		# These leading spaces cause problem with <pre> content,
1328
-		# so we need to fix that:
1329
-		$bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
1330
-			array(&$this, '_doBlockQuotes_callback2'), $bq);
1331
-
1332
-		return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
1333
-	}
1334
-	function _doBlockQuotes_callback2($matches) {
1335
-		$pre = $matches[1];
1336
-		$pre = preg_replace('/^  /m', '', $pre);
1337
-		return $pre;
1338
-	}
1339
-
1340
-
1341
-	function formParagraphs($text) {
1342
-	#
1343
-	#	Params:
1344
-	#		$text - string to process with html <p> tags
1345
-	#
1346
-		# Strip leading and trailing lines:
1347
-		$text = preg_replace('/\A\n+|\n+\z/', '', $text);
1348
-
1349
-		$grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
1350
-
1351
-		#
1352
-		# Wrap <p> tags and unhashify HTML blocks
1353
-		#
1354
-		foreach ($grafs as $key => $value) {
1355
-			if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
1356
-				# Is a paragraph.
1357
-				$value = $this->runSpanGamut($value);
1358
-				$value = preg_replace('/^([ ]*)/', "<p>", $value);
1359
-				$value .= "</p>";
1360
-				$grafs[$key] = $this->unhash($value);
1361
-			}
1362
-			else {
1363
-				# Is a block.
1364
-				# Modify elements of @grafs in-place...
1365
-				$graf = $value;
1366
-				$block = $this->html_hashes[$graf];
1367
-				$graf = $block;
1316
+            array(&$this, '_doBlockQuotes_callback'), $text);
1317
+
1318
+        return $text;
1319
+    }
1320
+    function _doBlockQuotes_callback($matches) {
1321
+        $bq = $matches[1];
1322
+        # trim one level of quoting - trim whitespace-only lines
1323
+        $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
1324
+        $bq = $this->runBlockGamut($bq);		# recurse
1325
+
1326
+        $bq = preg_replace('/^/m', "  ", $bq);
1327
+        # These leading spaces cause problem with <pre> content,
1328
+        # so we need to fix that:
1329
+        $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
1330
+            array(&$this, '_doBlockQuotes_callback2'), $bq);
1331
+
1332
+        return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
1333
+    }
1334
+    function _doBlockQuotes_callback2($matches) {
1335
+        $pre = $matches[1];
1336
+        $pre = preg_replace('/^  /m', '', $pre);
1337
+        return $pre;
1338
+    }
1339
+
1340
+
1341
+    function formParagraphs($text) {
1342
+    #
1343
+    #	Params:
1344
+    #		$text - string to process with html <p> tags
1345
+    #
1346
+        # Strip leading and trailing lines:
1347
+        $text = preg_replace('/\A\n+|\n+\z/', '', $text);
1348
+
1349
+        $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
1350
+
1351
+        #
1352
+        # Wrap <p> tags and unhashify HTML blocks
1353
+        #
1354
+        foreach ($grafs as $key => $value) {
1355
+            if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
1356
+                # Is a paragraph.
1357
+                $value = $this->runSpanGamut($value);
1358
+                $value = preg_replace('/^([ ]*)/', "<p>", $value);
1359
+                $value .= "</p>";
1360
+                $grafs[$key] = $this->unhash($value);
1361
+            }
1362
+            else {
1363
+                # Is a block.
1364
+                # Modify elements of @grafs in-place...
1365
+                $graf = $value;
1366
+                $block = $this->html_hashes[$graf];
1367
+                $graf = $block;
1368 1368
 //				if (preg_match('{
1369 1369
 //					\A
1370 1370
 //					(							# $1 = <div> tag
@@ -1400,52 +1400,52 @@  discard block
 block discarded – undo
1400 1400
 //
1401 1401
 //					$graf = $div_open . "\n" . $div_content . "\n" . $div_close;
1402 1402
 //				}
1403
-				$grafs[$key] = $graf;
1404
-			}
1405
-		}
1406
-
1407
-		return implode("\n\n", $grafs);
1408
-	}
1409
-
1410
-
1411
-	function encodeAttribute($text) {
1412
-	#
1413
-	# Encode text for a double-quoted HTML attribute. This function
1414
-	# is *not* suitable for attributes enclosed in single quotes.
1415
-	#
1416
-		$text = $this->encodeAmpsAndAngles($text);
1417
-		$text = str_replace('"', '&quot;', $text);
1418
-		return $text;
1419
-	}
1420
-
1421
-
1422
-	function encodeAmpsAndAngles($text) {
1423
-	#
1424
-	# Smart processing for ampersands and angle brackets that need to
1425
-	# be encoded. Valid character entities are left alone unless the
1426
-	# no-entities mode is set.
1427
-	#
1428
-		if ($this->no_entities) {
1429
-			$text = str_replace('&', '&amp;', $text);
1430
-		} else {
1431
-			# Ampersand-encoding based entirely on Nat Irons's Amputator
1432
-			# MT plugin: <http://bumppo.net/projects/amputator/>
1433
-			$text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
1434
-								'&amp;', $text);;
1435
-		}
1436
-		# Encode remaining <'s
1437
-		$text = str_replace('<', '&lt;', $text);
1438
-
1439
-		return $text;
1440
-	}
1441
-
1442
-
1443
-	function doAutoLinks($text) {
1444
-		$text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
1445
-			array(&$this, '_doAutoLinks_url_callback'), $text);
1446
-
1447
-		# Email addresses: <[email protected]>
1448
-		$text = preg_replace_callback('{
1403
+                $grafs[$key] = $graf;
1404
+            }
1405
+        }
1406
+
1407
+        return implode("\n\n", $grafs);
1408
+    }
1409
+
1410
+
1411
+    function encodeAttribute($text) {
1412
+    #
1413
+    # Encode text for a double-quoted HTML attribute. This function
1414
+    # is *not* suitable for attributes enclosed in single quotes.
1415
+    #
1416
+        $text = $this->encodeAmpsAndAngles($text);
1417
+        $text = str_replace('"', '&quot;', $text);
1418
+        return $text;
1419
+    }
1420
+
1421
+
1422
+    function encodeAmpsAndAngles($text) {
1423
+    #
1424
+    # Smart processing for ampersands and angle brackets that need to
1425
+    # be encoded. Valid character entities are left alone unless the
1426
+    # no-entities mode is set.
1427
+    #
1428
+        if ($this->no_entities) {
1429
+            $text = str_replace('&', '&amp;', $text);
1430
+        } else {
1431
+            # Ampersand-encoding based entirely on Nat Irons's Amputator
1432
+            # MT plugin: <http://bumppo.net/projects/amputator/>
1433
+            $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
1434
+                                '&amp;', $text);;
1435
+        }
1436
+        # Encode remaining <'s
1437
+        $text = str_replace('<', '&lt;', $text);
1438
+
1439
+        return $text;
1440
+    }
1441
+
1442
+
1443
+    function doAutoLinks($text) {
1444
+        $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
1445
+            array(&$this, '_doAutoLinks_url_callback'), $text);
1446
+
1447
+        # Email addresses: <[email protected]>
1448
+        $text = preg_replace_callback('{
1449 1449
 			<
1450 1450
 			(?:mailto:)?
1451 1451
 			(
@@ -1463,71 +1463,71 @@  discard block
 block discarded – undo
1463 1463
 			)
1464 1464
 			>
1465 1465
 			}xi',
1466
-			array(&$this, '_doAutoLinks_email_callback'), $text);
1467
-
1468
-		return $text;
1469
-	}
1470
-	function _doAutoLinks_url_callback($matches) {
1471
-		$url = $this->encodeAttribute($matches[1]);
1472
-		$link = "<a href=\"$url\">$url</a>";
1473
-		return $this->hashPart($link);
1474
-	}
1475
-	function _doAutoLinks_email_callback($matches) {
1476
-		$address = $matches[1];
1477
-		$link = $this->encodeEmailAddress($address);
1478
-		return $this->hashPart($link);
1479
-	}
1480
-
1481
-
1482
-	function encodeEmailAddress($addr) {
1483
-	#
1484
-	#	Input: an email address, e.g. "[email protected]"
1485
-	#
1486
-	#	Output: the email address as a mailto link, with each character
1487
-	#		of the address encoded as either a decimal or hex entity, in
1488
-	#		the hopes of foiling most address harvesting spam bots. E.g.:
1489
-	#
1490
-	#	  <p><a href="&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;
1491
-	#        &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;
1492
-	#        &#x6d;">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;
1493
-	#        &#101;&#46;&#x63;&#111;&#x6d;</a></p>
1494
-	#
1495
-	#	Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
1496
-	#   With some optimizations by Milian Wolff.
1497
-	#
1498
-		$addr = "mailto:" . $addr;
1499
-		$chars = preg_split('/(?<!^)(?!$)/', $addr);
1500
-		$seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
1501
-
1502
-		foreach ($chars as $key => $char) {
1503
-			$ord = ord($char);
1504
-			# Ignore non-ascii chars.
1505
-			if ($ord < 128) {
1506
-				$r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
1507
-				# roughly 10% raw, 45% hex, 45% dec
1508
-				# '@' *must* be encoded. I insist.
1509
-				if ($r > 90 && $char != '@') /* do nothing */;
1510
-				else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
1511
-				else              $chars[$key] = '&#'.$ord.';';
1512
-			}
1513
-		}
1514
-
1515
-		$addr = implode('', $chars);
1516
-		$text = implode('', array_slice($chars, 7)); # text without `mailto:`
1517
-		$addr = "<a href=\"$addr\">$text</a>";
1518
-
1519
-		return $addr;
1520
-	}
1521
-
1522
-
1523
-	function parseSpan($str) {
1524
-	#
1525
-	# Take the string $str and parse it into tokens, hashing embeded HTML,
1526
-	# escaped characters and handling code spans.
1527
-	#
1528
-		$output = '';
1529
-
1530
-		$span_re = '{
1466
+            array(&$this, '_doAutoLinks_email_callback'), $text);
1467
+
1468
+        return $text;
1469
+    }
1470
+    function _doAutoLinks_url_callback($matches) {
1471
+        $url = $this->encodeAttribute($matches[1]);
1472
+        $link = "<a href=\"$url\">$url</a>";
1473
+        return $this->hashPart($link);
1474
+    }
1475
+    function _doAutoLinks_email_callback($matches) {
1476
+        $address = $matches[1];
1477
+        $link = $this->encodeEmailAddress($address);
1478
+        return $this->hashPart($link);
1479
+    }
1480
+
1481
+
1482
+    function encodeEmailAddress($addr) {
1483
+    #
1484
+    #	Input: an email address, e.g. "[email protected]"
1485
+    #
1486
+    #	Output: the email address as a mailto link, with each character
1487
+    #		of the address encoded as either a decimal or hex entity, in
1488
+    #		the hopes of foiling most address harvesting spam bots. E.g.:
1489
+    #
1490
+    #	  <p><a href="&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;
1491
+    #        &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;
1492
+    #        &#x6d;">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;
1493
+    #        &#101;&#46;&#x63;&#111;&#x6d;</a></p>
1494
+    #
1495
+    #	Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
1496
+    #   With some optimizations by Milian Wolff.
1497
+    #
1498
+        $addr = "mailto:" . $addr;
1499
+        $chars = preg_split('/(?<!^)(?!$)/', $addr);
1500
+        $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
1501
+
1502
+        foreach ($chars as $key => $char) {
1503
+            $ord = ord($char);
1504
+            # Ignore non-ascii chars.
1505
+            if ($ord < 128) {
1506
+                $r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
1507
+                # roughly 10% raw, 45% hex, 45% dec
1508
+                # '@' *must* be encoded. I insist.
1509
+                if ($r > 90 && $char != '@') /* do nothing */;
1510
+                else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
1511
+                else              $chars[$key] = '&#'.$ord.';';
1512
+            }
1513
+        }
1514
+
1515
+        $addr = implode('', $chars);
1516
+        $text = implode('', array_slice($chars, 7)); # text without `mailto:`
1517
+        $addr = "<a href=\"$addr\">$text</a>";
1518
+
1519
+        return $addr;
1520
+    }
1521
+
1522
+
1523
+    function parseSpan($str) {
1524
+    #
1525
+    # Take the string $str and parse it into tokens, hashing embeded HTML,
1526
+    # escaped characters and handling code spans.
1527
+    #
1528
+        $output = '';
1529
+
1530
+        $span_re = '{
1531 1531
 				(
1532 1532
 					\\\\'.$this->escape_chars_re.'
1533 1533
 				|
@@ -1549,123 +1549,123 @@  discard block
 block discarded – undo
1549 1549
 				)
1550 1550
 				}xs';
1551 1551
 
1552
-		while (1) {
1553
-			#
1554
-			# Each loop iteration seach for either the next tag, the next
1555
-			# openning code span marker, or the next escaped character.
1556
-			# Each token is then passed to handleSpanToken.
1557
-			#
1558
-			$parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
1559
-
1560
-			# Create token from text preceding tag.
1561
-			if ($parts[0] != "") {
1562
-				$output .= $parts[0];
1563
-			}
1564
-
1565
-			# Check if we reach the end.
1566
-			if (isset($parts[1])) {
1567
-				$output .= $this->handleSpanToken($parts[1], $parts[2]);
1568
-				$str = $parts[2];
1569
-			}
1570
-			else {
1571
-				break;
1572
-			}
1573
-		}
1574
-
1575
-		return $output;
1576
-	}
1577
-
1578
-
1579
-	function handleSpanToken($token, &$str) {
1580
-	#
1581
-	# Handle $token provided by parseSpan by determining its nature and
1582
-	# returning the corresponding value that should replace it.
1583
-	#
1584
-		switch ($token{0}) {
1585
-			case "\\":
1586
-				return $this->hashPart("&#". ord($token{1}). ";");
1587
-			case "`":
1588
-				# Search for end marker in remaining text.
1589
-				if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
1590
-					$str, $matches))
1591
-				{
1592
-					$str = $matches[2];
1593
-					$codespan = $this->makeCodeSpan($matches[1]);
1594
-					return $this->hashPart($codespan);
1595
-				}
1596
-				return $token; // return as text since no ending marker found.
1597
-			default:
1598
-				return $this->hashPart($token);
1599
-		}
1600
-	}
1601
-
1602
-
1603
-	function outdent($text) {
1604
-	#
1605
-	# Remove one level of line-leading tabs or spaces
1606
-	#
1607
-		return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
1608
-	}
1609
-
1610
-
1611
-	# String length function for detab. `_initDetab` will create a function to
1612
-	# hanlde UTF-8 if the default function does not exist.
1613
-	var $utf8_strlen = 'mb_strlen';
1614
-
1615
-	function detab($text) {
1616
-	#
1617
-	# Replace tabs with the appropriate amount of space.
1618
-	#
1619
-		# For each line we separate the line in blocks delemited by
1620
-		# tab characters. Then we reconstruct every line by adding the
1621
-		# appropriate number of space between each blocks.
1622
-
1623
-		$text = preg_replace_callback('/^.*\t.*$/m',
1624
-			array(&$this, '_detab_callback'), $text);
1625
-
1626
-		return $text;
1627
-	}
1628
-	function _detab_callback($matches) {
1629
-		$line = $matches[0];
1630
-		$strlen = $this->utf8_strlen; # strlen function for UTF-8.
1631
-
1632
-		# Split in blocks.
1633
-		$blocks = explode("\t", $line);
1634
-		# Add each blocks to the line.
1635
-		$line = $blocks[0];
1636
-		unset($blocks[0]); # Do not add first block twice.
1637
-		foreach ($blocks as $block) {
1638
-			# Calculate amount of space, insert spaces, insert block.
1639
-			$amount = $this->tab_width -
1640
-				$strlen($line, 'UTF-8') % $this->tab_width;
1641
-			$line .= str_repeat(" ", $amount) . $block;
1642
-		}
1643
-		return $line;
1644
-	}
1645
-	function _initDetab() {
1646
-	#
1647
-	# Check for the availability of the function in the `utf8_strlen` property
1648
-	# (initially `mb_strlen`). If the function is not available, create a
1649
-	# function that will loosely count the number of UTF-8 characters with a
1650
-	# regular expression.
1651
-	#
1652
-		if (function_exists($this->utf8_strlen)) return;
1653
-		$this->utf8_strlen = create_function('$text', 'return preg_match_all(
1552
+        while (1) {
1553
+            #
1554
+            # Each loop iteration seach for either the next tag, the next
1555
+            # openning code span marker, or the next escaped character.
1556
+            # Each token is then passed to handleSpanToken.
1557
+            #
1558
+            $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
1559
+
1560
+            # Create token from text preceding tag.
1561
+            if ($parts[0] != "") {
1562
+                $output .= $parts[0];
1563
+            }
1564
+
1565
+            # Check if we reach the end.
1566
+            if (isset($parts[1])) {
1567
+                $output .= $this->handleSpanToken($parts[1], $parts[2]);
1568
+                $str = $parts[2];
1569
+            }
1570
+            else {
1571
+                break;
1572
+            }
1573
+        }
1574
+
1575
+        return $output;
1576
+    }
1577
+
1578
+
1579
+    function handleSpanToken($token, &$str) {
1580
+    #
1581
+    # Handle $token provided by parseSpan by determining its nature and
1582
+    # returning the corresponding value that should replace it.
1583
+    #
1584
+        switch ($token{0}) {
1585
+            case "\\":
1586
+                return $this->hashPart("&#". ord($token{1}). ";");
1587
+            case "`":
1588
+                # Search for end marker in remaining text.
1589
+                if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
1590
+                    $str, $matches))
1591
+                {
1592
+                    $str = $matches[2];
1593
+                    $codespan = $this->makeCodeSpan($matches[1]);
1594
+                    return $this->hashPart($codespan);
1595
+                }
1596
+                return $token; // return as text since no ending marker found.
1597
+            default:
1598
+                return $this->hashPart($token);
1599
+        }
1600
+    }
1601
+
1602
+
1603
+    function outdent($text) {
1604
+    #
1605
+    # Remove one level of line-leading tabs or spaces
1606
+    #
1607
+        return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
1608
+    }
1609
+
1610
+
1611
+    # String length function for detab. `_initDetab` will create a function to
1612
+    # hanlde UTF-8 if the default function does not exist.
1613
+    var $utf8_strlen = 'mb_strlen';
1614
+
1615
+    function detab($text) {
1616
+    #
1617
+    # Replace tabs with the appropriate amount of space.
1618
+    #
1619
+        # For each line we separate the line in blocks delemited by
1620
+        # tab characters. Then we reconstruct every line by adding the
1621
+        # appropriate number of space between each blocks.
1622
+
1623
+        $text = preg_replace_callback('/^.*\t.*$/m',
1624
+            array(&$this, '_detab_callback'), $text);
1625
+
1626
+        return $text;
1627
+    }
1628
+    function _detab_callback($matches) {
1629
+        $line = $matches[0];
1630
+        $strlen = $this->utf8_strlen; # strlen function for UTF-8.
1631
+
1632
+        # Split in blocks.
1633
+        $blocks = explode("\t", $line);
1634
+        # Add each blocks to the line.
1635
+        $line = $blocks[0];
1636
+        unset($blocks[0]); # Do not add first block twice.
1637
+        foreach ($blocks as $block) {
1638
+            # Calculate amount of space, insert spaces, insert block.
1639
+            $amount = $this->tab_width -
1640
+                $strlen($line, 'UTF-8') % $this->tab_width;
1641
+            $line .= str_repeat(" ", $amount) . $block;
1642
+        }
1643
+        return $line;
1644
+    }
1645
+    function _initDetab() {
1646
+    #
1647
+    # Check for the availability of the function in the `utf8_strlen` property
1648
+    # (initially `mb_strlen`). If the function is not available, create a
1649
+    # function that will loosely count the number of UTF-8 characters with a
1650
+    # regular expression.
1651
+    #
1652
+        if (function_exists($this->utf8_strlen)) return;
1653
+        $this->utf8_strlen = create_function('$text', 'return preg_match_all(
1654 1654
 			"/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/",
1655 1655
 			$text, $m);');
1656
-	}
1656
+    }
1657 1657
 
1658 1658
 
1659
-	function unhash($text) {
1660
-	#
1661
-	# Swap back in all the tags hashed by _HashHTMLBlocks.
1662
-	#
1663
-		return preg_replace_callback('/(.)\x1A[0-9]+\1/',
1664
-			array(&$this, '_unhash_callback'), $text);
1665
-	}
1666
-	function _unhash_callback($matches) {
1667
-		return $this->html_hashes[$matches[0]];
1668
-	}
1659
+    function unhash($text) {
1660
+    #
1661
+    # Swap back in all the tags hashed by _HashHTMLBlocks.
1662
+    #
1663
+        return preg_replace_callback('/(.)\x1A[0-9]+\1/',
1664
+            array(&$this, '_unhash_callback'), $text);
1665
+    }
1666
+    function _unhash_callback($matches) {
1667
+        return $this->html_hashes[$matches[0]];
1668
+    }
1669 1669
 
1670 1670
 }
1671 1671
 
@@ -1676,178 +1676,178 @@  discard block
 block discarded – undo
1676 1676
 
1677 1677
 class MarkdownExtra_Parser extends Markdown_Parser {
1678 1678
 
1679
-	# Prefix for footnote ids.
1680
-	var $fn_id_prefix = "";
1681
-
1682
-	# Optional title attribute for footnote links and backlinks.
1683
-	var $fn_link_title = MARKDOWN_FN_LINK_TITLE;
1684
-	var $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE;
1685
-
1686
-	# Optional class attribute for footnote links and backlinks.
1687
-	var $fn_link_class = MARKDOWN_FN_LINK_CLASS;
1688
-	var $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS;
1689
-
1690
-	# Predefined abbreviations.
1691
-	var $predef_abbr = array();
1692
-
1693
-
1694
-	function MarkdownExtra_Parser() {
1695
-	#
1696
-	# Constructor function. Initialize the parser object.
1697
-	#
1698
-		# Add extra escapable characters before parent constructor
1699
-		# initialize the table.
1700
-		$this->escape_chars .= ':|';
1701
-
1702
-		# Insert extra document, block, and span transformations.
1703
-		# Parent constructor will do the sorting.
1704
-		$this->document_gamut += array(
1705
-			"doFencedCodeBlocks" => 5,
1706
-			"stripFootnotes"     => 15,
1707
-			"stripAbbreviations" => 25,
1708
-			"appendFootnotes"    => 50,
1709
-			);
1710
-		$this->block_gamut += array(
1711
-			"doFencedCodeBlocks" => 5,
1712
-			"doTables"           => 15,
1713
-			"doDefLists"         => 45,
1714
-			);
1715
-		$this->span_gamut += array(
1716
-			"doFootnotes"        => 5,
1717
-			"doAbbreviations"    => 70,
1718
-			);
1719
-
1720
-		parent::Markdown_Parser();
1721
-	}
1722
-
1723
-
1724
-	# Extra variables used during extra transformations.
1725
-	var $footnotes = array();
1726
-	var $footnotes_ordered = array();
1727
-	var $abbr_desciptions = array();
1728
-	var $abbr_word_re = '';
1729
-
1730
-	# Give the current footnote number.
1731
-	var $footnote_counter = 1;
1732
-
1733
-
1734
-	function setup() {
1735
-	#
1736
-	# Setting up Extra-specific variables.
1737
-	#
1738
-		parent::setup();
1739
-
1740
-		$this->footnotes = array();
1741
-		$this->footnotes_ordered = array();
1742
-		$this->abbr_desciptions = array();
1743
-		$this->abbr_word_re = '';
1744
-		$this->footnote_counter = 1;
1745
-
1746
-		foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
1747
-			if ($this->abbr_word_re)
1748
-				$this->abbr_word_re .= '|';
1749
-			$this->abbr_word_re .= preg_quote($abbr_word);
1750
-			$this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
1751
-		}
1752
-	}
1753
-
1754
-	function teardown() {
1755
-	#
1756
-	# Clearing Extra-specific variables.
1757
-	#
1758
-		$this->footnotes = array();
1759
-		$this->footnotes_ordered = array();
1760
-		$this->abbr_desciptions = array();
1761
-		$this->abbr_word_re = '';
1762
-
1763
-		parent::teardown();
1764
-	}
1765
-
1766
-
1767
-	### HTML Block Parser ###
1768
-
1769
-	# Tags that are always treated as block tags:
1770
-	var $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend';
1771
-
1772
-	# Tags treated as block tags only if the opening tag is alone on it's line:
1773
-	var $context_block_tags_re = 'script|noscript|math|ins|del';
1774
-
1775
-	# Tags where markdown="1" default to span mode:
1776
-	var $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
1777
-
1778
-	# Tags which must not have their contents modified, no matter where
1779
-	# they appear:
1780
-	var $clean_tags_re = 'script|math';
1781
-
1782
-	# Tags that do not need to be closed.
1783
-	var $auto_close_tags_re = 'hr|img';
1784
-
1785
-
1786
-	function hashHTMLBlocks($text) {
1787
-	#
1788
-	# Hashify HTML Blocks and "clean tags".
1789
-	#
1790
-	# We only want to do this for block-level HTML tags, such as headers,
1791
-	# lists, and tables. That's because we still want to wrap <p>s around
1792
-	# "paragraphs" that are wrapped in non-block-level tags, such as anchors,
1793
-	# phrase emphasis, and spans. The list of tags we're looking for is
1794
-	# hard-coded.
1795
-	#
1796
-	# This works by calling _HashHTMLBlocks_InMarkdown, which then calls
1797
-	# _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
1798
-	# attribute is found whitin a tag, _HashHTMLBlocks_InHTML calls back
1799
-	#  _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
1800
-	# These two functions are calling each other. It's recursive!
1801
-	#
1802
-		#
1803
-		# Call the HTML-in-Markdown hasher.
1804
-		#
1805
-		list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
1806
-
1807
-		return $text;
1808
-	}
1809
-	function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
1810
-										$enclosing_tag_re = '', $span = false)
1811
-	{
1812
-	#
1813
-	# Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
1814
-	#
1815
-	# *   $indent is the number of space to be ignored when checking for code
1816
-	#     blocks. This is important because if we don't take the indent into
1817
-	#     account, something like this (which looks right) won't work as expected:
1818
-	#
1819
-	#     <div>
1820
-	#         <div markdown="1">
1821
-	#         Hello World.  <-- Is this a Markdown code block or text?
1822
-	#         </div>  <-- Is this a Markdown code block or a real tag?
1823
-	#     <div>
1824
-	#
1825
-	#     If you don't like this, just don't indent the tag on which
1826
-	#     you apply the markdown="1" attribute.
1827
-	#
1828
-	# *   If $enclosing_tag_re is not empty, stops at the first unmatched closing
1829
-	#     tag with that name. Nested tags supported.
1830
-	#
1831
-	# *   If $span is true, text inside must treated as span. So any double
1832
-	#     newline will be replaced by a single newline so that it does not create
1833
-	#     paragraphs.
1834
-	#
1835
-	# Returns an array of that form: ( processed text , remaining text )
1836
-	#
1837
-		if ($text === '') return array('', '');
1838
-
1839
-		# Regex to check for the presense of newlines around a block tag.
1840
-		$newline_before_re = '/(?:^\n?|\n\n)*$/';
1841
-		$newline_after_re =
1842
-			'{
1679
+    # Prefix for footnote ids.
1680
+    var $fn_id_prefix = "";
1681
+
1682
+    # Optional title attribute for footnote links and backlinks.
1683
+    var $fn_link_title = MARKDOWN_FN_LINK_TITLE;
1684
+    var $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE;
1685
+
1686
+    # Optional class attribute for footnote links and backlinks.
1687
+    var $fn_link_class = MARKDOWN_FN_LINK_CLASS;
1688
+    var $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS;
1689
+
1690
+    # Predefined abbreviations.
1691
+    var $predef_abbr = array();
1692
+
1693
+
1694
+    function MarkdownExtra_Parser() {
1695
+    #
1696
+    # Constructor function. Initialize the parser object.
1697
+    #
1698
+        # Add extra escapable characters before parent constructor
1699
+        # initialize the table.
1700
+        $this->escape_chars .= ':|';
1701
+
1702
+        # Insert extra document, block, and span transformations.
1703
+        # Parent constructor will do the sorting.
1704
+        $this->document_gamut += array(
1705
+            "doFencedCodeBlocks" => 5,
1706
+            "stripFootnotes"     => 15,
1707
+            "stripAbbreviations" => 25,
1708
+            "appendFootnotes"    => 50,
1709
+            );
1710
+        $this->block_gamut += array(
1711
+            "doFencedCodeBlocks" => 5,
1712
+            "doTables"           => 15,
1713
+            "doDefLists"         => 45,
1714
+            );
1715
+        $this->span_gamut += array(
1716
+            "doFootnotes"        => 5,
1717
+            "doAbbreviations"    => 70,
1718
+            );
1719
+
1720
+        parent::Markdown_Parser();
1721
+    }
1722
+
1723
+
1724
+    # Extra variables used during extra transformations.
1725
+    var $footnotes = array();
1726
+    var $footnotes_ordered = array();
1727
+    var $abbr_desciptions = array();
1728
+    var $abbr_word_re = '';
1729
+
1730
+    # Give the current footnote number.
1731
+    var $footnote_counter = 1;
1732
+
1733
+
1734
+    function setup() {
1735
+    #
1736
+    # Setting up Extra-specific variables.
1737
+    #
1738
+        parent::setup();
1739
+
1740
+        $this->footnotes = array();
1741
+        $this->footnotes_ordered = array();
1742
+        $this->abbr_desciptions = array();
1743
+        $this->abbr_word_re = '';
1744
+        $this->footnote_counter = 1;
1745
+
1746
+        foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
1747
+            if ($this->abbr_word_re)
1748
+                $this->abbr_word_re .= '|';
1749
+            $this->abbr_word_re .= preg_quote($abbr_word);
1750
+            $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
1751
+        }
1752
+    }
1753
+
1754
+    function teardown() {
1755
+    #
1756
+    # Clearing Extra-specific variables.
1757
+    #
1758
+        $this->footnotes = array();
1759
+        $this->footnotes_ordered = array();
1760
+        $this->abbr_desciptions = array();
1761
+        $this->abbr_word_re = '';
1762
+
1763
+        parent::teardown();
1764
+    }
1765
+
1766
+
1767
+    ### HTML Block Parser ###
1768
+
1769
+    # Tags that are always treated as block tags:
1770
+    var $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend';
1771
+
1772
+    # Tags treated as block tags only if the opening tag is alone on it's line:
1773
+    var $context_block_tags_re = 'script|noscript|math|ins|del';
1774
+
1775
+    # Tags where markdown="1" default to span mode:
1776
+    var $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
1777
+
1778
+    # Tags which must not have their contents modified, no matter where
1779
+    # they appear:
1780
+    var $clean_tags_re = 'script|math';
1781
+
1782
+    # Tags that do not need to be closed.
1783
+    var $auto_close_tags_re = 'hr|img';
1784
+
1785
+
1786
+    function hashHTMLBlocks($text) {
1787
+    #
1788
+    # Hashify HTML Blocks and "clean tags".
1789
+    #
1790
+    # We only want to do this for block-level HTML tags, such as headers,
1791
+    # lists, and tables. That's because we still want to wrap <p>s around
1792
+    # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
1793
+    # phrase emphasis, and spans. The list of tags we're looking for is
1794
+    # hard-coded.
1795
+    #
1796
+    # This works by calling _HashHTMLBlocks_InMarkdown, which then calls
1797
+    # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
1798
+    # attribute is found whitin a tag, _HashHTMLBlocks_InHTML calls back
1799
+    #  _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
1800
+    # These two functions are calling each other. It's recursive!
1801
+    #
1802
+        #
1803
+        # Call the HTML-in-Markdown hasher.
1804
+        #
1805
+        list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
1806
+
1807
+        return $text;
1808
+    }
1809
+    function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
1810
+                                        $enclosing_tag_re = '', $span = false)
1811
+    {
1812
+    #
1813
+    # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
1814
+    #
1815
+    # *   $indent is the number of space to be ignored when checking for code
1816
+    #     blocks. This is important because if we don't take the indent into
1817
+    #     account, something like this (which looks right) won't work as expected:
1818
+    #
1819
+    #     <div>
1820
+    #         <div markdown="1">
1821
+    #         Hello World.  <-- Is this a Markdown code block or text?
1822
+    #         </div>  <-- Is this a Markdown code block or a real tag?
1823
+    #     <div>
1824
+    #
1825
+    #     If you don't like this, just don't indent the tag on which
1826
+    #     you apply the markdown="1" attribute.
1827
+    #
1828
+    # *   If $enclosing_tag_re is not empty, stops at the first unmatched closing
1829
+    #     tag with that name. Nested tags supported.
1830
+    #
1831
+    # *   If $span is true, text inside must treated as span. So any double
1832
+    #     newline will be replaced by a single newline so that it does not create
1833
+    #     paragraphs.
1834
+    #
1835
+    # Returns an array of that form: ( processed text , remaining text )
1836
+    #
1837
+        if ($text === '') return array('', '');
1838
+
1839
+        # Regex to check for the presense of newlines around a block tag.
1840
+        $newline_before_re = '/(?:^\n?|\n\n)*$/';
1841
+        $newline_after_re =
1842
+            '{
1843 1843
 				^						# Start of text following the tag.
1844 1844
 				(?>[ ]*<!--.*?-->)?		# Optional comment.
1845 1845
 				[ ]*\n					# Must be followed by newline.
1846 1846
 			}xs';
1847 1847
 
1848
-		# Regex to match any tag.
1849
-		$block_tag_re =
1850
-			'{
1848
+        # Regex to match any tag.
1849
+        $block_tag_re =
1850
+            '{
1851 1851
 				(					# $2: Capture hole tag.
1852 1852
 					</?					# Any opening or closing tag.
1853 1853
 						(?>				# Tag name.
@@ -1891,165 +1891,165 @@  discard block
 block discarded – undo
1891 1891
 			}xs';
1892 1892
 
1893 1893
 
1894
-		$depth = 0;		# Current depth inside the tag tree.
1895
-		$parsed = "";	# Parsed text that will be returned.
1896
-
1897
-		#
1898
-		# Loop through every tag until we find the closing tag of the parent
1899
-		# or loop until reaching the end of text if no parent tag specified.
1900
-		#
1901
-		do {
1902
-			#
1903
-			# Split the text using the first $tag_match pattern found.
1904
-			# Text before  pattern will be first in the array, text after
1905
-			# pattern will be at the end, and between will be any catches made
1906
-			# by the pattern.
1907
-			#
1908
-			$parts = preg_split($block_tag_re, $text, 2,
1909
-								PREG_SPLIT_DELIM_CAPTURE);
1910
-
1911
-			# If in Markdown span mode, add a empty-string span-level hash
1912
-			# after each newline to prevent triggering any block element.
1913
-			if ($span) {
1914
-				$void = $this->hashPart("", ':');
1915
-				$newline = "$void\n";
1916
-				$parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
1917
-			}
1918
-
1919
-			$parsed .= $parts[0]; # Text before current tag.
1920
-
1921
-			# If end of $text has been reached. Stop loop.
1922
-			if (count($parts) < 3) {
1923
-				$text = "";
1924
-				break;
1925
-			}
1926
-
1927
-			$tag  = $parts[1]; # Tag to handle.
1928
-			$text = $parts[2]; # Remaining text after current tag.
1929
-			$tag_re = preg_quote($tag); # For use in a regular expression.
1930
-
1931
-			#
1932
-			# Check for: Code span marker
1933
-			#
1934
-			if ($tag{0} == "`") {
1935
-				# Find corresponding end marker.
1936
-				$tag_re = preg_quote($tag);
1937
-				if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)'.$tag_re.'(?!`)}',
1938
-					$text, $matches))
1939
-				{
1940
-					# End marker found: pass text unchanged until marker.
1941
-					$parsed .= $tag . $matches[0];
1942
-					$text = substr($text, strlen($matches[0]));
1943
-				}
1944
-				else {
1945
-					# Unmatched marker: just skip it.
1946
-					$parsed .= $tag;
1947
-				}
1948
-			}
1949
-			#
1950
-			# Check for: Indented code block.
1951
-			#
1952
-			else if ($tag{0} == "\n" || $tag{0} == " ") {
1953
-				# Indented code block: pass it unchanged, will be handled
1954
-				# later.
1955
-				$parsed .= $tag;
1956
-			}
1957
-			#
1958
-			# Check for: Fenced code block marker.
1959
-			#
1960
-			else if ($tag{0} == "~") {
1961
-				# Fenced code block marker: find matching end marker.
1962
-				$tag_re = preg_quote(trim($tag));
1963
-				if (preg_match('{^(?>.*\n)+?'.$tag_re.' *\n}', $text,
1964
-					$matches))
1965
-				{
1966
-					# End marker found: pass text unchanged until marker.
1967
-					$parsed .= $tag . $matches[0];
1968
-					$text = substr($text, strlen($matches[0]));
1969
-				}
1970
-				else {
1971
-					# No end marker: just skip it.
1972
-					$parsed .= $tag;
1973
-				}
1974
-			}
1975
-			#
1976
-			# Check for: Opening Block level tag or
1977
-			#            Opening Context Block tag (like ins and del)
1978
-			#               used as a block tag (tag is alone on it's line).
1979
-			#
1980
-			else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) ||
1981
-				(	preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) &&
1982
-					preg_match($newline_before_re, $parsed) &&
1983
-					preg_match($newline_after_re, $text)	)
1984
-				)
1985
-			{
1986
-				# Need to parse tag and following text using the HTML parser.
1987
-				list($block_text, $text) =
1988
-					$this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
1989
-
1990
-				# Make sure it stays outside of any paragraph by adding newlines.
1991
-				$parsed .= "\n\n$block_text\n\n";
1992
-			}
1993
-			#
1994
-			# Check for: Clean tag (like script, math)
1995
-			#            HTML Comments, processing instructions.
1996
-			#
1997
-			else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) ||
1998
-				$tag{1} == '!' || $tag{1} == '?')
1999
-			{
2000
-				# Need to parse tag and following text using the HTML parser.
2001
-				# (don't check for markdown attribute)
2002
-				list($block_text, $text) =
2003
-					$this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
2004
-
2005
-				$parsed .= $block_text;
2006
-			}
2007
-			#
2008
-			# Check for: Tag with same name as enclosing tag.
2009
-			#
2010
-			else if ($enclosing_tag_re !== '' &&
2011
-				# Same name as enclosing tag.
2012
-				preg_match('{^</?(?:'.$enclosing_tag_re.')\b}', $tag))
2013
-			{
2014
-				#
2015
-				# Increase/decrease nested tag count.
2016
-				#
2017
-				if ($tag{1} == '/')						$depth--;
2018
-				else if ($tag{strlen($tag)-2} != '/')	$depth++;
2019
-
2020
-				if ($depth < 0) {
2021
-					#
2022
-					# Going out of parent element. Clean up and break so we
2023
-					# return to the calling function.
2024
-					#
2025
-					$text = $tag . $text;
2026
-					break;
2027
-				}
2028
-
2029
-				$parsed .= $tag;
2030
-			}
2031
-			else {
2032
-				$parsed .= $tag;
2033
-			}
2034
-		} while ($depth >= 0);
2035
-
2036
-		return array($parsed, $text);
2037
-	}
2038
-	function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
2039
-	#
2040
-	# Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
2041
-	#
2042
-	# *   Calls $hash_method to convert any blocks.
2043
-	# *   Stops when the first opening tag closes.
2044
-	# *   $md_attr indicate if the use of the `markdown="1"` attribute is allowed.
2045
-	#     (it is not inside clean tags)
2046
-	#
2047
-	# Returns an array of that form: ( processed text , remaining text )
2048
-	#
2049
-		if ($text === '') return array('', '');
2050
-
2051
-		# Regex to match `markdown` attribute inside of a tag.
2052
-		$markdown_attr_re = '
1894
+        $depth = 0;		# Current depth inside the tag tree.
1895
+        $parsed = "";	# Parsed text that will be returned.
1896
+
1897
+        #
1898
+        # Loop through every tag until we find the closing tag of the parent
1899
+        # or loop until reaching the end of text if no parent tag specified.
1900
+        #
1901
+        do {
1902
+            #
1903
+            # Split the text using the first $tag_match pattern found.
1904
+            # Text before  pattern will be first in the array, text after
1905
+            # pattern will be at the end, and between will be any catches made
1906
+            # by the pattern.
1907
+            #
1908
+            $parts = preg_split($block_tag_re, $text, 2,
1909
+                                PREG_SPLIT_DELIM_CAPTURE);
1910
+
1911
+            # If in Markdown span mode, add a empty-string span-level hash
1912
+            # after each newline to prevent triggering any block element.
1913
+            if ($span) {
1914
+                $void = $this->hashPart("", ':');
1915
+                $newline = "$void\n";
1916
+                $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
1917
+            }
1918
+
1919
+            $parsed .= $parts[0]; # Text before current tag.
1920
+
1921
+            # If end of $text has been reached. Stop loop.
1922
+            if (count($parts) < 3) {
1923
+                $text = "";
1924
+                break;
1925
+            }
1926
+
1927
+            $tag  = $parts[1]; # Tag to handle.
1928
+            $text = $parts[2]; # Remaining text after current tag.
1929
+            $tag_re = preg_quote($tag); # For use in a regular expression.
1930
+
1931
+            #
1932
+            # Check for: Code span marker
1933
+            #
1934
+            if ($tag{0} == "`") {
1935
+                # Find corresponding end marker.
1936
+                $tag_re = preg_quote($tag);
1937
+                if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)'.$tag_re.'(?!`)}',
1938
+                    $text, $matches))
1939
+                {
1940
+                    # End marker found: pass text unchanged until marker.
1941
+                    $parsed .= $tag . $matches[0];
1942
+                    $text = substr($text, strlen($matches[0]));
1943
+                }
1944
+                else {
1945
+                    # Unmatched marker: just skip it.
1946
+                    $parsed .= $tag;
1947
+                }
1948
+            }
1949
+            #
1950
+            # Check for: Indented code block.
1951
+            #
1952
+            else if ($tag{0} == "\n" || $tag{0} == " ") {
1953
+                # Indented code block: pass it unchanged, will be handled
1954
+                # later.
1955
+                $parsed .= $tag;
1956
+            }
1957
+            #
1958
+            # Check for: Fenced code block marker.
1959
+            #
1960
+            else if ($tag{0} == "~") {
1961
+                # Fenced code block marker: find matching end marker.
1962
+                $tag_re = preg_quote(trim($tag));
1963
+                if (preg_match('{^(?>.*\n)+?'.$tag_re.' *\n}', $text,
1964
+                    $matches))
1965
+                {
1966
+                    # End marker found: pass text unchanged until marker.
1967
+                    $parsed .= $tag . $matches[0];
1968
+                    $text = substr($text, strlen($matches[0]));
1969
+                }
1970
+                else {
1971
+                    # No end marker: just skip it.
1972
+                    $parsed .= $tag;
1973
+                }
1974
+            }
1975
+            #
1976
+            # Check for: Opening Block level tag or
1977
+            #            Opening Context Block tag (like ins and del)
1978
+            #               used as a block tag (tag is alone on it's line).
1979
+            #
1980
+            else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) ||
1981
+                (	preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) &&
1982
+                    preg_match($newline_before_re, $parsed) &&
1983
+                    preg_match($newline_after_re, $text)	)
1984
+                )
1985
+            {
1986
+                # Need to parse tag and following text using the HTML parser.
1987
+                list($block_text, $text) =
1988
+                    $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
1989
+
1990
+                # Make sure it stays outside of any paragraph by adding newlines.
1991
+                $parsed .= "\n\n$block_text\n\n";
1992
+            }
1993
+            #
1994
+            # Check for: Clean tag (like script, math)
1995
+            #            HTML Comments, processing instructions.
1996
+            #
1997
+            else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) ||
1998
+                $tag{1} == '!' || $tag{1} == '?')
1999
+            {
2000
+                # Need to parse tag and following text using the HTML parser.
2001
+                # (don't check for markdown attribute)
2002
+                list($block_text, $text) =
2003
+                    $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
2004
+
2005
+                $parsed .= $block_text;
2006
+            }
2007
+            #
2008
+            # Check for: Tag with same name as enclosing tag.
2009
+            #
2010
+            else if ($enclosing_tag_re !== '' &&
2011
+                # Same name as enclosing tag.
2012
+                preg_match('{^</?(?:'.$enclosing_tag_re.')\b}', $tag))
2013
+            {
2014
+                #
2015
+                # Increase/decrease nested tag count.
2016
+                #
2017
+                if ($tag{1} == '/')						$depth--;
2018
+                else if ($tag{strlen($tag)-2} != '/')	$depth++;
2019
+
2020
+                if ($depth < 0) {
2021
+                    #
2022
+                    # Going out of parent element. Clean up and break so we
2023
+                    # return to the calling function.
2024
+                    #
2025
+                    $text = $tag . $text;
2026
+                    break;
2027
+                }
2028
+
2029
+                $parsed .= $tag;
2030
+            }
2031
+            else {
2032
+                $parsed .= $tag;
2033
+            }
2034
+        } while ($depth >= 0);
2035
+
2036
+        return array($parsed, $text);
2037
+    }
2038
+    function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
2039
+    #
2040
+    # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
2041
+    #
2042
+    # *   Calls $hash_method to convert any blocks.
2043
+    # *   Stops when the first opening tag closes.
2044
+    # *   $md_attr indicate if the use of the `markdown="1"` attribute is allowed.
2045
+    #     (it is not inside clean tags)
2046
+    #
2047
+    # Returns an array of that form: ( processed text , remaining text )
2048
+    #
2049
+        if ($text === '') return array('', '');
2050
+
2051
+        # Regex to match `markdown` attribute inside of a tag.
2052
+        $markdown_attr_re = '
2053 2053
 			{
2054 2054
 				\s*			# Eat whitespace before the `markdown` attribute
2055 2055
 				markdown
@@ -2064,8 +2064,8 @@  discard block
 block discarded – undo
2064 2064
 				()				# $4: make $3 always defined (avoid warnings)
2065 2065
 			}xs';
2066 2066
 
2067
-		# Regex to match any tag.
2068
-		$tag_re = '{
2067
+        # Regex to match any tag.
2068
+        $tag_re = '{
2069 2069
 				(					# $2: Capture hole tag.
2070 2070
 					</?					# Any opening or closing tag.
2071 2071
 						[\w:$]+			# Tag name.
@@ -2087,166 +2087,166 @@  discard block
 block discarded – undo
2087 2087
 				)
2088 2088
 			}xs';
2089 2089
 
2090
-		$original_text = $text;		# Save original text in case of faliure.
2091
-
2092
-		$depth		= 0;	# Current depth inside the tag tree.
2093
-		$block_text	= "";	# Temporary text holder for current text.
2094
-		$parsed		= "";	# Parsed text that will be returned.
2095
-
2096
-		#
2097
-		# Get the name of the starting tag.
2098
-		# (This pattern makes $base_tag_name_re safe without quoting.)
2099
-		#
2100
-		if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
2101
-			$base_tag_name_re = $matches[1];
2102
-
2103
-		#
2104
-		# Loop through every tag until we find the corresponding closing tag.
2105
-		#
2106
-		do {
2107
-			#
2108
-			# Split the text using the first $tag_match pattern found.
2109
-			# Text before  pattern will be first in the array, text after
2110
-			# pattern will be at the end, and between will be any catches made
2111
-			# by the pattern.
2112
-			#
2113
-			$parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
2114
-
2115
-			if (count($parts) < 3) {
2116
-				#
2117
-				# End of $text reached with unbalenced tag(s).
2118
-				# In that case, we return original text unchanged and pass the
2119
-				# first character as filtered to prevent an infinite loop in the
2120
-				# parent function.
2121
-				#
2122
-				return array($original_text{0}, substr($original_text, 1));
2123
-			}
2124
-
2125
-			$block_text .= $parts[0]; # Text before current tag.
2126
-			$tag         = $parts[1]; # Tag to handle.
2127
-			$text        = $parts[2]; # Remaining text after current tag.
2128
-
2129
-			#
2130
-			# Check for: Auto-close tag (like <hr/>)
2131
-			#			 Comments and Processing Instructions.
2132
-			#
2133
-			if (preg_match('{^</?(?:'.$this->auto_close_tags_re.')\b}', $tag) ||
2134
-				$tag{1} == '!' || $tag{1} == '?')
2135
-			{
2136
-				# Just add the tag to the block as if it was text.
2137
-				$block_text .= $tag;
2138
-			}
2139
-			else {
2140
-				#
2141
-				# Increase/decrease nested tag count. Only do so if
2142
-				# the tag's name match base tag's.
2143
-				#
2144
-				if (preg_match('{^</?'.$base_tag_name_re.'\b}', $tag)) {
2145
-					if ($tag{1} == '/')						$depth--;
2146
-					else if ($tag{strlen($tag)-2} != '/')	$depth++;
2147
-				}
2148
-
2149
-				#
2150
-				# Check for `markdown="1"` attribute and handle it.
2151
-				#
2152
-				if ($md_attr &&
2153
-					preg_match($markdown_attr_re, $tag, $attr_m) &&
2154
-					preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
2155
-				{
2156
-					# Remove `markdown` attribute from opening tag.
2157
-					$tag = preg_replace($markdown_attr_re, '', $tag);
2158
-
2159
-					# Check if text inside this tag must be parsed in span mode.
2160
-					$this->mode = $attr_m[2] . $attr_m[3];
2161
-					$span_mode = $this->mode == 'span' || $this->mode != 'block' &&
2162
-						preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag);
2163
-
2164
-					# Calculate indent before tag.
2165
-					if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) {
2166
-						$strlen = $this->utf8_strlen;
2167
-						$indent = $strlen($matches[1], 'UTF-8');
2168
-					} else {
2169
-						$indent = 0;
2170
-					}
2171
-
2172
-					# End preceding block with this tag.
2173
-					$block_text .= $tag;
2174
-					$parsed .= $this->$hash_method($block_text);
2175
-
2176
-					# Get enclosing tag name for the ParseMarkdown function.
2177
-					# (This pattern makes $tag_name_re safe without quoting.)
2178
-					preg_match('/^<([\w:$]*)\b/', $tag, $matches);
2179
-					$tag_name_re = $matches[1];
2180
-
2181
-					# Parse the content using the HTML-in-Markdown parser.
2182
-					list ($block_text, $text)
2183
-						= $this->_hashHTMLBlocks_inMarkdown($text, $indent,
2184
-							$tag_name_re, $span_mode);
2185
-
2186
-					# Outdent markdown text.
2187
-					if ($indent > 0) {
2188
-						$block_text = preg_replace("/^[ ]{1,$indent}/m", "",
2189
-													$block_text);
2190
-					}
2191
-
2192
-					# Append tag content to parsed text.
2193
-					if (!$span_mode)	$parsed .= "\n\n$block_text\n\n";
2194
-					else				$parsed .= "$block_text";
2195
-
2196
-					# Start over a new block.
2197
-					$block_text = "";
2198
-				}
2199
-				else $block_text .= $tag;
2200
-			}
2201
-
2202
-		} while ($depth > 0);
2203
-
2204
-		#
2205
-		# Hash last block text that wasn't processed inside the loop.
2206
-		#
2207
-		$parsed .= $this->$hash_method($block_text);
2208
-
2209
-		return array($parsed, $text);
2210
-	}
2211
-
2212
-
2213
-	function hashClean($text) {
2214
-	#
2215
-	# Called whenever a tag must be hashed when a function insert a "clean" tag
2216
-	# in $text, it pass through this function and is automaticaly escaped,
2217
-	# blocking invalid nested overlap.
2218
-	#
2219
-		return $this->hashPart($text, 'C');
2220
-	}
2221
-
2222
-
2223
-	function doHeaders($text) {
2224
-	#
2225
-	# Redefined to add id attribute support.
2226
-	#
2227
-		# Setext-style headers:
2228
-		#	  Header 1  {#header1}
2229
-		#	  ========
2230
-		#
2231
-		#	  Header 2  {#header2}
2232
-		#	  --------
2233
-		#
2234
-		$text = preg_replace_callback(
2235
-			'{
2090
+        $original_text = $text;		# Save original text in case of faliure.
2091
+
2092
+        $depth		= 0;	# Current depth inside the tag tree.
2093
+        $block_text	= "";	# Temporary text holder for current text.
2094
+        $parsed		= "";	# Parsed text that will be returned.
2095
+
2096
+        #
2097
+        # Get the name of the starting tag.
2098
+        # (This pattern makes $base_tag_name_re safe without quoting.)
2099
+        #
2100
+        if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
2101
+            $base_tag_name_re = $matches[1];
2102
+
2103
+        #
2104
+        # Loop through every tag until we find the corresponding closing tag.
2105
+        #
2106
+        do {
2107
+            #
2108
+            # Split the text using the first $tag_match pattern found.
2109
+            # Text before  pattern will be first in the array, text after
2110
+            # pattern will be at the end, and between will be any catches made
2111
+            # by the pattern.
2112
+            #
2113
+            $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
2114
+
2115
+            if (count($parts) < 3) {
2116
+                #
2117
+                # End of $text reached with unbalenced tag(s).
2118
+                # In that case, we return original text unchanged and pass the
2119
+                # first character as filtered to prevent an infinite loop in the
2120
+                # parent function.
2121
+                #
2122
+                return array($original_text{0}, substr($original_text, 1));
2123
+            }
2124
+
2125
+            $block_text .= $parts[0]; # Text before current tag.
2126
+            $tag         = $parts[1]; # Tag to handle.
2127
+            $text        = $parts[2]; # Remaining text after current tag.
2128
+
2129
+            #
2130
+            # Check for: Auto-close tag (like <hr/>)
2131
+            #			 Comments and Processing Instructions.
2132
+            #
2133
+            if (preg_match('{^</?(?:'.$this->auto_close_tags_re.')\b}', $tag) ||
2134
+                $tag{1} == '!' || $tag{1} == '?')
2135
+            {
2136
+                # Just add the tag to the block as if it was text.
2137
+                $block_text .= $tag;
2138
+            }
2139
+            else {
2140
+                #
2141
+                # Increase/decrease nested tag count. Only do so if
2142
+                # the tag's name match base tag's.
2143
+                #
2144
+                if (preg_match('{^</?'.$base_tag_name_re.'\b}', $tag)) {
2145
+                    if ($tag{1} == '/')						$depth--;
2146
+                    else if ($tag{strlen($tag)-2} != '/')	$depth++;
2147
+                }
2148
+
2149
+                #
2150
+                # Check for `markdown="1"` attribute and handle it.
2151
+                #
2152
+                if ($md_attr &&
2153
+                    preg_match($markdown_attr_re, $tag, $attr_m) &&
2154
+                    preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
2155
+                {
2156
+                    # Remove `markdown` attribute from opening tag.
2157
+                    $tag = preg_replace($markdown_attr_re, '', $tag);
2158
+
2159
+                    # Check if text inside this tag must be parsed in span mode.
2160
+                    $this->mode = $attr_m[2] . $attr_m[3];
2161
+                    $span_mode = $this->mode == 'span' || $this->mode != 'block' &&
2162
+                        preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag);
2163
+
2164
+                    # Calculate indent before tag.
2165
+                    if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) {
2166
+                        $strlen = $this->utf8_strlen;
2167
+                        $indent = $strlen($matches[1], 'UTF-8');
2168
+                    } else {
2169
+                        $indent = 0;
2170
+                    }
2171
+
2172
+                    # End preceding block with this tag.
2173
+                    $block_text .= $tag;
2174
+                    $parsed .= $this->$hash_method($block_text);
2175
+
2176
+                    # Get enclosing tag name for the ParseMarkdown function.
2177
+                    # (This pattern makes $tag_name_re safe without quoting.)
2178
+                    preg_match('/^<([\w:$]*)\b/', $tag, $matches);
2179
+                    $tag_name_re = $matches[1];
2180
+
2181
+                    # Parse the content using the HTML-in-Markdown parser.
2182
+                    list ($block_text, $text)
2183
+                        = $this->_hashHTMLBlocks_inMarkdown($text, $indent,
2184
+                            $tag_name_re, $span_mode);
2185
+
2186
+                    # Outdent markdown text.
2187
+                    if ($indent > 0) {
2188
+                        $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
2189
+                                                    $block_text);
2190
+                    }
2191
+
2192
+                    # Append tag content to parsed text.
2193
+                    if (!$span_mode)	$parsed .= "\n\n$block_text\n\n";
2194
+                    else				$parsed .= "$block_text";
2195
+
2196
+                    # Start over a new block.
2197
+                    $block_text = "";
2198
+                }
2199
+                else $block_text .= $tag;
2200
+            }
2201
+
2202
+        } while ($depth > 0);
2203
+
2204
+        #
2205
+        # Hash last block text that wasn't processed inside the loop.
2206
+        #
2207
+        $parsed .= $this->$hash_method($block_text);
2208
+
2209
+        return array($parsed, $text);
2210
+    }
2211
+
2212
+
2213
+    function hashClean($text) {
2214
+    #
2215
+    # Called whenever a tag must be hashed when a function insert a "clean" tag
2216
+    # in $text, it pass through this function and is automaticaly escaped,
2217
+    # blocking invalid nested overlap.
2218
+    #
2219
+        return $this->hashPart($text, 'C');
2220
+    }
2221
+
2222
+
2223
+    function doHeaders($text) {
2224
+    #
2225
+    # Redefined to add id attribute support.
2226
+    #
2227
+        # Setext-style headers:
2228
+        #	  Header 1  {#header1}
2229
+        #	  ========
2230
+        #
2231
+        #	  Header 2  {#header2}
2232
+        #	  --------
2233
+        #
2234
+        $text = preg_replace_callback(
2235
+            '{
2236 2236
 				(^.+?)								# $1: Header text
2237 2237
 				(?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})?	# $2: Id attribute
2238 2238
 				[ ]*\n(=+|-+)[ ]*\n+				# $3: Header footer
2239 2239
 			}mx',
2240
-			array(&$this, '_doHeaders_callback_setext'), $text);
2241
-
2242
-		# atx-style headers:
2243
-		#	# Header 1        {#header1}
2244
-		#	## Header 2       {#header2}
2245
-		#	## Header 2 with closing hashes ##  {#header3}
2246
-		#	...
2247
-		#	###### Header 6   {#header2}
2248
-		#
2249
-		$text = preg_replace_callback('{
2240
+            array(&$this, '_doHeaders_callback_setext'), $text);
2241
+
2242
+        # atx-style headers:
2243
+        #	# Header 1        {#header1}
2244
+        #	## Header 2       {#header2}
2245
+        #	## Header 2 with closing hashes ##  {#header3}
2246
+        #	...
2247
+        #	###### Header 6   {#header2}
2248
+        #
2249
+        $text = preg_replace_callback('{
2250 2250
 				^(\#{1,6})	# $1 = string of #\'s
2251 2251
 				[ ]*
2252 2252
 				(.+?)		# $2 = Header text
@@ -2256,44 +2256,44 @@  discard block
 block discarded – undo
2256 2256
 				[ ]*
2257 2257
 				\n+
2258 2258
 			}xm',
2259
-			array(&$this, '_doHeaders_callback_atx'), $text);
2260
-
2261
-		return $text;
2262
-	}
2263
-	function _doHeaders_attr($attr) {
2264
-		if (empty($attr))  return "";
2265
-		return " id=\"$attr\"";
2266
-	}
2267
-	function _doHeaders_callback_setext($matches) {
2268
-		if ($matches[3] == '-' && preg_match('{^- }', $matches[1]))
2269
-			return $matches[0];
2270
-		$level = $matches[3]{0} == '=' ? 1 : 2;
2271
-		$attr  = $this->_doHeaders_attr($id =& $matches[2]);
2272
-		$block = "<h$level$attr>".$this->runSpanGamut($matches[1])."</h$level>";
2273
-		return "\n" . $this->hashBlock($block) . "\n\n";
2274
-	}
2275
-	function _doHeaders_callback_atx($matches) {
2276
-		$level = strlen($matches[1]);
2277
-		$attr  = $this->_doHeaders_attr($id =& $matches[3]);
2278
-		$block = "<h$level$attr>".$this->runSpanGamut($matches[2])."</h$level>";
2279
-		return "\n" . $this->hashBlock($block) . "\n\n";
2280
-	}
2281
-
2282
-
2283
-	function doTables($text) {
2284
-	#
2285
-	# Form HTML tables.
2286
-	#
2287
-		$less_than_tab = $this->tab_width - 1;
2288
-		#
2289
-		# Find tables with leading pipe.
2290
-		#
2291
-		#	| Header 1 | Header 2
2292
-		#	| -------- | --------
2293
-		#	| Cell 1   | Cell 2
2294
-		#	| Cell 3   | Cell 4
2295
-		#
2296
-		$text = preg_replace_callback('
2259
+            array(&$this, '_doHeaders_callback_atx'), $text);
2260
+
2261
+        return $text;
2262
+    }
2263
+    function _doHeaders_attr($attr) {
2264
+        if (empty($attr))  return "";
2265
+        return " id=\"$attr\"";
2266
+    }
2267
+    function _doHeaders_callback_setext($matches) {
2268
+        if ($matches[3] == '-' && preg_match('{^- }', $matches[1]))
2269
+            return $matches[0];
2270
+        $level = $matches[3]{0} == '=' ? 1 : 2;
2271
+        $attr  = $this->_doHeaders_attr($id =& $matches[2]);
2272
+        $block = "<h$level$attr>".$this->runSpanGamut($matches[1])."</h$level>";
2273
+        return "\n" . $this->hashBlock($block) . "\n\n";
2274
+    }
2275
+    function _doHeaders_callback_atx($matches) {
2276
+        $level = strlen($matches[1]);
2277
+        $attr  = $this->_doHeaders_attr($id =& $matches[3]);
2278
+        $block = "<h$level$attr>".$this->runSpanGamut($matches[2])."</h$level>";
2279
+        return "\n" . $this->hashBlock($block) . "\n\n";
2280
+    }
2281
+
2282
+
2283
+    function doTables($text) {
2284
+    #
2285
+    # Form HTML tables.
2286
+    #
2287
+        $less_than_tab = $this->tab_width - 1;
2288
+        #
2289
+        # Find tables with leading pipe.
2290
+        #
2291
+        #	| Header 1 | Header 2
2292
+        #	| -------- | --------
2293
+        #	| Cell 1   | Cell 2
2294
+        #	| Cell 3   | Cell 4
2295
+        #
2296
+        $text = preg_replace_callback('
2297 2297
 			{
2298 2298
 				^							# Start of a line
2299 2299
 				[ ]{0,'.$less_than_tab.'}	# Allowed whitespace.
@@ -2311,17 +2311,17 @@  discard block
 block discarded – undo
2311 2311
 				)
2312 2312
 				(?=\n|\Z)					# Stop at final double newline.
2313 2313
 			}xm',
2314
-			array(&$this, '_doTable_leadingPipe_callback'), $text);
2315
-
2316
-		#
2317
-		# Find tables without leading pipe.
2318
-		#
2319
-		#	Header 1 | Header 2
2320
-		#	-------- | --------
2321
-		#	Cell 1   | Cell 2
2322
-		#	Cell 3   | Cell 4
2323
-		#
2324
-		$text = preg_replace_callback('
2314
+            array(&$this, '_doTable_leadingPipe_callback'), $text);
2315
+
2316
+        #
2317
+        # Find tables without leading pipe.
2318
+        #
2319
+        #	Header 1 | Header 2
2320
+        #	-------- | --------
2321
+        #	Cell 1   | Cell 2
2322
+        #	Cell 3   | Cell 4
2323
+        #
2324
+        $text = preg_replace_callback('
2325 2325
 			{
2326 2326
 				^							# Start of a line
2327 2327
 				[ ]{0,'.$less_than_tab.'}	# Allowed whitespace.
@@ -2337,87 +2337,87 @@  discard block
 block discarded – undo
2337 2337
 				)
2338 2338
 				(?=\n|\Z)					# Stop at final double newline.
2339 2339
 			}xm',
2340
-			array(&$this, '_DoTable_callback'), $text);
2341
-
2342
-		return $text;
2343
-	}
2344
-	function _doTable_leadingPipe_callback($matches) {
2345
-		$head		= $matches[1];
2346
-		$underline	= $matches[2];
2347
-		$content	= $matches[3];
2348
-
2349
-		# Remove leading pipe for each row.
2350
-		$content	= preg_replace('/^ *[|]/m', '', $content);
2351
-
2352
-		return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
2353
-	}
2354
-	function _doTable_callback($matches) {
2355
-		$head		= $matches[1];
2356
-		$underline	= $matches[2];
2357
-		$content	= $matches[3];
2358
-
2359
-		# Remove any tailing pipes for each line.
2360
-		$head		= preg_replace('/[|] *$/m', '', $head);
2361
-		$underline	= preg_replace('/[|] *$/m', '', $underline);
2362
-		$content	= preg_replace('/[|] *$/m', '', $content);
2363
-
2364
-		# Reading alignement from header underline.
2365
-		$separators	= preg_split('/ *[|] */', $underline);
2366
-		foreach ($separators as $n => $s) {
2367
-			if (preg_match('/^ *-+: *$/', $s))		$attr[$n] = ' align="right"';
2368
-			else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"';
2369
-			else if (preg_match('/^ *:-+ *$/', $s))	$attr[$n] = ' align="left"';
2370
-			else									$attr[$n] = '';
2371
-		}
2372
-
2373
-		# Parsing span elements, including code spans, character escapes,
2374
-		# and inline HTML tags, so that pipes inside those gets ignored.
2375
-		$head		= $this->parseSpan($head);
2376
-		$headers	= preg_split('/ *[|] */', $head);
2377
-		$col_count	= count($headers);
2378
-
2379
-		# Write column headers.
2380
-		$text = "<table>\n";
2381
-		$text .= "<thead>\n";
2382
-		$text .= "<tr>\n";
2383
-		foreach ($headers as $n => $header)
2384
-			$text .= "  <th$attr[$n]>".$this->runSpanGamut(trim($header))."</th>\n";
2385
-		$text .= "</tr>\n";
2386
-		$text .= "</thead>\n";
2387
-
2388
-		# Split content by row.
2389
-		$rows = explode("\n", trim($content, "\n"));
2390
-
2391
-		$text .= "<tbody>\n";
2392
-		foreach ($rows as $row) {
2393
-			# Parsing span elements, including code spans, character escapes,
2394
-			# and inline HTML tags, so that pipes inside those gets ignored.
2395
-			$row = $this->parseSpan($row);
2396
-
2397
-			# Split row by cell.
2398
-			$row_cells = preg_split('/ *[|] */', $row, $col_count);
2399
-			$row_cells = array_pad($row_cells, $col_count, '');
2400
-
2401
-			$text .= "<tr>\n";
2402
-			foreach ($row_cells as $n => $cell)
2403
-				$text .= "  <td$attr[$n]>".$this->runSpanGamut(trim($cell))."</td>\n";
2404
-			$text .= "</tr>\n";
2405
-		}
2406
-		$text .= "</tbody>\n";
2407
-		$text .= "</table>";
2408
-
2409
-		return $this->hashBlock($text) . "\n";
2410
-	}
2411
-
2412
-
2413
-	function doDefLists($text) {
2414
-	#
2415
-	# Form HTML definition lists.
2416
-	#
2417
-		$less_than_tab = $this->tab_width - 1;
2418
-
2419
-		# Re-usable pattern to match any entire dl list:
2420
-		$whole_list_re = '(?>
2340
+            array(&$this, '_DoTable_callback'), $text);
2341
+
2342
+        return $text;
2343
+    }
2344
+    function _doTable_leadingPipe_callback($matches) {
2345
+        $head		= $matches[1];
2346
+        $underline	= $matches[2];
2347
+        $content	= $matches[3];
2348
+
2349
+        # Remove leading pipe for each row.
2350
+        $content	= preg_replace('/^ *[|]/m', '', $content);
2351
+
2352
+        return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
2353
+    }
2354
+    function _doTable_callback($matches) {
2355
+        $head		= $matches[1];
2356
+        $underline	= $matches[2];
2357
+        $content	= $matches[3];
2358
+
2359
+        # Remove any tailing pipes for each line.
2360
+        $head		= preg_replace('/[|] *$/m', '', $head);
2361
+        $underline	= preg_replace('/[|] *$/m', '', $underline);
2362
+        $content	= preg_replace('/[|] *$/m', '', $content);
2363
+
2364
+        # Reading alignement from header underline.
2365
+        $separators	= preg_split('/ *[|] */', $underline);
2366
+        foreach ($separators as $n => $s) {
2367
+            if (preg_match('/^ *-+: *$/', $s))		$attr[$n] = ' align="right"';
2368
+            else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"';
2369
+            else if (preg_match('/^ *:-+ *$/', $s))	$attr[$n] = ' align="left"';
2370
+            else									$attr[$n] = '';
2371
+        }
2372
+
2373
+        # Parsing span elements, including code spans, character escapes,
2374
+        # and inline HTML tags, so that pipes inside those gets ignored.
2375
+        $head		= $this->parseSpan($head);
2376
+        $headers	= preg_split('/ *[|] */', $head);
2377
+        $col_count	= count($headers);
2378
+
2379
+        # Write column headers.
2380
+        $text = "<table>\n";
2381
+        $text .= "<thead>\n";
2382
+        $text .= "<tr>\n";
2383
+        foreach ($headers as $n => $header)
2384
+            $text .= "  <th$attr[$n]>".$this->runSpanGamut(trim($header))."</th>\n";
2385
+        $text .= "</tr>\n";
2386
+        $text .= "</thead>\n";
2387
+
2388
+        # Split content by row.
2389
+        $rows = explode("\n", trim($content, "\n"));
2390
+
2391
+        $text .= "<tbody>\n";
2392
+        foreach ($rows as $row) {
2393
+            # Parsing span elements, including code spans, character escapes,
2394
+            # and inline HTML tags, so that pipes inside those gets ignored.
2395
+            $row = $this->parseSpan($row);
2396
+
2397
+            # Split row by cell.
2398
+            $row_cells = preg_split('/ *[|] */', $row, $col_count);
2399
+            $row_cells = array_pad($row_cells, $col_count, '');
2400
+
2401
+            $text .= "<tr>\n";
2402
+            foreach ($row_cells as $n => $cell)
2403
+                $text .= "  <td$attr[$n]>".$this->runSpanGamut(trim($cell))."</td>\n";
2404
+            $text .= "</tr>\n";
2405
+        }
2406
+        $text .= "</tbody>\n";
2407
+        $text .= "</table>";
2408
+
2409
+        return $this->hashBlock($text) . "\n";
2410
+    }
2411
+
2412
+
2413
+    function doDefLists($text) {
2414
+    #
2415
+    # Form HTML definition lists.
2416
+    #
2417
+        $less_than_tab = $this->tab_width - 1;
2418
+
2419
+        # Re-usable pattern to match any entire dl list:
2420
+        $whole_list_re = '(?>
2421 2421
 			(								# $1 = whole list
2422 2422
 			  (								# $2
2423 2423
 				[ ]{0,'.$less_than_tab.'}
@@ -2444,38 +2444,38 @@  discard block
 block discarded – undo
2444 2444
 			)
2445 2445
 		)'; // mx
2446 2446
 
2447
-		$text = preg_replace_callback('{
2447
+        $text = preg_replace_callback('{
2448 2448
 				(?>\A\n?|(?<=\n\n))
2449 2449
 				'.$whole_list_re.'
2450 2450
 			}mx',
2451
-			array(&$this, '_doDefLists_callback'), $text);
2452
-
2453
-		return $text;
2454
-	}
2455
-	function _doDefLists_callback($matches) {
2456
-		# Re-usable patterns to match list item bullets and number markers:
2457
-		$list = $matches[1];
2458
-
2459
-		# Turn double returns into triple returns, so that we can make a
2460
-		# paragraph for the last item in a list, if necessary:
2461
-		$result = trim($this->processDefListItems($list));
2462
-		$result = "<dl>\n" . $result . "\n</dl>";
2463
-		return $this->hashBlock($result) . "\n\n";
2464
-	}
2465
-
2466
-
2467
-	function processDefListItems($list_str) {
2468
-	#
2469
-	#	Process the contents of a single definition list, splitting it
2470
-	#	into individual term and definition list items.
2471
-	#
2472
-		$less_than_tab = $this->tab_width - 1;
2473
-
2474
-		# trim trailing blank lines:
2475
-		$list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
2476
-
2477
-		# Process definition terms.
2478
-		$list_str = preg_replace_callback('{
2451
+            array(&$this, '_doDefLists_callback'), $text);
2452
+
2453
+        return $text;
2454
+    }
2455
+    function _doDefLists_callback($matches) {
2456
+        # Re-usable patterns to match list item bullets and number markers:
2457
+        $list = $matches[1];
2458
+
2459
+        # Turn double returns into triple returns, so that we can make a
2460
+        # paragraph for the last item in a list, if necessary:
2461
+        $result = trim($this->processDefListItems($list));
2462
+        $result = "<dl>\n" . $result . "\n</dl>";
2463
+        return $this->hashBlock($result) . "\n\n";
2464
+    }
2465
+
2466
+
2467
+    function processDefListItems($list_str) {
2468
+    #
2469
+    #	Process the contents of a single definition list, splitting it
2470
+    #	into individual term and definition list items.
2471
+    #
2472
+        $less_than_tab = $this->tab_width - 1;
2473
+
2474
+        # trim trailing blank lines:
2475
+        $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
2476
+
2477
+        # Process definition terms.
2478
+        $list_str = preg_replace_callback('{
2479 2479
 			(?>\A\n?|\n\n+)					# leading line
2480 2480
 			(								# definition terms = $1
2481 2481
 				[ ]{0,'.$less_than_tab.'}	# leading whitespace
@@ -2486,10 +2486,10 @@  discard block
 block discarded – undo
2486 2486
 			(?=\n?[ ]{0,3}:[ ])				# lookahead for following line feed
2487 2487
 											#   with a definition mark.
2488 2488
 			}xm',
2489
-			array(&$this, '_processDefListItems_callback_dt'), $list_str);
2489
+            array(&$this, '_processDefListItems_callback_dt'), $list_str);
2490 2490
 
2491
-		# Process actual definitions.
2492
-		$list_str = preg_replace_callback('{
2491
+        # Process actual definitions.
2492
+        $list_str = preg_replace_callback('{
2493 2493
 			\n(\n+)?						# leading line = $1
2494 2494
 			(								# marker space = $2
2495 2495
 				[ ]{0,'.$less_than_tab.'}	# whitespace before colon
@@ -2503,50 +2503,50 @@  discard block
 block discarded – undo
2503 2503
 				)
2504 2504
 			)
2505 2505
 			}xm',
2506
-			array(&$this, '_processDefListItems_callback_dd'), $list_str);
2507
-
2508
-		return $list_str;
2509
-	}
2510
-	function _processDefListItems_callback_dt($matches) {
2511
-		$terms = explode("\n", trim($matches[1]));
2512
-		$text = '';
2513
-		foreach ($terms as $term) {
2514
-			$term = $this->runSpanGamut(trim($term));
2515
-			$text .= "\n<dt>" . $term . "</dt>";
2516
-		}
2517
-		return $text . "\n";
2518
-	}
2519
-	function _processDefListItems_callback_dd($matches) {
2520
-		$leading_line	= $matches[1];
2521
-		$marker_space	= $matches[2];
2522
-		$def			= $matches[3];
2523
-
2524
-		if ($leading_line || preg_match('/\n{2,}/', $def)) {
2525
-			# Replace marker with the appropriate whitespace indentation
2526
-			$def = str_repeat(' ', strlen($marker_space)) . $def;
2527
-			$def = $this->runBlockGamut($this->outdent($def . "\n\n"));
2528
-			$def = "\n". $def ."\n";
2529
-		}
2530
-		else {
2531
-			$def = rtrim($def);
2532
-			$def = $this->runSpanGamut($this->outdent($def));
2533
-		}
2534
-
2535
-		return "\n<dd>" . $def . "</dd>\n";
2536
-	}
2537
-
2538
-
2539
-	function doFencedCodeBlocks($text) {
2540
-	#
2541
-	# Adding the fenced code block syntax to regular Markdown:
2542
-	#
2543
-	# ~~~
2544
-	# Code block
2545
-	# ~~~
2546
-	#
2547
-		$less_than_tab = $this->tab_width;
2548
-
2549
-		$text = preg_replace_callback('{
2506
+            array(&$this, '_processDefListItems_callback_dd'), $list_str);
2507
+
2508
+        return $list_str;
2509
+    }
2510
+    function _processDefListItems_callback_dt($matches) {
2511
+        $terms = explode("\n", trim($matches[1]));
2512
+        $text = '';
2513
+        foreach ($terms as $term) {
2514
+            $term = $this->runSpanGamut(trim($term));
2515
+            $text .= "\n<dt>" . $term . "</dt>";
2516
+        }
2517
+        return $text . "\n";
2518
+    }
2519
+    function _processDefListItems_callback_dd($matches) {
2520
+        $leading_line	= $matches[1];
2521
+        $marker_space	= $matches[2];
2522
+        $def			= $matches[3];
2523
+
2524
+        if ($leading_line || preg_match('/\n{2,}/', $def)) {
2525
+            # Replace marker with the appropriate whitespace indentation
2526
+            $def = str_repeat(' ', strlen($marker_space)) . $def;
2527
+            $def = $this->runBlockGamut($this->outdent($def . "\n\n"));
2528
+            $def = "\n". $def ."\n";
2529
+        }
2530
+        else {
2531
+            $def = rtrim($def);
2532
+            $def = $this->runSpanGamut($this->outdent($def));
2533
+        }
2534
+
2535
+        return "\n<dd>" . $def . "</dd>\n";
2536
+    }
2537
+
2538
+
2539
+    function doFencedCodeBlocks($text) {
2540
+    #
2541
+    # Adding the fenced code block syntax to regular Markdown:
2542
+    #
2543
+    # ~~~
2544
+    # Code block
2545
+    # ~~~
2546
+    #
2547
+        $less_than_tab = $this->tab_width;
2548
+
2549
+        $text = preg_replace_callback('{
2550 2550
 				(?:\n|\A)
2551 2551
 				# 1: Opening marker
2552 2552
 				(
@@ -2565,92 +2565,92 @@  discard block
 block discarded – undo
2565 2565
 				# Closing marker.
2566 2566
 				\1 [ ]* \n
2567 2567
 			}xm',
2568
-			array(&$this, '_doFencedCodeBlocks_callback'), $text);
2569
-
2570
-		return $text;
2571
-	}
2572
-	function _doFencedCodeBlocks_callback($matches) {
2573
-		$codeblock = $matches[2];
2574
-		$codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
2575
-		$codeblock = preg_replace_callback('/^\n+/',
2576
-			array(&$this, '_doFencedCodeBlocks_newlines'), $codeblock);
2577
-		$codeblock = "<pre><code>$codeblock</code></pre>";
2578
-		return "\n\n".$this->hashBlock($codeblock)."\n\n";
2579
-	}
2580
-	function _doFencedCodeBlocks_newlines($matches) {
2581
-		return str_repeat("<br$this->empty_element_suffix",
2582
-			strlen($matches[0]));
2583
-	}
2584
-
2585
-
2586
-	#
2587
-	# Redefining emphasis markers so that emphasis by underscore does not
2588
-	# work in the middle of a word.
2589
-	#
2590
-	var $em_relist = array(
2591
-		''  => '(?:(?<!\*)\*(?!\*)|(?<![a-zA-Z0-9_])_(?!_))(?=\S|$)(?![.,:;]\s)',
2592
-		'*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
2593
-		'_' => '(?<=\S|^)(?<!_)_(?![a-zA-Z0-9_])',
2594
-		);
2595
-	var $strong_relist = array(
2596
-		''   => '(?:(?<!\*)\*\*(?!\*)|(?<![a-zA-Z0-9_])__(?!_))(?=\S|$)(?![.,:;]\s)',
2597
-		'**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
2598
-		'__' => '(?<=\S|^)(?<!_)__(?![a-zA-Z0-9_])',
2599
-		);
2600
-	var $em_strong_relist = array(
2601
-		''    => '(?:(?<!\*)\*\*\*(?!\*)|(?<![a-zA-Z0-9_])___(?!_))(?=\S|$)(?![.,:;]\s)',
2602
-		'***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
2603
-		'___' => '(?<=\S|^)(?<!_)___(?![a-zA-Z0-9_])',
2604
-		);
2605
-
2606
-
2607
-	function formParagraphs($text) {
2608
-	#
2609
-	#	Params:
2610
-	#		$text - string to process with html <p> tags
2611
-	#
2612
-		# Strip leading and trailing lines:
2613
-		$text = preg_replace('/\A\n+|\n+\z/', '', $text);
2614
-
2615
-		$grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
2616
-
2617
-		#
2618
-		# Wrap <p> tags and unhashify HTML blocks
2619
-		#
2620
-		foreach ($grafs as $key => $value) {
2621
-			$value = trim($this->runSpanGamut($value));
2622
-
2623
-			# Check if this should be enclosed in a paragraph.
2624
-			# Clean tag hashes & block tag hashes are left alone.
2625
-			$is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value);
2626
-
2627
-			if ($is_p) {
2628
-				$value = "<p>$value</p>";
2629
-			}
2630
-			$grafs[$key] = $value;
2631
-		}
2632
-
2633
-		# Join grafs in one text, then unhash HTML tags.
2634
-		$text = implode("\n\n", $grafs);
2635
-
2636
-		# Finish by removing any tag hashes still present in $text.
2637
-		$text = $this->unhash($text);
2638
-
2639
-		return $text;
2640
-	}
2641
-
2642
-
2643
-	### Footnotes
2644
-
2645
-	function stripFootnotes($text) {
2646
-	#
2647
-	# Strips link definitions from text, stores the URLs and titles in
2648
-	# hash references.
2649
-	#
2650
-		$less_than_tab = $this->tab_width - 1;
2651
-
2652
-		# Link defs are in the form: [^id]: url "optional title"
2653
-		$text = preg_replace_callback('{
2568
+            array(&$this, '_doFencedCodeBlocks_callback'), $text);
2569
+
2570
+        return $text;
2571
+    }
2572
+    function _doFencedCodeBlocks_callback($matches) {
2573
+        $codeblock = $matches[2];
2574
+        $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
2575
+        $codeblock = preg_replace_callback('/^\n+/',
2576
+            array(&$this, '_doFencedCodeBlocks_newlines'), $codeblock);
2577
+        $codeblock = "<pre><code>$codeblock</code></pre>";
2578
+        return "\n\n".$this->hashBlock($codeblock)."\n\n";
2579
+    }
2580
+    function _doFencedCodeBlocks_newlines($matches) {
2581
+        return str_repeat("<br$this->empty_element_suffix",
2582
+            strlen($matches[0]));
2583
+    }
2584
+
2585
+
2586
+    #
2587
+    # Redefining emphasis markers so that emphasis by underscore does not
2588
+    # work in the middle of a word.
2589
+    #
2590
+    var $em_relist = array(
2591
+        ''  => '(?:(?<!\*)\*(?!\*)|(?<![a-zA-Z0-9_])_(?!_))(?=\S|$)(?![.,:;]\s)',
2592
+        '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
2593
+        '_' => '(?<=\S|^)(?<!_)_(?![a-zA-Z0-9_])',
2594
+        );
2595
+    var $strong_relist = array(
2596
+        ''   => '(?:(?<!\*)\*\*(?!\*)|(?<![a-zA-Z0-9_])__(?!_))(?=\S|$)(?![.,:;]\s)',
2597
+        '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
2598
+        '__' => '(?<=\S|^)(?<!_)__(?![a-zA-Z0-9_])',
2599
+        );
2600
+    var $em_strong_relist = array(
2601
+        ''    => '(?:(?<!\*)\*\*\*(?!\*)|(?<![a-zA-Z0-9_])___(?!_))(?=\S|$)(?![.,:;]\s)',
2602
+        '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
2603
+        '___' => '(?<=\S|^)(?<!_)___(?![a-zA-Z0-9_])',
2604
+        );
2605
+
2606
+
2607
+    function formParagraphs($text) {
2608
+    #
2609
+    #	Params:
2610
+    #		$text - string to process with html <p> tags
2611
+    #
2612
+        # Strip leading and trailing lines:
2613
+        $text = preg_replace('/\A\n+|\n+\z/', '', $text);
2614
+
2615
+        $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
2616
+
2617
+        #
2618
+        # Wrap <p> tags and unhashify HTML blocks
2619
+        #
2620
+        foreach ($grafs as $key => $value) {
2621
+            $value = trim($this->runSpanGamut($value));
2622
+
2623
+            # Check if this should be enclosed in a paragraph.
2624
+            # Clean tag hashes & block tag hashes are left alone.
2625
+            $is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value);
2626
+
2627
+            if ($is_p) {
2628
+                $value = "<p>$value</p>";
2629
+            }
2630
+            $grafs[$key] = $value;
2631
+        }
2632
+
2633
+        # Join grafs in one text, then unhash HTML tags.
2634
+        $text = implode("\n\n", $grafs);
2635
+
2636
+        # Finish by removing any tag hashes still present in $text.
2637
+        $text = $this->unhash($text);
2638
+
2639
+        return $text;
2640
+    }
2641
+
2642
+
2643
+    ### Footnotes
2644
+
2645
+    function stripFootnotes($text) {
2646
+    #
2647
+    # Strips link definitions from text, stores the URLs and titles in
2648
+    # hash references.
2649
+    #
2650
+        $less_than_tab = $this->tab_width - 1;
2651
+
2652
+        # Link defs are in the form: [^id]: url "optional title"
2653
+        $text = preg_replace_callback('{
2654 2654
 			^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?:	# note_id = $1
2655 2655
 			  [ ]*
2656 2656
 			  \n?					# maybe *one* newline
@@ -2665,180 +2665,180 @@  discard block
 block discarded – undo
2665 2665
 				)*
2666 2666
 			)
2667 2667
 			}xm',
2668
-			array(&$this, '_stripFootnotes_callback'),
2669
-			$text);
2670
-		return $text;
2671
-	}
2672
-	function _stripFootnotes_callback($matches) {
2673
-		$note_id = $this->fn_id_prefix . $matches[1];
2674
-		$this->footnotes[$note_id] = $this->outdent($matches[2]);
2675
-		return ''; # String that will replace the block
2676
-	}
2677
-
2678
-
2679
-	function doFootnotes($text) {
2680
-	#
2681
-	# Replace footnote references in $text [^id] with a special text-token
2682
-	# which will be replaced by the actual footnote marker in appendFootnotes.
2683
-	#
2684
-		if (!$this->in_anchor) {
2685
-			$text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text);
2686
-		}
2687
-		return $text;
2688
-	}
2689
-
2690
-
2691
-	function appendFootnotes($text) {
2692
-	#
2693
-	# Append footnote list to text.
2694
-	#
2695
-		$text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
2696
-			array(&$this, '_appendFootnotes_callback'), $text);
2697
-
2698
-		if (!empty($this->footnotes_ordered)) {
2699
-			$text .= "\n\n";
2700
-			$text .= "<div class=\"footnotes\">\n";
2701
-			$text .= "<hr". $this->empty_element_suffix ."\n";
2702
-			$text .= "<ol>\n\n";
2703
-
2704
-			$attr = " rev=\"footnote\"";
2705
-			if ($this->fn_backlink_class != "") {
2706
-				$class = $this->fn_backlink_class;
2707
-				$class = $this->encodeAttribute($class);
2708
-				$attr .= " class=\"$class\"";
2709
-			}
2710
-			if ($this->fn_backlink_title != "") {
2711
-				$title = $this->fn_backlink_title;
2712
-				$title = $this->encodeAttribute($title);
2713
-				$attr .= " title=\"$title\"";
2714
-			}
2715
-			$num = 0;
2716
-
2717
-			while (!empty($this->footnotes_ordered)) {
2718
-				$footnote = reset($this->footnotes_ordered);
2719
-				$note_id = key($this->footnotes_ordered);
2720
-				unset($this->footnotes_ordered[$note_id]);
2721
-
2722
-				$footnote .= "\n"; # Need to append newline before parsing.
2723
-				$footnote = $this->runBlockGamut("$footnote\n");
2724
-				$footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
2725
-					array(&$this, '_appendFootnotes_callback'), $footnote);
2726
-
2727
-				$attr = str_replace("%%", ++$num, $attr);
2728
-				$note_id = $this->encodeAttribute($note_id);
2729
-
2730
-				# Add backlink to last paragraph; create new paragraph if needed.
2731
-				$backlink = "<a href=\"#fnref:$note_id\"$attr>&#8617;</a>";
2732
-				if (preg_match('{</p>$}', $footnote)) {
2733
-					$footnote = substr($footnote, 0, -4) . "&#160;$backlink</p>";
2734
-				} else {
2735
-					$footnote .= "\n\n<p>$backlink</p>";
2736
-				}
2737
-
2738
-				$text .= "<li id=\"fn:$note_id\">\n";
2739
-				$text .= $footnote . "\n";
2740
-				$text .= "</li>\n\n";
2741
-			}
2742
-
2743
-			$text .= "</ol>\n";
2744
-			$text .= "</div>";
2745
-		}
2746
-		return $text;
2747
-	}
2748
-	function _appendFootnotes_callback($matches) {
2749
-		$node_id = $this->fn_id_prefix . $matches[1];
2750
-
2751
-		# Create footnote marker only if it has a corresponding footnote *and*
2752
-		# the footnote hasn't been used by another marker.
2753
-		if (isset($this->footnotes[$node_id])) {
2754
-			# Transfert footnote content to the ordered list.
2755
-			$this->footnotes_ordered[$node_id] = $this->footnotes[$node_id];
2756
-			unset($this->footnotes[$node_id]);
2757
-
2758
-			$num = $this->footnote_counter++;
2759
-			$attr = " rel=\"footnote\"";
2760
-			if ($this->fn_link_class != "") {
2761
-				$class = $this->fn_link_class;
2762
-				$class = $this->encodeAttribute($class);
2763
-				$attr .= " class=\"$class\"";
2764
-			}
2765
-			if ($this->fn_link_title != "") {
2766
-				$title = $this->fn_link_title;
2767
-				$title = $this->encodeAttribute($title);
2768
-				$attr .= " title=\"$title\"";
2769
-			}
2770
-
2771
-			$attr = str_replace("%%", $num, $attr);
2772
-			$node_id = $this->encodeAttribute($node_id);
2773
-
2774
-			return
2775
-				"<sup id=\"fnref:$node_id\">".
2776
-				"<a href=\"#fn:$node_id\"$attr>$num</a>".
2777
-				"</sup>";
2778
-		}
2779
-
2780
-		return "[^".$matches[1]."]";
2781
-	}
2782
-
2783
-
2784
-	### Abbreviations ###
2785
-
2786
-	function stripAbbreviations($text) {
2787
-	#
2788
-	# Strips abbreviations from text, stores titles in hash references.
2789
-	#
2790
-		$less_than_tab = $this->tab_width - 1;
2791
-
2792
-		# Link defs are in the form: [id]*: url "optional title"
2793
-		$text = preg_replace_callback('{
2668
+            array(&$this, '_stripFootnotes_callback'),
2669
+            $text);
2670
+        return $text;
2671
+    }
2672
+    function _stripFootnotes_callback($matches) {
2673
+        $note_id = $this->fn_id_prefix . $matches[1];
2674
+        $this->footnotes[$note_id] = $this->outdent($matches[2]);
2675
+        return ''; # String that will replace the block
2676
+    }
2677
+
2678
+
2679
+    function doFootnotes($text) {
2680
+    #
2681
+    # Replace footnote references in $text [^id] with a special text-token
2682
+    # which will be replaced by the actual footnote marker in appendFootnotes.
2683
+    #
2684
+        if (!$this->in_anchor) {
2685
+            $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text);
2686
+        }
2687
+        return $text;
2688
+    }
2689
+
2690
+
2691
+    function appendFootnotes($text) {
2692
+    #
2693
+    # Append footnote list to text.
2694
+    #
2695
+        $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
2696
+            array(&$this, '_appendFootnotes_callback'), $text);
2697
+
2698
+        if (!empty($this->footnotes_ordered)) {
2699
+            $text .= "\n\n";
2700
+            $text .= "<div class=\"footnotes\">\n";
2701
+            $text .= "<hr". $this->empty_element_suffix ."\n";
2702
+            $text .= "<ol>\n\n";
2703
+
2704
+            $attr = " rev=\"footnote\"";
2705
+            if ($this->fn_backlink_class != "") {
2706
+                $class = $this->fn_backlink_class;
2707
+                $class = $this->encodeAttribute($class);
2708
+                $attr .= " class=\"$class\"";
2709
+            }
2710
+            if ($this->fn_backlink_title != "") {
2711
+                $title = $this->fn_backlink_title;
2712
+                $title = $this->encodeAttribute($title);
2713
+                $attr .= " title=\"$title\"";
2714
+            }
2715
+            $num = 0;
2716
+
2717
+            while (!empty($this->footnotes_ordered)) {
2718
+                $footnote = reset($this->footnotes_ordered);
2719
+                $note_id = key($this->footnotes_ordered);
2720
+                unset($this->footnotes_ordered[$note_id]);
2721
+
2722
+                $footnote .= "\n"; # Need to append newline before parsing.
2723
+                $footnote = $this->runBlockGamut("$footnote\n");
2724
+                $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
2725
+                    array(&$this, '_appendFootnotes_callback'), $footnote);
2726
+
2727
+                $attr = str_replace("%%", ++$num, $attr);
2728
+                $note_id = $this->encodeAttribute($note_id);
2729
+
2730
+                # Add backlink to last paragraph; create new paragraph if needed.
2731
+                $backlink = "<a href=\"#fnref:$note_id\"$attr>&#8617;</a>";
2732
+                if (preg_match('{</p>$}', $footnote)) {
2733
+                    $footnote = substr($footnote, 0, -4) . "&#160;$backlink</p>";
2734
+                } else {
2735
+                    $footnote .= "\n\n<p>$backlink</p>";
2736
+                }
2737
+
2738
+                $text .= "<li id=\"fn:$note_id\">\n";
2739
+                $text .= $footnote . "\n";
2740
+                $text .= "</li>\n\n";
2741
+            }
2742
+
2743
+            $text .= "</ol>\n";
2744
+            $text .= "</div>";
2745
+        }
2746
+        return $text;
2747
+    }
2748
+    function _appendFootnotes_callback($matches) {
2749
+        $node_id = $this->fn_id_prefix . $matches[1];
2750
+
2751
+        # Create footnote marker only if it has a corresponding footnote *and*
2752
+        # the footnote hasn't been used by another marker.
2753
+        if (isset($this->footnotes[$node_id])) {
2754
+            # Transfert footnote content to the ordered list.
2755
+            $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id];
2756
+            unset($this->footnotes[$node_id]);
2757
+
2758
+            $num = $this->footnote_counter++;
2759
+            $attr = " rel=\"footnote\"";
2760
+            if ($this->fn_link_class != "") {
2761
+                $class = $this->fn_link_class;
2762
+                $class = $this->encodeAttribute($class);
2763
+                $attr .= " class=\"$class\"";
2764
+            }
2765
+            if ($this->fn_link_title != "") {
2766
+                $title = $this->fn_link_title;
2767
+                $title = $this->encodeAttribute($title);
2768
+                $attr .= " title=\"$title\"";
2769
+            }
2770
+
2771
+            $attr = str_replace("%%", $num, $attr);
2772
+            $node_id = $this->encodeAttribute($node_id);
2773
+
2774
+            return
2775
+                "<sup id=\"fnref:$node_id\">".
2776
+                "<a href=\"#fn:$node_id\"$attr>$num</a>".
2777
+                "</sup>";
2778
+        }
2779
+
2780
+        return "[^".$matches[1]."]";
2781
+    }
2782
+
2783
+
2784
+    ### Abbreviations ###
2785
+
2786
+    function stripAbbreviations($text) {
2787
+    #
2788
+    # Strips abbreviations from text, stores titles in hash references.
2789
+    #
2790
+        $less_than_tab = $this->tab_width - 1;
2791
+
2792
+        # Link defs are in the form: [id]*: url "optional title"
2793
+        $text = preg_replace_callback('{
2794 2794
 			^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?:	# abbr_id = $1
2795 2795
 			(.*)					# text = $2 (no blank lines allowed)
2796 2796
 			}xm',
2797
-			array(&$this, '_stripAbbreviations_callback'),
2798
-			$text);
2799
-		return $text;
2800
-	}
2801
-	function _stripAbbreviations_callback($matches) {
2802
-		$abbr_word = $matches[1];
2803
-		$abbr_desc = $matches[2];
2804
-		if ($this->abbr_word_re)
2805
-			$this->abbr_word_re .= '|';
2806
-		$this->abbr_word_re .= preg_quote($abbr_word);
2807
-		$this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
2808
-		return ''; # String that will replace the block
2809
-	}
2810
-
2811
-
2812
-	function doAbbreviations($text) {
2813
-	#
2814
-	# Find defined abbreviations in text and wrap them in <abbr> elements.
2815
-	#
2816
-		if ($this->abbr_word_re) {
2817
-			// cannot use the /x modifier because abbr_word_re may
2818
-			// contain significant spaces:
2819
-			$text = preg_replace_callback('{'.
2820
-				'(?<![\w\x1A])'.
2821
-				'(?:'.$this->abbr_word_re.')'.
2822
-				'(?![\w\x1A])'.
2823
-				'}',
2824
-				array(&$this, '_doAbbreviations_callback'), $text);
2825
-		}
2826
-		return $text;
2827
-	}
2828
-	function _doAbbreviations_callback($matches) {
2829
-		$abbr = $matches[0];
2830
-		if (isset($this->abbr_desciptions[$abbr])) {
2831
-			$desc = $this->abbr_desciptions[$abbr];
2832
-			if (empty($desc)) {
2833
-				return $this->hashPart("<abbr>$abbr</abbr>");
2834
-			} else {
2835
-				$desc = $this->encodeAttribute($desc);
2836
-				return $this->hashPart("<abbr title=\"$desc\">$abbr</abbr>");
2837
-			}
2838
-		} else {
2839
-			return $matches[0];
2840
-		}
2841
-	}
2797
+            array(&$this, '_stripAbbreviations_callback'),
2798
+            $text);
2799
+        return $text;
2800
+    }
2801
+    function _stripAbbreviations_callback($matches) {
2802
+        $abbr_word = $matches[1];
2803
+        $abbr_desc = $matches[2];
2804
+        if ($this->abbr_word_re)
2805
+            $this->abbr_word_re .= '|';
2806
+        $this->abbr_word_re .= preg_quote($abbr_word);
2807
+        $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
2808
+        return ''; # String that will replace the block
2809
+    }
2810
+
2811
+
2812
+    function doAbbreviations($text) {
2813
+    #
2814
+    # Find defined abbreviations in text and wrap them in <abbr> elements.
2815
+    #
2816
+        if ($this->abbr_word_re) {
2817
+            // cannot use the /x modifier because abbr_word_re may
2818
+            // contain significant spaces:
2819
+            $text = preg_replace_callback('{'.
2820
+                '(?<![\w\x1A])'.
2821
+                '(?:'.$this->abbr_word_re.')'.
2822
+                '(?![\w\x1A])'.
2823
+                '}',
2824
+                array(&$this, '_doAbbreviations_callback'), $text);
2825
+        }
2826
+        return $text;
2827
+    }
2828
+    function _doAbbreviations_callback($matches) {
2829
+        $abbr = $matches[0];
2830
+        if (isset($this->abbr_desciptions[$abbr])) {
2831
+            $desc = $this->abbr_desciptions[$abbr];
2832
+            if (empty($desc)) {
2833
+                return $this->hashPart("<abbr>$abbr</abbr>");
2834
+            } else {
2835
+                $desc = $this->encodeAttribute($desc);
2836
+                return $this->hashPart("<abbr title=\"$desc\">$abbr</abbr>");
2837
+            }
2838
+        } else {
2839
+            return $matches[0];
2840
+        }
2841
+    }
2842 2842
 
2843 2843
 }
2844 2844
 
Please login to merge, or discard this patch.
Spacing   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -12,8 +12,8 @@  discard block
 block discarded – undo
12 12
 #
13 13
 
14 14
 
15
-define( 'MARKDOWN_VERSION',  "1.0.1n" ); # Sat 10 Oct 2009
16
-define( 'MARKDOWNEXTRA_VERSION',  "1.2.4" ); # Sat 10 Oct 2009
15
+define('MARKDOWN_VERSION', "1.0.1n"); # Sat 10 Oct 2009
16
+define('MARKDOWNEXTRA_VERSION', "1.2.4"); # Sat 10 Oct 2009
17 17
 
18 18
 
19 19
 #
@@ -21,18 +21,18 @@  discard block
 block discarded – undo
21 21
 #
22 22
 
23 23
 # Change to ">" for HTML output
24
-@define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX',  " />");
24
+@define('MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />");
25 25
 
26 26
 # Define the width of a tab for code blocks.
27
-@define( 'MARKDOWN_TAB_WIDTH',     4 );
27
+@define('MARKDOWN_TAB_WIDTH', 4);
28 28
 
29 29
 # Optional title attribute for footnote links and backlinks.
30
-@define( 'MARKDOWN_FN_LINK_TITLE',         "" );
31
-@define( 'MARKDOWN_FN_BACKLINK_TITLE',     "" );
30
+@define('MARKDOWN_FN_LINK_TITLE', "");
31
+@define('MARKDOWN_FN_BACKLINK_TITLE', "");
32 32
 
33 33
 # Optional class attribute for footnote links and backlinks.
34
-@define( 'MARKDOWN_FN_LINK_CLASS',         "" );
35
-@define( 'MARKDOWN_FN_BACKLINK_CLASS',     "" );
34
+@define('MARKDOWN_FN_LINK_CLASS', "");
35
+@define('MARKDOWN_FN_BACKLINK_CLASS', "");
36 36
 
37 37
 
38 38
 #
@@ -40,14 +40,14 @@  discard block
 block discarded – undo
40 40
 #
41 41
 
42 42
 # Change to false to remove Markdown from posts and/or comments.
43
-@define( 'MARKDOWN_WP_POSTS',      true );
44
-@define( 'MARKDOWN_WP_COMMENTS',   true );
43
+@define('MARKDOWN_WP_POSTS', true);
44
+@define('MARKDOWN_WP_COMMENTS', true);
45 45
 
46 46
 
47 47
 
48 48
 ### Standard Function Interface ###
49 49
 
50
-@define( 'MARKDOWN_PARSER_CLASS',  'MarkdownExtra_Parser' );
50
+@define('MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser');
51 51
 
52 52
 function Markdown($text) {
53 53
 #
@@ -85,19 +85,19 @@  discard block
 block discarded – undo
85 85
 	# - Run Markdown on excerpt, then remove all tags.
86 86
 	# - Add paragraph tag around the excerpt, but remove it for the excerpt rss.
87 87
 	if (MARKDOWN_WP_POSTS) {
88
-		remove_filter('the_content',     'wpautop');
88
+		remove_filter('the_content', 'wpautop');
89 89
         remove_filter('the_content_rss', 'wpautop');
90
-		remove_filter('the_excerpt',     'wpautop');
91
-		add_filter('the_content',     'mdwp_MarkdownPost', 6);
90
+		remove_filter('the_excerpt', 'wpautop');
91
+		add_filter('the_content', 'mdwp_MarkdownPost', 6);
92 92
         add_filter('the_content_rss', 'mdwp_MarkdownPost', 6);
93 93
 		add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6);
94 94
 		add_filter('get_the_excerpt', 'trim', 7);
95
-		add_filter('the_excerpt',     'mdwp_add_p');
95
+		add_filter('the_excerpt', 'mdwp_add_p');
96 96
 		add_filter('the_excerpt_rss', 'mdwp_strip_p');
97 97
 
98
-		remove_filter('content_save_pre',  'balanceTags', 50);
99
-		remove_filter('excerpt_save_pre',  'balanceTags', 50);
100
-		add_filter('the_content',  	  'balanceTags', 50);
98
+		remove_filter('content_save_pre', 'balanceTags', 50);
99
+		remove_filter('excerpt_save_pre', 'balanceTags', 50);
100
+		add_filter('the_content', 'balanceTags', 50);
101 101
 		add_filter('get_the_excerpt', 'balanceTags', 9);
102 102
 	}
103 103
 
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 		if (is_single() || is_page() || is_feed()) {
112 112
 			$parser->fn_id_prefix = "";
113 113
 		} else {
114
-			$parser->fn_id_prefix = get_the_ID() . ".";
114
+			$parser->fn_id_prefix = get_the_ID().".";
115 115
 		}
116 116
 		return $parser->transform($text);
117 117
 	}
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 		add_filter('pre_comment_content', 'Markdown', 6);
128 128
 		add_filter('pre_comment_content', 'mdwp_hide_tags', 8);
129 129
 		add_filter('pre_comment_content', 'mdwp_show_tags', 12);
130
-		add_filter('get_comment_text',    'Markdown', 6);
130
+		add_filter('get_comment_text', 'Markdown', 6);
131 131
 		add_filter('get_comment_excerpt', 'Markdown', 6);
132 132
 		add_filter('get_comment_excerpt', 'mdwp_strip_p', 7);
133 133
 
@@ -192,13 +192,13 @@  discard block
 block discarded – undo
192 192
 	@include_once 'smartypants.php';
193 193
 	# Fake Textile class. It calls Markdown instead.
194 194
 	class Textile {
195
-		function TextileThis($text, $lite='', $encode='') {
195
+		function TextileThis($text, $lite = '', $encode = '') {
196 196
 			if ($lite == '' && $encode == '')    $text = Markdown($text);
197 197
 			if (function_exists('SmartyPants'))  $text = SmartyPants($text);
198 198
 			return $text;
199 199
 		}
200 200
 		# Fake restricted version: restrictions are not supported for now.
201
-		function TextileRestricted($text, $lite='', $noimage='') {
201
+		function TextileRestricted($text, $lite = '', $noimage = '') {
202 202
 			return $this->TextileThis($text, $lite);
203 203
 		}
204 204
 		# Workaround to ensure compatibility with TextPattern 4.0.3.
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 
333 333
 		$this->teardown();
334 334
 
335
-		return $text . "\n";
335
+		return $text."\n";
336 336
 	}
337 337
 
338 338
 	var $document_gamut = array(
@@ -381,7 +381,7 @@  discard block
 block discarded – undo
381 381
 		$link_id = strtolower($matches[1]);
382 382
 		$url = $matches[2] == '' ? $matches[3] : $matches[2];
383 383
 		$this->urls[$link_id] = $url;
384
-		$this->titles[$link_id] =& $matches[4];
384
+		$this->titles[$link_id] = & $matches[4];
385 385
 		return ''; # String that will replace the block
386 386
 	}
387 387
 
@@ -434,8 +434,8 @@  discard block
 block discarded – undo
434 434
 					(?>
435 435
 					  />
436 436
 					|
437
-					  >', $nested_tags_level).	# end of opening tag
438
-					  '.*?'.					# last level nested tag content
437
+					  >', $nested_tags_level).# end of opening tag
438
+					  '.*?'.# last level nested tag content
439 439
 			str_repeat('
440 440
 					  </\2\s*>	# closing nested tag
441 441
 					)
@@ -547,7 +547,7 @@  discard block
 block discarded – undo
547 547
 
548 548
 		# Then hash the block.
549 549
 		static $i = 0;
550
-		$key = "$boundary\x1A" . ++$i . $boundary;
550
+		$key = "$boundary\x1A".++$i.$boundary;
551 551
 		$this->html_hashes[$key] = $text;
552 552
 		return $key; # String that will replace the tag.
553 553
 	}
@@ -740,9 +740,9 @@  discard block
 block discarded – undo
740 740
 		return $text;
741 741
 	}
742 742
 	function _doAnchors_reference_callback($matches) {
743
-		$whole_match =  $matches[1];
744
-		$link_text   =  $matches[2];
745
-		$link_id     =& $matches[3];
743
+		$whole_match = $matches[1];
744
+		$link_text   = $matches[2];
745
+		$link_id     = & $matches[3];
746 746
 
747 747
 		if ($link_id == "") {
748 748
 			# for shortcut links like [this][] or [this].
@@ -758,10 +758,10 @@  discard block
 block discarded – undo
758 758
 			$url = $this->encodeAttribute($url);
759 759
 
760 760
 			$result = "<a href=\"$url\"";
761
-			if ( isset( $this->titles[$link_id] ) ) {
761
+			if (isset($this->titles[$link_id])) {
762 762
 				$title = $this->titles[$link_id];
763 763
 				$title = $this->encodeAttribute($title);
764
-				$result .=  " title=\"$title\"";
764
+				$result .= " title=\"$title\"";
765 765
 			}
766 766
 
767 767
 			$link_text = $this->runSpanGamut($link_text);
@@ -774,17 +774,17 @@  discard block
 block discarded – undo
774 774
 		return $result;
775 775
 	}
776 776
 	function _doAnchors_inline_callback($matches) {
777
-		$whole_match	=  $matches[1];
778
-		$link_text		=  $this->runSpanGamut($matches[2]);
779
-		$url			=  $matches[3] == '' ? $matches[4] : $matches[3];
780
-		$title			=& $matches[7];
777
+		$whole_match = $matches[1];
778
+		$link_text = $this->runSpanGamut($matches[2]);
779
+		$url = $matches[3] == '' ? $matches[4] : $matches[3];
780
+		$title = & $matches[7];
781 781
 
782 782
 		$url = $this->encodeAttribute($url);
783 783
 
784 784
 		$result = "<a href=\"$url\"";
785 785
 		if (isset($title)) {
786 786
 			$title = $this->encodeAttribute($title);
787
-			$result .=  " title=\"$title\"";
787
+			$result .= " title=\"$title\"";
788 788
 		}
789 789
 
790 790
 		$link_text = $this->runSpanGamut($link_text);
@@ -865,7 +865,7 @@  discard block
 block discarded – undo
865 865
 			if (isset($this->titles[$link_id])) {
866 866
 				$title = $this->titles[$link_id];
867 867
 				$title = $this->encodeAttribute($title);
868
-				$result .=  " title=\"$title\"";
868
+				$result .= " title=\"$title\"";
869 869
 			}
870 870
 			$result .= $this->empty_element_suffix;
871 871
 			$result = $this->hashPart($result);
@@ -878,17 +878,17 @@  discard block
 block discarded – undo
878 878
 		return $result;
879 879
 	}
880 880
 	function _doImages_inline_callback($matches) {
881
-		$whole_match	= $matches[1];
882
-		$alt_text		= $matches[2];
883
-		$url			= $matches[3] == '' ? $matches[4] : $matches[3];
884
-		$title			=& $matches[7];
881
+		$whole_match = $matches[1];
882
+		$alt_text = $matches[2];
883
+		$url = $matches[3] == '' ? $matches[4] : $matches[3];
884
+		$title = & $matches[7];
885 885
 
886 886
 		$alt_text = $this->encodeAttribute($alt_text);
887 887
 		$url = $this->encodeAttribute($url);
888 888
 		$result = "<img src=\"$url\" alt=\"$alt_text\"";
889 889
 		if (isset($title)) {
890 890
 			$title = $this->encodeAttribute($title);
891
-			$result .=  " title=\"$title\""; # $title already quoted
891
+			$result .= " title=\"$title\""; # $title already quoted
892 892
 		}
893 893
 		$result .= $this->empty_element_suffix;
894 894
 
@@ -933,12 +933,12 @@  discard block
 block discarded – undo
933 933
 
934 934
 		$level = $matches[2]{0} == '=' ? 1 : 2;
935 935
 		$block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
936
-		return "\n" . $this->hashBlock($block) . "\n\n";
936
+		return "\n".$this->hashBlock($block)."\n\n";
937 937
 	}
938 938
 	function _doHeaders_callback_atx($matches) {
939 939
 		$level = strlen($matches[1]);
940 940
 		$block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
941
-		return "\n" . $this->hashBlock($block) . "\n\n";
941
+		return "\n".$this->hashBlock($block)."\n\n";
942 942
 	}
943 943
 
944 944
 
@@ -1017,13 +1017,13 @@  discard block
 block discarded – undo
1017 1017
 		$list = $matches[1];
1018 1018
 		$list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
1019 1019
 
1020
-		$marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
1020
+		$marker_any_re = ($list_type == "ul" ? $marker_ul_re : $marker_ol_re);
1021 1021
 
1022 1022
 		$list .= "\n";
1023 1023
 		$result = $this->processListItems($list, $marker_any_re);
1024 1024
 
1025
-		$result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
1026
-		return "\n". $result ."\n\n";
1025
+		$result = $this->hashBlock("<$list_type>\n".$result."</$list_type>");
1026
+		return "\n".$result."\n\n";
1027 1027
 	}
1028 1028
 
1029 1029
 	var $list_level = 0;
@@ -1076,16 +1076,16 @@  discard block
 block discarded – undo
1076 1076
 	}
1077 1077
 	function _processListItems_callback($matches) {
1078 1078
 		$item = $matches[4];
1079
-		$leading_line =& $matches[1];
1080
-		$leading_space =& $matches[2];
1079
+		$leading_line = & $matches[1];
1080
+		$leading_space = & $matches[2];
1081 1081
 		$marker_space = $matches[3];
1082
-		$tailing_blank_line =& $matches[5];
1082
+		$tailing_blank_line = & $matches[5];
1083 1083
 
1084 1084
 		if ($leading_line || $tailing_blank_line ||
1085 1085
 			preg_match('/\n{2,}/', $item))
1086 1086
 		{
1087 1087
 			# Replace marker with the appropriate whitespace indentation
1088
-			$item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
1088
+			$item = $leading_space.str_repeat(' ', strlen($marker_space)).$item;
1089 1089
 			$item = $this->runBlockGamut($this->outdent($item)."\n");
1090 1090
 		}
1091 1091
 		else {
@@ -1095,7 +1095,7 @@  discard block
 block discarded – undo
1095 1095
 			$item = $this->runSpanGamut($item);
1096 1096
 		}
1097 1097
 
1098
-		return "<li>" . $item . "</li>\n";
1098
+		return "<li>".$item."</li>\n";
1099 1099
 	}
1100 1100
 
1101 1101
 
@@ -1173,7 +1173,7 @@  discard block
 block discarded – undo
1173 1173
 				$token_relist[] = $strong_re;
1174 1174
 
1175 1175
 				# Construct master expression from list.
1176
-				$token_re = '{('. implode('|', $token_relist) .')}';
1176
+				$token_re = '{('.implode('|', $token_relist).')}';
1177 1177
 				$this->em_strong_prepared_relist["$em$strong"] = $token_re;
1178 1178
 			}
1179 1179
 		}
@@ -1199,8 +1199,8 @@  discard block
 block discarded – undo
1199 1199
 			#
1200 1200
 			$parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
1201 1201
 			$text_stack[0] .= $parts[0];
1202
-			$token =& $parts[1];
1203
-			$text =& $parts[2];
1202
+			$token = & $parts[1];
1203
+			$text = & $parts[2];
1204 1204
 
1205 1205
 			if (empty($token)) {
1206 1206
 				# Reached end of text span: empty stack without emitting.
@@ -1227,7 +1227,7 @@  discard block
 block discarded – undo
1227 1227
 				} else {
1228 1228
 					# Other closing marker: close one em or strong and
1229 1229
 					# change current token state to match the other
1230
-					$token_stack[0] = str_repeat($token{0}, 3-$token_len);
1230
+					$token_stack[0] = str_repeat($token{0}, 3 - $token_len);
1231 1231
 					$tag = $token_len == 2 ? "strong" : "em";
1232 1232
 					$span = $text_stack[0];
1233 1233
 					$span = $this->runSpanGamut($span);
@@ -1321,7 +1321,7 @@  discard block
 block discarded – undo
1321 1321
 		$bq = $matches[1];
1322 1322
 		# trim one level of quoting - trim whitespace-only lines
1323 1323
 		$bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
1324
-		$bq = $this->runBlockGamut($bq);		# recurse
1324
+		$bq = $this->runBlockGamut($bq); # recurse
1325 1325
 
1326 1326
 		$bq = preg_replace('/^/m', "  ", $bq);
1327 1327
 		# These leading spaces cause problem with <pre> content,
@@ -1329,7 +1329,7 @@  discard block
 block discarded – undo
1329 1329
 		$bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
1330 1330
 			array(&$this, '_doBlockQuotes_callback2'), $bq);
1331 1331
 
1332
-		return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
1332
+		return "\n".$this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
1333 1333
 	}
1334 1334
 	function _doBlockQuotes_callback2($matches) {
1335 1335
 		$pre = $matches[1];
@@ -1431,7 +1431,7 @@  discard block
 block discarded – undo
1431 1431
 			# Ampersand-encoding based entirely on Nat Irons's Amputator
1432 1432
 			# MT plugin: <http://bumppo.net/projects/amputator/>
1433 1433
 			$text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
1434
-								'&amp;', $text);;
1434
+								'&amp;', $text); ;
1435 1435
 		}
1436 1436
 		# Encode remaining <'s
1437 1437
 		$text = str_replace('<', '&lt;', $text);
@@ -1495,9 +1495,9 @@  discard block
 block discarded – undo
1495 1495
 	#	Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
1496 1496
 	#   With some optimizations by Milian Wolff.
1497 1497
 	#
1498
-		$addr = "mailto:" . $addr;
1498
+		$addr = "mailto:".$addr;
1499 1499
 		$chars = preg_split('/(?<!^)(?!$)/', $addr);
1500
-		$seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
1500
+		$seed = (int) abs(crc32($addr) / strlen($addr)); # Deterministic seed.
1501 1501
 
1502 1502
 		foreach ($chars as $key => $char) {
1503 1503
 			$ord = ord($char);
@@ -1533,7 +1533,7 @@  discard block
 block discarded – undo
1533 1533
 				|
1534 1534
 					(?<![`\\\\])
1535 1535
 					`+						# code span marker
1536
-			'.( $this->no_markup ? '' : '
1536
+			'.($this->no_markup ? '' : '
1537 1537
 				|
1538 1538
 					<!--    .*?     -->		# comment
1539 1539
 				|
@@ -1583,7 +1583,7 @@  discard block
 block discarded – undo
1583 1583
 	#
1584 1584
 		switch ($token{0}) {
1585 1585
 			case "\\":
1586
-				return $this->hashPart("&#". ord($token{1}). ";");
1586
+				return $this->hashPart("&#".ord($token{1}).";");
1587 1587
 			case "`":
1588 1588
 				# Search for end marker in remaining text.
1589 1589
 				if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
@@ -1638,7 +1638,7 @@  discard block
 block discarded – undo
1638 1638
 			# Calculate amount of space, insert spaces, insert block.
1639 1639
 			$amount = $this->tab_width -
1640 1640
 				$strlen($line, 'UTF-8') % $this->tab_width;
1641
-			$line .= str_repeat(" ", $amount) . $block;
1641
+			$line .= str_repeat(" ", $amount).$block;
1642 1642
 		}
1643 1643
 		return $line;
1644 1644
 	}
@@ -1802,7 +1802,7 @@  discard block
 block discarded – undo
1802 1802
 		#
1803 1803
 		# Call the HTML-in-Markdown hasher.
1804 1804
 		#
1805
-		list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
1805
+		list($text,) = $this->_hashHTMLBlocks_inMarkdown($text);
1806 1806
 
1807 1807
 		return $text;
1808 1808
 	}
@@ -1874,25 +1874,25 @@  discard block
 block discarded – undo
1874 1874
 				|
1875 1875
 					# Code span marker
1876 1876
 					`+
1877
-				'. ( !$span ? ' # If not in span.
1877
+				'. (!$span ? ' # If not in span.
1878 1878
 				|
1879 1879
 					# Indented code block
1880 1880
 					(?: ^[ ]*\n | ^ | \n[ ]*\n )
1881
-					[ ]{'.($indent+4).'}[^\n]* \n
1881
+					[ ]{'.($indent + 4).'}[^\n]* \n
1882 1882
 					(?>
1883
-						(?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n
1883
+						(?: [ ]{'.($indent + 4).'}[^\n]* | [ ]* ) \n
1884 1884
 					)*
1885 1885
 				|
1886 1886
 					# Fenced code block marker
1887 1887
 					(?> ^ | \n )
1888 1888
 					[ ]{'.($indent).'}~~~+[ ]*\n
1889
-				' : '' ). ' # End (if not is span).
1889
+				' : '').' # End (if not is span).
1890 1890
 				)
1891 1891
 			}xs';
1892 1892
 
1893 1893
 
1894
-		$depth = 0;		# Current depth inside the tag tree.
1895
-		$parsed = "";	# Parsed text that will be returned.
1894
+		$depth = 0; # Current depth inside the tag tree.
1895
+		$parsed = ""; # Parsed text that will be returned.
1896 1896
 
1897 1897
 		#
1898 1898
 		# Loop through every tag until we find the closing tag of the parent
@@ -1913,7 +1913,7 @@  discard block
 block discarded – undo
1913 1913
 			if ($span) {
1914 1914
 				$void = $this->hashPart("", ':');
1915 1915
 				$newline = "$void\n";
1916
-				$parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
1916
+				$parts[0] = $void.str_replace("\n", $newline, $parts[0]).$void;
1917 1917
 			}
1918 1918
 
1919 1919
 			$parsed .= $parts[0]; # Text before current tag.
@@ -1938,7 +1938,7 @@  discard block
 block discarded – undo
1938 1938
 					$text, $matches))
1939 1939
 				{
1940 1940
 					# End marker found: pass text unchanged until marker.
1941
-					$parsed .= $tag . $matches[0];
1941
+					$parsed .= $tag.$matches[0];
1942 1942
 					$text = substr($text, strlen($matches[0]));
1943 1943
 				}
1944 1944
 				else {
@@ -1964,7 +1964,7 @@  discard block
 block discarded – undo
1964 1964
 					$matches))
1965 1965
 				{
1966 1966
 					# End marker found: pass text unchanged until marker.
1967
-					$parsed .= $tag . $matches[0];
1967
+					$parsed .= $tag.$matches[0];
1968 1968
 					$text = substr($text, strlen($matches[0]));
1969 1969
 				}
1970 1970
 				else {
@@ -1978,14 +1978,14 @@  discard block
 block discarded – undo
1978 1978
 			#               used as a block tag (tag is alone on it's line).
1979 1979
 			#
1980 1980
 			else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) ||
1981
-				(	preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) &&
1981
+				(preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) &&
1982 1982
 					preg_match($newline_before_re, $parsed) &&
1983
-					preg_match($newline_after_re, $text)	)
1983
+					preg_match($newline_after_re, $text))
1984 1984
 				)
1985 1985
 			{
1986 1986
 				# Need to parse tag and following text using the HTML parser.
1987 1987
 				list($block_text, $text) =
1988
-					$this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
1988
+					$this->_hashHTMLBlocks_inHTML($tag.$text, "hashBlock", true);
1989 1989
 
1990 1990
 				# Make sure it stays outside of any paragraph by adding newlines.
1991 1991
 				$parsed .= "\n\n$block_text\n\n";
@@ -2000,7 +2000,7 @@  discard block
 block discarded – undo
2000 2000
 				# Need to parse tag and following text using the HTML parser.
2001 2001
 				# (don't check for markdown attribute)
2002 2002
 				list($block_text, $text) =
2003
-					$this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
2003
+					$this->_hashHTMLBlocks_inHTML($tag.$text, "hashClean", false);
2004 2004
 
2005 2005
 				$parsed .= $block_text;
2006 2006
 			}
@@ -2015,14 +2015,14 @@  discard block
 block discarded – undo
2015 2015
 				# Increase/decrease nested tag count.
2016 2016
 				#
2017 2017
 				if ($tag{1} == '/')						$depth--;
2018
-				else if ($tag{strlen($tag)-2} != '/')	$depth++;
2018
+				else if ($tag{strlen($tag) - 2} != '/')	$depth++;
2019 2019
 
2020 2020
 				if ($depth < 0) {
2021 2021
 					#
2022 2022
 					# Going out of parent element. Clean up and break so we
2023 2023
 					# return to the calling function.
2024 2024
 					#
2025
-					$text = $tag . $text;
2025
+					$text = $tag.$text;
2026 2026
 					break;
2027 2027
 				}
2028 2028
 
@@ -2087,11 +2087,11 @@  discard block
 block discarded – undo
2087 2087
 				)
2088 2088
 			}xs';
2089 2089
 
2090
-		$original_text = $text;		# Save original text in case of faliure.
2090
+		$original_text = $text; # Save original text in case of faliure.
2091 2091
 
2092
-		$depth		= 0;	# Current depth inside the tag tree.
2093
-		$block_text	= "";	# Temporary text holder for current text.
2094
-		$parsed		= "";	# Parsed text that will be returned.
2092
+		$depth = 0; # Current depth inside the tag tree.
2093
+		$block_text = ""; # Temporary text holder for current text.
2094
+		$parsed = ""; # Parsed text that will be returned.
2095 2095
 
2096 2096
 		#
2097 2097
 		# Get the name of the starting tag.
@@ -2143,7 +2143,7 @@  discard block
 block discarded – undo
2143 2143
 				#
2144 2144
 				if (preg_match('{^</?'.$base_tag_name_re.'\b}', $tag)) {
2145 2145
 					if ($tag{1} == '/')						$depth--;
2146
-					else if ($tag{strlen($tag)-2} != '/')	$depth++;
2146
+					else if ($tag{strlen($tag) - 2} != '/')	$depth++;
2147 2147
 				}
2148 2148
 
2149 2149
 				#
@@ -2151,13 +2151,13 @@  discard block
 block discarded – undo
2151 2151
 				#
2152 2152
 				if ($md_attr &&
2153 2153
 					preg_match($markdown_attr_re, $tag, $attr_m) &&
2154
-					preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
2154
+					preg_match('/^1|block|span$/', $attr_m[2].$attr_m[3]))
2155 2155
 				{
2156 2156
 					# Remove `markdown` attribute from opening tag.
2157 2157
 					$tag = preg_replace($markdown_attr_re, '', $tag);
2158 2158
 
2159 2159
 					# Check if text inside this tag must be parsed in span mode.
2160
-					$this->mode = $attr_m[2] . $attr_m[3];
2160
+					$this->mode = $attr_m[2].$attr_m[3];
2161 2161
 					$span_mode = $this->mode == 'span' || $this->mode != 'block' &&
2162 2162
 						preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag);
2163 2163
 
@@ -2268,15 +2268,15 @@  discard block
 block discarded – undo
2268 2268
 		if ($matches[3] == '-' && preg_match('{^- }', $matches[1]))
2269 2269
 			return $matches[0];
2270 2270
 		$level = $matches[3]{0} == '=' ? 1 : 2;
2271
-		$attr  = $this->_doHeaders_attr($id =& $matches[2]);
2271
+		$attr  = $this->_doHeaders_attr($id = & $matches[2]);
2272 2272
 		$block = "<h$level$attr>".$this->runSpanGamut($matches[1])."</h$level>";
2273
-		return "\n" . $this->hashBlock($block) . "\n\n";
2273
+		return "\n".$this->hashBlock($block)."\n\n";
2274 2274
 	}
2275 2275
 	function _doHeaders_callback_atx($matches) {
2276 2276
 		$level = strlen($matches[1]);
2277
-		$attr  = $this->_doHeaders_attr($id =& $matches[3]);
2277
+		$attr  = $this->_doHeaders_attr($id = & $matches[3]);
2278 2278
 		$block = "<h$level$attr>".$this->runSpanGamut($matches[2])."</h$level>";
2279
-		return "\n" . $this->hashBlock($block) . "\n\n";
2279
+		return "\n".$this->hashBlock($block)."\n\n";
2280 2280
 	}
2281 2281
 
2282 2282
 
@@ -2342,8 +2342,8 @@  discard block
 block discarded – undo
2342 2342
 		return $text;
2343 2343
 	}
2344 2344
 	function _doTable_leadingPipe_callback($matches) {
2345
-		$head		= $matches[1];
2346
-		$underline	= $matches[2];
2345
+		$head = $matches[1];
2346
+		$underline = $matches[2];
2347 2347
 		$content	= $matches[3];
2348 2348
 
2349 2349
 		# Remove leading pipe for each row.
@@ -2352,17 +2352,17 @@  discard block
 block discarded – undo
2352 2352
 		return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
2353 2353
 	}
2354 2354
 	function _doTable_callback($matches) {
2355
-		$head		= $matches[1];
2356
-		$underline	= $matches[2];
2357
-		$content	= $matches[3];
2355
+		$head = $matches[1];
2356
+		$underline = $matches[2];
2357
+		$content = $matches[3];
2358 2358
 
2359 2359
 		# Remove any tailing pipes for each line.
2360
-		$head		= preg_replace('/[|] *$/m', '', $head);
2361
-		$underline	= preg_replace('/[|] *$/m', '', $underline);
2362
-		$content	= preg_replace('/[|] *$/m', '', $content);
2360
+		$head = preg_replace('/[|] *$/m', '', $head);
2361
+		$underline = preg_replace('/[|] *$/m', '', $underline);
2362
+		$content = preg_replace('/[|] *$/m', '', $content);
2363 2363
 
2364 2364
 		# Reading alignement from header underline.
2365
-		$separators	= preg_split('/ *[|] */', $underline);
2365
+		$separators = preg_split('/ *[|] */', $underline);
2366 2366
 		foreach ($separators as $n => $s) {
2367 2367
 			if (preg_match('/^ *-+: *$/', $s))		$attr[$n] = ' align="right"';
2368 2368
 			else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"';
@@ -2372,9 +2372,9 @@  discard block
 block discarded – undo
2372 2372
 
2373 2373
 		# Parsing span elements, including code spans, character escapes,
2374 2374
 		# and inline HTML tags, so that pipes inside those gets ignored.
2375
-		$head		= $this->parseSpan($head);
2376
-		$headers	= preg_split('/ *[|] */', $head);
2377
-		$col_count	= count($headers);
2375
+		$head = $this->parseSpan($head);
2376
+		$headers = preg_split('/ *[|] */', $head);
2377
+		$col_count = count($headers);
2378 2378
 
2379 2379
 		# Write column headers.
2380 2380
 		$text = "<table>\n";
@@ -2406,7 +2406,7 @@  discard block
 block discarded – undo
2406 2406
 		$text .= "</tbody>\n";
2407 2407
 		$text .= "</table>";
2408 2408
 
2409
-		return $this->hashBlock($text) . "\n";
2409
+		return $this->hashBlock($text)."\n";
2410 2410
 	}
2411 2411
 
2412 2412
 
@@ -2459,8 +2459,8 @@  discard block
 block discarded – undo
2459 2459
 		# Turn double returns into triple returns, so that we can make a
2460 2460
 		# paragraph for the last item in a list, if necessary:
2461 2461
 		$result = trim($this->processDefListItems($list));
2462
-		$result = "<dl>\n" . $result . "\n</dl>";
2463
-		return $this->hashBlock($result) . "\n\n";
2462
+		$result = "<dl>\n".$result."\n</dl>";
2463
+		return $this->hashBlock($result)."\n\n";
2464 2464
 	}
2465 2465
 
2466 2466
 
@@ -2512,27 +2512,27 @@  discard block
 block discarded – undo
2512 2512
 		$text = '';
2513 2513
 		foreach ($terms as $term) {
2514 2514
 			$term = $this->runSpanGamut(trim($term));
2515
-			$text .= "\n<dt>" . $term . "</dt>";
2515
+			$text .= "\n<dt>".$term."</dt>";
2516 2516
 		}
2517
-		return $text . "\n";
2517
+		return $text."\n";
2518 2518
 	}
2519 2519
 	function _processDefListItems_callback_dd($matches) {
2520 2520
 		$leading_line	= $matches[1];
2521 2521
 		$marker_space	= $matches[2];
2522
-		$def			= $matches[3];
2522
+		$def = $matches[3];
2523 2523
 
2524 2524
 		if ($leading_line || preg_match('/\n{2,}/', $def)) {
2525 2525
 			# Replace marker with the appropriate whitespace indentation
2526
-			$def = str_repeat(' ', strlen($marker_space)) . $def;
2527
-			$def = $this->runBlockGamut($this->outdent($def . "\n\n"));
2528
-			$def = "\n". $def ."\n";
2526
+			$def = str_repeat(' ', strlen($marker_space)).$def;
2527
+			$def = $this->runBlockGamut($this->outdent($def."\n\n"));
2528
+			$def = "\n".$def."\n";
2529 2529
 		}
2530 2530
 		else {
2531 2531
 			$def = rtrim($def);
2532 2532
 			$def = $this->runSpanGamut($this->outdent($def));
2533 2533
 		}
2534 2534
 
2535
-		return "\n<dd>" . $def . "</dd>\n";
2535
+		return "\n<dd>".$def."</dd>\n";
2536 2536
 	}
2537 2537
 
2538 2538
 
@@ -2670,7 +2670,7 @@  discard block
 block discarded – undo
2670 2670
 		return $text;
2671 2671
 	}
2672 2672
 	function _stripFootnotes_callback($matches) {
2673
-		$note_id = $this->fn_id_prefix . $matches[1];
2673
+		$note_id = $this->fn_id_prefix.$matches[1];
2674 2674
 		$this->footnotes[$note_id] = $this->outdent($matches[2]);
2675 2675
 		return ''; # String that will replace the block
2676 2676
 	}
@@ -2698,7 +2698,7 @@  discard block
 block discarded – undo
2698 2698
 		if (!empty($this->footnotes_ordered)) {
2699 2699
 			$text .= "\n\n";
2700 2700
 			$text .= "<div class=\"footnotes\">\n";
2701
-			$text .= "<hr". $this->empty_element_suffix ."\n";
2701
+			$text .= "<hr".$this->empty_element_suffix."\n";
2702 2702
 			$text .= "<ol>\n\n";
2703 2703
 
2704 2704
 			$attr = " rev=\"footnote\"";
@@ -2730,13 +2730,13 @@  discard block
 block discarded – undo
2730 2730
 				# Add backlink to last paragraph; create new paragraph if needed.
2731 2731
 				$backlink = "<a href=\"#fnref:$note_id\"$attr>&#8617;</a>";
2732 2732
 				if (preg_match('{</p>$}', $footnote)) {
2733
-					$footnote = substr($footnote, 0, -4) . "&#160;$backlink</p>";
2733
+					$footnote = substr($footnote, 0, -4)."&#160;$backlink</p>";
2734 2734
 				} else {
2735 2735
 					$footnote .= "\n\n<p>$backlink</p>";
2736 2736
 				}
2737 2737
 
2738 2738
 				$text .= "<li id=\"fn:$note_id\">\n";
2739
-				$text .= $footnote . "\n";
2739
+				$text .= $footnote."\n";
2740 2740
 				$text .= "</li>\n\n";
2741 2741
 			}
2742 2742
 
@@ -2746,7 +2746,7 @@  discard block
 block discarded – undo
2746 2746
 		return $text;
2747 2747
 	}
2748 2748
 	function _appendFootnotes_callback($matches) {
2749
-		$node_id = $this->fn_id_prefix . $matches[1];
2749
+		$node_id = $this->fn_id_prefix.$matches[1];
2750 2750
 
2751 2751
 		# Create footnote marker only if it has a corresponding footnote *and*
2752 2752
 		# the footnote hasn't been used by another marker.
Please login to merge, or discard this patch.
Braces   +87 added lines, -57 removed lines patch added patch discarded remove patch
@@ -193,8 +193,12 @@  discard block
 block discarded – undo
193 193
 	# Fake Textile class. It calls Markdown instead.
194 194
 	class Textile {
195 195
 		function TextileThis($text, $lite='', $encode='') {
196
-			if ($lite == '' && $encode == '')    $text = Markdown($text);
197
-			if (function_exists('SmartyPants'))  $text = SmartyPants($text);
196
+			if ($lite == '' && $encode == '') {
197
+			    $text = Markdown($text);
198
+			}
199
+			if (function_exists('SmartyPants')) {
200
+			    $text = SmartyPants($text);
201
+			}
198 202
 			return $text;
199 203
 		}
200 204
 		# Fake restricted version: restrictions are not supported for now.
@@ -387,7 +391,9 @@  discard block
 block discarded – undo
387 391
 
388 392
 
389 393
 	function hashHTMLBlocks($text) {
390
-		if ($this->no_markup)  return $text;
394
+		if ($this->no_markup) {
395
+		    return $text;
396
+		}
391 397
 
392 398
 		$less_than_tab = $this->tab_width - 1;
393 399
 
@@ -673,7 +679,9 @@  discard block
 block discarded – undo
673 679
 	#
674 680
 	# Turn Markdown link shortcuts into XHTML <a> tags.
675 681
 	#
676
-		if ($this->in_anchor) return $text;
682
+		if ($this->in_anchor) {
683
+		    return $text;
684
+		}
677 685
 		$this->in_anchor = true;
678 686
 
679 687
 		#
@@ -767,8 +775,7 @@  discard block
 block discarded – undo
767 775
 			$link_text = $this->runSpanGamut($link_text);
768 776
 			$result .= ">$link_text</a>";
769 777
 			$result = $this->hashPart($result);
770
-		}
771
-		else {
778
+		} else {
772 779
 			$result = $whole_match;
773 780
 		}
774 781
 		return $result;
@@ -869,8 +876,7 @@  discard block
 block discarded – undo
869 876
 			}
870 877
 			$result .= $this->empty_element_suffix;
871 878
 			$result = $this->hashPart($result);
872
-		}
873
-		else {
879
+		} else {
874 880
 			# If there's no such link ID, leave intact:
875 881
 			$result = $whole_match;
876 882
 		}
@@ -928,8 +934,9 @@  discard block
 block discarded – undo
928 934
 	}
929 935
 	function _doHeaders_callback_setext($matches) {
930 936
 		# Terrible hack to check we haven't found an empty list item.
931
-		if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
932
-			return $matches[0];
937
+		if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1])) {
938
+					return $matches[0];
939
+		}
933 940
 
934 941
 		$level = $matches[2]{0} == '=' ? 1 : 2;
935 942
 		$block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
@@ -996,8 +1003,7 @@  discard block
 block discarded – undo
996 1003
 						'.$whole_list_re.'
997 1004
 					}mx',
998 1005
 					array(&$this, '_doLists_callback'), $text);
999
-			}
1000
-			else {
1006
+			} else {
1001 1007
 				$text = preg_replace_callback('{
1002 1008
 						(?:(?<=\n)\n|\A\n?) # Must eat the newline
1003 1009
 						'.$whole_list_re.'
@@ -1087,8 +1093,7 @@  discard block
 block discarded – undo
1087 1093
 			# Replace marker with the appropriate whitespace indentation
1088 1094
 			$item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
1089 1095
 			$item = $this->runBlockGamut($this->outdent($item)."\n");
1090
-		}
1091
-		else {
1096
+		} else {
1092 1097
 			# Recursion for sub-lists:
1093 1098
 			$item = $this->doLists($this->outdent($item));
1094 1099
 			$item = preg_replace('/\n+$/', '', $item);
@@ -1358,8 +1363,7 @@  discard block
 block discarded – undo
1358 1363
 				$value = preg_replace('/^([ ]*)/', "<p>", $value);
1359 1364
 				$value .= "</p>";
1360 1365
 				$grafs[$key] = $this->unhash($value);
1361
-			}
1362
-			else {
1366
+			} else {
1363 1367
 				# Is a block.
1364 1368
 				# Modify elements of @grafs in-place...
1365 1369
 				$graf = $value;
@@ -1507,8 +1511,11 @@  discard block
 block discarded – undo
1507 1511
 				# roughly 10% raw, 45% hex, 45% dec
1508 1512
 				# '@' *must* be encoded. I insist.
1509 1513
 				if ($r > 90 && $char != '@') /* do nothing */;
1510
-				else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
1511
-				else              $chars[$key] = '&#'.$ord.';';
1514
+				else if ($r < 45) {
1515
+				    $chars[$key] = '&#x'.dechex($ord).';';
1516
+				} else {
1517
+				    $chars[$key] = '&#'.$ord.';';
1518
+				}
1512 1519
 			}
1513 1520
 		}
1514 1521
 
@@ -1566,8 +1573,7 @@  discard block
 block discarded – undo
1566 1573
 			if (isset($parts[1])) {
1567 1574
 				$output .= $this->handleSpanToken($parts[1], $parts[2]);
1568 1575
 				$str = $parts[2];
1569
-			}
1570
-			else {
1576
+			} else {
1571 1577
 				break;
1572 1578
 			}
1573 1579
 		}
@@ -1649,7 +1655,9 @@  discard block
 block discarded – undo
1649 1655
 	# function that will loosely count the number of UTF-8 characters with a
1650 1656
 	# regular expression.
1651 1657
 	#
1652
-		if (function_exists($this->utf8_strlen)) return;
1658
+		if (function_exists($this->utf8_strlen)) {
1659
+		    return;
1660
+		}
1653 1661
 		$this->utf8_strlen = create_function('$text', 'return preg_match_all(
1654 1662
 			"/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/",
1655 1663
 			$text, $m);');
@@ -1744,8 +1752,9 @@  discard block
 block discarded – undo
1744 1752
 		$this->footnote_counter = 1;
1745 1753
 
1746 1754
 		foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
1747
-			if ($this->abbr_word_re)
1748
-				$this->abbr_word_re .= '|';
1755
+			if ($this->abbr_word_re) {
1756
+							$this->abbr_word_re .= '|';
1757
+			}
1749 1758
 			$this->abbr_word_re .= preg_quote($abbr_word);
1750 1759
 			$this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
1751 1760
 		}
@@ -1834,7 +1843,9 @@  discard block
 block discarded – undo
1834 1843
 	#
1835 1844
 	# Returns an array of that form: ( processed text , remaining text )
1836 1845
 	#
1837
-		if ($text === '') return array('', '');
1846
+		if ($text === '') {
1847
+		    return array('', '');
1848
+		}
1838 1849
 
1839 1850
 		# Regex to check for the presense of newlines around a block tag.
1840 1851
 		$newline_before_re = '/(?:^\n?|\n\n)*$/';
@@ -1940,8 +1951,7 @@  discard block
 block discarded – undo
1940 1951
 					# End marker found: pass text unchanged until marker.
1941 1952
 					$parsed .= $tag . $matches[0];
1942 1953
 					$text = substr($text, strlen($matches[0]));
1943
-				}
1944
-				else {
1954
+				} else {
1945 1955
 					# Unmatched marker: just skip it.
1946 1956
 					$parsed .= $tag;
1947 1957
 				}
@@ -1966,8 +1976,7 @@  discard block
 block discarded – undo
1966 1976
 					# End marker found: pass text unchanged until marker.
1967 1977
 					$parsed .= $tag . $matches[0];
1968 1978
 					$text = substr($text, strlen($matches[0]));
1969
-				}
1970
-				else {
1979
+				} else {
1971 1980
 					# No end marker: just skip it.
1972 1981
 					$parsed .= $tag;
1973 1982
 				}
@@ -2014,8 +2023,11 @@  discard block
 block discarded – undo
2014 2023
 				#
2015 2024
 				# Increase/decrease nested tag count.
2016 2025
 				#
2017
-				if ($tag{1} == '/')						$depth--;
2018
-				else if ($tag{strlen($tag)-2} != '/')	$depth++;
2026
+				if ($tag{1} == '/') {
2027
+				    $depth--;
2028
+				} else if ($tag{strlen($tag)-2} != '/') {
2029
+				    $depth++;
2030
+				}
2019 2031
 
2020 2032
 				if ($depth < 0) {
2021 2033
 					#
@@ -2027,8 +2039,7 @@  discard block
 block discarded – undo
2027 2039
 				}
2028 2040
 
2029 2041
 				$parsed .= $tag;
2030
-			}
2031
-			else {
2042
+			} else {
2032 2043
 				$parsed .= $tag;
2033 2044
 			}
2034 2045
 		} while ($depth >= 0);
@@ -2046,7 +2057,9 @@  discard block
 block discarded – undo
2046 2057
 	#
2047 2058
 	# Returns an array of that form: ( processed text , remaining text )
2048 2059
 	#
2049
-		if ($text === '') return array('', '');
2060
+		if ($text === '') {
2061
+		    return array('', '');
2062
+		}
2050 2063
 
2051 2064
 		# Regex to match `markdown` attribute inside of a tag.
2052 2065
 		$markdown_attr_re = '
@@ -2097,8 +2110,9 @@  discard block
 block discarded – undo
2097 2110
 		# Get the name of the starting tag.
2098 2111
 		# (This pattern makes $base_tag_name_re safe without quoting.)
2099 2112
 		#
2100
-		if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
2101
-			$base_tag_name_re = $matches[1];
2113
+		if (preg_match('/^<([\w:$]*)\b/', $text, $matches)) {
2114
+					$base_tag_name_re = $matches[1];
2115
+		}
2102 2116
 
2103 2117
 		#
2104 2118
 		# Loop through every tag until we find the corresponding closing tag.
@@ -2135,15 +2149,17 @@  discard block
 block discarded – undo
2135 2149
 			{
2136 2150
 				# Just add the tag to the block as if it was text.
2137 2151
 				$block_text .= $tag;
2138
-			}
2139
-			else {
2152
+			} else {
2140 2153
 				#
2141 2154
 				# Increase/decrease nested tag count. Only do so if
2142 2155
 				# the tag's name match base tag's.
2143 2156
 				#
2144 2157
 				if (preg_match('{^</?'.$base_tag_name_re.'\b}', $tag)) {
2145
-					if ($tag{1} == '/')						$depth--;
2146
-					else if ($tag{strlen($tag)-2} != '/')	$depth++;
2158
+					if ($tag{1} == '/') {
2159
+					    $depth--;
2160
+					} else if ($tag{strlen($tag)-2} != '/') {
2161
+					    $depth++;
2162
+					}
2147 2163
 				}
2148 2164
 
2149 2165
 				#
@@ -2190,13 +2206,17 @@  discard block
 block discarded – undo
2190 2206
 					}
2191 2207
 
2192 2208
 					# Append tag content to parsed text.
2193
-					if (!$span_mode)	$parsed .= "\n\n$block_text\n\n";
2194
-					else				$parsed .= "$block_text";
2209
+					if (!$span_mode) {
2210
+					    $parsed .= "\n\n$block_text\n\n";
2211
+					} else {
2212
+					    $parsed .= "$block_text";
2213
+					}
2195 2214
 
2196 2215
 					# Start over a new block.
2197 2216
 					$block_text = "";
2217
+				} else {
2218
+				    $block_text .= $tag;
2198 2219
 				}
2199
-				else $block_text .= $tag;
2200 2220
 			}
2201 2221
 
2202 2222
 		} while ($depth > 0);
@@ -2261,12 +2281,15 @@  discard block
 block discarded – undo
2261 2281
 		return $text;
2262 2282
 	}
2263 2283
 	function _doHeaders_attr($attr) {
2264
-		if (empty($attr))  return "";
2284
+		if (empty($attr)) {
2285
+		    return "";
2286
+		}
2265 2287
 		return " id=\"$attr\"";
2266 2288
 	}
2267 2289
 	function _doHeaders_callback_setext($matches) {
2268
-		if ($matches[3] == '-' && preg_match('{^- }', $matches[1]))
2269
-			return $matches[0];
2290
+		if ($matches[3] == '-' && preg_match('{^- }', $matches[1])) {
2291
+					return $matches[0];
2292
+		}
2270 2293
 		$level = $matches[3]{0} == '=' ? 1 : 2;
2271 2294
 		$attr  = $this->_doHeaders_attr($id =& $matches[2]);
2272 2295
 		$block = "<h$level$attr>".$this->runSpanGamut($matches[1])."</h$level>";
@@ -2364,10 +2387,15 @@  discard block
 block discarded – undo
2364 2387
 		# Reading alignement from header underline.
2365 2388
 		$separators	= preg_split('/ *[|] */', $underline);
2366 2389
 		foreach ($separators as $n => $s) {
2367
-			if (preg_match('/^ *-+: *$/', $s))		$attr[$n] = ' align="right"';
2368
-			else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"';
2369
-			else if (preg_match('/^ *:-+ *$/', $s))	$attr[$n] = ' align="left"';
2370
-			else									$attr[$n] = '';
2390
+			if (preg_match('/^ *-+: *$/', $s)) {
2391
+			    $attr[$n] = ' align="right"';
2392
+			} else if (preg_match('/^ *:-+: *$/', $s)) {
2393
+			    $attr[$n] = ' align="center"';
2394
+			} else if (preg_match('/^ *:-+ *$/', $s)) {
2395
+			    $attr[$n] = ' align="left"';
2396
+			} else {
2397
+			    $attr[$n] = '';
2398
+			}
2371 2399
 		}
2372 2400
 
2373 2401
 		# Parsing span elements, including code spans, character escapes,
@@ -2380,8 +2408,9 @@  discard block
 block discarded – undo
2380 2408
 		$text = "<table>\n";
2381 2409
 		$text .= "<thead>\n";
2382 2410
 		$text .= "<tr>\n";
2383
-		foreach ($headers as $n => $header)
2384
-			$text .= "  <th$attr[$n]>".$this->runSpanGamut(trim($header))."</th>\n";
2411
+		foreach ($headers as $n => $header) {
2412
+					$text .= "  <th$attr[$n]>".$this->runSpanGamut(trim($header))."</th>\n";
2413
+		}
2385 2414
 		$text .= "</tr>\n";
2386 2415
 		$text .= "</thead>\n";
2387 2416
 
@@ -2399,8 +2428,9 @@  discard block
 block discarded – undo
2399 2428
 			$row_cells = array_pad($row_cells, $col_count, '');
2400 2429
 
2401 2430
 			$text .= "<tr>\n";
2402
-			foreach ($row_cells as $n => $cell)
2403
-				$text .= "  <td$attr[$n]>".$this->runSpanGamut(trim($cell))."</td>\n";
2431
+			foreach ($row_cells as $n => $cell) {
2432
+							$text .= "  <td$attr[$n]>".$this->runSpanGamut(trim($cell))."</td>\n";
2433
+			}
2404 2434
 			$text .= "</tr>\n";
2405 2435
 		}
2406 2436
 		$text .= "</tbody>\n";
@@ -2526,8 +2556,7 @@  discard block
 block discarded – undo
2526 2556
 			$def = str_repeat(' ', strlen($marker_space)) . $def;
2527 2557
 			$def = $this->runBlockGamut($this->outdent($def . "\n\n"));
2528 2558
 			$def = "\n". $def ."\n";
2529
-		}
2530
-		else {
2559
+		} else {
2531 2560
 			$def = rtrim($def);
2532 2561
 			$def = $this->runSpanGamut($this->outdent($def));
2533 2562
 		}
@@ -2801,8 +2830,9 @@  discard block
 block discarded – undo
2801 2830
 	function _stripAbbreviations_callback($matches) {
2802 2831
 		$abbr_word = $matches[1];
2803 2832
 		$abbr_desc = $matches[2];
2804
-		if ($this->abbr_word_re)
2805
-			$this->abbr_word_re .= '|';
2833
+		if ($this->abbr_word_re) {
2834
+					$this->abbr_word_re .= '|';
2835
+		}
2806 2836
 		$this->abbr_word_re .= preg_quote($abbr_word);
2807 2837
 		$this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
2808 2838
 		return ''; # String that will replace the block
Please login to merge, or discard this patch.
app/Plugin/Search/Model/Behavior/SearchableBehavior.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -135,7 +135,7 @@
 block discarded – undo
135 135
  * @param Model $Model
136 136
  * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
137 137
  * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
138
- * @return array Array of records
138
+ * @return string Array of records
139 139
  * @link http://book.cakephp.org/view/1018/find
140 140
  */
141 141
 	public function getQuery(Model $Model, $type = 'first', $query = array()) {
Please login to merge, or discard this patch.
Indentation   +350 added lines, -350 removed lines patch added patch discarded remove patch
@@ -26,13 +26,13 @@  discard block
 block discarded – undo
26 26
  *
27 27
  * @var array
28 28
  */
29
-	protected $_defaults = array(
30
-		'wildcardAny' => '*', //on windows/unix/mac/google/... thats the default one
31
-		'wildcardOne' => '?', //on windows/unix/mac thats the default one
32
-		'like' => array('before' => true, 'after' => true),
33
-		'connectorAnd' => null,
34
-		'connectorOr' => null,
35
-	);
29
+    protected $_defaults = array(
30
+        'wildcardAny' => '*', //on windows/unix/mac/google/... thats the default one
31
+        'wildcardOne' => '?', //on windows/unix/mac thats the default one
32
+        'like' => array('before' => true, 'after' => true),
33
+        'connectorAnd' => null,
34
+        'connectorOr' => null,
35
+    );
36 36
 
37 37
 /**
38 38
  * Configuration of model
@@ -41,24 +41,24 @@  discard block
 block discarded – undo
41 41
  * @param array $config
42 42
  * @return void
43 43
  */
44
-	public function setup(Model $Model, $config = array()) {
45
-		$this->_defaults = array_merge($this->_defaults, (array)Configure::read('Search.Searchable'));
46
-		$this->settings[$Model->alias] = array_merge($this->_defaults, $config);
47
-		if (empty($Model->filterArgs)) {
48
-			return;
49
-		}
50
-		foreach ($Model->filterArgs as $key => $val) {
51
-			if (!isset($val['name'])) {
52
-				$Model->filterArgs[$key]['name'] = $key;
53
-			}
54
-			if (!isset($val['field'])) {
55
-				$Model->filterArgs[$key]['field'] = $Model->filterArgs[$key]['name'];
56
-			}
57
-			if (!isset($val['type'])) {
58
-				$Model->filterArgs[$key]['type'] = 'value';
59
-			}
60
-		}
61
-	}
44
+    public function setup(Model $Model, $config = array()) {
45
+        $this->_defaults = array_merge($this->_defaults, (array)Configure::read('Search.Searchable'));
46
+        $this->settings[$Model->alias] = array_merge($this->_defaults, $config);
47
+        if (empty($Model->filterArgs)) {
48
+            return;
49
+        }
50
+        foreach ($Model->filterArgs as $key => $val) {
51
+            if (!isset($val['name'])) {
52
+                $Model->filterArgs[$key]['name'] = $key;
53
+            }
54
+            if (!isset($val['field'])) {
55
+                $Model->filterArgs[$key]['field'] = $Model->filterArgs[$key]['name'];
56
+            }
57
+            if (!isset($val['type'])) {
58
+                $Model->filterArgs[$key]['type'] = 'value';
59
+            }
60
+        }
61
+    }
62 62
 
63 63
 /**
64 64
  * parseCriteria
@@ -69,28 +69,28 @@  discard block
 block discarded – undo
69 69
  * @param array $data Criteria of key->value pairs from post/named parameters
70 70
  * @return array Array of conditions that express the conditions needed for the search
71 71
  */
72
-	public function parseCriteria(Model $Model, $data) {
73
-		$conditions = array();
74
-		foreach ($Model->filterArgs as $field) {
75
-			// If this field was not passed and a default value exists, use that instead.
76
-			if (!array_key_exists($field['name'], $data) && array_key_exists('defaultValue', $field)) {
77
-				$data[$field['name']] = $field['defaultValue'];
78
-			}
79
-
80
-			if (in_array($field['type'], array('like'))) {
81
-				$this->_addCondLike($Model, $conditions, $data, $field);
82
-			} elseif (in_array($field['type'], array('value'))) {
83
-				$this->_addCondValue($Model, $conditions, $data, $field);
84
-			} elseif ($field['type'] === 'expression') {
85
-				$this->_addCondExpression($Model, $conditions, $data, $field);
86
-			} elseif ($field['type'] === 'query') {
87
-				$this->_addCondQuery($Model, $conditions, $data, $field);
88
-			} elseif ($field['type'] === 'subquery') {
89
-				$this->_addCondSubquery($Model, $conditions, $data, $field);
90
-			}
91
-		}
92
-		return $conditions;
93
-	}
72
+    public function parseCriteria(Model $Model, $data) {
73
+        $conditions = array();
74
+        foreach ($Model->filterArgs as $field) {
75
+            // If this field was not passed and a default value exists, use that instead.
76
+            if (!array_key_exists($field['name'], $data) && array_key_exists('defaultValue', $field)) {
77
+                $data[$field['name']] = $field['defaultValue'];
78
+            }
79
+
80
+            if (in_array($field['type'], array('like'))) {
81
+                $this->_addCondLike($Model, $conditions, $data, $field);
82
+            } elseif (in_array($field['type'], array('value'))) {
83
+                $this->_addCondValue($Model, $conditions, $data, $field);
84
+            } elseif ($field['type'] === 'expression') {
85
+                $this->_addCondExpression($Model, $conditions, $data, $field);
86
+            } elseif ($field['type'] === 'query') {
87
+                $this->_addCondQuery($Model, $conditions, $data, $field);
88
+            } elseif ($field['type'] === 'subquery') {
89
+                $this->_addCondSubquery($Model, $conditions, $data, $field);
90
+            }
91
+        }
92
+        return $conditions;
93
+    }
94 94
 
95 95
 /**
96 96
  * Validate search
@@ -99,18 +99,18 @@  discard block
 block discarded – undo
99 99
  * @param null $data
100 100
  * @return boolean always true
101 101
  */
102
-	public function validateSearch(Model $Model, $data = null) {
103
-		if (!empty($data)) {
104
-			$Model->set($data);
105
-		}
106
-		$keys = array_keys($Model->data[$Model->alias]);
107
-		foreach ($keys as $key) {
108
-			if (empty($Model->data[$Model->alias][$key])) {
109
-				unset($Model->data[$Model->alias][$key]);
110
-			}
111
-		}
112
-		return true;
113
-	}
102
+    public function validateSearch(Model $Model, $data = null) {
103
+        if (!empty($data)) {
104
+            $Model->set($data);
105
+        }
106
+        $keys = array_keys($Model->data[$Model->alias]);
107
+        foreach ($keys as $key) {
108
+            if (empty($Model->data[$Model->alias][$key])) {
109
+                unset($Model->data[$Model->alias][$key]);
110
+            }
111
+        }
112
+        return true;
113
+    }
114 114
 
115 115
 /**
116 116
  * filter retrieving variables only that present in  Model::filterArgs
@@ -119,15 +119,15 @@  discard block
 block discarded – undo
119 119
  * @param array $vars
120 120
  * @return array, filtered args
121 121
  */
122
-	public function passedArgs(Model $Model, $vars) {
123
-		$result = array();
124
-		foreach ($vars as $var => $val) {
125
-			if (in_array($var, Set::extract($Model->filterArgs, '{n}.name'))) {
126
-				$result[$var] = $val;
127
-			}
128
-		}
129
-		return $result;
130
-	}
122
+    public function passedArgs(Model $Model, $vars) {
123
+        $result = array();
124
+        foreach ($vars as $var => $val) {
125
+            if (in_array($var, Set::extract($Model->filterArgs, '{n}.name'))) {
126
+                $result[$var] = $val;
127
+            }
128
+        }
129
+        return $result;
130
+    }
131 131
 
132 132
 /**
133 133
  * Generates a query string using the same API Model::find() uses, calling the beforeFind process for the model
@@ -138,13 +138,13 @@  discard block
 block discarded – undo
138 138
  * @return array Array of records
139 139
  * @link http://book.cakephp.org/view/1018/find
140 140
  */
141
-	public function getQuery(Model $Model, $type = 'first', $query = array()) {
142
-		$Model->findQueryType = $type;
143
-		$Model->id = $Model->getID();
144
-		$query = $Model->buildQuery($type, $query);
145
-		$this->findQueryType = null;
146
-		return $this->_queryGet($Model, $query);
147
-	}
141
+    public function getQuery(Model $Model, $type = 'first', $query = array()) {
142
+        $Model->findQueryType = $type;
143
+        $Model->id = $Model->getID();
144
+        $query = $Model->buildQuery($type, $query);
145
+        $this->findQueryType = null;
146
+        return $this->_queryGet($Model, $query);
147
+    }
148 148
 
149 149
 /**
150 150
  * Clear all associations
@@ -153,14 +153,14 @@  discard block
 block discarded – undo
153 153
  * @param boolean $reset
154 154
  * @return void
155 155
  */
156
-	public function unbindAllModels(Model $Model, $reset = false) {
157
-		$assocs = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
158
-		$unbind = array();
159
-		foreach ($assocs as $assoc) {
160
-			$unbind[$assoc] = array_keys($Model->{$assoc});
161
-		}
162
-		$Model->unbindModel($unbind, $reset);
163
-	}
156
+    public function unbindAllModels(Model $Model, $reset = false) {
157
+        $assocs = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
158
+        $unbind = array();
159
+        foreach ($assocs as $assoc) {
160
+            $unbind[$assoc] = array_keys($Model->{$assoc});
161
+        }
162
+        $Model->unbindModel($unbind, $reset);
163
+    }
164 164
 
165 165
 /**
166 166
  * For custom queries inside the model
@@ -172,17 +172,17 @@  discard block
 block discarded – undo
172 172
  * @param array $field
173 173
  * @return array of conditions
174 174
  */
175
-	public function condLike(Model $Model, $name, $data, $field = array()) {
176
-		$conditions = array();
177
-		$field['name'] = $name;
178
-		if (!is_array($data)) {
179
-			$data = array($name => $data);
180
-		}
181
-		if (!isset($field['field'])) {
182
-			$field['field'] = $field['name'];
183
-		}
184
-		return $this->_addCondLike($Model, $conditions, $data, $field);
185
-	}
175
+    public function condLike(Model $Model, $name, $data, $field = array()) {
176
+        $conditions = array();
177
+        $field['name'] = $name;
178
+        if (!is_array($data)) {
179
+            $data = array($name => $data);
180
+        }
181
+        if (!isset($field['field'])) {
182
+            $field['field'] = $field['name'];
183
+        }
184
+        return $this->_addCondLike($Model, $conditions, $data, $field);
185
+    }
186 186
 
187 187
 /**
188 188
  * Replace substitutions with original wildcards
@@ -193,29 +193,29 @@  discard block
 block discarded – undo
193 193
  * @param array $options
194 194
  * @return string queryLikeString
195 195
  */
196
-	public function formatLike(Model $Model, $data, $options = array()) {
197
-		$options = array_merge($this->settings[$Model->alias], $options);
198
-		$from = $to = $substFrom = $substTo = array();
199
-		if ($options['wildcardAny'] !== '%') {
200
-			$from[] = '%';
201
-			$to[] = '\%';
202
-			$substFrom[] = $options['wildcardAny'];
203
-			$substTo[] = '%';
204
-		}
205
-		if ($options['wildcardOne'] !== '_') {
206
-			$from[] = '_';
207
-			$to[] = '\_';
208
-			$substFrom[] = $options['wildcardOne'];
209
-			$substTo[] = '_';
210
-		}
211
-		if (!empty($from)) {
212
-			// escape first
213
-			$data = str_replace($from, $to, $data);
214
-			// replace wildcards
215
-			$data = str_replace($substFrom, $substTo, $data);
216
-		}
217
-		return $data;
218
-	}
196
+    public function formatLike(Model $Model, $data, $options = array()) {
197
+        $options = array_merge($this->settings[$Model->alias], $options);
198
+        $from = $to = $substFrom = $substTo = array();
199
+        if ($options['wildcardAny'] !== '%') {
200
+            $from[] = '%';
201
+            $to[] = '\%';
202
+            $substFrom[] = $options['wildcardAny'];
203
+            $substTo[] = '%';
204
+        }
205
+        if ($options['wildcardOne'] !== '_') {
206
+            $from[] = '_';
207
+            $to[] = '\_';
208
+            $substFrom[] = $options['wildcardOne'];
209
+            $substTo[] = '_';
210
+        }
211
+        if (!empty($from)) {
212
+            // escape first
213
+            $data = str_replace($from, $to, $data);
214
+            // replace wildcards
215
+            $data = str_replace($substFrom, $substTo, $data);
216
+        }
217
+        return $data;
218
+    }
219 219
 
220 220
 /**
221 221
  * Return the current chars for querying LIKE statements on this model
@@ -224,10 +224,10 @@  discard block
 block discarded – undo
224 224
  * @param array $options
225 225
  * @return array, [one=>..., any=>...]
226 226
  */
227
-	public function getWildcards(Model $Model, $options = array()) {
228
-		$options = array_merge($this->settings[$Model->alias], $options);
229
-		return array('any' => $options['wildcardAny'], 'one' => $options['wildcardOne']);
230
-	}
227
+    public function getWildcards(Model $Model, $options = array()) {
228
+        $options = array_merge($this->settings[$Model->alias], $options);
229
+        return array('any' => $options['wildcardAny'], 'one' => $options['wildcardOne']);
230
+    }
231 231
 
232 232
 /**
233 233
  * Add Conditions based on fuzzy comparison
@@ -238,72 +238,72 @@  discard block
 block discarded – undo
238 238
  * @param array $field Field definition information
239 239
  * @return array Conditions
240 240
  */
241
-	protected function _addCondLike(Model $Model, &$conditions, $data, $field) {
242
-		if (!is_array($this->settings[$Model->alias]['like'])) {
243
-			$this->settings[$Model->alias]['like'] = array('before' => $this->settings[$Model->alias]['like'], 'after' => $this->settings[$Model->alias]['like']);
244
-		}
245
-		$field = array_merge($this->settings[$Model->alias]['like'], $field);
246
-		if (empty($data[$field['name']])) {
247
-			return $conditions;
248
-		}
249
-		$fieldNames = (array)$field['field'];
250
-
251
-		$cond = array();
252
-		foreach ($fieldNames as $fieldName) {
253
-			if (strpos($fieldName, '.') === false) {
254
-				$fieldName = $Model->alias . '.' . $fieldName;
255
-			}
256
-
257
-			if ($field['before'] === true) {
258
-				$field['before'] = '%';
259
-			}
260
-			if ($field['after'] === true) {
261
-				$field['after'] = '%';
262
-			}
263
-			//if both before and after are false, LIKE allows custom placeholders, % and _ are always treated as normal chars
264
-			$options = $this->settings[$Model->alias];
265
-			$from = $to = $substFrom = $substTo = array();
266
-			if ($options['wildcardAny'] !== '%' || ($field['before'] !== false || $field['after'] !== false)) {
267
-				$from[] = '%';
268
-				$to[] = '\%';
269
-			}
270
-			if ($options['wildcardOne'] !== '_' || ($field['before'] !== false || $field['after'] !== false)) {
271
-				$from[] = '_';
272
-				$to[] = '\_';
273
-			}
274
-			$value = $data[$field['name']];
275
-			if (!empty($from)) {
276
-				$value = str_replace($from, $to, $value);
277
-			}
278
-			if ($field['before'] === false && $field['after'] === false) {
279
-				if ($options['wildcardAny'] !== '%') {
280
-					$substFrom[] = $options['wildcardAny'];
281
-					$substTo[] = '%';
282
-				}
283
-				if ($options['wildcardOne'] !== '_') {
284
-					$substFrom[] = $options['wildcardOne'];
285
-					$substTo[] = '_';
286
-				}
287
-				$value = str_replace($substFrom, $substTo, $value);
288
-			}
289
-
290
-			if (!empty($field['connectorAnd']) || !empty($field['connectorOr'])) {
291
-				$cond[] = $this->_connectedLike($value, $field, $fieldName);
292
-			} else {
293
-				$cond[$fieldName . " LIKE"] = $field['before'] . $value . $field['after'];
294
-			}
295
-		}
296
-		if (count($cond) > 1) {
297
-			if (isset($conditions['OR'])) {
298
-				$conditions[]['OR'] = $cond;
299
-			} else {
300
-				$conditions['OR'] = $cond;
301
-			}
302
-		} else {
303
-			$conditions = array_merge($conditions, $cond);
304
-		}
305
-		return $conditions;
306
-	}
241
+    protected function _addCondLike(Model $Model, &$conditions, $data, $field) {
242
+        if (!is_array($this->settings[$Model->alias]['like'])) {
243
+            $this->settings[$Model->alias]['like'] = array('before' => $this->settings[$Model->alias]['like'], 'after' => $this->settings[$Model->alias]['like']);
244
+        }
245
+        $field = array_merge($this->settings[$Model->alias]['like'], $field);
246
+        if (empty($data[$field['name']])) {
247
+            return $conditions;
248
+        }
249
+        $fieldNames = (array)$field['field'];
250
+
251
+        $cond = array();
252
+        foreach ($fieldNames as $fieldName) {
253
+            if (strpos($fieldName, '.') === false) {
254
+                $fieldName = $Model->alias . '.' . $fieldName;
255
+            }
256
+
257
+            if ($field['before'] === true) {
258
+                $field['before'] = '%';
259
+            }
260
+            if ($field['after'] === true) {
261
+                $field['after'] = '%';
262
+            }
263
+            //if both before and after are false, LIKE allows custom placeholders, % and _ are always treated as normal chars
264
+            $options = $this->settings[$Model->alias];
265
+            $from = $to = $substFrom = $substTo = array();
266
+            if ($options['wildcardAny'] !== '%' || ($field['before'] !== false || $field['after'] !== false)) {
267
+                $from[] = '%';
268
+                $to[] = '\%';
269
+            }
270
+            if ($options['wildcardOne'] !== '_' || ($field['before'] !== false || $field['after'] !== false)) {
271
+                $from[] = '_';
272
+                $to[] = '\_';
273
+            }
274
+            $value = $data[$field['name']];
275
+            if (!empty($from)) {
276
+                $value = str_replace($from, $to, $value);
277
+            }
278
+            if ($field['before'] === false && $field['after'] === false) {
279
+                if ($options['wildcardAny'] !== '%') {
280
+                    $substFrom[] = $options['wildcardAny'];
281
+                    $substTo[] = '%';
282
+                }
283
+                if ($options['wildcardOne'] !== '_') {
284
+                    $substFrom[] = $options['wildcardOne'];
285
+                    $substTo[] = '_';
286
+                }
287
+                $value = str_replace($substFrom, $substTo, $value);
288
+            }
289
+
290
+            if (!empty($field['connectorAnd']) || !empty($field['connectorOr'])) {
291
+                $cond[] = $this->_connectedLike($value, $field, $fieldName);
292
+            } else {
293
+                $cond[$fieldName . " LIKE"] = $field['before'] . $value . $field['after'];
294
+            }
295
+        }
296
+        if (count($cond) > 1) {
297
+            if (isset($conditions['OR'])) {
298
+                $conditions[]['OR'] = $cond;
299
+            } else {
300
+                $conditions['OR'] = $cond;
301
+            }
302
+        } else {
303
+            $conditions = array_merge($conditions, $cond);
304
+        }
305
+        return $conditions;
306
+    }
307 307
 
308 308
 /**
309 309
  * Form AND/OR query array using String::tokenize to separate
@@ -314,21 +314,21 @@  discard block
 block discarded – undo
314 314
  * @param string $fieldName
315 315
  * @return array Conditions
316 316
  */
317
-	protected function _connectedLike($value, $field, $fieldName) {
318
-		$or = array();
319
-		$orValues = String::tokenize($value, $field['connectorOr']);
320
-		foreach ($orValues as $orValue) {
321
-			$andValues = String::tokenize($orValue, $field['connectorAnd']);
322
-			$and = array();
323
-			foreach ($andValues as $andValue) {
324
-				$and[] = array($fieldName . " LIKE" => $field['before'] . $andValue . $field['after']);
325
-			}
326
-
327
-			$or[] = array('AND' => $and);
328
-		}
329
-
330
-		return array('OR' => $or);
331
-	}
317
+    protected function _connectedLike($value, $field, $fieldName) {
318
+        $or = array();
319
+        $orValues = String::tokenize($value, $field['connectorOr']);
320
+        foreach ($orValues as $orValue) {
321
+            $andValues = String::tokenize($orValue, $field['connectorAnd']);
322
+            $and = array();
323
+            foreach ($andValues as $andValue) {
324
+                $and[] = array($fieldName . " LIKE" => $field['before'] . $andValue . $field['after']);
325
+            }
326
+
327
+            $or[] = array('AND' => $and);
328
+        }
329
+
330
+        return array('OR' => $or);
331
+    }
332 332
 
333 333
 /**
334 334
  * Add Conditions based on exact comparison
@@ -339,46 +339,46 @@  discard block
 block discarded – undo
339 339
  * @param array $field Field definition information
340 340
  * @return array of conditions
341 341
  */
342
-	protected function _addCondValue(Model $Model, &$conditions, $data, $field) {
343
-		$fieldNames = (array)$field['field'];
344
-		$fieldValue = isset($data[$field['name']]) ? $data[$field['name']] : null;
345
-
346
-		$cond = array();
347
-		foreach ($fieldNames as $fieldName) {
348
-			if (strpos($fieldName, '.') === false) {
349
-				$fieldName = $Model->alias . '.' . $fieldName;
350
-			}
351
-			if (is_array($fieldValue) && empty($fieldValue)) {
352
-				continue;
353
-			}
354
-			if (!is_array($fieldValue) && ($fieldValue === null || $fieldValue === '' && empty($field['allowEmpty']))) {
355
-				continue;
356
-			}
357
-
358
-			if (is_array($fieldValue) || !is_array($fieldValue) && (string)$fieldValue !== '') {
359
-				$cond[$fieldName] = $fieldValue;
360
-			} elseif (isset($data[$field['name']]) && !empty($field['allowEmpty'])) {
361
-				$schema = $Model->schema($field['name']);
362
-				if (isset($schema) && ($schema['default'] !== null || !empty($schema['null']))) {
363
-					$cond[$fieldName] = $schema['default'];
364
-				} elseif (!empty($fieldValue)) {
365
-					$cond[$fieldName] = $fieldValue;
366
-				} else {
367
-					$cond[$fieldName] = $fieldValue;
368
-				}
369
-			}
370
-		}
371
-		if (count($cond) > 1) {
372
-			if (isset($conditions['OR'])) {
373
-				$conditions[]['OR'] = $cond;
374
-			} else {
375
-				$conditions['OR'] = $cond;
376
-			}
377
-		} else {
378
-			$conditions = array_merge($conditions, $cond);
379
-		}
380
-		return $conditions;
381
-	}
342
+    protected function _addCondValue(Model $Model, &$conditions, $data, $field) {
343
+        $fieldNames = (array)$field['field'];
344
+        $fieldValue = isset($data[$field['name']]) ? $data[$field['name']] : null;
345
+
346
+        $cond = array();
347
+        foreach ($fieldNames as $fieldName) {
348
+            if (strpos($fieldName, '.') === false) {
349
+                $fieldName = $Model->alias . '.' . $fieldName;
350
+            }
351
+            if (is_array($fieldValue) && empty($fieldValue)) {
352
+                continue;
353
+            }
354
+            if (!is_array($fieldValue) && ($fieldValue === null || $fieldValue === '' && empty($field['allowEmpty']))) {
355
+                continue;
356
+            }
357
+
358
+            if (is_array($fieldValue) || !is_array($fieldValue) && (string)$fieldValue !== '') {
359
+                $cond[$fieldName] = $fieldValue;
360
+            } elseif (isset($data[$field['name']]) && !empty($field['allowEmpty'])) {
361
+                $schema = $Model->schema($field['name']);
362
+                if (isset($schema) && ($schema['default'] !== null || !empty($schema['null']))) {
363
+                    $cond[$fieldName] = $schema['default'];
364
+                } elseif (!empty($fieldValue)) {
365
+                    $cond[$fieldName] = $fieldValue;
366
+                } else {
367
+                    $cond[$fieldName] = $fieldValue;
368
+                }
369
+            }
370
+        }
371
+        if (count($cond) > 1) {
372
+            if (isset($conditions['OR'])) {
373
+                $conditions[]['OR'] = $cond;
374
+            } else {
375
+                $conditions['OR'] = $cond;
376
+            }
377
+        } else {
378
+            $conditions = array_merge($conditions, $cond);
379
+        }
380
+        return $conditions;
381
+    }
382 382
 
383 383
 /**
384 384
  * Add Conditions based expressions to search conditions.
@@ -389,19 +389,19 @@  discard block
 block discarded – undo
389 389
  * @param array $field Info for field.
390 390
  * @return array of conditions modified by this method
391 391
  */
392
-	protected function _addCondExpression(Model $Model, &$conditions, $data, $field) {
393
-		$fieldName = $field['field'];
394
-
395
-		if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string)$data[$field['name']] !== ''))) {
396
-			$fieldValues = $Model->{$field['method']}($data, $field);
397
-			if (!empty($conditions[$fieldName]) && is_array($conditions[$fieldName])) {
398
-				$conditions[$fieldName] = array_unique(array_merge(array($conditions[$fieldName]), array($fieldValues)));
399
-			} else {
400
-				$conditions[$fieldName] = $fieldValues;
401
-			}
402
-		}
403
-		return $conditions;
404
-	}
392
+    protected function _addCondExpression(Model $Model, &$conditions, $data, $field) {
393
+        $fieldName = $field['field'];
394
+
395
+        if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string)$data[$field['name']] !== ''))) {
396
+            $fieldValues = $Model->{$field['method']}($data, $field);
397
+            if (!empty($conditions[$fieldName]) && is_array($conditions[$fieldName])) {
398
+                $conditions[$fieldName] = array_unique(array_merge(array($conditions[$fieldName]), array($fieldValues)));
399
+            } else {
400
+                $conditions[$fieldName] = $fieldValues;
401
+            }
402
+        }
403
+        return $conditions;
404
+    }
405 405
 
406 406
 /**
407 407
  * Add Conditions based query to search conditions.
@@ -412,16 +412,16 @@  discard block
 block discarded – undo
412 412
  * @param array $field Info for field.
413 413
  * @return array of conditions modified by this method
414 414
  */
415
-	protected function _addCondQuery(Model $Model, &$conditions, $data, $field) {
416
-		if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string)$data[$field['name']] !== ''))) {
417
-			$conditionsAdd = $Model->{$field['method']}($data, $field);
418
-			// if our conditions function returns something empty, nothing to merge in
419
-			if (!empty($conditionsAdd)) {
420
-				$conditions = Set::merge($conditions, (array)$conditionsAdd);
421
-			}
422
-		}
423
-		return $conditions;
424
-	}
415
+    protected function _addCondQuery(Model $Model, &$conditions, $data, $field) {
416
+        if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string)$data[$field['name']] !== ''))) {
417
+            $conditionsAdd = $Model->{$field['method']}($data, $field);
418
+            // if our conditions function returns something empty, nothing to merge in
419
+            if (!empty($conditionsAdd)) {
420
+                $conditions = Set::merge($conditions, (array)$conditionsAdd);
421
+            }
422
+        }
423
+        return $conditions;
424
+    }
425 425
 
426 426
 /**
427 427
  * Add Conditions based subquery to search conditions.
@@ -432,17 +432,17 @@  discard block
 block discarded – undo
432 432
  * @param array $field Info for field.
433 433
  * @return array of conditions modified by this method
434 434
  */
435
-	protected function _addCondSubquery(Model $Model, &$conditions, $data, $field) {
436
-		$fieldName = $field['field'];
437
-		if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string)$data[$field['name']] !== ''))) {
438
-			$subquery = $Model->{$field['method']}($data, $field);
439
-			// if our subquery function returns something empty, nothing to merge in
440
-			if (!empty($subquery)) {
441
-				$conditions[] = $Model->getDataSource()->expression("$fieldName in ($subquery)");
442
-			}
443
-		}
444
-		return $conditions;
445
-	}
435
+    protected function _addCondSubquery(Model $Model, &$conditions, $data, $field) {
436
+        $fieldName = $field['field'];
437
+        if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string)$data[$field['name']] !== ''))) {
438
+            $subquery = $Model->{$field['method']}($data, $field);
439
+            // if our subquery function returns something empty, nothing to merge in
440
+            if (!empty($subquery)) {
441
+                $conditions[] = $Model->getDataSource()->expression("$fieldName in ($subquery)");
442
+            }
443
+        }
444
+        return $conditions;
445
+    }
446 446
 
447 447
 /**
448 448
  * Helper method for getQuery.
@@ -452,58 +452,58 @@  discard block
 block discarded – undo
452 452
  * @param array $queryData
453 453
  * @return string
454 454
  */
455
-	protected function _queryGet(Model $Model, $queryData = array()) {
456
-		/** @var DboSource $db  */
457
-		$db = $Model->getDataSource();
458
-		$queryData = $this->_scrubQueryData($queryData);
459
-		$recursive = null;
460
-		$byPass = false;
461
-		$null = null;
462
-		$linkedModels = array();
463
-
464
-		if (isset($queryData['recursive'])) {
465
-			$recursive = $queryData['recursive'];
466
-		}
467
-
468
-		if ($recursive !== null) {
469
-			$_recursive = $Model->recursive;
470
-			$Model->recursive = $recursive;
471
-		}
472
-
473
-		if (!empty($queryData['fields'])) {
474
-			$byPass = true;
475
-			$queryData['fields'] = $db->fields($Model, null, $queryData['fields']);
476
-		} else {
477
-			$queryData['fields'] = $db->fields($Model);
478
-		}
479
-
480
-		$_associations = $Model->associations();
481
-
482
-		if ($Model->recursive == -1) {
483
-			$_associations = array();
484
-		} elseif ($Model->recursive == 0) {
485
-			unset($_associations[2], $_associations[3]);
486
-		}
487
-
488
-		foreach ($_associations as $type) {
489
-			foreach ($Model->{$type} as $assoc => $assocData) {
490
-				$linkModel = $Model->{$assoc};
491
-				$external = isset($assocData['external']);
492
-
493
-				$linkModel->getDataSource();
494
-				if ($Model->useDbConfig === $linkModel->useDbConfig) {
495
-					if ($byPass) {
496
-						$assocData['fields'] = false;
497
-					}
498
-					if ($db->generateAssociationQuery($Model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null) === true) {
499
-						$linkedModels[$type . '/' . $assoc] = true;
500
-					}
501
-				}
502
-			}
503
-		}
504
-
505
-		return trim($db->generateAssociationQuery($Model, null, null, null, null, $queryData, false, $null));
506
-	}
455
+    protected function _queryGet(Model $Model, $queryData = array()) {
456
+        /** @var DboSource $db  */
457
+        $db = $Model->getDataSource();
458
+        $queryData = $this->_scrubQueryData($queryData);
459
+        $recursive = null;
460
+        $byPass = false;
461
+        $null = null;
462
+        $linkedModels = array();
463
+
464
+        if (isset($queryData['recursive'])) {
465
+            $recursive = $queryData['recursive'];
466
+        }
467
+
468
+        if ($recursive !== null) {
469
+            $_recursive = $Model->recursive;
470
+            $Model->recursive = $recursive;
471
+        }
472
+
473
+        if (!empty($queryData['fields'])) {
474
+            $byPass = true;
475
+            $queryData['fields'] = $db->fields($Model, null, $queryData['fields']);
476
+        } else {
477
+            $queryData['fields'] = $db->fields($Model);
478
+        }
479
+
480
+        $_associations = $Model->associations();
481
+
482
+        if ($Model->recursive == -1) {
483
+            $_associations = array();
484
+        } elseif ($Model->recursive == 0) {
485
+            unset($_associations[2], $_associations[3]);
486
+        }
487
+
488
+        foreach ($_associations as $type) {
489
+            foreach ($Model->{$type} as $assoc => $assocData) {
490
+                $linkModel = $Model->{$assoc};
491
+                $external = isset($assocData['external']);
492
+
493
+                $linkModel->getDataSource();
494
+                if ($Model->useDbConfig === $linkModel->useDbConfig) {
495
+                    if ($byPass) {
496
+                        $assocData['fields'] = false;
497
+                    }
498
+                    if ($db->generateAssociationQuery($Model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null) === true) {
499
+                        $linkedModels[$type . '/' . $assoc] = true;
500
+                    }
501
+                }
502
+            }
503
+        }
504
+
505
+        return trim($db->generateAssociationQuery($Model, null, null, null, null, $queryData, false, $null));
506
+    }
507 507
 
508 508
 /**
509 509
  * Private helper method to remove query metadata in given data array.
@@ -511,13 +511,13 @@  discard block
 block discarded – undo
511 511
  * @param array $data
512 512
  * @return array
513 513
  */
514
-	protected function _scrubQueryData($data) {
515
-		static $base = null;
516
-		if ($base === null) {
517
-			$base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array());
518
-		}
519
-		return (array)$data + $base;
520
-	}
514
+    protected function _scrubQueryData($data) {
515
+        static $base = null;
516
+        if ($base === null) {
517
+            $base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array());
518
+        }
519
+        return (array)$data + $base;
520
+    }
521 521
 
522 522
 /**
523 523
  * Check if model have some method in attached behaviors
@@ -526,20 +526,20 @@  discard block
 block discarded – undo
526 526
  * @param string $method
527 527
  * @return boolean, true if method exists in attached and enabled behaviors
528 528
  */
529
-	protected function _checkBehaviorMethods(Model $Model, $method) {
530
-		$behaviors = $Model->Behaviors->enabled();
531
-		$count = count($behaviors);
532
-		$found = false;
533
-		for ($i = 0; $i < $count; $i++) {
534
-			$name = $behaviors[$i];
535
-			$methods = get_class_methods($Model->Behaviors->{$name});
536
-			$check = array_flip($methods);
537
-			$found = isset($check[$method]);
538
-			if ($found) {
539
-				return true;
540
-			}
541
-		}
542
-		return $found;
543
-	}
529
+    protected function _checkBehaviorMethods(Model $Model, $method) {
530
+        $behaviors = $Model->Behaviors->enabled();
531
+        $count = count($behaviors);
532
+        $found = false;
533
+        for ($i = 0; $i < $count; $i++) {
534
+            $name = $behaviors[$i];
535
+            $methods = get_class_methods($Model->Behaviors->{$name});
536
+            $check = array_flip($methods);
537
+            $found = isset($check[$method]);
538
+            if ($found) {
539
+                return true;
540
+            }
541
+        }
542
+        return $found;
543
+    }
544 544
 
545 545
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
  * @return void
43 43
  */
44 44
 	public function setup(Model $Model, $config = array()) {
45
-		$this->_defaults = array_merge($this->_defaults, (array)Configure::read('Search.Searchable'));
45
+		$this->_defaults = array_merge($this->_defaults, (array) Configure::read('Search.Searchable'));
46 46
 		$this->settings[$Model->alias] = array_merge($this->_defaults, $config);
47 47
 		if (empty($Model->filterArgs)) {
48 48
 			return;
@@ -246,12 +246,12 @@  discard block
 block discarded – undo
246 246
 		if (empty($data[$field['name']])) {
247 247
 			return $conditions;
248 248
 		}
249
-		$fieldNames = (array)$field['field'];
249
+		$fieldNames = (array) $field['field'];
250 250
 
251 251
 		$cond = array();
252 252
 		foreach ($fieldNames as $fieldName) {
253 253
 			if (strpos($fieldName, '.') === false) {
254
-				$fieldName = $Model->alias . '.' . $fieldName;
254
+				$fieldName = $Model->alias.'.'.$fieldName;
255 255
 			}
256 256
 
257 257
 			if ($field['before'] === true) {
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
 			if (!empty($field['connectorAnd']) || !empty($field['connectorOr'])) {
291 291
 				$cond[] = $this->_connectedLike($value, $field, $fieldName);
292 292
 			} else {
293
-				$cond[$fieldName . " LIKE"] = $field['before'] . $value . $field['after'];
293
+				$cond[$fieldName." LIKE"] = $field['before'].$value.$field['after'];
294 294
 			}
295 295
 		}
296 296
 		if (count($cond) > 1) {
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
 			$andValues = String::tokenize($orValue, $field['connectorAnd']);
322 322
 			$and = array();
323 323
 			foreach ($andValues as $andValue) {
324
-				$and[] = array($fieldName . " LIKE" => $field['before'] . $andValue . $field['after']);
324
+				$and[] = array($fieldName." LIKE" => $field['before'].$andValue.$field['after']);
325 325
 			}
326 326
 
327 327
 			$or[] = array('AND' => $and);
@@ -340,13 +340,13 @@  discard block
 block discarded – undo
340 340
  * @return array of conditions
341 341
  */
342 342
 	protected function _addCondValue(Model $Model, &$conditions, $data, $field) {
343
-		$fieldNames = (array)$field['field'];
343
+		$fieldNames = (array) $field['field'];
344 344
 		$fieldValue = isset($data[$field['name']]) ? $data[$field['name']] : null;
345 345
 
346 346
 		$cond = array();
347 347
 		foreach ($fieldNames as $fieldName) {
348 348
 			if (strpos($fieldName, '.') === false) {
349
-				$fieldName = $Model->alias . '.' . $fieldName;
349
+				$fieldName = $Model->alias.'.'.$fieldName;
350 350
 			}
351 351
 			if (is_array($fieldValue) && empty($fieldValue)) {
352 352
 				continue;
@@ -355,7 +355,7 @@  discard block
 block discarded – undo
355 355
 				continue;
356 356
 			}
357 357
 
358
-			if (is_array($fieldValue) || !is_array($fieldValue) && (string)$fieldValue !== '') {
358
+			if (is_array($fieldValue) || !is_array($fieldValue) && (string) $fieldValue !== '') {
359 359
 				$cond[$fieldName] = $fieldValue;
360 360
 			} elseif (isset($data[$field['name']]) && !empty($field['allowEmpty'])) {
361 361
 				$schema = $Model->schema($field['name']);
@@ -392,7 +392,7 @@  discard block
 block discarded – undo
392 392
 	protected function _addCondExpression(Model $Model, &$conditions, $data, $field) {
393 393
 		$fieldName = $field['field'];
394 394
 
395
-		if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string)$data[$field['name']] !== ''))) {
395
+		if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string) $data[$field['name']] !== ''))) {
396 396
 			$fieldValues = $Model->{$field['method']}($data, $field);
397 397
 			if (!empty($conditions[$fieldName]) && is_array($conditions[$fieldName])) {
398 398
 				$conditions[$fieldName] = array_unique(array_merge(array($conditions[$fieldName]), array($fieldValues)));
@@ -413,11 +413,11 @@  discard block
 block discarded – undo
413 413
  * @return array of conditions modified by this method
414 414
  */
415 415
 	protected function _addCondQuery(Model $Model, &$conditions, $data, $field) {
416
-		if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string)$data[$field['name']] !== ''))) {
416
+		if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string) $data[$field['name']] !== ''))) {
417 417
 			$conditionsAdd = $Model->{$field['method']}($data, $field);
418 418
 			// if our conditions function returns something empty, nothing to merge in
419 419
 			if (!empty($conditionsAdd)) {
420
-				$conditions = Set::merge($conditions, (array)$conditionsAdd);
420
+				$conditions = Set::merge($conditions, (array) $conditionsAdd);
421 421
 			}
422 422
 		}
423 423
 		return $conditions;
@@ -434,7 +434,7 @@  discard block
 block discarded – undo
434 434
  */
435 435
 	protected function _addCondSubquery(Model $Model, &$conditions, $data, $field) {
436 436
 		$fieldName = $field['field'];
437
-		if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string)$data[$field['name']] !== ''))) {
437
+		if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string) $data[$field['name']] !== ''))) {
438 438
 			$subquery = $Model->{$field['method']}($data, $field);
439 439
 			// if our subquery function returns something empty, nothing to merge in
440 440
 			if (!empty($subquery)) {
@@ -496,7 +496,7 @@  discard block
 block discarded – undo
496 496
 						$assocData['fields'] = false;
497 497
 					}
498 498
 					if ($db->generateAssociationQuery($Model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null) === true) {
499
-						$linkedModels[$type . '/' . $assoc] = true;
499
+						$linkedModels[$type.'/'.$assoc] = true;
500 500
 					}
501 501
 				}
502 502
 			}
@@ -516,7 +516,7 @@  discard block
 block discarded – undo
516 516
 		if ($base === null) {
517 517
 			$base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array());
518 518
 		}
519
-		return (array)$data + $base;
519
+		return (array) $data + $base;
520 520
 	}
521 521
 
522 522
 /**
Please login to merge, or discard this patch.
app/Plugin/Search/Test/Case/Controller/Component/PrgComponentTest.php 2 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -762,6 +762,7 @@
 block discarded – undo
762 762
 /**
763 763
  * replace the base64encoded values that could harm the url (/ and =) with harmless characters
764 764
  *
765
+ * @param string $str
765 766
  * @return string
766 767
  */
767 768
 	protected function _urlEncode($str) {
Please login to merge, or discard this patch.
Indentation   +692 added lines, -692 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
  *
25 25
  * @var array
26 26
  */
27
-	public $actsAs = array('Search.Searchable');
27
+    public $actsAs = array('Search.Searchable');
28 28
 
29 29
 }
30 30
 
@@ -39,27 +39,27 @@  discard block
 block discarded – undo
39 39
  *
40 40
  * @var array
41 41
  */
42
-	public $uses = array('Post');
42
+    public $uses = array('Post');
43 43
 
44 44
 /**
45 45
  * Components
46 46
  *
47 47
  * @var array
48 48
  */
49
-	public $components = array('Search.Prg', 'Session');
49
+    public $components = array('Search.Prg', 'Session');
50 50
 
51 51
 /**
52 52
  * beforeFilter
53 53
  *
54 54
  * @return void
55 55
  */
56
-	public function beforeFilter() {
57
-		parent::beforeFilter();
58
-		$this->Prg->actions = array(
59
-			'search' => array(
60
-				'controller' => 'Posts',
61
-				'action' => 'result'));
62
-	}
56
+    public function beforeFilter() {
57
+        parent::beforeFilter();
58
+        $this->Prg->actions = array(
59
+            'search' => array(
60
+                'controller' => 'Posts',
61
+                'action' => 'result'));
62
+    }
63 63
 
64 64
 /**
65 65
  * Overwrite redirect
@@ -69,9 +69,9 @@  discard block
 block discarded – undo
69 69
  * @param string $exit
70 70
  * @return void
71 71
  */
72
-	public function redirect($url, $status = null, $exit = true) {
73
-		$this->redirectUrl = $url;
74
-	}
72
+    public function redirect($url, $status = null, $exit = true) {
73
+        $this->redirectUrl = $url;
74
+    }
75 75
 
76 76
 }
77 77
 
@@ -86,14 +86,14 @@  discard block
 block discarded – undo
86 86
  *
87 87
  * @var array
88 88
  */
89
-	public $components = array(
90
-		'Search.Prg' => array(
91
-			'commonProcess' => array(
92
-				'form' => 'Post',
93
-				'modelMethod' => false,
94
-				'allowedParams' => array('lang'))),
95
-		'Session'
96
-	);
89
+    public $components = array(
90
+        'Search.Prg' => array(
91
+            'commonProcess' => array(
92
+                'form' => 'Post',
93
+                'modelMethod' => false,
94
+                'allowedParams' => array('lang'))),
95
+        'Session'
96
+    );
97 97
 }
98 98
 
99 99
 /**
@@ -107,169 +107,169 @@  discard block
 block discarded – undo
107 107
  *
108 108
  * @var array
109 109
  */
110
-	public $fixtures = array('plugin.search.post');
110
+    public $fixtures = array('plugin.search.post');
111 111
 
112 112
 /**
113 113
  * startTest
114 114
  *
115 115
  * @return void
116 116
  */
117
-	public function setUp() {
118
-		parent::setUp();
117
+    public function setUp() {
118
+        parent::setUp();
119 119
 
120
-		Configure::delete('Search');
120
+        Configure::delete('Search');
121 121
 
122
-		$this->Controller = new PostsTestController(new CakeRequest(), new CakeResponse());
123
-		$this->Controller->constructClasses();
124
-		$this->Controller->startupProcess();
125
-		$this->Controller->request->params = array(
126
-			'named' => array(),
127
-			'pass' => array(),
128
-			'url' => array());
129
-		$this->Controller->request->query = array();
130
-	}
122
+        $this->Controller = new PostsTestController(new CakeRequest(), new CakeResponse());
123
+        $this->Controller->constructClasses();
124
+        $this->Controller->startupProcess();
125
+        $this->Controller->request->params = array(
126
+            'named' => array(),
127
+            'pass' => array(),
128
+            'url' => array());
129
+        $this->Controller->request->query = array();
130
+    }
131 131
 
132 132
 /**
133 133
  * endTest
134 134
  *
135 135
  * @return void
136 136
  */
137
-	public function tearDown() {
138
-		unset($this->Controller);
139
-		ClassRegistry::flush();
137
+    public function tearDown() {
138
+        unset($this->Controller);
139
+        ClassRegistry::flush();
140 140
 
141
-		parent::tearDown();
142
-	}
141
+        parent::tearDown();
142
+    }
143 143
 
144 144
 /**
145 145
  * testOptions
146 146
  *
147 147
  * @return void
148 148
  */
149
-	public function testOptions() {
150
-		$this->Controller->presetVars = array();
151
-		$this->Controller->action = 'search';
152
-		$this->Controller->request->data = array(
153
-			'Post' => array(
154
-				'title' => 'test'));
155
-
156
-		$this->Controller->Prg->commonProcess('Post');
157
-		$expected = array(
158
-			'title' => 'test',
159
-			'action' => 'search');
160
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
161
-
162
-		$this->Controller->request->params = array_merge($this->Controller->request->params, array(
163
-			'lang' => 'en',
164
-			));
165
-		$this->Controller->Prg->commonProcess('Post', array('allowedParams' => array('lang')));
166
-		$expected = array(
167
-			'title' => 'test',
168
-			'action' => 'search',
169
-			'lang' => 'en');
170
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
171
-
172
-		$this->Controller->presetVars = array(
173
-			array('field' => 'title', 'type' => 'value'));
174
-		$this->Controller->Prg->commonProcess('Post', array('paramType' => 'querystring'));
175
-		$expected = array('action' => 'search', '?' => array('title' => 'test'));
176
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
177
-	}
149
+    public function testOptions() {
150
+        $this->Controller->presetVars = array();
151
+        $this->Controller->action = 'search';
152
+        $this->Controller->request->data = array(
153
+            'Post' => array(
154
+                'title' => 'test'));
155
+
156
+        $this->Controller->Prg->commonProcess('Post');
157
+        $expected = array(
158
+            'title' => 'test',
159
+            'action' => 'search');
160
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
161
+
162
+        $this->Controller->request->params = array_merge($this->Controller->request->params, array(
163
+            'lang' => 'en',
164
+            ));
165
+        $this->Controller->Prg->commonProcess('Post', array('allowedParams' => array('lang')));
166
+        $expected = array(
167
+            'title' => 'test',
168
+            'action' => 'search',
169
+            'lang' => 'en');
170
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
171
+
172
+        $this->Controller->presetVars = array(
173
+            array('field' => 'title', 'type' => 'value'));
174
+        $this->Controller->Prg->commonProcess('Post', array('paramType' => 'querystring'));
175
+        $expected = array('action' => 'search', '?' => array('title' => 'test'));
176
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
177
+    }
178 178
 
179 179
 /**
180 180
  * testPresetForm
181 181
  *
182 182
  * @return void
183 183
  */
184
-	public function testPresetForm() {
185
-		$this->Controller->presetVars = array(
186
-			array(
187
-				'field' => 'title',
188
-				'type' => 'value'),
189
-			array(
190
-				'field' => 'checkbox',
191
-				'type' => 'checkbox'),
192
-			array(
193
-				'field' => 'lookup',
194
-				'type' => 'lookup',
195
-				'formField' => 'lookup_input',
196
-				'modelField' => 'title',
197
-				'model' => 'Post'));
198
-		$this->Controller->passedArgs = array(
199
-			'title' => 'test',
200
-			'checkbox' => 'test|test2|test3',
201
-			'lookup' => '1');
202
-		$this->Controller->beforeFilter();
203
-
204
-		$this->Controller->Prg->presetForm('Post');
205
-		$expected = array(
206
-			'Post' => array(
207
-				'title' => 'test',
208
-				'checkbox' => array(
209
-					0 => 'test',
210
-					1 => 'test2',
211
-					2 => 'test3'),
212
-				'lookup' => 1,
213
-				'lookup_input' => 'First Post'));
214
-		$this->assertEquals($expected, $this->Controller->request->data);
215
-
216
-		$this->Controller->data = array();
217
-		$this->Controller->passedArgs = array();
218
-		$this->Controller->request->query = array(
219
-			'title' => 'test',
220
-			'checkbox' => 'test|test2|test3',
221
-			'lookup' => '1');
222
-		$this->Controller->beforeFilter();
223
-
224
-		$this->Controller->Prg->presetForm(array('model' => 'Post', 'paramType' => 'querystring'));
225
-		$this->assertTrue($this->Controller->Prg->isSearch);
226
-		$this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
227
-
228
-		// deprecated
229
-		$this->assertEquals($expected, $this->Controller->data);
230
-	}
184
+    public function testPresetForm() {
185
+        $this->Controller->presetVars = array(
186
+            array(
187
+                'field' => 'title',
188
+                'type' => 'value'),
189
+            array(
190
+                'field' => 'checkbox',
191
+                'type' => 'checkbox'),
192
+            array(
193
+                'field' => 'lookup',
194
+                'type' => 'lookup',
195
+                'formField' => 'lookup_input',
196
+                'modelField' => 'title',
197
+                'model' => 'Post'));
198
+        $this->Controller->passedArgs = array(
199
+            'title' => 'test',
200
+            'checkbox' => 'test|test2|test3',
201
+            'lookup' => '1');
202
+        $this->Controller->beforeFilter();
203
+
204
+        $this->Controller->Prg->presetForm('Post');
205
+        $expected = array(
206
+            'Post' => array(
207
+                'title' => 'test',
208
+                'checkbox' => array(
209
+                    0 => 'test',
210
+                    1 => 'test2',
211
+                    2 => 'test3'),
212
+                'lookup' => 1,
213
+                'lookup_input' => 'First Post'));
214
+        $this->assertEquals($expected, $this->Controller->request->data);
215
+
216
+        $this->Controller->data = array();
217
+        $this->Controller->passedArgs = array();
218
+        $this->Controller->request->query = array(
219
+            'title' => 'test',
220
+            'checkbox' => 'test|test2|test3',
221
+            'lookup' => '1');
222
+        $this->Controller->beforeFilter();
223
+
224
+        $this->Controller->Prg->presetForm(array('model' => 'Post', 'paramType' => 'querystring'));
225
+        $this->assertTrue($this->Controller->Prg->isSearch);
226
+        $this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
227
+
228
+        // deprecated
229
+        $this->assertEquals($expected, $this->Controller->data);
230
+    }
231 231
 
232 232
 /**
233 233
  * testPresetFormEmpty
234 234
  *
235 235
  * @return void
236 236
  */
237
-	public function testPresetFormEmpty() {
238
-		$this->Controller->presetVars = array(
239
-			array(
240
-				'field' => 'title',
241
-				'type' => 'value'),
242
-			array(
243
-				'field' => 'checkbox',
244
-				'type' => 'checkbox'),
245
-			array(
246
-				'field' => 'lookup',
247
-				'type' => 'lookup',
248
-				'formField' => 'lookup_input',
249
-				'modelField' => 'title',
250
-				'model' => 'Post'));
251
-		$this->Controller->passedArgs = array(
252
-			'page' => '2');
253
-		$this->Controller->beforeFilter();
254
-
255
-		$this->Controller->Prg->presetForm('Post');
256
-		$expected = array(
257
-			'Post' => array());
258
-		$this->assertEquals($expected, $this->Controller->request->data);
259
-
260
-		$this->Controller->data = array();
261
-		$this->Controller->passedArgs = array();
262
-		$this->Controller->request->query = array(
263
-			'page' => '2');
264
-		$this->Controller->beforeFilter();
265
-
266
-		$this->Controller->Prg->presetForm(array('model' => 'Post', 'paramType' => 'querystring'));
267
-		$this->assertFalse($this->Controller->Prg->isSearch);
268
-		$this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
269
-
270
-		// deprecated
271
-		$this->assertEquals($expected, $this->Controller->data);
272
-	}
237
+    public function testPresetFormEmpty() {
238
+        $this->Controller->presetVars = array(
239
+            array(
240
+                'field' => 'title',
241
+                'type' => 'value'),
242
+            array(
243
+                'field' => 'checkbox',
244
+                'type' => 'checkbox'),
245
+            array(
246
+                'field' => 'lookup',
247
+                'type' => 'lookup',
248
+                'formField' => 'lookup_input',
249
+                'modelField' => 'title',
250
+                'model' => 'Post'));
251
+        $this->Controller->passedArgs = array(
252
+            'page' => '2');
253
+        $this->Controller->beforeFilter();
254
+
255
+        $this->Controller->Prg->presetForm('Post');
256
+        $expected = array(
257
+            'Post' => array());
258
+        $this->assertEquals($expected, $this->Controller->request->data);
259
+
260
+        $this->Controller->data = array();
261
+        $this->Controller->passedArgs = array();
262
+        $this->Controller->request->query = array(
263
+            'page' => '2');
264
+        $this->Controller->beforeFilter();
265
+
266
+        $this->Controller->Prg->presetForm(array('model' => 'Post', 'paramType' => 'querystring'));
267
+        $this->assertFalse($this->Controller->Prg->isSearch);
268
+        $this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
269
+
270
+        // deprecated
271
+        $this->assertEquals($expected, $this->Controller->data);
272
+    }
273 273
 
274 274
 /**
275 275
  * This test checks that the search on an integer type field in the database
@@ -278,118 +278,118 @@  discard block
 block discarded – undo
278 278
  * @return void
279 279
  * @link http://github.com/CakeDC/Search/issues#issue/3
280 280
  */
281
-	public function testPresetFormWithIntegerField() {
282
-		$this->Controller->presetVars = array(
283
-			array(
284
-				'field' => 'views',
285
-				'type' => 'value'));
286
-		$this->Controller->passedArgs = array(
287
-			'views' => '0');
288
-		$this->Controller->beforeFilter();
289
-
290
-		$this->Controller->Prg->presetForm('Post');
291
-		$expected = array(
292
-			'Post' => array(
293
-				'views' => '0'));
294
-		$this->assertEquals($expected, $this->Controller->request->data);
295
-		$this->assertTrue($this->Controller->Prg->isSearch);
296
-		$this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
297
-	}
281
+    public function testPresetFormWithIntegerField() {
282
+        $this->Controller->presetVars = array(
283
+            array(
284
+                'field' => 'views',
285
+                'type' => 'value'));
286
+        $this->Controller->passedArgs = array(
287
+            'views' => '0');
288
+        $this->Controller->beforeFilter();
289
+
290
+        $this->Controller->Prg->presetForm('Post');
291
+        $expected = array(
292
+            'Post' => array(
293
+                'views' => '0'));
294
+        $this->assertEquals($expected, $this->Controller->request->data);
295
+        $this->assertTrue($this->Controller->Prg->isSearch);
296
+        $this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
297
+    }
298 298
 
299 299
 /**
300 300
  * testFixFormValues
301 301
  *
302 302
  * @return void
303 303
  */
304
-	public function testSerializeParams() {
305
-		$this->Controller->presetVars = array(
306
-			array(
307
-				'field' => 'options',
308
-				'type' => 'checkbox'));
304
+    public function testSerializeParams() {
305
+        $this->Controller->presetVars = array(
306
+            array(
307
+                'field' => 'options',
308
+                'type' => 'checkbox'));
309 309
 
310
-		$testData = array(
311
-			'options' => array(
312
-				0 => 'test1', 1 => 'test2', 2 => 'test3'));
310
+        $testData = array(
311
+            'options' => array(
312
+                0 => 'test1', 1 => 'test2', 2 => 'test3'));
313 313
 
314
-		$result = $this->Controller->Prg->serializeParams($testData);
315
-		$this->assertEquals(array('options' => 'test1|test2|test3'), $result);
314
+        $result = $this->Controller->Prg->serializeParams($testData);
315
+        $this->assertEquals(array('options' => 'test1|test2|test3'), $result);
316 316
 
317
-		$testData = array('options' => '');
317
+        $testData = array('options' => '');
318 318
 
319
-		$result = $this->Controller->Prg->serializeParams($testData);
320
-		$this->assertEquals(array('options' => ''), $result);
319
+        $result = $this->Controller->Prg->serializeParams($testData);
320
+        $this->assertEquals(array('options' => ''), $result);
321 321
 
322
-		$testData = array();
323
-		$result = $this->Controller->Prg->serializeParams($testData);
324
-		$this->assertEquals(array('options' => ''), $result);
325
-	}
322
+        $testData = array();
323
+        $result = $this->Controller->Prg->serializeParams($testData);
324
+        $this->assertEquals(array('options' => ''), $result);
325
+    }
326 326
 
327 327
 /**
328 328
  * testConnectNamed
329 329
  *
330 330
  * @return void
331 331
  */
332
-	public function testConnectNamed() {
333
-		$this->Controller->passedArgs = array(
334
-			'title' => 'test');
335
-		$this->assertNull($this->Controller->Prg->connectNamed());
336
-		$this->assertNull($this->Controller->Prg->connectNamed(1));
337
-	}
332
+    public function testConnectNamed() {
333
+        $this->Controller->passedArgs = array(
334
+            'title' => 'test');
335
+        $this->assertNull($this->Controller->Prg->connectNamed());
336
+        $this->assertNull($this->Controller->Prg->connectNamed(1));
337
+    }
338 338
 
339 339
 /**
340 340
  * testExclude
341 341
  *
342 342
  * @return void
343 343
  */
344
-	public function testExclude() {
345
-		$this->Controller->request->params['named'] = array();
344
+    public function testExclude() {
345
+        $this->Controller->request->params['named'] = array();
346 346
 
347
-		$array = array('foo' => 'test', 'bar' => 'test', 'test' => 'test');
348
-		$exclude = array('bar', 'test');
349
-		$result = $this->Controller->Prg->exclude($array, $exclude);
350
-		$this->assertEquals(array('foo' => 'test'), $result);
347
+        $array = array('foo' => 'test', 'bar' => 'test', 'test' => 'test');
348
+        $exclude = array('bar', 'test');
349
+        $result = $this->Controller->Prg->exclude($array, $exclude);
350
+        $this->assertEquals(array('foo' => 'test'), $result);
351 351
 
352
-		$array = array('foo' => 'test', 'bar' => 'test', 'test' => 'test', 0 => 'passed', 1 => 'passed_again');
353
-		$exclude = array('bar', 'test');
354
-		$result = $this->Controller->Prg->exclude($array, $exclude);
355
-		$this->assertEquals(array('foo' => 'test', 0 => 'passed', 1 => 'passed_again'), $result);
356
-	}
352
+        $array = array('foo' => 'test', 'bar' => 'test', 'test' => 'test', 0 => 'passed', 1 => 'passed_again');
353
+        $exclude = array('bar', 'test');
354
+        $result = $this->Controller->Prg->exclude($array, $exclude);
355
+        $this->assertEquals(array('foo' => 'test', 0 => 'passed', 1 => 'passed_again'), $result);
356
+    }
357 357
 
358 358
 /**
359 359
  * testCommonProcess
360 360
  *
361 361
  * @return void
362 362
  */
363
-	public function testCommonProcess() {
364
-		$this->Controller->request->params['named'] = array();
365
-		$this->Controller->presetVars = array();
366
-		$this->Controller->action = 'search';
367
-		$this->Controller->request->data = array(
368
-			'Post' => array(
369
-				'title' => 'test'));
370
-		$this->Controller->Prg->commonProcess('Post', array(
371
-			'form' => 'Post',
372
-			'modelMethod' => false));
373
-		$expected = array(
374
-			'title' => 'test',
375
-			'action' => 'search');
376
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
377
-
378
-		$this->Controller->Prg->commonProcess(null, array(
379
-			'modelMethod' => false));
380
-		$expected = array(
381
-			'title' => 'test',
382
-			'action' => 'search');
383
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
384
-
385
-		$this->Controller->Post->filterArgs = array(
386
-			array('name' => 'title', 'type' => 'value'));
387
-		$this->Controller->Prg->commonProcess('Post');
388
-		$expected = array(
389
-			'title' => 'test',
390
-			'action' => 'search');
391
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
392
-	}
363
+    public function testCommonProcess() {
364
+        $this->Controller->request->params['named'] = array();
365
+        $this->Controller->presetVars = array();
366
+        $this->Controller->action = 'search';
367
+        $this->Controller->request->data = array(
368
+            'Post' => array(
369
+                'title' => 'test'));
370
+        $this->Controller->Prg->commonProcess('Post', array(
371
+            'form' => 'Post',
372
+            'modelMethod' => false));
373
+        $expected = array(
374
+            'title' => 'test',
375
+            'action' => 'search');
376
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
377
+
378
+        $this->Controller->Prg->commonProcess(null, array(
379
+            'modelMethod' => false));
380
+        $expected = array(
381
+            'title' => 'test',
382
+            'action' => 'search');
383
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
384
+
385
+        $this->Controller->Post->filterArgs = array(
386
+            array('name' => 'title', 'type' => 'value'));
387
+        $this->Controller->Prg->commonProcess('Post');
388
+        $expected = array(
389
+            'title' => 'test',
390
+            'action' => 'search');
391
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
392
+    }
393 393
 
394 394
 /**
395 395
  * testCommonProcessWithPresetVarsNotEmpty
@@ -397,567 +397,567 @@  discard block
 block discarded – undo
397 397
  *
398 398
  * @return void
399 399
  */
400
-	public function testCommonProcessWithPresetVarsNotEmpty() {
401
-		$this->Controller->request->params['named'] = array();
402
-		$this->Controller->presetVars = array('title' => array('type' => 'value'));
400
+    public function testCommonProcessWithPresetVarsNotEmpty() {
401
+        $this->Controller->request->params['named'] = array();
402
+        $this->Controller->presetVars = array('title' => array('type' => 'value'));
403 403
 
404
-		$this->Controller->action = 'search';
405
-		$this->Controller->request->data = array(
406
-			'Post' => array(
407
-				'title' => 'test'));
404
+        $this->Controller->action = 'search';
405
+        $this->Controller->request->data = array(
406
+            'Post' => array(
407
+                'title' => 'test'));
408 408
 
409
-		$this->Controller->Prg->commonProcess('Post');
410
-		$expected = array(
411
-			'title' => 'test',
412
-			'action' => 'search');
413
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
414
-	}
409
+        $this->Controller->Prg->commonProcess('Post');
410
+        $expected = array(
411
+            'title' => 'test',
412
+            'action' => 'search');
413
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
414
+    }
415 415
 
416 416
 /**
417 417
  * testCommonProcessExtraParams
418 418
  *
419 419
  * @return void
420 420
  */
421
-	public function testCommonProcessAllowedParams() {
422
-		$this->Controller->request->params = array_merge($this->Controller->request->params, array(
423
-			'named' => array(),
424
-			'lang' => 'en',
425
-			));
426
-
427
-		$this->Controller->presetVars = array();
428
-		$this->Controller->action = 'search';
429
-		$this->Controller->request->data = array(
430
-			'Post' => array(
431
-				'title' => 'test'));
432
-
433
-		$this->Controller->Prg->commonProcess('Post', array(
434
-			'form' => 'Post',
435
-			'modelMethod' => false,
436
-			'allowedParams' => array('lang')));
437
-		$expected = array(
438
-			'title' => 'test',
439
-			'action' => 'search',
440
-			'lang' => 'en');
441
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
442
-	}
421
+    public function testCommonProcessAllowedParams() {
422
+        $this->Controller->request->params = array_merge($this->Controller->request->params, array(
423
+            'named' => array(),
424
+            'lang' => 'en',
425
+            ));
426
+
427
+        $this->Controller->presetVars = array();
428
+        $this->Controller->action = 'search';
429
+        $this->Controller->request->data = array(
430
+            'Post' => array(
431
+                'title' => 'test'));
432
+
433
+        $this->Controller->Prg->commonProcess('Post', array(
434
+            'form' => 'Post',
435
+            'modelMethod' => false,
436
+            'allowedParams' => array('lang')));
437
+        $expected = array(
438
+            'title' => 'test',
439
+            'action' => 'search',
440
+            'lang' => 'en');
441
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
442
+    }
443 443
 
444 444
 /**
445 445
  * testCommonProcessFilterEmpty
446 446
  *
447 447
  * @return void
448 448
  */
449
-	public function testCommonProcessResetNamed() {
450
-		$this->Controller->request->params = array_merge($this->Controller->request->params, array(
451
-			'named' => array('page' => 2, 'sort' => 'name', 'direction' => 'asc'),
452
-			'lang' => 'en',
453
-			));
454
-
455
-		$this->Controller->presetVars = array();
456
-		$this->Controller->action = 'search';
457
-		$this->Controller->request->data = array(
458
-			'Post' => array(
459
-				'title' => 'test',
460
-				'foo' => '',
461
-				'bar' => ''));
462
-
463
-		$this->Controller->Prg->commonProcess('Post', array(
464
-			'form' => 'Post',
465
-			'modelMethod' => false,
466
-			'allowedParams' => array('lang')));
467
-		$expected = array(
468
-			'sort' => 'name',
469
-			'direction' => 'asc',
470
-			'title' => 'test',
471
-			'foo' => '',
472
-			'bar' => '',
473
-			'action' => 'search',
474
-			'lang' => 'en');
475
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
476
-	}
449
+    public function testCommonProcessResetNamed() {
450
+        $this->Controller->request->params = array_merge($this->Controller->request->params, array(
451
+            'named' => array('page' => 2, 'sort' => 'name', 'direction' => 'asc'),
452
+            'lang' => 'en',
453
+            ));
454
+
455
+        $this->Controller->presetVars = array();
456
+        $this->Controller->action = 'search';
457
+        $this->Controller->request->data = array(
458
+            'Post' => array(
459
+                'title' => 'test',
460
+                'foo' => '',
461
+                'bar' => ''));
462
+
463
+        $this->Controller->Prg->commonProcess('Post', array(
464
+            'form' => 'Post',
465
+            'modelMethod' => false,
466
+            'allowedParams' => array('lang')));
467
+        $expected = array(
468
+            'sort' => 'name',
469
+            'direction' => 'asc',
470
+            'title' => 'test',
471
+            'foo' => '',
472
+            'bar' => '',
473
+            'action' => 'search',
474
+            'lang' => 'en');
475
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
476
+    }
477 477
 
478 478
 /**
479 479
  * testCommonProcessFilterEmpty
480 480
  *
481 481
  * @return void
482 482
  */
483
-	public function testCommonProcessFilterEmpty() {
484
-		$this->Controller->request->params = array_merge($this->Controller->request->params, array(
485
-			'named' => array(),
486
-			'lang' => 'en',
487
-			));
488
-
489
-		$this->Controller->presetVars = array();
490
-		$this->Controller->action = 'search';
491
-		$this->Controller->request->data = array(
492
-			'Post' => array(
493
-				'title' => 'test',
494
-				'foo' => '',
495
-				'bar' => ''));
496
-
497
-		$this->Controller->Prg->commonProcess('Post', array(
498
-			'form' => 'Post',
499
-			'modelMethod' => false,
500
-			'filterEmpty' => true,
501
-			'allowedParams' => array('lang')));
502
-		$expected = array(
503
-			'title' => 'test',
504
-			'action' => 'search',
505
-			'lang' => 'en');
506
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
507
-	}
483
+    public function testCommonProcessFilterEmpty() {
484
+        $this->Controller->request->params = array_merge($this->Controller->request->params, array(
485
+            'named' => array(),
486
+            'lang' => 'en',
487
+            ));
488
+
489
+        $this->Controller->presetVars = array();
490
+        $this->Controller->action = 'search';
491
+        $this->Controller->request->data = array(
492
+            'Post' => array(
493
+                'title' => 'test',
494
+                'foo' => '',
495
+                'bar' => ''));
496
+
497
+        $this->Controller->Prg->commonProcess('Post', array(
498
+            'form' => 'Post',
499
+            'modelMethod' => false,
500
+            'filterEmpty' => true,
501
+            'allowedParams' => array('lang')));
502
+        $expected = array(
503
+            'title' => 'test',
504
+            'action' => 'search',
505
+            'lang' => 'en');
506
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
507
+    }
508 508
 
509 509
 /**
510 510
  * testCommonProcessSpecialChars
511 511
  *
512 512
  * @return void
513 513
  */
514
-	public function testCommonProcessSpecialChars() {
515
-		$this->Controller->request->params = array_merge($this->Controller->request->params, array(
516
-			'named' => array(),
517
-			'lang' => 'en',
518
-			));
519
-
520
-		$this->Controller->presetVars = array();
521
-		$this->Controller->action = 'search';
522
-		$this->Controller->request->data = array(
523
-			'Post' => array(
524
-				'title' => 'test/slashes?!',
525
-				'foo' => '',
526
-				'bar' => ''));
527
-
528
-		$this->Controller->Prg->commonProcess('Post', array(
529
-			'form' => 'Post',
530
-			'modelMethod' => false,
531
-			'filterEmpty' => true,
532
-			'allowedParams' => array('lang')));
533
-		$expected = array(
534
-			'title' => 'test/slashes?!',
535
-			'action' => 'search',
536
-			'lang' => 'en');
537
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
538
-
539
-		$url = Router::url($this->Controller->redirectUrl);
540
-		$expected = '/search/title:test%2Fslashes%3F%21/lang:en';
541
-		$this->assertEquals($expected, $url);
542
-	}
514
+    public function testCommonProcessSpecialChars() {
515
+        $this->Controller->request->params = array_merge($this->Controller->request->params, array(
516
+            'named' => array(),
517
+            'lang' => 'en',
518
+            ));
519
+
520
+        $this->Controller->presetVars = array();
521
+        $this->Controller->action = 'search';
522
+        $this->Controller->request->data = array(
523
+            'Post' => array(
524
+                'title' => 'test/slashes?!',
525
+                'foo' => '',
526
+                'bar' => ''));
527
+
528
+        $this->Controller->Prg->commonProcess('Post', array(
529
+            'form' => 'Post',
530
+            'modelMethod' => false,
531
+            'filterEmpty' => true,
532
+            'allowedParams' => array('lang')));
533
+        $expected = array(
534
+            'title' => 'test/slashes?!',
535
+            'action' => 'search',
536
+            'lang' => 'en');
537
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
538
+
539
+        $url = Router::url($this->Controller->redirectUrl);
540
+        $expected = '/search/title:test%2Fslashes%3F%21/lang:en';
541
+        $this->assertEquals($expected, $url);
542
+    }
543 543
 
544 544
 /**
545 545
  * testCommonProcessQuerystring
546 546
  *
547 547
  * @return void
548 548
  */
549
-	public function testCommonProcessQuerystring() {
550
-		$this->Controller->request->params = array_merge($this->Controller->request->params, array(
551
-			'named' => array(),
552
-			'lang' => 'en',
553
-			));
554
-
555
-		$this->Controller->presetVars = array();
556
-		$this->Controller->action = 'search';
557
-		$this->Controller->request->data = array(
558
-			'Post' => array(
559
-				'title' => 'test',
560
-				'foo' => '',
561
-				'bar' => ''));
562
-
563
-		$this->Controller->Prg->commonProcess('Post', array(
564
-			'form' => 'Post',
565
-			'modelMethod' => false,
566
-			'paramType' => 'querystring',
567
-			'allowedParams' => array('lang')));
568
-		$expected = array(
569
-			'?' => array('title' => 'test', 'foo' => '', 'bar' => ''),
570
-			'action' => 'search',
571
-			'lang' => 'en');
572
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
573
-	}
549
+    public function testCommonProcessQuerystring() {
550
+        $this->Controller->request->params = array_merge($this->Controller->request->params, array(
551
+            'named' => array(),
552
+            'lang' => 'en',
553
+            ));
554
+
555
+        $this->Controller->presetVars = array();
556
+        $this->Controller->action = 'search';
557
+        $this->Controller->request->data = array(
558
+            'Post' => array(
559
+                'title' => 'test',
560
+                'foo' => '',
561
+                'bar' => ''));
562
+
563
+        $this->Controller->Prg->commonProcess('Post', array(
564
+            'form' => 'Post',
565
+            'modelMethod' => false,
566
+            'paramType' => 'querystring',
567
+            'allowedParams' => array('lang')));
568
+        $expected = array(
569
+            '?' => array('title' => 'test', 'foo' => '', 'bar' => ''),
570
+            'action' => 'search',
571
+            'lang' => 'en');
572
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
573
+    }
574 574
 
575 575
 /**
576 576
  * testCommonProcessQuerystringSpecialChars
577 577
  *
578 578
  * @return void
579 579
  */
580
-	public function testCommonProcessQuerystringSpecialChars() {
581
-		$this->Controller->request->params = array_merge($this->Controller->request->params, array(
582
-			'named' => array(),
583
-			'lang' => 'en',
584
-			));
585
-
586
-		$this->Controller->presetVars = array();
587
-		$this->Controller->action = 'search';
588
-		$this->Controller->request->data = array(
589
-			'Post' => array(
590
-				'title' => 'test/slashes?!',
591
-				'foo' => '',
592
-				'bar' => ''));
593
-
594
-		$this->Controller->Prg->commonProcess('Post', array(
595
-			'form' => 'Post',
596
-			'modelMethod' => false,
597
-			'filterEmpty' => true,
598
-			'paramType' => 'querystring',
599
-			'allowedParams' => array('lang')));
600
-		$expected = array(
601
-			'?' => array('title' => 'test/slashes?!'),
602
-			'action' => 'search',
603
-			'lang' => 'en');
604
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
605
-
606
-		$url = Router::url($this->Controller->redirectUrl);
607
-		$expected = '/search/lang:en?title=test%2Fslashes%3F%21';
608
-		$this->assertEquals($expected, $url);
609
-	}
580
+    public function testCommonProcessQuerystringSpecialChars() {
581
+        $this->Controller->request->params = array_merge($this->Controller->request->params, array(
582
+            'named' => array(),
583
+            'lang' => 'en',
584
+            ));
585
+
586
+        $this->Controller->presetVars = array();
587
+        $this->Controller->action = 'search';
588
+        $this->Controller->request->data = array(
589
+            'Post' => array(
590
+                'title' => 'test/slashes?!',
591
+                'foo' => '',
592
+                'bar' => ''));
593
+
594
+        $this->Controller->Prg->commonProcess('Post', array(
595
+            'form' => 'Post',
596
+            'modelMethod' => false,
597
+            'filterEmpty' => true,
598
+            'paramType' => 'querystring',
599
+            'allowedParams' => array('lang')));
600
+        $expected = array(
601
+            '?' => array('title' => 'test/slashes?!'),
602
+            'action' => 'search',
603
+            'lang' => 'en');
604
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
605
+
606
+        $url = Router::url($this->Controller->redirectUrl);
607
+        $expected = '/search/lang:en?title=test%2Fslashes%3F%21';
608
+        $this->assertEquals($expected, $url);
609
+    }
610 610
 
611 611
 /**
612 612
  * testCommonProcessQuerystringPagination
613 613
  *
614 614
  * @return void
615 615
  */
616
-	public function testCommonProcessQuerystringPagination() {
617
-		$this->Controller->request->query = array(
618
-			'sort' => 'created',
619
-			'direction' => 'asc',
620
-			'page' => 3,
621
-		);
622
-		$this->Controller->request->params = array_merge($this->Controller->request->params, array(
623
-			'named' => array(),
624
-			'lang' => 'en',
625
-			));
626
-
627
-		$this->Controller->presetVars = array();
628
-		$this->Controller->action = 'search';
629
-		$this->Controller->request->data = array(
630
-			'Post' => array(
631
-				'title' => 'test',
632
-				'foo' => '',
633
-				'bar' => ''));
634
-
635
-		$this->Controller->Prg->commonProcess('Post', array(
636
-			'form' => 'Post',
637
-			'modelMethod' => false,
638
-			'paramType' => 'querystring',
639
-			'allowedParams' => array('lang')));
640
-		$expected = array(
641
-			'?' => array('title' => 'test', 'foo' => '', 'bar' => '', 'sort' => 'created', 'direction' => 'asc'),
642
-			'action' => 'search',
643
-			'lang' => 'en');
644
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
645
-	}
616
+    public function testCommonProcessQuerystringPagination() {
617
+        $this->Controller->request->query = array(
618
+            'sort' => 'created',
619
+            'direction' => 'asc',
620
+            'page' => 3,
621
+        );
622
+        $this->Controller->request->params = array_merge($this->Controller->request->params, array(
623
+            'named' => array(),
624
+            'lang' => 'en',
625
+            ));
626
+
627
+        $this->Controller->presetVars = array();
628
+        $this->Controller->action = 'search';
629
+        $this->Controller->request->data = array(
630
+            'Post' => array(
631
+                'title' => 'test',
632
+                'foo' => '',
633
+                'bar' => ''));
634
+
635
+        $this->Controller->Prg->commonProcess('Post', array(
636
+            'form' => 'Post',
637
+            'modelMethod' => false,
638
+            'paramType' => 'querystring',
639
+            'allowedParams' => array('lang')));
640
+        $expected = array(
641
+            '?' => array('title' => 'test', 'foo' => '', 'bar' => '', 'sort' => 'created', 'direction' => 'asc'),
642
+            'action' => 'search',
643
+            'lang' => 'en');
644
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
645
+    }
646 646
 
647 647
 /**
648 648
  * testCommonProcessQuerystringFilterEmpty
649 649
  *
650 650
  * @return void
651 651
  */
652
-	public function testCommonProcessQuerystringFilterEmpty() {
653
-		$this->Controller->request->params = array_merge($this->Controller->request->params, array(
654
-			'named' => array(),
655
-			'lang' => 'en',
656
-			));
657
-
658
-		$this->Controller->presetVars = array();
659
-		$this->Controller->action = 'search';
660
-		$this->Controller->request->data = array(
661
-			'Post' => array(
662
-				'title' => 'test',
663
-				'foo' => '',
664
-				'bar' => ''));
665
-
666
-		$this->Controller->Prg->commonProcess('Post', array(
667
-			'form' => 'Post',
668
-			'modelMethod' => false,
669
-			'filterEmpty' => true,
670
-			'paramType' => 'querystring',
671
-			'allowedParams' => array('lang')));
672
-		$expected = array(
673
-			'?' => array('title' => 'test'),
674
-			'action' => 'search',
675
-			'lang' => 'en');
676
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
677
-	}
652
+    public function testCommonProcessQuerystringFilterEmpty() {
653
+        $this->Controller->request->params = array_merge($this->Controller->request->params, array(
654
+            'named' => array(),
655
+            'lang' => 'en',
656
+            ));
657
+
658
+        $this->Controller->presetVars = array();
659
+        $this->Controller->action = 'search';
660
+        $this->Controller->request->data = array(
661
+            'Post' => array(
662
+                'title' => 'test',
663
+                'foo' => '',
664
+                'bar' => ''));
665
+
666
+        $this->Controller->Prg->commonProcess('Post', array(
667
+            'form' => 'Post',
668
+            'modelMethod' => false,
669
+            'filterEmpty' => true,
670
+            'paramType' => 'querystring',
671
+            'allowedParams' => array('lang')));
672
+        $expected = array(
673
+            '?' => array('title' => 'test'),
674
+            'action' => 'search',
675
+            'lang' => 'en');
676
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
677
+    }
678 678
 
679 679
 /**
680 680
  * testCommonProcessGet
681 681
  *
682 682
  * @return void
683 683
  */
684
-	public function testCommonProcessGet() {
685
-		$this->Controller->action = 'search';
686
-		$this->Controller->presetVars = array(
687
-			array('field' => 'title', 'type' => 'value'));
688
-		$this->Controller->request->data = array();
689
-		$this->Controller->Post->filterArgs = array(
690
-			array('name' => 'title', 'type' => 'value'));
691
-		$this->Controller->request->params['named'] = array('title' => 'test');
692
-		$this->Controller->passedArgs = array_merge($this->Controller->request->params['named'], $this->Controller->request->params['pass']);
693
-		$this->Controller->Prg->commonProcess('Post');
694
-
695
-		$this->assertTrue($this->Controller->Prg->isSearch);
696
-		$expected = array('Post' => array('title' => 'test'));
697
-		$this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
698
-		$this->assertEquals($expected, $this->Controller->request->data);
699
-	}
700
-
701
-	public function testCommonProcessGetWithStringKeys() {
702
-		$this->Controller->action = 'search';
703
-		$this->Controller->presetVars = array(
704
-			'title' => array('type' => 'value'));
705
-		$this->Controller->Post->filterArgs = array(
706
-			'title' => array('type' => 'value'));
707
-
708
-		$this->Controller->Prg->__construct($this->Controller->Components, array());
709
-		$this->Controller->Prg->initialize($this->Controller);
710
-		$this->Controller->request->data = array();
711
-
712
-		$this->Controller->request->params['named'] = array('title' => 'test');
713
-		$this->Controller->passedArgs = array_merge($this->Controller->request->params['named'], $this->Controller->request->params['pass']);
714
-		$this->Controller->Prg->commonProcess('Post');
715
-		$expected = array('Post' => array('title' => 'test'));
716
-		$this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
717
-		$this->assertEquals($expected, $this->Controller->request->data);
718
-	}
719
-
720
-	public function testCommonProcessGetWithStringKeysShort() {
721
-		$this->Controller->action = 'search';
722
-		$this->Controller->presetVars = array(
723
-			'title' => true);
724
-		$this->Controller->Post->filterArgs = array(
725
-			'title' => array('type' => 'value'));
726
-
727
-		$this->Controller->Prg->__construct($this->Controller->Components, array());
728
-		$this->Controller->Prg->initialize($this->Controller);
729
-		$this->Controller->request->data = array();
730
-
731
-		$this->Controller->request->params['named'] = array('title' => 'test');
732
-		$this->Controller->passedArgs = array_merge($this->Controller->request->params['named'], $this->Controller->request->params['pass']);
733
-		$this->Controller->Prg->commonProcess('Post');
734
-		$expected = array('Post' => array('title' => 'test'));
735
-		$this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
736
-		$this->assertEquals($expected, $this->Controller->request->data);
737
-	}
684
+    public function testCommonProcessGet() {
685
+        $this->Controller->action = 'search';
686
+        $this->Controller->presetVars = array(
687
+            array('field' => 'title', 'type' => 'value'));
688
+        $this->Controller->request->data = array();
689
+        $this->Controller->Post->filterArgs = array(
690
+            array('name' => 'title', 'type' => 'value'));
691
+        $this->Controller->request->params['named'] = array('title' => 'test');
692
+        $this->Controller->passedArgs = array_merge($this->Controller->request->params['named'], $this->Controller->request->params['pass']);
693
+        $this->Controller->Prg->commonProcess('Post');
694
+
695
+        $this->assertTrue($this->Controller->Prg->isSearch);
696
+        $expected = array('Post' => array('title' => 'test'));
697
+        $this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
698
+        $this->assertEquals($expected, $this->Controller->request->data);
699
+    }
700
+
701
+    public function testCommonProcessGetWithStringKeys() {
702
+        $this->Controller->action = 'search';
703
+        $this->Controller->presetVars = array(
704
+            'title' => array('type' => 'value'));
705
+        $this->Controller->Post->filterArgs = array(
706
+            'title' => array('type' => 'value'));
707
+
708
+        $this->Controller->Prg->__construct($this->Controller->Components, array());
709
+        $this->Controller->Prg->initialize($this->Controller);
710
+        $this->Controller->request->data = array();
711
+
712
+        $this->Controller->request->params['named'] = array('title' => 'test');
713
+        $this->Controller->passedArgs = array_merge($this->Controller->request->params['named'], $this->Controller->request->params['pass']);
714
+        $this->Controller->Prg->commonProcess('Post');
715
+        $expected = array('Post' => array('title' => 'test'));
716
+        $this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
717
+        $this->assertEquals($expected, $this->Controller->request->data);
718
+    }
719
+
720
+    public function testCommonProcessGetWithStringKeysShort() {
721
+        $this->Controller->action = 'search';
722
+        $this->Controller->presetVars = array(
723
+            'title' => true);
724
+        $this->Controller->Post->filterArgs = array(
725
+            'title' => array('type' => 'value'));
726
+
727
+        $this->Controller->Prg->__construct($this->Controller->Components, array());
728
+        $this->Controller->Prg->initialize($this->Controller);
729
+        $this->Controller->request->data = array();
730
+
731
+        $this->Controller->request->params['named'] = array('title' => 'test');
732
+        $this->Controller->passedArgs = array_merge($this->Controller->request->params['named'], $this->Controller->request->params['pass']);
733
+        $this->Controller->Prg->commonProcess('Post');
734
+        $expected = array('Post' => array('title' => 'test'));
735
+        $this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
736
+        $this->assertEquals($expected, $this->Controller->request->data);
737
+    }
738 738
 
739 739
 /**
740 740
  * testSerializeParamsWithEncoding
741 741
  *
742 742
  * @return void
743 743
  */
744
-	public function testSerializeParamsWithEncoding() {
745
-		$this->Controller->action = 'search';
746
-		$this->Controller->presetVars = array(
747
-			array('field' => 'title', 'type' => 'value', 'encode' => true));
748
-		$this->Controller->request->data = array();
749
-		$this->Controller->Post->filterArgs = array(
750
-			array('name' => 'title', 'type' => 'value'));
744
+    public function testSerializeParamsWithEncoding() {
745
+        $this->Controller->action = 'search';
746
+        $this->Controller->presetVars = array(
747
+            array('field' => 'title', 'type' => 'value', 'encode' => true));
748
+        $this->Controller->request->data = array();
749
+        $this->Controller->Post->filterArgs = array(
750
+            array('name' => 'title', 'type' => 'value'));
751 751
 
752
-		$this->Controller->Prg->encode = true;
753
-		$test = array('title' => 'Something new');
754
-		$result = $this->Controller->Prg->serializeParams($test);
755
-		$this->assertEquals($this->_urlEncode('Something new'), $result['title']);
752
+        $this->Controller->Prg->encode = true;
753
+        $test = array('title' => 'Something new');
754
+        $result = $this->Controller->Prg->serializeParams($test);
755
+        $this->assertEquals($this->_urlEncode('Something new'), $result['title']);
756 756
 
757
-		$test = array('title' => 'ef?');
758
-		$result = $this->Controller->Prg->serializeParams($test);
759
-		$this->assertEquals($this->_urlEncode('ef?'), $result['title']);
760
-	}
757
+        $test = array('title' => 'ef?');
758
+        $result = $this->Controller->Prg->serializeParams($test);
759
+        $this->assertEquals($this->_urlEncode('ef?'), $result['title']);
760
+    }
761 761
 
762 762
 /**
763 763
  * replace the base64encoded values that could harm the url (/ and =) with harmless characters
764 764
  *
765 765
  * @return string
766 766
  */
767
-	protected function _urlEncode($str) {
768
-		return str_replace(array('/', '='), array('-', '_'), base64_encode($str));
769
-	}
767
+    protected function _urlEncode($str) {
768
+        return str_replace(array('/', '='), array('-', '_'), base64_encode($str));
769
+    }
770 770
 
771 771
 /**
772 772
  * testSerializeParamsWithEncoding
773 773
  *
774 774
  * @return void
775 775
  */
776
-	public function testSerializeParamsWithEncodingAndSpace() {
777
-		$this->Controller->action = 'search';
778
-		$this->Controller->presetVars = array(
779
-			array('field' => 'title', 'type' => 'value', 'encode' => true));
780
-		$this->Controller->request->data = array();
781
-		$this->Controller->Post->filterArgs = array(
782
-			array('name' => 'title', 'type' => 'value'));
776
+    public function testSerializeParamsWithEncodingAndSpace() {
777
+        $this->Controller->action = 'search';
778
+        $this->Controller->presetVars = array(
779
+            array('field' => 'title', 'type' => 'value', 'encode' => true));
780
+        $this->Controller->request->data = array();
781
+        $this->Controller->Post->filterArgs = array(
782
+            array('name' => 'title', 'type' => 'value'));
783 783
 
784
-		$this->Controller->Prg->encode = true;
785
-		$testData = $test = array('title' => 'Something new');
786
-		$result = $this->Controller->Prg->serializeParams($test);
787
-		$this->assertEquals($this->_urlEncode('Something new'), $result['title']);
784
+        $this->Controller->Prg->encode = true;
785
+        $testData = $test = array('title' => 'Something new');
786
+        $result = $this->Controller->Prg->serializeParams($test);
787
+        $this->assertEquals($this->_urlEncode('Something new'), $result['title']);
788 788
 
789
-		$this->Controller->passedArgs = $result;
790
-		$this->Controller->Prg->presetForm('Post');
791
-		$expected = array('Post' => $testData);
792
-		$this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
793
-		$this->assertEquals($expected, $this->Controller->request->data);
794
-	}
789
+        $this->Controller->passedArgs = $result;
790
+        $this->Controller->Prg->presetForm('Post');
791
+        $expected = array('Post' => $testData);
792
+        $this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
793
+        $this->assertEquals($expected, $this->Controller->request->data);
794
+    }
795 795
 
796 796
 /**
797 797
  * testPresetFormWithEncodedParams
798 798
  *
799 799
  * @return void
800 800
  */
801
-	public function testPresetFormWithEncodedParams() {
802
-		$this->Controller->presetVars = array(
803
-			array(
804
-				'field' => 'title',
805
-				'type' => 'value'),
806
-			array(
807
-				'field' => 'checkbox',
808
-				'type' => 'checkbox'),
809
-			array(
810
-				'field' => 'lookup',
811
-				'type' => 'lookup',
812
-				'formField' => 'lookup_input',
813
-				'modelField' => 'title',
814
-				'model' => 'Post'));
815
-		$this->Controller->passedArgs = array(
816
-			'title' => $this->_urlEncode('test'),
817
-			'checkbox' => $this->_urlEncode('test|test2|test3'),
818
-			'lookup' => $this->_urlEncode('1'));
819
-
820
-		$this->Controller->beforeFilter();
821
-
822
-		$this->Controller->Prg->encode = true;
823
-		$this->Controller->Prg->presetForm('Post');
824
-		$expected = array(
825
-			'Post' => array(
826
-				'title' => 'test',
827
-				'checkbox' => array(
828
-					0 => 'test',
829
-					1 => 'test2',
830
-					2 => 'test3'),
831
-				'lookup' => 1,
832
-				'lookup_input' => 'First Post'));
833
-		$this->assertEquals($expected, $this->Controller->request->data);
834
-		$this->assertTrue($this->Controller->Prg->isSearch);
835
-		$this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
836
-	}
801
+    public function testPresetFormWithEncodedParams() {
802
+        $this->Controller->presetVars = array(
803
+            array(
804
+                'field' => 'title',
805
+                'type' => 'value'),
806
+            array(
807
+                'field' => 'checkbox',
808
+                'type' => 'checkbox'),
809
+            array(
810
+                'field' => 'lookup',
811
+                'type' => 'lookup',
812
+                'formField' => 'lookup_input',
813
+                'modelField' => 'title',
814
+                'model' => 'Post'));
815
+        $this->Controller->passedArgs = array(
816
+            'title' => $this->_urlEncode('test'),
817
+            'checkbox' => $this->_urlEncode('test|test2|test3'),
818
+            'lookup' => $this->_urlEncode('1'));
819
+
820
+        $this->Controller->beforeFilter();
821
+
822
+        $this->Controller->Prg->encode = true;
823
+        $this->Controller->Prg->presetForm('Post');
824
+        $expected = array(
825
+            'Post' => array(
826
+                'title' => 'test',
827
+                'checkbox' => array(
828
+                    0 => 'test',
829
+                    1 => 'test2',
830
+                    2 => 'test3'),
831
+                'lookup' => 1,
832
+                'lookup_input' => 'First Post'));
833
+        $this->assertEquals($expected, $this->Controller->request->data);
834
+        $this->assertTrue($this->Controller->Prg->isSearch);
835
+        $this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
836
+    }
837 837
 
838 838
 /**
839 839
  * testCommonProcessGetWithEmptyValue
840 840
  *
841 841
  * @return void
842 842
  */
843
-	public function testCommonProcessGetWithEmptyValue() {
844
-		$this->Controller->request->params = array_merge($this->Controller->request->params, array(
845
-			'named' => array(),
846
-			'category_id' => '0',
847
-			));
848
-
849
-		$this->Controller->presetVars = array(
850
-			array(
851
-				'field' => 'category_id',
852
-				'name' => 'category_id',
853
-				'type' => 'value',
854
-				'allowEmpty' => true,
855
-				'emptyValue' => '0',
856
-			),
857
-			array(
858
-				'field' => 'checkbox',
859
-				'name' => 'checkbox',
860
-				'type' => 'checkbox'
861
-			),
862
-		);
863
-		$this->Controller->action = 'search';
864
-		$this->Controller->request->data = array(
865
-			'Post' => array(
866
-				'category_id' => '0',
867
-				'foo' => ''));
868
-
869
-		$this->Controller->Prg->commonProcess('Post', array(
870
-			'form' => 'Post',
871
-			'modelMethod' => false,
872
-			'filterEmpty' => true));
873
-		$expected = array(
874
-			'action' => 'search',
875
-			'category_id' => '');
876
-		$this->assertEquals($expected, $this->Controller->redirectUrl);
877
-	}
843
+    public function testCommonProcessGetWithEmptyValue() {
844
+        $this->Controller->request->params = array_merge($this->Controller->request->params, array(
845
+            'named' => array(),
846
+            'category_id' => '0',
847
+            ));
848
+
849
+        $this->Controller->presetVars = array(
850
+            array(
851
+                'field' => 'category_id',
852
+                'name' => 'category_id',
853
+                'type' => 'value',
854
+                'allowEmpty' => true,
855
+                'emptyValue' => '0',
856
+            ),
857
+            array(
858
+                'field' => 'checkbox',
859
+                'name' => 'checkbox',
860
+                'type' => 'checkbox'
861
+            ),
862
+        );
863
+        $this->Controller->action = 'search';
864
+        $this->Controller->request->data = array(
865
+            'Post' => array(
866
+                'category_id' => '0',
867
+                'foo' => ''));
868
+
869
+        $this->Controller->Prg->commonProcess('Post', array(
870
+            'form' => 'Post',
871
+            'modelMethod' => false,
872
+            'filterEmpty' => true));
873
+        $expected = array(
874
+            'action' => 'search',
875
+            'category_id' => '');
876
+        $this->assertEquals($expected, $this->Controller->redirectUrl);
877
+    }
878 878
 
879 879
 /**
880 880
  * testPresetFormWithEmptyValue
881 881
  *
882 882
  * @return void
883 883
  */
884
-	public function testPresetFormWithEmptyValue() {
885
-		$this->Controller->presetVars = array(
886
-			array(
887
-				'field' => 'category_id',
888
-				'type' => 'value',
889
-				'allowEmpty' => true,
890
-				'emptyValue' => '0',
891
-			),
892
-			array(
893
-				'field' => 'checkbox',
894
-				'type' => 'checkbox',
895
-				'allowEmpty' => true,
896
-			),
897
-		);
898
-		$this->Controller->passedArgs = array(
899
-			'category_id' => '',
900
-		);
901
-		$this->Controller->beforeFilter();
902
-
903
-		$this->Controller->Prg->encode = true;
904
-		$this->Controller->Prg->presetForm(array('model' => 'Post'));
905
-		$expected = array(
906
-			'Post' => array(
907
-				'category_id' => '0'));
908
-		$this->assertEquals($expected, $this->Controller->request->data);
909
-		$this->assertFalse($this->Controller->Prg->isSearch);
910
-
911
-		$expected = array(
912
-			'Post' => array(
913
-				'category_id' => ''));
914
-		$this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
915
-	}
884
+    public function testPresetFormWithEmptyValue() {
885
+        $this->Controller->presetVars = array(
886
+            array(
887
+                'field' => 'category_id',
888
+                'type' => 'value',
889
+                'allowEmpty' => true,
890
+                'emptyValue' => '0',
891
+            ),
892
+            array(
893
+                'field' => 'checkbox',
894
+                'type' => 'checkbox',
895
+                'allowEmpty' => true,
896
+            ),
897
+        );
898
+        $this->Controller->passedArgs = array(
899
+            'category_id' => '',
900
+        );
901
+        $this->Controller->beforeFilter();
902
+
903
+        $this->Controller->Prg->encode = true;
904
+        $this->Controller->Prg->presetForm(array('model' => 'Post'));
905
+        $expected = array(
906
+            'Post' => array(
907
+                'category_id' => '0'));
908
+        $this->assertEquals($expected, $this->Controller->request->data);
909
+        $this->assertFalse($this->Controller->Prg->isSearch);
910
+
911
+        $expected = array(
912
+            'Post' => array(
913
+                'category_id' => ''));
914
+        $this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
915
+    }
916 916
 
917 917
 /**
918 918
  * testPresetFormWithEmptyValueAndIsSearch
919 919
  *
920 920
  * @return void
921 921
  */
922
-	public function testPresetFormWithEmptyValueAndIsSearch() {
923
-		$this->Controller->presetVars = array(
924
-			array(
925
-				'field' => 'category_id',
926
-				'type' => 'value',
927
-				'allowEmpty' => true,
928
-				'emptyValue' => '0',
929
-			),
930
-			array(
931
-				'field' => 'checkbox',
932
-				'type' => 'checkbox'
933
-			),
934
-		);
935
-		$this->Controller->passedArgs = array(
936
-			'category_id' => '',
937
-			'checkbox' => $this->_urlEncode('test|test2|test3'),
938
-		);
939
-		$this->Controller->beforeFilter();
940
-
941
-		$this->Controller->Prg->encode = true;
942
-		$this->Controller->Prg->presetForm(array('model' => 'Post'));
943
-		$expected = array(
944
-			'Post' => array(
945
-				'category_id' => '0',
946
-				'checkbox' => array(
947
-					0 => 'test',
948
-					1 => 'test2',
949
-					2 => 'test3')));
950
-		$this->assertEquals($expected, $this->Controller->request->data);
951
-		$this->assertTrue($this->Controller->Prg->isSearch);
952
-
953
-		$expected = array(
954
-			'Post' => array(
955
-				'category_id' => '',
956
-				'checkbox' => array(
957
-					0 => 'test',
958
-					1 => 'test2',
959
-					2 => 'test3')));
960
-		$this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
961
-	}
922
+    public function testPresetFormWithEmptyValueAndIsSearch() {
923
+        $this->Controller->presetVars = array(
924
+            array(
925
+                'field' => 'category_id',
926
+                'type' => 'value',
927
+                'allowEmpty' => true,
928
+                'emptyValue' => '0',
929
+            ),
930
+            array(
931
+                'field' => 'checkbox',
932
+                'type' => 'checkbox'
933
+            ),
934
+        );
935
+        $this->Controller->passedArgs = array(
936
+            'category_id' => '',
937
+            'checkbox' => $this->_urlEncode('test|test2|test3'),
938
+        );
939
+        $this->Controller->beforeFilter();
940
+
941
+        $this->Controller->Prg->encode = true;
942
+        $this->Controller->Prg->presetForm(array('model' => 'Post'));
943
+        $expected = array(
944
+            'Post' => array(
945
+                'category_id' => '0',
946
+                'checkbox' => array(
947
+                    0 => 'test',
948
+                    1 => 'test2',
949
+                    2 => 'test3')));
950
+        $this->assertEquals($expected, $this->Controller->request->data);
951
+        $this->assertTrue($this->Controller->Prg->isSearch);
952
+
953
+        $expected = array(
954
+            'Post' => array(
955
+                'category_id' => '',
956
+                'checkbox' => array(
957
+                    0 => 'test',
958
+                    1 => 'test2',
959
+                    2 => 'test3')));
960
+        $this->assertEquals($expected['Post'], $this->Controller->Prg->parsedParams());
961
+    }
962 962
 
963 963
 }
Please login to merge, or discard this patch.