Core  3.2
PHP API documentation
 All Data Structures Namespaces Files Functions Variables Pages
Lib.Main.php
Go to the documentation of this file.
1 <?php
2 /*
3  * @author Anakeen
4  * @package FDL
5 */
6 /**
7  * Main first level function
8  *
9  * @author Anakeen
10  * @version $Id: Lib.Common.php,v 1.50 2008/09/11 14:50:04 eric Exp $
11  * @package FDL
12  * @subpackage CORE
13  */
14 /**
15  */
16 include_once ("WHAT/Lib.Common.php");
17 /**
18  * @param Authenticator $auth
19  * @param Action $action
20  */
22 {
23  include_once ('Class.Action.php');
24  include_once ('Class.Application.php');
25  include_once ('Class.Session.php');
26  include_once ('Lib.Http.php');
27  include_once ('Lib.Phpini.php');
28  include_once ('Class.Log.php');
29  include_once ('Class.DbObj.php');
30 
31  $CoreNull = "";
32 
33  global $_GET;
34  $defaultapp = false;
35  if (!getHttpVars("app")) {
36  $defaultapp = true;
37  $_GET["app"] = "CORE";
38  if (!empty($_SERVER["FREEDOM_ACCESS"])) {
39  $_GET["app"] = $_SERVER["FREEDOM_ACCESS"];
40  $_GET["action"] = "";
41  } else {
42  $defaultapp = false;
43  $_GET["action"] = "INVALID";
44  }
45  }
46 
47  if (isset($auth->auth_session)) {
48  $session = $auth->auth_session;
49  } else {
50  $session = new Session();
51  if (isset($_COOKIE[Session::PARAMNAME])) $sess_num = $_COOKIE[Session::PARAMNAME];
52  else $sess_num = GetHttpVars(Session::PARAMNAME); //$_GET["session"];
53  if (!$session->Set($sess_num)) {
54  print "<strong>:~((</strong>";
55  exit;
56  };
57  }
58  $core = new Application();
59  $core->Set("CORE", $CoreNull, $session);
60 
61  if (isset($_SERVER['PHP_AUTH_USER']) && ($core->user->login != $_SERVER['PHP_AUTH_USER'])) {
62  // reopen a new session
63  $session->Set("");
64  $core->SetSession($session);
65  }
66  if ($defaultapp && $core->GetParam("CORE_START_APP")) {
67  $_GET["app"] = $core->GetParam("CORE_START_APP");
68  }
69 
72  //$core->SetSession($session);
73  // ----------------------------------------
74  // Init PUBLISH URL from script name
75  initMainVolatileParam($core, $session);
76  // ----------------------------------------
77  // Init Application & Actions Objects
78  $appl = new Application();
79  $err = $appl->Set(getHttpVars("app") , $core, $session);
80  if ($err) {
81  print $err;
82  exit;
83  }
84 
85  if (($appl->machine != "") && ($_SERVER['SERVER_NAME'] != $appl->machine)) { // special machine to redirect
86  if (substr($_SERVER['REQUEST_URI'], 0, 6) == "http:/") {
87  $aquest = parse_url($_SERVER['REQUEST_URI']);
88  $aquest['host'] = $appl->machine;
89  $puburl = glue_url($aquest);
90  } else {
91  $puburl = "http://" . $appl->machine . $_SERVER['REQUEST_URI'];
92  }
93 
94  Header("Location: $puburl");
95  exit;
96  }
97  // ----------------------------------------
98  // test SSL mode needed or not
99  // redirect if needed
100  if ($appl->ssl == "Y") {
101  if ($_SERVER['HTTPS'] != 'on') {
102  // redirect to go to ssl http
103  $sslurl = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
104  Header("Location: $sslurl");
105  exit;
106  }
107 
108  $core->SetVolatileParam("CORE_BGCOLOR", $core->GetParam("CORE_SSLBGCOLOR"));
109  }
110  // -----------------------------------------------
111  // now we are in correct protocol (http or https)
112  $action = new Action();
113  $action->Set(getHttpVars("action") , $appl);
114 
115  if ($auth) {
116  $core_lang = $auth->getSessionVar('CORE_LANG');
117  if ($core_lang != '') {
118  $action->setParamU('CORE_LANG', $core_lang);
119  $auth->setSessionVar('CORE_LANG', '');
120  }
121  $action->auth = & $auth;
122  $core->SetVolatileParam("CORE_BASICAUTH", '&authtype=basic');
123  } else $core->SetVolatileParam("CORE_BASICAUTH", '');
124 
126  // init for gettext
127  setLanguage($action->Getparam("CORE_LANG"));
128 
129  $action->log->debug("gettext init for " . $action->parent->name . $action->Getparam("CORE_LANG"));
130 }
131 
132 function stripUrlSlahes($url)
133 {
134  $pos = mb_strpos($url, '://');
135  return mb_substr($url, 0, $pos + 3) . preg_replace('/\/+/u', '/', mb_substr($url, $pos + 3));
136 }
137 /**
138  * init user agent volatile param
139  * @param Application $app
140  * @param mixed $defaultValue
141  */
142 function initExplorerParam(Application & $app, $defaultValue = false)
143 {
144  $explorerP = getExplorerParamtersName();
145  foreach ($explorerP as $ep) {
146  $app->SetVolatileParam($ep, $defaultValue);
147  }
148  if (!empty($_SERVER["HTTP_HOST"])) {
149  initExplorerWebParam($app);
150  }
151 }
152 
154 {
155  return array(
156  "ISIE",
157  "ISIE6",
158  "ISIE7",
159  "ISIE8",
160  "ISIE9",
161  "ISIE10",
162  "ISAPPLEWEBKIT",
163  "ISSAFARI",
164  "ISCHROME"
165  );
166 }
167 /**
168  * set volatile patram to detect web user agent
169  * @param Application $app
170  */
172 {
173  $nav = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
174  $pos = strpos($nav, "MSIE");
175  if ($app->session->Read("navigator", "") == "") {
176  if ($pos !== false) {
177  $app->session->Register("navigator", "EXPLORER");
178  if (preg_match("/MSIE ([0-9.]+).*/", $nav, $reg)) {
179  $app->session->Register("navversion", $reg[1]);
180  }
181  } else {
182  $app->session->Register("navigator", "NETSCAPE");
183  if (preg_match("|([a-zA-Z]+)/([0-9.]+).*|", $nav, $reg)) {
184  $app->session->Register("navversion", $reg[2]);
185  }
186  }
187  }
188 
189  $ISIE6 = false;
190  $ISIE7 = false;
191  $ISIE8 = false;
192  $ISIE9 = false;
193  $ISIE10 = false;
194  $ISAPPLEWEBKIT = false;
195  $ISSAFARI = false;
196  $ISCHROME = false;
197  if (preg_match('/MSIE ([0-9]+).*/', $nav, $match)) {
198  switch ($match[1]) {
199  case "6":
200  $ISIE6 = true;
201  break;
202 
203  case "7":
204  $ISIE7 = true;
205  break;
206 
207  case "8":
208  $ISIE8 = true;
209  break;
210 
211  case "9":
212  $ISIE9 = true;
213  break;
214 
215  case "10":
216  $ISIE10 = true;
217  break;
218  }
219  } elseif (preg_match('|\bAppleWebKit/(.*?)\b|', $nav, $match)) {
220  $ISAPPLEWEBKIT = true;
221  if (preg_match('|\bChrome/(.*?)\b|', $nav, $match)) {
222  $ISCHROME = true;
223  } elseif (preg_match('|\bSafari/(.*?)\b|', $nav, $match)) {
224  $ISSAFARI = true;
225  }
226  }
227 
228  $app->SetVolatileParam("ISIE", ($app->session->read("navigator") == "EXPLORER"));
229  $app->SetVolatileParam("ISIE6", ($ISIE6 === true));
230  $app->SetVolatileParam("ISIE7", ($ISIE7 === true));
231  $app->SetVolatileParam("ISIE8", ($ISIE8 === true));
232  $app->SetVolatileParam("ISIE9", ($ISIE9 === true));
233  $app->SetVolatileParam("ISIE10", ($ISIE10 === true));
234  $app->SetVolatileParam("ISAPPLEWEBKIT", ($ISAPPLEWEBKIT === true));
235  $app->SetVolatileParam("ISSAFARI", ($ISSAFARI === true));
236  $app->SetVolatileParam("ISCHROME", ($ISCHROME === true));
237 }
238 /**
239  * Set various core URLs params
240  *
241  * @param Application $core
242  * @param Session $session
243  */
244 function initMainVolatileParam(Application & $core, Session & $session = null)
245 {
246  if (php_sapi_name() == 'cli') {
248  } else {
249  _initMainVolatileParamWeb($core, $session);
250  }
251 }
252 
254 {
255  $hostname = LibSystem::getHostName();
256  $puburl = $core->GetParam("CORE_PUBURL", "http://" . $hostname . "/freedom");
257 
258  $absindex = $core->GetParam("CORE_URLINDEX");
259  if ($absindex == '') {
260  $absindex = "$puburl/"; // try default
261 
262  }
263  $core_externurl = ($absindex) ? stripUrlSlahes($absindex) : stripUrlSlahes($puburl . "/");
264  $core_mailaction = $core->getParam("CORE_MAILACTION");
265  $core_mailactionurl = ($core_mailaction != '') ? ($core_mailaction) : ($core_externurl . "?app=FDL&action=OPENDOC&mode=view");
266 
267  $core->SetVolatileParam("CORE_EXTERNURL", $core_externurl);
268  $core->SetVolatileParam("CORE_PUBURL", "."); // relative links
269  $core->SetVolatileParam("CORE_ABSURL", $puburl . "/"); // absolute links
270  $core->SetVolatileParam("CORE_JSURL", "WHAT/Layout");
271  $core->SetVolatileParam("CORE_ROOTURL", "$absindex?sole=R&");
272  $core->SetVolatileParam("CORE_BASEURL", "$absindex?sole=A&");
273  $core->SetVolatileParam("CORE_SBASEURL", "$absindex?sole=A&"); // no session
274  $core->SetVolatileParam("CORE_STANDURL", "$absindex?sole=Y&");
275  $core->SetVolatileParam("CORE_SSTANDURL", "$absindex?sole=Y&"); // no session
276  $core->SetVolatileParam("CORE_ASTANDURL", "$absindex?sole=Y&"); // absolute links
277  $core->SetVolatileParam("CORE_MAILACTIONURL", $core_mailactionurl);
278 }
279 
280 function _initMainVolatileParamWeb(Application & $core, Session & $session = null)
281 {
282  $indexphp = basename($_SERVER["SCRIPT_NAME"]);
283  $pattern = preg_quote($indexphp, "|");
284  if (preg_match("|(.*)/$pattern|", $_SERVER['SCRIPT_NAME'], $reg)) {
285  // determine publish url (detect ssl require)
286  if (empty($_SERVER['HTTPS'])) $_SERVER['HTTPS'] = "off";
287  if ($_SERVER['HTTPS'] != 'on') $puburl = "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . $reg[1];
288  else $puburl = "https://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . $reg[1];
289  } else {
290  // it is not allowed
291  print "<strong>:~(</strong>";
292  exit;
293  }
294  $add_args = "";
295  if (array_key_exists('authtype', $_GET)) {
296  $add_args.= "&authtype=" . $_GET['authtype'];
297  }
298  $puburl = stripUrlSlahes($puburl);
299  $urlindex = $core->getParam("CORE_URLINDEX");
300  $core_externurl = ($urlindex) ? stripUrlSlahes($urlindex) : stripUrlSlahes($puburl . "/");
301  $core_mailaction = $core->getParam("CORE_MAILACTION");
302  $core_mailactionurl = ($core_mailaction != '') ? ($core_mailaction) : ($core_externurl . "?app=FDL&action=OPENDOC&mode=view");
303 
304  $sessKey = isset($session->id) ? $session->getUKey(getParam("WVERSION")) : uniqid(getParam("WVERSION"));
305  $core->SetVolatileParam("CORE_EXTERNURL", $core_externurl);
306  $core->SetVolatileParam("CORE_PUBURL", "."); // relative links
307  $core->SetVolatileParam("CORE_ABSURL", stripUrlSlahes($puburl . "/")); // absolute links
308  $core->SetVolatileParam("CORE_JSURL", "WHAT/Layout");
309  $core->SetVolatileParam("CORE_ROOTURL", "?sole=R$add_args&");
310  $core->SetVolatileParam("CORE_BASEURL", "?sole=A$add_args&");
311  $core->SetVolatileParam("CORE_SBASEURL", "?sole=A&_uKey_=$sessKey$add_args&");
312  $core->SetVolatileParam("CORE_STANDURL", "?sole=Y$add_args&");
313  $core->SetVolatileParam("CORE_SSTANDURL", "?sole=Y&_uKey_=$sessKey$add_args&");
314  $core->SetVolatileParam("CORE_ASTANDURL", "$puburl/$indexphp?sole=Y$add_args&"); // absolute links
315  $core->SetVolatileParam("CORE_MAILACTIONURL", $core_mailactionurl);
316 }
317 /**
318  * execute action
319  * app and action http param
320  * @param Action $action
321  * @param string $out
322  */
323 function executeAction(&$action, &$out = null)
324 {
325  $standalone = GetHttpVars("sole", "Y");
326  if ($standalone != "A") {
327  if ($out !== null) $out = $action->execute();
328  else echo ($action->execute());
329  } else {
330  if ((isset($action->parent)) && ($action->parent->with_frame != "Y")) {
331  // This document is not completed : does not contain header and footer
332  // HTML body result
333  // achieve action
334  $body = ($action->execute());
335  // write HTML header
336  $head = new Layout($action->GetLayoutFile("htmltablehead.xml") , $action);
337  // copy JS ref & code from action to header
338  //$head->jsref = $action->parent->GetJsRef();
339  //$head->jscode = $action->parent->GetJsCode();
340  $head->set("TITLE", _($action->parent->short_name));
341  if ($out !== null) {
342  $out = $head->gen();
343  $out.= $body;
344  $foot = new Layout($action->GetLayoutFile("htmltablefoot.xml") , $action);
345  $out.= $foot->gen();
346  } else {
347  echo ($head->gen());
348  // write HTML body
349  echo ($body);
350  // write HTML footer
351  $foot = new Layout($action->GetLayoutFile("htmltablefoot.xml") , $action);
352  echo ($foot->gen());
353  }
354  } else {
355  // This document is completed
356  if ($out !== null) $out = $action->execute();
357  else echo ($action->execute());
358  }
359  }
360 }
361 
363 {
364  $uid = posix_getuid();
365  if ($uid === 0) {
366  throw new \Dcp\Exception(sprintf("Error: this script must NOT be run as root (uid 0).\n"));
367  }
368  if (($owner = fileowner($file)) === false) {
369  throw new \Dcp\Exception(sprintf("Error: could not get owner of file '%s'.\n", $file));
370  }
371  if ($owner !== $uid) {
372  $msg = <<<'EOF'
373 Error: current uid %d does not match owner %d of file '%s'.
374 
375 You might need to either:
376 - run the script under the webserver's user;
377 - or set proper ownership of context's files to that of the webserver's user.
378 
379 EOF;
380  throw new \Dcp\Exception(sprintf($msg, $uid, $owner, $file));
381  }
382 }
383 /**
384  * @param Exception|Error $e
385  * @throws \Dcp\Core\Exception
386  */
387 function handleActionException($e)
388 {
389  global $action;
390 
391  if (php_sapi_name() !== "cli") {
392  if (method_exists($e, "addHttpHeader")) {
393  /**
394  * @var \Dcp\Exception $e
395  */
396  if ($e->getHttpHeader()) {
397  header($e->getHttpHeader());
398  } else {
399  header("HTTP/1.1 500 Dynacase Uncaught Exception");
400  }
401  } else {
402  header("HTTP/1.1 500 Dynacase Uncaught Exception");
403  }
404  }
405 
406  $displayMsg = \Dcp\Core\LogException::logMessage($e, $errId);
407  if (isset($action) && is_a($action, 'Action') && isset($action->parent)) {
408 
409  if ($action->parent->name === ApplicationParameterManager::getParameterValue("CORE", "CORE_START_APP")) {
410  $action->parent->session->Close();
411  $action->exitError(_("You don't have access to any content. Please contact your administrator."));
412  } else {
413 
414  if (php_sapi_name() === 'cli') {
415  fwrite(STDERR, sprintf("[%s]: %s\n", $errId, $displayMsg));
416  } else {
417  $action->exitError($displayMsg, true, $errId);
418  }
419  }
420  } else {
421  if (php_sapi_name() === 'cli') {
422  fwrite(STDERR, sprintf("[%s]: %s\n", $errId, $displayMsg));
423  } else {
424  print htmlspecialchars(sprintf("[%s]: %s\n", $errId, $displayMsg));
425  }
426  exit(1);
427  }
428 }
429 
430 function isInteractiveCLI()
431 {
432  if (php_sapi_name() !== 'cli') {
433  return false;
434  }
435  if (function_exists('posix_isatty')) {
436  return (posix_isatty(STDIN) || posix_isatty(STDOUT) || posix_isatty(STDERR));
437  }
438  return true;
439 }
440 
441 function _wsh_send_error($errMsg, $expand = array())
442 {
443  global $action;
444  $wshError = new Dcp\WSHMailError($action, $errMsg);
445  $wshError->prefix = sprintf('%s %s ', date('c') , php_uname('n'));
446  $wshError->addExpand($expand);
447  $wshError->autosend();
448 }
449 /**
450  * Handle exceptions by logging errors or by sending mails
451  * depending if the program is used in a CLI or not.
452  *
453  * @param Throwable $e
454  * @param bool $callStack If set to false: the error message is minimal.
455  * Otherwise the error message is the call stack.
456  */
457 function _wsh_exception_handler($e, $callStack = true)
458 {
459  if ($callStack === true) {
460  $errMsg = \Dcp\Core\LogException::formatErrorLogException($e);
461  error_log($errMsg);
462  } else {
463  $errMsg = $e->getMessage();
464  }
465 
466  if (!isInteractiveCLI()) {
467  $expand = array(
468  'm' => preg_replace('/^([^\n]*).*/s', '\1', $e->getMessage())
469  );
470  _wsh_send_error($errMsg, $expand);
471  }
472 
473  exit(255);
474 }
475 
476 function _wsh_shutdown_handler()
477 {
478  global $argv;
479 
480  $error = error_get_last();
481  if ($error === null) {
482  /* No error */
483  return;
484  }
485  /* Process error */
486  switch ($error["type"]) {
487  case E_ERROR:
488  $title = "Runtime Error";
489  break;
490 
491  case E_CORE_ERROR:
492  $title = "Startup Error";
493  break;
494 
495  case E_PARSE:
496  $title = "Parse Error";
497  break;
498 
499  case E_COMPILE_ERROR:
500  $title = "Compile Error";
501  break;
502 
503  case E_RECOVERABLE_ERROR:
504  $title = "Recoverable Error";
505  break;
506 
507  default:
508  return;
509  }
510 
511  $pid = getmypid();
512  $errMsg = <<<EOF
513 $pid> Dynacase $title
514 EOF;
515 
516  if (php_sapi_name() == 'cli' && is_array($argv)) {
517  $errMsg.= sprintf("\n%s> Command line arguments: %s", $pid, join(' ', array_map("escapeshellarg", $argv)));
518  $errMsg.= sprintf("\n%s> error_log: %s", $pid, ini_get('error_log'));
519  $errMsg.= "\n";
520  }
521 
522  $errMsg.= <<<EOF
523 $pid> Type: ${error['type']}
524 $pid> Message: ${error['message']}
525 $pid> File: ${error['file']}
526 $pid> Line: ${error['line']}
527 EOF;
528 
529  error_log($errMsg);
530  if (!isInteractiveCLI()) {
531  $expand = array(
532  'm' => preg_replace('/^([^\n]*).*/s', '\1', $error['message'])
533  );
534  _wsh_send_error($errMsg, $expand);
535  }
536 }
537 
538 function enable_wsh_safetybelts()
539 {
540  set_exception_handler("_wsh_exception_handler");
541  register_shutdown_function("_wsh_shutdown_handler");
542 }
543 /**
544  * @param Throwable $e
545  * @deprecated use Dcp\Core\LogException::formatErrorLogException()
546  * @return string
547  */
548 function formatErrorLogException($e)
549 {
550  return \Dcp\Core\LogException::formatErrorLogException($e);
551 }
552 /**
553  * @param Exception|Error $e
554  */
555 function errorLogException($e)
556 {
557  \Dcp\Core\LogException::writeLog($e);
558 }
559 
560 function handleFatalShutdown()
561 {
562  global $action;
563 
564  $error = error_get_last();
565 
566  if ($error !== NULL && $action) {
567 
568  if (in_array($error["type"], array(
569  E_ERROR,
570  E_PARSE,
571  E_COMPILE_ERROR,
572  E_CORE_ERROR,
573  E_USER_ERROR,
574  E_RECOVERABLE_ERROR
575  ))) {
576  ob_get_clean();
577  if (!headers_sent()) {
578  header("HTTP/1.1 500 Dynacase Fatal Error");
579  }
580 
581  $displayMsg = \Dcp\Core\LogException::logMessage($error, $errId);
582  if ($action) {
583  $action->exitError($displayMsg, false, $errId);
584  } else {
585  print $displayMsg;
586  }
587  // Fatal error are already logged by PHP
588 
589  }
590  }
591 }
592 
593 set_exception_handler('handleActionException');
594 
Layout is a template generator.
glue_url($parsed)
Definition: Lib.Http.php:286
global $appl
Definition: checkVault.php:9
$s type
Definition: dav.php:73
global $action
getParam($key, $default="")
print t $msg n
if(ActionRouter::inMaintenance()) $auth
Definition: authent.php:15
$file
static setCoreApplication(\Application $coreApplication)
Definition: Lib.Phpini.php:22
print t
Definition: cleanFamily.php:92
_wsh_exception_handler($e, $callStack=true)
Definition: Lib.Main.php:457
initMainVolatileParam(Application &$core, Session &$session=null)
Definition: Lib.Main.php:244
static getHostName()
Definition: Lib.System.php:37
_wsh_shutdown_handler()
Definition: Lib.Main.php:476
initExplorerParam(Application &$app, $defaultValue=false)
Definition: Lib.Main.php:142
_initMainVolatileParamCli(Application &$core)
Definition: Lib.Main.php:253
executeAction(&$action, &$out=null)
Definition: Lib.Main.php:323
_initMainVolatileParamWeb(Application &$core, Session &$session=null)
Definition: Lib.Main.php:280
$app
global $_GET
Definition: wsh.php:37
getParam($name, $def="")
must be in core or global type
Definition: Lib.Common.php:193
getMainAction($auth, &$action)
Definition: Lib.Main.php:21
getHttpVars($name, $def="", $scope="all")
Definition: Lib.Http.php:124
setLanguage($lang)
Definition: Lib.Common.php:886
set($tag, $val)
print
Definition: checklist.php:49
global $_SERVER
initExplorerWebParam(Application &$app)
Definition: Lib.Main.php:171
switch($command) exit
Definition: checkVault.php:46
stripUrlSlahes($url)
Definition: Lib.Main.php:132
checkWshExecUid($file)
Definition: Lib.Main.php:362
getExplorerParamtersName()
Definition: Lib.Main.php:153
const PARAMNAME
if($file) if($subject==""&&$file) if($subject=="") $err
static applyLimits()
Definition: Lib.Phpini.php:12
$CoreNull
Definition: chgpasswd.php:32
$core
Definition: chgpasswd.php:33
← centre documentaire © anakeen