-
Notifications
You must be signed in to change notification settings - Fork 3
/
classes.inc.php
executable file
·1044 lines (863 loc) · 31.1 KB
/
classes.inc.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
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
<?php
/* ********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
******************************************************************************************************** */
require_once('config.inc.php');
require_once('globals.inc.php');
class Database {
static private $_instance = NULL;
private function __construct() {}
private function __clone() {}
static function getInstance() {
if (self::$_instance == NULL) {
self::$_instance = new Database();
self::$_instance->dbConnect();
}
return self::$_instance;
}
public static $db = null;
protected function dbConnect() {
$this->db = new PDO( $this->getDsn(), Config::dbUser, Config::dbPass );
}
protected function dbDisconnect() {
unset($this->db);
}
public function getDsn() {
return ('mysql:dbname=' . trim(Config::dbName) . ';host=' . trim(Config::dbHost));
}
public function export($tablename, $filename) {
// Exports a table to CSV
// Accepts: table name, output file name
// Returns: CSV formatted file
$fp = fopen($filename,'w');
// Get column names into $columnList[]
$columns = $this->db->query('SHOW COLUMNS IN `'.$tablename.'`')->fetchAll();
$columnList = array();
foreach($columns as $thiscol) {
$columnList[] = $thiscol[0];
};
fputcsv($fp, $columnList);
// Get records into $records[]
$records = $this->db->query('SELECT * FROM `'.$tablename.'`')->fetchAll();
foreach($records as $thisrec) {
$line = array();
foreach($columnList as $thiscol) {
$line[] = $thisrec[$thiscol];
};
fputcsv($fp, $line);
};
fclose($fp);
}
public function import($tablename, $source) {
// Imports a table from CSV
// Accepts: Table name as $tablename, CSV file contents as $source
// Returns: true if successful, false if an error occurred
if(!function_exists('cleanupHeaders')) {
function cleanupHeaders(&$input) {
// Quick callback function used by Inventory::import()
$input = trim(stripslashes($input),'"');
};
};
$fp = fopen($source,'r');
$headers = fgetcsv($fp);
// Verify each column header exists in the destination table
$columns = $this->db->query('SHOW COLUMNS IN `'.$tablename.'`')->fetchAll();
$columnList = array();
foreach($columns as $thiscol) {
$columnList[] = $thiscol[0];
};
// Wipe out the existing table and reset the primary key
$this->db->query('TRUNCATE TABLE `'.$tablename.'`');
if(sizeof(array_intersect($headers, $columnList)) !== sizeof($headers)) {
// One or more headers not found; abort and return false
return false;
};
// Walk through the file and do the import
while($line = fgetcsv($fp)) {
// Logic on the next line avoids warning conditions on blank lines (near EOF, etc)
if(sizeof($line) >0) {
$prepare_array = array();
$execute_array = array();
$idx = 0;
foreach($headers as $thiskey) {
$prepare_array[$thiskey] = $tablename . '.' .$thiskey.'=:'.$thiskey;
// For proper handling of null values
if($line[$idx]=='') {
$execute_array[$thiskey] = null;
} else {
$execute_array[$thiskey] = $line[$idx];
};
$idx++;
};
// Preserved for posterity
// $st = $this->db->prepare('INSERT INTO `'.$tablename.'` (`' .implode('`, `', array_keys($execute_array)). '`) VALUES (:'.implode(', :',array_keys($execute_array)).') ON DUPLICATE KEY UPDATE '.implode(', ', $prepare_array).' WHERE id=:id');
$st = $this->db->prepare('INSERT INTO `'.$tablename.'` (`' .implode('`, `', array_keys($execute_array)). '`) VALUES (:'.implode(', :',array_keys($execute_array)).')');
$st -> execute($execute_array);
};
};
fclose($fp);
}
}
/* ********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
******************************************************************************************************** */
/**
*
* Generic Inventory Class
*
*/
class Inventory extends Database {
protected $attributes = array();
protected $items = array();
protected $locations = array();
protected $groups = array();
private $modified = false;
public function __construct() {
// Load all items into $this->items[]
$connection = Database::getInstance();
$this->items = array();
$st = $connection->db->query('SELECT id FROM items ORDER BY shortName');
while ($record = $st->fetch(PDO::FETCH_ASSOC)) {
$item = new Item($record['id']);
$this->items[$record['id']] = $item;
};
// Load all locations into $this->locations[]
$this->locations = array();
$st = $connection->db->query('SELECT id FROM locations WHERE TRIM(shortName) IS NOT NULL ORDER BY shortName');
while ($record = $st->fetch(PDO::FETCH_ASSOC)) {
$location = new Location($record['id']);
$this->locations[$record['id']] = $location;
};
// Load all groups into $this->groups[]
$this->groups = array();
$st = $connection->db->query('SELECT id FROM groups WHERE TRIM(shortName) IS NOT NULL ORDER BY shortName');
while ($record = $st->fetch(PDO::FETCH_ASSOC)) {
$group = new Group($record['id']);
$this->groups[$record['id']] = $group;
};
}
public function __destruct() {
$this->cleanup();
}
public function id() {
if(array_key_exists('id', $this->getAttributes())) {
return $this->getAttribute('id');
} else {
return false;
};
}
public function isEmpty() {
// Returns true if all attributes except 'id' are null
$allnull = true;
foreach (array_keys($this->getAttributes()) as $thiskey) {
if ($thiskey!=='id') {
if ($this->getAttribute($thiskey) !== null) {
$allnull = false;
}
}
}
return $allnull;
}
public function regenerateThumbs($doall = false) {
// Regenerates thumbnail images for all items
// Accepts: $doall .. if false, only generates missing thumbnails
// if true, deletes existing thumbnails first
$items = $this->allItems();
if($doall) {
// Prepare to regenerate all thumbnails
foreach($items as $item) {
$attachments = $item->getAttachments();
foreach($attachments as $attachment) {
if($attachment->hasThumbnail()) {
// Sanity check before trying to delete the file
// Thumbnails might not exist but hasThumbnail() could return true if restoring
if(file_exists($attachment->getThumbname())) {
unlink($attachment->getThumbname());
};
$attachment->setAttribute('hasThumb', false);
};
};
};
} else {
// Prepare to regenerate only missing thumbnails
foreach($items as $item) {
$attachments = $item->getAttachments();
foreach($attachments as $attachment) {
if($attachment->hasThumbnail()) {
if(!file_exists($attachment->getThumbname())) {
$attachment->setAttribute('hasThumb', false);
};
};
};
};
};
$attach = 0;
$count = 0;
$regen = 0;
foreach($items as $item) {
$count++;
$attachments = $item->getAttachments();
foreach($attachments as $attachment) {
$attach++;
if($attachment->hasThumbnail() == false) {
$regen++;
set_time_limit(300);
$attachment->makeThumbnail();
};
};
};
}
public function setAttribute($attribute, $value, $noDbUpdate=false) {
// Sets the specified attribute to provided value
// $noDbUpdate = true means do not update the database yet
if ( array_key_exists($attribute, $this->attributes) && ($attribute !== 'id')) {
$this->attributes[$attribute] = $value;
// Update the modification token
$this->modified = true;
return true;
} else {
return false;
};
if(!$noDbUpdate) {
$this->update('items',$attribute);
};
}
public function setAttributes($attributes) {
// Accepts an array of attributes and updates the corresponding keys
// Key exclusion (ie, for the 'id' key) is provided by the setAttribute() function
$attribUpdated = false;
foreach(array_keys($attributes) as $thiskey) {
if(array_key_exists($thiskey, $this->attributes)) {
$result = $this->setAttribute($thiskey, $attributes[$thiskey], true);
if($result) {
$attribUpdated = true;
};
};
};
$this->modified = true;
$this->update('items',false);
return $attribUpdated;
}
public function getAttribute($attribute) {
// Returns the specified individual attribute
if ( array_key_exists($attribute, $this->attributes)) {
return $this->attributes[$attribute];
} else {
return false;
};
}
public function getAttributes() {
// Returns the full attribute array
return $this->attributes;
}
protected function update($tablename='items', $onlykey=null) {
// Updates the database with current values, if changed
// If $onlykey is specified, then only the $onlykey will be updated
if(isset($this->attributes['id'])) { // prevents error during __destruct() if item is being deleted
if($this->modified) {
$connection = Database::getInstance();
$keynames = array_keys($this->attributes);
$prepare_array = array();
$execute_array = array();
foreach($keynames as $thiskey) {
if(($thiskey !== 'id') && ((($onlykey!=null) && ($thiskey==$onlykey)) || ($onlykey==null))) {
$prepare_array[$thiskey] = $tablename . '.' .$thiskey.'=:'.$thiskey;
// Update to provide proper handling of null values (we want to insert a NULL, not a "")
if(trim($this->attributes[$thiskey]=='')) {
$execute_array[$thiskey] = null;
} else {
$execute_array[$thiskey] = trim($this->attributes[$thiskey]);
}
};
};
$execute_array['id'] = $this->attributes['id'];
$st = $connection->db->prepare('UPDATE ' . $tablename . ' SET ' . implode(', ', $prepare_array). ' WHERE id=:id');
$st -> execute($execute_array);
unset($keynames);
unset($prepare_array);
unset($execute_array);
unset($st);
$this->modified = false;
};
};
return true;
}
public function getItem($id) {
// Returns the item from the current Inventory with $id or false if does not exist
if(array_key_exists($id, $this->items)) {
return $this->items[$id];
} else {
return false;
};
}
public function newItem() {
// Creates and returns a new item. Returns the ID in the $id reference variable
$item = new Item();
$id = $item->getAttribute('id');
$this->items[$id] = $item;
$this->modified = true;
return $this->items[$id];
}
public function allItems() {
// Returns all items
return $this->items;
}
public function allGroups() {
// Returns all groups
return $this->groups;
}
public function deleteItem($id) {
// Deletes the item with $id
$item = $this->getItem($id);
$item->delete();
$this->modified=true;
unset($this->items[$id]);
}
public function cleanup() {
$this->cleanupGroups();
$this->cleanupLocations();
}
private function cleanupGroups() {
// Deletes unused groups; do not allow deletion of "* Default" group
foreach($this->groups as $group) {
if (($group->getAttribute('shortName')!=='* Default') && (sizeof($this->itemsByGroup($group->id())) == 0)) {
$group->delete();
unset($this->groups[$group->id()]);
$this->modified=true;
};
};
}
private function cleanupLocations() {
// Deletes unused locations; do not allow deletion of "* Default" location
foreach($this->locations as $location) {
if(($location->getAttribute('shortName')!=='* Default') && (sizeof($this->itemsByLocation($location->id())) == 0)) {
$location->delete();
unset($this->locations[$location->id()]);
$this->modified=true;
};
};
}
public function allLocations($nonEmpty=0) {
return $this->locations;
}
public function getLocation($id) {
// Returns the location corresponding to single $id, or false if not found
if(array_key_exists($id, $this->locations)) {
return($this->locations[$id]);
} else {
return false;
};
}
public function getGroup($id) {
// Returns the group corresponding to single $id, or false if not found
if(array_key_exists($id, $this->groups)) {
return($this->groups[$id]);
} else {
return false;
};
}
public function matchLocation($shortName) {
// Performs a case-insensitive search for location by $shortName
// Returns the corresponding location, or false if none found
$connection = Database::getInstance();
$st = $connection->db->prepare('SELECT id FROM locations WHERE TRIM(LOWER(shortName))=?');
$st->execute(array(trim(strtolower($shortName))));
$record = $st->fetch(PDO::FETCH_ASSOC);
if($record) {
return $this->getLocation($record['id']);
} else {
return false;
};
}
public function newLocation($idnum) {
// Creates and returns a new location. Returns the ID in the $idnum reference variable
$location = new Location();
$this->locations[$location->id()] = $location;
$this->modified = true;
return $this->locations[$location->id()];
}
public function matchGroup($shortName) {
// Performs a case-insensitive search for group by $shortName
// Returns the corresponding group, or false if none found
$connection = Database::getInstance();
$st = $connection->db->prepare('SELECT id FROM groups WHERE TRIM(LOWER(shortName))=?');
$st->execute(array(trim(strtolower($shortName))));
$record = $st->fetch(PDO::FETCH_ASSOC);
if($record) {
return $this->getGroup($record['id']);
} else {
return false;
};
}
public function newGroup($idnum) {
// Creates and returns a new group. Returns the ID in the $idnum reference variable
$group = new Group();
$this->groups[$group->id()] = $group;
$this->modified = true;
return $this->groups[$group->id()];
}
public function itemsByGroup($group) {
// Returns an array of all items belonging to the specified $group
$list = array();
foreach($this->items as $item) {
if ($item->getAttribute('group') == $group) {
$list[$item->id()] = $item;
};
};
return $list;
}
public function itemsByLocation($location) {
// Returns a list of all items belonging to the specified $location id
$list = array();
foreach($this->items as $item) {
if ($item->getAttribute('location') == $location) {
$list[$item->id()] = $item;
};
};
return $list;
}
}
/* ********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
******************************************************************************************************** */
/**
*
* Item Class
*
*/
class Item extends Inventory {
private $attachments = array();
private $valid = false;
private $modified = false;
public function __construct($id=null) {
$this->buildItem($id, 'items');
}
public function __tostring() {
return $this->attributes['id'];
}
protected function buildItem($id, $tablename="items") {
$connection = Database::getInstance();
if($id==null) {
// Create new record
$connection->db->query('INSERT INTO ' . $tablename . ' () VALUES ()');
$this->attributes['id'] = $connection->db->lastInsertId();
// Read it back in to initialize the attributes
$record = $connection->db->query('SELECT * FROM ' . $tablename . ' WHERE id=' . $this->attributes['id']) -> fetch(PDO::FETCH_ASSOC);
$this->attributes = $record;
$this->valid = true;
$this->loadAttachments($this->attributes['id']);
$this->modified=true;
} else {
// Read existing record
$st = $connection->db->prepare('SELECT * FROM ' . $tablename . ' WHERE id=?');
$st->execute(array($id));
$record = $st->fetch(PDO::FETCH_ASSOC);
if($record['id'] == null) {
// No record returned, abort
$this->valid = false;
} else {
$this->valid = true;
$this->attributes = $record;
$this->loadAttachments($this->attributes['id']);
};
};
$this->dbDisconnect();
unset($record);
}
public function isValid() {
return $this->valid;
}
private function loadAttachments($id) {
// Loads attachment items from database
$attachmentList = Attachment::attachmentsForItem($id);
foreach($attachmentList as $attachmentId) {
$this->attachments[$attachmentId] = new Attachment($attachmentId);
};
unset($attachmentList);
unset($attachmentId);
}
public function addAttachment($filename, $originalName) {
// Adds a new attachment stored on the server as $filename
// $originalName is the name of the file on the client machine
$newAttachment = new Attachment();
$newAttachment->setAttribute('item', $this->attributes['id']);
$newAttachment->addFile($filename,$originalName);
$this->attachments[$newAttachment->getAttribute('id')] = $newAttachment;
$this->modified = true;
}
public function __destruct() {
foreach($this->attachments as $attachment) {
$attachment->__destruct();
}
$this->update('items');
}
public function getAttachment($id) {
// Returns specific attachment
if(array_key_exists($id, $this->attachments)) {
return $this->attachments[$id];
} else {
return false;
}
}
public function getAttachments() {
// Returns all attachments
return $this->attachments;
}
public function deleteAttachment($id) {
// Destroys the specified attachment with $id
$this->attachments[$id]->delete();
unset($this->attachments[$id]);
$this->modified = true;
}
public function delete() {
// Destroys the current item
// Inventory::deleteItem is probably what you're looking for
foreach ($this->attachments as $attachment) {
$this->deleteAttachment($attachment->getAttribute('id'));
};
$connection = Database::getInstance();
$st = $connection->db->prepare('DELETE FROM items WHERE id=?');
$st -> execute(array($this->attributes['id']));
$this->attributes = array();
return true;
}
}
/* ********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
******************************************************************************************************** */
class NullItem extends Item {
public function __construct() {
// Creates a simulated attributes() array with all values set to null
$connection = Database::getInstance();
$result = $connection -> db -> query('SHOW FULL COLUMNS IN items');
while($thiskey = $result->fetch(PDO::FETCH_ASSOC)) {
$this->attributes[$thiskey['Field']] = null;
};
}
public function __destruct() {
// Do nothing
}
}
/* ********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
******************************************************************************************************** */
/**
*
* Group class
*
*/
class Group extends Inventory {
protected $attributes = array();
public function __construct($id=null) {
$this->buildGroup($id, 'groups');
}
public function __destruct() {
$this->update('groups');
}
public function delete() {
// Deletes this ID from the database
// Note: Inventory::deleteGroup() is probably what you're looking for...
$connection = Database::getInstance();
$st = $connection->db->prepare('DELETE FROM groups WHERE id=?');
$st->execute(array($this->getAttribute('id')));
}
private function buildGroup($id, $tablename) {
$connection = Database::getInstance();
if($id==null) {
// Create new record
$connection->db->query('INSERT INTO ' . $tablename . ' () VALUES ()');
$this->attributes['id'] = $connection->db->lastInsertId();
// Read it back in to initialize the attributes
$record = $connection->db->query('SELECT * FROM ' . $tablename . ' WHERE id=' . $this->attributes['id']) -> fetch(PDO::FETCH_ASSOC);
$this->attributes = $record;
$this->valid = true;
} else {
// Read existing record
$st = $connection->db->prepare('SELECT * FROM ' . $tablename . ' WHERE id=?');
$st->execute(array($id));
$record = $st->fetch(PDO::FETCH_ASSOC);
if($record['id'] == null) {
// No record returned, abort
$this->valid = false;
} else {
$this->valid = true;
$this->attributes = $record;
};
};
}
}
/* ********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
******************************************************************************************************** */
/**
*
* Location class
*
*/
class Location extends Inventory {
protected $attributes = array();
public function __construct($id=null) {
$this->buildLocation($id, 'locations');
}
private function buildLocation($id, $tablename) {
$connection = Database::getInstance();
if($id==null) {
// Create new record
$connection->db->query('INSERT INTO ' . $tablename . ' () VALUES ()');
$this->attributes['id'] = $connection->db->lastInsertId();
// Read it back in to initialize the attributes
$record = $connection->db->query('SELECT * FROM ' . $tablename . ' WHERE id=' . $this->attributes['id']) -> fetch(PDO::FETCH_ASSOC);
$this->attributes = $record;
$this->valid = true;
} else {
// Read existing record
$st = $connection->db->prepare('SELECT * FROM ' . $tablename . ' WHERE id=?');
$st->execute(array($id));
$record = $st->fetch(PDO::FETCH_ASSOC);
if($record['id'] == null) {
// No record returned, abort
$this->valid = false;
} else {
$this->valid = true;
$this->attributes = $record;
};
};
unset($record);
}
public function __destruct() {
$this->update('locations');
}
public function delete() {
// Deletes this ID from the database
// Note: Inventory::deleteLocation() is probably what you're looking for...
$connection = Database::getInstance();
$st = $connection->db->prepare('DELETE FROM locations WHERE id=?');
$st->execute(array($this->getAttribute('id')));
}
public function contains() {
// returns an array list of item id's which belong to the location $id
$connection = Database::getInstance();
$st = $connection->db->prepare('SELECT id FROM items WHERE location=?');
$st -> execute(array($this->id()));
$result = $st->fetch(PDO::FETCH_ASSOC);
return $result;
}
}
/* ********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
********************************************************************************************************
******************************************************************************************************** */
/**
*
* Attachment class
*
*/
class Attachment extends Item {
protected $attributes = array();
public function __construct($id=null) {
$this->buildItem($id, 'attachments');
}
public function __destruct() {
$this->update('attachments');
}
public function addFile($filename, $originalName) {
// Adds the data from the specified $filename to the record
// $originalName is the name of the file from the client computer
// Determine if it's an image
$imgInfo = getimagesize($filename);
$isImg = ($imgInfo[2]>0);
if($isImg) {
// It's an image
$this->setAttribute('isImg',true);
$this->setAttribute('imgType',$imgInfo[2]);
$this->setAttribute('imgWidth',$imgInfo[0]);
$this->setAttribute('imgHeight',$imgInfo[1]);
$this->setAttribute('mime',$imgInfo['mime']);
$this->setAttribute('sha1',sha1_file($filename));
$this->setAttribute('originalExt',pathinfo(strtolower($originalName), PATHINFO_EXTENSION));
} else {
// Not an image
$this->setAttribute('isImg',false);
$this->setAttribute('imgType',null);
$this->setAttribute('imgWidth',null);
$this->setAttribute('imgHeight',null);
$this->setAttribute('mime', trim(shell_exec("/usr/bin/file -bi " . escapeshellarg($filename))));
$this->setAttribute('sha1', sha1_file($filename));
$this->setAttribute('originalExt', pathinfo(strtolower($originalName), PATHINFO_EXTENSION));
};
rename($filename, $this->getFilename());
$this->makeThumbnail();
$this->update('attachments');
unset($filename);
}
private function getFilename() {
// Returns the relative path and name of the attachment data file
return ('attachments/'.$this->getAttribute('sha1').'.'.$this->getAttribute('originalExt'));
}
public function getFiledata() {
// Returns the raw binary content of the attachment data file
return (file_get_contents($this->getFilename()));
}
public function getFileBase64($inline = false) {
// Returns the base64-encoded content of the attachment data file
// Adds base64 encoding if $inline parameter is set to BASE64_INLINE_IMG
if($inline == BASE64_INLINE_IMG) {
return ('data:' . $this->getAttribute('mime') . ';base64,' . base64_encode($this->getFiledata()));
} else {
return (base64_encode($this->getFiledata()));
};
}
public function getThumbname() {
// Returns relative path and name of thumbnail file
return ('thumbs/'.$this->getAttribute('sha1').'.jpg');
}
private function isPdf() {
// Returns true/false if file is a PDF
if (strpos($this->getAttribute('mime'), 'application/pdf') === false) {
return false;
} else {
return true;
};
}
public function makeThumbnail() {
// Generates a thumbnail image for a file
if (!class_exists('Imagick',false)) {
// Imagemagick is not installed, so abort
return false;
};
if ($this->isPdf()) {
if (file_exists($this->getThumbname())) {
// Use the existing thumbnail image
$this->setAttribute('hasThumb', true);
$imagick = new Imagick();
$imagick->readImage($this->getThumbname());
$this->setAttribute('imgWidth', $imagick->getImageWidth());
$this->setAttribute('imgHeight', $imagick->getImageHeight());
unset ($imagick);
return true;
} else {
// Make a thumbnail of the PDF if one does not already exist
$imagick = new Imagick();
$imagick->readImage($this->getFilename().'[0]');
$imagick = $imagick->flattenImages();
$imagick->writeImage($this->getThumbname()); // Temporarily write to disk so we can retrieve the dimensions
unset($imagick);
$imagick = new Imagick();
$imagick->readImage($this->getThumbname());
$this->setAttribute('imgWidth', $imagick->getImageWidth());
$this->setAttribute('imgHeight', $imagick->getImageHeight());
$imagick->scaleImage(256,256,false);
$imagick->writeImage($this->getThumbname());
$this->setAttribute('hasThumb', true);
unset ($imagick);
return true;
};
};
if ($this->getAttribute('isImg')) {
if (file_exists($this->getThumbname())) {
// Use the existing thumbnail image
$this->setAttribute('hasThumb', true);
$imagick = new Imagick();
$imagick->readImage($this->getThumbname());
$this->setAttribute('imgWidth', $imagick->getImageWidth());
$this->setAttribute('imgHeight', $imagick->getImageHeight());
unset ($imagick);
return true;
} else {
// Make a new thumbnail of the image if one does not already exist
$imagick = new Imagick();
$imagick->readImage($this->getFilename());
$imagick->scaleImage(256,256,false);
$imagick->writeImage($this->getThumbname());
$this->setAttribute('hasThumb', true);
unset ($imagick);
return true;
};
};
return false;
}
public function hasThumbnail() {
// returns true/false if a thumbnail exists
return ($this->getAttribute('hasThumb'));
}
public function getThumbBase64($inline = false) {
// Returns the base64-encoded content of the attachment data file
// Adds base64 encoding if $inline parameter is set to BASE64_INLINE_IMG
// Returns false if no thumbnail exists
if($this->hasThumbnail()) {
if($inline == BASE64_INLINE_IMG) {
return ('data:image/jpeg;base64,' . base64_encode(file_get_contents($this->getThumbname())));
} else {
return (base64_encode($this->getFiledata()));
};
} else {
return false;
};
}
private function getFileType() {
// Returns MIME data type of the file stored in the fileData attribute
if($this->getAttribute('fileData') !== false) {
$fi = new finfo(FILEINFO_MIME, '/usr/share/file/magic');
return $fi -> buffer($this->getAttribute('filedata'));
} else {
return false;
};
}
private function isImage() {
// Returns true if the file stored in the fileData attribute is an image
if($this->getAttribute('fileData') !== false) {
return (strpos( $this->getFileType(), 'image/') >= 1);
} else {
return false;
}
}
public function attachmentsForItem($id) {
// Returns an array of attachment id's which belong to the specified item id
if($id==null) {