title: Vqmod improve error logging, by adding the parent file name the error is referring too
body: <p>A default error logging using vqmod is as follows:</p>
  
  <pre><code>---------- Date: 2012-10-09 19:46:06 ~ IP : 127.0.0.1 ----------
  REQUEST URI : /oc/
  MOD DETAILS:
     modFile   : C:\wamp\www\oc\vqmod\xml\templace.xml
     id        : Template
     version   : 1.5.2 - 1.5.2.1
     vqmver    : 1.0.8
     author    : templace.com
  SEARCH NOT FOUND (ABORTING MOD): require_once(foo . 'library/template.php');
  
  ----------------------------------------------------------------------
  </code></pre>
  
  <p>Example vqmod causing the error</p>
  
  <pre><code>&lt;modification&gt;
      &lt;id&gt;Templace&lt;/id&gt;
      &lt;version&gt;1.5.2 - 1.5.2.1&lt;/version&gt;
      &lt;author&gt;templace.com&lt;/author&gt;   
      &lt;vqmver&gt;1.0.8&lt;/vqmver&gt;
  
      &lt;file name="system/startup.php"&gt;
          &lt;operation&gt;
              &lt;search position="before"&gt;&lt;![CDATA[
              require_once(foo . 'library/template.php');
              ]]&gt;&lt;/search&gt;
              &lt;add&gt;&lt;![CDATA[
              require_once(DIR_SYSTEM . 'library/templace.php');
              ]]&gt;&lt;/add&gt;
          &lt;/operation&gt;
      &lt;/file&gt;
  &lt;/modification&gt;
  </code></pre>
  
  <p>To resole this issue I would have to open the vqmod file <code>templace.xml</code> and search for the <code>file[name]</code> this error is referring too. </p>
  
  <p><strong>QUESTION:</strong> How could I add the parent <code>file[name]</code> the actual error is referring too?</p>
  
  <p>E.g adding: "system/startup.php" to the error message to make it easier to debug.</p>
  
  <p>vqmod.php</p>
  
  <pre><code>/**
   * VQMod
   * @description Main Object used
   */
  final class VQMod {
      private $_vqversion = '2.1.7';
      private $_modFileList = array();
      private $_mods = array();
      private $_filesModded = array();
      private $_cwd = '';
      private $_doNotMod = array();
      private $_virtualMode = true;
  
      public $useCache = false;
      public $logFilePath = 'vqmod/vqmod.log';
      public $vqCachePath = 'vqmod/vqcache/';
      public $protectedFilelist = 'vqmod/vqprotect.txt';
      public $logging = true;
      public $cacheTime = 5; // local=5secs live=60secs
      public $log;
  
      /**
       * VQMod::__construct()
       *
       * @param bool $path File path to use
       * @param bool $logging Enable/disabled logging
       * @return null
       * @description Startup of VQMod
       */
      public function __construct($path = false, $logging = true) {
          if(!class_exists('DOMDocument')) {
              die('ERROR - YOU NEED DOMDocument INSTALLED TO USE VQMod');
          }
  
          if(!$path){
              $path = dirname(dirname(__FILE__));
          }
          $this-&gt;_setCwd($path);
  
          $this-&gt;logging = (bool) $logging;
          $this-&gt;log = new VQModLog($this);
  
          $this-&gt;_getMods();
          $this-&gt;_loadProtected();
      }
  
      /**
       * VQMod::modCheck()
       *
       * @param string $sourceFile path for file
       * @return string
       * @description Checks if a file has modifications and applies them, returning cache files or the file name
       */
      public function modCheck($sourceFile) {
  
          if(!preg_match('%^([a-z]:)?[\\\\/]%i', $sourceFile)) {
              $sourcePath = $this-&gt;path($sourceFile);
          } else {
              $sourcePath = realpath($sourceFile);
          }
  
          if(!$sourcePath || is_dir($sourcePath) || in_array($sourcePath, $this-&gt;_doNotMod)) {
              return $sourceFile;
          }
  
          $stripped_filename = preg_replace('~^' . preg_quote($this-&gt;getCwd(), '~') . '~', '', $sourcePath);
          $cacheFile = $this-&gt;_cacheName($stripped_filename);
  
          if($this-&gt;useCache &amp;&amp; file_exists($cacheFile)) {
              //return $cacheFile; // useCache being Deprecated in favor of cacheTime
          }
  
          if(isset($this-&gt;_filesModded[$sourcePath])) {
              return $this-&gt;_filesModded[$sourcePath]['cached'] ? $cacheFile : $sourceFile;
          }
  
          $changed = false;
          $fileHash = sha1_file($sourcePath);
          $fileData = file_get_contents($sourcePath);
  
          foreach($this-&gt;_mods as $modObject) {
              foreach($modObject-&gt;mods as $path =&gt; $mods) {
                  if($this-&gt;_checkMatch($path, $sourcePath)) {
                      $modObject-&gt;applyMod($mods, $fileData);
                  }
              }
          }
  
          // START QPHORIA CACHELOCK CODE
          //
          if (sha1($fileData) != $fileHash) {
              $writePath = $cacheFile;
              $cacheLock = false;
              if(file_exists($writePath) &amp;&amp; ((filemtime($writePath) + (float)$this-&gt;cacheTime) &gt;= time())) {
                  $cacheLock = true;
                  $changed = true;
              }
              if(!$cacheLock &amp;&amp; (!file_exists($writePath) || is_writable($writePath))) {
                  file_put_contents($writePath, $fileData);
                  $changed = true;
              } else {
                  //file_put_contents('./cachelock.txt', "$writePath \r\n", FILE_APPEND); // debugging only.
              }
              //file_put_contents('./cachetotal.txt', "$writePath \r\n", FILE_APPEND);
          } // END QPHORIA CACHELOCK CODE
  
          /* Original Code
          if(sha1($fileData) != $fileHash) {
              $writePath = $this-&gt;_virtualMode ?  $cacheFile : $sourcePath;
              if(!file_exists($writePath) || is_writable($writePath)) {
                  file_put_contents($writePath, $fileData);
                  $changed = true;
              }
          }*/
  
          $this-&gt;_filesModded[$sourcePath] = array('cached' =&gt; $changed);
          return $changed ? $writePath : $sourcePath;
      }
  
      /**
       * VQMod::path()
       *
       * @param string $path File path
       * @param bool $skip_real If true path is full not relative
       * @return bool, string
       * @description Returns the full true path of a file if it exists, otherwise false
       */
      public function path($path, $skip_real = false) {
          $tmp = $this-&gt;_cwd . $path;
          $realpath = $skip_real ? $tmp : realpath($tmp);
          if(!$realpath) {
              return false;
          }
          if(is_dir($realpath)) {
              $realpath = rtrim($realpath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
          }
          return $realpath;
      }
  
      /**
       * VQMod::getCwd()
       *
       * @return string
       * @description Returns current working directory
       */
      public function getCwd() {
          return $this-&gt;_cwd;
      }
  
      /**
       * VQMod::_getMods()
       *
       * @return null
       * @description Gets list of XML files in vqmod xml folder for processing
       */
      private function _getMods() {
  
          $this-&gt;_modFileList = glob($this-&gt;path('vqmod/xml/') . '*.xml');
  
          if($this-&gt;_modFileList) {
              $this-&gt;_parseMods();
          } else {
              $this-&gt;log-&gt;write('NO MODS IN USE');
          }
      }
  
      /**
       * VQMod::_parseMods()
       *
       * @return null
       * @description Loops through xml files and attempts to load them as VQModObject's
       */
      private function _parseMods() {
  
          $dom = new DOMDocument('1.0', 'UTF-8');
          foreach($this-&gt;_modFileList as $modFileKey =&gt; $modFile) {
              if(file_exists($modFile)) {
                  if(@$dom-&gt;load($modFile)) {
                      $mod = $dom-&gt;getElementsByTagName('modification')-&gt;item(0);
                      $this-&gt;_mods[] = new VQModObject($mod, $modFile, $this);
                  } else {
                      $this-&gt;log-&gt;write('DOM UNABLE TO LOAD: ' . $modFile);
                  }
              } else {
                  $this-&gt;log-&gt;write('FILE NOT FOUND: ' . $modFile);
              }
          }
      }
  
      /**
       * VQMod::_loadProtected()
       *
       * @return null
       * @description Loads protected list and adds them to _doNotMod array
       */
      private function _loadProtected() {
          $file = $this-&gt;path($this-&gt;protectedFilelist);
          if($file &amp;&amp; is_file($file)) {
              $protected = file_get_contents($file);
              if(!empty($protected)) {
                  $protected = preg_replace('~\r?\n~', "\n", $protected);
                  $paths = explode("\n", $protected);
                  foreach($paths as $path) {
                      $fullPath = $this-&gt;path($path);
                      if($fullPath &amp;&amp; !in_array($fullPath, $this-&gt;_doNotMod)) {
                          $this-&gt;_doNotMod[] = $fullPath;
                      }
                  }
              }
          }
      }
  
      /**
       * VQMod::_cacheName()
       *
       * @param string $file Filename to be converted to cache filename
       * @return string
       * @description Returns cache file name for a path
       */
      private function _cacheName($file) {
          return $this-&gt;path($this-&gt;vqCachePath) . 'vq2-' . preg_replace('~[/\\\\]+~', '_', $file);
      }
  
      /**
       * VQMod::_setCwd()
       *
       * @param string $path Path to be used as current working directory
       * @return null
       * @description Sets the current working directory variable
       */
      private function _setCwd($path) {
          $realpath = realpath($path);
          if(!$realpath) {
              die('COULDNT RESOLVE CWD REALPATH');
          }
          $this-&gt;_cwd = rtrim($realpath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
      }
  
      /**
       * VQMod::_checkMatch()
       *
       * @param string $modFilePath Modification path from a &lt;file&gt; node
       * @param string $checkFilePath File path
       * @return bool
       * @description Checks a modification path against a file path
       */
      private function _checkMatch($modFilePath, $checkFilePath) {
          $modFilePath = str_replace('\\', '/', $modFilePath);
          $checkFilePath = str_replace('\\', '/', $checkFilePath);
  
          $modFilePath = preg_replace('/([^*]+)/e', 'preg_quote("$1", "~")', $modFilePath);
          $modFilePath = str_replace('*', '[^/]*', $modFilePath);
          $return = (bool) preg_match('~^' . $modFilePath . '$~', $checkFilePath);
          return $return;
  
      }
  }
  
  /**
   * VQModLog
   * @description Object to log information to a file
   */
  class VQModLog {
      private $_sep;
      private $_vqmod;
      private $_defhash = 'da39a3ee5e6b4b0d3255bfef95601890afd80709';
      private $_logs = array();
  
      /**
       * VQModLog::__construct()
       *
       * @param VQMod $vqmod VQMod main class as reference
       * @return null
       * @description Object instantiation method
       */
      public function __construct(VQMod $vqmod) {
          $this-&gt;_vqmod = $vqmod;
          $this-&gt;_sep = str_repeat('-', 70);
      }
  
      /**
       * VQModLog::__destruct()
       *
       * @return null
       * @description Logs any messages to the log file just before object is destroyed
       */
      public function __destruct() {
          if(empty($this-&gt;_logs) || $this-&gt;_vqmod-&gt;logging == false) {
              return;
          }
  
          $txt = array();
  
          $txt[] = str_repeat('-', 10) . ' Date: ' . date('Y-m-d H:i:s') . ' ~ IP : ' . (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'N/A') . ' ' . str_repeat('-', 10);
          $txt[] = 'REQUEST URI : ' . $_SERVER['REQUEST_URI'];
  
          foreach($this-&gt;_logs as $count =&gt; $log) {
              if($log['obj']) {
                  $vars = get_object_vars($log['obj']);
                  $txt[] = 'MOD DETAILS:';
                  foreach($vars as $k =&gt; $v) {
                      if(is_string($v)) {
                          $txt[] = '   ' . str_pad($k, 10, ' ', STR_PAD_RIGHT) . ': ' . $v;
                      }
                  }
  
              }
  
              foreach($log['log'] as $msg) {
                  $txt[] = $msg;
              }
  
              if ($count &gt; count($this-&gt;_logs)-1) {
                  $txt[] = '';
              }
          }
  
          $txt[] = $this-&gt;_sep;
          $txt[] = str_repeat(PHP_EOL, 2);
  
          $logPath = $this-&gt;_vqmod-&gt;path($this-&gt;_vqmod-&gt;logFilePath, true);
          if(!file_exists($logPath)) {
              $res = file_put_contents($logPath, '');
              if($res === false) {
                  die('COULD NOT WRITE TO LOG FILE');
              }
          }
  
          file_put_contents($logPath, implode(PHP_EOL, $txt), FILE_APPEND);
      }
  
      /**
       * VQModLog::write()
       *
       * @param string $data Text to be added to log file
       * @param VQModObject $obj Modification the error belongs to
       * @return null
       * @description Adds error to log object ready to be output
       */
      public function write($data, VQModObject $obj = NULL) {
          if($obj) {
              $hash = sha1($obj-&gt;id);
          } else {
              $hash = $this-&gt;_defhash;
          }
  
          if(empty($this-&gt;_logs[$hash])) {
              $this-&gt;_logs[$hash] = array(
                  'obj' =&gt; $obj,
                  'log' =&gt; array()
              );
          }
  
          $this-&gt;_logs[$hash]['log'][] = $data;
  
      }
  }
  
  /**
   * VQModObject
   * @description Object for the &lt;modification&gt; that orchestrates each applied modification
   */
  class VQModObject {
      public $modFile = '';
      public $id = '';
      public $version = '';
      public $vqmver = '';
      public $author = '';
      public $mods = array();
  
      private $_vqmod;
      private $_skip = false;
  
      /**
       * VQModObject::__construct()
       *
       * @param DOMNode $node &lt;modification&gt; node
       * @param string $modFile File modification is from
       * @param VQMod $vqmod VQMod object as reference
       * @return null
       * @description Loads modification meta information
       */
      public function __construct(DOMNode $node, $modFile, VQmod $vqmod) {
          if($node-&gt;hasChildNodes()) {
              foreach($node-&gt;childNodes as $child) {
                  $name = (string) $child-&gt;nodeName;
                  if(isset($this-&gt;$name)) {
                      $this-&gt;$name = (string) $child-&gt;nodeValue;
                  }
              }
          }
  
          $this-&gt;modFile = $modFile;
          $this-&gt;_vqmod = $vqmod;
          $this-&gt;_parseMods($node);
      }
  
      /**
       * VQModObject::skip()
       *
       * @return bool
       * @description Returns the skip status of a modification
       */
      public function skip() {
          return $this-&gt;_skip;
      }
  
      /**
       * VQModObject::applyMod()
       *
       * @param array $mods Array of search add nodes
       * @param string $data File contents to be altered
       * @return null
       * @description Applies all modifications to the text data
       */
      public function applyMod($mods, &amp;$data) {
          if($this-&gt;_skip) return;
          $tmp = $data;
  
          foreach($mods as $mod) {
              $indexCount = 0;
              $tmp = $this-&gt;_explodeData($tmp);
              $lineMax = count($tmp) - 1;
  
              switch($mod['search']-&gt;position) {
                  case 'top':
                  $tmp[$mod['search']-&gt;offset] =  $mod['add']-&gt;getContent() . $tmp[$mod['search']-&gt;offset];
                  break;
  
                  case 'bottom':
                  $offset = $lineMax - $mod['search']-&gt;offset;
                  if($offset &lt; 0){
                      $tmp[-1] = $mod['add']-&gt;getContent();
                  } else {
                      $tmp[$offset] .= $mod['add']-&gt;getContent();
                  }
                  break;
  
                  case 'all':
                  $tmp = array($mod['add']-&gt;getContent());
                  break;
  
                  default:
  
                  $changed = false;
                  foreach($tmp as $lineNum =&gt; $line) {
                      if($mod['search']-&gt;regex == 'true') {
                          $pos = @preg_match($mod['search']-&gt;getContent(), $line);
                          if($pos === false) {
                              if($mod['error'] == 'log' || $mod['error'] == 'abort' ) {
                                  $this-&gt;_vqmod-&gt;log-&gt;write('INVALID REGEX ERROR - ' . $mod['search']-&gt;getContent(), $this);
                              }
                              continue 2;
                          } elseif($pos == 0) {
                              $pos = false;
                          }
                      } else {
                          $pos = strpos($line, $mod['search']-&gt;getContent());
                      }
  
                      if($pos !== false) {
                          $indexCount++;
                          $changed = true;
  
                          if(!$mod['search']-&gt;indexes() || ($mod['search']-&gt;indexes() &amp;&amp; in_array($indexCount, $mod['search']-&gt;indexes()))) {
  
                              switch($mod['search']-&gt;position) {
                                  case 'before':
                                  $offset = ($lineNum - $mod['search']-&gt;offset &lt; 0) ? -1 : $lineNum - $mod['search']-&gt;offset;
                                  $tmp[$offset] = empty($tmp[$offset]) ? $mod['add']-&gt;getContent() : $mod['add']-&gt;getContent() . "\n" . $tmp[$offset];
                                  break;
  
                                  case 'after':
                                  $offset = ($lineNum + $mod['search']-&gt;offset &gt; $lineMax) ? $lineMax : $lineNum + $mod['search']-&gt;offset;
                                  $tmp[$offset] = $tmp[$offset] . "\n" . $mod['add']-&gt;getContent();
                                  break;
  
                                  default:
                                  if(!empty($mod['search']-&gt;offset)) {
                                      for($i = 1; $i &lt;= $mod['search']-&gt;offset; $i++) {
                                          if(isset($tmp[$lineNum + $i])) {
                                              $tmp[$lineNum + $i] = '';
                                          }
                                      }
                                  }
  
                                  if($mod['search']-&gt;regex == 'true') {
                                      $tmp[$lineNum] = preg_replace($mod['search']-&gt;getContent(), $mod['add']-&gt;getContent(), $line);
                                  } else {
                                      $tmp[$lineNum] = str_replace($mod['search']-&gt;getContent(), $mod['add']-&gt;getContent(), $line);
                                  }
                                  break;
                              }
                          }
                      }
                  }
  
                  if(!$changed) {
                      $skip = ($mod['error'] == 'skip' || $mod['error'] == 'log') ? ' (SKIPPED)' : ' (ABORTING MOD)';
  
                      if($mod['error'] == 'log' || $mod['error'] == 'abort') {
                          $this-&gt;_vqmod-&gt;log-&gt;write('SEARCH NOT FOUND' . $skip . ': ' . $mod['search']-&gt;getContent(), $this);
                      }
  
                      if($mod['error'] == 'abort') {
                          $this-&gt;_skip = true;
                          return;
                      }
  
                  }
  
                  break;
              }
              ksort($tmp);
              $tmp = $this-&gt;_implodeData($tmp);
          }
  
          $data = $tmp;
      }
  
      /**
       * VQModObject::_parseMods()
       *
       * @param DOMNode $node &lt;modification&gt; node to be parsed
       * @return null
       * @description Parses modifications in preparation for the applyMod method to work
       */
      private function _parseMods(DOMNode $node){
          $files = $node-&gt;getElementsByTagName('file');
  
          foreach($files as $file) {
              $fileToMod = $file-&gt;getAttribute('name');
              $error = ($file-&gt;hasAttribute('error')) ? $file-&gt;getAttribute('error') : 'log';
              $fullPath = $this-&gt;_vqmod-&gt;path($fileToMod);
  
              if(!$fullPath){
                  if(strpos($fileToMod, '*') !== false) {
                      $fullPath = $this-&gt;_vqmod-&gt;getCwd() . $fileToMod;
                  } else {
                      if ($error == 'log' || $error == 'abort') {
                          $skip = ($error == 'log') ? ' (SKIPPED)' : ' (ABORTING MOD)';
                          $this-&gt;_vqmod-&gt;log-&gt;write('Could not resolve path for [' . $fileToMod . ']' . $skip, $this);
                      }
  
                      if ($error == 'log' || $error == 'skip') {
                          continue;
                      } elseif ($error == 'abort') {
                          return false;
                      }
                  }
              }
  
              $operations = $file-&gt;getElementsByTagName('operation');
  
              foreach($operations as $operation) {
  
                  $error = ($operation-&gt;hasAttribute('error')) ? $operation-&gt;getAttribute('error') : 'abort';
  
                  $this-&gt;mods[$fullPath][] = array(
                      'search'        =&gt; new VQSearchNode($operation-&gt;getElementsByTagName('search')-&gt;item(0)),
                      'add'           =&gt; new VQAddNode($operation-&gt;getElementsByTagName('add')-&gt;item(0)),
                      'error'         =&gt; $error
                  );
              }
          }
      }
  
      /**
       * VQModObject::_explodeData()
       *
       * @param string $data File contents
       * @return string
       * @description Splits a file into an array of individual lines
       */
      private function _explodeData($data) {
          return explode("\n", $data);
      }
  
      /**
       * VQModObject::_implodeData()
       *
       * @param array $data Array of lines
       * @return string
       * @description Joins an array of lines back into a text file
       */
      private function _implodeData($data) {
          return implode("\n", $data);
      }
  }
  
  /**
   * VQNode
   * @description Basic node object blueprint
   */
  class VQNode {
      public $trim = 'false';
  
      private $_content = '';
  
      /**
       * VQNode::__construct()
       *
       * @param DOMNode $node Search/add node
       * @return null
       * @description Parses the node attributes and sets the node property
       */
      public function  __construct(DOMNode $node) {
          $this-&gt;_content = $node-&gt;nodeValue;
  
          if($node-&gt;hasAttributes()) {
              foreach($node-&gt;attributes as $attr) {
                  $name = $attr-&gt;nodeName;
                  if(isset($this-&gt;$name)) {
                      $this-&gt;$name = $attr-&gt;nodeValue;
                  }
              }
          }
      }
  
      /**
       * VQNode::getContent()
       *
       * @return string
       * @description Returns the content, trimmed if applicable
       */
      public function getContent() {
          $content = ($this-&gt;trim == 'true') ? trim($this-&gt;_content) : $this-&gt;_content;
          return $content;
      }
  }
  
  /**
   * VQSearchNode
   * @description Object for the &lt;search&gt; xml tags
   */
  class VQSearchNode extends VQNode {
      public $position = 'replace';
      public $offset = 0;
      public $index = 'false';
      public $regex = 'false';
      public $trim = 'true';
  
      /**
       * VQSearchNode::indexes()
       *
       * @return bool, array
       * @description Returns the index values to use the search on, or false if none
       */
      public function indexes() {
          if($this-&gt;index == 'false') {
              return false;
          }
          $tmp = explode(',', $this-&gt;index);
          foreach($tmp as $k =&gt; $v) {
              if(!is_int($v)) {
                  unset($k);
              }
          }
          $tmp = array_unique($tmp);
          return empty($tmp) ? false : $tmp;
      }
  }
  
  /**
   * VQAddNode
   * @description Object for the &lt;add&gt; xml tags
   */
  class VQAddNode extends VQNode {
  }
  </code></pre>
  
  <p>Also couple of other ideas to make debugging even easier:</p>
  
  <ol>
  <li><p>List any other vqmod files which have previously edited this same file. 
  This is another common issue where I find when two extensions are editing the same file and the latter is causing the error but it would be useful to know about any other vqmods editing the same file. Yes I suppose I could add <code>error="skip"</code> to everything but dont think this is the best approach to just hide all of the errors, the user should be made aware there is an error... </p></li>
  <li><p>"Suggested Fix", maybe some smart way you can test what type of error it is. 
  Contradict what I said above but even at its most basic form you could suggest hiding the error if its not essential. So that anybody can read it and understand how it fix it.
  E.g</p>
  
  <pre><code>OPEN: vqmod/xml/templace.xml (line:23)
  FIND: &lt;operation&gt;
  REPLACE &lt;operation error="skip"&gt;
  </code></pre></li>
  <li><p>Adding the line number in the XML file the error is coming from. It would be lovely not having to search all of the time and could quickly go to the line number in the vqmod</p></li>
  </ol>