Project

General

Profile

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
 * @subpackage   Accessfiles
26
 * @copyright    Manuela v.d.Decken <manuela@isteam.de>
27
 * @author       Manuela v.d.Decken <manuela@isteam.de>
28
 * @license      http://www.gnu.org/licenses/gpl.html   GPL License
29
 * @version      0.0.1
30
 * @revision     $Revision: 2070 $
31
 * @lastmodified $Date: 2014-01-03 02:21:42 +0100 (Fri, 03 Jan 2014) $
32
 * @since        File available since 17.01.2013
33
 * @description  Single standard accessfile with additional var-entries
34
 */
35
class AccessFile {
36

    
37
	/** int first private property */
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;
46

    
47
	const VAR_STRING  = 'string';
48
	const VAR_BOOL    = 'bool';
49
	const VAR_BOOLEAN = 'bool';
50
	const VAR_INT     = 'int';
51
	const VAR_INTEGER = 'int';
52
	const VAR_FLOAT   = 'float';
53

    
54
	const FORCE_DELETE = true;
55

    
56
	/**
57
	 * Constructor
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
63
	 */
64
	public function __construct($sAccessFilesRoot, $sFileName, $iPageId = 0)
65
	{
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.' ]');
71
		}
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

    
87
	}
88
	/**
89
	 * Set Id of current page
90
	 * @param integer PageId
91
	 */
92
	public function setPageId($iPageId)
93
	{
94
		$this->addVar('iPageId', $iPageId, $sType = self::VAR_INTEGER);
95
	}
96

    
97
	/**
98
	 * Add new variable into the vars list
99
	 * @param string name of the variable without leading '$'
100
	 * @param mixed Value of the variable (Only scalar data (boolean, integer, float and string) are allowed)
101
	 * @param string Type of the variable (use class constants to define)
102
	 */
103
	public function addVar($sName, $mValue, $sType = self::VAR_STRING)
104
	{
105
		$mValue = $this->sanitizeValue($mValue, $sType);
106
		$this->aVars[$sName] = $mValue;
107
	}
108

    
109
	/**
110
	 * Add new constant into the constants list
111
	 * @param string name of the constant (upper case chars only)
112
	 * @param mixed Value of the variable (Only scalar data (boolean, integer, float and string) are allowed)
113
	 * @param string Type of the variable (use class constants to define)
114
	 * @throws AccessFileConstForbiddenException
115
	 * @deprecated constants are not allowed from WB-version 2.9 and up
116
	 */
117
	public function addConst($sName, $mValue, $sType = self::VAR_STRING)
118
	{
119
		if (version_compare($this->oReg->AppVersion, '2.9', '<'))
120
		{
121
			$mValue = $this->sanitizeValue($mValue, $sType);
122
			$this->aConsts[strtoupper($sName)] = $mValue;
123
		} else {
124
			throw new AccessFileConstForbiddenException('define constants is not allowed from WB-version 2.9 and up');
125
		}
126
	}
127

    
128
/**
129
 * Write the accessfile
130
 * @throws AccessFileWriteableException
131
 */
132
	public function write() 
133
	{
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 . ']');
141
		}
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);
147
		}
148
	// create new file or overwrite existing one
149
		if (!file_put_contents($sFileName, $sContent)) {
150
			throw new AccessFileWriteableException('Unable to write file [' . $sDisplayFilename . ']');
151
		}
152
	// do chmod if os is not windows
153
		if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
154
			chmod($sFileName, $this->oReg->OctalFileMode);
155
		}
156
	}
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
	}
172
	/**
173
	 * Rename an existing Accessfile
174
	 * @param  string  $sNewName the new filename without path and without extension
175
	 * @return boolean
176
	 * @throws AccessFileRenameException
177
	 */
178
	public function rename($sNewName)
179
	{
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) . ']');
186
		}
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.'}]');
196
		}
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.']');
200
		}
201
		$bSubdirRenamed = false; // set default value
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.'/]');
206
				}
207
			} else {
208
				throw new AccessFileRenameException('directory is not writeable ['.$sDisplayOldFileName.'/]');
209
			}
210
		}
211
		// try to rename accessfile
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);
217
		}
218
		return true;
219
	}
220

    
221
	/**
222
	 * Delete the actual Accessfile
223
	 * @return boolean true if successfull
224
	 * @throws AccessFileIsNoAccessfileException
225
	 * @throws AccessFileWriteableException
226
	 */
227
	public function delete($bForceDelete = true)
228
	{
229
		$sFileName = $this->sFullFileName.$this->sFileExtension;
230

    
231
		if (!AccessFileHelper::isAccessFile($sFileName)) {
232
			throw new AccessFileIsNoAccessfileException('requested file is NOT an accessfile');
233
		}
234
		if (file_exists($sFileName) && is_writeable($sFileName))
235
		{
236
			if (is_writeable($this->sFullFileName)) {
237
				AccessFileHelper::delTree($this->sFullFileName, AccessFileHelper::DEL_ROOT_DELETE);
238
			}
239
			unlink($sFileName);
240
			$sFileName = '';
241
		} else {
242
			throw new AccessFileWriteableException('requested file not exists or permissions missing');
243
		}
244
	}
245

    
246
	/**
247
	 * getFilename
248
	 * @return string path+name of the current accessfile
249
	 */
250
	public function getFileName()
251
	{
252
		return $this->sFullFileName.$this->sFileExtension;
253
	}
254

    
255
	/**
256
	 * getPageId
257
	 * @return integer
258
	 */
259
	public function getPageId()
260
	{
261
		return (isset($this->aVars['iPageId']) ? $this->aVars['iPageId'] : 0);
262
	}
263
	/**
264
	 * get number of the last occured error
265
	 * @return int
266
	 */
267
	public function getError()
268
	{
269
		return $this->iErrorNo;
270
	}
271
	/**
272
	 * set number of error
273
	 * @param type $iErrNo
274
	 */
275
	protected function setError($iErrNo = self::ERR_NONE)
276
	{
277
		$this->iErrorNo = $iErrNo;
278
	}
279
	/**
280
	 * Create Path to Accessfile
281
	 * @param string full path/name to new access file
282
	 * @throws AccessFileWriteableException
283
	 * @throws AccessFileInvalidStructureException
284
	 */
285
	protected function createPath($sFilename)
286
	{
287
		$sFilename = str_replace($this->sAccessFilesRoot, '', $sFilename);
288
		$sPagesDir = $this->sAccessFilesRoot;
289
		if (($iSlashPosition = mb_strrpos($sFilename, '/')) !== false) {
290
			// if subdirs exists, then procceed extended check
291
			$sExtension = preg_replace('/.*?(\.[a-z][a-z0-9]+)$/siU', '\1', $sFilename);
292
			$sParentDir = mb_substr($sFilename, 0, $iSlashPosition);
293
			if (file_exists($sPagesDir . $sParentDir)) {
294
				if (!is_writable($sPagesDir . $sParentDir)) {
295
					throw new AccessFileWriteableException('No write permissions for ' . $sPagesDir . $sParentDir);
296
				}
297
			} else {
298
				// if parentdir not exists
299
				if (file_exists($sPagesDir . $sParentDir . $sExtension)) {
300
					// but parentaccessfile exists, create parentdir and ok
301
					$iOldUmask = umask(0);
302
					$bRetval = mkdir($sPagesDir . $sParentDir, $this->oReg->OctalDirMode);
303
					umask($iOldUmask);
304
				} else {
305
					throw new AccessFileInvalidStructureException('invalid structure - missing file: ' . $sFilename);
306
				}
307
				if (!$bRetval) {
308
					throw new AccessFileWriteableException('Unable to create ' . $sPagesDir . $sParentDir);
309
				}
310
			}
311
		}
312
	}
313
	/**
314
	 * Sanitize value
315
	 * @param mixed Value to sanitize
316
	 * @param string Type of the variable (use class constants to define)
317
	 * @return string printable value
318
	 * @throws InvalidArgumentException
319
	 */
320
	protected function sanitizeValue($mValue, $sType)
321
	{
322
		$mRetval = '';
323
		switch ($sType)
324
		{
325
			case self::VAR_BOOLEAN:
326
			case self::VAR_BOOL:
327
				$mRetval = (filter_var(strtolower($mValue), FILTER_VALIDATE_BOOLEAN) ? '1' : '0');
328
				break;
329
			case self::VAR_INTEGER:
330
			case self::VAR_INT:
331
				if (filter_var($mValue, FILTER_VALIDATE_INT) === false) {
332
					throw new InvalidArgumentException('value is not an integer');
333
				}
334
				$mRetval = (string) $mValue;
335
				break;
336
			case self::VAR_FLOAT:
337
				if (filter_var($mValue, FILTER_VALIDATE_FLOAT) === false) {
338
					throw new InvalidArgumentException('value is not a float');
339
				}
340
				$mRetval = (string) $mValue;
341
				break;
342
			default: // VAR_STRING
343
				$mRetval = '\'' . (string) $mValue . '\'';
344
				break;
345
		}
346
		return $mRetval;
347
	}
348

    
349
	/**
350
	 * Calculate backsteps in directory
351
	 * @param string accessfile
352
	 */
353
	protected function buildPathToIndexFile($sFileName)
354
	{
355
		$iBackSteps = substr_count(str_replace($this->oReg->AppPath, '', $sFileName), '/');
356
		return str_repeat('../', $iBackSteps) . 'index.php';
357
	}
358

    
359
	/**
360
	 * Build the content of the new accessfile
361
	 * @param string $sIndexFile name and path to the wb/index.php file
362
	 * @return string
363
	 */
364
	protected function buildFileContent($sIndexFile)
365
	{
366
		$sFileContent
367
				= '<?php' . "\n"
368
				. '// *** This file was created automatically by ' ."\n"
369
				. '// *** ' . $this->oReg->AppName	. ' Ver.' . $this->oReg->AppVersion
370
				. ($this->oReg->AppServicePack != '' ? ' '.$this->oReg->AppServicePack : '')
371
				. ' Rev.' . $this->oReg->AppRevision . "\n"
372
				. '// *** on ' . date('c') . "\n"
373
				. '//' . "\n"
374
				. '// *** Warning *************************************' . "\n"
375
				. '// *** Please do not manually change this file!' . "\n"
376
				. '// *** It will be recreated from time to time and' . "\n"
377
				. '// *** then all manual changes will get lost!!' . "\n"
378
				. '// *************************************************' . "\n"
379
				. '//' . "\n";
380
		foreach ($this->aVars as $sKey => $sVar) {
381
			$sFileContent .= "\t" . '$' . $sKey . ' = ' . $sVar . ';' . "\n";
382
		}
383
		foreach ($this->aConsts as $sKey => $sVar) {
384
			$sFileContent .= "\t" . 'define(\'' . $sKey . '\', ' . $sVar . '); // ** deprecated command **' . "\n";
385
		}
386
		$sFileContent
387
				.="\t" . 'require(\'' . $sIndexFile . '\');' . "\n"
388
				. "\t" . 'exit();' . "\n"
389
				. '// *************************************************' . "\n"
390
				. '// end of file' . "\n";
391
		return $sFileContent;
392
	}
393

    
394
}
395

    
396
// end of class AccessFile
397
// //////////////////////////////////////////////////////////////////////////////////// //
398
/**
399
 * AccessFileException
400
 *
401
 * @category     WBCore
402
 * @package      WBCore_Accessfiles
403
 * @author       M.v.d.Decken <manuela@isteam.de>
404
 * @copyright    M.v.d.Decken <manuela@isteam.de>
405
 * @license      http://www.gnu.org/licenses/gpl.html   GPL License
406
 * @version      2.9.0
407
 * @revision     $Revision: 2070 $
408
 * @lastmodified $Date: 2014-01-03 02:21:42 +0100 (Fri, 03 Jan 2014) $
409
 * @description  Exceptionhandler for the Accessfiles and depending classes
410
 */
411

    
412
class AccessFileException extends AppException { }
413
class AccessFileInvalidStructureException extends AccessFileException { }
414
class AccessFileIsNoAccessfileException extends AccessFileException { }
415
class AccessFileConstForbiddenException extends AccessFileException { }
416
class AccessFileInvalidFilePathException extends AccessFileException { }
417
class AccessFileRenameException extends AccessFileException { }
418
class AccessFileWriteableException extends AccessFileException { }
(1-1/36)