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

Last change on this file since 319 was 319, checked in by quinn, 16 years ago
File size: 20.6 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 '$admin_dir' directory not found.\n");
121}
122if (!is_dir("$admin_tpl_dir")) {
123    die(basename($_SERVER['argv'][0]) . " Error: admin_tpl_dir '$admin_tpl_dir' directory not found.\n");
124}
125if (!is_dir("$public_dir")) {
126    die(basename($_SERVER['argv'][0]) . " Error: public_dir '$public_dir' directory not found.\n");
127}
128if (!is_dir("$public_tpl_dir")) {
129    die(basename($_SERVER['argv'][0]) . " Error: public_tpl_dir '$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        if (mb_strpos($default, '0000') !== false || '0' == $default) {
178            $default = '';
179        }
180
181        // Get primary key.
182//         if ('PRI' == $col[3]) {
183//             $primary_key = $field;
184//         }
185
186        // Our form will require type="multipart/form-data".
187        if (preg_match('/file|image/i', $field)) {
188            $upload_file_capability = true;
189        }
190
191        // Column headers.
192        $headers[$field] = $field_title;
193
194        // Get php code for printing variables.
195        $public_list_page_vars[] = "<\x3fphp echo oTxt(\$" . $module_name_singular . "_list[\$i]['$field']); \x3f>";
196        $public_detail_page_vars[] = "<\x3fphp echo oTxt(\$item['$field']); \x3f>";
197        $set_values_default[] = "'$field' => '$default'";
198    }
199}
200
201// -------------FILES-------------
202
203$skel_files['skel_admin_script'] = file_get_contents($skel_dir . '/admin.php');
204$skel_files['skel_admin_list_template'] = file_get_contents($skel_dir . '/adm_list.ihtml');
205$skel_files['skel_admin_form_template'] = file_get_contents($skel_dir . '/adm_form.ihtml');
206$skel_files['skel_public_script'] = file_get_contents($skel_dir . '/public.php');
207$skel_files['skel_public_list_template'] = file_get_contents($skel_dir . '/public_list.ihtml');
208$skel_files['skel_public_detail_template'] = file_get_contents($skel_dir . '/public.ihtml');
209
210
211// Search-replace variables ----------------------------------
212
213// Admin script file upload replacement routines...
214
215$search['admin_form_tag_init'] = '/%ADMIN_FORM_TAG_INIT%/';
216$replace['admin_form_tag_init'] = "<form method=\"post\" action=\"<\x3fphp echo oTxt(\$_SERVER['PHP_SELF']); \x3f>\" class=\"sc-form\">";
217$search['admin_upload_include'] = '/%ADMIN_UPLOAD_INCLUDE%/';
218$replace['admin_upload_include'] = '';
219$search['admin_upload_config'] = '/%ADMIN_UPLOAD_CONFIG%/';
220$replace['admin_upload_config'] = '';
221$search['admin_upload_init'] = '/%ADMIN_UPLOAD_INIT%/';
222$replace['admin_upload_init'] = '';
223$search['admin_upload_del'] = '/%ADMIN_UPLOAD_DEL%/';
224$replace['admin_upload_del'] = '';
225$search['admin_upload_insert'] = '/%ADMIN_UPLOAD_INSERT%/';
226$replace['admin_upload_insert'] = '';
227$search['admin_upload_update'] = '/%ADMIN_UPLOAD_UPDATE%/';
228$replace['admin_upload_update'] = '';
229
230if ($upload_file_capability) {
231    // Form arguments
232    $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=\"<\x3fphp echo intval(ini_get('upload_max_filesize')) * 1024 * 1024; \x3f>\" />";
233
234    // Include statement.
235    $replace['admin_upload_include'] = "require_once 'codebase/lib/Upload.inc.php';\n";
236
237    // Config
238    $replace['admin_upload_config'] = <<<E_O_F
239
240// This module has file upload capability.
241\$upload = new Upload();
242\$upload->setParam(array(
243    'upload_path' => COMMON_BASE . '/html/_db_files/__///__',
244    'dest_file_perms' => 0666,
245    'allow_overwriting' => false,
246    'valid_file_extensions' => array('jpg', 'gif', 'png', 'jpeg'),
247));
248
249E_O_F;
250
251    // Main init.
252    $replace['admin_upload_init'] = <<<E_O_F
253
254// Copy uploaded image name into form data.
255\$_POST['__///__'] = isset(\$_FILES['__///__']) ? \$_FILES['__///__']['name'] : '';
256
257
258E_O_F;
259
260    // Delete.
261    $replace['admin_upload_del'] = <<<E_O_F
262
263    // Delete file.
264    if ('' != \$upload->getFilenameGlob(getFormData('%PRIMARY_KEY%') . '_*')) {
265        \$upload->deleteFile(\$upload->getFilenameGlob(getFormData('%PRIMARY_KEY%') . '_*'));
266    }
267E_O_F;
268
269    // Insert 1.
270    $replace['admin_upload_insert'] = <<<E_O_F
271
272        // Upload files with prepended primary key.
273        \$new_file = \$upload->process('__///__',  \$%PRIMARY_KEY% . '_' . getFormData('__///__'));
274
275        // If file upload errors, redirect to edit operation for the inserted record.
276        if (\$upload->anyErrors() || false === \$new_file) {
277            \$app->dieURL(\$_SERVER['PHP_SELF'] . '?op=edit&%PRIMARY_KEY%=' . \$%PRIMARY_KEY%);
278        }
279E_O_F;
280
281    // Update.
282    $replace['admin_upload_update'] = <<<E_O_F
283
284        // Upload new files.
285        if (getFormData('__///__')) {
286            // Get old file names for deletion.
287            \$old_file = \$upload->getFilenameGlob(getFormData('%PRIMARY_KEY%') . '_*');
288            // Process new file upload with prepended primary key.
289            \$new_file = \$upload->process('__///__',  getFormData('%PRIMARY_KEY%') . '_' . getFormData('__///__'));
290            if (false === \$new_file || \$upload->anyErrors()) {
291                // Upload failed. Reload form. Display errors.
292                \$frm =& editRecordForm(getFormData('%PRIMARY_KEY%'));
293                \$frm = array_merge(\$frm, getFormData());
294                \$nav->add(_("Edit %ITEM_TITLE%"));
295                \$main_template = '%ADMIN_FORM_TEMPLATE%';
296                break;
297            } else {
298                // Upload succeeded. Delete old files.
299                if ('' != \$old_file && \$old_file != \$new_file[0]['name']) {
300                    \$upload->deleteFile(\$old_file);
301                }
302            }
303        }
304E_O_F;
305} // End upload_file_capability.
306
307
308// Simple...
309
310$search['date'] = '/%DATE%/';
311$replace['date'] = date($app->getParam('date_format'));
312
313$search['name_plural'] = '/%NAME_PLURAL%/';
314$replace['name_plural'] = $module_name_plural;
315
316$search['name_singular'] = '/%NAME_SINGULAR%/';
317$replace['name_singular'] = $module_name_singular;
318
319$search['title'] = '/%TITLE%/';
320$replace['title'] = $module_title;
321
322$search['item_title'] = '/%ITEM_TITLE%/';
323$replace['item_title'] = $item_title;
324
325$search['primary_key'] = '/%PRIMARY_KEY%/';
326$replace['primary_key'] = $primary_key;
327
328$search['db_tbl'] = '/%DB_TBL%/';
329$replace['db_tbl'] = $db_tbl;
330
331$search['name_upper'] = '/%NAME_UPPER%/';
332$replace['name_upper'] = $module_name_upper;
333
334$search['admin_script'] = '/%ADMIN_SCRIPT%/';
335$replace['admin_script'] = $admin_script;
336
337$search['admin_list_template'] = '/%ADMIN_LIST_TEMPLATE%/';
338$replace['admin_list_template'] = $admin_list_template;
339
340$search['admin_form_template'] = '/%ADMIN_FORM_TEMPLATE%/';
341$replace['admin_form_template'] = $admin_form_template;
342
343$search['public_script'] = '/%PUBLIC_SCRIPT%/';
344$replace['public_script'] = $public_script;
345
346$search['public_list_template'] = '/%PUBLIC_LIST_TEMPLATE%/';
347$replace['public_list_template'] = $public_list_template;
348
349$search['public_detail_template'] = '/%PUBLIC_DETAIL_TEMPLATE%/';
350$replace['public_detail_template'] = $public_detail_template;
351
352$search['public_detail_page_vars'] = '/%PUBLIC_DETAIL_PAGE_VARS%/';
353$replace['public_detail_page_vars'] = join("\n", $public_detail_page_vars);
354
355$search['public_list_page_vars'] = '/%PUBLIC_LIST_PAGE_VARS%/';
356$replace['public_list_page_vars'] = join("\n", $public_list_page_vars);
357
358$search['set_values_default'] = '/%SET_VALUES_DEFAULT%/';
359$replace['set_values_default'] = join(",\n        ", $set_values_default);
360
361$search['search_fields'] = '/%SEARCH_FIELDS%/';
362$replace['search_fields'] = join(", ", $headers);
363
364
365
366// Complex....
367
368echo "Generating admin form table rows...\n";
369$output = array();
370exec(dirname($_SERVER['argv'][0]) . "/form_template.cli.php " . COMMON_BASE . " $db_tbl", $output, $return_val);
371if ($return_val == 0) {
372    $search['adm_form_table_rows'] = '/%ADM_FORM_TABLE_ROWS%/';
373    $replace['adm_form_table_rows'] = join("\n", $output);
374} else {
375    die(basename($_SERVER['argv'][0]) . " Error: could not execute form_template.cli.php.\n");
376}
377
378echo "Generating admin list table header rows...\n";
379$output = array();
380exec(dirname($_SERVER['argv'][0]) . "/list_template.cli.php " . COMMON_BASE . " $db_tbl headerrows", $output, $return_val);
381if ($return_val == 0) {
382    $search['adm_list_header_rows'] = '/%ADM_LIST_HEADER_ROWS%/';
383    $replace['adm_list_header_rows'] = join("\n", $output);
384} else {
385    die(basename($_SERVER['argv'][0]) . " Error: could not execute list_template.cli.php.\n");
386}
387
388echo "Generating admin list table rows...\n";
389$output = array();
390exec(dirname($_SERVER['argv'][0]) . "/list_template.cli.php " . COMMON_BASE . " $db_tbl listrows", $output, $return_val);
391if ($return_val == 0) {
392    $search['adm_list_rows'] = '/%ADM_LIST_ROWS%/';
393    $replace['adm_list_rows'] = join("\n", $output);
394} else {
395    die(basename($_SERVER['argv'][0]) . " Error: could not execute list_template.cli.php.\n");
396}
397
398echo "Generating sortorder...\n";
399$output = array();
400exec(dirname($_SERVER['argv'][0]) . "/sql.cli.php " . COMMON_BASE . " $db_tbl sortorder", $output, $return_val);
401if ($return_val == 0) {
402    $search['sort_order'] = '/%SORT_ORDER%/';
403    $replace['sort_order'] = join("\n", $output);
404} else {
405    die(basename($_SERVER['argv'][0]) . " Error: could not execute sql.cli.php.\n");
406}
407
408echo "Generating insert data...\n";
409$output = array();
410exec(dirname($_SERVER['argv'][0]) . "/sql.cli.php " . COMMON_BASE . " $db_tbl insert", $output, $return_val);
411if ($return_val == 0) {
412    $search['insert'] = '/%INSERT%/';
413    $replace['insert'] = join("\n", $output);
414} else {
415    die(basename($_SERVER['argv'][0]) . " Error: could not execute sql.cli.php.\n");
416}
417
418echo "Generating update data...\n";
419$output = array();
420exec(dirname($_SERVER['argv'][0]) . "/sql.cli.php " . COMMON_BASE . " $db_tbl update", $output, $return_val);
421if ($return_val == 0) {
422    $search['update'] = '/%UPDATE%/';
423    $replace['update'] = join("\n", $output);
424} else {
425    die(basename($_SERVER['argv'][0]) . " Error: could not execute sql.cli.php.\n");
426}
427
428echo "Generating search data...\n";
429$output = array();
430exec(dirname($_SERVER['argv'][0]) . "/sql.cli.php " . COMMON_BASE . " $db_tbl search", $output, $return_val);
431if ($return_val == 0) {
432    $search['search'] = '/%SEARCH%/';
433    $replace['search'] = join("\n", $output);
434} else {
435    die(basename($_SERVER['argv'][0]) . " Error: could not execute sql.cli.php.\n");
436}
437
438echo "Generating form validation data...\n";
439$output = array();
440exec(dirname($_SERVER['argv'][0]) . "/validation.cli.php " . COMMON_BASE . " $db_tbl", $output, $return_val);
441if ($return_val == 0) {
442    $search['form_validation'] = '/%FORM_VALIDATION%/';
443    $replace['form_validation'] = join("\n", $output);
444} else {
445    die(basename($_SERVER['argv'][0]) . " Error: could not execute validation.cli.php.\n");
446}
447
448/******************************************************************************
449 * PRINT VAR INSTEAD.
450 *****************************************************************************/
451
452if ('var' == $op) {
453    if (isset($_SERVER['argv'][5]) && isset($replace[$_SERVER['argv'][5]])) {
454        echo "\n\n" . $replace[$_SERVER['argv'][5]] . "\n\n";
455    } else if (isset($_SERVER['argv'][5]) && isset($skel_files[$_SERVER['argv'][5]])) {
456        echo "\n\n" . preg_replace($search, $replace, $skel_files[$_SERVER['argv'][5]]) . "\n\n";
457    } else {
458        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");
459    }
460    die;
461}
462
463
464/******************************************************************************
465 * WRITE FILES
466 *****************************************************************************/
467
468// (1) Admin script.
469if (file_exists("$admin_dir/$admin_script")) {
470    echo "Admin script already exists: $admin_dir/$admin_script\n";
471} else {
472    echo "Writing admin script: $admin_dir/$admin_script\n";
473    if ('test' != $op) {
474        $fp = fopen("$admin_dir/$admin_script", "w");
475        fwrite($fp, preg_replace($search, $replace, $skel_files['skel_admin_script']));
476        fclose($fp);
477    }
478}
479
480// (2) Admin list template.
481if (file_exists("$admin_tpl_dir/$admin_list_template")) {
482    echo "Admin list template already exists: $admin_tpl_dir/$admin_list_template\n";
483} else {
484    echo "Writing admin list template: $admin_tpl_dir/$admin_list_template\n";
485    if ('test' != $op) {
486        $fp = fopen("$admin_tpl_dir/$admin_list_template", "w");
487        fwrite($fp, preg_replace($search, $replace, $skel_files['skel_admin_list_template']));
488        fclose($fp);
489    }
490}
491
492// (3) Admin form template.
493if (file_exists("$admin_tpl_dir/$admin_form_template")) {
494    echo "Admin form template already exists: $admin_tpl_dir/$admin_form_template\n";
495} else {
496    echo "Writing admin form template: $admin_tpl_dir/$admin_form_template\n";
497    if ('test' != $op) {
498        $fp = fopen("$admin_tpl_dir/$admin_form_template", "w");
499        fwrite($fp, preg_replace($search, $replace, $skel_files['skel_admin_form_template']));
500        fclose($fp);
501    }
502}
503
504// (4) Public script.
505if (file_exists("$public_dir/$public_script")) {
506    echo "Public script already exists: $public_dir/$public_script\n";
507} else {
508    echo "Writing public script: $public_dir/$public_script\n";
509    if ('test' != $op) {
510        $fp = fopen("$public_dir/$public_script", "w");
511        fwrite($fp, preg_replace($search, $replace, $skel_files['skel_public_script']));
512        fclose($fp);
513    }
514}
515
516// (5) Public list template.
517if (file_exists("$public_tpl_dir/$public_list_template")) {
518    echo "Public list template already exists: $public_tpl_dir/$public_list_template\n";
519} else {
520    echo "Writing public list template: $public_tpl_dir/$public_list_template\n";
521    if ('test' != $op) {
522        $fp = fopen("$public_tpl_dir/$public_list_template", "w");
523        fwrite($fp, preg_replace($search, $replace, $skel_files['skel_public_list_template']));
524        fclose($fp);
525    }
526}
527
528// (6) Public detail template.
529if (file_exists("$public_tpl_dir/$public_detail_template")) {
530    echo "Public detail template already exists: $public_tpl_dir/$public_detail_template\n";
531} else {
532    echo "Writing public detail template: $public_tpl_dir/$public_detail_template\n";
533    if ('test' != $op) {
534        $fp = fopen("$public_tpl_dir/$public_detail_template", "w");
535        fwrite($fp, preg_replace($search, $replace, $skel_files['skel_public_detail_template']));
536        fclose($fp);
537    }
538}
539
540echo "Done!\n";
541
542
543/********************************************************************
544* FUNCTIONS
545********************************************************************/
546
547function trashFile($file_path_name)
548{
549    global $user_trash_folder;
550    static $file_prefix;
551
552    if (!isset($file_prefix)) {
553        $file_prefix = time();
554    } else {
555        $file_prefix++;
556    }
557
558    // Make user trash folder.
559    if (!is_dir($user_trash_folder)) {
560        echo "Attempting to create user trash folder: $user_trash_folder/\n";
561        mkdir($user_trash_folder);
562        chmod($user_trash_folder, 0700);
563    }
564    if (!is_dir("$user_trash_folder/") || !is_writable("$user_trash_folder/")) {
565        die("User trash directory not available: $user_trash_folder/\n");
566    }
567
568    // Move file to trash.
569    if (file_exists($file_path_name)) {
570        rename($file_path_name, sprintf('%s/%s_%s', $user_trash_folder, $file_prefix, basename($file_path_name)));
571        printf("Moved to trash: %s -> %s\n", $file_path_name, sprintf('%s/%s_%s', $user_trash_folder, $file_prefix, basename($file_path_name)));
572    } else {
573        printf("File not found: %s\n", $file_path_name);
574    }
575}
576
577?>
Note: See TracBrowser for help on using the repository browser.