-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathqa-user-import.php
500 lines (400 loc) · 12.6 KB
/
qa-user-import.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
<?php
/*
Question2Answer (c) 2011, Gideon Greenspan
http://www.question2answer.org/
File: qa-plugin/qa-user-import/qa-user-import.php
Version: (see qa-plugin.php)
Description: Module class for DB Backup plugin
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program 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 General Public License for more details.
More about this license: http://www.question2answer.org/license.php
*/
/*
* Plugin definitions
* TODO: Check if there is there is a better way of tackling this via Q2A API
*/
class qa_user_import {
var $urltoroot;
var $currentUrlDir;
var $savedpath = "";
var $error = "";
var $msg = "";
var $userimportDirUrl ="";
var $fileCount = 0;
var $listedFiles = "";
var $userimportDir = "";
function load_module($directory, $urltoroot)
{
$this->urltoroot=$urltoroot;
$this->currentUrlDir = $directory;
}
function option_default($option)
{
if ($option=='user_import_max_records') {
return 5000;
}
}
function admin_form(&$qa_content)
{
/*
* Add libraries
*/
require_once QA_INCLUDE_DIR.'qa-app-blobs.php';
require_once QA_INCLUDE_DIR.'qa-app-users.php';
require_once QA_INCLUDE_DIR.'qa-app-users-edit.php';
/*
* Declare global variables
*/
global $qa_root_url_relative, $QA_CONST_PATH_MAP;
/*
* Set up directory
*/
$this->userimportDirUrl = $qa_root_url_relative . "qa-content/userimport/";
$this->userimportDir = QA_BASE_DIR."qa-content/userimport/";
/* create dir if it doesn't exist */
if (!is_dir($this->userimportDir))
mkdir($this->userimportDir, 0755);
/*
* File status
*/
$this->listedFiles = $this->listFiles();
/**
* Events
*/
/*
* Delete All files
*/
if (qa_clicked('userimport_delete_files')) {
$this->doDelete();
}
/*
* Upload file
*/
if (qa_clicked('userimport_send_upload_file')) {
if (isset($_FILES["userimport_upload_file"])) {
$this->uploadFile();
}
}//
/*
* Test uploaded file
*/
if (qa_clicked('userimport_test_button')) {
$this->doImport();
}
/*
* Import users
*/
if (qa_clicked('userimport_import_button')) {
$this->doImport(TRUE);
}
/*
* Return HTML form for Admin panel/widget
*/
$this->listedFiles = $this->listFiles();
return array(
'ok' => $this->error ? '<span style="color:#f00;">ERROR: '.$this->error.'</span>' : ($this->msg ? $this->msg : null),
'tags' => ' method="post" action="'.qa_admin_plugin_options_path(QA_PLUGIN_DIR . QA_USER_IMPORT_PARENT_DIR . "/").'" enctype="multipart/form-data" ', // File upload form tags
'fields' => array(
array(
'label' => $this->listedFiles,
'type' => 'static',
'value' => '<input type="file" name="userimport_upload_file" class="qa-form-tall-button qa-form-tall-button-0" /> '.
'<input type="submit" value="Upload to server" name="userimport_send_upload_file" onclick="bck_t=\'\'" class="qa-form-tall-button qa-form-tall-button-0" /><br />'.
'<input type="submit" value="Delete all files" name="userimport_delete_files" onclick="bck_t=\'delete all files from a backup folder\'" class="qa-form-tall-button qa-form-tall-button-0" />',
'tags' => 'NAME="userimport_importFile"',
),
array(
'label' => '<span style="color:#f99; font-size:20px; text-align:center;">Caution! Ensure user CSV file is correctly formatted:<br />"<email>","<password>","<username>",',
'type' => 'custom',
'tags' => 'NAME="userimport_import_label"',
),
),
'buttons' => array(
array(
'label' => 'Import selected file !',
'tags' => 'NAME="userimport_import_button" onclick="confirm(\'Are you sure?\')" onmouseup="bck_t=\'It is recommended to make a backup first.\n\nNOTE: Backup files done with this plugin delete previous data and then do the import\'"',
),
array(
'label' => 'Test selected file !',
'tags' => 'NAME="userimport_test_button" onmouseup="bck_t=\'If you import data with the wrong format it won\'t work. \nIt is recommended to make a backup first.\n\nNOTE: Backup files done with this plugin delete previous data and then do the import\'"',
),
),
);
}//admin_form
/**
* Upload a file
* Enter description here ...
*/
function uploadFile()
{
$allowedExtensions = array("csv");
$allowedMimeTypes = array('text/csv',
'text/plain',
'application/csv',
'text/comma-separated-values',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel',
'text/anytext',
'application/octet-stream',
'application/txt',);
$filenameParts = explode(".", $_FILES["userimport_upload_file"]["name"]);
$extension = end($filenameParts);
if (!in_array($extension, $allowedExtensions)) {
$this->error = "Import only works with CSV files.";
return;
}
if ($_FILES["userimport_upload_file"]["size"] > 2*1024*1024) {
$this->error = "File is too large (".$this->formatKB($_FILES["userimport_upload_file"]["size"]).").";
return;
}
if (!$_FILES["userimport_upload_file"]["name"]) {
$this->error = "No files selected. Please, select a file.<br />";
return;
}
if (!in_array($_FILES["userimport_upload_file"]["type"], $allowedMimeTypes)) {
$this->error = "Wrong file type: ".$_FILES["userimport_upload_file"]["type"].". <br />You can only upload csv files!";
return;
}
if ($_FILES["userimport_upload_file"]["error"]) {
$this->error = " code: ".$_FILES["userimport_upload_file"]["error"]." - unexpected one...<br />";
return;
}
$dir = $this->userimportDir;
if (file_exists($dir . $_FILES["userimport_upload_file"]["name"]))
@unlink($dir . $_FILES["userimport_upload_file"]["name"]);
if (file_exists($dir . $_FILES["userimport_upload_file"]["name"]))
{
$this->error .= "Could not delete file ".$_FILES["userimport_upload_file"]["name"] . ". ";
}
else
{
move_uploaded_file($_FILES["userimport_upload_file"]["tmp_name"],
$dir . $_FILES["userimport_upload_file"]["name"]);
$this->msg = "File uploaded to: <br />" . $dir . $_FILES["userimport_upload_file"]["name"] . "<br />";
$this->msg .= "(type: " . $_FILES["userimport_upload_file"]["type"] . ", ";
$this->msg .= "size: " . ceil(($_FILES["userimport_upload_file"]["size"] / 1024)) . " KB)<br />";
}
}//uploadFile
/**
* Delete files
* Enter description here ...
*/
function doDelete()
{
$fileArr = $this->getFiles($this->userimportDir);
if (count($fileArr) == 0)
{
$this->msg = "There are no files to delete.";
return;
}
for ($i=0; $i < count($fileArr); $i++)
{
if (file_exists($this->userimportDir.$fileArr[$i]))
@unlink($this->userimportDir.$fileArr[$i]);
if (file_exists($this->userimportDir.$fileArr[$i]))
$this->error .= $this->userimportDir.$fileArr[$i] . "<br />";
}
if (strlen($this->error) > 0)
$this->error = "Can't delete files (are they locked by another process?): <br />".$this->error;
else
$this->msg = 'Files deleted';
}// doDelete
/**
* Import process
* Enter description here ...
*/
function doImport($live = FALSE)
{
if ($this->fileCount == 0)
{
$this->error = "No files found. Please, upload first.";
return;
}
$fileName = qa_post_text('file_name_selected');
if (!$fileName)
{
$this->error = "No files selected. Please, select a file.";
return;
}
$path = QA_BASE_DIR."qa-content/userimport" . "/" . $fileName;
if (!file_exists($path))
{
$this->error = "File does not exist: ". $path;
return;
}
/* import the file */
$this->launchCSVFile($path, $this->error, $live);
}
/**
* Import users via a CSV file
* Enter description here ...
* @param unknown_type $path
* @param unknown_type $error
*/
function launchCSVFile($path, &$error, $live = FALSE)
{
/* set up vars*/
$file = null;
$row = 1;
if (($handle = fopen($path, "r")) !== FALSE) {
/* Check the file isn't empty */
$size = filesize($path);
if(!$size)
{
$this->error = "File is empty: ". $path;
return;
}
/*
* Run through the file contents, line by line.
*
* While we still have rows appearing
*/
$importData = "<table>";
$importData .= "<tr><th>Count</th><th>Email</th><th>Password</th><th>Username</th><th>Info</th></tr>";
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
/* check the users is not already registered */
/*
* Filter handle/email
*/
$errors = qa_handle_email_filter($data[2], $data[0]);
/* check for unique username (handle) */
if(qa_handle_make_valid($data[2])) {
$usernameOK = true;
} else {
$usernameOK = false;
}
/* check for unique email address */
if(false) {
$emailOK = true;
} else {
$emailOK = false;
}
/*
* Insert data
*
* Email = $data[0]
* Password = $data[1]
* Username (handle) = $data[2]
*
*/
if(count($errors) == 0) {
if($live) {
$response = qa_create_new_user($data[0], $data[1], $data[2], QA_USER_LEVEL_BASIC, true);
} else {
$response = "Checked!";
}
} else {
/* output the errors generated */
$response = "";
foreach($errors as $line) {
$response .= $line ."<br />";
}
}
/* show the data */
$num = count($data);
$importData .= "<tr>";
$importData .= "<td>".$row."</td>";
for ($c=0; $c < $num; $c++) {
$importData .= "<td>" . $data[$c] . "</td>";
}
$importData .= "<td>".$response."</td>";
$importData .= "</tr>";
$row++;
}//while
$importData .= "</table>";
fclose($handle);
$this->msg = $importData;
} else {
$this->error = "Error opening data file: ". $path;
return;
}//if fopen
}//launchFile
/**
* Get a list of files
*/
function getFiles($dirpath)
{
$myDirectory = opendir($dirpath);
while($entryName = readdir($myDirectory))
$dirArray[] = $entryName;
closedir($myDirectory);
sort($dirArray);
$indexCount = count($dirArray);
$filesArr = array();
for ($index=0; $index < $indexCount; $index++)
{
if (substr("$dirArray[$index]", 0, 1) != "." // don't list hidden files
&& !$this->endsWith($dirArray[$index], "index.php") // ignore index.php
&& !is_dir($dirpath.$dirArray[$index]) // don't list directories
)
{
$filesArr[] = $dirArray[$index];
}
}
return $filesArr;
}
/**
*
* get a list of stored files.
*/
function listFiles()
{
$fileArr = $this->getFiles($this->userimportDir);
$strFiles = "";
for ($i=0; $i < count($fileArr); $i++)
{
$strFiles .= "<input type=\"radio\" name=\"file_name_selected\" value=\"$fileArr[$i]\">".
"<a href=\"".$this->userimportDirUrl.$fileArr[$i]."\" target=\"_blank\">$fileArr[$i]</a> (".$this->formatKB(@filesize($this->userimportDir.$fileArr[$i])).")".
"</input><br />";
}
$this->fileCount = count($fileArr);
$res = "";
if ($this->fileCount > 0)
{
$res .= '<div style="color:#000; font-size:12px; text-align:left; width:500px;">';
$res .= 'Files in User Import folder:<br />';
$res .= $strFiles;
$res .= "</div>";
}
return $res;
}
function formatKB($number)
{
if (!$number)
return 0;
$number = ceil($number/1024);
return number_format($number, 0, ",", " ")." KB";
}
function getDir($path)
{
$res = "";
$slash1 = strrpos($path, "\\");
$slash2 = strrpos($path, "/");
$maxSlash = -1;
if ($slash1) $maxSlash = $slash1;
if ($slash2 && $slash2>$maxSlash) $maxSlash = $slash2;
if ($maxSlash != -1)
$res = substr($path, 0, $maxSlash+1);
return $res;
}
function startsWith($string, $search)
{
return (strncmp($string, $search, strlen($search)) == 0);
}
function endsWith($string, $search)
{
$length = strlen($search);
$start = $length * -1; //negative
return (substr($string, $start) === $search);
}
}; // class
/*
Omit PHP closing tag to help avoid accidental output
*/