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

Last change on this file since 336 was 336, checked in by quinn, 16 years ago

Minor bugfixes.

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