We are trying to use this plugin code in our php script
https://github.com/wp-plugins/google-drive-wp-media/tree/master/gdwpm-api
We modified code and using successfully in our project, But its working only for small files, When we upload large files to google drive files showing only in KB size.
May be only last chunk is uploaded to google drive for large files,
We tried to solve this error but failed, Please check and tell what we are doing wrong.
Here is our modified files.
index.php
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script type='text/javascript' src='http://myweb.com/wp-admin/load-scripts.php?c=0&load%5B%5D=jquery-core,jquery-migrate,utils,plupload&ver=4.4.2'></script>
<div class="container">
<div id="tabs-2" aria-labelledby="ui-id-12" class="ui-tabs-panel ui-widget-content ui-corner-bottom" role="tabpanel" aria-hidden="false" style="display: block;">
<p style="display: flex; align-items: center;">
Select folder: <select id="folder_pilian_aplod" name="folder_pilian_aplod" style="display: block;"><option value="0B0pm8dZPprJ-cElGclFoc2tVZ1E">testdata</option></select>
</p>
<!--<p>Short Description: <input type="text" name="gdwpm_aplod_deskrip" value="" size="65" placeholder="Optional"></p>-->
<p>
</p><ul>
<li><dfn>Accepted Media MIME types: */*</dfn>
<!-- <br /> <dfn>All Filetypes are allowed.</dfn>
--></li>
</ul>
<p></p>
<ul id="filelist"></ul>
<br>
<button id="gdwpm_tombol_bersih" style="display:none;float:right;" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" role="button"><span class="ui-button-icon-primary ui-icon ui-icon-grip-dotted-horizontal"></span><span class="ui-button-text">Clear List</span></button>
<div id="gdwpm_upload_container"><p id="gdwpm-pilih-kt" style="position: relative;">Choose your files:
<a id="gdwpm_tombol_browse" href="javascript:;" style="position: relative; z-index: 1;"><button id="gdwpm_tombol_bk_folder" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" role="button"><span class="ui-button-icon-primary ui-icon ui-icon-folder-open"></span><span class="ui-button-text">Browse</span></button></a><div id="html5_1asc3hchetiq1f6q14bnli91i4k3_container" class="moxie-shim moxie-shim-html5" style="position: absolute; top: 5px; left: 123px; width: 92px; height: 16px; overflow: hidden; z-index: 0;"><input id="html5_1asc3hchetiq1f6q14bnli91i4k3" type="file" style="font-size: 999px; opacity: 0; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;" multiple="" accept="" class="ui-corner-all"></div></p>
<input type="checkbox" id="gdwpm_cekbok_masukperpus" name="gdwpm_cekbok_masukperpus" value="1" checked="" class="ui-corner-all"> Add to Media Library. (just linked to, all files still remain in Google Drive)<!-- (Image only: <i>*.jpg, *.jpeg, *.png, & *.gif</i>)--><p>
<a style="" id="gdwpm_start-upload" href="javascript:;"><button id="gdwpm_tombol_upload" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" role="button"><span class="ui-button-icon-primary ui-icon ui-icon-arrowthickstop-1-n"></span><span class="ui-button-text">Upload to Google Drive</span></button></a>
</p>
<pre id="console"></pre>
</div>
<div id="gdwpm_loding_128" style="display:none;"><center>
<img src="http://localhost/wordpress/wp-content/plugins/google-drive-wp-media/images/animation/gdwpm_loader_128.gif"><br>Uploading...<br><small id="respon_progress"></small></center></div>
<script type="text/javascript">
var uploader = new plupload.Uploader({
browse_button: 'gdwpm_tombol_browse',
url: 'uploader.php',
chunk_size: '700kb',
max_retries: 3 });
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
var html = '';
plupload.each(files, function(file) {
html += '<li id="' + file.id + '"><code>' + file.name + '</code> (' + plupload.formatSize(file.size) + ') <span class="hasilprog"></span> <input type="text" id="' + file.id + 'gdwpm_aplod_deskrip" name="' + file.id + 'lod_deskrip" value="" size="55" placeholder="Short Description (optional) *Alphanumeric*"><hr></li>';
});
document.getElementById('filelist').innerHTML += html;
jQuery('#console').empty();
jQuery('#gdwpm_tombol_bersih').hide();
jQuery('#gdwpm_start-upload').show();
jQuery('#infopraupload').remove();
});
uploader.bind('UploadProgress', function(up, file) {
document.getElementById(file.id).getElementsByClassName('hasilprog')[0].innerHTML = "<dfn>" + file.percent + "%</dfn> <small>" + jQuery('#' + file.id + 'gdwpm_aplod_deskrip').val().replace(/[^\w\s-]/gi, '') + "</small>";
jQuery('#' + file.id + 'gdwpm_aplod_deskrip').hide();
jQuery('#gdwpm_upload_container').hide();
jQuery('#gdwpm_loding_128').show();
jQuery('#gdwpm_tombol_bersih').hide();
});
uploader.bind('Error', function(up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
jQuery('#gdwpm_upload_container').show();
jQuery('#gdwpm_loding_128').hide();
jQuery('#gdwpm_start-upload').hide();
jQuery('#gdwpm_tombol_bersih').show();
});
document.getElementById('gdwpm_start-upload').onclick = function() {
uploader.start();
};
uploader.bind('FileUploaded', function(up, file, response ) {
response=response["response"];
jQuery('#console').html(response);
var totalspan = document.getElementById('filelist').getElementsByClassName('hasilprog').length;
var totaldfn = document.getElementById('filelist').getElementsByTagName('dfn').length;
if(totalspan == totaldfn){
jQuery('#gdwpm_upload_container').show();
jQuery('#gdwpm_tombol_bersih').show();
jQuery('#gdwpm_loding_128').hide();
}
jQuery('#gdwpm_start-upload').hide();
jQuery('#respon_progress').empty();
if(jQuery('#gdwpm_folder_anyar').val() != ''){
jQuery('#gdwpm_info_folder_baru').show();
}
});
uploader.bind('BeforeUpload', function (up, file) {
up.settings.multipart_params = {gdpwm_nm_bks: jQuery("#folder_pilian_aplod option:selected").text(), gdpwm_nm_id: jQuery('select[name=folder_pilian_aplod]').val(),
gdpwm_nm_br: jQuery('#gdwpm_folder_anyar').val(), gdpwm_sh_ds: jQuery('#' + file.id + 'gdwpm_aplod_deskrip').val().replace(/[^\w\s-]/gi, ''), gdpwm_med_ly: jQuery('#gdwpm_cekbok_masukperpus:checked').val(),
gdpwm_nama_file: file.name};
});
uploader.bind('ChunkUploaded', function(up, file, info) {
response=info["response"];
jQuery('#respon_progress').empty();
jQuery('#console').html(response);
jQuery('#respon_progress').html('[Chunked: ' + info["offset"] + ' of ' + info["total"] + ' bytes]');
//jQuery('#gdwpm_upload_container').show();
//jQuery('#gdwpm_loding_128').hide();
//jQuery('#gdwpm_start-upload').hide();
});
</script>
</div>
</div>
uploader.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once 'gdwpm-api/Google_Client.php';
require_once 'gdwpm-api/contrib/Google_DriveService.php';
require_once 'gwbp.php';
set_time_limit(600000000);
global $cek_kunci, $gdwpm_opt_akun, $gdwpm_service, $gdwpm_apiConfig;
if (empty($_FILES) || $_FILES["file"]["error"]) {
die('<div class="error"><p>Oops.. error, upload failed! '.$_FILES["file"]["error"].'</p></div>');
}
if (isset($_REQUEST["gdpwm_nama_file"])) {
$filename = $_REQUEST["gdpwm_nama_file"];
} elseif (!empty($_FILES)) {
$filename = $_FILES["file"]["name"];
} else {
$filename = uniqid("file_");
}
$targetDir = ini_get("upload_tmp_dir");
$maxFileAge = 5000 * 3600; // Temp file age in seconds
// Create target dir
if (!file_exists($targetDir)) {
//#mkdir($targetDir);
if (!file_exists($targetDir = sys_get_temp_dir())){
$upload_dir = wp_upload_dir();
if (!file_exists($targetDir = $upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'gdwpm-tmp')) {
#mkdir($targetDir);
}
}
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $filename;
// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
die('<div class="error"><p>Oops.. error. Failed to open temp directory.</p></div>');
}
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
// If temp file is current file proceed to the next
if ($tmpfilePath == "{$filePath}.part") {
continue;
}
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
#unlink($tmpfilePath);
}
}
closedir($dir);
// Open temp file
if (!$out = #fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
die('<div class="error"><p>Oops.. error. Failed to open output stream.</p></div>');
}
if (!empty($_FILES)) {
if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
die('<div class="error"><p>Oops.. error. Failed to move uploaded file.</p></div>');
}
// Read binary input stream and append it to temp file
if (!$in = #fopen($_FILES["file"]["tmp_name"], "rb")) {
die('<div class="error"><p>Oops.. error. Failed to open input stream.</p></div>');
}
} else {
if (!$in = #fopen("php://input", "rb")) {
die('<div class="error"><p>Oops.. error. Failed to open input stream.</p></div>');
}
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
#fclose($out);
#fclose($in);
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
if($filePath){
rename("{$filePath}.part", $filePath);
}else{
$filePath = $_FILES["file"]["tmp_name"];
}
$gdwpm_opt_imel = 'myemail#gmail.com';
$gdwpm_opt_klaen_aidi = 'myid';
$gdwpm_opt_nama_service = 'uploadservice#m.gserviceaccount.com';
$gdwpm_opt_kunci_rhs = 'UploadFiles-f15596286d09.p12';
$gdwpm_opt_akun = array($gdwpm_opt_imel, $gdwpm_opt_klaen_aidi, $gdwpm_opt_nama_service, $gdwpm_opt_kunci_rhs);
$gdwpm_service = new GDWPMBantuan( $gdwpm_opt_akun[1], $gdwpm_opt_akun[2], $gdwpm_opt_akun[3] );
//$mime_berkas_arr = wp_check_filetype($filename);
$finfo = new finfo;
$mime_berkas_arr['type'] = $finfo->file($filePath, FILEINFO_MIME);
//print_r($mime_berkas_arr);
$mime_berkas = $mime_berkas_arr['type'];
if(empty($mime_berkas)){$mime_berkas = $_FILES['file']['type'];}
$folder_ortu = preg_replace("/[^a-zA-Z0-9]+/", " ", $_POST['gdpwm_nm_br']);
$folder_ortu = trim(($folder_ortu));
$folderId = $_POST['gdpwm_nm_id'];
$nama_polder = $_POST['gdpwm_nm_bks'];
if($folder_ortu != ''){
//cek folder array id namafolder
$last_folder = get_option('gdwpm_new_folder_kecing');
if($folder_ortu != $last_folder[1]){
$folderId = $gdwpm_service->getFolderIdByName( $folder_ortu );
if( $folderId ) { update_option('gdwpm_new_folder_kecing', array($folderId, $folder_ortu)); }
$nama_polder = $folder_ortu;
}else{
$folderId = $last_folder[0];
$nama_polder = $last_folder[1];
}
}
$content = $_POST['gdpwm_sh_ds'];
if( ! $folderId ) {
$folderId = $gdwpm_service->createFolder( $folder_ortu );
$gdwpm_service->setPermissions( $folderId, $gdwpm_opt_akun[0] );
update_option('gdwpm_new_folder_kecing', array($folderId, $nama_polder));
}
if(strpos($mime_berkas_arr['type'], 'image') !== false){
// cek gambar if img auto create thumb .. array('checked', '', '122', '122', 'false');
$gdwpm_img_thumbs = get_option('gdwpm_img_thumbs');
// ITUNG DIMENSI
$image = wp_get_image_editor( $filePath );
if ( !is_wp_error( $image ) ) {
$ukuran_asli = $image->get_size(); // $ukuran_asli['width']; $ukuran_asli['height'];
}
$idthumb_w_h = '';
if ($gdwpm_img_thumbs[0] == 'checked'){
$folderId_thumb = $gdwpm_img_thumbs[1];
if(empty($folderId_thumb) || $folderId_thumb == ''){
//$folderId_thumb = $gdwpm_service->getFolderIdByName( 'gdwpm-thumbnails' );
//if(!$folderId_thumb){
$folderId_thumb = $gdwpm_service->createFolder( 'gdwpm-thumbnails' );
$gdwpm_service->setPermissions( $folderId_thumb, $gdwpm_opt_akun[0] );
//}
$gdwpm_img_thumbs[1] = trim($folderId_thumb);
update_option('gdwpm_img_thumbs', $gdwpm_img_thumbs);
}
if ( $ukuran_asli ) {
if($gdwpm_img_thumbs[4] == 'true'){
$image->resize( $gdwpm_img_thumbs[2], $gdwpm_img_thumbs[3], true );
}else{
$image->resize( $gdwpm_img_thumbs[2], $gdwpm_img_thumbs[3], false );
}
$img = $image->save(); // path, file, mime-type
$filename_thumb = $img['file'];
$filePath_thumb = $img['path'];
$mime_berkas_thumb = $img['mime-type'];
$imgwidth_thumb = $img['width'];
$imgheight_thumb = $img['height'];
}
$fileParent_thumb = new Google_ParentReference();
$fileParent_thumb->setId( $folderId_thumb );
$fileId_thumb = $gdwpm_service->createFileFromPath( $filePath_thumb, $filename_thumb, $content, $fileParent_thumb );
$gdwpm_service->setPermissions( $fileId_thumb, 'me', 'reader', 'anyone' );
$idthumb_w_h = 'thumbId:' . $fileId_thumb . ' thumbWidth:' . $imgwidth_thumb . ' thumbHeight:' . $imgheight_thumb;
}
$gdwpm_sizez_meta = 'selfWidth:' . $ukuran_asli['width'] . ' selfHeight:' . $ukuran_asli['height'] . ' ' . $idthumb_w_h;
#unlink($filename_thumb);
}else{
$gdwpm_sizez_meta = '';
}
$fileParent = new Google_ParentReference();
$fileParent->setId( $folderId );
//$fileId = $gdwpm_service->createFileFromPath( $_FILES["file"]["tmp_name"], $filename, $content, $fileParent );
$fileId = $gdwpm_service->createFileFromPath( $filePath, $filename, $content, $fileParent );
if($fileId){
$gdwpm_service->setPermissions( $fileId, 'me', 'reader', 'anyone' );
if(strpos($mime_berkas_arr['type'], 'image') !== false && !empty($gdwpm_sizez_meta)){
$gdwpm_service->insertProperty($fileId, 'gdwpm-sizes', $gdwpm_sizez_meta);
}
$sukinfo = '';
$metainfo = '';
if(!empty($mime_berkas) && isset($_POST['gdpwm_med_ly']) == '1'){
//gdwpm_ijin_masuk_perpus($mime_berkas, $filename, $fileId, $content, $nama_polder, $gdwpm_sizez_meta, $metainfo);
$sukinfo = ' and added into your Media Library';
}
$to = "myemail#gmail.com";
$subject = "File Uploaded";
$txt = $filename." successfully uploaded to ".$nama_polder;
$headers = "From: webmaster#gmail.com";
mail($to,$subject,$txt,$headers);
echo '<div class="updated"><p>'.$filename.' (<strong>'.$fileId.'</strong>) successfully uploaded to <strong>'.$nama_polder.'</strong>'.$sukinfo.'.</p></div>';
}else{
echo '<div class="error"><p>Failed to upload <strong>'.$filename.'</strong> to Google Drive.</p></div>';
}
#unlink($filePath);
}
?>
gwbp.php
<?php
class GDWPMBantuan {
protected $scope = array('https://www.googleapis.com/auth/drive');
private $_service;
public function __construct( $clientId, $serviceAccountName, $key ) {
$client = new Google_Client();
$client->setApplicationName("Google Drive WP Media");
$client->setClientId( $clientId );
$client->setAssertionCredentials( new Google_AssertionCredentials(
$serviceAccountName,
$this->scope,
$this->getKonten( $key ) )
);
$this->_service = new Google_DriveService($client);
}
public function __get( $name ) {
return $this->_service->$name;
}
public function getKonten( $url ) {
if(function_exists('curl_version')){
$data = curl_init();
curl_setopt($data, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($data, CURLOPT_URL, $url);
curl_setopt($data, CURLOPT_FOLLOWLOCATION,TRUE);
curl_setopt($data, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($data, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($data, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201');
$hasil = curl_exec($data);
curl_close($data);
return $hasil;
}else{
$hasil = file_get_contents(str_replace(' ', '%20', $url));
return $hasil;
}
}
public function getAbout( ) {
return $this->_service->about->get();
}
public function buangFile( $fileId ) {
$result = $this->_service->files->delete($fileId);
if(empty($result)){
return true;
}else{
return false;
}
}
public function getNameFromId( $fileId ) {
$file_proper = $this->_service->files->get($fileId);
$file_name = $file_proper->title;
return $file_name;
}
public function insertProperty($fileId, $key, $value, $visibility = 'PUBLIC') {
if(!empty($value) || $value != ''){
$newProperty = new Google_Property();
$newProperty->setKey($key);
$newProperty->setValue($value);
$newProperty->setVisibility($visibility);
return $this->_service->properties->insert($fileId, $newProperty);
}else{
return false;
}
}
public function createFileFromPath( $path, $fileName, $description, Google_ParentReference $fileParent = null ) {
$finfo = new finfo;
$mimeType['type'] = $finfo->file($path, FILEINFO_MIME);
// $mimeType = wp_check_filetype($fileName);
$file = new Google_DriveFile();
$file->setTitle( $fileName );
$file->setDescription( $description );
$file->setMimeType( $mimeType['type'] );
if( $fileParent ) {
$file->setParents( array( $fileParent ) );
}
// $gdwpm_opsi_chunk = get_option('gdwpm_opsi_chunk');
$gdwpm_opsi_chunk=array('local' => array(
'cekbok' =>'checked',
'chunk' => 700,
'retries' => 3
),
'drive' => array
(
'cekbok' => 'checked',
'chunk' => 2,
'retries' => 3
)
);
$chunks = $gdwpm_opsi_chunk['drive']['chunk'];
$max_retries = (int) $gdwpm_opsi_chunk['drive']['retries'];
$chunkSize = (1024 * 1024) * (int) $chunks; // 2mb chunk
$fileupload = new Google_MediaFileUpload($mimeType['type'], null, true, $chunkSize);
$fileupload->setFileSize(filesize($path));
$mkFile = $this->_service->files->insert($file, array('mediaUpload' => $fileupload));
$status = false;
$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;
}
}
if($max){
if($createdFile){
$this->_service->files->trash( $createdFile['id'] );
}
$createdFile = false;
break;
}
}
fclose($handle);
if($createdFile){
return $createdFile['id'];
}else{
return false;
}
}
public function createFolder( $name ) {
$file = new Google_DriveFile();
$file->setTitle( $name );
$file->setMimeType( 'application/vnd.google-apps.folder' );
$createdFolder = $this->_service->files->insert($file, array('mimeType' => 'application/vnd.google-apps.folder'));
return $createdFolder['id'];
}
public function setPermissions( $fileId, $value, $role = 'writer', $type = 'user' ) {
$perm = new Google_Permission();
$perm->setValue( $value );
$perm->setType( $type );
$perm->setRole( $role );
return $this->_service->permissions->insert($fileId, $perm);
}
public function getFolderIdByName( $name ) {
$parameters = array('q' => "mimeType = 'application/vnd.google-apps.folder'", 'maxResults' => 50);
$files = $this->_service->files->listFiles($parameters);
foreach( $files['items'] as $item ) {
if( $item['title'] == $name ) {
return $item['id'];
break;
}
}
return false;
}
public function getFilesInFolder($folderId, $maxResults, $pageToken = '', $in_type = 'radio') {
if($in_type == 'radio'){
$div_id = 'hasil';
$id_max = 'maxres';
$id_folid = 'folid';
$id_tblpagi = 'paginasi';
$div_hal = 'halaman';
$div_pagi = 'vaginasi';
$opsi_kecing = 'gdwpm_kecing_hal';
$in_name = 'gdwpm_berkas_terpilih[]';
}elseif($in_type == 'checkbox'){
$div_id = 'hasil_del';
$id_max = 'maxres_del';
$id_folid = 'folid_del';
$id_tblpagi = 'paginasi_del';
$div_hal = 'halaman_del';
$div_pagi = 'vaginasi_del';
$opsi_kecing = 'gdwpm_kecing_hal_del';
$in_name = 'gdwpm_buang_berkas_terpilih[]';
}else{
$in_type = 'checkbox';
$div_id = 'hasil_gal';
$id_max = 'maxres_gal';
$id_folid = 'folid_gal';
$id_tblpagi = 'paginasi_gal';
$div_hal = 'halaman_gal';
$div_pagi = 'vaginasi_gal';
$opsi_kecing = 'gdwpm_kecing_hal_gal';
$in_name = 'gdwpm_berkas_gallery[]';
}
//setup 1st pagetokn is always enpty n create pagintion butt
$haldepan = 1;
////$hal = '<input type="hidden" id="maxres" value="'.$maxResults.'" /><button id="halaman" value="">'.$haldepan.'</button>';
$parameters = array('maxResults' => $maxResults);
$pageTokenInput = $pageToken;
$gdwpm_kecing_hal = get_option($opsi_kecing);
if (empty($pageToken) || $pageToken == '') {
// generate halaman
//if($gdwpm_kecing_hal || !empty($gdwpm_kecing_hal)){
//delete_option($opsi_kecing);
//}
$gdwpm_kecing_hal = array();
$errormes = '';
$halarr = array($haldepan => 'bantuanhalamansatu');
do {
$haldepan++;
try {
if($haldepan == 1){$pageToken = '';} //halman prtama pokoke token kudu kosong
$parameters['pageToken'] = $pageToken;
$children = $this->_service->children->listChildren($folderId, $parameters);
$pageToken = $children->getNextPageToken();
if($pageToken){
//$hal .= ' <button id="halaman" value="'.$pageToken.'">'.$haldepan.'</button>';
$halarr[$haldepan] = $pageToken;
if($haldepan % 10 == 0){sleep(1);}
//}elseif($haldepan > 1){
//cek n buang halman trakir jika kosong
//$parameters['pageToken'] = $halarr[$haldepan - 1];
//$files = $this->_service->children->listChildren($folderId, $parameters);
//$result = array();
//if(count(array_merge($result, $files->getItems())) < 1){
//unset($halarr[$haldepan - 1]);
//}
}
} catch (Exception $e) {
$errormes = "<kbd>An error occurred: " . $e->getMessage() . "</kbd>";
$haldepan -= 1;
$pageToken = $halarr[$haldepan]; //NULL;
sleep(1);
}
} while ($pageToken);
unset($parameters['pageToken']);
$gdwpm_kecing_hal[$folderId] = $halarr;
update_option($opsi_kecing, $gdwpm_kecing_hal);
}else{
$parameters['pageToken'] = $pageToken;
}
$daftarfile = '';
if(count($halarr) <= 1 || $pageToken != ''){
if($pageToken == 'bantuanhalamansatu'){
unset($parameters['pageToken']);
}
$folder_proper = $this->_service->files->get($folderId);
$folder_name = $folder_proper->title;
$i = 0;
$daftarfile = '<div id="'.$div_id.'"><table id="box-table-a" summary="File Folder" class="'.$id_tblpagi.'"><thead><tr><th scope="col"><span class="ui-icon ui-icon-check"></span></th><th scope="col">File ID</th><th scope="col">Title</th><!--<th scope="col">Description</th>--><th scope="col">Size</th><th scope="col">Action</th></tr></thead>';
$children = $this->_service->children->listChildren($folderId, $parameters);
foreach ($children->getItems() as $child) {
$i++; if($i == 1 && $in_type == 'radio'){$checked = 'checked';}else{$checked = '';}
if($maxResults != $i && $maxResults > 30 && $i % 20 == 0){sleep(1);}
$fileId = $child->getId();
$file = $this->_service->files->get($fileId); //getDescription getMimeType
$file_mime = $file->getMimeType();
$file_title = $file->getTitle();
$file_desc = $file->getDescription();
$file_icon = $file->getIconLink();
$file_md5 = $file->getMd5Checksum();
$file_size = size_format($file->getFileSize(), 2);
$file_thumb = $file->getThumbnailLink(); // str_replace('=s220', '=s300', $file->getThumbnailLink());
$view = 'Download';
$file_pptis = '';
if(strpos($file_mime, 'image') !== false){
$view = 'View';
$properties = $this->_service->properties->listProperties($fileId);
$getfile_pptis = $properties->getItems();
if(count($getfile_pptis) > 0){
$file_pptis = $getfile_pptis[0]->getValue();
// selfWidth:xx selfHeight:xx thumbId:xxx thumbWidth:xx thumbHeight:xx
preg_match_all('/(\w+):("[^"]+"|\S+)/', $file_pptis, $matches);
$img_meta = array_combine($matches[1], $matches[2]);
if(array_key_exists('thumbId', $img_meta)){
$file_thumb = 'https://www.googledrive.com/host/' . $img_meta['thumbId'];
}
}
}
$valson = json_encode(array($file_mime, $file_title, $fileId, $file_desc, $folder_name, $file_pptis));
$daftarfile .= '<tbody><tr><td><input type="'.$in_type.'" name="'.$in_name.'" value="'.base64_encode($valson).'" ' . $checked . '></td><td class="kolom_file" title="' . $file_thumb . '">'.$fileId.'</td>';
$daftarfile .= '<td title="' . $file_desc . '"><img src="' . $file_icon . '" title="' . $file_mime . '"> ' . $file_title . '</td>';
$daftarfile .= '<!--<td>' . $file_desc . '</td>-->';
$daftarfile .= '<td title="md5Checksum : ' . $file_md5 . '">' . $file_size . '</td>';
$daftarfile .= '<td>' . $view . ' | Preview</td></tr>';
}
$daftarfile .= '</tbody></table></div><br/>';
}
// merangkai paginasi soretempe
$range = 5;
$showitems = ($range * 2)+1;
$hal_folderid = $gdwpm_kecing_hal[$folderId];
$halterlihat = array_search($pageToken, $hal_folderid);
if(empty($halterlihat)){$halterlihat = 1;}
$totalhal = count($hal_folderid);
if(1 != $totalhal)
{
$halsiap = '<input type="hidden" id="'.$id_max.'" value="'.$maxResults.'" /><input type="hidden" id="'.$id_folid.'" value="'.$folderId.'" />';
if($halterlihat > 2 && $halterlihat > $range+1 && $showitems < $totalhal) $halsiap .= '<button id="'.$div_hal.'" value="'.$hal_folderid[1].'">«</button>';
if($halterlihat > 1 && $showitems < $totalhal) $halsiap .= '<button id="'.$div_hal.'" value="'.$hal_folderid[$halterlihat - 1].'">‹</button>';
for ($j=1; $j <= $totalhal; $j++)
{
if (1 != $totalhal &&( !($j >= $halterlihat+$range+1 || $j <= $halterlihat-$range-1) || $totalhal <= $showitems ))
{
if($halterlihat == $j && $pageTokenInput != ''){$disable_butt = ' disabled';}else{$disable_butt = '';}
$halsiap .= '<button id="'.$div_hal.'" value="'.$hal_folderid[$j].'"'.$disable_butt.'>'.$j.'</button>';
}
}
if ($halterlihat < $totalhal && $showitems < $totalhal) $halsiap .= '<button id="'.$div_hal.'" value="'.$hal_folderid[$halterlihat + 1].'">›</button>';
if ($halterlihat < $totalhal-1 && $halterlihat+$range-1 < $totalhal && $showitems < $totalhal) $halsiap .= '<button id="'.$div_hal.'" value="'.$hal_folderid[$totalhal].'">»</button>';
}
$vaginasi = '<div id="'.$div_pagi.'">'.$halsiap.'</div>';
$daftarfile .= $vaginasi;
if($i == 0 && $totalhal > 1 && $halterlihat == $totalhal){$daftarfile = $vaginasi;}
return array($daftarfile, $i, $totalhal, $halterlihat);//, $halterlihat, $totalhal);//items, items onpage, currentpage, totalpage
}
}
?>
As discussed in Upload Files, for reliable transfer especially important with larger files, using Resumable upload is a good strategy to use for most applications, since it also works for smaller files at the cost of one additional HTTP request per upload.
Additionally, apps that use resumable upload need to have code to resume an interrupted upload. If an upload is interrupted, find out how much data was successfully received, and then resume the upload starting from that point which is one of the good advantages of this uploading type.
For more information and steps in using resumable upload, kindly try going through given documentations above.
Related
I want to upload image from galery to server. I succeed to upload image, but i just can upload 1 file. if i upload 2 file, the 2nd file will be upload. The 1st file will not upload. or if i edit and upload 2nd image file, then 1st image file will be replaced by 2nd image file.
this is webservicecontroller.php
$imagePath = IMAGE_PATH_FOR_TIM_THUMB.'/'.STUDY_MATERIAL_DIR.'/';
if (!empty($_POST))
{
$this->loadModel('StudyMaterial');
if($_POST['type'] != 'delete')
{
$shift = array();
if($_POST['type'] == 'edit')
{
$shift['StudyMaterial']['id'] = $_POST['study_material_id'];
}
$shift['StudyMaterial']['user_id'] = $_POST['user_id'];
$shift['StudyMaterial']['standard_id'] = $_POST['standard_id'];
$shift['StudyMaterial']['subject_id'] = $_POST['subject_id'];
$shift['StudyMaterial']['topic_id'] = $_POST['topic_id'];
$shift['StudyMaterial']['lesson_id'] = $_POST['lesson_id'];
$shift['StudyMaterial']['name'] = $_POST['name'];
$shift['StudyMaterial']['description'] = $_POST['description'];
$this->StudyMaterial->save($shift);
$study_material_id = $this->StudyMaterial->id;
if(isset($_FILES['study_material_file']) && !empty($_FILES['study_material_file']) && ($_FILES['study_material_file']['error'] == 0))
{
$name = $_FILES['study_material_file']['name'];
$ext = substr(strrchr($name, "."), 1);
$only_name = $name . "_" . time();
$filename = 'topic_file_'.microtime(true).'.'.strtolower($ext);
$original = STUDY_MATERIAL_DIR . "/" . $filename;
$file_type = $_POST['file_type'];
if($file_type == 'video')
{
if(strtolower($ext) == 'mov')
{
$original = STUDY_MATERIAL_DIR . "/" . $filename;
#move_uploaded_file($_FILES["study_material_file"]["tmp_name"], $original);
$new_filename = $only_name. '.mp4';
$srcFile = STUDY_MATERIAL_DIR . "/" . $filename;
$destFile = STUDY_MATERIAL_DIR . "/" . $new_filename;
exec('ffmpeg -i '.$srcFile.' -f mp4 -s 320x240 '.$destFile.'');
if($_POST['type'] == 'edit')
{
$checkAlready = $this->StudyMaterial->find('first',array('conditions'=>array('StudyMaterial.id'=>$_POST['study_material_id'])));
$image = $checkAlready['StudyMaterial']['file_name'];
if($image && file_exists(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image ))
{
#unlink(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image);
}
}
$this->StudyMaterial->saveField('file_name',$filename,false);
$this->StudyMaterial->saveField('type',$file_type,false);
}
else
{
#move_uploaded_file($_FILES["study_material_file"]["tmp_name"], $original);
if($_POST['type'] == 'edit')
{
$checkAlready = $this->StudyMaterial->find('first',array('conditions'=>array('StudyMaterial.id'=>$_POST['study_material_id'])));
$image = $checkAlready['StudyMaterial']['file_name'];
if($image && file_exists(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image ))
{
#unlink(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image);
}
}
$this->StudyMaterial->saveField('file_name',$filename,false);
$this->StudyMaterial->saveField('type',$file_type,false);
}
}
else
{
#move_uploaded_file($_FILES["study_material_file"]["tmp_name"], $original);
if($_POST['type'] == 'edit')
{
$checkAlready = $this->StudyMaterial->find('first',array('conditions'=>array('StudyMaterial.id'=>$_POST['study_material_id'])));
$image = $checkAlready['StudyMaterial']['file_name'];
if($image && file_exists(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image ))
{
#unlink(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image);
}
}
$this->StudyMaterial->saveField('file_name',$filename,false);
$this->StudyMaterial->saveField('type',$file_type,false);
}
}
else
{
if($_POST['type'] == 'edit')
{
$this->StudyMaterial->id = $_POST['study_material_id'];
$this->StudyMaterial->saveField('file_name','',false);
$this->StudyMaterial->saveField('type','',false);
}
}
if($_POST['type'] == 'edit')
{
$responseData = array(
'status' => 1,
'message' => "Study Material updated successfully."
);
}
else
{
$responseData = array(
'status' => 1,
'message' => "Study Material added successfully."
);
}
}
Is the problem in webservice or android? this is add_material.java
private void selectImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
getActivity().startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Problem in your server side please check your database query where you update your column.
Hello this is a 2 part question....
I have been trying to solve my problem for a while and gave up tonight and seeking answers :/
i have the following code and trying to download the image to the width of 1207px,
the download of the script works fine so i haven't included it below.
the second part is i like to screenshot to the ratio of 1207px wide but cant find way round it.
i have edited the following lines..
$w = 500;
$h = 768;
but this don't work, what ever the values are it downloads at 500px or very close width which is not ideal.
$url = trim(urldecode($url));
if ($url == '') {
exit();
}
if (!stristr($url, 'http://') and !stristr($url, 'https://')) {
$url = 'http://' . $url;
}
$url_segs = parse_url($url);
if (!isset($url_segs['host'])) {
exit();
}
$here = dirname(__FILE__) . DIRECTORY_SEPARATOR;
$bin_files = $here . 'bin' . DIRECTORY_SEPARATOR;
$jobs = $here . 'jobs' . DIRECTORY_SEPARATOR;
$cache = $here . 'cache' . DIRECTORY_SEPARATOR;
if (!is_dir($jobs)) {
mkdir($jobs);
file_put_contents($jobs . 'index.php', '<?php exit(); ?>');
}
if (!is_dir($cache)) {
mkdir($cache);
file_put_contents($cache . 'index.php', '<?php exit(); ?>');
}
$w = 500;
$h = 768;
if (isset($_REQUEST['w'])) {
$w = intval($_REQUEST['w']);
}
if (isset($_REQUEST['h'])) {
$h = intval($_REQUEST['h']);
}
if (isset($_REQUEST['clipw'])) {
$clipw = intval($_REQUEST['clipw']);
}
if (isset($_REQUEST['cliph'])) {
$cliph = intval($_REQUEST['cliph']);
}
if (isset($_REQUEST['download'])) {
$download = $_REQUEST['download'];
}
$url = strip_tags($url);
$url = str_replace(';', '', $url);
$url = str_replace('"', '', $url);
$url = str_replace('\'', '/', $url);
$url = str_replace('<?', '', $url);
$url = str_replace('<?', '', $url);
$url = str_replace('\077', ' ', $url);
$screen_file = $url_segs['host'] . crc32($url) . '_' . $w . '_' . $h . '.jpg';
$cache_job = $cache . $screen_file;
$refresh = false;
if (is_file($cache_job)) {
$filemtime = #filemtime($cache_job); // returns FALSE if file does not exist
if (!$filemtime or (time() - $filemtime >= $cache_life)) {
$refresh = true;
}
}
$url = escapeshellcmd($url);
if (!is_file($cache_job) or $refresh == true) {
$src = "
var page = require('webpage').create();
page.viewportSize = { width: {$w}, height: {$h} };
";
if (isset($clipw) && isset($cliph)) {
$src .= "page.clipRect = { top: 0, left: 0, width: {$clipw}, height: {$cliph} };";
}
$src .= "
page.open('{$url}', function () {
page.render('{$screen_file}');
phantom.exit();
});
";
$job_file = $jobs . $url_segs['host'] . crc32($src) . '.js';
file_put_contents($job_file, $src);
$exec = $bin_files . 'phantomjs ' . $job_file;
$escaped_command = escapeshellcmd($exec);
exec($escaped_command);
if (is_file($here . $screen_file)) {
rename($here . $screen_file, $cache_job);
}
}
if (is_file($cache_job)) {
if ($download != false) {
$file = $cache_job;
$file_name=basename($file);
$type = 'image/jpeg';
header("Content-disposition: attachment; filename={$file_name}");
header("Content-type: {$type}");
readfile($file);
;
} else {
$file = $cache_job;
$type = 'image/jpeg';
header('Content-Type:' . $type);
header('Content-Length: ' . filesize($file));
readfile($file);
}
}
?>
I have the php script as shown below. I want to ask that using this script how can i read normal .eml file as we read in gmail or yahoo? how can i get attachments from it ?
<?php
/**
*
* This code has been written by Alexis Ulrich (http://alx2002.free.fr)
* This code is in the public domain.
*
*/
define(EML_FILE_PATH,'');
define(PICTURE_DIRECTORY_PATH,'img/');
// gets parameters
$images = substr($_GET['images'],0,5);
$filename = substr($_GET['filename'],0,50);
if ($filename == '') $filename = 'toto.eml';
$eml_file = EML_FILE_PATH.$filename;
// opens file
if (!($content = fread(fopen(EML_FILE_PATH.$filename, 'r'), filesize(EML_FILE_PATH.$filename))))
die('File not found ('.EML_FILE_PATH.$filename.')');
// two kinds of separators
if (strpos($content,'------_') !== false) $separator = '------_';
else $separator = '------=_';
$aContent = explode($separator,$content);
$aImages = array();
foreach($aContent as $thisContent) {
if (strpos($thisContent,'Content-Type: text/html') !== false) {
// email HTML body
$thisContent = substr($thisContent,strpos($thisContent,'<!DOCTYPE'));
$thisHTMLContent = quoted_printable_decode($thisContent);
//echo "<hr>$thisHTMLContent<hr>\n\n";
}
if (strpos($thisContent,'Content-Type: image/gif;') !== false) {
// base64 gif picture
$begin = strpos($thisContent,'Content-ID: <') + 13;
$long = strpos(substr($thisContent,strpos($thisContent,'Content-ID: <') + 13),'>');
$img_id = substr($thisContent,$begin,$long);
$img_name = substr($thisContent,strpos($thisContent,'name="')+6,strpos($thisContent,'.gif"')-strpos($thisContent,'name="')-6);
if (strpos($thisContent,'Content-Location: ') !== false) {
$img_location = substr($thisContent,strpos($thisContent,'Content-Location: ')+18);
$img_location = substr($img_location,0,strpos($img_location,'.gif'));
$searched = 'Content-Location: ' . $img_location . '.gif';
$img_base64 = substr($thisContent,strpos($thisContent,$searched)+strlen($searched));
}
else {
$img_location = $img_name;
$searched = 'Content-ID: <' . $img_id . '>';
$Content_ID_pos = strpos($thisContent,'Content-ID: <');
$end_content = substr($thisContent,$Content_ID_pos);
$end_Content_ID_pos = strpos($end_content,'>');
$img_base64 = substr($end_content,$end_Content_ID_pos + 1);
}
$aThisImage = array('id'=>$img_id, 'name'=>$img_name, 'location'=>$img_location, 'type'=>'gif', 'base64'=>$img_base64);
//print_r($aThisImage);
$aImages[] = $aThisImage;
}
if (strpos($thisContent,'Content-Type: image/jpeg;') !== false) {
// base64 jpg picture
$begin = strpos($thisContent,'Content-ID: <') + 13;
$long = strpos(substr($thisContent,strpos($thisContent,'Content-ID: <') + 13),'>');
$img_id = substr($thisContent,$begin,$long);
$img_name = substr($thisContent,strpos($thisContent,'name="')+6,strpos($thisContent,'.jpg"')-strpos($thisContent,'name="')-6);
if (strpos($thisContent,'Content-Location: ') !== false) {
$img_location = substr($thisContent,strpos($thisContent,'Content-Location: ')+18);
$img_location = substr($img_location,0,strpos($img_location,'.jpg'));
$searched = 'Content-Location: ' . $img_location . '.jpg';
$img_base64 = substr($thisContent,strpos($thisContent,$searched)+strlen($searched));
}
else {
$img_location = $img_name;
$searched = 'Content-ID: <' . $img_id . '>';
$Content_ID_pos = strpos($thisContent,'Content-ID: <');
$end_content = substr($thisContent,$Content_ID_pos);
$end_Content_ID_pos = strpos($end_content,'>');
$img_base64 = substr($end_content,$end_Content_ID_pos + 1);
}
$aThisImage = array('id'=>$img_id, 'name'=>$img_name, 'location'=>$img_location, 'type'=>'jpg', 'base64'=>$img_base64);
$aImages[] = $aThisImage;
}
}
//print_r($aImages);
foreach($aImages as $image) {
if ($images == 'filed') {
// image file creation
if (!file_exists(PICTURE_DIRECTORY_PATH."$image[location].$image[type]")) {
if (!$handle = fopen (PICTURE_DIRECTORY_PATH."$image[location].$image[type]", "wb"))
die("Cannot open file (".PICTURE_DIRECTORY_PATH."$image[location].$image[type])");
if (!fwrite($handle, base64_decode($image[base64])))
die("Cannot write into file (".PICTURE_DIRECTORY_PATH."$image[location].$image[type])");
fclose($handle);
}
$thisHTMLContent = str_replace('cid:'.$image['id'],PICTURE_DIRECTORY_PATH."$image[location].$image[type]",$thisHTMLContent);
}
else {
// images to be created on the fly
$imageLocation = urlencode($image[location]);
$file = urlencode($eml_file);
$thisHTMLContent = str_replace('cid:'.$image['id'],"viewImage.php?imageLocation=$imageLocation&file=$file",$thisHTMLContent);
}
$thisHTMLContent = preg_replace("/<IMG HEIGHT=(\d*)/i","<img ",$thisHTMLContent);
// no base href referring to local file
$thisHTMLContent = preg_replace("/href=\"file(.*)\"/i","",$thisHTMLContent);
}
echo $thisHTMLContent;
?>
Thanks in advance and would hope to receive reply soon.
I want to be able to upload an MS word document and export it a page in my site.
Is there any way to accomplish this?
//FUNCTION :: read a docx file and return the string
function readDocx($filePath) {
// Create new ZIP archive
$zip = new ZipArchive;
$dataFile = 'word/document.xml';
// Open received archive file
if (true === $zip->open($filePath)) {
// If done, search for the data file in the archive
if (($index = $zip->locateName($dataFile)) !== false) {
// If found, read it to the string
$data = $zip->getFromIndex($index);
// Close archive file
$zip->close();
// Load XML from a string
// Skip errors and warnings
$xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
// Return data without XML formatting tags
$contents = explode('\n',strip_tags($xml->saveXML()));
$text = '';
foreach($contents as $i=>$content) {
$text .= $contents[$i];
}
return $text;
}
$zip->close();
}
// In case of failure return empty string
return "";
}
ZipArchive and DOMDocument are both inside PHP so you don't need to install/include/require additional libraries.
One may use PHPDocX.
It has support for practically all HTML CSS styles. Moreover you may use templates to add extra formatting to your HTML via the replaceTemplateVariableByHTML.
The HTML methods of PHPDocX also allow for the direct use of Word styles. You may use something like this:
$docx->embedHTML($myHTML, array('tableStyle' => 'MediumGrid3-accent5PHPDOCX'));
If you want that all your tables use the MediumGrid3-accent5 Word style. The embedHTML method as well as its version for templates (replaceTemplateVariableByHTML) preserve inheritance, meaning by that that you may use a predefined Word style and override with CSS any of its properties.
You may also extract selected parts of your HTML using 'JQuery type' selectors.
You can convert Word docx documents to html using Print2flash library. Here is an PHP excerpt from my client's site which converts a document to html:
include("const.php");
$p2fServ = new COM("Print2Flash4.Server2");
$p2fServ->DefaultProfile->DocumentType=HTML5;
$p2fServ->ConvertFile($wordfile,$htmlFile);
It converts a document which path is specified in $wordfile variable to a html page file specified by $htmlFile variable. All formatting, hyperlinks and charts are retained. You can get the required const.php file altogether with a fuller sample from Print2flash SDK.
this is a workaround based on David Lin's answer above
removing "w:" in a docx's xml tags leave behing Html like tags
function readDocx($filePath) {
// Create new ZIP archive
$zip = new ZipArchive;
$dataFile = 'word/document.xml';
// Open received archive file
if (true === $zip->open($filePath)) {
// If done, search for the data file in the archive
if (($index = $zip->locateName($dataFile)) !== false) {
// If found, read it to the string
$data = $zip->getFromIndex($index);
// Close archive file
$zip->close();
// Load XML from a string
// Skip errors and warnings
$xml = new DOMDocument("1.0", "utf-8");
$xml->loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING|LIBXML_PARSEHUGE);
$xml->encoding = "utf-8";
// Return data without XML formatting tags
$output = $xml->saveXML();
$output = str_replace("w:","",$output);
return $output;
}
$zip->close();
}
// In case of failure return empty string
return "";
}
Ok Im in very late, but thought I'd post this to save you all some time.
This is some php code I have put together not just to read the text from docx but the images too, currently it does not support floating images / text, but what I have done so far is a massive move forwards to whats already been posted on here - note you need to update https://example.co.uk to YOUR domain name.
<?php
class Docx_ws_imglnk {
public $originalpath = '';
public $extractedpath = '';
}
class Docx_ws_rel {
public $Id = '';
public $Target = '';
}
class Docx_ws_def {
public $styleId = '';
public $type = '';
public $color = '000000';
}
class Docx_p_def {
public $data = array();
public $text = "";
}
class Docx_p_item {
public $name = "";
public $value = "";
public $innerstyle = "";
public $type = "text";
}
class Docx_reader {
private $fileData = false;
private $errors = array();
public $rels = array();
public $imglnks = array();
public $styles = array();
public $document = null;
public $paragraphs = array();
public $path = '';
private $saveimgpath = 'docimages';
public function __construct() {
}
private function load($file) {
if (file_exists($file)) {
$zip = new ZipArchive();
$openedZip = $zip->open($file);
if ($openedZip === true) {
$this->path = $file;
//read and save images
for ( $i = 0; $i < $zip->numFiles; $i ++ ) {
$zip_element = $zip->statIndex( $i );
if ( preg_match( "([^\s]+(\.(?i)(jpg|jpeg|png|gif|bmp))$)", $zip_element['name'] ) ) {
$imglnk = new Docx_ws_imglnk;
$imglnk->originalpath = $zip_element['name'];
$imagename = explode( '/', $zip_element['name'] );
$imagename = end( $imagename );
$imglnk->extractedpath = dirname( __FILE__ ) . '/' . $this->savepath . $imagename;
$putres = file_put_contents( $imglnk->extractedpath, $zip->getFromIndex( $i ));
$imglnk->extractedpath = str_replace('var/www/', 'https://example.co.uk/', $imglnk->extractedpath);
$imglnk->extractedpath = substr($imglnk->extractedpath, 1);
array_push($this->imglnks, $imglnk);
}
}
//read relationships
if (($styleIndex = $zip->locateName('word/_rels/document.xml.rels')) !== false) {
$stylesRels = $zip->getFromIndex($styleIndex);
$xml = simplexml_load_string($stylesRels);
$XMLTEXT = $xml->saveXML();
$doc = new DOMDocument();
$doc->loadXML($XMLTEXT);
foreach($doc->documentElement->childNodes as $childnode)
{
$nodename = $childnode->nodeName;
if($childnode->hasAttributes())
{
$rel = new Docx_ws_rel;
for ($a = 0; $a < $childnode->attributes->count(); $a++)
{
$attrNode = $childnode->attributes->item($a);
if (strcmp( $attrNode->nodeName, 'Id') == 0)
{
$rel->Id = $attrNode->nodeValue;
}
if (strcmp( $attrNode->nodeName, 'Target') == 0)
{
$rel->Target = $attrNode->nodeValue;
}
}
array_push($this->rels, $rel);
}
}
}
//attempt to load styles:
if (($styleIndex = $zip->locateName('word/styles.xml')) !== false) {
$stylesXml = $zip->getFromIndex($styleIndex);
$xml = simplexml_load_string($stylesXml);
$XMLTEXT = $xml->saveXML();
$doc = new DOMDocument();
$doc->loadXML($XMLTEXT);
foreach($doc->documentElement->childNodes as $childnode)
{
$nodename = $childnode->nodeName;
//get style
if (strcmp($nodename, "w:style") == 0)
{
$ws_def = new Docx_ws_def;
for ($a=0; $a < $childnode->attributes->count(); $a++ )
{
$item = $childnode->attributes->item($a);
//style id
if (strcmp($item->nodeName, "w:styleId") == 0)
{
$ws_def->styleId = $item->nodeValue;
}
//style type
if (strcmp($item->nodeName, "w:type") == 0)
{
$ws_def->type = $item->nodeValue;
}
}
}
//push style to the array of styles
if (strcmp($ws_def->styleId, "") != 0 && strcmp($ws_def->type, "") != 0)
{
array_push($this->styles, $ws_def);
}
}
}
if (($index = $zip->locateName('word/document.xml')) !== false) {
$stylesDoc = $zip->getFromIndex($index);
$xml = simplexml_load_string($stylesDoc);
$XMLTEXT = $xml->saveXML();
$this->document = new DOMDocument();
$this->document->loadXML($XMLTEXT);
}
$zip->close();
} else {
switch($openedZip) {
case ZipArchive::ER_EXISTS:
$this->errors[] = 'File exists.';
break;
case ZipArchive::ER_INCONS:
$this->errors[] = 'Inconsistent zip file.';
break;
case ZipArchive::ER_MEMORY:
$this->errors[] = 'Malloc failure.';
break;
case ZipArchive::ER_NOENT:
$this->errors[] = 'No such file.';
break;
case ZipArchive::ER_NOZIP:
$this->errors[] = 'File is not a zip archive.';
break;
case ZipArchive::ER_OPEN:
$this->errors[] = 'Could not open file.';
break;
case ZipArchive::ER_READ:
$this->errors[] = 'Read error.';
break;
case ZipArchive::ER_SEEK:
$this->errors[] = 'Seek error.';
break;
}
}
} else {
$this->errors[] = 'File does not exist.';
}
}
public function setFile($path) {
$this->fileData = $this->load($path);
}
public function to_plain_text() {
if ($this->fileData) {
return strip_tags($this->fileData);
} else {
return false;
}
}
public function processDocument() {
$html = '';
foreach($this->document->documentElement->childNodes as $childnode)
{
$nodename = $childnode->nodeName;
//get the body of the document
if (strcmp($nodename, "w:body") == 0)
{
foreach($childnode->childNodes as $subchildnode)
{
$pnodename = $subchildnode->nodeName;
//process every paragraph
if (strcmp($pnodename, "w:p") == 0)
{
$pdef = new Docx_p_def;
foreach($subchildnode->childNodes as $pchildnode)
{
//process any inner children
if (strcmp($pchildnode, "w:pPr") == 0)
{
foreach($pchildnode->childNodes as $prchildnode)
{
//process text alignment
if (strcmp($prchildnode->nodeName, "w:pStyle") == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'styleId';
$pitem->value = $prchildnode->attributes->getNamedItem('val')->nodeValue;
array_push($pdef->data, $pitem);
}
//process text alignment
if (strcmp($prchildnode->nodeName, "w:jc") == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'align';
$pitem->value = $prchildnode->attributes->getNamedItem('val')->nodeValue;
if (strcmp($pitem->value, "left") == 0)
{
$pitem->innerstyle .= "text-align:" . $pitem->value . ";";
}
if (strcmp($pitem->value, "center") == 0)
{
$pitem->innerstyle .= "text-align:" . $pitem->value . ";";
}
if (strcmp($pitem->value, "right") == 0)
{
$pitem->innerstyle .= "text-align:" . $pitem->value . ";";
}
if (strcmp($pitem->value, "both") == 0)
{
$pitem->innerstyle .= "word-spacing:" . 10 . "px;";
}
array_push($pdef->data, $pitem);
}
//process drawing
if (strcmp($prchildnode->nodeName, "w:drawing") == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'drawing';
$pitem->value = '';
$pitem->type = 'graphic';
$extents = $prchildnode->getElementsByTagName('extent')[0];
$cx = $extents->attributes->getNamedItem('cx')->nodeValue;
$cy = $extents->attributes->getNamedItem('cy')->nodeValue;
$pcx = (int)$cx / 9525;
$pcy = (int)$cy / 9525;
$pitem->innerstyle .= "width:" . $pcx . "px;";
$pitem->innerstyle .= "height:" . $pcy . "px;";
$blip = $prchildnode->getElementsByTagName('blip')[0];
$pitem->value = $blip->attributes->getNamedItem('embed')->nodeValue;
array_push($pdef->data, $pitem);
}
//process spacing
if (strcmp($prchildnode->nodeName, "w:spacing") == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'paragraphSpacing';
$bval = $prchildnode->attributes->getNamedItem('before')->nodeValue;
if (strcmp($bval, '') == 0)
$bval = 0;
$pitem->innerstyle .= "padding-top:" . $bval . "px;";
$aval = $prchildnode->attributes->getNamedItem('after')->nodeValue;
if (strcmp($aval, '') == 0)
$aval = 0;
$pitem->innerstyle .= "padding-bottom:" . $aval . "px;";
array_push($pdef->data, $pitem);
}
}
}
if (strcmp($pchildnode, "w:r") == 0)
{
foreach($pchildnode->childNodes as $rchildnode)
{
//process text
if (strcmp($rchildnode->nodeName, "w:t") == 0)
{
$pdef->text .= $rchildnode->nodeValue;
if (count($pdef->data) == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'styleId';
$pitem->value = '';
array_push($pdef->data, $pitem);
}
}
if (strcmp($rchildnode->nodeName, "w:rPr") == 0)
{
foreach($rchildnode->childNodes as $rPrchildnode)
{
if (strcmp($rPrchildnode->nodeName, "w:b") == 0 )
{
$pitem = new Docx_p_item;
$pitem->name = 'textBold';
$pitem->value = '';
$pitem->innerstyle .= "text-weight: 500;";
array_push($pdef->data, $pitem);
}
if (strcmp($rPrchildnode->nodeName, "w:i") == 0 )
{
$pitem = new Docx_p_item;
$pitem->name = 'textItalic';
$pitem->value = '';
$pitem->innerstyle .= "text-style: italic;";
array_push($pdef->data, $pitem);
}
if (strcmp($rPrchildnode->nodeName, "w:u") == 0 )
{
$pitem = new Docx_p_item;
$pitem->name = 'textUnderline';
$pitem->value = '';
$pitem->innerstyle .= "text-decoration: underline;";
array_push($pdef->data, $pitem);
}
if (strcmp($rPrchildnode->nodeName, "w:sz") == 0 )
{
$pitem = new Docx_p_item;
$pitem->name = 'textSize';
$sz = $rPrchildnode->attributes->getNamedItem('val')->nodeValue;
if ($sz == '')
{
$sz=0;
}
$pitem->value = $sz;
array_push($pdef->data, $pitem);
}
}
}
}
}
}
array_push($this->paragraphs, $pdef);
}
}
}
}
}
public function to_html()
{
$html = '';
foreach($this->paragraphs as $para)
{
$styleselect = null;
$type = 'text';
$content = $para->text;
$sz = 0;
$extent = '';
$embedid = '';
$pinnerstylesid = '';
$pinnerstylesunderline = '';
$pinnerstylessz = '';
if (count($para->data) > 0)
{
foreach($para->data as $node)
{
if (strcmp($node->name, "styleId") == 0)
{
$type = $node->type;
$pinnerstylesid = $node->innerstyle;
foreach($this->styles as $style)
{
if (strcmp ($node->value, $style->styleId) == 0)
{
$styleselect = $style;
}
}
}
if (strcmp($node->name, "align") == 0)
{
$pinnerstylesid .= $node->innerstyle. ";";
}
if (strcmp($node->name, "drawing") == 0)
{
$type = $node->type;
$extent = $node->innerstyle;
$embedid = $node->value;
}
if (strcmp($node->name, "textSize") == 0)
{
$sz = $node->value;
}
if (strcmp($node->name, "textUnderline") == 0)
{
$pinnerstylesunderline = $node->innerstyle;
}
}
}
if (strcmp($type, 'text') == 0)
{
//echo "has valid para";
//echo "<br>";
if ($styleselect != null)
{
//echo "has valid style";
//echo "<br>";
if (strcmp($styleselect->color, '') != 0)
{
$pinnerstylesid .= "color:#" . $styleselect->color. ";";
}
}
if ($sz != 0)
{
$pinnerstylesid .= 'font-size:' . $sz . 'px;';
//echo "sz<br>";
}
$span = "<p style='". $pinnerstylesid . $pinnerstylesunderline ."'>";
$span .= $content;
$span .= "</p>";
//echo $span;
$html .= $span;
}
if (strcmp($type, 'graphic') == 0)
{
$imglnk = '';
foreach($this->rels as $rel)
{
if(strcmp($embedid, '') != 0 && strcmp($rel->Id, $embedid) == 0)
{
foreach($this->imglnks as $imgpathdef)
{
if (strpos($imgpathdef->extractedpath, $rel->Target) >= 0)
{
$imglnk = $imgpathdef->extractedpath;
//echo "has img link<br>";
//echo $imglnk . "<br>";
}
}
}
}
if ($styleselect != null)
{
//echo "has valid style";
//echo "<br>";
if (strcmp($styleselect->color, '') != 0)
{
$pinnerstylesid .= "color:#" . $styleselect->color. ";";
}
}
if ($sz != 0)
{
$pinnerstylesid .= 'font-size:' . $sz . 'px;';
//echo "sz<br>";
}
$span = "<p style='". $pinnerstylesid . $pinnerstylesunderline ."'>";
$span .= "<img style='". $extent ."' alt='image coming soon' src ='". $imglnk ."'/>";
$span .= "</p>";
//echo $span;
$html .= $span;
}
}
return $html;
}
public function get_errors() {
return $this->errors;
}
private function getStyles() {
}
}
function getDocX($path)
{
//echo $path;
$doc = new Docx_reader();
$doc->setFile($path);
if(!$doc->get_errors()) {
$doc->processDocument();
$html = $doc->to_html();
echo $html;
}
return "";
}
?>
I want to be able to upload an MS word document and export it a page in my site.
Is there any way to accomplish this?
//FUNCTION :: read a docx file and return the string
function readDocx($filePath) {
// Create new ZIP archive
$zip = new ZipArchive;
$dataFile = 'word/document.xml';
// Open received archive file
if (true === $zip->open($filePath)) {
// If done, search for the data file in the archive
if (($index = $zip->locateName($dataFile)) !== false) {
// If found, read it to the string
$data = $zip->getFromIndex($index);
// Close archive file
$zip->close();
// Load XML from a string
// Skip errors and warnings
$xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
// Return data without XML formatting tags
$contents = explode('\n',strip_tags($xml->saveXML()));
$text = '';
foreach($contents as $i=>$content) {
$text .= $contents[$i];
}
return $text;
}
$zip->close();
}
// In case of failure return empty string
return "";
}
ZipArchive and DOMDocument are both inside PHP so you don't need to install/include/require additional libraries.
One may use PHPDocX.
It has support for practically all HTML CSS styles. Moreover you may use templates to add extra formatting to your HTML via the replaceTemplateVariableByHTML.
The HTML methods of PHPDocX also allow for the direct use of Word styles. You may use something like this:
$docx->embedHTML($myHTML, array('tableStyle' => 'MediumGrid3-accent5PHPDOCX'));
If you want that all your tables use the MediumGrid3-accent5 Word style. The embedHTML method as well as its version for templates (replaceTemplateVariableByHTML) preserve inheritance, meaning by that that you may use a predefined Word style and override with CSS any of its properties.
You may also extract selected parts of your HTML using 'JQuery type' selectors.
You can convert Word docx documents to html using Print2flash library. Here is an PHP excerpt from my client's site which converts a document to html:
include("const.php");
$p2fServ = new COM("Print2Flash4.Server2");
$p2fServ->DefaultProfile->DocumentType=HTML5;
$p2fServ->ConvertFile($wordfile,$htmlFile);
It converts a document which path is specified in $wordfile variable to a html page file specified by $htmlFile variable. All formatting, hyperlinks and charts are retained. You can get the required const.php file altogether with a fuller sample from Print2flash SDK.
this is a workaround based on David Lin's answer above
removing "w:" in a docx's xml tags leave behing Html like tags
function readDocx($filePath) {
// Create new ZIP archive
$zip = new ZipArchive;
$dataFile = 'word/document.xml';
// Open received archive file
if (true === $zip->open($filePath)) {
// If done, search for the data file in the archive
if (($index = $zip->locateName($dataFile)) !== false) {
// If found, read it to the string
$data = $zip->getFromIndex($index);
// Close archive file
$zip->close();
// Load XML from a string
// Skip errors and warnings
$xml = new DOMDocument("1.0", "utf-8");
$xml->loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING|LIBXML_PARSEHUGE);
$xml->encoding = "utf-8";
// Return data without XML formatting tags
$output = $xml->saveXML();
$output = str_replace("w:","",$output);
return $output;
}
$zip->close();
}
// In case of failure return empty string
return "";
}
Ok Im in very late, but thought I'd post this to save you all some time.
This is some php code I have put together not just to read the text from docx but the images too, currently it does not support floating images / text, but what I have done so far is a massive move forwards to whats already been posted on here - note you need to update https://example.co.uk to YOUR domain name.
<?php
class Docx_ws_imglnk {
public $originalpath = '';
public $extractedpath = '';
}
class Docx_ws_rel {
public $Id = '';
public $Target = '';
}
class Docx_ws_def {
public $styleId = '';
public $type = '';
public $color = '000000';
}
class Docx_p_def {
public $data = array();
public $text = "";
}
class Docx_p_item {
public $name = "";
public $value = "";
public $innerstyle = "";
public $type = "text";
}
class Docx_reader {
private $fileData = false;
private $errors = array();
public $rels = array();
public $imglnks = array();
public $styles = array();
public $document = null;
public $paragraphs = array();
public $path = '';
private $saveimgpath = 'docimages';
public function __construct() {
}
private function load($file) {
if (file_exists($file)) {
$zip = new ZipArchive();
$openedZip = $zip->open($file);
if ($openedZip === true) {
$this->path = $file;
//read and save images
for ( $i = 0; $i < $zip->numFiles; $i ++ ) {
$zip_element = $zip->statIndex( $i );
if ( preg_match( "([^\s]+(\.(?i)(jpg|jpeg|png|gif|bmp))$)", $zip_element['name'] ) ) {
$imglnk = new Docx_ws_imglnk;
$imglnk->originalpath = $zip_element['name'];
$imagename = explode( '/', $zip_element['name'] );
$imagename = end( $imagename );
$imglnk->extractedpath = dirname( __FILE__ ) . '/' . $this->savepath . $imagename;
$putres = file_put_contents( $imglnk->extractedpath, $zip->getFromIndex( $i ));
$imglnk->extractedpath = str_replace('var/www/', 'https://example.co.uk/', $imglnk->extractedpath);
$imglnk->extractedpath = substr($imglnk->extractedpath, 1);
array_push($this->imglnks, $imglnk);
}
}
//read relationships
if (($styleIndex = $zip->locateName('word/_rels/document.xml.rels')) !== false) {
$stylesRels = $zip->getFromIndex($styleIndex);
$xml = simplexml_load_string($stylesRels);
$XMLTEXT = $xml->saveXML();
$doc = new DOMDocument();
$doc->loadXML($XMLTEXT);
foreach($doc->documentElement->childNodes as $childnode)
{
$nodename = $childnode->nodeName;
if($childnode->hasAttributes())
{
$rel = new Docx_ws_rel;
for ($a = 0; $a < $childnode->attributes->count(); $a++)
{
$attrNode = $childnode->attributes->item($a);
if (strcmp( $attrNode->nodeName, 'Id') == 0)
{
$rel->Id = $attrNode->nodeValue;
}
if (strcmp( $attrNode->nodeName, 'Target') == 0)
{
$rel->Target = $attrNode->nodeValue;
}
}
array_push($this->rels, $rel);
}
}
}
//attempt to load styles:
if (($styleIndex = $zip->locateName('word/styles.xml')) !== false) {
$stylesXml = $zip->getFromIndex($styleIndex);
$xml = simplexml_load_string($stylesXml);
$XMLTEXT = $xml->saveXML();
$doc = new DOMDocument();
$doc->loadXML($XMLTEXT);
foreach($doc->documentElement->childNodes as $childnode)
{
$nodename = $childnode->nodeName;
//get style
if (strcmp($nodename, "w:style") == 0)
{
$ws_def = new Docx_ws_def;
for ($a=0; $a < $childnode->attributes->count(); $a++ )
{
$item = $childnode->attributes->item($a);
//style id
if (strcmp($item->nodeName, "w:styleId") == 0)
{
$ws_def->styleId = $item->nodeValue;
}
//style type
if (strcmp($item->nodeName, "w:type") == 0)
{
$ws_def->type = $item->nodeValue;
}
}
}
//push style to the array of styles
if (strcmp($ws_def->styleId, "") != 0 && strcmp($ws_def->type, "") != 0)
{
array_push($this->styles, $ws_def);
}
}
}
if (($index = $zip->locateName('word/document.xml')) !== false) {
$stylesDoc = $zip->getFromIndex($index);
$xml = simplexml_load_string($stylesDoc);
$XMLTEXT = $xml->saveXML();
$this->document = new DOMDocument();
$this->document->loadXML($XMLTEXT);
}
$zip->close();
} else {
switch($openedZip) {
case ZipArchive::ER_EXISTS:
$this->errors[] = 'File exists.';
break;
case ZipArchive::ER_INCONS:
$this->errors[] = 'Inconsistent zip file.';
break;
case ZipArchive::ER_MEMORY:
$this->errors[] = 'Malloc failure.';
break;
case ZipArchive::ER_NOENT:
$this->errors[] = 'No such file.';
break;
case ZipArchive::ER_NOZIP:
$this->errors[] = 'File is not a zip archive.';
break;
case ZipArchive::ER_OPEN:
$this->errors[] = 'Could not open file.';
break;
case ZipArchive::ER_READ:
$this->errors[] = 'Read error.';
break;
case ZipArchive::ER_SEEK:
$this->errors[] = 'Seek error.';
break;
}
}
} else {
$this->errors[] = 'File does not exist.';
}
}
public function setFile($path) {
$this->fileData = $this->load($path);
}
public function to_plain_text() {
if ($this->fileData) {
return strip_tags($this->fileData);
} else {
return false;
}
}
public function processDocument() {
$html = '';
foreach($this->document->documentElement->childNodes as $childnode)
{
$nodename = $childnode->nodeName;
//get the body of the document
if (strcmp($nodename, "w:body") == 0)
{
foreach($childnode->childNodes as $subchildnode)
{
$pnodename = $subchildnode->nodeName;
//process every paragraph
if (strcmp($pnodename, "w:p") == 0)
{
$pdef = new Docx_p_def;
foreach($subchildnode->childNodes as $pchildnode)
{
//process any inner children
if (strcmp($pchildnode, "w:pPr") == 0)
{
foreach($pchildnode->childNodes as $prchildnode)
{
//process text alignment
if (strcmp($prchildnode->nodeName, "w:pStyle") == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'styleId';
$pitem->value = $prchildnode->attributes->getNamedItem('val')->nodeValue;
array_push($pdef->data, $pitem);
}
//process text alignment
if (strcmp($prchildnode->nodeName, "w:jc") == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'align';
$pitem->value = $prchildnode->attributes->getNamedItem('val')->nodeValue;
if (strcmp($pitem->value, "left") == 0)
{
$pitem->innerstyle .= "text-align:" . $pitem->value . ";";
}
if (strcmp($pitem->value, "center") == 0)
{
$pitem->innerstyle .= "text-align:" . $pitem->value . ";";
}
if (strcmp($pitem->value, "right") == 0)
{
$pitem->innerstyle .= "text-align:" . $pitem->value . ";";
}
if (strcmp($pitem->value, "both") == 0)
{
$pitem->innerstyle .= "word-spacing:" . 10 . "px;";
}
array_push($pdef->data, $pitem);
}
//process drawing
if (strcmp($prchildnode->nodeName, "w:drawing") == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'drawing';
$pitem->value = '';
$pitem->type = 'graphic';
$extents = $prchildnode->getElementsByTagName('extent')[0];
$cx = $extents->attributes->getNamedItem('cx')->nodeValue;
$cy = $extents->attributes->getNamedItem('cy')->nodeValue;
$pcx = (int)$cx / 9525;
$pcy = (int)$cy / 9525;
$pitem->innerstyle .= "width:" . $pcx . "px;";
$pitem->innerstyle .= "height:" . $pcy . "px;";
$blip = $prchildnode->getElementsByTagName('blip')[0];
$pitem->value = $blip->attributes->getNamedItem('embed')->nodeValue;
array_push($pdef->data, $pitem);
}
//process spacing
if (strcmp($prchildnode->nodeName, "w:spacing") == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'paragraphSpacing';
$bval = $prchildnode->attributes->getNamedItem('before')->nodeValue;
if (strcmp($bval, '') == 0)
$bval = 0;
$pitem->innerstyle .= "padding-top:" . $bval . "px;";
$aval = $prchildnode->attributes->getNamedItem('after')->nodeValue;
if (strcmp($aval, '') == 0)
$aval = 0;
$pitem->innerstyle .= "padding-bottom:" . $aval . "px;";
array_push($pdef->data, $pitem);
}
}
}
if (strcmp($pchildnode, "w:r") == 0)
{
foreach($pchildnode->childNodes as $rchildnode)
{
//process text
if (strcmp($rchildnode->nodeName, "w:t") == 0)
{
$pdef->text .= $rchildnode->nodeValue;
if (count($pdef->data) == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'styleId';
$pitem->value = '';
array_push($pdef->data, $pitem);
}
}
if (strcmp($rchildnode->nodeName, "w:rPr") == 0)
{
foreach($rchildnode->childNodes as $rPrchildnode)
{
if (strcmp($rPrchildnode->nodeName, "w:b") == 0 )
{
$pitem = new Docx_p_item;
$pitem->name = 'textBold';
$pitem->value = '';
$pitem->innerstyle .= "text-weight: 500;";
array_push($pdef->data, $pitem);
}
if (strcmp($rPrchildnode->nodeName, "w:i") == 0 )
{
$pitem = new Docx_p_item;
$pitem->name = 'textItalic';
$pitem->value = '';
$pitem->innerstyle .= "text-style: italic;";
array_push($pdef->data, $pitem);
}
if (strcmp($rPrchildnode->nodeName, "w:u") == 0 )
{
$pitem = new Docx_p_item;
$pitem->name = 'textUnderline';
$pitem->value = '';
$pitem->innerstyle .= "text-decoration: underline;";
array_push($pdef->data, $pitem);
}
if (strcmp($rPrchildnode->nodeName, "w:sz") == 0 )
{
$pitem = new Docx_p_item;
$pitem->name = 'textSize';
$sz = $rPrchildnode->attributes->getNamedItem('val')->nodeValue;
if ($sz == '')
{
$sz=0;
}
$pitem->value = $sz;
array_push($pdef->data, $pitem);
}
}
}
}
}
}
array_push($this->paragraphs, $pdef);
}
}
}
}
}
public function to_html()
{
$html = '';
foreach($this->paragraphs as $para)
{
$styleselect = null;
$type = 'text';
$content = $para->text;
$sz = 0;
$extent = '';
$embedid = '';
$pinnerstylesid = '';
$pinnerstylesunderline = '';
$pinnerstylessz = '';
if (count($para->data) > 0)
{
foreach($para->data as $node)
{
if (strcmp($node->name, "styleId") == 0)
{
$type = $node->type;
$pinnerstylesid = $node->innerstyle;
foreach($this->styles as $style)
{
if (strcmp ($node->value, $style->styleId) == 0)
{
$styleselect = $style;
}
}
}
if (strcmp($node->name, "align") == 0)
{
$pinnerstylesid .= $node->innerstyle. ";";
}
if (strcmp($node->name, "drawing") == 0)
{
$type = $node->type;
$extent = $node->innerstyle;
$embedid = $node->value;
}
if (strcmp($node->name, "textSize") == 0)
{
$sz = $node->value;
}
if (strcmp($node->name, "textUnderline") == 0)
{
$pinnerstylesunderline = $node->innerstyle;
}
}
}
if (strcmp($type, 'text') == 0)
{
//echo "has valid para";
//echo "<br>";
if ($styleselect != null)
{
//echo "has valid style";
//echo "<br>";
if (strcmp($styleselect->color, '') != 0)
{
$pinnerstylesid .= "color:#" . $styleselect->color. ";";
}
}
if ($sz != 0)
{
$pinnerstylesid .= 'font-size:' . $sz . 'px;';
//echo "sz<br>";
}
$span = "<p style='". $pinnerstylesid . $pinnerstylesunderline ."'>";
$span .= $content;
$span .= "</p>";
//echo $span;
$html .= $span;
}
if (strcmp($type, 'graphic') == 0)
{
$imglnk = '';
foreach($this->rels as $rel)
{
if(strcmp($embedid, '') != 0 && strcmp($rel->Id, $embedid) == 0)
{
foreach($this->imglnks as $imgpathdef)
{
if (strpos($imgpathdef->extractedpath, $rel->Target) >= 0)
{
$imglnk = $imgpathdef->extractedpath;
//echo "has img link<br>";
//echo $imglnk . "<br>";
}
}
}
}
if ($styleselect != null)
{
//echo "has valid style";
//echo "<br>";
if (strcmp($styleselect->color, '') != 0)
{
$pinnerstylesid .= "color:#" . $styleselect->color. ";";
}
}
if ($sz != 0)
{
$pinnerstylesid .= 'font-size:' . $sz . 'px;';
//echo "sz<br>";
}
$span = "<p style='". $pinnerstylesid . $pinnerstylesunderline ."'>";
$span .= "<img style='". $extent ."' alt='image coming soon' src ='". $imglnk ."'/>";
$span .= "</p>";
//echo $span;
$html .= $span;
}
}
return $html;
}
public function get_errors() {
return $this->errors;
}
private function getStyles() {
}
}
function getDocX($path)
{
//echo $path;
$doc = new Docx_reader();
$doc->setFile($path);
if(!$doc->get_errors()) {
$doc->processDocument();
$html = $doc->to_html();
echo $html;
}
return "";
}
?>