<commit_before><?php
/*=========================================================================
Program:   MIDAS Server
Language:  PHP/HTML/Java/Javascript/SQL
Date:      $Date$
Version:   $Revision$

Copyright (c) Kitware Inc. 28 Corporate Drive. All rights reserved.
Clifton Park, NY, 12065, USA.

See Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.
=========================================================================*/
?>
<?php
/**
 * globally useful utility functions.
 */
class KWUtils
{

  CONST DEFAULT_MKDIR_MODE = 0775;

  /**
   * @method mkDir
   * @TODO what to do with errors in a way that is consistent with error reporting
   * Will create the directory $dir and set the filemode so that the newly
   * created dir is writable by the current user.
   * @return true on success, false otherwise
   */
  public static function mkDir($dir, $mode = self::DEFAULT_MKDIR_MODE)
    {
    if(!file_exists($dir) && !mkdir($dir, $mode, true))
      {
      return false;
      }
    // change file mode
    // even though we are swallowing the error messages, we return false
    // if the operation can't be completed
    if(!is_writeable($dir) || @!chmod($dir, $mode))
      {
      return false;
      }
    return true;
    }

  /**
   * @method public getTempDirectory()
   * get the midas temporary directory
   * @return string
   */
  public static function getTempDirectory()
    {
    return BASE_PATH.'/tmp/misc';
    }


  /**
   * @method createSubDirectories recursively create subdirectories starting at
   * baseDirectory, sequentially creating each of the directories in the
   * subDirectories array, according to the passed in mode.
   * @param $baseDirectory the first directory to create
   * @param $subDirectories an array of directories that will be created in a
   * recursive fashion, each one appending to the last as a deeper subdirectory
   * of baseDirectory
   * @param the mode to create the new directories
   */
  public static function createSubDirectories($baseDirectory, $subDirectories, $mode = self::DEFAULT_MKDIR_MODE)
    {
    if(!file_exists($baseDirectory) )
      {
      throw new Zend_Exception($baseDirectory . ' does not exist');
      }
    $relpath = '';
    foreach($subDirectories as $directory)
      {
      $relpath .= $directory . "/";
      if(!is_dir($baseDirectory . $relpath) && !KwUtils::mkDir($baseDirectory . $relpath, $mode))
        {
        throw new Zend_Exception($baseDirectory . $relpath . ' could not be created');
        }
      }
    return $baseDirectory . $relpath;
    }

  /**
   * @method isWindows()
   * @return True if the current platform is windows
   */
  public static function isWindows()
    {
    return (strtolower(substr(PHP_OS, 0, 3)) == "win");
    }


  /**
   * @method escapeCommand
   * will escape a command respecting the format of the current platform
   * @param $command, the command to be escaped
   * @return the $command, $escaped for the current platform
   * @TODO, how to test this?
   */
  public static function escapeCommand($command )
    {
    // if windows platform, add extra double-quote
    // See http://www.mail-archive.com/<EMAIL>@lists.php.net/msg29874.html
    if(KWUtils::isWindows() )
      {
      $command = '"'.$command.'"';
      }

    return $command;
    }

  /**
   * @method appendStringIfNot will append the string $ext to
   * $subject if it is not already a suffix of $subject
   * @param $subject, the string to be appended to
   * @param $ext, the extension to check for and append
   * @return $subject, will end with the suffix $ext
   */
  public static function appendStringIfNot($subject, $ext)
    {
    if(!(substr($subject, strlen($subject) - strlen($ext)) === $ext)  )
      {
      $subject .= $ext;
      }
    return $subject;
    }

  /**
   * @method exec
   * will execute a command, respecting the format of the current platform.
   * @param $command to be executed, with all arguments, and formatted correctly
   * @param $output, a reference to put the output of the command
   * @param $chdir, the dir to change to for execution, if any
   * @param $return_val, a reference to put the return value of the command
   *  the temporary work dir
   */
  public static function exec($command, &$output = null, $chdir = "", &$return_val = null)
    {
    if(!empty($chdir) && is_dir($chdir))
      {
      if(!chdir($chdir))
        {
        throw new Zend_Exception("Failed to change directory: [".$chdir."]");
        }
      }
    // on Linux need to add redirection to handle stderr
    $redirect_error = KWUtils::isLinux() ? " 2>&1" : "";
    exec(KWUtils::escapeCommand($command) . $redirect_error, $output, $return_val);
    }

<commit_msg>BUG: refs #0068.  exec function was changing cwd, but not channging back.<commit_after><?php
/*=========================================================================
Program:   MIDAS Server
Language:  PHP/HTML/Java/Javascript/SQL
Date:      $Date$
Version:   $Revision$

Copyright (c) Kitware Inc. 28 Corporate Drive. All rights reserved.
Clifton Park, NY, 12065, USA.

See Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.
=========================================================================*/
?>
<?php
/**
 * globally useful utility functions.
 */
class KWUtils
{

  CONST DEFAULT_MKDIR_MODE = 0775;

  /**
   * @method mkDir
   * @TODO what to do with errors in a way that is consistent with error reporting
   * Will create the directory $dir and set the filemode so that the newly
   * created dir is writable by the current user.
   * @return true on success, false otherwise
   */
  public static function mkDir($dir, $mode = self::DEFAULT_MKDIR_MODE)
    {
    if(!file_exists($dir) && !mkdir($dir, $mode, true))
      {
      return false;
      }
    // change file mode
    // even though we are swallowing the error messages, we return false
    // if the operation can't be completed
    if(!is_writeable($dir) || @!chmod($dir, $mode))
      {
      return false;
      }
    return true;
    }

  /**
   * @method public getTempDirectory()
   * get the midas temporary directory
   * @return string
   */
  public static function getTempDirectory()
    {
    return BASE_PATH.'/tmp/misc';
    }


  /**
   * @method createSubDirectories recursively create subdirectories starting at
   * baseDirectory, sequentially creating each of the directories in the
   * subDirectories array, according to the passed in mode.
   * @param $baseDirectory the first directory to create
   * @param $subDirectories an array of directories that will be created in a
   * recursive fashion, each one appending to the last as a deeper subdirectory
   * of baseDirectory
   * @param the mode to create the new directories
   */
  public static function createSubDirectories($baseDirectory, $subDirectories, $mode = self::DEFAULT_MKDIR_MODE)
    {
    if(!file_exists($baseDirectory) )
      {
      throw new Zend_Exception($baseDirectory . ' does not exist');
      }
    $relpath = '';
    foreach($subDirectories as $directory)
      {
      $relpath .= $directory . "/";
      if(!is_dir($baseDirectory . $relpath) && !KwUtils::mkDir($baseDirectory . $relpath, $mode))
        {
        throw new Zend_Exception($baseDirectory . $relpath . ' could not be created');
        }
      }
    return $baseDirectory . $relpath;
    }

  /**
   * @method isWindows()
   * @return True if the current platform is windows
   */
  public static function isWindows()
    {
    return (strtolower(substr(PHP_OS, 0, 3)) == "win");
    }


  /**
   * @method escapeCommand
   * will escape a command respecting the format of the current platform
   * @param $command, the command to be escaped
   * @return the $command, $escaped for the current platform
   * @TODO, how to test this?
   */
  public static function escapeCommand($command )
    {
    // if windows platform, add extra double-quote
    // See http://www.mail-archive.com/internals@lists.php.net/msg29874.html
    if(KWUtils::isWindows() )
      {
      $command = '"'.$command.'"';
      }

    return $command;
    }

  /**
   * @method appendStringIfNot will append the string $ext to
   * $subject if it is not already a suffix of $subject
   * @param $subject, the string to be appended to
   * @param $ext, the extension to check for and append
   * @return $subject, will end with the suffix $ext
   */
  public static function appendStringIfNot($subject, $ext)
    {
    if(!(substr($subject, strlen($subject) - strlen($ext)) === $ext)  )
      {
      $subject .= $ext;
      }
    return $subject;
    }

  /**
   * @method exec
   * will execute a command, respecting the format of the current platform.
   * @param $command to be executed, with all arguments, and formatted correctly
   * @param $output, a reference to put the output of the command
   * @param $chdir, the dir to change to for execution, if any
   * @param $return_val, a reference to put the return value of the command
   *  the temporary work dir
   */
  public static function exec($command, &$output = null, $chdir = "", &$return_val = null)
    {
    $currCwd = getcwd();  
    if(!empty($chdir) && is_dir($chdir))
      {
      if(!chdir($chdir))
        {
        throw new Zend_Exception("Failed to change directory: [".$chdir."]");
        }
      }
    // on Linux need to add redirection to handle stderr
    $redirect_error = KWUtils::isLinux() ? " 2>&1" : "";
    exec(KWUtils::escapeCommand($command) . $redirect_error, $output, $return_val);
    // change back to original directory
    if(!chdir($currCwd))
      {
      throw new Zend_Exception("Failed to change back to original directory: [".$currCwd."]");
      }
    }


{'fraction_non_alphanumeric': 0.13473411670981877, 'fraction_numerical': 0.00438159729137622, 'mean_word_length': 3.0381986328910333, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 1, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2054042', 'n_tokens_mistral': 2928, 'n_tokens_neox': 2806, 'n_words': 1007}