=') && version_compare($phpCurrentVersion, '5.5.0', '<'))) { echo "PHP {$phpVersionRequired} required. Current version is {$phpCurrentVersion}.\n"; exit(1); } $cfg = call_user_func(function ($env) { $usrInfo = posix_getpwuid(posix_getuid()); switch ($env) { case 'development': return [ 'baseUrl' => "http://{$usrInfo['name']}.lynx.dev.adaptainc.com/carleyfoundry/trunk/www/", ]; case 'preview': return [ 'baseUrl' => 'http://tester:test@cfpreview.dev.adaptainc.com/', ]; case '': case 'live': // todo: enter live site url here return [ 'baseUrl' => '', ]; default: throw new \Exception('Unknown application env "' . $env . '"'); } }, getenv('APPLICATION_ENV')); if ('cli' === php_sapi_name()) { doProcessCLIArgs(); exit; } else { if ('POST' !== $_SERVER['REQUEST_METHOD']) { echo "This script should be executed in CLI mode.\n"; exit(1); } require_once '_lib/_sys/init.php'; doProcessPOST(); exit; } /** * CLI * Print help */ function doPrintHelp() { global $argv; $cmd = basename($argv[0]); $help = << [ 'method' => "POST", 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'content' => serialize($opt), ] ]; $context = stream_context_create($requestOpts); if (false == ($fp = fopen($requestUrl, 'r', false, $context))) { echo "Can't make request to PDF rendering page\n"; exit(1); } while (($line = fgetss($fp))) { echo $line; } fclose($fp); exit; } /** * WEB * Get options from POST and export pdf */ function doProcessPOST() { if (false === ($input = file_get_contents('php://input'))) { echo "Can not read options\n"; exit(1); } $opt = unserialize($input); $debug = isset($opt['debug']); $logFile = isset($opt['log']) ? $opt['log'] : (isset($opt['l']) ? $opt['l'] : null); $log = new Log($logFile); if ($debug) { $log->log("Received POST:\n" . var_export($opt, true) . "\n\n"); } $all = isset($opt['all']); $out = isset($opt['out']) ? $opt['out'] : (isset($opt['o']) ? $opt['o'] : null); $partId = (int) isset($opt['part']) ? $opt['part'] : (isset($opt['p']) ? $opt['p'] : null); $processId = (int) isset($opt['process']) ? $opt['process'] : (isset($opt['r']) ? $opt['r'] : null); $setId = (int) isset($opt['set']) ? $opt['set'] : (isset($opt['s']) ? $opt['s'] : null); $departmentId = (int) isset($opt['department']) ? $opt['department'] : (isset($opt['d']) ? $opt['d'] : null); if ($debug) { $log->log( <<< HEREDOC Received options: out: $out all: $all part: $partId process: $processId set: $setId department: $departmentId HEREDOC ); } if (empty($out)) { $out = App_Part_ExportView::getDefaultExportPath(); } $out = Qs_Fs::normalize($out); $validator = new Qs_Validate_ExportDir(); if (!$validator->isValid($out)) { $msg = 'Error: ' . implode(";\n", $validator->getMessages()); $log->log($msg); exit(1); } if ($all) { $log->log('Exporting all parts'); renderMulti($log, $out); $log->close(); exit; } if (empty($partId)) { $log->log('Nothing to export'); $log->close(); exit(1); } renderSingle($log, $out, $partId, $processId, $departmentId, $setId); $log->close(); exit; } function renderSingle(Log $log, $out, $partId, $processId, $departmentId, $setId) { $urlOptions = array('action' => 'print', 'partId' => $partId); $pdfName = App_Part_ExportObj::getPartNumber($partId); $obj = new App_Process_Obj(); if ($processId) { $urlOptions['processId'] = $processId; $obj->setPrimaryKey($processId); $departmentId = (int)$obj->initData()->getData('departmentId'); $pdfName .= ',department-' . $departmentId; $pdfName .= ',process-' . $processId; if ($setId) { $urlOptions['setId'] = $setId; $pdfName .= ',set-' . $setId; } } elseif ($departmentId) { $urlOptions['departmentId'] = $departmentId; $pdfName .= ',department-' . $departmentId; } if (false == ($printUrl = getPrintUrl())) { $log->log('Error: Can not find part export url'); exit(1); } $printUrl = $printUrl . '?' . http_build_query($urlOptions); $log->log('Rendering pdf from url: "' . $printUrl . '"'); $pdfPageHeader = App_Process_View::preparePdfPageHeader($partId); $file = tempnam(constant('BASE_PATH') . '/tmp', $pdfName); $info = App_Part_ExportView::callPdfRenderer( $printUrl, $file, array('pageHeader' => $pdfPageHeader, 'title' => $pdfName) ); $newFile = rtrim($out, '/') . '/' . $pdfName . '.pdf'; if (0 == $info['code']) { $log->log('...done'); file_exists($newFile) && @chmod($newFile, 0644); if (rename($info['file'], $newFile)) { $log->log('PDF saved to "' . $newFile . '"'); } else { $this->_log(App_Part_Export_NotMovedException::create($info['file'], $newFile)->createMessage()); } } else { $log->log('...fail'); $log->log( 'Error rendering pdf: #' . $info['code'] . ($info['out'] ? PHP_EOL . implode(PHP_EOL, $info['out']) : '') ); } return $file; } function renderMulti(Log $log, $out) { if (false == ($printUrl = getPrintUrl())) { $log->log('Error: Can not find part export url'); exit(1); } if (($info = App_Part_ExportView::getLock())) { $log->log('Import already running since ' . date('g:i a M j, Y', strftime($info['date']))); exit(1); } App_Part_ExportView::lock($out, false); sleep(2); $printUrl .= '?action=print'; set_time_limit(0); ignore_user_abort(false); Qs_Db::getInstance()->getProfiler()->setEnabled(false); $obj = new App_Part_ExportObj(); $parts = $obj->getParts4Export(); $count = count($parts); $num = 1; $log->log("PDF export started for {$count} parts"); foreach ($parts as $row) { $partId = $row['id']; $partNumber = $row['number']; $log->log("Rendering part #{$partNumber} ... ({$num} of {$count})"); $url = $printUrl . '&partId=' . $partId; $newPath = $out . '/' . $partNumber . '.pdf'; $pdfPageHeader = App_Process_View::preparePdfPageHeader($partId); $pdfName = 'part ' . $partId; $file = tempnam(constant('BASE_PATH') . '/tmp', $pdfName); $info = App_Part_ExportView::callPdfRenderer($url, $file, array('pageHeader' => $pdfPageHeader, 'title' => $pdfName)); $newFile = rtrim($out, '/') . '/' . $pdfName . '.pdf'; if (0 == $info['code']) { $log->log('... done (' . basename($newPath) . ')'); file_exists($newPath) && @chmod($newPath, 0644); if (rename($info['file'], $newPath)) { $log->log('PDF saved to "' . $newPath . '"'); } else { $this->_log(App_Part_Export_NotMovedException::create($info['file'], $newFile)->createMessage()); } } else { $log->log('... fail (' . basename($newPath) . ')'); $log->log( 'Error rendering pdf: #' . $info['code'] . ($info['out'] ? PHP_EOL . implode(PHP_EOL, $info['out']) : '') ); } ++$num; flush(); sleep(1); if (defined('DEV_PDF_EXPORT_LIMIT') && $num >= DEV_PDF_EXPORT_LIMIT) { break; } } $log->log('PDF export finished'); App_Part_ExportView::unlock(); exit; } function getPrintUrl() { if (null == ($alias = Qs_SiteMap::findFirst(null, array('type' => 'Process_'), array('type' => 'print'), 'fullAlias'))) { return $alias; } return rtrim(constant('BASE_URL'), '/') . '/' . $alias; } class Log { protected $handle; protected static $instance; public function __construct($filePath = null) { $this->open($filePath); } public static function getInstance() { if (null == self::$instance) { self::$instance = new self(); } return self::$instance; } public function log($message) { $prefix = date('Y-m-d H:i:s') . ' => '; $message = (is_scalar($message)) ? (string) $message : print_r($message, true); echo $prefix . $message . PHP_EOL; if ($this->handle) { fwrite($this->handle, $prefix . $message . PHP_EOL); } return $this; } public function open($filePath = null) { if (null === $this->handle) { if ($filePath) { if (is_dir($filePath)) { $filePath = realpath($filePath) . '/pdf-export-' . date('Y-m-d H:i:s') . '.txt'; } $path = dirname($filePath); if ((is_dir($path) || mkdir($path, 0777, true)) && ($handle = fopen($filePath, 'a'))) { $this->handle = $handle; } else { throw new Exception('Can not open log file: ' . $filePath); } } } return $this; } public function close() { if ($this->handle) { fclose($this->handle); $this->handle = null; } return $this; } }