PageRenderTime 40ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/components/com_myblog/libraries/imagebrowser.php

https://bitbucket.org/dgough/annamaria-daneswood-25102012
PHP | 512 lines | 309 code | 103 blank | 100 comment | 101 complexity | 2fe685b6acc59360880b8104a30d4757 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * MyBlog
  4. * @package MyBlog
  5. * @copyright (C) 2006 - 2008 by Azrul Rahim - All rights reserved!
  6. * @license Copyrighted Commercial Software
  7. **/
  8. (defined('_VALID_MOS') OR defined('_JEXEC')) or die('Direct Access to this location is not allowed.');
  9. // If the memory limit is too low, increase it
  10. if(ini_get('memory_limit') == '8M'){
  11. @ini_set('memory_limit', '16M');
  12. }
  13. //----------------------------------- FUNCTION ------------------------------------
  14. /**
  15. * Loads a directory based on parameter
  16. **/
  17. // function myxLoadFolder($directory){
  18. // global $_MY_CONFIG;
  19. //
  20. // $objResponse = new JAXResponse();
  21. //
  22. // $cms =& cmsInstance('CMSCore');
  23. // $cms->load('libraries', 'user');
  24. //
  25. // // Check if user really allowed to go out of current directory.
  26. // if($_MY_CONFIG->get('imgFolderRestrict') && $directory == '/..' && $cms->user->id != '62'){
  27. // $objResponse->addScriptCall('alert("Directory Permissions Error. Are you trying to exploit the system?");');
  28. // }else if($_MY_CONFIG->get('imgFolderRestrict') && $directory == '/..' && $cms->user->id == '62'){
  29. // // User is really allowed.
  30. // $printHTML = mnBrowse("$directory/");
  31. // $objResponse->addAssign('mn_fileExplorer','innerHTML', $printHTML);
  32. // }else {
  33. // // Other allowed directories.
  34. // $printHTML = mnBrowse("$directory/");
  35. // $objResponse->addAssign('mn_fileExplorer', 'innerHTML', $printHTML);
  36. // }
  37. // return $objResponse->sendResponse();
  38. // }
  39. /**
  40. * If imgFolderRestrict is enabled, we should first append the user folder in
  41. * the filename
  42. */
  43. function mnShowThumb($filename,$maxwidth=60){
  44. global $mainframe;
  45. $isCached = false;
  46. $cms =& cmsInstance('CMSCore');
  47. $filename = myGetImageBrowserRoot() . $filename;
  48. $cachedPath = $mainframe->getCfg('absolute_path').'/cache/cache_img'. md5($filename);
  49. if (is_file($cachedPath)){
  50. //$isCached = true;
  51. //$image_resized = $mosConfig_absolute_path.'/images/cache/'.md5($filename);
  52. if (strtolower (substr($filename,-3)) == 'png')
  53. header('Content-type: image/png');
  54. else if (strtolower (substr($filename,-3)) == 'gif')
  55. header('Content-type: image/gif');
  56. else if (strtolower (substr($filename,-3)) == 'jpg')
  57. header('Content-type: image/jpg');
  58. else
  59. header('Content-type: image/bmp');
  60. $handle = fopen($cachedPath, "r");
  61. $contents = fread($handle, filesize($cachedPath));
  62. fclose($handle);
  63. print($contents);
  64. die;
  65. } else if (!$isCached){
  66. $filename = urldecode($filename);
  67. $filepath = $filename;
  68. $image = mnOpenImage($filepath);
  69. if ($image === false) { die ('Unable to open image'); }
  70. // Get original width and height
  71. $width = imagesx($image);
  72. $height = imagesy($image);
  73. // New width and height
  74. if ($width > $maxwidth){
  75. $new_width = $maxwidth;
  76. $new_height = intval($maxwidth * $height / $width);
  77. } else {
  78. $new_width = $width;
  79. $new_height = $height;
  80. }
  81. $image_resized = imagecreatetruecolor( $new_width, $new_height );
  82. $background = imagecolorallocate($image_resized, 0, 0, 0);
  83. if (mnCheckFormat($filepath) == "gif" || mnCheckFormat($filepath) == "png"){
  84. ImageColorTransparent($image_resized, $background); // make the new temp image all transparent
  85. imagealphablending($image_resized, false); // turn off the alpha blending to keep the alpha channel
  86. }
  87. imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  88. // Display resized image
  89. ob_start();
  90. //imagejpeg ($image_resized, '', 70);
  91. $mimetype = mnCheckFormat($filepath);
  92. if ($mimetype == "gif"){
  93. header("Content-type: image/gif");
  94. imagegif ($image_resized);
  95. }
  96. else if ($mimetype == "png"){
  97. header("Content-type: image/png");
  98. imagepng ($image_resized, '', 7);
  99. }
  100. else{
  101. header("Content-type: image/jpeg");
  102. imagejpeg ($image_resized, '', 80);
  103. }
  104. $somecontent = ob_get_contents();
  105. ob_end_flush() ;
  106. // In our example we're opening $filename in append mode.
  107. // The file pointer is at the bottom of the file hence
  108. // that's where $somecontent will go when we fwrite() it.
  109. if (!$handle = fopen($cachedPath, 'w')) {
  110. echo "Cannot open file ($cachedPath)";
  111. exit;
  112. }
  113. // Write $somecontent to our opened file.
  114. if (fwrite($handle, $somecontent) === FALSE) {
  115. echo "Cannot write to file ($cachedPath)";
  116. exit;
  117. }
  118. fclose($handle);
  119. }
  120. die();
  121. }
  122. function mnPrintImage($filename){
  123. global $mainframe;
  124. $cms =& cmsInstance('CMSCore');
  125. $filename = urldecode($filename);
  126. $filename = $cms->get_path('root') . $filename;
  127. if (strtolower (substr($filename,-3)) == 'png')
  128. header('Content-type: image/png');
  129. else if (strtolower (substr($filename,-3)) == 'gif')
  130. header('Content-type: image/gif');
  131. else if (strtolower (substr($filename,-3)) == 'jpg')
  132. header('Content-type: image/jpg');
  133. else
  134. header('Content-type: image/bmp');
  135. $handle = fopen($filename, "r");
  136. print fread($handle, filesize($filename));
  137. fclose($handle);
  138. die();
  139. }
  140. function mnBrowse($directory = ''){
  141. global $mainframe, $_MY_CONFIG, $my;
  142. $cms =& cmsInstance('CMSCore');
  143. $cms->load('libraries', 'user');
  144. $imgroot = $_MY_CONFIG->get('imgFolderRoot');
  145. // The very base of url
  146. $basePath = myGetImageBrowserRoot();
  147. $baseUrl = myGetImageBrowserLive();
  148. $browseDir = $basePath. $directory;
  149. $browseUrl = $baseUrl .$directory;
  150. $dir = $browseDir;
  151. $cellcount=0;
  152. $thumnailperrow = "3";
  153. $thumnailmaxwidth = "44";
  154. $thumnailborder1 = "47";
  155. $thumnailborder2 = "46";
  156. $html = "";
  157. $html = <<< ENDHTML
  158. <script type="text/javascript">
  159. var dblClickTimer = false;
  160. function openFolder(path){
  161. jax.call('myblog', 'myxLoadFolder' , path);
  162. }
  163. </script>
  164. <table cellpadding=2 cellspacing=0 border=0>
  165. ENDHTML;
  166. $printdirarray = array();
  167. // List all files for the images folder
  168. if (is_dir($dir)) {
  169. if ($dh = opendir($dir)) {
  170. while (($file = readdir($dh)) !== false) {
  171. array_push($printdirarray, "$file");
  172. }
  173. closedir($dh);
  174. // Now we have all the files, group it into folders and files
  175. $files = array();
  176. $folders = array();
  177. foreach($printdirarray as $dirObject){
  178. if(is_file("$dir/$dirObject")){
  179. // Need to test is the file is an image. Use a simple
  180. // extenstion test
  181. $types = array(
  182. 'GIF', 'JPG', 'JPEG', 'PNG','SWF','PSD',
  183. 'BMP','TIFF','TIFF','JPC','JP2',
  184. 'JPX','JB2','SWC','IFF','WBMP','XBM'
  185. );
  186. $path_parts = pathinfo("$dir/$dirObject");
  187. if(!empty($path_parts['extension']) && in_array(strtoupper($path_parts['extension']) , $types))
  188. $files[] = $dirObject;
  189. } else
  190. $folders[] = $dirObject;
  191. }
  192. sort ($files);
  193. sort ($folders);
  194. // We don't need this anymore
  195. unset($printdirarray);
  196. // Now we have a list of files and folder, display them, obviously,
  197. // folder will be displayed first. And since, everything else if the
  198. // same except the last content, we can generate the content first
  199. $items = array();
  200. // Process folder items
  201. foreach($folders as $f){
  202. $img = '';
  203. $onclick = '';
  204. $title ='';
  205. $caption = '';
  206. if($f == '..' && !empty($directory) && $basePath != rtrim($browseDir, '\\/') ){
  207. $img = $cms->get_path('live') .'/components/com_myblog/images/folderup.gif';
  208. $parentPath = dirname($browseDir);
  209. $parentPath = str_replace($basePath, '', $parentPath);
  210. $onclick = "openFolder('$parentPath');";
  211. } elseif($f != '.'){
  212. $img = $cms->get_path('live').'/components/com_myblog/images/bigfolder.gif';
  213. $op = $f;
  214. if(empty($directory))
  215. $op = "/$op";
  216. $onclick = "openFolder('{$directory}{$op}');";
  217. }
  218. $title = $f;
  219. $caption = $f;
  220. if($f != '.' && $f != '/..'){
  221. $items[] = array('img' =>$img, 'onclick' => $onclick, 'title' => $title, 'caption' => $caption);
  222. } else if($f != '.' && $f == '/..' && !$_MY_CONFIG->get('imgFolderRestrict')){
  223. // If users are not restricted.
  224. $items[] = array('img' => $img, 'onclick' => $onclick, 'title' => $title, 'caption' => $caption);
  225. } else if ($f != '.' && $f == '/..' && $cms->user->id == '62') {
  226. // Default to allow admin to view all
  227. $items[] = array('img' => $img, 'onclick' => $onclick, 'title' => $title, 'caption' => $caption);
  228. }
  229. }
  230. // Process file items
  231. foreach($files as $f){
  232. $filepath = "$dir/$f";
  233. list($width, $height) = getimagesize($filepath);
  234. $img = '';
  235. $onclick = '';
  236. $title ='';
  237. $caption = '';
  238. // We assume files that we can getthe image sizes are the supported
  239. // ones
  240. if($sizes = getimagesize($filepath)){
  241. list($width, $height) = $sizes;
  242. $srcimg = rtrim ($browseUrl,'\\/') . '/' . ltrim ($f,'\\/');
  243. $img = $srcimg;
  244. if($width > $thumnailmaxwidth){
  245. $thumbimg = rtrim ($directory,'\\/') . '/' . ltrim ($f,'\\/');
  246. // If image is big, we parse it through a resizer
  247. $img = "index2.php?option=com_myblog&task=thumb&maxwidth=$thumnailmaxwidth&fn=". urlencode($thumbimg);
  248. }
  249. $onclick = "tinyMCE.execCommand('mceFocus',false, 'mce_editor_0'); ";
  250. $onclick .= "tinyMCE.execCommand('mceInsertContent',false, '<img border=\\'0\\' src=\\'$srcimg\\' /> ');";
  251. $caption = $f;
  252. $title = "$f - $width x $height";
  253. $items[] = array('img' =>$img, 'onclick' => $onclick, 'title' => $title, 'caption' => $caption);
  254. }
  255. }
  256. // Now, $items contain everything we need in the correct order. print
  257. // it out
  258. $html .= '<table>';
  259. foreach($items as $item){
  260. if (($cellcount % $thumnailperrow) == 0)
  261. $html .= "<tr>";
  262. $html .= '<td><div class="imgBrowserItem" style="cursor:pointer;width:100%" onclick="'.$item['onclick'].'" title="'.$item['title'].'">';
  263. $html .= '<table style="width:'.$thumnailborder1.'px; height: '.$thumnailborder1.'px; border: 1px solid #ece9d8;" align="center" valign="middle"><tr><td align="center" valign="middle">';
  264. $html .= '<img border="0" src="'.$item['img'].'" />';
  265. $html .= '</td></tr></table></div><div style="width:'.$thumnailborder1.'px;overflow:hidden; margin-bottom:2px">'.$item['caption'].'</div></td>';
  266. $cellcount++;
  267. if (($cellcount % $thumnailperrow) == 0)
  268. $html .= "</tr>";
  269. }
  270. $html .= '</table>';
  271. return $html;
  272. }
  273. }
  274. }
  275. function mnOpenImage ($file) {
  276. # JPEG:
  277. $im = @imagecreatefromjpeg($file);
  278. if ($im !== false) { return $im; }
  279. # GIF:
  280. $im = @imagecreatefromgif($file);
  281. if ($im !== false) { return $im; }
  282. # PNG:
  283. $im = @imagecreatefrompng($file);
  284. if ($im !== false) { return $im; }
  285. # GD File:
  286. $im = @imagecreatefromgd($file);
  287. if ($im !== false) { return $im; }
  288. # GD2 File:
  289. $im = @imagecreatefromgd2($file);
  290. if ($im !== false) { return $im; }
  291. # WBMP:
  292. $im = @imagecreatefromwbmp($file);
  293. if ($im !== false) { return $im; }
  294. # XBM:
  295. $im = @imagecreatefromxbm($file);
  296. if ($im !== false) { return $im; }
  297. # XPM:
  298. $im = @imagecreatefromxpm($file);
  299. if ($im !== false) { return $im; }
  300. # Try and load from string:
  301. $im = @imagecreatefromstring(file_get_contents($file));
  302. if ($im !== false) { return $im; }
  303. return false;
  304. }
  305. function mnCheckFormat ($file) {
  306. # JPEG:
  307. $im = @imagecreatefromjpeg($file);
  308. if ($im !== false) { return "jpeg"; }
  309. # GIF:
  310. $im = @imagecreatefromgif($file);
  311. if ($im !== false) { return "gif"; }
  312. # PNG:
  313. $im = @imagecreatefrompng($file);
  314. if ($im !== false) { return "png"; }
  315. # GD File:
  316. $im = @imagecreatefromgd($file);
  317. if ($im !== false) { return "gd"; }
  318. # GD2 File:
  319. $im = @imagecreatefromgd2($file);
  320. if ($im !== false) { return "gd2"; }
  321. # WBMP:
  322. $im = @imagecreatefromwbmp($file);
  323. if ($im !== false) { return "im"; }
  324. # XBM:
  325. $im = @imagecreatefromxbm($file);
  326. if ($im !== false) { return "xbm"; }
  327. # XPM:
  328. $im = @imagecreatefromxpm($file);
  329. if ($im !== false) { return "xpm"; }
  330. # Try and load from string:
  331. $im = @imagecreatefromstring(file_get_contents($file));
  332. if ($im !== false) { return "string"; }
  333. return false;
  334. }
  335. function myxAjaxUpload(){
  336. global $_MY_CONFIG;
  337. $error = "";
  338. $msg = "";
  339. //check if there are files uploaded
  340. if((isset($_FILES['fileToUpload']['error'])
  341. && $_FILES['fileToUpload'] == 0)
  342. || (!empty($_FILES['fileToUpload']['tmp_name'])
  343. && $_FILES['fileToUpload']['tmp_name'] != 'none')) {
  344. $userfile_name = $_FILES['fileToUpload']['name'];
  345. $savepath = myGetImageBrowserRoot(). '/'.$_FILES['fileToUpload']['name'];
  346. // Lowercase all extensions so that we can match it
  347. $extAllowed = strtolower($_MY_CONFIG->get('allowedUploadFileType'));
  348. $userfile_name = strtolower($userfile_name);
  349. // Verify file type, this isn't a very good code at all
  350. if (strpos($extAllowed, substr($userfile_name, -3)) === false){
  351. $error = $userfile_name . 'The file must be either'. $_MY_CONFIG->get('allowedUploadFileType');
  352. }
  353. // Check if image exceeds image upload size limit defined in My Blog config
  354. if ($_FILES['fileToUpload']['size'] >= $_MY_CONFIG->get('uploadSizeLimit') * 1024){
  355. $error = "Upload of ".$_FILES['fileToUpload']['name']." failed. File size too large.";
  356. }
  357. // Make sure similarly named files doesn't exist
  358. if(file_exists($savepath)){
  359. $error = "File with similar name already exist.";
  360. }
  361. // No error, move files to user's folder
  362. if(empty($error)){
  363. move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $savepath);
  364. }
  365. $msg .= " File Name: " . $_FILES['fileToUpload']['name'] . " successfully uploaded. ";
  366. //$msg .= " File Size: " . @filesize($_FILES['fileToUpload']['tmp_name']);
  367. //for security reason, we force to remove all uploaded file
  368. @unlink($_FILES['fileToUpload']);
  369. }else {
  370. $error = "No file has been uploaded.";
  371. }
  372. echo "{";
  373. echo "error: '" . $error . "',\n";
  374. echo "msg: '" . $msg . "'\n";
  375. echo "}";
  376. exit;
  377. }
  378. // Return the root path for current user. If the user is admin, it can view the
  379. // $_MY_CONFIG->get('imgFolderRoot') values, otherwise, if 'imgFolderRestrict' is
  380. // set, set the root path to userpath
  381. function myGetImageBrowserRoot(){
  382. global $_MY_CONFIG, $mainframe;
  383. $cms =& cmsInstance('CMSCore');
  384. $cms->load('libraries', 'user');
  385. $imgroot = $cms->get_path('root') .'/'. trim($_MY_CONFIG->get('imgFolderRoot'), '\\/');
  386. if($_MY_CONFIG->get('imgFolderRestrict')){
  387. $imgroot .= '/'.$cms->user->id;
  388. // Make sure the folder does exist, if not, create it
  389. if(!file_exists($imgroot)){
  390. mkdir($imgroot);
  391. }
  392. }
  393. return $imgroot;
  394. }
  395. function myGetImageBrowserLive(){
  396. global $_MY_CONFIG, $mainframe;
  397. $cms =& cmsInstance('CMSCore');
  398. $cms->load('libraries', 'user');
  399. $imgroot = $cms->get_path('live') .'/'. trim($_MY_CONFIG->get('imgFolderRoot'), '\\/');
  400. if($_MY_CONFIG->get('imgFolderRestrict')){
  401. $imgroot .= '/'.$cms->user->id;
  402. // This is for browsing.
  403. // Make sure the folder does exist, if not, create it
  404. // if(!file_exists($imgroot)){
  405. // mkdir($imgroot);
  406. // }
  407. }
  408. return $imgroot;
  409. }