Subversion Repositories computer_asset_manager_v1

Rev

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

Rev Author Line No. Line
54 rodolico 1
<?php
2
   include_once("library.php");
3
   include_once('reports.php');
4
   include_once( './database.php' );
5
 
63 rodolico 6
   function logIt ( $message ) {
7
      //return;
8
      $LOGFILE = '/home/rodolico/www/web/computer_asset_manager_v1/logs/debug.log';
9
      $fp = fopen( $LOGFILE , 'a');
10
      fwrite($fp, "$message\n" );
11
      fclose($fp);
12
   }
55 rodolico 13
 
14
   /*
15
    * function designed to handle input from a form. If the input is
16
    * unset, will retrun the $default value.
17
    * Otherwise, will filter the value based on $filter
18
    * Some common filters are:
19
    *    FILTER_SANITIZE_SPECIAL_CHARS - clean up text so no HTML
20
    *    FILTER_SANITIZE_EMAIL         - email addresses
21
    *    FILTER_SANITIZE_NUMBER_FLOAT  - floating point numbers
22
    *    FILTER_SANITIZE_NUMBER_INT    - integers
23
    *    FILTER_SANITIZE_URL           - A URL
24
    * http://php.net/manual/en/filter.filters.sanitize.php
25
    */
26
   function cleanInput ( $value, $default = '', $filter = FILTER_DEFAULT ) {
27
      // unset or empty values just get the default
28
      if ( ! isset( $value ) || strlen( trim( $value ) ) == 0 ) return $default;
29
 
30
      return filter_var( trim( $value ), $filter );
31
   }
32
 
33
 
34
   /*
35
    * function will attempt to make a constant ($value) safe for SQL depending on the type.
36
    * 
37
    * if $value is empty, $default is returned, as will happen if any of the
38
    * conversions (date, datetime, etc...) fail.
39
    * 
40
    * First, it will pass it through get_magic_quotes_gpc, 
41
    * then will run through mysql_real_escape_string
42
    * 
43
    * For strings, will encapsulate in quotes
44
    * Dates will attempt a conversion, then change to YYYY-MM-DD and encapsulate in quotes
63 rodolico 45
    *    if default is the constant now(), will pass that through to MySQL
55 rodolico 46
    * DateTime will perform the same, but change to YYYY-MM-DD HH:MM:SS
47
    * Integer and Floats are passed through builtins intval and floatval
48
    * Boolean only checks the first character, a '0', 'f' and 'n' denoting false
49
    *    all else denoting true. The result is converted based on the variable
50
    *    $falsetrue, with the first char denoting false and the second denoting true
51
    */
52
   function makeSafeSQLConstant ( $value, $type='S', $default='null', $falsetrue='10' ) {
53
      // return $default on undefined or empty values
54
      if ( ! isset( $value ) ) return $default;
55
      if (strlen($value) == 0) return $default;
56
      // print "Processing $value as $type with default $default<br>\n";
57
      switch ( strtolower( $type ) ) {
58
         case 'string' :
59
         case 's' : 
60
                  if ( get_magic_quotes_gpc() ) 
61
                     $value = stripslashes($value);
62
                  $value = mysql_real_escape_string( $value );
63
                  $value = strlen( $value ) > 0 ? "'$value'" : $default;
54 rodolico 64
                  break;
55 rodolico 65
         case 'date' :
66
         case 'd' :
63 rodolico 67
                  if ( $value != 'null' && $value != 'now()' ) {
55 rodolico 68
                     $result = strtotime( $value );
69
                     $value = ( $result === false ) ? $default : "'" . Date( 'Y-m-d', $result) . "'";
70
                  }
71
                  break;
72
         case 'datetime':
73
         case 'timestamp':
74
         case 'dt': 
63 rodolico 75
                  if ( $value != 'null' && $value != 'now()' ) {
55 rodolico 76
                     $result = strtotime( $value );
77
                     $value = ( $result === false ) ? $default : "'" . Date( 'Y-m-d H:i:s', $result) . "'";
78
                  }
79
                  break;
80
         case 'integer':
81
         case 'i' :  
82
                  $value = intval( $value );
83
                  break;
84
         case 'float':
85
         case 'f' :  
86
                  $value = floatval( $value );
87
                  break;
88
         case 'bool':
89
         case 'boolean':
90
         case 'b' :  // note, because of the way strpos works, you can not
91
                     // simply set $value based on the output; you MUST do
92
                     // as below; specifically check for false, then set the result
93
                     $value =  strpos( '0fn', strtolower(substr( $value, 0, 1 )) ) === false ? 0 : 1;
94
                     $value = substr( $falsetrue, $value, 0, 1 );
95
                     break;
96
      } // switch
97
      return $value;
98
   }
54 rodolico 99
 
100
   function lPad( $string, $count, $padChar = '0' ) {
101
      while ( strlen( $string) < $count ) {
102
         $string = '0' . $string;
103
      }
104
      return $string;
105
   }
106
 
107
   function makeFileName ( $name, $device_id, $client_id, $site_id ) {
108
      // we are getting an index. There is a small chance we could end up with duplicates, but since the file
109
      // name will not consist solely of the index, it should not cause a collision.
59 rodolico 110
      $thisIndex = getOneDBValue( "select theValue from _system where group_name= 'Files' and key_name = 'last index'" );
54 rodolico 111
      $thisIndex++;
59 rodolico 112
      doSQL( "update _system set theValue = '$thisIndex' where group_name= 'Files' and key_name = 'last index'" );
54 rodolico 113
      $thisIndex = lPad( $thisIndex, 6 );
55 rodolico 114
      // start building the file name
54 rodolico 115
      $nameOnDisk = $thisIndex . '-';
116
      if ( $device_id ) {
117
         $nameOnDisk .= 'd-';
118
         $nameOnDisk .= getOneDBValue( "select name from device where device_id = $device_id" );
119
      } elseif ( $site_id ) {
120
         $nameOnDisk .= 's-';
121
         $nameOnDisk .= getOneDBValue( "select name from site where site_id = $site_id" );
122
      } elseif ( $client_id ) {
123
         $nameOnDisk .= 'c-';
124
         $nameOnDisk .= getOneDBValue( "select name from client where client_id = $client_id" );
125
      } else {
126
         return array( 'valid' => false, 'message' => 'Error: not able to find client/site/device info' );
127
      }
63 rodolico 128
      logIt( "File name set to $nameOnDisk before processing" );
55 rodolico 129
      // add the extension
54 rodolico 130
      $nameOnDisk .= '.' . pathinfo($name, PATHINFO_EXTENSION);
63 rodolico 131
      logIt( "File name set to $nameOnDisk after adding extension" );
59 rodolico 132
      // and calculate the relative path to be added to the Files root path value
54 rodolico 133
      $nameOnDisk = getRelativePath( $nameOnDisk ) . $nameOnDisk;
63 rodolico 134
      logIt( "File name set to $nameOnDisk after adding rel path" );
54 rodolico 135
      return array( 'valid' => true, 'filename' => $nameOnDisk );
136
   } // function saveFile
137
 
55 rodolico 138
 
139
   /*
140
    * take the first digits of a file name (which is the index) and turn
141
    * them into a path, by breaking them into two character directories.
142
    * Thus, 123456-someFileName.something becomes
143
    * 12/34/123456-someFileName.something
144
    * however, this only returns the path part, so it will return
145
    * 12/34/
146
    */
54 rodolico 147
   function getRelativePath ( $filename ) {
148
      // the first part of the file name is the index, which is used to
149
      // calculate the path, so we'll throw away everything else.
150
      $filename = explode( '-', $filename )[0];
151
      while ( strlen( $filename ) > 2 ) {
152
         $path .= substr( $filename, 0, 2 ) . '/';
153
         $filename = substr( $filename, 2 );
154
      }
155
      return $path;
156
   }
157
 
55 rodolico 158
   /*
159
    * prepends two directory entries stored in _system table to
160
    * $filename
161
    */
162
   function getAbsolutePath ( $filename ) {
163
      $path = $_SESSION['file system root']
59 rodolico 164
                . '/' . getOneDBValue( "select theValue from _system where group_name = 'Files' and key_name = 'root path'" )
55 rodolico 165
                . '/' . $filename;
166
      return $path;
167
   }
168
 
169
   /*
170
    * returns the URL path to a file
171
    */
172
   function getURLPath ( $filename ) {
173
      $path = $_SESSION['html root']
59 rodolico 174
                . '/' . getOneDBValue( "select theValue from _system where group_name = 'Files' and key_name = 'root path'" )
55 rodolico 175
                . '/' . $filename;
176
      return $path;
177
   }
178
 
179
 
54 rodolico 180
   function makePath ( $filename ) {
181
      $path =  pathinfo( $filename, PATHINFO_DIRNAME );
182
      return is_dir( $path ) ? true : mkdir( $path, 0777, true );
183
   }
184
 
55 rodolico 185
   /*
186
    * Tries to find $value as a mime type
187
    * if $value is non-zero numeric, looks it up in the table as mime_type_id
188
    * if a string, checks for mime_type
189
    * if still not found, looks for extension
59 rodolico 190
    * returns index into file_mime_type, or 0 if not found
55 rodolico 191
    */
192
   function check_mime_type ( $value ) {
193
      if ( is_string( $value ) ) {
194
         $value = makeSafeSQLConstant( $value );
195
         // check if they passed in a mime type
59 rodolico 196
         $id = getOneDBValue( "select file_mime_type_id from file_mime_type where mime_type = $value" );
55 rodolico 197
         if ( $id ) return $id;
198
         // well, no, so check if they passed in an extension
59 rodolico 199
         return getOneDBValue( "select file_mime_type_id from file_mime_type where extension = $value" );
55 rodolico 200
      }
201
      return null;
202
   }
203
 
63 rodolico 204
   function addFile ( $fields ) {
205
      logIt( "entering addFile with fields set to\n" . print_r( $fields, true ) );
206
 
207
      // file_id is not set in any query, so get rid of it
208
      $file_id = $fields['file_id'];
209
      unset( $fields['file_id'] );
210
 
211
      // based on device, site or client, two fields are created
212
      if ( $fields['device_id'] ) {
213
         $fields['owner_type'] = 'd';
214
         $fields['owner_id'] = $fields['device_id'];
215
      } elseif ( $fields['site_id'] ) {
216
         $fields['owner_type'] = 's';
217
         $fields['owner_id'] = $fields['site_id'];
218
      } elseif ( $fields['client_id'] ) {
219
         $fields['owner_type'] = 'c';
220
         $fields['owner_id'] = $fields['client_id'];
54 rodolico 221
      }
63 rodolico 222
      // these are not actually part of the database, so trash them
223
      unset( $fields['client_id'] );
224
      unset( $fields['site_id'] );
225
      unset( $fields['device_id'] );
226
 
227
      if ( ! isset( $fields['mime_type'] ) ) {
228
         $extension = pathinfo( $fields['name_on_disk'], PATHINFO_EXTENSION);
229
         $fields['mime_type'] = getOneDBValue( "select mime_type from file_mime_type where extension = '$extension'" );
54 rodolico 230
      } // if we need to find the mime_type
63 rodolico 231
      foreach ( $fields as $key => $value ) {
232
         if ( strpos( $key, 'date' ) ) { // field name has date in it
233
            $fields[$key] = makeSafeSQLConstant( $value, 'd' );
234
         } else {
235
            $fields[$key] = makeSafeSQLConstant( $value );
236
         }
237
      }
238
      $fields['file_mime_type_id'] = getOneDBValue( "select file_mime_type_id from file_mime_type where mime_type = $fields[mime_type]" );
239
      unset( $fields['mime_type'] );
240
      if ( ! $fields['file_mime_type_id'] ) $fields['file_mime_type_id'] = 'null';
241
      if ( $file_id  ) { // we are updating an existing record
242
         $query = array();
243
         foreach ( $fields as $key => $value ) {
244
            $query[] = "$key = $value";
245
         }
246
         $query = 'update file set ' . implode( ',', $query ) . " where file_id = $file_id";
247
      } else { // we are adding a new record
248
         $query = 'insert into file (' . implode( ',', array_keys( $fields ) ) . ') values (' . implode( ',', array_values( $fields ) ) . ')';
249
      }
250
      logIt( $query );
54 rodolico 251
      $result = queryDatabaseExtended( $query );
63 rodolico 252
      if ( $result['insert_id'] )
253
         return array( 'valid' => true, 'message' => "New Record $result[insert_id]" );
254
      else
255
         return array( 'valid' => false, 'message' => "Database Error" );
54 rodolico 256
   }
55 rodolico 257
 
63 rodolico 258
   function return_bytes($val) {
259
       $val = trim($val);
260
       $last = strtolower($val[strlen($val)-1]);
261
       switch($last) 
262
       {
263
           case 'g':
264
           $val *= 1024;
265
           case 'm':
266
           $val *= 1024;
267
           case 'k':
268
           $val *= 1024;
269
       }
270
       return $val;
271
   } // return_bytes
272
 
273
   function prettyPrintBytes( $value ) {
274
      $sizes = array( '', 'kilo', 'mega', 'giga', 'tera' );
275
      while ( $value > 1024 ) {
276
         $value /= 1024;
277
         $index++;
278
      }
279
      return intval( $value ) . ' ' . $sizes[$index] . 'bytes';
280
   }
281
 
282
   function maxUploadFileSize () {
283
       //select maximum upload size
284
       $max_upload = return_bytes(ini_get('upload_max_filesize'));
285
       //select post limit
286
       $max_post = return_bytes(ini_get('post_max_size'));
287
       //select memory limit
288
       $memory_limit = return_bytes(ini_get('memory_limit'));
289
       // return the smallest of them, this defines the real limit
290
       return prettyPrintBytes( min($max_upload, $max_post, $memory_limit) );
291
    } // maxUploadFileSize
292
 
293
    function getFileUploadError( $error ) {
294
       $message = '';
295
       switch ( $error ) {
296
          case 0 : $message = 'There is no error, the file uploaded with success';
297
                   break;
298
          case 1 : $message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
299
                   break;
300
          case 2 : $message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
301
                   break;
302
          case 3 : $message = 'The uploaded file was only partially uploaded';
303
                   break;
304
          case 4 : $message = 'No file was uploaded';
305
                   break;
306
          case 6 : $message = 'Missing a temporary folder';
307
                   break;
308
          case 7 : $message = 'Failed to write file to disk.';
309
                   break;
310
          case 8 : $message = 'A PHP extension stopped the file upload.';
311
       }
312
       return array( 'valid' => $error == 0, 'message' => $message );
313
    } // getFileUploadError
314
 
315
   function uploadFile ( $source, $nameOnDisk ) {
316
      $saveTo = getAbsolutePath( $nameOnDisk );
317
      if ( makePath( $saveTo ) ) {
318
         logIt( "Path Made - $saveTo" );
319
         logIt( "moving $source to $saveTo" );
320
         $result['valid'] = move_uploaded_file( $source, $saveTo );
321
      } else {
322
         $result = array( 'valid'=>false, 'message' => print_r(error_get_last(), true) );
323
      } // if move_uploaded_file .. else
324
      return $result;
325
   } // uploadFile
54 rodolico 326
 
327
?>