sugarCRM add document from script - php

I am trying to add Document to Sugar object (client) from PHP script. I have a directory of files (on the same server where sugarCRM is installed) and xls with sugar objec ID and filename). PHP Script should add correct filename to specific sugar object (identified with ID). I can read XLS this is no problem, I can also get instance of sugar object (retrieve by ID), but I have no idea how can I assign the file to sugar. I was trying with Document, and upload_file.php, but those seem to be usable with uploading single file with html Form.
How can I automate this task, copy files with correct filename to cache\upload and create Document related to my Customer from PHP Script? I would prefer not to use SOAP if it's not necesarry...
Edit:
I was able to save document and revision, but something is wrong, and file can't be downloaded from browser ("incorrect call to file")
My Code so far is:
require_once('include/upload_file.php');
$upload_file = new UploadFile('uploadfile');
$document->filename = 'robots.txt';
$document->document_name = 'robots.txt';
$document->save();
$contents = file_get_contents ($document->filename);
$revision = new DocumentRevision;
$revision->document_id = $document->id;
$revision->file = base64_encode($contents);
$revision->filename = $document->filename;
$revision->revision = 1;
$revision->doc_type = 'Sugar';
$revision->file_mime_type = 'text/plain';
$revision->save();
$document->revision_id = $revision->id;
$document->save();
$destination = clean_path($upload_file->get_upload_path($document->id));
$fp = sugar_fopen($destination, 'wb');
if( !fwrite($fp, $contents) ){
die("ERROR: can't save file to $destination");
}
fclose($fp);

WORKS! I Hope this will help someone
I have corrected 3 lines from code abowe:
//$document->revision_id = $revision->id;
//$document->save();
$destination = clean_path($upload_file->get_upload_path($revision->id));

Related

Mysql file upload and pdf browser viewer failing to work

I am trying to build an interface with between my Wordpress page and my practice management software. When I upload files directly to my practice management software a physical copy shows up in the patient file. When browsing files within the software, on first click, I am able to view them in a browser based pdf viewer. If I click again on the file link, the file downloads and opens on my PC's PDF software.
PROBLEM: currently my file uploads to the server and a physical file is placed in the patient file. When browsing files it will not show up in my PDF viewer. It downloads to my PC on the first click and opens into my PDF software. However, the same file, when uploaded directly to the software behaves as expected.
I see no difference in the two files. So I assume there must be a problem with the $contents variable in my query. I am only working with PDF files. To upload attachments in my private messaging software I am using the following code:
function action_getmsgup($uploadid) {
global $wpdb, $out;
$query = $wpdb->prepare("SELECT ID, post_mime_type, guid FROM {$wpdb->prefix}posts WHERE ID = %d", array($uploadid));
$rows = $wpdb->get_results($query, ARRAY_A);
foreach ($rows as $row) {
$url = $row['guid'];
$filename = basename($url);
$path = parse_url($url, PHP_URL_PATH); // just the path part of the URL
$parts = explode('/', $path); // all the components
$parts = array_slice($parts, -6); // the last six
$path = implode('/', $parts);
$filepath = ABSPATH . $path;
// Get file contents and make a blob.
$tmpfile = fopen($filepath, "r");
$contents = fread($tmpfile, filesize($filepath));
$out['filename'] = $filename;
$out['mimetype'] = $row['mimetype'];
$out['contents'] = $contents;
}
}
QUESTION: Is there a problem with my upload method that is not filling $contents correctly?

How to save file in subfolder using php

I have a script with a mysql query which saves a file called invoice.xml every day automatically by running a cron job. In case no data is found a no_orders.txt is saved.
I would like this file not be saved to the same folder as the script.php file is in but to a subfolder called invoices.
The renaming of the old invoice.xml is done with the following code
// rename old file
$nowshort = date("Y-m-d");
if(file_exists('invoice.xml')) {
rename('invoice.xml','invoice_'.$nowshort.'.xml');
}
The saving is done with the following code:
if($xml1 !='') {
$File = "invoice.xml";
$Handle = fopen($File, 'w');
fwrite($Handle, $xml1);
print "Data Written - ".$nowMysql;
fclose($Handle);
#print $xml;
die();
} else {
print "No new orders - ".$nowMysql;
$File = "no_orders_".$nowshort.".txt";
$Handle = fopen($File, 'w');
fclose($Handle);
die();
}
Could I please get assistance how to save this file to a subfolder. Also the renaming of the existing file would need to be within the subfolder then. I have already tried with possibilities like ../invoice/invoice.xml but unfortunately without any success.
Thank you
Just give the path of file 'invoice.xml' to $File.
Otherwise create some $Dir object which will point to Folder named 'invoice', then use accordingly
Use __DIR__ magic constant to retrieve your script.php directory, then you can append /invoice/invoice.xml .
Example if path to your script php something like this:
/var/www/path/to/script.php
$currentDir = __DIR__; //this wil return /var/www/path/to
$invoicePath = $currentDir.'/invoice/invoice.xml';

Error in creating pdf file using google drive sdk

I am using google drive sdk for uploading files and also I think i can possibly create pdf file on it - so I tweak the code. So in my code, I generate HTML text format to be used as content for the PDF to be created in google drive.
this is a snip-it of my code.
$subcontent = "<h1>Hello World</h1><p>some text here</p>";
$file = new Google_DriveFile();
....
$mkFile = $this->_service->files->insert($file, array('data' => $subcontent));
$createdFile = $fileupload->nextChunk($mkFile, $subcontent); // I got error on this line
$this->_service->files->trash( $createdFile['id'] );
...
when I run the code I got an error based the comment I put in my code above:
Catchable fatal error: Argument 1 passed to Google_MediaFileUpload::nextChunk() must be an instance of Google_HttpRequest, array given, called in /home/site/public_html/mywp/wp-content/plugins/mycustomplugin/functions.php on line 689 and defined in /home/site/public_html/mywp/wp-content/plugins/mycustomplugin/gdwpm-api/service/Google_MediaFileUpload.php on line 212
I have no idea what should be the value in the 2nd parameter in nextChunk, in the original code it goes like this:
.....
$handle = fopen($path, "rb");
while (!$status && !feof($handle)) {
$max = false;
for ($i=1; $i<=$max_retries; $i++) {
$chunked = fread($handle, $chunkSize);
if ($chunked) {
$createdFile = $fileupload->nextChunk($mkFile, $chunked);
break;
}elseif($i == $max_retries){
$max = true;
}
}
.....
my question is that, how can I deal with this error? and how can I successfully create pdf file in google drive by tweaking this code? because I need the created file ID of the file to be linked in my post.
Thanks in advance...
You shouldn't be passing $mkFile to nextChunk. Have a read though the resumable uploads section in the documentation.
You have more fundamental issues than that though. For instance, the insert call you do already sets the data for the file. There is no need to do anything with nextChunk unless you are doing resumable uploads. Follow the "Multipart File Upload" section of the above doc to fix your insert statement and just remove the nextChunk line.

Check if file exists in .tar using PHP

In my program I need to read .png files from a .tar file.
I am using pear Archive_Tar class (http://pear.php.net/package/Archive_Tar/redirected)
Everything is fine if the file im looking for exists, but if it is not in the .tar file then the function timouts after 30 seconds. In the class documentation it states that it should return null if it does not find the file...
$tar = new Archive_Tar('path/to/mytar.tar');
$filePath = 'path/to/my/image/image.png';
$file = $tar->extractInString($filePath); // This works fine if the $filePath is correct
// if the path to the file does not exists
// the script will timeout after 30 seconds
var_dump($file);
return;
Any suggestions on solving this or any other library that I could use to solve my problem?
The listContent method will return an array of all files (and other information about them) present in the specified archive. So if you check if the file you wish to extract is present in that array first, you can avoid the delay that you are experiencing.
The below code isn't optimised - for multiple calls to extract different files for example the $files array should only be populated once - but is a good way forward.
include "Archive/Tar.php";
$tar = new Archive_Tar('mytar.tar');
$filePath = 'path/to/my/image/image.png';
$contents = $tar->listContent();
$files = array();
foreach ($contents as $entry) {
$files[] = $entry['filename'];
}
$exists = in_array($filePath, $files);
if ($exists) {
$fileContent = $tar->extractInString($filePath);
var_dump($fileContent);
} else {
echo "File $filePath does not exist in archive.\n";
}

PHP Foreach and jQuery

I am working on a piece of code that I am wanting to "spice" up with jQuery but I can't think of a way to actually make it work. I am sure its simple, I just need a little advice to get me going.
I am wanting to create a piece of code that makes an Ajax request out to start a big loop that will download files and then upload them to an S3 bucket of mine. The place where I am stuck is I am wanting to send back a request back to the browser everytime a file is uploaded and output a string of text to the screen upon completion.
I don't have any of the frontend code working... just trying to get my head wrapped around the logic first... any ideas?
PHP Backend Code:
<?php
public function photos($city) {
if(isset($city))
$this->city_name = "{$city}";
// grab data array from Dropbox folder
$postcard_assets = $this->conn->getPostcardDirContent("{$this->city_name}", "Photos", TRUE);
$data = array();
foreach($postcard_assets['contents'] as $asset) {
//only grab contents in root folder... do not traverse into sub folders && make sure the folder is not empty
if(!$asset['is_dir'] && $asset['bytes'] > 0) {
// get information on file
$file = pathinfo($asset['path']);
// download file from Dropbox
$original_file = $this->conn->downloadFile(str_replace(" ", "%20", $asset['path']));
// create file name
$file_name = $this->cleanFileName($file['basename']);
// write photo to TMP_DIR ("/tmp/photos/") for manipulation
$fh = fopen(self::TMP_DIR . $file_name, 'w');
fwrite($fh, $original_file);
fclose($fh);
// Resize photo
$this->resize_photo($file_name);
// hash file name
$raw_file = sha1($file_name);
// create S3 hashed name
$s3_file_name = "1_{$raw_file}.{$file['extension']}";
// Upload manipulated file to S3
$this->s3->putObject($s3_file_name, file_get_contents(self::TMP_DIR . $file_name), $this->photo_s3_bucket, 'public-read');
// check to see if file exists in S3 bucket
$s3_check = $this->s3->getObjectInfo($s3_file_name, $this->photo_s3_bucket);
// if the file uploaded successully to S3, load into DB
if($s3_check['content-length'] > 0) {
$data['src'] = $s3_file_name;
$data['width'] = $this->width;
$data['height'] = $this->height;
Photo::create_postcard_photo($data, "{$this->city_name}");
// Now that the photo has been uploaded to S3 and saved in the DB, remove local file for cleanup
unlink(self::TMP_DIR . $file_name);
echo "{$file_name} uploaded to S3 and resized!<br />";
}
}
}
// after loop is complete, kill script or nasty PHP header warnings will appear
exit();
}
?>
The main problem is that with PHP, the output is buffered so it won't return a line at a time. You can try and force the flush but it's not always reliable.
You could add an entry to the DB for each file that is exchanged and create a seperate API to get the details of what has completed.
Generally, Jquery will wait till the request has finished before it allows you to manipulate data from a HTTP request.

Categories