Subversion Repositories computer_asset_manager_v1

Rev

Rev 78 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

<?php

   /*
    * Kludge script that reads a tab delimited text file and generates the SQL that will be used to insert the values
    * into CAMP attributes table.
    *
    * It has a lot of shortcuts, such as automatically creating new attribute keys if they don't exist and assuming
    * the device already does exist and is unique.
    */

   function tabDelimToArray($contents, $delimiter = "\t" ) {
      $rows = array();
      $headers = explode( $delimiter, array_shift( $contents ) );
      for  ( $line = 0; $line < count( $contents ); $line++ ) {
         if ( $contents[$line] ) {
            $thisLine = explode( $delimiter, $contents[$line] );
            $thisLine = preg_replace( '/^\s+/', '', $thisLine );
            $thisLine = preg_replace( '/\s+$/', '', $thisLine );
            $columns = array();
            for ( $i = 0; $i < count( $headers ); $i++ ) {
               $columns[$headers[$i]] = $thisLine[$i];
            } // for
            $rows[] = $columns;
         } // if
      } // while
      return $rows;
   } // function

   function quoteString ( $str ) { // don't use this for production
      $str = str_replace( "'", "''", $str );
      return "'$str'";
   }

   function nullOrEmpty( $str ) {
      return ( !isset( $str) || trim($str) === '');
   }

   if ( isset( $argv[1] ) ) {
      $filename = $argv[1];
   } else {
      die( "You must tell me what file to process\n" ) ;
   }

   print "$filename\n";
   $data = tabDelimToArray( explode( "\n", file_get_contents( $filename ) ) );
   // get the names of all the units listed
   $keys = array_diff( array_keys( $data[0] ), array( 'device')  );
   //print_r( $keys ); die;
   $output = array();
   for ( $i = 0; $i < count($data); $i++ ) {
      $device = quoteString( $data[$i]['device'] );
      foreach ( $keys as $thisKey ) {
         /*
         print "$thisKey\n";
         print_r( $data[$i][$thisKey] ); die;
         continue;
         */
         if ( ! nullOrEmpty( $data[$i][$thisKey] ) ) {
            $value = quoteString( $data[$i][$thisKey] );
            $keyName = quoteString( $thisKey );
            $output[] = "insert into attrib_device select null,device_id,attrib_id,$value,now(),null from attrib, device where attrib.name = $keyName and device.name = $device";
         } // if
      } // foreach
   } // for
   print implode( ";\n", $output ) . ";\n";
?>