/**
  * End the current session and clear local session
  * @return void
  */
 public function endSession()
 {
     $session = CheckfrontModule::session();
     if ($sessionID = $session->getID()) {
         CheckfrontModule::api()->post(new CheckfrontAPIRequest('session/end', array('session_id' => $sessionID)));
     }
     $session->clear(null);
 }
 /**
  *
  */
 public function testListPackages()
 {
     $this->loadConfig();
     /** @var CheckfrontAPIPackagesResponse $response */
     $response = CheckfrontModule::api()->listPackages();
     $packages = $response->getPackages();
     $info = $packages->map('ItemID', 'Title');
     $this->assertContains('Package A', $info);
 }
 /**
  * Gets the package items using config.package_item_path as index into data and
  * return a list of CheckfrontItemModels.
  *
  * @return SS_List may be empty
  */
 public function getPackageItems()
 {
     $list = new ArrayList();
     if ($this->isValid()) {
         $path = self::get_config_setting('package_items_path');
         $packageItems = CheckfrontModule::lookup_path($path, $this->data, $found);
         if ($packageItems && $found) {
             foreach ($packageItems as $item) {
                 $list->push(CheckfrontItemModel::create()->fromCheckfront($item));
             }
         }
     }
     return $list;
 }
 /**
  * Loads all *.php files found at the sdk path module/sdk/{version}/lib and adds this.loadClass to
  * spl autoloader chain.
  *
  * @param string|null $version - either use this version (e.g. '3.0')
  * or take it from config.version if passed falsish value.
  *
  * @sideeffect if passed a version will update this.config to that version.
  */
 public function __construct($version = null)
 {
     if ($version) {
         // provided a version, update config so we can use in the class loader later
         Config::inst()->update(__CLASS__, 'version', $version);
     } else {
         // no version, try and take from config instead.
         $version = $this->config()->get('version');
     }
     $pathTemp = $this->config()->get('sdk_path');
     // if sdk path is 'absolute' then load from site root, otherwise load relative to checkfront module directory
     $this->sdkPath = Controller::join_links(Director::baseFolder(), substr($pathTemp, 0, 1) === '/' ? '' : CheckfrontModule::module_path(), $this->detokenise($pathTemp, $version));
     // now save the implementation path for later
     $this->implPath = Controller::join_links(Director::baseFolder(), CheckfrontModule::module_path(), $this->detokenise($this->config()->get('implementation_path'), $version));
     spl_autoload_register(array($this, 'loadClass'));
 }
 public static function factory($controller, CheckfrontAPIPackageResponse $packageResponse, array $info, array $data)
 {
     list($packageID, $startDate, $endDate, $linkType, $userType, $paymentType) = $info;
     // now build the form
     $fields = new FieldList();
     // add a hidden accessKey field if set
     $accessKey = isset($data[CheckfrontForm::AccessKeyFieldName]) ? $data[CheckfrontForm::AccessKeyFieldName] : null;
     $fields->push(new HiddenField(CheckfrontForm::AccessKeyFieldName, '', $accessKey));
     if ($userType === CheckfrontModule::UserTypeOrganiser) {
         // if organiser then add hidden start and end date fields for the actual booking
         $fields->merge(array(new HiddenField(CheckfrontForm::StartDateFieldName, '', $startDate), new HiddenField(CheckfrontForm::EndDateFieldName, '', $endDate)));
     } else {
         // if not organiser then let user specify their start and end dates
         $fields->merge(array(CheckfrontForm::make_date_field(CheckfrontForm::StartDateFieldName, 'Start Date', $startDate, $startDate, $endDate), CheckfrontForm::make_date_field(CheckfrontForm::EndDateFieldName, 'End Date', $endDate, $startDate, $endDate)));
     }
     // add the package items to the field list which will make the form as fields
     /** @var CheckfrontModel $item */
     foreach ($packageResponse->getPackageItems() as $item) {
         if ($controller->shouldShowItem($item, $userType, $linkType)) {
             $fields->merge($item->fieldsForForm('form'));
         }
     }
     $fields->merge(new FieldList(array(new HiddenField(CheckfrontAccessKeyForm::AccessKeyFieldName, '', $accessKey))));
     $actions = new FieldList();
     $required = array();
     // add the standard 'booking' fields (name etc)
     if ($response = CheckfrontModule::api()->fetchBookingForm()) {
         if ($response->isValid()) {
             // now add the booking fields to the fieldlist for the form
             $bookingFields = $response->getFormFields($required);
             $fields->merge($bookingFields);
         }
         $actions->push(new FormAction(static::SubmitButtonName, _t(__CLASS__ . ".SubmitButtonText")));
     }
     $validator = new RequiredFields($required);
     $form = new CheckfrontPackageBookingForm($controller, static::FormName, $fields, $actions, $validator);
     return $form;
 }
 public function makeBooking(CheckfrontBookingModel $booking)
 {
     $sessionID = CheckfrontModule::session()->getID();
     $params = array_merge(array('session_id' => $sessionID), $booking->toCheckfront('booking/create'));
     return new CheckfrontAPIBookingResponse($this()->api(new CheckfrontAPIRequest('booking/create', $params)));
 }
 /**
  * Find an item in data by a path e.g. 'request.status' or 'item.images.1.src'
  * @param $path
  * @param bool|false $found
  *
  * @return array
  */
 public function path($path, &$found = false)
 {
     return CheckfrontModule::lookup_path($path, $this->data, $found);
 }
 public function __construct()
 {
     parent::__construct();
     $this->cache = CheckfrontModule::api_cache();
 }
 /**
  * Return the desctructured token or part thereof.
  *
  * @param string $which     - optional single item to return, otherwise returns all
  * @param string $accessKey - to decrypt token, must be supplied first time around or force by resupplying
  *
  * @throws Exception
  * @return array|null
  */
 public function getTokenInfo($which = null, $accessKey = null)
 {
     $request = $this->owner->getRequest();
     if ($token = $request->param(self::TokenParam)) {
         $detokenised = CheckfrontModule::decrypt_token($accessKey, $token);
         if (!is_null($which)) {
             if (!array_key_exists($which, $detokenised)) {
                 return null;
             }
             return $detokenised[$which];
         }
         return $detokenised;
     } else {
         throw new CheckfrontException("No token", CheckfrontException::TypeError);
     }
 }
 /**
  * Iterates through config.casting and if key exist in data then applied casting rules.
  *
  * @param array $data
  * @param array $casted - receives names of fields which where casted mapped to the casting types.
  *
  * @return array
  * @throws Exception
  */
 protected function cast(array $data, array &$casted = array())
 {
     foreach ($this->config()->get('casting') as $name => $type) {
         // casting may deal with null values so don't use isset()
         if (array_key_exists($name, $data)) {
             switch ($type) {
                 case self::CastDate:
                     $data[$name] = CheckfrontModule::from_checkfront_date($data[$name]);
                     $casted[$name][] = $type;
                     break;
                 default:
                     throw new CheckfrontException("Unknown cast type '{$type}'", CheckfrontException::TypeError);
             }
         }
     }
     return $data;
 }
 public function buildDates($startDate, $endDate)
 {
     $numDays = static::get_config_setting('default_num_days');
     return array('start_date' => CheckfrontModule::checkfront_date($startDate ?: static::get_config_setting('default_start_date')), 'end_date' => CheckfrontModule::checkfront_date($endDate ?: (static::get_config_setting('default_end_date') ?: "{$startDate} +{$numDays} day")));
 }
 public function __construct($dataRecord = null)
 {
     $this->api = CheckfrontModule::api();
     parent::__construct($dataRecord);
 }
 /**
  * Make a public link/token to this booking
  *
  * @param $endPoint
  *
  * @return String
  */
 public function PublicLink($endPoint = null)
 {
     $endPoint = $endPoint ? $endPoint : Controller::curr()->getRequest()->getURL();
     return CheckfrontModule::make_link(null, $endPoint, $this->ItemID, '', '', CheckfrontModule::LinkTypePublic, CheckfrontModule::UserTypeIndividual, CheckfrontModule::PaymentPayNow);
 }
 /**
  * Override empty parent to store the session ID and data in CheckfrontSession.
  * @param $sessionID
  * @param array $data
  */
 public function session($sessionID, $data = array())
 {
     CheckfrontModule::session()->setID($sessionID)->setData('request', $data);
     parent::session($sessionID, $data);
 }
 /**
  * Add package to the current checkfront session.
  *
  * @param CheckfrontPackageModel $package
  * @param array $addOrUpdateParams
  * @return CheckfrontAPIResponse
  */
 public function addPackageToSession(CheckfrontPackageModel $package, array $addOrUpdateParams = array())
 {
     $params = array_merge(array('session_id' => CheckfrontModule::session()->getID()), $package->toCheckfront('booking/session'), $addOrUpdateParams);
     $response = new CheckfrontAPIResponse($this()->post(new CheckfrontAPIRequest('booking/session', $params)));
     return $response;
 }
 /**
  * Convert a date passed as 'YYYY-MM-DD', SS_Datetime or year, month, day
  * to checkfront 'YYYYMMDD' format.
  *
  * @param string|null $dateOrYear
  * @param null $month
  * @param null $day
  *
  * @return bool|mixed|string
  * @throws Exception
  */
 public static function checkfront_date($dateOrYear, $month = null, $day = null)
 {
     $checkfrontFormat = CheckfrontModule::checkfront_date_format();
     if (empty($dateOrYear)) {
         return date($checkfrontFormat);
     } elseif ($dateOrYear instanceof SS_Datetime) {
         // build from SS_Datetime
         $result = $dateOrYear->Year() . $dateOrYear->Month() . $dateOrYear->Day();
     } elseif (is_int($dateOrYear)) {
         // year is an integer year
         if (func_num_args() === 1 && $dateOrYear > mktime(0, 0, 0, 1, 1, 1970)) {
             // $dateOrYear is probably a unix timestamp
             $result = date($checkfrontFormat, $dateOrYear);
         } elseif (func_num_args() === 3) {
             // $dateOrYear is year, and month and day supplied
             $result = date($checkfrontFormat, mktime(0, 0, 0, $month, $day, $dateOrYear));
         } else {
             throw new CheckfrontException("Need either 1 or 3 arguments when dataOrYear is an integer", CheckfrontException::TypeError);
         }
     } elseif (3 === explode($dateOrYear, '-')) {
         // probably formatted as YYYY-MM-DD
         $result = str_replace(array('-', '_'), '', $dateOrYear);
         if (!is_numeric($result)) {
             throw new CheckfrontException("Invalid date passed: '{$dateOrYear}'", CheckfrontException::TypeError);
         }
     } else {
         // this may be something that strtotime can use e.g. 'today' or '+2 month'?
         $unixTime = strtotime($dateOrYear);
         if ($unixTime === false) {
             throw new CheckfrontException("Invalid date passed: '{$dateOrYear}'", CheckfrontException::TypeError);
         }
         $result = date($checkfrontFormat, $unixTime);
     }
     return $result;
 }
 /**
  * Returns and shortened URL which will redirect from CheckfrontModule.config.shortened_endpoint to
  * the full booking path when hit.
  *
  * @param $accessKey
  * @param $itemID
  * @param $startDate
  * @param $endDate
  * @param $linkType
  * @param $userType
  * @param $paymentType
  *
  * @return String
  * @throws ValidationException
  * @throws null
  */
 protected static function makeLink($accessKey, $itemID, $startDate, $endDate, $linkType, $userType, $paymentType)
 {
     $endPoint = Controller::join_links(CheckfrontModule::PrivateEndPoint, 'package');
     $fullURL = CheckfrontModule::make_link($accessKey, $endPoint, $itemID, $startDate, $endDate, $linkType, $userType, $paymentType);
     $shortURL = new CheckfrontShortenedURL(array('URL' => $fullURL));
     $shortURL->write();
     return Controller::join_links(Director::absoluteBaseURL(), CheckfrontModule::shorturl_endpoint(), $shortURL->Key);
 }
<?php

// dynamically add CheckfrontModule.private_endpoint to the routing table.
Director::addRules(100, array(CheckfrontModule::private_endpoint() => 'CheckfrontPackageController', CheckfrontModule::shorturl_endpoint() => 'CheckfrontURLShortenerController'));
 protected function makePaymentTypeField()
 {
     return new DropdownField(self::PaymentTypeFieldName, $this->getFieldLabel(self::PaymentTypeFieldName), CheckfrontModule::payment_types());
 }