source: trunk/bin/module_maker/skel/admin.php @ 137

Last change on this file since 137 was 137, checked in by scdev, 18 years ago

Q - Renamed SessionCache? to Cache, RecordVersion? to Version, and RecordLock? to Lock

File size: 14.6 KB
RevLine 
[1]1<?php
2/**
3 * %ADMIN_SCRIPT%
4 * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information
5 *
6 * Generated by module_maker.cli.php on %DATE%
7 */
8
9require_once dirname(__FILE__) . '/_config.inc.php';
10
11$auth->requireLogin();
12// $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%);
[136]13$app->sslOn();
[1]14
15require_once 'codebase/lib/PageNumbers.inc.php';
16require_once 'codebase/lib/SessionCache.inc.php';
17require_once 'codebase/lib/FormValidator.inc.php';
18require_once 'codebase/lib/SortOrder.inc.php';
19require_once 'codebase/lib/TemplateGlue.inc.php';
20require_once 'codebase/lib/Prefs.inc.php';
[137]21require_once 'codebase/lib/Lock.inc.php';
22require_once 'codebase/lib/Version.inc.php';
[20]23%ADMIN_UPLOAD_INCLUDE%
[1]24
25/******************************************************************************
26 * CONFIG
27 *****************************************************************************/
[42]28
[1]29// Titles and navigation header.
30$nav->addPage(_("%TITLE%"), $_SERVER['PHP_SELF']);
[42]31
[1]32// The object to validate form input.
33$fv = new FormValidator();
34
[136]35$cache =& SessionCache::getInstance();
36
[1]37%SORT_ORDER%
38
39// Instantiate page numbers. Total items are set and calculation is done in the getRecordList function.
40$page = new PageNumbers();
41$page->setPerPage(getFormData('per_page'), 100);
42$page->setPageNumber(getFormData('page_number'));
43
[20]44// Search limiters retain their values between page requests.
[136]45$app->carryQuery('search_query');
46$app->carryQuery('filter_<##>');
[20]47%ADMIN_UPLOAD_CONFIG%
[1]48/******************************************************************************
49 * MAIN
50 *****************************************************************************/
[20]51 %ADMIN_UPLOAD_INIT%
[1]52// We may want to use the add/edit interface from another script, so this
53// allows us to remember which page we came from so we can go back there.
[20]54if (getFormData('boomerang', false) && isset($_SERVER['HTTP_REFERER'])) {
[136]55    $app->setBoomerangURL($_SERVER['HTTP_REFERER'], '%NAME_PLURAL%');
[1]56}
57
58if (getFormData('break_list_cache', false)) {
59    // Break the cache because we are changing the list data.
[136]60    $cache->delete($_SERVER['PHP_SELF']);
[1]61}
62
63// What action to take.
64switch (getFormData('op')) {
65
66case 'add' :
67//     $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%_FUNC_ADD);
68    // Initialize variables for the form template.
69    $frm =& addRecordForm();
70    $nav->addPage(_("Add %ITEM_TITLE%"));
71    $main_template = '%ADMIN_FORM_TEMPLATE%';
72    break;
73
74case 'edit' :
75//     $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%_FUNC_EDIT);
76    // Initialize variables for the form template.
77    $frm =& editRecordForm(getFormData('%PRIMARY_KEY%'));
78    $nav->addPage(_("Edit %ITEM_TITLE%"));
79    $main_template = '%ADMIN_FORM_TEMPLATE%';
80    break;
81
82case 'del' :
83//     $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%_FUNC_DELETE);
[20]84    deleteRecord(getFormData('%PRIMARY_KEY%'));%ADMIN_UPLOAD_DEL%
[136]85    if ($app->validBoomerangURL('%NAME_PLURAL%')) {
[1]86        // Display boomerang page.
[136]87        $app->dieBoomerangURL('%NAME_PLURAL%');
[1]88    }
89    // Display default page.
[136]90    $app->dieURL($_SERVER['PHP_SELF']);
[1]91    break;
92
93case 'insert' :
94//     $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%_FUNC_ADD);
95    if (getFormdata('cancel', false)) {
[136]96        if ($app->validBoomerangURL('%NAME_PLURAL%')) {
[22]97            // Display boomerang page.
[136]98            $app->dieBoomerangURL('%NAME_PLURAL%');
[22]99        }
100        // Display default page.
[136]101        $app->dieURL($_SERVER['PHP_SELF']);
[1]102    }
103    validateInput();
104    if ($fv->anyErrors()) {
105        $frm =& addRecordForm();
106        $frm = array_merge($frm, getFormData());
107        $nav->addPage(_("Add %ITEM_TITLE%"));
108        $main_template = '%ADMIN_FORM_TEMPLATE%';
[22]109    } else {
110        $%PRIMARY_KEY% = insertRecord(getFormData());%ADMIN_UPLOAD_INSERT%
[1]111        if (getFormdata('repeat', false)) {
112            // Display function again.
[136]113            $app->dieURL($_SERVER['PHP_SELF'] . '?op=add');
114        } else if ($app->validBoomerangURL('%NAME_PLURAL%')) {
[1]115            // Display boomerang page.
[136]116            $app->dieBoomerangURL('%NAME_PLURAL%');
[1]117        }
118        // Display default page.
[136]119        $app->dieURL($_SERVER['PHP_SELF']);
[1]120    }
121    break;
122
123case 'update' :
124//     $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%_FUNC_EDIT);
125    if (getFormdata('reset', false)) {
[136]126        $app->raiseMsg(_("Saved values have been reloaded."), MSG_NOTICE, __FILE__, __LINE__);
127        $app->dieURL($_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . getFormData('%PRIMARY_KEY%'));
[1]128    }
129    if (getFormdata('cancel', false)) {
130        // Remove lock
131        $lock->select('%DB_TBL%', '%PRIMARY_KEY%', getFormData('%PRIMARY_KEY%'));
132        $lock->remove();
[136]133        if ($app->validBoomerangURL('%NAME_PLURAL%')) {
[1]134            // Display boomerang page.
[136]135            $app->dieBoomerangURL('%NAME_PLURAL%');
[1]136        }
137        // Display default page.
[136]138        $app->dieURL($_SERVER['PHP_SELF']);
[1]139    }
140    validateInput();
141    if ($fv->anyErrors()) {
142        $frm =& editRecordForm(getFormData('%PRIMARY_KEY%'));
143        $frm = array_merge($frm, getFormData());
144        $nav->addPage(_("Edit %ITEM_TITLE%"));
145        $main_template = '%ADMIN_FORM_TEMPLATE%';
[20]146    } else {%ADMIN_UPLOAD_UPDATE%
[1]147        updateRecord(getFormData());
148        if (getFormdata('repeat', false)) {
149            // Display edit function with next available ID.
[136]150            $qid = $db->query("SELECT %PRIMARY_KEY% FROM %DB_TBL% WHERE %PRIMARY_KEY% > '" . $db->escapeString(getFormData('%PRIMARY_KEY%')) . "' ORDER BY %PRIMARY_KEY% ASC LIMIT 1");
[1]151            if (list($next_id) = mysql_fetch_row($qid)) {
[136]152                $app->dieURL($_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . $next_id);
[1]153            } else {
[136]154                $app->raiseMsg(_("Cannot edit next, the end of the list was reached"), MSG_NOTICE, __FILE__, __LINE__);
[1]155            }
[136]156        } else if ($app->validBoomerangURL('%NAME_PLURAL%')) {
[1]157            // Display boomerang page.
[136]158            $app->dieBoomerangURL('%NAME_PLURAL%');
[1]159        }
160        // Display default page.
[136]161        $app->dieURL($_SERVER['PHP_SELF']);
[1]162    }
163    break;
164
165case _("Save rank") :
166//     $auth->requireAccessClearance(ZONE_ADMIN_PROGRAMS_FUNC_REORDER);
167    updateRank(getFormData('rank'));
[136]168    $app->dieURL($_SERVER['PHP_SELF']);
[1]169    break;
170
171default :
172//     $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%_FUNC_LIST, _("Permission to view %NAME_PLURAL% list denied."));
173    $list =& getRecordList();
174    $main_template = '%ADMIN_LIST_TEMPLATE%';
175    break;
176}
177
178/******************************************************************************
179 * TEMPLATE INITIALIZATION
180 *****************************************************************************/
181
182include 'header.ihtml';
183include $main_template;
184include 'footer.ihtml';
185
186/******************************************************************************
187 * FUNCTIONS
188 *****************************************************************************/
189
190%FORM_VALIDATION%
191
192function &addRecordForm()
193{
194    // Set default values for the reset of the fields.
195    $frm = array(
196        %SET_VALUES_DEFAULT%,
197        'new_op' => 'insert',
[10]198        'submit_buttons' => array(
199            'submit' => _("Add %ITEM_TITLE%"),
200            'repeat' => _("Add &amp; repeat"),
201            'cancel' => _("Cancel"),
[1]202        ),
203    );
204
205    return $frm;
206}
207
208function &editRecordForm($id)
209{
[22]210    global $lock;
[136]211    $db =& DB::getInstance();
212   
[1]213    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $id);
214    if ($lock->isLocked() && !$lock->isMine()) {
215        $lock->dieErrorPage();
[10]216    }
217
218    // Get the information for the form.
[136]219    $qid = $db->query("
[42]220        SELECT *
[10]221        FROM %DB_TBL%
[136]222        WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'
[10]223    ");
224    if (!$frm = mysql_fetch_assoc($qid)) {
[136]225        $app->logMsg('Could not find record with %PRIMARY_KEY%: ' . $id, LOG_WARNING, __FILE__, __LINE__);
226        $app->raiseMsg(sprintf(_("The requested record %s could not be found."), $id), MSG_ERR, __FILE__, __LINE__);
227        $app->dieBoomerangURL();
[10]228    }
229
230    // Lock this record.
[19]231    $lock->set('%DB_TBL%', '%PRIMARY_KEY%', $id, $frm['<##>']);
[42]232
[10]233    // Set misc values for the form.
234    $frm = array_merge(array(
235        %SET_VALUES_DEFAULT%,
236        'new_op' => 'update',
237        'submit_buttons' => array(
238            'submit' => _("Save changes"),
239            'repeat' => _("Save &amp; edit next"),
240            'reset' => _("Reset"),
241            'cancel' => _("Cancel"),
242        ),
243    ), $frm);
244
245    return $frm;
[1]246}
247
248function deleteRecord($id)
249{
[22]250    global $lock;
[136]251    $db =& DB::getInstance();
252    $cache =& SessionCache::getInstance();
253   
[1]254    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $id);
255    if ($lock->isLocked() && !$lock->isMine()) {
256        $lock->dieErrorPage();
[21]257    }
[1]258
[21]259    // Break the cache because we are changing the list data.
[136]260    $cache->delete($_SERVER['PHP_SELF']);
[42]261
[21]262    // Get the information for this object.
[136]263    $qid = $db->query("
[42]264        SELECT <##>
[21]265        FROM %DB_TBL%
[136]266        WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'
[21]267    ");
268    if (! list($name) = mysql_fetch_row($qid)) {
[136]269        $app->logMsg('Could not find record with %PRIMARY_KEY%: ' . $id, LOG_WARNING, __FILE__, __LINE__);
270        $app->raiseMsg(sprintf(_("The requested record %s could not be found."), $id), MSG_ERR, __FILE__, __LINE__);
271        $app->dieBoomerangURL();
[1]272    }
[42]273
[21]274    // Delete the record.
[136]275    $db->query("DELETE FROM %DB_TBL% WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'");
[42]276
[136]277    $app->raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been deleted."), $name), MSG_SUCCESS, __FILE__, __LINE__);
[21]278
279    // Unlock record.
280    $lock->remove();
[1]281}
282
283function insertRecord($frm)
284{
285    global $auth;
[136]286    $db =& DB::getInstance();
287    $cache =& SessionCache::getInstance();
288   
[1]289    // Break the cache because we are changing the list data.
[136]290    $cache->delete($_SERVER['PHP_SELF']);
[42]291
[1]292%INSERT%
[136]293    $last_insert_id = mysql_insert_id($db->getDBH());
[1]294
295    // Create version.
[137]296    $version = Version::getInstance($GLOBALS['auth']);
[1]297    $version->create('%DB_TBL%', '%PRIMARY_KEY%', $last_insert_id, $frm['<##>']);
[42]298
[136]299    $app->raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been added."), $frm['<##>']), MSG_SUCCESS, __FILE__, __LINE__);
[42]300
[1]301    return $last_insert_id;
302}
303
304function updateRecord($frm)
305{
[136]306    global $auth, $lock;
307    $app =& App::getInstance();
308    $cache =& SessionCache::getInstance();
309   
[1]310    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $frm['%PRIMARY_KEY%']);
311    if ($lock->isLocked() && !$lock->isMine()) {
312        $lock->dieErrorPage();
[21]313    }
[1]314
[21]315    // Break the cache because we are changing the list data.
[136]316    $cache->delete($_SERVER['PHP_SELF']);
[21]317
[1]318%UPDATE%
[42]319
[21]320    // Create version.
[137]321    $version = Version::getInstance($GLOBALS['auth']);
[21]322    $version->create('%DB_TBL%', '%PRIMARY_KEY%', $frm['%PRIMARY_KEY%'], $frm['<##>']);
[1]323
[136]324    $app->raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been updated."), $frm['<##>']), MSG_SUCCESS, __FILE__, __LINE__);
[21]325
326    // Unlock record.
327    $lock->remove();
[1]328}
329
330function &getRecordList()
331{
332    global $page;
333    global $so;
[136]334    $db =& DB::getInstance();
335    $prefs =& Prefs::getInstance();
336    $cache =& SessionCache::getInstance();
337   
[1]338    $where_clause = '';
[42]339
[1]340    // Build search query if available.
341    if (getFormData('search_query', false)) {
342        $qry_words = preg_split('/[^\w]/', getFormData('search_query'));
343        for ($i=0; $i<sizeof($qry_words); $i++) {
344%SEARCH%
345        }
346    }
[42]347
[1]348    if (getFormData('filter_<##>', false)) {
349        // Limit by filter.
[136]350        $where_clause .= (empty($where_clause) ? 'WHERE' : 'AND') . " <##> = '" . $db->escapeString(getFormData('filter_<##>')) . "'";
[1]351    }
[42]352
[1]353    // Count the total number of records so we can do something about the page numbers.
[136]354    $qid = $db->query("
[42]355        SELECT COUNT(*)
356        FROM %DB_TBL%
[1]357        $where_clause
358    ");
359    list($num_results) = mysql_fetch_row($qid);
[42]360
[1]361    // Set page numbers now we know (needed for next step).
362    $page->setTotalItems($num_results);
363    $page->calculate();
[42]364
[1]365    // Final SQL, with sort and page limiters.
366    $sql = "
[42]367        SELECT
368            %DB_TBL%.*,
[1]369            a1.username AS added_admin_username,
370            a2.username AS modified_admin_username
371        FROM %DB_TBL%
[19]372        LEFT JOIN admin_tbl a1 ON (%DB_TBL%.added_by_user_id = a1.admin_id)
373        LEFT JOIN admin_tbl a2 ON (%DB_TBL%.modified_by_user_id = a2.admin_id)
[1]374        $where_clause
375        " . $so->getSortOrderSQL() . "
376        " . $page->getLimitSQL() . "
377    ";
[42]378
[1]379    // A unique key for this query, with the total_items in case db records
380    // were added since the last cache. This identifies a unique set of
381    // cached data, but we must refer to the list that is cached by a more
382    // generic name. so that we can flush the cache (if records updated)
383    // without knowing the hash.
384    $cache_hash = md5($sql . '|' . $page->total_items);
[136]385    if ($prefs->get('cache_hash', $_SERVER['PHP_SELF']) != $cache_hash) {
386        $cache->delete($_SERVER['PHP_SELF']);
387        $prefs->set('cache_hash', $cache_hash, $_SERVER['PHP_SELF']);
[1]388    }
[42]389
[136]390    if ($cache->exists($_SERVER['PHP_SELF'])) {
[1]391        // Get the cached results.
[136]392        $list = $cache->get($_SERVER['PHP_SELF']);
[1]393    } else {
394        // If the list is not already cached, query now.
[136]395        $qid = $db->query($sql);
[1]396        // Fill an array with the items for this page.
397        while ($row = mysql_fetch_assoc($qid)) {
398            $list[] = $row;
399        }
[42]400
[1]401        if (isset($list) && !empty($list)) {
402            // Cache the results.
[136]403            $cache->set($list, $_SERVER['PHP_SELF']);
[1]404        }
405    }
406
407    return $list;
408}
409
410function updateRank($ranks)
[42]411{
[136]412    $db =& DB::getInstance();
413    $cache =& SessionCache::getInstance();
414   
[1]415    if (!is_array($ranks)) {
[136]416        $app->logMsg('Saving rank failed, data posted is not an array: ' . $ranks, LOG_ERR, __FILE__, __LINE__);
[1]417        return false;
418    }
419
420    // Break the cache because we are changing the list data.
[136]421    $cache->delete($_SERVER['PHP_SELF']);
[42]422
[1]423    // Count the ranks with invalid numbers
424    $unspecified_counter = 0;
[42]425
[1]426    // Go through the array of new ranks.
427    foreach ($ranks as $id => $new_rank) {
428        if ('' == trim($new_rank) || !is_numeric($new_rank) || $new_rank > 2147483646) {
[20]429            // Unspecified entries receive a sort order of 10000.
430            $new_rank = 10000;
[42]431            $unspecified_counter++;
[1]432        }
[136]433        $db->query("
[1]434            UPDATE %DB_TBL% SET
[136]435                rank = '" . $db->escapeString($new_rank) . "'
436            WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'
[1]437        ");
438    }
[42]439
[136]440    $app->raiseMsg(_("Records have been reordered with the new rank."), MSG_SUCCESS, __FILE__, __LINE__);
[1]441    if ($unspecified_counter > 0) {
[136]442        $app->raiseMsg(sprintf(_("%s items with unspecified ranks were automatically assigned a rank of 10000."), $unspecified_counter), MSG_NOTICE, __FILE__, __LINE__);
[1]443    }
444}
445
446?>
Note: See TracBrowser for help on using the repository browser.