示例#1
0
function Shipping_scheduled_response_content($params)
{
    // redirect to home page if not logged in
    if (!Users::loggedInUser()) {
        header("Location: " . Q_Request::baseUrl());
        exit;
    }
    // get "Shipping/shipments" stream
    $publisherId = Users::communityId();
    $streamName = 'Shipping/shipment/' . Q_Request::uri()->shipmentStreamName;
    $stream = Streams::fetchOne($publisherId, $publisherId, $streamName);
    //$xml = simplexml_load_file(APP_DIR.'/classes/dhl/response.xml');
    //$xml = simplexml_load_string(str_replace('req:', '', file_get_contents(APP_DIR.'/classes/dhl/response.xml')));
    //print_r($xml); exit;
    // test pickup
    //$carrier = new Shipping_Carrier_DHL();
    //$carrier->createAWBBarCode($stream, 'iVBORw0KGgoAAAANSUhEUgAAAYwAAABeAQMAAAAKdrGZAAAABlBMVEX///8AAABVwtN+AAAAaklEQVR42mNkYGBIyL8wZcutG2wTzVMZfG99eep7y1tp5oIokaMMOtabG6PuTflrnnHqVfI013vzlRYwMDAxkAxGtYxqGdUyqmVUy6iWUS2jWka1jGoZ1TKqZVTLqJZRLaNaRrWMaiEVAABqDRe8DYfcJgAAAABJRU5ErkJggg==', "AWBBarCode");
    // -----------
    //echo Shipping::getShipmentRelation($stream, true);
    //unlink("/tmp/dhl-api-autoload.php");
    if (!$stream || !$stream->testReadLevel('see')) {
        throw new Users_Exception_NotAuthorized();
    }
    return Q::view('Shipping/content/scheduled.php', compact('streamName'));
}
示例#2
0
function Shipping_shipment_response_content($params)
{
    $user = Users::loggedInUser(true);
    // copy from shipment
    $useTemplate = Q_Request::uri()->template ? "Shipping/shipment/" . Q_Request::uri()->template : false;
    // Check if stream "Shipping/shipments" exists for current user. If no -> create one.
    Shipping::shipments();
    // Check if stream "Shipping/templates" exists for current user. If no -> create one.
    Shipping::createTemplatesStream();
    // Collect streams for shipments. Relations: "describing", "scheduled", "confirmed", "shipping", "canceled", "returned"
    $shipment = Shipping::shipment();
    //$shipment->addPreloaded($userId);
    // test for UPS pickup
    //$stream = Streams::fetchOne("Shipping", "Shipping", "Shipping/shipment/Qdqpcspny");
    //$carrier = new Shipping_Carrier_UPS();
    //$carrier->pickupCreate($stream);
    //-------------------------------
    // add main style
    Q_Response::addStylesheet('css/Shipment.css');
    // set communityId
    Q_Response::setScriptData("Q.info.communityId", Users::communityId());
    Q_Response::setScriptData("Q.info.useTemplate", $useTemplate);
    Q_Response::addScript('js/shipment.js');
    Q_Response::addScript('js/date.js');
    // add jquery UI
    //Q_Response::addStylesheet('//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css');
    //Q_Response::addScript('//code.jquery.com/ui/1.11.4/jquery-ui.js');
    // add pickadate as date picker
    Q_Response::addStylesheet('js/pickadate/compressed/themes/default.css');
    Q_Response::addStylesheet('js/pickadate/compressed/themes/default.date.css');
    Q_Response::addScript('js/pickadate/compressed/picker.js');
    Q_Response::addScript('js/pickadate/compressed/picker.date.js');
    return Q::view('Shipping/content/shipment.php', compact('user', 'shipment', 'useTemplate'));
}
示例#3
0
 /**
  * Excecute web request
  * @method execute
  * @static
  */
 static function execute()
 {
     // Fixes for different platforms:
     if (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
         // ISAPI 3.0
         $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
     }
     // Get the base URL
     $base_url = Q_Request::baseUrl();
     if (Q::$controller === 'Q_ActionController') {
         // we detected action.php in the URL, but
         // a misconfigured web server executed index.php instead
         return Q_ActionController::execute();
     }
     // Set the controller that is being used
     if (!isset(Q::$controller)) {
         Q::$controller = 'Q_WebController';
     }
     try {
         $slots = Q_Request::slotNames(false);
         $slots = $slots ? ' slots: (' . implode(',', $slots) . ') from' : '';
         $method = Q_Request::method();
         Q::log("{$method}{$slots} url: " . Q_Request::url(true), null, null, array('maxLength' => 10000));
         Q_Dispatcher::dispatch();
         $dispatchResult = Q_Dispatcher::result();
         if (!isset($dispatchResult)) {
             $dispatchResult = 'Ran dispatcher';
         }
         $uri = Q_Request::uri();
         $module = $uri->module;
         $action = $uri->action;
         if ($module and $action) {
             $slotNames = Q_Request::slotNames();
             $returned_slots = empty($slotNames) ? '' : implode(',', $slotNames);
             Q::log("~" . ceil(Q::milliseconds()) . 'ms+' . ceil(memory_get_peak_usage() / 1000) . 'kb.' . " {$dispatchResult} for {$module}/{$action}" . " ({$returned_slots})", null, null, array('maxLength' => 10000));
         } else {
             Q::log("~" . ceil(Q::milliseconds()) . 'ms+' . ceil(memory_get_peak_usage() / 1000) . 'kb.' . " {$dispatchResult} No route for " . $_SERVER['REQUEST_URI'], null, null, array('maxLength' => 10000));
         }
     } catch (Exception $exception) {
         /**
          * @event Q/exception
          * @param {Exception} exception
          */
         Q::event('Q/exception', compact('exception'));
     }
 }
示例#4
0
 /**
  * Dispatches a URI for internal processing.
  * Usually called by a front controller.
  * @method dispatch
  * @static
  * @param {mixed} [$uri=null] You can pass a custom URI to dispatch. Otherwise, Qbix will attempt
  *  to route the requested URL, if any.
  * @param {array} [$check=array('accessible')] Pass array() to skip checking whether the URI can be obtained
  *  as a result of routing some URL.
  * @return {boolean}
  * @throws {Q_Exception_MethodNotSupported}
  * @throws {Q_Exception_Recursion}
  * @throws {Q_Exception_DispatcherErrors}
  * @throws {Q_Exception_DispatcherForward}
  */
 static function dispatch($uri = null, $check = array('accessible'))
 {
     if (!is_array($check)) {
         $check = array('accessible');
     }
     if (isset($uri)) {
         if (in_array('accessible', $check)) {
             if (!Q_Uri::url($uri)) {
                 // We shouldn't dispatch to this URI
                 $uri = Q_Uri::from(array());
             }
         }
         self::$uri = Q_Uri::from($uri);
     } else {
         $request_uri = Q_Request::uri();
         self::$uri = clone $request_uri;
     }
     // if file or dir is requested, try to serve it
     $served = false;
     $skip = Q_Config::get('Q', 'dispatcherSkipFilename', false);
     $filename = $skip ? false : Q_Request::filename();
     if ($filename) {
         if (is_dir($filename)) {
             /**
              * @event Q/dir
              * @param {string} filename
              * @param {string} routed_uri
              * @return {boolean}
              */
             $served = Q::event("Q/dir", compact('filename', 'routed_uri'));
             $dir_was_served = true;
         } else {
             /**
              * @event Q/file
              * @param {string} filename
              * @param {string} routed_uri
              * @return {boolean}
              */
             $served = Q::event("Q/file", compact('filename', 'routed_uri'));
             $dir_was_served = false;
         }
     }
     // if response was served, then return
     if ($served) {
         self::result($dir_was_served ? "Dir served" : "File served");
         return true;
     }
     // This loop is for forwarding
     $max_forwards = Q_Config::get('Q', 'maxForwards', 10);
     for ($try = 0; $try < $max_forwards; ++$try) {
         // Make an array from the routed URI
         $routed_uri_array = array();
         if (self::$uri instanceof Q_Uri) {
             $routed_uri_array = self::$uri->toArray();
         }
         // If no module was found, then respond with noModule and return
         if (!isset(self::$uri->module)) {
             /**
              * @event Q/noModule
              * @param {array} $routed_uri_array
              */
             Q::event("Q/noModule", $routed_uri_array);
             // should echo things
             self::result("No module");
             return false;
         }
         $module = self::$uri->module;
         try {
             // Implement restricting of modules we are allowed to access
             $routed_modules = Q_Config::get('Q', 'routedModules', null);
             if (isset($routed_modules)) {
                 if (!in_array($module, $routed_modules)) {
                     /**
                      * @event Q/notFound
                      * @param {array} $routed_uri_array
                      */
                     Q::event('Q/notFound', $routed_uri_array);
                     // should echo things
                     self::result("Unknown module");
                     return false;
                 }
             } else {
                 if (!Q::realPath("handlers/{$module}")) {
                     Q::event('Q/notFound', $routed_uri_array);
                     // should echo things
                     self::result("Unknown module");
                     return false;
                 }
             }
             // Implement notFound if action was not found
             if (empty(self::$uri->action)) {
                 Q::event('Q/notFound', $routed_uri_array);
                 // should echo things
                 self::result("Unknown action");
                 return false;
             }
             // Fire a pure event, for aggregation etc
             if (!isset(self::$skip['Q/prepare'])) {
                 /**
                  * @event Q/prepare
                  * @param {array} $routed_uri_array
                  */
                 Q::event('Q/prepare', $routed_uri_array, true);
             }
             // Perform validation
             if (!isset(self::$skip['Q/validate'])) {
                 /**
                  * @event Q/validate
                  * @param {array} $routed_uri_array
                  */
                 Q::event('Q/validate', $routed_uri_array);
                 if (!isset(self::$skip['Q/errors'])) {
                     // Check if any errors accumulated
                     if (Q_Response::getErrors()) {
                         // There were validation errors -- render a response
                         self::result('Validation errors');
                         self::errors(null, $module, null);
                         return false;
                     }
                 }
             }
             // Time to instantiate some app objects from the request
             if (!isset(self::$skip['Q/objects'])) {
                 /**
                  * @event Q/objects
                  * @param {array} $routed_uri_array
                  */
                 Q::event('Q/objects', $routed_uri_array, true);
             }
             // We might want to reroute the request
             if (!isset(self::$skip['Q/reroute'])) {
                 /**
                  * @event Q/reroute
                  * @param {array} $routed_uri_array
                  * @return {boolean} whether to stop the dispatch
                  */
                 $stop_dispatch = Q::event('Q/reroute', $routed_uri_array, true);
                 if ($stop_dispatch) {
                     self::result("Stopped dispatch");
                     return false;
                 }
             }
             // Make some changes to server state, possibly
             $method = Q_Request::method();
             if ($method != 'GET') {
                 $methods = Q_Config::get('Q', 'methods', array('POST', 'PUT', 'DELETE', 'OPTIONS', 'HEAD'));
                 if (!in_array($method, $methods)) {
                     throw new Q_Exception_MethodNotSupported(compact('method'));
                 }
                 $method_event = 'Q/' . strtolower($method);
                 if (!isset(self::$skip['Q/method']) and !isset(self::$skip[$method_event])) {
                     if (!Q::canHandle($method_event)) {
                         throw new Q_Exception_MethodNotSupported(compact('method'));
                     }
                     Q::event($method_event);
                 }
             }
             // You can calculate some analytics here, and store them somewhere
             if (!isset(self::$skip['Q/analytics'])) {
                 /**
                  * @event Q/analytics
                  * @param {array} $routed_uri_array
                  */
                 Q::event('Q/analytics', $routed_uri_array, true);
             }
             if (!isset(self::$skip['Q/errors'])) {
                 // Check if any errors accumulated
                 if (Q_Response::getErrors()) {
                     // There were processing errors -- render a response
                     self::result('Processing errors');
                     self::errors(null, $module, null);
                     return false;
                 }
             }
             // When handling all further events, you should probably
             // refrain from changing server state, and only do reading.
             // That is because GET in HTTP is not supposed to have side effects
             // for which the client is responsible.
             // Start buffering the response, unless otherwise requested
             $handler = Q_Response::isBuffered();
             if ($handler !== false) {
                 $ob = new Q_OutputBuffer($handler);
             }
             // Generate and render a response
             /**
              * @event Q/response
              * @param {array} $routed_uri_array
              */
             self::$response_started = true;
             Q::event("Q/response", $routed_uri_array);
             if (!empty($ob)) {
                 $ob->endFlush();
             }
             self::result("Served response");
             return true;
         } catch (Q_Exception_DispatcherForward $e) {
             if (!empty($ob)) {
                 $ob->getClean();
             }
             self::handleForwardException($e);
         } catch (Q_Exception_DispatcherErrors $e) {
             if (!empty($ob)) {
                 $partial_response = $ob->getClean();
             } else {
                 $partial_response = null;
             }
             self::errors(null, $module, $partial_response);
             self::result("Rendered errors");
             return true;
         } catch (Exception $exception) {
             if (!empty($ob)) {
                 $partial_response = $ob->getClean();
             } else {
                 $partial_response = null;
             }
             $message = $exception->getMessage();
             $file = $exception->getFile();
             $line = $exception->getLine();
             if (is_callable(array($exception, 'getTraceAsStringEx'))) {
                 $trace_string = $exception->getTraceAsStringEx();
             } else {
                 $trace_string = $exception->getTraceAsString();
             }
             $colored = Q_Exception::coloredString($message, $file, $line, $trace_string);
             self::result("Exception occurred:\n\n{$colored}");
             try {
                 self::errors($exception, $module, $partial_response);
             } catch (Exception $e) {
                 if (!empty($forwarding_to_error_action)) {
                     // Looks like there were errors in the error action
                     // So show the default one with the original exception
                     throw $exception;
                 }
                 if (get_class($e) === 'Q_Exception_DispatcherForward') {
                     $forwarding_to_error_action = true;
                     self::handleForwardException($e);
                     continue;
                 } else {
                     throw $e;
                 }
             }
             return false;
         }
     }
     // If we are here, we have done forwarding too much
     throw new Q_Exception_Recursion(array('function_name' => 'Dispatcher::forward()'));
 }
示例#5
0
 /**
  * @method uri
  * @static
  * @return {Q_Uri}
  */
 static function uri()
 {
     if (!isset(self::$uri)) {
         self::$uri = Q_Uri::from(self::url());
     }
     return self::$uri;
 }
示例#6
0
function Shipping_invoice_response_content($params)
{
    $publisherId = Users::communityId();
    $streamName = 'Shipping/shipment/' . Q_Request::uri()->shipmentStreamName;
    $stream = Streams::fetchOne($publisherId, $publisherId, $streamName);
    $relation = Shipping::getShipmentRelation($stream);
    if (!$stream->testReadLevel('see')) {
        throw new Users_Exception_NotAuthorized();
    }
    $carrier = json_decode($stream->carrier) ?: new StdClass();
    // check if related invoices exists
    $invoices = Streams::related($stream->publisherId, $stream->publisherId, $stream->name, true, array("type" => "invoice"));
    $invoicesCount = count($invoices[1]);
    if ($invoicesCount) {
        $invoice = array_shift($invoices[1]);
        // for UPS fix PDF invoice to use tracking id in Waybill Number field
        if ($carrier->name == "UPS") {
            Shipping_Carrier_UPS::fixInvoice(APP_DIR . "/web/" . $invoice->content, $stream);
            exit;
        }
        header("location: " . Q_Request::baseUrl() . '/' . $invoice->content);
        exit;
    }
    //----------------------------------
    // check if airwaybill bar code exist
    $carrier->AWBBarCode = false;
    $barCodes = Streams::related($stream->publisherId, $stream->publisherId, $stream->name, true, array("type" => "AWBBarCode"));
    $barCodesCount = count($barCodes[1]);
    if ($barCodesCount) {
        $barCode = array_shift($barCodes[1]);
        $carrier->AWBBarCode = Q_Request::baseUrl() . '/' . $barCode->content;
    }
    /*
    	 $carrier = json_decode($stream->fields['carrier']);
    	if($carrier->name == "TNT"){
    		header ("Content-Type:text/xml");
    		echo $stream->fields['carrierInvoice'];
    		exit;
    	}*/
    $addressReceiver = json_decode($stream->receiver) ?: new StdClass();
    $addressReceiver->street = implode("<br>", Shipping_Carrier::addAddressLine($addressReceiver));
    $addressFrom = json_decode($stream->origin) ?: new StdClass();
    $addressFrom->street = implode("<br>", Shipping_Carrier::addAddressLine($addressFrom));
    $addressTo = json_decode($stream->destination) ?: new StdClass();
    $addressTo->street = implode("<br>", Shipping_Carrier::addAddressLine($addressTo));
    $packages = json_decode($stream->packages) ?: new StdClass();
    $products = json_decode($stream->products) ?: new StdClass();
    $products->packages = Q::ifset($products, 'packages', array());
    $products->currency = Q::ifset($products, 'currency', '');
    if (!$carrier->name) {
        throw new exception("Carrier name empty!");
    }
    if (!array_key_exists($carrier->name, Q_Config::expect('Shipping', 'carriers'))) {
        throw new exception("Unexpected carrier name " . $carrier->name . "!");
    }
    $carrier->trackingId = Q::ifset($carrier, 'trackingId', '');
    //$carrier->shipmentId = Q::ifset($carrier, 'waybillNumber', '');
    $invoiceOptions = json_decode($stream->invoiceOptions) ?: new StdClass();
    $invoiceOptions->invoiceNumber = Q::ifset($invoiceOptions, 'invoiceNumber', '');
    $invoiceOptions->purchaseOrderNo = Q::ifset($invoiceOptions, 'purchaseOrderNo', '');
    $invoiceOptions->reasonForExport = Q::ifset($invoiceOptions, 'reasonForExport', '');
    $invoiceOptions->termsOfDelivery = Q::ifset($invoiceOptions, 'termsOfDelivery', '');
    // normalize termsOfDelivery
    if ($invoiceOptions->termsOfDelivery) {
        $termsOfDelivery = Q_Config::expect('Shipping', "options", "termsOfDelivery");
        if (array_key_exists($invoiceOptions->termsOfDelivery, $termsOfDelivery)) {
            $invoiceOptions->termsOfDelivery = $termsOfDelivery[$invoiceOptions->termsOfDelivery]["name"];
        }
    }
    $invoiceOptions->ftrExemptions = Q::ifset($invoiceOptions, 'ftrExemptions', '');
    $collectInstructions = json_decode($stream->collectInstructions) ?: new StdClass();
    $collectInstructions->exportDate = Q::ifset($collectInstructions, 'exportDate', '');
    Q_Response::addStylesheet('css/ShipmentInvoice.css');
    Q_Response::addStylesheet('css/ShipmentInvoice' . $carrier->name . '.css');
    //Q_Response::addStylesheet('js/jquery-editable/jquery-editable/css/jquery-editable.css');
    //Q_Response::addScript('js/jquery-editable/jquery-editable/js/jquery-editable-poshytip.js');
    //Q_Response::addScriptLine("$.fn.editable.defaults.mode = 'inline';");
    return Q::view('Shipping/content/invoice' . $carrier->name . '.php', compact('addressFrom', 'addressTo', 'addressReceiver', 'packages', 'products', 'carrier', 'invoiceOptions', 'collectInstructions', 'streamName', 'relation'));
}
示例#7
0
function Shipping_label_response_content($params)
{
    $streamName = Q_Request::uri()->shipmentStreamName;
    $publisherId = Users::communityId();
    $stream = Streams::fetchOne($publisherId, $publisherId, 'Shipping/shipment/' . $streamName);
    if (!$stream->testReadLevel('see')) {
        throw new Users_Exception_NotAuthorized();
    }
    $carrier = json_decode($stream->fields['carrier']) ?: new StdClass();
    if (!is_object($carrier)) {
        throw new exception("carrier is not an object!");
    }
    // TNT carrier
    if ($carrier->name == "TNT") {
        $xml = new XMLReader();
        // check if XML valid
        if (!$xml->xml($stream->fields['carrierLabel'], NULL, LIBXML_DTDVALID)) {
            die("XML not valid");
        }
        // add back button
        $stream->fields['carrierLabel'] = preg_replace("/<CONSIGNMENTBATCH>/", "<CONSIGNMENTBATCH>\n<ISWEBVIEW>" . Q_Request::isWebView() . "</ISWEBVIEW>", $stream->fields['carrierLabel']);
        // add FTR Exemptions
        $invoice = json_decode($stream->invoiceOptions) ?: new StdClass();
        $stream->fields['carrierLabel'] = preg_replace("/<CONSIGNMENTBATCH>/", "<CONSIGNMENTBATCH>\n<FTR>" . $invoice->ftrExemptions . "</FTR>", $stream->fields['carrierLabel']);
        header("Content-Type:text/xml");
        echo $stream->fields['carrierLabel'];
        exit;
    } elseif (in_array($carrier->name, array("UPS", "FEDEX"))) {
        $labels = Streams::related($stream->publisherId, $stream->publisherId, $stream->name, true, array("type" => "label"));
        $orient = Q_Config::expect('Shipping', 'labelsOption', 'orient');
        $perPage = (int) Q_Config::expect('Shipping', 'labelsOption', 'perPage');
        // angle label rotate 90 or -90
        $angle = 1;
        // for UPS -90, for other 90
        if ($carrier->name == "UPS") {
            $angle = -1;
        }
        // include labels size calculation for all labels
        Q_Response::addScript('js/labels.js');
        Q_Response::addStylesheet('css/ShipmentLabels.css');
        if ($orient == "vertical") {
            Q_Response::addStylesheet('css/ShipmentLabelsVertical.css');
        }
        return Q::view('Shipping/content/imgLabels.php', compact('labels', 'perPage', 'angle'));
    } elseif ($carrier->name == "DHL") {
        $labels = Streams::related($stream->publisherId, $stream->publisherId, $stream->name, true, array("type" => "label"));
        $labelsCount = count($labels[1]);
        if ($labelsCount) {
            $label = array_shift($labels[1]);
            Shipping_Carrier_DHL::fixLabels(APP_DIR . "/web/" . $label->content, $stream);
            exit;
            //header("location: ".Q_Request::baseUrl().'/'.$label->content);
            //exit;
        }
    }
    $title = $stream->fields['title'];
    $addressFrom = json_decode($stream->fields['origin']);
    $addressTo = json_decode($stream->fields['destination']);
    $packages = json_decode($stream->fields['packages']);
    //$carrier = json_decode($stream->fields['carrier']);
    $invoiceOptions = json_decode($stream->fields['invoiceOptions']);
    $addressFrom = ($addressFrom->name ? $addressFrom->name . "<br>" : '') . $addressFrom->street . ($addressFrom->unit ? ' ' . $addressFrom->unit : '') . "<br>" . $addressFrom->city . ' ' . $addressFrom->zipcode . "<br>" . $addressFrom->country;
    $addressTo = ($addressTo->name ? $addressTo->name . "<br>" : '') . $addressTo->street . ($addressTo->unit ? ' ' . $addressTo->unit : '') . "<br>" . "<span class='city'>" . $addressTo->city . ' ' . $addressTo->zipcode . "</span><br>" . $addressTo->country;
    $exportDate = $invoiceOptions->exportDate;
    $class = "Shipping_Carrier_" . strtoupper($carrier->name);
    $labels = $class::labels($addressFrom, $addressTo, $packages, $carrier, $exportDate);
    echo <<<EOT
\t<!DOCTYPE html>
\t<html>
\t<head>
\t\t<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
\t\t<title>Labels for {$title}</title>
\t</head>
\t<body>
\t{$labels}
\t</body>
</html>
EOT;
    exit;
}
示例#8
0
 /**
  * return environment variables
  * @method getVars
  * @static
  * @return Object
  */
 static function getVars()
 {
     $userId = Users::loggedInUser(true)->id;
     $asUserId = Q_Request::uri()->userId ?: $userId;
     return (object) array("userId" => $userId, "asUserId" => $asUserId, "communityId" => Users::communityId(), "shipmentsStreamName" => "Shipping/shipments/" . $userId, "asShipmentsStreamName" => "Shipping/shipments/" . $asUserId);
 }