Adgoal.php 7.59 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php

namespace App\Models;

use Cache;
use Illuminate\Support\Facades\Redis;
use Log;
use Request;
use LaravelLocalization;

class Adgoal
{
    const COUNTRIES = ["af","al","dz","um","as","vi","ad","ao","ai","ag","ar","am","aw","az","au","eg","gq","et","bs",
        "bh","bd","bb","be","bz","bj","bm","bt","bo","ba","bw","bv","br","vg","io","bn","bg","bf","bi","cl","cn","ck",
        "cr","ci","dk","de","dm","do","dj","ec","sv","er","ee","eu","fk","fo","fj","fi","fr","gf","pf","tf","ga","gm",
        "ge","gh","gi","gd","gr","gb","uk","gl","gp","gu","gt","gn","gw","gy","ht","hm","hn","hk","in","id","iq","ir",
        "ie","is","il","it","jm","sj","jp","ye","jo","yu","ky","kh","cm","ca","cv","kz","qa","ke","kg","ki","cc","co",
        "km","cg","cd","hr","cu","kw","la","ls","lv","lb","lr","ly","li","lt","lu","mo","mg","mw","my","mv","ml","mt",
        "mp","ma","mh","mq","mr","mu","yt","mk","mx","fm","md","mc","mn","ms","mz","mm","na","nr","np","nc","nz","ni",
        "nl","an","ne","ng","nu","kp","nf","no","om","tp","at","pk","pw","ps","pa","pg","py","pe","ph","pn","pl","pt",
        "pr","re","rw","ro","ru","st","sb","zm","ws","sm","sa","se","ch","sn","sc","sl","zw","sg","sk","si","so","es",
        "lk","sh","kn","lc","pm","vc","sd","sr","za","kr","sz","sy","tj","tw","tz","th","tg","to","tt","td","cz","tn",
        "tm","tc","tv","tr","us","ug","ua","xx","hu","uy","uz","vu","va","ve","ae","vn","wf","cx","by","eh","ww","zr","cf","cy",];

25
26
27
28
29
30
31
32
33
34
35
36
37
38

    public $hash;
    public $finished = false; // Is true when the Request was sent to and read from Admitad App
    private $affiliates = null;
    private $startTime;

    /**
     * Creates a new Adgoal object which will start a request for affiliate links
     * based on a result List from MetaGer.
     * It will parse the Links of the results and query any affiliate shops.
     * 
     * @param \App\MetaGer $metager
     */
    public function __construct(&$metager)
39
    {
40
        $this->startTime = microtime(true);
41
42
        $publicKey = config("metager.metager.adgoal.public_key");
        $privateKey = config("metager.metager.adgoal.private_key");
43
44
45
        if ($publicKey === false) {
            return true;
        }
46
        $results = $metager->getResults();
47
48
49
50
51
        $linkList = "";
        foreach ($results as $result) {
            if (!$result->new) {
                continue;
            }
52
            $link = $result->originalLink;
53
54
55
56
57
            if (strpos($link, "http") !== 0) {
                $link = "http://" . $link;
            }
            $linkList .= $link . ",";
        }
58
59
60
        if(empty($linkList)){
            return;
        }
61
62
63
64
    
        $linkList = rtrim($linkList, ",");
    
        # Hashwert
65
        $this->hash = md5($linkList . $privateKey);
66
67
68
69
70
71
72
73
74
75
    
        $link = "https://xf.gdprvalidate.de/v4/check";
    
        # Which country to use
        # Will be de for metager.de and en for metager.org
        $country = "de";
        if (LaravelLocalization::getCurrentLocale() === "en") {
            $country = "us";
        }
        $preferredLanguage = Request::getPreferredLanguage();
76
77
78
79
80
81
        if (!empty($preferredLanguage)) {
            if (str_contains($preferredLanguage, "_")) {
                $preferredLanguage = substr($preferredLanguage, stripos($preferredLanguage, "_")+1);
            } elseif (str_contains($preferredLanguage, "-")) {
                $preferredLanguage = substr($preferredLanguage, stripos($preferredLanguage, "-")+1);
            }
82

83
            $preferredLanguage = strtolower($preferredLanguage);
84

85
86
87
            if (in_array($preferredLanguage, self::COUNTRIES)) {
                $country = $preferredLanguage;
            }
88
89
90
91
92
93
        }
    
        $postfields = [
                "key" => $publicKey,
                "panel" => "ZMkW9eSKJS",
                "member" => "338b9Bnm",
94
                "signature" => $this->hash,
95
96
97
98
99
100
                "links" => $linkList,
                "country" => $country,
            ];
    
        // Submit fetch job to worker
        $mission = [
101
                "resulthash" => $this->hash,
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
                "url" => $link,
                "useragent" => "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0",
                "username" => null,
                "password" => null,
                "headers" => [
                    "Content-Type" => "application/x-www-form-urlencoded"
                ],
                "cacheDuration" => 60,
                "name" => "Adgoal",
                "curlopts" => [
                    CURLOPT_POST => true,
                    CURLOPT_POSTFIELDS => \http_build_query($postfields)
                ]
            ];
        $mission = json_encode($mission);
        Redis::rpush(\App\MetaGer::FETCHQUEUE_KEY, $mission);
    }
119
120
121
122

    public function fetchAffiliates($wait = false){
        if($this->affiliates !== null){
            return;
123
        }
124
125
126
127

        $answer = null;
        $startTime = microtime(true);
        if($wait){
128
            while (microtime(true) - $startTime < 5) {
129
                $answer = Cache::get($this->hash);
130
131
132
133
134
135
                if ($answer === null) {
                    usleep(50 * 1000);
                } else {
                    break;
                }
            }
136
137
        }else{
            $answer = Cache::get($this->hash);
138
        }
139
140
141
142
143
144
145
146
        $answer = json_decode($answer, true);
        
        // If the fetcher had an Error
        if($answer === "no-result"){
            $this->affiliates = [];
            return;
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
147
        if(empty($answer) && !is_array($answer)){
148
            return;
149
        }
150

151
152
        $this->affiliates = $answer;
    }
153
    
154
155
156
157
158
159
160
161
162
163
164
165
166
    /**
     * Converts all Affiliate Links.
     * 
     * @param \App\Models\Result[] $results
     */
    public function parseAffiliates(&$results)
    {
        if($this->finished || $this->affiliates === null){
            return;
        }
            
        foreach ($this->affiliates as $partnershop) {
            $targetUrl = $partnershop["url"];
167

168
            $tld = $partnershop["tld"];
169
170
171
172
173
174

            // Sometimes TLD is null
            if(empty($tld)){
                continue;
            }

175
            $targetHost = parse_url($targetUrl, PHP_URL_HOST);
176

177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
            /*
                Adgoal sometimes returns affiliate Links for every URL
                That's why we check if the corresponding TLD matches the orginial URL
            */
            if($targetHost !== false && stripos($targetHost, $tld) === false){
                continue;
            }
            $preference = config("metager.metager.affiliate_preference", "adgoal");
            foreach ($results as $result) {
                if ($result->originalLink === $targetUrl && (config("metager.metager.affiliate_preference", "adgoal") === "adgoal" || !$result->partnershop)) {
                    # Ein Advertiser gefunden
                    if ($result->image !== "" && !$result->partnershop) {
                        $result->logo = $partnershop["logo"];
                    } else {
                        $result->image = $partnershop["logo"];
192
                    }
193
194

                    # Den Link hinzufügen:
Dominik Hebeler's avatar
Dominik Hebeler committed
195
196
197
198
                    # Redirect the user over our tracker
                    # see \App\Http\Controllers\AdgoalController 
                    # for more information
                    $result->link = \App\Http\Controllers\AdgoalController::generateRedirectUrl($partnershop["click_url"], $targetUrl);
199
200
                    $result->partnershop = true;
                    $result->changed = true;
201
202
203
                }
            }
        }
204
205
206
207
    
        $requestTime = microtime(true) - $this->startTime;
        \App\PrometheusExporter::Duration($requestTime, "adgoal");
        $this->finished = true;
208
209
    }
}