/**
  * Can we add this object to a shopping feed?
  * 
  * @return boolean
  */
 public function canIncludeInGoogleShoppingFeed()
 {
     $can = true;
     // If object does not link to the current website or absolute
     // link not set.
     if ($this->owner->hasMethod('AbsoluteLink')) {
         $hostHttp = parse_url(Director::protocolAndHost(), PHP_URL_HOST);
         $objHttp = parse_url($this->owner->AbsoluteLink(), PHP_URL_HOST);
         if ($objHttp != $hostHttp) {
             $can = false;
         }
     } else {
         $can = false;
     }
     // If no price or title.
     if (!$this->owner->Title || !$this->owner->Price || !$this->owner->Condition || !$this->owner->Availability || !$this->owner->Brand || !$this->owner->MPN) {
         $can = false;
     }
     // Can any user view this item
     if ($can) {
         $can = $this->owner->canView();
     }
     if ($can && $this->owner->RemoveFromShoppingFeed) {
         $can = false;
     }
     $this->owner->invokeWithExtensions('alterCanIncludeInGoogleShoppingFeed', $can);
     return $can;
 }
 public function onBeforeInit()
 {
     $host = GlobalNavSiteTreeExtension::get_toolbar_hostname();
     if ((isset($_REQUEST['regenerate_nav']) || isset($_REQUEST['flush'])) && $host == Director::protocolAndHost() && (Permission::check('ADMIN') || Director::isDev())) {
         GlobalNavSiteTreeExtension::create_static_navs();
     }
 }
コード例 #3
0
 /**
  * If emailLogFileTo and logFilePathName is set then email the logFilePathName content if not empty
  */
 public function __destruct()
 {
     if ($this->emailLogFileTo && $this->logFilePathName) {
         if ($body = file_get_contents($this->logFilePathName)) {
             $email = new \Email($this->config()->get('send_emails_from'), $this->emailLogFileTo, 'Debug log from: ' . \Director::protocolAndHost(), $body);
             $email->sendPlain();
         }
     }
 }
 public static function CanTrackEvents(Controller $controller)
 {
     $bIsContentController = is_a($controller, 'ContentController');
     if ($bIsContentController && SiteConfig::current_site_config()->GoogleAnalyticsTrackingID) {
         $strCurrentDomain = str_replace(Director::protocol(), '', Director::protocolAndHost());
         $arrDomains = explode(',', SiteConfig::current_site_config()->GoogleAnalyticsTrackDomain);
         return in_array($strCurrentDomain, $arrDomains);
     }
 }
コード例 #5
0
 public function close()
 {
     $id = $this->getVar($this->attributes['name'] . 'ID');
     if (!$id) {
         return;
     }
     $image = DataObject::get_by_id('Image', $id);
     if ($image) {
         /* image specific attribute handling */
         if (!empty($this->attributes['width'])) {
             $newimage = $image->setWidth($this->attributes['width']);
             if ($newimage) {
                 $image = $newimage;
             }
         }
         if (!empty($this->attributes['height'])) {
             $newimage = $image->setHeight($this->attributes['height']);
             if ($newimage) {
                 $image = $newimage;
             }
         }
         $path = $image->Filename;
         $url = $image->getURL();
         if (strpos($url, 'http://') !== 0) {
             $url = '/' . ltrim($url, '/');
         }
         /*				if(substr($path,0,1) !== '/') 
         					$path = HOME_PATH . '/../userhomes/' . NSite::current_site()->PathName . '/' . $path;
         
         				$url = '/' . ltrim(Director::makeRelative(realpath($path)), '/');
         			}
         */
         if (file_exists($path)) {
             if (parse_url($url, PHP_URL_HOST) == '') {
                 // Convert relative url to absolute
                 $url = Director::protocolAndHost() . '/' . $url;
             }
             $title = $image->Title ? $image->Title : $image->Filename;
             if ($title) {
                 $title = Convert::raw2att($title);
             } else {
                 if (preg_match("/([^\\/]*)\\.[a-zA-Z0-9]{1,6}\$/", $title, $matches)) {
                     $title = Convert::raw2att($matches[1]);
                 }
             }
             echo "<img src=\"{$url}\" alt=\"{$title}\"";
             $copy_attributes = array('style', 'align');
             foreach ($copy_attributes as $name) {
                 if (isset($this->attributes[$name])) {
                     echo ' ' . $name . '="' . Convert::raw2att($this->attributes[$name]) . '"';
                 }
             }
             echo " />";
         }
     }
 }
コード例 #6
0
 /**
  * @param IFoundationMember                                 $foundation_member
  * @param IFoundationMemberRevocationNotification           $notification
  * @param IFoundationMemberRevocationNotificationRepository $notification_repository
  */
 public function send(IFoundationMember $foundation_member, IFoundationMemberRevocationNotification $notification, IFoundationMemberRevocationNotificationRepository $notification_repository)
 {
     $email = EmailFactory::getInstance()->buildEmail(REVOCATION_NOTIFICATION_EMAIL_FROM, $foundation_member->Email, REVOCATION_NOTIFICATION_EMAIL_SUBJECT);
     $email->setTemplate('RevocationNotificationEmail');
     do {
         $hash = $notification->generateHash();
     } while ($notification_repository->existsHash($hash));
     $link = sprintf('%s/revocation-notifications/%s/action', Director::protocolAndHost(), $hash);
     $email->populateTemplate(array('TakeActionLink' => $link, 'EmailFrom' => REVOCATION_NOTIFICATION_EMAIL_FROM, 'ExpirationDate' => $notification->expirationDate()->format('F j')));
     $email->send();
 }
コード例 #7
0
 public function canIncludeInGoogleSiteMap()
 {
     $can = true;
     if ($this->owner->hasMethod('AbsoluteLink')) {
         $hostHttp = parse_url(Director::protocolAndHost(), PHP_URL_HOST);
         $objHttp = parse_url($this->owner->AbsoluteLink(), PHP_URL_HOST);
         if ($objHttp != $hostHttp) {
             $can = false;
         }
     }
     return $can;
 }
 public function sendDeleteNotification(IDupeMemberDeleteRequest $request)
 {
     $dupe = $request->getDupeAccount();
     $email_to = $dupe->getEmail();
     $email = EmailFactory::getInstance()->buildEmail(DUPE_EMAIL_FROM, $email_to, "You Have Requested to Delete Openstack Duplicated Account");
     $template_data = array('FirstName' => $dupe->getFirstName(), 'LastName' => $dupe->getLastName(), 'DupeAccount' => $email_to);
     $email->setTemplate('DupeMembers_DeleteAccountEmail');
     do {
         $token = $request->generateConfirmationHash();
     } while ($this->delete_request_repository->existsConfirmationToken($token));
     $template_data['ConfirmationLink'] = sprintf('%s/dupes-members/%s/delete', Director::protocolAndHost(), $token);
     $email->populateTemplate($template_data);
     $email->send();
 }
コード例 #9
0
	/**
	 * Generate breadcrumb links to the URL path being displayed
	 *
	 * @return string
	 */
	public function Breadcrumbs() {
		$basePath = str_replace(Director::protocolAndHost(), '', Director::absoluteBaseURL());
		$relPath = parse_url(substr($_SERVER['REQUEST_URI'], strlen($basePath), strlen($_SERVER['REQUEST_URI'])), PHP_URL_PATH);
		$parts = explode('/', $relPath);
		$base = Director::absoluteBaseURL();
		$pathPart = "";
		$pathLinks = array();
		foreach($parts as $part) {
			if ($part != '') {
				$pathPart .= "$part/";
				$pathLinks[] = "<a href=\"$base$pathPart\">$part</a>";
			}
		}
		return implode('&rarr;&nbsp;', $pathLinks);
	}	
コード例 #10
0
 private function _getTablePages()
 {
     $tablePages = '<table class="widgetify-related">';
     $tablePages .= '<tr class="table-header"><td>Page Title</td><td>Page Link</td><td>CMS Link</td></tr>';
     $pages = $this->WidgetifyPages();
     if ($pages && $pages->count()) {
         foreach ($pages as $page) {
             $absLink = Controller::join_links(Director::protocolAndHost(), $page->Link());
             $absCMSLink = Controller::join_links(Director::protocolAndHost(), '/admin/pages/edit/show/', $page->ID);
             $tablePages .= '<tr><td>' . $page->MenuTitle . '</td><td><a href="' . $absLink . '" target="_blank">' . $absLink . '</a></td><td><a href="' . $absCMSLink . '" target="_blank">' . $absCMSLink . '</a></td></tr>';
         }
     }
     $tablePages .= '</table>';
     return $tablePages;
 }
コード例 #11
0
 public function fifth()
 {
     $this->Title = 'The OpenStack Fifth Anniversary';
     $this->FBImage = 'http://www.openstack.org/themes/openstack/images/anniversary/5/img/bot-facebook.jpg';
     $this->FBImageW = '200';
     $this->FBImageH = '284';
     $this->FBDesc = 'Happy 5th OpenStack! Come celebrate at one of 40 global events.';
     $this->FBUrl = Director::protocolAndHost() . $this->Link('fifth');
     $this->CurrentDomain = Director::protocolAndHost();
     Requirements::set_write_js_to_body(false);
     Requirements::combine_files('5.css', array());
     Requirements::css($this->ThemeDir() . '/images/anniversary/5/css/bootstrap.css');
     Requirements::css($this->ThemeDir() . '/images/anniversary/5/css/styles.css');
     Requirements::combine_files('5.js', array($this->ThemeDir() . '/images/anniversary/5/js/jquery.js', $this->ThemeDir() . '/images/anniversary/5/js/scripts.js', $this->ThemeDir() . '/images/anniversary/5/js/jquery.easing.min.js'));
     return $this->getViewer('fifth')->process($this, array('ImgPath' => '/themes/openstack/images/anniversary/5/img', 'BadgeImgUrl' => 'http://841038e5aa7ad2e38487-650bfe6158d7143a3437ef4c83572bc4.r48.cf1.rackcdn.com/5/openstack-5th-anniversary.png', 'SlideDeckUrl' => '//www.dropbox.com/s/8bvbo2dzp9jd61o/OpenStack%205th%20Birthday%20slide%20deck.pptx?dl=0', 'LocalEventUrl' => '//www.openstack.org/blog/2015/06/openstack-turns-5-its-time-to-celebrate-the-community/', 'SummitUrl' => '//www.openstack.org/summit/tokyo-2015/', 'FBSharerUrl' => 'http://www.openstack.org/birthday/fifth', 'FBSharerImg' => 'http://www.openstack.org/themes/openstack/images/anniversary/5/img/bot-facebook.jpg'));
 }
 /**
  * Post a contact form
  *
  * @return Form
  */
 public function ContactForm()
 {
     $form = new ContactForm($this, 'ContactForm');
     // we do not want to read a new URL when the form has already been submitted
     // which in here, it hasn't been.
     $url = isset($_SERVER['REQUEST_URI']) ? Director::protocolAndHost() . '' . $_SERVER['REQUEST_URI'] : false;
     $form->loadDataFrom(array('ReturnURL' => $url));
     $member = Member::currentUser();
     if ($member) {
         $form->loadDataFrom($member);
     }
     if ($form->hasExtension('FormSpamProtectionExtension')) {
         $form->enableSpamProtection();
     }
     // hook to allow further extensions to alter the comments form
     //$this->extend('alterContactForm', $form);
     return $form;
 }
コード例 #13
0
ファイル: DirectorTest.php プロジェクト: normann/sapphire
 public function testAlternativeBaseURL()
 {
     // relative base URLs - you should end them in a /
     Director::setBaseURL('/relativebase/');
     $this->assertEquals('/relativebase/', Director::baseURL());
     $this->assertEquals(Director::protocolAndHost() . '/relativebase/', Director::absoluteBaseURL());
     $this->assertEquals(Director::protocolAndHost() . '/relativebase/subfolder/test', Director::absoluteURL('subfolder/test'));
     // absolute base URLs - you should end them in a /
     Director::setBaseURL('http://www.example.org/');
     $this->assertEquals('http://www.example.org/', Director::baseURL());
     $this->assertEquals('http://www.example.org/', Director::absoluteBaseURL());
     $this->assertEquals('http://www.example.org/subfolder/test', Director::absoluteURL('subfolder/test'));
     // Setting it to false restores functionality
     Director::setBaseURL(false);
     $this->assertEquals(BASE_URL . '/', Director::baseURL());
     $this->assertEquals(Director::protocolAndHost() . BASE_URL . '/', Director::absoluteBaseURL(BASE_URL));
     $this->assertEquals(Director::protocolAndHost() . BASE_URL . '/subfolder/test', Director::absoluteURL('subfolder/test'));
 }
 public function getConfig($page = null)
 {
     $themeDir = $this->owner->ThemeDir();
     $baseDir = Director::baseURL();
     $baseHref = Director::protocolAndHost() . $baseDir;
     $editHref = $page ? $baseHref . $page->CMSEditLink() : null;
     $pageHierarchy = array();
     //        if ($page) {
     //            $pageHierarchy = array($page->ID);
     //            $parent        = $page->Parent();
     //            while ($parent && $parent->exists()) {
     //                $pageHierarchy[] = $parent->ID;
     //                $parent          = $parent->Parent();
     //            }
     //        }
     $jsConfig = array('linkURL' => Controller::join_links(FrontEndEditorToolbar::create()->Link(), "LinkForm"), 'mediaURL' => Controller::join_links(FrontEndEditorToolbar::create()->Link(), "MediaForm"), 'themeDir' => $themeDir, 'baseDir' => $baseDir, 'baseHref' => $baseHref, 'editHref' => $editHref, 'pageHierarchy' => Convert::raw2json(array_reverse($pageHierarchy)));
     return $jsConfig;
 }
コード例 #15
0
 /**
  * @return boolean
  */
 public function canIncludeInGoogleSitemap()
 {
     $can = true;
     if ($this->owner->hasMethod('AbsoluteLink')) {
         $hostHttp = parse_url(Director::protocolAndHost(), PHP_URL_HOST);
         $objHttp = parse_url($this->owner->AbsoluteLink(), PHP_URL_HOST);
         if ($objHttp != $hostHttp) {
             $can = false;
         }
     }
     if ($can) {
         $can = $this->owner->canView();
     }
     if ($can) {
         $can = $this->owner->getGooglePriority();
     }
     $this->owner->invokeWithExtensions('alterCanIncludeInGoogleSitemap', $can);
     return $can;
 }
    function IncludeGATrackingCode()
    {
        $strCurrentDomain = str_replace(Director::protocol(), '', Director::protocolAndHost());
        $strID = SiteConfig::current_site_config()->GoogleAnalyticsTrackingID;
        $strCode = <<<JS
\tvar _gaq = _gaq || [];
    _gaq.push(['_setAccount', '{$strID}']);
    _gaq.push(['_setDomainName', '{$strCurrentDomain}']);
    _gaq.push(['_setAllowLinker', true]);
    _gaq.push(['_trackPageview']);
    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();

JS;
        if (SiteConfig::current_site_config()->GoogleAnalyticsPosition == 'Head') {
            Requirements::insertHeadTags('<script>' . $strCode . '</script>', 'GA_TRACKING_CODE');
        } else {
            Requirements::customScript($strCode, 'GA_TRACKING_CODE');
        }
    }
コード例 #17
0
 /**
  * @param ITeamInvitation $invitation
  * @return void
  */
 public function sendInvitation(ITeamInvitation $invitation)
 {
     $invite_dto = $invitation->getInviteInfo();
     $email_to = $invite_dto->getEmail();
     //to avoid accidentally send undesired emails....
     if (defined('CCLA_DEBUG_EMAIL')) {
         $email_to = CCLA_DEBUG_EMAIL;
     }
     $email = EmailFactory::getInstance()->buildEmail(CCLA_TEAM_INVITATION_EMAIL_FROM, $email_to, "You Have been Invited to Team " . $invitation->getTeam()->getName());
     $template_data = array('FirstName' => $invite_dto->getFirstName(), 'LastName' => $invite_dto->getLastName(), 'TeamName' => $invitation->getTeam()->getName(), 'CompanyName' => $invitation->getTeam()->getCompany()->Name);
     if ($invitation->isInviteRegisteredAsUser()) {
         $email->setTemplate('TeamInvitation_RegisteredUser');
         do {
             $token = $invitation->generateConfirmationToken();
         } while ($this->team_invitation_repository->existsConfirmationToken($token));
         $template_data['ConfirmationLink'] = sprintf('%s/team-invitations/%s/confirm', Director::protocolAndHost(), $token);
     } else {
         $email->setTemplate('TeamInvitation_UnRegisteredUser');
         $template_data['RegistrationLink'] = sprintf('%s/join/register', Director::protocolAndHost());
     }
     $email->populateTemplate($template_data);
     $email->send();
 }
コード例 #18
0
 public function setDomainByPageLocale($host)
 {
     if ($tld = self::getTLD($host)) {
         $currentLocale = Translatable::get_current_locale();
         $domain = Director::protocolAndHost();
         $domain = substr($domain, 0, strripos($domain, $tld));
         $ext = array_search($currentLocale, self::$domain_locale_map);
         return $domain . $ext;
     }
 }
コード例 #19
0
 /**
  * Send the email through mandrill
  * 
  * @param string|array $to
  * @param string $from
  * @param string $subject
  * @param string $plainContent
  * @param array $attachedFiles
  * @param array $customheaders
  * @param bool $inlineImages
  * @return array|bool
  */
 protected function send($to, $from, $subject, $htmlContent, $attachedFiles = false, $customheaders = false, $plainContent = false, $inlineImages = false)
 {
     $original_to = $to;
     // Process recipients
     $to_array = array();
     $to_array = $this->appendTo($to_array, $to, 'to');
     if (isset($customheaders['Cc'])) {
         $to_array = $this->appendTo($to_array, $customheaders['Cc'], 'cc');
         unset($customheaders['Cc']);
     }
     if (isset($customheaders['Bcc'])) {
         $to_array = $this->appendTo($to_array, $customheaders['Bcc'], 'bcc');
         unset($customheaders['Bcc']);
     }
     // Process sender
     $fromArray = $this->processRecipient($from);
     $fromEmail = $fromArray['email'];
     $fromName = $fromArray['name'];
     // Create params to send to mandrill message api
     $default_params = array();
     if (self::getDefaultParams()) {
         $default_params = self::getDefaultParams();
     }
     $params = array_merge($default_params, array("subject" => $subject, "from_email" => $fromEmail, "to" => $to_array));
     if ($fromName) {
         $params['from_name'] = $fromName;
     }
     // Inject additional params into message
     if (isset($customheaders['X-MandrillMailer'])) {
         $params = array_merge($params, $customheaders['X-MandrillMailer']);
         unset($customheaders['X-MandrillMailer']);
     }
     if ($plainContent) {
         $params['text'] = $plainContent;
     }
     if ($htmlContent) {
         $params['html'] = $htmlContent;
     }
     // Attach tags to params
     if (self::getGlobalTags()) {
         if (!isset($params['tags'])) {
             $params['tags'] = array();
         }
         $params['tags'] = array_merge($params['tags'], self::getGlobalTags());
     }
     // Attach subaccount to params
     if (self::getSubaccount()) {
         $params['subaccount'] = self::getSubaccount();
     }
     $bcc_email = Config::inst()->get('Email', 'bcc_all_emails_to');
     if ($bcc_email) {
         if (is_string($bcc_email)) {
             $params['bcc_address'] = $bcc_email;
         }
     }
     // Google analytics domains
     if (self::getUseGoogleAnalytics() && !Director::isDev()) {
         if (!isset($params['google_analytics_domains'])) {
             // Compute host
             $host = str_replace(Director::protocol(), '', Director::protocolAndHost());
             // Define in params
             $params['google_analytics_domains'] = array($host);
         }
     }
     // Handle files attachments
     if ($attachedFiles) {
         $attachments = array();
         // Include any specified attachments as additional parts
         foreach ($attachedFiles as $file) {
             if (isset($file['tmp_name']) && isset($file['name'])) {
                 $attachments[] = $this->encodeFileForEmail($file['tmp_name'], $file['name']);
             } else {
                 $attachments[] = $this->encodeFileForEmail($file);
             }
         }
         $params['attachments'] = $attachments;
     }
     if ($customheaders) {
         $params['headers'] = $customheaders;
     }
     if (self::getEnableLogging()) {
         // Append some extra information at the end
         $logContent = $htmlContent;
         $logContent .= '<pre>';
         $logContent .= 'To : ' . print_r($original_to, true) . "\n";
         $logContent .= 'Subject : ' . $subject . "\n";
         $logContent .= 'Headers : ' . print_r($customheaders, true) . "\n";
         if (!empty($params['from_email'])) {
             $logContent .= 'From email : ' . $params['from_email'] . "\n";
         }
         if (!empty($params['from_name'])) {
             $logContent .= 'From name : ' . $params['from_name'] . "\n";
         }
         if (!empty($params['to'])) {
             $logContent .= 'Recipients : ' . print_r($params['to'], true) . "\n";
         }
         $logContent .= '</pre>';
         // Store it
         $logFolder = BASE_PATH . '/' . self::getLogFolder();
         if (!is_dir($logFolder)) {
             mkdir($logFolder, 0777, true);
         }
         $filter = new FileNameFilter();
         $title = substr($filter->filter($subject), 0, 20);
         $r = file_put_contents($logFolder . '/' . time() . '-' . $title . '.html', $logContent);
         if (!$r) {
             throw new Exception('Failed to store email in ' . $logFolder);
         }
     }
     if (self::getSendingDisabled()) {
         $customheaders['X-SendingDisabled'] = true;
         return array($original_to, $subject, $htmlContent, $customheaders);
     }
     try {
         $ret = $this->getMandrill()->messages->send($params);
     } catch (Exception $ex) {
         $ret = array(array('status' => 'rejected', 'reject_reason' => $ex->getMessage()));
     }
     $this->last_result = $ret;
     $sent = 0;
     $failed = 0;
     $reasons = array();
     if ($ret) {
         foreach ($ret as $result) {
             if (in_array($result['status'], array('rejected', 'invalid'))) {
                 $failed++;
                 if (!empty($result['reject_reason'])) {
                     $reasons[] = $result['reject_reason'];
                 } else {
                     if ($result['status'] == 'invalid') {
                         $reasons[] = 'Email "' . $result['email'] . '" is invalid';
                     }
                 }
                 continue;
             }
             $sent++;
         }
     }
     if ($sent) {
         $this->last_is_error = false;
         return array($original_to, $subject, $htmlContent, $customheaders);
     } else {
         $this->last_is_error = true;
         $this->last_error = $ret;
         SS_Log::log("Failed to send {$failed} emails", SS_Log::DEBUG);
         foreach ($reasons as $reason) {
             SS_Log::log("Failed to send because: {$reason}", SS_Log::DEBUG);
         }
         return false;
     }
 }
コード例 #20
0
 /**
  * @return int
  */
 public function getCurrentSiteId()
 {
     // Re-parse the protocol and host to ensure it's in a consistent
     // format.
     $host = Director::protocolAndHost();
     $parts = parse_url($host);
     $host = "{$parts['scheme']}://{$parts['host']}";
     if ($this->map) {
         if (isset($this->map['hosts'][$host])) {
             return $this->map['hosts'][$host];
         } else {
             // see if we're using sub URLs
             $base = Director::baseURL();
             $host = rtrim($host . $base, '/');
             if (isset($this->map['hosts'][$host])) {
                 return $this->map['hosts'][$host];
             }
         }
     }
     return $this->getDefaultSiteId();
 }
コード例 #21
0
 /**
  * Get domain name from current host
  *
  * @return boolean|string
  */
 public function getDomainFromHost()
 {
     $host = parse_url(Director::protocolAndHost(), PHP_URL_HOST);
     $hostParts = explode('.', $host);
     $parts = count($hostParts);
     if ($parts < 2) {
         return false;
     }
     $domain = $hostParts[$parts - 2] . "." . $hostParts[$parts - 1];
     return $domain;
 }
コード例 #22
0
 public function pdf($request)
 {
     $file = FileUtils::convertToFileName($this->Title) . '.pdf';
     $html_inner = $this->customise(array('BASEURL' => Director::protocolAndHost()))->renderWith("UserStoryPDF");
     $base = Director::baseFolder();
     $css = $base . "/themes/openstack/css/main.pdf.css";
     $html_outer = sprintf("<html><head><style>%s</style></head><body><div class='container'>%s</div></body></html>", str_replace("@host", $base, @file_get_contents($css)), str_replace('"/assets/', '"' . Director::protocolAndHost() . '/assets/', $html_inner));
     //for debug purposes
     if (isset($_GET['view'])) {
         echo $html_outer;
         die;
     }
     try {
         $html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8', array(15, 5, 15, 5));
         $html2pdf->setTestIsImage(false);
         $html2pdf->WriteHTML($html_outer);
         //clean output buffer
         ob_end_clean();
         $html2pdf->Output($file, "D");
     } catch (HTML2PDF_exception $e) {
         $message = array('errno' => '', 'errstr' => $e->__toString(), 'errfile' => 'UserStory.php', 'errline' => '', 'errcontext' => '');
         SS_Log::log($message, SS_Log::ERR);
         $this->httpError(404, 'There was an error on PDF generation!');
     }
 }
コード例 #23
0
 public function pdf()
 {
     $html_inner = '';
     $marketplace_type = $this->request->param('MARKETPLACETYPE');
     $instance_id = intval($this->request->param('ID'));
     $base = Director::protocolAndHost();
     $query = new QueryObject();
     $query->addAndCondition(QueryCriteria::id('ID', $instance_id));
     switch (strtolower($marketplace_type)) {
         case 'distribution':
             $distribution = $this->distribution_repository->getBy($query);
             if (!$distribution) {
                 throw new NotFoundEntityException('', '');
             }
             $render = new DistributionSapphireRender($distribution);
             $distribution->IsPreview = true;
             $html_inner = $render->pdf();
             $css = @file_get_contents($base . "/marketplace/code/ui/admin/css/pdf.css");
             break;
         case 'appliance':
             $appliance = $this->appliance_repository->getBy($query);
             $appliance->IsPreview = true;
             $render = new ApplianceSapphireRender($appliance);
             $html_inner = $render->pdf();
             $css = @file_get_contents($base . "/marketplace/code/ui/admin/css/pdf.css");
             break;
         case 'public_cloud':
             $public_cloud = $this->public_clouds_repository->getBy($query);
             $public_cloud->IsPreview = true;
             if (!$public_cloud) {
                 throw new NotFoundEntityException('', '');
             }
             $render = new PublicCloudSapphireRender($public_cloud);
             $html_inner = $render->pdf();
             $css = @file_get_contents($base . "/marketplace/code/ui/admin/css/pdf.css");
             break;
         case 'private_cloud':
             $private_cloud = $this->private_clouds_repository->getBy($query);
             $private_cloud->IsPreview = true;
             $render = new PrivateCloudSapphireRender($private_cloud);
             $html_inner = $render->pdf();
             $css = @file_get_contents($base . "/marketplace/code/ui/admin/css/pdf.css");
             break;
         case 'consultant':
             $consultant = $this->consultant_repository->getBy($query);
             if (!$consultant) {
                 throw new NotFoundEntityException('', '');
             }
             $consultant->IsPreview = true;
             $render = new ConsultantSapphireRender($consultant);
             $html_inner = $render->pdf();
             $css = @file_get_contents($base . "/marketplace/code/ui/admin/css/pdf.css");
             break;
         default:
             $this->httpError(404);
             break;
     }
     //create pdf
     $file = FileUtils::convertToFileName('preview') . '.pdf';
     $html_outer = sprintf("<html><head><style>%s</style></head><body><div class='container'>%s</div></body></html>", str_replace("@host", $base, $css), $html_inner);
     try {
         $html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8', array(15, 5, 15, 5));
         $html2pdf->setTestIsImage(false);
         //$html2pdf->addFont('Open Sans', '', $base.'/themes/openstack/assets/fonts/PT-Sans/PTC75F-webfont.ttf');
         $html2pdf->WriteHTML($html_outer);
         //clean output buffer
         ob_end_clean();
         $html2pdf->Output($file, "D");
     } catch (HTML2PDF_exception $e) {
         $message = array('errno' => '', 'errstr' => $e->__toString(), 'errfile' => 'MarketPlaceAdminPage.php', 'errline' => '', 'errcontext' => '');
         SS_Log::log($message, SS_Log::ERR);
         $this->httpError(404, 'There was an error on PDF generation!');
     }
 }
コード例 #24
0
 /**
  * Generate template vars for metadata
  * 
  * @return ArrayData
  */
 public function ExportMetaData()
 {
     $def = $this->getDefinition();
     return new ArrayData(array('ExportHost' => preg_replace("#http(s)?://#", '', Director::protocolAndHost()), 'ExportDate' => date('d/m/Y H-i-s'), 'ExportUser' => $this->member->FirstName . ' ' . $this->member->Surname, 'ExportVersionFramework' => $this->ssVersion(), 'ExportWorkflowDefName' => $this->processTitle($def->Title), 'ExportRemindDays' => $def->RemindDays, 'ExportSort' => $def->Sort));
 }
コード例 #25
0
 public function ExportFullSchedule()
 {
     $sort = $this->getRequest()->getVar('sort') ? $this->getRequest()->getVar('sort') : 'day';
     $show_desc = $this->getRequest()->getVar('show_desc') ? $this->getRequest()->getVar('show_desc') : false;
     $base = Director::protocolAndHost();
     if (is_null($this->Summit())) {
         return $this->httpError(404, 'Sorry, summit not found');
     }
     $schedule = $this->Summit()->getSchedule();
     $events = new ArrayList();
     $sort_list = false;
     foreach ($schedule as $event) {
         switch ($sort) {
             case 'day':
                 $group_label = $event->getDayLabel();
                 break;
             case 'track':
                 if (!$event->isPresentation() || !$event->Category() || !$event->Category()->Title) {
                     continue 2;
                 }
                 $group_label = $event->Category()->Title;
                 $sort_list = true;
                 break;
             case 'event_type':
                 $group_label = $event->Type->Type;
                 $sort_list = true;
                 break;
         }
         if ($group_array = $events->find('Group', $group_label)) {
             $group_array->Events->push($event);
         } else {
             $group_array = new ArrayData(array('Group' => $group_label, 'Events' => new ArrayList()));
             $group_array->Events->push($event);
             $events->push($group_array);
         }
     }
     if ($sort_list) {
         $events->sort('Group');
     }
     $html_inner = $this->renderWith(array('SummitAppMySchedulePage_pdf'), array('Schedule' => $events, 'Summit' => $this->Summit(), 'ShowDescription' => $show_desc, 'Heading' => 'Full Schedule by ' . $sort));
     $css = @file_get_contents($base . "/summit/css/summitapp-myschedule-pdf.css");
     //create pdf
     $file = FileUtils::convertToFileName('full-schedule') . '.pdf';
     $html_outer = sprintf("<html><head><style>%s</style></head><body><div class='container'>%s</div></body></html>", $css, $html_inner);
     try {
         $html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8', array(15, 5, 15, 5));
         $html2pdf->setTestIsImage(false);
         $html2pdf->WriteHTML($html_outer);
         //clean output buffer
         ob_end_clean();
         $html2pdf->Output($file, "D");
     } catch (HTML2PDF_exception $e) {
         $message = array('errno' => '', 'errstr' => $e->__toString(), 'errfile' => 'SummitAppSchedPage.php', 'errline' => '', 'errcontext' => '');
         SS_Log::log($message, SS_Log::ERR);
         $this->httpError(404, 'There was an error on PDF generation!');
     }
 }
コード例 #26
0
 /**
  * Return the server host name from file to url mappings. For cli mode you'll need to make sure a FILE_TO_URL_MAPPING is
  * setup in environment file for the server.
  *
  * @return string
  * @throws Exception
  */
 public static function hostname()
 {
     if (!($hostname = parse_url(\Director::protocolAndHost(), PHP_URL_HOST))) {
         throw new Exception("Can't determine hostname");
     }
     return $hostname;
 }
コード例 #27
0
 public function testAlternativeBaseURL()
 {
     // Get original protocol and hostname
     $rootURL = Director::protocolAndHost();
     // relative base URLs - you should end them in a /
     Config::inst()->update('Director', 'alternate_base_url', '/relativebase/');
     $_SERVER['REQUEST_URI'] = "{$rootURL}/relativebase/sub-page/";
     $this->assertEquals('/relativebase/', Director::baseURL());
     $this->assertEquals($rootURL . '/relativebase/', Director::absoluteBaseURL());
     $this->assertEquals($rootURL . '/relativebase/subfolder/test', Director::absoluteURL('subfolder/test'));
     // absolute base URLs - you should end them in a /
     Config::inst()->update('Director', 'alternate_base_url', 'http://www.example.org/');
     $_SERVER['REQUEST_URI'] = "http://www.example.org/sub-page/";
     $this->assertEquals('http://www.example.org/', Director::baseURL());
     $this->assertEquals('http://www.example.org/', Director::absoluteBaseURL());
     $this->assertEquals('http://www.example.org/sub-page/', Director::absoluteURL(''));
     $this->assertEquals('http://www.example.org/', Director::absoluteURL('', true));
     /*
     		 * See Legacy behaviour in testAbsoluteURL - sub-pages with '/' in the string are not correctly evaluated
     		$this->assertEquals(
     			'http://www.example.org/sub-page/subfolder/test',
     			Director::absoluteURL('subfolder/test')
     		);*/
     $this->assertEquals('http://www.example.org/subfolder/test', Director::absoluteURL('subfolder/test', true));
     // Setting it to false restores functionality
     Config::inst()->update('Director', 'alternate_base_url', false);
     $_SERVER['REQUEST_URI'] = $rootURL;
     $this->assertEquals(BASE_URL . '/', Director::baseURL());
     $this->assertEquals($rootURL . BASE_URL . '/', Director::absoluteBaseURL(BASE_URL));
     $this->assertEquals($rootURL . BASE_URL . '/subfolder/test', Director::absoluteURL('subfolder/test'));
 }
コード例 #28
0
 public function Absolute()
 {
     $relative = $this->getURL();
     return Director::is_site_url($relative) && Director::is_relative_url($relative) ? Controller::join_links(Director::protocolAndHost(), $relative) : $relative;
 }
コード例 #29
0
    /**
     * Log the currently logged in user out
     *
     * @param bool $redirect Redirect the user back to where they came.
     *                       - If it's false, the code calling logout() is
     *                         responsible for sending the user where-ever
     *                         they should go.
     */
    public function logout($redirect = true)
    {
        if (!defined('OPENSTACKID_ENABLED') || OPENSTACKID_ENABLED == false) {
            return parent::logout();
        }
        $member = Member::currentUser();
        if ($member) {
            $member->logOut();
        }
        $url = OpenStackIdCommon::getRedirectBackUrl();
        if (strpos($url, '/admin/pages') !== false) {
            $url = Director::protocolAndHost();
        }
        $idp = IDP_OPENSTACKID_URL . "/accounts/user/logout";
        $script = <<<SCRIPT
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <img alt="logout" width="0" height="0" src="{$idp}" id="logout_image" />
  <p>Performing logout...</p>
  <script>
        jQuery(document).ready(function(\$){
            \$("#logout_image").ready(function() {
                window.location ="{$url}";
            });
        });
  </script>
SCRIPT;
        echo $script;
    }
コード例 #30
0
 /**
  * Sends the email, either with the native {@link Email} class or with Postmark
  *
  * @param array The form data
  * @param Form The form object
  */
 public function sendEmail($data, $form)
 {
     $proxy = $form->proxy;
     $emailTo = $proxy->getToAddress();
     $emailSubject = $proxy->getMessageSubject();
     $replyTo = $proxy->getReplyTo();
     $emailTemplate = $proxy->getEmailTemplate();
     $fields = ArrayList::create(array());
     $uploadedFiles = array();
     foreach ($form->Fields()->dataFields() as $field) {
         if (!in_array($field->getName(), $proxy->getOmittedFields())) {
             if ($field instanceof CheckboxField) {
                 $value = $field->value ? _t('ContactForm.YES', 'Yes') : _t('ContactForm.NO', 'No');
             } elseif (class_exists("UploadifyField") && $field instanceof UploadifyField) {
                 $uploadedFiles[] = $field->Value();
             } else {
                 $value = nl2br($field->Value());
             }
             if (is_array($value)) {
                 $answers = ArrayList::create(array());
                 foreach ($value as $v) {
                     $answers->push(ArrayData::create(array('Value' => $v)));
                 }
                 $answers->Checkboxes = true;
                 $fields->push(ArrayData::create(array('Label' => $field->Title(), 'Values' => $answers)));
             } else {
                 $title = $field->Title() ? $field->Title() : $field->getName();
                 $fields->push(ArrayData::create(array('Label' => $title, 'Value' => $value)));
             }
         }
     }
     $messageData = array('IntroText' => $proxy->getIntroText(), 'Fields' => $fields, 'Domain' => Director::protocolAndHost());
     Requirements::clear();
     $html = $this->owner->customise($messageData)->renderWith($emailTemplate);
     Requirements::restore();
     if ($proxy->isPostmark()) {
         require_once Director::baseFolder() . "/contact_form/code/thirdparty/postmark/Postmark.php";
         $email = Mail_Postmark::compose()->subject($emailSubject)->messageHtml($html);
         try {
             $email->addTo($emailTo);
         } catch (Exception $e) {
             $form->sessionMessage(_t('ContactForm.BADTOADDRESS', 'It appears there is no receipient for this form. Please contact an administrator.'), 'bad');
             return $this->owner->redirectBack();
         }
         if ($replyTo) {
             try {
                 $email->replyTo($replyTo);
             } catch (Exception $e) {
             }
         }
         foreach ($uploadedFiles as $file_id) {
             if ($file = File::get()->byID($file_id)) {
                 $email->addAttachment($file->getFullPath());
             }
         }
     } else {
         $email = Email::create(null, $emailTo, $emailSubject, $html);
         if ($replyTo) {
             $email->replyTo($replyTo);
         }
         foreach ($uploadedFiles as $file_id) {
             if ($file = File::get()->byID($file_id)) {
                 $email->attachFile($file->getFullPath(), basename($file->Filename));
             }
         }
     }
     $email->send();
     foreach ($uploadedFiles as $file_id) {
         if ($file = File::get()->byID($file_id)->first()) {
             $file->delete();
         }
     }
 }