Subversion Repositories svnkaklik

Rev

Details | Last modification | View Log

Rev Author Line No. Line
36 kaklik 1
<?php
2
 
3
/*************************************************************
4
*  TorrentFlux - PHP Torrent Manager
5
*  www.torrentflux.com
6
**************************************************************/
7
/*
8
    This file is part of TorrentFlux.
9
 
10
    TorrentFlux is free software; you can redistribute it and/or modify
11
    it under the terms of the GNU General Public License as published by
12
    the Free Software Foundation; either version 2 of the License, or
13
    (at your option) any later version.
14
 
15
    TorrentFlux is distributed in the hope that it will be useful,
16
    but WITHOUT ANY WARRANTY; without even the implied warranty of
17
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
    GNU General Public License for more details.
19
 
20
    You should have received a copy of the GNU General Public License
21
    along with TorrentFlux; if not, write to the Free Software
22
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
*/
24
 
25
// Start Session and grab user
26
session_start("TorrentFlux");
27
 
28
if(isset($_SESSION['user']))
29
{
30
    $cfg["user"] = strtolower($_SESSION['user']);
31
}else{
32
    $cfg["user"] = "";
33
}
34
 
35
include_once('db.php');
36
include_once("settingsfunctions.php");
37
 
38
// Create Connection.
39
$db = getdb();
40
 
41
loadSettings();
42
 
43
// Free space in MB
44
$cfg["free_space"] = @disk_free_space($cfg["path"])/(1024*1024);
45
 
46
// Path to where the torrent meta files will be stored... usually a sub of $cfg["path"]
47
// also, not the '.' to make this a hidden directory
48
$cfg["torrent_file_path"] = $cfg["path"].".torrents/";
49
 
50
Authenticate();
51
 
52
include_once("language/".$cfg["language_file"]);
53
include_once("themes/".$cfg["theme"]."/index.php");
54
AuditAction($cfg["constants"]["hit"], $_SERVER['PHP_SELF']);
55
PruneDB();
56
 
57
// is there a stat and torrent dir?  If not then it will create it.
58
checkTorrentPath();
59
 
60
//**********************************************************************************
61
// START FUNCTIONS HERE
62
//**********************************************************************************
63
 
64
//*********************************************************
65
// avddelete()
66
function avddelete($file)
67
{
68
    chmod($file,0777);
69
    if (@is_dir($file))
70
    {
71
        $handle = @opendir($file);
72
        while($filename = readdir($handle))
73
        {
74
            if ($filename != "." && $filename != "..")
75
            {
76
                avddelete($file."/".$filename);
77
            }
78
        }
79
        closedir($handle);
80
        @rmdir($file);
81
    }
82
    else
83
    {
84
        @unlink($file);
85
    }
86
}
87
 
88
 
89
//*********************************************************
90
// Authenticate()
91
function Authenticate()
92
{
93
    global $cfg, $db;
94
 
95
    $create_time = time();
96
 
97
    if(!isset($_SESSION['user']))
98
    {
99
        header('location: login.php');
100
        exit();
101
    }
102
 
103
    if ($_SESSION['user'] == md5($cfg["pagetitle"]))
104
    {
105
        // user changed password and needs to login again
106
        header('location: logout.php');
107
        exit();
108
    }
109
 
110
    $sql = "SELECT uid, hits, hide_offline, theme, language_file FROM tf_users WHERE user_id=".$db->qstr($cfg['user']);
111
    $recordset = $db->Execute($sql);
112
    showError($db, $sql);
113
 
114
    if($recordset->RecordCount() != 1)
115
    {
116
        AuditAction($cfg["constants"]["error"], "FAILED AUTH: ".$cfg['user']);
117
        session_destroy();
118
        header('location: login.php');
119
        exit();
120
    }
121
 
122
    list($uid, $hits, $cfg["hide_offline"], $cfg["theme"], $cfg["language_file"]) = $recordset->FetchRow();
123
 
124
    // Check for valid theme
125
    if (!ereg('^[^./][^/]*$', $cfg["theme"]))
126
    {
127
        AuditAction($cfg["constants"]["error"], "THEME VARIABLE CHANGE ATTEMPT: ".$cfg["theme"]." from ".$cfg['user']);
128
        $cfg["theme"] = $cfg["default_theme"];
129
    }
130
 
131
    // Check for valid language file
132
    if(!ereg('^[^./][^/]*$', $cfg["language_file"]))
133
    {
134
        AuditAction($cfg["constants"]["error"], "LANGUAGE VARIABLE CHANGE ATTEMPT: ".$cfg["language_file"]." from ".$cfg['user']);
135
        $cfg["language_file"] = $cfg["default_language"];
136
    }
137
 
138
    if (!is_dir("themes/".$cfg["theme"]))
139
    {
140
        $cfg["theme"] = $cfg["default_theme"];
141
    }
142
 
143
    // Check for valid language file
144
    if (!is_file("language/".$cfg["language_file"]))
145
    {
146
        $cfg["language_file"] = $cfg["default_language"];
147
    }
148
 
149
    $hits++;
150
 
151
    $sql = 'select * from tf_users where uid = '.$uid;
152
    $rs = $db->Execute($sql);
153
    showError($db, $sql);
154
 
155
    $rec = array(
156
                    'hits' => $hits,
157
                    'last_visit' => $create_time,
158
                    'theme' => $cfg['theme'],
159
                    'language_file' => $cfg['language_file']
160
                );
161
    $sql = $db->GetUpdateSQL($rs, $rec);
162
 
163
    $result = $db->Execute($sql);
164
    showError($db,$sql);
165
}
166
 
167
 
168
//*********************************************************
169
// SaveMessage
170
function SaveMessage($to_user, $from_user, $message, $to_all=0, $force_read=0)
171
{
172
    global $_SERVER, $cfg, $db;
173
 
174
    $message = str_replace(array("'"), "", $message);
175
 
176
    $create_time = time();
177
 
178
    $sTable = 'tf_messages';
179
    if($to_all == 1)
180
    {
181
        $message .= "\n\n__________________________________\n*** "._MESSAGETOALL." ***";
182
        $sql = 'select user_id from tf_users';
183
        $result = $db->Execute($sql);
184
        showError($db,$sql);
185
 
186
        while($row = $result->FetchRow())
187
        {
188
            $rec = array(
189
                        'to_user' => $row['user_id'],
190
                        'from_user' => $from_user,
191
                        'message' => $message,
192
                        'IsNew' => 1,
193
                        'ip' => $cfg['ip'],
194
                        'time' => $create_time,
195
                        'force_read' => $force_read
196
                        );
197
 
198
            $sql = $db->GetInsertSql($sTable, $rec);
199
 
200
            $result2 = $db->Execute($sql);
201
            showError($db,$sql);
202
        }
203
    }
204
    else
205
    {
206
        // Only Send to one Person
207
        $rec = array(
208
                    'to_user' => $to_user,
209
                    'from_user' => $from_user,
210
                    'message' => $message,
211
                    'IsNew' => 1,
212
                    'ip' => $cfg['ip'],
213
                    'time' => $create_time,
214
                    'force_read' => $force_read
215
                    );
216
        $sql = $db->GetInsertSql($sTable, $rec);
217
        $result = $db->Execute($sql);
218
        showError($db,$sql);
219
    }
220
 
221
}
222
 
223
//*********************************************************
224
function addNewUser($newUser, $pass1, $userType)
225
{
226
    global $cfg, $db;
227
 
228
    $create_time = time();
229
 
230
    $record = array(
231
                    'user_id'=>strtolower($newUser),
232
                    'password'=>md5($pass1),
233
                    'hits'=>0,
234
                    'last_visit'=>$create_time,
235
                    'time_created'=>$create_time,
236
                    'user_level'=>$userType,
237
                    'hide_offline'=>"0",
238
                    'theme'=>$cfg["default_theme"],
239
                    'language_file'=>$cfg["default_language"]
240
                    );
241
 
242
    $sTable = 'tf_users';
243
    $sql = $db->GetInsertSql($sTable, $record);
244
    $result = $db->Execute($sql);
245
    showError($db,$sql);
246
}
247
 
248
//*********************************************************
249
function PruneDB()
250
{
251
    global $cfg, $db;
252
 
253
    // Prune LOG
254
    $testTime = time()-($cfg['days_to_keep'] * 86400); // 86400 is one day in seconds
255
    $sql = "delete from tf_log where time < " . $db->qstr($testTime);
256
    $result = $db->Execute($sql);
257
    showError($db,$sql);
258
    unset($result);
259
 
260
    $testTime = time()-($cfg['minutes_to_keep'] * 60);
261
    $sql = "delete from tf_log where time < " . $db->qstr($testTime). " and action=".$db->qstr($cfg["constants"]["hit"]);
262
    $result = $db->Execute($sql);
263
    showError($db,$sql);
264
    unset($result);
265
}
266
 
267
//*********************************************************
268
function IsOnline($user)
269
{
270
    global $cfg, $db;
271
 
272
    $online = false;
273
 
274
    $sql = "SELECT count(*) FROM tf_log WHERE user_id=" . $db->qstr($user)." AND action=".$db->qstr($cfg["constants"]["hit"]);
275
 
276
    $number_hits = $db->GetOne($sql);
277
    showError($db,$sql);
278
 
279
    if ($number_hits > 0)
280
    {
281
        $online = true;
282
    }
283
 
284
    return $online;
285
}
286
 
287
//*********************************************************
288
function IsUser($user)
289
{
290
    global $cfg, $db;
291
 
292
    $isUser = false;
293
 
294
    $sql = "SELECT count(*) FROM tf_users WHERE user_id=".$db->qstr($user);
295
    $number_users = $db->GetOne($sql);
296
 
297
    if ($number_users > 0)
298
    {
299
        $isUser = true;
300
    }
301
 
302
    return $isUser;
303
}
304
 
305
//*********************************************************
306
function getOwner($file)
307
{
308
    global $cfg, $db;
309
 
310
    $rtnValue = "n/a";
311
 
312
    // Check log to see what user has a history with this file
313
    $sql = "SELECT user_id FROM tf_log WHERE file=".$db->qstr($file)." AND (action=".$db->qstr($cfg["constants"]["file_upload"])." OR action=".$db->qstr($cfg["constants"]["url_upload"])." OR action=".$db->qstr($cfg["constants"]["reset_owner"]).") ORDER  BY time DESC";
314
    $user_id = $db->GetOne($sql);
315
 
316
    if($user_id != "")
317
    {
318
        $rtnValue = $user_id;
319
    }
320
    else
321
    {
322
        // try and get the owner from the stat file
323
        $rtnValue = resetOwner($file);
324
    }
325
 
326
    return $rtnValue;
327
}
328
 
329
//*********************************************************
330
function resetOwner($file)
331
{
332
    global $cfg, $db;
333
    include_once("AliasFile.php");
334
 
335
    // log entry has expired so we must renew it
336
    $rtnValue = "";
337
 
338
    $alias = getAliasName($file).".stat";
339
 
340
    if(file_exists($cfg["torrent_file_path"].$alias))
341
    {
342
        $af = new AliasFile($cfg["torrent_file_path"].$alias);
343
 
344
        if (IsUser($af->torrentowner))
345
        {
346
            // We have an owner!
347
            $rtnValue = $af->torrentowner;
348
        }
349
        else
350
        {
351
            // no owner found, so the super admin will now own it
352
            $rtnValue = GetSuperAdmin();
353
        }
354
 
355
        $host_resolved = gethostbyaddr($cfg['ip']);
356
        $create_time = time();
357
 
358
        $rec = array(
359
                        'user_id' => $rtnValue,
360
                        'file' => $file,
361
                        'action' => $cfg["constants"]["reset_owner"],
362
                        'ip' => $cfg['ip'],
363
                        'ip_resolved' => $host_resolved,
364
                        'user_agent' => $_SERVER['HTTP_USER_AGENT'],
365
                        'time' => $create_time
366
                    );
367
 
368
        $sTable = 'tf_log';
369
        $sql = $db->GetInsertSql($sTable, $rec);
370
 
371
        // add record to the log
372
        $result = $db->Execute($sql);
373
        showError($db,$sql);
374
    }
375
 
376
    return $rtnValue;
377
}
378
 
379
//*********************************************************
380
function getCookie($cid)
381
{
382
    global $cfg, $db;
383
 
384
    $rtnValue = "";
385
 
386
    $sql = "SELECT host, data FROM tf_cookies WHERE cid=".$cid;
387
    $rtnValue = $db->GetAll($sql);
388
 
389
    return $rtnValue[0];
390
}
391
 
392
// ***************************************************************************
393
// Delete Cookie Host Information
394
function deleteCookieInfo($cid)
395
{
396
    global $db;
397
    $sql = "delete from tf_cookies where cid=".$cid;
398
    $result = $db->Execute($sql);
399
    showError($db,$sql);
400
}
401
 
402
// ***************************************************************************
403
// addCookieInfo - Add New Cookie Host Information
404
function addCookieInfo( $newCookie )
405
{
406
    global $db, $cfg;
407
    // Get uid of user
408
    $sql = "SELECT uid FROM tf_users WHERE user_id = '" . $cfg["user"] . "'";
409
    $uid = $db->GetOne( $sql );
410
    $sql = "INSERT INTO tf_cookies ( cid, uid, host, data ) VALUES ( '', '" . $uid . "', '" . $newCookie["host"] . "', '" . $newCookie["data"] . "' )";
411
    $db->Execute( $sql );
412
    showError( $db, $sql );
413
}
414
 
415
// ***************************************************************************
416
// modCookieInfo - Modify Cookie Host Information
417
function modCookieInfo($cid, $newCookie)
418
{
419
    global $db;
420
    $sql = "UPDATE tf_cookies SET host='" . $newCookie["host"] . "', data='" . $newCookie["data"] . "' WHERE cid='" . $cid . "'";
421
    $db->Execute($sql);
422
    showError($db,$sql);
423
}
424
 
425
//*********************************************************
426
function getLink($lid)
427
{
428
    global $cfg, $db;
429
 
430
    $rtnValue = "";
431
 
432
    $sql = "SELECT url FROM tf_links WHERE lid=".$lid;
433
    $rtnValue = $db->GetOne($sql);
434
 
435
    return $rtnValue;
436
}
437
 
438
//*********************************************************
439
function getRSS($rid)
440
{
441
    global $cfg, $db;
442
 
443
    $rtnValue = "";
444
 
445
    $sql = "SELECT url FROM tf_rss WHERE rid=".$rid;
446
    $rtnValue = $db->GetOne($sql);
447
 
448
    return $rtnValue;
449
}
450
 
451
//*********************************************************
452
function IsOwner($user, $owner)
453
{
454
    $rtnValue = false;
455
 
456
    if (strtolower($user) == strtolower($owner))
457
    {
458
        $rtnValue = true;
459
    }
460
 
461
    return $rtnValue;
462
}
463
 
464
//*********************************************************
465
function GetActivityCount($user="")
466
{
467
    global $cfg, $db;
468
 
469
    $count = 0;
470
    $for_user = "";
471
 
472
    if ($user != "")
473
    {
474
        $for_user = "user_id=".$db->qstr($user)." AND ";
475
    }
476
 
477
    $sql = "SELECT count(*) FROM tf_log WHERE ".$for_user."(action=".$db->qstr($cfg["constants"]["file_upload"])." OR action=".$db->qstr($cfg["constants"]["url_upload"]).")";
478
    $count = $db->GetOne($sql);
479
 
480
    return $count;
481
}
482
 
483
//*********************************************************
484
function GetSpeedValue($inValue)
485
{
486
    $rtnValue = 0;
487
    $arTemp = split(" ", trim($inValue));
488
 
489
    if (is_numeric($arTemp[0]))
490
    {
491
        $rtnValue = $arTemp[0];
492
    }
493
    return $rtnValue;
494
}
495
 
496
// ***************************************************************************
497
// Is User Admin
498
// user is Admin if level is 1 or higher
499
function IsAdmin($user="")
500
{
501
    global $cfg, $db;
502
 
503
    $isAdmin = false;
504
 
505
    if($user == "")
506
    {
507
        $user = $cfg["user"];
508
    }
509
 
510
    $sql = "SELECT user_level FROM tf_users WHERE user_id=".$db->qstr($user);
511
    $user_level = $db->GetOne($sql);
512
 
513
    if ($user_level >= 1)
514
    {
515
        $isAdmin = true;
516
    }
517
    return $isAdmin;
518
}
519
 
520
// ***************************************************************************
521
// Is User SUPER Admin
522
// user is Super Admin if level is higher than 1
523
function IsSuperAdmin($user="")
524
{
525
    global $cfg, $db;
526
 
527
    $isAdmin = false;
528
 
529
    if($user == "")
530
    {
531
        $user = $cfg["user"];
532
    }
533
 
534
    $sql = "SELECT user_level FROM tf_users WHERE user_id=".$db->qstr($user);
535
    $user_level = $db->GetOne($sql);
536
 
537
    if ($user_level > 1)
538
    {
539
        $isAdmin = true;
540
    }
541
    return $isAdmin;
542
}
543
 
544
 
545
// ***************************************************************************
546
// Returns true if user has message from admin with force_read
547
function IsForceReadMsg()
548
{
549
    global $cfg, $db;
550
    $rtnValue = false;
551
 
552
    $sql = "SELECT count(*) FROM tf_messages WHERE to_user=".$db->qstr($cfg["user"])." AND force_read=1";
553
    $count = $db->GetOne($sql);
554
    showError($db,$sql);
555
 
556
    if ($count >= 1)
557
    {
558
        $rtnValue = true;
559
    }
560
    return $rtnValue;
561
}
562
 
563
// ***************************************************************************
564
// Get Message data in an array
565
function GetMessage($mid)
566
{
567
    global $cfg, $db;
568
 
569
    $sql = "select from_user, message, ip, time, isnew, force_read from tf_messages where mid=".$mid." and to_user=".$db->qstr($cfg['user']);
570
 
571
    $rtnValue = $db->GetRow($sql);
572
    showError($db,$sql);
573
 
574
    return $rtnValue;
575
}
576
 
577
// ***************************************************************************
578
// Get Themes data in an array
579
function GetThemes()
580
{
581
    $arThemes = array();
582
    $dir = "themes/";
583
 
584
    $handle = opendir($dir);
585
    while($entry = readdir($handle))
586
    {
587
        if (is_dir($dir.$entry) && ($entry != "." && $entry != ".."))
588
        {
589
            array_push($arThemes, $entry);
590
        }
591
    }
592
    closedir($handle);
593
 
594
    sort($arThemes);
595
 
596
    return $arThemes;
597
}
598
 
599
// ***************************************************************************
600
// Get Languages in an array
601
function GetLanguages()
602
{
603
    $arLanguages = array();
604
    $dir = "language/";
605
 
606
    $handle = opendir($dir);
607
    while($entry = readdir($handle))
608
    {
609
        if (is_file($dir.$entry) && (strcmp(strtolower(substr($entry, strlen($entry)-4, 4)), ".php") == 0))
610
        {
611
            array_push($arLanguages, $entry);
612
        }
613
    }
614
    closedir($handle);
615
 
616
    sort($arLanguages);
617
 
618
    return $arLanguages;
619
}
620
 
621
// ***************************************************************************
622
// Get Language name from file name
623
function GetLanguageFromFile($inFile)
624
{
625
    $rtnValue = "";
626
 
627
    $rtnValue = str_replace("lang-", "", $inFile);
628
    $rtnValue = str_replace(".php", "", $rtnValue);
629
 
630
    return $rtnValue;
631
}
632
 
633
// ***************************************************************************
634
// Delete Message
635
function DeleteMessage($mid)
636
{
637
    global $cfg, $db;
638
 
639
    $sql = "delete from tf_messages where mid=".$mid." and to_user=".$db->qstr($cfg['user']);
640
    $result = $db->Execute($sql);
641
    showError($db,$sql);
642
}
643
 
644
 
645
// ***************************************************************************
646
// Delete Link
647
function deleteOldLink($lid)
648
{
649
    global $db;
650
    $sql = "delete from tf_links where lid=".$lid;
651
    $result = $db->Execute($sql);
652
    showError($db,$sql);
653
}
654
 
655
// ***************************************************************************
656
// Delete RSS
657
function deleteOldRSS($rid)
658
{
659
    global $db;
660
    $sql = "delete from tf_rss where rid=".$rid;
661
    $result = $db->Execute($sql);
662
    showError($db,$sql);
663
}
664
 
665
// ***************************************************************************
666
// Delete User
667
function DeleteThisUser($user_id)
668
{
669
    global $db;
670
 
671
    $sql = "SELECT uid FROM tf_users WHERE user_id = ".$db->qstr($user_id);
672
    $uid = $db->GetOne( $sql );
673
    showError($db,$sql);
674
 
675
    // delete any cookies this user may have had
676
    //$sql = "DELETE tf_cookies FROM tf_cookies, tf_users WHERE (tf_users.uid = tf_cookies.uid) AND tf_users.user_id=".$db->qstr($user_id);
677
    $sql = "DELETE FROM tf_cookies WHERE uid=".$uid;
678
    $result = $db->Execute($sql);
679
    showError($db,$sql);
680
 
681
    // Now cleanup any message this person may have had
682
    $sql = "DELETE FROM tf_messages WHERE to_user=".$db->qstr($user_id);
683
    $result = $db->Execute($sql);
684
    showError($db,$sql);
685
 
686
    // now delete the user from the table
687
    $sql = "DELETE FROM tf_users WHERE user_id=".$db->qstr($user_id);
688
    $result = $db->Execute($sql);
689
    showError($db,$sql);
690
}
691
 
692
// ***************************************************************************
693
// Update User -- used by admin
694
function updateThisUser($user_id, $org_user_id, $pass1, $userType, $hideOffline)
695
{
696
    global $db;
697
 
698
    if ($hideOffline == "")
699
    {
700
        $hideOffline = 0;
701
    }
702
 
703
    $sql = 'select * from tf_users where user_id = '.$db->qstr($org_user_id);
704
    $rs = $db->Execute($sql);
705
    showError($db,$sql);
706
 
707
    $rec = array();
708
    $rec['user_id'] = $user_id;
709
    $rec['user_level'] = $userType;
710
    $rec['hide_offline'] = $hideOffline;
711
 
712
    if ($pass1 != "")
713
    {
714
        $rec['password'] = md5($pass1);
715
    }
716
 
717
    $sql = $db->GetUpdateSQL($rs, $rec);
718
 
719
    if ($sql != "")
720
    {
721
        $result = $db->Execute($sql);
722
        showError($db,$sql);
723
    }
724
 
725
    // if the original user id and the new id do not match, we need to update messages and log
726
    if ($user_id != $org_user_id)
727
    {
728
        $sql = "UPDATE tf_messages SET to_user=".$db->qstr($user_id)." WHERE to_user=".$db->qstr($org_user_id);
729
 
730
        $result = $db->Execute($sql);
731
        showError($db,$sql);
732
 
733
        $sql = "UPDATE tf_messages SET from_user=".$db->qstr($user_id)." WHERE from_user=".$db->qstr($org_user_id);
734
        $result = $db->Execute($sql);
735
        showError($db,$sql);
736
 
737
        $sql = "UPDATE tf_log SET user_id=".$db->qstr($user_id)." WHERE user_id=".$db->qstr($org_user_id);
738
        $result = $db->Execute($sql);
739
        showError($db,$sql);
740
    }
741
}
742
 
743
// ***************************************************************************
744
// changeUserLevel Changes the Users Level
745
function changeUserLevel($user_id, $level)
746
{
747
    global $db;
748
 
749
    $sql='select * from tf_users where user_id = '.$db->qstr($user_id);
750
    $rs = $db->Execute($sql);
751
    showError($db,$sql);
752
 
753
    $rec = array('user_level'=>$level);
754
    $sql = $db->GetUpdateSQL($rs, $rec);
755
    $result = $db->Execute($sql);
756
    showError($db,$sql);
757
}
758
 
759
// ***************************************************************************
760
// Mark Message as Read
761
function MarkMessageRead($mid)
762
{
763
    global $cfg, $db;
764
 
765
    $sql = 'select * from tf_messages where mid = '.$mid;
766
    $rs = $db->Execute($sql);
767
    showError($db,$sql);
768
 
769
    $rec = array('IsNew'=>0,
770
             'force_read'=>0);
771
 
772
    $sql = $db->GetUpdateSQL($rs, $rec);
773
    $db->Execute($sql);
774
    showError($db,$sql);
775
}
776
 
777
 
778
// ***************************************************************************
779
// addNewLink - Add New Link
780
function addNewLink($newLink)
781
{
782
    global $db;
783
    $rec = array('url'=>$newLink);
784
    $sTable = 'tf_links';
785
    $sql = $db->GetInsertSql($sTable, $rec);
786
    $db->Execute($sql);
787
    showError($db,$sql);
788
}
789
 
790
 
791
// ***************************************************************************
792
// addNewRSS - Add New RSS Link
793
function addNewRSS($newRSS)
794
{
795
    global $db;
796
    $rec = array('url'=>$newRSS);
797
    $sTable = 'tf_rss';
798
    $sql = $db->GetInsertSql($sTable, $rec);
799
    $db->Execute($sql);
800
    showError($db,$sql);
801
}
802
 
803
// ***************************************************************************
804
// UpdateUserProfile
805
function UpdateUserProfile($user_id, $pass1, $hideOffline, $theme, $language)
806
{
807
    global $cfg, $db;
808
 
809
    if (empty($hideOffline) || $hideOffline == "" || !isset($hideOffline))
810
    {
811
        $hideOffline = "0";
812
    }
813
 
814
    // update values
815
    $rec = array();
816
 
817
    if ($pass1 != "")
818
    {
819
        $rec['password'] = md5($pass1);
820
        AuditAction($cfg["constants"]["update"], _PASSWORD);
821
    }
822
 
823
    $sql = 'select * from tf_users where user_id = '.$db->qstr($user_id);
824
    $rs = $db->Execute($sql);
825
    showError($db,$sql);
826
 
827
    $rec['hide_offline'] = $hideOffline;
828
    $rec['theme'] = $theme;
829
    $rec['language_file'] = $language;
830
 
831
    $sql = $db->GetUpdateSQL($rs, $rec);
832
 
833
    $result = $db->Execute($sql);
834
    showError($db,$sql);
835
}
836
 
837
 
838
// ***************************************************************************
839
// Get Users in an array
840
function GetUsers()
841
{
842
    global $cfg, $db;
843
 
844
    $user_array = array();
845
 
846
    $sql = "select user_id from tf_users order by user_id";
847
    $user_array = $db->GetCol($sql);
848
    showError($db,$sql);
849
    return $user_array;
850
}
851
 
852
// ***************************************************************************
853
// Get Super Admin User ID as a String
854
function GetSuperAdmin()
855
{
856
    global $cfg, $db;
857
 
858
    $rtnValue = "";
859
 
860
    $sql = "select user_id from tf_users WHERE user_level=2";
861
    $rtnValue = $db->GetOne($sql);
862
    showError($db,$sql);
863
    return $rtnValue;
864
}
865
 
866
// ***************************************************************************
867
// Get Links in an array
868
function GetLinks()
869
{
870
    global $cfg, $db;
871
 
872
    $link_array = array();
873
 
874
    $link_array = $db->GetAssoc("SELECT lid, url FROM tf_links ORDER BY lid");
875
    return $link_array;
876
}
877
 
878
// ***************************************************************************
879
// Get RSS Links in an array
880
function GetRSSLinks()
881
{
882
    global $cfg, $db;
883
 
884
    $link_array = array();
885
 
886
    $sql = "SELECT rid, url FROM tf_rss ORDER BY rid";
887
    $link_array = $db->GetAssoc($sql);
888
    showError($db,$sql);
889
 
890
    return $link_array;
891
}
892
 
893
// ***************************************************************************
894
// Build Search Engine Drop Down List
895
function buildSearchEngineDDL($selectedEngine = 'TorrentSpy', $autoSubmit = false)
896
{
897
    $output = "<select name=\"searchEngine\" ";
898
    if ($autoSubmit)
899
    {
900
         $output .= "onchange=\"this.form.submit();\" ";
901
    }
902
    $output .= " STYLE=\"width: 125px\">";
903
 
904
    $handle = opendir("./searchEngines");
905
    while($entry = readdir($handle))
906
    {
907
        $entrys[] = $entry;
908
    }
909
    natcasesort($entrys);
910
 
911
    foreach($entrys as $entry)
912
    {
913
        if ($entry != "." && $entry != ".." && substr($entry, 0, 1) != ".")
914
            if(strpos($entry,"Engine.php"))
915
            {
916
                $tmpEngine = str_replace("Engine",'',substr($entry,0,strpos($entry,".")));
917
                $output .= "<option";
918
                if ($selectedEngine == $tmpEngine)
919
                {
920
                    $output .= " selected";
921
                }
922
                $output .= ">".str_replace("Engine",'',substr($entry,0,strpos($entry,".")))."</option>";
923
            }
924
    }
925
    $output .= "</select>\n";
926
 
927
    return $output;
928
}
929
 
930
// ***************************************************************************
931
// Build Search Engine Links
932
function buildSearchEngineLinks($selectedEngine = 'TorrentSpy')
933
{
934
    global $cfg;
935
 
936
    $settingsNeedsSaving = false;
937
    $settings['searchEngineLinks'] = Array();
938
 
939
    $output = '';
940
 
941
    if( (!array_key_exists('searchEngineLinks', $cfg)) || (!is_array($cfg['searchEngineLinks'])))
942
    {
943
        saveSettings($settings);
944
    }
945
 
946
    $handle = opendir("./searchEngines");
947
    while($entry = readdir($handle))
948
    {
949
        $entrys[] = $entry;
950
    }
951
    natcasesort($entrys);
952
 
953
    foreach($entrys as $entry)
954
    {
955
        if ($entry != "." && $entry != ".." && substr($entry, 0, 1) != ".")
956
            if(strpos($entry,"Engine.php"))
957
            {
958
                $tmpEngine = str_replace("Engine",'',substr($entry,0,strpos($entry,".")));
959
 
960
                if(array_key_exists($tmpEngine,$cfg['searchEngineLinks']))
961
                {
962
                    $hreflink = $cfg['searchEngineLinks'][$tmpEngine];
963
                    $settings['searchEngineLinks'][$tmpEngine] = $hreflink;
964
                }
965
                else
966
                {
967
                    $hreflink = getEngineLink($tmpEngine);
968
                    $settings['searchEngineLinks'][$tmpEngine] = $hreflink;
969
                    $settingsNeedsSaving = true;
970
                }
971
 
972
                if (strlen($hreflink) > 0)
973
                {
974
                    $output .=  "<a href=\"http://".$hreflink."/\" target=\"_blank\">";
975
                    if ($selectedEngine == $tmpEngine)
976
                    {
977
                        $output .= "<b>".$hreflink."</b>";
978
                    }
979
                    else
980
                    {
981
                        $output .= $hreflink;
982
                    }
983
                    $output .= "</a><br>\n";
984
                }
985
            }
986
    }
987
 
988
    if ( count($settings['searchEngineLinks'],COUNT_RECURSIVE) <> count($cfg['searchEngineLinks'],COUNT_RECURSIVE))
989
    {
990
        $settingsNeedsSaving = true;
991
    }
992
 
993
    if ($settingsNeedsSaving)
994
    {
995
        natcasesort($settings['searchEngineLinks']);
996
 
997
        saveSettings($settings);
998
    }
999
 
1000
    return $output;
1001
}
1002
function getEngineLink($searchEngine)
1003
{
1004
    $tmpLink = '';
1005
    $engineFile = 'searchEngines/'.$searchEngine.'Engine.php';
1006
    if (is_file($engineFile))
1007
    {
1008
        $fp = @fopen($engineFile,'r');
1009
        if ($fp)
1010
        {
1011
            $tmp = fread($fp, filesize($engineFile));
1012
            @fclose( $fp );
1013
 
1014
            $tmp = substr($tmp,strpos($tmp,'$this->mainURL'),100);
1015
            $tmp = substr($tmp,strpos($tmp,"=")+1);
1016
            $tmp = substr($tmp,0,strpos($tmp,";"));
1017
            $tmpLink = trim(str_replace(array("'","\""),"",$tmp));
1018
        }
1019
    }
1020
    return $tmpLink;
1021
}
1022
 
1023
// ***************************************************************************
1024
// ***************************************************************************
1025
// Display Functions
1026
 
1027
 
1028
// ***************************************************************************
1029
// ***************************************************************************
1030
// Display the header portion of admin views
1031
function DisplayHead($subTopic, $showButtons=true, $refresh="", $percentdone="")
1032
{
1033
    global $cfg;
1034
    ?>
1035
 
1036
    <html>
1037
    <HEAD>
1038
        <TITLE><?php echo $percentdone.$cfg["pagetitle"] ?></TITLE>
1039
        <link rel="icon" href="images/favicon.ico" type="image/x-icon" />
1040
        <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
1041
        <LINK REL="StyleSheet" HREF="themes/<?php echo $cfg["theme"] ?>/style.css" TYPE="text/css">
1042
        <META HTTP-EQUIV="Pragma" CONTENT="no-cache; charset=<?php echo _CHARSET ?>">
1043
 
1044
    <?php
1045
    if ($refresh != "")
1046
    {
1047
        echo "<meta http-equiv=\"REFRESH\" content=\"".$refresh."\">";
1048
    }
1049
    ?>
1050
    </HEAD>
1051
 
1052
    <body topmargin="8" leftmargin="5" bgcolor="<?php echo $cfg["main_bgcolor"] ?>">
1053
 
1054
    <div align="center">
1055
    <table border="0" cellpadding="0" cellspacing="0">
1056
    <tr>
1057
        <td>
1058
 
1059
    <table border="1" bordercolor="<?php echo $cfg["table_border_dk"] ?>" cellpadding="4" cellspacing="0">
1060
    <tr>
1061
        <td bgcolor="<?php echo $cfg["main_bgcolor"] ?>" background="themes/<?php echo $cfg["theme"] ?>/images/bar.gif">
1062
        <?php DisplayTitleBar($cfg["pagetitle"]." - ".$subTopic, $showButtons); ?>
1063
        </td>
1064
    </tr>
1065
    <tr>
1066
    <td bgcolor="<?php echo $cfg["table_header_bg"] ?>">
1067
    <div align="center">
1068
 
1069
    <table width="100%" bgcolor="<?php echo $cfg["body_data_bg"] ?>">
1070
     <tr><td>
1071
<?php
1072
}
1073
 
1074
 
1075
// ***************************************************************************
1076
// ***************************************************************************
1077
// Display the footer portion
1078
function DisplayFoot($showReturn=true)
1079
{
1080
    global $cfg;
1081
    ?>
1082
     </td></tr>
1083
    </table>
1084
<?php
1085
    if ($showReturn)
1086
    {
1087
        echo "[<a href=\"index.php\">"._RETURNTOTORRENTS."</a>]";
1088
    }
1089
?>
1090
    </div>
1091
    </td>
1092
    </tr>
1093
    </table>
1094
<?php
1095
    echo DisplayTorrentFluxLink();
1096
?>
1097
 
1098
        </td>
1099
    </tr>
1100
    </table>
1101
    </div>
1102
 
1103
   </body>
1104
  </html>
1105
 
1106
    <?php
1107
}
1108
 
1109
 
1110
// ***************************************************************************
1111
// ***************************************************************************
1112
// Dipslay TF Link and Version
1113
function DisplayTorrentFluxLink()
1114
{
1115
    global $cfg;
1116
 
1117
    echo "<div align=\"right\">";
1118
    echo "<a href=\"http://www.torrentflux.com\" target=\"_blank\"><font class=\"tinywhite\">TorrentFlux ".$cfg["version"]."</font></a>&nbsp;&nbsp;";
1119
    echo "</div>";
1120
}
1121
 
1122
 
1123
// ***************************************************************************
1124
// ***************************************************************************
1125
// Dipslay Title Bar
1126
// 2004-12-09 PFM: now using adodb.
1127
function DisplayTitleBar($pageTitleText, $showButtons=true)
1128
{
1129
    global $cfg, $db;
1130
    ?>
1131
        <table width="100%" cellpadding="0" cellspacing="0" border="0">
1132
        <tr>
1133
            <td align="left"><font class="title"><?php echo $pageTitleText ?></font></td>
1134
 
1135
    <?php
1136
    if ($showButtons)
1137
    {
1138
        echo "<td align=right>";
1139
        // Top Buttons
1140
        echo "&nbsp;&nbsp;";
1141
 
1142
        echo "<a href=\"index.php\"><img src=\"themes/".$cfg["theme"]."/images/home.gif\" width=49 height=13 title=\""._TORRENTS."\" border=0></a>&nbsp;";
1143
        echo "<a href=\"dir.php\"><img src=\"themes/".$cfg["theme"]."/images/directory.gif\" width=49 height=13 title=\""._DIRECTORYLIST."\" border=0></a>&nbsp;";
1144
        echo "<a href=\"history.php\"><img src=\"themes/".$cfg["theme"]."/images/history.gif\" width=49 height=13 title=\""._UPLOADHISTORY."\" border=0></a>&nbsp;";
1145
        echo "<a href=\"profile.php\"><img src=\"themes/".$cfg["theme"]."/images/profile.gif\" width=49 height=13 title=\""._MYPROFILE."\" border=0></a>&nbsp;";
1146
 
1147
        // Does the user have messages?
1148
        $sql = "select count(*) from tf_messages where to_user='".$cfg['user']."' and IsNew=1";
1149
 
1150
        $number_messages = $db->GetOne($sql);
1151
        showError($db,$sql);
1152
        if ($number_messages > 0)
1153
        {
1154
            // We have messages
1155
            $message_image = "themes/".$cfg["theme"]."/images/messages_on.gif";
1156
        }
1157
        else
1158
        {
1159
            // No messages
1160
            $message_image = "themes/".$cfg["theme"]."/images/messages_off.gif";
1161
        }
1162
 
1163
        echo "<a href=\"readmsg.php\"><img src=\"".$message_image."\" width=49 height=13 title=\""._MESSAGES."\" border=0></a>";
1164
 
1165
        if(IsAdmin())
1166
        {
1167
            echo "&nbsp;<a href=\"admin.php\"><img src=\"themes/".$cfg["theme"]."/images/admin.gif\" width=49 height=13 title=\""._ADMINISTRATION."\" border=0></a>";
1168
        }
1169
 
1170
        echo "&nbsp;<a href=\"logout.php\"><img src=\"images/logout.gif\" width=13 height=12 title=\"Logout\" border=0></a>";
1171
    }
1172
?>
1173
            </td>
1174
        </tr>
1175
        </table>
1176
<?php
1177
}
1178
 
1179
 
1180
// ***************************************************************************
1181
// ***************************************************************************
1182
// Dipslay dropdown list to send message to a user
1183
function DisplayMessageList()
1184
{
1185
    global $cfg;
1186
    $users = GetUsers();
1187
 
1188
    echo '<div align="center">'.
1189
    '<table border="0" cellpadding="0" cellspacing="0">'.
1190
    '<form name="formMessage" action="message.php" method="post">'.
1191
    '<tr><td>' . _SENDMESSAGETO ;
1192
 
1193
    echo '<select name="to_user">';
1194
        for($inx = 0; $inx < sizeof($users); $inx++)
1195
        {
1196
        echo '<option>'.$users[$inx].'</option>';
1197
        }
1198
    echo '</select>';
1199
    echo '<input type="Submit" value="' . _COMPOSE .'">';
1200
    echo '</td></tr></form></table></div>';
1201
}
1202
 
1203
// ***************************************************************************
1204
// ***************************************************************************
1205
// Removes HTML from Messages
1206
function check_html ($str, $strip="")
1207
{
1208
    /* The core of this code has been lifted from phpslash */
1209
    /* which is licenced under the GPL. */
1210
    if ($strip == "nohtml")
1211
    {
1212
        $AllowableHTML=array('');
1213
    }
1214
    $str = stripslashes($str);
1215
    $str = eregi_replace("<[[:space:]]*([^>]*)[[:space:]]*>",'<\\1>', $str);
1216
            // Delete all spaces from html tags .
1217
    $str = eregi_replace("<a[^>]*href[[:space:]]*=[[:space:]]*\"?[[:space:]]*([^\" >]*)[[:space:]]*\"?[^>]*>",'<a href="\\1">', $str);
1218
            // Delete all attribs from Anchor, except an href, double quoted.
1219
    $str = eregi_replace("<[[:space:]]* img[[:space:]]*([^>]*)[[:space:]]*>", '', $str);
1220
        // Delete all img tags
1221
    $str = eregi_replace("<a[^>]*href[[:space:]]*=[[:space:]]*\"?javascript[[:punct:]]*\"?[^>]*>", '', $str);
1222
        // Delete javascript code from a href tags -- Zhen-Xjell @ http://nukecops.com
1223
    $tmp = "";
1224
 
1225
    while (ereg("<(/?[[:alpha:]]*)[[:space:]]*([^>]*)>",$str,$reg))
1226
    {
1227
        $i = strpos($str,$reg[0]);
1228
        $l = strlen($reg[0]);
1229
        if ($reg[1][0] == "/")
1230
        {
1231
            $tag = strtolower(substr($reg[1],1));
1232
        }
1233
        else
1234
        {
1235
            $tag = strtolower($reg[1]);
1236
        }
1237
        if ($a = $AllowableHTML[$tag])
1238
        {
1239
            if ($reg[1][0] == "/")
1240
            {
1241
                $tag = "</$tag>";
1242
            }
1243
            elseif (($a == 1) || ($reg[2] == ""))
1244
            {
1245
                $tag = "<$tag>";
1246
            }
1247
            else
1248
            {
1249
              # Place here the double quote fix function.
1250
              $attrb_list=delQuotes($reg[2]);
1251
              // A VER
1252
              $attrb_list = ereg_replace("&","&amp;",$attrb_list);
1253
              $tag = "<$tag" . $attrb_list . ">";
1254
            } # Attribs in tag allowed
1255
        }
1256
        else
1257
        {
1258
            $tag = "";
1259
        }
1260
        $tmp .= substr($str,0,$i) . $tag;
1261
        $str = substr($str,$i+$l);
1262
    }
1263
    $str = $tmp . $str;
1264
    return $str;
1265
}
1266
 
1267
 
1268
// ***************************************************************************
1269
// ***************************************************************************
1270
// Checks for the location of the torrents
1271
// If it does not exist, then it creates it.
1272
function checkTorrentPath()
1273
{
1274
    global $cfg;
1275
    // is there a stat and torrent dir?
1276
    if (!@is_dir($cfg["torrent_file_path"]) && is_writable($cfg["path"]))
1277
    {
1278
        //Then create it
1279
        @mkdir($cfg["torrent_file_path"], 0777);
1280
    }
1281
}
1282
 
1283
// ***************************************************************************
1284
// ***************************************************************************
1285
// Returns the drive space used as a percentage i.e 85 or 95
1286
function getDriveSpace($drive)
1287
{
1288
    $percent = 0;
1289
 
1290
    if (is_dir($drive))
1291
    {
1292
        $dt = disk_total_space($drive);
1293
        $df = disk_free_space($drive);
1294
 
1295
        $percent = round((($dt - $df)/$dt) * 100);
1296
    }
1297
    return $percent;
1298
}
1299
 
1300
// ***************************************************************************
1301
// ***************************************************************************
1302
// Display the Drive Space Graphical Bar
1303
function displayDriveSpaceBar($drivespace)
1304
{
1305
    global $cfg;
1306
    $freeSpace = "";
1307
 
1308
    if ($drivespace > 20)
1309
    {
1310
        $freeSpace = " (".formatFreeSpace($cfg["free_space"])." Free)";
1311
    }
1312
?>
1313
    <table width="100%" border="0" cellpadding="0" cellspacing="0">
1314
    <tr nowrap>
1315
        <td width="2%"><div class="tiny"><?php echo _STORAGE ?>:</div></td>
1316
        <td width="80%">
1317
            <table width="100%" border="0" cellpadding="0" cellspacing="0">
1318
            <tr>
1319
                <td background="themes/<?php echo $cfg["theme"] ?>/images/proglass.gif" width="<?php echo $drivespace ?>%"><div class="tinypercent" align="center"><?php echo $drivespace."%".$freeSpace ?></div></td>
1320
                <td background="themes/<?php echo $cfg["theme"] ?>/images/noglass.gif" width="<?php echo (100 - $drivespace) ?>%"><img src="images/blank.gif" width="1" height="3" border="0"></td>
1321
            </tr>
1322
            </table>
1323
        </td>
1324
    </tr>
1325
    </table>
1326
<?php
1327
}
1328
 
1329
// ***************************************************************************
1330
// ***************************************************************************
1331
// Convert free space to GB or MB depending on size
1332
function formatFreeSpace($freeSpace)
1333
{
1334
    $rtnValue = "";
1335
    if ($freeSpace > 1024)
1336
    {
1337
        $rtnValue = number_format($freeSpace/1024, 2)." GB";
1338
    }
1339
    else
1340
    {
1341
        $rtnValue = number_format($freeSpace, 2)." MB";
1342
    }
1343
 
1344
    return $rtnValue;
1345
}
1346
 
1347
//**************************************************************************
1348
// getFileFilter()
1349
// Returns a string used as a file filter.
1350
// Takes in an array of file types.
1351
function getFileFilter($inArray)
1352
{
1353
    $filter = "(\.".strtolower($inArray[0]).")|"; // used to hold the file type filter
1354
    $filter .= "(\.".strtoupper($inArray[0]).")";
1355
    // Build the file filter
1356
    for($inx = 1; $inx < sizeof($inArray); $inx++)
1357
    {
1358
        $filter .= "|(\.".strtolower($inArray[$inx]).")";
1359
        $filter .= "|(\.".strtoupper($inArray[$inx]).")";
1360
    }
1361
    $filter .= "$";
1362
    return $filter;
1363
}
1364
 
1365
 
1366
//**************************************************************************
1367
// getAliasName()
1368
// Create Alias name for Text file and Screen Alias
1369
function getAliasName($inName)
1370
{
1371
    $replaceItems = array(" ", ".", "-", "[", "]", "(", ")", "#", "&", "@");
1372
    $alias = str_replace($replaceItems, "_", $inName);
1373
    $alias = strtolower($alias);
1374
    $alias = str_replace("_torrent", "", $alias);
1375
 
1376
    return $alias;
1377
}
1378
 
1379
 
1380
//**************************************************************************
1381
// cleanFileName()
1382
// Remove bad characters that cause problems
1383
function cleanFileName($inName)
1384
{
1385
    $replaceItems = array("?", "&", "'", "\"", "+", "@");
1386
    $cleanName = str_replace($replaceItems, "", $inName);
1387
    $cleanName = ltrim($cleanName, "-");
1388
    $cleanName = preg_replace("/[^0-9a-z.]+/i",'_', $cleanName);
1389
    return $cleanName;
1390
}
1391
 
1392
//**************************************************************************
1393
// usingTornado()
1394
// returns true if client is tornado
1395
function usingTornado()
1396
{
1397
    global $cfg;
1398
    $rtnValue = false;
1399
    if (preg_match("/btphptornado/i", $cfg["btphpbin"]))
1400
    {
1401
        $rtnValue = true;
1402
    }
1403
 
1404
    return $rtnValue;
1405
}
1406
 
1407
//**************************************************************************
1408
// cleanURL()
1409
// split on the "*" coming from Varchar URL
1410
function cleanURL($url)
1411
{
1412
    $rtnValue = $url;
1413
    $arURL = explode("*", $url);
1414
 
1415
    if (sizeof($arURL) > 1)
1416
    {
1417
        $rtnValue = $arURL[1];
1418
    }
1419
 
1420
    return $rtnValue;
1421
}
1422
 
1423
// -------------------------------------------------------------------
1424
// FetchTorrent() method to get data from URL
1425
// Has support for specific sites
1426
// -------------------------------------------------------------------
1427
function FetchTorrent($url)
1428
{
1429
    global $cfg, $db;
1430
    ini_set("allow_url_fopen", "1");
1431
    ini_set("user_agent", $_SERVER["HTTP_USER_AGENT"]);
1432
 
1433
    $domain  = parse_url( $url );
1434
 
1435
    if( strtolower( substr( $domain["path"], -8 ) ) != ".torrent" )
1436
    {
1437
        // Check know domain types
1438
        if( strpos( strtolower ( $domain["host"] ), "mininova" ) !== false )
1439
        {
1440
            // Sample (http://www.mininova.org/rss.xml):
1441
            // http://www.mininova.org/tor/2254847
1442
            // <a href="/get/2281554">FreeLinux.ISO.iso.torrent</a>
1443
 
1444
            // If received a /tor/ get the required information
1445
            if( strpos( $url, "/tor/" ) !== false )
1446
            {
1447
                // Get the contents of the /tor/ to find the real torrent name
1448
                $html = FetchHTML( $url );
1449
 
1450
                // Check for the tag used on mininova.org
1451
                if( preg_match( "/<a href=\"\/get\/[0-9].[^\"]+\">(.[^<]+)<\/a>/i", $html, $html_preg_match ) )
1452
                {
1453
                    // This is the real torrent filename
1454
                    $cfg["save_torrent_name"] = $html_preg_match[1];
1455
                }
1456
 
1457
                // Change to GET torrent url
1458
                $url = str_replace( "/tor/", "/get/", $url );
1459
            }
1460
 
1461
            // Now fetch the torrent file
1462
            $html = FetchHTML( $url );
1463
 
1464
            // This usually gets triggered if the original URL was /get/ instead of /tor/
1465
            if( strlen( $cfg["save_torrent_name"] ) == 0 )
1466
            {
1467
                // Get the name of the torrent, and make it the filename
1468
                if( preg_match( "/name([0-9][^:]):(.[^:]+)/i", $html, $html_preg_match ) )
1469
                {
1470
                    $filelength = $html_preg_match[1];
1471
                    $filename = $html_preg_match[2];
1472
                    $cfg["save_torrent_name"] = substr( $filename, 0, $filelength ) . ".torrent";
1473
                }
1474
            }
1475
 
1476
            // Make sure we have a torrent file
1477
            if( strpos( $html, "d8:" ) === false )
1478
            {
1479
                // We don't have a Torrent File... it is something else
1480
                AuditAction( $cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html );
1481
                $html = "";
1482
            }
1483
 
1484
            return $html;
1485
        }
1486
        elseif( strpos( strtolower ( $domain["host"] ), "isohunt" ) !== false )
1487
        {
1488
            // Sample (http://isohunt.com/js/rss.php):
1489
            // http://isohunt.com/download.php?mode=bt&id=8837938
1490
            // http://isohunt.com/btDetails.php?ihq=&id=8464972
1491
            $referer = "http://" . $domain["host"] . "/btDetails.php?id=";
1492
 
1493
            // If the url points to the details page, change it to the download url
1494
            if( strpos( strtolower( $url ), "/btdetails.php?" ) !== false )
1495
            {
1496
                $url = str_replace( "/btDetails.php?", "/download.php?", $url ) . "&mode=bt"; // Need to make it grab the torrent
1497
            }
1498
 
1499
            // Grab contents of details page
1500
            $html = FetchHTML( $url, $referer );
1501
 
1502
            // Get the name of the torrent, and make it the filename
1503
            if( preg_match( "/name([0-9][^:]):(.[^:]+)/i", $html, $html_preg_match ) )
1504
            {
1505
                $filelength = $html_preg_match[1];
1506
                $filename = $html_preg_match[2];
1507
                $cfg["save_torrent_name"] = substr( $filename, 0, $filelength ) . ".torrent";
1508
            }
1509
 
1510
            // Make sure we have a torrent file
1511
            if( strpos( $html, "d8:" ) === false )
1512
            {
1513
                // We don't have a Torrent File... it is something else
1514
                AuditAction( $cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html );
1515
                $html = "";
1516
            }
1517
 
1518
            return $html;
1519
        }
1520
        elseif( strpos( strtolower( $url ), "details.php?" ) !== false )
1521
        {
1522
            // Sample (http://www.bitmetv.org/rss.php?passkey=123456):
1523
            // http://www.bitmetv.org/details.php?id=18435&hit=1
1524
            $referer = "http://" . $domain["host"] . "/details.php?id=";
1525
 
1526
            $html = FetchHTML( $url, $referer );
1527
 
1528
            // Sample (http://www.bitmetv.org/details.php?id=18435)
1529
            // download.php/18435/SpiderMan%20Season%204.torrent
1530
            if( preg_match( "/(download.php.[^\"]+)/i", $html, $html_preg_match ) )
1531
            {
1532
                $torrent = str_replace( " ", "%20", substr( $html_preg_match[0], 0, -1 ) );
1533
                $url2 = "http://" . $domain["host"] . "/" . $torrent;
1534
                $html2 = FetchHTML( $url2 );
1535
 
1536
                // Make sure we have a torrent file
1537
                if (strpos($html2, "d8:") === false)
1538
                {
1539
                    // We don't have a Torrent File... it is something else
1540
                    AuditAction($cfg["constants"]["error"], "BAD TORRENT for: ".$url."\n".$html2);
1541
                    $html2 = "";
1542
                }
1543
                return $html2;
1544
            }
1545
            else
1546
            {
1547
                return "";
1548
            }
1549
        }
1550
        elseif( strpos( strtolower( $url ), "download.asp?" ) !== false )
1551
        {
1552
            // Sample (TF's TorrenySpy Search):
1553
            // http://www.torrentspy.com/download.asp?id=519793
1554
            $referer = "http://" . $domain["host"] . "/download.asp?id=";
1555
 
1556
            $html = FetchHTML( $url, $referer );
1557
 
1558
            // Get the name of the torrent, and make it the filename
1559
            if( preg_match( "/name([0-9][^:]):(.[^:]+)/i", $html, $html_preg_match ) )
1560
            {
1561
                $filelength = $html_preg_match[1];
1562
                $filename = $html_preg_match[2];
1563
                $cfg["save_torrent_name"] = substr( $filename, 0, $filelength ) . ".torrent";
1564
            }
1565
 
1566
            if( !empty( $html ) )
1567
            {
1568
                // Make sure we have a torrent file
1569
                if( strpos( $html, "d8:" ) === false )
1570
                {
1571
                    // We don't have a Torrent File... it is something else
1572
                    AuditAction( $cfg["constants"]["error"], "BAD TORRENT for: " . $url . "\n" . $html );
1573
                    $html = "";
1574
                }
1575
                return $html;
1576
            }
1577
            else
1578
            {
1579
                return "";
1580
            }
1581
        }
1582
    }
1583
 
1584
    $html = FetchHTML( $url );
1585
    // Make sure we have a torrent file
1586
    if( strpos( $html, "d8:" ) === false )
1587
    {
1588
        // We don't have a Torrent File... it is something else
1589
        AuditAction( $cfg["constants"]["error"], "BAD TORRENT for: " . $url.  "\n" . $html );
1590
        $html = "";
1591
    }
1592
    else
1593
    {
1594
        // Get the name of the torrent, and make it the filename
1595
        if( preg_match( "/name([0-9][^:]):(.[^:]+)/i", $html, $html_preg_match ) )
1596
        {
1597
            $filelength = $html_preg_match[1];
1598
            $filename = $html_preg_match[2];
1599
            $cfg["save_torrent_name"] = substr( $filename, 0, $filelength ) . ".torrent";
1600
        }
1601
    }
1602
 
1603
    return $html;
1604
}
1605
 
1606
// -------------------------------------------------------------------
1607
// FetchHTML() method to get data from URL -- uses timeout and user agent
1608
// -------------------------------------------------------------------
1609
function FetchHTML( $url, $referer = "" )
1610
{
1611
    global $cfg, $db;
1612
    ini_set("allow_url_fopen", "1");
1613
    ini_set("user_agent", $_SERVER["HTTP_USER_AGENT"]);
1614
 
1615
    //$url = cleanURL( $url );
1616
    $domain = parse_url( $url );
1617
    $getcmd  = $domain["path"];
1618
 
1619
    if(!array_key_exists("query", $domain))
1620
    {
1621
        $domain["query"] = "";
1622
    }
1623
 
1624
    $getcmd .= ( !empty( $domain["query"] ) ) ? "?" . $domain["query"] : "";
1625
 
1626
    $cookie = "";
1627
    $rtnValue = "";
1628
 
1629
    // If the url already doesn't contain a passkey, then check
1630
    // to see if it has cookies set to the domain name.
1631
    if( ( strpos( $domain["query"], "passkey=" ) ) === false )
1632
    {
1633
        $sql = "SELECT c.data FROM tf_cookies AS c LEFT JOIN tf_users AS u ON ( u.uid = c.uid ) WHERE u.user_id = '" . $cfg["user"] . "' AND c.host = '" . $domain['host'] . "'";
1634
        $cookie = $db->GetOne( $sql );
1635
        showError( $db, $sql );
1636
    }
1637
 
1638
    if( !array_key_exists("port", $domain) )
1639
    {
1640
        $domain["port"] = 80;
1641
    }
1642
 
1643
    // Check to see if this site requires the use of cookies
1644
    if( !empty( $cookie ) )
1645
    {
1646
        $socket = @fsockopen( $domain["host"], $domain["port"], $errno, $errstr, 30 ); //connect to server
1647
 
1648
        if( !empty( $socket ) )
1649
        {
1650
            // Write the outgoing header packet
1651
            // Using required cookie information
1652
            $packet  = "GET " . $url . "\r\n";
1653
            $packet .= ( !empty( $referer ) ) ? "Referer: " . $referer . "\r\n" : "";
1654
            $packet .= "Accept: */*\r\n";
1655
            $packet .= "Accept-Language: en-us\r\n";
1656
            $packet .= "User-Agent: ".$_SERVER["HTTP_USER_AGENT"]."\r\n";
1657
            $packet .= "Host: " . $_SERVER["SERVER_NAME"] . "\r\n";
1658
            $packet .= "Connection: Close\r\n";
1659
            $packet .= "Cookie: " . $cookie . "\r\n\r\n";
1660
 
1661
            // Send header packet information to server
1662
            @fputs( $socket, $packet );
1663
 
1664
            // Initialize variable, make sure null until we add too it.
1665
            $rtnValue = null;
1666
 
1667
            // If http 1.0 just take it all as 1 chunk (Much easier, but for old servers)
1668
            while( !@feof( $socket ) )
1669
            {
1670
                $rtnValue .= @fgets( $socket, 500000 );
1671
            }
1672
 
1673
            @fclose( $socket ); // Close our connection
1674
        }
1675
    }
1676
    else
1677
    {
1678
        if( $fp = @fopen( $url, 'r' ) )
1679
        {
1680
            $rtnValue = "";
1681
            while( !@feof( $fp ) )
1682
            {
1683
                $rtnValue .= @fgets( $fp, 4096 );
1684
            }
1685
            @fclose( $fp );
1686
        }
1687
    }
1688
 
1689
    // If the HTML is still empty, then try CURL
1690
    if (($rtnValue == "" && function_exists("curl_init")) || (strpos($rtnValue, "HTTP/1.1 302") > 0 && function_exists("curl_init")))
1691
    {
1692
        // Give CURL a Try
1693
        $ch = curl_init();
1694
        if ($cookie != "")
1695
        {
1696
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
1697
        }
1698
        curl_setopt($ch, CURLOPT_PORT, $domain["port"]);
1699
        curl_setopt($ch, CURLOPT_URL, $url);
1700
        curl_setopt($ch, CURLOPT_VERBOSE, FALSE);
1701
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
1702
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
1703
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
1704
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
1705
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
1706
        curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, TRUE);
1707
 
1708
        $response = curl_exec($ch);
1709
 
1710
        curl_close($ch);
1711
 
1712
        $rtnValue = substr($response, strpos($response, "d8:"));
1713
        $rtnValue = rtrim($rtnValue, "\r\n");
1714
    }
1715
 
1716
    return $rtnValue;
1717
}
1718
 
1719
//**************************************************************************
1720
// getDownloadSize()
1721
// Grab the full size of the download from the torrent metafile
1722
function getDownloadSize($torrent)
1723
{
1724
    $rtnValue = "";
1725
    if (file_exists($torrent))
1726
    {
1727
        include_once("BDecode.php");
1728
        $fd = fopen($torrent, "rd");
1729
        $alltorrent = fread($fd, filesize($torrent));
1730
        $array = BDecode($alltorrent);
1731
        fclose($fd);
1732
        $rtnValue = $array["info"]["piece length"] * (strlen($array["info"]["pieces"]) / 20);
1733
    }
1734
    return $rtnValue;
1735
}
1736
 
1737
//**************************************************************************
1738
// formatBytesToKBMGGB()
1739
// Returns a string in format of GB, MB, or KB depending on the size for display
1740
function formatBytesToKBMGGB($inBytes)
1741
{
1742
    $rsize = "";
1743
    if ($inBytes > (1024 * 1024 * 1024))
1744
    {
1745
        $rsize = round($inBytes / (1024 * 1024 * 1024), 2) . " GB";
1746
    }
1747
    elseif ($inBytes < 1024 * 1024)
1748
    {
1749
        $rsize = round($inBytes / 1024, 1) . " KB";
1750
    }
1751
    else
1752
    {
1753
        $rsize = round($inBytes / (1024 * 1024), 1) . " MB";
1754
    }
1755
    return $rsize;
1756
}
1757
 
1758
//**************************************************************************
1759
// HealthData
1760
// Stores the image and title of for the health of a file.
1761
class HealthData
1762
{
1763
    var $image = "";
1764
    var $title = "";
1765
}
1766
 
1767
//**************************************************************************
1768
// getStatusImage() Takes in an AliasFile object
1769
// Returns a string "file name" of the status image icon
1770
function getStatusImage($af)
1771
{
1772
    $hd = new HealthData();
1773
    $hd->image = "black.gif";
1774
    $hd->title = "";
1775
 
1776
    if ($af->running == "1")
1777
    {
1778
        // torrent is running
1779
        if ($af->seeds < 2)
1780
        {
1781
            $hd->image = "yellow.gif";
1782
        }
1783
        if ($af->seeds == 0)
1784
        {
1785
            $hd->image = "red.gif";
1786
        }
1787
        if ($af->seeds >= 2)
1788
        {
1789
            $hd->image = "green.gif";
1790
        }
1791
    }
1792
    if ($af->percent_done >= 100)
1793
    {
1794
        if(trim($af->up_speed) != "" && $af->running == "1")
1795
        {
1796
            // is seeding
1797
            $hd->image = "green.gif";
1798
        } else {
1799
            // the torrent is finished
1800
            $hd->image = "black.gif";
1801
        }
1802
    }
1803
 
1804
    if ($hd->image != "black.gif")
1805
    {
1806
        $hd->title = "S:".$af->seeds." P:".$af->peers." ";
1807
    }
1808
 
1809
    if ($af->running == "3")
1810
    {
1811
        // torrent is queued
1812
        $hd->image = "black.gif";
1813
    }
1814
 
1815
    return $hd;
1816
}
1817
 
1818
//**************************************************************************
1819
function writeQinfo($fileName,$command)
1820
{
1821
    $fp = fopen($fileName.".Qinfo","w");
1822
    fwrite($fp, $command);
1823
    fflush($fp);
1824
    fclose($fp);
1825
}
1826
 
1827
//**************************************************************************
1828
class ProcessInfo
1829
{
1830
    var $pid = "";
1831
    var $ppid = "";
1832
    var $cmdline = "";
1833
 
1834
    function ProcessInfo($psLine)
1835
    {
1836
        $psLine = trim($psLine);
1837
        if (strlen($psLine) > 12)
1838
        {
1839
            $this->pid = trim(substr($psLine, 0, 5));
1840
            $this->ppid = trim(substr($psLine, 5, 6));
1841
            $this->cmdline = trim(substr($psLine, 12));
1842
        }
1843
    }
1844
}
1845
 
1846
//**************************************************************************
1847
function runPS()
1848
{
1849
    global $cfg;
1850
 
1851
    return shell_exec("ps x -o pid='' -o ppid='' -o command='' -ww | grep btphptornado | grep ".$cfg["torrent_file_path"]." | grep -v grep");
1852
}
1853
 
1854
//**************************************************************************
1855
function RunningProcessInfo()
1856
{
1857
    global $cfg;
1858
 
1859
    if (IsAdmin())
1860
    {
1861
        include_once("RunningTorrent.php");
1862
 
1863
        $screenStatus = runPS();
1864
 
1865
        $arScreen = array();
1866
        $tok = strtok($screenStatus, "\n");
1867
        while ($tok)
1868
        {
1869
            array_push($arScreen, $tok);
1870
            $tok = strtok("\n");
1871
        }
1872
 
1873
        $cProcess = array();
1874
        $cpProcess = array();
1875
        $pProcess = array();
1876
        $ProcessCmd = array();
1877
 
1878
        $QLine = "";
1879
        for($i = 0; $i < sizeof($arScreen); $i++)
1880
        {
1881
            if(strpos($arScreen[$i], $cfg["tfQManager"]) > 0)
1882
            {
1883
                $pinfo = new ProcessInfo($arScreen[$i]);
1884
                $QLine = $pinfo->pid;
1885
            }
1886
            else
1887
            {
1888
               if(strpos($arScreen[$i], "btphptornado.py") !== false)
1889
               {
1890
                   $pinfo = new ProcessInfo($arScreen[$i]);
1891
 
1892
                   if (intval($pinfo->ppid) == 1)
1893
                   {
1894
                        if(!strpos($pinfo->cmdline, "rep python") > 0)
1895
                        {
1896
                            if(!strpos($pinfo->cmdline, "ps x") > 0)
1897
                            {
1898
                                array_push($pProcess,$pinfo->pid);
1899
                                $rt = new RunningTorrent($pinfo->pid . " " . $pinfo->cmdline);
1900
                                //array_push($ProcessCmd,$pinfo->cmdline);
1901
                                array_push($ProcessCmd,$rt->torrentOwner . "\t". str_replace(array(".stat"),"",$rt->statFile));
1902
                            }
1903
                        }
1904
                   }
1905
                   else
1906
                   {
1907
                        if(!strpos($pinfo->cmdline, "rep python") > 0)
1908
                        {
1909
                            if(!strpos($pinfo->cmdline, "ps x") > 0)
1910
                            {
1911
                                array_push($cProcess,$pinfo->pid);
1912
                                array_push($cpProcess,$pinfo->ppid);
1913
                            }
1914
                        }
1915
                   }
1916
               }
1917
            }
1918
        }
1919
        echo " --- Running Processes ---\n";
1920
        echo " Parents  : " . count($pProcess) . "\n";
1921
        echo " Children : " . count($cProcess) . "\n";
1922
        echo "\n";
1923
 
1924
        echo " PID \tOwner\tTorrent File\n";
1925
        foreach($pProcess as $key => $value)
1926
        {
1927
            echo " " . $value . "\t" . $ProcessCmd[$key] . "\n";
1928
            foreach($cpProcess as $cKey => $cValue)
1929
                if (intval($value) == intval($cValue))
1930
                    echo "\t" . $cProcess[$cKey] . "\n";
1931
        }
1932
        echo "\n";
1933
        echo " --- QManager --- \n";
1934
        echo " PID : ";
1935
        echo " ".$QLine;
1936
    }
1937
}
1938
 
1939
//**************************************************************************
1940
function getNumberOfQueuedTorrents()
1941
{
1942
    global $cfg;
1943
 
1944
    $rtnValue = 0;
1945
 
1946
    $dirName = $cfg["torrent_file_path"] . "queue/";
1947
 
1948
    $handle = @opendir($dirName);
1949
 
1950
    if ($handle)
1951
    {
1952
        while($entry = readdir($handle))
1953
        {
1954
            if ($entry != "." && $entry != "..")
1955
            {
1956
                if (!(@is_dir($dirName.$entry)) && (substr($entry, -6) == ".Qinfo"))
1957
                {
1958
                    $rtnValue = $rtnValue + 1;
1959
                }
1960
            }
1961
        }
1962
    }
1963
 
1964
    return $rtnValue;
1965
}
1966
 
1967
//**************************************************************************
1968
function getRunningTorrentCount()
1969
{
1970
    return count(getRunningTorrents());
1971
}
1972
 
1973
//**************************************************************************
1974
function getRunningTorrents()
1975
{
1976
 
1977
    global $cfg;
1978
 
1979
    $screenStatus = runPS();
1980
 
1981
    $arScreen = array();
1982
    $tok = strtok($screenStatus, "\n");
1983
    while ($tok)
1984
    {
1985
        array_push($arScreen, $tok);
1986
        $tok = strtok("\n");
1987
    }
1988
 
1989
    $artorrent = array();
1990
 
1991
    for($i = 0; $i < sizeof($arScreen); $i++)
1992
    {
1993
        if(! strpos($arScreen[$i], $cfg["tfQManager"]) > 0)
1994
        {
1995
           if(strpos($arScreen[$i], "btphptornado.py") !== false)
1996
           {
1997
               $pinfo = new ProcessInfo($arScreen[$i]);
1998
 
1999
               if (intval($pinfo->ppid) == 1)
2000
               {
2001
                    if(!strpos($pinfo->cmdline, "rep python") > 0)
2002
                    {
2003
                        if(!strpos($pinfo->cmdline, "ps x") > 0)
2004
                        {
2005
                            array_push($artorrent,$pinfo->pid . " " . $pinfo->cmdline);
2006
                        }
2007
                    }
2008
               }
2009
           }
2010
        }
2011
    }
2012
 
2013
    return $artorrent;
2014
}
2015
 
2016
//**************************************************************************
2017
function checkQManager()
2018
{
2019
    $x = getQManagerPID();
2020
    if (strlen($x) > 0)
2021
    {
2022
        $y = $x;
2023
        $arScreen = array();
2024
        $tok = strtok(shell_exec("ps -p " . $x . " | grep " . $y), "\n");
2025
 
2026
        while ($tok)
2027
        {
2028
            array_push($arScreen, $tok);
2029
            $tok = strtok("\n");
2030
        }
2031
 
2032
        $QMgrCount = sizeOf($arScreen);
2033
    }
2034
    else
2035
    {
2036
        $QMgrCount = 0;
2037
    }
2038
 
2039
    return $QMgrCount;
2040
}
2041
 
2042
//**************************************************************************
2043
function getQManagerPID()
2044
{
2045
    global $cfg;
2046
 
2047
    $rtnValue = "";
2048
 
2049
    $pidFile = $cfg["torrent_file_path"] . "queue/tfQManager.pid";
2050
 
2051
    if(file_exists($pidFile))
2052
    {
2053
        $fp = fopen($pidFile,"r");
2054
        if ($fp)
2055
        {
2056
            while (!feof($fp))
2057
            {
2058
                $tmpValue = fread($fp,1);
2059
                if($tmpValue != "\n")
2060
                    $rtnValue .= $tmpValue;
2061
            }
2062
            fclose($fp);
2063
        }
2064
    }
2065
    return $rtnValue;
2066
}
2067
 
2068
//**************************************************************************
2069
function startQManager($maxServerThreads=5,$maxUserThreads=2,$sleepInterval=10)
2070
{
2071
    global $cfg;
2072
 
2073
    // is there a stat and torrent dir?
2074
    if (is_dir($cfg["torrent_file_path"]))
2075
    {
2076
        if (is_writable($cfg["torrent_file_path"]) && !is_dir($cfg["torrent_file_path"]."queue/"))
2077
        {
2078
            //Then create it
2079
            mkdir($cfg["torrent_file_path"]."queue/", 0777);
2080
        }
2081
    }
2082
 
2083
    if (checkQManager() == 0)
2084
    {
2085
    $cmd1 = "cd " . $cfg["path"] . "TFQUSERNAME";
2086
 
2087
    if (! array_key_exists("pythonCmd",$cfg))
2088
    {
2089
        insertSetting("pythonCmd","/usr/bin/python");
2090
    }
2091
 
2092
    if (! array_key_exists("debugTorrents",$cfg))
2093
    {
2094
        insertSetting("debugTorrents",false);
2095
    }
2096
 
2097
        if (!$cfg["debugTorrents"])
2098
        {
2099
            $pyCmd = $cfg["pythonCmd"] . " -OO";
2100
        }
2101
        else
2102
        {
2103
            $pyCmd = $cfg["pythonCmd"];
2104
        }
2105
 
2106
        $btphp = "'" . $cmd1. "; HOME=".$cfg["path"]."; export HOME; nohup " . $pyCmd . " " .$cfg["btphpbin"] . " '";
2107
        $command = $pyCmd . " " . $cfg["tfQManager"] . " ".$cfg["torrent_file_path"]."queue/ ".$maxServerThreads." ".$maxUserThreads." ".$sleepInterval." ".$btphp." > /dev/null &";
2108
        //$command = $pyCmd . " " . $cfg["tfQManager"] . " ".$cfg["torrent_file_path"]."queue/ ".$maxServerThreads." ".$maxUserThreads." ".$sleepInterval." ".$btphp." > /dev/null2>&1 & &";
2109
 
2110
        $result = exec($command);
2111
 
2112
        sleep(2); // wait for it to start prior to getting pid
2113
 
2114
        AuditAction($cfg["constants"]["QManager"], "Started PID:" . getQManagerPID());
2115
 
2116
    }else{
2117
        AuditAction($cfg["constants"]["QManager"], "QManager Already Started  PID:" . getQManagerPID());
2118
    }
2119
}
2120
 
2121
//**************************************************************************
2122
function stopQManager()
2123
{
2124
    global $cfg;
2125
 
2126
    $QmgrPID = getQManagerPID();
2127
    if($QmgrPID != "")
2128
    {
2129
        AuditAction($cfg["constants"]["QManager"], "Stopping PID:" . $QmgrPID);
2130
        $result = exec("kill ".$QmgrPID);
2131
        unlink($cfg["torrent_file_path"] . "queue/tfQManager.pid");
2132
    }
2133
}
2134
 
2135
//**************************************************************************
2136
// file_size()
2137
// Returns file size... overcomes PHP limit of 2.0GB
2138
function file_size($file)
2139
{
2140
    $size = @filesize($file);
2141
    if ( $size == 0)
2142
    {
2143
        $size = exec("ls -l \"".$file."\" | awk '{print $5}'");
2144
    }
2145
    return $size;
2146
}
2147
 
2148
//**************************************************************************
2149
// getDirList()
2150
// This method Builds and displays the Torrent Section of the Index Page
2151
function getDirList($dirName)
2152
{
2153
    global $cfg, $db;
2154
    include_once("AliasFile.php");
2155
 
2156
    include_once("RunningTorrent.php");
2157
    $runningTorrents = getRunningTorrents();
2158
 
2159
    $arList = array();
2160
    $file_filter = getFileFilter($cfg["file_types_array"]);
2161
 
2162
    if (is_dir($dirName))
2163
    {
2164
        $handle = opendir($dirName);
2165
    }
2166
    else
2167
    {
2168
        // nothing to read
2169
        if (IsAdmin())
2170
        {
2171
            echo "<b>ERROR:</b> ".$dirName." Path is not valid. Please edit <a href='admin.php?op=configSettings'>settings</a><br>";
2172
        }
2173
        else
2174
        {
2175
            echo "<b>ERROR:</b> Contact an admin the Path is not valid.<br>";
2176
        }
2177
        return;
2178
    }
2179
 
2180
    $lastUser = "";
2181
    $arUserTorrent = array();
2182
    $arListTorrent = array();
2183
 
2184
    while($entry = readdir($handle))
2185
    {
2186
        if ($entry != "." && $entry != "..")
2187
        {
2188
            if (is_dir($dirName."/".$entry))
2189
            {
2190
                // don''t do a thing
2191
            }
2192
            else
2193
            {
2194
                if (ereg($file_filter, $entry))
2195
                {
2196
                    $key = filemtime($dirName."/".$entry).md5($entry);
2197
                    $arList[$key] = $entry;
2198
                }
2199
            }
2200
        }
2201
    }
2202
 
2203
    // sort the files by date
2204
    krsort($arList);
2205
 
2206
    foreach($arList as $entry)
2207
    {
2208
        $output = "";
2209
        $displayname = $entry;
2210
        $show_run = true;
2211
        $torrentowner = getOwner($entry);
2212
        $owner = IsOwner($cfg["user"], $torrentowner);
2213
        $kill_id = "";
2214
        $estTime = "&nbsp;";
2215
        $alias = getAliasName($entry).".stat";
2216
        $af = new AliasFile($dirName.$alias, $torrentowner);
2217
        $timeStarted = "";
2218
        $torrentfilelink = "";
2219
 
2220
        if(!file_exists($dirName.$alias))
2221
        {
2222
            $af->running = "2"; // file is new
2223
            $af->size = getDownloadSize($dirName.$entry);
2224
            $af->WriteFile();
2225
        }
2226
 
2227
        if(strlen($entry) >= 47)
2228
        {
2229
            // needs to be trimmed
2230
            $displayname = substr($entry, 0, 44);
2231
            $displayname .= "...";
2232
        }
2233
 
2234
        // find out if any screens are running and take their PID and make a KILL option
2235
        foreach ($runningTorrents as $key => $value)
2236
        {
2237
            $rt = new RunningTorrent($value);
2238
            if ($rt->statFile == $alias) {
2239
                if ($kill_id == "")
2240
                {
2241
                    $kill_id = $rt->processId;
2242
                }
2243
                else
2244
                {
2245
                    // there is more than one PID for this torrent
2246
                    // Add it so it can be killed as well.
2247
                    $kill_id .= "|".$rt->processId;
2248
                }
2249
            }
2250
        }
2251
 
2252
        // Check to see if we have a pid without a process.
2253
        if (is_file($cfg["torrent_file_path"].$alias.".pid") && empty($kill_id))
2254
        {
2255
            // died outside of tf and pid still exists.
2256
            @unlink($cfg["torrent_file_path"].$alias.".pid");
2257
 
2258
            if(($af->percent_done < 100) && ($af->percent_done >= 0))
2259
            {
2260
                // The file is not running and the percent done needs to be changed
2261
                $af->percent_done = ($af->percent_done+100)*-1;
2262
            }
2263
 
2264
            $af->running = "0";
2265
            $af->time_left = "Torrent Died";
2266
            $af->up_speed = "";
2267
            $af->down_speed = "";
2268
            // write over the status file so that we can display a new status
2269
            $af->WriteFile();
2270
        }
2271
 
2272
        if ($cfg["enable_torrent_download"])
2273
        {
2274
            $torrentfilelink = "<a href=\"maketorrent.php?download=".urlencode($entry)."\"><img src=\"images/down.gif\" width=9 height=9 title=\"Download Torrent File\" border=0 align=\"absmiddle\"></a>";
2275
        }
2276
 
2277
        $hd = getStatusImage($af);
2278
 
2279
        $output .= "<tr><td class=\"tiny\"><img src=\"images/".$hd->image."\" width=16 height=16 title=\"".$hd->title.$entry."\" border=0 align=\"absmiddle\">".$torrentfilelink.$displayname."</td>";
2280
        $output .= "<td align=\"right\"><font class=\"tiny\">".formatBytesToKBMGGB($af->size)."</font></td>";
2281
        $output .= "<td align=\"center\"><a href=\"message.php?to_user=".$torrentowner."\"><font class=\"tiny\">".$torrentowner."</font></a></td>";
2282
        $output .= "<td valign=\"bottom\"><div align=\"center\">";
2283
 
2284
        if ($af->running == "2")
2285
        {
2286
            $output .= "<i><font color=\"#32cd32\">"._NEW."</font></i>";
2287
        }
2288
        elseif ($af->running == "3" )
2289
        {
2290
            $estTime = "Waiting...";
2291
            $qDateTime = '';
2292
            if(is_file($dirName."queue/".$alias.".Qinfo"))
2293
            {
2294
                $qDateTime = date("m/d/Y H:i:s", strval(filectime($dirName."queue/".$alias.".Qinfo")));
2295
            }
2296
 
2297
            $output .= "<i><font color=\"#000000\" onmouseover=\"return overlib('"._QUEUED.": ".$qDateTime."<br>', CSSCLASS);\" onmouseout=\"return nd();\">"._QUEUED."</font></i>";
2298
        }
2299
        else
2300
        {
2301
            if ($af->time_left != "" && $af->time_left != "0")
2302
            {
2303
                $estTime = $af->time_left;
2304
            }
2305
 
2306
            $sql_search_time = "Select time from tf_log where action like '%Upload' and file like '".$entry."%'";
2307
            $result_search_time = $db->Execute($sql_search_time);
2308
            list($uploaddate) = $result_search_time->FetchRow();
2309
 
2310
            $lastUser = $torrentowner;
2311
            $sharing = $af->sharing."%";
2312
            $graph_width = 1;
2313
            $progress_color = "#00ff00";
2314
            $background = "#000000";
2315
            $bar_width = "4";
2316
            $popup_msg = _ESTIMATEDTIME.": ".$af->time_left;
2317
            $popup_msg .= "<br>"._DOWNLOADSPEED.": ".$af->down_speed;
2318
            $popup_msg .= "<br>"._UPLOADSPEED.": ".$af->up_speed;
2319
            $popup_msg .= "<br>"._SHARING.": ".$sharing;
2320
            $popup_msg .= "<br>Seeds: ".$af->seeds;
2321
            $popup_msg .= "<br>Peers: ".$af->peers;
2322
            $popup_msg .= "<br>"._USER.": ".$torrentowner;
2323
 
2324
            $eCount = 0;
2325
            foreach ($af->errors as $key => $value)
2326
            {
2327
                if(strpos($value," (x"))
2328
                {
2329
                    $curEMsg = substr($value,strpos($value," (x")+3);
2330
                    $eCount += substr($curEMsg,0,strpos($curEMsg,")"));
2331
                }
2332
                else
2333
                {
2334
                    $eCount += 1;
2335
                }
2336
            }
2337
            $popup_msg .= "<br>"._ERRORSREPORTED.": ".strval($eCount);
2338
 
2339
            $popup_msg .= "<br>"._UPLOADED.": ".date("m/d/Y H:i:s", $uploaddate);
2340
 
2341
            if (is_file($dirName.$alias.".pid"))
2342
            {
2343
                $timeStarted = "<br>"._STARTED.": ".date("m/d/Y H:i:s",  strval(filectime($dirName.$alias.".pid")));
2344
            }
2345
 
2346
            // incriment the totals
2347
            if(!isset($cfg["total_upload"])) $cfg["total_upload"] = 0;
2348
            if(!isset($cfg["total_download"])) $cfg["total_download"] = 0;
2349
 
2350
            $cfg["total_upload"] = $cfg["total_upload"] + GetSpeedValue($af->up_speed);
2351
            $cfg["total_download"] = $cfg["total_download"] + GetSpeedValue($af->down_speed);
2352
 
2353
            if($af->percent_done >= 100)
2354
            {
2355
                if(trim($af->up_speed) != "" && $af->running == "1")
2356
                {
2357
                    $popup_msg .= $timeStarted;
2358
                    $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=".$alias."&torrent=".urlencode($entry)."')\" style=\"font-size:7pt;\" onmouseover=\"return overlib('".$popup_msg."<br>', CSSCLASS);\" onmouseout=\"return nd();\">seeding (".$af->up_speed.") ".$sharing."</a>";
2359
                }
2360
                else
2361
                {
2362
                    $popup_msg .= "<br>"._ENDED.": ".date("m/d/Y H:i:s",  strval(filemtime($dirName.$alias)));
2363
                    $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=".$alias."&torrent=".urlencode($entry)."')\" onmouseover=\"return overlib('".$popup_msg."<br>', CSSCLASS);\" onmouseout=\"return nd();\"><i><font color=red>"._DONE."</font></i></a>";
2364
                }
2365
                $show_run = false;
2366
            }
2367
            else if ($af->percent_done < 0)
2368
            {
2369
                $popup_msg .= $timeStarted;
2370
                $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=".$alias."&torrent=".urlencode($entry)."')\" onmouseover=\"return overlib('".$popup_msg."<br>', CSSCLASS);\" onmouseout=\"return nd();\"><i><font color=\"#989898\">"._INCOMPLETE."</font></i></a>";
2371
                $show_run = true;
2372
            }
2373
            else
2374
            {
2375
                $popup_msg .= $timeStarted;
2376
 
2377
                if($af->percent_done > 1)
2378
                {
2379
                    $graph_width = $af->percent_done;
2380
                }
2381
                if($graph_width == 100)
2382
                {
2383
                    $background = $progress_color;
2384
                }
2385
                $output .= "<a href=\"JavaScript:ShowDetails('downloaddetails.php?alias=".$alias."&torrent=".urlencode($entry)."')\" onmouseover=\"return overlib('".$popup_msg."<br>', CSSCLASS);\" onmouseout=\"return nd();\">";
2386
                $output .= "<font class=\"tiny\"><strong>".$af->percent_done."%</strong> @ ".$af->down_speed."</font></a><br>";
2387
                $output .= "<table width=\"100\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">";
2388
                $output .= "<tr><td background=\"themes/".$cfg["theme"]."/images/progressbar.gif\" bgcolor=\"".$progress_color."\"><img src=\"images/blank.gif\" width=\"".$graph_width."\" height=\"".$bar_width."\" border=\"0\"></td>";
2389
                $output .= "<td bgcolor=\"".$background."\"><img src=\"images/blank.gif\" width=\"".(100 - $graph_width)."\" height=\"".$bar_width."\" border=\"0\"></td>";
2390
                $output .= "</tr></table>";
2391
            }
2392
 
2393
        }
2394
 
2395
        $output .= "</div></td>";
2396
        $output .= "<td><div class=\"tiny\" align=\"center\">".$estTime."</div></td>";
2397
        $output .= "<td><div align=center>";
2398
 
2399
        $torrentDetails = _TORRENTDETAILS;
2400
        if ($lastUser != "")
2401
        {
2402
            $torrentDetails .= "\n"._USER.": ".$lastUser;
2403
        }
2404
 
2405
        $output .= "<a href=\"details.php?torrent=".urlencode($entry);
2406
        if($af->running == 1)
2407
        {
2408
            $output .= "&als=false";
2409
        }
2410
        $output .= "\"><img src=\"images/properties.png\" width=18 height=13 title=\"".$torrentDetails."\" border=0></a>";
2411
 
2412
        if ($owner || IsAdmin($cfg["user"]))
2413
        {
2414
            if($kill_id != "" && $af->percent_done >= 0 && $af->running == 1)
2415
            {
2416
                $output .= "<a href=\"index.php?alias_file=".$alias."&kill=".$kill_id."&kill_torrent=".urlencode($entry)."\"><img src=\"images/kill.gif\" width=16 height=16 title=\""._STOPDOWNLOAD."\" border=0></a>";
2417
                $output .= "<img src=\"images/delete_off.gif\" width=16 height=16 border=0>";
2418
            }
2419
            else
2420
            {
2421
                if($torrentowner == "n/a")
2422
                {
2423
                    $output .= "<img src=\"images/run_off.gif\" width=16 height=16 border=0 title=\""._NOTOWNER."\">";
2424
                }
2425
                else
2426
                {
2427
                    if ($af->running == "3")
2428
                    {
2429
                        $output .= "<a href=\"index.php?alias_file=".$alias."&dQueue=".$kill_id."&QEntry=".urlencode($entry)."\"><img src=\"images/queued.gif\" width=16 height=16 title=\""._DELQUEUE."\" border=0></a>";
2430
                    }
2431
                    else
2432
                    {
2433
                        if (!is_file($cfg["torrent_file_path"].$alias.".pid"))
2434
                        {
2435
                            // Allow Avanced start popup?
2436
                            if ($cfg["advanced_start"])
2437
                            {
2438
                                if($show_run)
2439
                                {
2440
                                    $output .= "<a href=\"#\" onclick=\"StartTorrent('startpop.php?torrent=".urlencode($entry)."')\"><img src=\"images/run_on.gif\" width=16 height=16 title=\""._RUNTORRENT."\" border=0></a>";
2441
                                }
2442
                                else
2443
                                {
2444
                                    $output .= "<a href=\"#\" onclick=\"StartTorrent('startpop.php?torrent=".urlencode($entry)."')\"><img src=\"images/seed_on.gif\" width=16 height=16 title=\""._SEEDTORRENT."\" border=0></a>";
2445
                                }
2446
                            }
2447
                            else
2448
                            {
2449
                                // Quick Start
2450
                                if($show_run)
2451
                                {
2452
                                    $output .= "<a href=\"".$_SERVER['PHP_SELF']."?torrent=".urlencode($entry)."\"><img src=\"images/run_on.gif\" width=16 height=16 title=\""._RUNTORRENT."\" border=0></a>";
2453
                                }
2454
                                else
2455
                                {
2456
                                    $output .= "<a href=\"".$_SERVER['PHP_SELF']."?torrent=".urlencode($entry)."\"><img src=\"images/seed_on.gif\" width=16 height=16 title=\""._SEEDTORRENT."\" border=0></a>";
2457
                                }
2458
                            }
2459
                        }
2460
                        else
2461
                        {
2462
                            // pid file exists so this may still be running or dieing.
2463
                            $output .= "<img src=\"images/run_off.gif\" width=16 height=16 border=0 title=\""._STOPPING."\">";
2464
                        }
2465
                    }
2466
                }
2467
 
2468
                if (!is_file($cfg["torrent_file_path"].$alias.".pid"))
2469
                {
2470
                    $deletelink = $_SERVER['PHP_SELF']."?alias_file=".$alias."&delfile=".urlencode($entry);
2471
                    $output .= "<a href=\"".$deletelink."\" onclick=\"return ConfirmDelete('".$entry."')\"><img src=\"images/delete_on.gif\" width=16 height=16 title=\""._DELETE."\" border=0></a>";
2472
                }
2473
                else
2474
                {
2475
                    // pid file present so process may be still running. don't allow deletion.
2476
                    $output .= "<img src=\"images/delete_off.gif\" width=16 height=16 title=\""._STOPPING."\" border=0>";
2477
                }
2478
            }
2479
        }
2480
        else
2481
        {
2482
            $output .= "<img src=\"images/locked.gif\" width=16 height=16 border=0 title=\""._NOTOWNER."\">";
2483
            $output .= "<img src=\"images/locked.gif\" width=16 height=16 border=0 title=\""._NOTOWNER."\">";
2484
        }
2485
        $output .= "</div>";
2486
 
2487
        $output .= "</td>";
2488
        $output .= "</tr>\n";
2489
 
2490
        // Is this torrent for the user list or the general list?
2491
        if ($cfg["user"] == getOwner($entry))
2492
        {
2493
            array_push($arUserTorrent, $output);
2494
        }
2495
        else
2496
        {
2497
            array_push($arListTorrent, $output);
2498
        }
2499
    }
2500
    closedir($handle);
2501
 
2502
    // Now spit out the junk
2503
    echo "<table bgcolor=\"".$cfg["table_data_bg"]."\" width=\"100%\" bordercolor=\"".$cfg["table_border_dk"]."\" border=1 cellpadding=3 cellspacing=0>";
2504
 
2505
    if (sizeof($arUserTorrent) > 0)
2506
    {
2507
        echo "<tr><td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">".$cfg["user"].": "._TORRENTFILE."</div></td>";
2508
        echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">Size</div></td>";
2509
        echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._USER."</div></td>";
2510
        echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._STATUS."</div></td>";
2511
        echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._ESTIMATEDTIME."</div></td>";
2512
        echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._ADMIN."</div></td>";
2513
        echo "</tr>\n";
2514
        foreach($arUserTorrent as $torrentrow)
2515
        {
2516
            echo $torrentrow;
2517
        }
2518
    }
2519
 
2520
    if (sizeof($arListTorrent) > 0)
2521
    {
2522
        echo "<tr><td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._TORRENTFILE."</div></td>";
2523
        echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">Size</div></td>";
2524
        echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._USER."</div></td>";
2525
        echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._STATUS."</div></td>";
2526
        echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._ESTIMATEDTIME."</div></td>";
2527
        echo "<td background=\"themes/".$cfg["theme"]."/images/bar.gif\" bgcolor=\"".$cfg["table_header_bg"]."\"><div align=center class=\"title\">"._ADMIN."</div></td>";
2528
        echo "</tr>\n";
2529
        foreach($arListTorrent as $torrentrow)
2530
        {
2531
            echo $torrentrow;
2532
        }
2533
    }
2534
}
2535
?>