source: branches/2.0singleton/bin/module_maker/skel/admin.php @ 131

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

finished updating DB:: to $db->

File size: 14.4 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/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.
43$app->carryQuery('search_query');
44$app->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    $db =& DB::getInstance();
210   
211    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $id);
212    if ($lock->isLocked() && !$lock->isMine()) {
213        $lock->dieErrorPage();
214    }
215
216    // Get the information for the form.
217    $qid = $db->query("
218        SELECT *
219        FROM %DB_TBL%
220        WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'
221    ");
222    if (!$frm = mysql_fetch_assoc($qid)) {
223        $app->logMsg('Could not find record with %PRIMARY_KEY%: ' . $id, LOG_WARNING, __FILE__, __LINE__);
224        $app->raiseMsg(sprintf(_("The requested record %s could not be found."), $id), MSG_ERR, __FILE__, __LINE__);
225        $app->dieBoomerangURL();
226    }
227
228    // Lock this record.
229    $lock->set('%DB_TBL%', '%PRIMARY_KEY%', $id, $frm['<##>']);
230
231    // Set misc values for the form.
232    $frm = array_merge(array(
233        %SET_VALUES_DEFAULT%,
234        'new_op' => 'update',
235        'submit_buttons' => array(
236            'submit' => _("Save changes"),
237            'repeat' => _("Save &amp; edit next"),
238            'reset' => _("Reset"),
239            'cancel' => _("Cancel"),
240        ),
241    ), $frm);
242
243    return $frm;
244}
245
246function deleteRecord($id)
247{
248    global $lock;
249    $db =& DB::getInstance();
250   
251    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $id);
252    if ($lock->isLocked() && !$lock->isMine()) {
253        $lock->dieErrorPage();
254    }
255
256    // Break the cache because we are changing the list data.
257    SessionCache::breakCache($_SERVER['PHP_SELF']);
258
259    // Get the information for this object.
260    $qid = $db->query("
261        SELECT <##>
262        FROM %DB_TBL%
263        WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'
264    ");
265    if (! list($name) = mysql_fetch_row($qid)) {
266        $app->logMsg('Could not find record with %PRIMARY_KEY%: ' . $id, LOG_WARNING, __FILE__, __LINE__);
267        $app->raiseMsg(sprintf(_("The requested record %s could not be found."), $id), MSG_ERR, __FILE__, __LINE__);
268        $app->dieBoomerangURL();
269    }
270
271    // Delete the record.
272    $db->query("DELETE FROM %DB_TBL% WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'");
273
274    $app->raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been deleted."), $name), MSG_SUCCESS, __FILE__, __LINE__);
275
276    // Unlock record.
277    $lock->remove();
278}
279
280function insertRecord($frm)
281{
282    global $auth;
283    $db =& DB::getInstance();
284   
285    // Break the cache because we are changing the list data.
286    SessionCache::breakCache($_SERVER['PHP_SELF']);
287
288%INSERT%
289    $last_insert_id = mysql_insert_id($db->getDBH());
290
291    // Create version.
292    $version = RecordVersion::getInstance($GLOBALS['auth']);
293    $version->create('%DB_TBL%', '%PRIMARY_KEY%', $last_insert_id, $frm['<##>']);
294
295    $app->raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been added."), $frm['<##>']), MSG_SUCCESS, __FILE__, __LINE__);
296
297    return $last_insert_id;
298}
299
300function updateRecord($frm)
301{
302    global $auth, $lock;
303
304    $lock->select('%DB_TBL%', '%PRIMARY_KEY%', $frm['%PRIMARY_KEY%']);
305    if ($lock->isLocked() && !$lock->isMine()) {
306        $lock->dieErrorPage();
307    }
308
309    // Break the cache because we are changing the list data.
310    SessionCache::breakCache($_SERVER['PHP_SELF']);
311
312%UPDATE%
313
314    // Create version.
315    $version = RecordVersion::getInstance($GLOBALS['auth']);
316    $version->create('%DB_TBL%', '%PRIMARY_KEY%', $frm['%PRIMARY_KEY%'], $frm['<##>']);
317
318    $app->raiseMsg(sprintf(_("The %ITEM_TITLE% <strong>%s</strong> has been updated."), $frm['<##>']), MSG_SUCCESS, __FILE__, __LINE__);
319
320    // Unlock record.
321    $lock->remove();
322}
323
324function &getRecordList()
325{
326    global $page;
327    global $so;
328    $db =& DB::getInstance();
329   
330    $where_clause = '';
331
332    // Build search query if available.
333    if (getFormData('search_query', false)) {
334        $qry_words = preg_split('/[^\w]/', getFormData('search_query'));
335        for ($i=0; $i<sizeof($qry_words); $i++) {
336%SEARCH%
337        }
338    }
339
340    if (getFormData('filter_<##>', false)) {
341        // Limit by filter.
342        $where_clause .= (empty($where_clause) ? 'WHERE' : 'AND') . " <##> = '" . $db->escapeString(getFormData('filter_<##>')) . "'";
343    }
344
345    // Count the total number of records so we can do something about the page numbers.
346    $qid = $db->query("
347        SELECT COUNT(*)
348        FROM %DB_TBL%
349        $where_clause
350    ");
351    list($num_results) = mysql_fetch_row($qid);
352
353    // Set page numbers now we know (needed for next step).
354    $page->setTotalItems($num_results);
355    $page->calculate();
356
357    // Final SQL, with sort and page limiters.
358    $sql = "
359        SELECT
360            %DB_TBL%.*,
361            a1.username AS added_admin_username,
362            a2.username AS modified_admin_username
363        FROM %DB_TBL%
364        LEFT JOIN admin_tbl a1 ON (%DB_TBL%.added_by_user_id = a1.admin_id)
365        LEFT JOIN admin_tbl a2 ON (%DB_TBL%.modified_by_user_id = a2.admin_id)
366        $where_clause
367        " . $so->getSortOrderSQL() . "
368        " . $page->getLimitSQL() . "
369    ";
370
371    // A unique key for this query, with the total_items in case db records
372    // were added since the last cache. This identifies a unique set of
373    // cached data, but we must refer to the list that is cached by a more
374    // generic name. so that we can flush the cache (if records updated)
375    // without knowing the hash.
376    $cache_hash = md5($sql . '|' . $page->total_items);
377    if (Prefs::getValue('cache_hash', $_SERVER['PHP_SELF']) != $cache_hash) {
378        SessionCache::breakCache($_SERVER['PHP_SELF']);
379        Prefs::setValue('cache_hash', $cache_hash, $_SERVER['PHP_SELF']);
380    }
381
382    if (SessionCache::isCached($_SERVER['PHP_SELF'])) {
383        // Get the cached results.
384        $list = SessionCache::getCache($_SERVER['PHP_SELF']);
385    } else {
386        // If the list is not already cached, query now.
387        $qid = $db->query($sql);
388        // Fill an array with the items for this page.
389        while ($row = mysql_fetch_assoc($qid)) {
390            $list[] = $row;
391        }
392
393        if (isset($list) && !empty($list)) {
394            // Cache the results.
395            SessionCache::putCache($list, $_SERVER['PHP_SELF']);
396        }
397    }
398
399    return $list;
400}
401
402function updateRank($ranks)
403{
404    $db =& DB::getInstance();
405   
406    if (!is_array($ranks)) {
407        $app->logMsg('Saving rank failed, data posted is not an array: ' . $ranks, LOG_ERR, __FILE__, __LINE__);
408        return false;
409    }
410
411    // Break the cache because we are changing the list data.
412    SessionCache::breakCache($_SERVER['PHP_SELF']);
413
414    // Count the ranks with invalid numbers
415    $unspecified_counter = 0;
416
417    // Go through the array of new ranks.
418    foreach ($ranks as $id => $new_rank) {
419        if ('' == trim($new_rank) || !is_numeric($new_rank) || $new_rank > 2147483646) {
420            // Unspecified entries receive a sort order of 10000.
421            $new_rank = 10000;
422            $unspecified_counter++;
423        }
424        $db->query("
425            UPDATE %DB_TBL% SET
426                rank = '" . $db->escapeString($new_rank) . "'
427            WHERE %PRIMARY_KEY% = '" . $db->escapeString($id) . "'
428        ");
429    }
430
431    $app->raiseMsg(_("Records have been reordered with the new rank."), MSG_SUCCESS, __FILE__, __LINE__);
432    if ($unspecified_counter > 0) {
433        $app->raiseMsg(sprintf(_("%s items with unspecified ranks were automatically assigned a rank of 10000."), $unspecified_counter), MSG_NOTICE, __FILE__, __LINE__);
434    }
435}
436
437?>
Note: See TracBrowser for help on using the repository browser.