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

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

Q - Finished depreciating addslashes. array_map instances need to use array('DB', 'escapeString') as first argument.

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