$_ENV['API_URL'], //TODO use config() here instead of env. env should only be used in the config files
'WS_URL' => $_ENV['WS_URL'],
'FILEUPLOAD_URL' => $_ENV['FILEUPLOAD_URL'] ?? '', //these 3 file vars are from old 'thesite'. fileup_url might end up being same as api_url
'FILEUPLOAD_MAX_MB' => $_ENV['FILEUPLOAD_MAX_MB'] ?? 10,
'FILEUPLOAD_CHUNK_MB' => $_ENV['FILEUPLOAD_CHUNK_MB'] ?? '',
'MODE' => config('app.env'), //dev, prod,
];
return $vars;
}
//get a random dune quote
public static function duneQuote(){
$jsonFile = Storage::disk('local')->get('duneprechapterquotes.json');
$quotes = json_decode($jsonFile, true);
$book = array_rand($quotes); //random book
$quoteJSON = $quotes[$book][array_rand($quotes[$book])];
$html = "
${book}
${quoteJSON['quote']}
- ${quoteJSON['author']}
";
return $html;
}
public function uploadFiles(Request $req){
$files = $req->file('f');
$dir = $_ENV['FILEUPLOAD_DIR'] ?? 'uploads';
$returnJSON = true;
if ($req->input('response_format') == 'html'){
$returnJSON = false;
}
$res = [
'num_files' => sizeof($files),
'num_failed'=> 0,
'num_uploaded' => 0,
'success' => false,
'files' => []
];
//validate file
$maxsize = $_ENV['FILEUPLOAD_MAX_MB'] * 1024 ?? 10240; //SiteController::env()['FILEUPLOAD_MAX_MB'] * 1024;
$validated = $req->validate([
'f' => "required|array|max:${maxsize}",
'f.*' => "required|file|max:${maxsize}"
]);
foreach ($files as $f){
$filename = $f->getClientOriginalName();
if (Storage::disk('public')->exists("${dir}/${filename}")){
$filename = Carbon::now()->timestamp.'_'.$filename;
}
$path = $f->storeAs(
$dir,
$filename,
'public'
);
if ($path){
$res['num_uploaded'] += 1;
array_push($res['files'], $path);
} else {
$res['num_failed'] += 1;
}
}
if ($res['num_uploaded'] == sizeof($files)){
$res['success'] = true;
}
if ($returnJSON){
return $res;
} else {
//return "File uploaded: ${filename} ";
return redirect("f/${filename}"); //TODO homepage with data flashing (->with())
}
}
public function search4chan(Request $req){
Log::info('search4chan()');
$validated = $req->validate([
'query' => 'required|string',
'board' => 'nullable|string'
]);
$cmd = './4chan_query ';
Log::info($cmd);
if (isset($validated['board'])) {
$cmd .= ' -b ' . escapeshellarg($validated['board']);
}
$cmd .= ' ' . escapeshellarg($validated['query']);
exec($cmd, $res, $ret);
return $res;
}
//used for testing various things, from /test routes
public function test(Request $req){
//return $req->header('user_agent');
return config('app.env');
}
public function updateSession(){
}
//todo 2/14
public function importItems(Request $request) {
if (Auth::user()->role != 0) { //admin
return response()->json([
'success' => false,
'message' => 'Unauthorized'
], 401);
}
if (isset($request->modelType)){ //model type must be specified as a string
$modelClass = 'App\\Models\\' . ucfirst($request->modelType);
if (class_exists($modelClass)){
$jsonFile = $request->file('jsonFile');
if ($jsonFile == null){
return response()->json([
'success' => false,
'message' => 'No file uploaded'
], 400);
}
$f = str($jsonFile->get());
$items = json_decode($f); //this should be an array
//TODO verify valid json
if (!is_array($items)) {
return response()->json([
'success' => false,
'message' => 'json in submitted file must be an array of items'
], 400);
}
$imported = 0;
$failed = 0;
$errors = [];
foreach ($items as $item) {
try {
$instance = new $modelClass();
foreach ($instance->fillable as $field) {
if (isset($item->$field)){
$instance->$field = $item->$field;
}
}
$instance->user_id = Auth::user()->id;
$instance->saveOrFail();
$imported++;
} catch (\Exception $e) {
$failed++;
$errors[] = "Failed to import item: " . $e->getMessage();
}
}
return response()->json([
'success' => $failed === 0,
'imported' => $imported,
'failed' => $failed,
'errors' => $errors
]);
} else {
return response()->json([
"success"=> false,
'error' => 'model type does not exist'
]);
}
} else {
return response()->json([
'success'=> false,
'error'=> 'no modelType specified'
]);
}
}
public function updateTodo(Request $req){
$file = storage_path('app/todo.json');
$items = file_exists($file) ? json_decode(file_get_contents($file), true) ?? [] : [];
$op = $req->input('op', 'append');
if ($op === 'overwrite') {
$lines = array_filter(array_map('trim', explode("\n", $req->input('content', ''))));
$items = array_values($lines);
} elseif ($op === 'delete') {
$index = (int) $req->input('index');
array_splice($items, $index, 1);
} else {
// append (default)
$lines = array_filter(array_map('trim', explode("\n", $req->input('content', ''))));
$items = array_merge($items, $lines);
}
file_put_contents($file, json_encode(array_values($items), JSON_PRETTY_PRINT));
return redirect('/do')->with('status', 'List updated.');
}
public function updateTodoWithToken(Request $req){
$token = $req->input('token', $req->header('X-Token'));
if (!$token || $token !== env('TODO_TOKEN')) {
abort(403, 'Invalid token.');
}
$file = storage_path('app/todo.json');
$items = file_exists($file) ? json_decode(file_get_contents($file), true) ?? [] : [];
$op = $req->input('op', 'append');
if ($op === 'overwrite') {
$lines = array_filter(array_map('trim', explode("\n", $req->input('content', ''))));
$items = array_values($lines);
} elseif ($op === 'delete') {
$index = (int) $req->input('index');
array_splice($items, $index, 1);
} elseif ($op === 'list') {
return response()->json($items);
} else {
$lines = array_filter(array_map('trim', explode("\n", $req->input('content', ''))));
$items = array_merge($items, $lines);
}
file_put_contents($file, json_encode(array_values($items), JSON_PRETTY_PRINT));
return response()->json(['status' => 'ok', 'count' => count($items), 'items' => $items]);
}
}