PageRenderTime 59ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/source/libs/filemgr/global_function.php

https://github.com/yfg2014/ddim
PHP | 1257 lines | 935 code | 210 blank | 112 comment | 188 complexity | 0620383fb3904db41a4492390c811005 MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-1.0
  1. <?php
  2. function search($terms){
  3. global $database,$dateFormat,$fileinfo;
  4. jsonStart();
  5. $terms = mysql_escape_string($terms);
  6. foreach(getUserPaths() as $path){
  7. if(isset($where))$where .= " or ";
  8. $where .= "path like \"$path%\"";
  9. }
  10. #$query = "select *,date_format(`date`,\"$dateFormat\") as `dateformatted` from filesystem where ($where) and match(filename,description) against(\"$terms\")";
  11. $query = "select *,date_format(`date`,\"$dateFormat\") as `dateformatted`,match(filename,description,rpath) against(\"$terms\") as `rank` from $GLOBALS[tablePrefix]filesystem where ($where) and (match(filename,description,rpath) against(\"$terms\") or (filename like \"%$terms%\" or rpath like \"%$terms%\" or description like \"%$terms%\")) and status='found' order by rank desc";
  12. #echo $query;
  13. $resourceq = mysql_query($query,$database) ;
  14. #echo $resourceq;
  15. $toprank = 0.000001;
  16. while($files = mysql_fetch_assoc($resourceq)) {
  17. if($toprank == 0.000001 and $files['rank'] != 0)$toprank = $files['rank'];
  18. $myrank = round(($files['rank']/$toprank)*3)+2;
  19. getFileInfo($files['id']);
  20. jsonAdd("\"rank\":\"$myrank\",\"type\": \"file\", \"path\": \"$fileinfo[virtualpath]\",\"name\": \"$files[filename]\",\"date\":\"$files[dateformatted]\", \"id\": \"$files[id]\",\"flags\": \"$files[flags]\"");
  21. $results ++;
  22. }
  23. if($results > 0)
  24. echo jsonReturn('search');
  25. }
  26. function getFile($fileid){
  27. global $database,$filepath,$fileinfo;
  28. if(getFileInfo($fileid)){
  29. if(getUserAuth('download',$fileinfo['virtualpath'])){
  30. logAction('get',$fileid);
  31. $query = "update $GLOBALS[tablePrefix]filesystem set downloads=downloads+1 where id=$fileid";
  32. $result = mysql_query($query,$database);
  33. header("Pragma: public");
  34. header("Expires: 0");
  35. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  36. header("Cache-Control: private",false);
  37. header("Content-type: $fileinfo[type]");
  38. header("Content-Transfer-Encoding: Binary");
  39. header("Content-length: ".filesize($filepath));
  40. header("Content-disposition: attachment; filename=\"".basename($filepath)."\"");
  41. readfile("$filepath");
  42. }else{
  43. error("access denied to $fileid");
  44. }
  45. }else{
  46. error ('access denied');
  47. }
  48. }
  49. function emailFilePackage($fileids,$to,$from,$message){
  50. global $fileinfo,$filepath,$database;
  51. $fileids = preg_split("/\,/",$fileids);
  52. $boundary = "DU_" . md5(uniqid(time()));
  53. $headers = "From: $from". "\r\n";
  54. $headers .= "MIME-Version: 1.0"."\r\n";
  55. $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\";". "\r\n";
  56. $mailMessage = "--$boundary
  57. Content-Type: text/plain; charset=\"iso-8859-1\"
  58. Content-Transfer-Encoding: 7bit
  59. $message
  60. ";
  61. foreach($fileids as $fileid){
  62. if(getFileInfo($fileid)){
  63. #echo "$fileinfo[rpath] $fileid";
  64. if(getUserAuth('download',$fileinfo['virtualpath'])){
  65. logAction('get',$fileid);
  66. $query = "update $GLOBALS[tablePrefix]filesystem set downloads=downloads+1 where id=$fileid";
  67. $result = mysql_query($query,$database);
  68. $ct = $fileinfo['type'];
  69. if($ct=='')$ct = 'application/force-download';
  70. $mailMessage.= "--$boundary\nContent-Type: $ct\nContent-Transfer-Encoding: base64\nContent-Disposition: attachment; filename=\"$fileinfo[filename]\"\n\n";
  71. $mailMessage.= chunk_split(base64_encode(file_get_contents($filepath)));
  72. }
  73. }
  74. }
  75. $mailMessage.= "\n--$boundary--";
  76. #echo $mailMessage;
  77. ini_set(SMTP,'mvs5.duarte.com');
  78. if(mail($to,"File from $from",$mailMessage,$headers))
  79. $status = "Message Sent";
  80. else
  81. $status = "ERROR: Message Not Sent";
  82. #". base64_encode(getFilePackage($fileids,true))."
  83. #".file_get_contents($filepath)."
  84. jsonStart();
  85. jsonAdd("\"status\": \"$status\"");
  86. echo jsonReturn("bindings");
  87. }
  88. function getFilePackage($fileids,$returnContent = false){
  89. global $database,$fileinfo,$filepath;
  90. $fileids = preg_split("/\,/",$fileids);
  91. include_once("inc/createZip.inc.php");
  92. $createZip = new createZip;
  93. $fileCount = 0;
  94. logAction('getFilePackage',$fileids);
  95. foreach($fileids as $fileid){
  96. if(getFileInfo($fileid)){
  97. if(getUserAuth('download',$fileinfo['virtualpath'])){
  98. logAction('get',$fileid);
  99. $query = "update $GLOBALS[tablePrefix]filesystem set downloads=downloads+1 where id=$fileid";
  100. $result = mysql_query($query,$database);
  101. $createZip -> addFile(file_get_contents($filepath), "$fileinfo[filename]");
  102. $fileCount++;
  103. }else{
  104. // denied
  105. }
  106. }else{
  107. // denied
  108. }
  109. }
  110. if($fileCount > 0){
  111. if($returnContent != true){
  112. header("Content-Type: application/zip");
  113. header("Content-Transfer-Encoding: Binary");
  114. #header("Content-length: ".strlen($zipped));
  115. header("Content-disposition: attachment; filename=\"package.zip\"");
  116. echo $createZip -> getZippedfile();
  117. }else{
  118. return $createZip->getZippedfile();
  119. }
  120. }else{
  121. error('no files zipped');
  122. }
  123. }
  124. function getFolder($path){
  125. global $database,$resource,$dateFormat;
  126. userPermissions();
  127. $output = '';
  128. jsonStart();
  129. $path = mysql_escape_string($path);
  130. // For Virtual Directories
  131. if($path == '' || $path == '/'){
  132. $query = "select * from $GLOBALS[tablePrefix]permissions inner join $GLOBALS[tablePrefix]clients on $GLOBALS[tablePrefix]permissions.clientid=$GLOBALS[tablePrefix]clients.id where userid=\"$_SESSION[userid]\" and $GLOBALS[tablePrefix]clients.name =\"$_SESSION[user]\" order by display";
  133. $result = mysql_query($query,$database);
  134. while($clients = mysql_fetch_assoc($result))
  135. $output .= jsonAdd("\"displayname\":\"$clients[display]\",\"scheme\":\"$clients[scheme]\",\"type\": \"directory\", \"name\": \"$clients[name]\", \"path\": \"/$clients[name]\",\"virtual\":\"true\"");
  136. $query = "select * from $GLOBALS[tablePrefix]permissions inner join $GLOBALS[tablePrefix]clients on $GLOBALS[tablePrefix]permissions.clientid=$GLOBALS[tablePrefix]clients.id where userid=\"$_SESSION[userid]\" and $GLOBALS[tablePrefix]clients.name !=\"$_SESSION[user]\" order by display";
  137. $result = mysql_query($query,$database);
  138. $vdcount = mysql_num_rows($result);
  139. if($vdcount >= 1){ // If user has multiple virtual directorys display them all
  140. if($vdcount > 2){
  141. $virtual = "closed";
  142. }else if($vdcount == 1){
  143. $virtual = "true";
  144. }else{
  145. $virtual = "false";
  146. }
  147. while($clients = mysql_fetch_assoc($result)) {
  148. $output .= jsonAdd("\"displayname\":\"$clients[display]\",\"scheme\":\"$clients[scheme]\",\"type\": \"directory\", \"name\": \"$clients[name]\", \"path\": \"/$clients[name]\",\"virtual\":\"$virtual\"");
  149. }
  150. }
  151. $output .= jsonReturn('getFolder');
  152. #else{ // otherwise switch root directory to only virtual directory
  153. # $clients = mysql_fetch_assoc($result);
  154. # $path="/".$clients['name'];
  155. #}
  156. }
  157. if($output > ''){
  158. if($resource != true){
  159. echo $output;
  160. die;
  161. }else{
  162. return $output;
  163. }
  164. }
  165. // Non Virtual Directories
  166. if(getUserAuth('view',$path)){
  167. logAction('list',$path);
  168. $fullpath = getUserPath($path).$path;
  169. databaseSync($fullpath,$path);
  170. if (is_dir($fullpath)) {
  171. if ($dh = opendir($fullpath)) {
  172. while (($file = readdir($dh)) !== false) {
  173. #echo "$file";
  174. if($file != '.' && $file != '..' && filetype($fullpath . '/' . $file) == 'dir'){
  175. jsonAdd("\"type\": \"directory\", \"name\": \"$file\", \"path\": \"$path/$file\"");
  176. }
  177. }
  178. closedir($dh);
  179. }
  180. }else{
  181. error("directory doesnt exist $fullpath");
  182. }
  183. $query = "select *,date_format(`date`,\"$dateFormat\") as `dateformatted` from $GLOBALS[tablePrefix]filesystem where path=\"$fullpath\" and status=\"found\" order by `date` desc";
  184. $result = mysql_query($query,$database);
  185. while($files = mysql_fetch_assoc($result)) {
  186. jsonAdd("\"type\": \"file\", \"name\": \"$files[filename]\",\"date\":\"$files[dateformatted]\", \"id\": \"$files[id]\",\"flags\": \"$files[flags]\"");
  187. }
  188. $output .= jsonReturn('getFolder');
  189. if($resource != true)
  190. echo $output;
  191. else
  192. return $output;
  193. }else{
  194. error('no auth to view');
  195. }
  196. }
  197. function getFolderMeta($path){
  198. jsonStart();
  199. $path = mysql_escape_string($path);
  200. if(getUserAuth('view',$path)){
  201. logAction('getFolderMeta',$path);
  202. $fullpath = getUserPath($path).$path;
  203. $size = filesize_format(get_size($fullpath));
  204. $name = basename($fullpath);
  205. $modified = '';
  206. $created ='';
  207. jsonAdd("\"name\": \"$name\", \"size\": \"$size\"");
  208. echo jsonReturn('getFolderMeta');
  209. }else{
  210. error('access denied');
  211. }
  212. }
  213. function getMeta($fileid){
  214. global $fileinfo;
  215. if(getFileInfo($fileid)){
  216. if(getUserAuth('view',$fileinfo['virtualpath'])){
  217. jsonStart();
  218. logAction('getMeta',$fileid);
  219. if(getUserAuth('metaEdit',$fileinfo['virtualpath']))
  220. {
  221. jsonAdd("\"edit\": \"true\"");
  222. }else{
  223. jsonAdd("\"edit\": \"false\"");
  224. }
  225. if($fileinfo['type'] > '')
  226. $type = $fileinfo['type'];
  227. else
  228. $type = "document";
  229. jsonAdd("\"filename\": \"$fileinfo[filename]\",\"path\": \"$fileinfo[virtualpath]\",\"image\":$fileinfo[image],\"type\": \"$type\", \"date\": \"$fileinfo[date]\", \"downloads\": \"$fileinfo[downloads]\", \"description\": \"$fileinfo[description]\", \"flags\": \"$fileinfo[flags]\", \"type\": \"$fileinfo[type]\", \"size\": \"$fileinfo[size]\"");
  230. if($type == "image/jpeg"){
  231. if(function_exists("exif_read_data")){
  232. $exif = exif_read_data($fileinfo['path'].'/'.$fileinfo['filename']);
  233. }
  234. }
  235. }else{
  236. error('access denied2');
  237. }
  238. }else{
  239. error('access denied1');
  240. }
  241. echo jsonReturn('getMeta');
  242. }
  243. function setMeta($fileid,$filename,$description,$flags){
  244. global $database,$fileinfo;
  245. $fileid = mysql_escape_string($fileid);
  246. $filename = mysql_escape_string($filename);
  247. $description = mysql_escape_string($description);
  248. $flags = mysql_escape_string($flags);
  249. if(getFileInfo($fileid)){
  250. if(getUserAuth('metaEdit',$fileinfo['virtualpath'])){
  251. logAction('metaEdit',$fileid);
  252. if($filename != $fileinfo['filename']){
  253. fileRename($fileid,$filename);
  254. }else{
  255. $filename = $fileinfo['filename'];
  256. }
  257. $query = "update $GLOBALS[tablePrefix]filesystem set description=\"$description\",flags=\"$flags\" where id=$fileid";
  258. $result = mysql_query($query,$database);
  259. echo "done";
  260. }else{error('access denied');}
  261. }else{error('access denied');}
  262. }
  263. function fileRename($fileid,$filename){
  264. global $database,$fileinfo;
  265. $fileid = mysql_escape_string($fileid);
  266. $filename = mysql_escape_string($filename);
  267. $filename = str_replace("\\","",$filename);
  268. $filename = str_replace("/","",$filename);
  269. if(getFileInfo($fileid)){
  270. if(getUserAuth('rename',$fileinfo['virtualpath'])){
  271. logAction('rename',$fileid);
  272. $query = "update $GLOBALS[tablePrefix]filesystem set filename=\"$filename\" where id=$fileid";
  273. $result = mysql_query($query,$database);
  274. rename($fileinfo['path'].'/'.$fileinfo['filename'],$fileinfo['path'].'/'.$filename);
  275. } else{
  276. error('rename denied');
  277. }
  278. }else{
  279. error('rename denied');
  280. }
  281. }
  282. function fileDelete($fileid){
  283. global $database,$fileinfo;
  284. $fileid = mysql_escape_string($fileid);
  285. if(getFileInfo($fileid)){
  286. if(getUserAuth('delete',$fileinfo['virtualpath'])){
  287. logAction('delete',$fileid);
  288. $query = "delete from $GLOBALS[tablePrefix]filesystem where id=$fileid";
  289. $result = mysql_query($query,$database);
  290. unlink($fileinfo['path'].'/'.$fileinfo['filename']) || error('file error');
  291. echo "done";
  292. }else{error('file access denied');}
  293. }else{
  294. error('access denied');
  295. }
  296. }
  297. function fileMove($fileid,$path){
  298. global $database,$fileinfo;
  299. $fileid = mysql_escape_string($fileid);
  300. $path = str_replace("//","/",$path);
  301. $path = str_replace("..","",$path);
  302. $path = mysql_escape_string($path);
  303. if(getFileInfo($fileid)){
  304. if(getUserAuth('move',$path) && getUserAuth('move',$fileinfo['virtualpath'])){
  305. $newPath = getUserPath($path).$path;
  306. if(is_dir($newPath)){
  307. logAction('move',$fileid);
  308. $query = "update $GLOBALS[tablePrefix]filesystem set path=\"$newPath\",rpath=\"$path\" where id=$fileid";
  309. $result = mysql_query($query,$database);
  310. rename($fileinfo['path'].'/'.$fileinfo['filename'],$newPath.'/'.$fileinfo['filename']);
  311. echo "done";
  312. }else{
  313. error('new directory doesnt exist');
  314. }
  315. }else{
  316. error('file move denied');
  317. }
  318. }else{
  319. error('move denied');
  320. }
  321. }
  322. function folderRename($path,$name,$newname){
  323. global $database;
  324. $newname = mysql_escape_string($newname);
  325. $name = mysql_escape_string($name);
  326. $path = mysql_escape_string($path);
  327. if(getUserAuth('folderRename',$path)){
  328. $currentPath = getUserPath($path).$path.'/'.$name;
  329. $newPath = getUserPath($path).$path.'/'.$newname;
  330. if(is_dir($currentPath) && !is_dir($newPath)){
  331. logAction('folderRename',$newPath);
  332. if(rename($currentPath,$newPath)){
  333. $query = "update $GLOBALS[tablePrefix]filesystem set path=\"$newPath\",rpath=\"$path/$newname\" where path=\"$currentPath\"";
  334. $result = mysql_query($query,$database);
  335. echo "done";
  336. }else{
  337. echo "error";
  338. }
  339. }else{
  340. error('old name doesnt exist or new name already exists');
  341. }
  342. }else{
  343. error('rename denied');
  344. }
  345. }
  346. function folderMove($name,$path,$newpath){
  347. global $database;
  348. $name = mysql_escape_string($name);
  349. $path = mysql_escape_string($path);
  350. $newpath = str_replace("..","",$newpath);
  351. $newpath = mysql_escape_string($newpath);
  352. if(getUserAuth('folderMove',$path) && getUserAuth('folderMove',$newpath)){
  353. $userPath = getUserPath($path).$path.'/'.$name;
  354. $userNewPath = getUserPath($newpath).$newpath.'/'.$name;
  355. if(is_dir($userPath) && !is_dir($userNewPath)){
  356. logAction('folderMove',$userNewPath);
  357. if(rename($userPath,$userNewPath)){
  358. $query = "update $GLOBALS[tablePrefix]filesystem set path=\"$userNewPath\",rpath=\"$newpath/$name\" where path=\"$userPath\"";
  359. $result = mysql_query($query,$database);
  360. echo "done";
  361. }else{
  362. echo "error";
  363. }
  364. }else{
  365. error('old name doesnt exist or new name already exists');
  366. }
  367. }else{
  368. error('move denied');
  369. }
  370. }
  371. function folderDelete($folder){
  372. global $database;
  373. $folder = mysql_escape_string($folder);
  374. if(getUserAuth('folderDelete',$folder)){
  375. $deleteDir = getUserPath($folder).$folder;
  376. logAction('folderDelete',$deleteDir);
  377. if(deleteDir($deleteDir)){
  378. $query = "delete from $GLOBALS[tablePrefix]filesystem where path like \"$deleteDir\%\"";
  379. $result = mysql_query($query,$database);
  380. echo "ok";
  381. }else{
  382. echo "oops somethings wrong";
  383. }
  384. }else{
  385. error('delete denied');
  386. }
  387. }
  388. function newFolder($name,$path){
  389. global $database;
  390. $name = mysql_escape_string($name);
  391. $path = mysql_escape_string($path);
  392. $fullpath = getUserPath($path).$path.'/'.$name;
  393. if(getUserAuth('newFolder',$path)){
  394. logAction('newFolder',$path.'/'.$name);
  395. $i = 1;
  396. $append = "";
  397. while(is_dir($fullpath.$append)){
  398. $append = " $i";
  399. $i++;
  400. }
  401. if(mkdir($fullpath.$append)){
  402. echo "ok";
  403. }else{
  404. echo "oops somethings wrong";
  405. }
  406. }else{
  407. error('new folder');
  408. }
  409. }
  410. function checkLogin(){
  411. jsonStart();
  412. logAction('checkLogin',$_SESSION['user']);
  413. if(isset($_SESSION['userid'])){
  414. jsonAdd("\"login\": \"true\",\"name\": \"$_SESSION[name]\"");
  415. }else{
  416. jsonAdd("\"login\": \"false\"");
  417. }
  418. echo jsonReturn('userLogin');
  419. }
  420. function newPassword($current,$new){
  421. $query = "select * from $GLOBALS[tablePrefix]users where id=$_SESSION[userid] and password=md5(\"G8,rMzw6BrBApLU9$current\")";
  422. $result = mysql_query($query);
  423. if(mysql_num_rows($result) == 1){
  424. logAction('newPassword',$_SESSION['user']);
  425. $pass = mysql_escape_string($_GET['pass']);
  426. $query = "update $GLOBALS[tablePrefix]users set `password`=md5(\"G8,rMzw6BrBApLU9$new\") where id=$_SESSION[userid]";
  427. $result = mysql_query($query)||die(mysql_error());
  428. }else{
  429. error("bad current password");
  430. }
  431. }
  432. function userLogoff(){
  433. session_destroy();
  434. header('Location:index.php');
  435. exit;
  436. }
  437. function userLogin($username,$password){
  438. session_start();
  439. $_SESSION['userid'] = NULL;
  440. include_once("inc/adLDAP.php");
  441. global $database,$passwordKey;
  442. $username = mysql_escape_string($username);
  443. $password = mysql_escape_string($password);
  444. #ADauth check
  445. $query = "select * from $GLOBALS[tablePrefix]users where username=\"$username\"";
  446. $result = mysql_query($query);
  447. $userinfo = mysql_fetch_assoc($result);
  448. if($userinfo['ADauth'] == 1){
  449. $ADconn = new adLDAP;
  450. if($ADconn->authenticate($username,$password)){
  451. #success
  452. $loginSuccess = true;
  453. }else{
  454. $loginSuccess = false;
  455. }
  456. }else{
  457. $query = "select * from $GLOBALS[tablePrefix]users where username=\"$username\" and password=md5(\"$passwordKey$password\")";
  458. $result = mysql_query($query,$database);
  459. if($userinfo = mysql_fetch_assoc($result)){
  460. $loginSuccess = true;
  461. }
  462. }
  463. if($loginSuccess == true) {
  464. $_SESSION['userid']=$userinfo['id'];
  465. $_SESSION['user']=$username;
  466. $_SESSION['name']=$userinfo['name'];
  467. $_SESSION['path']=array();
  468. $_SESSION['admin']=$userinfo['admin'];
  469. userPermissions();
  470. logAction('login',$username);
  471. if($GLOBALS['resource'] != true)checkLogin();
  472. }else{
  473. logAction('loginFail',$username);
  474. if($GLOBALS['resource'] != true)checkLogin();
  475. }
  476. }
  477. function userPermissions(){
  478. global $database;
  479. if(isset($_SESSION['userid'])){
  480. $perQuery = "select $GLOBALS[tablePrefix]permissions.*,$GLOBALS[tablePrefix]clients.name as `cname`,$GLOBALS[tablePrefix]clients.path as `cpath`,$GLOBALS[tablePrefix]clients.id as `cid` from $GLOBALS[tablePrefix]permissions inner join $GLOBALS[tablePrefix]clients on $GLOBALS[tablePrefix]permissions.clientid=$GLOBALS[tablePrefix]clients.id where userid=\"$_SESSION[userid]\"";
  481. $permissions = mysql_query($perQuery,$database) or die(mysql_error());
  482. $_SESSION["admin.cid"]='';
  483. $_SESSION["path"]='';
  484. if(mysql_num_rows($permissions) > 0)
  485. while($userPermissions = mysql_fetch_assoc($permissions)) {
  486. #print_r($userPermissions);
  487. $thispath = $userPermissions['cpath'].'/'.$userPermissions['cname'];
  488. $_SESSION['path'][]=$thispath;
  489. $thispath = $userPermissions['cname'];
  490. $admin = $userPermissions['admin'];
  491. $_SESSION["auth.$thispath.view"]=$userPermissions['view'];
  492. $_SESSION["auth.$thispath.rename"]=$userPermissions['rename'];
  493. $_SESSION["auth.$thispath.download"]=$userPermissions['download'];
  494. $_SESSION["auth.$thispath.metaEdit"]=$userPermissions['metaEdit'];
  495. $_SESSION["auth.$thispath.delete"]=$userPermissions['delete'];
  496. $_SESSION["auth.$thispath.move"]=$userPermissions['move'];
  497. $_SESSION["auth.$thispath.folderRename"]=$userPermissions['folderRename'];
  498. $_SESSION["auth.$thispath.folderDelete"]=$userPermissions['folderDelete'];
  499. $_SESSION["auth.$thispath.folderMove"]=$userPermissions['folderMove'];
  500. $_SESSION["auth.$thispath.newFolder"]=$userPermissions['newFolder'];
  501. $_SESSION["auth.$thispath.upload"]=$userPermissions['upload'];
  502. if($admin==1){
  503. $cid = $userPermissions['cid'];
  504. $_SESSION["auth.$cid.admin"]=1;
  505. $_SESSION["admin.cid"][]=$cid;
  506. }
  507. }
  508. }
  509. }
  510. // internal functions //
  511. function logAction($type,$details){
  512. global $database;
  513. $type = mysql_escape_string($type);
  514. $details = mysql_escape_string($details);
  515. $query = "insert into $GLOBALS[tablePrefix]log set user=\"$_SESSION[user]\",ip=\"$_SERVER[REMOTE_ADDR]\",type=\"$type\",details=\"$details\"";
  516. $result = mysql_query($query,$database);
  517. }
  518. function getUserAuth($type,$path){
  519. if(isset($_SESSION['userid'])){
  520. $paths = preg_split("/\//", $path); // isolate virtual directory name
  521. return (isset($_SESSION['auth.'.$paths[1].'.'.$type]))?$_SESSION['auth.'.$paths[1].'.'.$type]:false;
  522. }
  523. }
  524. function getFileInfo($fileid){
  525. global $database,$filepath,$fileinfo,$imageTypes;
  526. $fileid=mysql_escape_string($fileid);
  527. $query = "select * from $GLOBALS[tablePrefix]filesystem where id=$fileid";
  528. $result = mysql_query($query,$database);
  529. if(mysql_num_rows($result) == 0){
  530. error('bad fileid');
  531. }
  532. $file = mysql_fetch_assoc($result);
  533. $fileinfo['filename'] = $file['filename'];
  534. $fileinfo['date'] = $file['date'];
  535. $fileinfo['description'] = $file['description'];
  536. $fileinfo['downloads'] = $file['downloads'];
  537. $fileinfo['flags'] = $file['flags'];
  538. $fileinfo['type'] = $file['type'];
  539. $fileinfo['uploader'] = $file['uploader'];
  540. $fileinfo['path'] = $file['path'];
  541. $fileinfo['virtualpath'] = $file['rpath'];
  542. $fileinfo['size'] = filesize_format($file['size']);
  543. if(preg_match("$imageTypes",$fileinfo['type'])){
  544. $fileinfo['image'] = 1;
  545. }else{
  546. $fileinfo['image'] = 0;
  547. }
  548. $filePath = $fileinfo['path'];
  549. /*
  550. if(isset($_SESSION['path']))
  551. foreach($_SESSION['path'] as $checkPath){
  552. #echo "$filePath $checkPath<br>";
  553. if(substr( $filePath, 0, strlen( $checkPath ) ) == $checkPath){
  554. $path = substr($filePath,strlen($checkPath));
  555. $checkPathArray = preg_split("/\//",$checkPath);
  556. $virtualPath = $checkPathArray[count($checkPathArray)-1];
  557. $fileinfo['virtualpath'] = "/$virtualPath$path";
  558. }
  559. }
  560. */
  561. $filepath = $file['path'] . '/' . $file['filename'];
  562. $userpath = getUserPath($fileinfo['path']); // replaces / with \/ from preg_match
  563. if(preg_match("/$userpath/i",$filepath)){
  564. return true;
  565. }else{
  566. return false;
  567. }
  568. }
  569. function getUserPaths(){
  570. global $database;
  571. $paths='';
  572. $query = "select * from $GLOBALS[tablePrefix]permissions inner join $GLOBALS[tablePrefix]clients on $GLOBALS[tablePrefix]permissions.clientid=$GLOBALS[tablePrefix]clients.id where userid=\"$_SESSION[userid]\"";
  573. $result = mysql_query($query,$database);
  574. while($clients = mysql_fetch_assoc($result)) {
  575. $paths[] = $clients['path'].'/'.$clients['name'];
  576. }
  577. return $paths;
  578. }
  579. function getUserPath($folderPath){
  580. global $database;
  581. if(isset($_SESSION['userid'])){
  582. $dirStructure = preg_split("/\//",$folderPath);
  583. $rootPath = (isset($dirStructure[1]))?$dirStructure[1]:'';
  584. $rootPath = mysql_escape_string($rootPath);
  585. if($rootPath==''){return '';}
  586. $query = "select * from $GLOBALS[tablePrefix]clients inner join $GLOBALS[tablePrefix]permissions on $GLOBALS[tablePrefix]permissions.clientid=$GLOBALS[tablePrefix]clients.id and $GLOBALS[tablePrefix]permissions.userid=$_SESSION[userid] where name=\"$rootPath\"";
  587. $result = mysql_query($query,$database) or die(mysql_error());
  588. $file = mysql_fetch_assoc($result);
  589. return mysql_escape_string($file['path']);
  590. }
  591. }
  592. function databaseSync($folderpath,$realitivePath=''){
  593. global $database;
  594. // get files from $folderpath and put them in array
  595. if (is_dir($folderpath)) {
  596. if ($dh = opendir($folderpath)) {
  597. while (($file = readdir($dh)) !== false) {
  598. #echo "$file";
  599. if($file != '.' && $file != '..' && filetype($folderpath . '/' . $file) == 'file' && substr($file,0,1) != '.'){
  600. $fileid = fileid($folderpath,$file);
  601. $files[$file] = array($fileid,'exist');
  602. #echo "1 $file<br>";
  603. }
  604. }
  605. closedir($dh);
  606. }
  607. }
  608. // get files from database
  609. $query = "select * from $GLOBALS[tablePrefix]filesystem where path=\"".mysql_escape_string($folderpath)."\" and status=\"found\"";
  610. $result = mysql_query($query,$database);
  611. while($dirinfo = mysql_fetch_assoc($result)) {
  612. $filename = $dirinfo['filename'];
  613. $fileid = $dirinfo['id'];
  614. if(isset($files[$filename]) && $files[$filename][0] == $dirinfo['id']){
  615. $files[$filename][1]='done';
  616. }else{
  617. databaseLost($fileid);
  618. }
  619. }
  620. if(isset($files)){
  621. $ak = array_keys($files);
  622. for($i=0;$i<sizeof($ak);$i++){
  623. $filename = $ak[$i];
  624. if($files[$filename][1]!='done'){
  625. #echo "$filename to search<br>";
  626. if(databaseSearch($folderpath , $filename)){
  627. databaseUpdate($folderpath,$filename,$realitivePath);
  628. }else{
  629. databaseAdd($folderpath,$filename,$realitivePath);
  630. }
  631. }
  632. }
  633. }
  634. }
  635. function databaseLost($fileid){
  636. global $database;
  637. $query = "update $GLOBALS[tablePrefix]filesystem set status=\"lost\" where id=$fileid";
  638. #echo $query;
  639. $result = mysql_query($query,$database) or die(mysql_error());
  640. }
  641. function databaseSearch($folderpath,$filename){
  642. global $database;
  643. $fileid = fileid($folderpath,$filename);
  644. $query = "select * from $GLOBALS[tablePrefix]filesystem where id=$fileid";
  645. $result = mysql_query($query,$database) or die(mysql_error());
  646. if($fileinfo = mysql_fetch_assoc($result)) {
  647. if(file_exists($fileinfo['path'].'/'.$fileinfo['filename'])){
  648. if($fileinfo['path'] == $folderpath && $fileinfo['filename'] == $filename){
  649. return true; // file was restored to origional location
  650. }else{
  651. return false; // exact file still exists somewhere else
  652. }
  653. }else{
  654. // file must have been moved
  655. return true;
  656. }
  657. }else{
  658. // file is new
  659. return false;
  660. }
  661. }
  662. function databaseUpdate($folderpath,$filename,$realitivePath){
  663. global $database,$finfo;
  664. $fileid = fileid($folderpath,$filename);
  665. $query = "update $GLOBALS[tablePrefix]filesystem set filename=\"$filename\",path=\"$folderpath\",rpath=\"$realitivePath\",status=\"found\" where id=$fileid";
  666. $result = mysql_query($query,$database);
  667. }
  668. function databaseAdd($folderpath,$filename,$realitivePath){
  669. global $database,$rootpath;
  670. if(function_exists('finfo')){
  671. $finfo = new finfo( FILEINFO_MIME,"$rootpath/inc/magic" );
  672. $type = $finfo->file( "$folderpath/$filename" );
  673. }else if(function_exists('mime_content_type') && mime_content_type("relay.php") != ""){
  674. $type = mime_content_type("$folderpath/$filename");
  675. }else{
  676. if(!$GLOBALS['mime']){
  677. include_once("inc/mimetypehandler.class.php");
  678. $GLOBALS['mime'] = new MimetypeHandler();
  679. }
  680. $type = $GLOBALS['mime']->getMimetype("$filename");
  681. }
  682. $size = get_size($folderpath.'/'.$filename);
  683. $fileid = fileid($folderpath,$filename);
  684. while(!checkId($fileid)){
  685. $fileid++;
  686. }
  687. $query = "insert into $GLOBALS[tablePrefix]filesystem set id=\"$fileid\",filename=\"$filename\",path=\"$folderpath\",rpath=\"$realitivePath\",type=\"$type\",size=\"$size\"";
  688. $result = mysql_query($query,$database) or die(mysql_error());
  689. chmod($folderpath . '/' . $filename,0755);
  690. touch($folderpath . '/' . $filename,$fileid);
  691. }
  692. function checkId($id){
  693. $query = "select id from $GLOBALS[tablePrefix]filesystem where id=$id";
  694. $result = mysql_query($query);
  695. if(mysql_num_rows($result) == 0){
  696. return true;
  697. }else{
  698. return false;
  699. }
  700. }
  701. function fileid($folderpath,$filename){
  702. $fileid = stat($folderpath . '/' . $filename);
  703. return $fileid[9];
  704. }
  705. function error($message){
  706. echo "{\"bindings\": [ {'error': \"$message\"} ]}";
  707. exit;
  708. }
  709. /*
  710. THUMBNAIL
  711. */
  712. function output_handler($in){
  713. global $output;
  714. $output="$in";
  715. }
  716. function getThumb($fileid){
  717. global $database,$fileinfo;
  718. if(getFileInfo($fileid)){ // if a file type we want to deal with
  719. if(!checkThumb($fileid)){
  720. thumbnail($fileid);
  721. }
  722. $query = "select thumb from $GLOBALS[tablePrefix]filesystem where id=\"".mysql_escape_string($fileid)."\"";
  723. $result = mysql_query($query,$database);
  724. $fileThumb = mysql_fetch_assoc($result);
  725. header("Content-type:image/jpeg");
  726. echo $fileThumb['thumb'];
  727. }
  728. }
  729. function checkThumb($fileid){
  730. global $database;
  731. $query = "select id from $GLOBALS[tablePrefix]filesystem where id=\"".mysql_escape_string($fileid)."\" and thumb !=''";
  732. $result = mysql_query($query,$database);
  733. if(mysql_num_rows($result) == 0)
  734. return false;
  735. else
  736. return true;
  737. }
  738. function thumbnail($fileid){
  739. $thumbsize = 192;
  740. global $convertpath, $database,$fileinfo,$output,$imageTypes,$resource,$ghostScript;
  741. $fileid=mysql_escape_string($fileid);
  742. if(getFileInfo($fileid) && preg_match("$imageTypes",$fileinfo['type']) ){
  743. $deletefile = '';
  744. if (preg_match("/image\/jpeg/",$fileinfo['type'])){$src_img=imagecreatefromjpeg($fileinfo['path'].'/'.$fileinfo['filename']);}
  745. elseif (preg_match("/image\/png/",$fileinfo['type'])){$src_img=imagecreatefrompng($fileinfo['path'].'/'.$fileinfo['filename']);}
  746. elseif (preg_match("/application\/pdf/",$fileinfo['type'])){
  747. $file1 = $fileinfo['path'].'/'.$fileinfo['filename'];
  748. $file2 = $fileinfo['path'].'/'.$fileinfo['filename'] .'temp';
  749. #echo "E:/duarte.com/relay/supportapps/gs/gs8.50/bin/gswin32c.exe -q -dNOPAUSE -dBATCH -sDEVICE=jpeg -sOutputFile=\"$file2\" \"$file1\" 2>&1";
  750. $code = "$ghostScript -q -dNOPAUSE -dBATCH -dFirstPage=1 -dLastPage=1 -sDEVICE=jpeg -sOutputFile=\"$file2\" \"$file1\" 2>&1";
  751. #if($resource == true)echo "$code";
  752. $result1 = @exec($code);
  753. $src_img=imagecreatefromjpeg($file2);
  754. $deletefile = $file2;
  755. }elseif(preg_match("/image\/x-photoshop|image\/|application\/postscript/",$fileinfo['type'])){
  756. #image magic coolthings
  757. $file1 = $fileinfo['path'].'/'.$fileinfo['filename'];
  758. $file2 = $fileinfo['path']."/thumb_$fileid.jpg";
  759. $code = "$convertpath \"$file1\" -render -flatten -resize ".$thumbsize."x".$thumbsize." \"$file2\"";
  760. #echo "$code";
  761. $result1 = @exec($code);
  762. $src_img=imagecreatefromjpeg($file2);
  763. $deletefile = $file2;
  764. }
  765. $old_x=imageSX($src_img);
  766. $old_y=imageSY($src_img);
  767. if ($old_x > $old_y)
  768. {
  769. $thumb_w=$thumbsize;
  770. $thumb_h=$old_y*($thumbsize/$old_x);
  771. }
  772. if ($old_x < $old_y)
  773. {
  774. $thumb_w=$old_x*($thumbsize/$old_y);
  775. $thumb_h=$thumbsize;
  776. }
  777. if ($old_x == $old_y)
  778. {
  779. $thumb_w=$thumbsize;
  780. $thumb_h=$thumbsize;
  781. }
  782. $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
  783. imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
  784. ob_start("output_handler");
  785. imagejpeg($dst_img,'',70);
  786. ob_end_clean();
  787. $thumb = mysql_escape_string($output);
  788. $query = "update $GLOBALS[tablePrefix]filesystem set thumb=\"$thumb\" where id=\"$fileid\"";
  789. #echo $query;
  790. $result = mysql_query($query,$database) || die("angry death");
  791. if ($deletefile > ''){
  792. unlink($deletefile);
  793. }
  794. #imagedestroy($dst_img);
  795. #imagedestroy($src_img);
  796. }
  797. }
  798. /*
  799. UPLOAD
  800. */
  801. function upload($dir){
  802. if(getUserAuth('upload',$dir)){
  803. $userpath = getUserPath($dir).$dir;
  804. $tmp_name = $_FILES["upload"]["tmp_name"];
  805. $uploadfile = basename($_FILES['upload']['name']);
  806. $i=1;
  807. while(file_exists($userpath.'/'.$uploadfile)){
  808. $uploadfile = $i . '_' . basename($_FILES['upload']['name']);
  809. $i++;
  810. }
  811. move_uploaded_file($tmp_name, $userpath.'/'.$uploadfile);
  812. }
  813. if(isset($_GET['redir'])){
  814. header("location: $_GET[redir]");
  815. }
  816. }
  817. function uploadAuth($path){
  818. global $uploadDir;
  819. $path = mysql_escape_string($path);
  820. jsonStart();
  821. if(getUserAuth('upload',$path)){
  822. $userpath = getUserPath($path).$path;
  823. if(is_dir($userpath)){
  824. $_SESSION['uploadPath'] = $path;
  825. if(file_exists($uploadDir."stats_".session_id().".txt"))
  826. unlink($uploadDir."stats_".session_id().".txt");
  827. if(file_exists($uploadDir."temp_".session_id()))
  828. unlink($uploadDir."temp_".session_id());
  829. jsonAdd("\"auth\":\"true\",\"sessionid\":\"".session_id()."\"");
  830. }else{
  831. jsonAdd("\"auth\":\"false\",\"error\":\"bad directory\"");
  832. }
  833. }else{
  834. jsonAdd("\"auth\":\"false\",\"error\":\"Unauthorized\"");
  835. }
  836. echo jsonReturn("bindings");
  837. }
  838. function uploadSmart(){
  839. global $uploadDir;
  840. if(!file_exists($uploadDir."stats_".session_id().".txt")){
  841. jsonStart();
  842. jsonAdd("\"percent\": 0, \"percentSec\": 0, \"speed\": \"0\", \"secondsLeft\": \"0\", \"done\": \"false\"");
  843. echo jsonReturn("bindings");
  844. exit();
  845. }
  846. $lines = file($uploadDir."stats_".session_id().".txt");
  847. jsonStart();
  848. $percent =round(($lines[0]/100),3);
  849. $percentSec =round($lines[1]/100,4);
  850. $speed =filesize_format($lines[2]).'s';
  851. $secondsLeft =secs_to_string(round($lines[3]));
  852. $size =filesize_format($lines[4]).'s';
  853. if($percent == 1){
  854. // cleanup time
  855. if(isset($_SESSION['uploadPath'])){
  856. $path = $_SESSION['uploadPath'];
  857. $userpath = getUserPath($path).$path;
  858. $sessionid = session_id();
  859. $dh = opendir($uploadDir);
  860. while (($file = readdir($dh)) !== false) {
  861. $sessionlen = strlen(session_id());
  862. if(substr($file,0,$sessionlen)==session_id()){
  863. $filename = substr($file,$sessionlen+1);
  864. $uploadfile=$filename;
  865. $i=1;
  866. while(file_exists($userpath.'/'.$uploadfile)){
  867. $uploadfile = $i . '_' . $filename;
  868. $i++;
  869. }
  870. if(file_exists("$uploadDir$file") && !rename("$uploadDir$file","$userpath/$uploadfile")){
  871. echo "Error";
  872. }
  873. }
  874. }closedir($dh);
  875. if(file_exists($uploadDir."stats_".session_id().".txt"))
  876. unlink($uploadDir."stats_".session_id().".txt");
  877. if(file_exists($uploadDir."temp_".session_id()))
  878. unlink($uploadDir."temp_".session_id());
  879. }
  880. $done = "true";
  881. }else{
  882. $done = "false";
  883. }
  884. jsonAdd("\"percent\": $percent, \"size\": \"$size\",\"percentSec\": $percentSec, \"speed\": \"$speed\", \"secondsLeft\": \"$secondsLeft\", \"done\": \"$done\"");
  885. echo jsonReturn("bindings");
  886. }
  887. /*
  888. function uploadFiles($path){
  889. $path = mysql_escape_string($path);
  890. if(getUserAuth('upload',$path)){
  891. $userpath = getUserPath($path).$path;
  892. if(is_dir($userpath)){
  893. foreach ($_FILES["file"]["error"] as $key => $error) {
  894. if ($error == UPLOAD_ERR_OK) {
  895. $tmp_name = $_FILES["file"]["tmp_name"][$key];
  896. $uploadfile = basename($_FILES['file']['name'][$key]);
  897. $i=1;
  898. while(file_exists($userpath.'/'.$uploadfile)){
  899. $uploadfile = $i . '_' . basename($_FILES['file']['name'][$key]);
  900. $i++;
  901. }
  902. move_uploaded_file($tmp_name, $userpath.'/'.$uploadfile);
  903. databaseAdd($userpath,$uploadfile);
  904. echo "<script>history.go(-1);</script>";
  905. }
  906. }
  907. }else{
  908. error('directory doesnt exist');
  909. }
  910. }else{
  911. error('no auth');
  912. }
  913. }
  914. */
  915. /*
  916. functions to do simple things
  917. simple simple simple simple simple simple simple simple simple simple simple
  918. simple simple simple simple simple simple simple simple simple simple simple
  919. simple simple simple simple simple simple simple simple simple simple simple
  920. simple simple simple simple simple simple simple simple simple simple simple
  921. */
  922. function deleteDir($dir)
  923. {
  924. if (substr($dir, strlen($dir)-1, 1) != '/')
  925. $dir .= '/';
  926. if (is_dir($dir) && $handle = opendir($dir)){
  927. while ($obj = readdir($handle)){
  928. if ($obj != '.' && $obj != '..'){
  929. if (is_dir($dir.$obj)){
  930. if (!deleteDir($dir.$obj))
  931. return false;
  932. }
  933. elseif (is_file($dir.$obj)){
  934. if (!unlink($dir.$obj))
  935. return false;
  936. }
  937. }
  938. }
  939. closedir($handle);
  940. if (!@rmdir($dir))
  941. return false;
  942. return true;
  943. }
  944. return false;
  945. }
  946. function get_size($path)
  947. {
  948. if(!is_dir($path)) return filesize($path);
  949. if ($handle = opendir("$path")) {
  950. $size = 0;
  951. while (false !== ($file = readdir($handle))) {
  952. if($file!='.' && $file!='..'){
  953. $size += get_size($path.'/'.$file);
  954. }
  955. }
  956. closedir($handle);
  957. return $size;
  958. }
  959. }
  960. function filesize_format($size){
  961. if( is_null($size) || $size === FALSE || $size == 0 )
  962. return $size;
  963. if( $size > 1024*1024*1024 )
  964. $size = sprintf( "%.1f GB", $size / (1024*1024*1024) );
  965. elseif( $size > 1024*1024 )
  966. $size = sprintf( "%.1f MB", $size / (1024*1024) );
  967. elseif( $size > 1024 )
  968. $size = sprintf( "%.1f kB", $size / 1024 );
  969. elseif( $size < 0 )
  970. $size = '&nbsp;';
  971. else
  972. $size = sprintf( "%d B", $size );
  973. return $size;
  974. }
  975. function secs_to_string ($secs, $long=false)
  976. {
  977. $initsecs = $secs;
  978. // reset hours, mins, and secs we'll be using
  979. $hours = 0;
  980. $mins = 0;
  981. $secs = intval ($secs);
  982. $t = array(); // hold all 3 time periods to return as string
  983. // take care of mins and left-over secs
  984. if ($secs >= 60) {
  985. $mins += (int) floor ($secs / 60);
  986. $secs = (int) $secs % 60;
  987. // now handle hours and left-over mins
  988. if ($mins >= 60) {
  989. $hours += (int) floor ($mins / 60);
  990. $mins = $mins % 60;
  991. }
  992. // we're done! now save time periods into our array
  993. $t['hours'] = (intval($hours) < 10) ? "" . $hours : $hours;
  994. $t['mins'] = (intval($mins) < 10) ? "" . $mins : $mins;
  995. }
  996. // what's the final amount of secs?
  997. $t['secs'] = (intval ($secs) < 10) ? "" . $secs : $secs;
  998. // decide how we should name hours, mins, sec
  999. $str_hours = ($long) ? "hour" : "hour";
  1000. $str_mins = ($long) ? "minute" : "min";
  1001. $str_secs = ($long) ? "second" : "sec";
  1002. // build the pretty time string in an ugly way
  1003. $time_string = "";
  1004. $time_string .= ($t['hours'] > 0) ? $t['hours'] . " $str_hours" . ((intval($t['hours']) == 1) ? " " : "s ") : "";
  1005. #$time_string .= ($t['mins']) ? (($t['hours']) ? ", " : "") : "";
  1006. $time_string .= ($t['mins']) ? $t['mins'] . " $str_mins" . ((intval($t['mins']) == 1) ? " " : "s ") : "";
  1007. #$time_string .= ($t['hours'] || $t['mins']) ? (($t['secs'] > 0) ? ", " : "") : "";
  1008. if($initsecs < 120){
  1009. $time_string .= ($t['secs']) ? $t['secs'] . " $str_secs" . ((intval($t['secs']) == 1) ? "" : "s ") : " ";
  1010. }else{
  1011. if($secs > 30){
  1012. $pre = ">";
  1013. }else{
  1014. $pre = "about";
  1015. }
  1016. $time_string = "$pre $time_string";
  1017. }
  1018. return empty($time_string) ? 0 : $time_string;
  1019. }
  1020. /*
  1021. JSON STUFF JSON STUFF JSON STUFF JSON STUFF JSON STUFF JSON STUFF JSON STUFF
  1022. JSON STUFF JSON STUFF JSON STUFF JSON STUFF JSON STUFF JSON STUFF JSON STUFF
  1023. JSON STUFF JSON STUFF JSON STUFF JSON STUFF JSON STUFF JSON STUFF JSON STUFF
  1024. JSON STUFF JSON STUFF JSON STUFF JSON STUFF JSON STUFF JSON STUFF JSON STUFF
  1025. */
  1026. function jsonStart(){
  1027. global $json;
  1028. $json = '';
  1029. }
  1030. function jsonAdd($jsonLine){
  1031. global $json;
  1032. if($json != '')
  1033. $json .= ",";
  1034. $json .= "{ $jsonLine }";
  1035. }
  1036. function jsonReturn($variableName){
  1037. global $json;
  1038. return "{\"bindings\": [ $json ]}";
  1039. }
  1040. ?>