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

Last change on this file since 767 was 767, checked in by anonymous, 2 years ago

Add App param ‘template_ext’ used to inform services where to find header and footer templates. Minor fixes.

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