Subversion Repositories computer_asset_manager_v1

Rev

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

<?php
   include_once("library.php");
   include_once('reports.php');
   include_once( './database.php' );

   function logIt ( $message ) {
      //return;
      $LOGFILE = '/home/rodolico/www/web/computer_asset_manager_v1/logs/debug.log';
      $fp = fopen( $LOGFILE , 'a');
      fwrite($fp, "$message\n" );
      fclose($fp);
   }

   /*
    * function designed to handle input from a form. If the input is
    * unset, will retrun the $default value.
    * Otherwise, will filter the value based on $filter
    * Some common filters are:
    *    FILTER_SANITIZE_SPECIAL_CHARS - clean up text so no HTML
    *    FILTER_SANITIZE_EMAIL         - email addresses
    *    FILTER_SANITIZE_NUMBER_FLOAT  - floating point numbers
    *    FILTER_SANITIZE_NUMBER_INT    - integers
    *    FILTER_SANITIZE_URL           - A URL
    * http://php.net/manual/en/filter.filters.sanitize.php
    */
   function cleanInput ( $value, $default = '', $filter = FILTER_DEFAULT ) {
      // unset or empty values just get the default
      if ( ! isset( $value ) || strlen( trim( $value ) ) == 0 ) return $default;
      
      return filter_var( trim( $value ), $filter );
   }


   /*
    * function will attempt to make a constant ($value) safe for SQL depending on the type.
    * 
    * if $value is empty, $default is returned, as will happen if any of the
    * conversions (date, datetime, etc...) fail.
    * 
    * First, it will pass it through get_magic_quotes_gpc, 
    * then will run through mysql_real_escape_string
    * 
    * For strings, will encapsulate in quotes
    * Dates will attempt a conversion, then change to YYYY-MM-DD and encapsulate in quotes
    *    if default is the constant now(), will pass that through to MySQL
    * DateTime will perform the same, but change to YYYY-MM-DD HH:MM:SS
    * Integer and Floats are passed through builtins intval and floatval
    * Boolean only checks the first character, a '0', 'f' and 'n' denoting false
    *    all else denoting true. The result is converted based on the variable
    *    $falsetrue, with the first char denoting false and the second denoting true
    */
   function makeSafeSQLConstant ( $value, $type='S', $default='null', $falsetrue='10' ) {
      // return $default on undefined or empty values
      if ( ! isset( $value ) ) return $default;
      if (strlen($value) == 0) return $default;
      // print "Processing $value as $type with default $default<br>\n";
      switch ( strtolower( $type ) ) {
         case 'string' :
         case 's' : 
                  if ( get_magic_quotes_gpc() ) 
                     $value = stripslashes($value);
                  $value = mysql_real_escape_string( $value );
                  $value = strlen( $value ) > 0 ? "'$value'" : $default;
                  break;
         case 'date' :
         case 'd' :
                  if ( $value != 'null' && $value != 'now()' ) {
                     $result = strtotime( $value );
                     $value = ( $result === false ) ? $default : "'" . Date( 'Y-m-d', $result) . "'";
                  }
                  break;
         case 'datetime':
         case 'timestamp':
         case 'dt': 
                  if ( $value != 'null' && $value != 'now()' ) {
                     $result = strtotime( $value );
                     $value = ( $result === false ) ? $default : "'" . Date( 'Y-m-d H:i:s', $result) . "'";
                  }
                  break;
         case 'integer':
         case 'i' :  
                  $value = intval( $value );
                  break;
         case 'float':
         case 'f' :  
                  $value = floatval( $value );
                  break;
         case 'bool':
         case 'boolean':
         case 'b' :  // note, because of the way strpos works, you can not
                     // simply set $value based on the output; you MUST do
                     // as below; specifically check for false, then set the result
                     $value =  strpos( '0fn', strtolower(substr( $value, 0, 1 )) ) === false ? 0 : 1;
                     $value = substr( $falsetrue, $value, 0, 1 );
                     break;
      } // switch
      return $value;
   }

   function lPad( $string, $count, $padChar = '0' ) {
      while ( strlen( $string) < $count ) {
         $string = '0' . $string;
      }
      return $string;
   }
   
   function makeFileName ( $name, $device_id, $client_id, $site_id ) {
      // we are getting an index. There is a small chance we could end up with duplicates, but since the file
      // name will not consist solely of the index, it should not cause a collision.
      $thisIndex = getOneDBValue( "select theValue from _system where group_name= 'Files' and key_name = 'last index'" );
      $thisIndex++;
      doSQL( "update _system set theValue = '$thisIndex' where group_name= 'Files' and key_name = 'last index'" );
      $thisIndex = lPad( $thisIndex, 6 );
      // start building the file name
      $nameOnDisk = $thisIndex . '-';
      if ( $device_id ) {
         $nameOnDisk .= 'd-';
         $nameOnDisk .= getOneDBValue( "select name from device where device_id = $device_id" );
      } elseif ( $site_id ) {
         $nameOnDisk .= 's-';
         $nameOnDisk .= getOneDBValue( "select name from site where site_id = $site_id" );
      } elseif ( $client_id ) {
         $nameOnDisk .= 'c-';
         $nameOnDisk .= getOneDBValue( "select name from client where client_id = $client_id" );
      } else {
         return array( 'valid' => false, 'message' => 'Error: not able to find client/site/device info' );
      }
      logIt( "File name set to $nameOnDisk before processing" );
      // add the extension
      $nameOnDisk .= '.' . pathinfo($name, PATHINFO_EXTENSION);
      logIt( "File name set to $nameOnDisk after adding extension" );
      // and calculate the relative path to be added to the Files root path value
      $nameOnDisk = getRelativePath( $nameOnDisk ) . $nameOnDisk;
      logIt( "File name set to $nameOnDisk after adding rel path" );
      return array( 'valid' => true, 'filename' => $nameOnDisk );
   } // function saveFile
   
   
   /*
    * take the first digits of a file name (which is the index) and turn
    * them into a path, by breaking them into two character directories.
    * Thus, 123456-someFileName.something becomes
    * 12/34/123456-someFileName.something
    * however, this only returns the path part, so it will return
    * 12/34/
    */
   function getRelativePath ( $filename ) {
      // the first part of the file name is the index, which is used to
      // calculate the path, so we'll throw away everything else.
      $filename = explode( '-', $filename )[0];
      while ( strlen( $filename ) > 2 ) {
         $path .= substr( $filename, 0, 2 ) . '/';
         $filename = substr( $filename, 2 );
      }
      return $path;
   }
   
   /*
    * prepends two directory entries stored in _system table to
    * $filename
    */
   function getAbsolutePath ( $filename ) {
      $path = $_SESSION['file system root']
                . '/' . getOneDBValue( "select theValue from _system where group_name = 'Files' and key_name = 'root path'" )
                . '/' . $filename;
      return $path;
   }
      
   /*
    * returns the URL path to a file
    */
   function getURLPath ( $filename ) {
      $path = $_SESSION['html root']
                . '/' . getOneDBValue( "select theValue from _system where group_name = 'Files' and key_name = 'root path'" )
                . '/' . $filename;
      return $path;
   }
   
   
   function makePath ( $filename ) {
      $path =  pathinfo( $filename, PATHINFO_DIRNAME );
      return is_dir( $path ) ? true : mkdir( $path, 0777, true );
   }

   /*
    * Tries to find $value as a mime type
    * if $value is non-zero numeric, looks it up in the table as mime_type_id
    * if a string, checks for mime_type
    * if still not found, looks for extension
    * returns index into file_mime_type, or 0 if not found
    */
   function check_mime_type ( $value ) {
      if ( is_string( $value ) ) {
         $value = makeSafeSQLConstant( $value );
         // check if they passed in a mime type
         $id = getOneDBValue( "select file_mime_type_id from file_mime_type where mime_type = $value" );
         if ( $id ) return $id;
         // well, no, so check if they passed in an extension
         return getOneDBValue( "select file_mime_type_id from file_mime_type where extension = $value" );
      }
      return null;
   }

   function addFile ( $fields ) {
      logIt( "entering addFile with fields set to\n" . print_r( $fields, true ) );
      
      // file_id is not set in any query, so get rid of it
      $file_id = $fields['file_id'];
      unset( $fields['file_id'] );

      // based on device, site or client, two fields are created
      if ( $fields['device_id'] ) {
         $fields['owner_type'] = 'd';
         $fields['owner_id'] = $fields['device_id'];
      } elseif ( $fields['site_id'] ) {
         $fields['owner_type'] = 's';
         $fields['owner_id'] = $fields['site_id'];
      } elseif ( $fields['client_id'] ) {
         $fields['owner_type'] = 'c';
         $fields['owner_id'] = $fields['client_id'];
      }
      // these are not actually part of the database, so trash them
      unset( $fields['client_id'] );
      unset( $fields['site_id'] );
      unset( $fields['device_id'] );
      
      if ( ! isset( $fields['mime_type'] ) ) {
         $extension = pathinfo( $fields['name_on_disk'], PATHINFO_EXTENSION);
         $fields['mime_type'] = getOneDBValue( "select mime_type from file_mime_type where extension = '$extension'" );
      } // if we need to find the mime_type
      foreach ( $fields as $key => $value ) {
         if ( strpos( $key, 'date' ) ) { // field name has date in it
            $fields[$key] = makeSafeSQLConstant( $value, 'd' );
         } else {
            $fields[$key] = makeSafeSQLConstant( $value );
         }
      }
      $fields['file_mime_type_id'] = getOneDBValue( "select file_mime_type_id from file_mime_type where mime_type = $fields[mime_type]" );
      unset( $fields['mime_type'] );
      if ( ! $fields['file_mime_type_id'] ) $fields['file_mime_type_id'] = 'null';
      if ( $file_id  ) { // we are updating an existing record
         $query = array();
         foreach ( $fields as $key => $value ) {
            $query[] = "$key = $value";
         }
         $query = 'update file set ' . implode( ',', $query ) . " where file_id = $file_id";
      } else { // we are adding a new record
         $query = 'insert into file (' . implode( ',', array_keys( $fields ) ) . ') values (' . implode( ',', array_values( $fields ) ) . ')';
      }
      logIt( $query );
      $result = queryDatabaseExtended( $query );
      if ( $result['insert_id'] )
         return array( 'valid' => true, 'message' => "New Record $result[insert_id]" );
      else
         return array( 'valid' => false, 'message' => "Database Error" );
   }
   
   function return_bytes($val) {
       $val = trim($val);
       $last = strtolower($val[strlen($val)-1]);
       switch($last) 
       {
           case 'g':
           $val *= 1024;
           case 'm':
           $val *= 1024;
           case 'k':
           $val *= 1024;
       }
       return $val;
   } // return_bytes
   
   function prettyPrintBytes( $value ) {
      $sizes = array( '', 'kilo', 'mega', 'giga', 'tera' );
      while ( $value > 1024 ) {
         $value /= 1024;
         $index++;
      }
      return intval( $value ) . ' ' . $sizes[$index] . 'bytes';
   }
   
   function maxUploadFileSize () {
       //select maximum upload size
       $max_upload = return_bytes(ini_get('upload_max_filesize'));
       //select post limit
       $max_post = return_bytes(ini_get('post_max_size'));
       //select memory limit
       $memory_limit = return_bytes(ini_get('memory_limit'));
       // return the smallest of them, this defines the real limit
       return prettyPrintBytes( min($max_upload, $max_post, $memory_limit) );
    } // maxUploadFileSize
    
    function getFileUploadError( $error ) {
       $message = '';
       switch ( $error ) {
          case 0 : $message = 'There is no error, the file uploaded with success';
                   break;
          case 1 : $message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                   break;
          case 2 : $message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                   break;
          case 3 : $message = 'The uploaded file was only partially uploaded';
                   break;
          case 4 : $message = 'No file was uploaded';
                   break;
          case 6 : $message = 'Missing a temporary folder';
                   break;
          case 7 : $message = 'Failed to write file to disk.';
                   break;
          case 8 : $message = 'A PHP extension stopped the file upload.';
       }
       return array( 'valid' => $error == 0, 'message' => $message );
    } // getFileUploadError
 
   function uploadFile ( $source, $nameOnDisk ) {
      $saveTo = getAbsolutePath( $nameOnDisk );
      if ( makePath( $saveTo ) ) {
         logIt( "Path Made - $saveTo" );
         logIt( "moving $source to $saveTo" );
         $result['valid'] = move_uploaded_file( $source, $saveTo );
      } else {
         $result = array( 'valid'=>false, 'message' => print_r(error_get_last(), true) );
      } // if move_uploaded_file .. else
      return $result;
   } // uploadFile

?>