/
class.fieldmanager.php
606 lines (530 loc) · 19 KB
/
class.fieldmanager.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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
<?php
/**
* @package toolkit
*/
/**
* The FieldManager class is responsible for managing all fields types in Symphony.
* Fields are stored on the file system either in the `/fields` folder of `TOOLKIT` or
* in a `fields` folder in an extension directory.
*/
require_once(TOOLKIT . '/class.field.php');
Class FieldManager implements FileResource {
/**
* An array of all the objects that the Manager is responsible for.
* Defaults to an empty array.
* @var array
*/
protected static $_pool = array();
/**
* An array of all fields whose have been created by ID
* @var array
*/
private static $_initialiased_fields = array();
/**
* Given the filename of a Field, return it's handle. This will remove
* the Symphony conventions of `field.*.php`
*
* @param string $filename
* The filename of the Field
* @return string
*/
public static function __getHandleFromFilename($filename){
return preg_replace(array('/^field./i', '/.php$/i'), '', $filename);
}
/**
* Given a type, returns the full class name of a Field. Fields use a
* 'field' prefix
*
* @param string $type
* A field handle
* @return string
*/
public static function __getClassName($type){
return 'field' . $type;
}
/**
* Finds a Field by type by searching the `TOOLKIT . /fields` folder and then
* any fields folders in the installed extensions. The function returns
* the path to the folder where the field class resides.
*
* @param string $name
* The field handle, that is, `field.{$handle}.php`
* @return string
*/
public static function __getClassPath($type){
if(is_file(TOOLKIT . "/fields/field.{$type}.php")) return TOOLKIT . '/fields';
else{
$extensions = Symphony::ExtensionManager()->listInstalledHandles();
if(is_array($extensions) && !empty($extensions)){
foreach($extensions as $e){
if(is_file(EXTENSIONS . "/{$e}/fields/field.{$type}.php")) return EXTENSIONS . "/{$e}/fields";
}
}
}
return false;
}
/**
* Given a field type, return the path to it's class
*
* @see __getClassPath()
* @param string $type
* The handle of the field to load (it's type)
* @return string
*/
public static function __getDriverPath($type){
return self::__getClassPath($type) . "/field.{$type}.php";
}
/**
* This function is not implemented by the `FieldManager` class
*/
public static function about($name) {
return false;
}
/**
* Given an associative array of fields, insert them into the database
* returning the resulting Field ID if successful, or false if there
* was an error. As fields are saved in order on a section, a query is
* made to determine the sort order of this field to be current sort order
* +1.
*
* @param array $fields
* Associative array of field names => values for the Field object
* @return integer|boolean
* Returns a Field ID of the created Field on success, false otherwise.
*/
public static function add(array $fields){
if(!isset($fields['sortorder'])){
$fields['sortorder'] = self::fetchNextSortOrder();
}
if(!Symphony::Database()->insert($fields, 'tbl_fields')) return false;
$field_id = Symphony::Database()->getInsertID();
return $field_id;
}
/**
* Save the settings for a Field given it's `$field_id` and an associative
* array of settings.
*
* @since Symphony 2.3
* @param integer $field_id
* The ID of the field
* @param array $settings
* An associative array of settings, where the key is the column name
* and the value is the value.
* @return boolean
* True on success, false on failure
*/
public static function saveSettings($field_id, $settings) {
// Get the type of this field:
$type = self::fetchFieldTypeFromID($field_id);
// Delete the original settings:
Symphony::Database()->delete("`tbl_fields_".$type."`", sprintf("`field_id` = %d LIMIT 1", $field_id));
// Insert the new settings into the type table:
if(!isset($settings['field_id'])) {
$settings['field_id'] = $field_id;
}
return Symphony::Database()->insert($settings, 'tbl_fields_'.$type);
}
/**
* Given a Field ID and associative array of fields, update an existing Field
* row in the `tbl_fields`table. Returns boolean for success/failure
*
* @param integer $id
* The ID of the Field that should be updated
* @param array $fields
* Associative array of field names => values for the Field object
* This array does need to contain every value for the field object, it
* can just be the changed values.
* @return boolean
*/
public static function edit($id, array $fields){
if(!Symphony::Database()->update($fields, "tbl_fields", " `id` = '$id'")) return false;
return true;
}
/**
* Given a Field ID, delete a Field from Symphony. This will remove the field from
* the fields table, all of the data stored in this field's `tbl_entries_data_$id` any
* existing section associations. This function additionally call the Field's `tearDown`
* method so that it can cleanup any additional settings or entry tables it may of created.
*
* @param integer $id
* The ID of the Field that should be deleted
* @return boolean
*/
public static function delete($id) {
$existing = self::fetch($id);
$existing->tearDown();
Symphony::Database()->delete('tbl_fields', " `id` = '$id'");
Symphony::Database()->delete('tbl_fields_'.$existing->handle(), " `field_id` = '$id'");
SectionManager::removeSectionAssociation($id);
Symphony::Database()->query('DROP TABLE `tbl_entries_data_'.$id.'`');
return true;
}
/**
* The fetch method returns a instance of a Field from tbl_fields. The most common
* use of this function is to retrieve a Field by ID, but it can be used to retrieve
* Fields from a Section also. There are several parameters that can be used to fetch
* fields by their Type, Location, by a Field Constant or with a custom WHERE query.
*
* @param integer|array $id
* The ID of the field to retrieve. Defaults to null which will return multiple field
* objects. Since Symphony 2.3, `$id` will accept an array of Field ID's
* @param integer $section_id
* The ID of the section to look for the fields in. Defaults to null which will allow
* all fields in the Symphony installation to be searched on.
* @param string $order
* Available values of ASC (Ascending) or DESC (Descending), which refer to the
* sort order for the query. Defaults to ASC (Ascending)
* @param string $sortfield
* The field to sort the query by. Can be any from the tbl_fields schema. Defaults to
* 'sortorder'
* @param string $type
* Filter fields by their type, ie. input, select. Defaults to null
* @param string $location
* Filter fields by their location in the entry form. There are two possible values,
* 'main' or 'sidebar'. Defaults to null
* @param string $where
* Allows a custom where query to be included. Must be valid SQL. The tbl_fields alias
* is t1
* @param string $restrict
* Only return fields if they match one of the Field Constants. Available values are
* `__TOGGLEABLE_ONLY__`, `__UNTOGGLEABLE_ONLY__`, `__FILTERABLE_ONLY__`,
* `__UNFILTERABLE_ONLY__` or `__FIELD_ALL__`. Defaults to `__FIELD_ALL__`
* @return array
* An array of Field objects. If no Field are found, null is returned.
*/
public static function fetch($id = null, $section_id = null, $order = 'ASC', $sortfield = 'sortorder', $type = null, $location = null, $where = null, $restrict=Field::__FIELD_ALL__){
$fields = array();
$returnSingle = false;
$ids = array();
$field_contexts = array();
if(!is_null($id)) {
if(is_numeric($id)) {
$returnSingle = true;
}
if(!is_array($id)) {
$field_ids = array((int)$id);
}
else {
$field_ids = $id;
}
// Loop over the `$field_ids` and check to see we have
// instances of the request fields
foreach($field_ids as $key => $field_id) {
if(
isset(self::$_initialiased_fields[$field_id])
&& self::$_initialiased_fields[$field_id] instanceof Field
) {
$fields[$field_id] = self::$_initialiased_fields[$field_id];
unset($field_ids[$key]);
}
}
}
// If there is any `$field_ids` left to be resolved lets do that, otherwise
// if `$id` wasn't provided in the first place, we'll also continue
if(!empty($field_ids) || is_null($id)) {
$sql = sprintf("
SELECT t1.*
FROM tbl_fields AS `t1`
WHERE 1
%s %s %s %s
%s
",
isset($type) ? " AND t1.`type` = '{$type}' " : NULL,
isset($location) ? " AND t1.`location` = '{$location}' " : NULL,
isset($section_id) ? " AND t1.`parent_section` = '{$section_id}' " : NULL,
$where,
isset($field_ids) ? " AND t1.`id` IN(" . implode(',', $field_ids) . ") " : " ORDER BY t1.`{$sortfield}` {$order}"
);
if(!$result = Symphony::Database()->fetch($sql)) return ($returnSingle ? null : array());
// Loop over the resultset building an array of type, field_id
foreach($result as $f) {
$ids[$f['type']][] = $f['id'];
}
// Loop over the `ids` array, which is grouped by field type
// and get the field context.
foreach($ids as $type => $field_id) {
$field_contexts[$type] = Symphony::Database()->fetch(sprintf(
"SELECT * FROM `tbl_fields_%s` WHERE `field_id` IN (%s)",
$type, implode(',', $field_id)
), 'field_id');
}
foreach($result as $f) {
// We already have this field in our static store
if(
isset(self::$_initialiased_fields[$f['id']])
&& self::$_initialiased_fields[$f['id']] instanceof Field
) {
$field = self::$_initialiased_fields[$f['id']];
}
// We don't have an instance of this field, so let's set one up
else {
$field = self::create($f['type']);
$field->setArray($f);
// Get the context for this field from our previous queries.
$context = $field_contexts[$f['type']][$f['id']];
if (is_array($context) && !empty($context)) {
try {
unset($context['id']);
$field->setArray($context);
}
catch (Exception $e) {
throw new Exception(__(
'Settings for field %s could not be found in table tbl_fields_%s.',
array($f['id'], $f['type'])
));
}
}
self::$_initialiased_fields[$f['id']] = $field;
}
// Check to see if there was any restricts imposed on the fields
if (
$restrict == Field::__FIELD_ALL__
|| ($restrict == Field::__TOGGLEABLE_ONLY__ && $field->canToggle())
|| ($restrict == Field::__UNTOGGLEABLE_ONLY__ && !$field->canToggle())
|| ($restrict == Field::__FILTERABLE_ONLY__ && $field->canFilter())
|| ($restrict == Field::__UNFILTERABLE_ONLY__ && !$field->canFilter())
) {
$fields[$f['id']] = $field;
}
}
}
return count($fields) <= 1 && $returnSingle ? current($fields) : $fields;
}
/**
* Given a field ID, return the type of the field by querying `tbl_fields`
*
* @param integer $id
* @return string
*/
public static function fetchFieldTypeFromID($id){
return Symphony::Database()->fetchVar('type', 0, "SELECT `type` FROM `tbl_fields` WHERE `id` = '$id' LIMIT 1");
}
/**
* Given a field ID, return the handle of the field by querying `tbl_fields`
*
* @param integer $id
* @return string
*/
public static function fetchHandleFromID($id){
return Symphony::Database()->fetchVar('element_name', 0, "SELECT `element_name` FROM `tbl_fields` WHERE `id` = '$id' LIMIT 1");
}
/**
* Given an `$element_name` and a `$section_id`, return the Field ID. Symphony enforces
* a uniqueness constraint on a section where every field must have a unique
* label (and therefore handle) so whilst it is impossible to have two fields
* from the same section, it would be possible to have two fields with the same
* name from different sections. Passing the `$section_id` lets you to specify
* which section should be searched. If `$element_name` is null, this function will
* return all the Field ID's from the given `$section_id`.
*
* @since Symphony 2.3 This function can now accept $element_name as an array
* of handles. These handles can now also include the handle's mode, eg. `title: formatted`
*
* @param string|array $element_name
* The handle of the Field label, or an array of handles. These handles may contain
* a mode as well, eg. `title: formatted`.
* @param integer $section_id
* The section that this field belongs too
* @return mixed
* The field ID, or an array of field ID's
*/
public static function fetchFieldIDFromElementName($element_name, $section_id = null){
if(is_null($element_name)) {
$schema_sql = sprintf("
SELECT `id`
FROM `tbl_fields`
WHERE `parent_section` = %d
ORDER BY `sortorder` ASC
",
$section_id
);
}
else {
$element_names = !is_array($element_name) ? array($element_name) : $element_name;
// allow for pseudo-fields containing colons (e.g. Textarea formatted/unformatted)
foreach ($element_names as $index => $name) {
$parts = explode(':', $name, 2);
if(count($parts) == 1) continue;
unset($element_names[$index]);
// Prevent attempting to look up 'system', which will arise
// from `system:pagination`, `system:id` etc.
if($parts[0] == 'system') continue;
$element_names[] = Symphony::Database()->cleanValue(trim($parts[0]));
}
$schema_sql = empty($element_names) ? null : sprintf("
SELECT `id`
FROM `tbl_fields`
WHERE 1
%s
AND `element_name` IN ('%s')
ORDER BY `sortorder` ASC
",
!is_null($section_id) ? sprintf("AND `parent_section` = %d", $section_id) : "",
implode("', '", array_unique($element_names))
);
}
if(is_null($schema_sql)) return false;
$result = Symphony::Database()->fetch($schema_sql);
if(count($result) == 1) {
return (int)$result[0]['id'];
}
else if(empty($result)) {
return false;
}
else {
foreach($result as &$r) {
$r = (int)$r['id'];
}
return $result;
}
}
/**
* Work out the next available sort order for a new field
*
* @return integer
* Returns the next sort order
*/
public static function fetchNextSortOrder(){
$next = Symphony::Database()->fetchVar("next", 0, "
SELECT
MAX(p.sortorder) + 1 AS `next`
FROM
`tbl_fields` AS p
LIMIT 1
");
return ($next ? (int)$next : 1);
}
/**
* Given a `$section_id`, this function returns an array of the installed
* fields schema. This includes the `id`, `element_name`, `type`
* and `location`.
*
* @since Symphony 2.3
* @param integer $section_id
* @return array
* An associative array that contains four keys, `id`, `element_name`,
* `type` and `location`
*/
public static function fetchFieldsSchema($section_id) {
return Symphony::Database()->fetch(sprintf("
SELECT `id`, `element_name`, `type`, `location`
FROM `tbl_fields`
WHERE `parent_section` = %d
ORDER BY `sortorder` ASC
",
$section_id
));
}
/**
* Returns an array of all available field handles discovered in the
* `TOOLKIT . /fields` or `EXTENSIONS . /{}/fields`.
*
* @return array
* A single dimensional array of field handles.
*/
public static function listAll() {
$structure = General::listStructure(TOOLKIT . '/fields', '/field.[a-z0-9_-]+.php/i', false, 'asc', TOOLKIT . '/fields');
$extensions = Symphony::ExtensionManager()->listInstalledHandles();
if(is_array($extensions) && !empty($extensions)){
foreach($extensions as $handle) {
if(is_dir(EXTENSIONS . '/' . $handle . '/fields')){
$tmp = General::listStructure(EXTENSIONS . '/' . $handle . '/fields', '/field.[a-z0-9_-]+.php/i', false, 'asc', EXTENSIONS . '/' . $handle . '/fields');
if(is_array($tmp['filelist']) && !empty($tmp['filelist'])) {
$structure['filelist'] = array_merge($structure['filelist'], $tmp['filelist']);
}
}
}
$structure['filelist'] = General::array_remove_duplicates($structure['filelist']);
}
$types = array();
foreach($structure['filelist'] as $filename) {
$types[] = self::__getHandleFromFilename($filename);
}
return $types;
}
/**
* Creates an instance of a given class and returns it. Adds the instance
* to the `$_pool` array with the key being the handle.
*
* @param string $type
* The handle of the Field to create (which is it's handle)
* @return Field
*/
public static function create($type){
if(!isset(self::$_pool[$type])){
$classname = self::__getClassName($type);
$path = self::__getDriverPath($type);
if(!file_exists($path)){
throw new Exception(
__('Could not find Field %1$s at %2$s.', array('<code>' . $type . '</code>', '<code>' . $path . '</code>'))
. ' ' . __('If it was provided by an Extension, ensure that it is installed, and enabled.')
);
}
if(!class_exists($classname)){
require_once($path);
}
self::$_pool[$type] = new $classname;
if(self::$_pool[$type]->canShowTableColumn() && !self::$_pool[$type]->get('show_column')){
self::$_pool[$type]->set('show_column', 'yes');
}
}
return clone self::$_pool[$type];
}
/**
* Return boolean if the given `$field_type` is in use anywhere in the
* current Symphony install.
*
* @since Symphony 2.3
* @param string $field_type
* @return boolean
*/
public static function isFieldUsed($field_type) {
return Symphony::Database()->fetchVar('count', 0, sprintf("
SELECT COUNT(*) AS `count` FROM `tbl_fields` WHERE `type` = '%s'
", $field_type
)) > 0;
}
/**
* Check if a specific text formatter is used by a Field
*
* @since Symphony 2.3
* @param $text_formatter_handle
* The handle of the `TextFormatter`
* @return boolean
* true if used, false if not
*/
public static function isTextFormatterUsed($text_formatter_handle) {
$fields = Symphony::Database()->fetchCol('type', "SELECT DISTINCT `type` FROM `tbl_fields` WHERE `type` NOT IN ('author', 'checkbox', 'date', 'input', 'select', 'taglist', 'upload')");
if(!empty($fields)) foreach($fields as $field) {
try {
$table = Symphony::Database()->fetchVar('count', 0, sprintf("
SELECT COUNT(*) AS `count`
FROM `tbl_fields_%s`
WHERE `formatter` = '%s'
",
Symphony::Database()->cleanValue($field),
$text_formatter_handle
));
}
catch (DatabaseException $ex) {
// Table probably didn't have that column
}
if($table > 0) {
return true;
}
}
return false;
}
/**
* Returns an array of all available field handles discovered in the
* `TOOLKIT . /fields` or `EXTENSIONS . /{}/fields`.
*
* @deprecated This function will be removed in Symphony 2.4. Use
* `FieldManager::listAll` instead.
* @return array
* A single dimensional array of field handles.
*/
public static function fetchTypes() {
return FieldManager::listAll();
}
}