Subversion Repositories computer_asset_manager_v2

Rev

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