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