blank
[squasher.git] / squasher.class.php
1 <?php
2 require_once("include/connect.inc.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','".mysql_escape_string($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
46 class squashweb {
47
48 var $basepath;
49 var $configs;
50 var $stats;
51 var $files;
52 var $subfolders;
53 var $folderrights;
54 var $userrights;
55 var $history;
56
57 function set_root($root) {
58         $this->basepath = $root;
59 }
60
61 function get_configs() {
62         return $this->configs;
63 }
64
65 function subfolders() {
66         return $this->subfolders;
67 }
68
69 function get_config($h) {
70
71         return $this->configs[$h];
72 }
73
74 function folderrights() {
75         return $this->folderrights;
76 }
77
78 function userrights() {
79         return $this->userrights;
80 }
81
82 function update_history() {
83         $q="SELECT md5_hash,file,completed,checked FROM file_hash";
84         $r=mysql_query($q);
85         while($o=mysql_fetch_object($r)) {
86                 $this->history[$o->md5_hash]['file']=$o->file;
87                 $this->history[$o->md5_hash]['completed']=$o->completed;
88                 $this->history[$o->md5_hash]['checked']=$o->checked;
89         }
90 }
91
92 function got_rights_checkbox($needle) {
93         $result = $this->got_rights_array($needle,'',0,'userrights');
94         switch($result) {
95                 case 0:
96                         $return = '';
97                         break;
98                 case 1:
99                 case 2:
100                         $return = 'checked';
101                         break;
102         }
103         return $return;
104 }
105
106 function get_users($user_level) {
107         $q = "SELECT * FROM users WHERE user_level < '".$user_level."' order by user_name asc";
108         $r = mysql_query($q);
109
110         while ($o = mysql_fetch_object($r)) {
111                 $return[$o->user_id]['id']              = $o->user_id;
112                 $return[$o->user_id]['name']    = $o->user_name;
113                 $return[$o->user_id]['level']   = $o->user_level;
114                 $return[$o->user_id]['enabled'] = ($o->user_pass == '') ? false : true ;
115         }
116
117         return $return;
118 }
119
120 function get_logs($type='all') {
121         $q="SELECT log.* FROM log WHERE log.user_id != '1' and ip != '87.233.211.2' ";
122         if ($_SESSION['creds']['user_id'] == 1)
123                 $q="SELECT log.* FROM log WHERE log.user_id != 'x' ";
124         switch($type) {
125         case "delete":
126                 $q.= " and log.action = 'delete'";
127                 break;
128         case "download":
129                 $q.= " and log.action = 'download'";
130                 break;
131         case "login":
132                 $q.= " and log.action = 'login'";
133                 break;
134         case "debug":
135                 $q.= " and log.action = 'debug'";
136                 break;
137         default:
138                 $q.= "";
139                 break;
140         }
141
142         $today     =" and date > date(date_add(now(), interval -0 day)) ";
143         $yesterday =" and date < date(date_add(now(), interval -0 day)) and date > date(date_add(now(), interval -1 day)) ";
144         $lastweek  =" and date < date(date_add(now(), interval -1 day)) and date > date(date_add(now(), interval -6 day)) ";
145         $older     =" and date < date(date_add(now(), interval -7 day)) and date > date(date_add(now(), interval -30 day)) ";
146
147         $order=" order by log.log_id desc ";
148         $r = mysql_query($q.$today.$order);
149         while($a = mysql_fetch_array($r)) {
150                 $qu="select users.user_name from users left join log on users.user_id = log.user_id where log.ip='{".$a['ip']."}' group by users.user_name";
151                 $ru = mysql_query($qu);
152                 $a['users_from_ip'] = " | ";
153                 while($au = mysql_fetch_array($ru))
154                         $a['users_from_ip'] .= $au['user_name']." | ";
155                 $return['today'][$a['log_id']] = $a;
156         }
157         $r = mysql_query($q.$yesterday.$order);
158         while($a = mysql_fetch_array($r)) {
159                 $qu="select users.user_name from users left join log on users.user_id = log.user_id where log.ip='{".$a['ip']."}' group by users.user_name";
160                 $ru = mysql_query($qu);
161                 $a['users_from_ip'] = " | ";
162                 while($au = mysql_fetch_array($ru))
163                         $a['users_from_ip'] .= $au['user_name']." | ";
164                 $return['yesterday'][$a['log_id']] = $a;
165         }
166         $r = mysql_query($q.$lastweek.$order);
167         while($a = mysql_fetch_array($r)) {
168                 $qu="select users.user_name from users left join log on users.user_id = log.user_id where log.ip='{".$a['ip']."}' group by users.user_name";
169                 $ru = mysql_query($qu);
170                 $a['users_from_ip'] = " | ";
171                 while($au = mysql_fetch_array($ru))
172                         $a['users_from_ip'] .= $au['user_name']." | ";
173                 $return['lastweek'][$a['log_id']] = $a;
174         }
175         $r = mysql_query($q.$older.$order);
176         while($a = mysql_fetch_array($r)) {
177                 $qu="select users.user_name from users left join log on users.user_id = log.user_id where log.ip='{".$a['ip']."}' group by users.user_name";
178                 $ru = mysql_query($qu);
179                 $a['users_from_ip'] = " | ";
180                 while($au = mysql_fetch_array($ru))
181                         $a['users_from_ip'] .= $au['user_name']." | ";
182                 $return['older'][$a['log_id']] = $a;
183         }
184
185         return $return;
186 }
187
188 function insert_users($submitted, $admin_level) {
189         $q = "INSERT INTO users (user_name,user_pass,user_level) values ('".$submitted['u']['user_name']."','".md5($submitted['u']['user_pass'])."','".$submitted['u']['user_level']."')";
190         $r = mysql_query($q);
191 }
192
193 function update_users($submitted) {
194         $q = "UPDATE users SET user_name = '".$submitted['u']['user_name']."', user_pass = '".md5($submitted['u']['user_pass'])."', user_level = '".$submitted['u']['user_level']."' WHERE user_id = '".$submitted['u']['user_id']."'";
195         $r = mysql_query($q);
196 }
197
198 function disable_users($submitted) {
199         $q = "UPDATE users SET user_name = '".$submitted['u']['user_name']."', user_pass = '', user_level = '".$submitted['u']['user_level']."' WHERE user_id = '".$submitted['u']['user_id']."'";
200         $r = mysql_query($q);
201 }
202
203 function remove_users($submitted) {
204         $q = "DELETE FROM users WHERE user_id = '".$submitted['u']['user_id']."'";
205         $r = mysql_query($q);
206 }
207
208 function give_rights($user_id, $type='folderrights') {
209
210         $q = "SELECT folder_path, access FROM user_rights WHERE user_id = '".$user_id."'";
211         $r = mysql_query($q);
212         while ($o = mysql_fetch_object($r)) {
213
214                 //clean vars
215                 $arr_string = '$this->'.$type;
216
217                 //get foldernames from path
218                 if ($o->folder_path != '/') {
219                         $path = $o->folder_path;
220                         if ($path{0}=='/')
221                                 $path=substr($path,1);
222                         $folder_arr = explode('/',$path);
223
224                         //create folder structure array
225                         foreach ($folder_arr AS $key => $value) {
226                                 $arr_string .= "['".$value."']";
227                         }
228                 }
229                 $arr_string .= "['__access__']";
230
231                 //choose access icon
232                 // access = # --deny-all
233                 // access = * --allow-dir-only
234                 // access = @ --allow-inc-subs
235 /*              switch($o->access) {
236                         case 0 :
237                                 $icon = '#';
238                                 break;
239                         case 1 :
240                                 $icon = '*';
241                                 break;
242                         case 2 :
243                                 $icon = '@';
244                                 break;
245                 }*/
246                 //echo $arr_string." = '".$icon."'\n";
247                 //echo $arr_string." = '".$o->access."';";
248                 eval($arr_string." = '".$o->access."';");
249         }
250
251         return $this->folderrights;
252 }
253
254 function update_rights($submitted, $admin_level) {
255         $q = "SELECT count(*) result FROM users WHERE user_id = '".$submitted['edited_user']."' AND user_level < '".$admin_level."'";
256         $r = mysql_query($q);
257         $o = mysql_fetch_object($r);
258
259         if ($o->result) {
260                 foreach ($submitted['m'] AS $path => $access) {
261                         $p_q = "SELECT count(*) result FROM user_rights WHERE user_id = '".$submitted['edited_user']."' AND folder_path = '".$path."'";
262                         $p_r = mysql_query($p_q);
263                         $p_o = mysql_fetch_object($p_r);
264                         if ($p_o->result == 1)
265                                 mysql_query("UPDATE user_rights SET access = ".$access." WHERE folder_path = '".$path."' AND user_id = '".$submitted['edited_user']."'");
266                         if ($p_o->result == 0)
267                                 mysql_query("INSERT INTO user_rights (user_id,folder_path,access) values ('".$submitted['edited_user']."','".$path."','".$access."') ");
268                 }
269         }
270 }
271
272
273 function show_rights_tree($path, $depth=0, $userid=0) {
274
275         if ($userid==0)
276                 return false;
277         if ($depth==0)
278                 $this->give_rights($userid, 'userrights');
279
280         // access = # | 0 --deny-all
281         // access = * | 1 --allow-dir-only
282         // access = @ | 2 --allow-inc-subs
283
284         for ($i=0;$depth > $i; $i++)
285                 $layout .= " ";
286         if ($dir = opendir($path)) {
287                 $layout .= "<div style='clear:both;' >\n";
288                 $f=0;
289                 while (false !== ($file = readdir($dir))) {
290                         $files_array[]=$file;
291                 }
292                 asort($files_array);
293                 foreach ($files_array as $f_index => $file) {
294 //              while (false !== ($file = readdir($dir)))
295 //              {
296                         if (($file{0} !== ".") && ($file !== ".."))
297                         {
298                                 $filename = $path."/".$file;
299                                 if (!is_file($filename) && $this->got_rights_array($filename) > 0) {
300                                         $f++;
301                                         if (substr($filename,0,strlen($this->basepath))==$this->basepath)
302                                                 $name = substr($filename,strlen($this->basepath));
303                                         //$check = $this->got_rights_checkbox($filename);
304                                         $check = $this->got_rights_array_admin($filename, '', 0, 'userrights');
305                                         $check_all = '';
306                                         $check_allow = '';
307                                         $check_deny = '';
308                                         switch($check) {
309                                                 case 2:
310                                                         $check_all = 'checked';
311                                                         break;
312                                                 case 1:
313                                                         $check_allow = 'checked';
314                                                         break;
315                                                 case 0:
316                                                 default:
317                                                         $check_deny = 'checked';
318                                                         break;
319                                         }
320
321                                         if ($f==1)
322                                                 $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).";}";
323                                         if ($f==1)
324                                                 $layout .= "<div class='depth".$depth."'>";
325                                         $layout .= "<div class='white_border' >".$file."</div>\n";
326                                         $layout .= "<div class='check_deny'><input name='m[".$name."]' value=0 type=radio ".$check_deny."></div>\n";
327                                         $layout .= "<div class='check_allow'><input name='m[".$name."]' value=1 type=radio ".$check_allow."></div>\n";
328                                         $layout .= "<div class='check_all'><input name='m[".$name."]' value=2 type=radio ".$check_all."></div>\n";
329                                         $sub_return = $this->show_rights_tree($filename,$depth+1,$userid);
330                                         if (is_array($style) && is_array($sub_return['style']))
331                                                 $style = $style + $sub_return['style'];
332                                         $layout .= $sub_return['layout'];
333                                 }
334                         }
335                 }
336                 if ($f!=0)
337                         $layout .= "</div>";
338                 $layout .= "</div>\n";
339         }
340
341         $return['style'] = $style;
342         $return['layout'] = $layout;
343
344         return $return;
345 }
346
347 function got_rights_path($needle, $haystack) {
348         if (!is_array($haystack))
349                 $haystack = $this->folderrights;
350         foreach($haystack as $v) {
351                 if (!is_array($v)) {
352                         if ($needle == $v)
353                                 return true;
354                 } else {
355                         if (is_in_array($needle, $v, $case_sensitive) === true)
356                                 return true;
357                 }
358         }
359         return false;
360 }
361
362 function got_rights_array($needle, $haystack='', $c=0, $type='folderrights') {
363         if (!is_array($haystack))
364                 eval('$haystack = $this->'.$type.';');
365         if (substr($needle, 0, strlen($this->basepath)) == $this->basepath)
366                 $needle=substr($needle,strlen($this->basepath));
367
368         //if ($needle{0}=='.')
369         //      $needle=substr($needle, strlen($this->basepath));
370
371         //check root rights
372         if ($needle{0}=='/' && $haystack['__access__'] == 2 )
373                 return 2;
374
375         //check folder tights
376         if ($needle{0}=='/')
377                 $needle=substr($needle,1);
378
379         $needle_arr = explode('/',$needle);
380         $n = count($needle_arr);
381         $d = $c+1;
382
383         foreach ($haystack as $k => $v) {
384                 if ($needle_arr[$c] == $k) {
385                         if (!is_array($v['__access__'])) {
386                                 if (($v['__access__'] == '@' || $v['__access__'] == 2)                     ) return 2;
387                                 if (($v['__access__'] == '*' || $v['__access__'] == 1) && $d == $n ) return 1;
388                                 if (($v['__access__'] == '#' || $v['__access__'] == 0) && $d == $n ) return 0;
389                         } else {
390                                 $return = $this->got_rights_array($needle, $v, $d);
391                         }
392                 }
393         }
394         return $return;
395 }
396
397 function got_rights_array_admin($needle, $haystack='', $c=0, $type='folderrights') {
398
399         if (!is_array($haystack))
400                 eval('$haystack = $this->'.$type.';');
401         if (substr($needle, 0, strlen($this->basepath)) == $this->basepath)
402                 $needle = substr($needle, strlen($this->basepath));
403
404         //if ($needle{0}=='.')
405         //      $needle=substr($needle,strlen($this->basepath));
406
407         //check root rights
408         if ($needle{0}=='/' && $haystack['__access__'] == 2 )
409                 return 2;
410
411         //check folder rights
412         if ($needle{0}=='/')
413                 $needle=substr($needle, 1);
414
415         $needle_arr = explode('/',$needle);
416         $n = count($needle_arr);
417         $d = $c+1;
418         $return = 0;
419
420         if ($c < $n) {
421                 if ($haystack['__access__'] == 2)
422                         return $haystack['__access__'];
423                 if (is_array($haystack[$needle_arr[$c]]))
424                         $return = $this->got_rights_array_admin($needle, $haystack[$needle_arr[$c]], $d);
425         } else {
426                 if ($haystack['__access__'] > 0)
427                         $return = $haystack['__access__'];
428         }
429
430         return $return;
431 }
432
433 function got_rights_array_recursive($needle, $haystack='', $c=0, $type='folderrights') {
434
435         if (!is_array($haystack))
436                 eval('$haystack = $this->'.$type.';');
437         if (substr($needle, 0, strlen($this->basepath)) == $this->basepath)
438                 $needle=substr($needle, strlen($this->basepath));
439
440         //if($needle{0}=='.')
441         //      $needle=substr($needle,strlen($this->basepath));
442
443         //check root rights
444         if($needle{0}=='/' && $haystack['__access__'] == 2 )
445                 return 2;
446
447         //check folder rights
448         if($needle{0}=='/')
449                 $needle=substr($needle,1);
450
451         $needle_arr = explode('/', $needle);
452         $n = count($needle_arr);
453         $d = $c+1;
454         $return = 0;
455
456         foreach($haystack as $k => $v) {
457                 if ($needle_arr[$c] == $k) {
458                         if ($c < $n) {
459                                 if ($v['__access__'] == 2)
460                                         $return = $return + $v['__access__'];
461                                 $return = $return + $this->got_rights_array_recursive($needle, $v, $d);
462                         } else {
463                                 $return = $return + $this->in_array_recursive($v);
464                         }
465                 } elseif ($c == $n) {
466                         $return = $return + $v['__access__'];
467                         if($k != '__access__')$return = $return + $this->in_array_recursive($v);
468                 }
469         }
470
471         return $return;
472 }
473
474 function in_array_recursive($haystack) {
475         $return = 0;
476         if (is_array($haystack)) {
477                 foreach ($haystack as $key1 => $value1) {
478                         if (is_array($value1)) {
479                                 $return = $return + $this->in_array_recursive($value1);
480                         }
481                         elseif ($value1 > 0) {
482                                 return $value1;
483                         }
484                 }
485         }
486         return $return;
487 }
488
489 function read_single_file($path, $file) {
490         $filename = $path."/".$file;
491         $i = 0;
492         if ($this->got_rights_array($path) > 0) {
493                 if (is_file($filename.'.Completed'))
494                         $file.='.Completed';
495                 if (is_file($filename.'.InProgress'))
496                         $file.='.InProgress';
497                 if (is_file($filename.'.Starting'))
498                         $file.='.Starting';
499                 if (is_file($filename.'.Processed'))
500                         $file.='.Processed';
501                 $filename = $path . "/" . $file;
502                 $handle = @fopen($filename, "rb");
503                 if (strpos($file,'.Completed'))
504                         $ext='.Completed';
505                 if (strpos($file,'.InProgress'))
506                         $ext='.InProgress';
507                 if (strpos($file,'.Starting'))
508                         $ext='.Starting';
509                 if (strpos($file,'.Processed'))
510                         $ext='.Processed';
511                 $sub_pos = strpos($file, $ext);
512                 $base_name = substr($file, 0, $sub_pos);
513                 $filecontent = @fread($handle, @filesize($filename));
514                 $config[$i] = explode("\r\n", $filecontent);
515                 /***
516                 *       $config:: array
517                 *       [0]     ->      versioncode
518                 *       [1]     ->      date&time
519                 *       [2]     ->      filename
520                 *       [3]     ->      filesize
521                 *       [4]     ->      chunksize
522                 *       [5]     ->      chunkcount
523                 *       [6]     ->      CRC32 checksum
524                 ***/
525                 if (@filesize($filename) > 0) {
526                         $h = md5($path."/".$config[$i][2]);
527                         $this->configs[$h] = $config[$i];
528                         $this->configs[$h]['squashed'] = true;
529                         $this->configs[$h]['path'] = $path;
530                         $this->configs[$h]['status'] = substr($ext, 1);
531                         $this->configs[$h]['mime'] = $this->set_mime($this->configs[$h][2]);
532                         $this->configs[$h]['hidden'] = (is_file($path.'/'.$base_name.'.hidden')) ? true : false ;
533                         //to prevent dates of 1-1-1970 we set te dates of the config file
534                         $this->configs[$h]['added'] = filectime($filename);
535                         $this->configs[$h]['lastchange'] = filemtime($filename);
536                         fclose($handle);
537                         $this->populate_stats($path, $h);
538                         //insert hash in db
539                         #$this->update_hash($h,$path."/".$config[$i][2]);
540                         //check stats
541                         $this->check_stats($h);
542                 }
543         }
544 }
545
546
547 function read_directory($path, $getsubs=false, $getfirstfiles=true, $getdeepfiles=true, $populate=true) {
548
549         if ($dir = @opendir($path)) {
550                 $i = 0;
551                 $last = 1;
552                 while (false !== ($file = readdir($dir))) {
553                         if (($file{0} !== ".") && substr($file,0,1) !== "SQ") {
554                                 $filename = $path."/".$file;
555                                 if (!is_file($filename) && !strpos($filename, './uploads/recieving')) {
556                                         if ($getsubs) {
557                                                 if ($this->got_rights_array_recursive($filename) > 0) {
558                                                         $key = substr($path,strlen($this->basepath)) . '/' . $file;
559                                                         $this->subfolders[$key] = $file;
560                                                 }
561                                         }
562                                         if ($getdeepfiles)$this->read_directory($filename, false, $getdeepfiles, $getdeepfiles, $populate);
563                                 } elseif (strpos($filename,'./uploads/ftp')) { //ftp files
564                                         if ($this->got_rights_array($path) > 0 && !strpos($filename, '.hidden') ) {
565                                                 $h = md5($filename);
566                                                 $name_only = substr($filename, strlen($path)+1);
567                                                 $file_structure = explode('.', $name_only);
568                                                 $ext = array_pop($file_structure);
569                                                 $base_name = array_pop($file_structure);
570                                                 $this->configs[$h]['path'] = $path;
571                                                 $this->configs[$h][0] = 'manual ftp';
572                                                 $this->configs[$h][2] = $name_only;
573                                                 $this->configs[$h][3] = filesize($filename);
574                                                 $this->configs[$h]['added'] = filectime($filename);
575                                                 $this->configs[$h]['lastchange'] = filemtime($filename);
576                                                 $this->configs[$h]['status'] = 'unknown';
577                                                 $this->configs[$h]['squashed'] = false;
578                                                 $this->configs[$h]['mime'] = $this->set_mime($name_only);
579                                                 $this->configs[$h]['hidden'] = (is_file($path.'/'.$base_name.'.hidden')) ? true : false ;
580                                         }
581                                 } elseif ($getfirstfiles) { //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($filename, "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($filename));
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($filename) > 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($path.'/'.$base_name.'.hidden')) ? true : false ;
618                                                                 //to prevent dates of 1-1-1970 we set te dates of the config file
619                                                                 $this->configs[$h]['added'] = filectime($filename);
620                                                                 $this->configs[$h]['lastchange'] = filemtime($filename);
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                 }
633         }
634 }
635
636 function check_stats($h) {
637         $config = $this->get_config($h);
638         $count = @array_sum($config['stats']);
639         if ($config['status']=='Completed' && $count != $config[5]) {
640                 $filepath=$config['path'].'/'.$config[2];
641                 if ($this->history[$h]['completed']=="1") {
642                         //don't display broken file, remove it instead
643                         unlink($config['path'].'/'.$config[2].'.Completed');
644                         unset($this->configs[$h]);
645
646                         if (!$count)
647                                 $count = 0;
648                         $m_subject = "Squasher Debug: File Removed";
649                         $m_body = "Upload removed: \n File: ".$config['path']."/".$config[2]." \n Status: ".$config['status']." \n Chunks: ".$count." out of ".$config[5];
650                         mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
651                         $qlog = "insert into log (hash,file,action,user_id,user_name,ip,date) values ('{$h}','{$filepath}','debug','-1','squasher-web','cleanup',NOW())";
652                         mysql_query($qlog);
653                 } else {
654                         //do move
655                         rename($config['path'].'/'.$config[2].'.Completed', $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 ('{$h}','{$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 = '".$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 ('".$hash."','".$path."')";
691                 mysql_query($insert_hash_query);
692         }
693 }
694
695 function path_to_arraystring($path, $arrayname) {
696         $path_values = explode('/', $path);
697         $return = $arrayname;
698         foreach ($path_values AS $key => $value) {
699                 if ($value != '.' && $value != '')
700                         $return.= "['".$value."']";
701         }
702         return $return;
703 }
704
705 function populate_stats($path, $h) {
706         /***
707         *       $config:: array
708         *       [0]     ->      versioncode
709         *       [1]     ->      date&time
710         *       [2]     ->      filename
711         *       [3]     ->      filesize
712         *       [4]     ->      chunksize
713         *       [5]     ->      chunkcount
714         *       [6]     ->      CRC32 checksum
715         ***/
716         $config = $this->configs[$h];
717
718         $q = "SELECT * FROM file_hash WHERE md5_hash = '{$h}'";
719         $r = mysql_query($q);
720         $o = mysql_fetch_object($r);
721         $validated_chunks = $o->validated_chunks;
722
723         if ($this->history[$h]['completed']=="1") {
724                 $file_part = $path."/SQ".zfill(1,6)."-".$config[2];
725                 if (!is_file($file_part))
726                         $file_part = $path."/SQ".zfill(1,3)."-".$config[2];
727                 if (is_file($file_part)) {
728                         $this->configs[$h]['added'] = filectime($file_part);
729                         $file_part = $path."/SQ".zfill($config[5],6)."-".$config[2];
730                         if (!is_file($file_part))
731                                 $file_part = $path."/SQ".zfill($config[5],3)."-".$config[2];
732                         if (is_file($file_part))
733                                 $this->configs[$h]['lastchange'] = filemtime($file_part);
734                         for ($i=1; $i<=$config[5]; $i++)
735                                 $this->configs[$h]['stats'][$i] = "1.00";
736                 } else {
737                         //failsafe voor verwijderde bestanden
738                         mysql_query("UPDATE file_hash SET completed = 0 WHERE md5_hash = '".$h."'");
739                 }
740         } else {
741                 $keep_validating = true;
742                 for ($i=1; $i<=$config[5]; $i++) {
743                         if ($validated_chunks > $i) {
744                                 $this->configs[$h]['stats'][$i]="1.00";
745                         } else {
746                                 $file_part = $path."/SQ".zfill($i,6)."-".$config[2];
747                                 if (!is_file($file_part))
748                                         $file_part = $path."/SQ".zfill($i,3)."-".$config[2];
749                                 if (is_file($file_part)) {
750                                         $handle = fopen($file_part, "rb");
751                                         $size_this = filesize($file_part);
752                                         $added = filectime($file_part);
753                                         $last_changed = filemtime($file_part);
754                                         if ($this->configs[$h]['added'] > $added || !is_numeric($this->configs[$h]['added']))
755                                                 $this->configs[$h]['added'] = $added;
756                                         if ($this->configs[$h]['lastchange'] < $last_changed)
757                                                 $this->configs[$h]['lastchange'] = $last_changed;
758                                         if ($i != $config[5]) {
759                                                 $this->configs[$h]['stats'][$i] = number_format((1/$config[4])*$size_this, 2, '.', '');
760                                         //number_format((100/$config[4])*$size_this, 2, '.', '')."%";
761                                         }else{
762                                                 $this->configs[$h]['stats'][$i] = number_format((1/($config[3]-($config[4]*($config[5]-1))))*$size_this, 2, '.', '');
763                                                 //number_format((100/($config[3]-($config[4]*($config[5]-1))))*$size_this, 2, '.', '')."%";
764                                         }
765                                         fclose($handle);
766                                         if ($config[4] == $size_this && $keep_validating) {
767                                                 $validated_chunks = $i;
768                                         } else {
769                                                 $keep_validating = false;
770                                         }
771                                 } else {
772                                         $this->configs[$h]['stats'][$i] = "0.00";
773                                         //$this->configs[$h]['stats'][$i]="0.00%";
774
775                                 }
776                         }
777                 }
778                 mysql_query("UPDATE file_hash SET validated_chunks = '{$validated_chunks}' WHERE md5_hash = '".$h."'");
779         }
780 }
781
782 function read_config($path, $filename) {
783         if (is_file($path."/".$filename.".InProgress")) {
784                 $config_handle = fopen($path."/".$filename.".InProgress", "r");
785                 $conf_path=$path."/".$filename.".InProgress";
786         } elseif (is_file($path."/".$filename.".Completed" )) {
787                 $config_handle = fopen($path."/".$filename.".Completed", "r");
788                 $conf_path=$path."/".$filename.".Completed";
789         } elseif (is_file($path."/".$filename.".Starting" )) {
790                 $config_handle = fopen($path."/".$filename.".Starting", "r");
791                 $conf_path=$path."/".$filename.".Starting";
792         } elseif (is_file($path."/".$filename.".Processed" )) {
793                 $config_handle = fopen($path."/".$filename.".Processed", "r");
794                 $conf_path=$path."/".$filename.".Processed";
795         } else {
796                 return "Not Found";
797         }
798         $config_content = fread($config_handle, filesize($conf_path));
799         fclose($config_handle);
800         $config = explode("\n", $config_content);
801
802         return $config;
803 //              print_r($config);
804 /*              $file_count = $config[5];
805                 $last=1;
806     for ($i=1; $i<=$file_count; $i++)
807     {
808         $file_part = $path."/SQ".zfill($i,6)."-".$filename;
809         if (is_file($file_part))
810        {
811
812         $handle = fopen($file_part, "rb");
813         $size_this = filesize($file_part);
814                                 //$stats[$i]=round((100/$config[4])*$size_this)."%";
815                                 if ((($size_this==$config[4] && ($last+1)==$i) )|| $i == $config[5]) {
816                                         $merged_file.=fread($handle, filesize($file_part));
817                                         $last = $i;
818                                 }
819         fclose($handle);
820        }
821      }
822      return $merged_file;
823      */
824 }
825
826 function print_files($path, $filename, $tovar=false) {
827         if (strpos($path, './uploads/ftp')) {
828                 $filestring = $path.'/'.$filename;
829                 if (is_file($filestring)) {
830                         $handle = fopen($filestring, "rb");
831                         while (!feof($handle))
832                         {
833                                 print(fread($handle, 1024));
834                                 ob_flush();
835                                 flush();
836                         }
837                 }
838         } else {
839                 if (is_file($path."/".$filename.".InProgress")) {
840                         $config_handle = fopen($path."/".$filename.".InProgress", "r");
841                         $conf_path=$path."/".$filename.".InProgress";
842                 } elseif (is_file($path."/".$filename.".Completed" )) {
843                         $config_handle = fopen($path."/".$filename.".Completed", "r");
844                         $conf_path=$path."/".$filename.".Completed";
845                 } elseif (is_file($path."/".$filename.".Starting" )) {
846                         $config_handle = fopen($path."/".$filename.".Starting", "r");
847                         $conf_path=$path."/".$filename.".Starting";
848                 } elseif (is_file($path."/".$filename.".Processed" )) {
849                         $config_handle = fopen($path."/".$filename.".Processed", "r");
850                         $conf_path=$path."/".$filename.".Processed";
851                 } else{
852                         return "Not Found";
853                 }
854                 $config_content = fread($config_handle, filesize($conf_path));
855                 fclose($config_handle);
856                 $config = explode("\n",$config_content);
857 //              print_r($config);
858                 $file_count = $config[5];
859                 $last = 0;
860                 $last_part_size = ( $config[3] - ( ( $config[5] -1 ) * $config[4] ) );
861                 for ($i=0;$i<=$file_count;$i++)
862                 {
863                         $file_part = $path."/SQ".zfill($i,6)."-".$filename;
864                         if (!is_file($file_part))
865                                 $file_part = $path."/SQ".zfill($i,3)."-".$filename;
866                         if (is_file($file_part))
867                         {
868                                 $handle = fopen($file_part, "rb");
869                                 $size_this = filesize($file_part);
870                                 if ( ( ( $size_this==$config[4] ) && ( ($last+1)==$i ) ) || ( ( $i == $config[5] ) && ( $size_this==$last_part_size ) && ( ($last+1)==$i ) ) ) {
871                                         if ($tovar) {
872                                                 $merged_file.=fread($handle, $size_this);
873                                                 $last = $i;
874                                         } else {
875                                                 while (!feof($handle))
876                                                 {
877                                                         print(fread($handle, 4096));
878                                                 #       @ob_flush();
879                                                 #       @flush();
880                                                 }
881                                                 $last = $i;
882                                         }
883                                 }
884                                 fclose($handle);
885                         }
886                 }
887                 if ($tovar)
888                         return $merged_file;
889         }
890 }
891
892 function check_md5($h) {
893         $return = false;
894         $config = $this->configs[$h];
895         $var = $this->print_files($config['path'], $config[2], true);
896         $hash = md5($var);
897         if ($hash==$config[6])
898                 $return=true;
899
900         return $return;
901 }
902
903 function file_crc($file_string) {
904         //$file_string = file_get_contents($file);
905
906         $crc = crc32($file_string);
907         return sprintf("%u\n", $crc);
908 }
909
910 function file_crc_debug($file) {
911         $file_string = file_get_contents($file);
912
913         $crc = crc32($file_string);
914         return sprintf("%u\n", $crc);
915 }
916
917 function delete_file($h, $s) {
918         $request = $this->get_config($h);
919         if (strpos($request['path'], './uploads/ftp')) {
920                 $filepath=$request['path'].'/'.$request[2];
921                 #remove file
922                 if (is_file($filepath))
923                         @unlink($filepath);
924                 if (is_file($filepath.'.hidden'))
925                         @unlink($filepath.'.hidden');
926         } else {
927                 #remove fileparts
928                 for ($i=0;$i<=$request[5];$i++) {
929                         $part_six   = $request['path']."/SQ".zfill($i,6)."-".$request[2];
930                         $part_three = $request['path']."/SQ".zfill($i,3)."-".$request[2];
931                         if (is_file($part_six))
932                                 @unlink($part_six);
933                         if (is_file($part_three))
934                                 @unlink($part_six);
935                 }
936                 #remove config file
937                 if (is_file($request['path'].'/'.$request[2].'.hidden'))        @unlink($request['path'].'/'.$request[2].'.hidden');
938                 if (is_file($request['path'].'/'.$request[2].'.Completed'))     @unlink($request['path'].'/'.$request[2].'.Completed');
939                 if (is_file($request['path'].'/'.$request[2].'.InProgress'))@unlink($request['path'].'/'.$request[2].'.InProgress');
940                 if (is_file($request['path'].'/'.$request[2].'.Processed'))     @unlink($request['path'].'/'.$request[2].'.Processed');
941                 if (is_file($request['path'].'/'.$request[2].'.Starting'))      @unlink($request['path'].'/'.$request[2].'.Starting');
942         }
943
944         #Update DB
945         $q = "delete from file_hash where file_hash = '{$h}'";
946         mysql_query($q);
947         $q = "insert into log (hash,file,action,user_id,user_name,ip,date) values ('{$h}','{$filepath}','delete','".$s['user_id']."','".$s['user_name']."','".$_SERVER['REMOTE_ADDR']."',NOW())";
948         mysql_query($q);
949
950         #Send debug mail
951         $m_name = $s['user_name'];
952         $m_subject = "Squasher Debug: File Deleted by {$m_name}";
953         $m_body = "File Deleted: \n Requested by: {$m_name} \n File: {$filepath}";
954         mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
955 }
956
957 function show_files() {
958
959         $path = "./uploads/";
960
961         if ($dir = opendir($path)) {
962                 $i = 1;
963                 $last = 1;
964                 $files = array();
965                 $files_merged = array();
966                 while (false !== ($file = readdir($dir)))
967                 {
968                         if (($file !== ".") && ($file !== ".."))
969                         {
970                                 $filename = $path.$file;
971                                 $handle = fopen($filename, "rb");
972                                 $size_this = filesize($filename);
973                                 if ($i==1)
974                                         $size_first = $size_this;
975                                 $filecontent = fread($handle, filesize($filename));
976                                 $files[$i++] = $filename;
977                                 $files_merged[$file_base][]=$filename;
978                                 fclose($handle);
979                         }
980                 }
981         }
982         echo "<pre>";
983         print_r($files);
984         print_r($files_merged);
985         echo "</pre>";
986 }
987
988 function set_mime($filename) {
989         $ext_arr = explode('.', $filename);
990         $ext = strtolower(array_pop($ext_arr));
991         switch($ext) {
992                 case 'avi':
993                         $mime = 'video/avi';
994                         break;
995                 case 'mpeg':
996                 case 'mpg':
997                         $mime = 'video/mpeg';                                   //MPEG Video
998                         break;
999                 case 'exe':
1000                 case 'bat':
1001                 case 'doc':
1002                 case 'xls':
1003                         $mime = 'application/octet-stream';
1004                         break;
1005                 case 'gif':
1006                         $mime = 'image/gif';                                    //GIF Image
1007                         break;
1008                 case 'jpg':
1009                 case 'jpeg':
1010                         $mime = 'image/jpeg';                                   //JPEG Image
1011                         break;
1012                 case 'png':
1013                         $mime = 'image/png';                                    //PNG Image
1014                         break;
1015                 case 'wav':
1016                 case 'wave':
1017                         $mime = 'audio/wav';                                    //WAV Audio
1018                         break;
1019                 case 'mp3':
1020                         $mime = 'audio/mpeg';                                   //MP3 Audio
1021                         break;
1022                 case 'mov':
1023                         $mime = 'video/mov';                                    //Quicktime Video
1024                         break;
1025                 case 'wmv':
1026                         $mime = 'video/x-ms-wmv';                       //Windows WMV video
1027                         break;
1028                 case 'wma':
1029                         $mime = 'audio/x-ms-wma';                       //Windows WMA audio
1030                         break;
1031                 case 'rm':
1032                         $mime = 'audio/x-realaudio';    //RealPlayer Audio/Video (.rm)
1033                         break;
1034                 case 'ram':
1035                         $mime = 'audio/x-pn-realaudio'; //RealPlayer Audio/Video (.ram)
1036                         break;
1037                 case 'pdf':
1038                         $mime = 'application/pdf';              //PDF Document
1039                         break;
1040                 case 'doc':
1041                         $mime = 'application/msword';   //MS Word .doc file
1042                         break;
1043                 case 'zip':
1044                         $mime = 'application/zip';              //Zip File
1045                         break;
1046                 default:
1047                         $mime = 'application/octet-stream';
1048                         break;
1049         }
1050         //$return['mime']=$mime;
1051         //$return['ext']=$ext;
1052
1053         return $mime;
1054 }
1055
1056 function embed_video($h) {
1057         /*JASPER FIX, use config->systemurl */
1058                 ?>
1059       <!-- begin embedded WindowsMedia file... -->
1060       <table border='0' cellpadding='0' align="center">
1061       <tr><td>
1062       <OBJECT id='mediaPlayer'
1063       classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'
1064       codebase='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'
1065       standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>
1066       <param name='fileName' value="http://master.squasher.netformatie.nl/?x=asx&f=<?=$h;?>">
1067       <param name='animationatStart' value='true'>
1068       <param name='transparentatStart' value='true'>
1069       <param name='autoStart' value="true">
1070       <param name='showControls' value="true">
1071       <param name='loop' value="true">
1072                         <param name="BufferingTime" value="3">
1073       <EMBED type='application/x-mplayer2'
1074         pluginspage='http://microsoft.com/windows/mediaplayer/en/download/'
1075         id='mediaPlayer' name='mediaPlayer' autosize='1'
1076         bgcolor='darkblue' showcontrols="true" showtracker='-1'
1077         showdisplay='0' showstatusbar='-1' videoborder3d='-1' width='480' height='320'
1078         src="http://master.squasher.netformatie.nl/?x=asx&f=<?=$h;?>" autostart="true" designtimesp='5311' loop="true">
1079       </EMBED>
1080       </OBJECT>
1081       </td></tr>
1082       <!-- ...end embedded WindowsMedia file -->
1083         <!-- begin link to launch external media player... -->
1084         <tr><td align='center'>
1085         <a href="http://master.squasher.netformatie.nl/?x=asx&f=<?=$h;?>" style='font-size: 85%;' target='_blank'>Launch in external player</a>
1086         <!-- ...end link to launch external media player... -->
1087         </td></tr>
1088       </table>
1089                 <?
1090         }
1091
1092 function create_playlist($h, $t='asx', $title='Title') {
1093         switch ($t) {
1094
1095                 case 'asx':
1096
1097                         header('Content-Disposition: attachment; filename="stream.asx"');
1098                         echo '<ASX version="3.0">
1099 <title>Squasher Streaming Video</title>
1100         <Entry>
1101                 <title>Video Stream</title>
1102                 <ref HREF="http://master.squasher.netformatie.nl/?a=x&f='.$h.'"/>
1103         </Entry>
1104 </ASX>';
1105
1106                         break;
1107
1108                 case 'vlc':
1109                         header('Content-Disposition: attachment; filename="stream.'.$t.'"');
1110                         echo '#EXTM3U
1111 #EXTINF:-1,Squasher Streaming Video - '.$title.'
1112 http://master.squasher.netformatie.nl/?a=x&f='.$h.'';
1113
1114                         break;
1115
1116                 case 'm3u':
1117                 default:
1118                         header('Content-Disposition: attachment; filename="stream.m3u"');
1119                         echo '#EXTM3U
1120 #EXTINF:-1,Squasher Streaming Video - '.$title.'
1121 http://master.squasher.netformatie.nl/?a=x&f='.$h.'';
1122
1123                         break;
1124                 }
1125         }
1126 }
1127 // vim: syntax=php ts=4 sw=4 sts=4 sr noet
1128 ?>