Subversion Repositories computer_asset_manager_v2

Rev

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