Subversion Repositories computer_asset_manager_v2

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
53 rodolico 1
<?php
2
 
3
   class Camp {
4
      protected static $dbStructure;
61 rodolico 5
      //public static $myName;
6
      //protected static $viewName = 'view_device_location_owner_type';
7
 
8
      /**
9
       * Builds an instance and loads data from database
10
       * 
11
       * #parameter int $id The id of the record to load
12
       */
63 rodolico 13
      public function __construct( $id = 0 ) {
14
         if ( $id )
15
            $this->loadFromDB( $id );
16
      } // __construct
17
 
18
      public function loadFromDB( $id ) {
59 rodolico 19
         global $dbConnection;
20
 
21
         $this->data = array();
22
         $fields = array();
64 rodolico 23
         $calculatedFields = array();
59 rodolico 24
         foreach ( static::$dbStructure['table']['fields'] as $key => $data ) {
64 rodolico 25
            switch ( $data['type'] ) {
26
               case '1:1H' : // one to one with history
27
                  $calculatedFields[] = $data['fieldname'];
28
                  $calculatedFields[] = $data['displayColumn'];
29
                  break;
30
               case '1:M' : // one to many
31
                  $calculatedFields[] = $data['fieldname'];
32
                  break;
33
               default: // standard
34
                  $fields[] = $data['fieldname'];
59 rodolico 35
            }
36
         }
37
         $query = sprintf( "select %s from %s where %s = %s",
38
            implode( ',', $fields ),
39
            static::$dbStructure['table']['tableName'],
40
            static::$dbStructure['table']['primaryKey'],
41
            $id
42
         );
43
         //print "<pre> Constructor using query\n$query</pre>";
44
         //print "<pre>Constructor finding dbstructure of\n" . print_r( static::$dbStructure, true) . '</pre>';
61 rodolico 45
         if ( ( $this->data = $dbConnection->getOneRow( $query ) ) === false )
46
            print DBQuery::error2String();
59 rodolico 47
 
48
         //print "<pre>" . print_r( $calculatedFields, true ) . "</pre>"; die;
49
         //print "<pre>" . print_r( $this->data, true ) . "</pre>"; die;
61 rodolico 50
         if ( count( $calculatedFields ) ) {
51
            $query = sprintf( 'select distinct %s from %s %s',
52
                     implode( ',', $calculatedFields ),
53
                     static::$dbStructure['view']['viewName'],
54
                     static::makeWhereClause( array( 
55
                        static::$dbStructure['table']['fields']['id']['fieldname'] . 
56
                        ' = ' . 
57
                        $this->data[static::$dbStructure['table']['primaryKey']] ) 
58
                        )
59
                     );
60
            //print "<pre>$query</pre>"; die;
61
            $result = $dbConnection->getOneRow( $query );
62
            foreach ( $calculatedFields as $field ) {
63
               $this->data[$field] = empty( $result[$field] ) ? '' : $result[$field];
64
            } // foreach
65
         }
64 rodolico 66
         //print "<pre>Data after loadFromDB\n" . print_r($this->data, true) . "</pre>"; die;
63 rodolico 67
      } // loadFromDB
59 rodolico 68
 
61 rodolico 69
      /**
70
       * gets the contents of $fieldname
71
       * 
72
       * @parameter string $fieldname name of the database field to retrieve
73
       * 
74
       * @return string The value of $fieldname stored in structure
75
       */
59 rodolico 76
      public function __get( $fieldname ) {
77
         return 
78
            isset( $this->data[static::$dbStructure['table']['fields'][$fieldname]['fieldname']] ) ?
79
               $this->data[static::$dbStructure['table']['fields'][$fieldname]['fieldname']] :
80
               null;
81
      } // __get
82
 
83
 
55 rodolico 84
      /**
85
       * Gets stats for an extended class.
86
       * 
87
       * Gets number of active and inactive rows for a class, using the
88
       * view ($viewName)
89
       * 
90
       * @return int[] array of integers which is a count
91
       */
53 rodolico 92
      public static function getStats () {
93
         global $dbConnection;
57 rodolico 94
         global $activeOnly;
53 rodolico 95
 
96
         $return = array();
97
         $restrictions = array();
56 rodolico 98
         $trueClass = get_called_class();
57 rodolico 99
         $saveActive = $activeOnly;
100
         $activeOnly = true;
54 rodolico 101
 
102
         $active = sprintf( 
57 rodolico 103
            'select count(distinct %s) from %s %s', 
54 rodolico 104
            static::$dbStructure['table']['primaryKey'],  
61 rodolico 105
            static::$dbStructure['view']['viewName'], 
57 rodolico 106
            self::makeWhereClause() 
107
         );
108
 
109
         $activeOnly = false;
54 rodolico 110
         $inactive = sprintf( 
57 rodolico 111
            'select count(distinct %s) from %s  %s', 
54 rodolico 112
            static::$dbStructure['table']['primaryKey'],  
61 rodolico 113
            static::$dbStructure['view']['viewName'], 
57 rodolico 114
            self::makeWhereClause( array( strtolower( $trueClass ) . "_removed is not null" ) )
115
         );
116
         $activeOnly = $saveActive;
117
 
118
         //print "<pre>Active\n$active</pre><pre>Inactive\n$inactive</pre>"; die;
119
 
54 rodolico 120
         $return['active'] = $dbConnection->getOneDBValue( $active );
121
         $return['inactive'] = $dbConnection->getOneDBValue( $inactive );
53 rodolico 122
         return $return;
123
      }
124
 
61 rodolico 125
      /**
126
       * Creates a where clause
127
       * 
128
       * Merges $restrictions with any restrictions which may be in place
129
       * for the current user. Also sets 'class_removed is null' if
130
       * $activeOnly (global) is set
131
       * 
132
       * @parameter string[] $restrictions array of conditionals
133
       * 
134
       * @return string all restricions ANDED together
135
       */
57 rodolico 136
      protected static function makeWhereClause( $restrictions = array() ) {
137
         global $activeOnly;
138
 
139
         //print "<pre>" . print_r( $restrictions, true ) . "</pre>";
140
 
141
         $trueClass = get_called_class();
142
         foreach ( $_SESSION['restrictions'] as $class => $restriction ) {
143
            $restrictions[] = $_SESSION['restrictions'][$class];
144
         }
145
         if ( $activeOnly ) {
146
            $restrictions[] = strtolower( $trueClass ) . '_removed is null';
147
         }
148
         return count( $restrictions ) ? 'where ' . implode( ' and ', $restrictions ) : '';
149
      } //
150
 
61 rodolico 151
      /**
152
       * Creates a list of all records for a particular class and returns
153
       * a UL with all LI's set as links (A's) to displaying a record.
154
       * 
155
       * @parameter string[] $filter array of conditionals to limit if $list not set
156
       * @parameter string[] $list An optional list of data to be displayed
157
       * 
158
       * @return string A UL with each LI containing a link to an entry
159
       */
56 rodolico 160
      public static function showSelectionList( $filter = array(), $list = array() ) {
53 rodolico 161
         global $url;
59 rodolico 162
         $return = array();
56 rodolico 163
         if ( empty( $list ) ) {
164
            $list = self::getAll( $filter );
165
         }
64 rodolico 166
         //print "<pre>showSelectionList\n" . print_r( $list, true ) . "</pre>"; die;
56 rodolico 167
         $module = get_called_class();
53 rodolico 168
         foreach ( $list as $id => $name ) {
64 rodolico 169
            if ( $id )
170
               $return[] = "<a href='$url?module=$module&id=$id'>$name</a>";
53 rodolico 171
         }
64 rodolico 172
         return count($return) ? "<ul>\n<li>" . implode( "</li>\n<li>", $return ) . "</li>\n</ul>" : '';
53 rodolico 173
      }
174
 
61 rodolico 175
      /**
176
       * Gets all matching rows
177
       * 
178
       * Does an SQL call to retrieve ID and Name for all rows matching
179
       * $filter and $_REQUEST['to_find'].
180
       * 
181
       * @parameter string[] $filter Optional list of conditionals for where clause
182
       * 
183
       * @return array[] An array of indexes and names matching query
184
       */
56 rodolico 185
      public static function getAll( $filter = array() ) {
53 rodolico 186
         global $activeOnly;
187
         global $dbConnection;
188
 
59 rodolico 189
         //print "<pre>" . print_r( $filter, true ) . "</pre>";
56 rodolico 190
         if ( isset( $_REQUEST['to_find'] ) ) {
191
            $filter[] = sprintf( " %s like '%%%s%%'", static::$dbStructure['view']['selectionDisplay'],  $_REQUEST['to_find']) ;
192
         }
53 rodolico 193
         $return = array();
57 rodolico 194
         $query = sprintf( 'select distinct %s id, %s name from %s %s', 
56 rodolico 195
               static::$dbStructure['view']['primaryKey'],
196
               static::$dbStructure['view']['selectionDisplay'],
197
               static::$dbStructure['view']['viewName'],
57 rodolico 198
               self::makeWhereClause( $filter )
53 rodolico 199
               );
56 rodolico 200
         $query .= " order by " . static::$dbStructure['view']['selectionDisplay'];
59 rodolico 201
         //print "<pre>$query</pre>\n";
53 rodolico 202
         $result = $dbConnection->doSQL( $query );
64 rodolico 203
         $result = $result['returnData'];
204
         foreach ( $result as $row ) {
53 rodolico 205
            $return[$row['id']] = $row['name'];
206
         }
207
         return $return;
208
      }
61 rodolico 209
 
210
      /**
211
       * Returns the "name" of an instance
212
       * 
213
       * Normally, this is $this->name, but some classes may want to put
214
       * in additional data
215
       * 
216
       * @return string Display name of this instance
217
       */
53 rodolico 218
      public function __toString() {
219
         return $this->name;
220
      }
221
 
61 rodolico 222
      /**
223
       * Returns an HTML structure which can display a record
224
       * 
225
       * Note that if the instance has children, they will be displayed 
226
       * also. Additionally, if it has fields marked as type 'calculated'
227
       * it will perform the limited calculations.
228
       * 
229
       * @return string HTML to display record
230
       */
56 rodolico 231
      public function display() {
64 rodolico 232
         //print '<pre>' . print_r( $this->data, true) . '</pre>'; die;
59 rodolico 233
         global $url;
56 rodolico 234
         $return = array();
59 rodolico 235
         $save = '';
236
 
237
         /* get the records for this, including from other tables */
56 rodolico 238
         foreach ( static::$dbStructure['table']['fields'] as $key => $record ) {
59 rodolico 239
            if ( isset( $record['display'] ) && $record['display'] === false ) // we don't try to show links
240
               continue;
64 rodolico 241
            if ( $record['type'] == '1:1H' ) { // this one is supposed to be set up as a link
59 rodolico 242
                  $return[] = sprintf( 
243
                     "<td>%s</td><td><a href='$url?module=%s&id=%s'>%s</a></td>",
244
                     $record['displayName'],
64 rodolico 245
                     $record['class'],
246
                     $this->data[$record['fieldname']],
247
                     $this->data[$record['displayColumn']]
59 rodolico 248
                  );
249
            } else { // just pulling data from the table itself
250
               $return[] = '<td>' . $record['displayName'] . "</td>\n<td>" . $this->data[$record['fieldname']] . '</td>';
251
            }
56 rodolico 252
         }
61 rodolico 253
         $return[] = sprintf( "<td colspan='2'><a href='$url?module=%s&id=%s&action=edit'>Edit</a></td>",
254
                     get_called_class(),
255
                     $this->data[static::$dbStructure['table']['primaryKey']]
256
                  );
257
 
59 rodolico 258
         $return = "<div class='show_record'>\n<table class='show_record'>\n<tr>" . implode("</tr>\n<tr>", $return ) . "</tr>\n</table>\n</div>";
259
 
260
         /* Now, get the children records */
261
         if ( isset( $_REQUEST['to_find'] ) ) {
262
            $save = $_REQUEST['to_find'];
263
            unset( $_REQUEST['to_find'] );
264
         }
64 rodolico 265
         foreach ( static::$dbStructure['children'] as $class => $record) {
266
            if ( isset( $record['filter'] ) ) { // we'll parse it against $this->data to fill in any variables
267
               global $dbConnection;
268
               $record['filter'] = $dbConnection->templateReplace( $record['filter'], $this->data );
269
               //print "<pre>$filter\n" . print_r( $this->data, true) . "</pre>"; die;
270
            } else {
271
               $record['filter'] = static::$dbStructure['table']['primaryKey'] . ' = ' . $this->data[static::$dbStructure['table']['primaryKey']];
272
            }
273
            if ( ! isset( $record['name'] ) )
274
               $record['name'] = $class;
275
            //print "<pre>record\n" . print_r( $record, true) . "</pre>"; die;
276
            $found = $class::showSelectionList( array( $record['filter'] ) );
277
            //print "<pre>[$found]</pre>"; die;
278
            if ( $found )
279
               $return .= "<div class='show_record'>\n<h3>$record[name]</h3>\n" . $class::showSelectionList( array( $record['filter'] )  )  . '</div>';
59 rodolico 280
         }
281
         if ( $save !== null ) {
282
            $_REQUEST['to_find'] = $save;
283
         }
284
         return $return;
56 rodolico 285
      }
286
 
61 rodolico 287
      /**
63 rodolico 288
       * Function is basically a placeholder in case a extended class
289
       * needs to do some additional processing when editing
290
       * 
291
       * In some cases, the edit function can not handle additional fields.
292
       * See the Device class, where device_type is a table with many-to-many
293
       * linkages to device. Since this type of thing is very rare, I decided
294
       * to just allow edit and post to call an additional function in
295
       * those cases.
296
       * 
297
       * Based on the action requested, will either return an HTML string
298
       * which will be placed in the edit screen (for edit), or an array
299
       * of SQL to be executed to update/add rows (for post).
300
       * 
301
       * If the action is edit, there should be a <td></td> around the 
302
       * whole thing
303
       */
304
 
305
      protected function editAdditionalFields() {
306
         if ( $_REQUEST['action'] == 'edit' ) {
307
            return '';
308
         } elseif ($_REQUEST['action'] == 'post' ) {
309
            return array();
310
         }
311
      }
312
 
313
      protected function edit() {
314
         global $dbConnection;
315
 
316
         // save everything we have right now
317
         $this->beforeEdit = $this->data;
318
         foreach ( static::$dbStructure['table']['fields'] as $key => $record ) {
319
            if ( isset( $record['display'] ) && $record['display'] === false ) // we don't things which aren't supposed to be shown
320
               continue;
321
            if ( isset( $record['link'] ) ) { // this one is supposed to be set up as a link
322
 
323
                  // get a list of all options
324
                  $list = static::$dbStructure['table']['fields'][$record['link']]['class']::getAll();
325
 
326
                  //print '<pre>' . print_r( $record, true ) . "\n----\n" . print_r( $this->data, true ) . '</pre>'; die;
327
                  $selectedRow = $this->data[static::$dbStructure['table']['fields'][$record['link']]['fieldname']];
328
                  $select = $dbConnection->htmlSelect( array (
329
                              'data'      => $list,
64 rodolico 330
                              'name'      => $record['foreign_column'],
63 rodolico 331
                              'nullok'    => true,
332
                              'selected'  => isset( $selectedRow ) ? $selectedRow : -1,
333
                              //'class'     => 
334
                           )
335
                  );
336
                  $return[] = sprintf( 
337
                     "<td>%s</td><td>%s</td>",
338
                     $record['displayName'],
339
                     $select
340
                  );
341
            } else { // just pulling data from the table itself
342
               if ( isset( $record['canEdit'] ) && $record['canEdit'] == false ) {
343
                  $return[] = sprintf( 
344
                           "<td>%s</td><td>%s</td>",
345
                           $record['displayName'],
346
                           $this->data[$record['fieldname']]
347
                        );
348
               } else {
349
                  $return[] = sprintf( 
350
                           "<td>%s</td><td><input type='text' name='%s' value='%s'></td>",
351
                           $record['displayName'],
352
                           $record['fieldname'],
353
                           $this->data[$record['fieldname']]
354
                           );
355
               }
356
            }
357
         }
358
         $return[] = $this->editAdditionalFields();
359
         $return[] = "<td colspan='2'><input type='submit' name='Save' value='Save'></td>";
360
         $hiddens = sprintf( "<input type='hidden' name='module' value='%s'>\n", get_called_class() ) .
361
                     sprintf( "<input type='hidden' name='id' value='%s'>\n", $this->data[static::$dbStructure['table']['primaryKey']] ) .
362
                     "<input type='hidden' name='action' value='post'>\n";
363
         return "<div class='show_record'>\n<form><table class='show_record'>\n<tr>" . implode("</tr>\n<tr>", $return ) . "</tr>\n</table>\n$hiddens</form></div>";
364
      } // edit
365
 
64 rodolico 366
 
367
      /**
368
       * Adds new row in linkage table after marking old row as inactive
369
       * 
370
       * Returns two queries which should be executed to update a linkage table
371
       * 
372
       * The "History" part of this is that the old rows are not removed.
373
       * Instead, they are marked as removed and this new row is added.
374
       * 
375
       * This function assumes the table has two date columns, created and removed
376
       * created should be default current_timestamp so we do not manually update
377
       * it here.
378
       */
379
      public function post1to1History( $linkageTable, $myColumn, $linkedToColumn, $newValue ) {
380
         $queries = array();
381
         if ( $newValue != -1 ) {
382
            $queries[] = sprintf( 
383
               "update %s set removed = date(now()) where %s = %s and removed is null",
384
               $linkageTable,
385
               $myColumn,
386
               $this->__get('id')
387
               );
388
            $queries[] = sprintf(
389
               "insert into %s ( %s, %s ) values ( %s, %s )",
390
               $linkageTable,
391
               $myColumn, 
392
               $linkedToColumn,
393
               $this->__get('id'),
394
               $newValue
395
               );
396
         }
397
         return $queries;
398
      }
399
 
400
      /**
401
       * Posts the results of a previous form
402
       * 
403
       * After a form is filled in, will search for any values which have
404
       * changed. It will generate a separate SQL statement for each of them
405
       * and execute the queries in in batch
406
       * 
407
       * Once this is done, will reload the values from the database, so
408
       * we immediately know if there was a problem.
409
       */
63 rodolico 410
      protected function post() {
411
         global $dbConnection;
412
 
413
         $queries = array();
414
         $fields = array();
415
         foreach ( static::$dbStructure['table']['fields'] as $key => $record ) {
416
            if ( isset( $record['display'] ) && $record['display'] === false ) // we don't try to show links
417
               continue;
418
            if ( isset( $record['canEdit'] ) && ! $record['canEdit'] )
419
               continue;
64 rodolico 420
            if ( $_REQUEST[$record['fieldname']] != $this->data[$record['fieldname']] ) { // they have changed a value
421
               if ( isset( $record['link'] ) ) { // this one is supposed to be set up as a link
422
                  if ( $record['linkage_type'] == '1:1H' ) {
423
                     $queries[] = $this->post1to1History( 
424
                                    $record['linkage_table'], 
425
                                    $record['linkage_column'], 
426
                                    $record['foreign_column'], 
427
                                    $_REQUEST[$record['fieldname']] 
428
                                 );
429
                  }
430
               } else { // just a regular field, and it has changed, so add it to fields
431
                  $fields[$record['fieldname']] = $_REQUEST[$record['fieldname']];
432
               } // else
433
            } // if data has changed
63 rodolico 434
         } // foreach
435
         //print "<pre>Fields\n" . print_r( $this->data, true ) . "</pre>"; die;
436
         if ( count( $fields ) ) {
437
            if ( isset( $this->data[static::$dbStructure['table']['primaryKey']] ) ) { // this is an update
438
               $queries[] = $dbConnection->updateQuery( 
439
                     static::$dbStructure['table']['tableName'],
440
                     array( static::$dbStructure['table']['primaryKey'] => $this->data[static::$dbStructure['table']['primaryKey']] ),
441
                     $fields );
442
            } else { // this is an insert
443
               $queries[] = $dbConnection->insertQuery(
444
                     static::$dbStructure['table']['tableName'],
445
                     $fields );
446
            }
447
         } // if there are fields
64 rodolico 448
         print "<pre>Request" . print_r( $_REQUEST, true ) . "</pre>";
449
         print "<pre>Data" . print_r( $this->data, true ) . "</pre>";
450
         print "<pre>Queries" . print_r( $queries, true ) . "</pre>"; die;
63 rodolico 451
         $dbConnection->runSQLScript( $queries );
452
         $this->loadFromDB( $this->data[static::$dbStructure['table']['primaryKey']] );
453
      } // post
454
 
455
      /**
61 rodolico 456
       * Simple controller. Will determine what action is going on, then
457
       * call the correct method, returning the HTML required
458
       */
56 rodolico 459
      public function run() {
63 rodolico 460
         if ( isset( $_REQUEST['action'] ) ) {
461
            switch ( $_REQUEST['action'] ) {
462
               case 'edit' :  $return = $this->edit();
463
                              break;
464
               case 'post' :  $this->post();
465
               default:       $return =  $this->display();
466
            } // switch
467
         } else {
468
            $return =  $this->display();
469
         }
470
         return $return;
56 rodolico 471
      }
53 rodolico 472
   } // abstract class Camp
473
 
474
?>