-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathbootstrap.php
333 lines (291 loc) · 10.6 KB
/
bootstrap.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
<?php
define("DOCUMENT_ROOT", __DIR__);
define("DS", DIRECTORY_SEPARATOR);
// Define application environment
defined("APPLICATION_ENV")
|| define("APPLICATION_ENV", (getenv("APPLICATION_ENV") ? getenv("APPLICATION_ENV") : "production"));
// Define application environment
define("APPLICATION_VERSION", require DOCUMENT_ROOT."/version.php");
// Constante utilisée pour forcer le navigateur à télécharger
// les fichiers statiques (js, css, html, etc)
define("STATIC_REV", 14);
define("COOKIE_PATH", DOCUMENT_ROOT."/var/tmp");
set_include_path(
__DIR__."/lib".PATH_SEPARATOR.get_include_path()
);
require_once "Http/Client/Curl.php";
require_once "Config/Lite.php";
require_once "Log4php/Logger.php";
class Application
{
/**
* @var Config_Lite
*/
protected $_config;
/**
* @var HttpClientCurl
*/
protected $_connectors = array();
protected function initAutoload()
{
spl_autoload_register(function ($className) {
$filename = ltrim(str_replace("\\", "/", $className), "/");
if (false !== strpos($filename, "App/")) {
$filename = __DIR__."/app/models/".
str_replace("App/", "", $filename).".php";
} else {
$filename = __DIR__."/lib/".$filename.".php";
}
if (is_file($filename)) {
require_once $filename;
}
});
}
protected function initPHPConfig()
{
mb_internal_encoding("UTF-8");
if (function_exists("date_default_timezone_set")) {
date_default_timezone_set("Europe/Paris");
}
if (APPLICATION_ENV == "development") {
ini_set("display_errors", true);
ini_set("error_reporting", -1);
}
}
protected function initLogger()
{
Logger::configure(array(
"rootLogger" => array(
"appenders" => array("default", "error"),
"level" => APPLICATION_ENV == "development"?"debug":"info"
),
"appenders" => array(
"default" => array(
"class" => "LoggerAppenderRollingFile",
"layout" => array(
"class" => "LoggerLayoutPattern",
"params" => array(
"conversionPattern" => "%date %-5level %msg%n"
)
),
"params" => array(
"file" => DOCUMENT_ROOT."/var/log/info.log",
"maxFileSize" => APPLICATION_ENV == "development"?"20MB":"3MB",
"maxBackupIndex" => 5,
"append" => true,
"threshold" => "all",
)
),
"error" => array(
"class" => "LoggerAppenderRollingFile",
"layout" => array(
"class" => "LoggerLayoutPattern",
"params" => array(
"conversionPattern" => "%date %-5level %msg%n"
)
),
"params" => array(
"file" => DOCUMENT_ROOT."/var/log/error.log",
"maxFileSize" => "3MB",
"maxBackupIndex" => 5,
"append" => true,
"threshold" => "error",
)
)
)
));
}
protected function initConfig()
{
// valeurs par défaut.
$this->_config->set("proxy", "ip", "");
$this->_config->set("proxy", "port", "");
$this->_config->set("proxy", "user", "");
$this->_config->set("proxy", "password", "");
$this->_config->set("http", "user_agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.6) Gecko/20100628 Ubuntu/10.04 (lucid) Firefox/3.6.6");
$this->_config->set("general", "check_start", 7);
$this->_config->set("general", "check_end", 24);
$this->_config->set("general", "version", 0);
$this->_config->set("general", "baseurl", "");
$this->_config->set("storage", "type", "files");
// lit la configuration du fichier.
try {
$this->_config->read();
} catch (Config_Lite_Exception_Runtime $e) {
return;
}
$baseurl_locked = $this->_config->get("general", "baseurl_locked", 0);
if (!$baseurl_locked && isset($_SERVER["HTTP_HOST"])) {
$current_base_url = $this->_config->get("general", "baseurl", "");
$base_url = "http";
if (!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] != "off") {
$base_url .= "s";
}
$base_url .= "://".$_SERVER["HTTP_HOST"]."/";
if (!empty($_SERVER["REQUEST_URI"])) {
$request_uri = trim($_SERVER["REQUEST_URI"], "/");
if (false !== $pos = strpos($request_uri, "?")) {
$request_uri = mb_substr($request_uri, 0, $pos);
}
if (false !== strpos($request_uri, ".php")) {
$request_uri = substr($request_uri, 0, strrpos($request_uri, "/"));
}
if ($request_uri) {
$base_url .= trim($request_uri, "/")."/";
}
}
if ($base_url != $current_base_url) {
$this->_config->set("general", "baseurl", $base_url);
$this->_config->save();
}
}
}
/**
*
* @param string $url
* @return HttpClientCurl
*/
public function getConnector($url)
{
$host = parse_url($url, PHP_URL_HOST);
if (!isset($this->_connectors[$host])) {
// Pour Leboncoin, limite le nombre de requête par seconde
if (false !== strpos($host, "leboncoin")) {
$connector = new App\Lbc\HTTPConnector();
$connector->setHeader("Accept", "*/*")
->setHeader("api_key", $this->_config->get("lbc", "api_key", "ba0c2dad52b3ec"))
->setHeader("origin", "https://www.leboncoin.fr")
->setHeader("content-type", "text/plain;charset=UTF-8");
} else {
$connector = new HttpClientCurl();
}
$proxy = $this->_config->get("proxy", null, array());
if (!empty($proxy["ip"])) {
$connector->setProxyIp($proxy["ip"]);
if (!empty($proxy["port"])) {
$connector->setProxyPort($proxy["port"]);
}
}
if ($userAgent = $this->_config->get("http", "user_agent", "")) {
$connector->setUserAgent($userAgent);
}
$connector->setCookiePath(COOKIE_PATH);
$this->_connectors[$host] = $connector;
}
$this->_connectors[$host]->setUrl($url);
return $this->_connectors[$host];
}
public function __construct()
{
set_exception_handler(array($this, "_exceptionHandler"));
set_error_handler(
array($this, "_errorHandler"),
E_ERROR | E_WARNING | E_USER_ERROR | E_USER_WARNING
);
}
public function bootstrap(Config_Lite $config)
{
$this->_config = $config;
foreach (get_class_methods($this) AS $method) {
if (0 === strpos($method, "init")) {
$this->$method();
}
}
}
/**
* @return boolean|string
*/
public function upgradeAvailable()
{
if (!$currentVersion = $this->_config->get("general", "version", "")) {
return false;
}
$updater = new \App\Updater(APPLICATION_VERSION);
try {
$latestVersion = $updater->getLatestVersion();
} catch (Exception $e) {
return false;
}
return version_compare($currentVersion, $latestVersion, "<") ?
$latestVersion : false;
}
public function _exceptionHandler($e)
{
Logger::getLogger("main")->error(
get_class($e)." : #".
$e->getCode()." ".
$e->getMessage()." (".$e->getFile().":".$e->getLine().")"
);
if ("development" == APPLICATION_ENV) {
var_dump($e);
return;
}
die("Un problème est survenu lors de l'exécution du programme.\n");
}
public function _errorHandler($errno, $errstr, $errfile, $errline)
{
$display_errors = ini_get("display_errors");
if ($display_errors || "development" == APPLICATION_ENV) {
var_dump($display_errors,$errno, $errstr, $errfile, $errline);
return false;
}
switch ($errno) {
case E_NOTICE:
$errno_const = "E_NOTICE";
break;
case E_ERROR:
$errno_const = "E_ERROR";
break;
case E_USER_ERROR:
$errno_const = "E_USER_ERROR";
break;
case E_WARNING:
$errno_const = "E_WARNING";
break;
case E_USER_WARNING:
$errno_const = "E_USER_WARNING";
break;
default:
$errno_const = $errno;
}
Logger::getLogger("main")->error(
$errno_const." ".$errstr." (".$errfile.":".$errline.")"
);
// Pour les ERROR, on stoppe l'exécution du script
if ($errno == E_ERROR || $errno == E_USER_ERROR) {
die("Un problème est survenu lors de l'exécution du programme.\n");
}
return true;
}
}
$config = new Config_Lite(DOCUMENT_ROOT."/var/config.ini", LOCK_EX);
$app = new Application();
$app->bootstrap($config);
$userAuthed = null;
// si stockage en base de données, on initialise la connexion
if ("db" == $config->get("storage", "type", "files")) {
$options = array_merge(array(
"host" => "",
"user" => "",
"password" => "",
"dbname" => ""
), $config->get("storage", "options"));
$dbConnection = new mysqli(
$options["host"],
$options["user"],
$options["password"],
$options["dbname"]
);
if ($dbConnection->connect_error) {
Logger::getLogger("main")->error(
"Connexion à la base de données échouée : ".
$dbConnection->connect_error
);
echo "Un problème est survenu lors de la génération de la page.";
exit;
}
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT;
$dbConnection->set_charset("utf8");
unset($options);
}