sync
[Pman.MTrack] / DataObjects / Mtrack_change.php
1 <?php
2 /**
3  * Table Definition for mtrack_change
4  */
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
6
7 class Pman_MTrack_DataObjects_Mtrack_change extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'mtrack_change';                   // table name
13     public $id;                              // int(11)  not_null primary_key auto_increment
14     public $person_id;                       // int(11)  
15     public $ontable;                         // string(128)  
16     public $onid;                            // int(11)  not_null
17     public $changedate;                      // datetime(19)  not_null binary
18     public $reason;                          // blob(65535)  blob
19
20     
21     /* the code above is auto generated do not remove the tag below */
22     ###END_AUTOCODE
23      ###END_AUTOCODE
24      
25     function objectCached()
26     {
27         static $cache;
28         if (empty($this->ontable) || empty($this->onid)) {
29             return false;
30         }
31         
32         if (isset($cache[$this->ontable.':'. $this->onid])) {
33             $cache[$this->ontable.':'. $this->onid];
34         }
35         $o = DB_DataObject::factory($this->ontable);
36         $o->get($this->onid);
37         $cache[$this->ontable.':'. $this->onid] = $o;
38         return $o;
39         
40      
41     }
42     
43      //checkPerm('S'/'E'/'A', $authuser) - can
44     function checkPerm($perm, $au)
45     {
46         
47         if ($au && $au->company()->comptype == 'OWNER') {
48             // owner can do anything..????
49             return true;
50         }
51         
52         if ($perm == 'E' || $perm == 'D' ) { // Edit and delete ..not allowed..
53             return false;
54         }
55         
56         if (!$au && $perm != 'S') {
57             // non-authenticated users can only list stuff..
58             return false;
59             
60         }
61         
62         //DB_DataObject::debugLevel(1);
63         $obj = $this->objectCached();
64         if (!$obj) {
65             return true;
66         }
67         if (!method_exists($obj, 'checkPerm')) {
68             return false;
69         }
70         
71         
72         return $obj->checkPerm($perm, $au);
73         
74          
75     }
76     
77     
78      
79     function applyFilters($q, $au, $roo)
80     {
81         
82         
83         if (!empty($q['timeline'])) {
84             return $this->applyFilterTimeline($q,$au, $roo);
85         }
86         
87         if (!empty($q['_is_update_request'])) {
88             return;
89         }
90         
91         $this->setFrom($q);
92         
93         
94         $obj = $this->objectCached();
95         
96         
97         // global searching on non-object...
98         // needed for timelime, but not ready yet...
99         
100         if (!$obj) {
101             $this->whereAdd('1=0');
102             return;
103            
104         }
105         if (!method_exists($obj, 'checkPerm')) {
106             $this->whereAdd('1=0');
107             return;
108         }
109         
110         if (!$au || (!$obj->checkPerm('S', $au) || !$obj->checkPerm('E', $au)) ) {
111             $this->whereAdd('1=0');
112             return;
113         }    
114         
115         
116         
117            
118     }
119     // this is the query for timelines..
120     function applyFilterTimeline($q, $au, $roo)
121     { 
122         
123         
124         $start = empty($q['on_date']) ? date('Y-m-d') : 
125             date('Y-m-d', strtotime($q['on_date']));
126
127         
128         //DB_DataObject::debugLevel(1);
129         
130         
131         $pd = DB_DataObject::factory('ProjectDirectory');
132         $pd->whereAdd("role != ''");
133         $pids = $pd->projects($au);
134         if (empty($pids)) {
135             $roo->jerr("User is not a member of any projects");
136         }
137         
138         if (!empty($q['project_id'])) {
139             if (!in_array($q['project_id'], $pids)) {
140                 $roo->jerr("Selected project not in your permitted project list.");
141             }
142             $pids = array($q['project_id']);
143         }
144         
145         $pids = implode(',', $pids);
146         
147         // add emails???
148         $this->whereAdd("
149             ( ontable='mtrack_ticket' AND
150                 onid IN (SELECT id FROM mtrack_ticket where project_id IN ( $pids ))
151             )
152             OR
153             ( ontable='mtrack_repos' AND
154                 onid IN (SELECT id FROM mtrack_repos where project_id IN ( $pids ))
155             )
156         ");
157         $this->orderBy('changedate DESC');
158  
159         if (!empty($q['viewtype']) && $q['viewtype'] == 'summary') {
160             //DB_DataObject::debugLevel(1);
161             $isSummary = true;
162             $this->whereAdd("
163                         changedate >= '$start 00:00:00'
164                         AND
165                         changedate < '$start 00:00:00' + INTERVAL 1 DAY
166             ");
167             
168             
169             $this->selectAdd();
170             //$this->joinAdd(DB_DataObject::factory('Person'), 'LEFT');
171             $this->selectAdd("
172                      DATE_FORMAT(changedate, '%Y-%m-%d')  as changeday,
173                      join_person_id_id.id   as person_id,
174                      join_person_id_id.name as person_name,
175                      Projects.id as  project_id,
176                      mtrack_repos.shortname as repo_name,
177                      mtrack_repos.id as repo_id,
178
179                      Projects.code  as project_code,
180                         
181                      COUNT(mtrack_change.id) as nchanges
182                     ");
183             $this->_join .= "
184                 LEFT JOIN Projects ON
185                    Projects.id = IF (ontable='mtrack_repos',
186                        (SELECT project_id FROM mtrack_repos where onid = mtrack_repos.id ),
187                        (SELECT project_id FROM mtrack_ticket where onid = mtrack_ticket.id )
188                      )
189                 LEFT JOIN mtrack_repos ON
190                    mtrack_repos.id = IF (ontable='mtrack_repos', onid,  0)
191                 
192                 
193                 ";
194                 
195             $this->groupBy("changeday,
196                             join_person_id_id.id,
197                             join_person_id_id.name,
198                             repo_id, repo_name,
199                             mtrack_repos.id,
200                              mtrack_repos.shortname,
201                             Projects.code");
202             $this->orderBy('project_code asc, repo_name ASC, person_name asc');
203             $ret = array();
204             $roo->jdata($this->fetchAll(false,false,'toArray'));   
205         }
206         
207          
208         $this->whereAdd("changedate >= '$start_day 00:00:00' AND
209                       changedate < '$start_day 00:00:00' + INTERVAL 1 DAY");
210          
211         //DB_DataObject::debugLevel(1);
212         
213        
214     
215     
216     }
217     // do not accept use input for this..
218     function autoJoinObject($tbl)
219     {
220          
221         
222         $d = DB_DataObject::Factory($tbl);
223         $ji = $d->autoJoin();
224         //echo '<PRE>';print_R($ji);
225         // get cols
226         foreach($ji['join_names'] as $cname=>$fname) {
227              $this->selectAdd($fname . ' as ontable_id_' . $cname );
228         }
229         
230         //$this->selectAdd($d->_query['data_select']); -- this will cause the same dataIndex...
231         $this->_join .= "
232             LEFT JOIN {$d->tableName()} ON {$this->tableName()}.onid = {$d->tableName()}.id
233             {$d->_join}
234         "; 
235         $this->selectAs($d, 'ontable_%s');
236         
237         
238         
239     }
240     
241     
242     
243     
244     function person()
245     {
246         static $cache = array();
247         if (isset($cache[$this->person_id])) {
248             return $cache[$this->person_id];
249         }
250         $p = DB_DataObject::factory('core_person');
251         $p->get($this->person_id);
252         $cache[$this->person_id] = $p;
253         return $p;
254         
255     }
256     
257     function getCommit($repo, $hash, $runhistory=true) 
258     {
259         $this->object = $repo->toIdString(); // should be repo:1
260         $this->rev = $id;
261         if ($this->find(true)) {
262             $this->fetchAudit();
263             return;
264         }
265         if (!$runhistory) {
266             throw new Exception("Can not find revision");
267         }
268         $this->refreshHistory($repo);
269         if ( $this->find(true)) {
270             $this->fetchAudit();
271             return true;
272         }; /// yes I know we say you should not run this twice...
273         return false;
274     }
275     
276     /**
277      *createFromCommit:
278      *@param {TrackCommitHookChangeEvent} ce the change event..
279      */
280     function createFromCommit($ce, $checker, $ticket = false)
281     {
282         $rev = substr(array_pop(explode(',', $ce->rev)), 0, -1);
283         
284         $tc = clone($this);
285         $tc->ontable = 'mtrack_repos';
286         $tc->onid = $checker->repo->id;
287         $tc->rev= $rev;
288         $tc->cgtype = 'COMMIT';
289         $tc->branch = $ce->branch;
290         if ($tc->count()) { // if we have already tracked this..
291             return false;
292         }
293         
294         
295         
296         
297         
298         $tcid = 0;
299         
300         if ($ticket) {
301             $tc = clone($this);    
302             $tc->ontable = $ticket->tableName();
303             $tc->onid = $ticket->id;
304             $tc->changedate = date('Y-m-d H:i:s', $ce->ctime);
305             $tc->reason = $ce->changelog;
306             $tc->person_id = $ce->changeby_id;
307             $tc->rev = $rev;
308             $tcid  = $tc->insert();
309             
310         }
311         
312         
313         $this->ontable = 'mtrack_repos';
314         $this->onid = $checker->repo->id;
315         $this->changedate = date('Y-m-d H:i:s', $ce->ctime);
316         $this->reason = $ce->changelog;
317         $this->person_id = $ce->changeby_id;
318         $this->branch = $ce->branch;
319         $this->rev = $rev;
320         $this->insert();
321         
322         // add all the chanedge files..
323         foreach($ce->fileActions as $f => $cg) { 
324             
325             $au = DB_DataObject::factory('mtrack_change_audit');  
326             $au->change_id  = $this->id;
327             $au->ticket_change_id  = $tcid;
328             $au->fieldname  = $rev;
329             $au->action     = 'commit-'.$cg;
330             $au->value      = $f; 
331             $au->insert();
332         }
333         
334         $this->onInsert(array(), HTML_FlexyFramework::get()->page);
335         
336         // finnaly trigger watchers
337         $matches = array();
338         if (!$ticket && preg_match('/_T([0-9]+)_/', $ce->branch, $matches)) {
339             $ticket = DB_DataObject::factory('mtrack_ticket');
340             if (!$ticket->get($matches[1])) {
341                 $ticket = false;
342             }
343         }
344         if ($ticket) {
345             $ts = DB_DataObject::Factory('cash_invoice_entry');
346             $ts->updateFromCommit($ce, $ticket);
347         }
348         
349         
350         return true;
351         
352         //print_r($this);
353         
354         // audit should contain files changed..
355     }
356     
357     function onInsert($request,$roo) 
358     { 
359         // this will send
360         // for a commit ? - ontable = repos, onid = the repo id...
361         // for a change... ontable - will be the ticked, and onid will be the ticket id..
362         
363         $obj = $this->objectCached();
364         $target = $obj;
365         if ($obj->tableName() == 'mtrack_ticket') {
366             $obj = $obj->project();
367             $target = $obj;
368         } else {
369             $target = empty($this->branch) ? $obj : $obj->branchObject($this->branch);
370         }
371         if ($obj) {
372            
373             $core_watch = DB_DataObject::Factory('core_watch');
374             $core_watch->notify(
375                     $obj->tableName(),
376                     $obj->pid(),
377                     "medium='ENDOFDAYMAIL'",
378                         // end of day..
379                     date('Y-m-d 23:59:59'),
380                     $target->tableName(),
381                     $target->pid()
382             );
383         }    
384     }
385     
386     
387     /*
388     * scans repo history and imports it... ??? does not know about branches yet...
389     */
390     function refreshHistory($repo) 
391     {
392         $c = DB_DataObject::factory('mtrack_changes');
393         $c->object =  $repo->toIdString(); 
394         $c->orderBy('changedate DESC');
395         $c->whereAdd("rev != ''");
396         $last  = '';
397         if ($c->find(true)) {
398             $last = $c->scmid;
399         }
400         // history returns an array of scmEvents... - should actually return an array of this object...
401         $recs = $repo->history('', null, $last ? 'rev' : null, $last ? $last  :null);
402         
403         foreach($recs as $r) { 
404             // see if we have a copy of it already.
405             $c = DB_DataObject::factory('mtrack_change');
406             $c->object =  $repo->toIdString(); 
407             $c->changedate != $r->ctime;
408             $cr  = clone($c);
409             $c->whereAdd("rev != ''");
410             if (!$c->find(true)) {
411                 // not found, create a new one..
412                 $c->insert();
413                 
414             }
415             $cr->rev = $r->rev;
416             $cr->reason = $r->changelog;
417             $cr->who =  $r->changeby;
418             $cr->update();
419             foreach($cr->files as $f) {
420                 // we could do with adding 'X' lines changed on this
421                 $ca = DB_DataObject::factory('change_audit');
422                 $ca->cid = $cr->id;
423                 $ca->fieldname = $cr->object. ':file';
424                 $ca->action = $f->status . ($f->added ? ' +' . $f->added : '') . ($f->removed ? ' -' . $f->removed : '') ;
425                 $ca->value = $f->name;
426                 $ca->insert();
427                 
428             }
429             
430             
431         }
432     
433     }
434      
435
436     function beginChange($object, $reason = '', $when = null)
437     {
438          // $db->beginTransaction();
439          //$this->query('BEGIN');
440         $pg = HTML_FlexyFramework::get()->page;
441         $au  = $pg->authUser;
442
443         $this->person_id = $au->id;
444         $this->ontable      = $object->tableName();                         // string(128)  
445         $this->onid = $object->id; // should use keys( really..)
446         $this->reason = $reason;
447         //$d = date_create("@" . (empty($when)  ? time() : $when), new DateTimeZone('UTC'));
448         $this->changedate =  date('Y-m-d H:i:s'); // everythign at server time..
449                                   //$d->format('Y-m-d\TH:i:s.u\Z');
450         $this->cgtype = $reason == 'Changed' ? 'CHANGE' : 'COMMENT';
451         $this->insert();
452         $this->onInsert(array(), $pg);
453          
454     }
455
456     function commit()
457     {
458         if ($this->count == 0) {
459             //      throw new Exception("no changes were made as part of this changeset");
460         }
461         if (self::$use_txn) {
462             //$this->query('COMMIT');
463           //$db->commit();
464         }
465     }
466     
467     function addentry($fieldname, $action, $old, $value = null)
468     {
469         
470         // final sanity check..
471         $o = DB_DataObject::factory($this->ontable);
472         $info = $o->tableColumns();
473         $far = explode(':',$fieldname);
474         $col = array_pop($far);
475         if (!isset($info[$col])) {
476             return 0;
477         }
478         
479         
480         if ($info[$col] & (defined('DB_DATAOBJECT_INT') ? DB_DATAOBJECT_INT : PDO_DataObject::INT)) {
481             if (((int) $old)  == ((int) $value)) {
482                 return 0;
483             }
484         }
485         
486         
487         
488         $ca = DB_DataObject::factory('mtrack_change_audit');
489         $ca->setFrom(array(
490             'change_id'     => $this->id,
491             'fieldname'     => $fieldname,
492             'action'        => $action,
493             'oldvalue'  => $old,
494             'value'     => $value
495         ));
496         $ca->insert();
497         //print_r($ca);
498         
499         return 1;
500     }
501    
502     /**
503      * usage
504      *      add('xxx:yyy:zzz' , new , old)
505      *      add('xxx:yyy', new_do, old_do) // two dataobjects.. (will diff the two..
506      *      add($new_do, $old_do) 
507      */
508     
509     
510     function add($fieldname, $new, $old = false)
511     {
512         //print_r(array("ADD", $fieldname, $new, $old));
513         //echo "check: $fieldname ($old) => ($new)\n"; 
514         $ret = 0;
515         if (is_object($fieldname)) {
516             return $this->add($this->ontable.':'. $this->onid , $fieldname, $new );  
517         }
518         if (is_object($new)) {
519             // should check keys() - so it does not log primary key addition.
520             
521             $cols = array_keys($new->tableColumns());
522             $keys  = $new->keys();
523             $links = $new->links();
524             
525             foreach($cols as $k) {
526                 if (in_array($k, $keys)) {
527                     continue;
528                 } 
529                 $alinks = isset($links[$k])  ? explode(':', $links[$k]) : false;
530                 if ($alinks && $this->tablename() == array_shift($alinks)) {
531                     continue;
532                 }
533                 if (!$old && !isset($new->{$k})) {
534                     continue;
535                 }
536                 
537                 $ret += $this->add($fieldname .':'. $k, $new->{$k}, !$old ? '' :  $old->{$k});
538             }
539             
540             return $ret;
541         }
542      
543         if ($old == $new) {
544             return $ret;
545         }
546         if ($old !== false) {
547             return  $this->addentry($fieldname, 'set', $old, $new);
548              
549         }
550         if ($new === false) {
551             return    $this->addentry($fieldname, 'deleted', $old, $new);
552             
553         }
554         return   $this->addentry($fieldname, 'changed', $old, $new);
555          
556     }
557     
558     
559     
560     
561     
562     var $_audit = false;
563     function cachedAudit()
564     {
565         static $cache = array();
566         
567         if (!isset($cache[$this->id])) {
568             $cache[$this->id]= $this->audit();
569         }
570         return $cache[$this->id];
571     }
572     function cachedAuditToJSONArray()
573     {
574          
575         $ar = $this->cachedAudit();
576         
577        
578         $ret = array();
579         foreach($ar as $a) {
580              
581             $add = $a->toJSONArray($this);
582             if (!$add) {
583                 continue;
584             }
585             
586             $ret[] = $add;
587         }
588         return $ret;
589         
590     }
591      
592     function relatedCommits()
593     {
594         if (empty($this->rev))  {
595             return '';
596         }
597         // occurs on a ticket... when listing...
598         $mc = DB_DataObject::Factory('mtrack_change');
599         $mc->rev = $this->rev;
600         $mc->ontable = 'mtrack_repos';
601         if (!$mc->find(true)) {
602             return '';
603         }
604         // got the repo.. and the commit..
605         
606         $repo = $mc->objectCached();
607          
608         return  $repo->historyToSummary(
609                     $repo->impl()->history('.', 1, 'rev', $this->rev),
610                 $this->changedate
611         );
612         
613         
614         
615         
616     }
617     
618     
619     function audit()
620     {
621         $a = DB_DataObject::Factory('mtrack_change_audit');
622         $a->whereAdd(" 
623            {$a->tableName()}.change_id = {$this->id} OR
624            {$a->tableName()}.ticket_change_id = {$this->id}   
625         ");
626         //       var_dump($a->find());exit;
627         
628         return $a->fetchAll();
629     }
630     
631     function changesSince($object,$since)
632     {
633         $q = DB_DataObject::factory('mtrack_change');
634         $q->onid = $object->id;
635         $q->ontable = $object->tableName();
636         $q->whereAdd("changedate > '$since'");
637         $q->orderBy('changedate ASC');
638         $q->autoJoin();
639         // we are going to end up with a list of objects that have changed.
640         // eg. a ticket or a repo..
641         
642         return  $q->fetchAll();
643         
644         
645     }
646     
647     
648     function cachedAuditToString()
649     {
650         // move these to 
651         $body = array();
652         $ar = $this->cachedAudit();
653         foreach($ar as $audit) {
654             $add = $audit->toAuditString($this);
655             if ($add === false) {
656                 continue;
657             }
658             $body[] = $add ;
659                   
660         }
661         return implode("\n",$body);
662     }
663     
664     function toRooArray()
665     {
666         $ret = $this->toArray();
667         $ret['audit'] = $this->cachedAuditToJSONArray();
668         $ret['commit']  = $this->relatedCommits();
669          
670         return $ret;
671         
672     }
673     
674     function beforeInsert($req, $roo)
675     {
676         // originally this was blocked - we are going to try and use it now???
677         if (empty($roo->authUser)) {
678             $roo->jerr("Invalid user inserting");
679         }
680         $this->person_id = $roo->authUser->id;
681         
682         
683         $obj = $this->objectCached();
684          
685         if (!$obj || !$obj->checkPerm('E', $roo->authUser)) {
686             $roo->jerr("Invalid object / permission denied");
687         }
688         
689         $this->changedate = $this->sqlValue('NOW()');
690         
691     }
692     function beforeUpdate($old,$req,$roo)
693     {
694         $roo->jerr("update not allowed by user interface.");
695         
696         
697     }
698     
699     function changedate($format)
700     {
701         return date($format, strtotime($this->changedate));
702     }
703     function postListFilter($data, $authUser, $q)
704     {
705         if (empty($q['ontable']) || empty($q['onid']) || $q['ontable'] != 'mtrack_ticket') {
706             return $data;
707         }
708         //DB_DataObject::debugLevel(1);
709         // look up in the accounting system what time was spent on the ticket..
710         $ie = DB_DataObject::factory('cash_invoice_entry');
711         $ie->ticket_id = $q['onid'];
712         $ie->orderBy('entered_dt ASC'); // doesnt matter really - we will sort it..
713         $ie->autoJoin();
714         $ie->selectAdd();
715         $ie->selectAdd("
716             cash_invoice_entry.id * -1 as id,
717             staff_id as person_id,
718             join_staff_id_id.name as person_id_name,
719             entered_dt as changedate,
720             'TIMESHEET' as cgtype ,
721             CONCAT(qtyvalue , ' Hours worked: ', cash_invoice_entry.description) as reason,
722             '' as rev,
723             '' as audit
724         ");
725         $hours = $ie->fetchAll(false,false,'toArray');
726         
727         $ret =  array_merge($data , $hours);
728         
729         usort($ret, function ($a,$b) use($q)  {
730             $aa = $a['changedate'];
731             $bb =  $b['changedate'];
732             if ($aa == $bb) {
733                 return 0;
734             }
735             if ($q['dir'] == 'ASC') {
736                 return strtotime($aa) < strtotime($bb) ? -1 : 1;
737             } else {
738                 return strtotime($aa) > strtotime($bb) ? -1 : 1;
739             }
740         });
741         
742         return $ret;
743         
744
745         
746         
747     }
748
749
750     
751 }