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

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

Updated copyright date, name to Strangecode LLC.

File size: 15.0 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-2010 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$app->sslOn();
33
34require_once 'codebase/lib/PageNumbers.inc.php';
35require_once 'codebase/lib/Cache.inc.php';
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';
40require_once 'codebase/lib/Lock.inc.php';
41require_once 'codebase/lib/Version.inc.php';
42%ADMIN_UPLOAD_INCLUDE%
43
44/********************************************************************
45* CONFIG
46********************************************************************/
47
48// Titles and navigation header.
49$nav->add(_("%TITLE%"), null);
50
51// The object to validate form input.
52$fv = new FormValidator();
53
54// Configure the prefs object.
55$tmp_prefs = new Prefs('%NAME_PLURAL%');
56$tmp_prefs->setParam(array('persistent' => false));
57
58// Configure the cache object.
59$cache = new Cache('%NAME_PLURAL%');
60$cache->setParam(array('enable' => true));
61
62%SORT_ORDER%
63
64// Instantiate page numbers. Total items are set and calculation is done in the getCachedList function.
65$page = new PageNumbers();
66$page->setPerPage(getFormData('per_page'), 100);
67$page->setPageNumber(getFormData('page_number'));
68
69// Search limiters retain their values between page requests.
70$app->carryQuery('search_query');
71$app->carryQuery('filter___///__');
72%ADMIN_UPLOAD_CONFIG%
73/********************************************************************
74* MAIN
75********************************************************************/
76 %ADMIN_UPLOAD_INIT%
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.
79if (getFormData('boomerang', false) && isset($_SERVER['HTTP_REFERER'])) {
80    $app->setBoomerangURL($_SERVER['HTTP_REFERER'], '%NAME_PLURAL%');
81}
82
83if (getFormData('break_list_cache', false)) {
84    // Remove any stale cached list data.
85    $cache->delete('list');
86}
87
88// What action to take.
89switch (getFormData('op')) {
90
91case 'add' :
92    // Initialize variables for the form template.
93    $frm =& addRecordForm();
94    $nav->add(_("Add %ITEM_TITLE%"));
95    $main_template = '%ADMIN_FORM_TEMPLATE%';
96    break;
97
98case 'edit' :
99    // Initialize variables for the form template.
100    $frm =& editRecordForm(getFormData('%PRIMARY_KEY%'));
101    $nav->add(_("Edit %ITEM_TITLE%"));
102    $main_template = '%ADMIN_FORM_TEMPLATE%';
103    break;
104
105case 'del' :
106    deleteRecord(getFormData('%PRIMARY_KEY%'));%ADMIN_UPLOAD_DEL%
107    if ($app->validBoomerangURL('%NAME_PLURAL%')) {
108        // Display boomerang page.
109        $app->dieBoomerangURL('%NAME_PLURAL%');
110    }
111    // Display default page.
112    $app->dieURL($_SERVER['PHP_SELF']);
113    break;
114
115case 'insert' :
116    if (getFormdata('cancel', false)) {
117        if ($app->validBoomerangURL('%NAME_PLURAL%')) {
118            // Display boomerang page.
119            $app->dieBoomerangURL('%NAME_PLURAL%');
120        }
121        // Display default page.
122        $app->dieURL($_SERVER['PHP_SELF']);
123    }
124    validateInput();
125    if ($fv->anyErrors()) {
126        $frm =& addRecordForm();
127        $frm = array_merge($frm, getFormData());
128        $nav->add(_("Add %ITEM_TITLE%"));
129        $main_template = '%ADMIN_FORM_TEMPLATE%';
130    } else {
131        $%PRIMARY_KEY% = insertRecord(getFormData());%ADMIN_UPLOAD_INSERT%
132        if (getFormdata('repeat', false)) {
133            // Display function again.
134            $app->dieURL($_SERVER['PHP_SELF'] . '?op=add');
135        } else if ($app->validBoomerangURL('%NAME_PLURAL%')) {
136            // Display boomerang page.
137            $app->dieBoomerangURL('%NAME_PLURAL%');
138        }
139        // Display default page.
140        $app->dieURL($_SERVER['PHP_SELF']);
141    }
142    break;
143
144case 'update' :
145    if (getFormdata('reset', false)) {
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%'));
148    }
149    if (getFormdata('cancel', false)) {
150        // Remove lock
151        $lock->select('%DB_TBL%', '%PRIMARY_KEY%', getFormData('%PRIMARY_KEY%'));
152        $lock->remove();
153        if ($app->validBoomerangURL('%NAME_PLURAL%')) {
154            // Display boomerang page.
155            $app->dieBoomerangURL('%NAME_PLURAL%');
156        }
157        // Display default page.
158        $app->dieURL($_SERVER['PHP_SELF']);
159    }
160    validateInput();
161    if ($fv->anyErrors()) {
162        $frm =& editRecordForm(getFormData('%PRIMARY_KEY%'));
163        $frm = array_merge($frm, getFormData());
164        $nav->add(_("Edit %ITEM_TITLE%"));
165        $main_template = '%ADMIN_FORM_TEMPLATE%';
166    } else {%ADMIN_UPLOAD_UPDATE%
167        updateRecord(getFormData());
168        if (getFormdata('repeat', false)) {
169            // Display edit function with next available ID.
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");
171            if (list($next_id) = mysql_fetch_row($qid)) {
172                $app->dieURL($_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . $next_id);
173            } else {
174                $app->raiseMsg(_("Cannot edit next, the end of the list was reached"), MSG_NOTICE, __FILE__, __LINE__);
175            }
176        } else if ($app->validBoomerangURL('%NAME_PLURAL%')) {
177            // Display boomerang page.
178            $app->dieBoomerangURL('%NAME_PLURAL%');
179        }
180        // Display default page.
181        $app->dieURL($_SERVER['PHP_SELF']);
182    }
183    break;
184
185case _("Save rank") :
186    updateRank(getFormData('rank'));
187    $app->dieURL($_SERVER['PHP_SELF']);
188    break;
189
190default :
191    $list =& getCachedList();
192    $main_template = '%ADMIN_LIST_TEMPLATE%';
193    break;
194}
195
196/********************************************************************
197* OUTPUT
198********************************************************************/
199
200include 'header.ihtml';
201include $main_template;
202include 'footer.ihtml';
203
204/********************************************************************
205* FUNCTIONS
206********************************************************************/
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',
216        'submit_buttons' => array(
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'),
220        ),
221    );
222
223    return $frm;
224}
225
226function &editRecordForm($id)
227{
228    global $lock;
229    $db =& DB::getInstance();
230    $app =& App::getInstance();
231   
232    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $id);
233    if ($lock->isLocked() && !$lock->isMine()) {
234        $lock->dieErrorPage();
235    }
236
237    // Get the information for the form.
238    $qid = $db->query("
239        SELECT *
240        FROM %DB_TBL%
241        WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'
242    ");
243    if (!$frm = mysql_fetch_assoc($qid)) {
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();
247    }
248
249    // Lock this record.
250    $lock->set('%DB_TBL%', '%PRIMARY_KEY%', $id, $frm['__///__']);
251
252    // Set misc values for the form.
253    $frm = array_merge(array(
254        %SET_VALUES_DEFAULT%,
255        'new_op' => 'update',
256        'submit_buttons' => array(
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'),
261        ),
262    ), $frm);
263
264    return $frm;
265}
266
267function deleteRecord($id)
268{
269    global $lock;
270    global $cache;
271    $db =& DB::getInstance();
272    $app =& App::getInstance();
273   
274    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $id);
275    if ($lock->isLocked() && !$lock->isMine()) {
276        $lock->dieErrorPage();
277    }
278
279    // Remove any stale cached list data.
280    $cache->delete('list');
281
282    // Get the information for this object.
283    $qid = $db->query("
284        SELECT __///__
285        FROM %DB_TBL%
286        WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'
287    ");
288    if (! list($name) = mysql_fetch_row($qid)) {
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();
292    }
293
294    // Delete the record.
295    $db->query("DELETE FROM %DB_TBL% WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'");
296
297    $app->raiseMsg(sprintf(_("The %ITEM_TITLE% <em>%s</em> has been deleted."), $name), MSG_SUCCESS, __FILE__, __LINE__);
298
299    // Unlock record.
300    $lock->remove();
301}
302
303function insertRecord($frm)
304{
305    global $auth;
306    global $cache;
307    $db =& DB::getInstance();
308    $app =& App::getInstance();
309   
310    // Remove any stale cached list data.
311    $cache->delete('list');
312
313%INSERT%
314    $last_insert_id = mysql_insert_id($db->getDBH());
315
316    // Create version.
317    $version = Version::getInstance($auth);
318    $version->create('%DB_TBL%', '%PRIMARY_KEY%', $last_insert_id, $frm['__///__']);
319
320    $app->raiseMsg(sprintf(_("The %ITEM_TITLE% <em>%s</em> has been added."), $frm['__///__']), MSG_SUCCESS, __FILE__, __LINE__);
321
322    return $last_insert_id;
323}
324
325function updateRecord($frm)
326{
327    global $auth;
328    global $lock;
329    global $cache;
330    $db =& DB::getInstance();
331    $app =& App::getInstance();
332   
333    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $frm['%PRIMARY_KEY%']);
334    if ($lock->isLocked() && !$lock->isMine()) {
335        $lock->dieErrorPage();
336    }
337
338    // Remove any stale cached list data.
339    $cache->delete('list');
340
341%UPDATE%
342
343    // Create version.
344    $version = Version::getInstance($auth);
345    $version->create('%DB_TBL%', '%PRIMARY_KEY%', $frm['%PRIMARY_KEY%'], $frm['__///__']);
346
347    $app->raiseMsg(sprintf(_("The %ITEM_TITLE% <em>%s</em> has been updated."), $frm['__///__']), MSG_SUCCESS, __FILE__, __LINE__);
348
349    // Unlock record.
350    $lock->remove();
351}
352
353function &getCachedList()
354{
355    global $page;
356    global $so;
357    global $tmp_prefs;
358    global $cache;
359    $db =& DB::getInstance();   
360    $app =& App::getInstance();
361   
362    $where_clause = '';
363
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    }
371
372    if (getFormData('filter___///__', false)) {
373        // Limit by filter.
374        $where_clause .= (empty($where_clause) ? 'WHERE' : 'AND') . " __///__ = '" . $db->escapeString(getFormData('filter___///__')) . "'";
375    }
376
377    // Count the total number of records so we can do something about the page numbers.
378    $qid = $db->query("
379        SELECT COUNT(*)
380        FROM %DB_TBL%
381        $where_clause
382    ");
383    list($num_results) = mysql_fetch_row($qid);
384
385    // Set page numbers now we know (needed for next step).
386    $page->setTotalItems($num_results);
387    $page->calculate();
388
389    // Final SQL, with sort and page limiters.
390    $sql = "
391        SELECT
392            %DB_TBL%.*,
393            a1.username AS added_by_username,
394            a2.username AS modified_by_username
395        FROM %DB_TBL%
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)
398        $where_clause
399        " . $so->getSortOrderSQL() . "
400        " . $page->getLimitSQL() . "
401    ";
402
403    // Use a cash hash to determine if the result-set has changed.
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);
410    if ($tmp_prefs->get('cache_hash') != $cache_hash) {
411        $cache->delete('list');
412        $tmp_prefs->set('cache_hash', $cache_hash);
413    }
414
415    // First try to return from the cache.
416    if ($cache->exists('list')) {
417        $list = $cache->get('list');
418        return $list;
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    }
426
427    // Save this list into the cache.
428    if (isset($list) && !empty($list)) {
429        $cache->set('list', $list);
430    }
431
432    return $list;
433}
434
435function updateRank($ranks)
436{
437    global $cache;
438    $db =& DB::getInstance();
439    $app =& App::getInstance();
440   
441    if (!is_array($ranks)) {
442        $app->logMsg('Saving rank failed, data posted is not an array: ' . $ranks, LOG_ERR, __FILE__, __LINE__);
443        return false;
444    }
445
446    // Remove any stale cached list data.
447    $cache->delete('list');
448
449    // Count the ranks with invalid numbers
450    $unspecified_counter = 0;
451
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) {
455            // Unspecified entries receive a sort order of 10000.
456            $new_rank = 10000;
457            $unspecified_counter++;
458        }
459        $db->query("
460            UPDATE %DB_TBL% SET
461                rank = '" . $db->escapeString($new_rank) . "'
462            WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'
463        ");
464    }
465
466    $app->raiseMsg(_("Records have been reordered with the new rank."), MSG_SUCCESS, __FILE__, __LINE__);
467    if ($unspecified_counter > 0) {
468        $app->raiseMsg(sprintf(_("%s items with unspecified ranks were automatically assigned a rank of 10000."), $unspecified_counter), MSG_NOTICE, __FILE__, __LINE__);
469    }
470}
471
472?>
Note: See TracBrowser for help on using the repository browser.