Project

General

Profile

1 1947 darkviper
<?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 1982 darkviper
/**
106
 * Write the accessfile
107
 * @throws AccessFileException
108
 */
109 1947 darkviper
	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 1949 darkviper
	 * @param  string  $sNewName the new filename without path and without extension
135 1947 darkviper
	 * @return boolean
136
	 * @throws AccessFileInvalidFilenameException
137
	 * @throws AccessFileAlreadyExistsException
138
	 * @throws AccessFileAccessFileRenameException
139
	 */
140
	public function rename($sNewName)
141
	{
142
		// sanitize new filename
143 1949 darkviper
		if (!preg_match('/[^\.\\ \/]*/si', $sNewName)) {
144
			throw new AccessFileInvalidFilenameException('invalid filename [' . str_replace($this->_oReg->AppPath, '', $sNewName) . ']');
145 1947 darkviper
		}
146
		// prepare old/new file-/dirname
147 1949 darkviper
		$sOldFilename   = $this->_sFileName;
148 1947 darkviper
		$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 1949 darkviper
			// if new filename or directory already exists
154
			throw new AccessFileAlreadyExistsException('new file/dirname already exists [' . str_replace($this->_oReg->AppPath, '', $sNewName) . ']');
155 1947 darkviper
		}
156 1949 darkviper
		if(!is_writeable($sOldFilename)) {
157
			throw new AccessFileRenameException('unable to rename file or file not exists [' . str_replace($this->_oReg->AppPath, '', $sOldFilename) . ']');
158
		}
159
		$bSubdirRenamed = false; // set default value
160
		if(file_exists($sOldSubDirname))
161
		{ //
162
			if(is_writeable($sOldSubDirname))
163 1947 darkviper
			{
164 1949 darkviper
				if(!( $bSubdirRenamed = rename($sOldSubDirname, $sNewSubDirname))) {
165
					throw new AccessFileRenameException('unable to rename directory [' . str_replace($this->_oReg->AppPath, '', $sOldSubDirname) . ']');
166 1947 darkviper
				}
167 1949 darkviper
			} else {
168
				throw new AccessFileRenameException('directory is not writeable [' . str_replace($this->_oReg->AppPath, '', $sOldSubDirname) . ']');
169 1947 darkviper
			}
170
		}
171 1949 darkviper
		// 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) . ']');
175 1947 darkviper
		}
176 1949 darkviper
		return true;
177 1947 darkviper
	}
178
179
	/**
180
	 * Delete the actual Accessfile
181
	 * @return boolean true if successfull
182
	 * @throws AccessFileIsNoAccessfileException
183
	 * @throws AccessFileNotWriteableException
184
	 */
185
	public function delete($bForceDelete = true)
186
	{
187
		$sFileName = $this->_sFileName;
188
		if (!AccessFileHelper::isAccessFile($sFileName)) {
189
			throw new AccessFileIsNoAccessfileException('requested file is NOT an accessfile');
190
		}
191
		if (file_exists($sFileName) && is_writeable($sFileName))
192
		{
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);
197
			}
198
			unlink($sFileName);
199
			$sFileName = '';
200
		} else {
201
			throw new AccessFileNotWriteableException('requested file not exists or permissions missing');
202
		}
203
	}
204
205
	/**
206
	 * getFilename
207
	 * @return string path+name of the current accessfile
208
	 */
209
	public function getFileName()
210
	{
211
		return $this->_sFileName;
212
	}
213
214
	/**
215
	 * getPageId
216
	 * @return integer
217
	 */
218
	public function getPageId()
219
	{
220
		return (isset($this->_aVars['iPageId']) ? $this->_aVars['iPageId'] : 0);
221
	}
222
	/**
223
	 * get number of the last occured error
224
	 * @return int
225
	 */
226
	public function getError()
227
	{
228
		return $this->_iErrorNo;
229
	}
230
	/**
231
	 * set number of error
232
	 * @param type $iErrNo
233
	 */
234
	protected function _setError($iErrNo = self::ERR_NONE)
235
	{
236
		$this->_iErrorNo = $iErrNo;
237
	}
238
	/**
239
	 * Create Path to Accessfile
240
	 * @param string full path/name to new access file
241
	 * @throws AccessFileNotWriteableException
242
	 * @throws AccessFileInvalidStructureException
243
	 */
244
	protected function _createPath($sFilename)
245
	{
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
		{
251
			// if subdirs exists, then procceed extended check
252
			$sExtension = preg_replace('/.*?(\.[a-z][a-z0-9]+)$/siU', '\1', $sFilename);
253
			$sParentDir = mb_substr($sFilename, 0, $iSlashPosition);
254
			if (file_exists($sPagesDir . $sParentDir))
255
			{
256
				if (!is_writable($sPagesDir . $sParentDir)) {
257
					throw new AccessFileNotWriteableException('No write permissions for ' . $sPagesDir . $sParentDir);
258
				}
259
			} else
260
			{
261
				// if parentdir not exists
262
				if (file_exists($sPagesDir . $sParentDir . $sExtension))
263
				{
264
					// but parentaccessfile exists, create parentdir and ok
265
					$iOldUmask = umask(0);
266
					$bRetval = mkdir($sPagesDir . $sParentDir, $this->_oReg->OctalDirMode);
267
					umask($iOldUmask);
268
				} else {
269
					throw new AccessFileInvalidStructureException('invalid structure ' . $sFilename);
270
				}
271
				if (!$bRetval) {
272
					throw new AccessFileNotWriteableException('Unable to create ' . $sPagesDir . $sParentDir);
273
				}
274
			}
275
		}
276
	}
277
	/**
278
	 * Sanitize value
279
	 * @param mixed Value to sanitize
280
	 * @param string Type of the variable (use class constants to define)
281
	 * @return string printable value
282
	 * @throws InvalidArgumentException
283
	 */
284
	protected function _sanitizeValue($mValue, $sType)
285
	{
286
		$mRetval = '';
287
		switch ($sType)
288
		{
289
			case self::VAR_BOOLEAN:
290
			case self::VAR_BOOL:
291
				$mRetval = (filter_var(strtolower($mValue), FILTER_VALIDATE_BOOLEAN) ? '1' : '0');
292
				break;
293
			case self::VAR_INTEGER:
294
			case self::VAR_INT:
295
				if (filter_var($mValue, FILTER_VALIDATE_INT) === false) {
296
					throw new InvalidArgumentException('value is not an integer');
297
				}
298
				$mRetval = (string) $mValue;
299
				break;
300
			case self::VAR_FLOAT:
301
				if (filter_var($mValue, FILTER_VALIDATE_FLOAT) === false) {
302
					throw new InvalidArgumentException('value is not a float');
303
				}
304
				$mRetval = (string) $mValue;
305
				break;
306
			default: // VAR_STRING
307
				$mRetval = '\'' . (string) $mValue . '\'';
308
				break;
309
		}
310
		return $mRetval;
311
	}
312
313
	/**
314
	 * Calculate backsteps in directory
315
	 * @param string accessfile
316
	 */
317
	protected function _buildPathToIndexFile($sFileName)
318
	{
319
		$iBackSteps = substr_count(str_replace($this->_oReg->AppPath, '', $sFileName), '/');
320
		return str_repeat('../', $iBackSteps) . 'index.php';
321
	}
322
323
	/**
324
	 * Build the content of the new accessfile
325
	 * @param string $sIndexFile name and path to the wb/index.php file
326
	 * @return string
327
	 */
328
	protected function _buildFileContent($sIndexFile)
329
	{
330
		$sFileContent
331
				= '<?php' . "\n"
332 1949 darkviper
				. '// *** This file was created automatically by ' ."\n"
333
				. '// *** ' . $this->_oReg->AppName	. ' Ver.' . $this->_oReg->AppVersion
334
				. ($this->_oReg->AppServicePack != '' ? ' '.$this->_oReg->AppServicePack : '')
335 1947 darkviper
				. ' Rev.' . $this->_oReg->AppRevision . "\n"
336 1949 darkviper
				. '// *** on ' . date('c') . "\n"
337
				. '//' . "\n"
338
				. '// *** Warning *************************************' . "\n"
339
				. '// *** Please do not manually change this file!' . "\n"
340
				. '// *** It will be recreated from time to time and' . "\n"
341
				. '// *** then all manual changes will get lost!!' . "\n"
342
				. '// *************************************************' . "\n"
343
				. '//' . "\n";
344 1947 darkviper
		foreach ($this->_aVars as $sKey => $sVar) {
345
			$sFileContent .= "\t" . '$' . $sKey . ' = ' . $sVar . ';' . "\n";
346
		}
347
		foreach ($this->_aConsts as $sKey => $sVar) {
348 1949 darkviper
			$sFileContent .= "\t" . 'define(\'' . $sKey . '\', ' . $sVar . '); // ** deprecated command **' . "\n";
349 1947 darkviper
		}
350
		$sFileContent
351 1949 darkviper
				.="\t" . 'require(\'' . $sIndexFile . '\');' . "\n"
352
				. "\t" . 'exit(0);' . "\n"
353 1947 darkviper
				. '// *************************************************' . "\n"
354
				. '// end of file' . "\n";
355
356
		return $sFileContent;
357
	}
358
359
}
360
361
// end of class AccessFile
362
// //////////////////////////////////////////////////////////////////////////////////// //
363
/**
364
 * AccessFileException
365
 *
366
 * @category     WBCore
367
 * @package      WBCore_Accessfiles
368
 * @author       M.v.d.Decken <manuela@isteam.de>
369
 * @copyright    M.v.d.Decken <manuela@isteam.de>
370
 * @license      http://www.gnu.org/licenses/gpl.html   GPL License
371
 * @version      2.9.0
372
 * @revision     $Revision: 12 $
373
 * @lastmodified $Date: 2012-12-29 21:39:37 +0100 (Sa, 29 Dez 2012) $
374
 * @description  Exceptionhandler for the Accessfiles and depending classes
375
 */
376
377
class AccessFileException extends Exception { }
378
class AccessFileConstForbiddenException extends AccessFileException { }
379
class AccessFileInvalidFilePathException extends AccessFileException { }
380 1949 darkviper
class AccessFileInvalidFilenameException extends AccessFileException { }
381 1947 darkviper
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 1949 darkviper
class AccessFileRenameException extends AccessFileException { }