MTrackWeb/Cron/Notify.php
[web.mtrack] / MTrackWeb / Cron / Notify.php
1 <?php
2 require_once 'MTrackWeb.php';
3
4 class MTrackWeb_Cron_Notify extends MTrackWeb
5 {
6     
7     function getAuth()
8     {
9         $ff = HTML_FlexyFramework::get();
10         if (!$ff->cli) {
11             die("access denied");
12         }
13         HTML_FlexyFramework::ensureSingle(__FILE__, $this);
14         return true;
15         
16     }
17     
18     function get()    
19     {
20         //DB_DataObject::debugLevel(1);
21         date_default_timezone_set('UTC');
22         
23         // what's the baserul..
24     
25         
26         $MAX_DIFF = 200 * 1024;
27         $USE_BATCHING = false;
28         
29          
30         $e= DB_DataObject::factory('Events');
31         $e->action = 'MTRACK.NOTIFY';
32         $e->selectAdd();
33         $e->selectAdd('MAX(event_when) as event_when');
34         $e->find(true);
35         if (empty($e->event_when)) {
36             $e->event_when = date('Y-m-d H:i:s', strtotime("NOW - 2 days")); // should be a long time ago..
37         }
38          
39         
40         
41         //stream_filter_register("mtrackcanonical", 'CanonicalLineEndingFilter');
42         //stream_filter_register("mtrackunix", 'UnixLineEndingFilter');
43         
44         $w = DB_DataObject::factory('core_watch');
45         //echo "gather watched";
46        // DB_DataObject::debugLevel(1);
47         // returns a list of user with the objects they are watching..
48         $watches = $w->watched('email');
49         //echo "\nDONE WATCHED\n";
50         $CS = DB_DataObject::factory('mtrack_change');
51         
52         $messages = array();
53         $cache = array();
54         foreach($watches as $uid => $ar) {
55             //echo "gather changes";
56             //print_r($uid); print_r($ar);
57             // we can now query mtrack_change for anything that occured in that list..
58             $messages = $CS->gatherChanges($e->event_when, $uid, $ar);
59             //print_R($messages);exit;
60             // we should cache the emails. = as multiple people might be getting the same email.
61             
62             // should be like a list of tickets
63             foreach ($messages as $m=>$ar) {
64                 
65                 $lr = explode(':', $m);
66                 $o = DB_DataObject::Factory($lr[0]);
67                 $o->autoJoin();
68                 $o->get($lr[1]);
69                 if (!isset($cache[implode(',', $ar)])) {
70                     $cs = clone($CS);
71                     $cs->whereAddIn('mtrack_change.id', $ar, 'int');
72                     $cs->autoJoin();
73                     $cache[implode(',', $ar)] = $cs->fetchAll();
74                 }
75                 $u  = DB_DataObject::factory('Person');
76                 $u->get($uid);
77                 $method =  'notify_'. $lr[0] ;
78                 if (method_exists($this,$method)) {
79                     $this->$method($o,  $cache[implode(',', $ar)], $u);
80                 }
81             }
82             
83             
84             
85             
86             
87             
88             
89         }
90        // print_R($messages);
91         die("done");
92         
93         
94         
95         
96          
97         /* For each watcher, compute the changes.
98          * Group changes by ticket, sending one email per ticket.
99          * Group tickets into batch updates if the only fields that changed are
100          * bulk update style (milestone, assignment etc.)
101          *
102          * For the wiki repo, group by file so that serial edits within the batch
103          * period show up as a single email.
104          */
105          
106     }
107     
108     
109     /**
110      * sets:
111      *   - from (system or a specific user.)
112      *   - replyto (system)
113      *   - to user...
114      *   
115      */
116     function calcAddress($ticket, $changes, $user)
117     {
118         $ff = HTML_FlexyFramework::get();
119         
120         
121         $changers = array();
122         foreach($changes as $c) {
123             if ($change->person_id == $user->id) {
124                 continue;
125             }
126             if (in_array($change->person_id_name, $changers)) {
127                 continue;
128             }
129             $changers[] = $change->person_id_name;
130             
131         }
132         
133         
134         $p = $ticket->project();
135         $headers['To'] = '"'. addslashes($user->name). '" <' . $user->email .'>';
136         $headers['From'] = '"'. addslashes($project->toEventString()). '" '. 
137                 $ff->MTrackWeb['email_address']; // could be the user who made the change...
138         
139         //if (count($from) > 1) {
140         //    $rep = array();
141         //    array_shift($from);
142          //       foreach ($from as $email) {
143          // $rep[] = make_email($email[0], $email[1]);
144         // }
145         
146         $headers['Reply-To'] =  $ff->MTrackWeb['email_address'];
147         //}
148         return $headers;
149     }
150     
151     /**
152      * convert notification into an email..
153      *
154      * @param object $ticket the DataObject
155      * @param array $items the ids of the mtrack_change's
156      * @parem object $user DataObject of the user..
157      * 
158      */
159     
160     function notify_mtrack_ticket($ticket, $changes, $user)
161     {
162         //global $MAX_DIFF;
163         $ff = HTML_FlexyFramework::get();
164      
165         
166         
167         
168      
169      
170         // from is always the system.. ??
171         // unless all the changers are the same..
172         $headers = $this->calcAddress($ticket, $changes, $user);
173         
174           
175         //$headers['To'] = '"'. addslashes($user->name). '" <' . $user->email .'>';
176         //$headers['From'] = make_email($from[0][0], $from[0][1]);
177         //if (count($from) > 1) {
178         //    $rep = array();
179         //    array_shift($from);
180          //       foreach ($from as $email) {
181          // $rep[] = make_email($email[0], $email[1]);
182         // }
183         //$headers['Reply-To'] = join(', ', $rep);
184         //}
185      
186         $headers += array(
187             'MIME-Version' => '1.0',
188             'Content-Type' => 'text/plain; charset="UTF-8"',
189             'Content-Transfer-Encoding' => 'quoted-printable',
190         );
191     
192         
193         $mid = $ticket->id . '@' . php_uname('n');
194         
195         
196         
197         
198         //if ($is_initial) {
199         //    $headers['Message-ID'] = "<$mid>";
200         //} else {
201         //$headers['Message-ID'] = "<$T->updated.$mid>";
202         //$headers['In-Reply-To'] = "<$mid>";
203         //$headers['References'] = "<$mid>";
204         //}
205       /* find related project(s) */
206         $p = $ticket->project();
207          
208         $subj = "[" . $p->code . ' - ' . $p->name . "] ";
209     
210         $headers['X-mtrack-project-list'] = $p->code;
211         //foreach ($projects as $pname) {
212         //  $headers["X-mtrack-project-$pname"] = $pname;
213          // $headers['X-mtrack-project'][] = $pname;
214         //}
215         //} else {
216         //$subj = '';
217         // }
218     
219         $headers['Subject'] = sprintf("%s#%s %s (%s %s)",
220           $subj, $ticket->id, $ticket->summary,
221           $ticket->status_name, $ticket->classification_id_name);
222     
223         $owner =  $ticket->owner_id ? $ticket->owner_id_name : 'nobody';
224     
225         $body = 
226             sprintf("%s/Ticket.php/%s\n\n", $ff->MTrackWeb['url'], $ticket->id) .
227             sprintf("#%s: %s (%s %s)\n", $ticket->id, $ticket->summary, $ticket->status_name, $ticket->classification_id_name) .
228             sprintf("Responsible: %s (%s / %s)\n", $owner, $ticket->priority_id_name, $ticket->severity_id_name) .
229     
230             //sprintf("Milestone: %s\n", join(', ', $T->getMilestones()));
231             //sprintf("Component: %s\n", join(', ', $T->getComponents()));
232             "\n";
233     
234       // Display changed fields grouped by the person that last changed them
235         //$who_changed = array();
236         //foreach ($field_changers as $field => $who) {
237         //  $who_changed[$who][] = $field;
238         //}
239         $body.="\n\n";
240         foreach ($changes as $change) {
241             
242             $body .= "{$change->changedate}:  Change by {$change->person_id_name}\n";
243             $body .= str_repeat('-', 80) . "\n";
244             if (!empty($change->reason)) {
245                 $body.= $change->reason;
246             }
247             $ar = $change->cachedAudit();
248             foreach($ar as $audit) {
249                 
250                 switch($audit->field()) {
251                     case 'id':
252                         continue; //??? ignore?
253                     case '@components':
254                         continue;
255                     //  $old = array();
256                     //  foreach (preg_split("/\s*,\s*/", $old_values[$field]) as $id) {
257                      /*   if (!strlen($id)) continue;
258                         $c = get_component($id);
259                         $old[$id] = $c->name;
260                       }
261                       $value = $T->getComponents();
262                       $field = 'Component';
263                       break;
264                      */
265                     case '@milestones':
266                         continue;
267                     //  $old = array();
268                     //  foreach (preg_split("/\s*,\s*/", $old_values[$field]) as $id) {
269                       /*  if (!strlen($id)) continue;
270                         $m = get_milestone($id);
271                         $old[$id] = $m->name;
272                       }
273                       $value = array();
274                       $value = $T->getMilestones();
275                       $field = 'Milestone';
276                       break;
277                       */
278                     case '@keywords':
279                         continue;
280                     /*
281                       $old = array();
282                       $field = 'Keywords';
283                       $value = $T->getKeywords();
284                       break;
285                       */
286                       
287                     //case 'commit?'  
288                       
289                     default:
290                         $oldvalue = $audit->oldvalue($this);
291                         $value = $audit->oldvalue(($this);
292                         if (!strlen($oldvalue)) {
293                             $body .= "Set {$audit->field()} to: {$value}\n";
294                             continue;
295                         }
296                         
297                         if (!strlen($value)) {
298                             $body .= "Removed {$audit->field()} - was: {$oldvalue}\n";
299                             continue;
300                         }
301                         $body .= "Changed {$audit->field()} from :{$oldvalue} -> {$value}\n";
302                         continue;  
303                 }
304             }
305         }
306         
307         $body .= sprintf("%s/Ticket.php/%s\n\n", $ff->MTrackWeb['url'], $ticket->id);
308         
309         echo $body;   
310     
311         //  send_mail($udata['email'], $plain);
312     }
313     
314 }
315
316
317 class CanonicalLineEndingFilter extends php_user_filter {
318     function filter($in, $out, &$consumed, $closing)
319     {
320       while ($bucket = stream_bucket_make_writeable($in)) {
321         $bucket->data = preg_replace("/\r?\n/", "\r\n", $bucket->data);
322         $consumed += $bucket->datalen;
323         stream_bucket_append($out, $bucket);
324       }
325       return PSFS_PASS_ON;
326     }
327     }
328     class UnixLineEndingFilter extends php_user_filter {
329     function filter($in, $out, &$consumed, $closing)
330     {
331       while ($bucket = stream_bucket_make_writeable($in)) {
332         $bucket->data = preg_replace("/\r?\n/", "\n", $bucket->data);
333         $consumed += $bucket->datalen;
334         stream_bucket_append($out, $bucket);
335       }
336       return PSFS_PASS_ON;
337     }
338     }