summaryrefslogtreecommitdiff
path: root/includes/classes/LibertyMime.php
blob: eaff99857dc99d0746d340836393a4b095013b90 (plain)
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
<?php
/**
 * Manages liberty Uploads
 *
 * @package  liberty
 */

/**
 * required setup
 */
namespace Bitweaver\Liberty;

use Bitweaver\BitBase;
use Bitweaver\KernelTools;

global $gBitSystem;

// load the image processor plugin, check for loaded 'gd' since that is the default processor, and config might not be set.
if( $gBitSystem->isFeatureActive( 'image_processor' ) || extension_loaded( 'gd' ) ) {
	require_once LIBERTY_PKG_PATH."plugins/processor.".$gBitSystem->getConfig( 'image_processor','gd' ).".php";
}

// maximum size of the 'original' image when converted to jpg
define( 'MAX_THUMBNAIL_DIMENSION', 20000 );

/**
 * LibertyMime class
 *
 * @package liberty
 */
class LibertyMime extends LibertyContent {
	public $mStoragePrefs = null;
	public array $mStorage = [] ;

	/**
	 * load the attachments for a given content id and then stuff them in mStorage
	 *
	 * @return bool true on success, false on failure - mErrors will contain reason for failure
	 */
	public function load() {
		global $gLibertySystem;
		if( BitBase::verifyId( $this->mContentId )) {
			// load up the content
			parent::load();

			// don't loadAttachmentPreferences() when we are forcing the installer since it breaks the login process before 2.1.0-beta
			if( !defined( 'INSTALLER_FORCE' ) && !defined( 'LOGIN_VALIDATE' )) {
				$this->loadAttachmentPreferences();
			}

			// mime plugins aren't loaded during BIT_INSTALL (active plugin list can't be read from DB), skip attachment rendering
			if( defined( 'BIT_INSTALL' ) ) {
				return true;
			}

			$query = "SELECT * FROM `".BIT_DB_PREFIX."liberty_attachments` la WHERE la.`content_id`=? ORDER BY la.`pos` ASC, la.`attachment_id` ASC";
			if( $result = $this->mDb->query( $query,[ $this->mContentId ])) {
				$this->mStorage = [];
				while( $row = $result->fetchRow() ) {
					if( !empty( $row['is_primary'] ) ) {
						// used by edit tpl's among other things
						$this->mInfo['primary_attachment_id'] = $row['attachment_id'];
					} elseif( !$this->getField( 'primary_attachment_id' ) && !empty( $row['attachment_id'] ) ) {
						// primary was not set by the above, default to first row. might be reset by later iterations via if is_primary above
						$this->mInfo['primary_attachment_id'] = $row['attachment_id'];
					}
					if( $func = $gLibertySystem->getPluginFunction( $row['attachment_plugin_guid'], 'load_function', 'mime' )) {
						// we will pass the preferences by reference that the plugin can easily update them
						if( empty( $this->mStoragePrefs[$row['attachment_id']] )) {
							$this->mStoragePrefs[$row['attachment_id']] = [];
						}
						$this->mStorage[$row['attachment_id']] = $func( $row, $this->mStoragePrefs[$row['attachment_id']], null );
					} else {
						print "No load_function for ".$row['attachment_plugin_guid'];
					}
				}
			}
		}
		return true;
	}

	/**
	 * Store a new upload
	 *
	 * @param array $pParamHash contains all data to store the gallery
	 * @return bool true on success, false if store could not occur. If false, $this->mErrors will have reason why
	 * @access public
	 **/
	public function store( array &$pParamHash ): bool {
		global $gLibertySystem;
		// make sure all the data is in order
		if( LibertyMime::verify( $pParamHash ) && ( !empty( $pParamHash['skip_content_store'] ) || parent::store( $pParamHash ) ) ) {
			$this->StartTrans();
			// files have been uploaded
			if( !empty( $pParamHash['upload_store']['files'] ) && is_array( $pParamHash['upload_store']['files'] )) {

				foreach( $pParamHash['upload_store']['files'] as $key => $upload ) {
					// if we don't have an upload, we'll simply update the file settings using the mime plugins
					if( empty( $upload['tmp_name'] ) ) {
						if( BitBase::verifyId( $upload['attachment_id'] ?? -3 )) {
							// since the form might have all options unchecked, we need to call the update function regardless
							// currently i can't think of a better way to get the plugin guid back when $pParamHash[plugin] is
							// empty. - xing - Friday Jul 11, 2008   20:21:18 CEST
							if( !empty( $this->mStorage[$upload['attachment_id']] )) {
								$attachment = $this->mStorage[$upload['attachment_id']];
								$data = [];
								if( !empty( $pParamHash['plugin'][$upload['attachment_id']][$attachment['attachment_plugin_guid']] )) {
									$data = $pParamHash['plugin'][$upload['attachment_id']][$attachment['attachment_plugin_guid']];
								}
								if( !$this->updateAttachmentParams( $upload['attachment_id'], $attachment['attachment_plugin_guid'], $data )) {
									$this->mErrors['attachment_update'] = "There was a problem updating the file settings.";
								}
							}
						}
						// skip rest of process
						continue;
					}

					$storeRow = $pParamHash['upload_store'];
					unset( $storeRow['files'] );

					// copy by reference that filetype changes are made in lookupMimeHandler()
					$storeRow['upload'] = &$upload;
					if( isset( $pParamHash['thumbnail'] ) ) {
						$storeRow['upload']['thumbnail'] = $pParamHash['thumbnail'];
					}

					// when content is created the content_id is only available after LibertyContent::store()
					$storeRow['content_id'] = $pParamHash['content_id'];

					// let the plugin do the rest
					$guid = $gLibertySystem->lookupMimeHandler( $upload );
					$this->pluginStore( $storeRow, $guid, BitBase::verifyId( $upload['attachment_id'] ?? 0 ));

					// finally, we need to update the original hash with the new values
					$pParamHash['upload_store']['files'][$key] = $storeRow;
				}
			}

			// some mime plugins might not have file uploads - these plugins will tell us what mime handlers they are using
			if( !empty( $pParamHash['mimeplugin'] ) && is_array( $pParamHash['mimeplugin'] )) {
				foreach( $pParamHash['mimeplugin'] as $guid => $storeRow ) {
					// check to see if we have anything worth storing in the array
					$plugin_store = false;
					foreach( array_values( $storeRow ) as $value ) {
						if( !empty( $value )) {
							$plugin_store = true;
						}
					}

					if( !empty( $plugin_store )) {
						// when content is created the content_id is only available after LibertyContent::store()
						$storeRow['content_id'] = $pParamHash['content_id'];
						$this->pluginStore( $storeRow, $guid, BitBase::verifyId( $upload['attachment_id'] ));
					}
				}
			}

			// deal with the primary attachment after we've dealt with all the files
			$this->setPrimaryAttachment(
				$pParamHash['liberty_attachments']['primary'],
				$pParamHash['content_id'],
				empty( $pParamHash['liberty_attachments']['auto_primary'] ) || $pParamHash['liberty_attachments']['auto_primary'] ? true : false,
			);

			// Roll back if something went wrong
			if( empty( $this->mErrors )) {
				$this->CompleteTrans();
			} else {
				$this->mDb->RollbackTrans();
			}
		}

		return count( $this->mErrors ) == 0;
	}

	/**
	 * pluginStore will use a given plugin to store uploaded file data
	 *
	 * @param string $pGuid GUID of plugin
	 * @param array $pParamHash Data to be prcessed and stored by the plugin
	 * @param boolean $pUpdate set to true if this is just an update
	 * @access public
	 * @return bool true on success, false on failure - mErrors will contain reason for failure
	 */
	public function pluginStore( &$pParamHash, $pGuid, $pUpdate = false ) {
		global $gLibertySystem;
		if( !empty( $pParamHash ) && $verify_function = $gLibertySystem->getPluginFunction( $pGuid, 'verify_function' )) {
			// pass along a pointer to the content object
			$pParamHash['this'] = &$this;
			// verify the uploaded file using the plugin
			if( $verify_function( $pParamHash )) {
				if( $process_function = $gLibertySystem->getPluginFunction( $pGuid,  $pUpdate ? 'update_function' : 'store_function' )) {
					if( !$process_function( $pParamHash )) {
						$this->mErrors = array_merge( $this->mErrors, $pParamHash['errors'] );
					}
				} else {
					$this->mErrors['store_function'] = KernelTools::tra( 'No suitable store function found.' );
				}
			} else {
				$this->mErrors = array_merge( $this->mErrors, $pParamHash['errors'] );
			}
		} else {
			$this->mErrors['verify_function'] = KernelTools::tra( 'No suitable verify function found.' );
		}

		return count( $this->mErrors ) == 0;
	}

	/**
	 * Verify content that is about to be stored
	 *
	 * @param array $pParamHash hash of all data that needs to be stored in the database
	 * @access public
	 * @return bool true on success, false on failure - mErrors will contain reason
	 * @todo If one of the uploaded files is an update, place the attachment_id with the upload hash in $_FILES or in _files_override
	 */
	public function verify( array &$pParamHash ): bool {
		global $gBitUser, $gLibertySystem;

		// check to see if we have any files to upload
		if( isset( $pParamHash['_files_override'] )) {
			// we have been passed in a manually stuffed files attachment, such as a custom uploader would have done.
			// process this, and skip over $_FILES
			$uploads = $pParamHash['_files_override'];
		} elseif( !empty( $_FILES )) {
			// we have some _FILES hanging around we will gobble up. This is inherently dagnerous chewing up a _FILES like this as
			// it can cause premature storing of a _FILE if you are trying to store multiple pieces of content at once.
			foreach( $_FILES as $key => $file ) {
				if( !empty( $file['name'] ) || !empty( $file['attachment_id'] )) {
					$uploads[$key] = $file;
				}
			}
		}

		// verify uploads
		if( !empty( $uploads ) ) {
			foreach( array_keys( $uploads ) as $file ) {
				$pParamHash['upload_store']['files'][$file] = LibertyMime::verifyAttachment( $uploads[$file] );
			}
		}

		// don't check for p_liberty_attach_attachments permission on bitpermuser class so registration with avatar upload works
		if( strtolower( get_class( $this )) == 'bitpermuser' ) {
			$pParamHash['upload_store']['no_perm_check'] = true;
		}

		// check for the required permissions to upload a file to the liberty attachments area
		if( !empty( $uploads ) && empty( $pParamHash['no_perm_check'] )) {
			if( !$this->hasUserPermission( 'p_liberty_attach_attachments' )) {
				$this->mErrors['permission'] = KernelTools::tra( 'You do not have permission to upload attachments.' );
			}
		}

		// primary attachment. Allow 'none' to clear the primary.
		if( !BitBase::verifyId( $pParamHash['liberty_attachments']['primary'] ?? '' ) && ( empty( $pParamHash['liberty_attachments']['primary'] ) || $pParamHash['liberty_attachments']['primary'] != 'none' ) ) {
			$pParamHash['liberty_attachments']['primary'] = null;
		}

		// if we have an error we get them all by checking parent classes for additional errors
		if( count( $this->mErrors ) > 0 ){
			// check errors of LibertyContent since LibertyMime means to override the parent verify
			LibertyContent::verify( $pParamHash );
		}

		return count( $this->mErrors ) == 0;
	}

	/**
	 * getThumbnailUrl will fetch the primary thumbnail for a given content. If nothing has been set, it will fetch the last thumbnail it can find.
	 *
	 * @param string $pSize
	 * @param array $mInfo
	 * @access public
	 * @return bool true on success, false on failure - $this->mErrors will contain reason for failure
	 */
	public function getThumbnailUrl(  string $pSize = 'small', ?array $mInfo = null, ?int $pSecondaryId = null, ?int $pDefault = null ): string|null {
		$ret = null;
		if( !empty( $mInfo ) ) {
			// do some stuff if we are given a hash of stuff
		} elseif( $this->isValid() && !empty( $this->mStorage ) ) {
			foreach( array_keys( $this->mStorage ) as $attachmentId ) {
				if( !empty( $this->mStorage[$attachmentId]['is_primary'] ) ) {
					break;
				}
			}
			if( !empty( $this->mStorage[$attachmentId]['thumbnail_url'][$pSize] )) {
				$ret = $this->mStorage[$attachmentId]['thumbnail_url'][$pSize];
			}
		}
		if( $pDefault && empty( $ret ) ) {
			$ret = parent::getThumbnailUrl( $pSize, $mInfo, $pSecondaryId );
		}
		return $ret;
	}

	/**
	 * updateAttachmentParams will update attachment parameters
	 *
	 * @param numeric $pAttachmentId attachment_id of the item we want the prefs from (optional)
	 * @param string $pPluginGuid GUID of the plugin that should process the data
	 * @param array $pParamHash Data to be processed by the plugin
	 * @access public
	 * @return bool true on success, false on failure - mErrors will contain reason for failure
	 */
	public function updateAttachmentParams( $pAttachmentId, $pPluginGuid, $pParamHash = [] ) {
		global $gLibertySystem;
		$ret = false;

		if( BitBase::verifyId( $pAttachmentId )) {
			$file = !empty( $this ) && !empty( $this->mStorage[$pAttachmentId] )
				? $this->mStorage[$pAttachmentId]
				: $this->getAttachment( $pAttachmentId );

			if( BitBase::verifyId( $file['attachment_id'] ) && !empty( $pPluginGuid ) && ( $update_function = $gLibertySystem->getPluginFunction( $pPluginGuid, 'update_function', 'mime' ))) {
				if( $update_function( $file, $pParamHash )) {
					$ret = true;
				} else {
					$this->mErrors['param_update'] = !empty( $file['errors'] )
						? $file['errors']
						: KernelTools::tra( 'There was an unspecified error while updating the file.' );
				}
			}
		}
		return $ret;
	}

	/**
	 * verifyAttachment will perform a generic check if a file is valid for processing
	 *
	 * @param array $pFile file array from $_FILES
	 * @access public
	 * @return bool true on success, false on failure - mErrors will contain reason for failure
	 */
	public function verifyAttachment( $pFile ): array|null {
		if( !empty( $pFile['tmp_name'] ) && is_file( $pFile['tmp_name'] ) && empty( $pFile['error'] ) || !empty( $pFile['attachment_id'] )) {
			return $pFile;
		}
		return null;
	}

	/**
	 * Increment the item hit flag by 1
	 *
	 * @access public
	 * @param numeric $pAttachmentId Attachment ID
	 * @return array adodb query result or false
	 * @note we're abusing the hits column for download count.
	 */
	public static function addDownloadHit( $pAttachmentId = null ) {
		global $gBitUser, $gBitSystem;
		if( BitBase::verifyId( $pAttachmentId ) && $attachment = static::loadAttachment( $pAttachmentId )) {
			if( !$gBitUser->isRegistered() || ( $gBitUser->isRegistered() && $gBitUser->mUserId != $attachment['user_id'] )) {
				$bindVars = [ $pAttachmentId ];
				if( $gBitSystem->mDb->getOne( "SELECT `attachment_id` FROM `".BIT_DB_PREFIX."liberty_attachments` WHERE `attachment_id` = ? AND `hits` IS null", $bindVars )) {
					$query = "UPDATE `".BIT_DB_PREFIX."liberty_attachments` SET `hits` = 1 WHERE `attachment_id` = ?";
				} else {
					$query = "UPDATE `".BIT_DB_PREFIX."liberty_attachments` SET `hits` = `hits`+1 WHERE `attachment_id` = ?";
				}
				return $gBitSystem->mDb->query( $query, $bindVars );
			}
		}
		return [];
	}

	// {{{ =================== Storage Directory Methods ====================
	function getSourceUrl( $pParamHash=[] ) {
		$ret = null;
		if( empty( $pParamHash ) && !empty( $this ) ) {
			$pParamHash = $this->mInfo;
		}
		if( $fileName = $this->getParameter( $pParamHash, 'file_name', $this->getField( 'file_name' ) ) ) {
			$defaultFileName = liberty_mime_get_default_file_name( $fileName, BitBase::getParameter( $pParamHash, 'mime_type' ) );
			$ret = file_exists( $this->getStoragePath( $pParamHash ).$defaultFileName )
				? $this->getStorageUrl( $pParamHash ).$defaultFileName
				: $this->getStorageUrl( $pParamHash ).basename( $fileName );
		}
		return $ret;
	}

	function getSourceFile( $pParamHash=[] ) {
		$ret = null;
		if( empty( $pParamHash ) && !empty( $this ) ) {
			$pParamHash = $this->mInfo;
		}
		if( $fileName = $this->getParameter( $pParamHash, 'file_name', $this->getField( 'file_name' ) ) ) {
			$defaultFileName = liberty_mime_get_default_file_name( $fileName, BitBase::getParameter( $pParamHash, 'mime_type' ) );
			$ret = $this->getStoragePath( $pParamHash );
			if ( !is_dir($ret) ) $ret = dirname($ret) .'/';
			$ret .= $defaultFileName;
			if( !file_exists( $ret ) ) {
				$ret = $this->getStoragePath( $pParamHash ).basename( $fileName );
			}
		}
		return $ret;
	}

	/**
	 * getStoragePath - get path to store files for the feature site_upload_dir. It creates a calculable hierarchy of directories
	 *
	 * @access public
	 * @author Christian Fowler<spider@steelsun.com>
	 * @param $pSubDir any desired directory below the StoragePath. this will be created if it doesn't exist
	 * @param $pCommon indicates not to use the 'common' branch, and not the 'users/.../<user_id>' branch
	 * @param $pRootDir override BIT_ROOT_DIR with a custom absolute path - useful for areas where no we access should be allowed
	 * @return string full path on local filsystem to store files.
	 */
	function getStoragePath( $pParamHash, $pRootDir=null ) {
		$ret = liberty_mime_get_storage_path( $pParamHash, $pRootDir );
		return $ret;
	}

	function getStorageUrl( $pParamHash ) {
		return STORAGE_PKG_URL.liberty_mime_get_storage_branch( $pParamHash );
	}

	/**
	 * getStorageBranch - get url to store files for the feature site_upload_dir. It creates a calculable hierarchy of directories
	 *
	 * @access public
	 * @author Christian Fowler<spider@steelsun.com>
	 * @param $pSubDir any desired directory below the StoragePath. this will be created if it doesn't exist
	 * @param $pUserId indicates the 'users/.../<user_id>' branch or use the 'common' branch if null
	 * @param $pRootDir **deprecated, unused, will be removed in future relase**.
	 * @return string full path on local filsystem to store files.
	 */
	function getStorageBranch( $pParamHash ) {
		return liberty_mime_get_storage_branch( $pParamHash );
	}

	/**
	 * getStorageSubDirName get a filename based on the uploaded file
	 *
	 * @param array $pFileHash File information provided in $_FILES
	 * @return string appropriate sub dir name
	 */
	public function getStorageSubDirName( $pFileHash = null ) {
		if( !empty( $pFileHash['mime_type'] ) && strstr( $pFileHash['mime_type'], "/" )) {
			$ret = strtolower( preg_replace( "!/.*$!", "", $pFileHash['mime_type'] ));
			// if we only got 'application' we will use the file extenstion
			if( $ret == 'application' && !empty( $pFileHash['name'] ) && ( $pos = strrpos( $pFileHash['name'], "." )) !== false ) {
				$ret = strtolower( substr( $pFileHash['name'], $pos + 1 ));
			}
		}

		// append an 's' to not create an image and images dir side by side (legacy reasons)
		if( empty( $ret ) || $ret == 'image' ) {
			$ret = 'images';
		}

		return $ret;
	}

	/**
	 * validateStoragePath make sure that the file/dir you are trying to delete is valid
	 *
	 * @param string $pPath absolute path to the file/dir we want to validate
	 * @return string
	 */
	public static function validateStoragePath( $pPath ) {
		// file_exists checks for file or directory
		if( !empty( $pPath ) && $pPath = realpath( $pPath )) {
			// ensure path sanity
			if( preg_match( "#^".realpath( STORAGE_PKG_PATH )."/(users|common)/\d+/\d+/\w+/\d+#", $pPath )) {
				return $pPath;
			}
		}
		return '';
	}

	// }}}

	// {{{ =================== Attachment Methods ====================
	/**
	 * Get a list of all available attachments
	 *
	 * @param array $pListHash
	 * @access public
	 * @return array
	 */
	public function getAttachmentList( &$pListHash ): array {
		global $gLibertySystem, $gBitUser, $gBitSystem;

		LibertyContent::prepGetList( $pListHash );

		// initialise some variables
		$attachments = $ret = $bindVars = [];
		$whereSql = $joinSql = $selectSql = '';

		// only admin may view attachments from other users
		if( !$gBitUser->isAdmin() ) {
			$pListHash['user_id'] = $gBitUser->mUserId;
		}

		if( !empty( $pListHash['user_id'] ) ) {
			$whereSql .= empty( $whereSql ) ? ' WHERE ' : ' AND ';
			$whereSql .= " la.user_id = ? ";
			$bindVars[] = $pListHash['user_id'];
		}

		if( !empty( $pListHash['content_id'] ) ) {
			$whereSql .= empty( $whereSql ) ? ' WHERE ' : ' AND ';
			$whereSql .= " la.`content_id` = ? ";
			$selectSql .= " , la.`content_id` ";
			$bindVars[] = $pListHash['content_id'];
		}
		$query = "SELECT la.* $selectSql FROM `".BIT_DB_PREFIX."liberty_attachments` la INNER JOIN `".BIT_DB_PREFIX."users_users` uu ON(la.`user_id` = uu.`user_id`) $joinSql $whereSql";
		$result = $this->mDb->query( $query, $bindVars, $pListHash['max_records'], $pListHash['offset'] );
		while( $res = $result->fetchRow() ) {
			$attachments[] = $res;
		}

		foreach( $attachments as $attachment ) {
			if( $loadFunc = $gLibertySystem->getPluginFunction( $attachment['attachment_plugin_guid'], 'load_function', 'mime' )) {
				/* @$prefs - quick hack to stop LibertyMime plugins from breaking until migration to LibertyMime is complete
				 * see expected arguments of liberty/plugins/mime.default.php::mime_default_load -wjames5
				 */
				$prefs = [];
				$ret[$attachment['attachment_id']] = $loadFunc( $attachment, $prefs );
			}
		}

		// count all entries
		$query = "SELECT COUNT(*)
			FROM `".BIT_DB_PREFIX."liberty_attachments` la
			INNER JOIN `".BIT_DB_PREFIX."users_users` uu ON(la.`user_id` = uu.`user_id`)
			$joinSql $whereSql
		";

		$pListHash['cant'] = $this->mDb->getOne( $query, $bindVars );
		$this->postGetList( $pListHash );
		return $ret;
	}

	/**
	 * Expunges the content deleting attached attachments
	 */
	public function expunge(): bool {
		if( !empty( $this->mStorage ) && count( $this->mStorage )) {
			foreach( array_keys( $this->mStorage ) as $i ) {
				$this->expungeAttachment( $this->mStorage[$i]['attachment_id'] );
			}
		}
		return true;
	}

	/**
	 * expunge attachment from the database (and file system via the plugin if required)
	 *
	 * @param numeric $pAttachmentId attachment id of the item that should be deleted
	 * @access public
	 * @return bool true on success, false on failure
	 */
	function expungeAttachment( $pAttachmentId ) {
		global $gLibertySystem, $gBitUser;
		$ret = null;
		if( @$this->verifyId( $pAttachmentId ) ) {
			$sql = "SELECT `attachment_plugin_guid`, `user_id` FROM `".BIT_DB_PREFIX."liberty_attachments` WHERE `attachment_id` = ?";
			if(( $row = $this->mDb->getRow( $sql, [ $pAttachmentId ])) && ( $this->isOwner( $row ) || $gBitUser->isAdmin() )) {
				// check if we have the means available to remove this attachment
				if(( $guid = $row['attachment_plugin_guid'] ) && $expungeFunc = $gLibertySystem->getPluginFunction( $guid, 'expunge_function', 'mime' )) {
					// --- Do the final cleanup of liberty related tables ---

					// there might be situations where we remove user images including portrait, avatar or logo
					// This needs to happen before the plugin can do it's work due to constraints
					$types = [ 'portrait', 'avatar', 'logo' ];
					foreach( $types as $type ) {
						$sql = "UPDATE `".BIT_DB_PREFIX."users_users` SET `{$type}_attachment_id` = null WHERE `{$type}_attachment_id` = ?";
						$this->mDb->query( $sql, [ $pAttachmentId ]);
					}

					if( $expungeFunc( $pAttachmentId )) {
						// Delete the attachment meta data, prefs and record.
						$sql = "DELETE FROM `".BIT_DB_PREFIX."liberty_attachment_meta_data` WHERE `attachment_id` = ?";
						$this->mDb->query( $sql, [ $pAttachmentId ]);
						$sql = "DELETE FROM `".BIT_DB_PREFIX."liberty_attachment_prefs` WHERE `attachment_id` = ?";
						$this->mDb->query( $sql, [ $pAttachmentId ]);
						$sql = "DELETE FROM `".BIT_DB_PREFIX."liberty_attachments` WHERE `attachment_id`=?";
						$this->mDb->query( $sql, [ $pAttachmentId ]);

						// Remove attachment from memory
						unset( $this->mStorage[$pAttachmentId] );
						$ret = true;
					}
				} else {
					print "Expunge function not found for this content!";
				}
			}
		}

		return $ret;
	}

	/**
	 * loadAttachment will load details of a given attachment
	 *
	 * @param int $pAttachmentId Attachment ID of the attachment
	 * @param array $pParams optional parameters that might contain information like display thumbnail size
	 * @access public
	 * @return array|null attachment details
	 */
	public static function loadAttachment( int $pAttachmentId, ?array $pParams = null ): array|null {
		global $gLibertySystem, $gBitSystem;
		$ret = null;

		if( BitBase::verifyId( $pAttachmentId )) {
			$query = "SELECT * FROM `".BIT_DB_PREFIX."liberty_attachments` la WHERE la.`attachment_id`=?";
			if( $result = $gBitSystem->mDb->query( $query, [ (int)$pAttachmentId ])) {
				if( $row = $result->fetchRow() ) {
					if( $func = $gLibertySystem->getPluginFunction( $row['attachment_plugin_guid'], 'load_function', 'mime' )) {
						$sql = "SELECT `pref_name`, `pref_value` FROM `".BIT_DB_PREFIX."liberty_attachment_prefs` WHERE `attachment_id` = ?";
						$prefs = $gBitSystem->mDb->getAssoc( $sql, [ $pAttachmentId ]);
						$ret = $func( $row, $prefs, $pParams );
					}
				}
			}
		}
		return $ret;
	}

	/**
	 * getAttachment will load details of a given attachment
	 *
	 * @param numeric $pAttachmentId Attachment ID of the attachment
	 * @param array $pParams optional parameters that might contain information like display thumbnail size
	 * @access public
	 * @return array attachment details
	 */
	public static function getAttachment( $pAttachmentId, $pParams = null ) {
		global $gLibertySystem, $gBitSystem;
		$ret = null;

		if( BitBase::verifyId( $pAttachmentId )) {
			$query = "SELECT * FROM `".BIT_DB_PREFIX."liberty_attachments` la WHERE la.`attachment_id`=?";
			if( $result = $gBitSystem->mDb->query( $query, [ (int)$pAttachmentId ])) {
				if( $row = $result->fetchRow() ) {
					if( $func = $gLibertySystem->getPluginFunction( $row['attachment_plugin_guid'], 'load_function', 'mime' )) {
						$prefs = static::getAttachmentPreferences( $pAttachmentId );
						$ret = $func( $row, $prefs, $pParams );
					}
				}
			}
		}
		return $ret;
	}

	/**
	 * setPrimaryAttachment will set is_primary 'y' for the specified
	 * attachment and will ensure that all others are set to 'n'
	 *
	 * @param mixed   $pAttachmentId attachment id of the item we want to
	 *				  set as the primary attachment. Use 'none' to clear.
	 * @param numeric $pContentId content id we are working with.
	 * @param boolean $pAutoPrimary automatically set primary if there is only
	 *				  one attachment. Defaults to true.
	 * @access public
	 * @return bool true on success, false on failure
	 */
	public function setPrimaryAttachment( $pAttachmentId = null, $pContentId = null, $pAutoPrimary = true ) {
		global $gBitSystem;

		$ret = false;

		// If we are not given an attachment id but we where told the
		// content_id and we are supposed to auto set the primary then
		// figure out which one it is
		if( !BitBase::verifyId( $pAttachmentId ) && ( empty( $pAttachmentId ) || $pAttachmentId != 'none' ) && BitBase::verifyId( $pContentId ) && $pAutoPrimary ) {
			$query = "
				SELECT `attachment_id`
				FROM `".BIT_DB_PREFIX."liberty_content` lc
				INNER JOIN `".BIT_DB_PREFIX."liberty_attachments` la ON( lc.`content_id` = la.`content_id` )
				WHERE lc.`content_id` = ?";
			$pAttachmentId = $this->mDb->getOne( $query,  [$pContentId]);
		}

		// If we have an attachment_id we'll set it to this
		if( BitBase::verifyId( $pAttachmentId )) {
			// get attachment we want to set primary
			$attachment = $this->getAttachment( $pAttachmentId );

			// Clear old primary. There can only be one!
			$this->clearPrimaryAttachment( $attachment['content_id'] );

			// now update the attachment to is_primary
			$query = "
				UPDATE `".BIT_DB_PREFIX."liberty_attachments`
				SET `is_primary` = ? WHERE `attachment_id` = ?";
			$this->mDb->query( $query, [ 'y', $pAttachmentId ]);

			$ret = true;
		// Otherwise, are we supposed to clear the primary entirely?
		} elseif( BitBase::verifyId( $pContentId ) && !empty( $pAttachmentId ) && $pAttachmentId == 'none' ) {
			// Okay then do the job
			$this->clearPrimaryAttachment( $pContentId );
		}

		return $ret;
	}

	/**
	 * clearPrimaryAttachment will remove the primary flag for all attachments
	 * with the given content_id
	 *
	 * @param numeric the content_id for which primary should be unset.
	 * @return bool true on succes
	 */
	function clearPrimaryAttachment( $pContentId ) {
		$ret = false;

		if( BitBase::verifyId( $pContentId )) {
			$query = "
				UPDATE `".BIT_DB_PREFIX."liberty_attachments`
				SET `is_primary` = ? WHERE `content_id` = ?";
			$this->mDb->query( $query, [ null, $pContentId ]);
			$ret = true;
		}

		return $ret;
	}
	// }}}

	/**
	 * === Attachment Preferences ===
	 */

	/**
	 * Returns the attachment preference value for the passed in key.
	 *
	 * @param string Hash key for the mPrefs value
	 * @param string Default value to return if the preference is empty
	 * @param int Optional content_id for arbitrary content preference
	 */
	function getAttachmentPreference( $pAttachmentId, $pPrefName, $pPrefDefault = null ) {
		if( is_null( $this->mStoragePrefs ) ) {
			$this->loadAttachmentPreferences();
		}

		$ret = null;
		if( BitBase::verifyId( $pAttachmentId ) && !empty( $pPrefName )) {
			$ret = isset( $this->mStoragePrefs ) && isset( $this->mStoragePrefs[$pAttachmentId][$pPrefName] )
				? $this->mStoragePrefs[$pAttachmentId][$pPrefName]
				: $pPrefDefault;
		}

		return $ret;
	}

	/**
	 * Returns the attachment preferences for a given attachment id
	 *
	 * @param string Hash key for the mPrefs value
	 * @param string Default value to return if the preference is empty
	 * @param int Optional content_id for arbitrary content preference
	 */
	protected static function getAttachmentPreferences( $pAttachmentId ) {
		global $gBitSystem;

		$ret = [];
		if( BitBase::verifyId( $pAttachmentId ) ) {
			// if the object isn't loaded, we need to get the prefs from the database
			$sql = "SELECT `pref_name`, `pref_value` FROM `".BIT_DB_PREFIX."liberty_attachment_prefs` WHERE `attachment_id` = ?";
			$ret = $gBitSystem->mDb->getAssoc( $sql, [ (int)$pAttachmentId ]);
		}

		return $ret;
	}

	/**
	 * setAttachmentPreference will set an attachment preferences without storing it in the database
	 *
	 * @param array $pAttachmentId
	 * @param array $pPrefName
	 * @param array $pPrefValue
	 * @access public
	 * @return void
	 */
	public function setAttachmentPreference( $pAttachmentId, $pPrefName, $pPrefValue ): void {
		$this->mStoragePrefs[$pAttachmentId][$pPrefName] = $pPrefValue;
	}

	/**
	 * Saves a preference to the liberty_content_prefs database table with the
	 * given pref name and value. If the value is null, the existing value will
	 * be delete and the value will not be saved. However, a zero will be
	 * stored.
	 *
	 * @param int $pAttachmentId
	 * @param string $pPrefName
	 * @param string $pPrefValue Value for the prefs hash key
	 */
	public static function storeAttachmentPreference( int $pAttachmentId, string $pPrefName, string $pPrefValue = ''): bool {
		global $gBitSystem;
		$ret = false;
		if( BitBase::verifyId( $pAttachmentId ) && !empty( $pPrefName )) {
			$query    = "DELETE FROM `".BIT_DB_PREFIX."liberty_attachment_prefs` WHERE `attachment_id` = ? AND `pref_name` = ?";
			$bindvars = [$pAttachmentId, $pPrefName];
			$result   = $gBitSystem->mDb->query( $query, $bindvars );
			if( !empty( $pPrefValue )) {
				$query      = "INSERT INTO `".BIT_DB_PREFIX."liberty_attachment_prefs` (`attachment_id`,`pref_name`,`pref_value`) VALUES(?, ?, ?)";
				$bindvars[] = substr( $pPrefValue, 0, 250 );
				$result     = $gBitSystem->mDb->query( $query, $bindvars );
			}

			// this function might be called statically
//			if( !empty( $this ) && $this->isValid() ) {
//				$this->mStoragePrefs[$pAttachmentId][$pPrefName] = $pPrefValue;
//			}

			$ret = true;
		}
		return $ret;
	}

	/**
	 * loadPreferences of the currently loaded object or pass in to get preferences of a specific content_id
	 *
	 * @param numeric $pContentId content_id of the item we want the prefs from (optional)
	 * @return array of preferences if $pContentId or $pAttachmentId is set or pass preferences on to $this->mStoragePrefs
	 */
	public function loadAttachmentPreferences( int $pContentId = -2 ): void {
		global $gBitSystem;

		if( !BitBase::verifyId( $pContentId ) && $this->isValid() && BitBase::verifyId( $this->mContentId )) {
			$pContentId = $this->mContentId;
			$store_prefs = true;
		}

		$ret = [];
		if( !empty( $this ) && !is_null( $this->mStoragePrefs )) {
			$ret = $this->mStoragePrefs;
		} elseif( BitBase::verifyId( $pContentId )) {
			$sql = "
				SELECT lap.`attachment_id`, lap.`pref_name`, lap.`pref_value`
				FROM `".BIT_DB_PREFIX."liberty_attachment_prefs` lap
					INNER JOIN `".BIT_DB_PREFIX."liberty_attachments` la ON (la.`attachment_id` = lap.`attachment_id`)
				WHERE la.`content_id` = ?";
			$result = $gBitSystem->mDb->query( $sql, [$pContentId]);
			if( !empty( $result )) {
				while( $aux = $result->fetchRow() ) {
					$ret[$aux['attachment_id']][$aux['pref_name']] = $aux['pref_value'];
				}
			}
		}

		// if neither a content id nor an attachment id are given, we will place the results in mStoragePrefs
		if( !empty( $store_prefs )) {
			$this->mStoragePrefs = $ret;
		}
	}

	/**
	 * expungeAttachmentPreferences will remove all attachment preferences of a given attachmtent
	 *
	 * @param array $pAttachmentId attachemnt we want to remove the prefs for
	 * @return bool true on success, false on failure
	 */
	public static function expungeAttachmentPreferences( $pAttachmentId ) {
		global $gBitSystem;
		$ret = false;
		if( BitBase::verifyId( $pAttachmentId ) ) {
			$sql = "DELETE FROM `".BIT_DB_PREFIX."liberty_attachment_prefs` WHERE `attachment_id` = ?";
			$gBitSystem->mDb->query( $sql, [ $pAttachmentId ]);
			$ret = true;
		}
		return $ret;
	}

	public static function getAttachmentDownloadUrl( $pAttachmentId ) {
		global $gBitSystem;
		$ret = null;
		if( BitBase::verifyId( $pAttachmentId ) ) {
			$ret = $gBitSystem->isFeatureActive( "pretty_urls" ) || $gBitSystem->isFeatureActive( "pretty_urls_extended" ) ? LIBERTY_PKG_URL."download/file/".$pAttachmentId : LIBERTY_PKG_URL."download_file.php?attachment_id=".$pAttachmentId;
		}
		return $ret;
	}

	public function getDownloadUrl():string {
		$ret = "";
		if( $this->isValid() && $this->getField( 'attachment_id' ) ) {
			$ret = LibertyMime::getAttachmentDownloadUrl( $this->getField( 'attachment_id' ) );
		}
		return $ret;
	}

	// {{{ =================== Meta Methods ====================
	/**
	 * storeMetaData
	 *
	 * @param numeric $pAttachmentId AttachmentID the data belongs to
	 * @param string $pType Type of data. e.g.: EXIF, ID3. This will default to "Meta Data"
	 * @param array $pParamHash Data that needs to be stored in the database in an array. The key will be used as the meta_title.
	 * @return bool true on success, false on failure
	 */
	public static function storeMetaData( $pAttachmentId, $pParamHash, $pType = "Meta Data",  ) {
		global $gBitSystem;
		$ret = false;
		if( BitBase::verifyId( $pAttachmentId ) && !empty( $pType ) && !empty( $pParamHash )) {
			if( \is_array( $pParamHash )) {
				foreach( $pParamHash as $key => $data ) {
					if( !\is_array( $data )) {
						// store the data in the meta table
						$meta = [
							'attachment_id' => $pAttachmentId,
							'meta_type_id'  => LibertyMime::storeMetaId( $pType, 'type' ),
							'meta_title_id' => LibertyMime::storeMetaId( $key, 'title' ),
						];

						// remove this entry from the database if it already exists
						$gBitSystem->mDb->query( "DELETE FROM `".BIT_DB_PREFIX."liberty_attachment_meta_data` WHERE `attachment_id` = ? AND `meta_type_id` = ? AND `meta_title_id` = ?", $meta );

						// don't insert empty lines
						if( !empty( $data )) {
							$meta['meta_value'] = $data;
							$gBitSystem->mDb->associateInsert( BIT_DB_PREFIX."liberty_attachment_meta_data", $meta );
						}

						$ret = true;
					}
						// should we recurse?

				}
			}
		}
		return $ret;
	}

	/**
	 * storeMetaId
	 *
	 * @param string $pDescription Description of meta key. e.g.: Exif, ID3, Album, Artist
	 * @param string $pTable Table data is stored in - either 'type' or 'title'
	 * @return int|bool newly stored ID on success, false on failure
	 */
	private static function storeMetaId( string $pDescription, string $pTable = 'type' ): int|bool {
		global $gBitSystem;
		$ret = false;
		if( !empty( $pDescription )) {
			if( !( $ret = LibertyMime::getMetaId( $pDescription, $pTable ))) {
				$store = [
					"meta_{$pTable}_id" => $gBitSystem->mDb->GenID( "liberty_meta_{$pTable}s_id_seq" ),
					"meta_{$pTable}"    => LibertyMime::normalizeMetaDescription( $pDescription ),
				];
				$gBitSystem->mDb->associateInsert( BIT_DB_PREFIX."liberty_meta_{$pTable}s", $store );
				$ret = $store["meta_{$pTable}_id"];
			}
		}
		return $ret;
	}

	/**
	 * getMetaData
	 *
	 * @param numeric $pAttachmentId AttachmentID the data belongs to
	 * @param string $pType Type of data. e.g.: EXIF, ID3.
	 * @param string $pTitle Title of data. e.g.: Artist, Album.
	 * @return array with meta data on success, false on failure
	 * $note: Output format varies depending on requested data
	 */
	public static function getMetaData( $pAttachmentId, $pType = null, $pTitle = null ) {
		global $gBitSystem;
		$ret = [];
		if( BitBase::verifyId( $pAttachmentId )) {
			$bindVars = [ $pAttachmentId ];
			$whereSql = "";
			if( !empty( $pType ) && !empty( $pTitle )) {

				// we have a type and title - only one entry will be returned
				$bindVars[] = LibertyMime::normalizeMetaDescription( $pType );
				$bindVars[] = LibertyMime::normalizeMetaDescription( $pTitle );

				$sql = "
					SELECT lmd.`meta_value`
					FROM `".BIT_DB_PREFIX."liberty_attachment_meta_data` lmd
						INNER JOIN `".BIT_DB_PREFIX."liberty_meta_types` lmtype ON( lmd.`meta_type_id` = lmtype.`meta_type_id` )
						INNER JOIN `".BIT_DB_PREFIX."liberty_meta_titles` lmtitle ON( lmd.`meta_title_id` = lmtitle.`meta_title_id` )
					WHERE lmd.`attachment_id` = ? AND lmtype.`meta_type` = ? AND lmtitle.`meta_title` = ?";
				$ret = $gBitSystem->mDb->getOne( $sql, $bindVars );

			} elseif( !empty( $pType )) {

				// only type given - return array with all vlues of this type
				$bindVars[] = LibertyMime::normalizeMetaDescription( $pType );

				$sql = "
					SELECT lmtitle.`meta_title`, lmd.`meta_value`
					FROM `".BIT_DB_PREFIX."liberty_attachment_meta_data` lmd
						INNER JOIN `".BIT_DB_PREFIX."liberty_meta_types` lmtype ON( lmd.`meta_type_id` = lmtype.`meta_type_id` )
						INNER JOIN `".BIT_DB_PREFIX."liberty_meta_titles` lmtitle ON( lmd.`meta_title_id` = lmtitle.`meta_title_id` )
					WHERE lmd.`attachment_id` = ? AND lmtype.`meta_type` = ?";
				$ret = $gBitSystem->mDb->getAssoc( $sql, $bindVars );

			} elseif( !empty( $pTitle )) {

				// only title given - return array with all vlues with this title
				$bindVars[] = LibertyMime::normalizeMetaDescription( $pTitle );

				$sql = "
					SELECT lmtype.`meta_type`, lmd.`meta_value`
					FROM `".BIT_DB_PREFIX."liberty_attachment_meta_data` lmd
						INNER JOIN `".BIT_DB_PREFIX."liberty_meta_types` lmtype ON( lmd.`meta_type_id` = lmtype.`meta_type_id` )
						INNER JOIN `".BIT_DB_PREFIX."liberty_meta_titles` lmtitle ON( lmd.`meta_title_id` = lmtitle.`meta_title_id` )
					WHERE lmd.`attachment_id` = ? AND lmtitle.`meta_title` = ?";
				$ret = $gBitSystem->mDb->getAssoc( $sql, $bindVars );

			} else {

				// nothing given - return nested array based on type and title
				$sql = "
					SELECT lmd.`attachment_id`, lmd.`meta_value`, lmtype.`meta_type`, lmtitle.`meta_title`
					FROM `".BIT_DB_PREFIX."liberty_attachment_meta_data` lmd
						INNER JOIN `".BIT_DB_PREFIX."liberty_meta_types` lmtype ON( lmd.`meta_type_id` = lmtype.`meta_type_id` )
						INNER JOIN `".BIT_DB_PREFIX."liberty_meta_titles` lmtitle ON( lmd.`meta_title_id` = lmtitle.`meta_title_id` )
					WHERE lmd.`attachment_id` = ?";

				$result = $gBitSystem->mDb->query( $sql, $bindVars );
				while( $aux = $result->fetchRow() ) {
					$ret[$aux['meta_type']][$aux['meta_title']] = $aux['meta_value'];
				}
			}
		}
		return $ret;
	}

	/**
	 * expungeMetaData will remove the meta data for a given attachment
	 *
	 * @param int $pAttachmentId Attachment ID of attachment
	 * @return bool
	 */
	public static function expungeMetaData( $pAttachmentId ) {
		global $gBitSystem;
		if( BitBase::verifyId( $pAttachmentId )) {
			return $gBitSystem->mDb->query( "DELETE FROM `".BIT_DB_PREFIX."liberty_attachment_meta_data` WHERE `attachment_id` = ?", [ $pAttachmentId ]);
		}
		return false;
	}

	/**
	 * getMetaId
	 *
	 * @param string $pDescription Description of meta key. e.g.: Exif, ID3, Album, Artist
	 * @param string $pTable Table data is stored in - either 'type' or 'title'
	 * @access public
	 * @return string meta type or title id on sucess, false on failure
	 */
	private static function getMetaId( $pDescription, $pTable = 'type' ) {
		global $gBitSystem;
		$ret = false;
		if( !empty( $pDescription ) && ( $pTable == 'type' || $pTable == 'title' )) {
			$ret = $gBitSystem->mDb->getOne( "SELECT `meta_{$pTable}_id` FROM `".BIT_DB_PREFIX."liberty_meta_{$pTable}s` WHERE `meta_{$pTable}` = ?", [ LibertyMime::normalizeMetaDescription( $pDescription )]);
		}
		return $ret;
	}

	/**
	 * getMetaDescription
	 *
	 * @param string $pId ID of type or title we want the description for
	 * @param string $pTable Table data is stored in - either 'type' or 'title'
	 * @access public
	 * @return string description on sucess, false on failure
	 */
	function getMetaDescription( $pId, $pTable = 'type' ) {
		global $gBitSystem;
		$ret = false;
		if( BitBase::verifyId( $pId )) {
			$ret = $gBitSystem->mDb->getOne( "SELECT `meta_{$pTable}` FROM `".BIT_DB_PREFIX."liberty_meta_{$pTable}s` WHERE `meta_{$pTable}_id` = ?", [ $pId ]);
		}
		return $ret;
	}

	/**
	 * normalizeMetaDescription
	 *
	 * @param string $pDescription Description of meta key. e.g.: Exif, ID3, Album, Artist
	 * @access public
	 * @return string normalized meta description that can be used as a guid
	 */
	public static function normalizeMetaDescription( $pDescription ) {
		return strtolower( substr( preg_replace( "![^a-zA-Z0-9]!", "", trim( $pDescription )), 0, 250 ));
	}
}

/**
 * mime_get_storage_sub_dir_name get a filename based on the uploaded file
 *
 * @param array pFileHash File information provided in $_FILES
 * @access public
 * @return string appropriate sub dir name
 */
if( !function_exists( '\Bitweaver\Liberty\liberty_mime_get_storage_sub_dir_name' )) {
	function liberty_mime_get_storage_sub_dir_name( $pFileHash = null ) {
		if( !empty( $pFileHash['type'] ) ) {
			// type is from upload file hash
			$mimeType = $pFileHash['type'];
		} elseif( !empty( $pFileHash['mime_type'] ) ) {
			// mime_type is from liberty_files
			$mimeType = $pFileHash['mime_type'];
		}

		if( !empty( $mimeType ) && strstr( $mimeType, "/" )) {
			$ret = strtolower( preg_replace( "!/.*$!", "", $mimeType ));
			// if we only got 'application' we will use the file extenstion
			if( $ret == 'application' && !empty( $pFileHash['name'] ) && ( $pos = strrpos( $pFileHash['name'], "." )) !== false ) {
				$ret = strtolower( substr( $pFileHash['name'], $pos + 1 ));
			}
		}

		// append an 's' to not create an image and images dir side by side (legacy reasons)
		if( empty( $ret ) || $ret == 'image' ) {
			$ret = 'images';
		}
		return $ret;
	}
}

/**
 * liberty_mime_get_storage_branch - get url to store files for the feature site_upload_dir. It creates a calculable hierarchy of directories
 *
 * @access public
 * @author Christian Fowler<spider@steelsun.com>
 * @param $pParamHash key=>value pairs to determine path. Possible keys in descending directory depth are: 'user_id' indicates the 'users/.../<user_id>' branch or use the 'common' branch if null, 'package' - any desired directory below the StoragePath. this will be created if it doesn't exist, 'sub_dir' -  the sub-directory in the package organization directory, this is often a primary id such as attachment_id
 * @return string full path on local filsystem to store files.
 */
if( !function_exists( '\Bitweaver\Liberty\liberty_mime_get_storage_path' )) {
	function liberty_mime_get_storage_path( $pParamHash, $pRootDir ) {
		$ret = null;

		if( $branch = liberty_mime_get_storage_branch( $pParamHash ) ) {
			$ret = ( !empty( $pRootDir ) ? $pRootDir : STORAGE_PKG_PATH ).$branch;
			if (!is_dir($ret)) KernelTools::mkdir_p($ret);
		}
		return $ret;
	}
}

if( !function_exists( '\Bitweaver\Liberty\liberty_mime_get_storage_branch' )) {
	function liberty_mime_get_storage_branch( $pParamHash ) {
		global $gBitSystem;
		$pathParts = [];

		if( $pUserId = BitBase::getParameter( $pParamHash, 'user_id' ) ) {
			$pathParts[] = 'users';
			$pathParts[] = (int)($pUserId % 1000);
			$pathParts[] = $pUserId;
		} elseif( $pAttachmentId = BitBase::getParameter( $pParamHash, 'attachment_id' ) ) {
			$pathParts[] = 'attachments';
			$pathParts[] = (int)($pAttachmentId % 1000);
			$pathParts[] = $pAttachmentId;
		} else {
			$pathParts[] = 'common';
		}

		if( $pPackage = BitBase::getParameter( $pParamHash, 'package' ) ) {
			$pathParts[] = $pPackage;
		}
		// In case $pSubDir is multiple levels deep we'll need to mkdir each directory if they don't exist
		if( $pSubDir = BitBase::getParameter( $pParamHash, 'sub_dir' ) ){
			$pSubDirParts = preg_split('#/#',$pSubDir);
			foreach ($pSubDirParts as $subDir) {
				$pathParts[] = $subDir;
			}
		} else {
			$pSubDir = liberty_mime_get_storage_sub_dir_name( $pParamHash );
		}

		$fullPath = implode( '/', $pathParts ).'/';
		if( BitBase::getParameter( $pParamHash, 'create_dir', true ) ){
			if( !file_exists( STORAGE_PKG_PATH.$fullPath ) ) {
				KernelTools::mkdir_p( STORAGE_PKG_PATH.$fullPath );
			}
		}
		return $fullPath;
	}
}

if( !function_exists( '\Bitweaver\Liberty\liberty_mime_get_storage_url' )) {
	function liberty_mime_get_storage_url( $pParamHash ) {
		return STORAGE_PKG_URL.liberty_mime_get_storage_branch( $pParamHash );
	}
}

if( !function_exists( '\Bitweaver\Liberty\liberty_mime_get_storage_path' )) {
	function liberty_mime_get_storage_path( $pParamHash ) {
		return STORAGE_PKG_PATH.liberty_mime_get_storage_branch( $pParamHash );
	}
}

if( !function_exists( '\Bitweaver\Liberty\liberty_mime_get_source_url' )) {
	function liberty_mime_get_source_url( $pParamHash ) {
		$fileName = BitBase::getParameter( $pParamHash, 'file_name' );
		if( empty( $pParamHash['package'] ) ) {
			$pParamHash['package'] = liberty_mime_get_storage_sub_dir_name( [ 'mime_type' => BitBase::getParameter( $pParamHash, 'mime_type' ), 'name' => $fileName ] );
		}
		if( empty( $pParamHash['sub_dir'] ) ) {
			$pParamHash['sub_dir'] = BitBase::getParameter( $pParamHash, 'attachment_id' );
		}
		$defaultFileName = liberty_mime_get_default_file_name( $fileName, BitBase::getParameter( $pParamHash, 'mime_type' ) );
		$fileBranch = liberty_mime_get_storage_branch( $pParamHash );
		$ret = file_exists( STORAGE_PKG_PATH.$fileBranch.$defaultFileName )
			? STORAGE_PKG_URL.$fileBranch.$defaultFileName
			: STORAGE_PKG_URL.$fileBranch.basename( BitBase::getParameter( $pParamHash, 'file_name' ) );
		return $ret;
	}
}

if( !function_exists( '\Bitweaver\Liberty\liberty_mime_get_source_file' )) {
	function liberty_mime_get_source_file( $pParamHash ) {
		$fileName = BitBase::getParameter( $pParamHash, 'file_name' );
		if( empty( $pParamHash['package'] ) ) {
			$pParamHash['package'] = liberty_mime_get_storage_sub_dir_name( [ 'mime_type' => BitBase::getParameter( $pParamHash, 'mime_type' ), 'name' => $fileName ] );
		}
		if( empty( $pParamHash['sub_dir'] ) ) {
			$pParamHash['sub_dir'] = BitBase::getParameter( $pParamHash, 'attachment_id' );
		}
		$defaultFileName = liberty_mime_get_default_file_name( $fileName, BitBase::getParameter( $pParamHash, 'mime_type' ) );
		$ret = STORAGE_PKG_PATH.liberty_mime_get_storage_branch( $pParamHash ).$defaultFileName;
		if( !file_exists( $ret ) ) {
			$ret = STORAGE_PKG_PATH.liberty_mime_get_storage_branch( $pParamHash ).basename( BitBase::getParameter( $pParamHash, 'file_name' ) );
		}
		return $ret;
	}
}

if( !function_exists( 'Bitweaver\Liberty\liberty_mime_get_default_file_name' )) {
	function liberty_mime_get_default_file_name( $pFileName, $pMimeType ) {
		global $gBitSystem;

		if( empty( $pMimeType ) ) {
			$pMimeType = $gBitSystem->lookupMimeType( substr( $pFileName, strrpos( $pFileName, '.' ) + 1 ) );
		}

		return $gBitSystem->isFeatureActive( 'liberty_originalize_file_names' ) ? 'original.'.$gBitSystem->getMimeExtension( $pMimeType ) : $pFileName;
	}
}

/* vim: :set fdm=marker : */