phIRCe / Class.phIRCe.php

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
<?php
/*  phIRCe - PHP IRC bot
 *  Copyright (C) 2009, 2010, 2011  Tony Manco <trmanco@gmx.com>
 *  Portions (C) 2010 Toby Thain <toby@telegraphics.com.au>.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

class phirce {
    private $socket, $conn, $line, $cmd, $version, $allowed=array(), $badwords=array(), $modules=array(),
            $message, $tmppath, $useragent, $logpath, $log, $arcpath, $archive, $modpath;
    public $nick, $ident, $pass, $realname, $host, $port, $chan;
    public function __construct($nick, $pass, $ident, $realname, $host, $port,
                                    $chan, $tmppath, $useragent, $logpath,$log, $arcpath, $archive, $modpath) {
        $this->nick = $nick;
        $this->pass = $pass;
        $this->ident = $ident;
        $this->realname = $realname;
        $this->host = $host;
        $this->port = $port;
        $this->chan = $chan;
        die_unless(is_dir($tmppath) || mkdir($tmppath, 0755, true), // use 0750 if don't trust other users
                   "Cannot create tmp directory $tmppath\r\n");
        $this->tmppath = $tmppath;
        $this->useragent = $useragent;
        die_unless(is_dir($logpath) || mkdir($logpath, 0755, true),
                   "Cannot create log directory $logpath\r\n");
        $this->logpath = $logpath;
        $this->log = $log;
        die_unless(is_dir($arcpath) || mkdir($arcpath, 0755, true),
                   "Cannot create archive directory $arcpath\r\n");
        $this->arcpath = $arcpath;
        $this->archive = $archive;
        $this->modpath = $modpath;
        $this->version = "phIRCe v0.50";

        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        die_unless($this->socket, "socket_create() failed: reason: "
                   . socket_strerror(socket_last_error()) . "\r\n");
        echo "Socket successfully created.\r\n";

        echo "Trying to connect to '$this->host' on port '$this->port'...";
        $this->conn = socket_connect($this->socket, $this->host, $this->port);
        die_unless($this->conn, "socket_connect() failed.\nReason: ($this->conn) "
                   . socket_strerror(socket_last_error($this->socket)) . "\r\n");
        echo "Successfully connected to $this->host.\r\n";
    }
    
    private function SendCommand($cmd) {
        $this->cmd = $cmd;
        $bytes = socket_write($this->socket, $cmd, strlen($cmd));
        if ($bytes){
            if (strpos($cmd, 'PASS') !== 0 && stripos($cmd, 'NickServ') === false)
                echo ("Message sent with success $cmd\r\n");
            return true;
        }
        else{
            echo "socket_write() failed: reason: " . socket_strerror(socket_last_error()) . "\r\n";
            return false;
        }
    }

    public function loop() {
       $this->SendCommand("PASS $this->pass\r\n");
       $this->SendCommand("USER $this->ident 0 * :$this->realname\r\n");
       $this->SendCommand("NICK $this->nick\r\n");
       $joinx = 0;
       $BeenHere = 0;
       while ($this->line = socket_read($this->socket, 5000)){
            if ($joinx < 3){
                $this->SendCommand("JOIN $this->chan\r\n");
                $joinx += 1;
            }
            print $this->line;
            foreach ($this->modules as $module) {
                // Windows path fix
                if ($_SERVER['OS'] == 'Windows_NT')
                    include "$this->modpath"."\\$module".'.php';
                else
                    include "$this->modpath"."/$module".'.php';
            }
            if ($this->log)
                $this->LogRaw($this->line);
            if ($this->IsPing($this->line)){
                $this->DoPong($this->line);
            }
            elseif ($this->IsVersion($this->line)){
                $this->DoVersion($this->line);
            }
            // Process URL section
            elseif ($this->IsURL($this->line) && strstr($this->line, $this->chan)){
            	$this->ProcessURLs($this->line, $this->archive, true);
            }
            elseif (strstr($this->line, 'PRIVMSG')){
                $msg = $this->MsgSplit($this->line);
                if ($this->log)
                    $this->LogChannel($msg['from'], $msg['msg']);
                if ($this->IsCMD(trim($msg['msg']))){
                    if (in_array($this->FilterCloak($this->line), $this->allowed)
                            || !in_array($this->FilterCloak($this->line), $this->allowed)){
                        $this->ExecCMDNonAdm($msg['chan'], $msg['msg']);
                    }
                    if (in_array($this->FilterCloak($this->line), $this->allowed)){
                        if (strstr($this->line,"!quit $this->nick")){
                            $this->SendCommand("QUIT :Exiting! phIRCe - ".
                                                "I told you so! .::. http://bitbucket.org/trmanco/phirce/\r\n");
                            sleep(1);
                            break;
                        }
                        // Command from channel
                        elseif (strstr($this->line, '#')){
                            $this->ExecCMD(trim($msg['chan']),trim($msg['msg']),trim($msg['from']));
                        }
                        // Command from query
                        else{
                            $this->QExecCMD(trim($this->chan),trim($msg['msg']),trim($msg['quser']));
                        }
                    }
                    else{
                        //$this->SendCommand("NOTICE $msg[from] :You are not allowed to control me!\r\n");
                    }
                }
                foreach ($this->badwords as $badword){
                    if (strstr($msg['msg'],$badword)){
                        $this->SendCommand("KICK ".$this->chan." ".$msg['from']." :Watch your language!\r\n");
                    }
                }
            }
            elseif (strstr($this->line, "KICK $this->chan $this->nick")){
                $BeenHere = 1;
                $this->SendCommand("JOIN $this->chan\r\n");
                sleep(1);
                $this->SendCommand("PRIVMSG $this->chan :How dare you kick me!\r\n");
            }
            else{
                $BeenHere = 0;
                continue;
            }
            $this->line = "";
        }
    }

    private function IsPing($line) {
        return strpos($line, 'PING') === 0;
    }

    private function DoPong($line) {
        $pingsend = trim(strstr($line, "PING"));
        $pingsend = trim(strstr($pingsend, " "), "\x01 , :");
        $this->SendCommand("PONG :".$pingsend."\r\n");
    }

    private function IsVersion($line) {
        return strstr($line, 'VERSION');
    }

    private function DoVersion($line) {
        $array = explode(":",$line);
        $to = explode("!",$array[1]);
        $to = trim($to[0]);
        $this->SendCommand("NOTICE $to :".$this->version."\r\n");
    }

    private function MsgSplit($line){
        $array = explode(':', $line);

        // Get who sent message
        $from = explode('!', $array[1]);

        // Get the message
        $msg = array('from'=>trim($from[0]),
                     'msg'=>trim($array[2]));

        if (strpos($array[1], '#') !== false){
            // Get the channel
            $chan = explode('#', $array[1]);
            $msg['chan'] = '#'.trim($chan[1]);
        }
        else{
            $msg['quser'] = trim(strstr($array[1], '!', true));
        }

        return $msg;
    }

    private function IsCMD($cmd) {
        return $cmd && $cmd[0] == '!' && strstr($cmd, ' ');
    }
    
    private function ExecCMD($chan,$cmd,$from) {
        $keys = preg_split("/\s+/", $cmd);
        $command = trim($keys[0]);
        $user = trim($keys[1]);
        switch ($command) {
            case "!kick":
                $this->SendCommand("KICK $chan $user :Don't take this personally!\r\n");
                break;
            case "!op":
                $this->SendCommand("MODE $chan +o $user\r\n");
                break;
            case "!deop":
                $this->SendCommand("MODE $chan -o $user\r\n");
                break;
            case "!voice":
                $this->SendCommand("MODE $chan +v $user\r\n");
                break;
            case "!devoice":
                $this->SendCommand("MODE $chan -v $user\r\n");
                break;
            case "!ban":
                $banop = trim($keys[2]);
                switch ($banop){
                    case 1:
                        $this->SendCommand("MODE $chan +b $user!*@*\r\n");
                        break;
                    default:
                        $this->SendCommand("PRIVMSG $chan :Not a valid ban option!\r\n");
                        break;
                }
                break;
            case "!unban":
                $banop = trim($keys[2]);
                switch ($banop){
                    case 1:
                        $this->SendCommand("MODE $chan -b $user!*@*\r\n");
                        break;
                    default:
                        $this->SendCommand("PRIVMSG $chan :Not a valid unban option!\r\n");
                        break;
                }
                break;
            case "!kickban":
                $banop = trim($keys[2]);
                switch ($banop){
                    case 1:
                        $this->SendCommand("MODE $chan +b $user!*@*\r\n");
                        $this->SendCommand("KICK $chan $user :Don't take this personally!\r\n");
                        break;
                    default:
                        $this->SendCommand("PRIVMSG $chan :Not a valid kickban option!\r\n");
                        break;
                }
                break;
            case "!help":
                $this->DisplayHelp($from);
                break;
            case "!license":
                $this->DisplayLicense($from);
                break;
            case "!memory":
                $this->SendCommand("PRIVMSG $chan :\x02Memory in use:\x02 "
                        .$this->MemoryUsage()." MB | \x02Peak usage:\x02 "
                            .$this->PeakMemoryUsage()." MB \r\n");
                break;
            default:
                //$this->SendCommand("PRIVMSG $chan :Not a valid command!\r\n");
                break;
        }
    }

    private function QExecCMD($chan,$cmd,$quser) {
        $keys = preg_split("/\s+/", $cmd);
        $command = trim($keys[0]);
        $user = trim($keys[1]);
        //For !say command
        foreach ($keys as $key) {
            $this->message.=$key." ";
        }
        $this->message = trim($this->message, '!say');
        switch ($command) {
            case "!kick":
                $this->SendCommand("KICK $chan $user :Don't take this personally!\r\n");
                break;
            case "!op":
                $this->SendCommand("MODE $chan +o $user\r\n");
                break;
            case "!deop":
                $this->SendCommand("MODE $chan -o $user\r\n");
                break;
            case "!voice":
                $this->SendCommand("MODE $chan +v $user\r\n");
                break;
            case "!devoice":
                $this->SendCommand("MODE $chan -v $user\r\n");
                break;
            case "!ban":
                $banop = trim($keys[2]);
                switch ($banop){
                    case 1:
                        $this->SendCommand("MODE $chan +b $user!*@*\r\n");
                        break;
                    default:
                        $this->SendCommand("PRIVMSG $quser :Not a valid ban option!\r\n");
                        break;
                }
                break;
            case "!unban":
                $banop = trim($keys[2]);
                switch ($banop){
                    case 1:
                        $this->SendCommand("MODE $chan -b $user!*@*\r\n");
                        break;
                    default:
                        $this->SendCommand("PRIVMSG $quser :Not a valid unban option!\r\n");
                        break;
                }
                break;
            case "!kickban":
                $banop = trim($keys[2]);
                switch ($banop){
                    case 1:
                        $this->SendCommand("MODE $chan +b $user!*@*\r\n");
                        $this->SendCommand("KICK $chan $user :Don't take this personally!\r\n");
                        break;
                    default:
                        $this->SendCommand("PRIVMSG $quser :Not a valid kickban option!\r\n");
                        break;
                }
                break;
            case "!help":
                $this->DisplayHelp($quser);
                break;
            case "!say":
                $this->SendCommand("PRIVMSG $chan :".trim($this->message)."\r\n");
                $this->message = "";
                break;
            case "!license":
                $this->DisplayLicense($quser);
                break;
            case "!clearlog":
                $r = $this->ClearLog();
                if ($r)
                   $this->SendCommand("PRIVMSG $quser :Log has been cleared!\r\n");
                else
                   $this->SendCommand("PRIVMSG $quser :There was a problem clearing the log!\r\n");
                break;
            case "!clear-rawlog":
                $r = $this->ClearRawLog();
                if ($r)
                    $this->SendCommand("PRIVMSG $quser :Raw log has been cleared!\r\n");
                else
                    $this->SendCommand("PRIVMSG $quser :There was a problem clearing the raw log!\r\n");
                break;
            case "!version":
                $this->DisplayVersion($quser);
                break;
            default:
                $this->SendCommand("PRIVMSG $quser :Not a valid command!\r\n");
                break;
        }
    }

    private function ExecCMDNonAdm($chan,$cmd) {
        $keys = preg_split('/\s+/', $cmd);
        $command = trim($keys[0]);
        switch ($command) {
            case "!google":
                $this->GoogSearch(implode(' ', array_slice($keys, 1)), $chan);
                break;
            default:
                //$this->SendCommand("PRIVMSG $chan :Not a valid command!\r\n");
                break;
        }
    }

    private function GoogSearch($query,$chan) {
        $url = "http://ajax.googleapis.com/ajax/services/search/web"
               ."?v=1.0&hl=en&rsz=small&q=".urlencode($query);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_REFERER, 'http://bitbucket.org/trmanco/phirce/');
        $body = curl_exec($ch);
        $searchresult = "";
        if(!curl_errno($ch)){
	        $json = json_decode($body);
	        if($json && $json->responseData->results){
		        foreach ($json->responseData->results as $n => $searchresult) {
		            if($searchresult->GsearchResultClass == 'GwebSearch')
		                $this->SendCommand("PRIVMSG $chan :\x02[".($n + 1)."]\x02 - "
						                   .html_entity_decode($searchresult->titleNoFormatting,
						                                       ENT_QUOTES,
						                                       'UTF-8')
		                                   ." | $searchresult->url\r\n");
		        }
	        }
	        else{
	            $this->SendCommand("PRIVMSG $chan :\x02No Google results\x02\r\n");
	        }
        }
        else{
        	$this->SendCommand("PRIVMSG $chan :\x02Could not get Google results\x02 - ".curl_error($ch)."\r\n");
        }
        curl_close($ch);
    }

    public function Nickserv($pass) {
        $this->SendCommand("/msg NickServ identify $pass\r\n");
    }

    public function allowed($allowed=array()) {
        $this->allowed = $allowed;
    }

    public function badwords($badwords=array()) {
        $this->badwords = $badwords;
    }

    public function modules($modules=array()) {
        $this->modules = $modules;
    }

    private function MemoryUsage() {
        // Returns memry usage in MB
        $usage = (memory_get_usage() / 1024);
        return round($usage / 1024, 3);
    }

    private function PeakMemoryUsage() {
       // Returns memry usage in MB
       $peak = (memory_get_peak_usage() / 1024);
       return round($peak / 1024, 3);
    }
    private function IsURL($line) {
        return preg_match('/(https?:\/\/)(www\.)?([a-zA-Z0-9]*\.)?([a-zA-Z0-9_%-]*)'
                        .'\b\.[a-z]{2,4}(\[a-z]{2})?((\/[a-zA-Z0-9_%-?@]*)+)?'
                        .'(\.[a-z]*)?/', $line);
    }

    private function CleanFilename($str){
    	// alternative set based on shell metachars, and path separators:
    	// Windows prohibits:  / : < > |
    	// '/[\s\/\\\\:&|()!{}\\[\\]<>~`$*\'"?#]/'
    	// original $banstrings=array("."," ","|",",",":","-","\"","'","/");
        // Don't allow timestamps on Windows, they fail.
        if ($_SERVER['OS'] == 'Windows_NT')
            return preg_replace('/[-.\s|,:"\'\/\\\\]/', '_', $str);
        else
            return '['.date('d.m.y@G:i:s').']-'.preg_replace('/[-.\s|,:"\'\/\\\\]/', '_', $str);
    }

    private function XPathFromUrl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 8); // don't hang the bot on redirect loop
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        $doc = curl_exec($ch);
        curl_close($ch);

        if($doc)
            return array ($doc, new DOMXPath(DOMDocument::loadHTML($doc)));

        return array (null, null);
    }
    
    private function GetTweet($url){
        $result = array();
        $doc = "";
        $xpath = "";
        list ($doc, $xpath) = $this->XPathFromUrl($url);
        if($xpath){
            $descElement = $xpath->query('/html/head/meta[@name="description"]');
            $screenNameElement = $xpath->query('/html/head/meta[@name="page-user-screen_name"]');
            if ($descElement->length && $screenNameElement->length){
                $result['text'] = $descElement->item(0)->getAttribute('content');
                $result['screen_name'] = $screenNameElement->item(0)->getAttribute('content');
            }
            else{
                $result['error'] = 'Not a tweet?';
            }

            if ($this->archive){
                if ($_SERVER['OS'] == 'Windows_NT')
                    file_put_contents($this->arcpath.'\\'.$this->CleanFilename(strstr($url, 'twitter')), $doc);
                else
                    file_put_contents($this->arcpath.'/'.$this->CleanFilename(strstr($url, 'twitter')), $doc);
            }
        }
        else{
           $result['error'] = 'Could not fetch Twitter page';
        }

        return $result;
    }

    private function GetDent($url){
        $result = array();
        $doc = "";
        $xpath = "";
        $fname = "";
        list ($doc, $xpath) = $this->XPathFromUrl($url);
        if($xpath){
            $titleElement = $xpath->query('/html/head/title');
            $textElement = $xpath->query('/html/head/meta[@property="og:description"]');
            if ($titleElement->length && $textElement->length){
                $result['text'] = $textElement->item(0)->getAttribute('content');
                $result['screen_name'] = $fname = $titleElement->item(0)->textContent;
            }
            else{
                $result['error'] = 'Not a dent?';
                $fname = strstr($url, 'identi'); // default filename
            }

            if ($this->archive){
                if ($_SERVER['OS'] == 'Windows_NT')
                    file_put_contents($this->arcpath.'\\'.$this->CleanFilename($fname), $doc);
                else
                    file_put_contents($this->arcpath.'/'.$this->CleanFilename($fname), $doc);
            }
        }
        else{
           $result['error'] = 'Could not fetch identi.ca page';
        }

        return $result;
    }

    private function ProcessURLs($line, $archive = false, $look_inside = false, $prefix = ''){
        $matches = '';
        $tweet = "";
        $data = "";
        $dent = "";
        $msg = "";
        preg_match_all('/https?:\/\/\S+/', $line, $matches);
        foreach ($matches[0] as $url){
            // Special case for Twitter
            if(preg_match('%^(https?://twitter\.com/)(#!/)?([^/]+/status.*)%', $url, $tweet)){
                // Fixup new Twitter URL so it fetches a specific resource
                $url = $tweet[1].$tweet[3];
                $data = $this->GetTweet($url);
            }
            // Special case for identi.ca
            else if(preg_match('%^https?://identi\.ca/notice/%', $url, $dent)){
                $data = $this->GetDent($url);
            }
            // All other URLs
            else{
            	// Fixup new Twitter URL so it fetches a specific resource
            	$matches2 = '';
                if(preg_match('%^(https?://twitter\.com/)#!/(.*)%', $url, $matches2))
                    $url = $matches2[1].$matches2[2];
                $data = $this->ParseURL($url, $archive);
            }
            
            if(empty($data['error'])){
            	$msg = isset($data['title'])
            	           ? "$prefix\x02Title:\x02 ".$data['title']
                             ." .::. \x02Size~:\x02 ".$data['pagesize']
                           : "@\x02{$data['screen_name']}\x02: "
                             .html_entity_decode(
                                preg_replace('/[\r\n]+/', ' ', $data['text']),
                                ENT_QUOTES,
                                'UTF-8');
            }
            else{
            	$msg = "\x02{$data['error']}\x02";
            }

            $this->SendCommand("PRIVMSG $this->chan :$msg\r\n");

            // Fetch URLs in tweet/dent. Linked documents will not be archived.
            if($look_inside && !empty($data['text']))
                $this->ProcessURLs($data['text'], false, false, '-> ');
         }
    }

    private function ParseURL($url, $archive = false) {
        $data = array();
        $ctype = "";
        $status = "";
        $skip = "";
        $urlpath = "";
        $filename = "";
        $ext = "";
        $headers = get_headers($url, 1);

        if ($headers){
			// because numeric and string keys are mixed, we have to step thru
			// the array to find status header for the final request.
	        for($i = 0; isset($headers[$i]); ++$i)
	            ;
	        $last_request = $i - 1;
		$status_header = $headers[$last_request];

	        foreach($headers as $name => $value){
	        	// the value may be an array if redirections occurred; take last one
	            if(!strcasecmp($name, 'Content-Type'))
	                $ctype = is_array($value) ? $value[$last_request] : $value;
	        }

	        $status = explode(' ', $status_header, 3);
        	if($status[1][0] == '2' /*|| $status[1][0] == '3'*/){
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_MAXREDIRS, 32); // don't hang the bot on redirect loop
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
                curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
                curl_setopt($ch, CURLOPT_USERAGENT, $this->useragent);
                curl_setopt($ch, CURLOPT_COOKIE, 1);
                //curl_setopt($ch, CURLOPT_ENCODING, '');
                $doc = curl_exec($ch);

                if($doc !== false){
		            if (strpos($ctype, 'text/html') !== false){
	                    $matches = array();
		                $title = preg_match('/<title[^>]*>(.*?)<\/title\s*>/si', $doc, $matches);
		                if ($title){
		                    $data['title'] = trim(html_entity_decode(
		                            strip_tags(preg_replace('/[\r\n]+/', ' ', $matches[1])),
		                            ENT_QUOTES,
		                            'UTF-8'));

		                    if ($archive){
		                        // Save to archive
                                        if ($_SERVER["OS"] == 'Windows_NT')
                                             file_put_contents("$this->arcpath\\"
		                                      .$this->CleanFilename($data['title'])
		                                      .".html",
		                                         $doc);
                                        else
                                            file_put_contents("$this->arcpath/"
		                                      .$this->CleanFilename($data['title'])
		                                      .".html",
		                                         $doc);
		                    }
		                    clearstatcache();
		                }
		            }
		            else{
		                $data['error'] = "Not a web page! Aborting \x02".$ctype."\x02 type";
		                $matches = array();
	                    if ($archive && preg_match('/:\/\/(.*?)([^\/]*?)(\.\w+)?([?#].*)?$/', $url, $matches)){
	                        // Save to archive
	                        // Take filename from url. If no base name, use whole hostname and path
	                        list ($skip, $urlpath, $filename, $ext) = $matches;
                                if ($_SERVER["OS"] == 'Windows_NT')
                                     file_put_contents("$this->arcpath\\"
	                                            .$this->CleanFilename($filename ? $filename : $urlpath)
	                                            .($ext ? $ext : ''), // add extension if present
	                                          $doc);
                                else
                                    file_put_contents("$this->arcpath/"
	                                            .$this->CleanFilename($filename ? $filename : $urlpath)
	                                            .($ext ? $ext : ''), // add extension if present
	                                          $doc);
	                    }
		            }
		            $data['pagesize'] = round(strlen($doc) / 1024 , 2)." KB";
                }
                else{
                	$data['error'] = curl_error($ch)." ( $url )";
                }

                curl_close($ch);
	        }
	        else{
	            $data['error'] = "Error processing the URL: \x02$headers[0]\x02";
	        }
        }
        else{
            $data['error'] = "Error processing the URL";
        }
        return $data;
    }

    private function DisplayHelp($user) {
        $helpers = array (0 => "---START---",
                        1 => "\x02[Help]\x02 - List of available commands:",
                        2 => "\x02[Kick]\x02 - Kick a user from the channel (!kick phIRCe)",
                        3 => "\x02[Op]\x02 - OPs a user from the channel (!op phIRCe)",
                        4 => "\x02[Deop]\x02 - DEOPs a user from the channel (!deop phIRCe)",
                        5 => "\x02[Ban]\x02 - Bans a user from the channel (!ban phIRCe 1)",
                        6 => "\x02[Unban]\x02 -Unbans a user from the channel (!unban phIRCe 1)",
                        7 => "\x02[Voice]\x02 - Give VOICE to a user from the channel (!voice phIRCe)",
                        8 => "\x02[Devoice]\x02 - Give DEVOICE to a user from the channel (!devoice phIRCe)",
                        9 => "\x02[Kickban]\x02 - Kickbans a user from the channel (!kickban phIRCe 1)",
                        10 => "\x02[Quit]\x02 - Disconnects the bot in a clean way (!quit phIRCe)",
                        11 => "\x02[Say]\x02 - Says something to the channel (!say Hello)",
                        12 => "\x02[License]\x02 - Shows a small licensing notice (!license phIRCe)",
                        13 => "\x02[Clearlog]\x02 - Clears the normal logfile (!clearlog phIRCe)",
                        14 => "\x02[Clear-rawlog]\x02 - Clears the raw logfile (!clear-rawlog phIRCe)",
                        15 => "\x02[Version]\x02 - Shows the version of the bot (!version phIRCe)",
                        16 => "---END---");
        foreach ($helpers as $help) {
            $this->SendCommand("PRIVMSG $user :$help\r\n");
        }
    }

    private function DisplayLicense($user) {
         $licensemsg = array( 0 => "phIRCe - Copyright (C) 2009  Tony Manco <trmanco@gmx.com>.",
                             1 => "Portions (C) 2010 Toby Thain <toby@telegraphics.com.au>.",
                             2 => "This program comes with ABSOLUTELY NO WARRANTY.",
                             3 => "This is free software, and you are welcome to redistribute",
                             4 => "it under certain conditions.");
         foreach ($licensemsg as $line) {
           $this->SendCommand("PRIVMSG $user :$line\r\n");
         }
    }
    
    private function FilterCloak($line) {
        $pieces = explode(" ", $line);
        $cloak = trim(strstr($pieces[0], '~'), '~');
        return "$cloak";
    }

    private function LogRaw($line) {
        if ($_SERVER["OS"] == 'Windows_NT')
            $handle = fopen("$this->logpath\\raw.log", 'a+');
        else
            $handle = fopen("$this->logpath/raw.log", 'a+');
        fwrite($handle, $line . "\r\n");
        fclose($handle);
    }

    private function LogChannel($from,$message) {
        if ($_SERVER['OS'] == 'Windows_NT')
            $handle = fopen("$this->logpath\\log.log", 'a+');
        else
            $handle = fopen("$this->logpath/log.log", 'a+');
        $line = date(DATE_RFC822).':'."[$from] $message\r\n";
        fwrite($handle, $line);
        fclose($handle);
    }

    private function ClearLog (){
        if ($_SERVER['OS'] == 'Windows_NT')
           $handle = fopen("$this->logpath\\log.log", 'w');
        else
           $handle = fopen("$this->logpath/log.log", 'w');
        $r = ftruncate($handle, 0);
        fclose ($handle);
        return $r;
    }

   private function ClearRawLog (){
        if ($_SERVER['OS'] == 'Windows_NT')
           $handle = fopen("$this->logpath\\raw.log", 'w');
        else
           $handle = fopen("$this->logpath/raw.log", 'w');
        $r = ftruncate($handle, 0);
        fclose ($handle);
        return $r;
    }

    private function DisplayVersion($user){
        $this->SendCommand("PRIVMSG $user :$this->version\r\n");
    }

    public function quit() {
        socket_shutdown($this->socket, 1);
        usleep(500);
        socket_shutdown($this->socket, 0);
        sleep(1);
        socket_close($this->socket);
    }
}
?>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.