Including OAuth in PHP stops OAuth separate Class from working - oauth

I am working with Google Analytics and Google Adwords, and I've installed the OAuth "pecl" package to get the Google Adwords working and now my Analytics code doesn't work.
When I open up my php.ini file and comment out (and restart apache)
extension=oauth.so
The analytics example code works (I adapted it from the OAuth playground that google has open sourced). Is there any way that I could keep my example code from working? I have found that the script crashes on this line:
require_once('common.inc.php');
Common.inc.php looks like this:
<?php
/* Copyright (c) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Eric Bidelman <e.bidelman#google.com>
*/
$PRIV_KEY_FILE = '/path/to/your/rsa_private_key.pem';
// OAuth library - http://oauth.googlecode.com/svn/code/php/
require_once('OAuth.php');
// Google's accepted signature methods
$hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
$rsa_method = new OAuthSignatureMethod_RSA_SHA1();
$SIG_METHODS = array($rsa_method->get_name() => $rsa_method,
$hmac_method->get_name() => $hmac_method);
/**
* Makes an HTTP request to the specified URL
*
* #param string $http_method The HTTP method (GET, POST, PUT, DELETE)
* #param string $url Full URL of the resource to access
* #param array $extraHeaders (optional) Additional headers to include in each
* request. Elements are header/value pair strings ('Host: example.com')
* #param string $postData (optional) POST/PUT request body
* #param bool $returnResponseHeaders True if resp. headers should be returned.
* #return string Response body from the server
*/
function send_signed_request($http_method, $url, $extraHeaders=null,
$postData=null, $returnResponseHeaders=true) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
// Return request headers in the reponse
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
// Return response headers ni the response?
if ($returnResponseHeaders) {
curl_setopt($curl, CURLOPT_HEADER, true);
}
$headers = array();
//$headers[] = 'GData-Version: 2.0'; // use GData v2 by default
if (is_array($extraHeaders)) {
$headers = array_merge($headers, $extraHeaders);
}
// Setup default curl options for each type of HTTP request.
// This is also a great place to add additional headers for each request.
switch($http_method) {
case 'GET':
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
break;
case 'POST':
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
break;
case 'PUT':
$headers[] = 'If-Match: *';
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $http_method);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
break;
case 'DELETE':
$headers[] = 'If-Match: *';
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $http_method);
break;
default:
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
// Execute the request. If an error occures, fill the response body with it.
$response = curl_exec($curl);
if (!$response) {
$response = curl_error($curl);
}
// Add server's response headers to our response body
$response = curl_getinfo($curl, CURLINFO_HEADER_OUT) . $response;
curl_close($curl);
return $response;
}
/**
* Takes XML as a string and returns it nicely indented
*
* #param string $xml The xml to beautify
* #param boolean $html_output True if returned XML should be escaped for HTML.
* #return string The beautified xml
*/
function xml_pretty_printer($xml, $html_output=false) {
$xml_obj = new SimpleXMLElement($xml);
$level = 2;
// Get an array containing each XML element
$xml = explode("\n", preg_replace('/>\s*</', ">\n<", $xml_obj->asXML()));
// Hold current indentation level
$indent = 0;
$pretty = array();
// Shift off opening XML tag if present
if (count($xml) && preg_match('/^<\?\s*xml/', $xml[0])) {
$pretty[] = array_shift($xml);
}
foreach ($xml as $el) {
if (preg_match('/^<([\w])+[^>\/]*>$/U', $el)) {
// opening tag, increase indent
$pretty[] = str_repeat(' ', $indent) . $el;
$indent += $level;
} else {
if (preg_match('/^<\/.+>$/', $el)) {
$indent -= $level; // closing tag, decrease indent
}
if ($indent < 0) {
$indent += $level;
}
$pretty[] = str_repeat(' ', $indent) . $el;
}
}
$xml = implode("\n", $pretty);
return $html_output ? htmlentities($xml) : $xml;
}
/**
* Joins key/value pairs by $inner_glue and each pair together by $outer_glue.
*
* Example: implode_assoc('=', '&', array('a' => 1, 'b' => 2)) === 'a=1&b=2'
*
* #param string $inner_glue What to implode each key/value pair with
* #param string $outer_glue What to impode each key/value string subset with
* #param array $array Associative array of query parameters
* #return string Urlencoded string of query parameters
*/
function implode_assoc($inner_glue, $outer_glue, $array) {
$output = array();
foreach($array as $key => $item) {
$output[] = $key . $inner_glue . urlencode($item);
}
return implode($outer_glue, $output);
}
/**
* Explodes a string of key/value url parameters into an associative array.
* This method performs the compliment operations of implode_assoc().
*
* Example: explode_assoc('=', '&', 'a=1&b=2') === array('a' => 1, 'b' => 2)
*
* #param string $inner_glue What each key/value pair is joined with
* #param string $outer_glue What each set of key/value pairs is joined with.
* #param array $array Associative array of query parameters
* #return array Urlencoded string of query parameters
*/
function explode_assoc($inner_glue, $outer_glue, $params) {
$tempArr = explode($outer_glue, $params);
foreach($tempArr as $val) {
$pos = strpos($val, $inner_glue);
$key = substr($val, 0, $pos);
$array2[$key] = substr($val, $pos + 1, strlen($val));
}
return $array2;
}
?>
I was wondering if anybody had experience with this extension. Perhaps I could rename some of the OAuth classnames? It seems to be that some of these classes are conflicting causing this not to work. I'm going to need to have these scripts working side by side, (ie. under the same php.ini configuration).
Another alternative that I have been wondering about: Is there a way to include an extension in the php.ini file for only one script (Adwords Script)? And then by default not include the extension?
Any advice would help! Thank you

I actually got around this by using dl() to dynamically load the extension
http://php.net/manual/en/function.dl.php

Related

TCPDF how do I create several pdf's without opening a browser

I need to create like 350 pdf's at once. Now the browser opens a window for each pdf. I takes longer to open all the 350 windows than to create the pdf's. How do I create and save the pdf's without opening a browser windows? (In my pdf I use Header, body and footer all with variables)
Now I do a loop on php_page_1 which opens the pdf create file.
$sql = "SELECT id FROM shipping_id WHERE datum BETWEEN $date_range AND acc_id=$acc_id;";
$STH = $dbo->prepare( $sql );
$STH->execute();
$contains_files = 0;
$client_id='';
while ( $row = $STH->fetch( PDO::FETCH_ASSOC ) ) {
$contains_files++;
$link = "vb_print_1_no_screen.php?id=" . $row[ 'id' ] . "&nr=".$contains_files;
echo '<script>window.open("https://' . $website_admin . $link . '");</script>';
}
You can use curl to make the request to the URL instead of opening it directly in the browser or you can just include the file that generates the PDF. Try this code
$sql = "SELECT id FROM shipping_id WHERE datum BETWEEN $date_range AND acc_id=$acc_id;";
$STH = $dbo->prepare( $sql );
$STH->execute();
$contains_files = 0;
$client_id='';
while ( $row = $STH->fetch( PDO::FETCH_ASSOC ) ) {
$contains_files++;
$link = "vb_print_1_no_screen.php?id=" . $row[ 'id' ] . "&nr=".$contains_files;
// echo '<script>window.open("https://' . $website_admin . $link . '");</script>';
// method 1 using curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $website_admin . $link);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
// method 2 include pdf generator script
$_GET['id'] = $row['id'];
$_GET['nr'] = $contains_files;
include "vb_print_1_no_screen.php";
}
Kindly make sure to use just one method.

Google Translate in Flash (SWF) Action Script

We tried to code Google Translate in action script for Flash Professional CS6, but it does not function .
Can anyone help ?
The code does not return the trasnlated result .
The Code :
private function translate(e)
{
var result_lv:LoadVars = new LoadVars();
result_lv.onLoad = function () {
var str:String = unescape(this);
var txtContent;
var translatedText:String = str.split('":"')[1].split('"}, ')[0];
if(translatedText != undefined)
txtContent.text = translatedText.split('r').join('n').split('"').join("'");
return txtContent.text;
}
var lorem_lv:LoadVars = new LoadVars();
var from:String = "fa";
var to:String = "en"
lorem_lv.v = "1.0";
lorem_lv.format = "text";
lorem_lv.q = e;
lorem_lv.langpair = from + "|" + to;
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
}
Code Explained :
Sample
LoadVars.sendAndLoad( )
Method Code Explained :
https://flylib.com/books/en/4.13.1.377/1/
================================================
Edit 1:
I edited my code :
I added the return code to the main function , so the main function has output .
but still the function does not return any transalted content .
The improved code :
private function translate(e)
{
var result_lv:LoadVars = new LoadVars();
var txtContent;
result_lv.onLoad = function () {
var str:String = unescape(this);
var translatedText:String = str.split('":"')[1].split('"}, ')[0];
if(translatedText != undefined)
txtContent.text = translatedText.split('r').join('n').split('"').join("'");
return txtContent.text;
}
var lorem_lv:LoadVars = new LoadVars();
var from:String = "fa";
var to:String = "en"
lorem_lv.v = "1.0";
lorem_lv.format = "text";
lorem_lv.q = e;
lorem_lv.langpair = from + "|" + to;
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
return txtContent.text;
}
================================================
Edit 2:
We have found a working PHP function that return the translated result properly :
https://github.com/statickidz/php-google-translate-free/blob/1.1.1/src/GoogleTranslate.php
Now we are trying to load the PHP function result in the Action Script 2 for Adobe Flash Professional CS6.
here is some explanation about how this is possible :
Flash calling a PHP function
================================================
Edit 3:
A Good and Complete Book about PHP for Flash :
Foundation PHP for Flash 1st Edition :
https://www.amazon.com/Foundation-PHP-Flash-Steve-Webster/dp/1903450160
================================================
Edit 4:
Some Other Good and Complete Books about PHP for Flash :
Foundation PHP 5 for Flash 1st Edition :
https://www.amazon.com/Foundation-PHP-Flash-David-Powers/dp/B0096EPX7Q
Advanced PHP for Flash 1st ed. Edition :
https://www.amazon.com/Advanced-PHP-Flash-Steve-Webster/dp/1590591879
================================================
Edit 5:
We have rewritten the action script function that now use the PHP GoogleTranslate function .
See the answers below .
But it does not return the Translated result .
Please can someone help ?
Thanks
In the PHP-script that you've mentioned in comments, authors used the link https://translate.google.com/translate_a/single?... with some client authenticaton data like iid and also set User-Agent to Android phone:
curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
I think this script is trying to masquerade request like it was sent from Android Google Translate App.
But in your AcrionScript code you are using another URL:
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
This simple-HTTP Google Translate API v1 is very old and already not available.
You can check it yourself by following this link - it's responds 404.
Here is the code that we have written :
Our function is written using the sample code on the below address :
Easy way to bring a php variable on flash with AS2
but it does not return the translated result . when I set the return String value to e variable the function work . but when I set the return to $output variable it does not function .
Action Script 2 Code :
function googletranslate(e:String):String
{
/*LoadVars send example*/
// init LoadVars Object
var lv:LoadVars = new LoadVars();
// set Variables
lv.sVar1 = "fa";
lv.sVar2 = "en";
lv.sVar3 = e;
// define onLoad Callback
lv.onLoad = onLoadCallBack;
// send and load variables
lv.sendAndLoad("google-translate-result.php?", lv, "POST");
var $output;
// onLoad Callback
function onLoadCallBack(succes)
{
// if succes
if(succes)
{
// trace variables
$output = this.lVarresult;
}
else
{
// loading failed
$output = "Loading Error!!";
}
}
return $output;
}
=============================================================
Edit :
The PHP (google-translate-result.php) Code is changed :
$_POST changed to $_GET and now the result php code is working itself through using this url :
Server_URL/google-translate-result.php?sVar1=fa&sVar2=en&sVar3=%DA%A9%D8%AA%D8%A7%D8%A8%20%D8%AA%D8%B3%D8%AA
but still the ActionScript does not return the Translated Result .
=============================================================
PHP Code (google-translate-result.php) :
<?php
require_once('GoogleTranslate.php');
// get variables
$var1 = $_GET['sVar1'];
$var2 = $_GET['sVar2'];
$var3 = $_GET['sVar3'];
$result = GoogleTranslate::translate($var1,$var2,$var3);
// send variables
echo "&lVarresult=$result&";
PHP Code (GoogleTranslate.php) :
<?php
/**
* GoogleTranslate.class.php
*
* Class to talk with Google Translator for free.
*
* #package PHP Google Translate Free;
* #category Translation
* #author Adrián Barrio Andrés
* #author Paris N. Baltazar Salguero <sieg.sb#gmail.com>
* #copyright 2016 Adrián Barrio Andrés
* #license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* #version 2.0
* #link https://statickidz.com/
*/
/**
* Main class GoogleTranslate
*
* #package GoogleTranslate
*
*/
class GoogleTranslate
{
/**
* Retrieves the translation of a text
*
* #param string $source
* Original language of the text on notation xx. For example: es, en, it, fr...
* #param string $target
* Language to which you want to translate the text in format xx. For example: es, en, it, fr...
* #param string $text
* Text that you want to translate
*
* #return string a simple string with the translation of the text in the target language
*/
public static function translate($source, $target, $text)
{
// Request translation
$response = self::requestTranslation($source, $target, $text);
// Get translation text
// $response = self::getStringBetween("onmouseout=\"this.style.backgroundColor='#fff'\">", "</span></div>", strval($response));
// Clean translation
$translation = self::getSentencesFromJSON($response);
return $translation;
}
/**
* Internal function to make the request to the translator service
*
* #internal
*
* #param string $source
* Original language taken from the 'translate' function
* #param string $target
* Target language taken from the ' translate' function
* #param string $text
* Text to translate taken from the 'translate' function
*
* #return object[] The response of the translation service in JSON format
*/
protected static function requestTranslation($source, $target, $text)
{
// Google translate URL
$url = "https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=es-ES&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e";
$fields = array(
'sl' => urlencode($source),
'tl' => urlencode($target),
'q' => urlencode($text)
);
// URL-ify the data for the POST
$fields_string = "";
foreach ($fields as $key => $value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
return $result;
}
/**
* Dump of the JSON's response in an array
*
* #param string $json
* The JSON object returned by the request function
*
* #return string A single string with the translation
*/
protected static function getSentencesFromJSON($json)
{
$sentencesArray = json_decode($json, true);
$sentences = "";
foreach ($sentencesArray["sentences"] as $s) {
$sentences .= isset($s["trans"]) ? $s["trans"] : '';
}
return $sentences;
}
}
According to the Comments of the previous answer Action Script 2 Code changed to:
function googletranslate(e:String):String
{
/*LoadVars send example*/
// init LoadVars Object
var lv:LoadVars = new LoadVars();
var result_lv:LoadVars = new LoadVars();
// set Variables
lv.sVar1 = "fa";
lv.sVar2 = "en";
lv.sVar3 = e;
// send and load variables
lv.sendAndLoad("google-translate-result.php?", result_lv, "POST");
return result_lv.lVarresult;
}

Youtube Data API is returning invalid data

I'm not really sure how to ask this, but I have a php script that pulls data from the youtube-v3-api for my youtube channel, mainly a list of videos that I have published. It's been working great up until earlier today when I went to run it again because I added a new video. Here's the output for the first object in the items array
items:[
{
kind:"youtube#searchResult",
etag:"" XpPGQXPnxQJhLgs6enD_n8JR4Qk/tluoWYe5GE9lVFAkcMtcec2Ycug"",
id:{
kind:"youtube#channel",
channelId:"UCD8d3FGC907iS1qiMF0ccxA"
},
snippet:{
publishedAt:"2006-04-30T19:39:08.000Z",
channelId:"UCD8d3FGC907iS1qiMF0ccxA",
title:"Travis Ballard",
description:"",
thumbnails:{
default:{
url:"https://yt3.ggpht.com/-L5MV7tUNjlk/AAAAAAAAAAI/AAAAAAAAAAA/dXNuqxAYprw/s88-c-k-no-mo-rj-c0xffffff/photo.jpg"
},
medium:{
url:"https://yt3.ggpht.com/-L5MV7tUNjlk/AAAAAAAAAAI/AAAAAAAAAAA/dXNuqxAYprw/s240-c-k-no-mo-rj-c0xffffff/photo.jpg"
},
high:{
url:"https://yt3.ggpht.com/-L5MV7tUNjlk/AAAAAAAAAAI/AAAAAAAAAAA/dXNuqxAYprw/s800-c-k-no-mo-rj-c0xffffff/photo.jpg"
}
},
channelTitle:"Travis Ballard",
liveBroadcastContent:"none"
}
}
]
This does not represent a video on my channel? also, it's not in order at all. It should be ordered by date as i'm asking it to in my php script:
<?php
const APIKEY = 'MyAPIKeyHere';
const CHANNELID = 'UCD8d3FGC907iS1qiMF0ccxA';
const VIDEO_COUNT = 50;
class FetchYoutubeVideos {
private $api_key = null;
private $channel_id = null;
private $count = null;
public function __construct($api_key, $channel_id, $count = 10) {
$this->api_key = $api_key;
$this->channel_id = $channel_id;
$this->count = $count;
$this->writeToFile(
'videos.json',
$this->fetch($this->getApiUrl())
);
printf( 'fetched videos from: %s', $this->getApiUrl());
}
public function getApiUrl($options = array()) {
$endpoint = 'https://www.googleapis.com/youtube/v3/search';
$default_options = array(
'key' => $this->api_key,
'channelId' => $this->channel_id,
'part' => 'snippet,id',
'order' => 'date',
'maxResults' => $this->count
);
$options = array_merge($options, $default_options);
return sprintf('%s/?%s', $endpoint, http_build_query($options));
}
public function fetch($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
return $result;
}
public function writeToFile($filename, $data) {;
$fh = fopen($filename, 'w+');
fwrite($fh, $data, strlen($data));
fclose($fh);
}
}
$fetchVideos = new FetchYoutubeVideos(APIKEY, CHANNELID, VIDEO_COUNT);
The newest video should be 'Tragic - Rock-a-Hoola Revisited' and then 'Rocket Timelapse - Anycubic i3 Mega'. You can reference my yt channel to see what it should be returning: https://www.youtube.com/channel/UCD8d3FGC907iS1qiMF0ccxA?view_as=subscriber
Any insights into why it changed? Or why it's not returning the data that it should be?
You experienced an API issue which is known for a few days now. Follow-up https://issuetracker.google.com/issues/128673552, or the answers already given on this site (e.g. https://stackoverflow.com/a/55246970/8327971).
Either of the two links we'll lead you to find a workaround for the issue at hand.
Note that, until now, Google has refrained itself from providing an ETA for when it'll enable back the API's features it disabled. I suppose that it may well take a few more days (perhaps weeks?) until we'll see those disabled features working again.

TYPO3 8 LTS how to generate frontend page URL in CLI/Scheduler context

I'm trying to figure out how to generate absolute frontend page URLs from CLI/Scheduler context. I've created the following helper class:
class FrontendUrlProvider
{
/**
* #var ObjectManagerInterface
*/
private $objectManager;
/**
* #var LoggerInterface
*/
private $logger;
/**
* #param ObjectManagerInterface $objectManager
* #param LoggerInterface $logger
*/
public function __construct(ObjectManagerInterface $objectManager, LoggerInterface $logger)
{
$this->objectManager = $objectManager;
$this->initializeTimeTracker();
$this->logger = $logger;
}
/**
* #param int $pageId
* #param int $languageId
* #return Uri
*/
public function pageUrl($pageId, $languageId)
{
$url = '';
$this->logger->error('generating preview link');
try {
$this->initializeTypoScriptFrontend($pageId);
$this->setUpPageDomainIfCliContext($pageId);
$contentRenderer = $this->objectManager->get(ContentObjectRenderer::class);
$command = $this->linkCommand($pageId, $languageId);
$url = $contentRenderer->typoLink_URL($command);
$this->logger->error("preview link is: $url");
} catch (\Exception $exception) {
$this->logger->error($exception->getMessage());
$this->logger->error($exception->getTraceAsString());
}
return new Uri($url);
}
private function initializeTimeTracker()
{
if (!is_object($GLOBALS['TT'])) {
$GLOBALS['TT'] = new \TYPO3\CMS\Core\TimeTracker\NullTimeTracker();
}
}
/**
* #param int $pageId
*/
private function initializeTypoScriptFrontend($pageId)
{
if (isset($GLOBALS['TSFE']) && is_object($GLOBALS['TFSE'])) {
return;
}
$GLOBALS['TSFE'] = $this->objectManager->get(TypoScriptFrontendController::class, $GLOBALS['TYPO3_CONF_VARS'], $pageId, '');
$GLOBALS['TSFE']->sys_page = $this->objectManager->get(PageRepository::class);
$GLOBALS['TSFE']->sys_page->init(false);
$GLOBALS['TSFE']->tmpl = $this->objectManager->get(TemplateService::class);
$GLOBALS['TSFE']->tmpl->init();
$GLOBALS['TSFE']->connectToDB();
$GLOBALS['TSFE']->initFEuser();
$GLOBALS['TSFE']->determineId();
$GLOBALS['TSFE']->initTemplate();
$GLOBALS['TSFE']->getConfigArray();
}
/**
* #param int $pageId
*/
private function setUpPageDomainIfCliContext($pageId)
{
if (!isset($_SERVER['HTTP_HOST']) || !$_SERVER['HTTP_HOST']) {
$domainData = $GLOBALS['TSFE']->getDomainDataForPid($pageId);
if (is_array($domainData) && isset($domainData['domainName']) && !empty($domainData['domainName'])) {
$_SERVER['HTTP_HOST'] = $domainData['domainName'] ?: '';
}
}
}
/**
* #param int $pageId
* #param int $languageId
* #return array
*/
private function linkCommand($pageId, $languageId)
{
$languageQuery = http_build_query(['L' => $languageId], null, '&', PHP_QUERY_RFC3986);
return array(
'parameter' => $pageId,
'useCacheHash' => false,
'forceAbsoluteUrl' => true,
'linkAccessRestrictedPages' => true,
'additionalParams' => '&' . $languageQuery,
);
}
}
I'm at the point that it works fine in TYPO3 7 LTS, as long as there's a domain record for the root line.
However this same snippet doesn't work in TYPO3 8 LTS and I need it working for both 7 and 8 at the same time. Obviously, I have set the domain record on the root line in v8, I cleared all the caches, etc. but I can't get an absolute URL in place. I only get the relative URL. At this point I'm not that interested in realUrl or anything like that.
For TYPO3 7 I basically reverse engineered it but with TYPO3 8 it seems a bit more complicated. Do you know what can I do more to get the page frontend URL?
It seems that the issue was an internal cache of the GeneralUtility, which cached a null value for the HTTP_HOST of $_SERVER superglobal.
Therefore the following line from my example above had no effect
$_SERVER['HTTP_HOST'] = $domainData['domainName'] ?: '';
In order to make it work under the CLI/Scheduler scope I had to clear the internal cache of the GeneralUtility by calling
TYPO3\CMS\Core\Utility\GeneralUtility::flushInternalRuntimeCaches();
before making a call to $contentRenderer->typoLink_URL($command);
Now frontend URL generation works fine on both TYPO3 7 and 8 LTS.
https://wissen.netzhaut.de/typo3/extensionentwicklung/typolink-realurl-in-scheduler-tasks/
But really: I'd recommend using a curl call against a custom page which will deliver the link (sort of as a rest API) - because thereby you go around almost all issues - and there are more beyond not having tsfe (e.g. safePath \ images).

Access specific node (custom_field) simplexml

This XML file, which can be accessed here # http://afdclinics.com/persistentpresence/category/brentwood/lobby-1/feed/ - has a custom_fields node with 2 fields called custom-bgcolor, and custom-fontcolor. I have tried numerous ways to try, and access the data inside them with no luck.
I have been accessing other nodes with simplexml, but haven't been able to get the custom_fields working. Here is what I have so far.
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL,'http://afdclinics.com/persistentpresence/category/brentwood/lobby-1/feed/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($curl);
if ($result === false) {
die('Error fetching data: ' . curl_error($curl));
}
curl_close ($curl);
//we can at this point echo the XML if you want
//echo $result;
//parse xml string into SimpleXML objects
$xml = simplexml_load_string($result);
if ($xml === false) {
die('Error parsing XML');
}
//now we can loop through the xml structure
foreach ($xml->channel->item as $item) {
//print $item->title; rss feed article title
//print $item->description; rss feed article description
//print $item->link; rss feed article link
//print $item->pubDate; rss feed article publish date
print $item->children('content', true); //rss feed article content
// here is where is would like to print the custom values
print $item->custom_fields->custom-bgcolor; // this line doesn't seem to work
//gets img url's and appends them to offline manifest file
$imgUrl = array();
$doc2 = new DOMDocument();
$doc2->loadHTML($item->children('content', true));
$imgUrl = simplexml_import_dom($doc2);
$images = $imgUrl->xpath('//img');
foreach ($images as $img) {
$imgUrl = $img['src'] . "\r\n";
print $imgUrl; //rss feed image url's
$i++;
}

Resources