source: trunk/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: 14.2 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%);
13App::sslOn();
14
15require_once 'codebase/lib/PageNumbers.inc.php';
16require_once 'codebase/lib/SessionCache.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/RecordLock.inc.php';
22require_once 'codebase/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    App::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//     $auth->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//     $auth->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//     $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%_FUNC_DELETE);
78    deleteRecord(getFormData('%PRIMARY_KEY%'));
79    if (App::validBoomerangURL('%NAME_PLURAL%')) {
80        // Display boomerang page.
81        App::dieBoomerangURL('%NAME_PLURAL%');
82    }
83    // Display default page.
84    App::dieURL($_SERVER['PHP_SELF']);
85    break;
86
87case 'insert' :
88//     $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%_FUNC_ADD);
89    if (getFormdata('cancel', false)) {
90        App::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            App::dieURL($_SERVER['PHP_SELF'] . '?op=add');
103        } else if (App::validBoomerangURL('%NAME_PLURAL%')) {
104            // Display boomerang page.
105            App::dieBoomerangURL('%NAME_PLURAL%');
106        }
107        // Display default page.
108        App::dieURL($_SERVER['PHP_SELF']);
109    }
110    break;
111
112case 'update' :
113//     $auth->requireAccessClearance(ZONE_ADMIN_%NAME_UPPER%_FUNC_EDIT);
114    if (getFormdata('reset', false)) {
115        App::raiseMsg(_("Saved values have been reloaded."), MSG_NOTICE, __FILE__, __LINE__);
116        App::dieURL($_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . getFormData('%PRIMARY_KEY%'));
117    }
118    if (getFormdata('cancel', false)) {
119        // Remove lock
120        $lock =& RecordLock::getInstance($GLOBALS['auth']);
121        $lock->select('%DB_TBL%', '%PRIMARY_KEY%', getFormData('%PRIMARY_KEY%'));
122        $lock->remove();
123        if (App::validBoomerangURL('%NAME_PLURAL%')) {
124            // Display boomerang page.
125            App::dieBoomerangURL('%NAME_PLURAL%');
126        }
127        // Display default page.
128        App::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 = DB::query("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                App::dieURL($_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . $next_id);
143            } else {
144                App::raiseMsg(_("Cannot edit next, the end of the list was reached"), MSG_NOTICE, __FILE__, __LINE__);
145            }
146        } else if (App::validBoomerangURL('%NAME_PLURAL%')) {
147            // Display boomerang page.
148            App::dieBoomerangURL('%NAME_PLURAL%');
149        }
150        // Display default page.
151        App::dieURL($_SERVER['PHP_SELF']);
152    }
153    break;
154
155case _("Save rank") :
156//     $auth->requireAccessClearance(ZONE_ADMIN_PROGRAMS_FUNC_REORDER);
157    updateRank(getFormData('rank'));
158    App::dieURL($_SERVER['PHP_SELF']);
159    break;
160
161default :
162//     $auth->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 = array(
186        %SET_VALUES_DEFAULT%,
187        'new_op' => 'insert',
188        'submit_buttons' = array(
189            'submit'   => _("Add %ITEM_TITLE%"),
190            'repeat'   => _("Add &amp; repeat"),
191            'cancel'   => _("Cancel")
192        ),
193    );
194
195    return $frm;
196}
197
198function &editRecordForm($id)
199{
200    $lock =& RecordLock::getInstance($GLOBALS['auth']);
201    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $id);
202    if ($lock->isLocked() && !$lock->isMine()) {
203        $lock->dieErrorPage();
204    } else {
205        // Get the information for the form.
206        $qid = DB::query("
207            SELECT *
208            FROM %DB_TBL%
209            WHERE %PRIMARY_KEY% = '" . addslashes($id) . "'
210        ");
211        if (!$frm = mysql_fetch_assoc($qid)) {
212            App::logMsg('Could not find record with %PRIMARY_KEY%: ' . $id, LOG_WARNING, __FILE__, __LINE__);
213            App::raiseMsg(sprintf(_("The requested record %s could not be found"), $id), MSG_ERR, __FILE__, __LINE__);
214            App::dieBoomerangURL();
215        }
216   
217        // Lock this record.
218        $lock->set('%DB_TBL%', '%PRIMARY_KEY%', $id, $frm['address']);
219       
220        // Set misc values for the form.
221        $frm['new_op'] = 'update';
222        $frm['submit_caption'] = _("Save changes");
223        $frm['repeat_caption'] = _("Save &amp; edit next");
224        $frm['reset_caption']  = _("Reset");
225        $frm['cancel_caption'] = _("Cancel");
226        $frm['%PRIMARY_KEY%'] = $id;
227   
228        return $frm;
229    }
230}
231
232function deleteRecord($id)
233{
234    $lock =& RecordLock::getInstance($GLOBALS['auth']);
235    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $id);
236    if ($lock->isLocked() && !$lock->isMine()) {
237        $lock->dieErrorPage();
238    } else {
239        // Break the cache because we are changing the list data.
240        SessionCache::breakCache($_SERVER['PHP_SELF']);
241       
242        // Get the information for this object.
243        $qid = DB::query("
244            SELECT <##>
245            FROM %DB_TBL%
246            WHERE %PRIMARY_KEY% = '" . addslashes($id) . "'
247        ");
248        if (! list($name) = mysql_fetch_row($qid)) {
249            App::logMsg('Could not find record with %PRIMARY_KEY%: ' . $id, LOG_WARNING, __FILE__, __LINE__);
250            App::raiseMsg(sprintf(_("The requested record %s could not be found"), $id), MSG_ERR, __FILE__, __LINE__);
251            App::dieBoomerangURL();
252        }
253       
254        // Delete the record.
255        DB::query("DELETE FROM %DB_TBL% WHERE %PRIMARY_KEY% = '" . addslashes($id) . "'");
256       
257        App::raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been deleted."), $name), MSG_SUCCESS, __FILE__, __LINE__);
258
259        // Unlock record.
260        $lock->remove();
261    }
262}
263
264function insertRecord($frm)
265{
266    global $auth;
267   
268    // Break the cache because we are changing the list data.
269    SessionCache::breakCache($_SERVER['PHP_SELF']);
270   
271%INSERT%
272    $last_insert_id = mysql_insert_id(DB::getDBH());
273
274    // Create version.
275    $version = new RecordVersion();
276    $version->create('%DB_TBL%', '%PRIMARY_KEY%', $last_insert_id, $frm['<##>']);
277   
278    App::raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been added."), $frm['<##>']), MSG_SUCCESS, __FILE__, __LINE__);
279   
280    return $last_insert_id;
281}
282
283function updateRecord($frm)
284{
285    global $auth;
286   
287    $lock =& RecordLock::getInstance($GLOBALS['auth']);
288    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $frm['%PRIMARY_KEY%']);
289    if ($lock->isLocked() && !$lock->isMine()) {
290        $lock->dieErrorPage();
291    } else {
292        // Break the cache because we are changing the list data.
293        SessionCache::breakCache($_SERVER['PHP_SELF']);
294
295%UPDATE%
296       
297        // Create version.
298        $version = new RecordVersion();
299        $version->create('%DB_TBL%', '%PRIMARY_KEY%', $frm['%PRIMARY_KEY%'], $frm['<##>']);
300   
301        App::raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been updated."), $frm['<##>']), MSG_SUCCESS, __FILE__, __LINE__);
302
303        // Unlock record.
304        $lock->remove();
305    }
306}
307
308function &getRecordList()
309{
310    global $page;
311    global $so;
312   
313    $where_clause = '';
314   
315    // Build search query if available.
316    if (getFormData('search_query', false)) {
317        $qry_words = preg_split('/[^\w]/', getFormData('search_query'));
318        for ($i=0; $i<sizeof($qry_words); $i++) {
319%SEARCH%
320        }
321    }
322   
323    if (getFormData('filter_<##>', false)) {
324        // Limit by filter.
325        $where_clause .= (empty($where_clause) ? 'WHERE' : 'AND') . " <##> = '" . addslashes(getFormData('filter_<##>')) . "'";
326    }
327   
328    // Count the total number of records so we can do something about the page numbers.
329    $qid = DB::query("
330        SELECT COUNT(*)
331        FROM %DB_TBL%
332        $where_clause
333    ");
334    list($num_results) = mysql_fetch_row($qid);
335   
336    // Set page numbers now we know (needed for next step).
337    $page->setTotalItems($num_results);
338    $page->calculate();
339   
340    // Final SQL, with sort and page limiters.
341    $sql = "
342        SELECT
343            %DB_TBL%.*,
344            a1.username AS added_admin_username,
345            a2.username AS modified_admin_username
346        FROM %DB_TBL%
347        LEFT JOIN admin_tbl a1 ON (%DB_TBL%.added_by_admin_id = a1.admin_id)
348        LEFT JOIN admin_tbl a2 ON (%DB_TBL%.modified_by_admin_id = a2.admin_id)
349        $where_clause
350        " . $so->getSortOrderSQL() . "
351        " . $page->getLimitSQL() . "
352    ";
353   
354    // A unique key for this query, with the total_items in case db records
355    // were added since the last cache. This identifies a unique set of
356    // cached data, but we must refer to the list that is cached by a more
357    // generic name. so that we can flush the cache (if records updated)
358    // without knowing the hash.
359    $cache_hash = md5($sql . '|' . $page->total_items);
360    if (Prefs::getValue('cache_hash', $_SERVER['PHP_SELF']) != $cache_hash) {
361        SessionCache::breakCache($_SERVER['PHP_SELF']);
362        Prefs::setValue('cache_hash', $cache_hash, $_SERVER['PHP_SELF']);
363    }
364   
365    if (SessionCache::isCached($_SERVER['PHP_SELF'])) {
366        // Get the cached results.
367        $list = SessionCache::getCache($_SERVER['PHP_SELF']);
368    } else {
369        // If the list is not already cached, query now.
370        $qid = DB::query($sql);
371        // Fill an array with the items for this page.
372        while ($row = mysql_fetch_assoc($qid)) {
373            $list[] = $row;
374        }
375           
376        if (isset($list) && !empty($list)) {
377            // Cache the results.
378            SessionCache::putCache($list, $_SERVER['PHP_SELF']);
379        }
380    }
381
382    return $list;
383}
384
385function updateRank($ranks)
386{   
387    if (!is_array($ranks)) {
388        App::logMsg('Saving rank failed, data posted is not an array: ' . $ranks, LOG_ERR, __FILE__, __LINE__);
389        return false;
390    }
391
392    // Break the cache because we are changing the list data.
393    SessionCache::breakCache($_SERVER['PHP_SELF']);
394   
395    // Count the ranks with invalid numbers
396    $unspecified_counter = 0;
397   
398    // Go through the array of new ranks.
399    foreach ($ranks as $id => $new_rank) {
400        if ('' == trim($new_rank) || !is_numeric($new_rank) || $new_rank > 2147483646) {
401            // Unspecified entries recieve a sort order of 1000.
402            $new_rank = 1000;
403            $unspecified_counter++; 
404        }
405        DB::query("
406            UPDATE %DB_TBL% SET
407                rank = '" . addslashes($new_rank) . "'
408            WHERE %PRIMARY_KEY% = '" . addslashes($id) . "'
409        ");
410    }
411   
412    App::raiseMsg(_("Records have been reordered with the new rank."), MSG_SUCCESS, __FILE__, __LINE__);
413    if ($unspecified_counter > 0) {
414        App::raiseMsg(sprintf(_("%s items with unspecified ranks were automatically assigned a rank of 1000."), $unspecified_counter), MSG_NOTICE, __FILE__, __LINE__);
415    }
416}
417
418?>
Note: See TracBrowser for help on using the repository browser.