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:
<?php
include_once(__DIR__.'/Order.php');
class Packager_Php_Scripts_Dependencies extends Packager_Php_Scripts_Order
{
private static $_includePaths = array(
'',
'/App',
'/Libs',
);
public function AutoloadCall ($className) {
$fileName = str_replace(array('_', '\\'), '/', $className) . '.php';
$includePath = '';
foreach (self::$_includePaths as $path) {
$fullPath = $this->cfg->sourcesDir . $path . '/' . $fileName;
if (file_exists($fullPath)) {
$includePath = $fullPath;
break;
}
}
if ($includePath) {
include_once($includePath);
} else {
$status = 0;
$backTraceLog = debug_backtrace();
foreach ($backTraceLog as $backTraceInfo) {
if ($status === 0 && $backTraceInfo['function'] == 'spl_autoload_call') {
$status = 1;
} else if ($status == 1 && $backTraceInfo['function'] == 'class_exists') {
$status = 2;
break;
} else if ($status > 0) {
break;
}
}
if ($status < 2) {
$this->exceptionsMessages[] = 'Class "' . $className . '" not found by class_exists() method.';
}
}
}
protected function completePhpFilesDependencies () {
foreach ($this->files->all as $fullPath => & $fileInfo) {
if ($fileInfo->extension == 'php') {
$this->filesPhpDependencies[$fullPath] = $this->_completeRequireRecords($fullPath, $fileInfo);
}
}
$this->_completeRequiredByRecords();
}
private function _completeRequireRecords ($fullPath, & $fileInfo) {
$byRequiresAndIncludes = $this->_completeDependenciesByRequiresAndIncludes($fullPath, $fileInfo);
if ($this->cfg->autoloadingOrderDetection) {
$autoloadedByDeclaration = $this->_completePhpFileDependenciesByAutoloadDeclaration($fileInfo);
foreach ($autoloadedByDeclaration as $autoLoadItem) {
if (isset($this->files->all[$autoLoadItem]) && !in_array($autoLoadItem, $byRequiresAndIncludes)) {
$byRequiresAndIncludes[] = $autoLoadItem;
}
}
}
return (object) array(
'requiredBy' => array(),
'requires' => $byRequiresAndIncludes,
);
}
private function _completeRequiredByRecords () {
foreach ($this->filesPhpDependencies as $fullPath => & $requirements) {
$requirements->requiredBy = $this->_completeRequiredByRecordsRecursive(
$fullPath, $requirements->requiredBy
);
}
foreach ($this->filesPhpDependencies as $fullPath => & $requirements) {
$requirements->requiredByCount = count($requirements->requiredBy);
$requirements->requiresCount = count($requirements->requires);
}
}
private function _completeRequiredByRecordsRecursive ($searchedFullPath, & $searchedRequirementsRequiredBy) {
foreach ($this->filesPhpDependencies as $fullPath => $requirements) {
if (in_array($searchedFullPath, $requirements->requires)) {
if (!in_array($fullPath, $searchedRequirementsRequiredBy)) {
$searchedRequirementsRequiredBy[] = $fullPath;
$requiredByLocal = $this->_completeRequiredByRecordsRecursive(
$searchedFullPath, $searchedRequirementsRequiredBy
);
foreach ($requiredByLocal as $requiredByLocalItem) {
if (!in_array($requiredByLocalItem, $searchedRequirementsRequiredBy)) {
$searchedRequirementsRequiredBy[] = $requiredByLocalItem;
}
}
}
}
}
return $searchedRequirementsRequiredBy;
}
private function _completeDependenciesByRequiresAndIncludes ($fullPath, & $fileInfo) {
$capturedItems = $this->_completeDependenciesByFileContentCapture(
$fileInfo
);
$capturedItems = $this->_completeDependenciesByReqsAndInclsReplaceConstsAndEval(
$fileInfo, $capturedItems
);
$this->_removeProperlyCapturedReqsAndInclsFromPhpFilesContents(
$fileInfo, $capturedItems
);
$dependentFilesByRequiresAndIncludes = $this->_completeDependenciesByReqsAndInclsAbsolutizeCapturedPaths(
$fileInfo, $capturedItems
);
return $dependentFilesByRequiresAndIncludes;
}
private function _completeDependenciesByFileContentCapture (& $fileInfo) {
$capturedItems = array();
$regExps = array(
"#([^a-zA-Z0-9_\\/\*])(require_once)([^;]*);#m" => array('$1', array(3)),
"#([^a-zA-Z0-9_\\/\*])(include_once)([^;]*);#m" => array('$1', array(3)),
);
foreach ($regExps as $regExp => $backReferences) {
$matches = array();
$catched = preg_match_all($regExp, $fileInfo->content, $matches, PREG_OFFSET_CAPTURE);
if ($catched > 0) {
foreach ($matches[0] as $matchKey => $matchItem) {
$backReferenceStr = '';
foreach ($backReferences[1] as $backReferenceIndex) {
$backReferenceStr .= $matches[$backReferenceIndex][$matchKey][0];
}
$catchedTextIndex = $matchItem[1];
$catchedTextLength = mb_strlen($matchItem[0]);
$capturedItems[] = array($backReferenceStr, $catchedTextIndex, $catchedTextLength);
}
}
}
usort($capturedItems, function ($a, $b) {
if ($a[1] == $b[1]) return 0;
return ($a[1] < $b[1]) ? -1 : 1;
});
return $capturedItems;
}
private function _completeDependenciesByReqsAndInclsReplaceConstsAndEval (& $fileInfo, & $capturedItems) {
$fullPathLastSlash = strrpos($fileInfo->fullPath, '/');
$fullPathDir = $fullPathLastSlash !== FALSE ? substr($fileInfo->fullPath, 0, $fullPathLastSlash) : $fileInfo->fullPath ;
$capturedItemKeysToUnset = array();
ob_start();
$this->errorHandlerData = array();
foreach ($capturedItems as $key => & $capturedItem) {
$capturedText = trim($capturedItem[0], "\t \r\n()");
$capturedText = str_replace(
array('__FILE__', '__DIR__',),
array("'".$fileInfo->fullPath."'", "'".$fullPathDir."'",),
$capturedText
);
$addDependency = TRUE;
ob_clean();
try {
@eval('echo '.$capturedText . ';');
} catch (Exception $e) {
$addDependency = FALSE;
}
if ($this->errorHandlerData) {
$addDependency = FALSE;
$this->errorHandlerData = array();
} else {
$capturedText = ob_get_contents();
}
ob_clean();
if ($addDependency && $capturedText) {
$capturedItem[3] = $capturedText;
} else {
$capturedItemKeysToUnset[] = $key;
}
}
foreach ($capturedItemKeysToUnset as $key) {
unset($capturedItems[$key]);
}
return $capturedItems;
}
private function _removeProperlyCapturedReqsAndInclsFromPhpFilesContents (& $fileInfo, & $capturedItems) {
if (count($capturedItems) > 0) {
$newFileContent = '';
$previousItem = array();
foreach ($capturedItems as $key => & $capturedItem) {
$previousItem = ($key > 0) ? $capturedItems[$key - 1] : array(0, 0, 0) ;
$previousIndex = $previousItem[1];
$previousLength = $previousItem[2];
$currentIndex = $capturedItem[1];
$currentLength = $capturedItem[2];
$start = $previousIndex + $previousLength;
$length = $currentIndex - $start;
$newFileContent .= mb_substr($fileInfo->content, $start, $length);
}
$newFileContent .= mb_substr($fileInfo->content, $currentIndex + $currentLength);
$fileInfo->content = $newFileContent;
}
}
private function _completeDependenciesByReqsAndInclsAbsolutizeCapturedPaths (& $fileInfo, & $capturedItems) {
$byRequiresAndIncludes = array();
$result = array();
foreach ($capturedItems as $key => $capturedItem) {
$requiredOrIncluded = $capturedItem[3];
$realPath = realpath($requiredOrIncluded);
$fullPath = '';
if ($realPath !== FALSE) {
$fullPath = $realPath;
} else {
foreach (self::$_includePaths as $possibleAutoloadingDirectory) {
$possibleFullPath = $this->cfg->sourcesDir . $possibleAutoloadingDirectory . '/' . ltrim($requiredOrIncluded, '/');
$realPath = realpath($possibleFullPath);
if ($realPath !== FALSE) {
$fullPath = $realPath;
break;
}
}
}
if (!$fullPath) {
$fullPathLastSlash = strrpos($fileInfo->fullPath, '/');
$fullPathDir = $fullPathLastSlash !== FALSE ? substr($fileInfo->fullPath, 0, $fullPathLastSlash) : $fileInfo->fullPath ;
$possibleFullPath = $fullPathDir . '/' . ltrim($requiredOrIncluded, '/');
$realPath = realpath($possibleFullPath);
if ($realPath !== FALSE) {
$fullPath = $realPath;
}
}
if (!$fullPath) {
$fullPath = $requiredOrIncluded;
}
$byRequiresAndIncludes[$key] = str_replace('\\', '/', $fullPath);
}
foreach ($byRequiresAndIncludes as $byRequiresAndIncludesItem) {
if (isset($this->files->all[$byRequiresAndIncludesItem]) && !isset($result[$byRequiresAndIncludesItem])) {
$result[$byRequiresAndIncludesItem] = 1;
}
}
return array_keys($result);
}
private function _completePhpFileDependenciesByAutoloadDeclaration (& $fileInfo) {
$result = array();
$autoloadJobResult = $this->executeJobAndGetResult(
'autoloadJob', array('file' => $fileInfo->fullPath), 'json'
);
if ($autoloadJobResult instanceof stdClass && $autoloadJobResult->success) {
$result = $autoloadJobResult->includedFiles;
} else if ($fileInfo->relPath !== '/index.php') {
if ($autoloadJobResult->type == 'json') {
$this->sendResult(
implode('<br />', $autoloadJobResult->exceptionsMessages),
$autoloadJobResult->exceptionsTraces,
'error'
);
} else {
$relPath = $fileInfo->relPath;
$newLine = php_sapi_name() == 'cli' ? "\n" : "<br />";
$this->sendResult(
"Autoload error by including file: $newLine"
. "'$relPath' $newLine"
. "Is this file used also in your development versions? $newLine"
. "Or does this file generate any output by simple include() $newLine "
. "which breaks compiling process?",
$fileInfo->fullPath . "\r\n" . $autoloadJobResult->data,
'error'
);
}
}
return $result;
}
protected function completePhpFilesDependenciesByAutoloadDeclaration ($file = '') {
$success = TRUE;
$content = '';
if (!$file) {
$success = FALSE;
$this->exceptionsMessages[] = 'File is an empty string.';
} else {
self::$instance->includedFilesCountTillNow = count(get_included_files());
if ($this->_prepareIncludePathsOrComposerAutoloadAndErrorHandlers($file)) {
try {
include($file);
} catch (Exception $e) {
$success = FALSE;
$this->exceptionsMessages[] = $e->getMessage();
$this->exceptionsTraces[] = $e->getTrace();
}
} else {
if ($this->exceptionsMessages) $success = FALSE;
}
$content = ob_get_clean();
}
$this->sendJsonResultAndExit((object) array(
'success' => $success,
'includedFiles' => self::CompleteIncludedFilesByTargetFile(),
'exceptionsMessages'=> $this->exceptionsMessages,
'exceptionsTraces' => $this->exceptionsTraces,
'content' => $content,
));
}
private function _prepareIncludePathsOrComposerAutoloadAndErrorHandlers ($file) {
$scriptFileName = $_SERVER['SCRIPT_FILENAME'];
$scriptFileName = strtoupper(mb_substr($scriptFileName, 0, 1)) . mb_substr($scriptFileName, 1);
$lastSlash = mb_strrpos($scriptFileName, DIRECTORY_SEPARATOR);
$documentRoot = ($lastSlash !== FALSE) ? mb_substr($scriptFileName, 0, $lastSlash) : $scriptFileName ;
$wrongComposerAutoloadFullPath = $documentRoot . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
$alreadyIncludedFiles = get_included_files();
if (in_array($wrongComposerAutoloadFullPath, $alreadyIncludedFiles)) {
$this->exceptionsMessages = array(
"Do not use 'include_once(\"vendor/autoload.php\");' for result packing.",
"Use direct path instead: 'include_once(\"vendor/mvccore/packager/src/Packager/Php.php\");'"
);
return FALSE;
}
$sourcesDir = trim($this->cfg->sourcesDir, '/');
$composerAutoloadFullPath = $sourcesDir . '/vendor/autoload.php';
$errorMsgs = array();
$errorTraces = array();
if (file_exists($composerAutoloadFullPath)) {
try {
include_once($composerAutoloadFullPath);
} catch (Exception $e1) {
$errorMsgs = array($e1->getMessage());
$errorTraces = $e1->getTrace();
} catch (Error $e2) {
$errorMsgs = array($e2->getMessage());
$errorTraces = $e2->getTrace();
} finally {
if ($errorMsgs) {
var_dump(get_included_files());
var_dump($errorMsgs);
}
}
if ($this->_isFileIncluded($file)) {
return FALSE;
}
} else {
$phpInclPath = get_include_path();
foreach (self::$_includePaths as $path) {
$phpInclPath .= PATH_SEPARATOR . $sourcesDir . '/' . ltrim($path, '/');
}
set_include_path($phpInclPath);
}
spl_autoload_register(array(__CLASS__, 'AutoloadCall'));
register_shutdown_function(array(__CLASS__, 'ShutdownHandler'));
set_exception_handler(array(__CLASS__, 'ExceptionHandler'));
set_error_handler(array(__CLASS__, 'ErrorHandler'));
$this->errorResponse = array(
'autoloadJob',
(object) array(
'success' => FALSE,
'includedFiles' => array(),
'exceptionsMessages'=> $errorMsgs,
'exceptionsTraces' => $errorTraces,
'content' => '',
)
);
return TRUE;
}
public static function CompleteIncludedFilesByTargetFile () {
$includedFilesCountTillNow = self::$instance->includedFilesCountTillNow;
$allIncludedFiles = array_slice(get_included_files(), $includedFilesCountTillNow);
$autoLoadedFiles = array();
foreach ($allIncludedFiles as $includedFileFullPath) {
$autoLoadedFiles[] = str_replace('\\', '/', $includedFileFullPath);
}
return $autoLoadedFiles;
}
private function _isFileIncluded ($file) {
$result = FALSE;
$inclFiles = get_included_files();
foreach ($inclFiles as $inclFile) {
$inclFile = str_replace('\\', '/', $inclFile);
if ($inclFile == $file) {
$result = TRUE;
break;
}
}
return $result;
}
}