Use an absolute upload dir that can be configured
[squasher.git] / webroot / squasher.class.php
1 <?php
2 require_once("../config.php");
3
4 function zfill($n, $a) {
5         return str_repeat("0", max(0,$a-strlen($n))) . $n;
6 }
7
8 function named_records_sort($named_recs, $order_by, $reverse=false, $flags=0) {
9         $named_hash = array();
10         foreach ($named_recs as $key => $fields)
11                 $named_hash[$key] = $fields[$order_by];
12
13         if ($reverse)
14                 arsort($named_hash,$flags=0) ;
15         else
16                 asort($named_hash, $flags=0);
17
18         $sorted_records = array();
19         foreach($named_hash as $key => $val)$sorted_records[$key] = $named_recs[$key];
20
21         return $sorted_records;
22 }
23
24 function validate_user($username, $password, $salt) {
25         $creds['validated'] = false;
26         $query="SELECT * FROM users WHERE user_name = '".mysql_escape_string($username)."'";
27         $q_result = mysql_query($query);
28         while ($fetched_object = mysql_fetch_object($q_result)) {
29                 if (md5($fetched_object->user_pass.$salt) == $password) {
30                         //validated
31                         $creds['user_id'] = $fetched_object->user_id;
32                         $creds['user_name'] = $fetched_object->user_name;
33                         $creds['user_level'] = $fetched_object->user_level;
34                         $creds['validated'] = true;
35                         $log_hash=str_repeat("0",32); // File ID is always empty on login
36                         $q="INSERT INTO log (hash,action,user_id,user_name,ip,date) VALUES ('".mysql_escape_string($log_hash)."','login',".$creds['user_id'].",'".mysql_escape_string($creds['user_name'])."','".mysql_escape_string($_SERVER['REMOTE_ADDR'])."',NOW())";
37                         mysql_query($q);
38                 }
39         }
40         $_SESSION['creds'] = $creds;
41         return $creds['validated'];
42 }
43
44
45 function get_smarty() {
46         require_once(SQUASHER_SMARTY_SOURCE); // See config.php
47
48         $smarty = new Smarty;
49         $smarty->setTemplateDir(SQUASHER_SMARTY_TEMPLATES)
50                ->setCompileDir(SQUASHER_SMARTY_TEMPLATES_C)
51                ->setCacheDir(SQUASHER_SMARTY_CACHE);
52
53         return $smarty;
54 }
55
56
57 class squashweb {
58
59 var $configs = array();
60 var $files = array();
61 var $subfolders = array();
62 var $folderrights;
63 var $userrights;
64 var $history = array();
65
66 function get_configs() {
67         return $this->configs;
68 }
69
70 function subfolders() {
71         return $this->subfolders;
72 }
73
74 function get_config($h) {
75
76         return $this->configs[$h];
77 }
78
79 function folderrights() {
80         return $this->folderrights;
81 }
82
83 function userrights() {
84         return $this->userrights;
85 }
86
87 function update_history() {
88         $q="SELECT md5_hash,file,completed,checked FROM file_hash";
89         $r=mysql_query($q);
90         while($o=mysql_fetch_object($r)) {
91                 $this->history[$o->md5_hash]['file']=$o->file;
92                 $this->history[$o->md5_hash]['completed']=$o->completed;
93                 $this->history[$o->md5_hash]['checked']=$o->checked;
94         }
95 }
96
97 function get_users($user_level) {
98         $q = "SELECT * FROM users WHERE user_level < ".$user_level." ORDER BY user_name ASC";
99         $r = mysql_query($q);
100
101         while ($o = mysql_fetch_object($r)) {
102                 $return[$o->user_id]['id']              = $o->user_id;
103                 $return[$o->user_id]['name']    = $o->user_name;
104                 $return[$o->user_id]['level']   = $o->user_level;
105                 $return[$o->user_id]['enabled'] = ($o->user_pass == '') ? false : true ;
106         }
107
108         return $return;
109 }
110
111 function get_logs($type='all') {
112         $q="SELECT log.* FROM log WHERE log.user_id != '1' and ip != '87.233.211.2' ";
113         if ($_SESSION['creds']['user_id'] == 1)
114                 $q="SELECT log.* FROM log WHERE log.user_id != 'x' ";
115         switch($type) {
116         case "delete":
117                 $q.= " AND log.action = 'delete'";
118                 break;
119         case "download":
120                 $q.= " AND log.action = 'download'";
121                 break;
122         case "login":
123                 $q.= " AND log.action = 'login'";
124                 break;
125         case "debug":
126                 $q.= " AND log.action = 'debug'";
127                 break;
128         default:
129                 $q.= "";
130                 break;
131         }
132
133         $today     =" AND date > date(date_add(now(), interval -0 day)) ";
134         $yesterday =" AND date < date(date_add(now(), interval -0 day)) AND date > date(date_add(now(), interval -1 day)) ";
135         $lastweek  =" AND date < date(date_add(now(), interval -1 day)) AND date > date(date_add(now(), interval -6 day)) ";
136         $older     =" AND date < date(date_add(now(), interval -7 day)) AND date > date(date_add(now(), interval -30 day)) ";
137
138         $order=" ORDER BY log.log_id desc ";
139         $r = mysql_query($q.$today.$order);
140         $return = array(
141                 'today'=>array(),
142                 'yesterday'=>array(),
143                 'lastweek'=>array(),
144                 'older'=>array(),
145                 );
146         while($a = mysql_fetch_array($r)) {
147                 $qu="SELECT users.user_name FROM users LEFT JOIN log ON users.user_id = log.user_id WHERE log.ip='".mysql_escape_string($a['ip'])."' GROUP BY users.user_name";
148                 $ru = mysql_query($qu);
149                 $a['users_from_ip'] = " | ";
150                 while($au = mysql_fetch_array($ru))
151                         $a['users_from_ip'] .= $au['user_name']." | ";
152                 $return['today'][$a['log_id']] = $a;
153         }
154         $r = mysql_query($q.$yesterday.$order);
155         while($a = mysql_fetch_array($r)) {
156                 $qu="SELECT users.user_name FROM users LEFT JOIN log ON users.user_id = log.user_id WHERE log.ip='".mysql_escape_string($a['ip'])."' GROUP BY users.user_name";
157                 $ru = mysql_query($qu);
158                 $a['users_from_ip'] = " | ";
159                 while($au = mysql_fetch_array($ru))
160                         $a['users_from_ip'] .= $au['user_name']." | ";
161                 $return['yesterday'][$a['log_id']] = $a;
162         }
163         $r = mysql_query($q.$lastweek.$order);
164         while($a = mysql_fetch_array($r)) {
165                 $qu="SELECT users.user_name FROM users LEFT JOIN log ON users.user_id = log.user_id WHERE log.ip='".mysql_escape_string($a['ip'])."' GROUP BY users.user_name";
166                 $ru = mysql_query($qu);
167                 $a['users_from_ip'] = " | ";
168                 while($au = mysql_fetch_array($ru))
169                         $a['users_from_ip'] .= $au['user_name']." | ";
170                 $return['lastweek'][$a['log_id']] = $a;
171         }
172         $r = mysql_query($q.$older.$order);
173         while($a = mysql_fetch_array($r)) {
174                 $qu="SELECT users.user_name FROM users LEFT JOIN log ON users.user_id = log.user_id WHERE log.ip='".mysql_escape_string($a['ip'])."' GROUP BY users.user_name";
175                 $ru = mysql_query($qu);
176                 $a['users_from_ip'] = " | ";
177                 while($au = mysql_fetch_array($ru))
178                         $a['users_from_ip'] .= $au['user_name']." | ";
179                 $return['older'][$a['log_id']] = $a;
180         }
181
182         return $return;
183 }
184
185 function insert_users($u, $admin_level) {
186         $user_name = $u['user_name'];
187         $user_pass = $u['user_pass'];
188         $user_level = (int)$u['user_level'];
189
190         $q = "INSERT INTO users (user_name,user_pass,user_level) VALUES ('".mysql_escape_string($user_name)."', '".mysql_escape_string(md5($user_pass))."', ".$user_level.")";
191         $r = mysql_query($q);
192 }
193
194 function update_users($u) {
195         $user_id = (int)$u['user_id'];
196         $user_name = @$u['user_name'];
197         $user_pass = @$u['user_pass'];
198         $user_level = (int)@$u['user_level'];
199         if ($user_name) {
200                 $q = "UPDATE users SET user_name = '".mysql_escape_string($user_name)."' WHERE user_id = ".$user_id;
201                 $r = mysql_query($q);
202         }
203         if ($user_pass) {
204                 $q = "UPDATE users SET user_pass = '".mysql_escape_string(md5($user_pass))."' WHERE user_id = ".$user_id;
205                 $r = mysql_query($q);
206         }
207         if ($user_level) {
208                 $q = "UPDATE users SET user_level = ".$user_level." WHERE user_id = ".$user_id;
209                 $r = mysql_query($q);
210         }
211 }
212
213 function disable_users($u) {
214         $user_id = (int)$u['user_id'];
215         $user_name = @$u['user_name'];
216         $user_level = (int)@$u['user_level'];
217         if ($user_name) {
218                 $q = "UPDATE users SET user_name = '".mysql_escape_string($user_name)."' WHERE user_id = ".$user_id;
219                 $r = mysql_query($q);
220         }
221         $q = "UPDATE users SET user_pass = '' WHERE user_id = ".$user_id;
222         $r = mysql_query($q);
223         if ($user_level) {
224                 $q = "UPDATE users SET user_level = ".$user_level." WHERE user_id = ".$user_id;
225                 $r = mysql_query($q);
226         }
227         $r = mysql_query($q);
228 }
229
230 function remove_users($u) {
231         $user_id = (int)$u['user_id'];
232         $q = "DELETE FROM users WHERE user_id = ".$user_id;
233         $r = mysql_query($q);
234 }
235
236 function get_rights($user_id) {
237         $result = array();
238
239         $q = "SELECT folder_path, access FROM user_rights WHERE user_id = ".(int)$user_id;
240         $r = mysql_query($q);
241         while ($o = mysql_fetch_object($r)) {
242
243                 //clean vars
244                 $arr_string = '$result';
245
246                 //get foldernames from path
247                 if ($o->folder_path != '/') {
248                         $path = $o->folder_path;
249                         if ($path{0}=='/')
250                                 $path=substr($path,1);
251                         $folder_arr = explode('/',$path);
252
253                         //create folder structure array
254                         foreach ($folder_arr AS $key => $value) {
255                                 $value_escaped = str_replace("'", "\\'", $value);
256                                 $arr_string .= "['".$value_escaped."']";
257                         }
258                 }
259                 $arr_string .= "['__access__']";
260
261                 eval($arr_string." = '".$o->access."';");
262         }
263         return $result;
264 }
265
266 function give_rights($user_id, $type='folderrights') {
267         if ($type=='folderrights')
268                 $this->folderrights = $this->get_rights($user_id);
269         else // $type=='userrights'
270                 $this->userrights = $this->get_rights($user_id);
271 }
272
273 function update_rights($edited_user, $m, $admin_level) {
274         $q = "SELECT count(*) result FROM users WHERE user_id = ".(int)$edited_user." AND user_level < ".(int)$admin_level;
275         $r = mysql_query($q);
276         $o = mysql_fetch_object($r);
277
278         if ($o->result) {
279                 foreach ($m AS $path => $access) {
280                         $p_q = "SELECT count(*) result FROM user_rights WHERE user_id = ".(int)$edited_user." AND folder_path = '".mysql_escape_string($path)."'";
281                         $p_r = mysql_query($p_q);
282                         $p_o = mysql_fetch_object($p_r);
283                         if ($p_o->result == 1)
284                                 mysql_query("UPDATE user_rights SET access = ".(int)$access." WHERE folder_path = '".mysql_escape_string($path)."' AND user_id = ".(int)$edited_user);
285                         if ($p_o->result == 0)
286                                 mysql_query("INSERT INTO user_rights (user_id,folder_path,access) values (".(int)$edited_user.",'".mysql_escape_string($path)."',".(int)$access.") ");
287                 }
288         }
289 }
290
291
292 function show_rights_tree($path, $depth=0, $userid=0) {
293
294         if ($userid==0)
295                 return false;
296         if ($depth==0)
297                 $this->give_rights($userid, 'userrights');
298
299         // access = 0 --deny-all
300         // access = 1 --allow-dir-only
301         // access = 2 --allow-inc-subs
302
303         $layout = '';
304         $style = '';
305
306         for ($i=0; $i<$depth; $i++)
307                 $layout .= " ";
308         if ($dir = opendir(SQUASHER_UPLOADS_DIR.$path)) {
309                 $layout .= "<div style='clear:both;' >\n";
310                 $f = 0;
311                 while (false !== ($file = readdir($dir))) {
312                         $files_array[] = $file;
313                 }
314                 asort($files_array);
315                 foreach ($files_array as $f_index => $file) {
316                         if (($file{0} !== ".") && ($file !== ".."))
317                         {
318                                 $filename = $path=='/' ? $path.$file : $path.'/'.$file;
319                                 if (!is_file(SQUASHER_UPLOADS_DIR.$filename) && $this->got_rights_array($filename) > 0) {
320                                         $f++;
321                                         $name = $filename;
322                                         $check = $this->got_rights_array_admin($filename, $this->userrights);
323                                         $check_all = '';
324                                         $check_allow = '';
325                                         $check_deny = '';
326                                         switch($check) {
327                                                 case 2:
328                                                         $check_all = 'checked';
329                                                         break;
330                                                 case 1:
331                                                         $check_allow = 'checked';
332                                                         break;
333                                                 case 0:
334                                                 default:
335                                                         $check_deny = 'checked';
336                                                         break;
337                                         }
338
339                                         if ($f==1)
340                                                 $style[$depth] = ".depth".$depth."{float:right;width:".(600-($depth*10))."px;border-left:2px solid #FFFFFF;border-top:1px solid #FFFFFF;background:#".dechex(14-$depth).dechex(14-$depth).dechex(14-$depth).dechex(14-$depth).dechex(14-$depth).dechex(14-$depth).";}";
341                                         if ($f==1)
342                                                 $layout .= "<div class='depth".$depth."'>";
343                                         $layout .= "<div class='white_border' >".htmlspecialchars($file)."</div>\n";
344                                         $name_escaped = htmlspecialchars($name);
345                                         $layout .= '<div class="check_deny"><input name="m['.$name_escaped.']" value=0 type=radio '.$check_deny."></div>\n";
346                                         $layout .= '<div class="check_allow"><input name="m['.$name_escaped.']" value=1 type=radio '.$check_allow."></div>\n";
347                                         $layout .= '<div class="check_all"><input name="m['.$name_escaped.']" value=2 type=radio '.$check_all."></div>\n";
348                                         $sub_return = $this->show_rights_tree($filename,$depth+1,$userid);
349                                         if (is_array($style) && is_array($sub_return['style']))
350                                                 $style = $style + $sub_return['style'];
351                                         $layout .= $sub_return['layout'];
352                                 }
353                         }
354                 }
355                 if ($f!=0)
356                         $layout .= "</div>";
357                 $layout .= "</div>\n";
358         }
359
360         $return['style'] = $style;
361         $return['layout'] = $layout;
362
363         return $return;
364 }
365
366 function got_rights_array($needle, $haystack='', $c=0) {
367         // used by:
368         // - read_single_file
369         // - read_directory
370         // - show_rights_tree
371
372         if (!is_array($haystack))
373                 $haystack = $this->folderrights;
374
375         // check root rights
376         if ($needle{0} == '/' && @$haystack['__access__'] == 2 )
377                 return 2;
378
379         // remove leading /
380         if ($needle{0}=='/')
381                 $needle = substr($needle, 1);
382
383         $needle_arr = explode('/', $needle);
384         $n = count($needle_arr);
385         $d = $c + 1;
386
387         foreach ($haystack as $k => $v) {
388                 if ($needle_arr[$c] == $k) {
389                         if (!is_array(@$v['__access__'])) {
390                                 if ($v['__access__'] == 2             ) return 2;
391                                 if ($v['__access__'] == 1 && $d == $n ) return 1;
392                                 if ($v['__access__'] == 0 && $d == $n ) return 0;
393                         } else {
394                                 $return = $this->got_rights_array($needle, $v, $d);
395                         }
396                 }
397         }
398         return $return;
399 }
400
401 function got_rights_array_admin($needle, $haystack='', $c=0) {
402         // used by:
403         // - show_rights_tree
404
405         if (!is_array($haystack))
406                 $haystack = $this->folderrights;
407
408         // check root rights
409         if ($needle{0} == '/' && @$haystack['__access__'] == 2 )
410                 return 2;
411
412         // remove leading /
413         if ($needle{0} == '/')
414                 $needle = substr($needle, 1);
415
416         $needle_arr = explode('/', $needle);
417         $n = count($needle_arr);
418         $d = $c + 1;
419         $return = 0;
420
421         if ($c < $n) {
422                 if (@$haystack['__access__'] == 2)
423                         return $haystack['__access__'];
424                 if (is_array($haystack[$needle_arr[$c]]))
425                         $return = $this->got_rights_array_admin($needle, $haystack[$needle_arr[$c]], $d);
426         } else {
427                 if (@$haystack['__access__'] > 0)
428                         $return = $haystack['__access__'];
429         }
430
431         return $return;
432 }
433
434 function got_rights_array_recursive($needle, $haystack='', $c=0) {
435         // used by:
436         // - read_directory, for subfolders
437
438         if (!is_array($haystack))
439                 $haystack = $this->folderrights;
440
441         // check root rights
442         if($needle{0}=='/' && @$haystack['__access__'] == 2 )
443                 return 2;
444
445         // check folder rights
446         if($needle{0}=='/')
447                 $needle=substr($needle,1);
448
449         $needle_arr = explode('/', $needle);
450         $n = count($needle_arr);
451         $d = $c + 1;
452         $return = 0;
453
454         foreach($haystack as $k => $v) {
455                 if ($c < sizeof($needle_arr) && $needle_arr[$c] == $k) {
456                         if ($c < $n) {
457                                 if ($v['__access__'] == 2)
458                                         $return = $return + $v['__access__'];
459                                 $return = $return + $this->got_rights_array_recursive($needle, $v, $d);
460                         } else {
461                                 $return = $return + $this->in_array_recursive($v);
462                         }
463                 } elseif ($c == $n) {
464                         $return = $return + $v['__access__'];
465                         if($k != '__access__')$return = $return + $this->in_array_recursive($v);
466                 }
467         }
468
469         return $return;
470 }
471
472 function in_array_recursive($haystack) {
473         $return = 0;
474         if (is_array($haystack)) {
475                 foreach ($haystack as $key1 => $value1) {
476                         if (is_array($value1)) {
477                                 $return = $return + $this->in_array_recursive($value1);
478                         }
479                         elseif ($value1 > 0) {
480                                 return $value1;
481                         }
482                 }
483         }
484         return $return;
485 }
486
487 function read_single_file($path, $file) {
488         $filename = $path=='/' ? $path.$file : $path.'/'.$file;
489         $fsfilename = SQUASHER_UPLOADS_DIR.$filename; // name on the file system
490         $i = 0;
491         if ($this->got_rights_array($path) > 0) {
492                 if (is_file($fsfilename.'.Completed'))
493                         $ext='.Completed';
494                 if (is_file($fsfilename.'.InProgress'))
495                         $ext='.InProgress';
496                 if (is_file($fsfilename.'.Starting'))
497                         $ext='.Starting';
498                 if (is_file($fsfilename.'.Processed'))
499                         $ext='.Processed';
500                 $fsfilename .= $ext;
501                 $handle = @fopen($fsfilename, "rb");
502                 $sub_pos = strpos($file, $ext);
503                 $base_name = substr($file, 0, $sub_pos);
504                 $filecontent = @fread($handle, @filesize($fsfilename));
505                 $config[$i] = explode("\r\n", $filecontent);
506                 /***
507                 *       $config:: array
508                 *       [0]     ->      versioncode
509                 *       [1]     ->      date&time
510                 *       [2]     ->      filename
511                 *       [3]     ->      filesize
512                 *       [4]     ->      chunksize
513                 *       [5]     ->      chunkcount
514                 *       [6]     ->      CRC32 checksum
515                 ***/
516                 if (@filesize($fsfilename) > 0) {
517                         $h = md5($path."/".$config[$i][2]);
518                         $this->configs[$h] = $config[$i];
519                         $this->configs[$h]['squashed'] = true;
520                         $this->configs[$h]['path'] = $path;
521                         $this->configs[$h]['status'] = substr($ext, 1);
522                         $this->configs[$h]['mime'] = $this->set_mime($this->configs[$h][2]);
523                         $this->configs[$h]['hidden'] = is_file(SQUASHER_UPLOADS_DIR.$path.'/'.$base_name.'.hidden');
524                         //to prevent dates of 1-1-1970 we set te dates of the config file
525                         $this->configs[$h]['added'] = filectime($fsfilename);
526                         $this->configs[$h]['lastchange'] = filemtime($fsfilename);
527                         fclose($handle);
528                         $this->populate_stats($path, $h);
529                         //insert hash in db
530                         #$this->update_hash($h,$path."/".$config[$i][2]);
531                         //check stats
532                         $this->check_stats($h);
533                 }
534         }
535 }
536
537
538 function read_directory($path, $getsubs=false, $getfirstfiles=true, $getdeepfiles=true, $populate=true) {
539         $fsdir = $path=='/' ? SQUASHER_UPLOADS_DIR : SQUASHER_UPLOADS_DIR.$path;
540         $hdir = @opendir(SQUASHER_UPLOADS_DIR.$path);
541         if (!$hdir)
542                 return;
543         $i = 0;
544         while (false !== ($file = readdir($hdir))) {
545                 if ($file{0} == "." || substr($file,0,2) == "SQ")
546                         continue;       // skip this file
547                 $filename = $path=='/' ? $path.$file : $path.'/'.$file;
548                 $fsfilename = SQUASHER_UPLOADS_DIR.$filename; // name on the file system
549                 if (!is_file($fsfilename) && strpos($filename, '/recieving/')!==0) {
550                         if ($getsubs) {
551                                 if ($this->got_rights_array_recursive($filename) > 0) {
552                                         $key = $path;
553                                         if ($key != '/')
554                                                 $key .=  '/';
555                                         $key .= $file;
556                                         $this->subfolders[$key] = $file;
557                                 }
558                         }
559                         if ($getdeepfiles)
560                                 $this->read_directory($filename, false, $getdeepfiles, $getdeepfiles, $populate);
561                 } elseif (strpos($filename,'/ftp/')===0) {
562                         //ftp files
563                         if ($this->got_rights_array($path) > 0 && !strpos($filename, '.hidden') ) {
564                                 $h = md5($filename);
565                                 $name_only = substr($filename, strlen($path)+1); // this is $file
566                                 $file_structure = explode('.', $name_only); // array of dot separated name fragment
567                                 $ext = array_pop($file_structure); // extension
568                                 $base_name = array_pop($file_structure); // (erk)
569                                 $this->configs[$h]['path'] = $path;
570                                 $this->configs[$h][0] = 'manual ftp';
571                                 $this->configs[$h][2] = $name_only;
572                                 $this->configs[$h][3] = filesize($fsfilename);
573                                 $this->configs[$h]['added'] = filectime($fsfilename);
574                                 $this->configs[$h]['lastchange'] = filemtime($fsfilename);
575                                 $this->configs[$h]['status'] = 'unknown';
576                                 $this->configs[$h]['squashed'] = false;
577                                 $this->configs[$h]['mime'] = $this->set_mime($name_only);
578                                 $this->configs[$h]['hidden'] = is_file(SQUASHER_UPLOADS_DIR.$path.'/'.$base_name.'.hidden');
579                         }
580                 } elseif ($getfirstfiles) {
581                         //squashed files
582                         if ($this->got_rights_array($path) > 0) {
583                                 if (strpos($filename, '.Completed') || strpos($filename, '.InProgress') || strpos($filename, '.Starting') || strpos($filename, '.Processed')) {
584                                         $i++;
585                                         $handle = @fopen($fsfilename, "rb");
586                                         if (strpos($file,'.Completed'))
587                                                 $ext='.Completed';
588                                         if (strpos($file,'.InProgress'))
589                                                 $ext='.InProgress';
590                                         if (strpos($file,'.Starting'))
591                                                 $ext='.Starting';
592                                         if (strpos($file,'.Processed'))
593                                                 $ext='.Processed';
594                                         $sub_pos = strpos($file, $ext);
595                                         $base_name = substr($file, 0, $sub_pos);
596                                         $filecontent = @fread($handle, @filesize($fsfilename));
597                                         $config[$i] = explode("\r\n", $filecontent);
598
599                                         /***
600                                         *       $config:: array
601                                         *       [0]     ->      versioncode
602                                         *       [1]     ->      date&time
603                                         *       [2]     ->      filename
604                                         *       [3]     ->      filesize
605                                         *       [4]     ->      chunksize
606                                         *       [5]     ->      chunkcount
607                                         *       [6]     ->      CRC32 checksum
608                                         ***/
609
610                                         if (@filesize($fsfilename) > 0) {
611                                                 $h = md5($path."/".$config[$i][2]);
612                                                 $this->configs[$h] = $config[$i];
613                                                 $this->configs[$h]['squashed'] = true;
614                                                 $this->configs[$h]['path'] = $path;
615                                                 $this->configs[$h]['status'] = substr($ext, 1);
616                                                 $this->configs[$h]['mime'] = $this->set_mime($this->configs[$h][2]);
617                                                 $this->configs[$h]['hidden'] = is_file(SQUASHER_UPLOADS_DIR.$path.'/'.$base_name.'.hidden');
618                                                 //to prevent dates of 1-1-1970 we set te dates of the config file
619                                                 $this->configs[$h]['added'] = filectime($fsfilename);
620                                                 $this->configs[$h]['lastchange'] = filemtime($fsfilename);
621                                                 fclose($handle);
622                                                 $this->populate_stats($path, $h);
623                                                 //insert hash in db
624                                                 $this->update_hash($h, $path."/".$config[$i][2]);
625                                                 //check stats
626                                                 $this->check_stats($h);
627                                         }
628                                 }
629                         }
630                 }
631         }
632         closedir($hdir);
633 }
634
635 function check_stats($h) {
636         $config = $this->get_config($h);
637         $count = @array_sum($config['stats']);
638         if ($config['status']=='Completed' && $count != $config[5]) {
639                 $filepath=$config['path'].'/'.$config[2];
640                 if ($this->history[$h]['completed']=="1") {
641                         //don't display broken file, remove it instead
642                         unlink(SQUASHER_UPLOADS_DIR.$config['path'].'/'.$config[2].'.Completed');
643                         unset($this->configs[$h]);
644
645                         if (!$count)
646                                 $count = 0;
647                         $m_subject = "Squasher Debug: File Removed";
648                         $m_body = "Upload removed: \n File: ".$config['path']."/".$config[2]." \n Status: ".$config['status']." \n Chunks: ".$count." out of ".$config[5];
649                         mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
650                         $qlog = "INSERT INTO log (hash,file,action,user_id,user_name,ip,date) VALUES ('".mysql_escape_string($h)."','".mysql_escape_string($filepath)."','debug',-1,'squasher-web','cleanup',NOW())";
651                         mysql_query($qlog);
652                 } else {
653                         //do move
654                         rename(SQUASHER_UPLOADS_DIR.$config['path'].'/'.$config[2].'.Completed',
655                                SQUASHER_UPLOADS_DIR.$config['path'].'/'.$config[2].'.InProgress');
656                         $this->configs[$h]['status'] = 'InProgress';
657
658                         //mail n4m
659                         if (!$count)
660                                 $count = 0;
661                         $m_subject = "Squasher Debug: Upload Error";
662                         $m_body = "Upload error: \n File: ".$config['path']."/".$config[2]." \n Status: ".$config['status']." \n Chunks: ".$count." out of ".$config[5];
663                         mail('support@netformatie.nl', $m_subject, $m_body, "From: squasher@netformatie.nl");
664                         mail('jan@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
665                         mail('joop@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
666                         mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
667
668                         //do sms
669                         //wget -o/dev/null "http://www.mollie.nl/xml/sms/?username=netformatie&password=SMSdolsi&originator=Netformatie&recipients=${ENGINEER}&message=${CALLERID}";
670
671                         //mail RO
672                         $ship = explode('/',$config['path']);
673                         if ($ship[2] == 'myas' || $ship[2] == 'myez' || $ship[2] == 'myrw')
674                                 mail('ro1@'.$ship[2].'.greenpeace.org','Squasher: '.$config[2].' resume request','The squasher server has detected an upload error. Please resume the squasher transmission for '.$config[2].' to correct this problem.',"From: support@netformatie.nl\nX-Priority: 1");
675
676                         $qlog = "INSERT INTO log (hash,file,action,user_id,user_name,ip,date) VALUES ('".mysql_escape_string($h)."','".mysql_escape_string($filepath)."','debug',-1,'squasher-web','retry',NOW())";
677                         mysql_query($qlog);
678
679                 }
680         } elseif ($config['status']=='Completed' && $count == $config[5]) {
681                 if ($this->history[$h]['completed']==0)
682                         mysql_query("UPDATE file_hash SET completed = 1 WHERE md5_hash = '".mysql_escape_string($h)."'");
683         }
684 }
685
686 function update_hash($hash, $path) {
687         $check_hash_query = "select * from file_hash where md5_hash = '".$hash."'";
688         $check_hash_result = mysql_query($check_hash_query);
689         if(mysql_num_rows($check_hash_result) == 0) {
690                 $insert_hash_query = "INSERT INTO file_hash (md5_hash,file) values ('".mysql_escape_string($hash)."','".mysql_escape_string($path)."')";
691                 mysql_query($insert_hash_query);
692         }
693 }
694
695 /* unused function */
696 /*
697 function path_to_arraystring($path, $arrayname) {
698         $path_values = explode('/', $path);
699         $return = $arrayname;
700         foreach ($path_values AS $key => $value) {
701                 if ($value != '.' && $value != '')
702                         $return.= "['".$value."']";
703         }
704         return $return;
705 } */
706
707 function populate_stats($path, $h) {
708         /***
709         *       $config:: array
710         *       [0]     ->      versioncode
711         *       [1]     ->      date&time
712         *       [2]     ->      filename
713         *       [3]     ->      filesize
714         *       [4]     ->      chunksize
715         *       [5]     ->      chunkcount
716         *       [6]     ->      CRC32 checksum
717         ***/
718         $config = $this->configs[$h];
719
720         $q = "SELECT * FROM file_hash WHERE md5_hash = '".mysql_escape_string($h)."'";
721         $r = mysql_query($q);
722         $o = mysql_fetch_object($r);
723         $validated_chunks = $o->validated_chunks;
724
725         if ($this->history[$h]['completed']=="1") {
726                 $file_part = $path."/SQ".zfill(1,6)."-".$config[2];
727                 if (!is_file(SQUASHER_UPLOADS_DIR.$file_part))
728                         $file_part = $path."/SQ".zfill(1,3)."-".$config[2];
729                 if (is_file(SQUASHER_UPLOADS_DIR.$file_part)) {
730                         $this->configs[$h]['added'] = filectime(SQUASHER_UPLOADS_DIR.$file_part);
731                         $file_part = $path."/SQ".zfill($config[5],6)."-".$config[2];
732                         if (!is_file(SQUASHER_UPLOADS_DIR.$file_part))
733                                 $file_part = $path."/SQ".zfill($config[5],3)."-".$config[2];
734                         if (is_file(SQUASHER_UPLOADS_DIR.$file_part))
735                                 $this->configs[$h]['lastchange'] = filemtime(SQUASHER_UPLOADS_DIR.$file_part);
736                         for ($i=1; $i<=$config[5]; $i++)
737                                 $this->configs[$h]['stats'][$i] = "1.00";
738                 } else {
739                         //failsafe voor verwijderde bestanden
740                         mysql_query("UPDATE file_hash SET completed = 0 WHERE md5_hash = '".mysql_escape_string($h)."'");
741                 }
742         } else {
743                 $keep_validating = true;
744                 for ($i=1; $i<=$config[5]; $i++) {
745                         if ($validated_chunks > $i) {
746                                 $this->configs[$h]['stats'][$i]="1.00";
747                         } else {
748                                 $file_part = $path."/SQ".zfill($i,6)."-".$config[2];
749                                 if (!is_file(SQUASHER_UPLOADS_DIR.$file_part))
750                                         $file_part = $path."/SQ".zfill($i,3)."-".$config[2];
751                                 if (is_file(SQUASHER_UPLOADS_DIR.$file_part)) {
752                                         $handle = fopen(SQUASHER_UPLOADS_DIR.$file_part, "rb");
753                                         $size_this = filesize(SQUASHER_UPLOADS_DIR.$file_part);
754                                         $added = filectime(SQUASHER_UPLOADS_DIR.$file_part);
755                                         $last_changed = filemtime(SQUASHER_UPLOADS_DIR.$file_part);
756                                         if ($this->configs[$h]['added'] > $added || !is_numeric($this->configs[$h]['added']))
757                                                 $this->configs[$h]['added'] = $added;
758                                         if ($this->configs[$h]['lastchange'] < $last_changed)
759                                                 $this->configs[$h]['lastchange'] = $last_changed;
760                                         if ($i != $config[5]) {
761                                                 $this->configs[$h]['stats'][$i] = number_format((1/$config[4])*$size_this, 2, '.', '');
762                                         //number_format((100/$config[4])*$size_this, 2, '.', '')."%";
763                                         }else{
764                                                 $this->configs[$h]['stats'][$i] = number_format((1/($config[3]-($config[4]*($config[5]-1))))*$size_this, 2, '.', '');
765                                                 //number_format((100/($config[3]-($config[4]*($config[5]-1))))*$size_this, 2, '.', '')."%";
766                                         }
767                                         fclose($handle);
768                                         if ($config[4] == $size_this && $keep_validating) {
769                                                 $validated_chunks = $i;
770                                         } else {
771                                                 $keep_validating = false;
772                                         }
773                                 } else {
774                                         $this->configs[$h]['stats'][$i] = "0.00";
775                                         //$this->configs[$h]['stats'][$i]="0.00%";
776
777                                 }
778                         }
779                 }
780                 mysql_query("UPDATE file_hash SET validated_chunks = '".mysql_escape_string($validated_chunks)."' WHERE md5_hash = '".mysql_escape_string($h)."'");
781         }
782 }
783
784
785 /* unused function
786 function read_config($path, $filename) {
787         if (is_file($path."/".$filename.".InProgress")) {
788                 $config_handle = fopen($path."/".$filename.".InProgress", "r");
789                 $conf_path=$path."/".$filename.".InProgress";
790         } elseif (is_file($path."/".$filename.".Completed" )) {
791                 $config_handle = fopen($path."/".$filename.".Completed", "r");
792                 $conf_path=$path."/".$filename.".Completed";
793         } elseif (is_file($path."/".$filename.".Starting" )) {
794                 $config_handle = fopen($path."/".$filename.".Starting", "r");
795                 $conf_path=$path."/".$filename.".Starting";
796         } elseif (is_file($path."/".$filename.".Processed" )) {
797                 $config_handle = fopen($path."/".$filename.".Processed", "r");
798                 $conf_path=$path."/".$filename.".Processed";
799         } else {
800                 return "Not Found";
801         }
802         $config_content = fread($config_handle, filesize($conf_path));
803         fclose($config_handle);
804         $config = explode("\n", $config_content);
805
806         return $config;
807 }
808 */
809 //              print_r($config);
810 /*              $file_count = $config[5];
811                 $last=1;
812     for ($i=1; $i<=$file_count; $i++)
813     {
814         $file_part = $path."/SQ".zfill($i,6)."-".$filename;
815         if (is_file($file_part))
816        {
817
818         $handle = fopen($file_part, "rb");
819         $size_this = filesize($file_part);
820                                 //$stats[$i]=round((100/$config[4])*$size_this)."%";
821                                 if ((($size_this==$config[4] && ($last+1)==$i) )|| $i == $config[5]) {
822                                         $merged_file.=fread($handle, filesize($file_part));
823                                         $last = $i;
824                                 }
825         fclose($handle);
826        }
827      }
828      return $merged_file;
829      */
830
831 /**
832  * Outputs one file (echo)
833  * @param string $path Absolute path within SQUASHER_UPLOADS_DIR
834  * @param string $filename File name in $path
835  * @param bool $tovar Returns content rather than outputing it
836  * @return file content if $tovar; or void
837  */
838 function print_files($path, $filename, $tovar=false) {
839         $fsfilename = SQUASHER_UPLOADS_DIR.$path.'/'.$filename;
840         if (strpos($path.'/', '/ftp/')===0) {
841                 if (is_file($fsfilename)) {
842                         $handle = fopen($fsfilename, 'rb');
843                         while (!feof($handle))
844                         {
845                                 print(fread($handle, 1024));
846                                 ob_flush();
847                                 flush();
848                         }
849                 }
850         } else {
851                 if (is_file($fsfilename.'.InProgress'))
852                         $conf_path = $fsfilename.'.InProgress';
853                 elseif (is_file($fsfilename.'.Completed' ))
854                         $conf_path = $fsfilename.'.Completed';
855                 elseif (is_file($fsfilename.'.Starting' ))
856                         $conf_path = $fsfilename.'.Starting';
857                 elseif (is_file($fsfilename.'.Processed' ))
858                         $conf_path = $fsfilename.'.Processed';
859                 else
860                         return 'Not Found';
861                 $config_handle = fopen($conf_path, 'r');
862                 $config_content = fread($config_handle, filesize($conf_path));
863                 fclose($config_handle);
864                 $config = explode("\n",$config_content);
865 //              print_r($config);
866                 $file_count = $config[5];
867                 $last = 0;
868                 $last_part_size = ( $config[3] - ( ( $config[5] -1 ) * $config[4] ) );
869                 for ($i=0;$i<=$file_count;$i++)
870                 {
871                         $file_part = SQUASHER_UPLOADS_DIR.$path."/SQ".zfill($i,6)."-".$filename;
872                         if (!is_file($file_part))
873                                 $file_part = $path."/SQ".zfill($i,3)."-".$filename;
874                         if (is_file($file_part))
875                         {
876                                 $handle = fopen($file_part, "rb");
877                                 $size_this = filesize($file_part);
878                                 if ( ( ( $size_this==$config[4] ) && ( ($last+1)==$i ) ) || ( ( $i == $config[5] ) && ( $size_this==$last_part_size ) && ( ($last+1)==$i ) ) ) {
879                                         if ($tovar) {
880                                                 $merged_file.=fread($handle, $size_this);
881                                                 $last = $i;
882                                         } else {
883                                                 while (!feof($handle))
884                                                 {
885                                                         print(fread($handle, 4096));
886                                                 #       @ob_flush();
887                                                 #       @flush();
888                                                 }
889                                                 $last = $i;
890                                         }
891                                 }
892                                 fclose($handle);
893                         }
894                 }
895                 if ($tovar)
896                         return $merged_file;
897         }
898 }
899
900 /* unused function */
901 /*
902 function check_md5($h) {
903         $return = false;
904         $config = $this->configs[$h];
905         $var = $this->print_files($config['path'], $config[2], true);
906         $hash = md5($var);
907         if ($hash==$config[6])
908                 $return=true;
909
910         return $return;
911 } */
912
913 /* unused function */
914 /*
915 function file_crc($file_string) {
916         //$file_string = file_get_contents($file);
917
918         $crc = crc32($file_string);
919         return sprintf("%u\n", $crc);
920 } */
921
922 /* unused function */
923 /*
924 function file_crc_debug($file) {
925         $file_string = file_get_contents($file);
926
927         $crc = crc32($file_string);
928         return sprintf("%u\n", $crc);
929 } */
930
931 /**
932  * Delete one file
933  *
934  * @param string $h Md5 hash of the file path, in lower case
935  * @param array $s Session credidentials
936  */
937 function delete_file($h, $s) {
938         $request = $this->get_config($h);
939         $filepath = $request['path'].'/'.$request[2];
940         if (strpos($request['path'], '/ftp/')===0) {
941                 #remove file
942                 $fsfilepath = SQUASHER_UPLOADS_DIR.$filepath;
943                 if (is_file($fsfilepath))
944                         @unlink($fsfilepath);
945                 if (is_file($fsfilepath.'.hidden'))
946                         @unlink($fsfilepath.'.hidden');
947         } else {
948                 $fspath = SQUASHER_UPLOADS_DIR.$request['path'];
949                 #remove fileparts
950                 for ($i=0;$i<=$request[5];$i++) {
951                         $part_six   = $fspath.'/SQ'.zfill($i,6).'-'.$request[2];
952                         $part_three = $fspath.'/SQ'.zfill($i,3).'-'.$request[2];
953                         if (is_file($part_six))
954                                 @unlink($part_six);
955                         if (is_file($part_three))
956                                 @unlink($part_three);
957                 }
958                 #remove config file
959                 if (is_file($fspath.'/'.$request[2].'.hidden'))
960                         @unlink($fspath.'/'.$request[2].'.hidden');
961                 if (is_file($fspath.'/'.$request[2].'.Completed'))
962                         @unlink($fspath.'/'.$request[2].'.Completed');
963                 if (is_file($fspath.'/'.$request[2].'.InProgress'))
964                         @unlink($fspath.'/'.$request[2].'.InProgress');
965                 if (is_file($fspath.'/'.$request[2].'.Processed'))
966                         @unlink($fspath.'/'.$request[2].'.Processed');
967                 if (is_file($fspath.'/'.$request[2].'.Starting'))
968                         @unlink($fspath.'/'.$request[2].'.Starting');
969         }
970
971         #Update DB
972         $q = "DELETE FROM file_hash WHERE md5_hash = '".mysql_escape_string($h)."'";
973         mysql_query($q);
974         $q = "INSERT INTO log (hash,file,action,user_id,user_name,ip,date) VALUES ('".mysql_escape_string($h)."','".mysql_escape_string($filepath)."','delete',".(int)$s['user_id'].",'".mysql_escape_string($s['user_name'])."','".mysql_escape_string($_SERVER['REMOTE_ADDR'])."',NOW())";
975         mysql_query($q);
976
977         #Send debug mail
978         $m_name = $s['user_name'];
979         $m_subject = "Squasher Debug: File Deleted by {$m_name}";
980         $m_body = "File Deleted: \n Requested by: {$m_name} \n File: {$filepath}";
981         mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
982 }
983
984 /* unused debug function (echo / print_r)
985 function show_files() {
986
987         $path = "./uploads/";
988
989         if ($dir = opendir($path)) {
990                 $i = 1;
991                 $last = 1;
992                 $files = array();
993                 $files_merged = array();
994                 while (false !== ($file = readdir($dir)))
995                 {
996                         if (($file !== ".") && ($file !== ".."))
997                         {
998                                 $filename = $path.$file;
999                                 $handle = fopen($filename, "rb");
1000                                 $size_this = filesize($filename);
1001                                 if ($i==1)
1002                                         $size_first = $size_this;
1003                                 $filecontent = fread($handle, filesize($filename));
1004                                 $files[$i++] = $filename;
1005                                 $files_merged[$file_base][]=$filename;
1006                                 fclose($handle);
1007                         }
1008                 }
1009         }
1010         echo "<pre>";
1011         print_r($files);
1012         print_r($files_merged);
1013         echo "</pre>";
1014 }
1015 */
1016
1017 /**
1018  * Get mime-type from filename
1019  *
1020  * Defaults to 'application/octet-stream'
1021  *
1022  * @param string $filename The filename with an extension
1023  * @return string mime type
1024  */
1025 function set_mime($filename) {
1026         $ext_arr = explode('.', $filename);
1027         $ext = strtolower(array_pop($ext_arr));
1028         switch($ext) {
1029                 case 'avi':
1030                         $mime = 'video/avi';
1031                         break;
1032                 case 'mpeg':
1033                 case 'mpg':
1034                         $mime = 'video/mpeg';                                   //MPEG Video
1035                         break;
1036                 case 'exe':
1037                 case 'bat':
1038                 case 'doc':
1039                 case 'xls':
1040                         $mime = 'application/octet-stream';
1041                         break;
1042                 case 'gif':
1043                         $mime = 'image/gif';                                    //GIF Image
1044                         break;
1045                 case 'jpg':
1046                 case 'jpeg':
1047                         $mime = 'image/jpeg';                                   //JPEG Image
1048                         break;
1049                 case 'png':
1050                         $mime = 'image/png';                                    //PNG Image
1051                         break;
1052                 case 'wav':
1053                 case 'wave':
1054                         $mime = 'audio/wav';                                    //WAV Audio
1055                         break;
1056                 case 'mp3':
1057                         $mime = 'audio/mpeg';                                   //MP3 Audio
1058                         break;
1059                 case 'mov':
1060                         $mime = 'video/mov';                                    //Quicktime Video
1061                         break;
1062                 case 'wmv':
1063                         $mime = 'video/x-ms-wmv';                       //Windows WMV video
1064                         break;
1065                 case 'wma':
1066                         $mime = 'audio/x-ms-wma';                       //Windows WMA audio
1067                         break;
1068                 case 'rm':
1069                         $mime = 'audio/x-realaudio';    //RealPlayer Audio/Video (.rm)
1070                         break;
1071                 case 'ram':
1072                         $mime = 'audio/x-pn-realaudio'; //RealPlayer Audio/Video (.ram)
1073                         break;
1074                 case 'pdf':
1075                         $mime = 'application/pdf';              //PDF Document
1076                         break;
1077                 case 'doc':
1078                         $mime = 'application/msword';   //MS Word .doc file
1079                         break;
1080                 case 'zip':
1081                         $mime = 'application/zip';              //Zip File
1082                         break;
1083                 default:
1084                         $mime = 'application/octet-stream';
1085                         break;
1086         }
1087         //$return['mime']=$mime;
1088         //$return['ext']=$ext;
1089
1090         return $mime;
1091 }
1092
1093 }
1094 // vim: syntax=php ts=4 sw=4 sts=4 sr noet
1095 ?>