forked from aaroneiche/do-want
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.class.php
executable file
·388 lines (286 loc) · 9.87 KB
/
db.class.php
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
<?php
class db{
public $dbname;
public $dbuser;
public $dbpass;
public $dbhost;
public $dbcharSet;
private $dbConn;
public $debug;
function dbConnect(){
$this->dbConn = mysqli_connect($this->dbhost,$this->dbuser,$this->dbpass);
if($this->dbcharSet != ''){
$setChar = mysqli_set_charset($this->dbConn,$this->dbcharSet);
}
$select = mysqli_select_db($this->dbConn,$this->dbname);
if(!$select){
$response = array(
"error"=>mysqli_errno($this->dbConn),
"message"=>mysqli_error($this->dbConn)
);
return $response;
}else{
return true;
}
}
function dbQuery($query){
$result = mysqli_query($this->dbConn,$query);
if($result !== false){
return $result;
}else{
error_log(mysqli_error($this->dbConn)." ".$query);
}
}
function dbValue($resource){
return mysqli_result($resource,0);
}
function dbAssoc($resource, $forceMulti = false){
/*
@resource: The Mysql Resource containing the data.
@forceMulti: Forces the row data to be put in an array, regardless of row count.
*/
while($row = mysqli_fetch_assoc($resource)){
if(mysqli_num_rows($resource) > 1 || $forceMulti == true){ //
$assocData[] = $row;
}else{
$assocData = $row;
}
}
if (!isset($assocData)) {
$assocData = NULL;
}
return $assocData;
}
function dbLastInsertId(){
return mysqli_insert_id($this->dbConn);
}
function dbRowCount($resource){
return mysqli_num_rows($resource);
}
//The escape function is built here so we can swap DB classes.
function dbEscape($queryString){
return mysqli_real_escape_string($this->dbConn,$queryString);
}
function dbDisconnect(){
mysqli_close($this->dbConn);
}
function __deconstruct(){
$this->dbDisconnect();
}
/*
Method sendMessage
Sends a message from the current user to another user in the system.
Because both user and wishlist classes need access to this method, it's being defined here.
senderId - The id of the Sender
receiverId - The id of the receiver
message - The Text of the Message
forceEmail - If this is true, email will be sent regardless of preference.
*/
function sendMessage($args){
$cleanSenderId = $this->dbEscape($args['senderId']);
$cleanReceiverId = $this->dbEscape($args['receiverId']);
$cleanMessage = $this->dbEscape($args['message']);
$cleanForceEmail = $this->dbEscape($args['forceEmail']);
$emailQuery = "select {$this->options["table_prefix"]}users.*, (select {$this->options["table_prefix"]}users.fullname from {$this->options["table_prefix"]}users where {$this->options["table_prefix"]}users.userid = $cleanSenderId) as senderFullname from {$this->options["table_prefix"]}users where userid = $cleanReceiverId";
/*
//This should be a compatible table prefix version of the above query. Kept here for later.
$emailQuery = "Select u.*,
(select u.fullname
from {$this->options["table_prefix"]}users as u
where u.userid = $cleanSenderId)
as senderFullname
from
{$this->options["table_prefix"]}users as u
where u.userid = $cleanReceiverId";
*/
$usersResult = $this->dbAssoc($this->dbQuery($emailQuery));
$query = "insert into {$this->options["table_prefix"]}messages(sender,recipient,message,created) values($cleanSenderId,$cleanReceiverId,\"$cleanMessage\",NOW())";
$result = $this->dbQuery($query);
$subject = "New message from the Wishlist!";
if($usersResult['email_msgs'] == 1 || $cleanForceEmail == 1){
$mailresult = mail($usersResult['email'],$subject,stripslashes($args['message']));
return $mailresult;
}
return $result;
}
function markMessageRead($messageId){
$query = "update {$this->options["table_prefix"]}messages set isread = 1 where messageid = $messageId";
$result = $this->dbQuery($query);
return $result;
}
/*
Method manageEvent
Adds, updates or deletes an event in the system
eventaction - which action to take: add, edit, or delete
eventid - (for edit or delete) The id of the event to manage.
userid - The id of the user creating this event.
date - The date of this event
description - A description of this event
recurring - whether or not this event
*/
function manageEvent($args){
}
/*
Method: checkForUpdates
Checks with a defined remote server to determine if any updates are available.
*/
function checkForUpdates(){
if (function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->options['updateSource']."?v=".VERSION);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, USER_AGENT_STRING);
$content = curl_exec($ch);
curl_close($ch);
return json_decode($content);
}else{
return array('message'=>"CURL is not installed.");
}
}
/*
Method: updateFiles
Unpacks an update, checks it for validity, and processes an update.
Returns a list of updated files.
@fileArray - The manifest file data (with filenames and relevant MD5 checksums)
@zipArchive - The zipArchive object created with the update archive.
*/
function updateFiles($fileArray,$zipArchive){
$responseObject = array(
"updateList"=>array()
);
foreach($fileArray as $file){
if(!isset($file['name'])){
$this->updateFiles($file,$zipArchive);
}else{
$fileChecksum = md5_file($file['path'].$file['name']);
if($fileChecksum != $file['checksum']){
$result = $zipArchive->extractTo(rtrim($file['path'],'/'), $file['name']);
if($result){
$responseObject['updateList'][$file['name']] = "Updated!";
}else{
$responseObject['updateList'][$file['name']] = "Update failed";
}
}
}
}
return $responseObject;
}
/*
Method: systemUpdate
Unzips an update archive, retrieves the manifest and applies updates across the file structure.
@updateFileLocation - the relative path to the file update.
*/
function systemUpdate($args){
$zip = new ZipArchive;
$res = $zip->open($args['updateFileLocation']);
if($res == true){
$manifestLocation = $zip->locateName("manifest.json");
$manifestFile = $zip->getFromIndex($manifestLocation);
$manifest = json_decode($manifestFile,true);
return $this->updateFiles($manifest['files'],$zip);
}
}
/*
Method: downloadUpdateFile
Downloads a file to the defined uploads directory and returns the path when complete.
@fileUri - The URI of the file to download.
@fileName - The Name of the file.
*/
function downloadUpdateFile($args){
if (function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->options['updateSource'].$args['fileUri']);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, USER_AGENT_STRING);
$content = curl_exec($ch);
error_log(curl_error($ch));
curl_close($ch);
$copiedfile = file_put_contents($this->options['filepath'].$args['fileName'], $content);
error_log($copiedfile);
$returnArray = array();
$returnArray['updateDownloaded'] = ($copiedfile === false)? false : true;
$returnArray['file'] = $args['fileName'];
$returnArray['fileSize'] = $copiedfile;
return $returnArray;
}
}
/*
Method: backupApp
This method builds a file-copy backup of the Do Want application. It adds items into a ZIP archive.
@exclude - an array of items to exclude.
*/
function backupApp($exclude = array()){
$backupName = "doWantBackup_".date("Ymd").".zip";
$zip = new ZipArchive();
$res = $zip->open($this->options['filepath'].$backupName,ZipArchive::CREATE);
//MySQL backup needs to be added in here as well.
$exclude_defaults = array(".", "..", ".htaccess", ".DS_Store",".git",".gitignore","custom","uploads","generateUpdate.php","update.zip");
$exclude_list = array_merge($exclude_defaults,$exclude);
$this->recursiveCreateArchive("./", $zip, $exclude_list);
//$zip->addFromString('manifest.json', json_encode($manifestArray));
$zip->close();
}
/*
Method: recursiveCreateArchive
Recursively iterates through a directory tree and adds all items to a zip Archive.
@dir - The directory to start in.
@zipArchive - An instantiated ZipArchive Object.
@zipdir - Optional:
*/
function recursiveCreateArchive($dir, $zipArchive, $excludeArray, $zipdir = ''){
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
//Add the directory
if(!empty($zipdir)) $zipArchive->addEmptyDir($zipdir);
// Loop through all the files
while (($file = readdir($dh)) !== false) {
if(!in_array($file,$excludeArray)){
//If it's a folder, run the function again!
if(!is_file($dir . $file)){
// Skip parent and root directories
$this->recursiveCreateArchive($dir . $file . "/", $zipArchive, $excludeArray, $zipdir . $file . "/");
}else{
// Add the files
$zipArchive->addFile($dir . $file, $zipdir . $file);
}
}
}
}
}
}
/*
Method: getDBPermissions
Gets grants for the db user on
*/
function getDBPermissions(){
$validPermissions = array(
"SELECT",
"INSERT",
"UPDATE",
"DELETE",
"CREATE",
"ALTER",
"DROP",
"ALL"
);
$query = "show grants for `{$this->dbuser}`@`{$this->dbhost}`";
$grantsResult = $this->dbAssoc($this->dbquery($query));
$grantSet = array();
//GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER ON *.* TO 'wishlist'@'localhost' IDENTIFIED BY PASSWORD '*A99D97056D4D0C7D7D453D99AB02F34E7CDD4160'
foreach($grantsResult as $grant){
$keyName = array_keys($grant);
$grantItems = explode(" TO ",$grant[$keyName[0]]);
$individualPermissions = explode($grantItems[0]," ");
foreach($individualPermissions as $word){
print $word;
if(in_array(trim($word," ,"),$validPermissions)){
$grantSet[] = $word;
}
}
}
return $grantSet;
}
}
?>