DataObjects/Core_notify_recur.php
[Pman.Core] / DataObjects / Core_notify_recur.php
1 <?php
2 /**
3  * Table Definition for core_notify_recur
4  */
5 require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Core_notify_recur extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'core_notify_recur';    // table name
13     public $id;                              // int(11)  not_null primary_key auto_increment
14     public $person_id;                       // int(11)  not_null
15     
16     public $dtstart;                         // datetime(19)  not_null binary
17     public $dtend;                           // datetime(19)  not_null binary
18     public $tz;                              // real(6)  not_null
19     
20     public $updated_dt;                      // datetime(19)  not_null binary
21     
22     public $last_applied_dt;                 // datetime(19)  not_null binary
23 //    public $max_applied_dtl
24     public $freq; //  varchar(8) NOT NULL;
25     public $freq_day; // text NOT NULL;
26     public $freq_hour; // text
27     
28     public $onid;                            // int(11)  not_null
29     public $ontable;                         // string(128)  not_null
30     public $last_event_id;                   // int(11)  
31     public $method;                         // depricated.
32     public $method_id;                         // string(128)  not_null
33     
34     public $recur_id;                       //INT(11) not_null
35
36     
37     ###END_AUTOCODE
38     //NOTE recur_id and method are depricated.
39     
40     
41     /*
42       freq =  DAILY | YEARLY | MONTHLY
43         *
44         *        THESE ARE EXCLUSIVE..
45         *        freq_day =  1,2,3,4,5" - day number.. or dayofmonth USES TIME FROM DTSTART (unless hours are speced.)
46         *        >> must..
47         *        freq_hourly = 'what hours' << OR IF EMPTY USES TIME FROM DTSTART
48         *
49     /* the code above is auto generated do not remove the tag below */
50     
51     function applyFilters($q, $au, $roo)
52     {
53         
54         if (isset($q['query']['person_id_name']) ) {
55             $this->whereAdd( "join_person_id_id.name LIKE '{$this->escape($q['query']['person_id_name'])}%'");
56              
57         }
58          
59         
60          
61         
62         
63     }
64     function notifytimesRange($advance) {
65         
66         $start = date('Y-m-d H:i:s', max(strtotime("NOW"), strtotime($this->dtstart)));
67         $end  = date('Y-m-d H:i:s', min(strtotime("NOW + $advance DAYS"), strtotime($this->dtend)));
68         
69     }
70     
71     function method()
72     {
73         $e = DB_DataObject::Factory('core_enum');
74         $e->get($this->method_id);
75         return $e;
76     }
77     
78     function notifytimes($advance)
79     {
80         
81         // make a list of datetimes when notifies need to be generated for.
82         // it starts 24 hours ago.. or when dtstart
83         
84         list($start, $end) = $this->notifytimesRange($advance);
85         
86         if (strtotime($start) > strtotime($end)) {
87             return array(); // no data..
88         }
89         $ret = array();
90         $hours = empty($this->freq_hour) ? array() : array_unique(json_decode($this->freq_hour));
91         $days = empty($this->freq_day) ? array() : json_decode($this->freq_day);
92         
93         //days to use are = MON FRI SUN
94         
95         //ARE there events on these day in advance days in the future?
96         //TODAY = 25th of may (FRI)
97         //TODAY+1  = 26th  (SAT)
98         //TODAY +2 = 27th = SUN (2== advance)
99         //foreeach day in the future upto >>> advance <<< days?
100             
101          // - does an event occur on this day?
102         //    -YES - then we will generate an event for it.
103          //   -NO nothing happens..
104         $usedays = array();
105         for (  $i =0; $i < $advance +1; $i++) {
106             $ut = strtotime("NOW + $i DAYS");
107             $day = strtoupper(date("D", $ut));
108             if (in_array($day, $days)) {
109                 $usedays[] = date("Y-m-d", $ut);
110             }
111         }
112                 
113         //print_r($this);
114         
115         
116         foreach($usedays as $d){
117             foreach($hours as $h){
118                 $date = new DateTime($d. ' ' . $h, new DateTimeZone($this->tz));
119                 $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
120                 $ret[] = $date->format('Y-m-d H:i:s');
121             }
122         }
123         return $ret;
124     }
125     
126     function generateNotifications()
127     {
128         //DB_DataObject::debugLevel(1);
129         $w = DB_DataObject::factory($this->tableName());
130         $w->id = 117;
131         $w->find();
132         
133         while($w->fetch()){
134             $w->generateNotificationsSingle();
135         
136         }
137     }
138     
139     
140     function generateNotificationsSingle()
141     {
142         
143
144         $notifytimes = $this->notifyTimes(2);
145         ////print_R($notifytimes);
146         
147         $newSearch = DB_DataObject::factory('core_notify');
148         $newSearch->whereAdd( 'act_start > NOW()');
149         $newSearch->recur_id = $this->id;
150         $old = $newSearch->fetchAll('act_start', 'id');
151         // returns array('2012-12-xx'=>12, 'date' => id....)
152
153         
154         
155         foreach($notifytimes as $time){
156            
157             if (isset($old[$time])) {
158                 // we already have it...
159                 
160                 $oo = DB_DataObject::Factory('core_notify');
161                 $oo->get($old[$time]);
162                 $oc = clone($oo);
163                 $oo->evtype = $this->method()->name;
164                 $oo->update($oc);
165                 
166                 unset($old[$time]);
167                 continue;
168             }
169             if (strtotime($time) < time()) {
170                 // will not get deleted..
171                 //echo "SKIP BEFORE NOW";
172                 unset($old[$time]);
173                continue;
174             }
175             // do not have a notify event... creat it..
176             $add = DB_DataObject::factory('core_notify');
177             $add->setFrom(array(
178                 "recur_id" => $this->id,
179                 "act_start" => $time,
180                 "act_when" => $time,
181                 "person_id" => $this->person_id,
182                 "onid" => $this->onid,
183                 "ontable" => $this->ontable,
184                 'evtype' => $this->method()->name,
185             ));
186             $add->insert();
187         }
188         foreach($old as $date => $id ) {
189                 $del = DB_DataObject::factory('core_notify');
190                 $del->get($id);
191                 $del->delete();
192         }
193         //echo("UPDATED");
194
195     }
196     
197     function onUpdate($old, $request,$roo)
198     {
199         $this->generateNotificationsSingle();
200         
201     }
202     function onInsert($request,$roo)
203     {
204         $this->generateNotificationsSingle();
205         
206     }
207     function beforeDelete($dependants_array, $roo)
208     {
209         $n = DB_DataObject::Factory("core_notify");
210         $n->recur_id = $this->id;
211         $n->whereAdd('act_start > NOW() OR act_when > NOW()');
212         // should delete old events that have not occurred...
213         $n->delete(DB_DATAOBJECT_WHEREADD_ONLY);
214     }
215     
216     function toRooSingleArray($authUser, $request)
217     {
218         $ret = $this->toArray();
219         
220         if(!empty($ret['keyword_filters'])){
221             $keywords = array_unique(array_filter(explode(',', $ret['keyword_filters'])));
222             
223             $clipping_keywords = DB_DataObject::factory('clipping_keywords');
224             $clipping_keywords->whereAddIn('id', $keywords, 'int');
225             
226             $li = array();
227             
228             foreach ($clipping_keywords->fetchAll('id', 'keyword') as $k => $v){
229                 $li[] = array(
230                     'id' => $k,
231                     'keyword' => $v
232                 );
233             }
234             
235             $ret['keywords'] = json_encode($li);
236         }
237         
238         return $ret;
239     }
240     
241     function toRooArray($request)
242     {
243         $ret = $this->toArray();
244         
245         if(!empty($ret['keyword_filters'])){
246             $keywords = array_unique(array_filter(explode(',', $ret['keyword_filters'])));
247             
248             $clipping_keywords = DB_DataObject::factory('clipping_keywords');
249             $clipping_keywords->whereAddIn('id', $keywords, 'int');
250             
251             $ret['keywords'] = implode(',', $clipping_keywords->fetchAll('keyword'));
252         }
253         
254         return $ret;
255     }
256 }