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
 * @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  $sNewName 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 [' . str_replace($this->_oReg->AppPath, '', $sNewName) . ']');
145
		}
146
		// prepare old/new file-/dirname
147
		$sOldFilename   = $this->_sFileName;
148
		$sOldSubDirname = dirname($sOldFilename) . '/';
149
		$sBaseDirname   = dirname($sOldSubDirname) . '/';
150
		$sPattern = '/^(' . preg_quote($sOldSubDirname, '/') . ')([^\/\.]+?)(\.[a-z0-9]+)$/siU';
151
		$sNewFilename = preg_replace($sPattern, '\1' . $sNewName . '\3', $sOldFilename);
152
		$sNewSubDirname = dirname($sNewFilename) . '/';
153
		if (file_exists($sNewFilename) || file_exists($sNewSubDirname)) {
154
			// if new filename or directory already exists
155
			throw new AccessFileAlreadyExistsException('new file/dirname already exists [' . str_replace($this->_oReg->AppPath, '', $sNewName) . ']');
156
		}
157
		if(!is_writeable($sOldFilename)) {
158
			throw new AccessFileRenameException('unable to rename file or file not exists [' . str_replace($this->_oReg->AppPath, '', $sOldFilename) . ']');
159
		}
160
		$bSubdirRenamed = false; // set default value
161
		if(file_exists($sOldSubDirname))
162
		{ //
163
			if(is_writeable($sOldSubDirname))
164
			{
165
				if(!( $bSubdirRenamed = rename($sOldSubDirname, $sNewSubDirname))) {
166
					throw new AccessFileRenameException('unable to rename directory [' . str_replace($this->_oReg->AppPath, '', $sOldSubDirname) . ']');
167
				}
168
			} else {
169
				throw new AccessFileRenameException('directory is not writeable [' . str_replace($this->_oReg->AppPath, '', $sOldSubDirname) . ']');
170
			}
171
		}
172
		// try to rename accessfile
173
		if(!rename($sOldFilename, $sNewFilename)) {
174
			if($bSubdirRenamed) { rename($sNewSubDirname, $sOldSubDirname); }
175
			throw new AccessFileRenameException('unable to rename file [' . str_replace($this->_oReg->AppPath, '', $sOldFilename) . ']');
176
		}
177
		return true;
178
	}
179

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

    
206
	/**
207
	 * getFilename
208
	 * @return string path+name of the current accessfile
209
	 */
210
	public function getFileName()
211
	{
212
		return $this->_sFileName;
213
	}
214

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

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

    
314
	/**
315
	 * Calculate backsteps in directory
316
	 * @param string accessfile
317
	 */
318
	protected function _buildPathToIndexFile($sFileName)
319
	{
320
		$iBackSteps = substr_count(str_replace($this->_oReg->AppPath, '', $sFileName), '/');
321
		return str_repeat('../', $iBackSteps) . 'index.php';
322
	}
323

    
324
	/**
325
	 * Build the content of the new accessfile
326
	 * @param string $sIndexFile name and path to the wb/index.php file
327
	 * @return string
328
	 */
329
	protected function _buildFileContent($sIndexFile)
330
	{
331
		$sFileContent
332
				= '<?php' . "\n"
333
				. '// *** This file was created automatically by ' ."\n"
334
				. '// *** ' . $this->_oReg->AppName	. ' Ver.' . $this->_oReg->AppVersion
335
				. ($this->_oReg->AppServicePack != '' ? ' '.$this->_oReg->AppServicePack : '')
336
				. ' Rev.' . $this->_oReg->AppRevision . "\n"
337
				. '// *** on ' . date('c') . "\n"
338
				. '//' . "\n"
339
				. '// *** Warning *************************************' . "\n"
340
				. '// *** Please do not manually change this file!' . "\n"
341
				. '// *** It will be recreated from time to time and' . "\n"
342
				. '// *** then all manual changes will get lost!!' . "\n"
343
				. '// *************************************************' . "\n"
344
				. '//' . "\n";
345
		foreach ($this->_aVars as $sKey => $sVar) {
346
			$sFileContent .= "\t" . '$' . $sKey . ' = ' . $sVar . ';' . "\n";
347
		}
348
		foreach ($this->_aConsts as $sKey => $sVar) {
349
			$sFileContent .= "\t" . 'define(\'' . $sKey . '\', ' . $sVar . '); // ** deprecated command **' . "\n";
350
		}
351
		$sFileContent
352
				.="\t" . 'require(\'' . $sIndexFile . '\');' . "\n"
353
				. "\t" . 'exit(0);' . "\n"
354
				. '// *************************************************' . "\n"
355
				. '// end of file' . "\n";
356

    
357
		return $sFileContent;
358
	}
359

    
360
}
361

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

    
378
class AccessFileException extends Exception { }
379
class AccessFileConstForbiddenException extends AccessFileException { }
380
class AccessFileInvalidFilePathException extends AccessFileException { }
381
class AccessFileInvalidFilenameException extends AccessFileException { }
382
class AccessFileAlreadyExistsException extends AccessFileException { }
383
class AccessFileNotWriteableException extends AccessFileException { }
384
class AccessFileIsInvalidFilenameException extends AccessFileException { }
385
class AccessFileIsNoAccessfileException extends AccessFileException { }
386
class AccessFileInvalidStructureException extends AccessFileException { }
387
class AccessFileRenameException extends AccessFileException { }
(1-1/34)