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