Core  3.2
PHP API documentation
 All Data Structures Namespaces Files Functions Variables Pages
Lib.Http.php
Go to the documentation of this file.
1 <?php
2 /*
3  * @author Anakeen
4  * @package FDL
5 */
6 /**
7  * Set of usefull HTTP functions
8  *
9  * @author Anakeen
10  * @version $Id: Lib.Http.php,v 1.38 2008/11/28 12:48:06 eric Exp $
11  * @package FDL
12  * @subpackage CORE
13  */
14 /**
15  * @param Action|Application $action
16  * @param string $appname
17  * @param string $actionname
18  * @param string $otherurl
19  * @param bool $httpparamredirect
20  */
21 function Redirect($action, $appname, $actionname, $otherurl = "", $httpparamredirect = false)
22 {
23  global $_SERVER, $_GET; // use only with HTTP
24  if (empty($_SERVER['HTTP_HOST'])) {
25  print "\n--Redirect $appname $actionname--\n";
26  return;
27  }
28 
29  if ($appname == "") {
30  $location = ".";
31  } else {
32  if ($otherurl == "") {
33  if (in_array($appname, array(
34  "CORE",
35  "APPMNG",
36  "ACCESS",
37  "AUTHENT"
38  ))) $baseurl = $action->GetParam("CORE_BASEURL");
39  else $baseurl = '?';
40  } else $baseurl = $otherurl;
41  $location = $baseurl . "app=" . $appname . "&action=" . $actionname;
42  // $location .= "&session=".$action->session->id;
43 
44  }
45 
46  $action->log->debug("Redirect : $location");
47 
48  if ($httpparamredirect) {
49  //add ZONE_ARGS
50  global $ZONE_ARGS;
51  if (is_array($ZONE_ARGS)) foreach ($ZONE_ARGS as $k => $v) $location.= "&$k=$v";
52  }
53  global $SQLDEBUG;
54  if ($SQLDEBUG) {
55  global $ticainit, $tic1, $trace;
56  global $TSQLDELAY, $SQLDELAY;
57  $trace["__url"] = $trace["url"];
58  $trace["__init"] = $trace["init"];
59  unset($trace["url"]);
60  unset($trace["init"]);
61  $deb = gettimeofday();
62  $tic4 = $deb["sec"] + $deb["usec"] / 1000000;
63  $trace["__app"] = sprintf("%.03fs", $tic4 - $ticainit);
64  $trace["__memory"] = sprintf("%dkb", round(memory_get_usage() / 1024));
65  $trace["__queries"] = sprintf("%.03fs #%d", $SQLDELAY, count($TSQLDELAY));
66  $trace["__server all"] = sprintf("%.03fs", $tic4 - $tic1);
67  $action->register("trace", $trace);
68  }
69  $viewext = isset($_GET["viewext"]) ? $_GET["viewext"] : (isset($_POST["viewext"]) ? $_POST["viewext"] : "");
70  if ($viewext === "yes") {
71  if (\Dcp\Autoloader::classExists("Dcp\\ExtUi\\defaultMenu")) {
72  /** @noinspection PhpUndefinedNamespaceInspection */
73  /** @noinspection PhpUndefinedClassInspection */
74  $location = \Dcp\ExtUi\defaultMenu::convertToExtUrl($location);
75  }
76  }
77  header("Location: $location");
78  exit;
79 }
80 
82 {
83  global $_SERVER;
84 
85  if ($_SERVER["HTTP_REFERER"] != "") {
86  Header("Location: " . $_SERVER["HTTP_REFERER"]); // return to sender
87  exit;
88  }
89  $referer = GetHttpVars("http_referer");
90  if ($referer != "") {
91  Header("Location: " . $referer); // return to sender
92  exit;
93  }
94 
95  $action->exitError(_("no referer url found"));
96  exit;
97 }
98 /**
99  * if in useIndexAsGuest mode
100  * redirect with authtication to current url
101  * only if it is anonymous also
102  * @param Action $action
103  */
105 {
106  $guestMode = getDbAccessValue("useIndexAsGuest");
107  if ($guestMode) {
108  if ($action->user->id == Account::ANONYMOUS_ID) {
109  /*
110  * @var htmlAuthenticator $auth
111  */
113  if (is_a($auth, "htmlAuthenticator")) $auth->connectTo($_SERVER['REQUEST_URI']);
114  }
115  }
116 }
117 /**
118  * return value of an http parameter
119  * @param string $name parameter key
120  * @param string $def default value if parameter is not set
121  * @param string $scope The scope for the search of the value ('zone' for $ZONE_ARGS, 'get' for $_GET, 'post' for $_POST and 'all' for searching in all)
122  * @return string
123  */
124 function getHttpVars($name, $def = "", $scope = "all")
125 {
126  global $_GET, $_POST, $ZONE_ARGS;
127 
128  if (($scope == "all" || $scope == "zone") && isset($ZONE_ARGS[$name])) {
129  // try zone args first : it is set be Layout::execute for a zone
130  return ($ZONE_ARGS[$name]);
131  }
132  if (($scope == "all" || $scope == "get") && isset($_GET[$name])) {
133  return $_GET[$name];
134  }
135  if (($scope == "all" || $scope == "post") && isset($_POST[$name])) {
136  return $_POST[$name];
137  }
138 
139  return ($def);
140 }
141 
142 function GetHttpCookie($name, $def = "")
143 {
144 
145  global $_COOKIE;
146  if (isset($_COOKIE[$name])) return $_COOKIE[$name];
147  return ($def);
148 }
149 
150 function SetHttpVar($name, $def)
151 {
152 
153  global $ZONE_ARGS;
154  if ($def == "") unset($ZONE_ARGS[$name]);
155  else $ZONE_ARGS[$name] = $def;
156 }
157 
158 function GetMimeType($ext)
159 {
160  $mimes = file("/etc/mime.types");
161  foreach ($mimes as $v) {
162  if (substr($v, 0, 1) == "#") continue;
163  $tab = preg_split('/\s+/', $v);
164  if ((isset($tab[1])) && ($tab[1] == $ext)) return ($tab[0]);
165  }
166  return ("text/any");
167 }
168 
169 function GetExt($mime_type)
170 {
171  $mimes = file("/etc/mime.types");
172  foreach ($mimes as $v) {
173  if (substr($v, 0, 1) == "#") continue;
174  $tab = preg_split('\s+/', $v);
175  if ((isset($tab[0])) && ($tab[0] == $mime_type)) {
176  if (isset($tab[1])) {
177  return ($tab[1]);
178  } else {
179  return ("");
180  }
181  }
182  }
183  return ("");
184 }
185 /**
186  * Send a response with the given data to be downloaded by the client.
187  *
188  * No output should be generated on stdout after calling this function.
189  *
190  * @param string $src the data to send to the client
191  * @param string $ext the extension of the data (e.g. "pdf", "png", etc.)
192  * @param string $name the filename that will be used by the client for saving to a file
193  * @param bool $add_ext add the $ext extension to the $name filename (default = TRUE)
194  * @param string $mime_type the Content-Type MIME type of the response. If empty, compute MIME type from $ext extension (this is the default behaviour)
195  * @return void
196  */
197 function Http_Download($src, $ext, $name, $add_ext = TRUE, $mime_type = "")
198 {
199  if ($mime_type == '') $mime_type = GetMimeType($ext);
200  if ($add_ext) $name = $name . "." . $ext;
201  $name = str_replace('"', '\\"', $name);
202  $uName = iconv("UTF-8", "ASCII//TRANSLIT", $name);
203  $name = rawurlencode($name);
204  header("Cache-control: private"); // for IE : don't know why !!
205  header('Content-Length: ' . strlen($src));
206  header("Pragma: "); // HTTP 1.0
207  header("Content-Disposition: attachment;filename=\"$uName\";filename*=UTF-8''$name;");
208  header("Content-type: " . $mime_type);
209  header("X-Content-Type-Options: nosniff");
210  echo $src;
211 }
212 /**
213  * Send a response with the content of a local file to be downloaded by the client
214  *
215  * No output should be generated on stdout after calling this function.
216  *
217  * @param string $filename pathname of the file that will be sent to the client (e.g. "/tmp/foo.pdf")
218  * @param string $name the basename of the file (e.g. "foo.pdf")
219  * @param string $mime_type the Content-Type MIME type of the response (e.g. "application/pdf")
220  * @param bool $inline Send the data with inline Content-Disposition (default = FALSE)
221  * @param bool $cache Instruct clients and/or proxies to cache the response for 24h (default = TRUE)
222  * @param bool $deleteafter Delete the $filename file when done (default = FALSE)
223  * @return void
224  */
225 function Http_DownloadFile($filename, $name, $mime_type = '', $inline = false, $cache = true, $deleteafter = false)
226 {
227  require_once 'FDL/Class.FileMimeConfig.php';
228 
229  if (!file_exists($filename)) {
230  printf(_("file not found : %s") , $filename);
231  return;
232  }
233 
234  if (php_sapi_name() !== 'cli') {
235  // Double quote not supported by all browsers - replace by minus
236  $name = str_replace('"', '-', $name);
237  $uName = iconv("UTF-8", "ASCII//TRANSLIT", $name);
238  $name = rawurlencode($name);
239  $fileMimeConfig = new \Dcp\FileMimeConfig();
240  if ($inline && !$fileMimeConfig->isInlineAllowed($mime_type)) {
241  /* Override requested inline mode as it is forbidden */
242  $inline = false;
243  }
244  if (!$inline) {
245  header("Content-Disposition: attachment;filename=\"$uName\";filename*=UTF-8''$name;");
246  } else {
247  header("Content-Disposition: inline;filename=\"$uName\";filename*=UTF-8''$name;");
248  }
249 
250  if ($cache) {
251  $duration = 24 * 3600;
252  header("Cache-Control: private, max-age=$duration"); // use cache client (one hour) for speed optimsation
253  header("Expires: " . gmdate("D, d M Y H:i:s T\n", time() + $duration)); // for mozilla
254 
255  } else {
256  header("Cache-Control: private");
257  }
258  header("Pragma: "); // HTTP 1.0
259  if ($inline && substr($mime_type, 0, 4) == "text" && substr($mime_type, 0, 9) != "text/html" && substr($mime_type, 0, 8) != "text/xml") $mime_type = preg_replace("_text/([^;]*)_", "text/plain", $mime_type);
260 
261  header("Content-type: " . $mime_type);
262  header("X-Content-Type-Options: nosniff");
263  header("Content-Transfer-Encoding: binary");
264  header("Content-Length: " . filesize($filename));
265  $buflen = ob_get_length();
266  if ($buflen !== false && $buflen > 0) {
267  ob_clean();
268  }
269  flush();
270  }
271  readfile($filename);
272  if ($deleteafter) unlink($filename);
273  exit;
274 }
275 
277 { // just to debug
278  global $_GET, $_POST, $ZONE_ARGS;
279  print "<PRE>";
280  if (isset($ZONE_ARGS)) print_r($ZONE_ARGS);
281  if (isset($_GET)) print_r($_GET);
282  if (isset($_POST)) print_r($_POST);
283  print "</PRE>";
284 }
285 
286 function glue_url($parsed)
287 {
288  if (!is_array($parsed)) return false;
289  $uri = $parsed['scheme'] ? $parsed['scheme'] . ':' . ((strtolower($parsed['scheme']) == 'mailto') ? '' : '//') : '';
290  $uri.= $parsed['user'] ? $parsed['user'] . ($parsed['pass'] ? ':' . $parsed['pass'] : '') . '@' : '';
291  $uri.= $parsed['host'] ? $parsed['host'] : '';
292  $uri.= $parsed['port'] ? ':' . $parsed['port'] : '';
293  $uri.= $parsed['path'] ? $parsed['path'] : '';
294  $uri.= $parsed['query'] ? '?' . $parsed['query'] : '';
295  $uri.= $parsed['fragment'] ? '#' . $parsed['fragment'] : '';
296  return $uri;
297 }
298 /**
299  * set in cache one hour
300  * @param string $mime
301  */
302 function setHeaderCache($mime = "text/css")
303 {
304  ini_set('session.cache_limiter', 'none');
305  $duration = 24 * 3600;
306  header("Cache-Control: private, max-age=$duration"); // use cache client (one hour) for speed optimsation
307  header("Expires: " . gmdate("D, d M Y H:i:s T\n", time() + $duration)); // for mozilla
308  header("Pragma: none"); // HTTP 1.0
309  header("Content-type: $mime");
310  header("X-Content-Type-Options: nosniff");
311 }
glue_url($parsed)
Definition: Lib.Http.php:286
$deb
Definition: indexq.php:20
$appname
global $SQLDEBUG
Definition: indexq.php:28
global $action
global $_POST
Definition: chgpasswd.php:17
getDbAccessValue($varName)
Definition: Lib.Common.php:425
if($dbaccess=="") $duration
GetExt($mime_type)
Definition: Lib.Http.php:169
SetHttpVar($name, $def)
Definition: Lib.Http.php:150
$tic4
Definition: indexq.php:87
setHeaderCache($mime="text/css")
Definition: Lib.Http.php:302
RedirectSender(Action &$action)
Definition: Lib.Http.php:81
const ANONYMOUS_ID
if(ActionRouter::inMaintenance()) $auth
Definition: authent.php:15
$filename
redirectAsGuest(Action &$action)
Definition: Lib.Http.php:104
Redirect($action, $appname, $actionname, $otherurl="", $httpparamredirect=false)
Definition: Lib.Http.php:21
global $TSQLDELAY
Definition: indexq.php:29
global $SQLDELAY
Definition: indexq.php:28
$trace
Definition: indexq.php:77
exitError($texterr, $exit=true, $code="")
Http_Download($src, $ext, $name, $add_ext=TRUE, $mime_type="")
Definition: Lib.Http.php:197
PrintAllHttpVars()
Definition: Lib.Http.php:276
global $_GET
Definition: wsh.php:37
if(!$img) $location
Definition: resizeimg.php:143
getHttpVars($name, $def="", $scope="all")
Definition: Lib.Http.php:124
print
Definition: checklist.php:49
global $_SERVER
switch($command) exit
Definition: checkVault.php:46
$ticainit
Definition: indexq.php:76
GetMimeType($ext)
Definition: Lib.Http.php:158
global $tic1
Definition: indexq.php:18
Http_DownloadFile($filename, $name, $mime_type= '', $inline=false, $cache=true, $deleteafter=false)
Definition: Lib.Http.php:225
$actionname
$guestMode
Definition: index.php:25
GetHttpCookie($name, $def="")
Definition: Lib.Http.php:142
← centre documentaire © anakeen