DataObjects/Core_notify.php
[Pman.Core] / DataObjects / Core_notify.php
1 <?php
2 /**
3  *
4  * Table is designed to be used with a mailer to notify or issue
5  * emails (or maybe others later??)
6  *
7  *
8 CREATE TABLE  core_notify  (
9   `id` int(11)  NOT NULL AUTO_INCREMENT,
10   `recur_id` INT(11) NOT NULL;
11   `act_when` DATETIME NOT NULL,
12   `onid` int(11)  NOT NULL DEFAULT 0,
13   `ontable` varchar(128)  NOT NULL DEFAULT '',
14   `person_id` int(11)  NOT NULL DEFAULT 0,
15   `msgid` varchar(128)  NOT NULL  DEFAULT '',
16   `sent` DATETIME  NOT NULL,
17   `event_id` int(11)  NOT NULL DEFAULT 0,
18   PRIMARY KEY (`id`),
19   INDEX `lookup`(`act_when`, `msgid`)
20 );
21 **/
22
23 require_once 'DB/DataObject.php';
24
25 class Pman_Core_DataObjects_Core_notify extends DB_DataObject 
26 {
27     ###START_AUTOCODE
28     /* the code below is auto generated do not remove the above tag */
29
30     public $__table = 'core_notify';                     // table name
31     public $id;                              // int(11)  not_null primary_key auto_increment
32     public $recur_id;                        // int(11) not_null
33     public $act_when;                        // datetime(19)  not_null multiple_key binary
34     public $onid;                            // int(11)  not_null
35     public $ontable;                         // string(128)  not_null
36     public $person_id;                       // int(11)  not_null
37     public $msgid;                           // string(128)  not_null
38     public $sent;                            // datetime(19)  not_null binary
39     public $event_id;                        // int(11)  
40     public $watch_id;                        // int(11)  
41     public $trigger_person_id;                 // int(11)
42     public $trigger_event_id;              // int(11)  
43     public $evtype;                         // event type (or method to call)fall
44     public $act_start;
45     public $person_table;
46
47
48     /* the code above is auto generated do not remove the tag below */
49     ###END_AUTOCODE
50     
51     function person($set = false)
52     {
53         $def_pt = 'core_person';
54         
55         if ($set !== false) {
56             $this->person_table = is_object($set) ? $set->tableName() : '';
57             
58             
59             
60             $person_table = empty($this->person_table) ? $def_pt  : strtolower($this->person_table);
61             $col = $person_table  == $def_pt ? 'person_id' : $person_table . '_id';
62             
63             $this->{$col} = is_object($set) ? $set->id : $set;
64             return;
65         }
66         static $cache  =array();
67         $person_table = empty($this->person_table) ? $def_pt  : strtolower($this->person_table);
68         $col = $person_table == $def_pt  ? 'person_id' : $person_table . '_id';
69         
70         if (isset($cache[$person_table .':'. $this->{$col}])) {
71             return $cache[$person_table .':'. $this->{$col}];
72         }
73         
74         $c = DB_DataObject::Factory($person_table == 'person' ? 'core_person' : $person_table);
75         $c->get($this->{$col});
76         $cache[$person_table .':'. $this->{$col}] = $c;
77         return $c;
78         
79     }
80     function object($set = false)
81     {
82         if ($set !== false) {
83             $this->ontable = $set->tableName();
84             $this->onid = $set->id;
85             return $set;
86         }
87         $c = DB_DataObject::factory($this->ontable);
88         
89         if ($this->onid == 0) {
90             return $c; // empty dataobject.
91         }
92         
93         $c->autoJoin();
94         
95         if ($c->get($this->onid)) {
96             return $c;
97         }
98         return false;
99         
100     }
101     
102     function lookup($obj, $person, $evtype='')
103     {
104         $x = DB_DataObject::Factory($this->tableName());
105         $x->object($obj);
106         $x->person($person);
107         if (!empty($evtype)) {
108             $x->evtype = $evtype;
109         }
110         if ($x->count() != 1) {
111             return false;
112         }
113         $x->find(true);
114         return $x;
115         
116     }
117     
118     
119     function beforeDelete($dependants_array, $roo) {
120         if ($this->delivered()) {
121             $roo->jerr("you can not delete a record of a successfull delivery");
122         }
123     }
124     function  beforeInsert($request,$roo)
125     {
126         if (empty($request['act_when']) && !empty($request['act_start'])) {
127             $this->act_start($request['act_start']);
128         }
129         
130     }
131     function beforeUpdate($old, $request,$roo)
132     {
133         if (empty($request['act_when']) && !empty($request['act_start'])) {
134             $this->act_start($request['act_start']);
135         }
136     }
137     
138     
139     function act_start($set = false)
140     {
141         if ($set === false) {
142             return $this->act_start;
143         }
144         $this->act_when = $set;
145         $this->act_start = $set;
146         return $set;
147     }
148     
149     function event()
150     {
151
152         $c = DB_DataObject::factory('Events');
153         
154         if ($c->get($this->event_id)) {
155             return $c;
156         }
157         return false;
158         
159     }
160     
161     function triggerEvent()
162     {
163
164         $c = DB_DataObject::factory('Events');
165         
166         if ($c->get($this->trigger_event_id)) {
167             return $c;
168         }
169         return false;
170         
171     }
172     
173     function delivered()
174     {
175         return !empty($this->msgid);
176     }
177     
178     function whereAddDeliveryStatus($delivered = false)
179     {
180         $tn = $this->tableName();
181         if ($delivered) {
182             $this->whereAdd("$tn.msgid IS NOT NULL AND $tn.msgid != ''");
183         } else {
184             $this->whereAdd("$tn.msgid IS NULL OR $tn.msgid = ''");    
185         }
186     }
187     
188     function status() // used by commandline reporting at present..
189     {
190         switch($this->event_id) {
191             case -1:
192                 return 'DELIVERED';   //not valid..
193             case 0:
194                 return 'PENDING';
195             default:
196                 $p ='';
197                 if (strtotime($this->act_when) > time()) {
198                     $p = "RETRY: {$this->act_when} ";
199                 }
200                 return  $p. $this->event()->remarks;
201         }
202         
203     }
204     /**
205      * current state of process
206      *
207      * 0 = pending
208      * 1 = delivered
209      * -1 = failed
210      *
211      *
212      */
213     function state()
214     {
215            
216         if ($this->msgid != '') {
217             return 1;
218         }
219         
220         // msgid is empty now..
221         // if act_when is greater than now, then it's still pending.
222         if (strtotime($this->act_when) > time()) {
223             return 0; 
224         }
225         
226         // event id can be filled in with a failed attempt.
227         
228         if ($this->event_id > 0) {
229             return -1;
230         }
231         
232         // event id is empty, and act_when is in the past... not sent yet..
233         
234         return 0; // pending
235         
236         
237     }
238     
239     
240     function applyFilters($q, $au, $roo)
241     {
242         if (isset($q['ontable']) && !in_array($q['ontable'], array('Person', 'Events',  'core_watch'))) {
243             // this will only work on tables not joined to ours.
244             
245             //DB_DAtaObject::DebugLevel(1);
246             // then we can build a join..
247             $d = DB_DataObject::Factory($q['ontable']);
248             $ji = $d->autoJoin();
249             //echo '<PRE>';print_R($ji);
250             // get cols
251             foreach($ji['join_names'] as $cname=>$fname) {
252                  $this->selectAdd($fname . ' as ontable_id_' . $cname );
253             }
254             
255             //$this->selectAdd($d->_query['data_select']); -- this will cause the same dataIndex...
256             $this->_join .= "
257                 LEFT JOIN {$d->tableName()} ON {$this->tableName()}.onid = {$d->tableName()}.id
258                 {$d->_join}
259             "; 
260             $this->selectAs($d, 'core_notify_%s');
261         } 
262         if (!empty($q['query']['person_id_name']) ) {
263             $this->whereAdd( "join_person_id_id.name LIKE '{$this->escape($q['query']['person_id_name'])}%'");
264              
265         }
266          if (!empty($q['query']['status'])) {
267             switch ($q['query']['status']) {
268                 
269                 case 'SUCCESS';
270                     $this->whereAdd("msgid  != ''");
271                     break;
272                 case 'FAILED';
273                     
274                     $this->whereAdd("msgid  = '' AND event_id > 0 AND act_when < NOW()");
275                     
276                     break;
277                 case 'PENDING';
278                     $this->whereAdd('event_id = 0 OR (event_id  > 0 AND act_when > NOW() )');
279                     break;
280                 
281                 case 'OPENED';
282                     $this->whereAdd('is_open > 0');
283                     break;
284                 
285                 case 'ALL':
286                 default:
287                     break;
288             }
289         }
290         
291         if(!empty($q['_evtype_align'])){
292             $this->selectAdd("
293                 (SELECT
294                         display_name
295                 FROM
296                         core_enum
297                 WHERE
298                         etype = 'Core.NotifyType'
299                     AND
300                         name = core_notify.evtype
301                     AND
302                         active = 1
303                 ) AS evtype_align
304             ");
305         }
306         
307         if(!empty($q['from'])){
308             $this->whereAdd("
309                 act_when >= '{$q['from']}'
310             ");
311         }
312         
313         if(!empty($q['to'])){
314             $this->whereAdd("
315                 act_when <= '{$q['to']}'
316             ");
317         }
318         
319     }
320     
321     function sendManual()
322     {   
323         require_once 'Pman/Core/NotifySend.php';
324         
325         $send = new Pman_Core_NotifySend();
326         $send->error_handler = 'exception';
327         
328         try {
329             $send->get($this->id, array());
330         } catch (Exception $e) {
331             
332         }
333         
334         ob_end_clean();
335         
336         return true;
337     }
338     
339 }