24a27c66b588c392edf17a7dd0d168f96e694e2b
[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      
338         
339         return true;
340         
341         //print_r($this);
342         
343         // audit should contain files changed..
344     }
345     
346     function onInsert($request,$roo) 
347     { 
348         // this will send
349         // for a commit ? - ontable = repos, onid = the repo id...
350         // for a change... ontable - will be the ticked, and onid will be the ticket id..
351         
352         $obj = $this->objectCached();
353         $target = $obj;
354         if ($obj->tableName() == 'mtrack_ticket') {
355             $obj = $obj->project();
356             $target = $obj;
357         } else {
358             $target = empty($this->branch) ? $obj : $obj->branchObject($this->branch);
359         }
360         if ($obj) {
361            
362             $core_watch = DB_DataObject::Factory('core_watch');
363             $core_watch->notify(
364                     $obj->tableName(),
365                     $obj->pid(),
366                     "medium='ENDOFDAYMAIL'",
367                         // end of day..
368                     date('Y-m-d 23:59:59'),
369                     $target->tableName(),
370                     $target->pid()
371             );
372         }    
373     }
374     
375     
376     /*
377     * scans repo history and imports it... ??? does not know about branches yet...
378     */
379     function refreshHistory($repo) 
380     {
381         $c = DB_DataObject::factory('mtrack_changes');
382         $c->object =  $repo->toIdString(); 
383         $c->orderBy('changedate DESC');
384         $c->whereAdd("rev != ''");
385         $last  = '';
386         if ($c->find(true)) {
387             $last = $c->scmid;
388         }
389         // history returns an array of scmEvents... - should actually return an array of this object...
390         $recs = $repo->history('', null, $last ? 'rev' : null, $last ? $last  :null);
391         
392         foreach($recs as $r) { 
393             // see if we have a copy of it already.
394             $c = DB_DataObject::factory('mtrack_change');
395             $c->object =  $repo->toIdString(); 
396             $c->changedate != $r->ctime;
397             $cr  = clone($c);
398             $c->whereAdd("rev != ''");
399             if (!$c->find(true)) {
400                 // not found, create a new one..
401                 $c->insert();
402                 
403             }
404             $cr->rev = $r->rev;
405             $cr->reason = $r->changelog;
406             $cr->who =  $r->changeby;
407             $cr->update();
408             foreach($cr->files as $f) {
409                 // we could do with adding 'X' lines changed on this
410                 $ca = DB_DataObject::factory('change_audit');
411                 $ca->cid = $cr->id;
412                 $ca->fieldname = $cr->object. ':file';
413                 $ca->action = $f->status . ($f->added ? ' +' . $f->added : '') . ($f->removed ? ' -' . $f->removed : '') ;
414                 $ca->value = $f->name;
415                 $ca->insert();
416                 
417             }
418             
419             
420         }
421     
422     }
423      
424
425     function beginChange($object, $reason = '', $when = null)
426     {
427          // $db->beginTransaction();
428          //$this->query('BEGIN');
429         $pg = HTML_FlexyFramework::get()->page;
430         $au  = $pg->authUser;
431
432         $this->person_id = $au->id;
433         $this->ontable      = $object->tableName();                         // string(128)  
434         $this->onid = $object->id; // should use keys( really..)
435         $this->reason = $reason;
436         //$d = date_create("@" . (empty($when)  ? time() : $when), new DateTimeZone('UTC'));
437         $this->changedate =  date('Y-m-d H:i:s'); // everythign at server time..
438                                   //$d->format('Y-m-d\TH:i:s.u\Z');
439         $this->cgtype = $reason == 'Changed' ? 'CHANGE' : 'COMMENT';
440         $this->insert();
441         $this->onInsert(array(), $pg);
442          
443     }
444
445     function commit()
446     {
447         if ($this->count == 0) {
448             //      throw new Exception("no changes were made as part of this changeset");
449         }
450         if (self::$use_txn) {
451             //$this->query('COMMIT');
452           //$db->commit();
453         }
454     }
455     
456     function addentry($fieldname, $action, $old, $value = null)
457     {
458         
459         // final sanity check..
460         $o = DB_DataObject::factory($this->ontable);
461         $info = $o->tableColumns();
462         $far = explode(':',$fieldname);
463         $col = array_pop($far);
464         if (!isset($info[$col])) {
465             return 0;
466         }
467         
468         
469         if ($info[$col] & (defined('DB_DATAOBJECT_INT') ? DB_DATAOBJECT_INT : PDO_DataObject::INT)) {
470             if (((int) $old)  == ((int) $value)) {
471                 return 0;
472             }
473         }
474         
475         
476         
477         $ca = DB_DataObject::factory('mtrack_change_audit');
478         $ca->setFrom(array(
479             'change_id'     => $this->id,
480             'fieldname'     => $fieldname,
481             'action'        => $action,
482             'oldvalue'  => $old,
483             'value'     => $value
484         ));
485         $ca->insert();
486         //print_r($ca);
487         
488         return 1;
489     }
490    
491     /**
492      * usage
493      *      add('xxx:yyy:zzz' , new , old)
494      *      add('xxx:yyy', new_do, old_do) // two dataobjects.. (will diff the two..
495      *      add($new_do, $old_do) 
496      */
497     
498     
499     function add($fieldname, $new, $old = false)
500     {
501         //print_r(array("ADD", $fieldname, $new, $old));
502         //echo "check: $fieldname ($old) => ($new)\n"; 
503         $ret = 0;
504         if (is_object($fieldname)) {
505             return $this->add($this->ontable.':'. $this->onid , $fieldname, $new );  
506         }
507         if (is_object($new)) {
508             // should check keys() - so it does not log primary key addition.
509             
510             $cols = array_keys($new->tableColumns());
511             $keys  = $new->keys();
512             $links = $new->links();
513             
514             foreach($cols as $k) {
515                 if (in_array($k, $keys)) {
516                     continue;
517                 } 
518                 $alinks = isset($links[$k])  ? explode(':', $links[$k]) : false;
519                 if ($alinks && $this->tablename() == array_shift($alinks)) {
520                     continue;
521                 }
522                 $ret += $this->add($fieldname .':'. $k, $new->{$k}, !$old ? '' :  $old->{$k});
523             }
524             
525             return $ret;
526         }
527      
528         if ($old == $new) {
529             return $ret;
530         }
531         if ($old !== false) {
532             return  $this->addentry($fieldname, 'set', $old, $new);
533              
534         }
535         if ($new === false) {
536             return    $this->addentry($fieldname, 'deleted', $old, $new);
537             
538         }
539         return   $this->addentry($fieldname, 'changed', $old, $new);
540          
541     }
542     
543     
544     
545     
546     
547     var $_audit = false;
548     function cachedAudit()
549     {
550         static $cache = array();
551         
552         if (!isset($cache[$this->id])) {
553             $cache[$this->id]= $this->audit();
554         }
555         return $cache[$this->id];
556     }
557     function cachedAuditToJSONArray()
558     {
559          
560         $ar = $this->cachedAudit();
561         
562        
563         $ret = array();
564         foreach($ar as $a) {
565              
566             $add = $a->toJSONArray($this);
567             if (!$add) {
568                 continue;
569             }
570             
571             $ret[] = $add;
572         }
573         return $ret;
574         
575     }
576      
577     function relatedCommits()
578     {
579         if (empty($this->rev))  {
580             return '';
581         }
582         // occurs on a ticket... when listing...
583         $mc = DB_DataObject::Factory('mtrack_change');
584         $mc->rev = $this->rev;
585         $mc->ontable = 'mtrack_repos';
586         if (!$mc->find(true)) {
587             return '';
588         }
589         // got the repo.. and the commit..
590         
591         $repo = $mc->objectCached();
592          
593         return  $repo->historyToSummary(
594                     $repo->impl()->history('.', 1, 'rev', $this->rev),
595                 $this->changedate
596         );
597         
598         
599         
600         
601     }
602     
603     
604     function audit()
605     {
606         $a = DB_DataObject::Factory('mtrack_change_audit');
607         $a->whereAdd(" 
608            {$a->tableName()}.change_id = {$this->id} OR
609            {$a->tableName()}.ticket_change_id = {$this->id}   
610         ");
611         //       var_dump($a->find());exit;
612         
613         return $a->fetchAll();
614     }
615     
616     function changesSince($object,$since)
617     {
618         $q = DB_DataObject::factory('mtrack_change');
619         $q->onid = $object->id;
620         $q->ontable = $object->tableName();
621         $q->whereAdd("changedate > '$since'");
622         $q->orderBy('changedate ASC');
623         $q->autoJoin();
624         // we are going to end up with a list of objects that have changed.
625         // eg. a ticket or a repo..
626         
627         return  $q->fetchAll();
628         
629         
630     }
631     
632     
633     function cachedAuditToString()
634     {
635         // move these to 
636         $body = array();
637         $ar = $this->cachedAudit();
638         foreach($ar as $audit) {
639             $add = $audit->toAuditString($this);
640             if ($add === false) {
641                 continue;
642             }
643             $body[] = $add ;
644                   
645         }
646         return implode("\n",$body);
647     }
648     
649     function toRooArray()
650     {
651         $ret = $this->toArray();
652         $ret['audit'] = $this->cachedAuditToJSONArray();
653         $ret['commit']  = $this->relatedCommits();
654          
655         return $ret;
656         
657     }
658     
659     function beforeInsert($req, $roo)
660     {
661         // originally this was blocked - we are going to try and use it now???
662         if (empty($roo->authUser)) {
663             $roo->jerr("Invalid user inserting");
664         }
665         $this->person_id = $roo->authUser->id;
666         
667         
668         $obj = $this->objectCached();
669          
670         if (!$obj || !$obj->checkPerm('E', $roo->authUser)) {
671             $roo->jerr("Invalid object / permission denied");
672         }
673         
674         $this->changedate = $this->sqlValue('NOW()');
675         
676     }
677     function beforeUpdate($old,$req,$roo)
678     {
679         $roo->jerr("update not allowed by user interface.");
680         
681         
682     }
683     
684     function changedate($format)
685     {
686         return date($format, strtotime($this->changedate));
687     }
688     function postListFilter($data, $authUser, $q)
689     {
690         if (empty($q['ontable']) || empty($q['onid']) || $q['ontable'] != 'mtrack_ticket') {
691             return $data;
692         }
693         //DB_DataObject::debugLevel(1);
694         // look up in the accounting system what time was spent on the ticket..
695         $ie = DB_DataObject::factory('cash_invoice_entry');
696         $ie->ticket_id = $q['onid'];
697         $ie->orderBy('entered_dt ASC'); // doesnt matter really - we will sort it..
698         $ie->autoJoin();
699         $ie->selectAdd();
700         $ie->selectAdd("
701             cash_invoice_entry.id * -1 as id,
702             staff_id as person_id,
703             join_staff_id_id.name as person_id_name,
704             entered_dt as changedate,
705             'TIMESHEET' as cgtype ,
706             CONCAT(qtyvalue , ' Hours worked: ', cash_invoice_entry.description) as reason,
707             '' as rev,
708             '' as audit
709         ");
710         $hours = $ie->fetchAll(false,false,'toArray');
711         
712         $ret =  array_merge($data , $hours);
713         
714         usort($ret, function ($a,$b) use($q)  {
715             $aa = $a['changedate'];
716             $bb =  $b['changedate'];
717             if ($aa == $bb) {
718                 return 0;
719             }
720             if ($q['dir'] == 'ASC') {
721                 return strtotime($aa) < strtotime($bb) ? -1 : 1;
722             } else {
723                 return strtotime($aa) > strtotime($bb) ? -1 : 1;
724             }
725         });
726         
727         return $ret;
728         
729
730         
731         
732     }
733
734
735     
736 }