I have the following code from google adwords api and for some reason there is a specific section that prevents the browser from displaying output. I can't figure out why but can someone please tell me how to fix and why this line would prevent the browser from displaying output but allows the cli to display output.
<?php
// Include the initialization file
require_once 'src/Google/Api/Ads/AdWords/init.php';
require_once ADWORDS_UTIL_PATH . '/ReportUtils.php';
/**
* Runs the example.
* #param AdWordsUser $user the user to run the example with
* #param string $filePath the path of the file to download the report to
*/
function DownloadCriteriaReportExample(AdWordsUser $user, $filePath) {
// Load the service, so that the required classes are available.
$user->LoadService('ReportDefinitionService', ADWORDS_VERSION);
// Create selector.
$selector = new Selector();
$selector->fields = array('CampaignName', 'AdGroupName', 'Criteria',
'AverageCpc', 'Impressions', 'Clicks', 'Cost', 'AveragePosition', 'Ctr');
// Filter out deleted criteria.
$selector->predicates[] = new Predicate('Status', 'NOT_IN', array('DELETED'));
// Create report definition.
$reportDefinition = new ReportDefinition();
$reportDefinition->selector = $selector;
$reportDefinition->reportName = 'Criteria performance report #' . uniqid();
$reportDefinition->dateRangeType = 'LAST_30_DAYS';
$reportDefinition->reportType = 'CRITERIA_PERFORMANCE_REPORT';
$reportDefinition->downloadFormat = 'CSV';
// Exclude criteria that haven't recieved any impressions over the date range.
$reportDefinition->includeZeroImpressions = FALSE;
// Set additional options.
$options = array('version' => ADWORDS_VERSION, 'returnMoneyInMicros' => FALSE);
// Download report.
ReportUtils::DownloadReport($reportDefinition, $filePath, $user, $options);
printf("Report with name '%s' was downloaded to '%s'.\n",
$reportDefinition->reportName, $filePath);
}
This is the line that is causing the issue for some reason
// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
return;
}
End of line causing issue
try {
// Get AdWordsUser from credentials in "../auth.ini"
// relative to the AdWordsUser.php file's directory.
$user = new AdWordsUser();
// Log every SOAP XML request and response.
$user->LogAll();
// Download the report to a file in the same directory as the example.
$filePath = dirname(__FILE__) . '/report.csv';
// Run the example.
DownloadCriteriaReportExample($user, $filePath);
} catch (Exception $e) {
printf("An error has occurred: %s\n", $e->getMessage());
}
Related
I'm trying to follow this link: https://learn.microsoft.com/en-us/rest/api/storageservices/copy-file
with examples from this repo: https://github.com/Azure/azure-storage-php/blob/master/samples/FileSamples.php#L235
The file is indeed copied to the azure server but the content aren't readable, to say the least, it takes a size but it's empty. This is only a text file as well, and what I plan to achieve after fixing this is to copy excel files generated via PHP to an azure file storage server.
Also, we are using file.core not blob.core
<?php
require_once "vendor/autoload.php";
use MicrosoftAzure\Storage\File\FileRestProxy;
use MicrosoftAzure\Storage\Common\Models\Range;
$accountName = "test";
$accountKey = "test";
$shareName = 'test';
$connectionString = "DefaultEndpointsProtocol=https;AccountName=$accountName;AccountKey=$accountKey";
$fileClient = FileRestProxy::createFileService($connectionString);
$dstfileName = 'demo-4.txt';
$srcfileName = 'demo-4.txt';
$sourcePath = sprintf(
'%s%s/%s',
(string)$fileClient->getPsrPrimaryUri(),
$shareName,
$srcfileName
);
try {
// Create destination file.
$fileClient->createFile($shareName, $dstfileName, 1024);
// Copy file.
return $fileClient->copyFile($shareName, $dstfileName, $sourcePath);
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code . ": " . $error_message . PHP_EOL;
}
Update using file_get_contents
$srcfileName = 'demo-4.txt';
$content = file_get_contents('demo-4.txt');
$range = new Range(0, filesize('demo-4.txt') - 1);
$sourcePath = sprintf(
'%s%s/%s',
(string)$fileClient->getPsrPrimaryUri(),
$shareName,
$srcfileName
);
try {
// Create source file.
$fileClient->createFile($shareName, $srcfileName, 1024);
$fileClient->putFileRange($shareName, $srcfileName, $content, $range);
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code . ": " . $error_message . PHP_EOL;
}
This is able to create the file with the content from the source file, but the problem is that the range is incorrect since I don't know how to correctly get that value.
The created file is presented by the image attached, it has multiple nulls in it because I'm guessing my range exceeds the actual length of the source file contents.
createFile method simply creates an empty file of size specified in the method call. It essentially maps to Create File REST API operation.
You should use createFileFromContent convenience method to create a file with content. It basically first creates an empty file and then writes the contents to that file.
Other option would be to call putFileRange method to write the contents to the file after you have created it using createFile method.
I'm using the SSRS SDK For PHP which has not been updated since years surprisingly (08.04.2010) .
It works fine under PHP 5.4 (5.4.44) but not under 5.5+ (5.5.37, 5.6.28, 7.x)
The error is :
array ( )Failed to connect to Reporting Service Make sure that the url
(https://myHost:60004/ReportServer/) and credentials are
correct!
The exception is thrown in line 207 because the var $content is equals to FALSE (so can't load the content).
It's perfectly fine with PHP 5.4.44.
I can't find the "SSRS SDK For PHP" documentation regarding the PHP version supported...
I'm not using any framework such as Symfony2, CakePHP, Zend Framework,... except Bootstrap.
Does anyone know or have figured out this issue?
EDIT
As asked in a comment, here is my code :
function buildSSRSReport($companyId)
{
require_once '../tools/SSRSReport/SSRSReport.php';
try {
// Create a connection to the SSRS Server
$rs = new SSRSReport(new Credentials(SSRS_USER_ID, SSRS_PASSWORD), SSRS_REPORT_SERVER_URL);
$sqlConnection = self::getSqlConnection();
// Load the report and specify the params required for its execution
$executionInfo = $rs->LoadReport2(self::getSSRSEnvironment(), NULL);
$parameters = array();
$parameters[0] = new ParameterValue();
$parameters[0]->Name = "CompanyId";
$parameters[0]->Value = $companyId;
$rs->SetExecutionParameters2($parameters);
// Require the Report to be rendered in HTML format
$renderAsHTML = new RenderAsPDF();
// Set the links in the reports to point to the php app
//$renderAsHTML->ReplacementRoot = getPageURL();
// Set the root path on the server for any image included in the report
//$renderAsHTML->StreamRoot = './images/';
// Execute the Report
$result_html = $rs->Render2($renderAsHTML,
PageCountModeEnum::$Actual,
$Extension,
$MimeType,
$Encoding,
$Warnings,
$StreamIds);
$pdfFileName = self::getCompanyAlias($sqlConnection, $companyId) . ".pdf";
header('Content-Type: application/x-download');
header('Content-Disposition: attachment; filename="' . $pdfFileName . '"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
return $result_html;
} catch (SSRSReportException $serviceException) {
echo $serviceException->GetErrorMessage();
}
}
function getSSRSEnvironment()
{
return "/DEV/CompanyESGReportingServices-DEV/Main";
}
private function getSqlConnection()
{
require_once("../inc/eth_connexion.php");
/* These 4 variables are contained within the eth_connexion.php file */
$serverName = SQL_SERVERNAME;
$userName = SQL_USERNAME;
$dbName = SQL_DATABASENAME;
$password = SQL_PASSWORD;
// SQLSRV : Connection array used when calling SQL via sqlsrv_query
$connectionInfo = array("Database"=> SQL_DATABASENAME,
"UID"=> SQL_USERNAME,
"PWD"=> SQL_PASSWORD,
"ReturnDatesAsStrings" => true);
$sqlConnection = sqlsrv_connect($serverName, $connectionInfo);
if (!$sqlConnection) {
die('Can't log to the database');
}
return $sqlConnection;
}
And here is the source code of the SSRSReport constructor (original from the SSRS SDK For PHP) :
public function SSRSReport($credentials, $url, $proxy = null)
{
$this->_BaseUrl = ($url[strlen($url) - 1] == '/')? $url : $url . '/';
$executionServiceUrl = $this->_BaseUrl . self::ExecutionService;
$managementServiceUrl = $this->_BaseUrl . self::ManagementService;
$options = $credentials->getCredentails();
$stream_conext_params = array( 'http' =>
array('header' =>
array($credentials->getBase64Auth())));
if(isset($proxy))
{
$options = array_merge($options, $proxy->getProxy());
$stream_conext_params['http']['proxy'] = 'tcp://' .
$proxy->getHost() .
':' .
$proxy->getPort();
if($proxy->getLogin() != null)
{
$stream_conext_params['http']['header'][1] = $proxy->getBase64Auth();
}
}
/**
* If the SoapClient call fails, we cannot catch exception or supress warning
* since it throws php fatal exception.
* http://bugs.php.net/bug.php?id=34657
* So try to load the wsdl by
* calling file_get_contents (with warning supressed i.e. using # symbol
* infront of the function call)
* http://stackoverflow.com/questions/272361/how-can-i-handle-the-warning-of-filegetcontents-function-in-php
*/
$context = stream_context_create($stream_conext_params);
$content = #file_get_contents($executionServiceUrl, false, $context);
if ($content === FALSE) // I'M GOING HERE WITH PHP 5.5+
{
throw new SSRSReportException("",
"Failed to connect to Reporting Service <br/> Make sure " .
"that the url ($this->_BaseUrl) and credentials are correct!");
}
$this->_soapHandle_Exe = new SoapClient ($executionServiceUrl, $options);
$this->_soapHandle_Mgt = new SoapClient ($managementServiceUrl, $options);
$this->ClearRequest();
}
The exact error message is :
https://myPublicHostProvider:60004/ReportServer/ReportExecution2005.asmx?wsdl
Authorization: Basic = array(1) {
["http"]=> array(1) { ["header"]=> array(1) { [0]=> string(57)
"Authorization: Basic =" } } }
Failed to connect to Reporting Service
Make sure that the url (https://myPublicHostProvider:60004/ReportServer/) and credentials are correct!
SSRS SDK for PHP Configuration Pointers
Make sure your Report Server instance is accessible. Test it by going to the Web Portal or the Service URL.
Provide your credentials. If you are authenticated, then the credentials that you used are valid.
After that, go to the directory \Program Files\Microsoft SQL Server\<INSTANCE_NAME>\Reporting Services\ReportServer and look for the file named rsreportserver.config
Find this snippet
<Authentication>
<AuthenticationTypes>
<RSWindowsNTLM/>
</AuthenticationTypes>
<Authentication>
Add <RSWindowsBasic/> below the <RSWindowsNTLM/> entry.
For your reference, this was the snippet I used to test my instance during configuration.
require_once( 'SSRSReport\bin\SSRSReport.php' );
define( 'UID', 'DOMAIN\Username' );
define( 'PASWD', 'Password' );
define( 'SERVICE_URL', 'http://127.0.0.1/SERVICE_URL/' );
try {
$ssrs_report = new SSRSReport( new Credentials( UID, PASWD ), SERVICE_URL );
$ssrs_report->LoadReport2( '/test', NULL );
$renderAsHTML = new RenderAsHTML();
$result_html = $ssrs_report->Render2(
$renderAsHTML,
PageCountModeEnum::$Estimate,
$Extension,
$MimeType,
$Encoding,
$Warnings,
$StreamIds
);
echo $result_html;
} catch ( SSRSReportException $serviceException ) {
echo $serviceException->GetErrorMessage();
}
It can successfully load the RDL that is located on the load path.
Thanks for your help MiSAKACHi. It pointed me on the right direction. Actually, I'm using a remote dedicated server on a hosting provider on which I don't have access. But the <RSWindowsBasic/> is there as it can load the report with PHP 5.4. Everything is fine under this version.
Thanks to you, I found the issue : I'm using HTTPS and with HTTPS it doesn't work whereas it works when I'm using HTTP !
I'm check with my hosting provider if they can do something.
EDIT - Solution
My hosting provider fixed the issue last year (forgot to post it here). During the time it wasn't fixed, I was still under PHP 5.4.
I paste their original message :
These issues that you describe is because the installed Certificate is a self signed Certificate. New Web Browsers and PHP Version don't accept these Certificates because of Security Risks.
We have changed the Certificate with a official issued Certificate
I just want to add that I was facing issue using the codeplex ssrsphp, therefore I googled and found another sdk, which works perfectly. I'm using php 7+. Here is the link and I'm available if there're any questions related to this.
I've recently created a page on our site where users can upload an image and email it to an email address set up specifically to keep the uploaded documents.
I've tested this myself and it works, with the attachments arriving in gmail as expected.
However, whenever someone from outside uses this feature the attachment in the email is unavailable, or not could not be loaded, when we try to open it.
The code is split between 2 files, a controller and a helper. Here's the code (For the sake of saving some space I've removed all error checks, but in the actual code they are all still in place and not picking up any errors whatsoever):
controller
$helper = [GET HELPER];
/** Upload the file to a temp location so that we can attach it to an email */
$uploader = new Varien_File_Uploader('filename');
$uploader->setAllowedExtensions(array(
'image/jpeg',
'image/jpg',
'image/png',
'application/pdf'
))
->setAllowRenameFiles(true)
->setFilesDispersion(false);
$path = $helper->getFileStorageLocation(); // Will store files in /tmp
if (!is_dir($path))
{
mkdir($path, 0775, true);
}
$uploader->save($path, $_FILES['filename']['name']);
$result = $helper->sendMail($_FILES['filename']['name']);
if ($result)
{
$uploadSuccess = true;
/** Remove the temp file */
unlink($path . DS . $_FILES['filename']['name']);
}
helper
/** Declare variables */
$order = Mage::getModel('sales/order')->load($orderId);
$file_incremented_id = $order->getIncrementId();
$copyTo = $this->getCopyTo();
$copyFrom = $this->getCopyFrom();
$subject = 'proof of upload for ' . $file_incremented_id;
$copyTo = explode(',', $copyTo);
$body = '<span>Please see attachment</span>';
$file = $this->getFileStorageLocation() . DS . $filename; // function receives filename from whatever is calling it
$attachment = file_get_contents($file);
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (!$copyTo)
{
return false;
}
$mail = Mage::getModel('core/email_template');
$mail->setSenderName('Uploader');
$mail->setSenderEmail($copyFrom);
$mail->setTemplateSubject($subject);
$mail->setTemplateText($body);
$mail->getMail()->createAttachment(
$attachement,
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
$file_incremented_id . '.' . $extension // Set order number as file name
);
try
{
$mail->send($copyTo);
return true;
}
catch (Exception $e)
{
return false;
}
Can anyone see anything that might be causing the issue, or think of what it might be based on my explanation of the setup?
So the problem, in the end, was filesize. My fault for not posting the $_FILES variable.
I saw it a bit later and the variable had error = 1, meaning that the file's size was larger than what was allowed by the max_upload_filesize in the php.ini
I'm using the Apache Chemistry CMIS PHP client to upload documents from a local folder to Alfresco Community Edition 5.1 via ATOM. Here's the script I'm using to do so:
require_once ('cmis_repository_wrapper.php');
require_once ('cmis_service.php');
$repo_url = "http://127.0.0.1:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom";
$repo_username = "user";
$repo_password = "pass";
$client = new CMISService($repo_url, $repo_username, $repo_password);
$repo_folder = "/alfrescoFolder";
$source_folder = "localFolder/";
$source_files = array_diff(scandir("$source_folder", 1), array('..', '.'));
$myfolder = $client->getObjectByPath($repo_folder);
foreach($source_files as $file)
{
try
{
$upload = $client->createDocumentFromSource($myfolder->id, $file, "$source_folder/$file");
}
catch(Exception $e)
{
echo "Some error here.";
}
}
This script works fine and documents are uploaded without problem, provided that the document doesn't already exist in the Alfresco repository. For example, let's say I have a document in my Alfresco repository named example.txt, and so, if I try to upload a document from my local folder with the same name, I get a CMIS constraint exception. I dont't know how I can upload a new version of an existing document.
This is what I've tried so far, but it doesn't work:
$objs = $client->getChildren($myfolder->id);
foreach($source_files as $file)
{
foreach($objs->objectList as $obj)
{
if($obj->properties['cmis:name'] == $file)
{
try
{
$checkedout = $client->checkOut($obj->id);
$client->checkIn($checkedout->id);
}
catch(Exception $e)
{
echo "Some error here.";
}
}
else
{
try
{
$upload = $client->createDocumentFromSource($myfolder->id, $file, "$source_folder/$file", array('cmis:objectTypeId'=>'D:ex:document'));
}
catch(Exception $e)
{
echo "Some error here";
}
}
}
}
I get this error:
DEBUG: postEntry: myURL = http://127.0.0.1:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom/checkedoutDEBUG: postEntry: entry_template = {title} {SUMMARY} {CONTENT} {PROPERTIES} DEBUG: postEntry: properties_xml = b549c715-9a9d-427c-bd4b-c6ea29d222cb;1.0 DEBUG: postEntry: hash_values = Array ( [PROPERTIES] => b549c715-9a9d-427c-bd4b-c6ea29d222cb;1.0 [SUMMARY] => {summary} ) DEBUG: postEntry: post_value = b549c715-9a9d-427c-bd4b-c6ea29d222cb;1.0
What's funny is that the document is in fact locked for editing, so I don't really know what's going on. I also don't know if checking out and then checking in a document is how I'm supposed to version a document.
TL;DR
I want to be able to specify that the document I'm uploading is a new version of an existing document. Does anyone know how I can do that?
The function coverage page on the Apache Chemistry web site lists what the CMIS PHP client can and cannot do. Check out, check in, and cancel checkout are all unsupported at the present time. I know they would welcome contributions.
The underlying CMIS specification supports it, of course, so you can either update the library to support checkout/checkin or use the raw binding.
I'm not an expert on CMIS, but I think that this forum post answers the question. See the answer from "jevon" that provides an example and a link to this page (see the "Updating a document" section)
I've recently found out about an alternative CMIS PHP library that implements versioning services, including example usage. I've used it to successfully solve the problem I posted in my question.
Edit: additional information added.
So, to get versioning working, I used the example code provided in the library. The script I used can be used to create new documents and to update and version existing documents. So, here it is:
<?php
require_once(__DIR__ . '/../vendor/autoload.php');
if (!is_file(__DIR__ . '/conf/Configuration.php')) {
die("Please add your connection credentials to the file \"" . __DIR__ . "/conf/Configuration.php\".\n");
} else {
require_once(__DIR__ . '/conf/Configuration.php');
}
$major = (boolean) isset($argv[1]) ? $argv[1] : false;
$httpInvoker = new \GuzzleHttp\Client(
array(
'defaults' => array(
'auth' => array(
CMIS_BROWSER_USER,
CMIS_BROWSER_PASSWORD
)
)
)
);
$parameters = array(
\Dkd\PhpCmis\SessionParameter::BINDING_TYPE => \Dkd\PhpCmis\Enum\BindingType::BROWSER,
\Dkd\PhpCmis\SessionParameter::BROWSER_URL => CMIS_BROWSER_URL,
\Dkd\PhpCmis\SessionParameter::BROWSER_SUCCINCT => false,
\Dkd\PhpCmis\SessionParameter::HTTP_INVOKER_OBJECT => $httpInvoker,
);
$sessionFactory = new \Dkd\PhpCmis\SessionFactory();
// If no repository id is defined use the first repository
if (CMIS_REPOSITORY_ID === null) {
$repositories = $sessionFactory->getRepositories($parameters);
$repositoryId = $repositories[0]->getId();
} else {
$repositoryId = CMIS_REPOSITORY_ID;
}
$parameters[\Dkd\PhpCmis\SessionParameter::REPOSITORY_ID] = $repositoryId;
$session = $sessionFactory->createSession($parameters);
$rootFolder = $session->getObject($session->createObjectId($session->getRootFolder()->getId()));
try {
$document = null;
$stream = \GuzzleHttp\Stream\Stream::factory(fopen($filePath, 'r'));
foreach ($rootFolder->getChildren() as $child) {
if ($child->getName() === $fileName) {
$document = $child;
break;
}
}
if (!$document) {
$properties = array(
\Dkd\PhpCmis\PropertyIds::OBJECT_TYPE_ID => 'cmis:document',
\Dkd\PhpCmis\PropertyIds::NAME => $fileName
);
$document = $session->createDocument($properties, $rootFolder, $stream);
$document = $session->getObject($document);
}
$checkedOutDocumentId = $document->getVersionSeriesCheckedOutId();
if ($checkedOutDocumentId) {
$checkedOutDocumentId = $session->createObjectId($checkedOutDocumentId);
} else {
$checkedOutDocumentId = $document->checkOut();
}
$checkedInDocumentId = $session->getObject($checkedOutDocumentId)->checkIn(
$major,
array(
\Dkd\PhpCmis\PropertyIds::DESCRIPTION => 'New description'
),
$stream,
'Comments'
);
} catch (\Dkd\PhpCmis\Exception\CmisVersioningException $e) {
echo "********* ERROR **********\n";
echo $e->getMessage() . "\n";
echo "**************************\n";
exit();
}
I'm uploading a file through Symfony2 and I am trying to rename original in order to avoid override the same file. This is what I am doing:
$uploadedFile = $request->files;
$uploadPath = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/';
try {
$uploadedFile->get('avatar')->move($uploadPath, $uploadedFile->get('avatar')->getClientOriginalName());
} catch (\ Exception $e) {
// set error 'can not upload avatar file'
}
// this get right filename
$avatarName = $uploadedFile->get('avatar')->getClientOriginalName();
// this get wrong extension meaning empty, why?
$avatarExt = $uploadedFile->get('avatar')->getExtension();
$resource = fopen($uploadPath . $uploadedFile->get('avatar')->getClientOriginalName(), 'r');
unlink($uploadPath . $uploadedFile->get('avatar')->getClientOriginalName());
I am renaming file as follow:
$avatarName = sptrinf("%s.%s", uniqid(), $uploadedFile->get('avatar')->getExtension());
But $uploadedFile->get('avatar')->getExtension() is not giving me the extension of the uploaded file so I give a wrong filename like jdsfhnhjsdf. without extension, Why? What is the right way to rename file after or before move to the end path? Any advice?
Well, the solution is really simple if you know it.
Since you moved the UploadedFile, the current object instance cannot be used anymore. The file no longer exists, and so the getExtension will return in null. The new file instance is returned from the move.
Change your code to (refactored for clarity):
$uploadPath = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/';
try {
$uploadedAvatarFile = $request->files->get('avatar');
/* #var $avatarFile \Symfony\Component\HttpFoundation\File\File */
$avatarFile = $uploadedAvatarFile->move($uploadPath, $uploadedAvatarFile->getClientOriginalName());
unset($uploadedAvatarFile);
} catch (\Exception $e) {
/* if you don't set $avatarFile to a default file here
* you cannot execute the next instruction.
*/
}
$avatarName = $avatarFile->getBasename();
$avatarExt = $avatarFile->getExtension();
$openFile = $avatarFile->openFile('r');
while (! $openFile->eof()) {
$line = $openFile->fgets();
// do something here...
}
// close the file
unset($openFile);
unlink($avatarFile->getRealPath());
(Code not tested, just wrote it) Hope it helps!