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