Project

General

Profile

« Previous | Next » 

Revision 1947

Added by darkviper over 11 years ago

added classes AccessFile and AccessFileHelper to /framework/

View differences:

branches/2.8.x/CHANGELOG
11 11
! = Update/Change
12 12
===============================================================================
13 13

  
14
03 Aug-2013 Build 1947 M.v.d.Decken(DarkViper)
15
+ added classes AccessFile and AccessFileHelper to /framework/
14 16
03 Aug-2013 Build 1946 M.v.d.Decken(DarkViper)
15 17
! Droplet iParentPageIcon
16 18
03 Aug-2013 Build 1945 M.v.d.Decken(DarkViper)
branches/2.8.x/wb/admin/interface/version.php
51 51

  
52 52
// check if defined to avoid errors during installation (redirect to admin panel fails if PHP error/warnings are enabled)
53 53
if(!defined('VERSION')) define('VERSION', '2.8.3');
54
if(!defined('REVISION')) define('REVISION', '1946');
54
if(!defined('REVISION')) define('REVISION', '1947');
55 55
if(!defined('SP')) define('SP', '');
branches/2.8.x/wb/framework/AccessFileHelper.php
1
<?php
2

  
3
/**
4
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19

  
20
/**
21
 * AccessFileHelper.php
22
 *
23
 * @category     Core
24
 * @package      Core_Routing
25
 * @copyright    M.v.d.Decken <manuela@isteam.de>
26
 * @author       M.v.d.Decken <manuela@isteam.de>
27
 * @license      http://www.gnu.org/licenses/gpl.html   GPL License
28
 * @version      0.0.1
29
 * @revision     $Revision: $
30
 * @link         $HeadURL: $
31
 * @lastmodified $Date: $
32
 * @since        File available since 01.08.2013
33
 * @description  this class provides some helper methodes to handle access files
34
 */
35

  
36
class AccessFileHelper {
37

  
38
/**
39
 * do not delete start directory of deltree
40
 */
41
	const DEL_ROOT_PRESERVE = 0;
42
/**
43
 * delete start directory of deltree
44
 */
45
	const DEL_ROOT_DELETE   = 1;
46
/**
47
 * to store the last delTree log
48
 */
49
	static $aDelTreeLog = array();
50

  
51
/**
52
 * private constructor to deny instantiating
53
 */
54
	private function __construct() {
55
		;
56
	}
57
/**
58
 * Test if file is an access file
59
 * @param       string $sFileName  qualified path/file
60
 * @return      boolean
61
 * @description test given file for typical accessfile signature
62
 */
63
	static public function isAccessFile($sFileName)
64
	{
65
		$bRetval = false;
66
		if (($sFile = file_get_contents($sFileName)) !== false)
67
		{
68
			$sPattern = '/^\s*?<\?php.*?\$i?page_?id\s*=\s*[0-9]+;.*?(?:require|include)'
69
					. '(?:_once)?\s*\(\s*\'.*?index\.php\'\s?\);/siU';
70
			$bRetval = (bool) preg_match($sPattern, $sFile);
71
			unset($sFile);
72
		}
73
		return $bRetval;
74
	}
75
/**
76
 * Delete all contents of basedir, but not the basedir itself
77
 * @param string  $sRootDir the content of which should be deleted
78
 * @param integer $iMode    the mode can be set to self::DEL_ROOT_PRESERVE(default) or self::DEL_ROOT_DELETE
79
 * @return boolean          false if a file or directory can't be deleted
80
 */
81
	static public function delTree($sRootDir, $iMode = self::DEL_ROOT_PRESERVE)
82
	{
83
		// check if root dir is inside the installation and is writeable
84
		$oReg = WbAdaptor::getInstance();
85
		self::$aDelTreeLog = array();
86
		$bResult = true;
87
		if (!is_writeable($sRootDir))
88
		{
89
			return false;
90
			self::$aDelTreeLog[] = 'insufficient rights or directory not empty in : '.str_replace($oReg->AppPath, '', $sRootDir);
91
		}
92
		$oIterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sRootDir), RecursiveIteratorIterator::CHILD_FIRST);
93
		foreach ($oIterator as $oPath)
94
		{
95
			$sPath = trim(str_replace('\\', '/', $oPath->__toString()), '/');
96
			if ($oPath->isDir())
97
			{
98
				// proceed directories
99
				if (!rmdir($sPath))
100
				{
101
					$bResult = false;
102
					self::$aDelTreeLog[] = 'insufficient rights or directory not empty in : '.str_replace($oReg->AppPath, '', $sPath);
103
				}else {
104
					self::$aDelTreeLog[] = 'Directory successful removed : '.str_replace($oReg->AppPath, '', $sPath);
105
				}
106
			} elseif ($oPath->isFile())
107
			{
108
				// proceed files
109
				if (!unlink($sPath))
110
				{
111
					$bResult = false;
112
					self::$aDelTreeLog[] = 'insufficient rights or directory not empty in : '.str_replace($oReg->AppPath, '', $sPath);
113
				}else {
114
					self::$aDelTreeLog[] = 'File successful deleted : '.str_replace($oReg->AppPath, '', $sPath);
115
				}
116
			}
117
		}
118
		if (($iMode & self::DEL_ROOT_DELETE))
119
		{
120
			if ($bResult)
121
			{ // if there was no error before
122
				if (rmdir($sRootDir))
123
				{
124
					self::$aDelTreeLog[] = 'Directory successful removed : '.str_replace($oReg->AppPath, '', $sRootDir);
125
					return $bResult;
126
				}
127
			}
128
			self::$aDelTreeLog[] = 'insufficient rights or directory not empty in : '.str_replace($oReg->AppPath, '', $sRootDir);
129
		}
130
		return $bResult;
131
	}
132
/**
133
 * returns the log of the last delTree request
134
 * @return array
135
 */
136
	static function getDelTreeLog()
137
	{
138
		return self::$aDelTreeLog;
139
	}
140

  
141
} // end of class AccessFileHelper
branches/2.8.x/wb/framework/AccessFile.php
1
<?php
2

  
3
/**
4
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19

  
20
/**
21
 * AccessFile.php
22
 *
23
 * @category     Core
24
 * @package      Core_Routing
25
 * @copyright    M.v.d.Decken <manuela@isteam.de>
26
 * @author       M.v.d.Decken <manuela@isteam.de>
27
 * @license      http://www.gnu.org/licenses/gpl.html   GPL License
28
 * @version      0.0.1
29
 * @revision     $Revision: $
30
 * @lastmodified $Date: $
31
 * @since        File available since 17.01.2013
32
 * @description  Create a single standard accessfile with additional var-entries
33
 */
34
class AccessFile {
35

  
36
	/** int first private property */
37
	protected $_oReg      = null;
38
	protected $_sFileName = '';
39
	protected $_aVars     = array();
40
	protected $_aConsts   = array();
41
	protected $_iErrorNo  = 0;
42

  
43
	const VAR_STRING  = 'string';
44
	const VAR_BOOL    = 'bool';
45
	const VAR_BOOLEAN = 'bool';
46
	const VAR_INT     = 'int';
47
	const VAR_INTEGER = 'int';
48
	const VAR_FLOAT   = 'float';
49

  
50
	const FORCE_DELETE = true;
51

  
52
	/**
53
	 * Constructor
54
	 * @param string full path and filename to the new access file
55
	 * @param integer Id of the page or 0 for dummy files
56
	 */
57
	public function __construct($sFileName, $iPageId = 0)
58
	{
59
		$this->_oReg = WbAdaptor::getInstance();
60
		$this->_sFileName = str_replace('\\', '/', $sFileName);
61
		if (!preg_match('/^' . preg_quote($this->_oReg->AppPath, '/') . '/siU', $this->_sFileName)) {
62
			throw new AccessFileInvalidFilePathException('tried to place file out of application path');
63
		}
64
		$this->_aVars['iPageId'] = intval($iPageId);
65
	}
66
	/**
67
	 * Set Id of current page
68
	 * @param integer PageId
69
	 */
70
	public function setPageId($iPageId)
71
	{
72
		$this->addVar('iPageId', $iPageId, $sType = self::VAR_INTEGER);
73
	}
74

  
75
	/**
76
	 * Add new variable into the vars list
77
	 * @param string name of the variable without leading '$'
78
	 * @param mixed Value of the variable (Only scalar data (boolean, integer, float and string) are allowed)
79
	 * @param string Type of the variable (use class constants to define)
80
	 */
81
	public function addVar($sName, $mValue, $sType = self::VAR_STRING)
82
	{
83
		$mValue = $this->_sanitizeValue($mValue, $sType);
84
		$this->_aVars[$sName] = $mValue;
85
	}
86

  
87
	/**
88
	 * Add new constant into the constants list
89
	 * @param string name of the constant (upper case chars only)
90
	 * @param mixed Value of the variable (Only scalar data (boolean, integer, float and string) are allowed)
91
	 * @param string Type of the variable (use class constants to define)
92
	 * @deprecated constants are not allowed from WB-version 2.9 and up
93
	 */
94
	public function addConst($sName, $mValue, $sType = self::VAR_STRING)
95
	{
96
		if (version_compare($this->_oReg->AppVersion, '2.9', '<'))
97
		{
98
			$mValue = $this->_sanitizeValue($mValue, $sType);
99
			$this->_aConsts[strtoupper($sName)] = $mValue;
100
		} else {
101
			throw new AccessFileConstForbiddenException('define constants is not allowed from WB-version 2.9 and up');
102
		}
103
	}
104

  
105
	/**
106
	 * Write the accessfile
107
	 * @throws AccessFileException
108
	 */
109
	public function write() 
110
	{
111
		// remove AppPath from File for use in error messages
112
		$sTmp = str_replace($this->_oReg->AppPath, '', $this->_sFileName);
113
		if (file_exists($this->_sFileName)) {
114
			throw new AccessFileAlreadyExistsException('Accessfile already exists: * ' . $sTmp . ' *');
115
		}
116

  
117
		if (!$this->_aVars['iPageId']) {
118
			// search for the parent pageID if current ID is 0
119
			$this->_aVars['iPageId'] = $this->searchParentPageId($this->_sFileName);
120
		}
121
		$sIndexFile = $this->_buildPathToIndexFile($this->_sFileName);
122
		$this->_createPath($this->_sFileName);
123
		$sContent = $this->_buildFileContent($sIndexFile);
124
		if (!file_put_contents($this->_sFileName, $sContent)) {
125
			throw new AccessFileNotWriteableException('Unable to write file * ' . $sTmp . ' *');
126
		}
127
		if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') { // Only chmod if os is not windows
128
			chmod($this->_sFileName, $this->_oReg->OctalFileMode);
129
		}
130
	}
131

  
132
	/**
133
	 * Rename an existing Accessfile
134
	 * @param string the new filename without path and without extension
135
	 * @return boolean
136
	 * @throws AccessFileInvalidFilenameException
137
	 * @throws AccessFileAlreadyExistsException
138
	 * @throws AccessFileAccessFileRenameException
139
	 */
140
	public function rename($sNewName)
141
	{
142
		// sanitize new filename
143
		if (!preg_match('/[^\.\\\/]*/si', $sNewName)) {
144
			throw new AccessFileInvalidFilenameException('invalid filename [' . $sNewName . ']');
145
		}
146
		// prepare old/new file-/dirname
147
		$sOldFilename = $this->_sFileName;
148
		$sOldSubDirname = dirname($sOldFilename) . '/';
149
		$sPattern = '/^(' . preg_quote($sOldSubDirname, '/') . ')([^\/\.]+?)(\.[a-z0-9]+)$/siU';
150
		$sNewFilename = preg_replace($sPattern, '\1' . $sNewName . '\3', $sOldFilename);
151
		$sNewSubDirname = dirname($sNewFilename) . '/';
152
		if (file_exists($sNewFilename) || file_exists($sNewSubDirname)) {
153
			// check if new filename already exists
154
			throw new AccessFileAlreadyExistsException('new file/dirname already exists [' . $sNewName . ']');
155
		}
156
		// try to rename a depending subdirectory
157
		$bSubdirRenamed = false;
158
		$bRetval = true;
159
		if (file_exists($sOldSubDirname))
160
		{
161
			// old subdir exists but is it writeable?
162
			if (($bRetval = is_writable($sOldSubDirname)))
163
			{
164
				if (rename($sOldSubDirname, $sNewSubDirname)) {
165
					$bRetval = $bSubdirRenamed = true;
166
				}
167
			}
168
		}
169
		if (!$bRetval) {
170
			// if old subdir exists and renaming failed
171
			throw new AccessFileRenameException('unable to rename directory [' . $sOldSubDirname . ']');
172
		}
173
		if (($bRetval = is_writeable($this->_sFileName))) {
174
			// try to rename accessfile
175
			$bRetval = rename($sOldFilename, $sNewFilename);
176
		}
177
		if (!$bRetval)
178
		{
179
			if ($bSubdirRenamed) {
180
				// on error undo renaming of subdir
181
				rename($sNewSubDirname, $sOldSubDirname);
182
			}
183
			throw new AccessFileRenameException('unable to rename file [' . $sOldFilename . ']');
184
		}
185
	}
186

  
187
	/**
188
	 * Delete the actual Accessfile
189
	 * @return boolean true if successfull
190
	 * @throws AccessFileIsNoAccessfileException
191
	 * @throws AccessFileNotWriteableException
192
	 */
193
	public function delete($bForceDelete = true)
194
	{
195
		$sFileName = $this->_sFileName;
196
		if (!AccessFileHelper::isAccessFile($sFileName)) {
197
			throw new AccessFileIsNoAccessfileException('requested file is NOT an accessfile');
198
		}
199
		if (file_exists($sFileName) && is_writeable($sFileName))
200
		{
201
			$sPattern = '/^(.*?)(\.[a-z0-9]+)$/siU';
202
			$sDir = preg_replace($sPattern, '\1/', $sFileName);
203
			if (is_writeable($sDir)) {
204
				AccessFileHelper::delTree($sDir, AccessFileHelper::DEL_ROOT_DELETE);
205
			}
206
			unlink($sFileName);
207
			$sFileName = '';
208
		} else {
209
			throw new AccessFileNotWriteableException('requested file not exists or permissions missing');
210
		}
211
	}
212

  
213
	/**
214
	 * getFilename
215
	 * @return string path+name of the current accessfile
216
	 */
217
	public function getFileName()
218
	{
219
		return $this->_sFileName;
220
	}
221

  
222
	/**
223
	 * getPageId
224
	 * @return integer
225
	 */
226
	public function getPageId()
227
	{
228
		return (isset($this->_aVars['iPageId']) ? $this->_aVars['iPageId'] : 0);
229
	}
230
	/**
231
	 * get number of the last occured error
232
	 * @return int
233
	 */
234
	public function getError()
235
	{
236
		return $this->_iErrorNo;
237
	}
238
	/**
239
	 * set number of error
240
	 * @param type $iErrNo
241
	 */
242
	protected function _setError($iErrNo = self::ERR_NONE)
243
	{
244
		$this->_iErrorNo = $iErrNo;
245
	}
246
	/**
247
	 * Create Path to Accessfile
248
	 * @param string full path/name to new access file
249
	 * @throws AccessFileNotWriteableException
250
	 * @throws AccessFileInvalidStructureException
251
	 */
252
	protected function _createPath($sFilename)
253
	{
254
		$sFilename = str_replace($this->_oReg->AppPath . $this->_oReg->PagesDir, '', $sFilename);
255
		$sPagesDir = $this->_oReg->AppPath . $this->_oReg->PagesDir;
256

  
257
		if (($iSlashPosition = mb_strrpos($sFilename, '/')) !== false)
258
		{
259
			// if subdirs exists, then procceed extended check
260
			$sExtension = preg_replace('/.*?(\.[a-z][a-z0-9]+)$/siU', '\1', $sFilename);
261
			$sParentDir = mb_substr($sFilename, 0, $iSlashPosition);
262
			if (file_exists($sPagesDir . $sParentDir))
263
			{
264
				if (!is_writable($sPagesDir . $sParentDir)) {
265
					throw new AccessFileNotWriteableException('No write permissions for ' . $sPagesDir . $sParentDir);
266
				}
267
			} else
268
			{
269
				// if parentdir not exists
270
				if (file_exists($sPagesDir . $sParentDir . $sExtension))
271
				{
272
					// but parentaccessfile exists, create parentdir and ok
273
					$iOldUmask = umask(0);
274
					$bRetval = mkdir($sPagesDir . $sParentDir, $this->_oReg->OctalDirMode);
275
					umask($iOldUmask);
276
				} else {
277
					throw new AccessFileInvalidStructureException('invalid structure ' . $sFilename);
278
				}
279
				if (!$bRetval) {
280
					throw new AccessFileNotWriteableException('Unable to create ' . $sPagesDir . $sParentDir);
281
				}
282
			}
283
		}
284
	}
285
	/**
286
	 * Sanitize value
287
	 * @param mixed Value to sanitize
288
	 * @param string Type of the variable (use class constants to define)
289
	 * @return string printable value
290
	 * @throws InvalidArgumentException
291
	 */
292
	protected function _sanitizeValue($mValue, $sType)
293
	{
294
		$mRetval = '';
295
		switch ($sType)
296
		{
297
			case self::VAR_BOOLEAN:
298
			case self::VAR_BOOL:
299
				$mRetval = (filter_var(strtolower($mValue), FILTER_VALIDATE_BOOLEAN) ? '1' : '0');
300
				break;
301
			case self::VAR_INTEGER:
302
			case self::VAR_INT:
303
				if (filter_var($mValue, FILTER_VALIDATE_INT) === false) {
304
					throw new InvalidArgumentException('value is not an integer');
305
				}
306
				$mRetval = (string) $mValue;
307
				break;
308
			case self::VAR_FLOAT:
309
				if (filter_var($mValue, FILTER_VALIDATE_FLOAT) === false) {
310
					throw new InvalidArgumentException('value is not a float');
311
				}
312
				$mRetval = (string) $mValue;
313
				break;
314
			default: // VAR_STRING
315
				$mRetval = '\'' . (string) $mValue . '\'';
316
				break;
317
		}
318
		return $mRetval;
319
	}
320

  
321
	/**
322
	 * Calculate backsteps in directory
323
	 * @param string accessfile
324
	 */
325
	protected function _buildPathToIndexFile($sFileName)
326
	{
327
		$iBackSteps = substr_count(str_replace($this->_oReg->AppPath, '', $sFileName), '/');
328
		return str_repeat('../', $iBackSteps) . 'index.php';
329
	}
330

  
331
	/**
332
	 * Build the content of the new accessfile
333
	 * @param string $sIndexFile name and path to the wb/index.php file
334
	 * @return string
335
	 */
336
	protected function _buildFileContent($sIndexFile)
337
	{
338
		$sFileContent
339
				= '<?php' . "\n"
340
				. '// *** This file is generated by ' . $this->_oReg->AppName
341
				. ' Ver.' . $this->_oReg->AppVersion
342
				. ($this->_oReg->AppServicePack != '' ? $this->_oReg->AppServicePack : '')
343
				. ' Rev.' . $this->_oReg->AppRevision . "\n"
344
				. '// *** Creation date: ' . date('c') . "\n"
345
				. '// *** Do not modify this file manually' . "\n"
346
				. '// *** This file will be rebuild from time to time!!' . "\n"
347
				. '// *** Then all manual changes will get lost!! ' . "\n"
348
				. '// *************************************************' . "\n";
349
		foreach ($this->_aVars as $sKey => $sVar) {
350
			$sFileContent .= "\t" . '$' . $sKey . ' = ' . $sVar . ';' . "\n";
351
		}
352
		foreach ($this->_aConsts as $sKey => $sVar) {
353
			$sFileContent .= "\t" . 'define(\'' . $sKey . '\', ' . $sVar . '); // *deprecated command*' . "\n";
354
		}
355
		$sFileContent
356
				.= "\t" . 'require(\'' . $sIndexFile . '\');' . "\n"
357
				. '// *************************************************' . "\n"
358
				. '// end of file' . "\n";
359

  
360
		return $sFileContent;
361
	}
362

  
363
}
364

  
365
// end of class AccessFile
366
// //////////////////////////////////////////////////////////////////////////////////// //
367
/**
368
 * AccessFileException
369
 *
370
 * @category     WBCore
371
 * @package      WBCore_Accessfiles
372
 * @author       M.v.d.Decken <manuela@isteam.de>
373
 * @copyright    M.v.d.Decken <manuela@isteam.de>
374
 * @license      http://www.gnu.org/licenses/gpl.html   GPL License
375
 * @version      2.9.0
376
 * @revision     $Revision: 12 $
377
 * @lastmodified $Date: 2012-12-29 21:39:37 +0100 (Sa, 29 Dez 2012) $
378
 * @description  Exceptionhandler for the Accessfiles and depending classes
379
 */
380

  
381
class AccessFileException extends Exception { }
382
class AccessFileConstForbiddenException extends AccessFileException { }
383
class AccessFileInvalidFilePathException extends AccessFileException { }
384
class AccessFileAlreadyExistsException extends AccessFileException { }
385
class AccessFileNotWriteableException extends AccessFileException { }
386
class AccessFileIsInvalidFilenameException extends AccessFileException { }
387
class AccessFileIsNoAccessfileException extends AccessFileException { }
388
class AccessFileInvalidStructureException extends AccessFileException { }

Also available in: Unified diff