source: tags/2.1.5/bin/module_maker/skel/admin.php @ 377

Last change on this file since 377 was 377, checked in by quinn, 14 years ago

Releasing trunk as stable version 2.1.5

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