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

Last change on this file since 202 was 202, checked in by scdev, 18 years ago

Q - updated usage of $nav.

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