1 <?php
2
3 4 5 6 7 8 9 10
11
12 namespace Icybee\Modules\Contents;
13
14 use ICanBoogie\HTTP\ForceRedirect;
15
16 use ICanBoogie\ActiveRecord;
17 use ICanBoogie\ActiveRecord\Query;
18 use ICanBoogie\ActiveRecord\RecordNotFound;
19
20 class ViewProvider extends \Icybee\Modules\Nodes\ViewProvider
21 {
22 23 24
25 public function __invoke()
26 {
27 $rc = parent::__invoke();
28
29 if (!$rc && $this->returns == self::RETURNS_ONE)
30 {
31 $rc = $this->rescue();
32 }
33
34 return $rc;
35 }
36
37 38 39 40 41 42 43
44 protected function alter_query(Query $query, array $conditions)
45 {
46 foreach ($conditions as $property => $value)
47 {
48 switch ($property)
49 {
50 case 'year':
51 $query->where('YEAR(date) = ?', (int) $value);
52 break;
53
54 case 'month':
55 $query->where('MONTH(date) = ?', (int) $value);
56 break;
57
58 case 'day':
59 $query->where('DAY(date) = ?', (int) $value);
60 break;
61 }
62 }
63
64 if ($this->view->type == 'home')
65 {
66 $query->where('is_home_excluded = 0');
67 }
68
69 return parent::alter_query($query, $conditions)->order('date DESC, created_at DESC');
70 }
71
72 73 74 75 76 77 78 79 80 81 82 83 84
85 protected function rescue()
86 {
87 $conditions = $this->conditions;
88
89 if (!empty($conditions['nid']) || empty($conditions['slug']))
90 {
91 return;
92 }
93
94 $slug = $conditions['slug'];
95 $model = $this->module->model;
96 $tries = $model->select('nid, slug')->own->visible->order('date DESC')->pairs;
97 $key = null;
98 $max = 0;
99
100 foreach ($tries as $nid => $compare)
101 {
102 similar_text($slug, $compare, $p);
103
104 if ($p > $max)
105 {
106 $key = $nid;
107
108 if ($p > 90)
109 {
110 break;
111 }
112
113 $max = $p;
114 }
115 }
116
117 if ($p < 60)
118 {
119 throw new RecordNotFound('Record not found.', []);
120 }
121 else if ($key)
122 {
123 $record = $model[$key];
124
125 \ICanBoogie\log('The record %title was rescued!', [ 'title' => $record->title ]);
126
127 throw new ForceRedirect($record->url, 301);
128 }
129 }
130 }