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
 
6
      /**
7
       * Builds an instance and loads data from database
8
       * 
9
       * #parameter int $id The id of the record to load
10
       */
63 rodolico 11
      public function __construct( $id = 0 ) {
66 rodolico 12
         if ( $id ) {
63 rodolico 13
            $this->loadFromDB( $id );
66 rodolico 14
            $_SESSION['workingon'][get_called_class()] = $id;
15
         }
63 rodolico 16
      } // __construct
17
 
18
      public function loadFromDB( $id ) {
69 rodolico 19
         //print "<pre>Loading from DB\nClass = " . get_called_class() . "\nID = $id\n</pre>";
59 rodolico 20
         global $dbConnection;
21
 
22
         $this->data = array();
23
         $fields = array();
64 rodolico 24
         $calculatedFields = array();
59 rodolico 25
         foreach ( static::$dbStructure['table']['fields'] as $key => $data ) {
64 rodolico 26
            switch ( $data['type'] ) {
27
               case '1:1H' : // one to one with history
69 rodolico 28
                  $calculatedFields[$key] = $data;
64 rodolico 29
                  break;
30
               case '1:M' : // one to many
69 rodolico 31
                  $calculatedFields[$key] = $data;
64 rodolico 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
 
69 rodolico 48
         // note, we had to wait to do the calculated fields since they needed the primary key from this record
49
         foreach ( $calculatedFields as $key => $data ) {
50
            switch ( $data['type'] ) {
51
               case '1:1H' : // one to one with history
52
                  $this->data[$key] = $this->oneToOneHistoryLoad( $data );
53
                  break;
54
               case '1:M' : // one to many
55
                  $this->data[$key] = $this->oneToManyLoad( $data );
56
                  break;
57
               default:
58
                  print "<pre>Error, I do not know how to load calculated field type $data[type]</pre>";
59
            } // switch
60
         } // foreach
64 rodolico 61
         //print "<pre>Data after loadFromDB\n" . print_r($this->data, true) . "</pre>"; die;
63 rodolico 62
      } // loadFromDB
59 rodolico 63
 
61 rodolico 64
      /**
65
       * gets the contents of $fieldname
66
       * 
67
       * @parameter string $fieldname name of the database field to retrieve
68
       * 
69
       * @return string The value of $fieldname stored in structure
70
       */
59 rodolico 71
      public function __get( $fieldname ) {
66 rodolico 72
         if ( empty( $this->data ) )
73
            $this->data = array();
59 rodolico 74
         return 
75
            isset( $this->data[static::$dbStructure['table']['fields'][$fieldname]['fieldname']] ) ?
76
               $this->data[static::$dbStructure['table']['fields'][$fieldname]['fieldname']] :
77
               null;
78
      } // __get
79
 
80
 
55 rodolico 81
      /**
82
       * Gets stats for an extended class.
83
       * 
84
       * Gets number of active and inactive rows for a class, using the
85
       * view ($viewName)
86
       * 
87
       * @return int[] array of integers which is a count
88
       */
53 rodolico 89
      public static function getStats () {
90
         global $dbConnection;
57 rodolico 91
         global $activeOnly;
53 rodolico 92
 
93
         $return = array();
94
         $restrictions = array();
56 rodolico 95
         $trueClass = get_called_class();
57 rodolico 96
         $saveActive = $activeOnly;
66 rodolico 97
         $activeOnly = false;
98
/*         
99
         $query = sprintf( 
100
            'select count(*) num,isnull(removed) active from %s %s group by isnull(removed) order by isnull(removed) desc',
101
            static::$dbStructure['table']['tableName'],  
102
            self::makeWhereClause()
103
         );
104
         $result = $dbConnection->doSQL( $query );
105
         foreach ( $result['returnData'] as $row ) {
106
            if ( $row['active'] == 1 ) {
107
               $return['active'] = $row['num'];
108
            } elseif ( $row['active'] == 0 ) {
109
               $return['inactive'] = $row['num'];
110
            }
111
         }
112
*/
69 rodolico 113
         if ( isset( static::$dbStructure['table']['inactiveField'] ) ) {
70 rodolico 114
            $return['active'] = 0;
115
            $return['inactive'] = 0;
69 rodolico 116
            $query = sprintf(
117
               'select count(*) num, isnull(%s) active from %s %s group by isnull(%s) order by isnull(%s) desc',
118
               static::$dbStructure['table']['inactiveField'],
119
               static::$dbStructure['table']['tableName'],
120
               self::makeWhereClause(),
121
               static::$dbStructure['table']['inactiveField'],
122
               static::$dbStructure['table']['inactiveField']
123
               );
70 rodolico 124
            //print "<pre>Getting Active\n$query</pre>"; die;
69 rodolico 125
            $activeOnly = $saveActive;
126
            $result = $dbConnection->doSQL( $query );
127
            foreach ( $result['returnData'] as $row ) {
128
               if ( $row['active'] == 1 ) {
129
                  $return['active'] = $row['num'];
130
               } elseif ( $row['active'] == 0 ) {
131
                  $return['inactive'] = $row['num'];
132
               }
133
            }
134
         } else {
135
            $query = sprintf(
136
               'select count(*) num from %s %s',
137
               static::$dbStructure['table']['tableName'],
138
               self::makeWhereClause()
139
               );
140
            $return['total'] = $dbConnection->getOneDBValue( $query );
141
         }
142
 
143
 
144
         /*
54 rodolico 145
         $active = sprintf( 
69 rodolico 146
            'select count(%s) from %s %s', 
54 rodolico 147
            static::$dbStructure['table']['primaryKey'],  
69 rodolico 148
            static::$dbStructure['table']['tableName'], 
57 rodolico 149
            self::makeWhereClause() 
150
         );
151
 
152
         $activeOnly = false;
54 rodolico 153
         $inactive = sprintf( 
69 rodolico 154
            'select count(%s) from %s  %s', 
54 rodolico 155
            static::$dbStructure['table']['primaryKey'],  
69 rodolico 156
            static::$dbStructure['table']['tableName'], 
157
            self::makeWhereClause( "removed is not null" ) )
57 rodolico 158
         );
159
 
160
         //print "<pre>Active\n$active</pre><pre>Inactive\n$inactive</pre>"; die;
161
 
54 rodolico 162
         $return['active'] = $dbConnection->getOneDBValue( $active );
163
         $return['inactive'] = $dbConnection->getOneDBValue( $inactive );
69 rodolico 164
         */
66 rodolico 165
 
166
         $activeOnly = $saveActive;
53 rodolico 167
         return $return;
168
      }
169
 
61 rodolico 170
      /**
171
       * Creates a where clause
172
       * 
173
       * Merges $restrictions with any restrictions which may be in place
174
       * for the current user. Also sets 'class_removed is null' if
175
       * $activeOnly (global) is set
176
       * 
177
       * @parameter string[] $restrictions array of conditionals
178
       * 
179
       * @return string all restricions ANDED together
180
       */
68 rodolico 181
      public static function makeWhereClause( $restrictions = array(), $restrictGlobals = array(), $tablename = null ) {
57 rodolico 182
         global $activeOnly;
183
 
184
         //print "<pre>" . print_r( $restrictions, true ) . "</pre>";
185
 
186
         $trueClass = get_called_class();
70 rodolico 187
         foreach ( $_SESSION['restrictions'][$trueClass] as $restriction ) {
188
            $restrictions[] = $restriction;
57 rodolico 189
         }
69 rodolico 190
         if ( $activeOnly && isset( $trueClass::$dbStructure['table']['inactiveField'] ) ) {
191
            $restrictions[] = $trueClass::$dbStructure['table']['inactiveField'] .  ' is null';
57 rodolico 192
         }
66 rodolico 193
         /*
194
         if ( isset( $restrictGlobals['workingon'] ) && isset( $_SESSION['workingon'] ) ) {
195
            foreach ( $_SESSION['workingon'] as $class => $id ) {
196
               $restrictions[] = strtolower( $class ) . "_id = $id";
197
            }
198
         }
199
         */
57 rodolico 200
         return count( $restrictions ) ? 'where ' . implode( ' and ', $restrictions ) : '';
201
      } //
202
 
61 rodolico 203
      /**
204
       * Creates a list of all records for a particular class and returns
205
       * a UL with all LI's set as links (A's) to displaying a record.
206
       * 
207
       * @parameter string[] $filter array of conditionals to limit if $list not set
208
       * @parameter string[] $list An optional list of data to be displayed
209
       * 
210
       * @return string A UL with each LI containing a link to an entry
211
       */
66 rodolico 212
      public static function showSelectionList( $filter = array(), $list = array(), $noAdd = false ) {
53 rodolico 213
         global $url;
59 rodolico 214
         $return = array();
66 rodolico 215
         $module = get_called_class();
70 rodolico 216
         unset ( $_SESSION['workingon'][$module] );
56 rodolico 217
         if ( empty( $list ) ) {
218
            $list = self::getAll( $filter );
219
         }
64 rodolico 220
         //print "<pre>showSelectionList\n" . print_r( $list, true ) . "</pre>"; die;
53 rodolico 221
         foreach ( $list as $id => $name ) {
64 rodolico 222
            if ( $id )
223
               $return[] = "<a href='$url?module=$module&id=$id'>$name</a>";
53 rodolico 224
         }
66 rodolico 225
         //print "<pre>noadd is $noAdd</pre>"; die;
226
         if ( ! $noAdd && $_SESSION['user']->isAuthorized( strtolower($module) . '_add') )
227
            $return[] = "<br /><a href='$url?module=$module&action=add'>Add New</a>";
64 rodolico 228
         return count($return) ? "<ul>\n<li>" . implode( "</li>\n<li>", $return ) . "</li>\n</ul>" : '';
53 rodolico 229
      }
230
 
61 rodolico 231
      /**
232
       * Gets all matching rows
233
       * 
234
       * Does an SQL call to retrieve ID and Name for all rows matching
235
       * $filter and $_REQUEST['to_find'].
236
       * 
237
       * @parameter string[] $filter Optional list of conditionals for where clause
238
       * 
239
       * @return array[] An array of indexes and names matching query
240
       */
66 rodolico 241
      public static function getAll( $filter = array(), $restrictGlobals = array() ) {
53 rodolico 242
         global $activeOnly;
243
         global $dbConnection;
244
 
59 rodolico 245
         //print "<pre>" . print_r( $filter, true ) . "</pre>";
56 rodolico 246
         if ( isset( $_REQUEST['to_find'] ) ) {
69 rodolico 247
            $filter[] = sprintf( " %s like '%%%s%%'", static::$dbStructure['table']['selectionDisplay'],  $_REQUEST['to_find']) ;
56 rodolico 248
         }
53 rodolico 249
         $return = array();
69 rodolico 250
         $query = sprintf( 'select %s id, %s name from %s %s', 
251
               static::$dbStructure['table']['primaryKey'],
252
               static::$dbStructure['table']['selectionDisplay'],
253
               static::$dbStructure['table']['tableName'],
66 rodolico 254
               self::makeWhereClause( $filter, $restrictGlobals )
53 rodolico 255
               );
69 rodolico 256
         $query .= " order by " . static::$dbStructure['table']['selectionDisplay'];
59 rodolico 257
         //print "<pre>$query</pre>\n";
53 rodolico 258
         $result = $dbConnection->doSQL( $query );
64 rodolico 259
         $result = $result['returnData'];
260
         foreach ( $result as $row ) {
53 rodolico 261
            $return[$row['id']] = $row['name'];
262
         }
263
         return $return;
264
      }
61 rodolico 265
 
266
      /**
267
       * Returns the "name" of an instance
268
       * 
269
       * Normally, this is $this->name, but some classes may want to put
270
       * in additional data
271
       * 
272
       * @return string Display name of this instance
273
       */
53 rodolico 274
      public function __toString() {
275
         return $this->name;
276
      }
277
 
61 rodolico 278
      /**
279
       * Returns an HTML structure which can display a record
280
       * 
281
       * Note that if the instance has children, they will be displayed 
282
       * also. Additionally, if it has fields marked as type 'calculated'
283
       * it will perform the limited calculations.
284
       * 
285
       * @return string HTML to display record
286
       */
56 rodolico 287
      public function display() {
69 rodolico 288
         //print "<pre>In Display\n" . print_r( $this->data, true) . '</pre>'; die;
59 rodolico 289
         global $url;
56 rodolico 290
         $return = array();
59 rodolico 291
         $save = '';
292
 
293
         /* get the records for this, including from other tables */
56 rodolico 294
         foreach ( static::$dbStructure['table']['fields'] as $key => $record ) {
59 rodolico 295
            if ( isset( $record['display'] ) && $record['display'] === false ) // we don't try to show links
296
               continue;
64 rodolico 297
            if ( $record['type'] == '1:1H' ) { // this one is supposed to be set up as a link
59 rodolico 298
                  $return[] = sprintf( 
299
                     "<td>%s</td><td><a href='$url?module=%s&id=%s'>%s</a></td>",
300
                     $record['displayName'],
64 rodolico 301
                     $record['class'],
69 rodolico 302
                     $this->data[$key]['id'],
303
                     $this->data[$key]['display']
59 rodolico 304
                  );
69 rodolico 305
            } elseif ( $record['type'] == '1:M' ) { // this is an array in data, so we just grab the values
306
               $return[] = '<td>' . $record['displayName'] . "</td>\n<td>" . implode( ',', array_values( $this->data[$key] ) ) . '</td>';
59 rodolico 307
            } else { // just pulling data from the table itself
308
               $return[] = '<td>' . $record['displayName'] . "</td>\n<td>" . $this->data[$record['fieldname']] . '</td>';
309
            }
56 rodolico 310
         }
66 rodolico 311
         if ( $_SESSION['user']->isAuthorized( strtolower(get_called_class()) . '_edit') )
312
            $return[] = sprintf( "<td colspan='2'><a href='$url?module=%s&id=%s&action=edit'>Edit</a></td>",
313
                        get_called_class(),
314
                        $this->data[static::$dbStructure['table']['primaryKey']]
315
                     );
61 rodolico 316
 
59 rodolico 317
         $return = "<div class='show_record'>\n<table class='show_record'>\n<tr>" . implode("</tr>\n<tr>", $return ) . "</tr>\n</table>\n</div>";
318
 
319
         /* Now, get the children records */
320
         if ( isset( $_REQUEST['to_find'] ) ) {
321
            $save = $_REQUEST['to_find'];
322
            unset( $_REQUEST['to_find'] );
323
         }
64 rodolico 324
         foreach ( static::$dbStructure['children'] as $class => $record) {
325
            if ( isset( $record['filter'] ) ) { // we'll parse it against $this->data to fill in any variables
326
               global $dbConnection;
327
               $record['filter'] = $dbConnection->templateReplace( $record['filter'], $this->data );
328
               //print "<pre>$filter\n" . print_r( $this->data, true) . "</pre>"; die;
329
            } else {
69 rodolico 330
               if ( isset( $record['intermediateTable'] ) ) {
331
                  // they have defined an intermediate table, so we need to use that
332
                  $record['filter'] = sprintf(
333
                     '%s in (select %s from %s where %s = %s and removed is null)',
334
                     $record['remoteID'],
335
                     $record['remoteID'],
336
                     $record['intermediateTable'],
337
                     $record['myID'],
338
                     $this->id
339
                     );
340
               } else {
341
                  $record['filter'] = static::$dbStructure['table']['primaryKey'] . ' = ' . $this->data[static::$dbStructure['table']['primaryKey']];
342
               }
64 rodolico 343
            }
344
            if ( ! isset( $record['name'] ) )
345
               $record['name'] = $class;
346
            //print "<pre>record\n" . print_r( $record, true) . "</pre>"; die;
69 rodolico 347
 
66 rodolico 348
            $found = $class::showSelectionList( array( $record['filter'] ), array(), isset( $record['noAdd'] )  );
64 rodolico 349
            //print "<pre>[$found]</pre>"; die;
350
            if ( $found )
66 rodolico 351
               $return .= "<div class='show_record'>\n<h3>$record[name]</h3>\n" . $found  . '</div>';
59 rodolico 352
         }
353
         if ( $save !== null ) {
354
            $_REQUEST['to_find'] = $save;
355
         }
356
         return $return;
66 rodolico 357
      } // display
56 rodolico 358
 
61 rodolico 359
      /**
63 rodolico 360
       * Function is basically a placeholder in case a extended class
361
       * needs to do some additional processing when editing
362
       * 
363
       * In some cases, the edit function can not handle additional fields.
364
       * See the Device class, where device_type is a table with many-to-many
365
       * linkages to device. Since this type of thing is very rare, I decided
366
       * to just allow edit and post to call an additional function in
367
       * those cases.
368
       * 
369
       * Based on the action requested, will either return an HTML string
370
       * which will be placed in the edit screen (for edit), or an array
371
       * of SQL to be executed to update/add rows (for post).
372
       * 
373
       * If the action is edit, there should be a <td></td> around the 
374
       * whole thing
375
       */
376
 
377
      protected function editAdditionalFields() {
378
         if ( $_REQUEST['action'] == 'edit' ) {
379
            return '';
380
         } elseif ($_REQUEST['action'] == 'post' ) {
381
            return array();
382
         }
383
      }
384
 
69 rodolico 385
      protected function oneToOneHistoryLoad( $field ) {
386
         //print "<pre>In oneToOneHistoryLoad, field is\n" . print_r( $field, true ) . '</pre>'; die;
387
         global $dbConnection;
388
         if ( isset( $field['displayQuery'] ) ) { // They want us to run a query
389
            // 
390
            $return = $dbConnection->getOneRow(
391
               $dbConnection->templateReplace( $field['displayQuery'], 
392
                  array( 'id' => $this->data[static::$dbStructure['table']['primaryKey']] ) 
393
                  )
394
               ); 
395
         } elseif ( isset( $field['linkageTable'] ) ) { // we have to come up with the query ourselves
396
            /* Since we have a linkage table, we assume the column name in the linkage table is the
397
             * same as the primary key in the remote table (see the using).
398
             * Everything else is chosen from the definition
399
             * 
400
             * Note, on 1:1H, assume the linkage table has a full history with a null removed
401
             * date for the current value
402
             */
403
            $query = sprintf( 
404
               'select a.%s id,a.%s display from %s b join %s a using (%s) where b.%s = %s and b.removed is null',
405
               $field['fieldname'],
406
               $field['displayColumn'],
407
               $field['linkageTable'],
408
               $field['foreignTable'],
409
               $field['foreignColumn'],
410
               $field['linkageColumn'],
411
               $this->data[static::$dbStructure['table']['primaryKey']],
412
               $field['linkageTable']
413
               );
414
            //print "<pre>oneToOneHistory Query is \n$query</pre>"; die;
415
            $return = $dbConnection->getOneRow( $query );
416
         } // if..else
417
         //print "<pre>return from oneToOneHistory is\n$return</pre>"; die;
418
         return $return;
419
      }
420
 
65 rodolico 421
      /**
69 rodolico 422
       * Gets all rows in a one to many relationship and returns it as an array
423
       * 
424
       * If 'displayQuery' is defined, it should return one row for each match, with two columns
425
       * 'id' is a unique ID, and 'display' is a textual display of the value. An
426
       * order by clause can be used to determine the display order of the values 
427
       * returned.
428
       * 
429
       * If 'displayQuery' is not defined, will build a query based on the definition.
430
       * 
431
       * The returned array uses the 'id' field for the index and the 'display' field
432
       * for the value
433
       * 
434
       * @parameter array[] $field A Field Definition from $dbStructure
435
       * 
436
       * @returns array[] where the the key is the id and the value is the display field
65 rodolico 437
       */
69 rodolico 438
      public function oneToManyLoad ( $field ) {
439
         global $dbConnection;
440
         $query = '';
441
         if ( isset( $field['displayQuery'] ) ) { // They want us to run a query
442
            $query = $dbConnection->templateReplace( 
443
               $field['displayQuery'], 
444
               array( 'id' => $this->data[static::$dbStructure['table']['primaryKey']] ) 
445
            );
446
         } else {
447
            $query = sprintf(
448
               'select %s id, %s display from %s a join %s b using ( %s ) where a.%s = %s order by %s',
449
               $field['foreignColumn'],
450
               $field['foreignDisplayColumn'],
451
               $field['linkageTable'],
452
               $field['foreignTable'],
453
               $field['foreignColumn'],
454
               $field['linkageColumn'],
455
               $this->data[static::$dbStructure['table']['primaryKey']],
456
               $field['foreignDisplayColumn']
457
               );
458
         } // else
459
         $return = $dbConnection->doSQL( $query, array( 'returnType' => 'associative' ) );
460
         $returnArray = array();
461
         foreach ( $return['returnData'] as $row => $data ) {
462
            $returnArray[$data['id']] = $data['display'];
463
         }
464
         return $returnArray;
465
      } // oneToManyLoad
466
 
467
 
468
      /**
469
       * Allow one to many types to be edited also
470
       */
65 rodolico 471
      protected function oneToManyEdit( $key, $record ) {
472
         global $dbConnection;
66 rodolico 473
 
474
         $id = $this->__get('id') === null ? 0 : $this->__get('id');
65 rodolico 475
         $query = $dbConnection->templateReplace (
476
            sprintf(
477
           "select 
478
               ~~foreignTable~~.~~foreignColumn~~ id,
479
               ~~foreignTable~~.~~foreignDisplayColumn~~ name,
480
               not isnull(~~linkageColumn~~) checked
481
            from
482
               ~~foreignTable~~ ~~foreignTable~~
483
               left outer join (
484
                     select
485
                        ~~linkageColumn~~,
486
                        ~~foreignColumn~~
487
                     from
488
                        ~~linkageTable~~
489
                     where
490
                        ~~linkageColumn~~ = %s
491
                  ) current using ( ~~foreignColumn~~ )
492
                  order by ~~foreignDisplayColumn~~
66 rodolico 493
            ", $id
65 rodolico 494
            ),
495
            $record
496
            );
497
         //print "<pre>$query</pre>"; die;
498
         $data = $dbConnection->doSQL( $query );
499
         $data = $data['returnData'];
500
         // save current state in data
501
         $this->data[$key] = array();
502
         foreach ( $data as $row ) {
503
            if ( count( $row ) > 1 ) 
504
               $this->data[$key][$row['id']] = $row['checked'];
505
         }
506
         //print "<pre>" . print_r($this->data, true) . "</pre>"; die;
507
         //print "<pre>" . print_r($query, true) . "</pre>"; die;
508
         $html = $dbConnection->htmlCheckBoxes( array( 'data' => $data, 'arrayName' => $key ) );
509
         //print "<pre>" . print_r($html, true) . "</pre>"; die;
510
         return $html;
66 rodolico 511
      } // oneToManyEdit
65 rodolico 512
 
513
 
63 rodolico 514
      protected function edit() {
515
         global $dbConnection;
516
 
517
         // save everything we have right now
66 rodolico 518
         //$this->beforeEdit = $this->data;
519
         $return = array();
520
         //print "<pre>In Edit\n" . print_r( $this->data, true ) . "</pre>"; die;
63 rodolico 521
         foreach ( static::$dbStructure['table']['fields'] as $key => $record ) {
66 rodolico 522
            //print "<pre>Processing $record[displayName]\n</pre>";
523
            if ( isset( $record['display'] ) && $record['display'] === false ) // we don't do things which aren't supposed to be shown
63 rodolico 524
               continue;
65 rodolico 525
            switch ( $record['type'] ) {
526
               case '1:1H':
66 rodolico 527
                  //print "<pre>Doing 1:1H\n</pre>";
63 rodolico 528
                  // get a list of all options
66 rodolico 529
                  $list = $record['class']::getAll( array(), array( 'workingon' => true ));
530
                  //print "<pre> list is\n" . print_r( $list, true ) . "</pre>";
69 rodolico 531
                  $selectedRow = isset( $this->data[$key]['id'] ) ? $this->data[$key]['id'] : null;
66 rodolico 532
                  //print "<pre>Selected value is $selectedRow</pre>";
63 rodolico 533
                  $select = $dbConnection->htmlSelect( array (
534
                              'data'      => $list,
69 rodolico 535
                              'name'      => $key, //$record['foreignColumn'],
63 rodolico 536
                              'nullok'    => true,
537
                              'selected'  => isset( $selectedRow ) ? $selectedRow : -1,
538
                              //'class'     => 
539
                           )
540
                  );
541
                  $return[] = sprintf( 
542
                     "<td>%s</td><td>%s</td>",
543
                     $record['displayName'],
544
                     $select
545
                  );
65 rodolico 546
                  break;
547
               case '1:M' :
66 rodolico 548
                  //print "<pre>Doing 1:M\n</pre>";
65 rodolico 549
                  $checkBoxes = $this->oneToManyEdit( $key, $record );
550
                  $return[] = "<td>$record[displayName]</td>\n<td>$checkBoxes</td>";
551
                  break;
552
               default: 
66 rodolico 553
                  //print "<pre>Adding $record[displayName]\n</pre>";
65 rodolico 554
                  if ( isset( $record['canEdit'] ) && $record['canEdit'] == false ) {
555
                     $return[] = sprintf( 
556
                              "<td>%s</td><td>%s</td>",
557
                              $record['displayName'],
66 rodolico 558
                              isset( $this->data[$record['fieldname']] ) ? $this->data[$record['fieldname']] : ''
63 rodolico 559
                           );
65 rodolico 560
                  } else {
561
                     $return[] = sprintf( 
562
                              "<td>%s</td><td><input type='text' name='%s' value='%s'></td>",
563
                              $record['displayName'],
564
                              $record['fieldname'],
565
                              $this->data[$record['fieldname']]
566
                              );
567
                  } // if..else
568
            } // switch
569
         } // foreach
570
         //$return[] = $this->editAdditionalFields();
66 rodolico 571
         //print "<pre>In Edit, return is\n" . print_r( $return, true ) . "</pre>";
63 rodolico 572
         $return[] = "<td colspan='2'><input type='submit' name='Save' value='Save'></td>";
573
         $hiddens = sprintf( "<input type='hidden' name='module' value='%s'>\n", get_called_class() ) .
66 rodolico 574
                     sprintf( "<input type='hidden' name='id' value='%s'>\n", isset( $this->data[static::$dbStructure['table']['primaryKey']] ) ? $this->data[static::$dbStructure['table']['primaryKey']] : 0 ) .
63 rodolico 575
                     "<input type='hidden' name='action' value='post'>\n";
576
         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>";
577
      } // edit
578
 
64 rodolico 579
 
580
      /**
581
       * Adds new row in linkage table after marking old row as inactive
582
       * 
583
       * Returns two queries which should be executed to update a linkage table
584
       * 
585
       * The "History" part of this is that the old rows are not removed.
586
       * Instead, they are marked as removed and this new row is added.
587
       * 
588
       * This function assumes the table has two date columns, created and removed
589
       * created should be default current_timestamp so we do not manually update
590
       * it here.
591
       */
592
      public function post1to1History( $linkageTable, $myColumn, $linkedToColumn, $newValue ) {
593
         $queries = array();
594
         if ( $newValue != -1 ) {
595
            $queries[] = sprintf( 
596
               "update %s set removed = date(now()) where %s = %s and removed is null",
597
               $linkageTable,
598
               $myColumn,
599
               $this->__get('id')
600
               );
601
            $queries[] = sprintf(
602
               "insert into %s ( %s, %s ) values ( %s, %s )",
603
               $linkageTable,
604
               $myColumn, 
605
               $linkedToColumn,
606
               $this->__get('id'),
607
               $newValue
608
               );
609
         }
610
         return $queries;
611
      }
612
 
65 rodolico 613
      protected function oneToManyPost( $key, $record ) {
614
         global $dbConnection;
615
 
616
         $request = $_REQUEST[$key];
617
         $queries = array();
618
         foreach ( $this->data[$key] as $index => $checked ) {
619
            if ( $checked && empty( $request[$index] ) ) { // we unchecked something
620
               $queries[] = $dbConnection->templateReplace( 
621
                  sprintf(
622
                     'delete from ~~linkageTable~~ where ~~linkageColumn~~ = %s and ~~foreignColumn~~ = %s',
623
                     $this->__get('id'),
624
                     $index
625
                     ),
626
                  $record
627
               );
628
            } elseif ( ! $checked && isset( $request[$index] ) ) { // we checked something
629
               $queries[] = $dbConnection->templateReplace( 
630
                  sprintf(
631
                     'insert into ~~linkageTable~~ (~~linkageColumn~~, ~~foreignColumn~~ ) values (%s, %s)',
632
                     $this->__get('id'),
633
                     $index
634
                     ),
635
                  $record
636
               );
637
            } // if..elseif
638
         } // foreach
639
         return $queries;
640
      }
641
 
64 rodolico 642
      /**
643
       * Posts the results of a previous form
644
       * 
645
       * After a form is filled in, will search for any values which have
646
       * changed. It will generate a separate SQL statement for each of them
647
       * and execute the queries in in batch
648
       * 
649
       * Once this is done, will reload the values from the database, so
650
       * we immediately know if there was a problem.
651
       */
63 rodolico 652
      protected function post() {
653
         global $dbConnection;
654
 
67 rodolico 655
         //print "<pre>Function Post\n" .  print_r($_REQUEST, true) . '</pre>'; die;
656
 
657
         // first, if this is a new record, just insert a blank one and get the ID.
658
         // A little bit of overhead, but it allows us
659
         if ( empty( $this->data[static::$dbStructure['table']['primaryKey']] ) ) {
660
            // by default, we pre-populate some fields and that means they won't get updated, so init structure
661
            foreach ( $this->data as $key => $record ) {
662
               if ( ! is_array( $this->data[$key] ) && $this->data[$key] )
663
                  $this->data[$key] = '';
664
            }
665
            $insertQuery = $dbConnection->insertQuery(
666
                  static::$dbStructure['table']['tableName'],
667
                  array( static::$dbStructure['table']['selectionDisplay'] => 'Blank Record' ) );
668
            $this->data[static::$dbStructure['table']['primaryKey']] = $dbConnection->insert( $insertQuery );
669
 
69 rodolico 670
            print "<pre>\n" . print_r( $this->data , true ) . "</pre>"; die;
67 rodolico 671
         }
672
 
63 rodolico 673
         $queries = array();
674
         $fields = array();
675
         foreach ( static::$dbStructure['table']['fields'] as $key => $record ) {
676
            if ( isset( $record['display'] ) && $record['display'] === false ) // we don't try to show links
677
               continue;
678
            if ( isset( $record['canEdit'] ) && ! $record['canEdit'] )
679
               continue;
69 rodolico 680
            switch ( $record['type'] ) {
681
               case '1:1H' :
682
                  if ( $_REQUEST[$key] != $this->data[$key]['id'] ) { // they have changed a value
683
                     //print "<pre>Doing 1:1H\nRequest\n" . $_REQUEST[$record['fieldname']] . "\nData" . $this->data[$record['fieldname']]['id'] . "</pre>"; die;
65 rodolico 684
                     $queries = array_merge( $queries, 
69 rodolico 685
                                 $this->post1to1History( 
686
                                    $record['linkageTable'], 
687
                                    $record['linkageColumn'], 
688
                                    $record['foreignColumn'], 
689
                                    $_REQUEST[$key]
690
                                 )
691
                              );
692
                  } // if
693
                  break;
694
               case '1:M' :
695
                  $queries = array_merge( $queries, $this->oneToManyPost( $key, $record ) );
696
                  break;
697
               default:
698
                  if ( $_REQUEST[$record['fieldname']] != $this->data[$record['fieldname']] ) { // they have changed a value
65 rodolico 699
                     $fields[$record['fieldname']] = $_REQUEST[$record['fieldname']];
69 rodolico 700
                  }
701
            } // switch
63 rodolico 702
         } // foreach
69 rodolico 703
         //print "<pre>posting fields in data\n" . print_r( $this->data, true ) . "</pre>"; die;
63 rodolico 704
         if ( count( $fields ) ) {
67 rodolico 705
            $queries[] = $dbConnection->updateQuery( 
706
                  static::$dbStructure['table']['tableName'],
707
                  array( static::$dbStructure['table']['primaryKey'] => $this->data[static::$dbStructure['table']['primaryKey']] ),
708
                  $fields );
63 rodolico 709
         } // if there are fields
65 rodolico 710
         /*
64 rodolico 711
         print "<pre>Request" . print_r( $_REQUEST, true ) . "</pre>";
712
         print "<pre>Data" . print_r( $this->data, true ) . "</pre>";
713
         print "<pre>Queries" . print_r( $queries, true ) . "</pre>"; die;
65 rodolico 714
         */
63 rodolico 715
         $dbConnection->runSQLScript( $queries );
716
         $this->loadFromDB( $this->data[static::$dbStructure['table']['primaryKey']] );
717
      } // post
718
 
719
      /**
61 rodolico 720
       * Simple controller. Will determine what action is going on, then
721
       * call the correct method, returning the HTML required
722
       */
56 rodolico 723
      public function run() {
63 rodolico 724
         if ( isset( $_REQUEST['action'] ) ) {
725
            switch ( $_REQUEST['action'] ) {
66 rodolico 726
               case 'add':
727
                  // prepopulate some fields with what we've been working on
728
                  $this->data = array();
729
                  foreach ( static::$dbStructure['table']['fields'] as $fieldname => $record ) {
730
                     if ( isset( $record['class'] ) && isset( $_SESSION['workingon'][$record['class']] ) ) {
731
                        $this->data[$record['fieldname']] = $_SESSION['workingon'][$record['class']];
732
                     } else {
733
                        $this->data[$fieldname] = '';
734
                     } // if..else
735
                  } // foreach
736
                  $this->data['id'] = 0;
737
                  //print '<pre>' . print_r( $this->data, true ) . '</pre>'; die;
738
                  // now, fall through and do the edit
739
               case 'edit':
740
                  $return = $this->edit();
741
                  break;
742
               case 'post':
743
                  $this->post();
744
                  // fall through and display the record
745
               default:
746
                  $return =  $this->display();
63 rodolico 747
            } // switch
748
         } else {
749
            $return =  $this->display();
750
         }
751
         return $return;
56 rodolico 752
      }
53 rodolico 753
   } // abstract class Camp
754
 
755
?>