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

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

Q - Merged branches/2.0singleton into trunk. Completed updating classes to use singleton methods. Implemented tests. Fixed some bugs. Changed some interfaces.

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