2570c860710937cb02a754b1aabac6bd041d8af8
[Pman.Core] / DataObjects / Core_notify.php
1 <?php
2 /**
3  *
4  * Table iend 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 class_exists('DB_DataObject') ? '' : 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     public $to_email;
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             $person_table = empty($this->person_table) ? $def_pt  : strtolower($this->person_table);
59             $col = $person_table  == $def_pt ? 'person_id' : $person_table . '_id';
60             
61             $this->{$col} = is_object($set) ? $set->id : $set;
62             return;
63         }
64         static $cache  =array();
65         $person_table = empty($this->person_table) ? $def_pt  : strtolower($this->person_table);
66         $col = $person_table == $def_pt  ? 'person_id' : $person_table . '_id';
67         
68         if (isset($cache[$person_table .':'. $this->{$col}])) {
69             return $cache[$person_table .':'. $this->{$col}];
70         }
71         
72         $c = DB_DataObject::Factory($person_table == 'person' ? 'core_person' : $person_table);
73         $c->get($this->{$col});
74         $cache[$person_table .':'. $this->{$col}] = $c;
75         return $c;
76         
77     }
78     function object($set = false)
79     {
80         if ($set !== false) {
81             $this->ontable = $set->tableName();
82             $this->onid = $set->id;
83             return $set;
84         }
85         $c = DB_DataObject::factory($this->ontable);
86         
87         if ($this->onid == 0) {
88             return $c; // empty dataobject.
89         }
90         
91         $c->autoJoin();
92         
93         if ($c->get($this->onid)) {
94             return $c;
95         }
96         return false;
97         
98     }
99     
100     function lookup($obj, $person, $evtype='')
101     {
102         $x = DB_DataObject::Factory($this->tableName());
103         $x->object($obj);
104         $x->person($person);
105         if (!empty($evtype)) {
106             $x->evtype = $evtype;
107         }
108         if ($x->count() != 1) {
109             return false;
110         }
111         $x->find(true);
112         return $x;
113         
114     }
115     
116     
117     function beforeDelete($dependants_array, $roo) {
118         if ($this->delivered()) {
119             $roo->jerr("you can not delete a record of a successfull delivery");
120         }
121     }
122     function  beforeInsert($request,$roo)
123     {
124         if (empty($request['act_when']) && !empty($request['act_start'])) {
125             $this->act_start($request['act_start']);
126         }
127         
128     }
129     function beforeUpdate($old, $request,$roo)
130     {
131         if (empty($request['act_when']) && !empty($request['act_start'])) {
132             $this->act_start($request['act_start']);
133         }
134     }
135     
136     
137     function act_start($set = false)
138     {
139         if ($set === false) {
140             return $this->act_start;
141         }
142         $this->act_when = $set;
143         $this->act_start = $set;
144         return $set;
145     }
146     
147     function event()
148     {
149
150         $c = DB_DataObject::factory('Events');
151         
152         if ($c->get($this->event_id)) {
153             return $c;
154         }
155         return false;
156         
157     }
158     
159     function triggerEvent()
160     {
161
162         $c = DB_DataObject::factory('Events');
163         
164         if ($c->get($this->trigger_event_id)) {
165             return $c;
166         }
167         return false;
168         
169     }
170     
171     function delivered()
172     {
173         return !empty($this->msgid);
174     }
175     
176     function whereAddDeliveryStatus($delivered = false)
177     {
178         $tn = $this->tableName();
179         if ($delivered) {
180             $this->whereAdd("$tn.msgid IS NOT NULL AND $tn.msgid != ''");
181         } else {
182             $this->whereAdd("$tn.msgid IS NULL OR $tn.msgid = ''");    
183         }
184     }
185     
186     function status() // used by commandline reporting at present..
187     {
188         switch($this->event_id) {
189             case -1:
190                 return 'DELIVERED';   //not valid..
191             case 0:
192                 return 'PENDING';
193             default:
194                 $p ='';
195                 if (strtotime($this->act_when) > time()) {
196                     $p = "RETRY: {$this->act_when} ";
197                 }
198                 return  $p. $this->event()->remarks;
199         }
200         
201     }
202     /**
203      * current state of process
204      *
205      * 0 = pending
206      * 1 = delivered
207      * -1 = failed
208      *
209      *
210      */
211     function state()
212     {
213            
214         if ($this->msgid != '') {
215             return 1;
216         }
217         
218         // msgid is empty now..
219         // if act_when is greater than now, then it's still pending.
220         if (strtotime($this->act_when) > time()) {
221             return 0; 
222         }
223         
224         // event id can be filled in with a failed attempt.
225         
226         if ($this->event_id > 0) {
227             return -1;
228         }
229         
230         // event id is empty, and act_when is in the past... not sent yet..
231         
232         return 0; // pending
233         
234         
235     }
236     
237     
238     function applyFilters($q, $au, $roo)
239     {
240         
241         if (!empty($q['search']['contains'])) {
242             $this->whereAdd("join_event_id_id.remarks LIKE '%".$this->escape($q['search']['contains']) ."%'");
243             
244         }
245         if (isset($q['ontable']) && !in_array($q['ontable'], array('Person', 'Events',  'core_watch'))) {
246             // this will only work on tables not joined to ours.
247             
248             //DB_DAtaObject::DebugLevel(1);
249             // then we can build a join..
250             $d = DB_DataObject::Factory($q['ontable']);
251             $ji = $d->autoJoin();
252             //echo '<PRE>';print_R($ji);
253             // get cols
254             foreach($ji['join_names'] as $cname=>$fname) {
255                  $this->selectAdd($fname . ' as ontable_id_' . $cname );
256             }
257             
258             //$this->selectAdd($d->_query['data_select']); -- this will cause the same dataIndex...
259             $this->_join .= "
260                 LEFT JOIN {$d->tableName()} ON {$this->tableName()}.onid = {$d->tableName()}.id
261                 {$d->_join}
262             "; 
263             $this->selectAs($d, 'core_notify_%s');
264         } 
265         if (!empty($q['query']['person_id_name']) ) {
266             $this->whereAdd( "join_person_id_id.name LIKE '{$this->escape($q['query']['person_id_name'])}%'");
267              
268         }
269          if (!empty($q['query']['status'])) {
270             switch ($q['query']['status']) {
271                 
272                 case 'SUCCESS';
273                     $this->whereAdd("msgid  != ''");
274                     break;
275                 case 'FAILED';
276                     
277                     $this->whereAdd("msgid  = '' AND event_id > 0 AND act_when < NOW()");
278                     
279                     break;
280                 case 'PENDING';
281                     $this->whereAdd('event_id = 0 OR (event_id  > 0 AND act_when > NOW() )');
282                     $this->whereAdd("sent < '2000-01-01'");
283                     break;
284                 
285                 case 'OPENED';
286                     $this->whereAdd('is_open > 0');
287                     break;
288                 
289                 case 'ALL':
290                 default:
291                     break;
292             }
293         }
294         
295         if(!empty($q['_evtype_align'])){
296             $this->selectAdd("
297                 (SELECT
298                         display_name
299                 FROM
300                         core_enum
301                 WHERE
302                         etype = 'Core.NotifyType'
303                     AND
304                         name = core_notify.evtype
305                     AND
306                         active = 1
307                 ) AS evtype_align
308             ");
309         }
310         
311         if(!empty($q['from'])){
312             $this->whereAdd("
313                 act_when >= '{$q['from']}'
314             ");
315         }
316         
317         if(!empty($q['to'])){
318             $this->whereAdd("
319                 act_when <= '{$q['to']}'
320             ");
321         }
322         
323     }
324     
325     function sendManual($debug=false)
326     {   
327         require_once 'Pman/Core/NotifySend.php';
328         
329         $send = new Pman_Core_NotifySend();
330         $send->error_handler = 'exception';
331         
332         if ($debug) {
333             $send->get($this->id, array());
334             return true;
335         }
336         
337         try {
338             $send->get($this->id, array('force' => 1));
339         } catch (Exception $e) {
340             ob_end_clean();
341             return $e;
342         }
343         
344         ob_end_clean();
345         
346         return true;
347     }
348     // after called do not rely on content as it includes NOW()
349     function flagDone($event,$msgid)
350     {
351         $ww = clone($this);
352         if(strtotime($this->act_when) > strtotime("NOW")){
353             $this->act_when = $this->sqlValue('NOW()');
354         }
355         $this->sent = empty($this->sent) || strtotime($this->sent) < 1 ? $this->sqlValue('NOW()') :$this->sent; // do not update if sent.....
356         $this->msgid = $msgid;
357         $this->event_id = $event->id;
358         $this->update($ww);
359     }
360     
361     function flagLater($when)
362     {
363         $ww = clone($this);
364         $this->act_when = $when;
365         $this->update($ww);
366     }
367     
368 }