<?php

define('VIOLET_APP_DIR', realpath(dirname(__FILE__).'/..'));

class violetUtil {

  public static function getTempPath($dir = '', $create = false) {
    $tempPath = VIOLET_APP_DIR . '/Temp/' . $dir;
    if ($dir != '' && !file_exists($tempPath)) mkdir($tempPath, 0777, true);;
    return $tempPath;
  }

  public static function Unzip($zipFile, $destFolder) {
    self::execCmd("/usr/bin/unzip -o -d '$destFolder' '$zipFile'");
  }

  public static function createZip($srcFolder, $zipFile) {
    chdir($srcFolder);
    self::execCmd("/usr/bin/zip -R '$zipFile' '*'");
  }

  public static function execCmd($command) {
    $descriptorspec = array(
       0 => array('pipe', 'r'),  // stdin is a pipe that the child will read from
       1 => array('pipe', 'w'),  // stdout is a pipe that the child will write to
    );
    $process = proc_open($command, $descriptorspec, $pipes);
    if (is_resource($process)) {
      while (!feof($pipes[1])) {
        $line = fgets($pipes[1], 1024);
      }
      fclose($pipes[1]);
      proc_close($process);
    }
  }

  public static function cleanDirectory($path) {
    foreach (scandir($path) as $dir) {
      if ($dir=='.' || $dir=='..') continue;
      $dname = $path.'/'.$dir; 
      if (is_dir($dname)) self::cleanDirectory($dname);
      else if (is_file($dname)) unlink($dname);
    }
    rmdir($path);
  }

  public static function copyAllFile($pattern, $src, $dest) {
    foreach (glob($src.$pattern) as $srcFileName) {
      $fileName = substr($srcFileName, strlen($src));
      copy($srcFileName, $dest.$fileName);
    }
  }
}
