forked from pimcore/pimcore
/
Dao.php
430 lines (357 loc) · 16.5 KB
/
Dao.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
<?php
/**
* Pimcore
*
* This source file is subject to the GNU General Public License version 3 (GPLv3)
* For the full copyright and license information, please view the LICENSE.md and gpl-3.0.txt
* files that are distributed with this source code.
*
* @category Pimcore
* @package Object|Class
* @copyright Copyright (c) 2009-2015 pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license GNU General Public License version 3 (GPLv3)
*/
namespace Pimcore\Model\Object\ClassDefinition;
use Pimcore\Model;
use Pimcore\Model\Object;
use Pimcore\Tool\Serialize;
use Pimcore\File;
class Dao extends Model\Dao\AbstractDao {
/**
* @var Object\Class\ClassDefinition
*/
protected $model;
protected $_sqlChangeLog = array();
protected $tableDefinitions = null;
/**
* @param null $id
* @throws \Exception
*/
public function getById($id = null) {
if (!$id) {
$id = $this->model->getId();
}
$classRaw = $this->db->fetchRow("SELECT * FROM classes WHERE id = ?", $id);
if($classRaw["id"]) {
$this->assignVariablesToModel($classRaw);
$this->model->setPropertyVisibility(Serialize::unserialize($classRaw["propertyVisibility"]));
$this->model->setLayoutDefinitions($this->getLayoutData());
} else {
throw new \Exception("Class with ID " . $id . " doesn't exist");
}
}
/**
* @param null $name
* @throws \Exception
*/
public function getByName($name = null) {
if (!$name) {
$name = $this->model->getName();
}
$classRaw = $this->db->fetchRow("SELECT id FROM classes WHERE name = ?", $name);
if($classRaw["id"]) {
$this->assignVariablesToModel($classRaw);
// the layout is loaded in Object|Class::getByName();
} else {
throw new \Exception("Class with name " . $name . " doesn't exist");
}
}
/**
* Save object to database
*
* @return mixed
*/
protected function getLayoutData () {
$file = PIMCORE_CLASS_DIRECTORY."/definition_". $this->model->getId() .".psf";
if(is_file($file)) {
return Serialize::unserialize(file_get_contents($file));
}
return;
}
/**
* Save object to database
*
* @return void
*/
public function save() {
if ($this->model->getId()) {
return $this->update();
}
return $this->create();
}
/**
* @throws \Exception
* @throws \Zend_Db_Adapter_Exception
*/
public function update() {
$class = get_object_vars($this->model);
$data = array();
foreach ($class as $key => $value) {
if (in_array($key, $this->getValidTableColumns("classes"))) {
if (is_array($value) || is_object($value)) {
$value = Serialize::serialize($value);
} else if(is_bool($value)) {
$value = (int)$value;
}
$data[$key] = $value;
}
}
$this->db->update("classes", $data, $this->db->quoteInto("id = ?", $this->model->getId()));
// save definition as a serialized file
$definitionFile = PIMCORE_CLASS_DIRECTORY."/definition_". $this->model->getId() .".psf";
if(!is_writable(dirname($definitionFile)) || (is_file($definitionFile) && !is_writable($definitionFile))) {
throw new \Exception("Cannot write definition file in: " . $definitionFile . " please check write permission on this directory.");
}
File::put($definitionFile, Serialize::serialize($this->model->layoutDefinitions));
$objectTable = "object_query_" . $this->model->getId();
$objectDatastoreTable = "object_store_" . $this->model->getId();
$objectDatastoreTableRelation = "object_relations_" . $this->model->getId();
$objectView = "object_" . $this->model->getId();
// create object table if not exists
$protectedColums = array("oo_id", "oo_classId", "oo_className");
$protectedDatastoreColumns = array("oo_id");
$this->db->query("CREATE TABLE IF NOT EXISTS `" . $objectTable . "` (
`oo_id` int(11) NOT NULL default '0',
`oo_classId` int(11) default '" . $this->model->getId() . "',
`oo_className` varchar(255) default '" . $this->model->getName() . "',
PRIMARY KEY (`oo_id`)
) DEFAULT CHARSET=utf8;");
// update default value of classname columns
$this->db->query('ALTER TABLE `' . $objectTable . "` ALTER COLUMN `oo_className` SET DEFAULT '" . $this->model->getName() . "';");
$this->db->query("CREATE TABLE IF NOT EXISTS `" . $objectDatastoreTable . "` (
`oo_id` int(11) NOT NULL default '0',
PRIMARY KEY (`oo_id`)
) DEFAULT CHARSET=utf8;");
$this->db->query("CREATE TABLE IF NOT EXISTS `" . $objectDatastoreTableRelation . "` (
`src_id` int(11) NOT NULL DEFAULT '0',
`dest_id` int(11) NOT NULL DEFAULT '0',
`type` varchar(50) NOT NULL DEFAULT '',
`fieldname` varchar(70) NOT NULL DEFAULT '0',
`index` int(11) unsigned NOT NULL DEFAULT '0',
`ownertype` enum('object','fieldcollection','localizedfield','objectbrick') NOT NULL DEFAULT 'object',
`ownername` varchar(70) NOT NULL DEFAULT '',
`position` varchar(70) NOT NULL DEFAULT '0',
PRIMARY KEY (`src_id`,`dest_id`,`ownertype`,`ownername`,`fieldname`,`type`,`position`),
KEY `index` (`index`),
KEY `src_id` (`src_id`),
KEY `dest_id` (`dest_id`),
KEY `fieldname` (`fieldname`),
KEY `position` (`position`),
KEY `ownertype` (`ownertype`),
KEY `type` (`type`),
KEY `ownername` (`ownername`)
) DEFAULT CHARSET=utf8;");
$existingColumns = $this->getValidTableColumns($objectTable, false); // no caching of table definition
$existingDatastoreColumns = $this->getValidTableColumns($objectDatastoreTable, false); // no caching of table definition
$columnsToRemove = $existingColumns;
$datastoreColumnsToRemove = $existingDatastoreColumns;
Object\ClassDefinition\Service::updateTableDefinitions($this->tableDefinitions, array($objectTable, $objectDatastoreTable));
// add non existing columns in the table
if (is_array($this->model->getFieldDefinitions()) && count($this->model->getFieldDefinitions())) {
foreach ($this->model->getFieldDefinitions() as $key => $value) {
// if a datafield requires more than one column in the query table
if (is_array($value->getQueryColumnType())) {
foreach ($value->getQueryColumnType() as $fkey => $fvalue) {
$this->addModifyColumn($objectTable, $key . "__" . $fkey, $fvalue, "", "NULL");
$protectedColums[] = $key . "__" . $fkey;
}
}
// if a datafield requires more than one column in the datastore table => only for non-relation types
if(!$value->isRelationType() && is_array($value->getColumnType())) {
foreach ($value->getColumnType() as $fkey => $fvalue) {
$this->addModifyColumn($objectDatastoreTable, $key . "__" . $fkey, $fvalue, "", "NULL");
$protectedDatastoreColumns[] = $key . "__" . $fkey;
}
}
// everything else
// if (!is_array($value->getQueryColumnType()) && !is_array($value->getColumnType())) {
if (!is_array($value->getQueryColumnType()) && $value->getQueryColumnType()) {
$this->addModifyColumn($objectTable, $key, $value->getQueryColumnType(), "", "NULL");
$protectedColums[] = $key;
}
if (!is_array($value->getColumnType()) && $value->getColumnType() && !$value->isRelationType()) {
$this->addModifyColumn($objectDatastoreTable, $key, $value->getColumnType(), "", "NULL");
$protectedDatastoreColumns[] = $key;
}
// }
// add indices
$this->addIndexToField($value, $objectTable);
$this->addIndexToField($value, $objectDatastoreTable);
}
}
// remove unused columns in the table
$this->removeUnusedColumns($objectTable, $columnsToRemove, $protectedColums);
$this->removeUnusedColumns($objectDatastoreTable, $datastoreColumnsToRemove, $protectedDatastoreColumns, true);
// create view
try {
//$this->db->query('CREATE OR REPLACE VIEW `' . $objectView . '` AS SELECT * FROM `objects` left JOIN `' . $objectTable . '` ON `objects`.`o_id` = `' . $objectTable . '`.`oo_id` WHERE `objects`.`o_classId` = ' . $this->model->getId() . ';');
$this->db->query('CREATE OR REPLACE VIEW `' . $objectView . '` AS SELECT * FROM `' . $objectTable . '` JOIN `objects` ON `objects`.`o_id` = `' . $objectTable . '`.`oo_id`;');
}
catch (\Exception $e) {
\Logger::debug($e);
}
$this->tableDefinitions = null;
}
/**
* @param $table
* @param $columnsToRemove
* @param $protectedColumns
* @param bool $emptyRelations
*/
private function removeUnusedColumns ($table, $columnsToRemove, $protectedColumns, $emptyRelations = false) {
if (is_array($columnsToRemove) && count($columnsToRemove) > 0) {
foreach ($columnsToRemove as $value) {
//if (!in_array($value, $protectedColumns)) {
if (!in_array(strtolower($value), array_map('strtolower', $protectedColumns))) {
$this->db->query('ALTER TABLE `' . $table . '` DROP COLUMN `' . $value . '`;');
if($emptyRelations) {
$tableRelation = "object_relations_" . $this->model->getId();
$this->db->delete($tableRelation, "fieldname = " . $this->db->quote($value) . " AND ownertype = 'object'");
}
// @TODO: remove localized fields and fieldcollections
}
}
}
}
/**
* @param $table
* @param $colName
* @param $type
* @param $default
* @param $null
*/
private function addModifyColumn ($table, $colName, $type, $default, $null) {
$existingColumns = $this->getValidTableColumns($table, false);
$existingColName = null;
// check for existing column case insensitive eg a rename from myInput to myinput
$matchingExisting = preg_grep('/^' . preg_quote($colName, '/') . '$/i', $existingColumns);
if(is_array($matchingExisting) && !empty($matchingExisting)) {
$existingColName = current($matchingExisting);
}
if ($existingColName === null) {
$this->db->query('ALTER TABLE `' . $table . '` ADD COLUMN `' . $colName . '` ' . $type . $default . ' ' . $null . ';');
$this->resetValidTableColumnsCache($table);
} else {
if (!Object\ClassDefinition\Service::skipColumn($this->tableDefinitions, $table, $colName, $type, $default, $null)) {
$this->db->query('ALTER TABLE `' . $table . '` CHANGE COLUMN `' . $existingColName . '` `' . $colName . '` ' . $type . $default . ' ' . $null . ';');
}
}
}
/**
* @param $field
* @param $table
*/
private function addIndexToField ($field, $table) {
if ($field->getIndex()) {
if (is_array($field->getQueryColumnType())) {
// multicolumn field
foreach ($field->getQueryColumnType() as $fkey => $fvalue) {
$columnName = $field->getName() . "__" . $fkey;
try {
$this->db->query("ALTER TABLE `" . $table . "` ADD INDEX `p_index_" . $columnName . "` (`" . $columnName . "`);");
} catch (\Exception $e) {}
}
} else {
// single -column field
$columnName = $field->getName();
try {
$this->db->query("ALTER TABLE `" . $table . "` ADD INDEX `p_index_" . $columnName . "` (`" . $columnName . "`);");
} catch (\Exception $e) {}
}
} else {
if (is_array($field->getQueryColumnType())) {
// multicolumn field
foreach ($field->getQueryColumnType() as $fkey => $fvalue) {
$columnName = $field->getName() . "__" . $fkey;
try {
$this->db->query("ALTER TABLE `" . $table . "` DROP INDEX `p_index_" . $columnName . "`;");
} catch (\Exception $e) {}
}
} else {
// single -column field
$columnName = $field->getName();
try {
$this->db->query("ALTER TABLE `" . $table . "` DROP INDEX `p_index_" . $columnName . "`;");
} catch (\Exception $e) {}
}
}
}
/**
* @param $fieldtype
* @return bool
*/
private function isRelationType($fieldtype) {
if ($fieldtype == 'multihref' || $fieldtype == 'objects' || $fieldtype == 'href')
return true;
return false;
}
/**
* Create a new record for the object in database
*
* @return boolean
*/
public function create() {
$this->db->insert("classes", array("name" => $this->model->getName()));
$this->model->setId($this->db->lastInsertId());
$this->model->setCreationDate(time());
$this->model->setModificationDate(time());
$this->save();
}
/**
* Deletes object from database
*
* @return void
*/
public function delete() {
$this->db->delete("classes", $this->db->quoteInto("id = ?", $this->model->getId()));
$objectTable = "object_query_" . $this->model->getId();
$objectDatastoreTable = "object_store_" . $this->model->getId();
$objectDatastoreTableRelation = "object_relations_" . $this->model->getId();
$objectMetadataTable = "object_metadata_" . $this->model->getId();
$this->db->query('DROP TABLE `' . $objectTable . '`');
$this->db->query('DROP TABLE `' . $objectDatastoreTable . '`');
$this->db->query('DROP TABLE `' . $objectDatastoreTableRelation . '`');
$this->db->query('DROP TABLE IF EXISTS `' . $objectMetadataTable . '`');
$this->db->query('DROP VIEW `object_' . $this->model->getId() . '`');
// delete data
$this->db->delete("objects", $this->db->quoteInto("o_classId = ?", $this->model->getId()));
// remove fieldcollection tables
$allTables = $this->db->fetchAll("SHOW TABLES LIKE 'object_collection_%_" . $this->model->getId() . "'");
foreach ($allTables as $table) {
$collectionTable = current($table);
$this->db->query("DROP TABLE IF EXISTS `".$collectionTable."`");
}
// remove localized fields tables and views
$allViews = $this->db->fetchAll("SHOW TABLES LIKE 'object_localized_" . $this->model->getId() . "_%'");
foreach ($allViews as $view) {
$localizedView = current($view);
$this->db->query("DROP VIEW IF EXISTS `".$localizedView."`");
}
$allTables = $this->db->fetchAll("SHOW TABLES LIKE 'object_localized_query_" . $this->model->getId() . "_%'");
foreach ($allTables as $table) {
$queryTable = current($table);
$this->db->query("DROP TABLE IF EXISTS `".$queryTable."`");
}
$this->db->query("DROP TABLE IF EXISTS object_localized_data_" . $this->model->getId());
// objectbrick tables
$allTables = $this->db->fetchAll("SHOW TABLES LIKE 'object_brick_%_" . $this->model->getId() . "'");
foreach ($allTables as $table) {
$brickTable = current($table);
$this->db->query("DROP TABLE `".$brickTable."`");
}
@unlink(PIMCORE_CLASS_DIRECTORY."/definition_". $this->model->getId() .".psf");
}
/**
* Update the class name in all object
*
* @return void
*/
public function updateClassNameInObjects($newName) {
$this->db->update("objects", array(
"o_className" => $newName
), $this->db->quoteInto("o_classId = ?", $this->model->getId()));
$this->db->update("object_query_" . $this->model->getId(), array(
"oo_className" => $newName
));
}
}