-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathdata-manager.php
More file actions
376 lines (322 loc) · 10.3 KB
/
data-manager.php
File metadata and controls
376 lines (322 loc) · 10.3 KB
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
<?php
namespace Grav\Plugin;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Filesystem\Folder;
use Grav\Common\Plugin;
use Grav\Common\Twig\Twig;
use Grav\Common\Uri;
use Grav\Common\Utils;
use Grav\Plugin\Admin\Admin;
use RocketTheme\Toolbox\File\File;
use RocketTheme\Toolbox\File\JsonFile;
class DataManagerPlugin extends Plugin
{
protected $route = 'data-manager';
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
'onPluginsInitialized' => ['onPluginsInitialized', 0],
];
}
/**
* Enable only if url matches to the configuration.
*/
public function onPluginsInitialized()
{
if (!$this->isAdmin()) {
return;
}
$this->enable([
'onPagesInitialized' => ['onPagesInitialized', 0],
'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0],
'onAdminMenu' => ['onAdminMenu', 0],
]);
}
/**
* @throws \Exception
*/
public function onPagesInitialized()
{
/** @var Uri $uri */
$uri = $this->grav['uri'];
// Get data path
$locator = $this->grav['locator'];
$path = $locator->findResource('user-data://', true);
if (strpos($uri->path(), $this->config->get('plugins.admin.route') . '/' . $this->route) === false) {
return;
}
/** @var Twig $twig */
$twig = $this->grav['twig'];
$pathParts = $uri->paths();
$extension = '.' . $uri->extension();
$csv = false;
if (isset($pathParts[1]) && $pathParts[1] === $this->route) {
$type = isset($pathParts[2]) ? $pathParts[2] : null;
if (preg_match( '/\.csv$/', $type)) {
$type = basename($type, '.csv');
$file = null;
$csv = true;
} else {
$file = isset($pathParts[3]) ? $uri->basename() : null;
$ext = $this->getExtension($type, $file);
if ($extension && $ext !== $extension) {
$filename = $file . $extension;
} else {
$filename = $file;
}
}
if ($file && !$csv) {
// handle delete
if ($uri->query('delete') !== null) {
$fileObj = new \Grav\Framework\File\File(
sprintf('%s/%s/%s', $path, $type, $filename)
);
if ($fileObj) {
$paths = $uri->paths();
array_pop($paths);
$fileObj->delete();
$this->grav->redirect(implode('/', $paths), 301);
}
}
// Individual data entry.
$twig->itemData = $this->getFileContent($type, $filename, $path);
} elseif ($type) {
// List of data entries.
$twig->items = $this->getDataType($type, $path);
} else {
// List of data types.
$twig->types = $this->getDataTypes($path);
}
}
// Handle CSV call
if (isset($twig->items) && $csv) {
$data = array_column($twig->items, 'content');
$this->downloadCSV($data);
}
}
private function getExtension($type, $filename)
{
$extension = $this->config->get("plugins.data-manager.types.{$type}.file_extension");
if (!$extension) {
$pos = strrpos($filename, '.');
$extension = $pos ? substr($filename, $pos) : null;
}
return $extension;
}
/**
* Given a data file route, return the file content.
*
* @param string $type
* @param string $filename
* @return array|string|null
*/
private function getFileContent($type, $filename, $path)
{
$extension = $this->getExtension($type, $filename);
switch ($extension) {
case '.txt':
case '.yaml':
$file = CompiledYamlFile::instance($path . '/' . $type . '/' . $filename);
break;
case '.json':
$file = JsonFile::instance($path . '/' . $type . '/' . $filename);
break;
case '.html':
default:
$file = File::instance($path . '/' . $type . '/' . $filename);
}
if (!$file->exists()) {
return null;
}
try {
return $file->content();
} catch (\Exception $e) {
return $file->raw();
}
}
/**
* @param string $type
* @return array
*/
protected function getDataType($type, $path)
{
$extension = $this->config->get("plugins.data-manager.types.{$type}.file_extension");
$items = [];
$fileIterator = new \FilesystemIterator($path . '/' . $type, \FilesystemIterator::SKIP_DOTS);
/** @var \FilesystemIterator $entry */
foreach ($fileIterator as $entry) {
$file = $entry->getFilename();
if (!$entry->isFile() || ($extension && !preg_match('/' . preg_quote($extension, '/') . '$/', $file))) {
// Is not file or file extension does not match.
continue;
}
$name = substr($file, 0, strrpos($file, '.'));
$items[] = [
'name' => $name,
'route' => $file,
'content' => $this->getFileContent($type, $file, $path)
];
}
return $this->sortArrayByKey($items, 'name', SORT_DESC, SORT_NATURAL);
}
/**
* @return array
*/
protected function getDataTypes($path)
{
$types = [];
$entry = null;
//Find data types excluded by plugins
$this->grav->fireEvent('onDataTypeExcludeFromDataManagerPluginHook');
$typesIterator = new \FilesystemIterator($path, \FilesystemIterator::SKIP_DOTS);
foreach ($typesIterator as $type) {
$typeName = $type->getFilename();
if ($typeName[0] === '.') {
continue;
}
if (!is_dir($path . '/' . $typeName)) {
continue;
}
$iterator = new \FilesystemIterator($path . '/' . $typeName, \FilesystemIterator::SKIP_DOTS);
$count = 0;
foreach ($iterator as $fileinfo) {
if ($fileinfo->getFilename()[0] === '.') {
continue;
}
$count++;
}
if (isset($this->grav['admin']->dataTypesExcludedFromDataManagerPlugin)) {
if (!\in_array($typeName, $this->grav['admin']->dataTypesExcludedFromDataManagerPlugin, true)) {
$types[$typeName] = $count;
}
} else {
$types[$typeName] = $count;
}
}
return $types;
}
/**
* @param array $data
* @throws \Exception
*/
protected function downloadCSV(array $data)
{
$csv_data = $this->arrayToCsv($data);
/** @var File $csv_file */
$tmp_dir = Admin::getTempDir();
$tmp_file = uniqid() . '.csv';
$tmp = $tmp_dir . '/data-manager/' . basename($tmp_file);
$csv_file = File::instance($tmp . '/', $tmp_file);
$csv_file->save($csv_data);
Utils::download($csv_file->filename(), true);
exit;
}
/**
* Add plugin templates path
*/
public function onTwigTemplatePaths()
{
$this->grav['twig']->twig_paths[] = __DIR__ . '/admin/templates';
}
/**
* Add navigation item to the admin plugin
*/
public function onAdminMenu()
{
$this->grav['twig']->plugins_hooked_nav['PLUGIN_DATA_MANAGER.DATA_MANAGER'] = ['route' => $this->route, 'icon' => 'fa-database'];
}
/**
* sort a multidimensional array by a key
* Local version until Grav 1.4.3 is released
*
* @param $array
* @param $array_key
* @param int $direction
* @param int $sort_flags
* @return array
*/
public function sortArrayByKey($array, $array_key, $direction = SORT_DESC, $sort_flags = SORT_REGULAR)
{
$output = [];
if (!is_array($array) || !$array) {
return $output;
}
foreach ($array as $key => $row) {
$output[$key] = $row[$array_key];
}
array_multisort($output, $direction, $sort_flags, $array);
return $array;
}
/**
*
*
* @param array $array
* @return null|string
*/
private function arrayToCsv(array $array)
{
$rows = [];
foreach ($array as $row) {
$row = $this->csvFlatten($row);
if ($row) {
$rows[] = $row;
}
}
if (count($rows) === 0) {
return null;
}
$fields = array_map(function() { return ''; }, call_user_func_array('array_replace', $rows));
$values = [];
foreach ($rows as $row) {
$values[] = array_merge($fields, $row);
}
ob_start();
$df = fopen('php://output', 'wb');
fputcsv($df, array_keys($fields));
foreach ($values as $value) {
fputcsv($df, $value);
}
fclose($df);
return ob_get_clean();
}
private function csvFlatten($row)
{
if (!is_array($row)) {
return [];
}
if (isset($row['_data_type'], $row['content']) && is_array($row['content'])) {
return ['timestamp' => $row['timestamp']] + $this->arrayFlatten($row['content']);
}
$flat_data = [];
foreach ($row as $key => $item) {
if (is_array($item)) {
$flat_data[$key] = json_encode($item);
} else {
$flat_data[$key] = $item;
}
}
return $flat_data;
}
/**
* Flatten an array
*
* @param array $array
* @param string $prefix
* @return array
*/
private function arrayFlatten($array, $prefix = '')
{
$flatten = [];
foreach ($array as $key => $inner) {
if (is_array($inner)) {
$flatten += $this->arrayFlatten($inner, $prefix . $key . '.');
} else {
$flatten[$prefix . $key] = $inner;
}
}
return $flatten;
}
}