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

Last change on this file since 655 was 655, checked in by anonymous, 5 years ago

Update module_maker. Minor fixes.

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