CommonJavascript - Javascript-like AMD loader in PHP

Go back Parent node: Webfan

Webfan\CommonJavascript

Description

This is based on the idea of https://github.com/olivierphi/CommonJSForPHP

Config Example:

            $publicKeyChanged = false;
                 $increaseTimelimit = true;

        $setPublicKey = function($baseUrl, $expFile, $pubKeyFile){
         if(file_exists($expFile)){
          $expires = intval(file_get_contents($expFile));
         }else{
           $expires = 0;
         }

            if(!is_dir(dirname($expFile))){
               mkdir(dirname($expFile), 0755, true);
            }

            if(!is_dir(dirname($pubKeyFile))){
               mkdir(dirname($pubKeyFile), 0755, true);
            }

           if($expires > 0 && ($expires === time() || ($expires > time() - 3 && $expires < time() + 3))){
           sleep(3);
           }
          if($expires <= time()  || !file_exists($pubKeyFile) ){
              $opts =[
        'http'=>[
            'method'=>'GET',
            //'header'=>"Accept-Encoding: deflate, gzip\r\n",
            ],

            ];
          $context = stream_context_create($opts);
          $key = file_get_contents($baseUrl.'?source=@server.key', false, $context);
          foreach($http_response_header as $i => $header){
            $h = explode(':', $header);
            if('x-frdlweb-source-expires' === strtolower(trim($h[0]))){
                file_put_contents($expFile, trim($h[1]) );
                break;
            }
         }

          file_put_contents($pubKeyFile, $key);
          }

         };

         $getDefaultValidatorForUrl = function($baseUrl, $cacheDir, $increaseTimelimit = true) use($setPublicKey, &$publicKeyChanged) {
         $expFile =  rtrim($cacheDir, '\\/ ') .    \DIRECTORY_SEPARATOR.'validator-'.sha1($baseUrl).strlen($baseUrl).'.expires.txt';
         $pubKeyFile =  rtrim($cacheDir, '\\/ ') .    \DIRECTORY_SEPARATOR.'validator-'.sha1($baseUrl).strlen($baseUrl).'.public-key.txt';

         $setPublicKey($baseUrl, $expFile, $pubKeyFile);

         $condition = function($url) use($baseUrl, $increaseTimelimit){
        if($increaseTimelimit){
            set_time_limit(min(180, intval(ini_get('max_execution_time')) + 90));
        }

        if($baseUrl === substr($url, 0, strlen($baseUrl) ) ){
            return true;
        }else{
          return false;
        }
         };



         $filter = function($code) use($baseUrl, $expFile, $pubKeyFile, $setPublicKey, &$publicKeyChanged) {
        $sep = 'X19oYWx0X2NvbXBpbGVyKCk7';
        $my_signed_data=$code;
        $public_key = file_get_contents($pubKeyFile);

        list($plain_data,$sigdata) = explode(base64_decode($sep), $my_signed_data, 2);
        list($nullVoid,$old_sig_1) = explode("----SIGNATURE:----", $sigdata, 2);
        list($old_sig,$ATTACHMENT) = explode("----ATTACHMENT:----", $old_sig_1, 2);
         $old_sig = base64_decode($old_sig);
         $ATTACHMENT = base64_decode($ATTACHMENT);
        if(empty($old_sig)){
          return new \Exception("ERROR -- unsigned data");
        }
        \openssl_public_decrypt($old_sig, $decrypted_sig, $public_key);
        $data_hash = sha1($plain_data.$ATTACHMENT).substr(str_pad(strlen($plain_data.$ATTACHMENT).'', 128, strlen($plain_data.$ATTACHMENT) % 10, \STR_PAD_LEFT), 0, 128);
        if($decrypted_sig === $data_hash && strlen($data_hash)>0){
        return $plain_data;
        }else{
        if(!$publicKeyChanged){
            $publicKeyChanged = true;
           unlink($pubKeyFile);
           unlink($expFile);
           $setPublicKey($baseUrl, $expFile, $pubKeyFile);
        }
        return new \Exception("ERROR -- untrusted signature");
        }
          };

           return [$condition, $filter];
         };


         $getDefaultValidators = function($cacheDir, $increaseTimelimit = true) use($getDefaultValidatorForUrl) {
        return [
         $getDefaultValidatorForUrl('https://webfan.de/install/stable/', $cacheDir, $increaseTimelimit),
         $getDefaultValidatorForUrl('https://webfan.de/install/latest/', $cacheDir, $increaseTimelimit),
        $getDefaultValidatorForUrl('https://webfan.de/install/modules/', $cacheDir, $increaseTimelimit),
        ];
         };




               $commonJS =\Webfan\CommonJavascript::getInstance('default',[
                   'tmpPath' => \sys_get_temp_dir(),
                   // 'basePath' => __DIR__,
                   'basePath' =>[
                       $ContainerBuilder->getAppKernel()->getDir('modules'),
                       getcwd(),
                       'https://webfan.de/install/modules/',
                       'https://webfan.de/install/stable/',
                       'https://webfan.de/install/latest/',
                   ],
                   'modulesExt' => '.php',
                   'folderAsModuleFileName' => 'index.php',
                   'packageInfoFileName' => 'package.php',
                   //   'autoNamespacing' => false,
                   'autoNamespacing' => true,
                   'autoNamespacingCacheExpires' => 24*60*60,
                   'validators' => $getDefaultValidators($ContainerBuilder->getAppKernel()->getDir('cache')
                                                         .'prune-month'.\DIRECTORY_SEPARATOR, true),
               ],
                [
                    'json' => __DIR__ . '/plugins/commonsjs-plugin.json.php',
                    'yaml' => __DIR__ . '/plugins/commonsjs-plugin.yaml.php',
                    ]
                );
               $commonJS['exec'] = function(\callable | \closure $callback, array $params = []) use(&$commonJS){
                      extract($commonJS);
                   $args = [$define, $require, &$exports, &$module];
                   foreach($params as $param){
                      array_push($args, $param);
                   }
                   return call_user_func_array($callback, $args);
               };

 

Usage Example:

        extract($commonJS);

        $define('logger', function($require) {
        return function($msg) {
           //syslog(LOG_DEBUG, $msg);
            print_r($msg);
          };
           });
        $logger = $require('logger');
        $logger('Hihallihallo');

        $test= $require('test');
        print_r(array_merge([$App->getDir('modules')], [
            $test,
            'https://webfan.de/install/modules/',
        ]));
        //return;
        $exec(function($define, $require, &$exports, &$module, ...$args){
        echo implode(' ', $args);
        }, ['Hello', ' ', 'World!']);

Source code

Subordinate objects

ID RA Comment Created Updated
No items available

Alternative Identifiers

IdentifierDescription
aid:D276000186B200055912E35B0BAD37A0
(No PIX allowed)
OIDplus Information Object Application Identifier (ISO/IEC 7816) More information
guid:5912e35b-4b41-8000-a6f0-107ea655ba36OIDplus Information Object Custom UUID (RFC4122bis) More information
mac:42-22-0B-AD-37-A0OIDplus Information Object MAC address, Unicast (AAI)
mac:43-22-0B-AD-37-A0OIDplus Information Object MAC address, Multicast (AAI)
oid:1.3.6.1.4.1.37476.30.9.1494410075.195901344OIDplus Information Object OID
x500dn:/​dc=com/​dc=example/​cn=oidplus/​1.3.6.1.4.1.37476.2.5.2.9.4.1=1494410075/​1.3.6.1.4.1.37476.2.5.2.9.4.2=195901344OIDplus Information Object X.500 DN

CDN/Files
RDAP
Whois
REST API (Documentation)

Share Static link to this page


Deutsch English (USA)
oidplus:webfan_goto_frdlweb | Frdlweb
oidplus:webfan_goto_webfan | Webfan
oidplus:login_webfan | Login using Webfan
oidplus:weid_info | WEID Documentation
oidplus:webfan_goto_webfan_home | Webfan Objects
oidplus:resources$Tools/Whois.html | Whois Lookup
oidplus:system | System
pen: | IANA Enterprise Numbers
oid: | Object Identifier (OID)
guid: | Globally Unique Identifier (GUID)
other: | Other objects
php: | PHP Namespaces
     php:Webfan |
          php:Webfan\CommonJavascript | -- CommonJavascript - Javascript-like AMD loader in PHP
circuit: | Circuit Definition
uri: | URI objects
web+fan: | web+fan:// [#@resources]
mac: | MAC adresses (EUI/ELI/AAI/SAI)
ipv4: | IPv4 Network Blocks
ipv6: | IPv6 Network Blocks
java: | Java Package Names
domain: | Domain Names
aid: | Application Identifier (ISO/IEC 7816)
fourcc: | Four-Character-Code (FourCC)
x500dn: | X.500 Distinguished Name
oidplus:login | Login
oidplus:whois | OID-IP / WHOIS
oidplus:com.viathinksoft.freeoid | Register a free OID
oidplus:search | Search
oidplus:resources | Documents and Resources
oidplus:contact | Contact administrator
com.frdlweb.freeweid | Register a free WEID as OID Arc