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

Last change on this file since 347 was 336, checked in by quinn, 16 years ago

Minor bugfixes.

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