/** * 加载模板 * @param null $template */ public function display($template = null, $isPath = false) { //$template = isset($template)?self::$routeUrl['module']."/".self::$routeUrl['controller']."_".$template.'.html':self::$routeUrl['module']."_".self::$routeUrl['controller'].'.html'; //m:c:a or index //TODO 代码重用性 ↓↓↓↓↓↓↓ if (is_array(self::$assignData)) { foreach (self::$assignData as $key => $value) { self::$view->assign($key, $value); } } //TODO 代码重用性 ↑↑↑↑↑↑↑ //如果直接 :分割 传入路径 不解析模型 应用于common if ($isPath) { self::$view->display($template); exit; } if (isset($template)) { $pos = strpos($template, ":"); if ($pos) { $tArr = explode(":", $template); if (count($tArr) == 3) { $template = $tArr[0] . "/" . $tArr[1] . "_" . $tArr[2]; } else { return exception($template . "格式错误,必须为 M:C:A!"); } } else { $template = self::$routeUrl['module'] . "/" . self::$routeUrl['controller'] . "_" . $template; } } else { $template = self::$routeUrl['module'] . "/" . self::$routeUrl['controller'] . "_" . self::$routeUrl['action']; } self::$view->display($template); }
public static function init($date, $form) { $dateArray = array(); $safeFilter = new safeFilter(); foreach ($date as $k => $v) { if (isset($form[$k]['datatype'])) { $dataType = $form[$k]['datatype']; if (array_key_exists($dataType, self::$type)) { //直接匹配验证 if (!preg_match(self::$type[$dataType], $date[$k])) { return exception("不合法的数据:['{$date[$k]}'']"); } } else { if (array_key_exists(preg_replace("/\\d+/is", "?", $dataType), self::$type)) { //正则匹配 $key = preg_replace("/\\d+/is", "?", $dataType); //获取数值 preg_match("/.+(\\d)+-(\\d+)/", $dataType, $matchAll); //组装正则 $preg = sprintf(self::$type[$key], $matchAll[1], $matchAll[2]); if (!preg_match($preg, $date[$k])) { return exception("不合法的数据:['{$date[$k]}'']"); } } elseif (preg_match("/^\\/.*\\/\$/", $dataType)) { //直接正则 if (!preg_match($dataType, $date[$k])) { return exception("不合法的数据:['{$date[$k]}'']"); } } } } } return $date; }
/** * 设置数据 * * @param int|string $id * @param string $key * @param $name */ protected function set($id, $key = null, $name = null) { if (is_null($key) && is_null($name)) { exception('请添加正确状态表数据'); } $this->data[$id] = array('id' => $id, 'key' => $key, 'name' => $name); }
protected function handleException(Throwable $e) { if (response()->getCode() == 200) { response()->code(404); } $code = $e->getCode() ? $e->getCode() : response()->getCode(); $message = $e->getMessage(); if (class_exists(DeriveAssets::class)) { Reflect::create(DeriveAssets::class)->register(); } $handled = false; $codes = [$code, 'default']; foreach ($codes as $file) { try { $response = view('Pckg\\Framework:error/' . $file, ['message' => $message, 'code' => $code, 'exception' => $e])->autoparse(); if ($response) { $handled = true; break; } } catch (Throwable $e) { dd(exception($e)); } } if ($handled) { echo $response; } else { echo $code . ' : ' . $message; } exit; }
public function JsonToArray($json) { if (isJson($json)) { $array = json_decode($json, true); return $array; } else { throw exception("Invalid Json Array"); } }
/** * @param array $options */ public function __construct($options = array()) { if (!extension_loaded('memcache')) { exception('_nofund_' . ':memcache'); } $options = array_merge(array('host' => C('cache:memcache:host') ?: '127.0.0.1', 'port' => C('cache:memcache:port') ?: 11211, 'timeout' => C('cache:memcache:timeout') ?: false, 'persistent' => false), $options); $this->options = $options; $this->options['expire'] = isset($options['expire']) ? $options['expire'] : C('cache:expire'); $this->options['prefix'] = isset($options['prefix']) ? $options['prefix'] : C('cache:prefix'); $func = $options['persistent'] ? 'pconnect' : 'connect'; $this->handler = new \Memcache(); $options['timeout'] === false ? $this->handler->{$func}($options['host'], $options['port']) : $this->handler->{$func}($options['host'], $options['port'], $options['timeout']); }
public function execute(callable $next) { try { /** * First argument is always 'console'. * Second argument is app name or command. * If it's command, we leave things as they are. * Id it's app, we unset it. */ $argv = $_SERVER['argv']; /** * Remove application name. */ if (isset($argv[1]) && !strpos($argv[1], ':')) { unset($argv[1]); } /** * Remove platform name. */ if (isset($argv[2]) && !strpos($argv[2], ':') && false === strpos($argv[2], '-')) { unset($argv[2]); } /** * Get Symfony Console Application, find available commands and run app. */ $application = context()->get(SymfonyConsole::class); try { /** * Apply global middlewares. */ if ($middlewares = $this->response->getMiddlewares()) { chain($middlewares, 'execute'); } $application->run(new ArgvInput(array_values($argv))); /** * Apply global afterwares/decorators. */ if ($afterwares = $this->response->getAfterwares()) { chain($afterwares, 'execute', [$this->response]); } } catch (Throwable $e) { die("EXCEPTION: " . exception($e)); } /** * This is here just for better readability. =) */ echo "\n"; } catch (Throwable $e) { } return $next(); }
/** * 初始化 * @param $config */ public function init($type = '', $options = array()) { if (empty($type)) { $type = C('cache_type'); } $type = strtolower(trim($type)); $class = 'System\\Library\\Cache\\cache' . ucwords($type); if (class_exists($class)) { $this->cache = new $class($options); } else { exception('CACHE_TYPE Error:' . $type); } return $this->cache; }
public function getAvailableRelations() { return $this->table->relations->each(function (Relation $relation) { $entity = $relation->showTable->createEntity(); $options = $relation->onField && $relation->dynamic_relation_type_id == 1 ? $entity->all()->each(function ($record) use($relation, $entity) { try { $eval = eval(' return ' . $relation->value . '; '); } catch (Throwable $e) { $eval = exception($e); } return ['key' => $record->id, 'value' => $eval]; }, true) : []; return ['id' => $relation->id, 'field' => $relation->id, 'table' => $relation->showTable->table, 'fields' => $this->makeFields($relation->showTable->fields), 'type' => $relation->dynamic_relation_type_id, 'options' => ['options' => $options]]; }); }
/** * 控制器实现 */ public static function routeToCm() { //require_once(APP_PATH.'/'.ucfirst(self::$routeUrl['module']).'/Controller/abstractController.php'); //require_once(APP_PATH.'/'.ucfirst(self::$routeUrl['module']).'/Controller/'.self::$routeUrl['controller'].'Controller.php'); //Admin\Controller\Index; $controller = "\\" . ucfirst(self::$routeUrl['module']) . "\\Controller\\" . self::$routeUrl['controller'] . 'Controller'; $controller = new $controller(); $action = self::$routeUrl['action'] . 'Action'; try { $ca = new \ReflectionMethod($controller, $action); $ca->invoke(new $controller(), isset($params) ? $params : null); } catch (\Exception $e) { exception('控制器方法' . $action . '不存在'); } }
function action() { // This needs form validation in a bad way. $site = owa_coreAPI::entityFactory('base.site'); if (!$this->getParam('siteId')) { throw exception('No siteId passed on request'); } $site->load($site->generateId($this->getParam('siteId'))); $site->set('name', $this->getParam('name')); $site->set('domain', $this->getParam('domain')); $site->set('description', $this->getParam('description')); $site->save(); //$data['view_method'] = 'redirect'; //$data['do'] = 'base.sites'; $this->setRedirectAction('base.sites'); $this->set('status_code', 3201); }
function __construct($l = NULL) { $lang = api_config::getInstance()->lang; if (!$l) { $currentLang = $lang['default']; } else { if (in_array($l, $lang['languages'])) { $currentlang = $l; } else { // No language what to do? throw exception(new Exception("Language {$l} missing")); } } $langFile = PROJECT_DIR . "config/locale/" . $currentLang . ".yml"; $yaml = file_get_contents($langFile); $langYaml = sfYaml::load($yaml); $langArray = $langYaml[$currentLang]; $this->content = $langArray; }
public function fetch($templateFile = '', $content = '', $prefix = '') { if (empty($content)) { $templateFile = $this->parseTemplate($templateFile); if (!is_file($templateFile)) { exception("模板文件" . $templateFile . "不存在"); } } ob_start(); ob_implicit_flush(0); if ('php' == strtolower($this->config['tmpl_engine_type'])) { extract($this->tVar, EXTR_OVERWRITE); empty($content) ? include $templateFile : eval('?>' . $content); } else { $params = array('var' => $this->tVar, 'file' => $templateFile, 'content' => $content, 'prefix' => $prefix); $this->ParseTemplateBehavior($params); } $content = ob_get_clean(); $this->ContentReplaceBehavior($content); return $content; }
/** * We */ public function handle() { $this->app = $this->getApp(); if (!$this->app) { throw new Exception('App name is required in migrator'); } context()->bind(InstallMigrator::class, $this); $requestedMigrations = $this->getRequestedMigrations(); $installedMigrations = (array) $this->getInstalledMigrations(); $installed = 0; $updated = 0; foreach ($requestedMigrations as $requestedMigration) { /** * @T00D00 * Implement beforeFirstUp(), beforeUp(), afterUp(), afterFirstUp(), isFirstUp() */ try { $migration = new $requestedMigration(); $migration->up(); if (!in_array($requestedMigration, $installedMigrations)) { $migration->afterFirstUp(); } $this->output($migration->getRepository() . ' : ' . $requestedMigration); $this->output(); } catch (Throwable $e) { dd(exception($e)); } if (in_array($requestedMigration, $installedMigrations)) { $updated++; } else { $installedMigrations[] = $requestedMigration; $installed++; } } $this->output('Updated: ' . $updated); $this->output('Installed: ' . $installed); $this->output('Total: ' . count($installedMigrations)); $this->putInstalledMigrations($installedMigrations); }
public function internal($url = null) { try { if (!$url) { $url = $_SERVER['REQUEST_URI']; } message('Internal redirect to ' . $url); /** * Set GET method. */ $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REQUEST_URI'] = $url; $_POST = []; /** * Replace prefix in url because environment was already set. */ $url = env()->replaceUrlPrefix($url); /** * Set request url. */ request()->setUrl($url); /** * Make request internal so we increase counter. */ request()->setInternal(); /** * Find match. */ request()->init(); /** * Run actions. */ request()->run(); /** * Output. */ response()->run(); exit; } catch (Throwable $e) { if (prod()) { die(exception($e)); die("Unknown internal error"); } die(exception($e)); } exit; }
/** * 删除记录 * * @param $table * @param array $where * @return int */ public function delete($table, array $where) { if (is_array($where)) { $whereData = ""; $whereVal = array(); foreach ($where as $key => $val) { $whereVal[$key] = $val; $wz = strpos($key, "?"); $parame = $wz ? substr($key, $wz + 1) : "="; $k = substr($key, 0, $wz); $whereData .= " and " . "`" . $key . "`" . $parame . "(:{$key})"; } $this->sql = "DELETE FROM " . $this->prefix . $table . " WHERE 1=1 " . $whereData; try { $stmt = $this->pdo->prepare($this->sql); $stmt->execute($whereVal); return $stmt->rowCount(); } catch (\Exception $ex) { exception($ex->getMessage()); } } else { exception("ERROR:delete必须传入参数"); } }
/** * Registers a new package of files to be built by * the 'build' CLI command. * * $package array the package array takes the form of * * 'name' => 'mypackage' * 'output_dir' => '/path/to/output' * 'files' => array('foo' => array('path' => '/path/to/file/file.js', * 'compression' => 'minify')) */ protected function registerBuildPackage($package) { if (!isset($package['name'])) { throw exception('Build Package does not have a name.'); } if (!isset($package['output_dir'])) { throw exception('Build Package does not have an output directory.'); } else { //check for trailing slash $check = substr($package['output_dir'], -1, 1); if ($check != '/') { $package['output_dir'] = $package['output_dir'] . '/'; } } if (!isset($package['files'])) { throw exception('Build Package does not any files.'); } // filter the pcakge in case other modules want to change something. $eq = owa_coreAPI::getEventDispatch(); $package = $eq->filter('register_build_package', $package); $s = owa_coreAPI::serviceSingleton(); $s->setMapValue('build_packages', $package['name'], $package); }
/** * 0'=>'不限','1'=>'200元以下/天','2'=>'201元-300元/天','3'=>'301元-400元/天','4'=>'401元-500元/天','5'=>'501元-600元/天','6'=>'600元以上/天' * 判断每天的价格是否在价格区间中 * @param $priceRangeType 价格区别的类型编号 * @param int $basePrice 每天价格 * @return bool 如果在返回true ,否则返回false */ public static function isPriceRange($priceRangeType, $basePrice = 0) { $status = false; if (!empty($priceRangeType)) { $unitPriceRange_array = exception('_', $priceRangeType); $unitPriceRange_start = $unitPriceRange_array[0]; $unitPriceRange_end = $unitPriceRange_array[1]; if (!is_numeric($unitPriceRange_start) || !is_numeric($unitPriceRange_end)) { $return_json = json_encode(array('status' => false, 'error_msg' => '0x190005_unitPriceRange格式不正确')); exit($return_json); } } return $status; }
require_once BASE_PATH . "vendor/autoload.php"; /** * Create context instance. * This is actually dependency container. */ $context = Pckg\Framework\Helper\Context::createInstance(); /** * Create development environment. * We automatically display errors and load debugbar. */ $environment = $context->createEnvironment(Pckg\Framework\Environment\Development::class); try { /** * Create application. * It should be passed as parameter. */ $application = $context->createConsoleApplication(); /** * Initialize application. * This will parse config, set localization 'things', estamblish connection to database, * set application autoloaders and providers. */ $application->init(); /** * Run applications. * Everything was preset, we need to run command. */ $application->run(); } catch (Throwable $e) { dd(exception($e)); }
/** * Get the list of users. * * @return Array */ function getUsers() { if (!Core_Access::isSuperUser()) { throw exception('You need to be super user to perform this action'); } $db = Zend_Registry::get('db'); $select = $db->select()->from('t_users', array('userid', 'coach', 'athlete', 'superuser'))->order('userid DESC'); $stmt = $db->query($select); return $stmt->fetchAll(); }
function fatal_error($mode = '404', $bp_message = '') { global $user, $config; $current_page = _page(); $error = 'La página <strong>' . $current_page . '</strong> '; $username = (@method_exists($user, 'd')) ? $user->d('username') : ''; $bp_message .= nr(false, 2) . $current_page . nr(false, 2) . $username; switch ($mode) { case 'mysql': if (isset($config['default_lang']) && isset($user->lang)) { // Send email notification $emailer = new emailer(); $emailer->from('info'); $emailer->set_subject('MySQL error'); $emailer->use_template('mcp_delete', $config['default_lang']); $emailer->email_address('*****@*****.**'); $emailer->assign_vars(array( 'MESSAGE' => $bp_message, 'TIME' => $user->format_date(time(), 'r')) ); //$emailer->send(); $emailer->reset(); } else { $email_message = $bp_message . nr(false, 2) . date('r'); $email_headers = "From: info@rockrepublik.net\nReturn-Path: " . $config['board_email'] . "\nMessage-ID: <" . md5(uniqid(time())) . "@" . $config['server_name'] . ">\nMIME-Version: 1.0\nContent-type: text/plain; charset=iso-8859-1\nContent-transfer-encoding: 8bit\nDate: " . date('r', time()) . "\nX-Priority: 3\nX-MSMail-Priority: Normal\n"; //$result = @mail('*****@*****.**', 'MySQL error', preg_replace("#(?<!\r)\n#s", "\n", $email_message), $email_headers, "-f{$config['board_email']}"); } $title = 'Error del sistema'; $error .= 'tiene un error'; break; case '600': $title = 'Origen inválido'; $error .= 'no puede ser accesada porque no se reconoce su IP de origen.'; @error_log('[php client empty ip] File does not exist: ' . $current_page, 0); break; default: $title = 'Archivo no encontrado'; $error .= 'no existe'; $bp_message = ''; status("404 Not Found"); @error_log('[php client ' . $user->ip . ($user->d('username') ? ' - ' . $user->d('username') : '') . '] File does not exist: ' . $current_page, 0); break; } if ($mode != '600') { $error .= ', puedes regresar a<br /><a href="/">página de inicio de Rock Republik</a> para encontrar información.'; if (!empty($bp_message)) { $error .= '<br /><br />' . $bp_message; } } sql_close(); $replaces = array( 'PAGE_TITLE' => $title, 'PAGE_MESSAGE' => $error ); echo exception('error', $replaces); exit; }
/** * @param $name */ public function __get($name) { $method = 'get' . ucfirst($name); if (method_exists($this, $method)) { return call_user_func(array(&$this, $method)); } else { throw exception('Call to undefined property %s', $name); } }
public function firstOrFail($object = true) { if (!is_null($item = $this->first($object))) { return $item; } exception('blazz', "Row '{$id}' in '{$this->table}' is unknown."); }
require 'functions.php'; require 'bootstrap.php'; set_error_handler(function ($c, $e, $f = 0, $l = 0) { $v = new View('error'); $v->e = $e; $v->f = $f; $v->l = $l; echo $v; _log("{$e} [{$f}:{$l}]"); }); function exception($e) { $v = new View('exception'); $v->e = $e; _log($e->getMessage() . ' ' . $e->getFile()); die($v); } set_exception_handler('exception'); register_shutdown_function(function () { if ($e = error_get_last()) { exception(new ErrorException($e['message'], $e['type'], 0, v($e['file']), $e['line'])); } }); $c = 'controller_' . (url(0) ?: 'home'); $m = url(1) ?: 'index'; if (!is_file(p("classes/{$c}")) || !($c = new $c()) || $m == 'render' || !in_array($m, get_class_methods($c))) { $c = new controller(); $m = 'show_404'; } call_user_func_array(array($c, $m), array_slice(url(), 2)); $c->render();
public function jsonSerialize() { try { $serialize = $this->__toArray(); } catch (Throwable $e) { return exception($e); } if (!$serialize) { return []; } return $serialize; }
/** * @param $url * @param array $params * * @return string */ function url($url, $params = [], $absolute = false, $envPrefix = true) { try { $url = router()->make($url, $params, $absolute, $envPrefix); return $url; } catch (Throwable $e) { if (prod()) { return null; } return exception($e); } }
public function autoparse() { self::addDir(path('root'), Twig::PRIORITY_LAST); $this->initTwig($this->file); if ($this->file) { $this->twig = $this->twig->loadTemplate($this->file . ".twig"); } else { $this->twig = $this->twig->createTemplate($this->template); } try { /** * Trigger rendering event so we can attach some handlers. */ trigger(RenderingView::class, ['view' => $this->file]); /** * Render template. */ $render = measure('Rendering ' . $this->file, function () { return $this->twig->render($this->getFullData()); }); if ($render == $this->file . '.twig') { if (prod()) { return null; } return '<p style="color: black; font-weight: bold; background-color: red;">' . 'Cannot load file ' . $this->file . '</p>'; } return $render; } catch (Twig_Error_Syntax $e) { return "<pre>Twig error:" . exception($e) . "</pre>"; } catch (Throwable $e) { return '<pre>' . exception($e) . '</pre>'; } }
public function __toString() { try { return $this->getMeta(); } catch (Throwable $e) { return exception($e); } }
public function firstMyZelift($reseller_id, $disposition = null) { $bucket = new Bucket(SITE_NAME, 'http://zelift.com/bucket'); $disposition = is_null($disposition) ? 'attachment' : $disposition; $reseller = Model::Reseller()->find((int) $reseller_id); if ($reseller) { $zid = $reseller->zechallenge_id; $myzelift = Model::Myzelift()->where(['zechallenge_id', '=', (int) $zid])->first(true); if ($myzelift) { $contract = Model::FacturationContrat()->where(['zechallenge_id', '=', (int) $zid])->where(['platform', '=', 'MyZeLift'])->first(true); if (!$contract) { exception("facture", 'Aucun contrat zechallenge trouvé.'); } $products = lib('facturation')->abonnementMyzelift(lib('zechallenge')->getContext($reseller->id)); $toBilled = $acomptes = $hasAcomptes = $purchases = []; foreach ($products as $product) { $haveTobeBilled = Model::FacturationAcompte()->where(['status', '=', 'UNBILLED'])->where(['product_id', '=', (int) $product['id']])->where(['zechallenge_id', '=', (int) $zid])->with('product'); foreach ($haveTobeBilled as $hasToBilled) { $purchases[] = $hasToBilled; $acomptes[] = $hasToBilled; $hasAcomptes[$hasToBilled['product_id']] = true; } $haveTobeBilled = Model::FacturationPurchase()->where(['status', '=', 'UNBILLED'])->where(['product_id', '=', (int) $product['id']])->where(['zechallenge_id', '=', (int) $zid])->with('product'); foreach ($haveTobeBilled as $hasToBilled) { if (!isset($hasAcomptes[$hasToBilled['product_id']])) { $purchases[] = $toBilled[] = $hasToBilled; } } } // dd($toBilled); $total = 0; $details = []; foreach ($toBilled as $hastoBilled) { $sum = $hastoBilled['quantity'] * $hastoBilled['product']['amount']; $total += $sum; $details[] = '<tr style="border:1px solid #a4a4a4;border-top:none;"> <td style="width:500px;"> <div style="width:500px; text-indent:30px; height:25px; line-height:25px;"> ' . $hastoBilled['product']['name'] . ' </div> </td> <td style="width:300px; font-size:0; padding:0;"> <div style="width:75px; display:inline-block; font-size:15px; text-align:center;">' . number_format($hastoBilled['product']['amount'], 2) . '€</div> <div style="width:75px; display:inline-block; font-size:15px; text-align:center;">' . $hastoBilled['quantity'] . '</div> <div style="width:75px; display:inline-block; font-size:15px; text-align:center;"></div> <div style="width:75px; display:inline-block; font-size:15px; text-align:center;"> ' . number_format($sum, 2) . '€ </div> </td> </tr>'; } foreach ($acomptes as $hastoBilled) { $sum = $hastoBilled['quantity'] * $hastoBilled['amount']; $total += $sum; $normalPrice = $hastoBilled['product']['amount'] * $hastoBilled['quantity']; $pc = $sum / $normalPrice * 100; $details[] = '<tr style="border:1px solid #a4a4a4;border-top:none;"> <td style="width:500px;"> <div style="width:500px; text-indent:30px; height:25px; line-height:25px;"> ' . $hastoBilled['product']['name'] . ' (Acompte de ' . $pc . ' %) </div> </td> <td style="width:300px; font-size:0; padding:0;"> <div style="width:75px; display:inline-block; font-size:15px; text-align:center;">' . number_format($hastoBilled['amount'], 2) . '€</div> <div style="width:75px; display:inline-block; font-size:15px; text-align:center;">' . $hastoBilled['quantity'] . '</div> <div style="width:75px; display:inline-block; font-size:15px; text-align:center;"></div> <div style="width:75px; display:inline-block; font-size:15px; text-align:center;"> ' . number_format($sum, 2) . '€ </div> </td> </tr>'; } $facture = Model::FacturationFacture()->refresh()->firstOrCreate(['zechallenge_id' => $zid, 'products' => $purchases]); $tva = number_format(round($total * 0.2, 2), 2); $ttc = number_format($total + $tva, 2); $details = implode("\n", $details); $tpl = File::read(APPLICATION_PATH . DS . 'templates/premiere_facture_zechallenge.html'); $ib = Model::Inovibackend()->find((int) $reseller->inovibackend_id); $tpl = str_replace(['##typoColor##', '##typo##', '##no_facture##', '##compte_inovi##', '##no_contrat##', '##univers##', '##affil##', '##nom_client##', '##adresse_client##', '##cp_client##', '##ville_client##', '##lieu_contrat##', '##date_contrat##', '##date_debut##', '##date_fin##', '##date_jour##', '##total##', '##total_tva##', '##total_ttc##', '##details##'], ['#ba68c8', 'MyZeLift', $facture->id, $reseller->inovibackend_id, $zid, lib('zechallenge')->getMarket($reseller->id), lib('segment')->getAffiliation($reseller->id, false), $ib->name, $ib->address, $ib->zip, $ib->city, $ib->city, date('d/m/Y', $contract->contract_date), date('d/m/Y', $contract->contract_date), date('d/m/Y', $contract->end), date('d/m/Y'), number_format($total, 2), $tva, $ttc, $details], $tpl); $pdf = pdfFile($tpl, 'Facture-MyZeLift', 'portrait'); $url = $bucket->data($pdf, 'pdf'); if (!fnmatch('http://*', $url)) { return ['url' => false, 'error' => $url]; } if ($disposition == 'attachment') { return ['url' => $url, 'error' => false]; } header('Content-Type: application/pdf'); header('Content-Length: ' . strlen($pdf)); header('Content-Disposition: ' . $disposition . '; filename="Contrat-MyZeLift.pdf"'); header('Cache-Control: private, max-age=0, must-revalidate'); header('Pragma: public'); ini_set('zlib.output_compression', '0'); die($pdf); } } }
/** * @param Queue $queue */ public function handle(Queue $queueService) { $waitingQueue = $queueService->getWaiting(); /** * Set queue as started, we'll execute it later. */ $waitingQueue->each(function (QueueRecord $queue) { $this->output('#' . $queue->id . ': ' . 'started (' . date('Y-m-d H:i:s') . ')'); $queue->changeStatus('started'); }, false); /** * Execute jobs. */ $waitingQueue->each(function (QueueRecord $queue) { $this->output('#' . $queue->id . ': ' . 'running (' . date('Y-m-d H:i:s') . ')'); $queue->changeStatus('running'); $this->output('#' . $queue->id . ': ' . $queue->command); $output = null; $sha1Id = sha1($queue->id); try { $timeout = strtotime($queue->execute_at) - time(); $command = $queue->command . ' && echo ' . $sha1Id; $lastLine = null; if (false && $timeout > 0) { exec('timeout -k 60 ' . $timeout . ' ' . $command, $output); } else { if (strpos($command, 'furs:')) { $command = str_replace(['/www/schtr4jh/derive.foobar.si/htdocs/', '/www/schtr4jh/beta.derive.foobar.si/htdocs/'], '/www/schtr4jh/bob.pckg.derive/htdocs/', $command); $connection = ssh2_connect(config('furs.sship'), 22); ssh2_auth_password($connection, config('furs.sshuser'), config('furs.sshpass')); $stream = ssh2_exec($connection, $command); $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); stream_set_blocking($errorStream, true); stream_set_blocking($stream, true); $errorStreamContent = stream_get_contents($errorStream); $streamContent = stream_get_contents($stream); $output = $errorStreamContent . "\n" . $streamContent; $lastLine = substr($streamContent, -41, 40); } else { exec($command, $output); $lastLine = end($output); } } if ($lastLine != $sha1Id) { $queue->changeStatus('failed_permanently', ['log' => 'FAILED: ' . (is_string($output) ? $output : implode("\n", $output))]); return; throw new Exception('Job failed'); } } catch (Throwable $e) { $queue->changeStatus('failed_permanently', ['log' => exception($e)]); return; } if (!$output) { $queue->changeStatus('failed_permanently', ['log' => 'No output']); return; } $this->output('#' . $queue->id . ': ' . 'finished (' . date('Y-m-d H:i:s') . ')'); $queue->changeStatus('finished', ['log' => is_string($output) ? $output : implode("\n", $output)]); }, false); }