aboutsummaryrefslogtreecommitdiff
path: root/bootstrap/comments/backend/classes/database.php
blob: 70984db40edb2b66e0988844cd63faaa75c5762e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
<?php namespace HashOver;

// Copyright (C) 2010-2018 Jacob Barkdull
// This file is part of HashOver.
//
// HashOver is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// HashOver is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with HashOver.  If not, see <http://www.gnu.org/licenses/>.


// Database! Database! Just living in the database! Wow! Wow!
class Database
{
	public $setup;
	public $storageMode;
	public $database;

	public function __construct (Setup $setup)
	{
		$this->setup = $setup;
		$this->storageMode = $setup->databaseType;

		try {
			if ($setup->databaseType === 'sqlite') {
				$sqlite_file = $setup->commentsDirectory . '/' . $setup->databaseName . '.sqlite';
				$this->database = new \PDO ('sqlite:' . $sqlite_file);
			} else {
				$sql_connection = implode (';', array (
					'host=' . $setup->databaseHost,
					'dbname=' . $setup->databaseName,
					'charset=' . $setup->databaseCharset
				));

				$this->database = new \PDO (
					$setup->databaseType . ':' . $sql_connection,
					$setup->databaseUser,
					$setup->databasePassword
				);
			}
		} catch (\PDOException $error) {
			throw new \Exception ($error->getMessage ());
		}
	}

	public function getCommentThread ($thread)
	{
		return ($thread !== 'auto') ? $thread : $this->setup->threadName;
	}

	// Gets the appropriate metadata table name
	protected function getMetaTable ($name, $thread, $global)
	{
		// Check if we're getting metadata for a specific thread
		if ($global !== true) {
			// If so, use the thread's table
			if ($thread === 'auto') {
				$table = $this->setup->threadName . '/metadata';
			} else {
				$table = $thread . '/metadata';
			}
		} else {
			// If not, use the global metadata table
			$table = 'hashover-metadata';
		}

		// Final table name
		$table .= '/' . $name;

		return $table;
	}

	// Read and return specific metadata from JSON file
	public function readMeta ($name, $thread = 'auto', $global = false)
	{
		// Metadata table
		$metadata_table = $this->getMetaTable ($name, $thread, $global);

		// Query statement array
		$statement = 'SELECT * FROM `' . $metadata_table . '`';

		// Query statement
		$results = $this->database->query ($statement);

		// Return threads if successful
		if ($results !== false) {
			$fetch_all = $results->fetchAll (\PDO::FETCH_ASSOC);

			if (isset ($fetch_all[0]['items'])) {
				$columns = array ();

				foreach ($fetch_all as $column) {
					foreach ($column as $key => $value) {
						$columns[] = $value;
					}
				}

				return $columns;
			}

			return $fetch_all[0];
		}

		return false;
	}

	// Create table creation statement from array
	protected function creationStatement (array $columns)
	{
		$statement = array ();

		// Check if the array is associative
		if (array_keys ($columns) !== range (0, count ($columns) - 1)) {
			// If so, create a statement using specific columns
			foreach ($columns as $name => $value) {
				$type = is_numeric ($value) ? 'INTEGER' : 'TEXT';
				$statement[] = sprintf ('`%s` %s', $name, $type);
			}
		} else {
			// If not, create statement using generic "items" column
			$statement[] = '`items` TEXT';
		}

		return $statement;
	}

	// Prepare and execute an SQL statement
	protected function executeStatement ($statement, $data = null)
	{
		try {
			// Prepare statement
			$prepare = $this->database->prepare ($statement);

			// Attempt to execute statement
			if ($prepare !== false) {
				return $prepare->execute ($data);
			}

			return $prepare;

		} catch (\PDOException $error) {
			throw new \Exception ($error->getMessage ());
		}
	}

	// Create comment table if it doesn't exist
	protected function createTable ($name, array $columns)
	{
		// Statement for creating initial comment thread table
		$statement  = 'CREATE TABLE IF NOT EXISTS `' . $name . '` ';
		$statement .= '(' . implode (', ', $columns) . ')';

		// Execute statement
		$created = $this->executeStatement ($statement);

		// Throw exception on failure
		if ($created === false) {
			throw new \Exception (sprintf (
				'Failed to create table "%s"',
				$this->setup->threadName
			));
		}

		return true;
	}

	// Create table query statement from array
	protected function queryStatement (array $columns)
	{
		$statement = array ();

		foreach ($columns as $name => $value) {
			$statement[] = ':' . $name;
		}

		return $statement;
	}

	// Delete all rows from a given table
	protected function deleteAllRows ($table)
	{
		// Deletion statement
		$statement = 'DELETE FROM `' . $table . '`';

		// Execute statement
		$deleted = $this->executeStatement ($statement);

		// Throw exception on failure
		if ($deleted === false) {
			throw new \Exception ('Failed to delete existing metadata!');
		}
	}

	// Save metadata to specific metadata JSON file
	public function saveMeta ($name, array $data, $thread = 'auto', $global = false)
	{
		// Metadata table
		$metadata_table = $this->getMetaTable ($name, $thread, $global);

		// Create metadata table creation statement
		$creation_statement = $this->creationStatement ($data);

		// Attempt to create metadata table
		$this->createTable ($metadata_table, $creation_statement);

		// Delete existing data from database
		$this->deleteAllRows ($metadata_table);

		// Check if the array is associative
		if (array_keys ($data) !== range (0, count ($data) - 1)) {
			// If so, create metadata columns insertion statement array
			$columns = $this->queryStatement ($data);

			// Insert data into specific columns
			$save  = 'INSERT INTO `' . $metadata_table . '` ';
			$save .= 'VALUES (' . implode (', ', $columns) . ')';

			// Execute statement
			$saved = $this->executeStatement ($save, $data);
		} else {
			// If not, insert each item individually
			$save  = 'INSERT INTO `' . $metadata_table . '` ';
			$save .= 'VALUES (:items)';

			// Insert each item individually
			for ($i = 0, $il = count ($data); $i < $il; $i++) {
				// Execute statement
				$saved = $this->executeStatement ($save, array (
					'items' => $data[$i]
				));

				// Stop on any failures
				if ($saved === false) {
					break;
				}
			}
		}

		// Throw exception on failure
		if ($saved === false) {
			throw new \Exception ('Failed to save metadata!');
		}
	}

	public function write ($action, $thread, array $array, $alt = false)
	{
		$thread = $this->getCommentThread ($thread);

		switch ($action) {
			// Action for posting a comment
			case 'insert': {
				$columns = implode (', ', array (
					':id',
					':body',
					':status',
					':date',
					':name',
					':password',
					':login_id',
					':email',
					':encryption',
					':email_hash',
					':notifications',
					':website',
					':ipaddr',
					':likes',
					':dislikes'
				));

				$query  = 'INSERT INTO `' . $thread . '` ';
				$query .= 'VALUES (' . $columns . ')';

				break;
			}

			// Action for editing a comment
			case 'update': {
				$columns = implode (', ', array (
					'body=:body',
					'status=:status',
					'name=:name',
					'password=:password',
					'email=:email',
					'encryption=:encryption',
					'email_hash=:email_hash',
					'notifications=:notifications',
					'website=:website',
					'likes=:likes',
					'dislikes=:dislikes'
				));

				$query  = 'UPDATE `' . $thread . '` ';
				$query .= 'SET ' . $columns . ' ';
				$query .= 'WHERE id=:id';

				break;
			}

			// Action for deleting a comment
			case 'delete': {
				// Check if we're actually deleting the comment
				if ($alt === true) {
					// If so, use delete statement
					$query  = 'DELETE FROM `' . $thread . '` ';
					$query .= 'WHERE id=:id';
				} else {
					// If not, use status update statement
					$query  = 'UPDATE `' . $thread . '` ';
					$query .= 'SET status=:status ';
					$query .= 'WHERE id=:id';
				}

				break;
			}
		}

		// Execute statement
		$queried = $this->executeStatement ($query, $array);

		// Throw exception on failure
		if ($queried === false) {
			throw new \Exception ('Failed to write to database!');
		}

		return true;
	}

	// Create comment thread if it doesn't exist
	public function checkThread ()
	{
		$thread = $this->setup->threadName;

		return $this->createTable ($thread, array (
			'`id` TEXT',
			'`body` TEXT',
			'`status` TEXT',
			'`date` TEXT',
			'`name` TEXT',
			'`password` TEXT',
			'`login_id` TEXT',
			'`email` TEXT',
			'`encryption` TEXT',
			'`email_hash` TEXT',
			'`notifications` TEXT',
			'`website` TEXT',
			'`ipaddr` TEXT',
			'`likes` INTEGER',
			'`dislikes` INTEGER'
		));
	}

	// Queries a list of comment threads
	public function queryThreads ()
	{
		// Database name
		$name = $this->setup->databaseName;

		// Check if database type if SQLite
		if ($this->setup->databaseType === 'sqlite') {
			// If so, use SQLite statement
			$statement  = 'SELECT * FROM sqlite_master ';
			$statement .= 'WHERE type=\'table\'';
		} else {
			// If not, use MySQL statement
			$statement  = 'SELECT * FROM INFORMATION_SCHEMA.TABLES ';
			$statement .= 'WHERE TABLE_TYPE=\'BASE TABLE\' ';
			$statement .= 'AND TABLE_SCHEMA=\'' . $name . '\'';
		}

		// Query statement
		$results = $this->database->query ($statement);

		// Return threads if successful
		if ($results !== false) {
			$fetch_all = $results->fetchAll (\PDO::FETCH_ASSOC);
			$threads = array ();

			foreach ($fetch_all as $table) {
				$threads[] = $table['name'];
			}

			return $threads;
		}

		return false;
	}
}