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

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

Tons of little updates and bugfixes. CSS updates to templates and core css files. File upload ability to module_maker. Remade Upload interface to use setParam/getParam.

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