source: tags/1.0.0/bin/module_maker/skel/admin.php @ 1

Last change on this file since 1 was 1, checked in by scdev, 19 years ago

Initial import.

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