<?php
#-------------------------------------------------------------------------
# Module: Newsletter Made Simple
#        (c) to 2008 by Paul Lempkepf
#        (c) 2008 and on by Robert Campbell (calguy1000@cmsmadesimple.org)
#
#  An addon module for CMS Made Simple to provide a flexible
#  mailing list solution.
#
#-------------------------------------------------------------------------
# CMSMS - CMS Made Simple is (c) 2005 by Ted Kulp (wishy@cmsmadesimple.org)
# Visit the CMSMS Homepage at: http://www.cmsmadesimple.org
#
#-------------------------------------------------------------------------
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# However, as a special exception to the GPL, this software is distributed
# as an addon module to CMS Made Simple.  You may not use this software
# in any Non GPL version of CMS Made simple, or in any version of CMS
# Made simple that does not indicate clearly and obviously in its admin
# section that the site was built with CMS Made simple.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Or read it online: http://www.gnu.org/licenses/licenses.html#GPL
#
#-------------------------------------------------------------------------
#END_LICENSE
if( !$gCms ) exit;

$_statusToText = function( $status )
{
    switch( $status ) {
    case NMS_JOBSTATUS_ABORTED:
        return $this->Lang('status_aborted');
    case NMS_JOBSTATUS_ERROR:
        return $this->Lang('status_error');
    case NMS_JOBSTATUS_UNSTARTED:
        return $this->Lang('status_unstarted');
    case NMS_JOBSTATUS_STARTING:
        return $this->Lang('status_starting');
    case NMS_JOBSTATUS_RUNNING:
        return $this->Lang('status_inprogress');
    case NMS_JOBSTATUS_PAUSED:
        return $this->Lang('status_paused');
    case NMS_JOBSTATUS_FINISHED:
        return $this->Lang('status_complete');
    case NMS_JOBSTATUS_FINISHING:
        return $this->Lang('status_finishing');
    default:
        return $this->Lang('status_unknown');
    }
};

$lists = $this->GetListsAsArray();
$error = null;
if( !count($lists) ) {
    $error = $this->Lang('error_nolists');
}

if( !$error ) {
    $query= "SELECT * FROM ".NMS_MESSAGES_TABLE;
    $dbresult = $db->GetRow($query);
    if( !is_array($dbresult) ) $error = $this->Lang('error_nomessages');
}

// Get progress information for all non aborted/completed jobs.
$query = 'SELECT M.jobid,count(M.email) AS total FROM '.NMS_MAILS_TABLE.' M LEFT JOIN '.NMS_JOBS_TABLE.' J ON J.jobid = M.jobid AND J.status IN ('.
  implode(',',array(NMS_JOBSTATUS_STARTING,NMS_JOBSTATUS_RUNNING,NMS_JOBSTATUS_PAUSED)).') GROUP BY M.jobid';
$stats = cge_array::to_hash($db->GetArray($query),'jobid');
$query = 'SELECT M.jobid,count(M.email) AS unsent FROM '.NMS_MAILS_TABLE.' M LEFT JOIN '.NMS_JOBS_TABLE.' J ON J.jobid = M.jobid AND J.status IN ('.
  implode(',',array(NMS_JOBSTATUS_STARTING,NMS_JOBSTATUS_RUNNING,NMS_JOBSTATUS_PAUSED)).') WHERE COALESCE(M.status,\'__empty__\') = \'__empty__\' GROUP BY M.jobid';
$tmp2 = cge_array::to_hash($db->GetArray($query),'jobid');
foreach( array_keys($stats) as $jobid ) {
  if( isset($tmp2[$jobid]) ) {
    $stats[$jobid]['unsent'] = $tmp2[$jobid]['unsent'];
    $total = (int)$stats[$jobid]['total'];
    $sent  = $total - (int)$stats[$jobid]['unsent'];
    $stats[$jobid]['percent'] = (int)($sent / $total * 100.0);
  }
}


// Display the current job queue
// (all entries in message_list grouped by job id I guess
// and allow him to edit jobs
//
$rowarray = array();
$q= "SELECT * FROM ".NMS_JOBS_TABLE." ORDER BY created DESC";
$dbresult= $db->GetArray($q);
foreach( $dbresult as $row ) {
  $onerow= new StdClass();
  $onerow->id= $row['jobid'];
  $onerow->name= $row['title'];
  $onerow->created= $row['created'];
  $onerow->started= $row['started'];
  $onerow->finished= $row['finished'];
  $onerow->status= $_statusToText($row['status']);
  $onerow->progress = '';
  if( isset($stats[$onerow->id]['percent']) ) {
    $onerow->progress = $stats[$onerow->id]['percent'].'%';
  }

  $onerow->actions = array();

  switch ($row['status']) {
  case NMS_JOBSTATUS_ABORTED:
  case NMS_JOBSTATUS_ERROR:
    $onerow->actions[] = $this->CreateImageLink($id, 'admin_reset_job', $returnid,
                                                $this->Lang('reset'), 'refresh.png',
                                                array ('jobid' => $row['jobid'] ), '',
                                                $this->Lang('warn_resetjob') );
    break;

  case NMS_JOBSTATUS_UNSTARTED:
    $onerow->actions[]= $this->CreateImageLink($id, 'start_job', $returnid,
					       $this->Lang('startjob'), 'play.png',
					       array ('jobid' => $row['jobid'] ));
    break;

  case NMS_JOBSTATUS_RUNNING:
    $onerow->actions[]= $this->CreateImageLink($id, 'admin_stop_job', $returnid,
					       $this->Lang('abort'), 'stop.png',
					       array ('jobid' => $row['jobid'] ));
    break;

  case NMS_JOBSTATUS_PAUSED :
      // should not get here
      break;
  }

  // we can only delete a job if the status is not in progress
  if ($row['status'] == NMS_JOBSTATUS_UNSTARTED) {
      $onerow->actions[] = $this->CreateLink($id, 'create_edit_job', $returnid, $themeObject->DisplayImage('icons/system/edit.gif', $this->Lang('edit'), '', '', 'systemicon'),
                                             array('jobid'=>$row['jobid']) );
  }

  if ($row['status'] != NMS_JOBSTATUS_RUNNING ) {
      $onerow->actions[] = $this->CreateLink($id, 'delete_job', $returnid, $themeObject->DisplayImage('icons/system/delete.gif', $this->Lang('delete'), '', '', 'systemicon'),
                                             array('jobid'=>$row['jobid']), $this->Lang('confirmdeletejob'));
  }


  $rowarray[]= $onerow;
}


$smarty->assign('title_warning',$this->Lang('warning'));
$smarty->assign('jobs_warning',$this->Lang('jobs_warning'));
$smarty->assign('idtext', $this->Lang('id'));
$smarty->assign('emailstext', $this->Lang('nummessages'));
$smarty->assign('nametext', $this->Lang('name'));
$smarty->assign('createdtext', $this->Lang('created'));
$smarty->assign('startedtext', $this->Lang('started'));
$smarty->assign('finishedtext', $this->Lang('finished'));
$smarty->assign('actiontext', $this->Lang('action'));
$smarty->assign('statustext', $this->Lang('status'));
$smarty->assign('itemsfound', $this->Lang('jobsfoundtext'));
$smarty->assign('itemcount', count($rowarray));
$smarty->assign('items', $rowarray);
$smarty->assign('createlink',
		$this->CreateImageLink($id,'create_edit_job',$returnid,
				       $this->Lang('title_mod_compose_job'),
				       'lightning_add.png',
				       array(), '', '', false));

if (count($rowarray))
  {
    $smarty->assign('deletecompletedlink',
		    $this->CreateImageLink($id,'delete_completed',$returnid,
					   $this->Lang('deletecompleted'),
					   'lightning_delete.png',
					   array(), '', '', false));
  }
echo $this->ProcessTemplate('jobs.tpl');

#
# EOF
#
?>