function sigHandler($signo)
 {
     if (SQLIImportToken::importIsRunning()) {
         // Note : SIGKILL cannot be caught
         // So try to always send a SIGINT (kill -2) or SIGTERM (kill -15) to request interruption
         switch ($signo) {
             case SIGTERM:
             case SIGINT:
                 SQLIImportLogger::logNotice('Caught SIGTERM while importing. Demanding import interruption (might take a little while)');
                 $factory = SQLIImportFactory::instance();
                 $currentItem = $factory->getCurrentImportItem();
                 $currentItem->setAttribute('status', SQLIImportItem::STATUS_INTERRUPTED);
                 $currentItem->store();
                 break;
         }
     }
 }
    // Check if user has access to handler alteration
    $aLimitation = array('SQLIImport_Type' => $import->attribute('handler'));
    $hasAccess = SQLIImportUtils::hasAccessToLimitation($Module->currentModule(), 'manageimports', $aLimitation);
    if (!$hasAccess) {
        return $Module->handleError(eZError::KERNEL_ACCESS_DENIED, 'kernel');
    }
    switch ($action) {
        case 'cancel':
            // Check if import is already running. Maybe user has not refreshed import list in the admin...
            $status = $import->attribute('status') == SQLIImportItem::STATUS_RUNNING ? SQLIImportItem::STATUS_INTERRUPTED : SQLIImportItem::STATUS_CANCELED;
            SQLIImportLogger::logNotice('User "' . $userLogin . '" (#' . $userID . ') requested cancelation of pending import #' . $importID . ' on ' . date('Y-m-d H:i'), false);
            $import->setAttribute('status', $status);
            $import->store();
            break;
        case 'interrupt':
            SQLIImportLogger::logNotice('User "' . $userLogin . '" (#' . $userID . ') requested interruption of running import #' . $importID . ' on ' . date('Y-m-d H:i'), false);
            $import->setAttribute('status', SQLIImportItem::STATUS_INTERRUPTED);
            $import->store();
            break;
        default:
            throw new SQLIImportBaseException(SQLIImportUtils::translate('extension/sqliimport/error', "Unknown alter import action '%action'", null, array('%action' => $action)));
    }
    $Module->redirectToView('list');
} catch (Exception $e) {
    $errMsg = $e->getMessage();
    SQLIImportLogger::writeError($errMsg);
    $tpl->setVariable('error_message', $errMsg);
    $Result['path'] = array(array('url' => false, 'text' => SQLIImportUtils::translate('extension/sqliimport/error', 'Error')));
    $Result['left_menu'] = 'design:sqliimport/parts/leftmenu.tpl';
    $Result['content'] = $tpl->fetch('design:sqliimport/altererror.tpl');
}
$db = eZDB::instance();
try {
    $user = eZUser::currentUser();
    $userID = $user->attribute('contentobject_id');
    $userLogin = $user->attribute('login');
    $importID = $Params['ImportID'];
    $db->begin();
    $import = SQLIScheduledImport::fetch($importID);
    if (!$import instanceof SQLIScheduledImport) {
        throw new SQLIImportBaseException(SQLIImportUtils::translate('extension/sqliimport/error', "No import item found with ID #%importID", null, array('%importID' => $importID)));
    }
    // Check if user has access to handler alteration
    $aLimitation = array('SQLIImport_Type' => $import->attribute('handler'));
    $hasAccess = SQLIImportUtils::hasAccessToLimitation($Module->currentModule(), 'manageimports', $aLimitation);
    if ($hasAccess) {
        SQLIImportLogger::logNotice('User "' . $userLogin . '" (#' . $userID . ') removed scheduled import #' . $importID . ' on ' . date('Y-m-d H:i'), false);
        $import->remove();
        $db->commit();
        $Module->redirectToView('scheduledlist');
    } else {
        $db->rollback();
        return $Module->handleError(eZError::KERNEL_ACCESS_DENIED, 'kernel');
    }
} catch (Exception $e) {
    $errMsg = $e->getMessage();
    SQLIImportLogger::writeError($errMsg);
    $tpl->setVariable('error_message', $errMsg);
    $Result['path'] = array(array('url' => false, 'text' => SQLIImportUtils::translate('extension/sqliimport/error', 'Error')));
    $Result['left_menu'] = 'design:sqliimport/parts/leftmenu.tpl';
    $Result['content'] = $tpl->fetch('design:sqliimport/altererror.tpl');
}
 /**
  * Starts to run the import
  * @param array( SQLIImportItem ) $aImportItems
  * @throws SQLIImportBaseException
  * @throws ezcConfigurationNoConfigException
  */
 public function runImport(array $aImportItems)
 {
     // First check if an import is already running
     if (SQLIImportToken::importIsRunning()) {
         throw new SQLIImportBaseException('Another import is already running. Aborting...', SQLIImportBaseException::IMPORT_ALREADY_RUNNING);
     }
     $this->token = SQLIImportToken::registerNewImport();
     $this->handlePerformanceSettings();
     if (empty($aImportItems)) {
         // If no source handler is provided, consider processing all source handlers available
         $aImportItems = $this->importINI->variable('ImportSettings', 'AvailableSourceHandlers');
     }
     // Process import items one by one
     for ($i = 0, $iMax = count($aImportItems); $i < $iMax; ++$i) {
         try {
             if (!$aImportItems[$i] instanceof SQLIImportItem) {
                 throw new SQLIImportRuntimeException('Invalid import item !');
             }
             // Update status for import item
             $aImportItems[$i]->setAttribute('status', SQLIImportItem::STATUS_RUNNING);
             $aImportItems[$i]->store();
             $this->currentImportItem = $aImportItems[$i];
             // First check if this handler has all needed configuration
             $handler = $aImportItems[$i]->attribute('handler');
             $handlerSection = $handler . '-HandlerSettings';
             if (!$this->importINI->hasSection($handlerSection)) {
                 // Check INI Section
                 throw new ezcConfigurationNoConfigException('Error : Handler "' . $handler . '" does not have proper config section in sqliimport.ini !');
             }
             if (!$this->importINI->hasVariable($handlerSection, 'ClassName')) {
                 // Check if ClassName is properly defined
                 throw new ezcConfigurationNoConfigException('Error : ClassName not defined for "' . $handler . '" in sqliimport.ini !');
             }
             // Default values
             $handlerClassName = $this->importINI->variable($handlerSection, 'ClassName');
             $handlerEnabled = true;
             $debug = false;
             $defaultParentNodeID = $this->importINI->variable('ImportSettings', 'DefaultParentNodeID');
             $streamTimeout = $this->importINI->variable('ImportSettings', 'StreamTimeout');
             if ($this->importINI->hasVariable($handlerSection, 'Enabled')) {
                 $handlerEnabled = $this->importINI->variable($handlerSection, 'Enabled') === 'true';
             }
             if ($this->importINI->hasVariable($handlerSection, 'Debug')) {
                 $debug = $this->importINI->variable($handlerSection, 'Debug') === 'enabled';
             }
             if ($this->importINI->hasVariable($handlerSection, 'DefaultParentNodeID')) {
                 $localParentNodeID = $this->importINI->variable($handlerSection, 'DefaultParentNodeID');
                 $defaultParentNodeID = is_int($localParentNodeID) ? (int) $localParentNode : $defaultParentNodeID;
             }
             if ($this->importINI->hasVariable($handlerSection, 'StreamTimeout')) {
                 $streamTimeout = (int) $this->importINI->variable($handlerSection, 'StreamTimeout');
             }
             // Check $defaultParentNodeID and throw an exception if not consistent
             $parentNode = eZContentObjectTreeNode::fetch($defaultParentNodeID, false, false);
             if (!$parentNode) {
                 throw new SQLIImportRuntimeException('Error : invalid DefaultParentNodeID ( ' . $defaultParentNodeID . ' )');
             }
             unset($parentNode);
             // Check handler class validity
             if (!class_exists($handlerClassName)) {
                 throw new SQLIImportRuntimeException('Error : invalid handler class "' . $handlerClassName . '". Did you regenerate autolads ?');
             }
             // ####################################
             // ##### IMPORT HANDLER PROCESSING
             // ####################################
             // Instantiate the handler with appropriate options and process it.
             // Handler must implement ISQLIImportHandler and extend SQLIImportAbstractHandler
             $handlerOptions = $aImportItems[$i]->attribute('options');
             $importHandler = new $handlerClassName($handlerOptions);
             if (!$importHandler instanceof ISQLIImportHandler || !$importHandler instanceof SQLIImportAbstractHandler) {
                 throw new SQLIImportRuntimeException('Error : invalid handler "' . $handlerClassName . '". Must implement ISQLIImportHandler and extend SQLIImportAbstractHandler.');
             }
             $importHandler->handlerConfArray = $this->importINI->group($handlerSection);
             $importHandler->initialize();
             // Get process length to calculate advancement percentage to track advancement
             $processLength = $importHandler->getProcessLength();
             $percentageAdvancementStep = 100 / $processLength;
             $handlerName = $importHandler->getHandlerName();
             $handlerIdentifier = $importHandler->getHandlerIdentifier();
             // Progress bar implementation
             $progressBarOptions = array('emptyChar' => ' ', 'barChar' => '=');
             $progressBar = new ezcConsoleProgressbar($this->output, $processLength, $progressBarOptions);
             $progressBar->start();
             $this->cli->warning('Now processing "' . $handlerName . '" handler.');
             $isInterrupted = false;
             while ($row = $importHandler->getNextRow()) {
                 try {
                     $progressBar->advance();
                     $startTime = time();
                     $importHandler->process($row);
                 } catch (Exception $e) {
                     SQLIImportLogger::logError('An error occurred during "' . $handlerIdentifier . '" import process : ' . $e->getMessage());
                 }
                 $aImportItems[$i]->updateProgress($percentageAdvancementStep, $importHandler->getProgressionNotes());
                 // Now calculate process time for this iteration
                 $endTime = time();
                 $diffTime = $endTime - $startTime;
                 $oldProcessTime = $aImportItems[$i]->attribute('process_time');
                 $aImportItems[$i]->setAttribute('process_time', $oldProcessTime + $diffTime);
                 $aImportItems[$i]->store(array('process_time'));
                 // Interruption handling
                 if ($aImportItems[$i]->isInterrupted()) {
                     $this->cli->notice();
                     SQLIImportLogger::logNotice('Interruption has been requested for current import ! Cleaning and aborting process...');
                     $isInterrupted = true;
                     break;
                 }
             }
             $importHandler->cleanup();
             $progressBar->finish();
             $this->cli->notice();
             unset($importHandler);
             if (!$isInterrupted) {
                 $aImportItems[$i]->setAttribute('status', SQLIImportItem::STATUS_COMPLETED);
                 $aImportItems[$i]->setAttribute('percentage', 100);
                 // Force percentage to 100%
                 $aImportItems[$i]->store();
             }
             // ####################################
             // ##### END IMPORT HANDLER PROCESSING
             // ####################################
         } catch (Exception $e) {
             SQLIImportLogger::logError($e->getMessage());
             $aImportItems[$i]->setAttribute('status', SQLIImportItem::STATUS_FAILED);
             $aImportItems[$i]->store();
             if (isset($importHandler)) {
                 $importHandler->cleanup();
                 unset($importHandler);
             }
             continue;
         }
     }
 }
<?php

/**
 * SQLi Import import purge history import view
 * @copyright Copyright (C) 2010 - SQLi Agency. All rights reserved
 * @licence http://www.gnu.org/licenses/gpl-2.0.txt GNU GPLv2
 * @author Jerome Vieilledent
 * @version @@@VERSION@@@
 * @package sqliimport
 */
$Module = $Params['Module'];
$Result = array();
$tpl = SQLIImportUtils::templateInit();
try {
    $user = eZUser::currentUser();
    $userID = $user->attribute('contentobject_id');
    $userLogin = $user->attribute('login');
    SQLIImportLogger::logNotice('User "' . $userLogin . '" (#' . $userID . ') requested import history purge on ' . date('Y-m-d H:i'), false);
    SQLIImportItem::purgeImportHistory();
    $Module->redirectToView('list');
} catch (Exception $e) {
    $errMsg = $e->getMessage();
    SQLIImportLogger::writeError($errMsg);
    $tpl->setVariable('error_message', $errMsg);
    $Result['path'] = array(array('url' => false, 'text' => SQLIImportUtils::translate('extension/sqliimport/error', 'Error')));
    $Result['left_menu'] = 'design:sqliimport/parts/leftmenu.tpl';
    $Result['content'] = $tpl->fetch('design:sqliimport/altererror.tpl');
}