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

Last change on this file since 601 was 558, checked in by anonymous, 9 years ago

Minor fixes

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