masterTemplate = 'ticket_edit.html'; $this->id = $pi ? $pi : (isset($_GET['id']) ? $_GET['id'] : 0); $this->id = $this->id == 'new' ? 0 : $this->id; $this->id = (int) $this->id; // var_dump($this->id); $ret = $this->loadIssue(); $this->initEditForm(); return $ret; } function loadIssue() { // -- load issue.. $this->issue = DB_DataObject::factory('mtrack_ticket'); if ($this->id) { if (!$this->issue->get($this->id)) { throw new Exception("Invalid ticket $this->id"); } if ($this->id && $this->currentProject() != $this->issue->project_id) { throw new Exception("Project and ticket do not match.."); } } //$this->issue->augmentFormFields($this->fieldset()); $this->preview = false; $this->error = array(); if (!$this->id && !$this->hasPerm('MTrack.Issue','A')) { $this->jerr('Permission denied = no rights to create tickets', array('noperm' => true)); //return HTML_FlexyFramework::run('Noperm'); } if ($this->id && ( !$this->hasPerm('MTrack.Issue','E') )) { $this->jerr('Permission denied = no rights to edit tickets', array('noperm' => true)); return HTML_FlexyFramework::run('Noperm'); } // new is always editable..???? $this->editable = true; //$this->id ? //$this->ticket->hasPerm($this->authUser,'E') : true; $this->issue->milestoneURL = $this->baseURL.'/Milestone'; // fix me later.. $this->showEditBar = false; if ($this->editable && $this->id && !$this->preview) { $this->showEditBar = true; } } function post() // handle the post... { $this->id = $_REQUEST['id']; $ret = $this->loadIssue(); if (!empty($ret)) { $this->jerr("load issue failed"); exit; } //echo '
';print_R($this);exit;
        /// $this->preview = isset($_POST['preview']) ? true : false;

        // hopefull get has sorted out permissions..
         
        //    $CS = MTrackChangeset::begin("ticket:X", $comment);
        
        $old = clone($this->issue);
        
        if (!$this->issue->id) {
            // set some defaults.
            $en = DB_DataObject::factory('core_enum');
            $en->setFrom(array('etype' => 'ticketstate', 'name' => 'new'));
            $en->find(true);
            $this->issue->status = $en->id;
        }
        
        
        //  VALIDATE POST!??!
        
        
        if (!empty($_REQUEST['act_now'])) { //=+ adding act now..
            // check project / assigned person / !closed for more than 3 'act_now'
            //DB_DataObject::DebugLevel(1);
            $xx = DB_DataObject::factory('mtrack_ticket');
            $xx->owner_id = $this->issue->owner_id;
            $xx->project_id  = $this->issue->project_id;
            $xx->act_now = 1;
            $xx->resolution_id = 0;
            $xx->whereAdd('id != ' . ((int) $this->issue->id)); // just in case we are double setting...
            if ($xx->count() > 2) {
                $this->jerr("To many act-now tasks assigned to that person, wait until the have completed some");
            }
            
            
            
        }
        
        
        
        
        $this->issue->setFrom($_POST); 
        
        /*
        $kw = $this->issue->getKeywords();
          $kill = array_values($kw);
          foreach (preg_split('/[ \t,]+/', $_POST['keywords']) as $w) {
            if (!strlen($w)) {
              continue;
            }
            $x = array_search($w, $kw);
            if ($x === false) {
              $k = MTrackKeyword::loadByWord($w);
              if ($k === null) {
                $k = new MTrackKeyword;
                $k->keyword = $w;
                $k->save($CS);
              }
              $this->issue->assocKeyword($k);
            } else {
              $w = array_search($w, $kill);
              if ($w !== false) {
                unset($kill[$w]);
              }
            }
          }
          foreach ($kill as $w) {
            $this->issue->dissocKeyword($w);
          }
     
        
          $ms = $this->issue->getMilestones();
          $kill = $ms;
          if (isset($_POST['milestone']) && is_array($_POST['milestone'])) {
            foreach ($_POST['milestone'] as $mid) {
              $this->issue->assocMilestone($mid);
              unset($kill[$mid]);
            }
          }
          foreach ($kill as $mid) {
            $this->issue->dissocMilestone($mid);
          }
        
          $ms = $this->issue->getComponents();
          $kill = $ms;
          if (isset($_POST['component']) && is_array($_POST['component'])) {
            foreach ($_POST['component'] as $mid) {
              $this->issue->assocComponent($mid);
              unset($kill[$mid]);
            }
          }
          foreach ($kill as $mid) {
            $this->issue->dissocComponent($mid);
          }
          
            if (!empty($_POST['comment'])) {
               $this->issue->addComment($_POST['comment']);
            }
          
          $this->issue->addEffort(
            empty($_POST['spent']) ? 0 : $_POST['spent'], 
            empty($_POST['estimate']) ? 0 : $_POST['estimate']
        );
        */
        
        
        
        
        $this->issue->project_id = $this->currentProject();
        
        
        $CS = DB_DataObject::factory('mtrack_change');
        
       
        
        if ($this->issue->id) {
            if (0 === $this->issue->update($old)) {
                $this->jerr("nothing changed?");
            
            }
        } else {
            $this->issue->insert();
            $old = false;
        }
        
        $CS->begin($this->issue, $old ? 'Changed' : 'Created');
        if (!$old) {
            $this->issue->created = $CS->id;
            $this->issue->update();
        }
        $CS->add($this->issue, $old);
        
        // issue ticket... - add watches etc... 
        
        
        
         
        
        $notify_query = "
                (ontable='mtrack_ticket' and onid = {$this->issue->id})
                 OR
                 (ontable='Projects' and onid = {$this->issue->project_id})
                 ";
         $w = DB_DataObject::factory('core_watch');
        $w->ensureNotify(  'mtrack_ticket' ,
                            $this->issue->id,
                            $this->authUser->id,
                        $notify_query
            );
        
        $w->ensureNotify(  'mtrack_ticket' ,
                            $this->issue->id,
                            $this->issue->owner_id,
                        $notify_query
            );
        
         $w->ensureNotify(  'mtrack_ticket' ,
                            $this->issue->id,
                            $this->issue->developer_id,
                        $notify_query
            );
        //DB_DataObject::debugLevel(1);
        // who to notify.. -- originall did not send to issuer..
        // we should probably make this configurable..
       
        $w->notify( 'mtrack_ticket' , $this->issue->id,
                   $notify_query 
                   /*
                 " ( $notify_query )
                    AND
                    (person_id != {$this->authUser->id})   "  */
        );
        
        
        /*
        //$this->issue->save($CS);
        
          if (!count($this->error)) {
            try {
              $this->issue->save($CS);
              
              // make sure everyone is watching it!!!!
                if($this->issue->owner && $this->issue->tid) {
                  // make sure owner is tracking it...
                    MTrackWatch::watch_object('ticket', $this->issue->tid,  $this->issue->owner);
                }
                
                if ($this->id == 'new') {
                    MTrackWatch::watch_object('ticket', $this->issue->tid,  MTrackAuth::whoami());
                }
              
              
              $CS->setObject("ticket:" . $this->issue->tid);
            } catch (Exception $e) {
              $this->error[] = $e->getMessage();
            }
        }
        */
        /*
        if (!count($this->error)) {
            if (!empty($_FILES['attachments'])) {
                require_once 'MTrack/Attachment.php';
                foreach ($_FILES['attachments']['name'] as $fileid => $name) {
                      
                    MTrackAttachment::add("ticket:{$this->issue->tid}",
                        $_FILES['attachments']['tmp_name'][$fileid],
                        $_FILES['attachments']['name'][$fileid],
                        $CS
                    );
                }
            }
        }
        if (!count($this->error) && $this->id != 'new') {
            require_once 'MTrack/Attachment.php';
            MTrackAttachment::process_delete("ticket:{$this->issue->tid}", $CS);
        }

        if (isset($_POST['apply']) && !count($this->error)) {
          $CS->commit();
          header("Location: {$this->baseURL}/Ticket/{$this->issue->nsident}");
          exit;
        }
        */
        $this->jok($this->issue->id);
    }
      
         
    function initEditForm($params = array())
    {
        require_once 'HTML/Template/Flexy/Element.php';
        require_once 'HTML/Template/Flexy/Factory.php';
        
        
        
        foreach(array( 'classification', 'priority', 'severity' ) as $c)  {
            $d = DB_DataObject::factory('core_enum');
            $d->etype = $c;
            $d->orderBy('seqid ASC, name ASC');
            if (!$d->count()) {
                $d->createBaseEntries();
                
            }
            $ar = $d->fetchAll('id','name');
            
            // mid point..
            $ak = array_keys($ar);
            $mid = floor(count($ak) / 2 );
            $def = $ak[$mid];
            
            //var_dump($ar[$def]);
            
            $this->elements[$c.'_id'] = new HTML_Template_Flexy_Element('select');
            $this->elements[$c.'_id']->setOptions($ar);
            if (!$this->id) {
                $this->elements[$c.'_id']->setValue($def);
            }
            
            
        }
       // DB_DAtaObject::DebugLevel(1);
        
        $pd = DB_DataObject::factory('ProjectDirectory');
        $pd->project_id = $this->currentProject();
        $pd->whereAdd("ProjectDirectory.role != ''");
        $pd->joinAdd(DB_DataObject::factory('core_person'), 'LEFT');
        $pd->selectAdd();
        $pd->selectAdd("distinct(Person.id) as id ,  CONCAT(Person.name , '<', Person.email , '>') as name");
        $pd->groupBy('Person.id, Person.name');
        $pd->orderBy('Person.name');
        $users = $pd->fetchAll('id', 'name');
        $users = array('' => '--select--') + $users;
        
        //$users = array();
         
        $this->elements['owner_id'] = new HTML_Template_Flexy_Element('select');
        $this->elements['owner_id']->setOptions($users);
        
        $this->elements['developer_id'] = new HTML_Template_Flexy_Element('select');
        $this->elements['developer_id']->setOptions($users);
        
          
        if ($this->currentProject()) {
            /*
            $d = DB_DataObject::factory('mtrack_project_component');
            $d->project_id = $this->currentProject();
            $d->orderBy('name');
            $d->whereAdd('deleted != 1');
            $this->elements['component[]'] = new HTML_Template_Flexy_Element('select');
            $this->elements['component[]']->setOptions($d->fetchAll('id', 'name'));
            $ar = $this->issue->components();
            $this->elements['component[]']->setValue(array_keys($ar));
            */
            //DB_DataObject::debugLevel(1);
            $d = DB_DataObject::factory('mtrack_milestone');
            $d->project_id = $this->currentProject();
            $d->orderBy('(case when duedate is null then 1 else 0 end), duedate, name');
            $d->whereAdd('completed != 1');
            $d->whereAdd('deleted != 1');
            $this->elements['milestone_id'] = new HTML_Template_Flexy_Element('select');
            $this->elements['milestone_id']->setOptions(array(''=>'--select--') + $d->fetchAll('id', 'name'));
            //$ar = $this->issue->milestone();
            //$this->elements['milestone_id']->setValue(array_keys($ar));
        }
        
        // FIX ME - need to determine who the owner is..
        // for a new issue it's the person who created it.
        // later on it's an assignement???
        
       
        
        if ($this->id) {
            $this->elements = HTML_Template_Flexy_Factory::fromArray($this->issue->toArray(), $this->elements);
        }

        
        // keywords -- in toArray...
        // milestone 
          
          
        

          
    }
   
     
    function eq($a,$b) {
        return $a == $b;
    }
    
}