public function resolveParams(StorageFacilityInfo $sfInfo)
 {
     $params = $sfInfo->getStorageFacilityParams();
     $params->Domain = $this->resolveProperties(URLUtils::resolveVariables($params->Domain));
     $params->BaseURI = $this->resolveProperties(URLUtils::resolveVariables($params->BaseURI));
     $params->BaseStoragePath = $this->resolveProperties(URLUtils::resolveVariables($params->BaseStoragePath));
     return $params;
 }
 public function items()
 {
     $feedURL = (string) $this->getRequiredTemplateVariable('FeedURL');
     $nativeOrder = StringUtils::strToBool((string) $this->getTemplateVariable('NativeOrder'));
     $includeImage = StringUtils::strToBool((string) $this->getTemplateVariable('IncludeImage'));
     $maxRows = intval((string) $this->getRequiredTemplateVariable('MaxRows'));
     $items = array();
     if (!URLUtils::isUrl($feedURL)) {
         return $items;
     }
     try {
         $feed = $this->FeedParser->parseFeed($feedURL, $nativeOrder);
         $i = 0;
         foreach ($feed->get_items() as $item) {
             if ($i >= $maxRows) {
                 break;
             }
             if (trim($item->get_title()) == '') {
                 continue;
             }
             $itemDate = null;
             if ($item->get_date() != '') {
                 $itemDate = $this->DateFactory->newStorageDate($item->get_date());
             }
             $img = null;
             if ($includeImage) {
                 // first try to get it from the enclosure node itself
                 $tags = $item->get_item_tags('', 'enclosure');
                 if (is_array($tags)) {
                     foreach ($tags as $tag) {
                         if (!isset($tag['attribs']['']['type'])) {
                             continue;
                         }
                         if (strpos($tag['attribs']['']['type'], 'image') !== false) {
                             $img = isset($tag['attribs']['']['url']) ? $tag['attribs']['']['url'] : null;
                             break;
                         }
                     }
                 }
                 if (empty($img)) {
                     $enclosure = $item->get_enclosure();
                     if ($enclosure) {
                         $img = $enclosure->get_thumbnail();
                         if (empty($img)) {
                             $img = $enclosure->get_link();
                         }
                     }
                 }
             }
             $items[] = array('Permalink' => $item->get_permalink(), 'Title' => $item->get_title(), 'Description' => $item->get_description(), 'PublishDate' => $itemDate, 'Image' => $img);
             $i++;
         }
     } catch (FeedParserException $fpe) {
         $this->Logger->debug($fpe->getMessage());
     }
     return $items;
 }
 public function preDeploy()
 {
     $siteArray = $this->site;
     if (empty($siteArray)) {
         throw new Exception('Site array could not be loaded');
     }
     $site = URLUtils::resolveSiteFromArray($siteArray, !empty($siteArray['matched_alias']) ? $siteArray['matched_alias'] : false);
     //
     //        $site = new Site();
     //        $site->Slug = $siteArray['slug'];
     //        $site->Name = isset($siteArray['name'])?$siteArray['name']:$site->Slug;
     //        $site->Description = isset($siteArray['description'])?$siteArray['description']:'';
     //
     //        if(isset($siteArray['domain']))
     //            $site->Domain = $siteArray['domain'];
     //        if(isset($siteArray['domain_base_uri']))
     //            $site->DomainBaseURI = $siteArray['domain_base_uri'];
     //        if(isset($siteArray['domain_aliases']))
     //            $site->DomainAliases = $siteArray['domain_aliases'];
     //        if(isset($siteArray['domain_redirects']))
     //            $site->DomainRedirects = $siteArray['domain_redirects'];
     //
     //        $site->BaseURL = 'http'.($site->isSSL()?'s':'').'://'.rtrim($domain.$site->DomainBaseURI,'/');
     $this->RequestContext->setSite($site);
     //        if(isset($siteArray['storagefacilities']))
     //        {
     //
     //            $sfs = $siteArray['storagefacilities'];
     //            foreach($sfs as $key => $sfArray)
     //            {
     //
     //                if(empty($sfArray['for']))
     //                    throw new Exception('storage_facility property "for" is missing');
     //
     //                if(empty($sfArray['ref']))
     //                    throw new Exception('storage_facility property "ref" is missing');
     //
     //                $info = new StorageFacilityInfo();
     //                $info->For = $sfArray['for'];
     //                $info->GenerateRewriteRules = isset($sfArray['generate_rewrite_rules'])?StringUtils::strToBool($sfArray['generate_rewrite_rules']):false;
     //                $info->ObjectRef = $sfArray['ref'];
     //
     //                $params = new StorageFacilityParams();
     //                $params->BaseURI = $sfArray['base_uri'];
     //                $params->BaseStoragePath = $sfArray['base_storage_path'];
     //                $params->Domain = $sfArray['domain'];
     //
     //                $info->StorageFacilityParams = $params;
     //
     //                $this->RequestContext->setStorageFacilityInfo($info->For, $info);
     //            }
     //        }
     foreach ($site->getStorageFacilityInfo() as $slug => $sf) {
         $this->RequestContext->setStorageFacilityInfo($slug, $sf);
     }
 }
Esempio n. 4
0
 public static function queryStringToMap($queryString)
 {
     $result = array();
     if ($queryString != null && strlen($queryString) > 0) {
         $pairs = explode(self::PARAM_SEPARATOR, $queryString);
         foreach ($pairs as $pair) {
             $keyVal = explode(self::PAIR_SEPARATOR, $pair);
             $key = URLUtils::formURLDecode($keyVal[0]);
             $value = count($keyVal) > 1 ? URLUtils::formURLDecode($keyVal[1]) : self::EMPTY_STRING;
             $result[$key] = $value;
         }
     }
     return $result;
 }
 /**
  * Loads a presenter, calls its method and sets the resulting string into
  * the PRESENTER_RESULT template variable.
  *
  * @return array
  * @throws \Exception
  */
 protected function render()
 {
     $presenter = $this->createPresenter($this->getRequiredTemplateVariable('Presenter'));
     try {
         $arguments = $this->getArguments($presenter);
         $result = call_user_func_array($presenter, $arguments);
     } catch (\Exception $e) {
         if ($this->throwRenderExceptions) {
             throw $e;
         }
         $this->Logger->error($e->getMessage() . "\n\nURL: " . \URLUtils::fullUrl() . "\n\nTemplate Vars:\n" . print_r($this->templateVars, true) . (isset($arguments) ? "\n\n{$presenter} args:\n" . print_r($arguments, true) : ''));
         $result = '';
     }
     $this->setTemplateVariable('PRESENTER_RESULT', $result);
     // just return something so the template engine thinks
     // something happened.
     return array(array());
 }
Esempio n. 6
0
 public function getFullURL()
 {
     return URLUtils::fullUrl();
 }
 protected function _sendErrorNotification($prefix, $message, $subject = null, $customMessage = false, $extraRecipients = null)
 {
     $c = '';
     if ($customMessage) {
         $c .= $customMessage . "\n\n";
     }
     if ($message instanceof Exception) {
         $c .= get_class($message) . ": " . $message->getMessage() . "\n";
         if ($message instanceof SQLException) {
             $c .= "SQL: " . $message->getSQL() . "\n";
         }
         $c .= "Code: " . $message->getCode() . "\n";
         $c .= "File: " . $message->getFile() . "\n";
         $c .= "Line: " . $message->getLine() . "\n";
         $c .= "Stack Trace: " . $message->getTraceAsString() . "\n\n";
     } else {
         $c .= str_replace("\t", "  ", $message) . "\n\n";
     }
     $c .= "\nURL: " . URLUtils::fullUrl() . "\n\n";
     if ($this->verbose) {
         $debugServerVars = array_intersect_key($_SERVER, array_flip(array('SCRIPT_URL', 'SCRIPT_URI', 'ENVIRONMENT', 'PATH', 'SERVER_SIGNATURE', 'SERVER_SOFTWARE', 'SERVER_NAME', 'SERVER_ADDR', 'SERVER_PORT', 'REMOTE_ADDR', 'DOCUMENT_ROOT', 'SERVER_ADMIN', 'SCRIPT_FILENAME', 'REMOTE_PORT', 'GATEWAY_INTERFACE', 'SERVER_PROTOCOL', 'REQUEST_METHOD', 'QUERY_STRING', 'REQUEST_URI', 'SCRIPT_NAME', 'PHP_SELF', 'REQUEST_TIME', 'DEVICE_VIEW', 'DESIGN', 'DOMAIN', 'CONTEXT', 'ROUTER_BASE', 'MATCHED_ALIAS', 'REWRITE_BASE', 'DEPLOYMENT_BASE_PATH', 'SITE', 'SYSTEM_VERSION')));
         $c .= "SERVER: " . print_r($this->Security->filterLoggedParameters($debugServerVars), true) . "\n\n";
         $headers = array();
         foreach ($_SERVER as $name => $value) {
             if (strpos($name, 'HTTP_') === 0) {
                 $headers[$name] = $value;
             }
         }
         if (!empty($headers)) {
             $c .= "HEADERS: " . print_r($this->Security->filterLoggedParameters($headers), true) . "\n\n";
         }
         if (isset($_FILES)) {
             $c .= "FILES: " . print_r($_FILES, true) . "\n\n";
         }
         if (isset($_POST)) {
             $c .= "POST: " . print_r($this->Security->filterLoggedParameters($_POST), true) . "\n\n";
         }
         if (isset($_GET)) {
             $c .= "GET: " . print_r($this->Security->filterLoggedParameters($_GET), true) . "\n\n";
         }
         if (isset($_SESSION)) {
             $c .= "SESSION: " . print_r($this->Security->filterLoggedParameters($_SESSION), true) . "\n\n";
         }
     }
     if ($message instanceof Exception) {
         if (!$subject) {
             $subject = '%k: %.100m';
         }
         $subject = preg_replace_callback('/%(\\.(\\d+))?([kmcfl%])/', function ($match) use($message) {
             switch ($match[3]) {
                 case 'k':
                     $out = get_class($message);
                     break;
                 case 'm':
                     $out = $message->getMessage();
                     break;
                 case 'c':
                     $out = $message->getCode();
                     break;
                 case 'f':
                     $out = $message->getFile();
                     break;
                 case 'l':
                     $out = $message->getLine();
                     break;
                 default:
                     $out = $match[3];
             }
             if (!empty($match[2])) {
                 $out = substr($out, 0, $match[2]);
             }
             return $out;
         }, $subject);
     } else {
         if (!$subject) {
             $subject = substr($message, 0, 100);
         }
     }
     // don't send email about post max or missing boundary errors
     // there's nothing we can do code wise to fix those anyways
     $isPostContentLengthError = false;
     if (false !== strpos($c, 'POST Content-Length of') || false !== strpos($c, 'Missing boundary in multipart/form-data')) {
         $isPostContentLengthError = true;
         $prefix = 'WARN';
     }
     $context = isset($_SERVER['CONTEXT']) ? $_SERVER['CONTEXT'] : 'none';
     if (array_key_exists('SITE', $_SERVER)) {
         $appName = (string) $_SERVER['SITE']['slug'];
         if ($appName === $context) {
             $appName = $this->SiteService->getAnchoredSite()->Slug;
         }
     } else {
         $appName = $_SERVER['SERVER_NAME'];
     }
     $deviceView = isset($_SERVER['DEVICE_VIEW']) ? $_SERVER['DEVICE_VIEW'] : '';
     $design = isset($_SERVER['DESIGN']) ? $_SERVER['DESIGN'] : '';
     if (!empty($deviceView) && !empty($design)) {
         $errorPrefix = "[{$this->environment}][{$appName}][{$context}][{$deviceView}:{$design}][{$prefix}]";
     } else {
         $errorPrefix = "[{$this->environment}][{$appName}][{$context}][{$prefix}]";
     }
     $subject = "{$errorPrefix} {$subject}";
     if (!$this->multiline) {
         $c = str_replace("\n", "<br/>", $c);
     }
     // Do standard PHP error logging
     error_log("{$errorPrefix} {$c}");
     // Bail out if we shouldn't be sending emails.
     if (!$this->sendEmails || empty($this->systemEmailAddress) || empty($this->Email) || $isPostContentLengthError) {
         return;
     }
     $recipients = array($this->systemEmailAddress);
     if (!empty($extraRecipients)) {
         if (!is_array($extraRecipients)) {
             $recipients[] = $extraRecipients;
         } else {
             $recipients = array_merge($recipients, $extraRecipients);
         }
     }
     // emails always need line breaks replaced
     if ($this->multiline) {
         $c = str_replace("\n", "<br/>", $c);
     }
     $body = '<p><font face="&#39;courier new&#39;, monospace">' . $c . '</font></p>';
     $this->Email->clear();
     $this->Email->from($this->sendEmailsFrom);
     foreach ($recipients as $recipient) {
         $this->Email->to($recipient);
     }
     $this->Email->subject($subject);
     $this->Email->body($body);
     $this->Email->altMessage($c);
     if (is_a($this->Email, 'EmailTagInterface')) {
         $this->Email->tag('error');
     }
     $this->Email->send();
 }
Esempio n. 8
0
 public function testFetch()
 {
     $page = URLUtils::get('http://www.google.com');
     $this->assertContains('google', $page);
 }
 /**
  * Calls an rss feed and returns up to $count rows from that feed.
  * Feeds are stored in cache but passing a different count will not store
  * a new cache entry, it will simply return that number of items from the
  * cached feed.
  *
  * Count is not guaranteed to be returned if the feed doesn't supply that
  * many items.
  *
  * Returns a simple array of the feed and its items
  *
  * <code>
  * array(
  *      'status' => 200,
  *      'permalink' => '',
  *      'title' => '',
  *      'description' => '',
  *      'timestamp' => '',
  *      'item_count' => '',
  *      'items' => array(
  *          'permalink' => ''
  *          'title' => ''
  *          'description' => ''
  *          'image' => ''
  *      )
  * );
  * </code>
  *
  * @param string $feedURL   the full url to an rss feed.
  * @param int $count        number of items to return from the feed
  * @param bool $nativeOrder sets the order the feed items are returned in @see SimplePie
  * @param int $itemLimit    total number of items from the feed to store
  *
  * @return array
  *
  * @throws \InvalidArgumentException
  */
 public function getFeed($feedURL, $count = 25, $nativeOrder = false, $itemLimit = 100)
 {
     if (!\URLUtils::isUrl($feedURL)) {
         return array('status' => 404, 'item_count' => 0, 'items' => array());
     }
     if ($count > $itemLimit) {
         throw new \InvalidArgumentException('Count cannot be greater than the item limit.');
     }
     $cacheKey = $this->cacheKey($feedURL . ($nativeOrder ? ':nativeorder' : '') . ':' . $itemLimit);
     $this->logger->info("Lookup for key [{$cacheKey}]");
     $feed = $this->cacheStore->get($cacheKey);
     if (is_array($feed)) {
         $this->logger->info("Found feed in cache for key [{$cacheKey}]");
         $feed['items'] = array_slice($feed['items'], 0, $count);
         return $feed;
     }
     try {
         $this->logger->info("Calling feed [{$feedURL}]");
         /* @var \SimplePie $rawFeed */
         $rawFeed = $this->feedParser->parseFeed($feedURL, $nativeOrder);
         if ($publishDate = $rawFeed->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'pubDate')) {
             $publishDate = $this->dateFactory->newStorageDate($publishDate[0]['data'])->toUnix();
         } else {
             $publishDate = null;
         }
         $feed = array('status' => 200, 'permalink' => $rawFeed->get_permalink(), 'title' => trim($rawFeed->get_title()), 'description' => trim($rawFeed->get_description()), 'timestamp' => $publishDate, 'item_count' => $rawFeed->get_item_quantity(), 'items' => array());
         $this->logger->debug($feed);
         $i = 0;
         /* @var \SimplePie_Item $item */
         foreach ($rawFeed->get_items() as $item) {
             if ($i >= $itemLimit) {
                 break;
             }
             if (trim($item->get_title()) == '') {
                 continue;
             }
             $itemDate = null;
             if ($item->get_date() != '') {
                 $itemDate = $this->dateFactory->newStorageDate($item->get_date())->toUnix();
             }
             $img = null;
             // first try to get it from the enclosure node itself
             $tags = $item->get_item_tags('', 'enclosure');
             if (is_array($tags)) {
                 foreach ($tags as $tag) {
                     if (!isset($tag['attribs']['']['type'])) {
                         continue;
                     }
                     if (strpos($tag['attribs']['']['type'], 'image') !== false) {
                         $img = isset($tag['attribs']['']['url']) ? $tag['attribs']['']['url'] : null;
                         break;
                     }
                 }
             }
             if (empty($img)) {
                 /* @var \SimplePie_Enclosure $enclosure */
                 $enclosure = $item->get_enclosure();
                 if ($enclosure) {
                     $img = $enclosure->get_thumbnail();
                     if (empty($img)) {
                         $img = $enclosure->get_link();
                     }
                 }
             }
             $feed['items'][] = array('permalink' => $item->get_permalink(), 'title' => $item->get_title(), 'description' => $item->get_description(), 'timestamp' => $itemDate, 'image' => $img);
             $i++;
         }
     } catch (\FeedParserException $fpe) {
         $this->logger->error($fpe->getMessage());
         $feed = array('status' => $fpe->getCode(), 'item_count' => 0, 'items' => array());
     } catch (\Exception $e) {
         $this->logger->error($e->getMessage());
         $feed = array('status' => $e->getCode(), 'item_count' => 0, 'items' => array());
     }
     $this->logger->info("Putting feed into cache with key [{$cacheKey}] and ttl of [{$this->cacheTtl}]");
     $this->cacheStore->put($cacheKey, $feed, $this->cacheTtl);
     $feed['items'] = array_slice($feed['items'], 0, $count);
     return $feed;
 }
Esempio n. 10
0
 /**
  * Takes the content specified by parameter 'value' and converts all urls
  * contained within into links
  *
  * Expected Params:
  *  value string The content
  *
  * @return string the specified content with all urls contained within turned into links
  */
 public function autoLinkURLs()
 {
     return URLUtils::autoLinkUrls($this->getParameter('value'));
 }
 /**
  * Returns TRUE if the given value passes validation.
  *
  * @param string $value A value to test
  *
  * @return boolean
  */
 public function isValid($value)
 {
     if ($this->skipValidation) {
         return true;
     }
     $datatype = $this->validation['datatype'];
     //NULL check, empty strings are considered null
     if (in_array($datatype, array('string', 'url', 'email', 'slug', 'slugwithslash', 'html', 'binary', 'json')) && strlen(trim($value)) == 0) {
         $value = null;
     }
     if ($this->validation['nullable'] === false && $value === null && $datatype != 'boolean') {
         $this->failureCode = 'nullable';
         $this->failureMessage = 'cannot be empty';
         return false;
     }
     //Nothing more to validate if the value is null...
     if ($value === null) {
         return true;
     }
     //Check date makes sense
     if ($datatype === 'date') {
         //todo: not sure how to check validity of date... it's already a DateTime instance.
         if (false) {
             $this->failureCode = 'invalid';
             $this->failureMessage = 'is an invalid date';
             return false;
         }
     }
     //Validate MIN
     $min = $this->validation['min'];
     if ($min != null) {
         if ($datatype === 'float') {
             if ($value < floatval($min)) {
                 $this->failureCode = 'min';
                 $this->failureMessage = 'is less than the minimum value';
                 return false;
             }
         } else {
             if ($datatype === 'int') {
                 if ($value < intval($min)) {
                     $this->failureCode = 'min';
                     $this->failureMessage = 'is less than the minimum value';
                     return false;
                 }
             } else {
                 if (is_string($value) && strlen($value) < intval($min)) {
                     $this->failureCode = 'minlength';
                     $this->failureMessage = 'must be at least ' . $min . ' characters';
                     return false;
                 }
             }
         }
     }
     //Validate MAX
     $max = $this->validation['max'];
     if ($max != null) {
         if ($datatype === 'float') {
             if ($value > floatval($max)) {
                 $this->failureCode = 'max';
                 $this->failureMessage = 'is more than the maximum value';
                 return false;
             }
         } else {
             if ($datatype === 'int') {
                 if ($value > intval($max)) {
                     $this->failureCode = 'max';
                     $this->failureMessage = 'is more than the maximum value';
                     return false;
                 }
             } else {
                 $maxbytes = intval($max);
                 if (intval($max) < 255) {
                     // count characters
                     if (is_string($value) && StringUtils::charCount($value) > intval($max)) {
                         $this->failureCode = 'maxlength';
                         $this->failureMessage = 'must be a maximum of ' . $max . ' characters';
                         return false;
                     }
                     $maxbytes = 255;
                 }
                 // count bytes
                 if (is_string($value) && StringUtils::byteCount($value) > intval($maxbytes)) {
                     $this->failureCode = 'maxlength';
                     $this->failureMessage = 'must be a maximum of ' . $maxbytes . ' bytes';
                     return false;
                 }
             }
         }
     }
     if ($datatype === 'slug') {
         if (!SlugUtils::isSlug($value, false)) {
             $this->failureCode = 'invalid';
             $this->failureMessage = 'is not a valid slug, cannot contain slashes';
             return false;
         }
     }
     if ($datatype === 'slugwithslash') {
         if (!SlugUtils::isSlug($value, true)) {
             $this->failureCode = 'invalid';
             $this->failureMessage = 'is not a valid slug';
             return false;
         }
     }
     if ($datatype === 'url') {
         if (!URLUtils::isUrl($value)) {
             $this->failureCode = 'invalid';
             $this->failureMessage = 'is not a valid URL';
             return false;
         }
     }
     if ($datatype === 'email') {
         if (!EmailUtils::isEmailAddress($value)) {
             $this->failureCode = 'invalid';
             $this->failureMessage = 'is not a valid email address';
             return false;
         }
     }
     if ($datatype === 'json') {
         if (!JSONUtils::isValid($value)) {
             $this->failureCode = 'invalid';
             $this->failureMessage = 'is not a valid json string';
             return false;
         }
     }
     //Validate MATCH expression
     $match = $this->validation['match'];
     if ($match != null) {
         // Automatically escape unescaped slashes in the match before running it
         $match = preg_replace('/([^\\\\])\\//', '$1\\/', $match);
         if (preg_match('/' . $match . '/s', $value) === 0) {
             $this->failureCode = 'invalid';
             //$this->failureMessage = 'is invalid (' . substr($value, 0, 255) . ')';
             $this->failureMessage = 'is invalid';
             return false;
         }
     }
     // Validate all custom functions
     foreach ($this->validation['callback'] as $callback) {
         if (!empty($callback) && call_user_func($callback, $value) === false) {
             $this->failureCode = $callback;
             $this->failureMessage = 'is invalid';
             return false;
         }
     }
     return true;
 }
 protected function parse()
 {
     if ($this->changed) {
         return;
     }
     if ($this->parsed != true) {
         $this->cmsNavItems = array();
         $this->plugins = array();
         $this->aspects = array();
         $this->elements = array();
         $this->site = null;
         $xml = $this->SimpleXMLParser->parseXMLFile($this->environmentsXMLFile);
         foreach ($xml as $ename => $enode) {
             switch ((string) $ename) {
                 case 'environment':
                     foreach ($enode->attributes() as $name => $value) {
                         $environment[$name] = (string) $value;
                     }
                     if (!empty($environment['slug']) && strtolower($environment['slug']) != strtolower($_SERVER['ENVIRONMENT'])) {
                         continue;
                     }
                     $this->rewriteBase = strval($enode->rewrite_base);
                     $this->publicFilesBaseURI = strval($enode->public_files_base_uri);
                     foreach ($enode as $name => $node) {
                         switch ((string) $name) {
                             case 'context':
                                 $context = array('sites' => array());
                                 foreach ($node->attributes() as $name => $value) {
                                     $context[$name] = (string) $value;
                                 }
                                 foreach ($node as $childNode) {
                                     if ($childNode->getName() == 'sites') {
                                         foreach ($childNode as $siteNode) {
                                             $site = array();
                                             foreach ($siteNode->attributes() as $name => $value) {
                                                 $site[$name] = (string) $value;
                                             }
                                             // By default if a site is not specified as enabled, it is enabled.
                                             if (!array_key_exists('enabled', $site)) {
                                                 $site['enabled'] = true;
                                             }
                                             // If the context that contains the site is disabled
                                             // The site within it should always be disabled.
                                             if (!StringUtils::strToBool($context['enabled'])) {
                                                 $site['enabled'] = false;
                                             }
                                             foreach ($siteNode as $siteChildNode) {
                                                 if ((string) $siteChildNode->getName() == 'storage_facility') {
                                                     $sf = array();
                                                     foreach ($siteChildNode->attributes() as $name => $value) {
                                                         $sf[$name] = (string) $value;
                                                     }
                                                     foreach ($siteChildNode as $sfChildNode) {
                                                         $sf[(string) $sfChildNode->getName()] = (string) $sfChildNode;
                                                     }
                                                     if (isset($sf['for'])) {
                                                         $site['storagefacilities'][$sf['for']] = $sf;
                                                     }
                                                 } else {
                                                     $site[(string) $siteChildNode->getName()] = (string) $siteChildNode;
                                                 }
                                             }
                                             $this->siteContext = $context;
                                             $this->site = $site;
                                             break;
                                         }
                                     } else {
                                         if ($childNode->getName() == 'storage_facility') {
                                             $sf = array();
                                             foreach ($childNode->attributes() as $name => $value) {
                                                 $sf[$name] = (string) $value;
                                             }
                                             foreach ($childNode as $sfChildNode) {
                                                 $sf[(string) $sfChildNode->getName()] = (string) $sfChildNode;
                                             }
                                             if (isset($sf['for'])) {
                                                 $context['storagefacilities'][$sf['for']] = $sf;
                                             }
                                         } else {
                                             $context[(string) $childNode->getName()] = (string) $childNode;
                                         }
                                     }
                                 }
                                 if (empty($context['sites'])) {
                                     unset($context['sites']);
                                 }
                                 $contextObject = URLUtils::resolveContextFromArray($context, $this->isAliasDomain);
                                 $contextObject->ContextID = count($this->contexts) + 1;
                                 $this->contexts[] = $contextObject;
                                 break;
                         }
                     }
                     break;
             }
         }
         $xml = $this->SimpleXMLParser->parseXMLFile($this->systemXMLFile);
         foreach ($xml as $name => $node) {
             $array = array();
             $sort_array = array();
             $sort_array2 = array();
             switch ((string) $name) {
                 case 'plugins':
                     foreach ($node as $pluginNode) {
                         if ($pluginNode->getName() == 'plugin') {
                             $item = $this->SystemXMLConverter->xmlToPlugin(new Plugin(), $pluginNode);
                             $sort_array[] = $item->Slug;
                             $array[] = $item;
                         }
                     }
                     array_multisort($sort_array, SORT_ASC, $array);
                     $this->plugins = $array;
                     break;
                 case 'elements':
                     foreach ($node as $elementNode) {
                         if ($elementNode->getName() == 'element') {
                             $item = $this->SystemXMLConverter->xmlToElement(new Element(), $elementNode);
                             $sort_array[] = $item->Slug;
                             $array[] = $item;
                         }
                     }
                     array_multisort($sort_array, SORT_ASC, $array);
                     $this->elements = $array;
                     break;
                 case 'aspects':
                     foreach ($node as $aspectNode) {
                         if ($aspectNode->getName() == 'aspect') {
                             $item = $this->SystemXMLConverter->xmlToAspect(new Aspect(), $aspectNode);
                             $sort_array[] = $item->Slug;
                             $array[] = $item;
                         }
                     }
                     array_multisort($sort_array, SORT_ASC, $array);
                     $this->aspects = $array;
                     break;
                 case 'cmsnavitems':
                     foreach ($node as $cmsNavNode) {
                         if ($cmsNavNode->getName() == 'item') {
                             $item = $this->SystemXMLConverter->xmlToCMSNavItem(new CMSNavItem(), $cmsNavNode);
                             $sort_array[] = $item->SortOrder;
                             $sort_array2[] = $item->Slug;
                             $array[] = $item;
                         }
                     }
                     array_multisort($sort_array, SORT_ASC, $sort_array2, SORT_ASC, $array);
                     $this->cmsNavItems = $array;
                     break;
             }
         }
         $contextArray = $this->siteContext;
         $site2 = array_merge($contextArray, $this->site);
         if (isset($contextArray['storagefacilities'])) {
             foreach ($contextArray['storagefacilities'] as $key => $sf) {
                 $site2['storagefacilities'][$key] = $sf;
             }
         }
         if (isset($site['storagefacilities'])) {
             foreach ($site['storagefacilities'] as $key => $sf) {
                 $site2['storagefacilities'][$key] = $sf;
             }
         }
         $site2['context'] = $contextArray['slug'];
         unset($site2['sites']);
         $siteArray = $site2;
         $site = URLUtils::resolveSiteFromArray($siteArray, $this->isAliasDomain);
         $site->SiteID = 1;
         $this->sites[$site->Slug] = $site;
         $this->parsed = true;
     }
 }
Esempio n. 13
0
 public function processTemplate(Template $template, $contentType, &$globals, $isFinalPass = false, $isDependentPass = false)
 {
     if (!$isFinalPass && $template->isDeferred() || $isDependentPass && !$template->isDependent()) {
         $this->Logger->debug("Deferring template [{$template->getName()}]");
         // defer my execution
         return $template->getMatchString();
     }
     $this->Logger->debug("Processing template [{$template->getName()}]");
     if ($this->benchmarkRendering) {
         $this->Benchmark->start('process-template-' . $template->getName());
     }
     if ($this->noTemplatesCalled == true) {
         $this->topTemplate = $template;
         $this->noTemplatesCalled = false;
         $template->setTopTemplate(true);
     }
     $templateEngine = $this->getTemplateEngine($template->getName());
     try {
         $template = $templateEngine->loadTemplateExtended($template, $globals);
     } catch (Exception $e) {
         if ($this->throwRenderExceptions) {
             throw $e;
         } else {
             $this->Logger->error($e->getMessage() . "\nURL: " . URLUtils::fullUrl());
             return '';
         }
     }
     $cacheThisModule = false;
     $usedCache = false;
     if ($this->cacheEnabled && $template->isCacheable()) {
         $cacheThisModule = true;
     }
     if ($cacheThisModule) {
         $cacheKey = $this->TemplateCache->getTemplateCacheKey($template, $globals);
         if (!in_array($template->getName(), (array) $this->pushCache) && ($cachedTemplate = $this->TemplateCache->get($cacheKey))) {
             // check the timestamp
             //if ($cachedTemplate->getTimestamp() == $template->getTimestamp()) {
             $this->Logger->debug("Loaded from cache [" . $template->getName() . "]");
             $locals = $template->Locals;
             // load from cache
             $template = $templateEngine->loadFromCache($cachedTemplate);
             $template->Locals = $locals;
             $content = $template->getProcessedContent();
             $usedCache = true;
             //}
         }
     }
     if (!$usedCache) {
         $this->Logger->debug("Processing [{$template->getName()}]");
         // process the template and all dependent includes
         $content = $templateEngine->processTemplateContents($template, $globals, $this, $isFinalPass, $isDependentPass);
         $template->setProcessedContent($content);
         if ($cacheThisModule) {
             // snapshot of the cache contents at this moment
             $toBeCachedTemplate = clone $templateEngine->prepareForCache($template);
         }
     }
     // parse all independent includes, outside of caching (recurse!)
     $content = $templateEngine->parseTemplateIncludes($content, $contentType, $template, $globals, $this, $isFinalPass, false);
     if (!$usedCache) {
         $this->Logger->debug("Processing template set globals [{$template->getName()}]...");
         // parse template set globals
         $templateSetGlobals = $templateEngine->processTemplateSetGlobals($template, $globals, $isFinalPass);
     } else {
         $templateSetGlobals = $cachedTemplate->getTemplateSetGlobals();
     }
     $globals = array_merge($globals, $templateSetGlobals);
     // store in cache
     if (!$usedCache && $cacheThisModule) {
         $toBeCachedTemplate->setIndependentTemplates($template->isIndependentTemplates());
         $toBeCachedTemplate->setParsedIndependent(true);
         if ($template->isTopTemplate()) {
             $toBeCachedTemplate->setTemplateSetGlobals($globals);
         } else {
             $toBeCachedTemplate->setTemplateSetGlobals($templateSetGlobals);
         }
         $this->Logger->debug("Storing in cache [" . $toBeCachedTemplate->getName() . "]");
         unset($toBeCachedTemplate->Locals);
         unset($toBeCachedTemplate->Data);
         unset($toBeCachedTemplate->Contents);
         unset($toBeCachedTemplate->SetMatches);
         unset($toBeCachedTemplate->File);
         unset($toBeCachedTemplate->TemplateBlocks);
         $this->TemplateCache->putTemplate($cacheKey, $toBeCachedTemplate);
     }
     if ($this->benchmarkRendering) {
         $this->Benchmark->end('process-template-' . $template->getName());
     }
     return $content;
 }
Esempio n. 14
0
 public function convertFromString(ValidationExpression $validation, $value, $rawValue = null, $fromStorage = false)
 {
     if (is_null($rawValue)) {
         $rawValue = $value;
     }
     $vArray = $validation->getValidationArray();
     $datatype = $validation->getDatatype();
     switch ($datatype) {
         case 'flag':
             if ($value == false || strlen(trim($value)) == 0) {
                 $value = null;
             } else {
                 $value = 1;
             }
             break;
             //Clean HTML
         //Clean HTML
         case 'html':
             $value = $this->InputClean->clean($rawValue, array_key_exists('allowedtags', $vArray) ? $vArray['allowedtags'] : null);
             break;
             // Sanitize URL
         // Sanitize URL
         case 'url':
             $urlCleaned = URLUtils::safeURL($rawValue);
             if (!empty($urlCleaned)) {
                 $value = $urlCleaned;
             }
             break;
             //Convert INT
         //Convert INT
         case 'int':
             if (!empty($value) && is_numeric(str_replace(',', '', $value)) == FALSE) {
                 throw new TypeConversionException("Cannot convert string value [{$value}] to integer");
             } else {
                 if ($value === '') {
                     $value = null;
                 } else {
                     $value = intval(str_replace(',', '', $value));
                 }
             }
             break;
             //Convert FLOAT
         //Convert FLOAT
         case 'float':
             if (!empty($value) && is_numeric(str_replace(',', '', $value)) == FALSE) {
                 throw new TypeConversionException("Cannot convert string value [{$value}] to float");
             } else {
                 if ($value === '') {
                     $value = null;
                 } else {
                     $value = floatval(str_replace(',', '', $value));
                 }
             }
             break;
             //Convert BOOLEAN
         //Convert BOOLEAN
         case 'boolean':
             $value = StringUtils::strToBool($value);
             break;
             //Convert DATE
         //Convert DATE
         case 'date':
             if (!empty($value) && strlen(trim($value)) > 0) {
                 try {
                     if ($fromStorage) {
                         $value = $this->DateFactory->newStorageDate(trim($value));
                     } else {
                         $value = $this->DateFactory->newLocalDate(trim($value));
                     }
                 } catch (DateException $e) {
                     throw new TypeConversionException("Cannot convert string value [{$value}] to date");
                 }
             } else {
                 $value = null;
             }
             break;
     }
     unset($vArray);
     unset($datatype);
     unset($rawValue);
     unset($validation);
     return $value;
 }
Esempio n. 15
0
 /**
  * Arguably the most important function in all of CrowdFusion, this function kickstarts our
  * response to the incoming request.
  *
  * It first locates the proper route and initializes the request parameters from the route.
  * Next, all the interceptors are given a chance to run.
  *
  * Then the appropriate controller is called and allowed to run
  *
  * The output is constructed via redirect or renderer and then
  * the function ends by allowing all interceptors to run their postHandle method
  *
  * @return void
  */
 public function processRequest()
 {
     $returnContent = true;
     $this->Benchmark->end('boot');
     /*** START OUTPUT BUFFERING FOR RESPONSE ***/
     $this->Response->start();
     //        $this->Benchmark->start('route');
     /*** ROUTE THE REQUEST ***/
     $routeVariables = $this->Router->route();
     /*** ROUTE TO THE 404 ***/
     if (is_null($routeVariables)) {
         $routeVariables = array('view' => $this->view404);
     }
     //        $this->Benchmark->end('route');
     //        $this->Benchmark->start('input-clean');
     /*** INITIALIZE REQUEST PARAMETERS ***/
     $this->Request->addRouteParameters($routeVariables);
     $this->Request->addInputParameters(array_merge($_POST, $_GET));
     $this->Logger->debug($this->Security->filterLoggedParameters($this->Request->getParameters()));
     //        $this->Benchmark->end('input-clean');
     //        $this->Benchmark->start('controls');
     /*** INIT WEB CONTEXT & CONTROLS ***/
     $this->RequestContext->setControls(new Controls($this->Request->getRouteParameters(), $this->Security->filterInputControlParameters($this->Request->getInputParameters())));
     $this->Events->trigger('Dispatcher.preDeploy');
     //        $this->Benchmark->end('controls');
     $this->Benchmark->start('deployment');
     // DEPLOY ASSETS
     $this->AssetService->deploy();
     //DEPLOY TEMPLATES
     $this->TemplateService->deploy();
     //DEPLOY MESSAGES
     $this->MessageService->deploy();
     $this->Benchmark->end('deployment');
     /*** PRE-INTERCEPTORS ***/
     $transport = new Transport();
     $transport->RouteVariables = $routeVariables;
     $this->Events->trigger('Dispatcher.preHandle', $transport);
     $routeVariables = $transport->RouteVariables;
     /*** INIT VIEW ***/
     $view = new View($this->RequestContext->getControls()->getControl('view'));
     $this->Logger->debug('---');
     $handler = $this->RequestContext->getControls()->getControl('view_handler');
     try {
         /*** CONTROLLER ACTION ***/
         if (($action = $this->RequestContext->getControls()->getControl('action')) != null) {
             $actionBuffer = $this->RequestContext->getControls()->getControl('action_buffer');
             if ($actionBuffer == true) {
                 $this->Response->prepare();
             }
             $this->Events->trigger('Dispatcher.preAction');
             $this->Logger->debug('Executing action [' . $action . ']');
             $view = $this->ControllerManager->invokeAction($action);
             $this->Events->trigger('Dispatcher.postAction', $view);
             if ($actionBuffer == true) {
                 $this->Response->flush();
             }
         }
         /*** NO VIEW? BLANK PAGE ***/
         if ($view == null || $view->getName() == null || $view->getName() == 'null') {
             $this->Logger->debug('No view.');
             $this->Response->prepare()->flush();
             $this->Events->trigger('Dispatcher.terminate', new Transport());
             return;
         }
         /*** PROCESS REDIRECTS ***/
         if ($view->isRedirect()) {
             $this->Session->setFlashAttribute('original_referer', $this->Request->getFullURL());
             if ($view->isPermanentRedirect()) {
                 $this->Response->sendStatus(Response::SC_MOVED_PERMANENTLY);
             }
             $this->Response->sendRedirect(URLUtils::resolveUrl($view->getRedirect(), $view->getData()));
             //END OF FLOW
         } else {
             if ($view->getName() == 'original_referer') {
                 $url = $this->Session->getFlashAttribute('original_referer');
                 if (empty($url)) {
                     $url = $this->Request->getReferrer();
                 }
                 if ($url == $this->Request->getFullURL()) {
                     $this->Response->sendRedirect('/');
                 }
                 $this->Response->sendRedirect($url);
                 //END OF FLOW
             }
         }
         $this->Session->keepFlashAttribute('original_referer');
         $this->Logger->debug('---');
         $this->Benchmark->start('render');
         /*** RENDER VIEW ***/
         $globals = array();
         list($content, $globals) = $this->Renderer->renderView($view, $handler, StringUtils::strToBool($this->RequestContext->getControls()->getControl('view_nocache')) == false && $this->RequestContext->getControls()->getControl('action_executing') == null, $this->Request->getUserAgent() == 'crowdfusion-cli' ? $this->RequestContext->getControls()->getControl('view_pushcache') : false);
         if ($view->getName() === $this->view404) {
             $this->Response->sendStatus(Response::SC_NOT_FOUND);
         }
     } catch (NotFoundException $nfe) {
         $this->Router->checkRedirects();
         $this->Response->sendStatus(Response::SC_NOT_FOUND);
         if (!empty($this->view404)) {
             try {
                 // 404 view is responsible for loading 404 page template, if desired
                 list($content, $globals) = $this->Renderer->renderView(new View($this->view404, array_merge($view->getData(), array('NotFoundException' => $nfe->getMessage()))), $handler);
             } catch (NotFoundException $nfe) {
             }
         }
         if (empty($content)) {
             $content = "404 Not Found";
         }
     }
     if (empty($globals['Content-Type'])) {
         switch ($handler) {
             case 'html':
             default:
                 $globals['Content-Type'] = 'text/html; charset="' . $this->charset . '"';
                 break;
             case 'txt':
                 $globals['Content-Type'] = 'text/plain; charset="' . $this->charset . '"';
                 break;
             case 'rss':
             case 'xml':
                 $globals['Content-Type'] = 'application/xml; charset="' . $this->charset . '"';
                 break;
             case 'json':
                 $globals['Content-Type'] = 'application/json; charset="' . $this->charset . '"';
                 break;
         }
     }
     $this->Response->addHeader('Content-Type', $globals['Content-Type']);
     if (empty($globals['BrowserCacheTime'])) {
         $this->Response->addHeader('Cache-Control', 'no-cache, must-revalidate, post-check=0, pre-check=0');
         $this->Response->addHeader('Expires', $this->DateFactory->newLocalDate()->toRFCDate());
     } else {
         $this->Response->addHeader('Cache-Control', 'max-age=' . $globals['BrowserCacheTime']);
         $this->Response->addHeader('Expires', $this->DateFactory->newLocalDate('+' . $globals['BrowserCacheTime'] . ' seconds')->toRFCDate());
     }
     $this->Logger->debug('---');
     /* Process ETags */
     if (isset($globals['ETag']) && $this->Response->getStatus() === Response::SC_OK && !$this->Response->containsHeader('ETag')) {
         $etag = $this->ApplicationContext->getSystemVersionTimestamp() . "-{$this->deviceView}-{$this->design}-" . $globals['ETag'] . ($this->Request->acceptsGzip() ? '-gzip' : '');
         $globals['ETag'] = md5($etag);
         $this->Logger->info('Raw ETag=' . $etag . ', md5=' . $globals['ETag']);
         $this->Response->addHeader('ETag', '"' . $globals['ETag'] . '"');
         $ifNoneMatch = trim($this->Request->getHeader('If-None-Match'), '"');
         $this->Logger->info('If-None-Match request header: ' . $ifNoneMatch);
         if (strcmp($ifNoneMatch, $globals['ETag']) === 0) {
             $this->Logger->info('ETag match: ' . $ifNoneMatch);
             // remove headers that MUST NOT be included with 304 Not Modified responses
             foreach (array('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified') as $header) {
                 $this->Response->removeHeader($header);
             }
             $this->Response->sendStatus(Response::SC_NOT_MODIFIED);
             $returnContent = false;
         }
     }
     /*** POST-INTERCEPTORS ***/
     $transport = new Transport();
     $transport->Content = $content;
     $transport->Globals = $globals;
     $this->Events->trigger('Dispatcher.postHandle', $transport);
     $this->Benchmark->end('render');
     $this->Response->prepare();
     if ($returnContent) {
         echo $transport->Content;
     }
     $this->Response->flush();
     $this->Events->trigger('Dispatcher.terminate', $transport);
     $this->Benchmark->end('all');
 }
 /**
  * Loads a presenter, calls its method and returns the result.
  *
  * @param Template $template
  * @return string
  * @throws Exception
  */
 protected function render(Template $template)
 {
     $presenter = $this->createPresenter($template->getPresenter());
     try {
         $arguments = $this->getArguments($presenter, $template);
         $this->logger->debug($arguments);
         $result = call_user_func_array($presenter, $arguments);
     } catch (Exception $e) {
         if ($this->throwRenderExceptions) {
             throw $e;
         }
         $this->logger->error($e->getMessage() . "\n\nURL: " . URLUtils::fullUrl() . "\n\nTemplate:\n" . print_r($template, true) . (isset($arguments) ? "\n\n{$presenter} args:\n" . print_r($arguments, true) : ''));
         $result = '';
     }
     return $result;
 }
 /**
  * Private internal function. Returns a URL that will link to the page specified in {@link $value}
  *
  * @param string $value        The page number
  * @param string $pagingString The string for paging
  *
  * @return string URL
  */
 protected function _createLink($value, $pagingString = null)
 {
     if ($pagingString != null) {
         $link = $this->RequestContext->getSite()->getBaseURL() . preg_replace("/\\/[\\/]+/", "/", ltrim($pagingString . '/' . $value . '/'));
         if ($this->getLocal('UseQueryStringInCacheKey') != null) {
             $link .= $this->Request->getQueryString() != "" ? "?" . $this->Request->getQueryString() : "";
         }
         return $link;
     } else {
         return URLUtils::appendQueryString($this->Request->getFullURL(), array('view_page' => $value));
     }
 }
 protected function callbackAssets($match)
 {
     $assetBlock = $match[0];
     $assetType = $match[1];
     $assetParams = $match[3];
     try {
         if ($assetType == "version") {
             $fname = $this->parseParameterValue(substr($assetParams, 4), $this->tempAssetsFV, $this->tempAssetsFinalParse);
             //removes 'src=/'
             return $this->AssetAggregator->renderVersionedFile($fname);
         } elseif ($assetType == "resolve") {
             $fname = $this->parseParameterValue(substr($assetParams, 4), $this->tempAssetsFV, $this->tempAssetsFinalParse);
             //removes 'src=/'
             return $this->AssetAggregator->renderResolvedFile($fname);
         } elseif ($assetType == "relative") {
             $fname = $this->parseParameterValue(substr($assetParams, 4), $this->tempAssetsFV, $this->tempAssetsFinalParse);
             //removes 'src=/'
             $url = $this->AssetAggregator->renderResolvedFile($fname);
             $pos = strpos($url, '/', 8);
             return substr($url, $pos);
         }
     } catch (Exception $e) {
         if ($this->throwRenderExceptions) {
             throw $e;
         } else {
             $this->Logger->error($e->getMessage() . "\nURL: " . URLUtils::fullUrl());
         }
     }
     return $assetBlock;
     //throw new Exception("ERROR PARSING ASSETS: unrecognized type, allowed types = [css,js,version]");
 }