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->MTrackWeb['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         
125         $headers['Reply-To'] =  $ff->MTrackWeb['email_address'];
126         //}
127         return $headers;
128     }
129     
130     /**
131      * convert notification into an email..
132      *
133      * @param object $ticket the DataObject
134      * @param array $items the ids of the mtrack_change's
135      * @parem object $user DataObject of the user..
136      * 
137      */
138     
139     function notify_mtrack_ticket($ticket, $changes, $user)
140     {
141         //global $MAX_DIFF;
142       
143         // from is always the system.. ??
144         // unless all the changers are the same..
145         $headers = $this->calcAddress($changes, $user);
146         
147           
148         //$headers['To'] = '"'. addslashes($user->name). '" <' . $user->email .'>';
149         //$headers['From'] = make_email($from[0][0], $from[0][1]);
150         //if (count($from) > 1) {
151         //    $rep = array();
152         //    array_shift($from);
153          //       foreach ($from as $email) {
154          // $rep[] = make_email($email[0], $email[1]);
155         // }
156         //$headers['Reply-To'] = join(', ', $rep);
157         //}
158      
159         $headers += array(
160             'MIME-Version' => '1.0',
161             'Content-Type' => 'text/plain; charset="UTF-8"',
162             'Content-Transfer-Encoding' => 'quoted-printable',
163         );
164     
165         
166         $mid = $ticket->id . '@' . php_uname('n');
167         
168         
169         
170         
171         //if ($is_initial) {
172         //    $headers['Message-ID'] = "<$mid>";
173         //} else {
174         //$headers['Message-ID'] = "<$T->updated.$mid>";
175         //$headers['In-Reply-To'] = "<$mid>";
176         //$headers['References'] = "<$mid>";
177         //}
178       /* find related project(s) */
179         $p = $ticket->project();
180          
181         $subj = "[" . $p->code . ' - ' . $p->name . "] ";
182     
183         $headers['X-mtrack-project-list'] = $p->code;
184         //foreach ($projects as $pname) {
185         //  $headers["X-mtrack-project-$pname"] = $pname;
186          // $headers['X-mtrack-project'][] = $pname;
187         //}
188         //} else {
189         //$subj = '';
190         // }
191     
192         $headers['Subject'] = sprintf("%s#%s %s (%s %s)",
193           $subj, $ticket->id, $ticket->summary, $ticket->status_name, $ticket->classification_id_name);
194     
195         $owner = strlen($ticket->owner_id) ? $ticket->owner_id_name : 'nobody';
196     
197         $body = 
198             sprintf("%s/Ticket.php/%s\n\n", $ff->MTrackWeb['url'], $ticket->id) .
199             sprintf("#%s: %s (%s %s)\n", $ticket->id, $ticket->summary, $ticket->status_name, $ticket->classification_id_name) .
200             sprintf("Responsible: %s (%s / %s)\n", $owner, $ticket->priority_id_name, $ticket->severity_id_name) .
201     
202             //sprintf("Milestone: %s\n", join(', ', $T->getMilestones()));
203             //sprintf("Component: %s\n", join(', ', $T->getComponents()));
204             "\n";
205     
206       // Display changed fields grouped by the person that last changed them
207         //$who_changed = array();
208         //foreach ($field_changers as $field => $who) {
209         //  $who_changed[$who][] = $field;
210         //}
211         $body.="\n\n";
212         foreach ($changes as $change) {
213             
214             $body .= "{$change->changedate}:  Change by {$change->person_id_name}\n";
215             $body .= str_repeat('-', 80) . "\n";
216             if (!empty($change->reason)) {
217                 $body.= $change->reason;
218             }
219             $ar = $change->cachedAudit();
220             foreach($ar as $audit) {
221                 
222                 switch($audit->field()) {
223                     case 'id':
224                         continue; //??? ignore?
225                     case '@components':
226                         continue;
227                     //  $old = array();
228                     //  foreach (preg_split("/\s*,\s*/", $old_values[$field]) as $id) {
229                      /*   if (!strlen($id)) continue;
230                         $c = get_component($id);
231                         $old[$id] = $c->name;
232                       }
233                       $value = $T->getComponents();
234                       $field = 'Component';
235                       break;
236                      */
237                     case '@milestones':
238                         continue;
239                     //  $old = array();
240                     //  foreach (preg_split("/\s*,\s*/", $old_values[$field]) as $id) {
241                       /*  if (!strlen($id)) continue;
242                         $m = get_milestone($id);
243                         $old[$id] = $m->name;
244                       }
245                       $value = array();
246                       $value = $T->getMilestones();
247                       $field = 'Milestone';
248                       break;
249                       */
250                     case '@keywords':
251                         continue;
252                     /*
253                       $old = array();
254                       $field = 'Keywords';
255                       $value = $T->getKeywords();
256                       break;
257                       */
258                       
259                     //case 'commit?'  
260                       
261                     default:
262                         if (!strlen($audit->oldvalue)) {
263                             $body .= "Set {$audit->field()} to: {$audit->value}\n";
264                             continue;
265                         }
266                         if (!strlen($audit->value)) {
267                             $body .= "Removed {$audit->field()} - was: {$audit->oldvalue}\n";
268                             continue;
269                         }
270                         $body .= "Changed {$audit->field()} from :{$audit->oldvalue} -> {$audit->value}\n";
271                         continue;  
272                 }
273             }
274         }
275         
276         $body .= sprintf("%s/Ticket.php/%s\n\n", $ff->MTrackWeb['url'], $ticket->id);
277         
278         echo $body;   
279     
280         //  send_mail($udata['email'], $plain);
281     }
282     
283 }
284
285
286 class CanonicalLineEndingFilter extends php_user_filter {
287     function filter($in, $out, &$consumed, $closing)
288     {
289       while ($bucket = stream_bucket_make_writeable($in)) {
290         $bucket->data = preg_replace("/\r?\n/", "\r\n", $bucket->data);
291         $consumed += $bucket->datalen;
292         stream_bucket_append($out, $bucket);
293       }
294       return PSFS_PASS_ON;
295     }
296     }
297     class UnixLineEndingFilter extends php_user_filter {
298     function filter($in, $out, &$consumed, $closing)
299     {
300       while ($bucket = stream_bucket_make_writeable($in)) {
301         $bucket->data = preg_replace("/\r?\n/", "\n", $bucket->data);
302         $consumed += $bucket->datalen;
303         stream_bucket_append($out, $bucket);
304       }
305       return PSFS_PASS_ON;
306     }
307     }