source: trunk/bin/module_maker/module.cli.php @ 295

Last change on this file since 295 was 295, checked in by quinn, 16 years ago

Updated example config file. Added admin2.inc.css and minor corrections into HTML. Module maker fixes.

File size: 20.4 KB
Line 
1#!/usr/local/bin/php -q
2<?php
3/**
4 * module.cli.php
5 * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information
6 */
7
8include_once dirname(__FILE__) . '/_config.inc.php';
9
10$op = null;
11$valid_ops = array('clean', 'var', 'test');
12
13// Test for arguments.
14if (isset($_SERVER['argv'][2]) && isset($_SERVER['argv'][3])) {
15    $module_name_singular = $_SERVER['argv'][2];
16    $module_name_plural = $_SERVER['argv'][3];
17} else {
18    die(basename($_SERVER['argv'][0]) . " Error: invalid arguments. Try like this:
19
20    " . basename($_SERVER['argv'][0]) . " site_directory name_singular name_plural [operation]
21   
22Valid operations include: " . join(', ', $valid_ops) . "
23
24The following files will be generated by this script:
25<site_directory>/admin/nameplural.php
26<site_directory>/admin/_templates/namesingular_list.ihtml
27<site_directory>/admin/_templates/namesingular_form.ihtml
28<site_directory>/html/nameplural.php
29<site_directory>/html/_templates/namesingular_list.ihtml
30<site_directory>/html/_templates/namesingular.ihtml
31
32");
33}
34
35// Test for operation.
36if (isset($_SERVER['argv'][4])) {
37    // Optional fourth arg is op.
38    $op = $_SERVER['argv'][4];
39    // Make sure op is valid.
40    if (!in_array($op, $valid_ops)) {
41        die(basename($_SERVER['argv'][0]) . " Warning: Operation '$op' is not something I know how to do Please select one of: " . join(", ", $valid_ops) . "\n");
42    }
43}
44
45switch ($op) {
46case 'test' :
47    echo "RUNNING MODULE MAKER IN TEST MODE.\n\n";
48    break;
49default :
50
51}
52
53
54/********************************************************************
55* CONFIG
56********************************************************************/
57
58// Where deleted files go:
59$user_trash_folder = $_SERVER['HOME'] . '/.Trash';
60
61// Directories
62$skel_dir = realpath(dirname(__FILE__) . '/skel');
63$admin_dir = realpath(COMMON_BASE . '/admin');
64$admin_tpl_dir = realpath(COMMON_BASE . '/admin/_templates');
65$public_dir = realpath(COMMON_BASE . '/html');
66$public_tpl_dir = realpath(COMMON_BASE . '/html/_templates');
67
68// Names
69$module_title = ucwords(str_replace('_', ' ', $module_name_plural));
70$item_title = ucwords(str_replace('_', ' ', $module_name_singular));
71$module_name_upper = mb_strtoupper(str_replace('_', ' ', $module_name_plural));
72
73// Admin files
74$admin_script = $module_name_plural . '.php';
75$admin_list_template = $module_name_singular . '_list.ihtml';
76$admin_form_template = $module_name_singular . '_form.ihtml';
77
78// Public files
79$public_script = $module_name_plural . '.php';
80$public_list_template = $module_name_singular . '_list.ihtml';
81$public_detail_template = $module_name_singular . '_view.ihtml';
82
83// Databaes names
84$db_tbl = $module_name_singular . '_tbl';
85$primary_key = $module_name_singular . '_id';
86
87// Only after we've defined essential files can we clean.
88if ('clean' == $op) {
89    echo "Beginning file cleanup\n";
90    trashFile("$admin_dir/$admin_script");
91    trashFile("$admin_tpl_dir/$admin_list_template");
92    trashFile("$admin_tpl_dir/$admin_form_template");
93    trashFile("$public_dir/$public_script");
94    trashFile("$public_tpl_dir/$public_list_template");
95    trashFile("$public_tpl_dir/$public_detail_template");
96    echo "End file cleanup\n";
97    die;
98}
99
100// Go!
101echo 'Running Module Maker. Using database: ' . $app->getParam('db_name') . "\n";
102
103
104/********************************************************************
105* PREPROCESSING
106********************************************************************/
107
108// Ensure skel files exist.
109if (
110    !file_exists("$skel_dir/admin.php") ||
111    !file_exists("$skel_dir/public.php") ||
112    !file_exists("$skel_dir/public.ihtml") ||
113    !file_exists("$skel_dir/public_list.ihtml")
114) {
115    die(basename($_SERVER['argv'][0]) . " Warning: one or more skeleton source files missing. Please check directory: $skel_dir.\n");
116}
117
118// Ensure essential directories exist.
119if (!is_dir("$admin_dir")) {
120    die(basename($_SERVER['argv'][0]) . " Error: $admin_dir directory not found.\n");
121}
122if (!is_dir("$admin_tpl_dir")) {
123    die(basename($_SERVER['argv'][0]) . " Error: $admin_tpl_dir directory not found.\n");
124}
125if (!is_dir("$public_dir")) {
126    die(basename($_SERVER['argv'][0]) . " Error: $public_dir directory not found.\n");
127}
128if (!is_dir("$public_tpl_dir")) {
129    die(basename($_SERVER['argv'][0]) . " Error: $public_tpl_dir directory not found.\n");
130}
131
132// Get DB tables.
133$qid = $db->query("SHOW TABLES");
134while (list($row) = mysql_fetch_row($qid)) {
135    $tables[] = $row;
136}
137
138// Make sure requested table is in database.
139if (!isset($tables)) {
140    die(sprintf("%s Warning: %s does not exist in database %s. No DB tables found!", basename($_SERVER['argv'][0]), $db_tbl, $app->getParam('db_name')));
141}
142if (!in_array($db_tbl, $tables)) {
143    die(sprintf("%s Warning: %s does not exist in database %s. Please select one of: \n\n%s\n\n", basename($_SERVER['argv'][0]), $db_tbl, $app->getParam('db_name'), join("\n", $tables)));
144}
145
146// Ensure requested table contains columns.
147// Get DB table column info.
148$qid = $db->query("DESCRIBE " . $db->escapeString($db_tbl));
149while ($row = mysql_fetch_row($qid)) {
150    $cols[] = $row;
151}
152if (!is_array($cols) || empty($cols)) {
153    die(basename($_SERVER['argv'][0]) . " Warning: $db_tbl does not have any columns.\n");
154}
155
156
157/******************************************************************************
158 * SETUP VARIABLES
159 *****************************************************************************/
160
161
162// Loop through columns
163$upload_file_capability = false;
164$headers = array();
165$public_list_page_vars = array();
166$public_detail_page_vars = array();
167$set_values_default = array();
168if (is_array($cols) && !empty($cols)) {
169    foreach ($cols as $col) {
170
171        // Human readable.
172        $field = $col[0];
173        $field_title = ucfirst(str_replace('_', ' ', $field));
174        $type = preg_replace('/^(\w+).*$/', '\\1', $col[1]);
175        $default = $col[4];
176
177        // Get primary key.
178//         if ('PRI' == $col[3]) {
179//             $primary_key = $field;
180//         }
181
182        // Our form will require type="multipart/form-data".
183        if (preg_match('/file|image/i', $field)) {
184            $upload_file_capability = true;
185        }
186
187        // Column headers.
188        $headers[$field] = $field_title;
189
190        // Get php code for printing variables.
191        $public_list_page_vars[] = "<\x3fphp echo oTxt(\$" . $module_name_singular . "_list[\$i]['$field']); \x3f>";
192        $public_detail_page_vars[] = "<\x3fphp echo oTxt(\$item['$field']); \x3f>";
193        $set_values_default[] = "'$field' => '$default'";
194    }
195}
196
197// -------------FILES-------------
198
199$skel_files['skel_admin_script'] = file_get_contents($skel_dir . '/admin.php');
200$skel_files['skel_admin_list_template'] = file_get_contents($skel_dir . '/adm_list.ihtml');
201$skel_files['skel_admin_form_template'] = file_get_contents($skel_dir . '/adm_form.ihtml');
202$skel_files['skel_public_script'] = file_get_contents($skel_dir . '/public.php');
203$skel_files['skel_public_list_template'] = file_get_contents($skel_dir . '/public_list.ihtml');
204$skel_files['skel_public_detail_template'] = file_get_contents($skel_dir . '/public.ihtml');
205
206
207// Search-replace variables ----------------------------------
208
209// Admin script file upload replacement routines...
210
211$search['admin_form_tag_init'] = '/%ADMIN_FORM_TAG_INIT%/';
212$replace['admin_form_tag_init'] = "<form method=\"post\" action=\"<\x3fphp echo oTxt(\$_SERVER['PHP_SELF']); \x3f>\" class=\"sc-form\">";
213$search['admin_upload_include'] = '/%ADMIN_UPLOAD_INCLUDE%/';
214$replace['admin_upload_include'] = '';
215$search['admin_upload_config'] = '/%ADMIN_UPLOAD_CONFIG%/';
216$replace['admin_upload_config'] = '';
217$search['admin_upload_init'] = '/%ADMIN_UPLOAD_INIT%/';
218$replace['admin_upload_init'] = '';
219$search['admin_upload_del'] = '/%ADMIN_UPLOAD_DEL%/';
220$replace['admin_upload_del'] = '';
221$search['admin_upload_insert'] = '/%ADMIN_UPLOAD_INSERT%/';
222$replace['admin_upload_insert'] = '';
223$search['admin_upload_update'] = '/%ADMIN_UPLOAD_UPDATE%/';
224$replace['admin_upload_update'] = '';
225
226if ($upload_file_capability) {
227    // Form arguments
228    $replace['admin_form_tag_init'] = "<form enctype=\"multipart/form-data\" method=\"post\" action=\"<\x3fphp echo oTxt(\$_SERVER['PHP_SELF']); \x3f>\" class=\"sc-form\">\n<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"__///__\" />";
229
230    // Include statement.
231    $replace['admin_upload_include'] = "require_once 'codebase/lib/Upload.inc.php';\n";
232
233    // Config
234    $replace['admin_upload_config'] = <<<E_O_F
235
236// This module has file upload capability.
237\$upload = new Upload();
238\$upload->setParam(array(
239    'upload_path' => COMMON_BASE . '/html/_db_files/__///__',
240    'dest_file_perms' => 0666,
241    'allow_overwriting' => false,
242    'valid_file_extensions' => array('jpg', 'gif', 'png', 'jpeg'),
243));
244
245E_O_F;
246
247    // Main init.
248    $replace['admin_upload_init'] = <<<E_O_F
249
250// Copy uploaded image name into form data.
251\$_POST['__///__'] = isset(\$_FILES['__///__']) ? \$_FILES['__///__']['name'] : '';
252
253
254E_O_F;
255
256    // Delete.
257    $replace['admin_upload_del'] = <<<E_O_F
258
259    // Delete file.
260    if ('' != \$upload->getFilenameGlob(getFormData('%PRIMARY_KEY%') . '_*')) {
261        \$upload->deleteFile(\$upload->getFilenameGlob(getFormData('%PRIMARY_KEY%') . '_*'));
262    }
263E_O_F;
264
265    // Insert 1.
266    $replace['admin_upload_insert'] = <<<E_O_F
267
268        // Upload files with prepended primary key.
269        \$new_file = \$upload->process('__///__',  \$%PRIMARY_KEY% . '_' . getFormData('__///__'));
270
271        // If file upload errors, redirect to edit operation for the inserted record.
272        if (\$upload->anyErrors() || false === \$new_file) {
273            \$app->dieURL(\$_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . \$%PRIMARY_KEY%);
274        }
275E_O_F;
276
277    // Update.
278    $replace['admin_upload_update'] = <<<E_O_F
279
280        // Upload new files.
281        if (getFormData('__///__')) {
282            // Get old file names for deletion.
283            \$old_file = \$upload->getFilenameGlob(getFormData('%PRIMARY_KEY%') . '_*');
284            // Process new file upload with prepended primary key.
285            \$new_file = \$upload->process('__///__',  getFormData('%PRIMARY_KEY%') . '_' . getFormData('__///__'));
286            if (false === \$new_file || \$upload->anyErrors()) {
287                // Upload failed. Reload form. Display errors.
288                \$frm =& editRecordForm(getFormData('%PRIMARY_KEY%'));
289                \$frm = array_merge(\$frm, getFormData());
290                \$nav->add(_("Edit %ITEM_TITLE%"));
291                \$main_template = '%ADMIN_FORM_TEMPLATE%';
292                break;
293            } else {
294                // Upload succeeded. Delete old files.
295                if ('' != \$old_file && \$old_file != \$new_file[0]['name']) {
296                    \$upload->deleteFile(\$old_file);
297                }
298            }
299        }
300E_O_F;
301} // End upload_file_capability.
302
303
304// Simple...
305
306$search['date'] = '/%DATE%/';
307$replace['date'] = date($app->getParam('date_format'));
308
309$search['name_plural'] = '/%NAME_PLURAL%/';
310$replace['name_plural'] = $module_name_plural;
311
312$search['name_singular'] = '/%NAME_SINGULAR%/';
313$replace['name_singular'] = $module_name_singular;
314
315$search['title'] = '/%TITLE%/';
316$replace['title'] = $module_title;
317
318$search['item_title'] = '/%ITEM_TITLE%/';
319$replace['item_title'] = $item_title;
320
321$search['primary_key'] = '/%PRIMARY_KEY%/';
322$replace['primary_key'] = $primary_key;
323
324$search['db_tbl'] = '/%DB_TBL%/';
325$replace['db_tbl'] = $db_tbl;
326
327$search['name_upper'] = '/%NAME_UPPER%/';
328$replace['name_upper'] = $module_name_upper;
329
330$search['admin_script'] = '/%ADMIN_SCRIPT%/';
331$replace['admin_script'] = $admin_script;
332
333$search['admin_list_template'] = '/%ADMIN_LIST_TEMPLATE%/';
334$replace['admin_list_template'] = $admin_list_template;
335
336$search['admin_form_template'] = '/%ADMIN_FORM_TEMPLATE%/';
337$replace['admin_form_template'] = $admin_form_template;
338
339$search['public_script'] = '/%PUBLIC_SCRIPT%/';
340$replace['public_script'] = $public_script;
341
342$search['public_list_template'] = '/%PUBLIC_LIST_TEMPLATE%/';
343$replace['public_list_template'] = $public_list_template;
344
345$search['public_detail_template'] = '/%PUBLIC_DETAIL_TEMPLATE%/';
346$replace['public_detail_template'] = $public_detail_template;
347
348$search['public_detail_page_vars'] = '/%PUBLIC_DETAIL_PAGE_VARS%/';
349$replace['public_detail_page_vars'] = join("\n", $public_detail_page_vars);
350
351$search['public_list_page_vars'] = '/%PUBLIC_LIST_PAGE_VARS%/';
352$replace['public_list_page_vars'] = join("\n", $public_list_page_vars);
353
354$search['set_values_default'] = '/%SET_VALUES_DEFAULT%/';
355$replace['set_values_default'] = join(",\n        ", $set_values_default);
356
357$search['search_fields'] = '/%SEARCH_FIELDS%/';
358$replace['search_fields'] = join(", ", $headers);
359
360
361
362// Complex....
363
364echo "Generating admin form table rows...\n";
365$output = array();
366exec(dirname($_SERVER['argv'][0]) . "/form_template.cli.php " . COMMON_BASE . " $db_tbl", $output, $return_val);
367if ($return_val == 0) {
368    $search['adm_form_table_rows'] = '/%ADM_FORM_TABLE_ROWS%/';
369    $replace['adm_form_table_rows'] = join("\n", $output);
370} else {
371    die(basename($_SERVER['argv'][0]) . " Error: could not execute form_template.cli.php.\n");
372}
373
374echo "Generating admin list table header rows...\n";
375$output = array();
376exec(dirname($_SERVER['argv'][0]) . "/list_template.cli.php " . COMMON_BASE . " $db_tbl headerrows", $output, $return_val);
377if ($return_val == 0) {
378    $search['adm_list_header_rows'] = '/%ADM_LIST_HEADER_ROWS%/';
379    $replace['adm_list_header_rows'] = join("\n", $output);
380} else {
381    die(basename($_SERVER['argv'][0]) . " Error: could not execute list_template.cli.php.\n");
382}
383
384echo "Generating admin list table rows...\n";
385$output = array();
386exec(dirname($_SERVER['argv'][0]) . "/list_template.cli.php " . COMMON_BASE . " $db_tbl listrows", $output, $return_val);
387if ($return_val == 0) {
388    $search['adm_list_rows'] = '/%ADM_LIST_ROWS%/';
389    $replace['adm_list_rows'] = join("\n", $output);
390} else {
391    die(basename($_SERVER['argv'][0]) . " Error: could not execute list_template.cli.php.\n");
392}
393
394echo "Generating sortorder...\n";
395$output = array();
396exec(dirname($_SERVER['argv'][0]) . "/sql.cli.php " . COMMON_BASE . " $db_tbl sortorder", $output, $return_val);
397if ($return_val == 0) {
398    $search['sort_order'] = '/%SORT_ORDER%/';
399    $replace['sort_order'] = join("\n", $output);
400} else {
401    die(basename($_SERVER['argv'][0]) . " Error: could not execute sql.cli.php.\n");
402}
403
404echo "Generating insert data...\n";
405$output = array();
406exec(dirname($_SERVER['argv'][0]) . "/sql.cli.php " . COMMON_BASE . " $db_tbl insert", $output, $return_val);
407if ($return_val == 0) {
408    $search['insert'] = '/%INSERT%/';
409    $replace['insert'] = join("\n", $output);
410} else {
411    die(basename($_SERVER['argv'][0]) . " Error: could not execute sql.cli.php.\n");
412}
413
414echo "Generating update data...\n";
415$output = array();
416exec(dirname($_SERVER['argv'][0]) . "/sql.cli.php " . COMMON_BASE . " $db_tbl update", $output, $return_val);
417if ($return_val == 0) {
418    $search['update'] = '/%UPDATE%/';
419    $replace['update'] = join("\n", $output);
420} else {
421    die(basename($_SERVER['argv'][0]) . " Error: could not execute sql.cli.php.\n");
422}
423
424echo "Generating search data...\n";
425$output = array();
426exec(dirname($_SERVER['argv'][0]) . "/sql.cli.php " . COMMON_BASE . " $db_tbl search", $output, $return_val);
427if ($return_val == 0) {
428    $search['search'] = '/%SEARCH%/';
429    $replace['search'] = join("\n", $output);
430} else {
431    die(basename($_SERVER['argv'][0]) . " Error: could not execute sql.cli.php.\n");
432}
433
434echo "Generating form validation data...\n";
435$output = array();
436exec(dirname($_SERVER['argv'][0]) . "/validation.cli.php " . COMMON_BASE . " $db_tbl", $output, $return_val);
437if ($return_val == 0) {
438    $search['form_validation'] = '/%FORM_VALIDATION%/';
439    $replace['form_validation'] = join("\n", $output);
440} else {
441    die(basename($_SERVER['argv'][0]) . " Error: could not execute validation.cli.php.\n");
442}
443
444/******************************************************************************
445 * PRINT VAR INSTEAD.
446 *****************************************************************************/
447
448if ('var' == $op) {
449    if (isset($_SERVER['argv'][5]) && isset($replace[$_SERVER['argv'][5]])) {
450        echo "\n\n" . $replace[$_SERVER['argv'][5]] . "\n\n";
451    } else if (isset($_SERVER['argv'][5]) && isset($skel_files[$_SERVER['argv'][5]])) {
452        echo "\n\n" . preg_replace($search, $replace, $skel_files[$_SERVER['argv'][5]]) . "\n\n";
453    } else {
454        die(basename($_SERVER['argv'][0]) . " Error: variable " . (isset($_SERVER['argv'][5]) ? $_SERVER['argv'][5] : '') . " not defined. Please choose one of:\n" . join(', ', array_keys(array_merge($replace, $skel_files))) . "\n");
455    }
456    die;
457}
458
459
460/******************************************************************************
461 * WRITE FILES
462 *****************************************************************************/
463
464// (1) Admin script.
465if (file_exists("$admin_dir/$admin_script")) {
466    echo "Admin script already exists: $admin_dir/$admin_script\n";
467} else {
468    echo "Writing admin script: $admin_dir/$admin_script\n";
469    if ('test' != $op) {
470        $fp = fopen("$admin_dir/$admin_script", "w");
471        fwrite($fp, preg_replace($search, $replace, $skel_files['skel_admin_script']));
472        fclose($fp);
473    }
474}
475
476// (2) Admin list template.
477if (file_exists("$admin_tpl_dir/$admin_list_template")) {
478    echo "Admin list template already exists: $admin_tpl_dir/$admin_list_template\n";
479} else {
480    echo "Writing admin list template: $admin_tpl_dir/$admin_list_template\n";
481    if ('test' != $op) {
482        $fp = fopen("$admin_tpl_dir/$admin_list_template", "w");
483        fwrite($fp, preg_replace($search, $replace, $skel_files['skel_admin_list_template']));
484        fclose($fp);
485    }
486}
487
488// (3) Admin form template.
489if (file_exists("$admin_tpl_dir/$admin_form_template")) {
490    echo "Admin form template already exists: $admin_tpl_dir/$admin_form_template\n";
491} else {
492    echo "Writing admin form template: $admin_tpl_dir/$admin_form_template\n";
493    if ('test' != $op) {
494        $fp = fopen("$admin_tpl_dir/$admin_form_template", "w");
495        fwrite($fp, preg_replace($search, $replace, $skel_files['skel_admin_form_template']));
496        fclose($fp);
497    }
498}
499
500// (4) Public script.
501if (file_exists("$public_dir/$public_script")) {
502    echo "Public script already exists: $public_dir/$public_script\n";
503} else {
504    echo "Writing public script: $public_dir/$public_script\n";
505    if ('test' != $op) {
506        $fp = fopen("$public_dir/$public_script", "w");
507        fwrite($fp, preg_replace($search, $replace, $skel_files['skel_public_script']));
508        fclose($fp);
509    }
510}
511
512// (5) Public list template.
513if (file_exists("$public_tpl_dir/$public_list_template")) {
514    echo "Public list template already exists: $public_tpl_dir/$public_list_template\n";
515} else {
516    echo "Writing public list template: $public_tpl_dir/$public_list_template\n";
517    if ('test' != $op) {
518        $fp = fopen("$public_tpl_dir/$public_list_template", "w");
519        fwrite($fp, preg_replace($search, $replace, $skel_files['skel_public_list_template']));
520        fclose($fp);
521    }
522}
523
524// (6) Public detail template.
525if (file_exists("$public_tpl_dir/$public_detail_template")) {
526    echo "Public detail template already exists: $public_tpl_dir/$public_detail_template\n";
527} else {
528    echo "Writing public detail template: $public_tpl_dir/$public_detail_template\n";
529    if ('test' != $op) {
530        $fp = fopen("$public_tpl_dir/$public_detail_template", "w");
531        fwrite($fp, preg_replace($search, $replace, $skel_files['skel_public_detail_template']));
532        fclose($fp);
533    }
534}
535
536echo "Done!\n";
537
538
539/********************************************************************
540* FUNCTIONS
541********************************************************************/
542
543function trashFile($file_path_name)
544{
545    global $user_trash_folder;
546    static $file_prefix;
547
548    if (!isset($file_prefix)) {
549        $file_prefix = time();
550    } else {
551        $file_prefix++;
552    }
553
554    // Make user trash folder.
555    if (!is_dir($user_trash_folder)) {
556        echo "Attempting to create user trash folder: $user_trash_folder/\n";
557        mkdir($user_trash_folder);
558        chmod($user_trash_folder, 0700);
559    }
560    if (!is_dir("$user_trash_folder/") || !is_writable("$user_trash_folder/")) {
561        die("User trash directory not available: $user_trash_folder/\n");
562    }
563
564    // Move file to trash.
565    if (file_exists($file_path_name)) {
566        rename($file_path_name, sprintf('%s/%s_%s', $user_trash_folder, $file_prefix, basename($file_path_name)));
567        printf("Moved to trash: %s -> %s\n", $file_path_name, sprintf('%s/%s_%s', $user_trash_folder, $file_prefix, basename($file_path_name)));
568    } else {
569        printf("File not found: %s\n", $file_path_name);
570    }
571}
572
573?>
Note: See TracBrowser for help on using the repository browser.