Subversion Repositories computer_asset_manager_v1

Rev

Rev 99 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
99 rodolico 1
<?php
2
 
3
 
4
   /*
5
    * function will attempt to make a constant ($value) safe for SQL depending on the type.
6
    * 
7
    * if $value is empty, $default is returned, as will happen if any of the
8
    * conversions (date, datetime, etc...) fail.
9
    * 
10
    * First, it will pass it through get_magic_quotes_gpc, 
11
    * then will run through mysql_real_escape_string
12
    * 
13
    * For strings, will encapsulate in quotes
14
    * Dates will attempt a conversion, then change to YYYY-MM-DD and encapsulate in quotes
15
    *    if default is the constant now(), will pass that through to MySQL
16
    * DateTime will perform the same, but change to YYYY-MM-DD HH:MM:SS
17
    * Integer and Floats are passed through builtins intval and floatval
18
    * Boolean only checks the first character, a '0', 'f' and 'n' denoting false
19
    *    all else denoting true. The result is converted based on the variable
20
    *    $falsetrue, with the first char denoting false and the second denoting true
21
    */
22
   function makeSafeSQLConstant ( $value, $type='S', $default='null', $falsetrue='10' ) {
23
      // return $default on undefined or empty values
24
      if ( ! isset( $value ) ) return $default;
25
      if (strlen($value) == 0) return $default;
26
      // print "Processing $value as $type with default $default<br>\n";
27
      switch ( strtolower( $type ) ) {
28
         case 'string' :
29
         case 's' : 
30
                  if ( get_magic_quotes_gpc() ) 
31
                     $value = stripslashes($value);
32
                  $value = mysql_real_escape_string( $value );
33
                  $value = strlen( $value ) > 0 ? "'$value'" : $default;
34
                  break;
35
         case 'date' :
36
         case 'd' :
37
                  if ( $value != 'null' && $value != 'now()' ) {
38
                     $result = strtotime( $value );
39
                     $value = ( $result === false ) ? $default : "'" . Date( 'Y-m-d', $result) . "'";
40
                  }
41
                  break;
42
         case 'datetime':
43
         case 'timestamp':
44
         case 'dt': 
45
                  if ( $value != 'null' && $value != 'now()' ) {
46
                     $result = strtotime( $value );
47
                     $value = ( $result === false ) ? $default : "'" . Date( 'Y-m-d H:i:s', $result) . "'";
48
                  }
49
                  break;
50
         case 'integer':
51
         case 'i' :  
52
                  $value = intval( $value );
53
                  break;
54
         case 'float':
55
         case 'f' :  
56
                  $value = floatval( $value );
57
                  break;
58
         case 'bool':
59
         case 'boolean':
60
         case 'b' :  // note, because of the way strpos works, you can not
61
                     // simply set $value based on the output; you MUST do
62
                     // as below; specifically check for false, then set the result
63
                     $value =  strpos( '0fn', strtolower(substr( $value, 0, 1 )) ) === false ? 0 : 1;
64
                     $value = substr( $falsetrue, $value, 0, 1 );
65
                     break;
66
      } // switch
67
      return $value;
68
   }
69
   /****************************************************************************************
70
    * Functions to process an array the device_attrib table
71
    ***************************************************************************************/
72
 
73
   /*
74
    * takes a tab delimited array of lines and turns it into an array of array
75
    * Assumes first line contains the headers
76
    * turns the file
77
    * header1\theader2\theader3
78
    * value1\tvalue2\tvalue3
79
    *
80
    * into
81
    * [0]
82
    *    header1=>value1
83
    *    header2=>value2
84
    *    header3=>value3
85
    *
86
    * $contents is an array of lines, with each line having multiple
87
    * fields delimited by $delimiter
88
    * 
89
    */
90
   function tabDelimToArray($contents, $delimiter = "\t" ) {
91
      $rows = array();
92
      if ( gettype($contents) != 'array' )
93
         $contents = explode( "\n", $contents );
94
      $headers = explode( $delimiter, array_shift( $contents ) );
95
      for  ( $line = 0; $line < count( $contents ); $line++ ) {
96
         if ( $contents[$line] ) {
97
            $thisLine = explode( $delimiter, $contents[$line] );
98
            $thisLine = preg_replace( '/^\s+/', '', $thisLine );
99
            $thisLine = preg_replace( '/\s+$/', '', $thisLine );
100
            $columns = array();
101
            for ( $i = 0; $i < count( $headers ); $i++ ) {
102
               $columns[$headers[$i]] = $thisLine[$i];
103
            } // for
104
            $rows[] = $columns;
105
         } // if
106
      } // while
107
      return $rows;
108
   } // function
109
 
110
   /*
111
    * getDeviceID
112
    */
113
   function getDeviceID( $device, $createIfNotFound = false, $site = '', $client = '', $site_id = 0, $client_id = 0 ) {
114
      $device = makeSafeSQLConstant( $device, 's', '' );
115
      if ( ! $device ) return 0;
116
      $device_id = getOneDBValue( "select device_id from device where name = $device" );
117
      if ( $device_id ) return $device_id;
118
      if ( $createIfNotFound ) {
119
         if ( ! $site_id ) {
120
            $site_id = findSite( $site, $client, $site_id, $client_id );
121
         }
122
         if ( $site_id ) {
123
            $site_id = makeSafeSQLConstant( $site_id,'i','' );
124
            $result = queryDatabaseExtended( "insert into device (site_id,device_type_id,name,added_date,removed_date) values( $site_id,1,$device,now(),null )" );
125
            if ( $result['insert_id'] )
126
               return $result[insert_id];
127
         }
128
      }
129
      return 0;
130
   } // getDeviceID
131
 
132
 
133
   function getAttributeID( $attribute, $createIfNotFound = false ) {
134
      $attribute = makeSafeSQLConstant( $attribute, 's', '' );
135
      if ( ! $attribute ) return 0;
136
      $return = getOneDBValue( "select attrib_id from attrib where name = $attribute" );
137
      if ( ! $return && $createIfNotFound ) {
138
         $return = queryDatabaseExtended( "insert into attrib( name, added_date, removed_date ) values ( $attribute, now(), null )" );
139
         return $result['insert_id'] ? $result['insert_id'] : 0;
140
      }
141
      return $return;
142
   }
143
 
144
   /*
145
    * returns true if the value is empty or null
146
    */
147
   function nullOrEmpty( $str ) {
148
      return ( !isset( $str) || trim($str) === '');
149
   }
150
 
151
   /*
152
    * Takes a two dimensional array and adds/updates the values in device_attrib
153
    * 
154
    * $contents is an array of array, where they keys for each sub-array is the field name of the table to insert/update
155
    * $unique if true will replace any existing key for the device in question
156
    * $createDeviceIfNotFound, if true, will create any device name found if it doesn't exist
157
    * $device_id is used for the insert/update unless $device_id is a key in any row in the array
158
    * $site_id is used to A) uniquely identify a device or B) create the device if $createDeviceIfNotFound is true and device not foudn
159
    * $client_id is used the same way as $site_id
160
    *
161
    * $contents is assumed to be
162
    * [0] => {
163
    *           [value]     => string to be set/added to device_attrib table
164
    *           [attrib_id] => key from attrib table
165
    *           [attribute] => string matching name from attrib table
166
    *           [device_id] => key from device table
167
    *           [device]    => string matching name from device table
168
    *           [site_id]   => key from site table
169
    *           [site]      => string matching name from site table
170
    *           [client_id] => key from client table
171
    *           [client]    => string matching name from client table
172
    *         }
173
    * [1] =>  { another set of values the same as above }
174
    *
175
    * The only required values are attrib_id (or attribute) and value. If this is the case, it will be added to the device from
176
    * parameter $device_id
177
    *
178
    * If [something_id] is found, that is used. If it is null (or doesn't exist), an attempt is made to determine the proper
179
    * id from the database by looking for the string. If that is null, the parameter passed to this function is used. If all of
180
    * that fails, the row is returned to the caller.
181
    *
182
    */
183
   function parseTabDelimFile ( $contents, $createAttributeIfNotFound = false, $createDeviceIfNotFound = false, $default_device_id='', $default_site_id='', $default_client_id='' ) {
184
      $data = tabDelimToArray( $contents );
185
      // we'll put our SQL into an array, then dump it.
186
      $sql = array();
100 rodolico 187
      /*
188
      print "<pre>";
189
      var_dump( $createAttributeIfNotFound, $createDeviceIfNotFound, $default_device_id, $default_site_id, $default_client_id );
190
      print "</pre>";
191
      return $sql;
192
      */
99 rodolico 193
      // the following two arrays will store attributes and devices as we find them
194
      // we can then FIRST look them up here, in memory, and go to database only when we don't know them
195
      $attributesFromDatabase = array(); // uniquely store our attributes here
196
      $deviceFromDatabase = array();
197
      for ( $i = 0; $i < count( $data ); $i++ ) {  // go through each line and grab fields we need
198
 
199
         // get device_id
200
         if ( ! $data[$i]['device_id'] ) {
201
            if ( $data[$i]['device'] ) {
202
               if ( isset( $deviceFromDatabase[$data[$i]['device']] ) ) {
203
                  $data[$i]['device_id'] = $deviceFromDatabase[$data[$i]['device']];
204
               } else {
205
                  $data[$i]['device_id'] = getDeviceID( $data[$i]['device'], $createDeviceIfNotFound, $default_site_id, $default_client_id );
206
               }
207
               if ( $data[$i]['device_id'] )
208
                  $deviceFromDatabase[$data[$i]['device']] = $data[$i]['device_id'];
209
            }
210
            if ( ! $data[$i]['device_id'] ) {
211
               if ( $default_device_id ) {
212
                  $data[$i]['device_id'] = $default_device_id;
213
               } else {
214
                  $sql[] = "/* Can not locate device in line $i */";
215
                  continue;
216
               }
217
            }
218
         }
219
 
220
         // get attribute_id
221
         if ( ! $data[$i]['attrib_id'] ) {
222
            if ( $data[$i]['attribute'] ) {
223
               if ( isset( $attributesFromDatabase[$data[$i]['attribute']] ) ) {
224
                  $data[$i]['attrib_id'] = $attributesFromDatabase[$data[$i]['attribute']];
225
               } else {
226
                  $data[$i]['attrib_id'] = getAttributeID( $data[$i]['attribute'], $createAttributeIfNotFound );
227
               }
228
               if ( $data[$i]['attrib_id'] )
229
                  $attributesFromDatabase[$data[$i]['attribute']] = $data[$i]['attrib_id'];
230
            }
231
            if ( ! $data[$i]['attrib_id'] ) {
232
               $sql[] = "/* Can not locate attribute in line $i */";
233
               continue;
234
            }
235
         }
236
 
237
         if ( ! $data[$i]['value'] ) {
238
            $sql[] = "/* No Value given for line $i, skipped */";
239
            continue;
240
         }
241
 
242
         $value = makeSafeSQLConstant( $data[$i]['value'] );
243
         $attrib_id = makeSafeSQLConstant( $data[$i]['attrib_id'], 'i' );
244
         $device_id = makeSafeSQLConstant( $data[$i]['device_id'],'i' );
245
         // standard SQL that does an insert if the value doesn't already exist.
246
         $sql[] =
247
            "insert into attrib_device ( device_id, attrib_id,value, added_date )
248
               select $device_id,$attrib_id, $value, now()
249
               from dual
250
               where
251
                  not exists (
252
                     select * from attrib_device join device using (device_id) join attrib using (attrib_id) where device_id = $device_id and attrib_id = $attrib_id
253
                     );";
254
      }
255
      return $sql;
256
   }
257
 
258
 
259
   /*
260
    * following block of code is duplicated from the files module. It should instead be placed in root/include/library.php or something
261
    */
262
 
263
   /*
264
    * function designed to handle input from a form. If the input is
265
    * unset, will retrun the $default value.
266
    * Otherwise, will filter the value based on $filter
267
    * Some common filters are:
268
    *    FILTER_SANITIZE_SPECIAL_CHARS - clean up text so no HTML
269
    *    FILTER_SANITIZE_EMAIL         - email addresses
270
    *    FILTER_SANITIZE_NUMBER_FLOAT  - floating point numbers
271
    *    FILTER_SANITIZE_NUMBER_INT    - integers
272
    *    FILTER_SANITIZE_URL           - A URL
273
    * http://php.net/manual/en/filter.filters.sanitize.php
274
    */
275
   function cleanInput ( $value, $default = '', $filter = FILTER_DEFAULT ) {
276
      // unset or empty values just get the default
277
      if ( ! isset( $value ) || strlen( trim( $value ) ) == 0 ) return $default;
278
 
279
      return filter_var( trim( $value ), $filter );
280
   }
281
 
282
 
283
   function return_bytes($val) {
284
       $val = trim($val);
285
       $last = strtolower($val[strlen($val)-1]);
286
       switch($last) 
287
       {
288
           case 'g':
289
           $val *= 1024;
290
           case 'm':
291
           $val *= 1024;
292
           case 'k':
293
           $val *= 1024;
294
       }
295
       return $val;
296
   } // return_bytes
297
 
298
   function prettyPrintBytes( $value ) {
299
      $sizes = array( '', 'kilo', 'mega', 'giga', 'tera' );
300
      while ( $value > 1024 ) {
301
         $value /= 1024;
302
         $index++;
303
      }
304
      return intval( $value ) . ' ' . $sizes[$index] . 'bytes';
305
   }
306
 
307
   function maxUploadFileSize () {
308
       //select maximum upload size
309
       $max_upload = return_bytes(ini_get('upload_max_filesize'));
310
       //select post limit
311
       $max_post = return_bytes(ini_get('post_max_size'));
312
       //select memory limit
313
       $memory_limit = return_bytes(ini_get('memory_limit'));
314
       // return the smallest of them, this defines the real limit
315
       return prettyPrintBytes( min($max_upload, $max_post, $memory_limit) );
316
    } // maxUploadFileSize
317
 
318
    function getFileUploadError( $error ) {
319
       $message = '';
320
       switch ( $error ) {
321
          case 0 : $message = 'There is no error, the file uploaded with success';
322
                   break;
323
          case 1 : $message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
324
                   break;
325
          case 2 : $message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
326
                   break;
327
          case 3 : $message = 'The uploaded file was only partially uploaded';
328
                   break;
329
          case 4 : $message = 'No file was uploaded';
330
                   break;
331
          case 6 : $message = 'Missing a temporary folder';
332
                   break;
333
          case 7 : $message = 'Failed to write file to disk.';
334
                   break;
335
          case 8 : $message = 'A PHP extension stopped the file upload.';
336
       }
337
       return array( 'valid' => $error == 0, 'message' => $message );
338
    } // getFileUploadError
339
 
340
   function uploadFile ( $source, $nameOnDisk ) {
341
      $saveTo = getAbsolutePath( $nameOnDisk );
342
      if ( makePath( $saveTo ) ) {
343
         logIt( "Path Made - $saveTo" );
344
         logIt( "moving $source to $saveTo" );
345
         $result['valid'] = move_uploaded_file( $source, $saveTo );
346
      } else {
347
         $result = array( 'valid'=>false, 'message' => print_r(error_get_last(), true) );
348
      } // if move_uploaded_file .. else
349
      return $result;
350
   } // uploadFile
351
 
352
 
353
?>
354
 
355
 
356
?>