-
Notifications
You must be signed in to change notification settings - Fork 0
/
TheAppBuilder.class.php
580 lines (509 loc) · 16.6 KB
/
TheAppBuilder.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
<?php
class TheAppBuilder extends TheAppFactory {
/**
* Allow this flavour of the Factory to setup what it wants
*
* @return void
*/
public function setup() {
self::setup_environment();
return void;
}
public static function setup_environment(){
$the_app = & TheAppFactory::getInstance();
global $post;
$uploads = wp_upload_dir();
// Some vars for building
$the_app->set('build_root',trailingslashit($uploads['basedir'])); // multisite safe - uploads or files directory
$the_app->set('build_root_url',trailingslashit($uploads['baseurl']));
$the_app->set('production_root',$the_app->get('build_root') . trailingslashit( "wp-app-factory/build/production/$post->post_name" ));
$the_app->set('production_root_url',$the_app->get('build_root_url') . trailingslashit( "wp-app-factory/build/production/$post->post_name" ));
// Additional vars for administrators who are doing the actual building
if (current_user_can('administrator') && (get_query_var(APP_COMMAND_VAR) == 'build' || get_query_var(APP_COMMAND_VAR) == 'build_no_minify')){
$the_app->is('building',true);
$the_app->is('doing_build_command',true);
// If building, we want to make sure that the Desktop is an allowed browser
$the_app->apply('meta',array(
'unacceptable_browser' => array(
'desktop' => false
)
));
$the_app->enqueue('controller','Build');
$the_app->is('minifying',strpos(get_query_var(APP_COMMAND_VAR),'no_minify') === false);
add_filter('TheAppFactory_helpers',array( __CLASS__,'build_helper'),10,2);
}
elseif( isset($_REQUEST['building']) && 'true' === $_REQUEST['building'] ){
$the_app->is('building',true);
}
if ( isset($_REQUEST['minify'])){
$the_app->is('minifying',($_REQUEST['minify'] == 'true'));
}
$app_meta = get_post_meta(get_the_ID(),'app_meta',true);
$key = (current_user_can('administrator') ? 'admin' : 'regular');
if ( current_user_can('administrator') and $the_app->is('doing_build_command')){
// We are building or packaging the app. Set the environment to development so as to load the dev files
$the_app->set('environment', 'development');
}
elseif (isset($_GET['building']) and $_GET['building'] == 'true'){
// True for anything called via build_cp();
$the_app->set('environment', 'development');
}
else{
TheAppFactory::set_environment();
}
}
/**
* Ajax endpoint for when the app is building
*
* @return dead
*/
public function build_app(){
global $post;
$post = get_post($_POST['id']);
ob_start();
$the_app = & TheAppFactory::getInstance( 'TheAppBuilder' );
include_once('extras/JSMin.php');
include_once('extras/JSMinPlus.php');
//include_once('extras/class.JavaScriptPacker.php'); // Packer Code
switch($_POST['command']){
case 'deploy':
// Step 1 - Deploy. This creates the production directory structure
// and copies over sencha-touch.js plus other resources
self::deploy();
do_action('the_app_factory_build_resources');
break;
case 'dependencies':
self::concat_dependencies();
break;
case 'index':
self::generate_index();
break;
case 'get_production_url': // Packer Code
self::get_production_url();
break;
case 'wrapup':
self::wrapup();
}
self::build_succeed(ob_get_clean());
die();
}
/**
* Deploy the Javascript and CSS for the app
*
* @action the_app_factory_build_resources
*/
public function deploy( $json = null, $target_root = null ){
$the_app = & TheAppFactory::getInstance();
$permalink = get_permalink();
// For this step we need to read app.json
if (!isset($json)){
$json = self::get_app_json('development');
}
if (!isset($target_root)){
$target_root = $the_app->get('production_root');
$relative_target_root = $the_app->get('production_root_url');
}
else{
$relative_target_root = '';
}
if ( is_dir($the_app->get( 'production_root' ) ) ){
self::rrmdir($the_app->get( 'production_root' ));
}
$minify = $the_app->is('minifying');
// Let's do the JS files
if (is_array($json->js)){
foreach ($json->js as $key => $js){
if ($js->path != 'app.js'){ // app.js is handled later
if (isset($js->remote)){
$target = $target_root.'resources/js/'.basename($js->path);
self::build_mkdir(dirname($target));
self::build_cp($js->path,$target);
}
else{
$target = $target_root.$js->path;
self::build_mkdir(dirname($target));
self::build_cp($permalink.$js->path,$target,$minify);
}
}
}
}
// Now the CSS
if (is_array($json->css)){
foreach ($json->css as $key => $css){
if (isset($css->remote)){
$target = $target_root.'resources/css/'.basename($css->path);
self::build_mkdir(dirname($target));
self::build_cp($css->path,$target,$minify ? 'css' : false);
}
else{
$target = $target_root.$css->path;
self::build_mkdir(dirname($target));
self::build_cp($permalink.$css->path,$target,$minify ? 'css' : false);
}
}
}
// Finally, we'll create our app.json file
$jsonout = new stdClass();
$jsonout->id = $json->id;
$jsonout->js = $json->js;
$jsonout->css = $json->css;
foreach ($jsonout->js as $key => $js){
if (isset($js->remote)){
$js->path = $relative_target_root.'resources/js/'.basename($js->path);
}
else{
$js->path = $relative_target_root.$js->path;
}
$jsonout->js[$key] = $js;
}
foreach ($jsonout->css as $key => $css){
if (isset($css->remote)){
$css->path = $relative_target_root.'resources/css/'.basename($css->path);
}
else{
$css->path = $relative_target_root.$css->path;
}
$jsonout->css[$key] = $css;
}
echo '[GENERATE] app.json file'."\n";
$the_app->set_app_json($jsonout);
return $jsonout;
}
/**
* Returns a message to the front end that the build step failed
*
* @return dead
*/
public function build_fail($message=''){
header('Content-type: text/javascript');
echo json_encode(array(
'success' => false,
'message' => ob_get_clean()."\n[FAIL] ".$message
));
die();
}
/**
* Returns a message to the front end that the build step succeeded
*
* @return dead
*/
public function build_succeed($message='',$data = ''){
header('Content-type: text/javascript');
echo json_encode(array(
'success' => true,
'message' => $message,
'data' => $data
));
die();
}
/**
* Attempts to mkdir (deep) the $target directory
*
* @return void
*/
public function build_mkdir($target){
if (!wp_mkdir_p($target)){
self::build_fail('Could not create build directory at '.$target);
}
}
/**
* Fetches (by cURL) the $url and copies it to the $dest
*
* @return void
*/
public function build_cp($url,$dest,$minify = false, $silent = false){
$fp = fopen($dest,'w');
$content = self::get_by_curl($url);
if ($minify){
if (!$silent){
echo "[COPY - MINIFIED] ".basename($url)."\n";
}
switch(true){
case ($minify === 'css'):
$packed = self::compressCSS($content);
break;
default:
try{
$packed = JSMin::minify($content);
}
catch(Exception $e){
die('Could not minify '.$url.'. JSMin returned '.$e->getMessage());
}
break;
}
fwrite($fp,$packed);
}
else{
if (!$silent){
echo "[COPY] ".basename($url)."\n";
}
fwrite($fp,$content);
}
fclose($fp);
}
// Thanks http://php.net/manual/en/function.rmdir.php
// Recursively remove a directory
public function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") self::rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
/**
* Compresses CSS. Which I could remember the site I got this from to give credit. I sure didn't write it.
*
* @return void
*/
public function compressCSS($css) {
return
preg_replace(
array('@\s\s+@','@(\w+:)\s*([\w\s,#]+;?)@'),
array(' ','$1$2'),
str_replace(
array("\r","\n","\t",' {','} ',';}'),
array('','','','{','}','}'),
preg_replace('@/\*[^*]*\*+([^/][^*]*\*+)*/@', '', $css)
)
)
;
}
/**
* Attempt to cp (deep) $src to $dest
*
* @return dead
*/
public function build_cp_deep($src,$dest,$ignores=null,$quiet = false){
if (!isset($ignores)){
$ignores = array('^.DS_Store$','^.svn','^.git');
}
$ignores[] = '^\.$';
$ignores[] = '^\.\.$';
if (is_dir($src)){
self::build_mkdir($dest);
$contents = glob(trailingslashit($src).'{,.}*', GLOB_BRACE);
foreach ($contents as $file){
$basename = basename($file);
$continue = true;
$target = str_replace($src,$dest,$file);
foreach ($ignores as $ignore){
if (preg_match('/'.$ignore.'/',$basename)){
$continue = false;
}
}
if ($continue){
if (is_dir($file)){
self::build_cp_deep($file,$target,$ignores,$quiet);
}
else{
if (!$quiet){
echo "[COPY] ".str_replace(ABSPATH,'',$file)." to ".str_replace(ABSPATH,'',$target)."\n";
}
copy($file,$target);
if (fileperms($file) != fileperms($target)){
// Makes sure scripts are executable
chmod($target,fileperms($file));
}
}
}
}
}
}
public function recurse_copy($src,$dst) {
$dir = opendir($src);
@mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
self::recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
/**
* Gets a URL by curl and returts the result
*
* @return $result result of curl_exec() - should be the contents of the url
*/
public function get_by_curl($url,$ch=null,$url_parms = 'building=true'){
if (isset($ch)){
$_ch = & $ch;
}
else{
$_ch = curl_init();
}
curl_setopt($_ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($_ch, CURLOPT_HEADER, false);
curl_setopt($_ch, CURLOPT_FOLLOWLOCATION, true);
$sep = (strpos($url,'?') === false ? '?' : '&');
curl_setopt($_ch, CURLOPT_URL, $url.$sep.$url_parms);
// Access this hook if you need to add anything like user authentication
do_action_ref_array('the_app_factory_get_by_curl',array(&$_ch));
$result = curl_exec($_ch);
if (!isset($ch)){
curl_close($_ch);
}
return $result;
}
/**
* Concatenates all dependencies (as sent in $_POST['dependencies']) into
* a single file
*
* @return void
*/
public function concat_dependencies( $target_root = null ){
set_time_limit(0);
$the_app = & TheAppFactory::getInstance();
if ( !isset($target_root) ){
$target_root = $the_app->get('production_root');
}
$dependencies = json_decode(stripslashes($_POST['dependencies']));
$permalink = get_permalink();
$app_js = '';
$minify = $the_app->is('minifying');
echo '[FOUND] '.count($dependencies).' dependencies. Concatenating all into app.js';
$fp = fopen($target_root.'app.js','w');
$ch = curl_init();
foreach ($dependencies as $dependency){
if (substr($dependency->path,0,3) == 'sdk'){
// These are safe just to get via file system
$path = APP_FACTORY_PATH.'the-app/'.$dependency->path;
$content = file_get_contents($path);
}
else{
// I get these via HTTP, because some might be dynamic
$path = $permalink.$dependency->path;
$path = apply_filters('get_dependency_for_concatenation_url', $path );
$content = self::get_by_curl($path,$ch);
}
try{
fwrite($fp, $minify ? JSMin::minify($content) : $content );
}
catch(Exception $e){
die('Could not minify '.$path.': '.$content.''."\n\n".' JSMin returned '.$e->getMessage());
}
}
// finally, do app.js itself
$path = $permalink.'app.js';
$path = apply_filters('get_dependency_for_concatenation_url', $path );
$content = self::get_by_curl($path,$ch);
fwrite($fp, $minify ? JSMin::minify($content) : $content );
curl_close($ch);
fclose($fp);
}
public function generate_index(){
$the_app = & TheAppFactory::getInstance();
$permalink = get_permalink();
$index = self::get_by_curl($permalink);
// For this step we need to read app.json
$json = self::get_app_json('development');
$jsonout = new stdClass;
$jsonout->id = $json->id;
$microloader = file_get_contents(APP_FACTORY_PATH."the-app/sdk{$the_app->get('sdk')}/microloader/production.js");
if ( $the_app->is( 'minifying' ) ){
$microloader = JSMin::minify( $microloader );
}
$target = $the_app->get('production_root').'index.html';
$index = preg_replace('/<html manifest=""/', '<html manifest="'.$permalink.'manifest"',$index);
$index = preg_replace('/<script id="microloader"([^<]+)<\/script>/','
<script type="text/javascript">
'.$microloader.';Ext.blink('.json_encode($jsonout).');
</script>
',$index);
$fh = fopen($target,'w');
fwrite($fh,$index);
fclose($fh);
echo '[GENERATE] index.html';
}
public function get_production_url(){
$the_app = & TheAppFactory::getInstance();
$json = self::get_app_json();
self::build_succeed('',array(
'root' => $the_app->get('production_root_url'),
'js' => $json->js
));
}
public function get_app_json($which = 'production'){
$the_app = & TheAppFactory::getInstance();
$permalink = get_permalink();
switch($which){
case 'development':
$json = self::get_by_curl($permalink.'app.json');
break;
case 'production':
default:
$json = file_get_contents($the_app->get('production_root').'app.json');
break;
}
return TheAppFactory::sanitize_json( $json );
}
public function set_app_json($json){
$the_app = & TheAppFactory::getInstance();
$dest = $the_app->get('production_root').'app.json';
$fh = fopen($dest,'w');
fwrite($fh,json_encode($json));
fclose($fh);
}
public function wrapup(){
$the_app = & TheAppFactory::getInstance();
$json = self::get_app_json();
// Need to generate the versions and make sure that updates are set to full
// I decided to move this here to the wrapup section so that I could be sure to
// get it all one in one fell swoop
$these = array('js','css');
foreach ($these as $that){
foreach ($json->$that as $key => $thing){
if ( strpos( $thing->path, $the_app->get('production_root_url') ) !== false ){
$thing->remote = false;
}
$path = str_replace($the_app->get('production_root_url'),$the_app->get('production_root'),$thing->path);
$thing->update = 'full';
if (!file_exists($path)){
self::build_fail(sprintf(__('could not find %s','app-factory'),$thing->path));
}
$content = file_get_contents($path);
// Remove previous version comments from file
while( preg_match('#/\*.+\*/#', substr($content,0,36) ) ){
$content = substr($content,36);
}
$version = md5($content);
$fp = fopen($path,'w');
fwrite($fp,'/*'.$version.'*/');
fwrite($fp,$content);
fclose($fp);
$thing->version = $version;
$json->{$that}[$key] = $thing;
}
}
self::set_app_json($json);
echo "[PREPARED] app.json file with file versions";
}
public static function build_helper( $helpers, $args ){
$the_app = & $args[0];
$helpers['WP']['isMinifying'] = $the_app->is('minifying');
return $helpers;
}
public static function build_metabox( $app ){
// Use nonce for verification
$the_app = & TheAppFactory::getInstance( 'TheAppBuilder' );
?>
<p><?php printf(__('Build and test your app and when you are ready to release it to the public, hit this Build button:','app-factory')); ?></p>
<a href="<?php bloginfo('url'); ?>/<?php echo APP_POST_TYPE; ?>/<?php echo $app->post_name; ?>::build" class="button-primary" target="_blank"><?php echo __('Build','app-factory'); ?></a>
<a href="<?php bloginfo('url'); ?>/<?php echo APP_POST_TYPE; ?>/<?php echo $app->post_name; ?>::build_no_minify" class="button-primary" target="_blank"><?php echo __('Build (no minify)','app-factory'); ?></a>
<p><?php printf(__('The Build process optimizes your app such that it loads and runs faster. It does this by launching your app, gathering the list of file dependencies and then concatenating all javascript files into a single, minimized file. ','app-factory')); ?></p>
<?php
if ( file_exists($the_app->get('production_root').'index.html') ){
echo '<p class="description">'.sprintf(__('When switching from production to development, if you\'re testing in Chrome, you should visit %s and clear the Application Cache for %s','app-factory'),'<code>chrome://appcache-internals</code>','<code>'.get_permalink().'manifest</code>').'</p>';
}
}
}
?>