Project

General

Profile

« Previous | Next » 

Revision 2045

Added by Dietmar almost 11 years ago

! update Access Files Classes with easier handling
for modules who create their own accessfiles

View differences:

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

  
36 37
	/** int first private property */
37
	protected $_oReg      = null;
38
	protected $_sFileName = '';
39
	protected $_aVars     = array();
40
	protected $_aConsts   = array();
41
	protected $_iErrorNo  = 0;
38
	protected $oReg             = null;
39
	protected $sAccessFilesRoot = '';      // basedir of the current AccessFile structure
40
	protected $sFileName        = '';      // filename and path from AccessFilesRoot (without extension)
41
	protected $sFullFileName    = '';      // full path and filename (without extension)
42
	protected $sFileExtension   = '.php';  // extension for all accessfiles (default: '.php')
43
	protected $aVars            = array(); // variables in accessfile
44
	protected $aConsts          = array(); // constants in accessfile
45
	protected $iErrorNo         = 0;
42 46

  
43 47
	const VAR_STRING  = 'string';
44 48
	const VAR_BOOL    = 'bool';
......
51 55

  
52 56
	/**
53 57
	 * 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
58
	 * @param string  $sAccessFilesRoot  full path to the base directory of accessfiles-tree
59
	 * @param string  $sFileName         subdirectory and filename of the new access file from AccessFilesRoot<br />
60
	 *                                   (indirect addressing (./ | ../) is not allowed here!!)
61
	 * @param integer $iPageId           (default: 0) Id of the page or 0 for dummy files
62
	 * @throws AccessFileInvalidFilePathException
56 63
	 */
57
	public function __construct($sFileName, $iPageId = 0)
64
	public function __construct($sAccessFilesRoot, $sFileName, $iPageId = 0)
58 65
	{
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');
66
		$this->oReg = WbAdaptor::getInstance();
67
		$this->sFileExtension = $this->oReg->PageExtension;
68
	// sanitize AccessFilesRoot
69
		if (($sX = realpath($sAccessFilesRoot)) == false) {
70
			throw new AccessFileInvalidFilePathException('invalid path for AccessFilesRoot given [ '.$sAccessFilesRoot.' ]');
63 71
		}
64
		$this->_aVars['iPageId'] = intval($iPageId);
72
		$sAccessFilesRoot = rtrim(str_replace('\\', '/', $sX), '/').'/';
73
	// check location of AccessFilesRoot
74
		if (!preg_match('/^' . preg_quote($this->oReg->AppPath, '/') . '/siU', $sAccessFilesRoot)) {
75
			throw new AccessFileInvalidFilePathException('tried to place AccessFilesRoot out of application path [ '.$sAccessFilesRoot.' ]');
76
		}
77
		$this->sAccessFilesRoot = $sAccessFilesRoot;
78
	// sanitize Filename
79
		$sFileName = preg_replace('/'.preg_quote($this->sFileExtension, '/').'$/', '', $sFileName);
80
		$this->sFileName = ltrim(rtrim(trim(str_replace('\\', '/', $sFileName)), '/'), './');
81
		if (preg_match('/\.\.+\//', $this->sFileName)) {
82
			throw new AccessFileInvalidFilePathException('relative path (./ or ../) is not allowed in Filename!! [ '.$this->sFileName.' ]');
83
		}
84
		$this->sFullFileName = $this->sAccessFilesRoot . $this->sFileName;
85
		$this->aVars['iPageId'] = intval($iPageId);
86

  
65 87
	}
66 88
	/**
67 89
	 * Set Id of current page
......
80 102
	 */
81 103
	public function addVar($sName, $mValue, $sType = self::VAR_STRING)
82 104
	{
83
		$mValue = $this->_sanitizeValue($mValue, $sType);
84
		$this->_aVars[$sName] = $mValue;
105
		$mValue = $this->sanitizeValue($mValue, $sType);
106
		$this->aVars[$sName] = $mValue;
85 107
	}
86 108

  
87 109
	/**
......
89 111
	 * @param string name of the constant (upper case chars only)
90 112
	 * @param mixed Value of the variable (Only scalar data (boolean, integer, float and string) are allowed)
91 113
	 * @param string Type of the variable (use class constants to define)
114
	 * @throws AccessFileConstForbiddenException
92 115
	 * @deprecated constants are not allowed from WB-version 2.9 and up
93 116
	 */
94 117
	public function addConst($sName, $mValue, $sType = self::VAR_STRING)
95 118
	{
96
		if (version_compare($this->_oReg->AppVersion, '2.9', '<'))
119
		if (version_compare($this->oReg->AppVersion, '2.9', '<'))
97 120
		{
98
			$mValue = $this->_sanitizeValue($mValue, $sType);
99
			$this->_aConsts[strtoupper($sName)] = $mValue;
121
			$mValue = $this->sanitizeValue($mValue, $sType);
122
			$this->aConsts[strtoupper($sName)] = $mValue;
100 123
		} else {
101 124
			throw new AccessFileConstForbiddenException('define constants is not allowed from WB-version 2.9 and up');
102 125
		}
......
104 127

  
105 128
/**
106 129
 * Write the accessfile
107
 * @throws AccessFileException
130
 * @throws AccessFileWriteableException
108 131
 */
109 132
	public function write() 
110 133
	{
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 . ' *');
134
	// full path and filename
135
		$sFileName = $this->sFullFileName.$this->sFileExtension;
136
	// remove AppPath from File for use in error messages
137
		$sDisplayFilename = str_replace($this->oReg->AppPath, '', $sFileName);
138
	// do not allow writing if PageId is missing!
139
		if (!$this->aVars['iPageId']) {
140
			throw new AccessFileWriteableException('Missing PageId for file [' . $sDisplayFilename . ']');
115 141
		}
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);
142
	// build the content for the access file
143
		$sContent = $this->buildFileContent($this->buildPathToIndexFile($sFileName));
144
	// create path if file does not already exists
145
		if (!file_exists($sFileName)) {
146
			$this->createPath($sFileName);
120 147
		}
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 . ' *');
148
	// create new file or overwrite existing one
149
		if (!file_put_contents($sFileName, $sContent)) {
150
			throw new AccessFileWriteableException('Unable to write file [' . $sDisplayFilename . ']');
126 151
		}
127
		if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') { // Only chmod if os is not windows
128
			chmod($this->_sFileName, $this->_oReg->OctalFileMode);
152
	// do chmod if os is not windows
153
		if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
154
			chmod($sFileName, $this->oReg->OctalFileMode);
129 155
		}
130 156
	}
131 157

  
158
/**
159
 * searchParentPageId
160
 * @param string $sAccessFilesRoot
161
 * @param string $sFullFilePath
162
 * @return int   found page-id
163
 * @description  find first valid accessfile backwards in the parent line<br />
164
 *               or the start page if no parent is found.
165
 */
166
	protected function searchParentPageId($sAccessFilesRoot, $sFullFilePath)
167
	{
168

  
169

  
170
		return $iPageId;
171
	}
132 172
	/**
133 173
	 * Rename an existing Accessfile
134 174
	 * @param  string  $sNewName the new filename without path and without extension
135 175
	 * @return boolean
136
	 * @throws AccessFileInvalidFilenameException
137
	 * @throws AccessFileAlreadyExistsException
138 176
	 * @throws AccessFileAccessFileRenameException
139 177
	 */
140 178
	public function rename($sNewName)
141 179
	{
142
		// sanitize new filename
143
		if (!preg_match('/[^\.\\ \/]*/si', $sNewName)) {
144
			throw new AccessFileInvalidFilenameException('invalid filename [' . str_replace($this->_oReg->AppPath, '', $sNewName) . ']');
180
		// validate and sanitize new filename
181
		$sPattern = '/(^'.preg_quote($this->sAccessFilesRoot, '/').'|^'.preg_quote($this->oReg->AppPath, '/')
182
		          . ')?([^\/]*?)(?:'.preg_quote($this->sFileExtension, '/').')?$/s';
183
		if (!preg_match($sPattern, $sNewName, $aMatches)) {
184
		// sorry, but the given filename is not valid!
185
			throw new AccessFileRenameException('invalid filename [' . str_replace($this->oReg->AppPath, '', $sNewName) . ']');
145 186
		}
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
			// if new filename or directory already exists
154
			throw new AccessFileAlreadyExistsException('new file/dirname already exists [' . str_replace($this->_oReg->AppPath, '', $sNewName) . ']');
187
		$sOldFileName = $this->sFullFileName;
188
		// $aMatches[sizeof($aMatches)-1] contains the new filename without extension only
189
		$sNewFileName = preg_replace('/(^.*?)[^\/]*$/', '\1'.$aMatches[sizeof($aMatches)-1], $sOldFileName);
190
		$sDisplayOldFileName = str_replace($this->oReg->AppPath, '', $sOldFileName);
191
		$sDisplayNewFileName = str_replace($this->oReg->AppPath, '', $sNewFileName);
192

  
193
		if (file_exists($sNewFileName.$this->sFileExtension) || file_exists($sNewFileName.'/')) {
194
		// if new filename or directory already exists
195
			throw new AccessFileRenameException('new file or new dirname already exists ['.$sDisplayNewFileName.'{'.$this->sFileExtension.'}]');
155 196
		}
156
		if(!is_writeable($sOldFilename)) {
157
			throw new AccessFileRenameException('unable to rename file or file not exists [' . str_replace($this->_oReg->AppPath, '', $sOldFilename) . ']');
197
		if (!is_writeable($sOldFileName.$this->sFileExtension)) {
198
		// old file is not writable an can not be renamed
199
			throw new AccessFileRenameException('file not exists or file is readonly ['.$sDisplayOldFileName.$this->sFileExtension.']');
158 200
		}
159 201
		$bSubdirRenamed = false; // set default value
160
		if(file_exists($sOldSubDirname))
161
		{ //
162
			if(is_writeable($sOldSubDirname))
163
			{
164
				if(!( $bSubdirRenamed = rename($sOldSubDirname, $sNewSubDirname))) {
165
					throw new AccessFileRenameException('unable to rename directory [' . str_replace($this->_oReg->AppPath, '', $sOldSubDirname) . ']');
202
		if (file_exists($sOldFileName.'/')) { //
203
			if (is_writeable($sOldFileName.'/')) {
204
				if (!( $bSubdirRenamed = rename($sOldFileName.'/', $sOldFileName.'/'))) {
205
					throw new AccessFileRenameException('unable to rename directory ['.$sDisplayOldFileName.'/] to ['.$sDisplayNewFileName.'/]');
166 206
				}
167 207
			} else {
168
				throw new AccessFileRenameException('directory is not writeable [' . str_replace($this->_oReg->AppPath, '', $sOldSubDirname) . ']');
208
				throw new AccessFileRenameException('directory is not writeable ['.$sDisplayOldFileName.'/]');
169 209
			}
170 210
		}
171 211
		// try to rename accessfile
172
		if(!rename($sOldFilename, $sNewFilename)) {
173
			if($bSubdirRenamed) { rename($sNewSubDirname, $sOldSubDirname); }
174
			throw new AccessFileRenameException('unable to rename file [' . str_replace($this->_oReg->AppPath, '', $sOldFilename) . ']');
212
		if (!rename($sOldFileName.$this->sFileExtension, $sNewFileName.$this->sFileExtension)) {
213
			if ($bSubdirRenamed) { rename($sNewFileName.'/', $sOldFileName.'/'); }
214
			$sMsg = 'unable to rename file ['.$sDisplayOldFileName.$this->sFileExtension
215
			      . '] to ['.$sDisplayOldFileName.$this->sFileExtension.']';
216
			throw new AccessFileRenameException($sMsg);
175 217
		}
176 218
		return true;
177 219
	}
......
180 222
	 * Delete the actual Accessfile
181 223
	 * @return boolean true if successfull
182 224
	 * @throws AccessFileIsNoAccessfileException
183
	 * @throws AccessFileNotWriteableException
225
	 * @throws AccessFileWriteableException
184 226
	 */
185 227
	public function delete($bForceDelete = true)
186 228
	{
187
		$sFileName = $this->_sFileName;
229
		$sFileName = $this->sFullFileName.$this->sFileExtension;
230

  
188 231
		if (!AccessFileHelper::isAccessFile($sFileName)) {
189 232
			throw new AccessFileIsNoAccessfileException('requested file is NOT an accessfile');
190 233
		}
191 234
		if (file_exists($sFileName) && is_writeable($sFileName))
192 235
		{
193
			$sPattern = '/^(.*?)(\.[a-z0-9]+)$/siU';
194
			$sDir = preg_replace($sPattern, '\1/', $sFileName);
195
			if (is_writeable($sDir)) {
196
				AccessFileHelper::delTree($sDir, AccessFileHelper::DEL_ROOT_DELETE);
236
			if (is_writeable($this->sFullFileName)) {
237
				AccessFileHelper::delTree($this->sFullFileName, AccessFileHelper::DEL_ROOT_DELETE);
197 238
			}
198 239
			unlink($sFileName);
199 240
			$sFileName = '';
200 241
		} else {
201
			throw new AccessFileNotWriteableException('requested file not exists or permissions missing');
242
			throw new AccessFileWriteableException('requested file not exists or permissions missing');
202 243
		}
203 244
	}
204 245

  
......
208 249
	 */
209 250
	public function getFileName()
210 251
	{
211
		return $this->_sFileName;
252
		return $this->sFullFileName.$this->sFileExtension;
212 253
	}
213 254

  
214 255
	/**
......
217 258
	 */
218 259
	public function getPageId()
219 260
	{
220
		return (isset($this->_aVars['iPageId']) ? $this->_aVars['iPageId'] : 0);
261
		return (isset($this->aVars['iPageId']) ? $this->aVars['iPageId'] : 0);
221 262
	}
222 263
	/**
223 264
	 * get number of the last occured error
......
225 266
	 */
226 267
	public function getError()
227 268
	{
228
		return $this->_iErrorNo;
269
		return $this->iErrorNo;
229 270
	}
230 271
	/**
231 272
	 * set number of error
232 273
	 * @param type $iErrNo
233 274
	 */
234
	protected function _setError($iErrNo = self::ERR_NONE)
275
	protected function setError($iErrNo = self::ERR_NONE)
235 276
	{
236
		$this->_iErrorNo = $iErrNo;
277
		$this->iErrorNo = $iErrNo;
237 278
	}
238 279
	/**
239 280
	 * Create Path to Accessfile
240 281
	 * @param string full path/name to new access file
241
	 * @throws AccessFileNotWriteableException
282
	 * @throws AccessFileWriteableException
242 283
	 * @throws AccessFileInvalidStructureException
243 284
	 */
244
	protected function _createPath($sFilename)
285
	protected function createPath($sFilename)
245 286
	{
246
		$sFilename = str_replace($this->_oReg->AppPath . $this->_oReg->PagesDir, '', $sFilename);
247
		$sPagesDir = $this->_oReg->AppPath . $this->_oReg->PagesDir;
248

  
249
		if (($iSlashPosition = mb_strrpos($sFilename, '/')) !== false)
250
		{
287
		$sFilename = str_replace($this->sAccessFilesRoot, '', $sFilename);
288
		$sPagesDir = $this->sAccessFilesRoot;
289
		if (($iSlashPosition = mb_strrpos($sFilename, '/')) !== false) {
251 290
			// if subdirs exists, then procceed extended check
252 291
			$sExtension = preg_replace('/.*?(\.[a-z][a-z0-9]+)$/siU', '\1', $sFilename);
253 292
			$sParentDir = mb_substr($sFilename, 0, $iSlashPosition);
254
			if (file_exists($sPagesDir . $sParentDir))
255
			{
293
			if (file_exists($sPagesDir . $sParentDir)) {
256 294
				if (!is_writable($sPagesDir . $sParentDir)) {
257
					throw new AccessFileNotWriteableException('No write permissions for ' . $sPagesDir . $sParentDir);
295
					throw new AccessFileWriteableException('No write permissions for ' . $sPagesDir . $sParentDir);
258 296
				}
259
			} else
260
			{
297
			} else {
261 298
				// if parentdir not exists
262
				if (file_exists($sPagesDir . $sParentDir . $sExtension))
263
				{
299
				if (file_exists($sPagesDir . $sParentDir . $sExtension)) {
264 300
					// but parentaccessfile exists, create parentdir and ok
265 301
					$iOldUmask = umask(0);
266
					$bRetval = mkdir($sPagesDir . $sParentDir, $this->_oReg->OctalDirMode);
302
					$bRetval = mkdir($sPagesDir . $sParentDir, $this->oReg->OctalDirMode);
267 303
					umask($iOldUmask);
268 304
				} else {
269
					throw new AccessFileInvalidStructureException('invalid structure ' . $sFilename);
305
					throw new AccessFileInvalidStructureException('invalid structure - missing file: ' . $sFilename);
270 306
				}
271 307
				if (!$bRetval) {
272
					throw new AccessFileNotWriteableException('Unable to create ' . $sPagesDir . $sParentDir);
308
					throw new AccessFileWriteableException('Unable to create ' . $sPagesDir . $sParentDir);
273 309
				}
274 310
			}
275 311
		}
......
281 317
	 * @return string printable value
282 318
	 * @throws InvalidArgumentException
283 319
	 */
284
	protected function _sanitizeValue($mValue, $sType)
320
	protected function sanitizeValue($mValue, $sType)
285 321
	{
286 322
		$mRetval = '';
287 323
		switch ($sType)
......
314 350
	 * Calculate backsteps in directory
315 351
	 * @param string accessfile
316 352
	 */
317
	protected function _buildPathToIndexFile($sFileName)
353
	protected function buildPathToIndexFile($sFileName)
318 354
	{
319
		$iBackSteps = substr_count(str_replace($this->_oReg->AppPath, '', $sFileName), '/');
355
		$iBackSteps = substr_count(str_replace($this->oReg->AppPath, '', $sFileName), '/');
320 356
		return str_repeat('../', $iBackSteps) . 'index.php';
321 357
	}
322 358

  
......
325 361
	 * @param string $sIndexFile name and path to the wb/index.php file
326 362
	 * @return string
327 363
	 */
328
	protected function _buildFileContent($sIndexFile)
364
	protected function buildFileContent($sIndexFile)
329 365
	{
330 366
		$sFileContent
331 367
				= '<?php' . "\n"
332 368
				. '// *** This file was created automatically by ' ."\n"
333
				. '// *** ' . $this->_oReg->AppName	. ' Ver.' . $this->_oReg->AppVersion
334
				. ($this->_oReg->AppServicePack != '' ? ' '.$this->_oReg->AppServicePack : '')
335
				. ' Rev.' . $this->_oReg->AppRevision . "\n"
369
				. '// *** ' . $this->oReg->AppName	. ' Ver.' . $this->oReg->AppVersion
370
				. ($this->oReg->AppServicePack != '' ? ' '.$this->oReg->AppServicePack : '')
371
				. ' Rev.' . $this->oReg->AppRevision . "\n"
336 372
				. '// *** on ' . date('c') . "\n"
337 373
				. '//' . "\n"
338 374
				. '// *** Warning *************************************' . "\n"
......
341 377
				. '// *** then all manual changes will get lost!!' . "\n"
342 378
				. '// *************************************************' . "\n"
343 379
				. '//' . "\n";
344
		foreach ($this->_aVars as $sKey => $sVar) {
380
		foreach ($this->aVars as $sKey => $sVar) {
345 381
			$sFileContent .= "\t" . '$' . $sKey . ' = ' . $sVar . ';' . "\n";
346 382
		}
347
		foreach ($this->_aConsts as $sKey => $sVar) {
383
		foreach ($this->aConsts as $sKey => $sVar) {
348 384
			$sFileContent .= "\t" . 'define(\'' . $sKey . '\', ' . $sVar . '); // ** deprecated command **' . "\n";
349 385
		}
350 386
		$sFileContent
351 387
				.="\t" . 'require(\'' . $sIndexFile . '\');' . "\n"
352
				. "\t" . 'exit(0);' . "\n"
388
				. "\t" . 'exit();' . "\n"
353 389
				. '// *************************************************' . "\n"
354 390
				. '// end of file' . "\n";
355

  
356 391
		return $sFileContent;
357 392
	}
358 393

  
......
374 409
 * @description  Exceptionhandler for the Accessfiles and depending classes
375 410
 */
376 411

  
377
class AccessFileException extends Exception { }
412
class AccessFileException extends AppException { }
413
class AccessFileInvalidStructureException extends AccessFileException { }
414
class AccessFileIsNoAccessfileException extends AccessFileException { }
378 415
class AccessFileConstForbiddenException extends AccessFileException { }
379 416
class AccessFileInvalidFilePathException extends AccessFileException { }
380
class AccessFileInvalidFilenameException extends AccessFileException { }
381
class AccessFileAlreadyExistsException extends AccessFileException { }
382
class AccessFileNotWriteableException extends AccessFileException { }
383
class AccessFileIsInvalidFilenameException extends AccessFileException { }
384
class AccessFileIsNoAccessfileException extends AccessFileException { }
385
class AccessFileInvalidStructureException extends AccessFileException { }
386 417
class AccessFileRenameException extends AccessFileException { }
418
class AccessFileWriteableException extends AccessFileException { }

Also available in: Unified diff