-
Notifications
You must be signed in to change notification settings - Fork 0
/
SmartCCDGUT
executable file
·1283 lines (1075 loc) · 34.3 KB
/
SmartCCDGUT
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env php
<?php
/**
* Created by PhpStorm.
* User: Zhensheng
* Date: 2018/11/16
* Time: 23:00
*/
namespace SmartCCDGUT;
abstract class Constants
{
const SCHEMA = "https";
const HOST = "smart.ccdgut.edu.cn";
const SLAT = 'jw134#%pqNLVfn';
// Relative URI based on self::HOST
const APP_URIS = [
"login" => "/app/user/login",
"logout" => "/app/user/logout",
];
// Absolute URL
const URLS = [
"ccdgutAutoAuth" => "http://10.20.208.220/ccdgutwx/zhwebapp/gong/logincityhot.jsp",
"ccdgutAuth" => "http://10.20.208.220/ccdgutwx/zhuochuangAction/dy!loginCityHot.action",
];
const USER_DIRECTORY = __DIR__ . "/users/";
const CREDENTIAL_FILE_NAME = "credentials";
const USER_FILE_NAME = "user";
public static function namedUrl($name)
{
if (array_key_exists($name, static::APP_URIS)) {
return static::url(static::APP_URIS[$name]);
}
if (array_key_exists($name, static::URLS)) {
return static::URLS[$name];
}
return null;
}
public static function url($uri)
{
return sprintf("%s://%s%s", Constants::SCHEMA, Constants::HOST, $uri);
}
public static function hasher($plainText)
{
return md5(md5(Constants::SLAT . $plainText));
}
public static function userCredentialFilePath($username)
{
@mkdir(static::USER_DIRECTORY . $username, 0700, true);
return sprintf("%s%s/%s", static::USER_DIRECTORY, $username, static::CREDENTIAL_FILE_NAME);
}
public static function userFilePath($username)
{
@mkdir(static::USER_DIRECTORY . $username, 0700, true);
return sprintf("%s%s/%s", static::USER_DIRECTORY, $username, static::USER_FILE_NAME);
}
}
if (!function_exists("\\readline")) {
function readline($prompt = "")
{
echo $prompt;
return stream_get_line(STDIN, 1024, PHP_EOL);
}
}
final class Common
{
final public static function readline($prompt)
{
return readline($prompt);
}
final public static function log($text)
{
self::fprintf(STDOUT, "%s", $text);
}
final public static function logf($format, ... $args)
{
self::fprintf(STDOUT, $format, ... $args);
}
final public static function error($text)
{
self::fprintf(STDERR, "%s", $text);
}
final public static function errorf($format, ... $args)
{
self::fprintf(STDERR, $format, ... $args);
}
private static function fprintf($resource, $format, ... $args)
{
return \fprintf($resource, $format, ... $args);
}
}
class SmartCCDGUTException extends \Exception
{
}
/**
* Class Argv
* @package SmartCCDGUT
* @property-read array $originArgv
* @property-read array $argv
* @property-read string $file
* @property-read string $command
*/
class Argv
{
/**
* @var Argv $globalInstance
*/
public static $globalInstance;
private $originArgv;
private $argv;
private $file;
private $command;
public function __construct($argv = null)
{
if (is_null($argv)) {
$argv = $_SERVER["argv"];
}
$this->originArgv = $argv;
$this->file = @array_shift($argv);
$this->command = @array_shift($argv);
$this->argv = $argv;
}
public function setAsGlobal()
{
static::$globalInstance = $this;
return $this;
}
public function __get($name)
{
return $this->{$name};
}
public function at($index)
{
return @$this->argv[$index];
}
public function atOrigin($index)
{
return @$this->originArgv[$index];
}
}
class CommandRouter
{
private $controllers = [];
private $singletons = [];
private $singletonInstances = [];
private $normalProviders = [];
private $names = [];
/**
* @var Argv
*/
private $argv;
public function __construct(Argv $argv)
{
$this->argv = $argv;
$this->controllers = [
"login" => SmartCCDGUTLoginController::class . "@login",
"logout" => SmartCCDGUTLoginController::class . "@logout",
"electric" => SmartCCDGUTElectricQueryController::class . "@query",
"attendance" => SmartCCDGUTAttendanceController::class . "@query",
"extraCredit" => SmartCCDGUTExtraCredit::class . "@query",
"ccdgutAutoAuth" => CCDGUTNetworkAuthenticate::class . "@autoAuth",
"ccdgutAuth" => CCDGUTNetworkAuthenticate::class . "@auth",
];
$this->singletons = [
Argv::class => Argv::class,
];
$this->singletonInstances[Argv::class] = $argv;
$credentialCreator = function () {
$username = $this->argv->at(0);
if (empty($username)) {
throw new SmartCCDGUTException("username is required by command " . $this->argv->command . ".");
}
$userCredentialFilePath = Constants::userCredentialFilePath($username);
if (!file_exists($userCredentialFilePath)) {
throw new SmartCCDGUTException("User " . $username . " not login.");
}
$decodedContent = json_decode(file_get_contents($userCredentialFilePath));
if (is_null($decodedContent)) {
throw new SmartCCDGUTException("Invalid credential file: " . json_last_error_msg());
}
$credential = new Credential($decodedContent->userToken, $decodedContent->token,
$decodedContent->userId);
// $credential->setAsGlobal();
return $credential;
};
$this->normalProviders = [
SmartCCDGUTNetwork::class => function () use ($credentialCreator) {
// These urls required token
static $tokenRequiredUrls = [
"electric" => "https://smart-ccdgut.com/elecharge/data.php",
"attendance" => "http://wx.ccdgut.edu.cn:9000/zhcy.htm",
"extraCredit" => "http://218.16.63.158:8990/remote/token",
"ccdgutAutoAuth" => Constants::URLS["ccdgutAutoAuth"],
];
// These commands required login
static $loginRequiredCommands = [
"logout" => true,
"electric" => true,
"attendance" => true,
"extraCredit" => true,
"ccdgutAutoAuth" => true,
];
$command = $this->argv->command;
$smartCCDGUTNetwork = new SmartCCDGUTNetwork();
if (array_key_exists($command, $loginRequiredCommands)) {
$credential = $credentialCreator();
$smartCCDGUTNetwork->setCredential($credential);
}
if (array_key_exists($command, $tokenRequiredUrls)) {
// Create token url
$apiUrl = sprintf("%s?needLogin=1&token=%s&XPS-UserId=%s&", $tokenRequiredUrls[$command],
$credential->token, $credential->userId);
} else {
$apiUrl = Constants::namedUrl($command);
}
$smartCCDGUTNetwork->setApiUrl($apiUrl);
return $smartCCDGUTNetwork;
},
Credential::class => $credentialCreator,
DOMDocumentOperator::class => function () {
return new PHPDOMDocument();
},
];
$this->names = [
"apiUrl" => function () {
return Constants::namedUrl($this->argv->command);
},
];
}
public static function start()
{
try {
$argv = new Argv();
$argv->setAsGlobal();
$commandRouter = new CommandRouter($argv);
$result = $commandRouter->run();
if (is_string($result)) {
Common::log($result);
} else {
var_dump($result);
}
} catch (SmartCCDGUTException $e) {
Common::errorf("[CODE %d]: %s" . PHP_EOL, $e->getCode(), $e->getMessage());
}
}
public function run()
{
$controller = self::make($this->argv->command);
$parameters = $this->resolveParameters($controller);
return call_user_func($controller, ... $parameters);
}
public static function helpMessage()
{
Common::errorf("Usage: %s COMMAND%s", __FILE__, PHP_EOL);
Common::errorf("Available commands:" . PHP_EOL);
Common::errorf("\tlogin [USERNAME] [PASSWORD]\t\tLogin to Smart CCDGUT and save token." . PHP_EOL);
Common::errorf("\tlogout USERNAME \t\tLogout." . PHP_EOL);
Common::errorf(PHP_EOL);
Common::errorf("\telectric USERNAME\t\tQuery electric usage details." . PHP_EOL);
Common::errorf("\tattendance USERNAME\t\tQuery attendance details." . PHP_EOL);
Common::errorf("\textraCredit USERNAME\t\tQuery extraCredit details." . PHP_EOL);
Common::errorf(PHP_EOL);
Common::errorf("\tccdgutAutoAuth USERNAME\t\tCCDGUT Network authenticate, without manual IP input, APP login is requried." . PHP_EOL);
Common::errorf("\tccdgutAuth USERNAME IP\t\tCCDGUT Network authenticate, APP login is not required." . PHP_EOL);
Common::errorf(PHP_EOL . PHP_EOL);
Common::errorf("Zhensheng Yuan: https://zhensheng.im." . PHP_EOL);
}
private function make($command)
{
if (!array_key_exists($command, $this->controllers)) {
static::helpMessage();
exit(1);
}
$controller = $this->controllers[$command];
if (is_callable($controller)) {
return $controller;
}
@list($controllerClass, $method) = explode("@", $controller, 2);
$controllerObject = new $controllerClass;
if (empty($method)) {
return $controllerObject;
}
return [$controllerObject, $method];
}
private function resolveParameters($callable)
{
$parameters = [];
$reflectionParameters = $this->getParameters($callable);
$argvIndex = 0;
foreach ($reflectionParameters as $index => $parameter) {
$parameterName = $parameter->getName();
if ($parameter->hasType()) {
$reflectionClass = $parameter->getClass();
$className = $reflectionClass->getName();
// Is singleton?
if (array_key_exists($className, $this->singletons)) {
// Is instance exists?
if (!array_key_exists($className, $this->singletonInstances)) {
// Create instance and store it on not exists
if (is_callable($this->singletons[$className])) {
$instance = call_user_func($this->singletons[$className]);
} else {
$instance = new $className;
}
$this->singletonInstances[$className] = $instance;
}
// Add singleton instance to $parameters
$parameters[] = $this->singletonInstances[$className];
} else {
if (array_key_exists($className, $this->normalProviders)) {
$parameters[] = call_user_func($this->normalProviders[$className]);
} else {
// Simply create an instance
$parameters[] = new $className;
}
}
} else {
if (array_key_exists($parameterName, $this->names)) {
$parameters[] = call_user_func($this->names[$parameterName]);
} else {
// Simply retrieve next argv
$parameters[] = $this->argv->at($argvIndex++);
}
}
}
return $parameters;
}
private function getParameters($callable)
{
$CReflection = is_array($callable) ? new \ReflectionMethod($callable[0],
$callable[1]) : new \ReflectionFunction($callable);
return $CReflection->getParameters();
}
}
class Credential
{
/**
* @var Credential
*/
public static $globalInstance;
public $userToken;
public $token;
public $userId;
public function __construct($userToken = null, $token = null, $userId = null)
{
$this->userToken = $userToken;
$this->token = $token;
$this->userId = $userId;
}
public function setAsGlobal()
{
self::$globalInstance = $this;
}
}
class SmartCCDGUTLoginController
{
/**
* @param SmartCCDGUTNetwork $smartCCDGUTNetwork
* @param string|null $username
* @param string|null $password
* @return string
* @throws SmartCCDGUTException
* @throws SmartCCDGUTNetworkException
*/
public function login(SmartCCDGUTNetwork $smartCCDGUTNetwork, $username = null, $password = null)
{
if (empty($username)) {
$username = Common::readline("Username: ");
}
if (empty($password)) {
$password = Common::readline("Password: ");
}
$credential = new Credential();
$smartCCDGUTNetwork
->curlSetopt(function ($ch) use ($credential) {
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, $header) use ($credential) {
@list($name, $value) = explode(": ", $header, 2);
$name = trim($name);
$value = trim($value);
switch ($name) {
case "XPS-UserToken":
$credential->userToken = $value;
break;
case "XPS-Token":
$credential->token = $value;
break;
case "XPS-UserId":
$credential->userId = $value;
break;
}
return strlen($header);
});
})
->addPostField("account", $username)
->addPostField("password", Constants::hasher($password))
->addPostField("sign", "2");
$result = $smartCCDGUTNetwork->preformDecodeOrFail();
if ($result->result == "0") {
throw new SmartCCDGUTNetworkException($result->msg);
}
if (empty($credential->userToken) || empty($credential->token) || empty($credential->userId)) {
throw new SmartCCDGUTException("Login failed with invalid token.");
}
file_put_contents(Constants::userCredentialFilePath($username), json_encode($credential));
file_put_contents(Constants::userFilePath($username), json_encode($result->item));
$text = sprintf("Hello, %s.%s", $result->item->xm, PHP_EOL);
$text .= "Login successfully with credentials save to " . Constants::userCredentialFilePath($username) . "." . PHP_EOL;
return $text;
}
/**
* @param SmartCCDGUTNetwork $smartCCDGUTNetwork
* @return string
* @throws SmartCCDGUTException
* @throws SmartCCDGUTNetworkException
*/
public function logout(SmartCCDGUTNetwork $smartCCDGUTNetwork, $username)
{
$smartCCDGUTNetwork->curlSetopt(function ($ch) {
curl_setopt($ch, CURLOPT_POST, true);
});
$result = $smartCCDGUTNetwork->preformDecodeOrFail();
if ($result->result == "1") {
unlink(Constants::userCredentialFilePath($username));
unlink(Constants::userFilePath($username));
return "Logout successfully." . PHP_EOL;
}
throw new SmartCCDGUTException("Logout unsuccessfully.");
}
}
class SmartCCDGUTElectricQueryController
{
const AVAILABLE_AREAS = [
"01" => "学1A",
"02" => "学1B",
"03" => "学1C",
"04" => "学1D",
"05" => "学2A",
"06" => "学2B",
"07" => "学2C",
"08" => "学2D",
"09" => "学3A",
"10" => "学3B",
"11" => "学3C",
"12" => "学3D",
"13" => "学4A",
"14" => "学4B",
"15" => "学4C",
"16" => "学4D",
"17" => "学5A",
"18" => "学5B",
"19" => "学5C",
"20" => "学5D",
"21" => "学6A",
"22" => "学6B",
"23" => "学6C",
"24" => "学6D",
"25" => "学7A",
"26" => "学7B",
"27" => "学7C",
"28" => "学8A",
"29" => "学8B",
"30" => "学8C",
"31" => "学9A",
"32" => "学9B",
"33" => "学9C",
"34" => "学10",
"35" => "学11",
"36" => "学12",
];
public function query(
Credential $credential,
SmartCCDGUTNetwork $smartCCDGUTNetwork,
$username,
$area = null,
$room = null
) {
if (empty($area)) {
Common::logf("%s%s", "Available areas: ", PHP_EOL);
Common::logf("%s%s", "Code\t\tName", PHP_EOL);
foreach (static::AVAILABLE_AREAS as $code => $name) {
Common::logf("%s\t\t%s%s", $code, $name, PHP_EOL);
}
Common::log(PHP_EOL);
$area = Common::readline("Please select your area by code: ");
}
if (empty($room)) {
$room = Common::readline("Please input your room no: ");
}
$smartCCDGUTNetwork
->addHeader("Referer: https://smart-ccdgut.com/elecharge/index.php")
->addPostField("loudong", $area)
->addPostField("sushe", $room)
->addPostField("token", $credential->token)
->addPostField("isBind", "1");
$result = $smartCCDGUTNetwork->preformDecodeOrFail();
if ($result->errorNumber != 1) {
throw new SmartCCDGUTException("Query unsuccessfully", $result->errorNumber);
}
$text = sprintf("Electric credit: %s%s%s", $result->remainelectric, PHP_EOL, PHP_EOL);
$usage = $result->table;
while ($date = array_shift($usage)) {
$v = array_shift($usage);
$text .= sprintf("%s => %s%s", $date, $v, PHP_EOL);
}
return $text;
}
}
class SmartCCDGUTAttendanceController
{
public function query(
SmartCCDGUTNetwork $smartCCDGUTNetwork,
DOMDocumentOperator $DOMDocumentOperator
) {
$html = $smartCCDGUTNetwork->preformOrFail();
$DOMDocumentOperator->setHTML($html);
$elements = $DOMDocumentOperator->getElementByClass("card");
$text = "";
foreach ($elements as $element) {
$cardChildElements = $element->getChildElements();
$time = trim($cardChildElements[1]->getTextContent());
$lesson = trim($cardChildElements[3]->getTextContent());
$text .= sprintf("%s => %s%s", $time, $lesson, PHP_EOL);
}
return $text;
}
}
class SmartCCDGUTExtraCredit
{
public function query(
SmartCCDGUTNetwork $smartCCDGUTNetwork,
DOMDocumentOperator $DOMDocumentOperator
) {
$html = $smartCCDGUTNetwork->preformOrFail();
$DOMDocumentOperator->setHTML($html);
$items = $DOMDocumentOperator->getElementByClass("mui-media-body");
$summary = trim(array_shift($items)->getTextContent());
$text = $summary . PHP_EOL . PHP_EOL;
foreach ($items as $DOMElementOperator) {
$childElements = $DOMElementOperator->getChildElements();
$itemName = trim($childElements[0]->getText());
$itemCredit = trim($childElements[1]->getTextContent());
$itemStatus = trim($childElements[3]->getChildElements()[1]->getTextContent());
$text .= sprintf("%s". PHP_EOL ."\t%s\t%s" . PHP_EOL . PHP_EOL, $itemName, $itemCredit, $itemStatus);
}
return $text;
}
}
class CCDGUTNetworkAuthenticate
{
public function autoAuth(SmartCCDGUTNetwork $smartCCDGUTNetwork)
{
$response = $smartCCDGUTNetwork->preformOrFail();
if (!preg_match("#'(http://.*loginCityHot\.action.*)'#", $response, $matches))
return "Error: " . $response . PHP_EOL;
$loginURL = array_pop($matches);
return self::loginResponseHandler(file_get_contents($loginURL));
}
public function auth(SmartCCDGUTNetwork $smartCCDGUTNetwork, $username, $IPAddress)
{
$response = $smartCCDGUTNetwork
->addPostField("uid", $username)
->addPostField("sip", $IPAddress)
->preformOrFail()
;
return self::loginResponseHandler($response);
}
private static function loginResponseHandler($response)
{
if (strstr($response, ">code=00<"))
return "Authenticated successfully." . PHP_EOL;
return "Error: " . $response;
}
}
class DOMException extends SmartCCDGUTException
{
}
interface DOMDocumentOperator
{
/**
* @return \DOMDocument
*/
public function DOMDocument();
/**
* @return \DOMXPath
*/
public function DOMXPath();
/**
* @param string $html
* @param int $options
* @return mixed
*/
public function setHTML($html = "", $options = 0);
/**
* @param string $id
* @return DOMElementOperator
*/
public function getElementById($id);
/**
* @param string $tagName
* @return DOMElementOperator[]
*/
public function getElementsByTagName($tagName);
/**
* @param string|string[] $class
* @return DOMElementOperator[]
*/
public function getElementByClass($class);
}
class PHPDOMDocument implements DOMDocumentOperator
{
/**
* @var \DOMDocument $document
*/
private $document;
/**
* @var \DOMXPath $XPath
*/
private $XPath;
/**
* PHPDOMDocument constructor.
* @param null $html
* @param int $options
* @throws DOMException
*/
public function __construct($html = null, $options = 0, $charset = null)
{
if (!is_null($html)) {
$this->setHTML($html, $options, $charset);
}
}
/**
* @return \DOMDocument
*/
public function DOMDocument()
{
return $this->document;
}
public function DOMXPath()
{
return $this->XPath;
}
/**
* @param string $html
* @param int $options
* @param null $charset
* @return mixed|void
* @throws DOMException
*/
public function setHTML($html = "", $options = 0, $charset = null)
{
$this->document = new \DOMDocument();
if (!defined("DEBUG")) {
libxml_use_internal_errors(true);
}
if (!$this->document->loadHTML($html, $options)) {
// printf(STDERR, $html);
throw new DOMException();
}
if (!is_null($charset)) {
$this->document->encoding = $charset;
}
libxml_clear_errors();
$this->XPath = new \DOMXPath($this->document);
}
public function getElementById($id)
{
return new PHPDOMElement($this->document->getElementById($id));
}
public function getElementsByTagName($tagName)
{
$elements = [];
foreach ($this->document->getElementsByTagName($tagName) as $element) {
$elements[] = new PHPDOMElement($element);
}
return $elements;
}
public function getElementByClass($class)
{
$elements = [];
if (is_array($class)) {
$expressionSet = [];
foreach ($class as $c) {
$expressionSet[] = 'contains(concat(" ", normalize-space(@class), " "), " ' . $c . ' ")';
}
$expression = implode(" and ", $expressionSet);
} else {
$expression = 'contains(concat(" ", normalize-space(@class), " "), " ' . $class . ' ")';
}
foreach ($this->XPath->query('//*[' . $expression . ']') as $element) {
$elements[] = new PHPDOMElement($element);
}
return $elements;
}
public function HTML()
{
return $this->DOMDocument()->saveHTML();
}
public function __call($name, $arguments)
{
call_user_func([$this->document, $name], ... $arguments);
}
public function __set($name, $value)
{
$this->document->{$name} = $value;
}
public function __get($name)
{
return $this->document->{$name};
}
}
interface DOMElementOperator
{
/**
* @return \DOMElement
*/
public function DOMElement();
/**
* @return array
*/
public function getChildElements();
/**
* @return string mixed
*/
public function getTagName();
/**
* @param string $name
* @return string
*/
public function getAttribute($name);
/**
* @param string $tagName
* @return DOMElementOperator[]
*/
public function getElementsByTagName($tagName);
/**
* @return string
*/
public function getTextContent();
/**
* @param string $name
* @return bool
*/
public function hasAttribute($name);
/**
* @return string
*/
public function getHTMLCode();
/**
* @return string
*/
public function getInnerHTMLCode();
/**
* @return mixed
*/
public function remove();
}
class PHPDOMElement implements DOMElementOperator
{
private $element;
public function __construct(\DOMElement $element)
{
$this->element = $element;
}
/**
* @return \DOMElement
*/
public function DOMElement()
{
return $this->element;
}
public function getChildElements()
{
$nodes = [];
foreach ($this->element->childNodes as $node) {
if ($node instanceof \DOMElement) {
$nodes[] = new PHPDOMElement($node);
} else {
if ($node instanceof \DOMText) {
$nodes[] = new PHPDOMText($node);
}
}
}
return $nodes;
}
public function getTagName()
{
return $this->element->tagName;
}
public function getAttribute($name)
{
return $this->element->getAttribute($name);
}
public function getElementsByTagName($tagName)
{
$elements = [];
foreach ($this->element->getElementsByTagName($tagName) as $element) {
$elements[] = new PHPDOMElement($element);
}
return $elements;
}
public function getTextContent()
{
return $this->element->textContent;
}
public function hasAttribute($name)
{
return $this->element->hasAttribute($name);
}
public function getHTMLCode()
{
return $this->element->ownerDocument->saveHTML($this->element);
}
public function getInnerHTMLCode()
{
$innerHTML = "";
foreach ($this->element->childNodes as $node) {
$innerHTML .= $node->ownerDocument->saveHTML($node);
}
return $innerHTML;
}
public function remove()
{
$this->DOMElement()->parentNode->removeChild($this->DOMElement());
}
public function __call($name, $arguments)
{
call_user_func([$this->element, $name], ... $arguments);
}
}
interface DOMElementFormOperator
{
/**
* @return array
*/
public function formSerializeArray();
/**
* @return DOMElementOperator[]
*/
public function getElements();