1: <?php
2: /*
3: You may not change or alter any portion of this comment or credits
4: of supporting developers from this source code or any supporting source code
5: which is considered copyrighted (c) material of the original comment or credit authors.
6:
7: This program is distributed in the hope that it will be useful,
8: but WITHOUT ANY WARRANTY; without even the implied warranty of
9: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10: */
11:
12: namespace Xmf\Key;
13:
14: /**
15: * Xmf\Key\StorageInterface
16: *
17: * load a database table
18: *
19: * @category Xmf\Key\FileStorage
20: * @package Xmf
21: * @author Richard Griffith <richard@geekwright.com>
22: * @copyright 2016 XOOPS Project (http://xoops.org)
23: * @license GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
24: * @link http://xoops.org
25: */
26: class FileStorage implements StorageInterface
27: {
28:
29: /**
30: * Fetch key data by name
31: *
32: * @param string $name key name
33: *
34: * @return string file name
35: */
36: protected function fileName($name)
37: {
38: $syssec = $this->systemSecret();
39: return XOOPS_VAR_PATH . "/data/{$syssec}-key-{$name}.php";
40: }
41:
42: /**
43: * Construct a string related to the system to make name less predictable
44: *
45: * @return string
46: */
47: protected function systemSecret()
48: {
49: $db = \XoopsDatabaseFactory::getDatabaseConnection();
50: $prefix = $db->prefix();
51: $secret = md5($prefix);
52: $secret = substr($secret, 8, 8);
53: return $secret;
54: }
55:
56: /**
57: * Save key data by name
58: *
59: * @param string $name key name
60: * @param string $data key data, serialized to string if required
61: *
62: * @return boolean true if key saved, otherwise false
63: */
64: public function save($name, $data)
65: {
66: if (empty($data) || !is_string($data)) {
67: throw new \DomainException('Invalid key data');
68: }
69: $fileContents = "<?php\n//**Warning** modifying this file will break things!\n"
70: . "return '{$data}';\n";
71: return (false !== file_put_contents($this->fileName($name), $fileContents));
72: }
73:
74: /**
75: * Fetch key data by name
76: *
77: * @param string $name key name
78: *
79: * @return string|false key data (possibly serialized) or false on error
80: */
81: public function fetch($name)
82: {
83: return include $this->fileName($name);
84: }
85:
86: /**
87: * Check if key data exists
88: *
89: * @param string $name key name
90: *
91: * @return boolean true if key exists, otherwise false
92: */
93: public function exists($name)
94: {
95: return file_exists($this->fileName($name));
96: }
97:
98: /**
99: * Delete a key
100: *
101: * @param string $name key name
102: *
103: * @return boolean true if key deleted, otherwise false
104: */
105: public function delete($name)
106: {
107: return unlink($this->fileName($name));
108: }
109: }
110: