Add progress bar for all import process
[civicrm-core.git] / CRM / Import / Parser.php
index 738254e5c1898605fbecd18511c7b351e7923840..b17821f0e4776ca1f76c35d0e55e43e3d5a95183 100644 (file)
@@ -286,6 +286,58 @@ abstract class CRM_Import_Parser {
     return $params;
   }
 
+  /**
+   * @param $statusID
+   * @param bool $startImport
+   *   True when progress bar is to be initiated.
+   * @param $startTimestamp
+   *   Initial timstamp when the import was started.
+   * @param $prevTimestamp
+   *   Previous timestamp when this function was last called.
+   * @param $totalRowCount
+   *   Total number of rows in the import file.
+   *
+   * @return NULL|$currTimestamp
+   */
+  public function progressImport($statusID, $startImport = TRUE, $startTimestamp = NULL, $prevTimestamp = NULL, $totalRowCount = NULL) {
+    $config = CRM_Core_Config::singleton();
+    $statusFile = "{$config->uploadDir}status_{$statusID}.txt";
+
+    if ($startImport) {
+      $status = "<div class='description'>&nbsp; " . ts('No processing status reported yet.') . "</div>";
+      //do not force the browser to display the save dialog, CRM-7640
+      $contents = json_encode(array(0, $status));
+      file_put_contents($statusFile, $contents);
+    }
+    else {
+      $rowCount = isset($this->_rowCount) ? $this->_rowCount : $this->_lineCount;
+      $currTimestamp = time();
+      $totalTime = ($currTimestamp - $startTimestamp);
+      $time = ($currTimestamp - $prevTimestamp);
+      $recordsLeft = $totalRowCount - $rowCount;
+      if ($recordsLeft < 0) {
+        $recordsLeft = 0;
+      }
+      $estimatedTime = ($recordsLeft / 50) * $time;
+      $estMinutes = floor($estimatedTime / 60);
+      $timeFormatted = '';
+      if ($estMinutes > 1) {
+        $timeFormatted = $estMinutes . ' ' . ts('minutes') . ' ';
+        $estimatedTime = $estimatedTime - ($estMinutes * 60);
+      }
+      $timeFormatted .= round($estimatedTime) . ' ' . ts('seconds');
+      $processedPercent = (int ) (($rowCount * 100) / $totalRowCount);
+      $statusMsg = ts('%1 of %2 records - %3 remaining',
+        array(1 => $rowCount, 2 => $totalRowCount, 3 => $timeFormatted)
+      );
+      $status = "<div class=\"description\">&nbsp; <strong>{$statusMsg}</strong></div>";
+      $contents = json_encode(array($processedPercent, $status));
+
+      file_put_contents($statusFile, $contents);
+      return $currTimestamp;
+    }
+  }
+
   /**
    * @return array
    */