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

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

Q - updated usage of $nav.

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