forked from omeka/plugin-CsvImport
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathCsvImportPlusPlugin.php
360 lines (327 loc) · 11.8 KB
/
CsvImportPlusPlugin.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
<?php
/**
* CsvImportPlusPlugin class - represents the Csv Import plugin
*
* @copyright Copyright 2008-2012 Roy Rosenzweig Center for History and New Media
* @license http://www.gnu.org/licenses/gpl-3.0.txt GNU GPLv3
* @package CsvImportPlus
*/
defined('CSV_IMPORT_PLUS_DIRECTORY') or define('CSV_IMPORT_PLUS_DIRECTORY', dirname(__FILE__));
/**
* Csv Import plugin.
*/
class CsvImportPlusPlugin extends Omeka_Plugin_AbstractPlugin
{
const MEMORY_LIMIT_OPTION_NAME = 'csv_import_plus_memory_limit';
const PHP_PATH_OPTION_NAME = 'csv_import_plus_php_path';
/**
* @var array Hooks for the plugin.
*/
protected $_hooks = array(
'initialize',
'install',
'upgrade',
'uninstall',
'config_form',
'config',
'admin_head',
'define_acl',
'admin_items_batch_edit_form',
'items_batch_edit_custom',
);
/**
* @var array Filters for the plugin.
*/
protected $_filters = array('admin_navigation_main');
/**
* @var array Options and their default values.
*/
protected $_options = array(
// With some combinations of Apache/FPM/Varnish, the self constant
// can't be used as key for properties.
'csv_import_plus_memory_limit' => '',
'csv_import_plus_php_path' => '',
'csv_import_plus_identifier_field' => CsvImportPlus_ColumnMap_IdentifierField::DEFAULT_IDENTIFIER_FIELD,
'csv_import_plus_column_delimiter' => CsvImportPlus_RowIterator::DEFAULT_COLUMN_DELIMITER,
'csv_import_plus_enclosure' => CsvImportPlus_RowIterator::DEFAULT_ENCLOSURE,
'csv_import_plus_element_delimiter' => CsvImportPlus_ColumnMap_Element::DEFAULT_ELEMENT_DELIMITER,
'csv_import_plus_tag_delimiter' => CsvImportPlus_ColumnMap_Tag::DEFAULT_TAG_DELIMITER,
'csv_import_plus_file_delimiter' => CsvImportPlus_ColumnMap_File::DEFAULT_FILE_DELIMITER,
// Option used during the first step only.
'csv_import_plus_html_elements' => false,
'csv_import_plus_extra_data' => 'manual',
// With roles, in particular if Guest User is installed.
'csv_import_plus_allow_roles' => 'a:1:{i:0;s:5:"super";}',
'csv_import_plus_slow_process' => 0,
'csv_import_plus_repeat_amazon_s3' => 100,
);
/**
* Add the translations.
*/
public function hookInitialize()
{
add_translation_source(dirname(__FILE__) . '/languages');
// Get the backend settings from the security.ini file.
// This simplifies tests too (use of local paths instead of urls).
// TODO Probably a better location to set this.
if (!Zend_Registry::isRegistered('csv_import_plus')) {
$iniFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'security.ini';
$settings = new Zend_Config_Ini($iniFile, 'csv-import-plus');
Zend_Registry::set('csv_import_plus', $settings);
}
}
/**
* Install the plugin.
*/
public function hookInstall()
{
$db = $this->_db;
// Create csv imports plus table.
// Note: CsvImportPlus_Import and CsvImportPlus_ImportedRecord are standard Zend
// records, but not Omeka ones fully.
$db->query("CREATE TABLE IF NOT EXISTS `{$db->CsvImportPlus_Import}` (
`id` int(10) unsigned NOT NULL auto_increment,
`format` varchar(255) collate utf8_unicode_ci NOT NULL,
`delimiter` varchar(1) collate utf8_unicode_ci NOT NULL,
`enclosure` varchar(1) collate utf8_unicode_ci NOT NULL,
`status` varchar(255) collate utf8_unicode_ci,
`row_count` int(10) unsigned NOT NULL,
`skipped_row_count` int(10) unsigned NOT NULL,
`skipped_record_count` int(10) unsigned NOT NULL,
`updated_record_count` int(10) unsigned NOT NULL,
`file_position` bigint unsigned NOT NULL,
`original_filename` text collate utf8_unicode_ci NOT NULL,
`file_path` text collate utf8_unicode_ci NOT NULL,
`serialized_default_values` text collate utf8_unicode_ci NOT NULL,
`serialized_column_maps` text collate utf8_unicode_ci NOT NULL,
`owner_id` int unsigned NOT NULL,
`added` timestamp NOT NULL default '2000-01-01 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
// Create csv imported records table.
$db->query("CREATE TABLE IF NOT EXISTS `{$db->CsvImportPlus_ImportedRecord}` (
`id` int(10) unsigned NOT NULL auto_increment,
`import_id` int(10) unsigned NOT NULL,
`record_type` varchar(50) collate utf8_unicode_ci NOT NULL,
`record_id` int(10) unsigned NOT NULL,
`identifier` varchar(255) collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY (`import_id`),
KEY `record_type_record_id` (`record_type`, `record_id`),
KEY (`identifier`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
$db->query("
CREATE TABLE IF NOT EXISTS `{$db->CsvImportPlus_Log}` (
`id` int(10) unsigned NOT NULL auto_increment,
`import_id` int(10) unsigned NOT NULL,
`priority` tinyint unsigned NOT NULL,
`created` timestamp DEFAULT CURRENT_TIMESTAMP,
`message` text NOT NULL,
`params` text DEFAULT NULL,
PRIMARY KEY (`id`),
KEY (`import_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
");
$this->_installOptions();
}
/**
* Upgrade the plugin.
*/
public function hookUpgrade($args)
{
$oldVersion = $args['old_version'];
$newVersion = $args['new_version'];
$db = $this->_db;
if (version_compare($oldVersion, '2.3', '<')) {
$message = __('There is no upgrade path from the old fork of CSV Import to CSV Import+, because they can be installed simultaneously.');
throw new Omeka_Plugin_Exception($message);
}
}
/**
* Uninstall the plugin.
*/
public function hookUninstall()
{
$db = $this->_db;
// Drop the tables.
$sql = "DROP TABLE IF EXISTS `{$db->CsvImportPlus_Import}`";
$db->query($sql);
$sql = "DROP TABLE IF EXISTS `{$db->CsvImportPlus_ImportedRecord}`";
$db->query($sql);
$sql = "DROP TABLE IF EXISTS `{$db->CsvImportPlus_Log}`";
$db->query($sql);
$this->_uninstallOptions();
}
/**
* Shows plugin configuration page.
*/
public function hookConfigForm($args)
{
$view = get_view();
echo $view->partial(
'plugins/csv-import-plus-config-form.php'
);
}
/**
* Saves plugin configuration page.
*
* @param array Options set in the config form.
*/
public function hookConfig($args)
{
$post = $args['post'];
foreach ($this->_options as $optionKey => $optionValue) {
if (in_array($optionKey, array(
'csv_import_plus_allow_roles',
))) {
$post[$optionKey] = serialize($post[$optionKey]) ?: serialize(array());
}
if (isset($post[$optionKey])) {
set_option($optionKey, $post[$optionKey]);
}
}
}
/**
* Defines the plugin's access control list.
*
* @param array $args
*/
public function hookDefineAcl($args)
{
$acl = $args['acl'];
$resource = 'CsvImportPlus_Index';
// TODO This is currently needed for tests for an undetermined reason.
if (!$acl->has($resource)) {
$acl->addResource($resource);
}
// Hack to disable CRUD actions.
$acl->deny(null, $resource, array('show', 'add', 'edit', 'delete'));
$acl->deny(null, $resource);
$roles = $acl->getRoles();
// Check that all the roles exist, in case a plugin-added role has
// been removed (e.g. GuestUser).
$allowRoles = unserialize(get_option('csv_import_plus_allow_roles')) ?: array();
$allowRoles = array_intersect($roles, $allowRoles);
if ($allowRoles) {
$acl->allow($allowRoles, $resource);
}
$denyRoles = array_diff($roles, $allowRoles);
if ($denyRoles) {
$acl->deny($denyRoles, $resource);
}
}
/**
* Configure admin theme header.
*
* @param array $args
*/
public function hookAdminHead($args)
{
$request = Zend_Controller_Front::getInstance()->getRequest();
if ($request->getModuleName() == 'csv-import-plus') {
queue_css_file('csv-import-plus');
queue_js_file('csv-import-plus');
}
}
/**
* Add the CSV Import+ link to the admin main navigation.
*
* @param array Navigation array.
* @return array Filtered navigation array.
*/
public function filterAdminNavigationMain($nav)
{
$nav[] = array(
'label' => __('CSV Import+'),
'uri' => url('csv-import-plus'),
'resource' => 'CsvImportPlus_Index',
'privilege' => 'index',
);
return $nav;
}
/**
* Add a partial batch edit form.
*
* @return void
*/
public function hookAdminItemsBatchEditForm($args)
{
$view = get_view();
echo $view->partial(
'forms/csv-import-plus-batch-edit.php'
);
}
/**
* Process the partial batch edit form.
*
* @return void
*/
public function hookItemsBatchEditCustom($args)
{
$item = $args['item'];
$orderByFilename = $args['custom']['csvimportplus']['orderByFilename'];
$mixImages = $args['custom']['csvimportplus']['mixImages'];
if ($orderByFilename) {
$this->_sortFiles($item, (boolean) $mixImages);
}
}
/**
* Sort all files of an item by name and eventually sort images first.
*
* @param Item $item
* @param boolean $mixImages
* @return void
*/
protected function _sortFiles($item, $mixImages = false)
{
if ($item->fileCount() < 2) {
return;
}
$list = $item->Files;
// Make a sort by name before sort by type.
usort($list, function($fileA, $fileB) {
return strcmp($fileA->original_filename, $fileB->original_filename);
});
// The sort by type doesn't remix all filenames.
if (!$mixImages) {
$images = array();
$nonImages = array();
foreach ($list as $file) {
// Image.
if (strpos($file->mime_type, 'image/') === 0) {
$images[] = $file;
}
// Non image.
else {
$nonImages[] = $file;
}
}
$list = array_merge($images, $nonImages);
}
// To avoid issues with unique index when updating (order should be
// unique for each file of an item), all orders are reset to null before
// true process.
$db = $this->_db;
$bind = array(
$item->id,
);
$sql = "
UPDATE `$db->File` files
SET files.order = NULL
WHERE files.item_id = ?
";
$db->query($sql, $bind);
// To avoid multiple updates, a single query is used.
foreach ($list as &$file) {
$file = $file->id;
}
// The array is made unique, because a file can be repeated.
$list = implode(',', array_unique($list));
$sql = "
UPDATE `$db->File` files
SET files.order = FIND_IN_SET(files.id, '$list')
WHERE files.id in ($list)
";
$db->query($sql);
}
}