Design/Database.pm untested

filter: Statementstmt 0.0% 0 / 755 Branchbran 0.0% 0 / 204 Conditioncond 0.0% 0 / 68 MC/DCmcdc 0.0% 0 / 42 Subroutinesub 0.0% 0 / 49 Podpod 0.0% 0 / 32 totaltotal 0.0% 0 / 1150 CC 103 SCAR 44.7
CC
103
Cov
0%
test_size
306.0
process_feature
210.0
process_property
110.0
CRAP 87.7
1 package WWW::Garden::Design::Database;
2  
3 use Moo::Role;
4  
5 use boolean;
6 use strict;
7 use warnings;
8  
9 use Data::Dumper::Concise; # For Dumper().
10  
11 use File::Copy;
12 use File::Slurper qw/read_dir/;
13 use File::Spec;
14  
15 use Imager;
16 use Imager::Fill;
17  
18 use Lingua::EN::Inflect qw/inflect PL_N/; # PL_N: plural of a singular noun.
19  
20 use Text::CSV::Encoded;
21  
22 use Time::HiRes qw/gettimeofday tv_interval/;
23  
24 use Try::Tiny;
25  
26 use Types::Standard qw/Any Object HashRef/;
27  
28 use Unicode::Collate;
29  
30 use WWW::Garden::Design::Util::Config;
31  
32 has config =>
33 (
34 default => sub{WWW::Garden::Design::Util::Config -> new -> config},
35 is => 'rw',
36 isa => HashRef,
37 required => 0,
38 );
39  
40 has constants =>
41 (
42 default => sub{return {} },
43 is => 'rw',
44 isa => HashRef,
45 required => 0,
46 );
47  
48 has db =>
49 (
50 is => 'rw',
51 isa => Any,
52 required => 0,
53 );
54  
55 has logger =>
56 (
57 is => 'rw',
58 isa => Object,
59 required => 0,
60 );
61  
62 has title_font =>
63 (
64 default => sub{return ''},
65 is => 'rw',
66 isa => Any,
67 required => 0,
68 );
69  
70 our $VERSION = '0.97';
71  
72 # -----------------------------------------------
73  
74 sub activity
75 {
76 my($self) = @_;
77  
78 $self -> logger -> debug("Database.activity(). Entered");
79  
80 my(@result);
81  
82 my($activity) = sort{$$a{timestamp} cmp $$b{timestamp} } $self -> read_table('log'); # Uses db()!
83  
84 for my $record (reverse @$activity)
85 {
86 push @result,
87 {
88 context => $$record{context},
89 file_name => $$record{file_name},
90 name => $$record{name},
91 note => $$record{note},
92 outcome => $$record{outcome},
93 timestamp => $$record{timestamp},
94 };
95 }
96  
97 return [@result];
98  
99 } # End of activity.
100  
101 # --------------------------------------------------
102  
103 sub add_flower
104 {
105 my($self) = @_;
106  
107 return '';
108  
109 } # End of add_flower.
110  
111 # -----------------------------------------------
112  
113 sub analyze_gardens_property_menu
114 {
115 my($self, $gardens_table, $default_id) = @_;
116  
117 #$self -> logger -> debug("Database.analyze_gardens_property_menu(). Entered");
118  
119 my(%property_name);
120  
121 for my $garden (@$gardens_table)
122 {
123 $property_name{$$garden{property_name} } = $$garden{property_id};
124 }
125  
126 my($current_property_id) = 0;
127 my($found) = false;
128  
129 # Warning: Apart from the HTML stuff, this code is the same as in build_gardens_property_menu(),
130 # because that way we can get build_garden_menu() to use that method to replicate the logic here.
131  
132 for my $property_name (sort keys %property_name)
133 {
134 my($property_id) = $property_name{$property_name};
135  
136 if ($found -> isFalse &&
137 (
138 ($default_id == 0) || ($default_id == $property_id)
139 )
140 )
141 {
142 # Set this on the 1st menu item (default_id == 0) or the one desired.
143  
144 $found = true;
145  
146 # current_property_id is used in build_garden_menu().
147  
148 $current_property_id = $property_id;
149 }
150 }
151  
152 return $current_property_id;
153  
154 } # End of analyze_gardens_property_menu.
155  
156 # -----------------------------------------------
157  
158 sub build_garden_menu
159 {
160 my($self, $controller, $gardens_table, $jquery_id) = @_;
161  
162 #$self -> logger -> debug('Database.build_garden_menu(). Entered');
163  
164 my($property_id) = $self -> analyze_gardens_property_menu($gardens_table, 0);
165 my($found) = false;
166 my($html) = "<select id = '$jquery_id' name = '$jquery_id'>";
167 my($selected) = '';
168  
169 for my $garden (@$gardens_table)
170 {
171 # This test assumes that within a property, all garden names are unique.
172  
173 next if ($property_id ne $$garden{property_id});
174  
175 if ($found -> isFalse)
176 {
177 # Set this on the 1st menu item.
178  
179 $found = true;
180 $selected = 'selected';
181 }
182  
183 $html .= "<option $selected value = '$$garden{id}'>$$garden{name}</option>";
184 $selected = '';
185 }
186  
187 $html .= '</select>';
188  
189 return $html;
190  
191 } # End of build_garden_menu.
192  
193 # -----------------------------------------------
194  
195 sub build_gardens_property_menu
196 {
197 my($self, $controller, $gardens_table, $jquery_id, $default_id) = @_;
198  
199 #$self -> logger -> debug("Database.build_gardens_property_menu(default_id: $default_id). Entered");
200  
201 my(%property_name);
202  
203 for my $garden (@$gardens_table)
204 {
205 $property_name{$$garden{property_name} } = $$garden{property_id};
206 }
207  
208 my($found) = false;
209 my($html) = "<select id = '$jquery_id' name = '$jquery_id'>";
210 my($selected) = '';
211  
212 # Warning: Apart from the HTML stuff, this code is the same as in analyze_gardens_property_menu(),
213 # because that way we can get build_garden_menu() to use that method to replicate the logic here.
214  
215 for my $property_name (sort keys %property_name)
216 {
217 my($property_id) = $property_name{$property_name};
218  
219 if ($found -> isFalse &&
220 (
221 ($default_id == 0) || ($default_id == $property_id)
222 )
223 )
224 {
225 # Set this on the 1st menu item or the one desired.
226  
227 $found = true;
228 $selected = ' selected';
229 }
230  
231 $html .= "<option$selected value = '$property_id'>$property_name</option>";
232 $selected = '';
233 }
234  
235 $html .= '</select>';
236  
237 return $html;
238  
239 } # End of build_gardens_property_menu.
240  
241 # -----------------------------------------------
242  
243 sub build_feature_menu
244 {
245 my($self, $features, $default_id) = @_;
246 my($found) = false;
247 my($html) = "<div class = 'feature_toolbar'>"
248 . "<select id = 'feature_menu'>";
249 my($selected) = '';
250  
251 for my $feature (@$features)
252 {
253 my($feature_id) = $$feature{id};
254  
255 if ($found -> isFalse &&
256 (
257 ($default_id == 0) || ($default_id == $feature_id)
258 )
259 )
260 {
261 # Set this on the 1st menu item or the one desired.
262  
263 $found = true;
264 $selected = ' selected';
265 }
266  
267 $html .= "<option$selected value = '$feature_id'>$$feature{name}</option>";
268 $selected = '';
269 }
270  
271 $html .= "</select>\n</div>\n";
272  
273 return $html;
274  
275 } # End of build_feature_menu.
276  
277 # -----------------------------------------------
278  
279 sub build_properties_property_menu
280 {
281 my($self, $properties, $jquery_id, $default_id) = @_;
282 my($html) = "<select id = '$jquery_id' name = '$jquery_id'>";
283 my($last_name) = '';
284  
285 my($id);
286 my($name);
287 my($selected);
288  
289 for my $property (sort{$$a{name} cmp $$b{name} } @$properties)
290 {
291 # $id can never be 0, but $default_id can be.
292  
293 $id = $$property{id};
294 $name = $$property{name};
295  
296 if ($default_id == $id)
297 {
298 # Set given id as selected.
299  
300 $default_id = 0;
301 $last_name = $name;
302 $selected = ' selected';
303 }
304 elsif ($default_id > 0)
305 {
306 $selected = '';
307 }
308 elsif ($last_name eq '')
309 {
310 # Set first id as selected if no id given.
311  
312 $last_name = $name;
313 $selected = ' selected';
314 }
315 else
316 {
317 $selected = '';
318 }
319  
320 $html .= "<option$selected value = '$$property{id}'>$name</option>";
321 $selected = '';
322 }
323  
324 $html .= '</select>';
325  
326 return $html;
327  
328 } # End of build_properties_property_menu.
329  
330 # --------------------------------------------------
331  
332 sub clean_up_feature_name
333 {
334 my($self, $name) = @_;
335 my($file_name) = $name =~ s/\s/./gr;
336  
337 return $file_name;
338  
339 } # End of clean_up_feature_name.
340  
341 # -----------------------------------------------
342  
343 sub crosscheck
344 {
345 my($self) = @_;
346  
347 #$self -> logger -> debug("Database.crosscheck(). Entered");
348  
349 my($constants) = $self -> read_constants_table; # Uses db()!
350 my($homepage_dir) = $$constants{homepage_dir};
351 my($homepage_url) = $$constants{homepage_url};
352 my($flowers) = $self -> read_flowers_table;
353  
354 # Read in the flower image names.
355  
356 my(%file_list);
357  
358 my($image_dir) = $$constants{image_dir};
359 my($image_path) = File::Spec -> catfile($homepage_dir, $image_dir);
360 my(@entries) = read_dir $image_path;
361 @entries = sort grep{! -d File::Spec -> catfile($image_path, $_)} @entries; # Can't call sort directly on output of read_dir!
362 $file_list{file_names} = [@entries];
363 @{$file_list{name_hash} }{@entries} = (1) x @entries;
364 my($action) = 'crosscheck';
365 my($log_table_name) = 'log';
366 my($table_name) = 'flowers';
367  
368 # Check that the files which ought to be there, are.
369  
370 my($common_name, $context);
371 my($file_name, $fields);
372 my($image, $id);
373 my($log_id);
374 my($pig_latin);
375 my(@result);
376 my($scientific_name);
377 my($target_dir);
378  
379 for my $flower (@$flowers)
380 {
381 $common_name = $$flower{common_name};
382 $scientific_name = $$flower{scientific_name};
383 $pig_latin = $self -> scientific_name2pig_latin($flowers, $scientific_name, $common_name);
384 $file_name = "$pig_latin.0.jpg";
385  
386 if (! $file_list{name_hash}{$file_name})
387 {
388 $context = 'Thumbnail';
389 $file_name = File::Spec -> catdir($homepage_dir, $image_dir, $file_name);
390  
391 push @result, {context => 'Thumbnail', file => $file_name, outcome => 'Missing'};
392  
393 $fields =
394 {
395 action => $action,
396 context => $context,
397 file_name => $file_name,
398 key => 0,
399 name => $scientific_name,
400 note => '',
401 outcome => 'Missing',
402 };
403  
404 $log_id = $self -> db -> insert
405 (
406 $log_table_name,
407 $fields,
408 {returning => 'id'}
409 ) -> hash -> {id};
410 }
411  
412 for $image (@{$$flower{images} })
413 {
414 $file_name = File::Spec -> catdir($homepage_dir, $image_dir, $$image{raw_name});
415  
416 if (! -e $file_name)
417 {
418 push @result, {context => 'Image', file => $file_name, outcome => 'Missing'};
419  
420 $context = 'Image';
421 $fields =
422 {
423 action => $action,
424 context => $context,
425 file_name => $file_name,
426 key => 0,
427 name => $scientific_name,
428 note => '',
429 outcome => 'Missing',
430 };
431  
432 $log_id = $self -> db -> insert
433 (
434 $log_table_name,
435 $fields,
436 {returning => 'id'}
437 ) -> hash -> {id};
438 }
439 }
440 }
441  
442 # Read in the features table.
443  
444 my($features) = $self -> read_features_table; # Uses db()!
445  
446 # Read in the feature icon names.
447  
448 my($feature_file);
449 my(%icon_list);
450  
451 my($feature_dir) = $$constants{feature_dir};
452 my($feature_path) = File::Spec -> catfile($homepage_dir, $feature_dir);
453 @entries = read_dir $feature_path;
454 @entries = sort grep{! -d File::Spec -> catfile($feature_path, $_)} @entries; # Can't call sort directly on output of read_dir!
455 @icon_list{@entries} = (1) x @entries;
456 $context = 'Feature';
457 $table_name = 'features';
458  
459 # Check that the files which ought to be there, are.
460  
461 for my $feature (@$features)
462 {
463 $feature_file = "$$feature{feature_file}.png";
464  
465 if (! $icon_list{$feature_file})
466 {
467 $file_name = File::Spec -> catfile($homepage_dir, $feature_dir, $feature_file);
468  
469 push @result, {context => 'Feature', file => $file_name, outcome => 'Missing'};
470  
471 $fields =
472 {
473 action => $action,
474 context => 'Feature',
475 file_name => $file_name,
476 key => 0,
477 name => $$feature{name},
478 note => '',
479 outcome => 'Missing',
480 };
481  
482 $log_id = $self -> db -> insert
483 (
484 $log_table_name,
485 $fields,
486 {returning => 'id'}
487 ) -> hash -> {id};
488 }
489 }
490  
491 return [@result];
492  
493 } # End of crosscheck.
494  
495 # --------------------------------------------------
496  
497 sub find_unique_items
498 {
499 my($self, $sql) = @_;
500  
501 my(@list) = map{$$_[0]} $self -> db -> query($sql) -> arrays -> each;
502  
503 my(@result);
504 my(%seen);
505  
506 for my $item (@list)
507 {
508 push @result, $item if (! $seen{$item});
509  
510 $seen{$item} = 1;
511 }
512  
513 return [sort @result];
514  
515 } # End of find_unique_items.
516  
517 # --------------------------------------------------
518  
519 sub format_height_width
520 {
521 my($self, $height, $width) = @_;
522  
523 my($result);
524  
525 if ($height)
526 {
527 if ($width)
528 {
529 $result = "$height x $width";
530 }
531 else
532 {
533 $result = "Height: $height";
534 }
535 }
536 else
537 {
538 if ($width)
539 {
540 $result = "Width: $width";
541 }
542 else
543 {
544 $result = '';
545 }
546 }
547  
548 return $result;
549  
550 } # End of format_height_width.
551  
552 # -----------------------------------------------
553 # The cooked message is now not used, since I adopted humane-js.
554  
555 sub format_raw_message
556 {
557 my($self, $result) = @_;
558 my($class) = ($$result{outcome} eq 'Success') ? 'success' : 'error';
559 $$result{cooked} = "<h2 class = 'centered'><span class = '$class'>$$result{outcome}</span>: $$result{raw}</h2>";
560  
561 return $result;
562  
563 } # End of format_raw_message.
564  
565 # -----------------------------------------------
566  
567 sub generate_tile
568 {
569 my($self, $constants, $feature) = @_;
570 my($color) = Imager::Color -> new($$feature{hex_color});
571 my($fill) = Imager::Fill -> new(fg => $color, hatch => $$constants{tile_hatch_pattern});
572 my($id) = $$feature{id};
573 my($image) = Imager -> new(xsize => $$constants{cell_width}, ysize => $$constants{cell_height});
574 my($name) = $$feature{name};
575 my($file_name) = $self -> clean_up_feature_name($name);
576  
577 $image -> box(fill => $fill);
578 $self -> shrink_string($$constants{cell_width}, $$constants{cell_height}, $image, $name);
579  
580 my($feature_name) = File::Spec -> catfile($$feature{feature_dir}, "$file_name.png");
581 my($result) =
582 {
583 name => $name,
584 file_name => $feature_name,
585 file_url => $$feature{feature_url},
586 message => "Feature's icon file created",
587 outcome => 'Success'
588 };
589  
590 try
591 {
592 $image -> write(file => $feature_name);
593 }
594 catch
595 {
596 $$result{message} = "Unable to write file: $feature_name";
597 $$result{outcome} = 'Error';
598 };
599  
600 if ($$result{outcome} eq 'Success')
601 {
602 # If the constant 'doc_root' is present and points to a directory,
603 # we copy the new file into it so the web server can see it.
604  
605 my($doc_root) = $$constants{doc_root};
606  
607 if ($doc_root && -d $doc_root)
608 {
609 my($feature_dest) = File::Spec -> catfile($$constants{doc_root}, $$constants{feature_dir}, "$file_name.png");
610  
611 if (copy($feature_name, $feature_dest) == 0)
612 {
613 $$result{message} = "Unable to write file: $feature_dest";
614 $$result{outcome} = 'Error';
615 }
616 else
617 {
618 $self -> logger -> debug("Copy $feature_name to $feature_dest");
619 }
620 }
621 else
622 {
623 $$result{message} = "The 'constants' does not contain doc_root or it's not a directory";
624 $$result{outcome} = 'Error';
625 }
626 }
627  
628 return $result;
629  
630 } # End of generate_tile.
631  
632 # --------------------------------------------------
633  
634 sub get_flower_by_id
635 {
636 my($self, $flower_id) = @_;
637 my($attribute_types_table) = $self -> read_table('attribute_types');
638 my($sql) = "select * from flowers where id = $flower_id";
639 my($query) = $self -> db -> query($sql);
640 my($flower) = $query -> hash; # Only 1 record can match, so no need to call finish().
641  
642 my(%attribute_type);
643  
644 for (@$attribute_types_table)
645 {
646 $attribute_type{$$_{id} } = $_;
647 }
648  
649 for my $table_name (qw/attributes flower_locations images notes urls/)
650 {
651 # Return an arrayref of hashrefs.
652  
653 $$flower{$table_name} = $self -> read_flower_dependencies($table_name, $$flower{id});
654 }
655  
656 my($attribute);
657 my($id);
658  
659 # Annotate the attributes with their types.
660  
661 for my $i (0 .. $#{$$flower{attributes} })
662 {
663 $attribute = $$flower{attributes}[$i];
664 $id = $$attribute{attribute_type_id};
665  
666 for my $name (qw/name sequence/)
667 {
668 $$flower{attributes}[$i]{$name} = $attribute_type{$id}{$name};
669 }
670 }
671  
672 # Return a hashref.
673  
674 return $flower;
675  
676 } # End of get_flower_by_id.
677  
678 # -----------------------------------------------
679  
680 sub init_title_font
681 {
682 my($self, $config) = @_;
683  
684 $self -> constants($self -> read_constants_table); # Uses db()!
685  
686 my($constants) = $self -> constants; # Might be empty at the start of an import.
687 my($font_file) = $$constants{tile_font_file} || $$config{tile_font_file};
688 my($font_size) = $$constants{tile_font_size} || $$config{tile_font_size};
689  
690 $self -> title_font
691 (
692 Imager::Font -> new
693 (
694 color => Imager::Color -> new(0, 0, 0), # Black.
695 file => $font_file,
696 size => $font_size,
697 ) || die "Error. Can't define title font: " . Imager -> errstr
698 );
699  
700 } # End of init_title_font.
701  
702 # -----------------------------------------------
703  
704 sub parse_attribute_checkboxes
705 {
706 my($self, $defaults, $search_attributes) = @_;
707  
708 #$self -> logger -> debug('Database.parse_attribute_checkboxes()');
709  
710 my($attribute_type_names) = $$defaults{attribute_type_names};
711 my($attribute_type_fields) = $$defaults{attribute_type_fields};
712  
713 my($attribute_name, $attribute_value);
714 my(%checkboxes);
715 my($name);
716  
717 # Ensure every checkbox has a value of 'true' and a name like:
718 # 'A known attribute type' . '_' . 'A value',
719 # where the value is one of the known values for the given type.
720  
721 for my $key (keys %$search_attributes)
722 {
723 # Strip off the leading 'search_'.
724  
725 next if (substr($key, 0, 7) ne 'search_');
726  
727 $name = substr($key, 7);
728  
729 next if ($$search_attributes{$key} ne 'true');
730  
731 for my $type_name (@$attribute_type_names)
732 {
733 if ($name =~ /^($type_name)_(.+)$/)
734 {
735 # Warning: Because of the s/// you cannot combine these into 1 line
736 # such as $result{$1} = $2 =~ s/_/ /gr. I know - I tried.
737  
738 $attribute_name = $1;
739 $attribute_value = $2;
740 $attribute_value =~ s/_/ /g;
741 $attribute_value = 'Semi-dwarf' if ($attribute_value eq 'Semi dwarf');
742  
743 for my $type_value (@{$$attribute_type_fields{$type_name} })
744 {
745 $checkboxes{$attribute_name} = [] if (! $checkboxes{$attribute_name});
746  
747 push @{$checkboxes{$attribute_name} }, $attribute_value if ($attribute_value eq $type_value);
748 }
749 }
750 }
751 }
752  
753 return \%checkboxes;
754  
755 } # End of parse_attribute_checkboxes.
756  
757 # -----------------------------------------------
758  
759 sub parse_search_attributes
760 {
761 my($self, $defaults, $search_attributes) = @_;
762  
763 #$self -> logger -> debug('Database.parse_search_attributes()');
764  
765 my($checkboxes) = $self -> parse_attribute_checkboxes($defaults, $search_attributes);
766 my(@type_names) = keys %$checkboxes;
767 my($type_name_count) = scalar @type_names;
768  
769 if ($type_name_count == 0)
770 {
771 return (false, {});
772 }
773  
774 my($attributes_table) = $$defaults{attributes_table};
775 my($attribute_types_table) = $$defaults{attribute_types_table};
776  
777 my($all_match);
778 my(%candidate_flower_ids);
779  
780 # Did the user provide attributes?
781  
782 for my $type_name (@type_names)
783 {
784 my($attribute_type_id) = 0;
785  
786 for my $attribute_type (@$attribute_types_table)
787 {
788 if ($$attribute_type{name} eq $type_name)
789 {
790 $attribute_type_id = $$attribute_type{id};
791 }
792 }
793  
794 if ($attribute_type_id)
795 {
796 for my $attribute (@$attributes_table)
797 {
798 next if ($$attribute{attribute_type_id} != $attribute_type_id);
799  
800 $all_match = true;
801 my($count) = 0;
802  
803 for my $candidate (@{$$checkboxes{$type_name} })
804 {
805 if ($$attribute{range} !~ /$candidate/)
806 {
807 $all_match = false;
808  
809 last;
810 }
811  
812 $count++;
813 }
814  
815 # $self -> logger -> debug("attribute type: $type_name. range: $$attribute{range}. "
816 # . "Matches: $count. Checkboxes: " . join(', ', @{$$checkboxes{$type_name} }) )
817 # if ($count > 0);
818  
819 if ($all_match -> isTrue)
820 {
821 $candidate_flower_ids{$$attribute{flower_id} } = 1;
822 }
823 }
824 }
825 }
826  
827 return (true, \%candidate_flower_ids);
828  
829 } # End of parse_search_attributes.
830  
831 # -----------------------------------------------
832  
833 sub parse_search_text
834 {
835 my($self, $search_text) = @_;
836  
837 #$self -> logger -> debug("Database.parse_search_text($search_text)");
838  
839 my($request) =
840 {
841 error_message => '',
842 height_provided => false,
843 lc_search_text => 'See below',
844 original_text => $search_text, # Save in original case for display to the user.
845 search_text => 'See below',
846 size_provided => false,
847 text_is_clean => true,
848 text_provided => true,
849 width_provided => false,
850 };
851  
852 # Test input and return structured result.
853  
854 if ($search_text eq '')
855 {
856 $$request{text_provided} = false;
857 }
858 elsif ($search_text =~ /^(h|height|w|width)\s*([<=>])\s*([0-9]{0,3}(?:[.][0-9]{0,2})?)\s*(cm|m)?$/i)
859 {
860 my($direction) = $1;
861  
862 $$request{direction} = ($direction eq 'height') ? 'h' : ($direction eq 'width') ? 'w' : $direction;
863 $$request{height_provided} = true if ($$request{direction} eq 'h');
864 $$request{operator} = $2;
865 $$request{size} = $3 || 1;
866 $$request{size_provided} = true;
867 $$request{unit} = $4 || 'm';
868 $$request{width_provided} = true if ($$request{direction} eq 'w');
869  
870 if ($$request{unit} eq 'm')
871 {
872 $$request{size} *= 100;
873 $$request{unit} = 'cm';
874 }
875 }
876 elsif (length($search_text) > 100) # Arbitrary limit.
877 {
878 $$request{error_message} = 'Search text suspiciously long. Check Search FAQ for help with sizes';
879 $$request{text_is_clean} = false;
880 }
881  
882 $$request{search_text} = $search_text;
883 $$request{lc_search_text} = lc $search_text;
884  
885 return $request;
886  
887 } # End of parse_search_text.
888  
889 # --------------------------------------------------
890  
891 sub process_feature
892 {
893 my($self, $item) = @_;
894  
895 #$self -> logger -> debug('Database.process_feature(...)');
896  
897 my($action) = $$item{action};
898 my($id) = $$item{id};
899 my($log_table_name) = 'log';
900 my($name) = $$item{name};
901 my($table_name) = 'features';
902 my($features_table) = $self -> read_table($table_name);
903 my($result) = {feature_id => 0, outcome => 'Success'};
904 my($fields) =
905 {
906 hex_color => $$item{color_chosen},
907 name => $name,
908 publish => $$item{publish},
909 };
910  
911 # color_chosen: color_chosen,
912 # color_code: $('#color_code').val(),
913 # color_name: $('#color_name').val(),
914 # id: features_current_feature_id,
915 # name: feature_name,
916 # publish: $('#feature_publish').prop('checked') ? 'Yes' : 'No'
917  
918 my(%feature);
919 my($log_id);
920  
921 if ($action eq 'add')
922 {
923 # It's a feature insert. Is the feature name on file?
924 # Feature.pm checked that the user entered something!
925  
926 for (@$features_table)
927 {
928 $feature{uc $$_{name} } = $$_{id};
929 }
930  
931 if (exists($feature{uc $name}) )
932 {
933 $result = {%$result, outcome => 'Error', raw => "That feature name is on file"};
934 }
935 else
936 {
937 $id = $self -> db -> insert
938 (
939 $table_name,
940 $fields,
941 {returning => 'id'}
942 ) -> hash -> {id};
943  
944 $self -> logger -> info("Table: $table_name. Record id: $id. Feature: $name. Action: $action");
945  
946 $result = {%$result, feature_id => $id, raw => "Added feature: $name"};
947 }
948 }
949 elsif ($action eq 'delete')
950 {
951 # Is the feature id on file? Feature.pm checked that the user entered something!
952  
953 for (@$features_table)
954 {
955 $feature{$$_{id} } = $$_{name};
956 }
957  
958 if (exists($feature{$id}) )
959 {
960 # It's a feature delete. But is this feature used in any gardens?
961  
962 my($found) = false;
963 my($feature_table) = $self -> read_table('feature_locations');
964  
965 for my $feature (@$feature_table)
966 {
967 if ($$feature{feature_id} == $$item{id})
968 {
969 $found = true;
970 }
971 }
972  
973 if ($found -> isTrue)
974 {
975 my($note) = "Feature not deleted because it is used in some gardens";
976  
977 $self -> logger -> info("Table: $table_name. Record id: $id. Feature: $name. $note");
978  
979 $result = {%$result, outcome => 'Error', raw => $note};
980 }
981 else
982 {
983 $self -> db -> delete
984 (
985 $table_name,
986 {id => $$item{id} }
987 );
988  
989 $self -> logger -> info("Table: $table_name. Record id: $id. Feature: $name. Action: $action");
990  
991 # After a delete we default the id to the feature whose name is sorted 1st alphabetically.
992  
993 my($min_id) = 999_999_999;
994  
995 for (@$features_table)
996 {
997 $min_id = $$_{id} if ($$_{id} < $min_id); # TODO: Ensure loop ends. Use List::Utils.
998 }
999  
1000 $result = {%$result, id => $min_id, raw => "Action $action"};
1001 }
1002 }
1003 else
1004 {
1005 $result = {%$result, outcome => 'Error', raw => "Cannot update the database. That feature was not found"};
1006 }
1007 }
1008 elsif ($action eq 'update')
1009 {
1010 # Is the feature id on file? Feature.pm checked that the user entered something!
1011  
1012 for (@$features_table)
1013 {
1014 $feature{$$_{id} } = $$_{name};
1015 }
1016  
1017 if (exists($feature{$id}) )
1018 {
1019 # It's a feature update.
1020  
1021 $self -> db -> update
1022 (
1023 $table_name,
1024 $fields,
1025 {id => $$item{id} }
1026 );
1027  
1028 $self -> logger -> info("Table: $table_name. Record id '$id'. Feature: $name. Action: $action");
1029  
1030 $result = {%$result, feature_id => $$item{id}, raw => "Action: $action"};
1031 }
1032 else
1033 {
1034 $result = {%$result, outcome => 'Error', raw => "Cannot update the database. That feature was not found"};
1035 }
1036 }
1037 else
1038 {
1039 $result = {%$result, outcome => 'Error', raw => "Unrecognized action: $action. Must be one of 'add', 'update' or 'delete'"};
1040 }
1041  
1042 $fields =
1043 {
1044 action => $action,
1045 context => 'Feature',
1046 file_name => '',
1047 key => $id,
1048 name => $name,
1049 note => $$result{raw},
1050 outcome => $$result{outcome},
1051 };
1052  
1053 $log_id = $self -> db -> insert
1054 (
1055 $log_table_name,
1056 $fields,
1057 {returning => 'id'}
1058 ) -> hash -> {id};
1059  
1060 $features_table = $self -> read_features_table;
1061 my($tile_status) = ['N/A', 'N/A', 'N/A', 'Success'];
1062  
1063 if ( ($$result{outcome} eq 'Success') && ( ($action eq 'add') || ($action eq 'update') ) )
1064 {
1065 # Find the index of the new/updated feature.
1066  
1067 my($index) = -1;
1068  
1069 for my $feature (sort{$$a{name} cmp $$b{name} } @$features_table)
1070 {
1071 $index++;
1072  
1073 last if ($$feature{name} eq $name);
1074 }
1075  
1076 # generate_tile() returns:
1077 # o name => $name,
1078 # o file_name => $feature_name,
1079 # o file_url => $$feature{feature_url},
1080 # o message => "Feature's icon file created",
1081 # o outcome => 'Success'
1082  
1083 my($constants) = $self -> constants;
1084 $tile_status = $self -> generate_tile($constants, @$features_table[$index]);
1085  
1086 if ($$tile_status{outcome} eq 'Error')
1087 {
1088 $$result{raw} = $$tile_status{message};
1089 $$result{outcome} = 'Error';
1090 }
1091  
1092 $fields =
1093 {
1094 action => $action,
1095 context => 'Feature',
1096 file_name => $$tile_status{file_name},
1097 key => 0,
1098 name => $$tile_status{name},
1099 note => $$tile_status{message},
1100 outcome => $$tile_status{outcome},
1101 };
1102  
1103 $log_id = $self -> db -> insert
1104 (
1105 $log_table_name,
1106 $fields,
1107 {returning => 'id'}
1108 ) -> hash -> {id};
1109 }
1110  
1111 $self -> logger -> info("Outcome: $$result{outcome}. $$result{raw}");
1112  
1113 $id = defined($$result{feature_id}) ? $$result{feature_id} : 0;
1114  
1115 return
1116 {
1117 message => $self -> format_raw_message($result),
1118 feature_menu => $self -> build_feature_menu($features_table, $id),
1119 features_table => $features_table,
1120 tile_status => $tile_status,
1121 };
1122  
1123 } # End of process_feature.
1124  
1125 # --------------------------------------------------
1126  
1127 sub process_garden
1128 {
1129 my($self, $controller, $item) = @_;
1130  
1131 #$self -> logger -> debug('Database.process_garden(...)');
1132  
1133 my($action) = $$item{action};
1134 my($garden_name) = $$item{name};
1135 my($id) = $$item{id};
1136 my($property_name) = $$item{property_name};
1137 my($result) = {garden_id => 0, outcome => 'Success'};
1138 my($table_name) = 'gardens';
1139 my($gardens_table) = $self -> read_table($table_name);
1140 my($fields) =
1141 {
1142 description => $$item{description},
1143 name => $garden_name,
1144 property_id => $$item{property_id},
1145 publish => $$item{publish},
1146 };
1147  
1148 my(%garden);
1149  
1150 if ($action eq 'add')
1151 {
1152 # It's a garden insert. Is the garden name on file?
1153 # Garden.pm checked that the user entered something!
1154  
1155 for (@$gardens_table)
1156 {
1157 $garden{uc $$_{name} } = $$_{id} if ($$_{property_id} == $$item{property_id});
1158 }
1159  
1160 if (exists($garden{uc $garden_name}) )
1161 {
1162 $result = {%$result, outcome => 'Error', raw => 'That garden name is on file'};
1163 }
1164 else
1165 {
1166 $id = $self -> db -> insert
1167 (
1168 $table_name,
1169 $fields,
1170 {returning => 'id'}
1171 ) -> hash -> {id};
1172  
1173 $self -> logger -> info("Table: $table_name. Record id: $id. Action: $action. Property: $property_name. Garden: $garden_name");
1174  
1175 $result = {%$result, garden_id => $id, raw => "Added garden: $garden_name"};
1176 }
1177 }
1178 elsif ($action eq 'delete')
1179 {
1180 # Is the garden id on file? Garden.pm checked that the user entered something!
1181  
1182 for (@$gardens_table)
1183 {
1184 $garden{$$_{id} } = $$_{name};
1185 }
1186  
1187 if (exists($garden{$id}) )
1188 {
1189 $self -> db -> delete
1190 (
1191 $table_name,
1192 {id => $$item{id} }
1193 );
1194  
1195 my($message) = "Action: $action";
1196  
1197 $self -> logger -> info("Table '$table_name'. Record id '$id'. $message");
1198  
1199 $result = {%$result, raw => $message};
1200 }
1201 else
1202 {
1203 $result = {%$result, outcome => 'Error', raw => "Cannot update the database. That garden was not found"};
1204 }
1205 }
1206 elsif ($action eq 'update')
1207 {
1208 # Is the garden id on file? Garden.pm checked that the user entered something!
1209  
1210 for (@$gardens_table)
1211 {
1212 $garden{$$_{id} } = $$_{name};
1213 }
1214  
1215 if (exists($garden{$id}) )
1216 {
1217 # It's a garden update.
1218  
1219 $self -> db -> update
1220 (
1221 $table_name,
1222 $fields,
1223 {id => $$item{id} }
1224 );
1225  
1226 $self -> logger -> info("Table: $table_name. Record id: $id. Property: $property_name. Garden: $garden_name. Action: $action");
1227  
1228 $result = {%$result, garden_id => $$item{id}, raw => "Action: $action"};
1229 }
1230 else
1231 {
1232 $result = {%$result, outcome => 'Error', raw => 'Cannot update the database. That garden was not found'};
1233 }
1234 }
1235 else
1236 {
1237 $result = {%$result, outcome => 'Error', raw => "Unrecognized action: $action. Must be one of 'add', 'update' or 'delete'"};
1238 }
1239  
1240 $self -> logger -> info("Outcome: $$result{outcome}. $$result{raw}");
1241  
1242 $gardens_table = $self -> read_gardens_table;
1243  
1244 return
1245 {
1246 gardens_table => $gardens_table,
1247 message => $self -> format_raw_message($result),
1248 property_menu => $self -> build_gardens_property_menu($controller, $gardens_table, 'gardens_property_menu_1', $$item{property_id}),
1249 };
1250  
1251 } # End of process_garden.
1252  
1253 # --------------------------------------------------
1254  
1255 sub process_property
1256 {
1257 my($self, $item) = @_;
1258  
1259 #$self -> logger -> debug('Database.process_property(...)');
1260  
1261 my($action) = $$item{action};
1262 my($id) = $$item{id};
1263 my($property_name) = $$item{name};
1264 my($table_name) = 'properties';
1265 my($properties_table) = $self -> read_table($table_name);
1266 my($result) = {property_id => 0, outcome => 'Success'};
1267 my($fields) =
1268 {
1269 description => $$item{description},
1270 name => $property_name,
1271 publish => $$item{publish},
1272 };
1273  
1274 my(%property);
1275  
1276 if ($action eq 'add')
1277 {
1278 # It's a property insert. Is the property name on file?
1279 # Property.pm checked that the user entered something!
1280  
1281 for (@$properties_table)
1282 {
1283 $property{uc $$_{name} } = $$_{id};
1284 }
1285  
1286 if (exists($property{uc $property_name}) )
1287 {
1288 $result = {%$result, outcome => 'Error', raw => ' That property name is on file'};
1289 }
1290 else
1291 {
1292 $id = $self -> db -> insert
1293 (
1294 $table_name,
1295 $fields,
1296 {returning => 'id'}
1297 ) -> hash -> {id};
1298  
1299 $self -> logger -> info("Table: $table_name. Record id: $id. Property: $property_name. Action: $action");
1300  
1301 $result = {%$result, property_id => $id, raw => "Added property: $property_name"};
1302 }
1303 }
1304 elsif ($action eq 'delete')
1305 {
1306 # Is the property id on file? Property.pm checked that the user entered something!
1307  
1308 for (@$properties_table)
1309 {
1310 $property{$$_{id} } = $$_{name};
1311 }
1312  
1313 if (exists($property{$id}) )
1314 {
1315 # It's a property delete. But does this property have any gardens?
1316  
1317 my($found) = false;
1318 my($garden_table) = $self -> read_table('gardens');
1319  
1320 for my $garden (@$garden_table)
1321 {
1322 if ($$garden{property_id} == $$item{id})
1323 {
1324 $found = true;
1325 }
1326 }
1327  
1328 if ($found -> isTrue)
1329 {
1330 my($note) = "Property not deleted because it has gardens";
1331  
1332 $self -> logger -> info("Table: $table_name. Record id: $id. Property: $property_name. $note");
1333  
1334 $result = {%$result, outcome => 'Error', raw => $note};
1335 }
1336 else
1337 {
1338 $self -> db -> delete
1339 (
1340 $table_name,
1341 {id => $$item{id} }
1342 );
1343  
1344 $self -> logger -> info("Table: $table_name. Record id: $id. Property: $property_name. Action: $action");
1345  
1346 $result = {%$result, raw => "Action $action"};
1347 }
1348 }
1349 else
1350 {
1351 $result = {outcome => 'Error', raw => "Cannot update the database. That property was not found"};
1352 }
1353 }
1354 elsif ($action eq 'update')
1355 {
1356 # Is the property id on file? Property.pm checked that the user entered something!
1357  
1358 for (@$properties_table)
1359 {
1360 $property{$$_{id} } = $$_{name};
1361 }
1362  
1363 if (exists($property{$id}) )
1364 {
1365 # It's a property update.
1366  
1367 $self -> db -> update
1368 (
1369 $table_name,
1370 $fields,
1371 {id => $$item{id} }
1372 );
1373  
1374 $self -> logger -> info("Table: $table_name. Record id '$id'. Property: $property_name. Action: $action");
1375  
1376 $result = {%$result, property_id => $$item{id}, raw => "Action: $action"};
1377 }
1378 else
1379 {
1380 $result = {%$result, outcome => 'Error', raw => "Cannot update the database. That property was not found"};
1381 }
1382 }
1383 else
1384 {
1385 $result = {%$result, outcome => 'Error', raw => "Unrecognized action: $action. Must be one of 'add', 'update' or 'delete'"};
1386 }
1387  
1388 $self -> logger -> info("Outcome: $$result{outcome}. $$result{raw}");
1389  
1390 $id = defined($$result{property_id}) ? $$result{property_id} : 0;
1391  
1392 return
1393 {
1394 properties_table => $self -> read_properties_table,
1395 message => $self -> format_raw_message($result),
1396 property_menu => $self -> build_properties_property_menu($self -> read_table('properties'), 'properties_property_menu', $id),
1397 };
1398  
1399 } # End of process_property.
1400  
1401 # -----------------------------------------------
1402  
1403 sub read_constants_table
1404 {
1405 my($self) = @_;
1406 my($constants) = {};
1407  
1408 # Reorder so we can return a hashref and not an arrayref.
1409  
1410 $$constants{$$_{name} } = $$_{value} for (@{$self -> read_table('constants')});
1411  
1412 return $constants;
1413  
1414 } # End of read_constants_table.
1415  
1416 # --------------------------------------------------
1417  
1418 sub read_features_table
1419 {
1420 my($self) = @_;
1421 my($constants) = $self -> constants;
1422  
1423 my($record, @records);
1424  
1425 for my $feature (@{$self -> read_table('features')})
1426 {
1427 $record = {};
1428  
1429 for my $key (keys %$feature)
1430 {
1431 $$record{$key} = $$feature{$key};
1432 }
1433  
1434 $$record{feature_dir} = File::Spec -> catfile($$constants{homepage_dir}, $$constants{feature_dir});
1435 $$record{feature_file} = $self -> clean_up_feature_name($$feature{name});
1436 $$record{feature_url} = "$$constants{homepage_url}$$constants{feature_url}/$$record{feature_file}.png";
1437  
1438 for my $table_name (qw/feature_locations/)
1439 {
1440 $$record{$table_name} = $self -> read_feature_dependencies($table_name, $$record{id});
1441 }
1442  
1443 push @records, $record;
1444 }
1445  
1446 # Return an arrayref of hashrefs.
1447  
1448 return [sort{$$a{name} cmp $$b{name} } @records];
1449  
1450 } # End of read_features_table.
1451  
1452 # --------------------------------------------------
1453  
1454 sub read_flowers_table
1455 {
1456 my($self) = @_;
1457 my($constants) = $self -> constants;
1458 my($attribute_types_table) = $self -> read_table('attribute_types');
1459 my($flower_table) = $self -> read_table('flowers'); # Avoid 'Deep Recursion'! Don't call read_flowers_table()!
1460  
1461 my(%attribute_type);
1462  
1463 for (@$attribute_types_table)
1464 {
1465 $attribute_type{$$_{id} } = $_;
1466 }
1467  
1468 my($attribute);
1469 my($id);
1470 my($pig_latin);
1471 my($record, @records);
1472 my($thumbnail);
1473  
1474 for my $flower (@$flower_table)
1475 {
1476 $record = {};
1477  
1478 for my $key (keys %$flower)
1479 {
1480 $$record{$key} = $$flower{$key};
1481 }
1482  
1483 $pig_latin = $$flower{pig_latin};
1484 $$record{hxw} = $self -> format_height_width($$flower{height}, $$flower{width});
1485 $$record{thumbnail_url} = "$$constants{homepage_url}$$constants{image_url}/$pig_latin.0.jpg";
1486 $$record{web_page_url} = "$$constants{homepage_url}$$constants{flower_url}/$pig_latin.html";
1487  
1488 # Warning: Obviously this loop only works if $table_name never matches $key in the above loop.
1489  
1490 for my $table_name (qw/attributes flower_locations images notes urls/)
1491 {
1492 # Return an arrayref of hashrefs.
1493  
1494 $$record{$table_name} = $self -> read_flower_dependencies($table_name, $$record{id});
1495 }
1496  
1497 # Annotate the attributes with their types.
1498  
1499 for my $i (0 .. $#{$$record{attributes} })
1500 {
1501 $attribute = $$record{attributes}[$i];
1502 $id = $$attribute{attribute_type_id};
1503  
1504 for my $name (qw/name sequence/)
1505 {
1506 $$record{attributes}[$i]{$name} = $attribute_type{$id}{$name};
1507 }
1508 }
1509  
1510 # Fix the urls.
1511  
1512 for my $i (0 .. $#{$$record{images} })
1513 {
1514 $$record{images}[$i]{raw_name} = $$record{images}[$i]{file_name};
1515 $$record{images}[$i]{file_name} = "$$constants{homepage_url}$$constants{image_url}/$$record{images}[$i]{file_name}";
1516 }
1517  
1518 push @records, $record;
1519 }
1520  
1521 # Sort the flowers according to their scientific name.
1522 # Warning: This sort is overridden by JS in Datatables. See Base.pm.
1523  
1524 my($index) = 0;
1525  
1526 my($key, @keys);
1527 my(%records);
1528  
1529 for my $record (@records)
1530 {
1531 $index++;
1532  
1533 $key = "$$record{scientific_name}:$index";
1534 $records{$key} = $record;
1535  
1536 push @keys, $key;
1537 }
1538  
1539 @keys = Unicode::Collate -> new -> sort(@keys);
1540 @records = ();
1541  
1542 for $key (@keys)
1543 {
1544 push @records, $records{$key};
1545 }
1546  
1547 # Return an arrayref of hashrefs.
1548  
1549 return [@records];
1550  
1551 } # End of read_flowers_table.
1552  
1553 # --------------------------------------------------
1554  
1555 sub read_gardens_table
1556 {
1557 my($self) = @_;
1558 my($constants) = $self -> constants;
1559 my($garden_table) = $self -> read_table('gardens'); # Avoid 'Deep Recursion'! Don't call read_gardens_table()!
1560 my($properties_table) = $self -> read_table('properties');
1561  
1562 my($id);
1563 my($property_id);
1564 my($record, @records);
1565  
1566 my(%property);
1567  
1568 for (@$properties_table)
1569 {
1570 $property{$$_{id} } = $_;
1571 }
1572  
1573 for my $garden (@$garden_table)
1574 {
1575 $record = {};
1576  
1577 for my $key (keys %$garden)
1578 {
1579 $$record{$key} = $$garden{$key};
1580 }
1581  
1582  
1583 for my $table_name (qw/flower_locations feature_locations/)
1584 {
1585 $$record{$table_name} = $self -> read_garden_dependencies($table_name, $$record{id});
1586 }
1587  
1588 # Annotate the records with their properties.
1589  
1590 $$record{property_description} = $property{$$record{property_id} }{description};
1591 $$record{property_name} = $property{$$record{property_id} }{name};
1592 $$record{property_publish} = $property{$$record{property_id} }{publish};
1593  
1594 push @records, $record;
1595 }
1596  
1597 # Return an arrayref of hashrefs.
1598  
1599 return [sort{$$a{property_name} cmp $$b{property_name} || $$a{name} cmp $$b{name} } @records];
1600  
1601 } # End of read_gardens_table.
1602  
1603 # --------------------------------------------------
1604  
1605 sub read_properties_table
1606 {
1607 my($self) = @_;
1608 my($constants) = $self -> constants;
1609  
1610 # Return an arrayref of hashrefs.
1611  
1612 return [sort{$$a{name} cmp $$b{name} } @{$self -> read_table('properties')}];
1613  
1614 } # End of read_properties_table.
1615  
1616 # --------------------------------------------------
1617  
1618 sub scientific_name2pig_latin
1619 {
1620 my($self, $flowers, $scientific_name, $common_name) = @_;
1621 my(@chars) = split(//, $scientific_name);
1622 my($pig_latin) = '';
1623  
1624 for (@chars)
1625 {
1626 $pig_latin .= $1 if (m|([-_. a-zA-Z0-9])|)
1627 }
1628  
1629 $pig_latin =~ s!^\s!!;
1630 $pig_latin =~ s!\s$!!;
1631 $pig_latin =~ s!\s!\.!g;
1632  
1633 my(%seen);
1634  
1635 for my $flower (@$flowers)
1636 {
1637 $seen{$$flower{scientific_name} } = 0 if (! $seen{$$flower{scientific_name} });
1638  
1639 $seen{$$flower{scientific_name} }++;
1640 }
1641  
1642 if ($seen{$scientific_name} > 1)
1643 {
1644 $pig_latin .= ".$1" if ($common_name =~ /^.+\s(\d+)$/);
1645 }
1646  
1647 $pig_latin =~ s!\.\.!\.!g;
1648  
1649 return ucfirst lc $pig_latin;
1650  
1651 } # End of scientific_name2pig_latin.
1652  
1653 # --------------------------------------------------
1654  
1655 sub search
1656 {
1657 my($self, $defaults, $constants_table, $search_attributes, $search_text) = @_;
1658  
1659 $self -> logger -> debug('Database.search()');
1660  
1661 my($request) = $self -> parse_search_text($self -> trim($search_text) );
1662  
1663 if ($$request{text_is_clean} -> isFalse)
1664 {
1665 $$request{time_taken} = 0;
1666  
1667 return ([], $request);
1668 }
1669  
1670 my($attribute_provided, $wanted_flower_ids) = $self -> parse_search_attributes($defaults, $search_attributes);
1671 my($flowers) = $self -> read_flowers_table;
1672 my($result_set) = [];
1673  
1674 my($attribute_match);
1675 my($flower_id);
1676 my($item);
1677 my($match);
1678 my($pig_latin);
1679 my($text_match);
1680  
1681 my($start_time) = [gettimeofday];
1682  
1683 for my $flower (@$flowers)
1684 {
1685 $flower_id = $$flower{id};
1686 $attribute_match = $$wanted_flower_ids{$flower_id} || 0;
1687 $text_match = $$request{size_provided}
1688 ? $$flower{height} && $$request{height_provided} -> isTrue
1689 ? $self -> test_size($defaults, $flower, $request)
1690 : $$flower{width} && $$request{width_provided} -> isTrue
1691 ? $self -> test_size($defaults, $flower, $request)
1692 : false # Impossible, presumably.
1693 : $self -> test_text($flower, $request);
1694  
1695 if ($attribute_provided)
1696 {
1697 $match = $$request{text_provided} ? $attribute_match && $text_match : $attribute_match;
1698 }
1699 else
1700 {
1701 $match = $$request{text_provided} ? $text_match : 0;
1702 }
1703  
1704 if ($match)
1705 {
1706 $pig_latin = $$flower{pig_latin};
1707 $item =
1708 {
1709 aliases => $$flower{aliases},
1710 attributes => $$flower{attributes},
1711 common_name => $$flower{common_name},
1712 height => $$flower{height},
1713 hxw => $self -> format_height_width($$flower{height}, $$flower{width}),
1714 id => $flower_id,
1715 pig_latin => $pig_latin,
1716 publish => $$flower{publish},
1717 scientific_name => $$flower{scientific_name},
1718 thumbnail_url => "$$constants_table{homepage_url}$$constants_table{image_url}/$pig_latin.0.jpg",
1719 width => $$flower{width},
1720 };
1721  
1722 push @$result_set, $item;
1723 }
1724 }
1725  
1726 $$request{time_taken} = tv_interval($start_time);
1727  
1728 $self -> logger -> info("Match count: @{[$#$result_set + 1]}");
1729  
1730 return ([sort{$$a{common_name} cmp $$b{common_name} } @$result_set], $request);
1731  
1732 } # End of search.
1733  
1734 # -----------------------------------------------
1735  
1736 sub shrink_string
1737 {
1738 my($self, $cell_width, $cell_height, $image, $string) = @_;
1739 my(@words) = split(/\s+/, $string);
1740 $#words = 2 if ($#words > 2); # Limit arbitrarily to 3 words.
1741 my($vertical_step) = int($cell_height / (scalar @words + 1) );
1742 my($y) = 0;
1743 my(%vowel) = (a => 1, e => 1, i => 1, o => 1, u => 1);
1744  
1745 my($candidate);
1746 my($finished);
1747 my($index);
1748 my(@letters);
1749 my($word);
1750  
1751 for my $step (0 .. $#words)
1752 {
1753 $y += $vertical_step; # Vertical position of word on tile.
1754  
1755 # Algorithm: Shrink the word letter-by-letter, from the right-hand end.
1756 # Don't try to shrink short words.
1757 # In particular, don't zap the letter 'a' in the word 'a'.
1758 # Index is the offset of the last letter in the word.
1759 # Step 1: Zap vowels.
1760  
1761 $word = $words[$step];
1762 @letters = split(//, $word);
1763 $index = $#letters;
1764 $finished = ($index <= 7) ? true : false;
1765  
1766 while ($finished -> isFalse)
1767 {
1768 if ($vowel{$letters[$index]})
1769 {
1770 # There are vowels left in the word, so zap them.
1771  
1772 splice(@letters, $index, 1);
1773 }
1774  
1775 $index--;
1776  
1777 $finished = true if ( ($index < 0) || ($#letters <= 7) );
1778 }
1779  
1780 # Step 2: Zap letters.
1781  
1782 $word = join('', @letters);
1783 $finished = (length($word) <= 7) ? true : false;
1784  
1785 while ($finished -> isFalse)
1786 {
1787 # The word is too long, so zap letters.
1788  
1789 substr($word, length($word) - 1) = '';
1790  
1791 $index--;
1792  
1793 $finished = true if (length($word) <= 7);
1794 }
1795  
1796 $image -> align_string
1797 (
1798 aa => 1,
1799 font => $self -> title_font,
1800 halign => 'center',
1801 string => $word,
1802 x => int($cell_width / 2),
1803 y => $y,
1804 );
1805 }
1806  
1807 } # End of shrink_string.
1808  
1809 # -----------------------------------------------
1810  
1811 sub test_size
1812 {
1813 my($self, $defaults, $flower, $request) = @_;
1814 my($height_latitude) = $$defaults{constants_table}{height_latitude};
1815 my($result) = false;
1816 my($width_latitude) = $$defaults{constants_table}{width_latitude};
1817  
1818 my($lower_bound);
1819 my($upper_bound);
1820  
1821 if ($$request{height_provided} -> isTrue)
1822 {
1823 if ($$request{operator} eq '<')
1824 {
1825 if ($$flower{max_height} < $$request{size})
1826 {
1827 $result = true;
1828 }
1829 }
1830 elsif ($$request{operator} eq '=')
1831 {
1832 $height_latitude = 30 if ($height_latitude <= 0);
1833 $lower_bound = $$request{size} - ($$request{size} * $height_latitude / 100);
1834 $lower_bound = 0 if ($lower_bound < 0);
1835 $upper_bound = $$request{size} + ($$request{size} * $height_latitude / 100);
1836  
1837 if ( ($$flower{min_height} >= $lower_bound) && ($$flower{max_height} <= $upper_bound) )
1838 {
1839 $result = true;
1840 }
1841 }
1842 elsif ($$flower{min_height} > $$request{size})
1843 {
1844 $result = true;
1845 }
1846 }
1847 elsif ($$request{width_provided} -> isTrue)
1848 {
1849 if ($$request{operator} eq '<')
1850 {
1851 if ($$flower{max_width} < $$request{size})
1852 {
1853 $result = true;
1854 }
1855 }
1856 elsif ($$request{operator} eq '=')
1857 {
1858 $width_latitude = 30 if ($width_latitude <= 0);
1859 $lower_bound = $$request{size} - ($$request{size} * $width_latitude / 100);
1860 $lower_bound = 0 if ($lower_bound < 0);
1861 $upper_bound = $$request{size} + ($$request{size} * $width_latitude / 100);
1862  
1863 if ( ($$flower{min_width} >= $lower_bound) && ($$flower{max_width} <= $upper_bound) )
1864 {
1865 $result = true;
1866 }
1867 }
1868 elsif ($$flower{min_width} > $$request{size})
1869 {
1870 $result = true;
1871 }
1872 }
1873  
1874 return $result;
1875  
1876 } # End of test_size.
1877  
1878 # -----------------------------------------------
1879  
1880 sub test_text
1881 {
1882 my($self, $flower, $request) = @_;
1883  
1884 return ( (lc($$flower{aliases}) =~ /$$request{lc_search_text}/)
1885 || (lc($$flower{common_name}) =~ /$$request{lc_search_text}/)
1886 || (lc($$flower{scientific_name}) =~ /$$request{lc_search_text}/) );
1887  
1888 } # End of test_text.
1889  
1890 # -----------------------------------------------
1891  
1892 sub trim
1893 {
1894 my($self, $value) = @_;
1895 $value =~ s/^\s+//;
1896 $value =~ s/\s+$//;
1897 $value =~ s/\s{2,}/ /g;
1898  
1899 return $value;
1900  
1901 } # End of trim.
1902  
1903 # --------------------------------------------------
1904  
1905 1;
1906  
1907 =pod
1908  
1909 =head1 NAME
1910  
1911 WWW::Garden::Design::Database - Manage the 'novels' database
1912  
1913 =head1 Machine-Readable Change Log
1914  
1915 The file Changes was converted into Changelog.ini by L<Module::Metadata::Changes>.
1916  
1917 =head1 Version Numbers
1918  
1919 Version numbers < 1.00 represent development versions. From 1.00 up, they are production versions.
1920  
1921 =head1 Repository
1922  
1923 L<https://github.com/ronsavage/WWW-Garden-Design>
1924  
1925 =head1 Support
1926  
1927 Email the author, or log a bug on RT:
1928  
1929 L<https://rt.cpan.org/Public/Dist/Display.html?Name=WWW::Garden::Design>.
1930  
1931 =head1 Author
1932  
1933 L<WWW::Garden::Design> was written by Ron Savage I<E<lt>ron@savage.net.auE<gt>> in 2014.
1934  
1935 My homepage: L<https://savage.net.au/>.
1936  
1937 =head1 Copyright
1938  
1939 Australian copyright (c) 2018, Ron Savage.
1940  
1941 All Programs of mine are 'OSI Certified Open Source Software';
1942 you can redistribute them and/or modify them under the terms of
1943 The Perl License, a copy of which is available at:
1944 http://dev.perl.org/licenses/
1945  
1946 =cut