Example #1
0
function scriptReturn($return, $buffer = false, $json = true)
{
    global $initime;
    if ($buffer) {
        // start and end user output so this can happen without the user waiting
        ob_end_clean();
        header("Connection: close");
        ignore_user_abort();
        // optional
        ob_start();
    }
    if ($json) {
        $return['memory_usage'] = formatBytes(memory_get_usage());
        $return['memory_peak_usage'] = formatBytes(memory_get_peak_usage());
        $return['script_run_time'] = round((microtime(true) - $initime) * 1000);
        header('Content-Type: application/json');
        echo json_encode($return, JSON_NUMERIC_CHECK);
    } else {
        header('Content-Type: text/html');
        echo htmlArray($return);
    }
    if ($buffer) {
        $size = ob_get_length();
        header("Content-Length: {$size}");
        ob_end_flush();
        // Strange behaviour, will not work
        flush();
        // Unless both are called !
    }
}
 /**
  * Ajax handler for Admin Widget
  *
  * @return json|int
  */
 function ajax_widget_reports()
 {
     global $GADASH_Config;
     if (!isset($_REQUEST['gadash_security_widget_reports']) or !wp_verify_nonce($_REQUEST['gadash_security_widget_reports'], 'gadash_get_widgetreports')) {
         wp_die(-30);
     }
     $projectId = $_REQUEST['projectId'];
     $from = $_REQUEST['from'];
     $to = $_REQUEST['to'];
     $query = $_REQUEST['query'];
     if (ob_get_length()) {
         ob_clean();
     }
     $tools = new GADASH_Tools();
     if (!$tools->check_roles($GADASH_Config->options['ga_dash_access_back']) or 0 == $GADASH_Config->options['dashboard_widget']) {
         wp_die(-31);
     }
     if ($GADASH_Config->options['ga_dash_token'] and $projectId and $from and $to) {
         include_once $GADASH_Config->plugin_path . '/tools/gapi.php';
         global $GADASH_GAPI;
     } else {
         wp_die(-24);
     }
     $profile_info = $tools->get_selected_profile($GADASH_Config->options['ga_dash_profile_list'], $projectId);
     if (isset($profile_info[4])) {
         $GADASH_GAPI->timeshift = $profile_info[4];
     } else {
         $GADASH_GAPI->timeshift = (int) current_time('timestamp') - time();
     }
     $GADASH_GAPI->get($projectId, $query, $from, $to);
 }
 public function service($request, $response)
 {/*{{{*/
     ob_start();
     $result = $this->callCenterApi->returnSuccess();
     $function = $request->service;
     if(method_exists($this, $function))
     {
         try
         {
             $lockName = $this->getLockerName($request);
             $cacher= DAL::get()->getCache(Cacher::CACHETYPE_LOCKER);
             $locker  = LockUtil::factory(LockUtil::LOCK_TYPE_MEMCACHE, array('memcache' => $cacher));
             $locker->getLock($lockName);
             $result = $this->$function($request,$response);
             $locker->releaseLock($lockName);
         }
         catch(LockException $ex)
         {
             error_log(XDateTime::now()->toString()."并发锁错误 $lockName\n", 3 , $this->logFileName);
         }
         catch(Exception $ex)
         {
             error_log(XDateTime::now()->toString()."释放锁 $lockName\n", 3 , $this->logFileName);
             $locker->releaseLock($lockName);
         }
     }
     echo $result;
     $this->logTxt .= XDateTime::now()->toString().'--->'.print_r($result, true)."\n";
     header('Content-Length: ' . ob_get_length());
     return parent::DIRECT_OUTPUT;
 }/*}}}*/
Example #4
0
File: i.php Project: donseba/Piwigo
function ierror($msg, $code)
{
    global $logger;
    if ($code == 301 || $code == 302) {
        if (ob_get_length() !== FALSE) {
            ob_clean();
        }
        // default url is on html format
        $url = html_entity_decode($msg);
        $logger->warning($code . ' ' . $url, 'i.php', array('url' => $_SERVER['REQUEST_URI']));
        header('Request-URI: ' . $url);
        header('Content-Location: ' . $url);
        header('Location: ' . $url);
        exit;
    }
    if ($code >= 400) {
        $protocol = $_SERVER["SERVER_PROTOCOL"];
        if ('HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol) {
            $protocol = 'HTTP/1.0';
        }
        header("{$protocol} {$code} {$msg}", true, $code);
    }
    //todo improve
    echo $msg;
    $logger->error($code . ' ' . $msg, 'i.php', array('url' => $_SERVER['REQUEST_URI']));
    exit;
}
 /**
  * starts new clean output buffer
  *
  * @access  public
  *
  * @author  patrick.kracht
  */
 public function clean_ob()
 {
     if (!ob_get_length() || !ob_get_level()) {
         ob_start();
     }
     session_cache_limiter('must-revalidate');
 }
Example #6
0
 function vp_ajax_wrapper()
 {
     $function = $_POST['func'];
     $params = $_POST['params'];
     if (VP_Security::instance()->is_function_whitelisted($function)) {
         if (!is_array($params)) {
             $params = array($params);
         }
         try {
             $result['data'] = call_user_func_array($function, $params);
             $result['status'] = true;
             $result['message'] = __("Successful", 'vp_textdomain');
         } catch (Exception $e) {
             $result['data'] = '';
             $result['status'] = false;
             $result['message'] = $e->getMessage();
         }
     } else {
         $result['data'] = '';
         $result['status'] = false;
         $result['message'] = __("Unauthorized function", 'vp_textdomain');
     }
     if (ob_get_length()) {
         ob_clean();
     }
     header('Content-type: application/json');
     echo json_encode($result);
     die;
 }
Example #7
0
 public function render($display = true)
 {
     $render = false;
     $this->pdf_renderer->setFontForLang(Context::getContext()->language->iso_code);
     foreach ($this->objects as $object) {
         $template = $this->getTemplateObject($object);
         if (!$template) {
             continue;
         }
         if (empty($this->filename)) {
             $this->filename = $template->getFilename();
             if (count($this->objects) > 1) {
                 $this->filename = $template->getBulkFilename();
             }
         }
         $template->assignHookData($object);
         $this->pdf_renderer->createHeader($template->getHeader());
         $this->pdf_renderer->createFooter($template->getFooter());
         $this->pdf_renderer->createContent($template->getContent());
         $this->pdf_renderer->writePage();
         $render = true;
         unset($template);
     }
     if ($render) {
         // clean the output buffer
         if (ob_get_level() && ob_get_length() > 0) {
             ob_clean();
         }
         return $this->pdf_renderer->render($this->filename, $display);
     }
 }
Example #8
0
 /**
  * Render template
  * @var string Template to be rendered (optional)
  */
 public function render($template = '')
 {
     $template = is_string($template) ? $template . '.php' : null;
     if ($template) {
         $this->appendData(array('global' => $this->global));
         $content = parent::render($template);
     } else {
         $content = '';
     }
     // make sure buffers flushed
     ob_end_flush();
     if (ob_get_length() !== false) {
         ob_flush();
     }
     ob_start();
     extract(array('content' => $content, 'global' => $this->global));
     if ($this->layout) {
         $layoutPath = $this->getTemplatesDirectory() . '/' . ltrim($this->layout, '/');
         if (!is_readable($layoutPath)) {
             throw new RuntimeException('View cannot render layout `' . $layoutPath);
         }
         require $layoutPath;
     } else {
         echo $content;
     }
     return ob_get_clean();
 }
Example #9
0
function ierror($msg, $code)
{
    if ($code == 301 || $code == 302) {
        if (ob_get_length() !== FALSE) {
            ob_clean();
        }
        // default url is on html format
        $url = html_entity_decode($msg);
        header('Request-URI: ' . $url);
        header('Content-Location: ' . $url);
        header('Location: ' . $url);
        ilog('WARN', $code, $url, $_SERVER['REQUEST_URI']);
        exit;
    }
    if ($code >= 400) {
        $protocol = $_SERVER["SERVER_PROTOCOL"];
        if ('HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol) {
            $protocol = 'HTTP/1.0';
        }
        header("{$protocol} {$code} {$msg}", true, $code);
    }
    //todo improve
    echo $msg;
    ilog('ERROR', $code, $msg, $_SERVER['REQUEST_URI']);
    exit;
}
Example #10
0
 public function after_output()
 {
     # flush once, because we're nice
     if (QM_Util::is_ajax() and ob_get_length()) {
         ob_flush();
     }
 }
Example #11
0
 function espresso_ical()
 {
     do_action('action_hook_espresso_log', __FILE__, __FUNCTION__, '');
     $name = $_REQUEST['event_summary'] . ".ics";
     $output = "BEGIN:VCALENDAR\n" . "VERSION:2.0\n" . "PRODID:-//" . $_REQUEST['organization'] . " - Event Espresso Version " . espresso_version() . "//NONSGML v1.0//EN\n" . "METHOD:PUBLISH\n" . "X-WR-CALNAME:" . $_REQUEST['organization'] . "\n" . "X-ORIGINAL-URL:" . $_REQUEST['eereg_url'] . "\n" . "X-WR-CALDESC:" . $_REQUEST['organization'] . "\n" . "X-WR-TIMEZONE:" . get_option('timezone_string') . "\n" . "BEGIN:VEVENT\n" . "DTSTAMP:" . $_REQUEST['currentyear'] . $_REQUEST['currentmonth'] . $_REQUEST['currentday'] . "T" . $_REQUEST['currenttime'] . "\n" . "UID:" . $_REQUEST['registration_id'] . "@" . $_REQUEST['eereg_url'] . "\n" . "ORGANIZER:MAILTO:" . $_REQUEST['contact_email'] . "\n" . "DTSTART:" . $_REQUEST['startyear'] . $_REQUEST['startmonth'] . $_REQUEST['startday'] . "T" . $_REQUEST['starttime'] . "\n" . "DTEND:" . $_REQUEST['endyear'] . $_REQUEST['endmonth'] . $_REQUEST['endday'] . "T" . $_REQUEST['endtime'] . "\n" . "STATUS:CONFIRMED\n" . "URL:" . $_REQUEST['eereg_url'] . "\n" . "SUMMARY:" . $_REQUEST['event_summary'] . "\n" . "LOCATION:" . $_REQUEST['location'] . "\n" . "END:VEVENT\n" . "END:VCALENDAR";
     if (ob_get_length()) {
         echo 'Some data has already been output, can\'t send iCal file';
     }
     header('Content-Type: application/x-download');
     if (headers_sent()) {
         echo 'Some data has already been output, can\'t send iCal file';
     }
     header('Content-Length: ' . strlen($output));
     header('Content-Disposition: attachment; filename="' . $name . '"');
     header('Cache-Control: private, max-age=0, must-revalidate');
     header('Pragma: public');
     header('Content-Type: application/octet-stream');
     header('Content-Type: application/force-download');
     header('Content-type: application/pdf');
     header("Cache-Control: no-cache, must-revalidate");
     // HTTP/1.1
     header("Content-Transfer-Encoding: binary");
     header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
     // Date in the past
     ini_set('zlib.output_compression', '0');
     echo $output;
     die;
 }
 /**
  * @return SS_HTTPRequest
  */
 public function backup()
 {
     $name = 'assets_' . SS_DateTime::now()->Format('Y-m-d') . '.zip';
     $tmpName = TEMP_FOLDER . '/' . $name;
     $zip = new ZipArchive();
     if (!$zip->open($tmpName, ZipArchive::OVERWRITE)) {
         user_error('Asset Export Extension: Unable to read/write temporary zip archive', E_USER_ERROR);
         return;
     }
     $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(ASSETS_PATH, RecursiveDirectoryIterator::SKIP_DOTS));
     foreach ($files as $file) {
         $local = str_replace(ASSETS_PATH . '/', '', $file);
         $zip->addFile($file, $local);
     }
     if (!$zip->status == ZipArchive::ER_OK) {
         user_error('Asset Export Extension: ZipArchive returned an error other than OK', E_USER_ERROR);
         return;
     }
     $zip->close();
     if (ob_get_length()) {
         @ob_flush();
         @flush();
         @ob_end_flush();
     }
     @ob_start();
     $content = file_get_contents($tmpName);
     unlink($tmpName);
     return SS_HTTPRequest::send_file($content, $name);
 }
 public static function export()
 {
     // Set default handlers
     set_error_handler(array('Ai1wm_Error', 'error_handler'));
     set_exception_handler(array('Ai1wm_Error', 'exception_handler'));
     // Get options
     if (isset($_POST['options']) && ($options = $_POST['options'])) {
         $storage = new StorageArea();
         // Export archive
         $model = new Ai1wm_Export();
         $file = $model->export($storage, $options);
         // Send the file to the user
         header('Content-Description: File Transfer');
         header('Content-Type: application/octet-stream');
         header(sprintf('Content-Disposition: attachment; filename=%s-%s.%s', Ai1wm_Export::EXPORT_ARCHIVE_NAME, time(), 'zip'));
         header('Content-Transfer-Encoding: binary');
         header('Expires: 0');
         header('Cache-Control: must-revalidate');
         header('Pragma: public');
         header('Content-Length: ' . filesize($file->getAs('string')));
         // Clear output buffering and read file content
         if (ob_get_length() > 0) {
             @ob_end_clean();
         }
         readfile($file->getAs('string'));
         $storage->flush();
         exit;
     }
 }
Example #14
0
 public function loadDatabaseDump($dump, $flush = false, $force = false)
 {
     // newlines
     $dump = str_replace("\r", '', $dump);
     // clear comments
     $dump = preg_replace('/#.*#/', '', $dump);
     // get queries
     $queries = preg_split('/;\\n/', $dump);
     if ($flush && ob_get_length()) {
         ob_flush();
         ob_end_clean();
     }
     foreach ($queries as $query) {
         $query = trim($query);
         if (!empty($query)) {
             try {
                 ActiveRecord::executeUpdate($query);
             } catch (Exception $e) {
                 if (!$force) {
                     throw $e;
                 }
             }
         }
         if ($flush) {
             echo '.';
             flush();
         }
     }
     return true;
 }
Example #15
0
 /**
  * Вывод содержимого переменной
  *
  * @param      $var
  * @param bool $return
  * @param bool $exit
  *
  * @return mixed|void
  */
 public static function dump($var, $return = false, $exit = true)
 {
     parent::$maxDepth = 15;
     ob_get_contents() || ob_get_length() ? ob_clean() : null;
     parent::dump($var, $return);
     !$exit ?: exit;
 }
Example #16
0
 /**
  * Start a big file download on Laravel Framework 4.0 / 4.1
  * Source (originally for Laravel 3.*) : http://stackoverflow.com/questions/15942497/why-dont-large-files-download-easily-in-laravel
  * @param  string $path    Path to the big file
  * @param  string $name    Name of the file (used in Content-disposition header)
  * @param  array  $headers Some extra headers
  */
 public function sendFile($path, $name = null, array $headers = array())
 {
     if (is_null($name)) {
         $name = basename($path);
     }
     $file = new \Symfony\Component\HttpFoundation\File\File($path);
     $mime = $file->getMimeType();
     // Prepare the headers
     $headers = array_merge(array('Content-Description' => 'File Transfer', 'Content-Type' => $mime, 'Content-Transfer-Encoding' => 'binary', 'Expires' => 0, 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Pragma' => 'public', 'Content-Length' => \File::size($path), 'Content-Disposition' => 'attachment; filename=' . $name), $headers);
     $response = new \Symfony\Component\HttpFoundation\Response('', 200, $headers);
     // If there's a session we should save it now
     if (\Config::get('session.driver') !== '') {
         \Session::save();
     }
     session_write_close();
     if (ob_get_length()) {
         ob_end_clean();
     }
     $response->sendHeaders();
     // Read the file
     if ($file = fopen($path, 'rb')) {
         while (!feof($file) and connection_status() == 0) {
             print fread($file, 1024 * 8);
             flush();
         }
         fclose($file);
     }
     // Finish off, like Laravel would
     \Event::fire('laravel.done', array($response));
     $response->send();
 }
function wbMain()
{
    wbCore::init();
    list($module, $class, $method) = wbRequest::getController();
    // theme override
    $theme = wbRequest::getVarClean('theme');
    if (!empty($theme)) {
        wbPage::setTheme($theme);
    }
    $page = wbRequest::getVarClean('page');
    if (!empty($page)) {
        wbPage::setPage($page);
    }
    ob_start();
    $modView = wbModule::getView($module, $class, $method);
    if (ob_get_length() > 0) {
        $rawOutput = ob_get_contents();
        $modView = 'The following lines were printed in raw mode by module, however this
                      should not happen. The module is probably directly calling functions
                      like echo, print, or printf. Please modify the module to exclude direct output.
                      The module is violating Webi architecture principles.<br /><br />' . $rawOutput . '<br /><br />This is the real module output:<br /><br />' . $modView;
    }
    ob_end_clean();
    wbPage::render($modView);
}
 public function service($request, $response)
 {/*{{{*/
     ob_start();
     $result = "";
     $function = $request->service;
     if(method_exists($this, $function))
     {
         try
         {
             $lockName = $this->getLockerName($request);
             $cacher= DAL::get()->getCache(Cacher::CACHETYPE_LOCKER);
             $locker  = LockUtil::factory(LockUtil::LOCK_TYPE_MEMCACHE, array('memcache' => $cacher));
             $locker->getLock($lockName);
             $result = $this->$function($request,$response);
             $locker->releaseLock($lockName);
         }
         catch(LockException $ex)
         {
             $this->ioLogRecorder->addLog(XDateTime::now()->toString()."并发锁错误 $lockName\n");
         }
         catch(Exception $ex)
         {
             $locker->releaseLock($lockName);
         }
     }
     echo $result;
     header('Content-Length: ' . ob_get_length());
     return parent::DIRECT_OUTPUT;
 }/*}}}*/
Example #19
0
 function Page_Main()
 {
     global $conn;
     $GLOBALS["Page"] =& $this;
     //***$conn = ew_Connect();
     // Get fn / table name parameters
     $key = EW_RANDOM_KEY . session_id();
     $fn = @$_GET["fn"] != "" ? ew_StripSlashes($_GET["fn"]) : "";
     if ($fn != "" && EW_ENCRYPT_FILE_PATH) {
         $fn = ew_Decrypt($fn, $key);
     }
     $table = @$_GET["t"] != "" ? ew_StripSlashes($_GET["t"]) : "";
     if ($table != "" && EW_ENCRYPT_FILE_PATH) {
         $table = ew_Decrypt($table, $key);
     }
     // Global Page Loading event (in userfn*.php)
     //***Page_Loading();
     // Get resize parameters
     $resize = @$_GET["resize"] != "";
     $width = @$_GET["width"] != "" ? $_GET["width"] : 0;
     $height = @$_GET["height"] != "" ? $_GET["height"] : 0;
     if (@$_GET["width"] == "" && @$_GET["height"] == "") {
         $width = EW_THUMBNAIL_DEFAULT_WIDTH;
         $height = EW_THUMBNAIL_DEFAULT_HEIGHT;
     }
     // Resize image from physical file
     if ($fn != "") {
         $fn = str_replace("", "", $fn);
         $fn = ew_IncludeTrailingDelimiter(ew_AppRoot(), TRUE) . $fn;
         if (file_exists($fn) || @fopen($fn, "rb") !== FALSE) {
             // Allow remote file
             if (ob_get_length()) {
                 ob_end_clean();
             }
             $pathinfo = pathinfo($fn);
             $ext = strtolower(@$pathinfo["extension"]);
             $ct = ew_ContentType("", $fn);
             if ($ct != "") {
                 header("Content-type: " . $ct);
             }
             if (in_array($ext, explode(",", EW_IMAGE_ALLOWED_FILE_EXT))) {
                 $size = @getimagesize($fn);
                 if ($size) {
                     header("Content-type: {$size['mime']}");
                 }
                 if ($width > 0 || $height > 0) {
                     echo ew_ResizeFileToBinary($fn, $width, $height);
                 } else {
                     echo file_get_contents($fn);
                 }
             } elseif (in_array($ext, explode(",", EW_DOWNLOAD_ALLOWED_FILE_EXT))) {
                 echo file_get_contents($fn);
             }
         }
     }
     // Global Page Unloaded event (in userfn*.php)
     //***Page_Unloaded();
     // Close connection
     //***ew_CloseConn();
 }
Example #20
0
 public function export($formName, $options = null)
 {
     header('Content-Type: text/x-ms-iqy');
     header("Content-Disposition: attachment; filename=\"{$formName}.iqy\"");
     $url = get_bloginfo('wpurl');
     $encFormName = urlencode($formName);
     $uri = "?action=cfdb-export&form={$encFormName}&enc=HTMLBOM";
     if (is_array($options)) {
         foreach ($options as $key => $value) {
             if ($key != 'form' && $key != 'enc') {
                 $uri = $uri . '&' . urlencode($key) . '=' . urlencode($options[$key]);
             }
         }
     }
     $encRedir = urlencode('wp-admin/admin-ajax.php' . $uri);
     if (ob_get_length()) {
         // Prevents misc chars/newlines from being printed during export.
         ob_clean();
     }
     // To get this to work right, we have to submit to the same page that the login form does and post
     // the same parameters that the login form does. This includes "log" and "pwd" for the login and
     // also "redirect_to" which is the URL of the page where we want to end up including a "form_name" parameter
     // to tell that final page to select which contact form data is to be displayed.
     //
     // "Selection=1" references the 1st HTML table in the page which is the data table.
     // "Formatting" can be "None", "All", or "RTF"
     echo "WEB\r\n1\r\n{$url}/wp-login.php?redirect_to={$encRedir}\r\nlog=[\"Username for {$url}\"]&pwd=[\"Password for {$url}\"]\r\n\r\nSelection=1\r\nFormatting=All\r\nPreFormattedTextToColumns=True\r\nConsecutiveDelimitersAsOne=True\r\nSingleBlockTextImport=False\r\nDisableDateRecognition=False\r\nDisableRedirections=False\r\n";
 }
 public function Render()
 {
     $RenderedCount = 0;
     foreach ($this->Items as $Item) {
         $this->EventArguments['AssetName'] = $this->AssetName;
         if (is_string($Item)) {
             if (!empty($Item)) {
                 if ($RenderedCount > 0) {
                     $this->FireEvent('BetweenRenderAsset');
                 }
                 echo $Item;
                 $RenderedCount++;
             }
         } elseif ($Item instanceof Gdn_IModule) {
             if (!GetValue('Visible', $Item, TRUE)) {
                 continue;
             }
             $LengthBefore = ob_get_length();
             $Item->Render();
             $LengthAfter = ob_get_length();
             if ($LengthBefore !== FALSE && $LengthAfter > $LengthBefore) {
                 if ($RenderedCount > 0) {
                     $this->FireEvent('BetweenRenderAsset');
                 }
                 $RenderedCount++;
             }
         } else {
             throw new Exception();
         }
     }
     unset($this->EventArguments['AssetName']);
 }
Example #22
0
 /**
  * Setup basic error handling checks/types, as well as register the error and exception
  * handlers.
  *
  * Called on static class initialization (i.e. when first loaded).
  *
  * @return void
  */
 public static function __init()
 {
     static::$_checks = array('type' => function ($config, $info) {
         return (bool) array_filter((array) $config['type'], function ($type) use($info) {
             return $type == $info['type'] || is_subclass_of($info['type'], $type);
         });
     }, 'code' => function ($config, $info) {
         return $config['code'] & $info['code'];
     }, 'stack' => function ($config, $info) {
         return (bool) array_intersect((array) $config['stack'], $info['stack']);
     }, 'message' => function ($config, $info) {
         return preg_match($config['message'], $info['message']);
     });
     $self = get_called_class();
     static::$_exceptionHandler = function ($exception, $return = false) use($self) {
         if (ob_get_length()) {
             ob_end_clean();
         }
         $info = compact('exception') + array('type' => get_class($exception), 'stack' => $self::trace($exception->getTrace()));
         foreach (array('message', 'file', 'line', 'trace') as $key) {
             $method = 'get' . ucfirst($key);
             $info[$key] = $exception->{$method}();
         }
         return $return ? $info : $self::handle($info);
     };
 }
Example #23
0
 /**
  * Handles a webservice command
  *
  * @param int       $commandCode
  *
  * @access public
  * @return boolean
  * @throws SoapFault
  */
 public function Handle($commandCode)
 {
     if (Request::GetDeviceType() !== "webservice" || Request::GetDeviceID() !== "webservice") {
         throw new FatalException("Invalid device id and type for webservice execution");
     }
     if (Request::GetGETUser() != Request::GetAuthUser()) {
         ZLog::Write(LOGLEVEL_INFO, sprintf("Webservice::HandleWebservice('%s'): user '%s' executing action for user '%s'", $commandCode, Request::GetAuthUser(), Request::GetGETUser()));
     }
     // initialize non-wsdl soap server
     $this->server = new SoapServer(null, array('uri' => "http://z-push.sf.net/webservice"));
     // the webservice command is handled by its class
     if ($commandCode == ZPush::COMMAND_WEBSERVICE_DEVICE) {
         ZLog::Write(LOGLEVEL_DEBUG, sprintf("Webservice::HandleWebservice('%s'): executing WebserviceDevice service", $commandCode));
         include_once 'webservicedevice.php';
         $this->server->setClass("WebserviceDevice");
     }
     // the webservice command is handled by its class
     if ($commandCode == ZPush::COMMAND_WEBSERVICE_USERS) {
         if (!defined("ALLOW_WEBSERVICE_USERS_ACCESS") || ALLOW_WEBSERVICE_USERS_ACCESS !== true) {
             throw new HTTPReturnCodeException(sprintf("Access to the WebserviceUsers service is disabled in configuration. Enable setting ALLOW_WEBSERVICE_USERS_ACCESS.", Request::GetAuthUser()), 403);
         }
         ZLog::Write(LOGLEVEL_DEBUG, sprintf("Webservice::HandleWebservice('%s'): executing WebserviceUsers service", $commandCode));
         if (ZPush::GetBackend()->Setup("SYSTEM", true) == false) {
             throw new AuthenticationRequiredException(sprintf("User '%s' has no admin privileges", Request::GetAuthUser()));
         }
         include_once 'webserviceusers.php';
         $this->server->setClass("WebserviceUsers");
     }
     $this->server->handle();
     ZLog::Write(LOGLEVEL_DEBUG, sprintf("Webservice::HandleWebservice('%s'): sucessfully sent %d bytes", $commandCode, ob_get_length()));
     return true;
 }
Example #24
0
 /**
  * Helper for endBlock and also clears the output buffer.
  * @param boolean $append Indicates that the new content should be appended to the existing block content.
  * @return void
  */
 public function endPut($append = false)
 {
     $this->endBlock($append);
     if (!count($this->blockStack) && ob_get_length() > 0) {
         ob_end_clean();
     }
 }
Example #25
0
/**
 * Sends a formated data file to the browser
 *
 * @package    core
 * @subpackage dataformat
 *
 * @param string $filename The base filename without an extension
 * @param string $dataformat A dataformat name
 * @param array $columns An ordered map of column keys and labels
 * @param Iterator $iterator An iterator over the records, usually a RecordSet
 * @param function $callback An option function applied to each record before writing
 * @param mixed $extra An optional value which is passed into the callback function
 */
function download_as_dataformat($filename, $dataformat, $columns, $iterator, $callback = null)
{
    if (ob_get_length()) {
        throw new coding_exception("Output can not be buffered before calling download_as_dataformat");
    }
    $classname = 'dataformat_' . $dataformat . '\\writer';
    if (!class_exists($classname)) {
        throw new coding_exception("Unable to locate dataformat/{$type}/classes/writer.php");
    }
    $format = new $classname();
    // The data format export could take a while to generate...
    set_time_limit(0);
    // Close the session so that the users other tabs in the same session are not blocked.
    \core\session\manager::write_close();
    $format->set_filename($filename);
    $format->send_http_headers();
    $format->write_header($columns);
    $c = 0;
    foreach ($iterator as $row) {
        if ($callback) {
            $row = $callback($row);
        }
        if ($row === null) {
            continue;
        }
        $format->write_record($row, $c++);
    }
    $format->write_footer($columns);
}
 /**
  * Запуск программы, единая точка входа.
  */
 public static function run()
 {
     if (session_status() == PHP_SESSION_NONE) {
         session_start();
     }
     $instance = new FrontController();
     try {
         $instance->init();
         $instance->handleRequest();
     } catch (\REXFramework\exceptions\AppException $e) {
         $e->process();
     } catch (\PDOException $e) {
         if (ob_get_length()) {
             ob_end_clean();
         }
         $myException = new \REXFramework\exceptions\AppException($e->getMessage());
         $myException->process();
     } catch (\Exception $e) {
         if (ob_get_length()) {
             ob_end_clean();
         }
         header('HTTP/1.0 404 Not Found');
         echo $e->getMessage();
     }
 }
 /**
  * @param \Throwable $exception
  *
  * @return bool
  */
 public function exceptionHandler(\Throwable $exception)
 {
     if ($exception instanceof ResponseCode) {
         try {
             $out = $this->render($exception->getCode(), [], $exception->display());
         } catch (\Throwable $exception) {
             return $this->exceptionHandler($exception);
         }
         // debug on dev / display trace
         if (!(AbstractApp::env() != AbstractApp::PRODUCTION && ob_get_length() > 0)) {
             self::response()->addHeader('Content-Type', $this->getErrorContentType());
         }
         self::response()->setStatus($exception->getCode());
         self::response()->setBody($out);
         HttpApp::instance()->end();
     } else {
         Handler::log($exception);
         if (AbstractApp::env() != AbstractApp::PRODUCTION) {
             Handler::exceptionHandler($exception);
         } else {
             $throw = new ResponseCode($exception->getMessage(), 500, $exception);
             $this->exceptionHandler($throw);
         }
     }
     return true;
 }
Example #28
0
 protected function after_output()
 {
     # flush once, because we're nice
     if (ob_get_length()) {
         ob_flush();
     }
 }
Example #29
0
function espresso_ical()
{
    $name = $_REQUEST['event_summary'] . ".ics";
    $output = "BEGIN:VCALENDAR\n" . "PRODID:-//xyz Corp//NONSGML PDA Calendar Version 1.0//EN\n" . "VERSION:2.0\n" . "BEGIN:VEVENT\n" . "DTSTAMP:" . $_REQUEST['currentyear'] . $_REQUEST['currentmonth'] . $_REQUEST['currentday'] . "T" . $_REQUEST['currenttime'] . "\n" . "UID:" . $_REQUEST['attendee_id'] . "@" . $_REQUEST['event_id'] . "\n" . "ORGANIZER:MAILTO:" . $_REQUEST['contact'] . "\n" . "DTSTART:" . $_REQUEST['startyear'] . $_REQUEST['startmonth'] . $_REQUEST['startday'] . "T" . $_REQUEST['starttime'] . "\n" . "DTEND:" . $_REQUEST['endyear'] . $_REQUEST['endmonth'] . $_REQUEST['endday'] . "T" . $_REQUEST['endtime'] . "\n" . "STATUS:CONFIRMED\n" . "CATEGORIES:" . $_REQUEST['event_categories'] . "\n" . "SUMMARY:" . $_REQUEST['event_summary'] . "\n" . "DESCRIPTION:" . $_REQUEST['event_description'] . "\n" . "END:VEVENT\n" . "END:VCALENDAR";
    if (ob_get_length()) {
        echo 'Some data has already been output, can\'t send iCal file';
    }
    header('Content-Type: application/x-download');
    if (headers_sent()) {
        echo 'Some data has already been output, can\'t send iCal file';
    }
    header('Content-Length: ' . strlen($output));
    header('Content-Disposition: attachment; filename="' . $name . '"');
    header('Cache-Control: private, max-age=0, must-revalidate');
    header('Pragma: public');
    header('Content-Type: application/octet-stream');
    header('Content-Type: application/force-download');
    header('Content-type: application/pdf');
    header("Cache-Control: no-cache, must-revalidate");
    // HTTP/1.1
    header("Content-Transfer-Encoding: binary");
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
    // Date in the past
    ini_set('zlib.output_compression', '0');
    echo $output;
    die;
}
Example #30
0
/**
 * 文件下载/或输出显示
 * @param $filepath 文件路径
 * @param $filename 文件名称
 */
function download($filepath, $filename = '', $output = 0)
{
    if (!$filename) {
        $filename = basename($filepath);
    }
    if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'msie ') !== false) {
        $filename = rawurlencode($filename);
    }
    $filetype = get_ext($filename);
    if (!file_exists($filepath)) {
        MSG('文件不存在');
    }
    $filesize = sprintf("%u", filesize($filepath));
    if (ob_get_length() !== false) {
        @ob_end_clean();
    }
    header('Pragma: public');
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Cache-Control: pre-check=0, post-check=0, max-age=0');
    header('Content-Transfer-Encoding: binary');
    header('Content-Encoding: none');
    header('Content-type: ' . $filetype);
    if (!$output) {
        header('Content-Disposition: attachment; filename="' . $filename . '"');
    }
    header('Content-length: ' . $filesize);
    readfile($filepath);
    exit;
}